diff --git a/app/Api/V1/Controllers/Autocomplete/AccountController.php b/app/Api/V1/Controllers/Autocomplete/AccountController.php index 51aa06ce3d..73e85dac63 100644 --- a/app/Api/V1/Controllers/Autocomplete/AccountController.php +++ b/app/Api/V1/Controllers/Autocomplete/AccountController.php @@ -88,11 +88,11 @@ class AccountController extends Controller // set date to end-of-day for account balance. so it is at $date 23:59:59 $date->endOfDay(); - $return = []; - $timer = Timer::getInstance(); + $return = []; + $timer = Timer::getInstance(); $timer->start(sprintf('AC accounts "%s"', $query)); - $result = $this->repository->searchAccount((string) $query, $types, $limit); - $allBalances = Steam::accountsBalancesOptimized($result, $date, $this->primaryCurrency, $this->convertToPrimary); + $result = $this->repository->searchAccount((string) $query, $types, $limit); + $allBalances = Steam::accountsBalancesOptimized($result, $date, $this->primaryCurrency, $this->convertToPrimary); /** @var Account $account */ foreach ($result as $account) { @@ -109,7 +109,7 @@ class AccountController extends Controller $nameWithBalance = sprintf('%s (%s)', $account->name, Amount::formatAnything($useCurrency, $amount, false)); } - $return[] = [ + $return[] = [ 'id' => (string) $account->id, 'name' => $account->name, 'name_with_balance' => $nameWithBalance, @@ -124,7 +124,7 @@ class AccountController extends Controller 'account_currency_name' => $currency->name, 'account_currency_code' => $currency->code, 'account_currency_symbol' => $currency->symbol, - 'account_currency_decimal_places' => $currency->decimal_places, + 'account_currency_decimal_places' => $currency->decimal_places ]; } diff --git a/app/Api/V1/Controllers/Autocomplete/BillController.php b/app/Api/V1/Controllers/Autocomplete/BillController.php index b43e56e1f2..cae9dd63b4 100644 --- a/app/Api/V1/Controllers/Autocomplete/BillController.php +++ b/app/Api/V1/Controllers/Autocomplete/BillController.php @@ -63,7 +63,7 @@ class BillController extends Controller public function bills(AutocompleteApiRequest $request): JsonResponse { $result = $this->repository->searchBill($request->attributes->get('query'), $request->attributes->get('limit')); - $filtered = $result->map(static fn (Bill $item): array => ['id' => (string) $item->id, 'name' => $item->name, 'active' => $item->active]); + $filtered = $result->map(static fn(Bill $item): array => ['id' => (string) $item->id, 'name' => $item->name, 'active' => $item->active]); return response()->api($filtered->toArray()); } diff --git a/app/Api/V1/Controllers/Autocomplete/BudgetController.php b/app/Api/V1/Controllers/Autocomplete/BudgetController.php index 40d42d5c18..d919648529 100644 --- a/app/Api/V1/Controllers/Autocomplete/BudgetController.php +++ b/app/Api/V1/Controllers/Autocomplete/BudgetController.php @@ -63,7 +63,7 @@ class BudgetController extends Controller public function budgets(AutocompleteApiRequest $request): JsonResponse { $result = $this->repository->searchBudget($request->attributes->get('query'), $request->attributes->get('limit')); - $filtered = $result->map(static fn (Budget $item): array => ['id' => (string) $item->id, 'name' => $item->name, 'active' => $item->active]); + $filtered = $result->map(static fn(Budget $item): array => ['id' => (string) $item->id, 'name' => $item->name, 'active' => $item->active]); return response()->api($filtered->toArray()); } diff --git a/app/Api/V1/Controllers/Autocomplete/CategoryController.php b/app/Api/V1/Controllers/Autocomplete/CategoryController.php index 27fa145d52..39a5bf614e 100644 --- a/app/Api/V1/Controllers/Autocomplete/CategoryController.php +++ b/app/Api/V1/Controllers/Autocomplete/CategoryController.php @@ -63,7 +63,7 @@ class CategoryController extends Controller public function categories(AutocompleteApiRequest $request): JsonResponse { $result = $this->repository->searchCategory($request->attributes->get('query'), $request->attributes->get('limit')); - $filtered = $result->map(static fn (Category $item): array => ['id' => (string) $item->id, 'name' => $item->name]); + $filtered = $result->map(static fn(Category $item): array => ['id' => (string) $item->id, 'name' => $item->name]); return response()->api($filtered->toArray()); } diff --git a/app/Api/V1/Controllers/Autocomplete/CurrencyController.php b/app/Api/V1/Controllers/Autocomplete/CurrencyController.php index 656c96b493..327d73e9a4 100644 --- a/app/Api/V1/Controllers/Autocomplete/CurrencyController.php +++ b/app/Api/V1/Controllers/Autocomplete/CurrencyController.php @@ -74,7 +74,7 @@ class CurrencyController extends Controller 'name' => $currency->name, 'code' => $currency->code, 'symbol' => $currency->symbol, - 'decimal_places' => $currency->decimal_places, + 'decimal_places' => $currency->decimal_places ]; } @@ -99,7 +99,7 @@ class CurrencyController extends Controller 'name' => sprintf('%s (%s)', $currency->name, $currency->code), 'code' => $currency->code, 'symbol' => $currency->symbol, - 'decimal_places' => $currency->decimal_places, + 'decimal_places' => $currency->decimal_places ]; } diff --git a/app/Api/V1/Controllers/Autocomplete/PiggyBankController.php b/app/Api/V1/Controllers/Autocomplete/PiggyBankController.php index a7d54eff6b..4c031d7a6b 100644 --- a/app/Api/V1/Controllers/Autocomplete/PiggyBankController.php +++ b/app/Api/V1/Controllers/Autocomplete/PiggyBankController.php @@ -52,7 +52,7 @@ class PiggyBankController extends Controller parent::__construct(); $this->middleware(function (Request $request, $next) { $this->validateUserGroup($request); - $this->piggyRepository = app(PiggyBankRepositoryInterface::class); + $this->piggyRepository = app(PiggyBankRepositoryInterface::class); $this->accountRepository = app(AccountRepositoryInterface::class); $this->piggyRepository->setUser($this->user); $this->piggyRepository->setUserGroup($this->userGroup); @@ -72,7 +72,7 @@ class PiggyBankController extends Controller foreach ($piggies as $piggy) { $currency = $piggy->transactionCurrency; $objectGroup = $piggy->objectGroups()->first(); - $response[] = [ + $response[] = [ 'id' => (string) $piggy->id, 'name' => $piggy->name, 'currency_id' => (string) $currency->id, @@ -82,7 +82,7 @@ class PiggyBankController extends Controller 'currency_decimal_places' => $currency->decimal_places, 'object_group_id' => null === $objectGroup ? null : (string) $objectGroup->id, 'object_group_title' => $objectGroup?->title, - 'object_group_order' => $objectGroup?->order, + 'object_group_order' => $objectGroup?->order ]; } @@ -100,7 +100,7 @@ class PiggyBankController extends Controller $currency = $piggy->transactionCurrency; $currentAmount = $this->piggyRepository->getCurrentAmount($piggy); $objectGroup = $piggy->objectGroups()->first(); - $response[] = [ + $response[] = [ 'id' => (string) $piggy->id, 'name' => $piggy->name, 'name_with_balance' => sprintf( @@ -115,7 +115,7 @@ class PiggyBankController extends Controller 'currency_symbol' => $currency->symbol, 'currency_decimal_places' => $currency->decimal_places, 'object_group_id' => null === $objectGroup ? null : (string) $objectGroup->id, - 'object_group_title' => $objectGroup?->title, + 'object_group_title' => $objectGroup?->title ]; } diff --git a/app/Api/V1/Controllers/Autocomplete/RecurrenceController.php b/app/Api/V1/Controllers/Autocomplete/RecurrenceController.php index 2d243b4d2b..22a2e87110 100644 --- a/app/Api/V1/Controllers/Autocomplete/RecurrenceController.php +++ b/app/Api/V1/Controllers/Autocomplete/RecurrenceController.php @@ -67,7 +67,7 @@ class RecurrenceController extends Controller 'id' => (string) $recurrence->id, 'name' => $recurrence->title, 'description' => $recurrence->description, - 'active' => $recurrence->active, + 'active' => $recurrence->active ]; } diff --git a/app/Api/V1/Controllers/Autocomplete/RuleController.php b/app/Api/V1/Controllers/Autocomplete/RuleController.php index d0a509156a..1801850cbf 100644 --- a/app/Api/V1/Controllers/Autocomplete/RuleController.php +++ b/app/Api/V1/Controllers/Autocomplete/RuleController.php @@ -67,7 +67,7 @@ class RuleController extends Controller 'id' => (string) $rule->id, 'name' => $rule->title, 'description' => $rule->description, - 'active' => $rule->active, + 'active' => $rule->active ]; } diff --git a/app/Api/V1/Controllers/Autocomplete/RuleGroupController.php b/app/Api/V1/Controllers/Autocomplete/RuleGroupController.php index 51acc4a3c2..2327442eb2 100644 --- a/app/Api/V1/Controllers/Autocomplete/RuleGroupController.php +++ b/app/Api/V1/Controllers/Autocomplete/RuleGroupController.php @@ -67,7 +67,7 @@ class RuleGroupController extends Controller 'id' => (string) $group->id, 'name' => $group->title, 'description' => $group->description, - 'active' => $group->active, + 'active' => $group->active ]; } diff --git a/app/Api/V1/Controllers/Autocomplete/TransactionController.php b/app/Api/V1/Controllers/Autocomplete/TransactionController.php index 6f17845992..3b88b39427 100644 --- a/app/Api/V1/Controllers/Autocomplete/TransactionController.php +++ b/app/Api/V1/Controllers/Autocomplete/TransactionController.php @@ -53,7 +53,7 @@ class TransactionController extends Controller parent::__construct(); $this->middleware(function (Request $request, $next) { $this->validateUserGroup($request); - $this->repository = app(JournalRepositoryInterface::class); + $this->repository = app(JournalRepositoryInterface::class); $this->groupRepository = app(TransactionGroupRepositoryInterface::class); $this->repository->setUser($this->user); $this->repository->setUserGroup($this->userGroup); @@ -66,7 +66,7 @@ class TransactionController extends Controller public function transactions(AutocompleteTransactionApiRequest $request): JsonResponse { - $result = $this->repository->searchJournalDescriptions($request->attributes->get('query'), $request->attributes->get('limit')); + $result = $this->repository->searchJournalDescriptions($request->attributes->get('query'), $request->attributes->get('limit')); // limit and unique $filtered = $result->unique('description'); @@ -78,7 +78,7 @@ class TransactionController extends Controller 'id' => (string) $journal->id, 'transaction_group_id' => (string) $journal->transaction_group_id, 'name' => $journal->description, - 'description' => $journal->description, + 'description' => $journal->description ]; } @@ -103,7 +103,7 @@ class TransactionController extends Controller } // limit and unique - $array = []; + $array = []; /** @var TransactionJournal $journal */ foreach ($result as $journal) { @@ -111,7 +111,7 @@ class TransactionController extends Controller 'id' => (string) $journal->id, 'transaction_group_id' => (string) $journal->transaction_group_id, 'name' => sprintf('#%d: %s', $journal->transaction_group_id, $journal->description), - 'description' => sprintf('#%d: %s', $journal->transaction_group_id, $journal->description), + 'description' => sprintf('#%d: %s', $journal->transaction_group_id, $journal->description) ]; } diff --git a/app/Api/V1/Controllers/Chart/AccountController.php b/app/Api/V1/Controllers/Chart/AccountController.php index 36effec09a..7f07f63622 100644 --- a/app/Api/V1/Controllers/Chart/AccountController.php +++ b/app/Api/V1/Controllers/Chart/AccountController.php @@ -51,7 +51,7 @@ class AccountController extends Controller protected array $acceptedRoles = [UserRoleEnum::READ_ONLY]; - private array $chartData = []; + private array $chartData = []; private AccountRepositoryInterface $repository; /** @@ -99,18 +99,18 @@ class AccountController extends Controller private function renderAccountData(array $params, Account $account): void { Log::debug(sprintf('Now in %s(array, #%d)', __METHOD__, $account->id)); - $currency = $this->repository->getAccountCurrency($account); - $currentStart = clone $params['start']; - $range = Steam::finalAccountBalanceInRange($account, $params['start'], clone $params['end'], $this->convertToPrimary); - $period = $params['period'] ?? '1D'; + $currency = $this->repository->getAccountCurrency($account); + $currentStart = clone $params['start']; + $range = Steam::finalAccountBalanceInRange($account, $params['start'], clone $params['end'], $this->convertToPrimary); + $period = $params['period'] ?? '1D'; - $previous = array_values($range)[0]['balance']; - $pcPrevious = null; + $previous = array_values($range)[0]['balance']; + $pcPrevious = null; if (!$currency instanceof TransactionCurrency) { $currency = $this->primaryCurrency; } - $currentSet = [ - 'label' => $account->name, + $currentSet = [ + 'label' => $account->name, // the currency that belongs to the account. 'currency_id' => (string) $currency->id, @@ -120,43 +120,43 @@ class AccountController extends Controller 'currency_decimal_places' => $currency->decimal_places, // the primary currency - 'primary_currency_id' => (string) $this->primaryCurrency->id, + 'primary_currency_id' => (string) $this->primaryCurrency->id, // the default currency of the user (could be the same!) - 'date' => $params['start']->toAtomString(), - 'start_date' => $params['start']->toAtomString(), - 'end_date' => $params['end']->toAtomString(), - 'type' => 'line', - 'yAxisID' => 0, - 'period' => $period, - 'entries' => [], - 'pc_entries' => [], + 'date' => $params['start']->toAtomString(), + 'start_date' => $params['start']->toAtomString(), + 'end_date' => $params['end']->toAtomString(), + 'type' => 'line', + 'yAxisID' => 0, + 'period' => $period, + 'entries' => [], + 'pc_entries' => [] ]; if ($this->convertToPrimary) { - $currentSet['pc_entries'] = []; - $currentSet['primary_currency_id'] = (string) $this->primaryCurrency->id; - $currentSet['primary_currency_code'] = $this->primaryCurrency->code; - $currentSet['primary_currency_symbol'] = $this->primaryCurrency->symbol; + $currentSet['pc_entries'] = []; + $currentSet['primary_currency_id'] = (string) $this->primaryCurrency->id; + $currentSet['primary_currency_code'] = $this->primaryCurrency->code; + $currentSet['primary_currency_symbol'] = $this->primaryCurrency->symbol; $currentSet['primary_currency_decimal_places'] = $this->primaryCurrency->decimal_places; - $pcPrevious = array_values($range)[0]['pc_balance']; + $pcPrevious = array_values($range)[0]['pc_balance']; } // create array of values to collect. while ($currentStart <= $params['end']) { - $format = $currentStart->format('Y-m-d'); - $label = $currentStart->toAtomString(); - $balance = array_key_exists($format, $range) ? $range[$format]['balance'] : $previous; - $previous = $balance; + $format = $currentStart->format('Y-m-d'); + $label = $currentStart->toAtomString(); + $balance = array_key_exists($format, $range) ? $range[$format]['balance'] : $previous; + $previous = $balance; $currentSet['entries'][$label] = $balance; // do the same for the primary currency balance, if relevant: - $pcBalance = null; + $pcBalance = null; if ($this->convertToPrimary) { - $pcBalance = array_key_exists($format, $range) ? $range[$format]['pc_balance'] : $pcPrevious; - $pcPrevious = $pcBalance; + $pcBalance = array_key_exists($format, $range) ? $range[$format]['pc_balance'] : $pcPrevious; + $pcPrevious = $pcBalance; $currentSet['pc_entries'][$label] = $pcBalance; } - $currentStart = Navigation::addPeriod($currentStart, $period); + $currentStart = Navigation::addPeriod($currentStart, $period); // $currentStart->addDay(); } diff --git a/app/Api/V1/Controllers/Chart/BalanceController.php b/app/Api/V1/Controllers/Chart/BalanceController.php index e65a3af8ad..74c69fcc2e 100644 --- a/app/Api/V1/Controllers/Chart/BalanceController.php +++ b/app/Api/V1/Controllers/Chart/BalanceController.php @@ -47,7 +47,7 @@ class BalanceController extends Controller protected array $acceptedRoles = [UserRoleEnum::READ_ONLY]; - private array $chartData = []; + private array $chartData = []; private GroupCollectorInterface $collector; private AccountRepositoryInterface $repository; @@ -59,7 +59,7 @@ class BalanceController extends Controller $this->middleware(function (Request $request, $next) { $this->validateUserGroup($request); $this->repository = app(AccountRepositoryInterface::class); - $this->collector = app(GroupCollectorInterface::class); + $this->collector = app(GroupCollectorInterface::class); $this->repository->setUserGroup($this->userGroup); $this->collector->setUserGroup($this->userGroup); $this->repository->setUser($this->user); @@ -95,12 +95,11 @@ class BalanceController extends Controller TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::RECONCILIATION->value, - TransactionTypeEnum::TRANSFER->value, - ]) - ; - $journals = $this->collector->getExtractedJournals(); + TransactionTypeEnum::TRANSFER->value + ]); + $journals = $this->collector->getExtractedJournals(); - $object = new AccountBalanceGrouped(); + $object = new AccountBalanceGrouped(); $object->setPreferredRange($queryParameters['period']); $object->setPrimary($this->primaryCurrency); $object->setAccounts($accounts); @@ -108,7 +107,7 @@ class BalanceController extends Controller $object->setStart($queryParameters['start']); $object->setEnd($queryParameters['end']); $object->groupByCurrencyAndPeriod(); - $data = $object->convertToChartData(); + $data = $object->convertToChartData(); foreach ($data as $entry) { $this->chartData[] = $entry; } diff --git a/app/Api/V1/Controllers/Chart/BudgetController.php b/app/Api/V1/Controllers/Chart/BudgetController.php index 07fd41b6b5..7f19cc6d35 100644 --- a/app/Api/V1/Controllers/Chart/BudgetController.php +++ b/app/Api/V1/Controllers/Chart/BudgetController.php @@ -56,7 +56,7 @@ class BudgetController extends Controller protected OperationsRepositoryInterface $opsRepository; private BudgetLimitRepositoryInterface $blRepository; - private array $currencies = []; + private array $currencies = []; private BudgetRepositoryInterface $repository; public function __construct() @@ -64,8 +64,8 @@ class BudgetController extends Controller parent::__construct(); $this->middleware(function (Request $request, $next) { $this->validateUserGroup($request); - $this->repository = app(BudgetRepositoryInterface::class); - $this->blRepository = app(BudgetLimitRepositoryInterface::class); + $this->repository = app(BudgetRepositoryInterface::class); + $this->blRepository = app(BudgetLimitRepositoryInterface::class); $this->opsRepository = app(OperationsRepositoryInterface::class); $this->repository->setUserGroup($this->userGroup); $this->opsRepository->setUserGroup($this->userGroup); @@ -86,10 +86,10 @@ class BudgetController extends Controller public function overview(DateRangeRequest $request): JsonResponse { /** @var Carbon $start */ - $start = $request->attributes->get('start'); + $start = $request->attributes->get('start'); /** @var Carbon $end */ - $end = $request->attributes->get('end'); + $end = $request->attributes->get('end'); // code from FrontpageChartGenerator, but not in separate class $budgets = $this->repository->getActiveBudgets(); @@ -123,48 +123,48 @@ class BudgetController extends Controller */ foreach ($expenses as $currencyId => $row) { // budgeted, left and overspent are now 0. - $limit = $this->filterLimit($currencyId, $limits); + $limit = $this->filterLimit($currencyId, $limits); // primary currency entries - $row['pc_budgeted'] = '0'; - $row['pc_spent'] = '0'; - $row['pc_left'] = '0'; + $row['pc_budgeted'] = '0'; + $row['pc_spent'] = '0'; + $row['pc_left'] = '0'; $row['pc_overspent'] = '0'; if ($limit instanceof BudgetLimit) { - $row['budgeted'] = $limit->amount; - $row['left'] = bcsub((string) $row['budgeted'], bcmul((string) $row['spent'], '-1')); + $row['budgeted'] = $limit->amount; + $row['left'] = bcsub((string) $row['budgeted'], bcmul((string) $row['spent'], '-1')); $row['overspent'] = bcmul($row['left'], '-1'); - $row['left'] = 1 === bccomp($row['left'], '0') ? $row['left'] : '0'; + $row['left'] = 1 === bccomp($row['left'], '0') ? $row['left'] : '0'; $row['overspent'] = 1 === bccomp($row['overspent'], '0') ? $row['overspent'] : '0'; } // convert data if necessary. if ($this->convertToPrimary && $currencyId !== $this->primaryCurrency->id) { $currencies[$currencyId] ??= Amount::getTransactionCurrencyById($currencyId); - $row['pc_budgeted'] = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $row['budgeted']); - $row['pc_spent'] = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $row['spent']); - $row['pc_left'] = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $row['left']); + $row['pc_budgeted'] = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $row['budgeted']); + $row['pc_spent'] = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $row['spent']); + $row['pc_left'] = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $row['left']); $row['pc_overspent'] = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $row['overspent']); } if ($this->convertToPrimary && $currencyId === $this->primaryCurrency->id) { - $row['pc_budgeted'] = $row['budgeted']; - $row['pc_spent'] = $row['spent']; - $row['pc_left'] = $row['left']; + $row['pc_budgeted'] = $row['budgeted']; + $row['pc_spent'] = $row['spent']; + $row['pc_left'] = $row['left']; $row['pc_overspent'] = $row['overspent']; } - $rows[] = $row; + $rows[] = $row; } // is always an array - $return = []; + $return = []; foreach ($rows as $row) { - $current = [ - 'label' => $budget->name, - 'currency_id' => (string) $row['currency_id'], - 'currency_name' => $row['currency_name'], - 'currency_code' => $row['currency_code'], - 'currency_decimal_places' => $row['currency_decimal_places'], + $current = [ + 'label' => $budget->name, + 'currency_id' => (string) $row['currency_id'], + 'currency_name' => $row['currency_name'], + 'currency_code' => $row['currency_code'], + 'currency_decimal_places' => $row['currency_decimal_places'], 'primary_currency_id' => (string) $this->primaryCurrency->id, 'primary_currency_name' => $this->primaryCurrency->name, @@ -172,19 +172,19 @@ class BudgetController extends Controller 'primary_currency_symbol' => $this->primaryCurrency->symbol, 'primary_currency_decimal_places' => $this->primaryCurrency->decimal_places, - 'period' => null, - 'date' => $row['start'], - 'start_date' => $row['start'], - 'end_date' => $row['end'], - 'yAxisID' => 0, - 'type' => 'bar', - 'entries' => ['budgeted' => $row['budgeted'], 'spent' => $row['spent'], 'left' => $row['left'], 'overspent' => $row['overspent']], - 'pc_entries' => [ + 'period' => null, + 'date' => $row['start'], + 'start_date' => $row['start'], + 'end_date' => $row['end'], + 'yAxisID' => 0, + 'type' => 'bar', + 'entries' => ['budgeted' => $row['budgeted'], 'spent' => $row['spent'], 'left' => $row['left'], 'overspent' => $row['overspent']], + 'pc_entries' => [ 'budgeted' => $row['pc_budgeted'], 'spent' => $row['pc_spent'], 'left' => $row['pc_left'], - 'overspent' => $row['pc_overspent'], - ], + 'overspent' => $row['pc_overspent'] + ] ]; $return[] = $current; } @@ -224,7 +224,7 @@ class BudgetController extends Controller */ foreach ($spent as $currencyId => $block) { $this->currencies[$currencyId] ??= Amount::getTransactionCurrencyById($currencyId); - $return[$currencyId] ??= [ + $return[$currencyId] ??= [ 'currency_id' => (string) $currencyId, 'currency_code' => $block['currency_code'], 'currency_name' => $block['currency_name'], @@ -235,7 +235,7 @@ class BudgetController extends Controller 'budgeted' => '0', 'spent' => '0', 'left' => '0', - 'overspent' => '0', + 'overspent' => '0' ]; $currentBudgetArray = $block['budgets'][$budgetId]; @@ -243,7 +243,7 @@ class BudgetController extends Controller /** @var array $journal */ foreach ($currentBudgetArray['transaction_journals'] as $journal) { /** @var numeric-string $amount */ - $amount = (string) $journal['amount']; + $amount = (string) $journal['amount']; $return[$currencyId]['spent'] = bcadd($return[$currencyId]['spent'], $amount); } } @@ -251,7 +251,7 @@ class BudgetController extends Controller return $return; } - private function filterLimit(int $currencyId, Collection $limits): ?BudgetLimit + private function filterLimit(int $currencyId, Collection $limits): null|BudgetLimit { $amount = '0'; $limit = null; diff --git a/app/Api/V1/Controllers/Chart/CategoryController.php b/app/Api/V1/Controllers/Chart/CategoryController.php index 679dab4e5c..cd22995017 100644 --- a/app/Api/V1/Controllers/Chart/CategoryController.php +++ b/app/Api/V1/Controllers/Chart/CategoryController.php @@ -60,7 +60,7 @@ class CategoryController extends Controller parent::__construct(); $this->middleware(function (Request $request, $next) { $this->validateUserGroup($request); - $this->accountRepos = app(AccountRepositoryInterface::class); + $this->accountRepos = app(AccountRepositoryInterface::class); $this->currencyRepos = app(CurrencyRepositoryInterface::class); $this->accountRepos->setUserGroup($this->userGroup); $this->currencyRepos->setUserGroup($this->userGroup); @@ -82,7 +82,7 @@ class CategoryController extends Controller public function overview(DateRangeRequest $request): JsonResponse { /** @var Carbon $start */ - $start = $request->attributes->get('start'); + $start = $request->attributes->get('start'); /** @var Carbon $end */ $end = $request->attributes->get('end'); @@ -90,7 +90,7 @@ class CategoryController extends Controller AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value, - AccountTypeEnum::ASSET->value, + AccountTypeEnum::ASSET->value ]); $currencies = []; $return = []; @@ -98,26 +98,26 @@ class CategoryController extends Controller // get journals for entire period: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setRange($start, $end)->withAccountInformation(); $collector->setXorAccounts($accounts)->withCategoryInformation(); $collector->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::DEPOSIT->value]); - $journals = $collector->getExtractedJournals(); + $journals = $collector->getExtractedJournals(); /** @var array $journal */ foreach ($journals as $journal) { // find journal: - $journalCurrencyId = (int) $journal['currency_id']; - $type = $journal['transaction_type_type']; - $currency = $currencies[$journalCurrencyId] ?? $this->currencyRepos->find($journalCurrencyId); + $journalCurrencyId = (int) $journal['currency_id']; + $type = $journal['transaction_type_type']; + $currency = $currencies[$journalCurrencyId] ?? $this->currencyRepos->find($journalCurrencyId); $currencies[$journalCurrencyId] = $currency; - $currencyId = $currency->id; - $currencyName = $currency->name; - $currencyCode = $currency->code; - $currencySymbol = $currency->symbol; - $currencyDecimalPlaces = $currency->decimal_places; - $amount = Steam::positive((string) $journal['amount']); - $pcAmount = null; + $currencyId = $currency->id; + $currencyName = $currency->name; + $currencyCode = $currency->code; + $currencySymbol = $currency->symbol; + $currencyDecimalPlaces = $currency->decimal_places; + $amount = Steam::positive((string) $journal['amount']); + $pcAmount = null; // overrule if necessary: if ($this->convertToPrimary && $journalCurrencyId === $this->primaryCurrency->id) { @@ -133,8 +133,8 @@ class CategoryController extends Controller Log::debug(sprintf('Converted %s %s to %s %s', $journal['currency_code'], $amount, $this->primaryCurrency->code, $pcAmount)); } - $categoryName = $journal['category_name'] ?? (string) trans('firefly.no_category'); - $key = sprintf('%s-%s', $categoryName, $currencyCode); + $categoryName = $journal['category_name'] ?? (string) trans('firefly.no_category'); + $key = sprintf('%s-%s', $categoryName, $currencyCode); // create arrays $return[$key] ??= [ 'label' => $categoryName, @@ -154,7 +154,7 @@ class CategoryController extends Controller 'yAxisID' => 0, 'type' => 'bar', 'entries' => ['spent' => '0', 'earned' => '0'], - 'pc_entries' => ['spent' => '0', 'earned' => '0'], + 'pc_entries' => ['spent' => '0', 'earned' => '0'] ]; // add monies @@ -175,10 +175,10 @@ class CategoryController extends Controller } } } - $return = array_values($return); + $return = array_values($return); // order by amount - usort($return, static fn (array $a, array $b): int => ((float) $a['entries']['spent'] + (float) $a['entries']['earned']) + usort($return, static fn(array $a, array $b): int => ((float) $a['entries']['spent'] + (float) $a['entries']['earned']) < ((float) $b['entries']['spent'] + (float) $b['entries']['earned']) ? 1 : -1); diff --git a/app/Api/V1/Controllers/Controller.php b/app/Api/V1/Controllers/Controller.php index eab84c1be8..1ee342bcbc 100644 --- a/app/Api/V1/Controllers/Controller.php +++ b/app/Api/V1/Controllers/Controller.php @@ -66,9 +66,9 @@ abstract class Controller extends BaseController protected const string CONTENT_TYPE = 'application/vnd.api+json'; protected const string JSON_CONTENT_TYPE = 'application/json'; - protected array $accepts = ['application/json', 'application/vnd.api+json']; + protected array $accepts = ['application/json', 'application/vnd.api+json']; - protected bool $convertToPrimary = false; + protected bool $convertToPrimary = false; protected TransactionCurrency $primaryCurrency; /** @deprecated use Request classes */ @@ -83,9 +83,9 @@ abstract class Controller extends BaseController $this->middleware(function ($request, $next) { $this->parameters = $this->getParameters(); if (auth()->check()) { - $language = Steam::getLanguage(); + $language = Steam::getLanguage(); $this->convertToPrimary = Amount::convertToPrimary(); - $this->primaryCurrency = Amount::getPrimaryCurrency(); + $this->primaryCurrency = Amount::getPrimaryCurrency(); app()->setLocale($language); } @@ -99,18 +99,18 @@ abstract class Controller extends BaseController } #[Deprecated(message: <<<'TXT' - use Request classes - Method to grab all parameters from the URL - TXT)] + use Request classes + Method to grab all parameters from the URL + TXT)] private function getParameters(): ParameterBag { - $bag = new ParameterBag(); - $page = (int) request()->get('page'); - $page = min(max(1, $page), 2 ** 16); + $bag = new ParameterBag(); + $page = (int) request()->get('page'); + $page = min(max(1, $page), 2 ** 16); $bag->set('page', $page); // some date fields: - $dates = ['start', 'end', 'date']; + $dates = ['start', 'end', 'date']; foreach ($dates as $field) { $date = null; @@ -121,7 +121,7 @@ abstract class Controller extends BaseController Log::error($e->getMessage()); Log::error($e->getTraceAsString()); } - $obj = null; + $obj = null; if (null !== $date) { try { $obj = Carbon::parse((string) $date, config('app.timezone')); @@ -158,7 +158,7 @@ abstract class Controller extends BaseController ) { // set default for user: /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $pageSize = (int) Preferences::getForUser($user, 'listPageSize', 50)->data; $bag->set($integer, $pageSize); @@ -190,14 +190,14 @@ abstract class Controller extends BaseController $params[$key] = $value; } - return $return.http_build_query($params); + return $return . http_build_query($params); } final protected function getManager(): Manager { // create some objects: $manager = new Manager(); - $baseUrl = request()->getSchemeAndHttpHost().'/api/v1'; + $baseUrl = request()->getSchemeAndHttpHost() . '/api/v1'; $manager->setSerializer(new JsonApiSerializer($baseUrl)); return $manager; @@ -205,14 +205,14 @@ abstract class Controller extends BaseController final protected function jsonApiList(string $key, LengthAwarePaginator $paginator, AbstractTransformer $transformer): array { - $manager = new Manager(); - $baseUrl = sprintf('%s/api/v1/', request()->getSchemeAndHttpHost()); + $manager = new Manager(); + $baseUrl = sprintf('%s/api/v1/', request()->getSchemeAndHttpHost()); // TODO add stuff to path? $manager->setSerializer(new JsonApiSerializer($baseUrl)); - $objects = $paginator->getCollection(); + $objects = $paginator->getCollection(); // the transformer, at this point, needs to collect information that ALL items in the collection // require, like meta-data and stuff like that, and save it for later. @@ -233,8 +233,8 @@ abstract class Controller extends BaseController final protected function jsonApiObject(string $key, array|Model $object, AbstractTransformer $transformer): array { // create some objects: - $manager = new Manager(); - $baseUrl = sprintf('%s/api/v1', request()->getSchemeAndHttpHost()); + $manager = new Manager(); + $baseUrl = sprintf('%s/api/v1', request()->getSchemeAndHttpHost()); $manager->setSerializer(new JsonApiSerializer($baseUrl)); $resource = new Item($object, $transformer, $key); diff --git a/app/Api/V1/Controllers/Data/Bulk/TransactionController.php b/app/Api/V1/Controllers/Data/Bulk/TransactionController.php index d896f60fe8..4f4012244c 100644 --- a/app/Api/V1/Controllers/Data/Bulk/TransactionController.php +++ b/app/Api/V1/Controllers/Data/Bulk/TransactionController.php @@ -24,13 +24,13 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Controllers\Data\Bulk; -use Illuminate\Http\Request; use FireflyIII\Api\V1\Controllers\Controller; use FireflyIII\Api\V1\Requests\Data\Bulk\TransactionRequest; use FireflyIII\Enums\UserRoleEnum; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Services\Internal\Destroy\AccountDestroyService; use Illuminate\Http\JsonResponse; +use Illuminate\Http\Request; /** * Class TransactionController @@ -51,16 +51,14 @@ class TransactionController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function (Request $request, $next) { - $this->validateUserGroup($request); - $this->repository = app(AccountRepositoryInterface::class); - $this->repository->setUserGroup($this->userGroup); - $this->repository->setUser($this->user); + $this->middleware(function (Request $request, $next) { + $this->validateUserGroup($request); + $this->repository = app(AccountRepositoryInterface::class); + $this->repository->setUserGroup($this->userGroup); + $this->repository->setUser($this->user); - return $next($request); - } - ); + return $next($request); + }); } public function update(TransactionRequest $request): JsonResponse @@ -76,7 +74,7 @@ class TransactionController extends Controller $destination = $this->repository->find((int) $params['update']['account_id']); /** @var AccountDestroyService $service */ - $service = app(AccountDestroyService::class); + $service = app(AccountDestroyService::class); $service->moveTransactions($original, $destination); } diff --git a/app/Api/V1/Controllers/Data/DestroyController.php b/app/Api/V1/Controllers/Data/DestroyController.php index ab519becbe..ce9d9ab6dd 100644 --- a/app/Api/V1/Controllers/Data/DestroyController.php +++ b/app/Api/V1/Controllers/Data/DestroyController.php @@ -72,8 +72,8 @@ class DestroyController extends Controller public function destroy(DestroyRequest $request): JsonResponse { - $objects = $request->getObjects(); - $this->unused = $request->boolean('unused'); + $objects = $request->getObjects(); + $this->unused = $request->boolean('unused'); $allExceptAssets = [ AccountTypeEnum::BENEFICIARY->value, @@ -85,7 +85,7 @@ class DestroyController extends Controller AccountTypeEnum::INITIAL_BALANCE->value, AccountTypeEnum::LIABILITY_CREDIT->value, AccountTypeEnum::RECONCILIATION->value, - AccountTypeEnum::REVENUE->value, + AccountTypeEnum::REVENUE->value ]; $all = [ AccountTypeEnum::ASSET->value, @@ -100,36 +100,36 @@ class DestroyController extends Controller AccountTypeEnum::LIABILITY_CREDIT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value, - AccountTypeEnum::RECONCILIATION->value, + AccountTypeEnum::RECONCILIATION->value ]; $liabilities = [AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::CREDITCARD->value]; $transactions = [ TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value, - TransactionTypeEnum::RECONCILIATION->value, + TransactionTypeEnum::RECONCILIATION->value ]; match ($objects) { - 'budgets' => $this->destroyBudgets(), - 'bills' => $this->destroyBills(), - 'piggy_banks' => $this->destroyPiggyBanks(), - 'rules' => $this->destroyRules(), - 'recurring' => $this->destroyRecurringTransactions(), - 'categories' => $this->destroyCategories(), - 'tags' => $this->destroyTags(), - 'object_groups' => $this->destroyObjectGroups(), + 'budgets' => $this->destroyBudgets(), + 'bills' => $this->destroyBills(), + 'piggy_banks' => $this->destroyPiggyBanks(), + 'rules' => $this->destroyRules(), + 'recurring' => $this->destroyRecurringTransactions(), + 'categories' => $this->destroyCategories(), + 'tags' => $this->destroyTags(), + 'object_groups' => $this->destroyObjectGroups(), 'not_assets_liabilities' => $this->destroyAccounts($allExceptAssets), - 'accounts' => $this->destroyAccounts($all), - 'asset_accounts' => $this->destroyAccounts([AccountTypeEnum::ASSET->value, AccountTypeEnum::DEFAULT->value]), - 'expense_accounts' => $this->destroyAccounts([AccountTypeEnum::BENEFICIARY->value, AccountTypeEnum::EXPENSE->value]), - 'revenue_accounts' => $this->destroyAccounts([AccountTypeEnum::REVENUE->value]), - 'liabilities' => $this->destroyAccounts($liabilities), - 'transactions' => $this->destroyTransactions($transactions), - 'withdrawals' => $this->destroyTransactions([TransactionTypeEnum::WITHDRAWAL->value]), - 'deposits' => $this->destroyTransactions([TransactionTypeEnum::DEPOSIT->value]), - 'transfers' => $this->destroyTransactions([TransactionTypeEnum::TRANSFER->value]), - default => throw new FireflyException(sprintf('200033: This endpoint can\'t handle object "%s"', $objects)) + 'accounts' => $this->destroyAccounts($all), + 'asset_accounts' => $this->destroyAccounts([AccountTypeEnum::ASSET->value, AccountTypeEnum::DEFAULT->value]), + 'expense_accounts' => $this->destroyAccounts([AccountTypeEnum::BENEFICIARY->value, AccountTypeEnum::EXPENSE->value]), + 'revenue_accounts' => $this->destroyAccounts([AccountTypeEnum::REVENUE->value]), + 'liabilities' => $this->destroyAccounts($liabilities), + 'transactions' => $this->destroyTransactions($transactions), + 'withdrawals' => $this->destroyTransactions([TransactionTypeEnum::WITHDRAWAL->value]), + 'deposits' => $this->destroyTransactions([TransactionTypeEnum::DEPOSIT->value]), + 'transfers' => $this->destroyTransactions([TransactionTypeEnum::TRANSFER->value]), + default => throw new FireflyException(sprintf('200033: This endpoint can\'t handle object "%s"', $objects)) }; Preferences::mark(); @@ -140,11 +140,11 @@ class DestroyController extends Controller private function destroyBudgets(): void { /** @var AvailableBudgetRepositoryInterface $abRepository */ - $abRepository = app(AvailableBudgetRepositoryInterface::class); + $abRepository = app(AvailableBudgetRepositoryInterface::class); $abRepository->destroyAll(); /** @var BudgetLimitRepositoryInterface $blRepository */ - $blRepository = app(BudgetLimitRepositoryInterface::class); + $blRepository = app(BudgetLimitRepositoryInterface::class); $blRepository->destroyAll(); /** @var BudgetRepositoryInterface $budgetRepository */ diff --git a/app/Api/V1/Controllers/Data/Export/ExportController.php b/app/Api/V1/Controllers/Data/Export/ExportController.php index 0f055c4428..ce4c1c8472 100644 --- a/app/Api/V1/Controllers/Data/Export/ExportController.php +++ b/app/Api/V1/Controllers/Data/Export/ExportController.php @@ -24,12 +24,12 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Controllers\Data\Export; -use Illuminate\Http\Request; use FireflyIII\Api\V1\Controllers\Controller; use FireflyIII\Api\V1\Requests\Data\Export\ExportRequest; use FireflyIII\Enums\UserRoleEnum; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Support\Export\ExportDataGenerator; +use Illuminate\Http\Request; use Illuminate\Http\Response as LaravelResponse; use Safe\Exceptions\DatetimeException; @@ -49,16 +49,14 @@ class ExportController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function (Request $request, $next) { - $this->validateUserGroup($request); - $this->exporter = app(ExportDataGenerator::class); - $this->exporter->setUserGroup($this->userGroup); - $this->exporter->setUser($this->user); + $this->middleware(function (Request $request, $next) { + $this->validateUserGroup($request); + $this->exporter = app(ExportDataGenerator::class); + $this->exporter->setUserGroup($this->userGroup); + $this->exporter->setUser($this->user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -89,14 +87,13 @@ class ExportController extends Controller $response ->header('Content-Description', 'File Transfer') ->header('Content-Type', 'application/octet-stream') - ->header('Content-Disposition', 'attachment; filename='.$fileName) + ->header('Content-Disposition', 'attachment; filename=' . $fileName) ->header('Content-Transfer-Encoding', 'binary') ->header('Connection', 'Keep-Alive') ->header('Expires', '0') ->header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0') ->header('Pragma', 'public') - ->header('Content-Length', (string) strlen((string) $data[$key])) - ; + ->header('Content-Length', (string) strlen((string) $data[$key])); return $response; } diff --git a/app/Api/V1/Controllers/Data/PurgeController.php b/app/Api/V1/Controllers/Data/PurgeController.php index 2af2cd8bab..c49e436a0b 100644 --- a/app/Api/V1/Controllers/Data/PurgeController.php +++ b/app/Api/V1/Controllers/Data/PurgeController.php @@ -64,7 +64,7 @@ class PurgeController extends Controller public function purge(): JsonResponse { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); // some manual code, too lazy to call all repositories. diff --git a/app/Api/V1/Controllers/Insight/Expense/AccountController.php b/app/Api/V1/Controllers/Insight/Expense/AccountController.php index 889fdce65d..c4d71f3e3e 100644 --- a/app/Api/V1/Controllers/Insight/Expense/AccountController.php +++ b/app/Api/V1/Controllers/Insight/Expense/AccountController.php @@ -42,7 +42,7 @@ class AccountController extends Controller use ApiSupport; private OperationsRepositoryInterface $opsRepository; - private AccountRepositoryInterface $repository; + private AccountRepositoryInterface $repository; /** * AccountController constructor. @@ -50,18 +50,16 @@ class AccountController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $user = auth()->user(); - $this->repository = app(AccountRepositoryInterface::class); - $this->repository->setUser($user); + $this->middleware(function ($request, $next) { + $user = auth()->user(); + $this->repository = app(AccountRepositoryInterface::class); + $this->repository->setUser($user); - $this->opsRepository = app(OperationsRepositoryInterface::class); - $this->opsRepository->setUser($user); + $this->opsRepository = app(OperationsRepositoryInterface::class); + $this->opsRepository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } public function asset(GenericRequest $request): JsonResponse @@ -79,8 +77,8 @@ class AccountController extends Controller 'name' => $expense['name'], 'difference' => $expense['sum'], 'difference_float' => (float) $expense['sum'], // intentional float - 'currency_id' => (string) $expense['currency_id'], - 'currency_code' => $expense['currency_code'], + 'currency_id' => (string) $expense['currency_id'], + 'currency_code' => $expense['currency_code'] ]; } @@ -103,8 +101,8 @@ class AccountController extends Controller 'name' => $expense['name'], 'difference' => $expense['sum'], 'difference_float' => (float) $expense['sum'], // intentional float - 'currency_id' => (string) $expense['currency_id'], - 'currency_code' => $expense['currency_code'], + 'currency_id' => (string) $expense['currency_id'], + 'currency_code' => $expense['currency_code'] ]; } diff --git a/app/Api/V1/Controllers/Insight/Expense/BillController.php b/app/Api/V1/Controllers/Insight/Expense/BillController.php index 55cd1dc77c..2b253bcca0 100644 --- a/app/Api/V1/Controllers/Insight/Expense/BillController.php +++ b/app/Api/V1/Controllers/Insight/Expense/BillController.php @@ -46,15 +46,13 @@ class BillController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $user = auth()->user(); - $this->repository = app(BillRepositoryInterface::class); - $this->repository->setUser($user); + $this->middleware(function ($request, $next) { + $user = auth()->user(); + $this->repository = app(BillRepositoryInterface::class); + $this->repository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -76,11 +74,11 @@ class BillController extends Controller } // collect all expenses in this period (regardless of type) by the given bills and accounts. - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setTypes([TransactionTypeEnum::WITHDRAWAL->value])->setRange($start, $end)->setSourceAccounts($accounts); $collector->setBills($bills); - $genericSet = $collector->getExtractedJournals(); + $genericSet = $collector->getExtractedJournals(); foreach ($genericSet as $journal) { $billId = (int) $journal['bill_id']; $currencyId = (int) $journal['currency_id']; @@ -97,9 +95,16 @@ class BillController extends Controller if ($convertToPrimary && $journal['currency_id'] !== $primary->id && $primary->id === $journal['foreign_currency_id']) { $field = 'foreign_amount'; } - Log::debug(sprintf('Journal #%d in bill #%d will use %s (%s %s)', $journal['transaction_group_id'], $billId, $field, $currencyCode, $journal[$field] ?? '0')); + Log::debug(sprintf( + 'Journal #%d in bill #%d will use %s (%s %s)', + $journal['transaction_group_id'], + $billId, + $field, + $currencyCode, + $journal[$field] ?? '0' + )); - $key = sprintf('%d-%d', $billId, $currencyId); + $key = sprintf('%d-%d', $billId, $currencyId); if (0 !== $currencyId) { $response[$key] ??= [ @@ -108,9 +113,9 @@ class BillController extends Controller 'difference' => '0', 'difference_float' => 0, 'currency_id' => (string) $currencyId, - 'currency_code' => $currencyCode, + 'currency_code' => $currencyCode ]; - $response[$key]['difference'] = bcadd($response[$key]['difference'], (string) ($journal[$field] ?? '0')); + $response[$key]['difference'] = bcadd($response[$key]['difference'], (string) ($journal[$field] ?? '0')); $response[$key]['difference_float'] = (float) $response[$key]['difference']; // intentional float } } @@ -131,11 +136,11 @@ class BillController extends Controller $response = []; // collect all expenses in this period (regardless of type) by the given bills and accounts. - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setTypes([TransactionTypeEnum::WITHDRAWAL->value])->setRange($start, $end)->setSourceAccounts($accounts); $collector->withoutBill(); - $genericSet = $collector->getExtractedJournals(); + $genericSet = $collector->getExtractedJournals(); foreach ($genericSet as $journal) { $currencyId = (int) $journal['currency_id']; @@ -159,9 +164,9 @@ class BillController extends Controller 'difference' => '0', 'difference_float' => 0, 'currency_id' => (string) $currencyId, - 'currency_code' => $currencyCode, + 'currency_code' => $currencyCode ]; - $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], (string) ($journal[$field] ?? '0')); + $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], (string) ($journal[$field] ?? '0')); $response[$currencyId]['difference_float'] = (float) $response[$currencyId]['difference']; // intentional float } } diff --git a/app/Api/V1/Controllers/Insight/Expense/BudgetController.php b/app/Api/V1/Controllers/Insight/Expense/BudgetController.php index 84686fb367..8b7d53b87e 100644 --- a/app/Api/V1/Controllers/Insight/Expense/BudgetController.php +++ b/app/Api/V1/Controllers/Insight/Expense/BudgetController.php @@ -38,9 +38,9 @@ use Illuminate\Support\Collection; */ class BudgetController extends Controller { - private NoBudgetRepositoryInterface $noRepository; + private NoBudgetRepositoryInterface $noRepository; private OperationsRepositoryInterface $opsRepository; - private BudgetRepositoryInterface $repository; + private BudgetRepositoryInterface $repository; /** * AccountController constructor. @@ -48,19 +48,17 @@ class BudgetController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->opsRepository = app(OperationsRepositoryInterface::class); - $this->repository = app(BudgetRepositoryInterface::class); - $this->noRepository = app(NoBudgetRepositoryInterface::class); - $user = auth()->user(); - $this->opsRepository->setUser($user); - $this->repository->setUser($user); - $this->noRepository->setUser($user); + $this->middleware(function ($request, $next) { + $this->opsRepository = app(OperationsRepositoryInterface::class); + $this->repository = app(BudgetRepositoryInterface::class); + $this->noRepository = app(NoBudgetRepositoryInterface::class); + $user = auth()->user(); + $this->opsRepository->setUser($user); + $this->repository->setUser($user); + $this->noRepository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } public function budget(GenericRequest $request): JsonResponse @@ -85,8 +83,8 @@ class BudgetController extends Controller 'name' => $budget->name, 'difference' => $expense['sum'], 'difference_float' => (float) $expense['sum'], // intentional float - 'currency_id' => (string) $expense['currency_id'], - 'currency_code' => $expense['currency_code'], + 'currency_id' => (string) $expense['currency_id'], + 'currency_code' => $expense['currency_code'] ]; } } @@ -107,8 +105,8 @@ class BudgetController extends Controller $result[] = [ 'difference' => $expense['sum'], 'difference_float' => (float) $expense['sum'], // intentional float - 'currency_id' => (string) $expense['currency_id'], - 'currency_code' => $expense['currency_code'], + 'currency_id' => (string) $expense['currency_id'], + 'currency_code' => $expense['currency_code'] ]; } diff --git a/app/Api/V1/Controllers/Insight/Expense/CategoryController.php b/app/Api/V1/Controllers/Insight/Expense/CategoryController.php index c470cef7ae..34d62bfb9d 100644 --- a/app/Api/V1/Controllers/Insight/Expense/CategoryController.php +++ b/app/Api/V1/Controllers/Insight/Expense/CategoryController.php @@ -40,7 +40,7 @@ class CategoryController extends Controller { private NoCategoryRepositoryInterface $noRepository; private OperationsRepositoryInterface $opsRepository; - private CategoryRepositoryInterface $repository; + private CategoryRepositoryInterface $repository; /** * AccountController constructor. @@ -48,19 +48,17 @@ class CategoryController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->opsRepository = app(OperationsRepositoryInterface::class); - $this->repository = app(CategoryRepositoryInterface::class); - $this->noRepository = app(NoCategoryRepositoryInterface::class); - $user = auth()->user(); - $this->opsRepository->setUser($user); - $this->repository->setUser($user); - $this->noRepository->setUser($user); + $this->middleware(function ($request, $next) { + $this->opsRepository = app(OperationsRepositoryInterface::class); + $this->repository = app(CategoryRepositoryInterface::class); + $this->noRepository = app(NoCategoryRepositoryInterface::class); + $user = auth()->user(); + $this->opsRepository->setUser($user); + $this->repository->setUser($user); + $this->noRepository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } public function category(GenericRequest $request): JsonResponse @@ -85,8 +83,8 @@ class CategoryController extends Controller 'name' => $category->name, 'difference' => $expense['sum'], 'difference_float' => (float) $expense['sum'], // intentional float - 'currency_id' => (string) $expense['currency_id'], - 'currency_code' => $expense['currency_code'], + 'currency_id' => (string) $expense['currency_id'], + 'currency_code' => $expense['currency_code'] ]; } } @@ -107,8 +105,8 @@ class CategoryController extends Controller $result[] = [ 'difference' => $expense['sum'], 'difference_float' => (float) $expense['sum'], // intentional float - 'currency_id' => (string) $expense['currency_id'], - 'currency_code' => $expense['currency_code'], + 'currency_id' => (string) $expense['currency_id'], + 'currency_code' => $expense['currency_code'] ]; } diff --git a/app/Api/V1/Controllers/Insight/Expense/PeriodController.php b/app/Api/V1/Controllers/Insight/Expense/PeriodController.php index 3e03ec287b..db65c264c8 100644 --- a/app/Api/V1/Controllers/Insight/Expense/PeriodController.php +++ b/app/Api/V1/Controllers/Insight/Expense/PeriodController.php @@ -47,14 +47,14 @@ class PeriodController extends Controller $primary = Amount::getPrimaryCurrency(); // collect all expenses in this period (regardless of type) - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setTypes([TransactionTypeEnum::WITHDRAWAL->value])->setRange($start, $end)->setSourceAccounts($accounts); - $genericSet = $collector->getExtractedJournals(); + $genericSet = $collector->getExtractedJournals(); foreach ($genericSet as $journal) { // same code as many other sumExpense methods. I think this needs some kind of generic method. - $amount = '0'; - $currencyId = (int) $journal['currency_id']; - $currencyCode = $journal['currency_code']; + $amount = '0'; + $currencyId = (int) $journal['currency_id']; + $currencyCode = $journal['currency_code']; if ($convertToPrimary) { $amount = Amount::getAmountFromJournal($journal); if ($primary->id !== (int) $journal['currency_id'] && $primary->id !== (int) $journal['foreign_currency_id']) { @@ -73,14 +73,13 @@ class PeriodController extends Controller $amount = $journal['amount']; } - $response[$currencyId] ??= [ 'difference' => '0', 'difference_float' => 0, 'currency_id' => (string) $currencyId, - 'currency_code' => $currencyCode, + 'currency_code' => $currencyCode ]; - $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], $amount); + $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], $amount); $response[$currencyId]['difference_float'] = (float) $response[$currencyId]['difference']; // intentional float } diff --git a/app/Api/V1/Controllers/Insight/Expense/TagController.php b/app/Api/V1/Controllers/Insight/Expense/TagController.php index ff98df82fe..b98e5898c5 100644 --- a/app/Api/V1/Controllers/Insight/Expense/TagController.php +++ b/app/Api/V1/Controllers/Insight/Expense/TagController.php @@ -46,14 +46,12 @@ class TagController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(TagRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(TagRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -69,17 +67,17 @@ class TagController extends Controller $primary = Amount::getPrimaryCurrency(); // collect all expenses in this period (regardless of type) by the given bills and accounts. - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setTypes([TransactionTypeEnum::WITHDRAWAL->value])->setRange($start, $end)->setSourceAccounts($accounts); $collector->withoutTags(); - $genericSet = $collector->getExtractedJournals(); + $genericSet = $collector->getExtractedJournals(); foreach ($genericSet as $journal) { // same code as many other sumExpense methods. I think this needs some kind of generic method. - $amount = '0'; - $currencyId = (int) $journal['currency_id']; - $currencyCode = $journal['currency_code']; + $amount = '0'; + $currencyId = (int) $journal['currency_id']; + $currencyCode = $journal['currency_code']; if ($convertToPrimary) { $amount = Amount::getAmountFromJournal($journal); if ($primary->id !== (int) $journal['currency_id'] && $primary->id !== (int) $journal['foreign_currency_id']) { @@ -102,9 +100,9 @@ class TagController extends Controller 'difference' => '0', 'difference_float' => 0, 'currency_id' => (string) $currencyId, - 'currency_code' => $currencyCode, + 'currency_code' => $currencyCode ]; - $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], $amount); + $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], $amount); $response[$currencyId]['difference_float'] = (float) $response[$currencyId]['difference']; // float but on purpose. } @@ -116,11 +114,11 @@ class TagController extends Controller */ public function tag(GenericRequest $request): JsonResponse { - $accounts = $request->getAssetAccounts(); - $tags = $request->getTags(); - $start = $request->getStart(); - $end = $request->getEnd(); - $response = []; + $accounts = $request->getAssetAccounts(); + $tags = $request->getTags(); + $start = $request->getStart(); + $end = $request->getEnd(); + $response = []; // get all tags: if (0 === $tags->count()) { @@ -128,7 +126,7 @@ class TagController extends Controller } // collect all expenses in this period (regardless of type) by the given bills and accounts. - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setTypes([TransactionTypeEnum::WITHDRAWAL->value])->setRange($start, $end)->setSourceAccounts($accounts); $collector->setTags($tags); $genericSet = $collector->getExtractedJournals(); @@ -152,21 +150,21 @@ class TagController extends Controller 'difference' => '0', 'difference_float' => 0, 'currency_id' => (string) $currencyId, - 'currency_code' => $journal['currency_code'], + 'currency_code' => $journal['currency_code'] ]; - $response[$key]['difference'] = bcadd((string) $response[$key]['difference'], (string) $journal['amount']); + $response[$key]['difference'] = bcadd((string) $response[$key]['difference'], (string) $journal['amount']); $response[$key]['difference_float'] = (float) $response[$key]['difference']; // float but on purpose. } // on foreign ID if (0 !== $foreignCurrencyId) { - $response[$foreignKey] = $journal[$foreignKey] ?? [ + $response[$foreignKey] = $journal[$foreignKey] ?? [ 'difference' => '0', 'difference_float' => 0, 'currency_id' => (string) $foreignCurrencyId, - 'currency_code' => $journal['foreign_currency_code'], + 'currency_code' => $journal['foreign_currency_code'] ]; - $response[$foreignKey]['difference'] = bcadd((string) $response[$foreignKey]['difference'], (string) $journal['foreign_amount']); + $response[$foreignKey]['difference'] = bcadd((string) $response[$foreignKey]['difference'], (string) $journal['foreign_amount']); $response[$foreignKey]['difference_float'] = (float) $response[$foreignKey]['difference']; // float but on purpose. } } diff --git a/app/Api/V1/Controllers/Insight/Income/AccountController.php b/app/Api/V1/Controllers/Insight/Income/AccountController.php index d167092261..9343a9ff4a 100644 --- a/app/Api/V1/Controllers/Insight/Income/AccountController.php +++ b/app/Api/V1/Controllers/Insight/Income/AccountController.php @@ -42,7 +42,7 @@ class AccountController extends Controller use ApiSupport; private OperationsRepositoryInterface $opsRepository; - private AccountRepositoryInterface $repository; + private AccountRepositoryInterface $repository; /** * AccountController constructor. @@ -50,18 +50,16 @@ class AccountController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $user = auth()->user(); - $this->repository = app(AccountRepositoryInterface::class); - $this->repository->setUser($user); + $this->middleware(function ($request, $next) { + $user = auth()->user(); + $this->repository = app(AccountRepositoryInterface::class); + $this->repository->setUser($user); - $this->opsRepository = app(OperationsRepositoryInterface::class); - $this->opsRepository->setUser($user); + $this->opsRepository = app(OperationsRepositoryInterface::class); + $this->opsRepository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } public function asset(GenericRequest $request): JsonResponse @@ -70,8 +68,8 @@ class AccountController extends Controller $end = $request->getEnd(); $assetAccounts = $request->getAssetAccounts(); - $income = $this->opsRepository->sumIncomeByDestination($start, $end, $assetAccounts); - $result = []; + $income = $this->opsRepository->sumIncomeByDestination($start, $end, $assetAccounts); + $result = []; /** @var array $entry */ foreach ($income as $entry) { @@ -80,8 +78,8 @@ class AccountController extends Controller 'name' => $entry['name'], 'difference' => $entry['sum'], 'difference_float' => (float) $entry['sum'], // float but on purpose. - 'currency_id' => (string) $entry['currency_id'], - 'currency_code' => $entry['currency_code'], + 'currency_id' => (string) $entry['currency_id'], + 'currency_code' => $entry['currency_code'] ]; } @@ -104,8 +102,8 @@ class AccountController extends Controller 'name' => $entry['name'], 'difference' => $entry['sum'], 'difference_float' => (float) $entry['sum'], // float but on purpose. - 'currency_id' => (string) $entry['currency_id'], - 'currency_code' => $entry['currency_code'], + 'currency_id' => (string) $entry['currency_id'], + 'currency_code' => $entry['currency_code'] ]; } diff --git a/app/Api/V1/Controllers/Insight/Income/CategoryController.php b/app/Api/V1/Controllers/Insight/Income/CategoryController.php index e2fb1d527d..774a8d91af 100644 --- a/app/Api/V1/Controllers/Insight/Income/CategoryController.php +++ b/app/Api/V1/Controllers/Insight/Income/CategoryController.php @@ -40,7 +40,7 @@ class CategoryController extends Controller { private NoCategoryRepositoryInterface $noRepository; private OperationsRepositoryInterface $opsRepository; - private CategoryRepositoryInterface $repository; + private CategoryRepositoryInterface $repository; /** * AccountController constructor. @@ -48,19 +48,17 @@ class CategoryController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->opsRepository = app(OperationsRepositoryInterface::class); - $this->repository = app(CategoryRepositoryInterface::class); - $this->noRepository = app(NoCategoryRepositoryInterface::class); - $user = auth()->user(); - $this->opsRepository->setUser($user); - $this->repository->setUser($user); - $this->noRepository->setUser($user); + $this->middleware(function ($request, $next) { + $this->opsRepository = app(OperationsRepositoryInterface::class); + $this->repository = app(CategoryRepositoryInterface::class); + $this->noRepository = app(NoCategoryRepositoryInterface::class); + $user = auth()->user(); + $this->opsRepository->setUser($user); + $this->repository->setUser($user); + $this->noRepository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } public function category(GenericRequest $request): JsonResponse @@ -85,8 +83,8 @@ class CategoryController extends Controller 'name' => $category->name, 'difference' => $expense['sum'], 'difference_float' => (float) $expense['sum'], // float but on purpose. - 'currency_id' => (string) $expense['currency_id'], - 'currency_code' => $expense['currency_code'], + 'currency_id' => (string) $expense['currency_id'], + 'currency_code' => $expense['currency_code'] ]; } } @@ -107,8 +105,8 @@ class CategoryController extends Controller $result[] = [ 'difference' => $expense['sum'], 'difference_float' => (float) $expense['sum'], // float but on purpose. - 'currency_id' => (string) $expense['currency_id'], - 'currency_code' => $expense['currency_code'], + 'currency_id' => (string) $expense['currency_id'], + 'currency_code' => $expense['currency_code'] ]; } diff --git a/app/Api/V1/Controllers/Insight/Income/PeriodController.php b/app/Api/V1/Controllers/Insight/Income/PeriodController.php index f413788066..9fd3f92490 100644 --- a/app/Api/V1/Controllers/Insight/Income/PeriodController.php +++ b/app/Api/V1/Controllers/Insight/Income/PeriodController.php @@ -47,14 +47,14 @@ class PeriodController extends Controller $primary = Amount::getPrimaryCurrency(); // collect all expenses in this period (regardless of type) - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setTypes([TransactionTypeEnum::DEPOSIT->value])->setRange($start, $end)->setDestinationAccounts($accounts); - $genericSet = $collector->getExtractedJournals(); + $genericSet = $collector->getExtractedJournals(); foreach ($genericSet as $journal) { // currency - $currencyId = $journal['currency_id']; - $currencyCode = $journal['currency_code']; - $field = $convertToPrimary && $currencyId !== $primary->id ? 'pc_amount' : 'amount'; + $currencyId = $journal['currency_id']; + $currencyCode = $journal['currency_code']; + $field = $convertToPrimary && $currencyId !== $primary->id ? 'pc_amount' : 'amount'; // perhaps use default currency instead? if ($convertToPrimary && $journal['currency_id'] !== $primary->id) { @@ -70,9 +70,9 @@ class PeriodController extends Controller 'difference' => '0', 'difference_float' => 0, 'currency_id' => (string) $currencyId, - 'currency_code' => $currencyCode, + 'currency_code' => $currencyCode ]; - $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], Steam::positive($journal[$field])); + $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], Steam::positive($journal[$field])); $response[$currencyId]['difference_float'] = (float) $response[$currencyId]['difference']; // float but on purpose. } diff --git a/app/Api/V1/Controllers/Insight/Income/TagController.php b/app/Api/V1/Controllers/Insight/Income/TagController.php index 49d6721b02..168bd891d9 100644 --- a/app/Api/V1/Controllers/Insight/Income/TagController.php +++ b/app/Api/V1/Controllers/Insight/Income/TagController.php @@ -46,15 +46,13 @@ class TagController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $user = auth()->user(); - $this->repository = app(TagRepositoryInterface::class); - $this->repository->setUser($user); + $this->middleware(function ($request, $next) { + $user = auth()->user(); + $this->repository = app(TagRepositoryInterface::class); + $this->repository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -70,17 +68,17 @@ class TagController extends Controller $primary = Amount::getPrimaryCurrency(); // collect all expenses in this period (regardless of type) by the given bills and accounts. - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setTypes([TransactionTypeEnum::DEPOSIT->value])->setRange($start, $end)->setDestinationAccounts($accounts); $collector->withoutTags(); - $genericSet = $collector->getExtractedJournals(); + $genericSet = $collector->getExtractedJournals(); foreach ($genericSet as $journal) { // currency - $currencyId = $journal['currency_id']; - $currencyCode = $journal['currency_code']; - $field = $convertToPrimary && $currencyId !== $primary->id ? 'pc_amount' : 'amount'; + $currencyId = $journal['currency_id']; + $currencyCode = $journal['currency_code']; + $field = $convertToPrimary && $currencyId !== $primary->id ? 'pc_amount' : 'amount'; // perhaps use default currency instead? if ($convertToPrimary && $journal['currency_id'] !== $primary->id) { @@ -96,11 +94,10 @@ class TagController extends Controller 'difference' => '0', 'difference_float' => 0, 'currency_id' => (string) $currencyId, - 'currency_code' => $currencyCode, + 'currency_code' => $currencyCode ]; - $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], Steam::positive($journal[$field])); + $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], Steam::positive($journal[$field])); $response[$currencyId]['difference_float'] = (float) $response[$currencyId]['difference']; - } return response()->json(array_values($response)); @@ -111,11 +108,11 @@ class TagController extends Controller */ public function tag(GenericRequest $request): JsonResponse { - $accounts = $request->getAssetAccounts(); - $tags = $request->getTags(); - $start = $request->getStart(); - $end = $request->getEnd(); - $response = []; + $accounts = $request->getAssetAccounts(); + $tags = $request->getTags(); + $start = $request->getStart(); + $end = $request->getEnd(); + $response = []; // get all tags: if (0 === $tags->count()) { @@ -123,7 +120,7 @@ class TagController extends Controller } // collect all expenses in this period (regardless of type) by the given bills and accounts. - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setTypes([TransactionTypeEnum::DEPOSIT->value])->setRange($start, $end)->setDestinationAccounts($accounts); $collector->setTags($tags); $genericSet = $collector->getExtractedJournals(); @@ -147,21 +144,21 @@ class TagController extends Controller 'difference' => '0', 'difference_float' => 0, 'currency_id' => (string) $currencyId, - 'currency_code' => $journal['currency_code'], + 'currency_code' => $journal['currency_code'] ]; - $response[$key]['difference'] = bcadd((string) $response[$key]['difference'], Steam::positive($journal['amount'])); + $response[$key]['difference'] = bcadd((string) $response[$key]['difference'], Steam::positive($journal['amount'])); $response[$key]['difference_float'] = (float) $response[$key]['difference']; } // on foreign ID if (0 !== $foreignCurrencyId) { - $response[$foreignKey] = $journal[$foreignKey] ?? [ + $response[$foreignKey] = $journal[$foreignKey] ?? [ 'difference' => '0', 'difference_float' => 0, 'currency_id' => (string) $foreignCurrencyId, - 'currency_code' => $journal['foreign_currency_code'], + 'currency_code' => $journal['foreign_currency_code'] ]; - $response[$foreignKey]['difference'] = bcadd((string) $response[$foreignKey]['difference'], Steam::positive($journal['foreign_amount'])); + $response[$foreignKey]['difference'] = bcadd((string) $response[$foreignKey]['difference'], Steam::positive($journal['foreign_amount'])); $response[$foreignKey]['difference_float'] = (float) $response[$foreignKey]['difference']; } } diff --git a/app/Api/V1/Controllers/Insight/Transfer/AccountController.php b/app/Api/V1/Controllers/Insight/Transfer/AccountController.php index ce9e1635aa..968f22bd64 100644 --- a/app/Api/V1/Controllers/Insight/Transfer/AccountController.php +++ b/app/Api/V1/Controllers/Insight/Transfer/AccountController.php @@ -45,15 +45,13 @@ class AccountController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $user = auth()->user(); - $this->opsRepository = app(OperationsRepositoryInterface::class); - $this->opsRepository->setUser($user); + $this->middleware(function ($request, $next) { + $user = auth()->user(); + $this->opsRepository = app(OperationsRepositoryInterface::class); + $this->opsRepository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } public function asset(GenericRequest $request): JsonResponse diff --git a/app/Api/V1/Controllers/Insight/Transfer/CategoryController.php b/app/Api/V1/Controllers/Insight/Transfer/CategoryController.php index 4df25a96f8..9c8083932c 100644 --- a/app/Api/V1/Controllers/Insight/Transfer/CategoryController.php +++ b/app/Api/V1/Controllers/Insight/Transfer/CategoryController.php @@ -40,7 +40,7 @@ class CategoryController extends Controller { private NoCategoryRepositoryInterface $noRepository; private OperationsRepositoryInterface $opsRepository; - private CategoryRepositoryInterface $repository; + private CategoryRepositoryInterface $repository; /** * AccountController constructor. @@ -48,19 +48,17 @@ class CategoryController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->opsRepository = app(OperationsRepositoryInterface::class); - $this->repository = app(CategoryRepositoryInterface::class); - $this->noRepository = app(NoCategoryRepositoryInterface::class); - $user = auth()->user(); - $this->opsRepository->setUser($user); - $this->repository->setUser($user); - $this->noRepository->setUser($user); + $this->middleware(function ($request, $next) { + $this->opsRepository = app(OperationsRepositoryInterface::class); + $this->repository = app(CategoryRepositoryInterface::class); + $this->noRepository = app(NoCategoryRepositoryInterface::class); + $user = auth()->user(); + $this->opsRepository->setUser($user); + $this->repository->setUser($user); + $this->noRepository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } public function category(GenericRequest $request): JsonResponse @@ -86,7 +84,7 @@ class CategoryController extends Controller 'difference' => $expense['sum'], 'difference_float' => (float) $expense['sum'], 'currency_id' => (string) $expense['currency_id'], - 'currency_code' => $expense['currency_code'], + 'currency_code' => $expense['currency_code'] ]; } } @@ -108,7 +106,7 @@ class CategoryController extends Controller 'difference' => $expense['sum'], 'difference_float' => (float) $expense['sum'], 'currency_id' => (string) $expense['currency_id'], - 'currency_code' => $expense['currency_code'], + 'currency_code' => $expense['currency_code'] ]; } diff --git a/app/Api/V1/Controllers/Insight/Transfer/PeriodController.php b/app/Api/V1/Controllers/Insight/Transfer/PeriodController.php index bc716225bb..2532bf53b0 100644 --- a/app/Api/V1/Controllers/Insight/Transfer/PeriodController.php +++ b/app/Api/V1/Controllers/Insight/Transfer/PeriodController.php @@ -47,14 +47,14 @@ class PeriodController extends Controller $primary = Amount::getPrimaryCurrency(); // collect all expenses in this period (regardless of type) - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setTypes([TransactionTypeEnum::TRANSFER->value])->setRange($start, $end)->setDestinationAccounts($accounts); - $genericSet = $collector->getExtractedJournals(); + $genericSet = $collector->getExtractedJournals(); foreach ($genericSet as $journal) { // currency - $currencyId = $journal['currency_id']; - $currencyCode = $journal['currency_code']; - $field = $convertToPrimary && $currencyId !== $primary->id ? 'pc_amount' : 'amount'; + $currencyId = $journal['currency_id']; + $currencyCode = $journal['currency_code']; + $field = $convertToPrimary && $currencyId !== $primary->id ? 'pc_amount' : 'amount'; // perhaps use default currency instead? if ($convertToPrimary && $journal['currency_id'] !== $primary->id) { @@ -70,11 +70,10 @@ class PeriodController extends Controller 'difference' => '0', 'difference_float' => 0, 'currency_id' => (string) $currencyId, - 'currency_code' => $currencyCode, + 'currency_code' => $currencyCode ]; - $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], Steam::positive($journal[$field])); + $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], Steam::positive($journal[$field])); $response[$currencyId]['difference_float'] = (float) $response[$currencyId]['difference']; - } return response()->json(array_values($response)); diff --git a/app/Api/V1/Controllers/Insight/Transfer/TagController.php b/app/Api/V1/Controllers/Insight/Transfer/TagController.php index 0fe8b86e17..4dce153611 100644 --- a/app/Api/V1/Controllers/Insight/Transfer/TagController.php +++ b/app/Api/V1/Controllers/Insight/Transfer/TagController.php @@ -46,15 +46,13 @@ class TagController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $user = auth()->user(); - $this->repository = app(TagRepositoryInterface::class); - $this->repository->setUser($user); + $this->middleware(function ($request, $next) { + $user = auth()->user(); + $this->repository = app(TagRepositoryInterface::class); + $this->repository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } public function noTag(GenericRequest $request): JsonResponse @@ -66,19 +64,18 @@ class TagController extends Controller $convertToPrimary = Amount::convertToPrimary(); $primary = Amount::getPrimaryCurrency(); - // collect all expenses in this period (regardless of type) by the given bills and accounts. - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setTypes([TransactionTypeEnum::TRANSFER->value])->setRange($start, $end)->setDestinationAccounts($accounts); $collector->withoutTags(); - $genericSet = $collector->getExtractedJournals(); + $genericSet = $collector->getExtractedJournals(); foreach ($genericSet as $journal) { // currency - $currencyId = $journal['currency_id']; - $currencyCode = $journal['currency_code']; - $field = $convertToPrimary && $currencyId !== $primary->id ? 'pc_amount' : 'amount'; + $currencyId = $journal['currency_id']; + $currencyCode = $journal['currency_code']; + $field = $convertToPrimary && $currencyId !== $primary->id ? 'pc_amount' : 'amount'; // perhaps use default currency instead? if ($convertToPrimary && $journal['currency_id'] !== $primary->id) { @@ -94,11 +91,10 @@ class TagController extends Controller 'difference' => '0', 'difference_float' => 0, 'currency_id' => (string) $currencyId, - 'currency_code' => $currencyCode, + 'currency_code' => $currencyCode ]; - $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], Steam::positive($journal[$field])); + $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], Steam::positive($journal[$field])); $response[$currencyId]['difference_float'] = (float) $response[$currencyId]['difference']; - } return response()->json(array_values($response)); @@ -109,11 +105,11 @@ class TagController extends Controller */ public function tag(GenericRequest $request): JsonResponse { - $accounts = $request->getAssetAccounts(); - $tags = $request->getTags(); - $start = $request->getStart(); - $end = $request->getEnd(); - $response = []; + $accounts = $request->getAssetAccounts(); + $tags = $request->getTags(); + $start = $request->getStart(); + $end = $request->getEnd(); + $response = []; // get all tags: if (0 === $tags->count()) { @@ -121,7 +117,7 @@ class TagController extends Controller } // collect all expenses in this period (regardless of type) by the given bills and accounts. - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setTypes([TransactionTypeEnum::TRANSFER->value])->setRange($start, $end)->setDestinationAccounts($accounts); $collector->setTags($tags); $genericSet = $collector->getExtractedJournals(); @@ -145,24 +141,21 @@ class TagController extends Controller 'difference' => '0', 'difference_float' => 0, 'currency_id' => (string) $currencyId, - 'currency_code' => $journal['currency_code'], + 'currency_code' => $journal['currency_code'] ]; - $response[$key]['difference'] = bcadd((string) $response[$key]['difference'], Steam::positive($journal['amount'])); + $response[$key]['difference'] = bcadd((string) $response[$key]['difference'], Steam::positive($journal['amount'])); $response[$key]['difference_float'] = (float) $response[$key]['difference']; } // on foreign ID if (0 !== $foreignCurrencyId) { - $response[$foreignKey] = $journal[$foreignKey] ?? [ + $response[$foreignKey] = $journal[$foreignKey] ?? [ 'difference' => '0', 'difference_float' => 0, 'currency_id' => (string) $foreignCurrencyId, - 'currency_code' => $journal['foreign_currency_code'], + 'currency_code' => $journal['foreign_currency_code'] ]; - $response[$foreignKey]['difference'] = bcadd( - (string) $response[$foreignKey]['difference'], - Steam::positive($journal['foreign_amount']) - ); + $response[$foreignKey]['difference'] = bcadd((string) $response[$foreignKey]['difference'], Steam::positive($journal['foreign_amount'])); $response[$foreignKey]['difference_float'] = (float) $response[$foreignKey]['difference']; // intentional float } } diff --git a/app/Api/V1/Controllers/Models/Account/DestroyController.php b/app/Api/V1/Controllers/Models/Account/DestroyController.php index d772b44557..c3359d66cf 100644 --- a/app/Api/V1/Controllers/Models/Account/DestroyController.php +++ b/app/Api/V1/Controllers/Models/Account/DestroyController.php @@ -45,14 +45,12 @@ class DestroyController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(AccountRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(AccountRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** diff --git a/app/Api/V1/Controllers/Models/Account/ListController.php b/app/Api/V1/Controllers/Models/Account/ListController.php index 5cf90ff2e6..47caec7efa 100644 --- a/app/Api/V1/Controllers/Models/Account/ListController.php +++ b/app/Api/V1/Controllers/Models/Account/ListController.php @@ -60,37 +60,31 @@ class ListController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(AccountRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(AccountRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } public function attachments(PaginationRequest $request, Account $account): JsonResponse { - $manager = $this->getManager(); - [ - 'limit' => $limit, - 'offset' => $offset, - 'page' => $page, - ] = $request->attributes->all(); - $collection = $this->repository->getAttachments($account); + $manager = $this->getManager(); + ['limit' => $limit, 'offset' => $offset, 'page' => $page] = $request->attributes->all(); + $collection = $this->repository->getAttachments($account); $count = $collection->count(); $attachments = $collection->slice($offset, $limit); // make paginator: - $paginator = new LengthAwarePaginator($attachments, $count, $limit, $page); - $paginator->setPath(route('api.v1.accounts.attachments', [$account->id]).$this->buildParams()); + $paginator = new LengthAwarePaginator($attachments, $count, $limit, $page); + $paginator->setPath(route('api.v1.accounts.attachments', [$account->id]) . $this->buildParams()); /** @var AttachmentTransformer $transformer */ $transformer = app(AttachmentTransformer::class); - $resource = new FractalCollection($attachments, $transformer, 'attachments'); + $resource = new FractalCollection($attachments, $transformer, 'attachments'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -99,35 +93,31 @@ class ListController extends Controller public function piggyBanks(PaginationRequest $request, Account $account): JsonResponse { // create some objects: - $manager = $this->getManager(); + $manager = $this->getManager(); - [ - 'limit' => $limit, - 'offset' => $offset, - 'page' => $page, - ] = $request->attributes->all(); + ['limit' => $limit, 'offset' => $offset, 'page' => $page] = $request->attributes->all(); // get list of piggy banks. Count it and split it. - $collection = $this->repository->getPiggyBanks($account); - $count = $collection->count(); - $piggyBanks = $collection->slice($offset, $limit); + $collection = $this->repository->getPiggyBanks($account); + $count = $collection->count(); + $piggyBanks = $collection->slice($offset, $limit); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new PiggyBankEnrichment(); + $admin = auth()->user(); + $enrichment = new PiggyBankEnrichment(); $enrichment->setUser($admin); - $piggyBanks = $enrichment->enrich($piggyBanks); + $piggyBanks = $enrichment->enrich($piggyBanks); // make paginator: - $paginator = new LengthAwarePaginator($piggyBanks, $count, $limit, $page); - $paginator->setPath(route('api.v1.accounts.piggy-banks', [$account->id]).$this->buildParams()); + $paginator = new LengthAwarePaginator($piggyBanks, $count, $limit, $page); + $paginator->setPath(route('api.v1.accounts.piggy-banks', [$account->id]) . $this->buildParams()); /** @var PiggyBankTransformer $transformer */ $transformer = app(PiggyBankTransformer::class); // $transformer->setParameters($this->parameters); - $resource = new FractalCollection($piggyBanks, $transformer, 'piggy-banks'); + $resource = new FractalCollection($piggyBanks, $transformer, 'piggy-banks'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -138,21 +128,15 @@ class ListController extends Controller */ public function transactions(PaginationDateRangeRequest $request, Account $account): JsonResponse { - [ - 'limit' => $limit, - 'page' => $page, - 'start' => $start, - 'end' => $end, - 'types' => $types, - ] = $request->attributes->all(); - $manager = $this->getManager(); + ['limit' => $limit, 'page' => $page, 'start' => $start, 'end' => $end, 'types' => $types] = $request->attributes->all(); + $manager = $this->getManager(); /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setUser($admin)->setAccounts(new Collection()->push($account))->withAPIInformation()->setLimit($limit)->setPage($page)->setTypes($types); if (null !== $start) { $collector->setStart($start); @@ -161,18 +145,18 @@ class ListController extends Controller $collector->setEnd($end); } - $paginator = $collector->getPaginatedGroups(); - $paginator->setPath(route('api.v1.accounts.transactions', [$account->id]).$this->buildParams()); + $paginator = $collector->getPaginatedGroups(); + $paginator->setPath(route('api.v1.accounts.transactions', [$account->id]) . $this->buildParams()); // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); $transactions = $enrichment->enrich($paginator->getCollection()); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); - $resource = new FractalCollection($transactions, $transformer, 'transactions'); + $resource = new FractalCollection($transactions, $transformer, 'transactions'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Models/Account/ShowController.php b/app/Api/V1/Controllers/Models/Account/ShowController.php index 4e979c84ba..08cd1c0568 100644 --- a/app/Api/V1/Controllers/Models/Account/ShowController.php +++ b/app/Api/V1/Controllers/Models/Account/ShowController.php @@ -55,14 +55,12 @@ class ShowController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(AccountRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(AccountRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -70,7 +68,7 @@ class ShowController extends Controller */ public function index(ShowRequest $request): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); [ 'types' => $types, 'page' => $page, @@ -79,38 +77,37 @@ class ShowController extends Controller 'sort' => $sort, 'start' => $start, 'end' => $end, - 'date' => $date, - ] - = $request->attributes->all(); + 'date' => $date + ] = $request->attributes->all(); // get list of accounts. Count it and split it. $this->repository->resetAccountOrder(); - $collection = $this->repository->getAccountsByType($types, $sort); - $count = $collection->count(); + $collection = $this->repository->getAccountsByType($types, $sort); + $count = $collection->count(); // continue sort: // TODO if the user sorts on DB dependent field there must be no slice before enrichment, only after. // TODO still need to figure out how to do this easily. - $accounts = $collection->slice($offset, $limit); + $accounts = $collection->slice($offset, $limit); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new AccountEnrichment(); + $admin = auth()->user(); + $enrichment = new AccountEnrichment(); $enrichment->setSort($sort); $enrichment->setDate($date); $enrichment->setStart($start); $enrichment->setEnd($end); $enrichment->setUser($admin); - $accounts = $enrichment->enrich($accounts); + $accounts = $enrichment->enrich($accounts); // make paginator: - $paginator = new LengthAwarePaginator($accounts, $count, $limit, $page); - $paginator->setPath(route('api.v1.accounts.index').$this->buildParams()); + $paginator = new LengthAwarePaginator($accounts, $count, $limit, $page); + $paginator->setPath(route('api.v1.accounts.index') . $this->buildParams()); /** @var AccountTransformer $transformer */ $transformer = app(AccountTransformer::class); - $resource = new FractalCollection($accounts, $transformer, self::RESOURCE_KEY); + $resource = new FractalCollection($accounts, $transformer, self::RESOURCE_KEY); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -127,25 +124,22 @@ class ShowController extends Controller // get list of accounts. Count it and split it. $this->repository->resetAccountOrder(); $account->refresh(); - $manager = $this->getManager(); - ['start' => $start, - 'end' => $end, - 'date' => $date,] = $request->attributes->all(); + $manager = $this->getManager(); + ['start' => $start, 'end' => $end, 'date' => $date] = $request->attributes->all(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new AccountEnrichment(); + $admin = auth()->user(); + $enrichment = new AccountEnrichment(); $enrichment->setDate($date); $enrichment->setStart($start); $enrichment->setEnd($end); $enrichment->setUser($admin); - $account = $enrichment->enrichSingle($account); - + $account = $enrichment->enrichSingle($account); /** @var AccountTransformer $transformer */ - $transformer = app(AccountTransformer::class); - $resource = new Item($account, $transformer, self::RESOURCE_KEY); + $transformer = app(AccountTransformer::class); + $resource = new Item($account, $transformer, self::RESOURCE_KEY); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Account/StoreController.php b/app/Api/V1/Controllers/Models/Account/StoreController.php index 3d9addc3c5..521e2b5c75 100644 --- a/app/Api/V1/Controllers/Models/Account/StoreController.php +++ b/app/Api/V1/Controllers/Models/Account/StoreController.php @@ -48,14 +48,12 @@ class StoreController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(AccountRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(AccountRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -66,23 +64,23 @@ class StoreController extends Controller */ public function store(StoreRequest $request): JsonResponse { - $data = $request->getAllAccountData(); + $data = $request->getAllAccountData(); $this->repository->resetAccountOrder(); - $account = $this->repository->store($data); - $manager = $this->getManager(); + $account = $this->repository->store($data); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new AccountEnrichment(); + $admin = auth()->user(); + $enrichment = new AccountEnrichment(); $enrichment->setDate(null); $enrichment->setUser($admin); - $account = $enrichment->enrichSingle($account); + $account = $enrichment->enrichSingle($account); /** @var AccountTransformer $transformer */ $transformer = app(AccountTransformer::class); - $resource = new Item($account, $transformer, self::RESOURCE_KEY); + $resource = new Item($account, $transformer, self::RESOURCE_KEY); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Account/UpdateController.php b/app/Api/V1/Controllers/Models/Account/UpdateController.php index 71cf69152f..526d1aadfa 100644 --- a/app/Api/V1/Controllers/Models/Account/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Account/UpdateController.php @@ -51,14 +51,12 @@ class UpdateController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(AccountRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(AccountRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -70,24 +68,24 @@ class UpdateController extends Controller public function update(UpdateRequest $request, Account $account): JsonResponse { Log::debug(sprintf('Now in %s', __METHOD__)); - $data = $request->getUpdateData(); - $data['type'] = config('firefly.shortNamesByFullName.'.$account->accountType->type); - $account = $this->repository->update($account, $data); - $manager = $this->getManager(); + $data = $request->getUpdateData(); + $data['type'] = config('firefly.shortNamesByFullName.' . $account->accountType->type); + $account = $this->repository->update($account, $data); + $manager = $this->getManager(); $account->refresh(); Preferences::mark(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new AccountEnrichment(); + $admin = auth()->user(); + $enrichment = new AccountEnrichment(); $enrichment->setDate(null); $enrichment->setUser($admin); - $account = $enrichment->enrichSingle($account); + $account = $enrichment->enrichSingle($account); /** @var AccountTransformer $transformer */ - $transformer = app(AccountTransformer::class); - $resource = new Item($account, $transformer, self::RESOURCE_KEY); + $transformer = app(AccountTransformer::class); + $resource = new Item($account, $transformer, self::RESOURCE_KEY); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Attachment/DestroyController.php b/app/Api/V1/Controllers/Models/Attachment/DestroyController.php index 09cfbe1557..98181e7eb1 100644 --- a/app/Api/V1/Controllers/Models/Attachment/DestroyController.php +++ b/app/Api/V1/Controllers/Models/Attachment/DestroyController.php @@ -48,16 +48,14 @@ class DestroyController extends Controller { parent::__construct(); $this->middleware(ApiDemoUser::class)->except(['delete', 'download', 'show', 'index']); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); - $this->repository = app(AttachmentRepositoryInterface::class); - $this->repository->setUser($user); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); + $this->repository = app(AttachmentRepositoryInterface::class); + $this->repository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** diff --git a/app/Api/V1/Controllers/Models/Attachment/ShowController.php b/app/Api/V1/Controllers/Models/Attachment/ShowController.php index 8b5099946b..844f5ae3f9 100644 --- a/app/Api/V1/Controllers/Models/Attachment/ShowController.php +++ b/app/Api/V1/Controllers/Models/Attachment/ShowController.php @@ -55,16 +55,14 @@ class ShowController extends Controller { parent::__construct(); $this->middleware(ApiDemoUser::class)->except(['delete', 'download', 'show', 'index']); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); - $this->repository = app(AttachmentRepositoryInterface::class); - $this->repository->setUser($user); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); + $this->repository = app(AttachmentRepositoryInterface::class); + $this->repository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -89,25 +87,24 @@ class ShowController extends Controller throw new FireflyException('200000: File has not been uploaded (yet).'); } if ($this->repository->exists($attachment)) { - $content = $this->repository->getContent($attachment); + $content = $this->repository->getContent($attachment); if ('' === $content) { throw new FireflyException('200002: File is empty (zero bytes).'); } - $quoted = sprintf('"%s"', addcslashes(basename($attachment->filename), '"\\')); + $quoted = sprintf('"%s"', addcslashes(basename($attachment->filename), '"\\')); /** @var LaravelResponse $response */ $response = response($content); $response ->header('Content-Description', 'File Transfer') ->header('Content-Type', 'application/octet-stream') - ->header('Content-Disposition', 'attachment; filename='.$quoted) + ->header('Content-Disposition', 'attachment; filename=' . $quoted) ->header('Content-Transfer-Encoding', 'binary') ->header('Connection', 'Keep-Alive') ->header('Expires', '0') ->header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0') ->header('Pragma', 'public') - ->header('Content-Length', (string) strlen($content)) - ; + ->header('Content-Length', (string) strlen($content)); return $response; } @@ -123,11 +120,7 @@ class ShowController extends Controller */ public function index(PaginationRequest $request): JsonResponse { - [ - 'limit' => $limit, - 'offset' => $offset, - 'page' => $page, - ] = $request->attributes->all(); + ['limit' => $limit, 'offset' => $offset, 'page' => $page] = $request->attributes->all(); if (true === auth()->user()->hasRole('demo')) { Log::channel('audit')->warning(sprintf('Demo user tries to access attachment API in %s', __METHOD__)); @@ -135,7 +128,7 @@ class ShowController extends Controller throw new NotFoundHttpException(); } - $manager = $this->getManager(); + $manager = $this->getManager(); // get list of attachments. Count it and split it. $collection = $this->repository->get(); @@ -143,13 +136,13 @@ class ShowController extends Controller $attachments = $collection->slice($offset, $limit); // make paginator: - $paginator = new LengthAwarePaginator($attachments, $count, $limit, $page); - $paginator->setPath(route('api.v1.attachments.index').$this->buildParams()); + $paginator = new LengthAwarePaginator($attachments, $count, $limit, $page); + $paginator->setPath(route('api.v1.attachments.index') . $this->buildParams()); /** @var AttachmentTransformer $transformer */ $transformer = app(AttachmentTransformer::class); - $resource = new FractalCollection($attachments, $transformer, 'attachments'); + $resource = new FractalCollection($attachments, $transformer, 'attachments'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -168,12 +161,12 @@ class ShowController extends Controller throw new NotFoundHttpException(); } - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var AttachmentTransformer $transformer */ $transformer = app(AttachmentTransformer::class); - $resource = new Item($attachment, $transformer, 'attachments'); + $resource = new Item($attachment, $transformer, 'attachments'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Attachment/StoreController.php b/app/Api/V1/Controllers/Models/Attachment/StoreController.php index 77e2060c36..b623993844 100644 --- a/app/Api/V1/Controllers/Models/Attachment/StoreController.php +++ b/app/Api/V1/Controllers/Models/Attachment/StoreController.php @@ -53,16 +53,14 @@ class StoreController extends Controller { parent::__construct(); $this->middleware(ApiDemoUser::class)->except(['delete', 'download', 'show', 'index']); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); - $this->repository = app(AttachmentRepositoryInterface::class); - $this->repository->setUser($user); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); + $this->repository = app(AttachmentRepositoryInterface::class); + $this->repository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -81,14 +79,14 @@ class StoreController extends Controller throw new NotFoundHttpException(); } Log::debug(sprintf('Now in %s', __METHOD__)); - $data = $request->getAll(); - $attachment = $this->repository->store($data); - $manager = $this->getManager(); + $data = $request->getAll(); + $attachment = $this->repository->store($data); + $manager = $this->getManager(); /** @var AttachmentTransformer $transformer */ $transformer = app(AttachmentTransformer::class); - $resource = new Item($attachment, $transformer, 'attachments'); + $resource = new Item($attachment, $transformer, 'attachments'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Attachment/UpdateController.php b/app/Api/V1/Controllers/Models/Attachment/UpdateController.php index 9945b61697..5b7900490a 100644 --- a/app/Api/V1/Controllers/Models/Attachment/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Attachment/UpdateController.php @@ -50,16 +50,14 @@ class UpdateController extends Controller { parent::__construct(); $this->middleware(ApiDemoUser::class)->except(['delete', 'download', 'show', 'index']); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); - $this->repository = app(AttachmentRepositoryInterface::class); - $this->repository->setUser($user); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); + $this->repository = app(AttachmentRepositoryInterface::class); + $this->repository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -75,14 +73,14 @@ class UpdateController extends Controller throw new NotFoundHttpException(); } - $data = $request->getAll(); + $data = $request->getAll(); $this->repository->update($attachment, $data); - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var AttachmentTransformer $transformer */ $transformer = app(AttachmentTransformer::class); - $resource = new Item($attachment, $transformer, 'attachments'); + $resource = new Item($attachment, $transformer, 'attachments'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/AvailableBudget/ShowController.php b/app/Api/V1/Controllers/Models/AvailableBudget/ShowController.php index c621d3fbab..638903e488 100644 --- a/app/Api/V1/Controllers/Models/AvailableBudget/ShowController.php +++ b/app/Api/V1/Controllers/Models/AvailableBudget/ShowController.php @@ -50,16 +50,14 @@ class ShowController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); - $this->abRepository = app(AvailableBudgetRepositoryInterface::class); - $this->abRepository->setUser($user); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); + $this->abRepository = app(AvailableBudgetRepositoryInterface::class); + $this->abRepository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -70,14 +68,8 @@ class ShowController extends Controller */ public function index(PaginationDateRangeRequest $request): JsonResponse { - $manager = $this->getManager(); - [ - 'limit' => $limit, - 'offset' => $offset, - 'page' => $page, - 'start' => $start, - 'end' => $end, - ] = $request->attributes->all(); + $manager = $this->getManager(); + ['limit' => $limit, 'offset' => $offset, 'page' => $page, 'start' => $start, 'end' => $end] = $request->attributes->all(); // get list of available budgets. Count it and split it. $collection = $this->abRepository->getAvailableBudgetsByDate($start, $end); @@ -86,19 +78,19 @@ class ShowController extends Controller // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new AvailableBudgetEnrichment(); + $admin = auth()->user(); + $enrichment = new AvailableBudgetEnrichment(); $enrichment->setUser($admin); $availableBudgets = $enrichment->enrich($availableBudgets); // make paginator: - $paginator = new LengthAwarePaginator($availableBudgets, $count, $limit, $page); - $paginator->setPath(route('api.v1.available-budgets.index').$this->buildParams()); + $paginator = new LengthAwarePaginator($availableBudgets, $count, $limit, $page); + $paginator->setPath(route('api.v1.available-budgets.index') . $this->buildParams()); /** @var AvailableBudgetTransformer $transformer */ - $transformer = app(AvailableBudgetTransformer::class); + $transformer = app(AvailableBudgetTransformer::class); - $resource = new FractalCollection($availableBudgets, $transformer, 'available_budgets'); + $resource = new FractalCollection($availableBudgets, $transformer, 'available_budgets'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -112,22 +104,21 @@ class ShowController extends Controller */ public function show(AvailableBudget $availableBudget): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // $start = $this->parameters->get('start'); // $end = $this->parameters->get('end'); /** @var AvailableBudgetTransformer $transformer */ - $transformer = app(AvailableBudgetTransformer::class); + $transformer = app(AvailableBudgetTransformer::class); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new AvailableBudgetEnrichment(); + $admin = auth()->user(); + $enrichment = new AvailableBudgetEnrichment(); $enrichment->setUser($admin); $availableBudget = $enrichment->enrichSingle($availableBudget); - - $resource = new Item($availableBudget, $transformer, 'available_budgets'); + $resource = new Item($availableBudget, $transformer, 'available_budgets'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Bill/DestroyController.php b/app/Api/V1/Controllers/Models/Bill/DestroyController.php index a709c73ec2..68f2f2322e 100644 --- a/app/Api/V1/Controllers/Models/Bill/DestroyController.php +++ b/app/Api/V1/Controllers/Models/Bill/DestroyController.php @@ -43,14 +43,12 @@ class DestroyController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(BillRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(BillRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** diff --git a/app/Api/V1/Controllers/Models/Bill/ListController.php b/app/Api/V1/Controllers/Models/Bill/ListController.php index 7face940cf..6d90120acb 100644 --- a/app/Api/V1/Controllers/Models/Bill/ListController.php +++ b/app/Api/V1/Controllers/Models/Bill/ListController.php @@ -56,14 +56,12 @@ class ListController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(BillRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(BillRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -74,25 +72,21 @@ class ListController extends Controller */ public function attachments(PaginationRequest $request, Bill $bill): JsonResponse { - [ - 'limit' => $limit, - 'offset' => $offset, - 'page' => $page, - ] = $request->attributes->all(); - $manager = $this->getManager(); - $collection = $this->repository->getAttachments($bill); + ['limit' => $limit, 'offset' => $offset, 'page' => $page] = $request->attributes->all(); + $manager = $this->getManager(); + $collection = $this->repository->getAttachments($bill); $count = $collection->count(); $attachments = $collection->slice($offset, $limit); // make paginator: - $paginator = new LengthAwarePaginator($attachments, $count, $limit, $page); - $paginator->setPath(route('api.v1.bills.attachments', [$bill->id]).$this->buildParams()); + $paginator = new LengthAwarePaginator($attachments, $count, $limit, $page); + $paginator->setPath(route('api.v1.bills.attachments', [$bill->id]) . $this->buildParams()); /** @var AttachmentTransformer $transformer */ $transformer = app(AttachmentTransformer::class); - $resource = new FractalCollection($attachments, $transformer, 'attachments'); + $resource = new FractalCollection($attachments, $transformer, 'attachments'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -106,20 +100,16 @@ class ListController extends Controller */ public function rules(PaginationRequest $request, Bill $bill): JsonResponse { - [ - 'limit' => $limit, - 'offset' => $offset, - 'page' => $page, - ] = $request->attributes->all(); + ['limit' => $limit, 'offset' => $offset, 'page' => $page] = $request->attributes->all(); - $manager = $this->getManager(); - $collection = $this->repository->getRulesForBill($bill); - $count = $collection->count(); - $rules = $collection->slice($offset, $limit); + $manager = $this->getManager(); + $collection = $this->repository->getRulesForBill($bill); + $count = $collection->count(); + $rules = $collection->slice($offset, $limit); // make paginator: - $paginator = new LengthAwarePaginator($rules, $count, $limit, $page); - $paginator->setPath(route('api.v1.bills.rules', [$bill->id]).$this->buildParams()); + $paginator = new LengthAwarePaginator($rules, $count, $limit, $page); + $paginator->setPath(route('api.v1.bills.rules', [$bill->id]) . $this->buildParams()); /** @var RuleTransformer $transformer */ $transformer = app(RuleTransformer::class); @@ -137,22 +127,16 @@ class ListController extends Controller */ public function transactions(PaginationDateRangeRequest $request, Bill $bill): JsonResponse { - [ - 'limit' => $limit, - 'page' => $page, - 'types' => $types, - 'start' => $start, - 'end' => $end, - ] = $request->attributes->all(); + ['limit' => $limit, 'page' => $page, 'types' => $types, 'start' => $start, 'end' => $end] = $request->attributes->all(); - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setUser($admin) // include source + destination account name and type. @@ -164,8 +148,7 @@ class ListController extends Controller // set page to retrieve ->setPage($page) // set types of transactions to return. - ->setTypes($types) - ; + ->setTypes($types); if (null !== $start) { $collector->setStart($start); @@ -175,18 +158,18 @@ class ListController extends Controller } // get paginator. - $paginator = $collector->getPaginatedGroups(); - $paginator->setPath(route('api.v1.bills.transactions', [$bill->id]).$this->buildParams()); + $paginator = $collector->getPaginatedGroups(); + $paginator->setPath(route('api.v1.bills.transactions', [$bill->id]) . $this->buildParams()); // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); $transactions = $enrichment->enrich($paginator->getCollection()); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); - $resource = new FractalCollection($transactions, $transformer, 'transactions'); + $resource = new FractalCollection($transactions, $transformer, 'transactions'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Models/Bill/ShowController.php b/app/Api/V1/Controllers/Models/Bill/ShowController.php index 873c8c8d4e..3cb71f90c5 100644 --- a/app/Api/V1/Controllers/Models/Bill/ShowController.php +++ b/app/Api/V1/Controllers/Models/Bill/ShowController.php @@ -51,14 +51,12 @@ class ShowController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(BillRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(BillRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -69,34 +67,28 @@ class ShowController extends Controller */ public function index(PaginationDateRangeRequest $request): JsonResponse { - [ - 'limit' => $limit, - 'offset' => $offset, - 'start' => $start, - 'end' => $end, - 'page' => $page, - ] = $request->attributes->all(); + ['limit' => $limit, 'offset' => $offset, 'start' => $start, 'end' => $end, 'page' => $page] = $request->attributes->all(); $this->repository->correctOrder(); - $bills = $this->repository->getBills(); - $manager = $this->getManager(); - $count = $bills->count(); - $bills = $bills->slice($offset, $limit); - $paginator = new LengthAwarePaginator($bills, $count, $limit, $page); + $bills = $this->repository->getBills(); + $manager = $this->getManager(); + $count = $bills->count(); + $bills = $bills->slice($offset, $limit); + $paginator = new LengthAwarePaginator($bills, $count, $limit, $page); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new SubscriptionEnrichment(); + $admin = auth()->user(); + $enrichment = new SubscriptionEnrichment(); $enrichment->setUser($admin); $enrichment->setStart($start); $enrichment->setEnd($end); - $bills = $enrichment->enrich($bills); + $bills = $enrichment->enrich($bills); /** @var BillTransformer $transformer */ $transformer = app(BillTransformer::class); - $resource = new FractalCollection($bills, $transformer, 'bills'); + $resource = new FractalCollection($bills, $transformer, 'bills'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -110,26 +102,23 @@ class ShowController extends Controller */ public function show(DateRangeRequest $request, Bill $bill): JsonResponse { - [ - 'start' => $start, - 'end' => $end, - ] = $request->attributes->all(); + ['start' => $start, 'end' => $end] = $request->attributes->all(); - $manager = $this->getManager(); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new SubscriptionEnrichment(); + $admin = auth()->user(); + $enrichment = new SubscriptionEnrichment(); $enrichment->setUser($admin); $enrichment->setStart($start); $enrichment->setEnd($end); - $bill = $enrichment->enrichSingle($bill); + $bill = $enrichment->enrichSingle($bill); /** @var BillTransformer $transformer */ $transformer = app(BillTransformer::class); - $resource = new Item($bill, $transformer, 'bills'); + $resource = new Item($bill, $transformer, 'bills'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Bill/StoreController.php b/app/Api/V1/Controllers/Models/Bill/StoreController.php index e0ab4b23d5..2c45baa991 100644 --- a/app/Api/V1/Controllers/Models/Bill/StoreController.php +++ b/app/Api/V1/Controllers/Models/Bill/StoreController.php @@ -50,14 +50,12 @@ class StoreController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(BillRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(BillRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -70,24 +68,24 @@ class StoreController extends Controller */ public function store(StoreRequest $request): JsonResponse { - $data = $request->getAll(); - $bill = $this->repository->store($data); - $manager = $this->getManager(); + $data = $request->getAll(); + $bill = $this->repository->store($data); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new SubscriptionEnrichment(); + $admin = auth()->user(); + $enrichment = new SubscriptionEnrichment(); $enrichment->setUser($admin); $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); - $bill = $enrichment->enrichSingle($bill); + $bill = $enrichment->enrichSingle($bill); /** @var BillTransformer $transformer */ $transformer = app(BillTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($bill, $transformer, 'bills'); + $resource = new Item($bill, $transformer, 'bills'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Bill/UpdateController.php b/app/Api/V1/Controllers/Models/Bill/UpdateController.php index bca0351efe..c84e5d4c88 100644 --- a/app/Api/V1/Controllers/Models/Bill/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Bill/UpdateController.php @@ -47,14 +47,12 @@ class UpdateController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(BillRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(BillRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -65,24 +63,24 @@ class UpdateController extends Controller */ public function update(UpdateRequest $request, Bill $bill): JsonResponse { - $data = $request->getAll(); - $bill = $this->repository->update($bill, $data); - $manager = $this->getManager(); + $data = $request->getAll(); + $bill = $this->repository->update($bill, $data); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new SubscriptionEnrichment(); + $admin = auth()->user(); + $enrichment = new SubscriptionEnrichment(); $enrichment->setUser($admin); $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); - $bill = $enrichment->enrichSingle($bill); + $bill = $enrichment->enrichSingle($bill); /** @var BillTransformer $transformer */ $transformer = app(BillTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($bill, $transformer, 'bills'); + $resource = new Item($bill, $transformer, 'bills'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Budget/DestroyController.php b/app/Api/V1/Controllers/Models/Budget/DestroyController.php index 05ee1da9e8..797f51a64b 100644 --- a/app/Api/V1/Controllers/Models/Budget/DestroyController.php +++ b/app/Api/V1/Controllers/Models/Budget/DestroyController.php @@ -43,14 +43,12 @@ class DestroyController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(BudgetRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(BudgetRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** diff --git a/app/Api/V1/Controllers/Models/Budget/ListController.php b/app/Api/V1/Controllers/Models/Budget/ListController.php index f2a80bbcb7..6fd01dbeed 100644 --- a/app/Api/V1/Controllers/Models/Budget/ListController.php +++ b/app/Api/V1/Controllers/Models/Budget/ListController.php @@ -49,7 +49,7 @@ class ListController extends Controller use TransactionFilter; private BudgetLimitRepositoryInterface $blRepository; - private BudgetRepositoryInterface $repository; + private BudgetRepositoryInterface $repository; /** * ListController constructor. @@ -57,16 +57,14 @@ class ListController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(BudgetRepositoryInterface::class); - $this->blRepository = app(BudgetLimitRepositoryInterface::class); - $this->repository->setUser(auth()->user()); - $this->blRepository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(BudgetRepositoryInterface::class); + $this->blRepository = app(BudgetLimitRepositoryInterface::class); + $this->repository->setUser(auth()->user()); + $this->blRepository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -75,22 +73,22 @@ class ListController extends Controller */ public function attachments(Budget $budget): JsonResponse { - $manager = $this->getManager(); - $pageSize = $this->parameters->get('limit'); - $collection = $this->repository->getAttachments($budget); + $manager = $this->getManager(); + $pageSize = $this->parameters->get('limit'); + $collection = $this->repository->getAttachments($budget); $count = $collection->count(); $attachments = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($attachments, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.budgets.attachments', [$budget->id]).$this->buildParams()); + $paginator = new LengthAwarePaginator($attachments, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.budgets.attachments', [$budget->id]) . $this->buildParams()); /** @var AttachmentTransformer $transformer */ $transformer = app(AttachmentTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($attachments, $transformer, 'attachments'); + $resource = new FractalCollection($attachments, $transformer, 'attachments'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -104,27 +102,26 @@ class ListController extends Controller */ public function budgetLimits(Budget $budget): JsonResponse { - $manager = $this->getManager(); - $pageSize = $this->parameters->get('limit'); + $manager = $this->getManager(); + $pageSize = $this->parameters->get('limit'); $this->parameters->set('budget_id', $budget->id); $collection = $this->blRepository->getBudgetLimits($budget, $this->parameters->get('start'), $this->parameters->get('end')); $count = $collection->count(); $budgetLimits = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); $paginator = new LengthAwarePaginator($budgetLimits, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.budgets.budget-limits', [$budget->id]).$this->buildParams()); + $paginator->setPath(route('api.v1.budgets.budget-limits', [$budget->id]) . $this->buildParams()); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new BudgetLimitEnrichment(); + $admin = auth()->user(); + $enrichment = new BudgetLimitEnrichment(); $enrichment->setUser($admin); $budgetLimits = $enrichment->enrich($budgetLimits); - /** @var BudgetLimitTransformer $transformer */ - $transformer = app(BudgetLimitTransformer::class); + $transformer = app(BudgetLimitTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($budgetLimits, $transformer, 'budget_limits'); + $resource = new FractalCollection($budgetLimits, $transformer, 'budget_limits'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -138,20 +135,20 @@ class ListController extends Controller */ public function transactions(Request $request, Budget $budget): JsonResponse { - $pageSize = $this->parameters->get('limit'); + $pageSize = $this->parameters->get('limit'); - $type = $request->get('type') ?? 'default'; + $type = $request->get('type') ?? 'default'; $this->parameters->set('type', $type); - $types = $this->mapTransactionTypes($this->parameters->get('type')); - $manager = $this->getManager(); + $types = $this->mapTransactionTypes($this->parameters->get('type')); + $manager = $this->getManager(); /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setUser($admin) // filter on budget. @@ -163,8 +160,7 @@ class ListController extends Controller // set page to retrieve ->setPage($this->parameters->get('page')) // set types of transactions to return. - ->setTypes($types) - ; + ->setTypes($types); if (null !== $this->parameters->get('start')) { $collector->setStart($this->parameters->get('start')); @@ -173,18 +169,18 @@ class ListController extends Controller $collector->setEnd($this->parameters->get('end')); } - $paginator = $collector->getPaginatedGroups(); - $paginator->setPath(route('api.v1.budgets.transactions', [$budget->id]).$this->buildParams()); + $paginator = $collector->getPaginatedGroups(); + $paginator->setPath(route('api.v1.budgets.transactions', [$budget->id]) . $this->buildParams()); // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); $transactions = $enrichment->enrich($paginator->getCollection()); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($transactions, $transformer, 'transactions'); + $resource = new FractalCollection($transactions, $transformer, 'transactions'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -198,20 +194,20 @@ class ListController extends Controller */ public function withoutBudget(Request $request): JsonResponse { - $pageSize = $this->parameters->get('limit'); + $pageSize = $this->parameters->get('limit'); - $type = $request->get('type') ?? 'default'; + $type = $request->get('type') ?? 'default'; $this->parameters->set('type', $type); - $types = $this->mapTransactionTypes($this->parameters->get('type')); - $manager = $this->getManager(); + $types = $this->mapTransactionTypes($this->parameters->get('type')); + $manager = $this->getManager(); /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setUser($admin) // withdrawals only @@ -225,8 +221,7 @@ class ListController extends Controller // set page to retrieve ->setPage($this->parameters->get('page')) // set types of transactions to return. - ->setTypes($types) - ; + ->setTypes($types); if (null !== $this->parameters->get('start')) { $collector->setStart($this->parameters->get('start')); @@ -235,18 +230,18 @@ class ListController extends Controller $collector->setEnd($this->parameters->get('end')); } - $paginator = $collector->getPaginatedGroups(); - $paginator->setPath(route('api.v1.budgets.without-budget').$this->buildParams()); + $paginator = $collector->getPaginatedGroups(); + $paginator->setPath(route('api.v1.budgets.without-budget') . $this->buildParams()); // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); $transactions = $enrichment->enrich($paginator->getCollection()); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($transactions, $transformer, 'transactions'); + $resource = new FractalCollection($transactions, $transformer, 'transactions'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Models/Budget/ShowController.php b/app/Api/V1/Controllers/Models/Budget/ShowController.php index 7b3dfde927..756258c780 100644 --- a/app/Api/V1/Controllers/Models/Budget/ShowController.php +++ b/app/Api/V1/Controllers/Models/Budget/ShowController.php @@ -43,7 +43,7 @@ use League\Fractal\Resource\Item; class ShowController extends Controller { private BudgetLimitRepositoryInterface $blRepository; - private BudgetRepositoryInterface $repository; + private BudgetRepositoryInterface $repository; /** * ListController constructor. @@ -51,16 +51,14 @@ class ShowController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(BudgetRepositoryInterface::class); - $this->blRepository = app(BudgetLimitRepositoryInterface::class); - $this->repository->setUser(auth()->user()); - $this->blRepository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(BudgetRepositoryInterface::class); + $this->blRepository = app(BudgetLimitRepositoryInterface::class); + $this->repository->setUser(auth()->user()); + $this->blRepository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -71,34 +69,34 @@ class ShowController extends Controller */ public function index(): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // types to get, page size: - $pageSize = $this->parameters->get('limit'); + $pageSize = $this->parameters->get('limit'); // get list of budgets. Count it and split it. - $collection = $this->repository->getBudgets(); - $count = $collection->count(); - $budgets = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $collection = $this->repository->getBudgets(); + $count = $collection->count(); + $budgets = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new BudgetEnrichment(); + $admin = auth()->user(); + $enrichment = new BudgetEnrichment(); $enrichment->setUser($admin); $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); - $budgets = $enrichment->enrich($budgets); + $budgets = $enrichment->enrich($budgets); // make paginator: - $paginator = new LengthAwarePaginator($budgets, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.budgets.index').$this->buildParams()); + $paginator = new LengthAwarePaginator($budgets, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.budgets.index') . $this->buildParams()); /** @var BudgetTransformer $transformer */ $transformer = app(BudgetTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($budgets, $transformer, 'budgets'); + $resource = new FractalCollection($budgets, $transformer, 'budgets'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -109,22 +107,22 @@ class ShowController extends Controller */ public function show(Budget $budget): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new BudgetEnrichment(); + $admin = auth()->user(); + $enrichment = new BudgetEnrichment(); $enrichment->setUser($admin); $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); - $budget = $enrichment->enrichSingle($budget); + $budget = $enrichment->enrichSingle($budget); /** @var BudgetTransformer $transformer */ $transformer = app(BudgetTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($budget, $transformer, 'budgets'); + $resource = new Item($budget, $transformer, 'budgets'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Budget/StoreController.php b/app/Api/V1/Controllers/Models/Budget/StoreController.php index 66a8f36153..4d8658707e 100644 --- a/app/Api/V1/Controllers/Models/Budget/StoreController.php +++ b/app/Api/V1/Controllers/Models/Budget/StoreController.php @@ -47,14 +47,12 @@ class StoreController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(BudgetRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(BudgetRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -67,24 +65,24 @@ class StoreController extends Controller */ public function store(StoreRequest $request): JsonResponse { - $data = $request->getAll(); + $data = $request->getAll(); $data['fire_webhooks'] ??= true; - $budget = $this->repository->store($data); + $budget = $this->repository->store($data); $budget->refresh(); - $manager = $this->getManager(); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new BudgetEnrichment(); + $admin = auth()->user(); + $enrichment = new BudgetEnrichment(); $enrichment->setUser($admin); - $budget = $enrichment->enrichSingle($budget); + $budget = $enrichment->enrichSingle($budget); /** @var BudgetTransformer $transformer */ $transformer = app(BudgetTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($budget, $transformer, 'budgets'); + $resource = new Item($budget, $transformer, 'budgets'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Budget/UpdateController.php b/app/Api/V1/Controllers/Models/Budget/UpdateController.php index 54bddb72a6..f7d64ac91f 100644 --- a/app/Api/V1/Controllers/Models/Budget/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Budget/UpdateController.php @@ -47,35 +47,33 @@ class UpdateController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(BudgetRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(BudgetRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } public function update(UpdateRequest $request, Budget $budget): JsonResponse { - $data = $request->getAll(); + $data = $request->getAll(); $data['fire_webhooks'] ??= true; - $budget = $this->repository->update($budget, $data); - $manager = $this->getManager(); + $budget = $this->repository->update($budget, $data); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new BudgetEnrichment(); + $admin = auth()->user(); + $enrichment = new BudgetEnrichment(); $enrichment->setUser($admin); - $budget = $enrichment->enrichSingle($budget); + $budget = $enrichment->enrichSingle($budget); /** @var BudgetTransformer $transformer */ $transformer = app(BudgetTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($budget, $transformer, 'budgets'); + $resource = new Item($budget, $transformer, 'budgets'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/BudgetLimit/DestroyController.php b/app/Api/V1/Controllers/Models/BudgetLimit/DestroyController.php index af96515cfb..c06607e9ac 100644 --- a/app/Api/V1/Controllers/Models/BudgetLimit/DestroyController.php +++ b/app/Api/V1/Controllers/Models/BudgetLimit/DestroyController.php @@ -46,16 +46,14 @@ class DestroyController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); - $this->blRepository = app(BudgetLimitRepositoryInterface::class); - $this->blRepository->setUser($user); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); + $this->blRepository = app(BudgetLimitRepositoryInterface::class); + $this->blRepository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** diff --git a/app/Api/V1/Controllers/Models/BudgetLimit/ListController.php b/app/Api/V1/Controllers/Models/BudgetLimit/ListController.php index f21f276843..5896a5e96f 100644 --- a/app/Api/V1/Controllers/Models/BudgetLimit/ListController.php +++ b/app/Api/V1/Controllers/Models/BudgetLimit/ListController.php @@ -51,19 +51,19 @@ class ListController extends Controller */ public function transactions(Request $request, Budget $budget, BudgetLimit $budgetLimit): JsonResponse { - $pageSize = $this->parameters->get('limit'); - $type = $request->get('type') ?? 'default'; + $pageSize = $this->parameters->get('limit'); + $type = $request->get('type') ?? 'default'; $this->parameters->set('type', $type); - $types = $this->mapTransactionTypes($this->parameters->get('type')); - $manager = $this->getManager(); + $types = $this->mapTransactionTypes($this->parameters->get('type')); + $manager = $this->getManager(); /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setUser($admin) // filter on budget. @@ -75,24 +75,23 @@ class ListController extends Controller // set page to retrieve ->setPage($this->parameters->get('page')) // set types of transactions to return. - ->setTypes($types) - ; + ->setTypes($types); $collector->setRange($budgetLimit->start_date, $budgetLimit->end_date); $collector->setTypes($types); - $paginator = $collector->getPaginatedGroups(); - $paginator->setPath(route('api.v1.budgets.limits.transactions', [$budget->id, $budgetLimit->id]).$this->buildParams()); + $paginator = $collector->getPaginatedGroups(); + $paginator->setPath(route('api.v1.budgets.limits.transactions', [$budget->id, $budgetLimit->id]) . $this->buildParams()); // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); $transactions = $enrichment->enrich($paginator->getCollection()); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($transactions, $transformer, 'transactions'); + $resource = new FractalCollection($transactions, $transformer, 'transactions'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Models/BudgetLimit/ShowController.php b/app/Api/V1/Controllers/Models/BudgetLimit/ShowController.php index 501d680599..7d4029f68e 100644 --- a/app/Api/V1/Controllers/Models/BudgetLimit/ShowController.php +++ b/app/Api/V1/Controllers/Models/BudgetLimit/ShowController.php @@ -47,7 +47,7 @@ use League\Fractal\Resource\Item; class ShowController extends Controller { private BudgetLimitRepositoryInterface $blRepository; - private BudgetRepositoryInterface $repository; + private BudgetRepositoryInterface $repository; /** * BudgetLimitController constructor. @@ -55,18 +55,16 @@ class ShowController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); - $this->repository = app(BudgetRepositoryInterface::class); - $this->blRepository = app(BudgetLimitRepositoryInterface::class); - $this->repository->setUser($user); - $this->blRepository->setUser($user); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); + $this->repository = app(BudgetRepositoryInterface::class); + $this->blRepository = app(BudgetLimitRepositoryInterface::class); + $this->repository->setUser($user); + $this->blRepository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -78,36 +76,35 @@ class ShowController extends Controller public function index(Budget $budget): JsonResponse { /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // enrich budget: - $enrichment = new BudgetEnrichment(); + $enrichment = new BudgetEnrichment(); $enrichment->setUser($admin); $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); /** @var Budget $budget */ - $budget = $enrichment->enrichSingle($budget); + $budget = $enrichment->enrichSingle($budget); - - $manager = $this->getManager(); + $manager = $this->getManager(); $manager->parseIncludes('budget'); $pageSize = $this->parameters->get('limit'); $collection = $this->blRepository->getBudgetLimits($budget, $this->parameters->get('start'), $this->parameters->get('end')); $count = $collection->count(); $budgetLimits = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); $paginator = new LengthAwarePaginator($budgetLimits, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.budgets.limits.index', [$budget->id]).$this->buildParams()); + $paginator->setPath(route('api.v1.budgets.limits.index', [$budget->id]) . $this->buildParams()); // enrich - $enrichment = new BudgetLimitEnrichment(); + $enrichment = new BudgetLimitEnrichment(); $enrichment->setUser($admin); $budgetLimits = $enrichment->enrich($budgetLimits); /** @var BudgetLimitTransformer $transformer */ - $transformer = app(BudgetLimitTransformer::class); + $transformer = app(BudgetLimitTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($budgetLimits, $transformer, 'budget_limits'); + $resource = new FractalCollection($budgetLimits, $transformer, 'budget_limits'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -123,27 +120,27 @@ class ShowController extends Controller */ public function indexAll(SameDateRequest $request): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); $manager->parseIncludes('budget'); $pageSize = $this->parameters->get('limit'); $collection = $this->blRepository->getAllBudgetLimits($this->parameters->get('start'), $this->parameters->get('end')); $count = $collection->count(); $budgetLimits = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); $paginator = new LengthAwarePaginator($budgetLimits, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.budget-limits.index').$this->buildParams()); + $paginator->setPath(route('api.v1.budget-limits.index') . $this->buildParams()); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new BudgetLimitEnrichment(); + $admin = auth()->user(); + $enrichment = new BudgetLimitEnrichment(); $enrichment->setUser($admin); $budgetLimits = $enrichment->enrich($budgetLimits); /** @var BudgetLimitTransformer $transformer */ - $transformer = app(BudgetLimitTransformer::class); + $transformer = app(BudgetLimitTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($budgetLimits, $transformer, 'budget_limits'); + $resource = new FractalCollection($budgetLimits, $transformer, 'budget_limits'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -161,19 +158,19 @@ class ShowController extends Controller throw new FireflyException('20028: The budget limit does not belong to the budget.'); } // continue! - $manager = $this->getManager(); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new BudgetLimitEnrichment(); + $admin = auth()->user(); + $enrichment = new BudgetLimitEnrichment(); $enrichment->setUser($admin); $budgetLimit = $enrichment->enrichSingle($budgetLimit); /** @var BudgetLimitTransformer $transformer */ $transformer = app(BudgetLimitTransformer::class); - $resource = new Item($budgetLimit, $transformer, 'budget_limits'); + $resource = new Item($budgetLimit, $transformer, 'budget_limits'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/BudgetLimit/StoreController.php b/app/Api/V1/Controllers/Models/BudgetLimit/StoreController.php index 3b16016efa..9fa8c07ce6 100644 --- a/app/Api/V1/Controllers/Models/BudgetLimit/StoreController.php +++ b/app/Api/V1/Controllers/Models/BudgetLimit/StoreController.php @@ -47,16 +47,14 @@ class StoreController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); - $this->blRepository = app(BudgetLimitRepositoryInterface::class); - $this->blRepository->setUser($user); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); + $this->blRepository = app(BudgetLimitRepositoryInterface::class); + $this->blRepository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -67,27 +65,27 @@ class StoreController extends Controller */ public function store(StoreRequest $request, Budget $budget): JsonResponse { - $data = $request->getAll(); + $data = $request->getAll(); $data['start_date'] = $data['start']; - $data['end_date'] = $data['end']; + $data['end_date'] = $data['end']; $data['fire_webhooks'] ??= true; - $data['budget_id'] = $budget->id; + $data['budget_id'] = $budget->id; - $budgetLimit = $this->blRepository->store($data); - $manager = $this->getManager(); + $budgetLimit = $this->blRepository->store($data); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new BudgetLimitEnrichment(); + $admin = auth()->user(); + $enrichment = new BudgetLimitEnrichment(); $enrichment->setUser($admin); - $budgetLimit = $enrichment->enrichSingle($budgetLimit); + $budgetLimit = $enrichment->enrichSingle($budgetLimit); /** @var BudgetLimitTransformer $transformer */ - $transformer = app(BudgetLimitTransformer::class); + $transformer = app(BudgetLimitTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($budgetLimit, $transformer, 'budget_limits'); + $resource = new Item($budgetLimit, $transformer, 'budget_limits'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/BudgetLimit/UpdateController.php b/app/Api/V1/Controllers/Models/BudgetLimit/UpdateController.php index 3517062e2b..5af898a023 100644 --- a/app/Api/V1/Controllers/Models/BudgetLimit/UpdateController.php +++ b/app/Api/V1/Controllers/Models/BudgetLimit/UpdateController.php @@ -52,16 +52,14 @@ class UpdateController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); - $this->blRepository = app(BudgetLimitRepositoryInterface::class); - $this->blRepository->setUser($user); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); + $this->blRepository = app(BudgetLimitRepositoryInterface::class); + $this->blRepository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -76,24 +74,24 @@ class UpdateController extends Controller if ($budget->id !== $budgetLimit->budget_id) { throw new FireflyException('20028: The budget limit does not belong to the budget.'); } - $data = $request->getAll(); + $data = $request->getAll(); $data['fire_webhooks'] ??= true; $data['budget_id'] = $budget->id; - $budgetLimit = $this->blRepository->update($budgetLimit, $data); - $manager = $this->getManager(); + $budgetLimit = $this->blRepository->update($budgetLimit, $data); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new BudgetLimitEnrichment(); + $admin = auth()->user(); + $enrichment = new BudgetLimitEnrichment(); $enrichment->setUser($admin); - $budgetLimit = $enrichment->enrichSingle($budgetLimit); + $budgetLimit = $enrichment->enrichSingle($budgetLimit); /** @var BudgetLimitTransformer $transformer */ - $transformer = app(BudgetLimitTransformer::class); + $transformer = app(BudgetLimitTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($budgetLimit, $transformer, 'budget_limits'); + $resource = new Item($budgetLimit, $transformer, 'budget_limits'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Category/DestroyController.php b/app/Api/V1/Controllers/Models/Category/DestroyController.php index 7d7295596f..32c6444315 100644 --- a/app/Api/V1/Controllers/Models/Category/DestroyController.php +++ b/app/Api/V1/Controllers/Models/Category/DestroyController.php @@ -43,14 +43,12 @@ class DestroyController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(CategoryRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(CategoryRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** diff --git a/app/Api/V1/Controllers/Models/Category/ListController.php b/app/Api/V1/Controllers/Models/Category/ListController.php index fa71b0a631..62a64811bd 100644 --- a/app/Api/V1/Controllers/Models/Category/ListController.php +++ b/app/Api/V1/Controllers/Models/Category/ListController.php @@ -54,14 +54,12 @@ class ListController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(CategoryRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(CategoryRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -70,22 +68,22 @@ class ListController extends Controller */ public function attachments(Category $category): JsonResponse { - $manager = $this->getManager(); - $pageSize = $this->parameters->get('limit'); - $collection = $this->repository->getAttachments($category); + $manager = $this->getManager(); + $pageSize = $this->parameters->get('limit'); + $collection = $this->repository->getAttachments($category); $count = $collection->count(); $attachments = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($attachments, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.categories.attachments', [$category->id]).$this->buildParams()); + $paginator = new LengthAwarePaginator($attachments, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.categories.attachments', [$category->id]) . $this->buildParams()); /** @var AttachmentTransformer $transformer */ $transformer = app(AttachmentTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($attachments, $transformer, 'attachments'); + $resource = new FractalCollection($attachments, $transformer, 'attachments'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -99,19 +97,19 @@ class ListController extends Controller */ public function transactions(Request $request, Category $category): JsonResponse { - $pageSize = $this->parameters->get('limit'); - $type = $request->get('type') ?? 'default'; + $pageSize = $this->parameters->get('limit'); + $type = $request->get('type') ?? 'default'; $this->parameters->set('type', $type); - $types = $this->mapTransactionTypes($this->parameters->get('type')); - $manager = $this->getManager(); + $types = $this->mapTransactionTypes($this->parameters->get('type')); + $manager = $this->getManager(); /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setUser($admin) // filter on category. @@ -123,8 +121,7 @@ class ListController extends Controller // set page to retrieve ->setPage($this->parameters->get('page')) // set types of transactions to return. - ->setTypes($types) - ; + ->setTypes($types); if (null !== $this->parameters->get('start')) { $collector->setStart($this->parameters->get('start')); @@ -133,19 +130,19 @@ class ListController extends Controller $collector->setEnd($this->parameters->get('end')); } - $paginator = $collector->getPaginatedGroups(); - $paginator->setPath(route('api.v1.categories.transactions', [$category->id]).$this->buildParams()); + $paginator = $collector->getPaginatedGroups(); + $paginator->setPath(route('api.v1.categories.transactions', [$category->id]) . $this->buildParams()); // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); $transactions = $enrichment->enrich($paginator->getCollection()); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($transactions, $transformer, 'transactions'); + $resource = new FractalCollection($transactions, $transformer, 'transactions'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Models/Category/ShowController.php b/app/Api/V1/Controllers/Models/Category/ShowController.php index 2fc4137ad7..d4e6db27b3 100644 --- a/app/Api/V1/Controllers/Models/Category/ShowController.php +++ b/app/Api/V1/Controllers/Models/Category/ShowController.php @@ -49,14 +49,12 @@ class ShowController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(CategoryRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(CategoryRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -67,33 +65,33 @@ class ShowController extends Controller */ public function index(): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // types to get, page size: - $pageSize = $this->parameters->get('limit'); + $pageSize = $this->parameters->get('limit'); // get list of budgets. Count it and split it. - $collection = $this->repository->getCategories(); - $count = $collection->count(); - $categories = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $collection = $this->repository->getCategories(); + $count = $collection->count(); + $categories = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new CategoryEnrichment(); + $admin = auth()->user(); + $enrichment = new CategoryEnrichment(); $enrichment->setUser($admin); $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); - $categories = $enrichment->enrich($categories); + $categories = $enrichment->enrich($categories); // make paginator: - $paginator = new LengthAwarePaginator($categories, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.categories.index').$this->buildParams()); + $paginator = new LengthAwarePaginator($categories, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.categories.index') . $this->buildParams()); /** @var CategoryTransformer $transformer */ $transformer = app(CategoryTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($categories, $transformer, 'categories'); + $resource = new FractalCollection($categories, $transformer, 'categories'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -107,7 +105,7 @@ class ShowController extends Controller */ public function show(Category $category): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var CategoryTransformer $transformer */ $transformer = app(CategoryTransformer::class); @@ -115,14 +113,14 @@ class ShowController extends Controller // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new CategoryEnrichment(); + $admin = auth()->user(); + $enrichment = new CategoryEnrichment(); $enrichment->setUser($admin); $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); - $category = $enrichment->enrichSingle($category); + $category = $enrichment->enrichSingle($category); - $resource = new Item($category, $transformer, 'categories'); + $resource = new Item($category, $transformer, 'categories'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Category/StoreController.php b/app/Api/V1/Controllers/Models/Category/StoreController.php index 99d53fcb5d..a4082580c7 100644 --- a/app/Api/V1/Controllers/Models/Category/StoreController.php +++ b/app/Api/V1/Controllers/Models/Category/StoreController.php @@ -47,14 +47,12 @@ class StoreController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(CategoryRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(CategoryRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -67,8 +65,8 @@ class StoreController extends Controller */ public function store(StoreRequest $request): JsonResponse { - $category = $this->repository->store($request->getAll()); - $manager = $this->getManager(); + $category = $this->repository->store($request->getAll()); + $manager = $this->getManager(); /** @var CategoryTransformer $transformer */ $transformer = app(CategoryTransformer::class); @@ -76,14 +74,14 @@ class StoreController extends Controller // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new CategoryEnrichment(); + $admin = auth()->user(); + $enrichment = new CategoryEnrichment(); $enrichment->setUser($admin); $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); - $category = $enrichment->enrichSingle($category); + $category = $enrichment->enrichSingle($category); - $resource = new Item($category, $transformer, 'categories'); + $resource = new Item($category, $transformer, 'categories'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Category/UpdateController.php b/app/Api/V1/Controllers/Models/Category/UpdateController.php index bcb82e927a..35340733e0 100644 --- a/app/Api/V1/Controllers/Models/Category/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Category/UpdateController.php @@ -47,14 +47,12 @@ class UpdateController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(CategoryRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(CategoryRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -65,9 +63,9 @@ class UpdateController extends Controller */ public function update(UpdateRequest $request, Category $category): JsonResponse { - $data = $request->getAll(); - $category = $this->repository->update($category, $data); - $manager = $this->getManager(); + $data = $request->getAll(); + $category = $this->repository->update($category, $data); + $manager = $this->getManager(); /** @var CategoryTransformer $transformer */ $transformer = app(CategoryTransformer::class); @@ -75,14 +73,14 @@ class UpdateController extends Controller // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new CategoryEnrichment(); + $admin = auth()->user(); + $enrichment = new CategoryEnrichment(); $enrichment->setUser($admin); $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); - $category = $enrichment->enrichSingle($category); + $category = $enrichment->enrichSingle($category); - $resource = new Item($category, $transformer, 'categories'); + $resource = new Item($category, $transformer, 'categories'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/CurrencyExchangeRate/DestroyController.php b/app/Api/V1/Controllers/Models/CurrencyExchangeRate/DestroyController.php index 807ff96f31..6a6512f5e3 100644 --- a/app/Api/V1/Controllers/Models/CurrencyExchangeRate/DestroyController.php +++ b/app/Api/V1/Controllers/Models/CurrencyExchangeRate/DestroyController.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Controllers\Models\CurrencyExchangeRate; -use Illuminate\Http\Request; use Carbon\Carbon; use FireflyIII\Api\V1\Controllers\Controller; use FireflyIII\Api\V1\Requests\Models\CurrencyExchangeRate\DestroyRequest; @@ -35,26 +34,26 @@ use FireflyIII\Models\TransactionCurrency; use FireflyIII\Repositories\ExchangeRate\ExchangeRateRepositoryInterface; use FireflyIII\Support\Http\Api\ValidatesUserGroupTrait; use Illuminate\Http\JsonResponse; +use Illuminate\Http\Request; class DestroyController extends Controller { use ValidatesUserGroupTrait; public const string RESOURCE_KEY = 'exchange-rates'; - protected array $acceptedRoles = [UserRoleEnum::OWNER]; + + protected array $acceptedRoles = [UserRoleEnum::OWNER]; private ExchangeRateRepositoryInterface $repository; public function __construct() { parent::__construct(); - $this->middleware( - function (Request $request, $next) { - $this->repository = app(ExchangeRateRepositoryInterface::class); - $this->repository->setUserGroup($this->validateUserGroup($request)); + $this->middleware(function (Request $request, $next) { + $this->repository = app(ExchangeRateRepositoryInterface::class); + $this->repository->setUserGroup($this->validateUserGroup($request)); - return $next($request); - } - ); + return $next($request); + }); } public function destroy(DestroyRequest $request, TransactionCurrency $from, TransactionCurrency $to): JsonResponse diff --git a/app/Api/V1/Controllers/Models/CurrencyExchangeRate/IndexController.php b/app/Api/V1/Controllers/Models/CurrencyExchangeRate/IndexController.php index 226a091487..ff8f0fe566 100644 --- a/app/Api/V1/Controllers/Models/CurrencyExchangeRate/IndexController.php +++ b/app/Api/V1/Controllers/Models/CurrencyExchangeRate/IndexController.php @@ -24,13 +24,13 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Controllers\Models\CurrencyExchangeRate; -use Illuminate\Http\Request; use FireflyIII\Api\V1\Controllers\Controller; use FireflyIII\Enums\UserRoleEnum; use FireflyIII\Repositories\ExchangeRate\ExchangeRateRepositoryInterface; use FireflyIII\Support\Http\Api\ValidatesUserGroupTrait; use FireflyIII\Transformers\ExchangeRateTransformer; use Illuminate\Http\JsonResponse; +use Illuminate\Http\Request; use Illuminate\Pagination\LengthAwarePaginator; /** @@ -41,20 +41,19 @@ class IndexController extends Controller use ValidatesUserGroupTrait; public const string RESOURCE_KEY = 'exchange-rates'; - protected array $acceptedRoles = [UserRoleEnum::OWNER]; + + protected array $acceptedRoles = [UserRoleEnum::OWNER]; private ExchangeRateRepositoryInterface $repository; public function __construct() { parent::__construct(); - $this->middleware( - function (Request $request, $next) { - $this->repository = app(ExchangeRateRepositoryInterface::class); - $this->repository->setUserGroup($this->validateUserGroup($request)); + $this->middleware(function (Request $request, $next) { + $this->repository = app(ExchangeRateRepositoryInterface::class); + $this->repository->setUserGroup($this->validateUserGroup($request)); - return $next($request); - } - ); + return $next($request); + }); } public function index(): JsonResponse @@ -67,9 +66,6 @@ class IndexController extends Controller $transformer = new ExchangeRateTransformer(); $transformer->setParameters($this->parameters); // give params to transformer - return response() - ->json($this->jsonApiList(self::RESOURCE_KEY, $paginator, $transformer)) - ->header('Content-Type', self::CONTENT_TYPE) - ; + return response()->json($this->jsonApiList(self::RESOURCE_KEY, $paginator, $transformer))->header('Content-Type', self::CONTENT_TYPE); } } diff --git a/app/Api/V1/Controllers/Models/CurrencyExchangeRate/ShowController.php b/app/Api/V1/Controllers/Models/CurrencyExchangeRate/ShowController.php index ac6e94100a..f5b4095e7d 100644 --- a/app/Api/V1/Controllers/Models/CurrencyExchangeRate/ShowController.php +++ b/app/Api/V1/Controllers/Models/CurrencyExchangeRate/ShowController.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Controllers\Models\CurrencyExchangeRate; -use Illuminate\Http\Request; use Carbon\Carbon; use FireflyIII\Api\V1\Controllers\Controller; use FireflyIII\Enums\UserRoleEnum; @@ -34,6 +33,7 @@ use FireflyIII\Repositories\ExchangeRate\ExchangeRateRepositoryInterface; use FireflyIII\Support\Http\Api\ValidatesUserGroupTrait; use FireflyIII\Transformers\ExchangeRateTransformer; use Illuminate\Http\JsonResponse; +use Illuminate\Http\Request; use Illuminate\Pagination\LengthAwarePaginator; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; @@ -45,38 +45,34 @@ class ShowController extends Controller use ValidatesUserGroupTrait; public const string RESOURCE_KEY = 'exchange-rates'; - protected array $acceptedRoles = [UserRoleEnum::OWNER]; + + protected array $acceptedRoles = [UserRoleEnum::OWNER]; private ExchangeRateRepositoryInterface $repository; public function __construct() { parent::__construct(); - $this->middleware( - function (Request $request, $next) { - $this->repository = app(ExchangeRateRepositoryInterface::class); - $this->repository->setUserGroup($this->validateUserGroup($request)); + $this->middleware(function (Request $request, $next) { + $this->repository = app(ExchangeRateRepositoryInterface::class); + $this->repository->setUserGroup($this->validateUserGroup($request)); - return $next($request); - } - ); + return $next($request); + }); } public function show(TransactionCurrency $from, TransactionCurrency $to): JsonResponse { - $pageSize = $this->parameters->get('limit'); - $page = $this->parameters->get('page'); - $rates = $this->repository->getRates($from, $to); - $count = $rates->count(); - $rates = $rates->slice(($page - 1) * $pageSize, $pageSize); - $paginator = new LengthAwarePaginator($rates, $count, $pageSize, $page); + $pageSize = $this->parameters->get('limit'); + $page = $this->parameters->get('page'); + $rates = $this->repository->getRates($from, $to); + $count = $rates->count(); + $rates = $rates->slice(($page - 1) * $pageSize, $pageSize); + $paginator = new LengthAwarePaginator($rates, $count, $pageSize, $page); $transformer = new ExchangeRateTransformer(); $transformer->setParameters($this->parameters); // give params to transformer - return response() - ->json($this->jsonApiList(self::RESOURCE_KEY, $paginator, $transformer)) - ->header('Content-Type', self::CONTENT_TYPE) - ; + return response()->json($this->jsonApiList(self::RESOURCE_KEY, $paginator, $transformer))->header('Content-Type', self::CONTENT_TYPE); } public function showSingleById(CurrencyExchangeRate $exchangeRate): JsonResponse @@ -84,15 +80,12 @@ class ShowController extends Controller $transformer = new ExchangeRateTransformer(); $transformer->setParameters($this->parameters); - return response() - ->api($this->jsonApiObject(self::RESOURCE_KEY, $exchangeRate, $transformer)) - ->header('Content-Type', self::CONTENT_TYPE) - ; + return response()->api($this->jsonApiObject(self::RESOURCE_KEY, $exchangeRate, $transformer))->header('Content-Type', self::CONTENT_TYPE); } public function showSingleByDate(TransactionCurrency $from, TransactionCurrency $to, Carbon $date): JsonResponse { - $transformer = new ExchangeRateTransformer(); + $transformer = new ExchangeRateTransformer(); $transformer->setParameters($this->parameters); $exchangeRate = $this->repository->getSpecificRateOnDate($from, $to, $date); @@ -100,9 +93,6 @@ class ShowController extends Controller throw new NotFoundHttpException(); } - return response() - ->api($this->jsonApiObject(self::RESOURCE_KEY, $exchangeRate, $transformer)) - ->header('Content-Type', self::CONTENT_TYPE) - ; + return response()->api($this->jsonApiObject(self::RESOURCE_KEY, $exchangeRate, $transformer))->header('Content-Type', self::CONTENT_TYPE); } } diff --git a/app/Api/V1/Controllers/Models/CurrencyExchangeRate/StoreController.php b/app/Api/V1/Controllers/Models/CurrencyExchangeRate/StoreController.php index 2b9bd95dbd..d0253019a2 100644 --- a/app/Api/V1/Controllers/Models/CurrencyExchangeRate/StoreController.php +++ b/app/Api/V1/Controllers/Models/CurrencyExchangeRate/StoreController.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Controllers\Models\CurrencyExchangeRate; -use Illuminate\Http\Request; use Carbon\Carbon; use FireflyIII\Api\V1\Controllers\Controller; use FireflyIII\Api\V1\Requests\Models\CurrencyExchangeRate\StoreByCurrenciesRequest; @@ -38,6 +37,7 @@ use FireflyIII\Support\Facades\Amount; use FireflyIII\Support\Http\Api\ValidatesUserGroupTrait; use FireflyIII\Transformers\ExchangeRateTransformer; use Illuminate\Http\JsonResponse; +use Illuminate\Http\Request; use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Support\Collection; @@ -45,28 +45,26 @@ class StoreController extends Controller { use ValidatesUserGroupTrait; - public const string RESOURCE_KEY = 'exchange-rates'; - protected array $acceptedRoles = [UserRoleEnum::OWNER]; + public const string RESOURCE_KEY = 'exchange-rates'; + + protected array $acceptedRoles = [UserRoleEnum::OWNER]; private ExchangeRateRepositoryInterface $repository; public function __construct() { parent::__construct(); - $this->middleware( - function (Request $request, $next) { - $this->repository = app(ExchangeRateRepositoryInterface::class); - $this->repository->setUserGroup($this->validateUserGroup($request)); + $this->middleware(function (Request $request, $next) { + $this->repository = app(ExchangeRateRepositoryInterface::class); + $this->repository->setUserGroup($this->validateUserGroup($request)); - return $next($request); - } - ); + return $next($request); + }); } public function storeByCurrencies(StoreByCurrenciesRequest $request, TransactionCurrency $from, TransactionCurrency $to): JsonResponse { - - $data = $request->getAll(); - $collection = new Collection(); + $data = $request->getAll(); + $collection = new Collection(); foreach ($data as $date => $rate) { $date = Carbon::createFromFormat('Y-m-d', $date); @@ -78,7 +76,7 @@ class StoreController extends Controller continue; } - $new = $this->repository->storeExchangeRate($from, $to, $rate, $date); + $new = $this->repository->storeExchangeRate($from, $to, $rate, $date); $collection->push($new); } @@ -87,18 +85,14 @@ class StoreController extends Controller $transformer = new ExchangeRateTransformer(); $transformer->setParameters($this->parameters); // give params to transformer - return response() - ->json($this->jsonApiList(self::RESOURCE_KEY, $paginator, $transformer)) - ->header('Content-Type', self::CONTENT_TYPE) - ; + return response()->json($this->jsonApiList(self::RESOURCE_KEY, $paginator, $transformer))->header('Content-Type', self::CONTENT_TYPE); } public function storeByDate(StoreByDateRequest $request, Carbon $date): JsonResponse { - - $data = $request->getAll(); - $from = $request->getFromCurrency(); - $collection = new Collection(); + $data = $request->getAll(); + $from = $request->getFromCurrency(); + $collection = new Collection(); foreach ($data['rates'] as $key => $rate) { $to = Amount::getTransactionCurrencyByCode($key); $existing = $this->repository->getSpecificRateOnDate($from, $to, $date); @@ -109,7 +103,7 @@ class StoreController extends Controller continue; } - $new = $this->repository->storeExchangeRate($from, $to, $rate, $date); + $new = $this->repository->storeExchangeRate($from, $to, $rate, $date); $collection->push($new); } @@ -118,21 +112,18 @@ class StoreController extends Controller $transformer = new ExchangeRateTransformer(); $transformer->setParameters($this->parameters); // give params to transformer - return response() - ->json($this->jsonApiList(self::RESOURCE_KEY, $paginator, $transformer)) - ->header('Content-Type', self::CONTENT_TYPE) - ; + return response()->json($this->jsonApiList(self::RESOURCE_KEY, $paginator, $transformer))->header('Content-Type', self::CONTENT_TYPE); } public function store(StoreRequest $request): JsonResponse { - $date = $request->getDate(); - $rate = $request->getRate(); - $from = $request->getFromCurrency(); - $to = $request->getToCurrency(); + $date = $request->getDate(); + $rate = $request->getRate(); + $from = $request->getFromCurrency(); + $to = $request->getToCurrency(); // already has rate? - $object = $this->repository->getSpecificRateOnDate($from, $to, $date); + $object = $this->repository->getSpecificRateOnDate($from, $to, $date); if ($object instanceof CurrencyExchangeRate) { // just update it, no matter. $rate = $this->repository->updateExchangeRate($object, $rate, $date); @@ -145,9 +136,6 @@ class StoreController extends Controller $transformer = new ExchangeRateTransformer(); $transformer->setParameters($this->parameters); - return response() - ->api($this->jsonApiObject(self::RESOURCE_KEY, $rate, $transformer)) - ->header('Content-Type', self::CONTENT_TYPE) - ; + return response()->api($this->jsonApiObject(self::RESOURCE_KEY, $rate, $transformer))->header('Content-Type', self::CONTENT_TYPE); } } diff --git a/app/Api/V1/Controllers/Models/CurrencyExchangeRate/UpdateController.php b/app/Api/V1/Controllers/Models/CurrencyExchangeRate/UpdateController.php index c5fc27d76b..8c37eed1df 100644 --- a/app/Api/V1/Controllers/Models/CurrencyExchangeRate/UpdateController.php +++ b/app/Api/V1/Controllers/Models/CurrencyExchangeRate/UpdateController.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Controllers\Models\CurrencyExchangeRate; -use Illuminate\Http\Request; use Carbon\Carbon; use FireflyIII\Api\V1\Controllers\Controller; use FireflyIII\Api\V1\Requests\Models\CurrencyExchangeRate\UpdateRequest; @@ -35,27 +34,27 @@ use FireflyIII\Repositories\ExchangeRate\ExchangeRateRepositoryInterface; use FireflyIII\Support\Http\Api\ValidatesUserGroupTrait; use FireflyIII\Transformers\ExchangeRateTransformer; use Illuminate\Http\JsonResponse; +use Illuminate\Http\Request; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; class UpdateController extends Controller { use ValidatesUserGroupTrait; - public const string RESOURCE_KEY = 'exchange-rates'; - protected array $acceptedRoles = [UserRoleEnum::OWNER]; + public const string RESOURCE_KEY = 'exchange-rates'; + + protected array $acceptedRoles = [UserRoleEnum::OWNER]; private ExchangeRateRepositoryInterface $repository; public function __construct() { parent::__construct(); - $this->middleware( - function (Request $request, $next) { - $this->repository = app(ExchangeRateRepositoryInterface::class); - $this->repository->setUserGroup($this->validateUserGroup($request)); + $this->middleware(function (Request $request, $next) { + $this->repository = app(ExchangeRateRepositoryInterface::class); + $this->repository->setUserGroup($this->validateUserGroup($request)); - return $next($request); - } - ); + return $next($request); + }); } public function updateById(UpdateRequest $request, CurrencyExchangeRate $exchangeRate): JsonResponse @@ -66,10 +65,7 @@ class UpdateController extends Controller $transformer = new ExchangeRateTransformer(); $transformer->setParameters($this->parameters); - return response() - ->api($this->jsonApiObject(self::RESOURCE_KEY, $exchangeRate, $transformer)) - ->header('Content-Type', self::CONTENT_TYPE) - ; + return response()->api($this->jsonApiObject(self::RESOURCE_KEY, $exchangeRate, $transformer))->header('Content-Type', self::CONTENT_TYPE); } public function updateByDate(UpdateRequest $request, TransactionCurrency $from, TransactionCurrency $to, Carbon $date): JsonResponse @@ -82,11 +78,8 @@ class UpdateController extends Controller $rate = $request->getRate(); $exchangeRate = $this->repository->updateExchangeRate($exchangeRate, $rate, $date); - $transformer = new ExchangeRateTransformer(); + $transformer = new ExchangeRateTransformer(); - return response() - ->api($this->jsonApiObject(self::RESOURCE_KEY, $exchangeRate, $transformer)) - ->header('Content-Type', self::CONTENT_TYPE) - ; + return response()->api($this->jsonApiObject(self::RESOURCE_KEY, $exchangeRate, $transformer))->header('Content-Type', self::CONTENT_TYPE); } } diff --git a/app/Api/V1/Controllers/Models/ObjectGroup/DestroyController.php b/app/Api/V1/Controllers/Models/ObjectGroup/DestroyController.php index 097abb404b..643277a0e8 100644 --- a/app/Api/V1/Controllers/Models/ObjectGroup/DestroyController.php +++ b/app/Api/V1/Controllers/Models/ObjectGroup/DestroyController.php @@ -44,16 +44,14 @@ class DestroyController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); - $this->repository = app(ObjectGroupRepositoryInterface::class); - $this->repository->setUser($user); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); + $this->repository = app(ObjectGroupRepositoryInterface::class); + $this->repository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** diff --git a/app/Api/V1/Controllers/Models/ObjectGroup/ListController.php b/app/Api/V1/Controllers/Models/ObjectGroup/ListController.php index 86a5d8bac4..71d44b7584 100644 --- a/app/Api/V1/Controllers/Models/ObjectGroup/ListController.php +++ b/app/Api/V1/Controllers/Models/ObjectGroup/ListController.php @@ -50,16 +50,14 @@ class ListController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); - $this->repository = app(ObjectGroupRepositoryInterface::class); - $this->repository->setUser($user); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); + $this->repository = app(ObjectGroupRepositoryInterface::class); + $this->repository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -70,32 +68,32 @@ class ListController extends Controller */ public function bills(ObjectGroup $objectGroup): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); - $pageSize = $this->parameters->get('limit'); + $pageSize = $this->parameters->get('limit'); // get list of piggy banks. Count it and split it. - $collection = $this->repository->getBills($objectGroup); - $count = $collection->count(); - $bills = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $collection = $this->repository->getBills($objectGroup); + $count = $collection->count(); + $bills = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new SubscriptionEnrichment(); + $admin = auth()->user(); + $enrichment = new SubscriptionEnrichment(); $enrichment->setUser($admin); $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); - $bills = $enrichment->enrich($bills); + $bills = $enrichment->enrich($bills); // make paginator: - $paginator = new LengthAwarePaginator($bills, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.currencies.bills', [$objectGroup->id]).$this->buildParams()); + $paginator = new LengthAwarePaginator($bills, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.currencies.bills', [$objectGroup->id]) . $this->buildParams()); /** @var BillTransformer $transformer */ $transformer = app(BillTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($bills, $transformer, 'bills'); + $resource = new FractalCollection($bills, $transformer, 'bills'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -110,32 +108,32 @@ class ListController extends Controller public function piggyBanks(ObjectGroup $objectGroup): JsonResponse { // create some objects: - $manager = $this->getManager(); + $manager = $this->getManager(); // types to get, page size: - $pageSize = $this->parameters->get('limit'); + $pageSize = $this->parameters->get('limit'); // get list of piggy banks. Count it and split it. - $collection = $this->repository->getPiggyBanks($objectGroup); - $count = $collection->count(); - $piggyBanks = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $collection = $this->repository->getPiggyBanks($objectGroup); + $count = $collection->count(); + $piggyBanks = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new PiggyBankEnrichment(); + $admin = auth()->user(); + $enrichment = new PiggyBankEnrichment(); $enrichment->setUser($admin); - $piggyBanks = $enrichment->enrich($piggyBanks); + $piggyBanks = $enrichment->enrich($piggyBanks); // make paginator: - $paginator = new LengthAwarePaginator($piggyBanks, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.object-groups.piggy-banks', [$objectGroup->id]).$this->buildParams()); + $paginator = new LengthAwarePaginator($piggyBanks, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.object-groups.piggy-banks', [$objectGroup->id]) . $this->buildParams()); /** @var PiggyBankTransformer $transformer */ $transformer = app(PiggyBankTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($piggyBanks, $transformer, 'piggy-banks'); + $resource = new FractalCollection($piggyBanks, $transformer, 'piggy-banks'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Models/ObjectGroup/ShowController.php b/app/Api/V1/Controllers/Models/ObjectGroup/ShowController.php index 4b06061ee2..79d3f6c414 100644 --- a/app/Api/V1/Controllers/Models/ObjectGroup/ShowController.php +++ b/app/Api/V1/Controllers/Models/ObjectGroup/ShowController.php @@ -48,16 +48,14 @@ class ShowController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); - $this->repository = app(ObjectGroupRepositoryInterface::class); - $this->repository->setUser($user); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); + $this->repository = app(ObjectGroupRepositoryInterface::class); + $this->repository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -68,10 +66,10 @@ class ShowController extends Controller */ public function index(): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // types to get, page size: - $pageSize = $this->parameters->get('limit'); + $pageSize = $this->parameters->get('limit'); $this->repository->resetOrder(); $collection = $this->repository->get(); @@ -79,14 +77,14 @@ class ShowController extends Controller $objectGroups = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($objectGroups, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.object-groups.index').$this->buildParams()); + $paginator = new LengthAwarePaginator($objectGroups, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.object-groups.index') . $this->buildParams()); /** @var ObjectGroupTransformer $transformer */ - $transformer = app(ObjectGroupTransformer::class); + $transformer = app(ObjectGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($objectGroups, $transformer, 'object_groups'); + $resource = new FractalCollection($objectGroups, $transformer, 'object_groups'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -100,14 +98,14 @@ class ShowController extends Controller */ public function show(ObjectGroup $objectGroup): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); $this->repository->resetOrder(); $objectGroup->refresh(); /** @var ObjectGroupTransformer $transformer */ $transformer = app(ObjectGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($objectGroup, $transformer, 'object_groups'); + $resource = new Item($objectGroup, $transformer, 'object_groups'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/ObjectGroup/UpdateController.php b/app/Api/V1/Controllers/Models/ObjectGroup/UpdateController.php index 8fe4f20952..db00c35e27 100644 --- a/app/Api/V1/Controllers/Models/ObjectGroup/UpdateController.php +++ b/app/Api/V1/Controllers/Models/ObjectGroup/UpdateController.php @@ -46,16 +46,14 @@ class UpdateController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); - $this->repository = app(ObjectGroupRepositoryInterface::class); - $this->repository->setUser($user); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); + $this->repository = app(ObjectGroupRepositoryInterface::class); + $this->repository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -64,15 +62,15 @@ class UpdateController extends Controller */ public function update(UpdateRequest $request, ObjectGroup $objectGroup): JsonResponse { - $data = $request->getUpdateData(); + $data = $request->getUpdateData(); $this->repository->update($objectGroup, $data); $this->repository->resetOrder(); - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var ObjectGroupTransformer $transformer */ $transformer = app(ObjectGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($objectGroup, $transformer, 'object_groups'); + $resource = new Item($objectGroup, $transformer, 'object_groups'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/PiggyBank/DestroyController.php b/app/Api/V1/Controllers/Models/PiggyBank/DestroyController.php index ce77892d37..26cb9da47f 100644 --- a/app/Api/V1/Controllers/Models/PiggyBank/DestroyController.php +++ b/app/Api/V1/Controllers/Models/PiggyBank/DestroyController.php @@ -43,14 +43,12 @@ class DestroyController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(PiggyBankRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(PiggyBankRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** diff --git a/app/Api/V1/Controllers/Models/PiggyBank/ListController.php b/app/Api/V1/Controllers/Models/PiggyBank/ListController.php index e22e88337d..0cee0c0207 100644 --- a/app/Api/V1/Controllers/Models/PiggyBank/ListController.php +++ b/app/Api/V1/Controllers/Models/PiggyBank/ListController.php @@ -51,14 +51,12 @@ class ListController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(PiggyBankRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(PiggyBankRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -70,30 +68,30 @@ class ListController extends Controller public function accounts(PiggyBank $piggyBank): JsonResponse { // types to get, page size: - $pageSize = $this->parameters->get('limit'); - $manager = $this->getManager(); + $pageSize = $this->parameters->get('limit'); + $manager = $this->getManager(); - $collection = $piggyBank->accounts; - $count = $collection->count(); - $accounts = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $collection = $piggyBank->accounts; + $count = $collection->count(); + $accounts = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new AccountEnrichment(); + $admin = auth()->user(); + $enrichment = new AccountEnrichment(); $enrichment->setDate($this->parameters->get('date')); $enrichment->setUser($admin); - $accounts = $enrichment->enrich($accounts); + $accounts = $enrichment->enrich($accounts); // make paginator: - $paginator = new LengthAwarePaginator($accounts, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.piggy-banks.accounts', [$piggyBank->id]).$this->buildParams()); + $paginator = new LengthAwarePaginator($accounts, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.piggy-banks.accounts', [$piggyBank->id]) . $this->buildParams()); /** @var AccountTransformer $transformer */ $transformer = app(AccountTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($accounts, $transformer, 'accounts'); + $resource = new FractalCollection($accounts, $transformer, 'accounts'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -105,22 +103,22 @@ class ListController extends Controller */ public function attachments(PiggyBank $piggyBank): JsonResponse { - $manager = $this->getManager(); - $pageSize = $this->parameters->get('limit'); - $collection = $this->repository->getAttachments($piggyBank); + $manager = $this->getManager(); + $pageSize = $this->parameters->get('limit'); + $collection = $this->repository->getAttachments($piggyBank); $count = $collection->count(); $attachments = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($attachments, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.piggy-banks.attachments', [$piggyBank->id]).$this->buildParams()); + $paginator = new LengthAwarePaginator($attachments, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.piggy-banks.attachments', [$piggyBank->id]) . $this->buildParams()); /** @var AttachmentTransformer $transformer */ $transformer = app(AttachmentTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($attachments, $transformer, 'attachments'); + $resource = new FractalCollection($attachments, $transformer, 'attachments'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -135,29 +133,29 @@ class ListController extends Controller public function piggyBankEvents(PiggyBank $piggyBank): JsonResponse { // types to get, page size: - $pageSize = $this->parameters->get('limit'); - $manager = $this->getManager(); + $pageSize = $this->parameters->get('limit'); + $manager = $this->getManager(); - $collection = $this->repository->getEvents($piggyBank); - $count = $collection->count(); - $events = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $collection = $this->repository->getEvents($piggyBank); + $count = $collection->count(); + $events = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new PiggyBankEventEnrichment(); + $admin = auth()->user(); + $enrichment = new PiggyBankEventEnrichment(); $enrichment->setUser($admin); - $events = $enrichment->enrich($events); + $events = $enrichment->enrich($events); // make paginator: - $paginator = new LengthAwarePaginator($events, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.piggy-banks.events', [$piggyBank->id]).$this->buildParams()); + $paginator = new LengthAwarePaginator($events, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.piggy-banks.events', [$piggyBank->id]) . $this->buildParams()); /** @var PiggyBankEventTransformer $transformer */ $transformer = app(PiggyBankEventTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($events, $transformer, sprintf('piggy-banks/%d/events', $piggyBank->id)); + $resource = new FractalCollection($events, $transformer, sprintf('piggy-banks/%d/events', $piggyBank->id)); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Models/PiggyBank/ShowController.php b/app/Api/V1/Controllers/Models/PiggyBank/ShowController.php index 7fb1fb5e71..8dea00b766 100644 --- a/app/Api/V1/Controllers/Models/PiggyBank/ShowController.php +++ b/app/Api/V1/Controllers/Models/PiggyBank/ShowController.php @@ -49,14 +49,12 @@ class ShowController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(PiggyBankRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(PiggyBankRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -67,31 +65,31 @@ class ShowController extends Controller */ public function index(): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // types to get, page size: - $pageSize = $this->parameters->get('limit'); + $pageSize = $this->parameters->get('limit'); // get list of piggy banks. Count it and split it. - $collection = $this->repository->getPiggyBanks(); - $count = $collection->count(); - $piggyBanks = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $collection = $this->repository->getPiggyBanks(); + $count = $collection->count(); + $piggyBanks = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new PiggyBankEnrichment(); + $admin = auth()->user(); + $enrichment = new PiggyBankEnrichment(); $enrichment->setUser($admin); - $piggyBanks = $enrichment->enrich($piggyBanks); + $piggyBanks = $enrichment->enrich($piggyBanks); // make paginator: - $paginator = new LengthAwarePaginator($piggyBanks, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.piggy-banks.index').$this->buildParams()); + $paginator = new LengthAwarePaginator($piggyBanks, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.piggy-banks.index') . $this->buildParams()); /** @var PiggyBankTransformer $transformer */ $transformer = app(PiggyBankTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($piggyBanks, $transformer, 'piggy-banks'); + $resource = new FractalCollection($piggyBanks, $transformer, 'piggy-banks'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -105,21 +103,20 @@ class ShowController extends Controller */ public function show(PiggyBank $piggyBank): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new PiggyBankEnrichment(); + $admin = auth()->user(); + $enrichment = new PiggyBankEnrichment(); $enrichment->setUser($admin); - $piggyBank = $enrichment->enrichSingle($piggyBank); - + $piggyBank = $enrichment->enrichSingle($piggyBank); /** @var PiggyBankTransformer $transformer */ $transformer = app(PiggyBankTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($piggyBank, $transformer, 'piggy-banks'); + $resource = new Item($piggyBank, $transformer, 'piggy-banks'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/PiggyBank/StoreController.php b/app/Api/V1/Controllers/Models/PiggyBank/StoreController.php index 175962c507..6682ef250a 100644 --- a/app/Api/V1/Controllers/Models/PiggyBank/StoreController.php +++ b/app/Api/V1/Controllers/Models/PiggyBank/StoreController.php @@ -47,14 +47,12 @@ class StoreController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(PiggyBankRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(PiggyBankRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -67,21 +65,21 @@ class StoreController extends Controller */ public function store(StoreRequest $request): JsonResponse { - $piggyBank = $this->repository->store($request->getAll()); - $manager = $this->getManager(); + $piggyBank = $this->repository->store($request->getAll()); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new PiggyBankEnrichment(); + $admin = auth()->user(); + $enrichment = new PiggyBankEnrichment(); $enrichment->setUser($admin); - $piggyBank = $enrichment->enrichSingle($piggyBank); + $piggyBank = $enrichment->enrichSingle($piggyBank); /** @var PiggyBankTransformer $transformer */ $transformer = app(PiggyBankTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($piggyBank, $transformer, 'piggy_banks'); + $resource = new Item($piggyBank, $transformer, 'piggy_banks'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/PiggyBank/UpdateController.php b/app/Api/V1/Controllers/Models/PiggyBank/UpdateController.php index ba53793505..0e8fb4ab20 100644 --- a/app/Api/V1/Controllers/Models/PiggyBank/UpdateController.php +++ b/app/Api/V1/Controllers/Models/PiggyBank/UpdateController.php @@ -47,14 +47,12 @@ class UpdateController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(PiggyBankRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(PiggyBankRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -65,23 +63,23 @@ class UpdateController extends Controller */ public function update(UpdateRequest $request, PiggyBank $piggyBank): JsonResponse { - $data = $request->getAll(); - $piggyBank = $this->repository->update($piggyBank, $data); + $data = $request->getAll(); + $piggyBank = $this->repository->update($piggyBank, $data); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new PiggyBankEnrichment(); + $admin = auth()->user(); + $enrichment = new PiggyBankEnrichment(); $enrichment->setUser($admin); - $piggyBank = $enrichment->enrichSingle($piggyBank); + $piggyBank = $enrichment->enrichSingle($piggyBank); - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var PiggyBankTransformer $transformer */ $transformer = app(PiggyBankTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($piggyBank, $transformer, 'piggy-banks'); + $resource = new Item($piggyBank, $transformer, 'piggy-banks'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Recurrence/DestroyController.php b/app/Api/V1/Controllers/Models/Recurrence/DestroyController.php index 8d596798d9..6bc9d9d635 100644 --- a/app/Api/V1/Controllers/Models/Recurrence/DestroyController.php +++ b/app/Api/V1/Controllers/Models/Recurrence/DestroyController.php @@ -43,14 +43,12 @@ class DestroyController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(RecurringRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(RecurringRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** diff --git a/app/Api/V1/Controllers/Models/Recurrence/ListController.php b/app/Api/V1/Controllers/Models/Recurrence/ListController.php index ce6a9d61a9..253cf66329 100644 --- a/app/Api/V1/Controllers/Models/Recurrence/ListController.php +++ b/app/Api/V1/Controllers/Models/Recurrence/ListController.php @@ -52,14 +52,12 @@ class ListController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(RecurringRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(RecurringRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -70,21 +68,21 @@ class ListController extends Controller */ public function transactions(Request $request, Recurrence $recurrence): JsonResponse { - $pageSize = $this->parameters->get('limit'); - $type = $request->get('type') ?? 'default'; + $pageSize = $this->parameters->get('limit'); + $type = $request->get('type') ?? 'default'; $this->parameters->set('type', $type); - $types = $this->mapTransactionTypes($this->parameters->get('type')); - $manager = $this->getManager(); + $types = $this->mapTransactionTypes($this->parameters->get('type')); + $manager = $this->getManager(); // whatever is returned by the query, it must be part of these journals: - $journalIds = $this->repository->getJournalIds($recurrence); + $journalIds = $this->repository->getJournalIds($recurrence); /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setUser($admin) // filter on journal IDs. @@ -96,8 +94,7 @@ class ListController extends Controller // set page to retrieve ->setPage($this->parameters->get('page')) // set types of transactions to return. - ->setTypes($types) - ; + ->setTypes($types); if (null !== $this->parameters->get('start')) { $collector->setStart($this->parameters->get('start')); @@ -106,19 +103,19 @@ class ListController extends Controller $collector->setEnd($this->parameters->get('end')); } - $paginator = $collector->getPaginatedGroups(); - $paginator->setPath(route('api.v1.transactions.index').$this->buildParams()); + $paginator = $collector->getPaginatedGroups(); + $paginator->setPath(route('api.v1.transactions.index') . $this->buildParams()); // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); $transactions = $enrichment->enrich($paginator->getCollection()); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($transactions, $transformer, 'transactions'); + $resource = new FractalCollection($transactions, $transformer, 'transactions'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Models/Recurrence/ShowController.php b/app/Api/V1/Controllers/Models/Recurrence/ShowController.php index 7b3b9a23b9..42297a896a 100644 --- a/app/Api/V1/Controllers/Models/Recurrence/ShowController.php +++ b/app/Api/V1/Controllers/Models/Recurrence/ShowController.php @@ -49,14 +49,12 @@ class ShowController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(RecurringRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(RecurringRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -67,10 +65,10 @@ class ShowController extends Controller */ public function index(): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // types to get, page size: - $pageSize = $this->parameters->get('limit'); + $pageSize = $this->parameters->get('limit'); // get list of budgets. Count it and split it. $collection = $this->repository->get(); @@ -79,20 +77,20 @@ class ShowController extends Controller // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new RecurringEnrichment(); + $admin = auth()->user(); + $enrichment = new RecurringEnrichment(); $enrichment->setUser($admin); $recurrences = $enrichment->enrich($recurrences); // make paginator: - $paginator = new LengthAwarePaginator($recurrences, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.recurrences.index').$this->buildParams()); + $paginator = new LengthAwarePaginator($recurrences, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.recurrences.index') . $this->buildParams()); /** @var RecurrenceTransformer $transformer */ $transformer = app(RecurrenceTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($recurrences, $transformer, 'recurrences'); + $resource = new FractalCollection($recurrences, $transformer, 'recurrences'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -106,20 +104,20 @@ class ShowController extends Controller */ public function show(Recurrence $recurrence): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new RecurringEnrichment(); + $admin = auth()->user(); + $enrichment = new RecurringEnrichment(); $enrichment->setUser($admin); - $recurrence = $enrichment->enrichSingle($recurrence); + $recurrence = $enrichment->enrichSingle($recurrence); /** @var RecurrenceTransformer $transformer */ $transformer = app(RecurrenceTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($recurrence, $transformer, 'recurrences'); + $resource = new Item($recurrence, $transformer, 'recurrences'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Recurrence/StoreController.php b/app/Api/V1/Controllers/Models/Recurrence/StoreController.php index 48148bbc3b..1b27ce8f1a 100644 --- a/app/Api/V1/Controllers/Models/Recurrence/StoreController.php +++ b/app/Api/V1/Controllers/Models/Recurrence/StoreController.php @@ -47,14 +47,12 @@ class StoreController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(RecurringRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(RecurringRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -67,22 +65,22 @@ class StoreController extends Controller */ public function store(StoreRequest $request): JsonResponse { - $data = $request->getAll(); - $recurrence = $this->repository->store($data); - $manager = $this->getManager(); + $data = $request->getAll(); + $recurrence = $this->repository->store($data); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new RecurringEnrichment(); + $admin = auth()->user(); + $enrichment = new RecurringEnrichment(); $enrichment->setUser($admin); - $recurrence = $enrichment->enrichSingle($recurrence); + $recurrence = $enrichment->enrichSingle($recurrence); /** @var RecurrenceTransformer $transformer */ $transformer = app(RecurrenceTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($recurrence, $transformer, 'recurrences'); + $resource = new Item($recurrence, $transformer, 'recurrences'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Recurrence/TriggerController.php b/app/Api/V1/Controllers/Models/Recurrence/TriggerController.php index 7f4ad30b60..dd0bb08c8d 100644 --- a/app/Api/V1/Controllers/Models/Recurrence/TriggerController.php +++ b/app/Api/V1/Controllers/Models/Recurrence/TriggerController.php @@ -1,6 +1,7 @@ middleware( - function ($request, $next) { - $this->repository = app(RecurringRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(RecurringRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } public function trigger(SingleDateRequest $request, Recurrence $recurrence): JsonResponse { // find recurrence occurrence for this date and trigger it. // grab the date from the last time the recurrence fired: - $backupDate = $recurrence->latest_date; - $date = $request->getDate(); + $backupDate = $recurrence->latest_date; + $date = $request->getDate(); // fire the recurring cron job on the given date, then post-date the created transaction. Log::info(sprintf('Trigger: will now fire recurring cron job task for date "%s".', $date->format('Y-m-d H:i:s'))); /** @var CreateRecurringTransactions $job */ - $job = app(CreateRecurringTransactions::class); + $job = app(CreateRecurringTransactions::class); $job->setRecurrences(new Collection()->push($recurrence)); $job->setDate($date); $job->setForce(false); $job->handle(); Log::debug('Done with recurrence.'); - $groups = $job->getGroups(); + $groups = $job->getGroups(); $this->repository->markGroupsAsNow($groups); - $recurrence->latest_date = $backupDate; + $recurrence->latest_date = $backupDate; $recurrence->latest_date_tz = $backupDate?->format('e'); $recurrence->save(); Preferences::mark(); // enrich groups and return them: - $paginator = new LengthAwarePaginator(new Collection(), 0, 1); + $paginator = new LengthAwarePaginator(new Collection(), 0, 1); if ($groups->count() > 0) { /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); - $collector - ->setUser($admin) - ->setIds($groups->pluck('id')->toArray()) - ->withAPIInformation() - ; + $collector->setUser($admin)->setIds($groups->pluck('id')->toArray())->withAPIInformation(); $paginator = $collector->getPaginatedGroups(); } - $manager = $this->getManager(); - $paginator->setPath(route('api.v1.recurrences.trigger', [$recurrence->id]).$this->buildParams()); + $manager = $this->getManager(); + $paginator->setPath(route('api.v1.recurrences.trigger', [$recurrence->id]) . $this->buildParams()); // enrich - $admin = auth()->user(); - $enrichment = new TransactionGroupEnrichment(); + $admin = auth()->user(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); - $transactions = $enrichment->enrich($paginator->getCollection()); + $transactions = $enrichment->enrich($paginator->getCollection()); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($transactions, $transformer, 'transactions'); + $resource = new FractalCollection($transactions, $transformer, 'transactions'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Models/Recurrence/UpdateController.php b/app/Api/V1/Controllers/Models/Recurrence/UpdateController.php index e34a445032..1855a39982 100644 --- a/app/Api/V1/Controllers/Models/Recurrence/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Recurrence/UpdateController.php @@ -47,14 +47,12 @@ class UpdateController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(RecurringRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(RecurringRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -65,22 +63,22 @@ class UpdateController extends Controller */ public function update(UpdateRequest $request, Recurrence $recurrence): JsonResponse { - $data = $request->getAll(); - $recurrence = $this->repository->update($recurrence, $data); - $manager = $this->getManager(); + $data = $request->getAll(); + $recurrence = $this->repository->update($recurrence, $data); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new RecurringEnrichment(); + $admin = auth()->user(); + $enrichment = new RecurringEnrichment(); $enrichment->setUser($admin); - $recurrence = $enrichment->enrichSingle($recurrence); + $recurrence = $enrichment->enrichSingle($recurrence); /** @var RecurrenceTransformer $transformer */ $transformer = app(RecurrenceTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($recurrence, $transformer, 'recurrences'); + $resource = new Item($recurrence, $transformer, 'recurrences'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Rule/DestroyController.php b/app/Api/V1/Controllers/Models/Rule/DestroyController.php index e8a9dbd124..51154bbe1f 100644 --- a/app/Api/V1/Controllers/Models/Rule/DestroyController.php +++ b/app/Api/V1/Controllers/Models/Rule/DestroyController.php @@ -44,17 +44,15 @@ class DestroyController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); - $this->ruleRepository = app(RuleRepositoryInterface::class); - $this->ruleRepository->setUser($user); + $this->ruleRepository = app(RuleRepositoryInterface::class); + $this->ruleRepository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** diff --git a/app/Api/V1/Controllers/Models/Rule/ExpressionController.php b/app/Api/V1/Controllers/Models/Rule/ExpressionController.php index 2187dd7fa5..6f24527c6e 100644 --- a/app/Api/V1/Controllers/Models/Rule/ExpressionController.php +++ b/app/Api/V1/Controllers/Models/Rule/ExpressionController.php @@ -41,8 +41,6 @@ class ExpressionController extends Controller */ public function validateExpression(ValidateExpressionRequest $request): JsonResponse { - return response()->json([ - 'valid' => true, - ]); + return response()->json(['valid' => true]); } } diff --git a/app/Api/V1/Controllers/Models/Rule/ShowController.php b/app/Api/V1/Controllers/Models/Rule/ShowController.php index 045c61ad28..585c3509b8 100644 --- a/app/Api/V1/Controllers/Models/Rule/ShowController.php +++ b/app/Api/V1/Controllers/Models/Rule/ShowController.php @@ -48,17 +48,15 @@ class ShowController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); - $this->ruleRepository = app(RuleRepositoryInterface::class); - $this->ruleRepository->setUser($user); + $this->ruleRepository = app(RuleRepositoryInterface::class); + $this->ruleRepository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -69,25 +67,25 @@ class ShowController extends Controller */ public function index(): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // types to get, page size: - $pageSize = $this->parameters->get('limit'); + $pageSize = $this->parameters->get('limit'); // get list of budgets. Count it and split it. - $collection = $this->ruleRepository->getAll(); - $count = $collection->count(); - $rules = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $collection = $this->ruleRepository->getAll(); + $count = $collection->count(); + $rules = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($rules, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.rules.index').$this->buildParams()); + $paginator = new LengthAwarePaginator($rules, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.rules.index') . $this->buildParams()); /** @var RuleTransformer $transformer */ $transformer = app(RuleTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($rules, $transformer, 'rules'); + $resource = new FractalCollection($rules, $transformer, 'rules'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -101,13 +99,13 @@ class ShowController extends Controller */ public function show(Rule $rule): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var RuleTransformer $transformer */ $transformer = app(RuleTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($rule, $transformer, 'rules'); + $resource = new Item($rule, $transformer, 'rules'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Rule/StoreController.php b/app/Api/V1/Controllers/Models/Rule/StoreController.php index 640ebb738b..5f419aa5b8 100644 --- a/app/Api/V1/Controllers/Models/Rule/StoreController.php +++ b/app/Api/V1/Controllers/Models/Rule/StoreController.php @@ -45,17 +45,15 @@ class StoreController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); - $this->ruleRepository = app(RuleRepositoryInterface::class); - $this->ruleRepository->setUser($user); + $this->ruleRepository = app(RuleRepositoryInterface::class); + $this->ruleRepository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -66,14 +64,14 @@ class StoreController extends Controller */ public function store(StoreRequest $request): JsonResponse { - $rule = $this->ruleRepository->store($request->getAll()); - $manager = $this->getManager(); + $rule = $this->ruleRepository->store($request->getAll()); + $manager = $this->getManager(); /** @var RuleTransformer $transformer */ $transformer = app(RuleTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($rule, $transformer, 'rules'); + $resource = new Item($rule, $transformer, 'rules'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Rule/TriggerController.php b/app/Api/V1/Controllers/Models/Rule/TriggerController.php index 2fab36ba92..0881bafd2a 100644 --- a/app/Api/V1/Controllers/Models/Rule/TriggerController.php +++ b/app/Api/V1/Controllers/Models/Rule/TriggerController.php @@ -52,17 +52,15 @@ class TriggerController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); - $this->ruleRepository = app(RuleRepositoryInterface::class); - $this->ruleRepository->setUser($user); + $this->ruleRepository = app(RuleRepositoryInterface::class); + $this->ruleRepository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -71,24 +69,24 @@ class TriggerController extends Controller */ public function testRule(TestRequest $request, Rule $rule): JsonResponse { - $parameters = $request->getTestParameters(); + $parameters = $request->getTestParameters(); /** @var RuleEngineInterface $ruleEngine */ - $ruleEngine = app(RuleEngineInterface::class); + $ruleEngine = app(RuleEngineInterface::class); $ruleEngine->setRules(new Collection()->push($rule)); // overrule the rule(s) if necessary. if (array_key_exists('start', $parameters) && null !== $parameters['start']) { // add a range: - $ruleEngine->addOperator(['type' => 'date_after', 'value' => $parameters['start']->format('Y-m-d')]); + $ruleEngine->addOperator(['type' => 'date_after', 'value' => $parameters['start']->format('Y-m-d')]); } if (array_key_exists('end', $parameters) && null !== $parameters['end']) { // add a range: - $ruleEngine->addOperator(['type' => 'date_before', 'value' => $parameters['end']->format('Y-m-d')]); + $ruleEngine->addOperator(['type' => 'date_before', 'value' => $parameters['end']->format('Y-m-d')]); } if (array_key_exists('accounts', $parameters) && '' !== $parameters['accounts']) { - $ruleEngine->addOperator(['type' => 'account_id', 'value' => implode(',', $parameters['accounts'])]); + $ruleEngine->addOperator(['type' => 'account_id', 'value' => implode(',', $parameters['accounts'])]); } // file the rule(s) @@ -96,21 +94,21 @@ class TriggerController extends Controller $count = $transactions->count(); // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($rule->user); $transactions = $enrichment->enrich($transactions); - $paginator = new LengthAwarePaginator($transactions, $count, 31337, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.rules.test', [$rule->id]).$this->buildParams()); + $paginator = new LengthAwarePaginator($transactions, $count, 31337, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.rules.test', [$rule->id]) . $this->buildParams()); // resulting list is presented as JSON thing. - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($transactions, $transformer, 'transactions'); + $resource = new FractalCollection($transactions, $transformer, 'transactions'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -134,15 +132,15 @@ class TriggerController extends Controller // overrule the rule(s) if necessary. if (array_key_exists('start', $parameters) && null !== $parameters['start']) { // add a range: - $ruleEngine->addOperator(['type' => 'date_after', 'value' => $parameters['start']->format('Y-m-d')]); + $ruleEngine->addOperator(['type' => 'date_after', 'value' => $parameters['start']->format('Y-m-d')]); } if (array_key_exists('end', $parameters) && null !== $parameters['end']) { // add a range: - $ruleEngine->addOperator(['type' => 'date_before', 'value' => $parameters['end']->format('Y-m-d')]); + $ruleEngine->addOperator(['type' => 'date_before', 'value' => $parameters['end']->format('Y-m-d')]); } if (array_key_exists('accounts', $parameters) && is_array($parameters['accounts']) && count($parameters['accounts']) > 0) { - $ruleEngine->addOperator(['type' => 'account_id', 'value' => implode(',', $parameters['accounts'])]); + $ruleEngine->addOperator(['type' => 'account_id', 'value' => implode(',', $parameters['accounts'])]); } // fire the rule(s) diff --git a/app/Api/V1/Controllers/Models/Rule/UpdateController.php b/app/Api/V1/Controllers/Models/Rule/UpdateController.php index d58c9bd5c0..a863b73a90 100644 --- a/app/Api/V1/Controllers/Models/Rule/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Rule/UpdateController.php @@ -46,17 +46,15 @@ class UpdateController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); - $this->ruleRepository = app(RuleRepositoryInterface::class); - $this->ruleRepository->setUser($user); + $this->ruleRepository = app(RuleRepositoryInterface::class); + $this->ruleRepository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -67,15 +65,15 @@ class UpdateController extends Controller */ public function update(UpdateRequest $request, Rule $rule): JsonResponse { - $data = $request->getAll(); - $rule = $this->ruleRepository->update($rule, $data); - $manager = $this->getManager(); + $data = $request->getAll(); + $rule = $this->ruleRepository->update($rule, $data); + $manager = $this->getManager(); /** @var RuleTransformer $transformer */ $transformer = app(RuleTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($rule, $transformer, 'rules'); + $resource = new Item($rule, $transformer, 'rules'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/RuleGroup/DestroyController.php b/app/Api/V1/Controllers/Models/RuleGroup/DestroyController.php index 9924ba1c75..cd002c83b2 100644 --- a/app/Api/V1/Controllers/Models/RuleGroup/DestroyController.php +++ b/app/Api/V1/Controllers/Models/RuleGroup/DestroyController.php @@ -44,17 +44,15 @@ class DestroyController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); - $this->ruleGroupRepository = app(RuleGroupRepositoryInterface::class); - $this->ruleGroupRepository->setUser($user); + $this->ruleGroupRepository = app(RuleGroupRepositoryInterface::class); + $this->ruleGroupRepository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** diff --git a/app/Api/V1/Controllers/Models/RuleGroup/ListController.php b/app/Api/V1/Controllers/Models/RuleGroup/ListController.php index 2d296ce903..9ba8ba9707 100644 --- a/app/Api/V1/Controllers/Models/RuleGroup/ListController.php +++ b/app/Api/V1/Controllers/Models/RuleGroup/ListController.php @@ -47,17 +47,15 @@ class ListController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); - $this->ruleGroupRepository = app(RuleGroupRepositoryInterface::class); - $this->ruleGroupRepository->setUser($user); + $this->ruleGroupRepository = app(RuleGroupRepositoryInterface::class); + $this->ruleGroupRepository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -66,24 +64,24 @@ class ListController extends Controller */ public function rules(RuleGroup $group): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // types to get, page size: - $pageSize = $this->parameters->get('limit'); + $pageSize = $this->parameters->get('limit'); // get list of budgets. Count it and split it. - $collection = $this->ruleGroupRepository->getRules($group); - $count = $collection->count(); - $rules = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $collection = $this->ruleGroupRepository->getRules($group); + $count = $collection->count(); + $rules = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($rules, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.rule-groups.rules', [$group->id]).$this->buildParams()); + $paginator = new LengthAwarePaginator($rules, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.rule-groups.rules', [$group->id]) . $this->buildParams()); /** @var RuleTransformer $transformer */ $transformer = app(RuleTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($rules, $transformer, 'rules'); + $resource = new FractalCollection($rules, $transformer, 'rules'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Models/RuleGroup/ShowController.php b/app/Api/V1/Controllers/Models/RuleGroup/ShowController.php index b5f08d9d9a..eb26ecf7a2 100644 --- a/app/Api/V1/Controllers/Models/RuleGroup/ShowController.php +++ b/app/Api/V1/Controllers/Models/RuleGroup/ShowController.php @@ -48,17 +48,15 @@ class ShowController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); - $this->ruleGroupRepository = app(RuleGroupRepositoryInterface::class); - $this->ruleGroupRepository->setUser($user); + $this->ruleGroupRepository = app(RuleGroupRepositoryInterface::class); + $this->ruleGroupRepository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -68,24 +66,24 @@ class ShowController extends Controller */ public function index(): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // types to get, page size: - $pageSize = $this->parameters->get('limit'); + $pageSize = $this->parameters->get('limit'); // get list of rule groups. Count it and split it. - $collection = $this->ruleGroupRepository->get(); - $count = $collection->count(); - $ruleGroups = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $collection = $this->ruleGroupRepository->get(); + $count = $collection->count(); + $ruleGroups = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($ruleGroups, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.rule-groups.index').$this->buildParams()); + $paginator = new LengthAwarePaginator($ruleGroups, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.rule-groups.index') . $this->buildParams()); /** @var RuleGroupTransformer $transformer */ $transformer = app(RuleGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($ruleGroups, $transformer, 'rule_groups'); + $resource = new FractalCollection($ruleGroups, $transformer, 'rule_groups'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -99,13 +97,13 @@ class ShowController extends Controller */ public function show(RuleGroup $ruleGroup): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var RuleGroupTransformer $transformer */ $transformer = app(RuleGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($ruleGroup, $transformer, 'rule_groups'); + $resource = new Item($ruleGroup, $transformer, 'rule_groups'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/RuleGroup/StoreController.php b/app/Api/V1/Controllers/Models/RuleGroup/StoreController.php index e73cf05d65..75858725a8 100644 --- a/app/Api/V1/Controllers/Models/RuleGroup/StoreController.php +++ b/app/Api/V1/Controllers/Models/RuleGroup/StoreController.php @@ -38,7 +38,7 @@ use League\Fractal\Resource\Item; */ class StoreController extends Controller { - private AccountRepositoryInterface $accountRepository; + private AccountRepositoryInterface $accountRepository; private RuleGroupRepositoryInterface $ruleGroupRepository; /** @@ -47,20 +47,18 @@ class StoreController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); - $this->ruleGroupRepository = app(RuleGroupRepositoryInterface::class); - $this->ruleGroupRepository->setUser($user); + $this->ruleGroupRepository = app(RuleGroupRepositoryInterface::class); + $this->ruleGroupRepository->setUser($user); - $this->accountRepository = app(AccountRepositoryInterface::class); - $this->accountRepository->setUser($user); + $this->accountRepository = app(AccountRepositoryInterface::class); + $this->accountRepository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -71,14 +69,14 @@ class StoreController extends Controller */ public function store(StoreRequest $request): JsonResponse { - $ruleGroup = $this->ruleGroupRepository->store($request->getAll()); - $manager = $this->getManager(); + $ruleGroup = $this->ruleGroupRepository->store($request->getAll()); + $manager = $this->getManager(); /** @var RuleGroupTransformer $transformer */ $transformer = app(RuleGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($ruleGroup, $transformer, 'rule_groups'); + $resource = new Item($ruleGroup, $transformer, 'rule_groups'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/RuleGroup/TriggerController.php b/app/Api/V1/Controllers/Models/RuleGroup/TriggerController.php index 4a4ef9eb69..44e900344d 100644 --- a/app/Api/V1/Controllers/Models/RuleGroup/TriggerController.php +++ b/app/Api/V1/Controllers/Models/RuleGroup/TriggerController.php @@ -53,17 +53,15 @@ class TriggerController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); - $this->ruleGroupRepository = app(RuleGroupRepositoryInterface::class); - $this->ruleGroupRepository->setUser($user); + $this->ruleGroupRepository = app(RuleGroupRepositoryInterface::class); + $this->ruleGroupRepository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -74,28 +72,28 @@ class TriggerController extends Controller */ public function testGroup(TestRequest $request, RuleGroup $group): JsonResponse { - $rules = $this->ruleGroupRepository->getActiveRules($group); + $rules = $this->ruleGroupRepository->getActiveRules($group); if (0 === $rules->count()) { throw new FireflyException('200023: No rules in this rule group.'); } - $parameters = $request->getTestParameters(); + $parameters = $request->getTestParameters(); /** @var RuleEngineInterface $ruleEngine */ - $ruleEngine = app(RuleEngineInterface::class); + $ruleEngine = app(RuleEngineInterface::class); $ruleEngine->setRules($rules); // overrule the rule(s) if necessary. if (array_key_exists('start', $parameters) && null !== $parameters['start']) { // add a range: - $ruleEngine->addOperator(['type' => 'date_after', 'value' => $parameters['start']->format('Y-m-d')]); + $ruleEngine->addOperator(['type' => 'date_after', 'value' => $parameters['start']->format('Y-m-d')]); } if (array_key_exists('end', $parameters) && null !== $parameters['end']) { // add a range: - $ruleEngine->addOperator(['type' => 'date_before', 'value' => $parameters['end']->format('Y-m-d')]); + $ruleEngine->addOperator(['type' => 'date_before', 'value' => $parameters['end']->format('Y-m-d')]); } if (array_key_exists('accounts', $parameters) && '' !== $parameters['accounts']) { - $ruleEngine->addOperator(['type' => 'account_id', 'value' => implode(',', $parameters['accounts'])]); + $ruleEngine->addOperator(['type' => 'account_id', 'value' => implode(',', $parameters['accounts'])]); } // file the rule(s) @@ -103,21 +101,21 @@ class TriggerController extends Controller $count = $transactions->count(); // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($group->user); $transactions = $enrichment->enrich($transactions); - $paginator = new LengthAwarePaginator($transactions, $count, 31337, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.rule-groups.test', [$group->id]).$this->buildParams()); + $paginator = new LengthAwarePaginator($transactions, $count, 31337, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.rule-groups.test', [$group->id]) . $this->buildParams()); // resulting list is presented as JSON thing. - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($transactions, $transformer, 'transactions'); + $resource = new FractalCollection($transactions, $transformer, 'transactions'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -133,7 +131,7 @@ class TriggerController extends Controller */ public function triggerGroup(TriggerRequest $request, RuleGroup $group): JsonResponse { - $rules = $this->ruleGroupRepository->getActiveRules($group); + $rules = $this->ruleGroupRepository->getActiveRules($group); if (0 === $rules->count()) { throw new FireflyException('200023: No rules in this rule group.'); } @@ -148,15 +146,15 @@ class TriggerController extends Controller // overrule the rule(s) if necessary. if (array_key_exists('start', $parameters) && null !== $parameters['start']) { // add a range: - $ruleEngine->addOperator(['type' => 'date_after', 'value' => $parameters['start']->format('Y-m-d')]); + $ruleEngine->addOperator(['type' => 'date_after', 'value' => $parameters['start']->format('Y-m-d')]); } if (array_key_exists('end', $parameters) && null !== $parameters['end']) { // add a range: - $ruleEngine->addOperator(['type' => 'date_before', 'value' => $parameters['end']->format('Y-m-d')]); + $ruleEngine->addOperator(['type' => 'date_before', 'value' => $parameters['end']->format('Y-m-d')]); } if (array_key_exists('accounts', $parameters) && is_array($parameters['accounts']) && count($parameters['accounts']) > 0) { - $ruleEngine->addOperator(['type' => 'account_id', 'value' => implode(',', $parameters['accounts'])]); + $ruleEngine->addOperator(['type' => 'account_id', 'value' => implode(',', $parameters['accounts'])]); } // file the rule(s) diff --git a/app/Api/V1/Controllers/Models/RuleGroup/UpdateController.php b/app/Api/V1/Controllers/Models/RuleGroup/UpdateController.php index 3d3c514768..bcfe10e602 100644 --- a/app/Api/V1/Controllers/Models/RuleGroup/UpdateController.php +++ b/app/Api/V1/Controllers/Models/RuleGroup/UpdateController.php @@ -46,17 +46,15 @@ class UpdateController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); - $this->ruleGroupRepository = app(RuleGroupRepositoryInterface::class); - $this->ruleGroupRepository->setUser($user); + $this->ruleGroupRepository = app(RuleGroupRepositoryInterface::class); + $this->ruleGroupRepository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -67,14 +65,14 @@ class UpdateController extends Controller */ public function update(UpdateRequest $request, RuleGroup $ruleGroup): JsonResponse { - $ruleGroup = $this->ruleGroupRepository->update($ruleGroup, $request->getAll()); - $manager = $this->getManager(); + $ruleGroup = $this->ruleGroupRepository->update($ruleGroup, $request->getAll()); + $manager = $this->getManager(); /** @var RuleGroupTransformer $transformer */ $transformer = app(RuleGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($ruleGroup, $transformer, 'rule_groups'); + $resource = new Item($ruleGroup, $transformer, 'rule_groups'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Tag/DestroyController.php b/app/Api/V1/Controllers/Models/Tag/DestroyController.php index fa6a31071a..35c982314a 100644 --- a/app/Api/V1/Controllers/Models/Tag/DestroyController.php +++ b/app/Api/V1/Controllers/Models/Tag/DestroyController.php @@ -44,17 +44,15 @@ class DestroyController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); - $this->repository = app(TagRepositoryInterface::class); - $this->repository->setUser($user); + $this->repository = app(TagRepositoryInterface::class); + $this->repository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** diff --git a/app/Api/V1/Controllers/Models/Tag/ListController.php b/app/Api/V1/Controllers/Models/Tag/ListController.php index aed5652f85..20bb2113c7 100644 --- a/app/Api/V1/Controllers/Models/Tag/ListController.php +++ b/app/Api/V1/Controllers/Models/Tag/ListController.php @@ -54,17 +54,15 @@ class ListController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); - $this->repository = app(TagRepositoryInterface::class); - $this->repository->setUser($user); + $this->repository = app(TagRepositoryInterface::class); + $this->repository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -73,22 +71,22 @@ class ListController extends Controller */ public function attachments(Tag $tag): JsonResponse { - $manager = $this->getManager(); - $pageSize = $this->parameters->get('limit'); - $collection = $this->repository->getAttachments($tag); + $manager = $this->getManager(); + $pageSize = $this->parameters->get('limit'); + $collection = $this->repository->getAttachments($tag); $count = $collection->count(); $attachments = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($attachments, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.tags.attachments', [$tag->id]).$this->buildParams()); + $paginator = new LengthAwarePaginator($attachments, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.tags.attachments', [$tag->id]) . $this->buildParams()); /** @var AttachmentTransformer $transformer */ $transformer = app(AttachmentTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($attachments, $transformer, 'attachments'); + $resource = new FractalCollection($attachments, $transformer, 'attachments'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -102,19 +100,19 @@ class ListController extends Controller */ public function transactions(Request $request, Tag $tag): JsonResponse { - $pageSize = $this->parameters->get('limit'); - $type = $request->get('type') ?? 'default'; + $pageSize = $this->parameters->get('limit'); + $type = $request->get('type') ?? 'default'; $this->parameters->set('type', $type); - $types = $this->mapTransactionTypes($this->parameters->get('type')); - $manager = $this->getManager(); + $types = $this->mapTransactionTypes($this->parameters->get('type')); + $manager = $this->getManager(); /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setUser($admin) // filter on tag. @@ -126,8 +124,7 @@ class ListController extends Controller // set page to retrieve ->setPage($this->parameters->get('page')) // set types of transactions to return. - ->setTypes($types) - ; + ->setTypes($types); if (null !== $this->parameters->get('start')) { $collector->setStart($this->parameters->get('start')); @@ -135,20 +132,19 @@ class ListController extends Controller if (null !== $this->parameters->get('end')) { $collector->setEnd($this->parameters->get('end')); } - $paginator = $collector->getPaginatedGroups(); - $paginator->setPath(route('api.v1.tags.transactions', [$tag->id]).$this->buildParams()); + $paginator = $collector->getPaginatedGroups(); + $paginator->setPath(route('api.v1.tags.transactions', [$tag->id]) . $this->buildParams()); // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); $transactions = $enrichment->enrich($paginator->getCollection()); - /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($transactions, $transformer, 'transactions'); + $resource = new FractalCollection($transactions, $transformer, 'transactions'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Models/Tag/ShowController.php b/app/Api/V1/Controllers/Models/Tag/ShowController.php index f239cb35c5..72b3644332 100644 --- a/app/Api/V1/Controllers/Models/Tag/ShowController.php +++ b/app/Api/V1/Controllers/Models/Tag/ShowController.php @@ -48,17 +48,15 @@ class ShowController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); - $this->repository = app(TagRepositoryInterface::class); - $this->repository->setUser($user); + $this->repository = app(TagRepositoryInterface::class); + $this->repository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -69,24 +67,24 @@ class ShowController extends Controller */ public function index(): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // types to get, page size: - $pageSize = $this->parameters->get('limit'); + $pageSize = $this->parameters->get('limit'); // get list of budgets. Count it and split it. - $collection = $this->repository->get(); - $count = $collection->count(); - $rules = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $collection = $this->repository->get(); + $count = $collection->count(); + $rules = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($rules, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.tags.index').$this->buildParams()); + $paginator = new LengthAwarePaginator($rules, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.tags.index') . $this->buildParams()); /** @var TagTransformer $transformer */ $transformer = app(TagTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($rules, $transformer, 'tags'); + $resource = new FractalCollection($rules, $transformer, 'tags'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -100,13 +98,13 @@ class ShowController extends Controller */ public function show(Tag $tag): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var TagTransformer $transformer */ $transformer = app(TagTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($tag, $transformer, 'tags'); + $resource = new Item($tag, $transformer, 'tags'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Tag/StoreController.php b/app/Api/V1/Controllers/Models/Tag/StoreController.php index 8308532e79..16a09d7fd0 100644 --- a/app/Api/V1/Controllers/Models/Tag/StoreController.php +++ b/app/Api/V1/Controllers/Models/Tag/StoreController.php @@ -45,17 +45,15 @@ class StoreController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); - $this->repository = app(TagRepositoryInterface::class); - $this->repository->setUser($user); + $this->repository = app(TagRepositoryInterface::class); + $this->repository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -66,14 +64,14 @@ class StoreController extends Controller */ public function store(StoreRequest $request): JsonResponse { - $rule = $this->repository->store($request->getAll()); - $manager = $this->getManager(); + $rule = $this->repository->store($request->getAll()); + $manager = $this->getManager(); /** @var TagTransformer $transformer */ $transformer = app(TagTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($rule, $transformer, 'tags'); + $resource = new Item($rule, $transformer, 'tags'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Tag/UpdateController.php b/app/Api/V1/Controllers/Models/Tag/UpdateController.php index 515322370c..339238e5f6 100644 --- a/app/Api/V1/Controllers/Models/Tag/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Tag/UpdateController.php @@ -46,17 +46,15 @@ class UpdateController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); - $this->repository = app(TagRepositoryInterface::class); - $this->repository->setUser($user); + $this->repository = app(TagRepositoryInterface::class); + $this->repository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -67,14 +65,14 @@ class UpdateController extends Controller */ public function update(UpdateRequest $request, Tag $tag): JsonResponse { - $rule = $this->repository->update($tag, $request->getAll()); - $manager = $this->getManager(); + $rule = $this->repository->update($tag, $request->getAll()); + $manager = $this->getManager(); /** @var TagTransformer $transformer */ $transformer = app(TagTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($rule, $transformer, 'tags'); + $resource = new Item($rule, $transformer, 'tags'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Transaction/DestroyController.php b/app/Api/V1/Controllers/Models/Transaction/DestroyController.php index ecf6a28432..a228a59ce7 100644 --- a/app/Api/V1/Controllers/Models/Transaction/DestroyController.php +++ b/app/Api/V1/Controllers/Models/Transaction/DestroyController.php @@ -51,20 +51,18 @@ class DestroyController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $admin */ - $admin = auth()->user(); + $this->middleware(function ($request, $next) { + /** @var User $admin */ + $admin = auth()->user(); - $this->repository = app(JournalRepositoryInterface::class); - $this->repository->setUser($admin); + $this->repository = app(JournalRepositoryInterface::class); + $this->repository->setUser($admin); - $this->groupRepository = app(TransactionGroupRepository::class); - $this->groupRepository->setUser($admin); + $this->groupRepository = app(TransactionGroupRepository::class); + $this->groupRepository->setUser($admin); - return $next($request); - } - ); + return $next($request); + }); } /** diff --git a/app/Api/V1/Controllers/Models/Transaction/ListController.php b/app/Api/V1/Controllers/Models/Transaction/ListController.php index ab96a00af7..680d581bad 100644 --- a/app/Api/V1/Controllers/Models/Transaction/ListController.php +++ b/app/Api/V1/Controllers/Models/Transaction/ListController.php @@ -52,17 +52,15 @@ class ListController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $admin */ - $admin = auth()->user(); + $this->middleware(function ($request, $next) { + /** @var User $admin */ + $admin = auth()->user(); - $this->journalAPIRepository = app(JournalAPIRepositoryInterface::class); - $this->journalAPIRepository->setUser($admin); + $this->journalAPIRepository = app(JournalAPIRepositoryInterface::class); + $this->journalAPIRepository->setUser($admin); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -71,9 +69,9 @@ class ListController extends Controller */ public function attachments(TransactionGroup $transactionGroup): JsonResponse { - $manager = $this->getManager(); - $pageSize = $this->parameters->get('limit'); - $collection = new Collection(); + $manager = $this->getManager(); + $pageSize = $this->parameters->get('limit'); + $collection = new Collection(); foreach ($transactionGroup->transactionJournals as $transactionJournal) { $collection = $this->journalAPIRepository->getAttachments($transactionJournal)->merge($collection); } @@ -82,14 +80,14 @@ class ListController extends Controller $attachments = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($attachments, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.transactions.attachments', [$transactionGroup->id]).$this->buildParams()); + $paginator = new LengthAwarePaginator($attachments, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.transactions.attachments', [$transactionGroup->id]) . $this->buildParams()); /** @var AttachmentTransformer $transformer */ $transformer = app(AttachmentTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($attachments, $transformer, 'attachments'); + $resource = new FractalCollection($attachments, $transformer, 'attachments'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -101,31 +99,31 @@ class ListController extends Controller */ public function piggyBankEvents(TransactionGroup $transactionGroup): JsonResponse { - $manager = $this->getManager(); - $collection = new Collection(); - $pageSize = $this->parameters->get('limit'); + $manager = $this->getManager(); + $collection = new Collection(); + $pageSize = $this->parameters->get('limit'); foreach ($transactionGroup->transactionJournals as $transactionJournal) { $collection = $this->journalAPIRepository->getPiggyBankEvents($transactionJournal)->merge($collection); } - $count = $collection->count(); - $events = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $count = $collection->count(); + $events = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new PiggyBankEventEnrichment(); + $admin = auth()->user(); + $enrichment = new PiggyBankEventEnrichment(); $enrichment->setUser($admin); - $events = $enrichment->enrich($events); + $events = $enrichment->enrich($events); // make paginator: - $paginator = new LengthAwarePaginator($events, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.transactions.piggy-bank-events', [$transactionGroup->id]).$this->buildParams()); + $paginator = new LengthAwarePaginator($events, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.transactions.piggy-bank-events', [$transactionGroup->id]) . $this->buildParams()); /** @var PiggyBankEventTransformer $transformer */ $transformer = app(PiggyBankEventTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($events, $transformer, 'piggy_bank_events'); + $resource = new FractalCollection($events, $transformer, 'piggy_bank_events'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); // /** @var PiggyBankEventTransformer $transformer */ // $transformer = app(PiggyBankEventTransformer::class); @@ -149,14 +147,14 @@ class ListController extends Controller $journalLinks = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($journalLinks, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.transaction-journals.transaction-links', [$transactionJournal->id]).$this->buildParams()); + $paginator = new LengthAwarePaginator($journalLinks, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.transaction-journals.transaction-links', [$transactionJournal->id]) . $this->buildParams()); /** @var TransactionLinkTransformer $transformer */ - $transformer = app(TransactionLinkTransformer::class); + $transformer = app(TransactionLinkTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($journalLinks, $transformer, 'transaction_links'); + $resource = new FractalCollection($journalLinks, $transformer, 'transaction_links'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Models/Transaction/ShowController.php b/app/Api/V1/Controllers/Models/Transaction/ShowController.php index ee45ded96d..20ed91b321 100644 --- a/app/Api/V1/Controllers/Models/Transaction/ShowController.php +++ b/app/Api/V1/Controllers/Models/Transaction/ShowController.php @@ -54,19 +54,19 @@ class ShowController extends Controller */ public function index(Request $request): JsonResponse { - $pageSize = $this->parameters->get('limit'); - $type = $request->get('type') ?? 'default'; + $pageSize = $this->parameters->get('limit'); + $type = $request->get('type') ?? 'default'; $this->parameters->set('type', $type); - $types = $this->mapTransactionTypes($this->parameters->get('type')); - $manager = $this->getManager(); + $types = $this->mapTransactionTypes($this->parameters->get('type')); + $manager = $this->getManager(); /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setUser($admin) // all info needed for the API: @@ -76,24 +76,23 @@ class ShowController extends Controller // set page to retrieve ->setPage($this->parameters->get('page')) // set types of transactions to return. - ->setTypes($types) - ; + ->setTypes($types); if (null !== $this->parameters->get('start') || null !== $this->parameters->get('end')) { $collector->setRange($this->parameters->get('start'), $this->parameters->get('end')); } - $paginator = $collector->getPaginatedGroups(); - $paginator->setPath(route('api.v1.transactions.index').$this->buildParams()); + $paginator = $collector->getPaginatedGroups(); + $paginator->setPath(route('api.v1.transactions.index') . $this->buildParams()); // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); $transactions = $enrichment->enrich($paginator->getCollection()); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($transactions, $transformer, 'transactions'); + $resource = new FractalCollection($transactions, $transformer, 'transactions'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -118,21 +117,20 @@ class ShowController extends Controller */ public function show(TransactionGroup $transactionGroup): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setUser($admin) // filter on transaction group. ->setTransactionGroup($transactionGroup) // all info needed for the API: - ->withAPIInformation() - ; + ->withAPIInformation(); $selectedGroup = $collector->getGroups()->first(); if (null === $selectedGroup) { @@ -140,15 +138,14 @@ class ShowController extends Controller } // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); $selectedGroup = $enrichment->enrichSingle($selectedGroup); - /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($selectedGroup, $transformer, 'transactions'); + $resource = new Item($selectedGroup, $transformer, 'transactions'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Transaction/StoreController.php b/app/Api/V1/Controllers/Models/Transaction/StoreController.php index cb4901341d..c65cc0437a 100644 --- a/app/Api/V1/Controllers/Models/Transaction/StoreController.php +++ b/app/Api/V1/Controllers/Models/Transaction/StoreController.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Controllers\Models\Transaction; -use Illuminate\Http\Request; use FireflyIII\Api\V1\Controllers\Controller; use FireflyIII\Api\V1\Requests\Models\Transaction\StoreRequest; use FireflyIII\Enums\UserRoleEnum; @@ -40,6 +39,7 @@ use FireflyIII\Support\JsonApi\Enrichments\TransactionGroupEnrichment; use FireflyIII\Transformers\TransactionGroupTransformer; use FireflyIII\User; use Illuminate\Http\JsonResponse; +use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Validator; use Illuminate\Validation\ValidationException; @@ -63,19 +63,17 @@ class StoreController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function (Request $request, $next) { - /** @var User $admin */ - $admin = auth()->user(); - $userGroup = $this->validateUserGroup($request); + $this->middleware(function (Request $request, $next) { + /** @var User $admin */ + $admin = auth()->user(); + $userGroup = $this->validateUserGroup($request); - $this->groupRepository = app(TransactionGroupRepositoryInterface::class); - $this->groupRepository->setUser($admin); - $this->groupRepository->setUserGroup($userGroup); + $this->groupRepository = app(TransactionGroupRepositoryInterface::class); + $this->groupRepository->setUser($admin); + $this->groupRepository->setUserGroup($userGroup); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -89,18 +87,18 @@ class StoreController extends Controller public function store(StoreRequest $request): JsonResponse { Log::debug('Now in API StoreController::store()'); - $data = $request->getAll(); - $data['user'] = auth()->user(); + $data = $request->getAll(); + $data['user'] = auth()->user(); $data['user_group'] = $this->userGroup; - Log::channel('audit')->info('Store new transaction over API.', $data); try { $transactionGroup = $this->groupRepository->store($data); } catch (DuplicateTransactionException $e) { Log::warning('Caught a duplicate transaction. Return error message.'); - $validator = Validator::make(['transactions' => [['description' => $e->getMessage()]]], ['transactions.0.description' => new IsDuplicateTransaction()]); + $validator = Validator::make(['transactions' => [['description' => $e->getMessage()]]], ['transactions.0.description' => + new IsDuplicateTransaction()]); throw new ValidationException($validator); } catch (FireflyException $e) { @@ -112,41 +110,40 @@ class StoreController extends Controller throw new ValidationException($validator); } Preferences::mark(); - $applyRules = $data['apply_rules'] ?? true; - $fireWebhooks = $data['fire_webhooks'] ?? true; + $applyRules = $data['apply_rules'] ?? true; + $fireWebhooks = $data['fire_webhooks'] ?? true; event(new StoredTransactionGroup($transactionGroup, $applyRules, $fireWebhooks)); - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setUser($admin) ->setUserGroup($this->userGroup) // filter on transaction group. ->setTransactionGroup($transactionGroup) // all info needed for the API: - ->withAPIInformation() - ; + ->withAPIInformation(); - $selectedGroup = $collector->getGroups()->first(); + $selectedGroup = $collector->getGroups()->first(); if (null === $selectedGroup) { throw HttpException::fromStatusCode(410, '200032: Cannot find transaction. Possibly, a rule deleted this transaction after its creation.'); } // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); - $selectedGroup = $enrichment->enrichSingle($selectedGroup); + $selectedGroup = $enrichment->enrichSingle($selectedGroup); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($selectedGroup, $transformer, 'transactions'); + $resource = new Item($selectedGroup, $transformer, 'transactions'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/Transaction/UpdateController.php b/app/Api/V1/Controllers/Models/Transaction/UpdateController.php index 02fbb9b023..c2108c8299 100644 --- a/app/Api/V1/Controllers/Models/Transaction/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Transaction/UpdateController.php @@ -52,17 +52,15 @@ class UpdateController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $admin */ - $admin = auth()->user(); + $this->middleware(function ($request, $next) { + /** @var User $admin */ + $admin = auth()->user(); - $this->groupRepository = app(TransactionGroupRepositoryInterface::class); - $this->groupRepository->setUser($admin); + $this->groupRepository = app(TransactionGroupRepositoryInterface::class); + $this->groupRepository->setUser($admin); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -74,11 +72,11 @@ class UpdateController extends Controller public function update(UpdateRequest $request, TransactionGroup $transactionGroup): JsonResponse { Log::debug('Now in update routine for transaction group'); - $data = $request->getAll(); - $oldHash = $this->groupRepository->getCompareHash($transactionGroup); - $transactionGroup = $this->groupRepository->update($transactionGroup, $data); - $newHash = $this->groupRepository->getCompareHash($transactionGroup); - $manager = $this->getManager(); + $data = $request->getAll(); + $oldHash = $this->groupRepository->getCompareHash($transactionGroup); + $transactionGroup = $this->groupRepository->update($transactionGroup, $data); + $newHash = $this->groupRepository->getCompareHash($transactionGroup); + $manager = $this->getManager(); Preferences::mark(); $applyRules = $data['apply_rules'] ?? true; @@ -87,33 +85,32 @@ class UpdateController extends Controller event(new UpdatedTransactionGroup($transactionGroup, $applyRules, $fireWebhooks, $runRecalculations)); /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setUser($admin) // filter on transaction group. ->setTransactionGroup($transactionGroup) // all info needed for the API: - ->withAPIInformation() - ; + ->withAPIInformation(); - $selectedGroup = $collector->getGroups()->first(); + $selectedGroup = $collector->getGroups()->first(); if (null === $selectedGroup) { throw new NotFoundHttpException(); } // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); - $selectedGroup = $enrichment->enrichSingle($selectedGroup); + $selectedGroup = $enrichment->enrichSingle($selectedGroup); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($selectedGroup, $transformer, 'transactions'); + $resource = new Item($selectedGroup, $transformer, 'transactions'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/TransactionCurrency/DestroyController.php b/app/Api/V1/Controllers/Models/TransactionCurrency/DestroyController.php index a40d05dd2f..7f03e61466 100644 --- a/app/Api/V1/Controllers/Models/TransactionCurrency/DestroyController.php +++ b/app/Api/V1/Controllers/Models/TransactionCurrency/DestroyController.php @@ -41,7 +41,7 @@ use Illuminate\Validation\ValidationException; class DestroyController extends Controller { private CurrencyRepositoryInterface $repository; - private UserRepositoryInterface $userRepository; + private UserRepositoryInterface $userRepository; /** * CurrencyRepository constructor. @@ -49,15 +49,13 @@ class DestroyController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(CurrencyRepositoryInterface::class); - $this->userRepository = app(UserRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(CurrencyRepositoryInterface::class); + $this->userRepository = app(UserRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** diff --git a/app/Api/V1/Controllers/Models/TransactionCurrency/ListController.php b/app/Api/V1/Controllers/Models/TransactionCurrency/ListController.php index 08bda85dbe..10496c3c86 100644 --- a/app/Api/V1/Controllers/Models/TransactionCurrency/ListController.php +++ b/app/Api/V1/Controllers/Models/TransactionCurrency/ListController.php @@ -73,15 +73,15 @@ class ListController extends Controller */ public function accounts(Request $request, TransactionCurrency $currency): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // read type from URL - $type = $request->get('type') ?? 'all'; + $type = $request->get('type') ?? 'all'; $this->parameters->set('type', $type); // types to get, page size: - $types = $this->mapAccountTypes($this->parameters->get('type')); - $pageSize = $this->parameters->get('limit'); + $types = $this->mapAccountTypes($this->parameters->get('type')); + $pageSize = $this->parameters->get('limit'); // get list of accounts. Count it and split it. /** @var AccountRepositoryInterface $accountRepository */ @@ -89,16 +89,14 @@ class ListController extends Controller $unfiltered = $accountRepository->getAccountsByType($types); // filter list on currency preference: - $collection = $unfiltered->filter( - static function (Account $account) use ($currency, $accountRepository): bool { - $currencyId = (int) $accountRepository->getMetaValue($account, 'currency_id'); + $collection = $unfiltered->filter(static function (Account $account) use ($currency, $accountRepository): bool { + $currencyId = (int) $accountRepository->getMetaValue($account, 'currency_id'); - return $currencyId === $currency->id; - } - ); + return $currencyId === $currency->id; + }); - $count = $collection->count(); - $accounts = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $count = $collection->count(); + $accounts = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // #11007 go to the end of the previous day. $this->parameters->set('start', $this->parameters->get('start')?->subSecond()); @@ -107,22 +105,22 @@ class ListController extends Controller // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new AccountEnrichment(); + $admin = auth()->user(); + $enrichment = new AccountEnrichment(); $enrichment->setDate($this->parameters->get('date')); $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); $enrichment->setUser($admin); - $accounts = $enrichment->enrich($accounts); + $accounts = $enrichment->enrich($accounts); // make paginator: - $paginator = new LengthAwarePaginator($accounts, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.currencies.accounts', [$currency->code]).$this->buildParams()); + $paginator = new LengthAwarePaginator($accounts, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.currencies.accounts', [$currency->code]) . $this->buildParams()); /** @var AccountTransformer $transformer */ - $transformer = app(AccountTransformer::class); + $transformer = app(AccountTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($accounts, $transformer, 'accounts'); + $resource = new FractalCollection($accounts, $transformer, 'accounts'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -136,26 +134,26 @@ class ListController extends Controller */ public function availableBudgets(TransactionCurrency $currency): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // types to get, page size: - $pageSize = $this->parameters->get('limit'); + $pageSize = $this->parameters->get('limit'); // get list of available budgets. Count it and split it. /** @var AvailableBudgetRepositoryInterface $abRepository */ - $abRepository = app(AvailableBudgetRepositoryInterface::class); + $abRepository = app(AvailableBudgetRepositoryInterface::class); $collection = $abRepository->getAvailableBudgetsByCurrency($currency); $count = $collection->count(); $availableBudgets = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($availableBudgets, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.currencies.available-budgets', [$currency->code]).$this->buildParams()); + $paginator = new LengthAwarePaginator($availableBudgets, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.currencies.available-budgets', [$currency->code]) . $this->buildParams()); /** @var AvailableBudgetTransformer $transformer */ - $transformer = app(AvailableBudgetTransformer::class); + $transformer = app(AvailableBudgetTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($availableBudgets, $transformer, 'available_budgets'); + $resource = new FractalCollection($availableBudgets, $transformer, 'available_budgets'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -169,38 +167,36 @@ class ListController extends Controller */ public function bills(TransactionCurrency $currency): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var BillRepositoryInterface $billRepos */ - $billRepos = app(BillRepositoryInterface::class); - $pageSize = $this->parameters->get('limit'); - $unfiltered = $billRepos->getBills(); + $billRepos = app(BillRepositoryInterface::class); + $pageSize = $this->parameters->get('limit'); + $unfiltered = $billRepos->getBills(); // filter and paginate list: - $collection = $unfiltered->filter( - static fn (Bill $bill): bool => $bill->transaction_currency_id === $currency->id - ); - $count = $collection->count(); - $bills = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $collection = $unfiltered->filter(static fn(Bill $bill): bool => $bill->transaction_currency_id === $currency->id); + $count = $collection->count(); + $bills = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new SubscriptionEnrichment(); + $admin = auth()->user(); + $enrichment = new SubscriptionEnrichment(); $enrichment->setUser($admin); $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); - $bills = $enrichment->enrich($bills); + $bills = $enrichment->enrich($bills); // make paginator: - $paginator = new LengthAwarePaginator($bills, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.currencies.bills', [$currency->code]).$this->buildParams()); + $paginator = new LengthAwarePaginator($bills, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.currencies.bills', [$currency->code]) . $this->buildParams()); /** @var BillTransformer $transformer */ $transformer = app(BillTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($bills, $transformer, 'bills'); + $resource = new FractalCollection($bills, $transformer, 'bills'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -223,20 +219,20 @@ class ListController extends Controller $count = $collection->count(); $budgetLimits = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); $paginator = new LengthAwarePaginator($budgetLimits, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.currencies.budget-limits', [$currency->code]).$this->buildParams()); + $paginator->setPath(route('api.v1.currencies.budget-limits', [$currency->code]) . $this->buildParams()); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new BudgetLimitEnrichment(); + $admin = auth()->user(); + $enrichment = new BudgetLimitEnrichment(); $enrichment->setUser($admin); $budgetLimits = $enrichment->enrich($budgetLimits); /** @var BudgetLimitTransformer $transformer */ - $transformer = app(BudgetLimitTransformer::class); + $transformer = app(BudgetLimitTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($budgetLimits, $transformer, 'budget_limits'); + $resource = new FractalCollection($budgetLimits, $transformer, 'budget_limits'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -250,9 +246,9 @@ class ListController extends Controller */ public function recurrences(TransactionCurrency $currency): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); // types to get, page size: - $pageSize = $this->parameters->get('limit'); + $pageSize = $this->parameters->get('limit'); // get list of budgets. Count it and split it. /** @var RecurringRepositoryInterface $recurringRepos */ @@ -260,34 +256,35 @@ class ListController extends Controller $unfiltered = $recurringRepos->get(); // filter selection - $collection = $unfiltered->filter( - static function (Recurrence $recurrence) use ($currency): ?Recurrence { // @phpstan-ignore-line - if (array_any($recurrence->recurrenceTransactions, static fn ($transaction): bool => $transaction->transaction_currency_id === $currency->id || $transaction->foreign_currency_id === $currency->id)) { - return $recurrence; - } - - return null; + $collection = $unfiltered->filter(static function (Recurrence $recurrence) use ($currency): null|Recurrence { // @phpstan-ignore-line + if (array_any( + $recurrence->recurrenceTransactions, + static fn($transaction): bool => $transaction->transaction_currency_id === $currency->id || $transaction->foreign_currency_id === $currency->id + )) { + return $recurrence; } - ); - $count = $collection->count(); - $recurrences = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + + return null; + }); + $count = $collection->count(); + $recurrences = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new RecurringEnrichment(); + $admin = auth()->user(); + $enrichment = new RecurringEnrichment(); $enrichment->setUser($admin); - $recurrences = $enrichment->enrich($recurrences); + $recurrences = $enrichment->enrich($recurrences); // make paginator: - $paginator = new LengthAwarePaginator($recurrences, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.currencies.recurrences', [$currency->code]).$this->buildParams()); + $paginator = new LengthAwarePaginator($recurrences, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.currencies.recurrences', [$currency->code]) . $this->buildParams()); /** @var RecurrenceTransformer $transformer */ - $transformer = app(RecurrenceTransformer::class); + $transformer = app(RecurrenceTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($recurrences, $transformer, 'recurrences'); + $resource = new FractalCollection($recurrences, $transformer, 'recurrences'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -301,36 +298,37 @@ class ListController extends Controller */ public function rules(TransactionCurrency $currency): JsonResponse { - $manager = $this->getManager(); - $pageSize = $this->parameters->get('limit'); + $manager = $this->getManager(); + $pageSize = $this->parameters->get('limit'); // get list of budgets. Count it and split it. /** @var RuleRepositoryInterface $ruleRepos */ - $ruleRepos = app(RuleRepositoryInterface::class); - $unfiltered = $ruleRepos->getAll(); + $ruleRepos = app(RuleRepositoryInterface::class); + $unfiltered = $ruleRepos->getAll(); - $collection = $unfiltered->filter( - static function (Rule $rule) use ($currency): ?Rule { // @phpstan-ignore-line - if (array_any($rule->ruleTriggers, static fn ($trigger): bool => 'currency_is' === $trigger->trigger_type && $currency->name === $trigger->trigger_value)) { - return $rule; - } - - return null; + $collection = $unfiltered->filter(static function (Rule $rule) use ($currency): null|Rule { // @phpstan-ignore-line + if (array_any( + $rule->ruleTriggers, + static fn($trigger): bool => 'currency_is' === $trigger->trigger_type && $currency->name === $trigger->trigger_value + )) { + return $rule; } - ); - $count = $collection->count(); - $rules = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + return null; + }); + + $count = $collection->count(); + $rules = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($rules, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.rules.index').$this->buildParams()); + $paginator = new LengthAwarePaginator($rules, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.rules.index') . $this->buildParams()); /** @var RuleTransformer $transformer */ $transformer = app(RuleTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($rules, $transformer, 'rules'); + $resource = new FractalCollection($rules, $transformer, 'rules'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -344,19 +342,19 @@ class ListController extends Controller */ public function transactions(Request $request, TransactionCurrency $currency): JsonResponse { - $pageSize = $this->parameters->get('limit'); - $type = $request->get('type') ?? 'default'; + $pageSize = $this->parameters->get('limit'); + $type = $request->get('type') ?? 'default'; $this->parameters->set('type', $type); - $types = $this->mapTransactionTypes($this->parameters->get('type')); - $manager = $this->getManager(); + $types = $this->mapTransactionTypes($this->parameters->get('type')); + $manager = $this->getManager(); /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setUser($admin) // filter on currency. @@ -368,27 +366,26 @@ class ListController extends Controller // set page to retrieve ->setPage($this->parameters->get('page')) // set types of transactions to return. - ->setTypes($types) - ; + ->setTypes($types); if (null !== $this->parameters->get('start')) { $collector->setStart($this->parameters->get('start')); } if (null !== $this->parameters->get('end')) { $collector->setEnd($this->parameters->get('end')); } - $paginator = $collector->getPaginatedGroups(); - $paginator->setPath(route('api.v1.currencies.transactions', [$currency->code]).$this->buildParams()); + $paginator = $collector->getPaginatedGroups(); + $paginator->setPath(route('api.v1.currencies.transactions', [$currency->code]) . $this->buildParams()); // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); $transactions = $enrichment->enrich($paginator->getCollection()); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($transactions, $transformer, 'transactions'); + $resource = new FractalCollection($transactions, $transformer, 'transactions'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Models/TransactionCurrency/ShowController.php b/app/Api/V1/Controllers/Models/TransactionCurrency/ShowController.php index d0920b00f5..34f0b39681 100644 --- a/app/Api/V1/Controllers/Models/TransactionCurrency/ShowController.php +++ b/app/Api/V1/Controllers/Models/TransactionCurrency/ShowController.php @@ -53,14 +53,12 @@ class ShowController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(CurrencyRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(CurrencyRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -71,21 +69,21 @@ class ShowController extends Controller */ public function index(): JsonResponse { - $pageSize = $this->parameters->get('limit'); - $collection = $this->repository->getAll(); - $count = $collection->count(); + $pageSize = $this->parameters->get('limit'); + $collection = $this->repository->getAll(); + $count = $collection->count(); // slice them: - $currencies = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); - $paginator = new LengthAwarePaginator($currencies, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.currencies.index').$this->buildParams()); - $manager = $this->getManager(); + $currencies = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $paginator = new LengthAwarePaginator($currencies, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.currencies.index') . $this->buildParams()); + $manager = $this->getManager(); /** @var CurrencyTransformer $transformer */ $transformer = app(CurrencyTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($currencies, $transformer, 'currencies'); + $resource = new FractalCollection($currencies, $transformer, 'currencies'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -100,8 +98,8 @@ class ShowController extends Controller public function show(TransactionCurrency $currency): JsonResponse { /** @var User $user */ - $user = auth()->user(); - $manager = $this->getManager(); + $user = auth()->user(); + $manager = $this->getManager(); $this->parameters->set('primaryCurrency', $this->primaryCurrency); // update fields with user info. @@ -111,7 +109,7 @@ class ShowController extends Controller $transformer = app(CurrencyTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($currency, $transformer, 'currencies'); + $resource = new Item($currency, $transformer, 'currencies'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } @@ -122,9 +120,9 @@ class ShowController extends Controller public function showPrimary(): JsonResponse { /** @var User $user */ - $user = auth()->user(); - $manager = $this->getManager(); - $currency = $this->primaryCurrency; + $user = auth()->user(); + $manager = $this->getManager(); + $currency = $this->primaryCurrency; // update fields with user info. $currency->refreshForUser($user); @@ -133,7 +131,7 @@ class ShowController extends Controller $transformer = app(CurrencyTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($currency, $transformer, 'currencies'); + $resource = new Item($currency, $transformer, 'currencies'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/TransactionCurrency/StoreController.php b/app/Api/V1/Controllers/Models/TransactionCurrency/StoreController.php index b225556b54..ea8158ff73 100644 --- a/app/Api/V1/Controllers/Models/TransactionCurrency/StoreController.php +++ b/app/Api/V1/Controllers/Models/TransactionCurrency/StoreController.php @@ -51,14 +51,12 @@ class StoreController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(CurrencyRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(CurrencyRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -69,22 +67,22 @@ class StoreController extends Controller */ public function store(StoreRequest $request): JsonResponse { - $currency = $this->repository->store($request->getAll()); + $currency = $this->repository->store($request->getAll()); if (true === $request->boolean('default')) { $this->repository->makePrimary($currency); Preferences::mark(); } - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $currency->refreshForUser($user); /** @var CurrencyTransformer $transformer */ $transformer = app(CurrencyTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($currency, $transformer, 'currencies'); + $resource = new Item($currency, $transformer, 'currencies'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/TransactionCurrency/UpdateController.php b/app/Api/V1/Controllers/Models/TransactionCurrency/UpdateController.php index ca8b3f14da..0af39c7403 100644 --- a/app/Api/V1/Controllers/Models/TransactionCurrency/UpdateController.php +++ b/app/Api/V1/Controllers/Models/TransactionCurrency/UpdateController.php @@ -54,14 +54,12 @@ class UpdateController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(CurrencyRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(CurrencyRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -84,9 +82,9 @@ class UpdateController extends Controller } /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->repository->disable($currency); - $manager = $this->getManager(); + $manager = $this->getManager(); $currency->refreshForUser($user); @@ -94,7 +92,7 @@ class UpdateController extends Controller $transformer = app(CurrencyTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($currency, $transformer, 'currencies'); + $resource = new Item($currency, $transformer, 'currencies'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } @@ -102,20 +100,20 @@ class UpdateController extends Controller public function makePrimary(TransactionCurrency $currency): JsonResponse { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->repository->enable($currency); $this->repository->makePrimary($currency); Preferences::mark(); - $manager = $this->getManager(); + $manager = $this->getManager(); $currency->refreshForUser($user); /** @var CurrencyTransformer $transformer */ $transformer = app(CurrencyTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($currency, $transformer, 'currencies'); + $resource = new Item($currency, $transformer, 'currencies'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } @@ -129,10 +127,10 @@ class UpdateController extends Controller public function enable(TransactionCurrency $currency): JsonResponse { $this->repository->enable($currency); - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $currency->refreshForUser($user); @@ -140,7 +138,7 @@ class UpdateController extends Controller $transformer = app(CurrencyTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($currency, $transformer, 'currencies'); + $resource = new Item($currency, $transformer, 'currencies'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } @@ -155,14 +153,14 @@ class UpdateController extends Controller */ public function update(UpdateRequest $request, TransactionCurrency $currency): JsonResponse { - $data = $request->getAll(); + $data = $request->getAll(); Log::debug(__METHOD__, $data); /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); // safety catch on currency disablement. - $set = $this->repository->get(); + $set = $this->repository->get(); if (array_key_exists('enabled', $data) && false === $data['enabled'] && 1 === count($set) && $set->first()->id === $currency->id) { return response()->json([], 409); } @@ -171,17 +169,17 @@ class UpdateController extends Controller return response()->json([], 409); } - $currency = $this->repository->update($currency, $data); + $currency = $this->repository->update($currency, $data); Preferences::mark(); - $manager = $this->getManager(); + $manager = $this->getManager(); $currency->refreshForUser($user); /** @var CurrencyTransformer $transformer */ $transformer = app(CurrencyTransformer::class); - $resource = new Item($currency, $transformer, 'currencies'); + $resource = new Item($currency, $transformer, 'currencies'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/TransactionLink/DestroyController.php b/app/Api/V1/Controllers/Models/TransactionLink/DestroyController.php index 25c2b85008..88bda8f29f 100644 --- a/app/Api/V1/Controllers/Models/TransactionLink/DestroyController.php +++ b/app/Api/V1/Controllers/Models/TransactionLink/DestroyController.php @@ -44,18 +44,16 @@ class DestroyController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); - $this->repository = app(LinkTypeRepositoryInterface::class); + $this->repository = app(LinkTypeRepositoryInterface::class); - $this->repository->setUser($user); + $this->repository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** diff --git a/app/Api/V1/Controllers/Models/TransactionLink/ShowController.php b/app/Api/V1/Controllers/Models/TransactionLink/ShowController.php index fb2e80204d..414b283109 100644 --- a/app/Api/V1/Controllers/Models/TransactionLink/ShowController.php +++ b/app/Api/V1/Controllers/Models/TransactionLink/ShowController.php @@ -49,18 +49,16 @@ class ShowController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); - $this->repository = app(LinkTypeRepositoryInterface::class); + $this->repository = app(LinkTypeRepositoryInterface::class); - $this->repository->setUser($user); + $this->repository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -72,13 +70,13 @@ class ShowController extends Controller public function index(Request $request): JsonResponse { // create some objects: - $manager = $this->getManager(); + $manager = $this->getManager(); // read type from URL - $name = $request->get('name'); + $name = $request->get('name'); // types to get, page size: - $pageSize = $this->parameters->get('limit'); - $linkType = $this->repository->findByName($name); + $pageSize = $this->parameters->get('limit'); + $linkType = $this->repository->findByName($name); // get list of transaction links. Count it and split it. $collection = $this->repository->getJournalLinks($linkType); @@ -86,14 +84,14 @@ class ShowController extends Controller $journalLinks = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($journalLinks, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.transaction-links.index').$this->buildParams()); + $paginator = new LengthAwarePaginator($journalLinks, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.transaction-links.index') . $this->buildParams()); /** @var TransactionLinkTransformer $transformer */ - $transformer = app(TransactionLinkTransformer::class); + $transformer = app(TransactionLinkTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($journalLinks, $transformer, 'transaction_links'); + $resource = new FractalCollection($journalLinks, $transformer, 'transaction_links'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -107,13 +105,13 @@ class ShowController extends Controller */ public function show(TransactionJournalLink $journalLink): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var TransactionLinkTransformer $transformer */ $transformer = app(TransactionLinkTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($journalLink, $transformer, 'transaction_links'); + $resource = new Item($journalLink, $transformer, 'transaction_links'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/TransactionLink/StoreController.php b/app/Api/V1/Controllers/Models/TransactionLink/StoreController.php index 2d0b04cba8..48ce4827f2 100644 --- a/app/Api/V1/Controllers/Models/TransactionLink/StoreController.php +++ b/app/Api/V1/Controllers/Models/TransactionLink/StoreController.php @@ -43,7 +43,7 @@ class StoreController extends Controller { use TransactionFilter; - private JournalRepositoryInterface $journalRepository; + private JournalRepositoryInterface $journalRepository; private LinkTypeRepositoryInterface $repository; /** @@ -52,20 +52,18 @@ class StoreController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); - $this->repository = app(LinkTypeRepositoryInterface::class); - $this->journalRepository = app(JournalRepositoryInterface::class); + $this->repository = app(LinkTypeRepositoryInterface::class); + $this->journalRepository = app(JournalRepositoryInterface::class); - $this->repository->setUser($user); - $this->journalRepository->setUser($user); + $this->repository->setUser($user); + $this->journalRepository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -78,22 +76,22 @@ class StoreController extends Controller */ public function store(StoreRequest $request): JsonResponse { - $manager = $this->getManager(); - $data = $request->getAll(); - $inward = $this->journalRepository->find($data['inward_id'] ?? 0); - $outward = $this->journalRepository->find($data['outward_id'] ?? 0); + $manager = $this->getManager(); + $data = $request->getAll(); + $inward = $this->journalRepository->find($data['inward_id'] ?? 0); + $outward = $this->journalRepository->find($data['outward_id'] ?? 0); if (!$inward instanceof TransactionJournal || !$outward instanceof TransactionJournal) { throw new FireflyException('200024: Source or destination does not exist.'); } $data['direction'] = 'inward'; - $journalLink = $this->repository->storeLink($data, $inward, $outward); + $journalLink = $this->repository->storeLink($data, $inward, $outward); /** @var TransactionLinkTransformer $transformer */ - $transformer = app(TransactionLinkTransformer::class); + $transformer = app(TransactionLinkTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($journalLink, $transformer, 'transaction_links'); + $resource = new Item($journalLink, $transformer, 'transaction_links'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/TransactionLink/UpdateController.php b/app/Api/V1/Controllers/Models/TransactionLink/UpdateController.php index 289774ad39..bc9830ec3b 100644 --- a/app/Api/V1/Controllers/Models/TransactionLink/UpdateController.php +++ b/app/Api/V1/Controllers/Models/TransactionLink/UpdateController.php @@ -39,7 +39,7 @@ use League\Fractal\Resource\Item; */ class UpdateController extends Controller { - private JournalRepositoryInterface $journalRepository; + private JournalRepositoryInterface $journalRepository; private LinkTypeRepositoryInterface $repository; /** @@ -48,20 +48,18 @@ class UpdateController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); - $this->repository = app(LinkTypeRepositoryInterface::class); - $this->journalRepository = app(JournalRepositoryInterface::class); + $this->repository = app(LinkTypeRepositoryInterface::class); + $this->journalRepository = app(JournalRepositoryInterface::class); - $this->repository->setUser($user); - $this->journalRepository->setUser($user); + $this->repository->setUser($user); + $this->journalRepository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -80,7 +78,7 @@ class UpdateController extends Controller $transformer = app(TransactionLinkTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($journalLink, $transformer, 'transaction_links'); + $resource = new Item($journalLink, $transformer, 'transaction_links'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/TransactionLinkType/DestroyController.php b/app/Api/V1/Controllers/Models/TransactionLinkType/DestroyController.php index df18a2ba62..e7804b5d82 100644 --- a/app/Api/V1/Controllers/Models/TransactionLinkType/DestroyController.php +++ b/app/Api/V1/Controllers/Models/TransactionLinkType/DestroyController.php @@ -48,16 +48,14 @@ class DestroyController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); - $this->repository = app(LinkTypeRepositoryInterface::class); - $this->repository->setUser($user); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); + $this->repository = app(LinkTypeRepositoryInterface::class); + $this->repository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** diff --git a/app/Api/V1/Controllers/Models/TransactionLinkType/ListController.php b/app/Api/V1/Controllers/Models/TransactionLinkType/ListController.php index 03537cfe62..890348dfc9 100644 --- a/app/Api/V1/Controllers/Models/TransactionLinkType/ListController.php +++ b/app/Api/V1/Controllers/Models/TransactionLinkType/ListController.php @@ -52,16 +52,14 @@ class ListController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); - $this->repository = app(LinkTypeRepositoryInterface::class); - $this->repository->setUser($user); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); + $this->repository = app(LinkTypeRepositoryInterface::class); + $this->repository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -70,22 +68,22 @@ class ListController extends Controller */ public function transactions(Request $request, LinkType $linkType): JsonResponse { - $pageSize = $this->parameters->get('limit'); - $type = $request->get('type') ?? 'default'; + $pageSize = $this->parameters->get('limit'); + $type = $request->get('type') ?? 'default'; $this->parameters->set('type', $type); - $types = $this->mapTransactionTypes($this->parameters->get('type')); - $manager = $this->getManager(); + $types = $this->mapTransactionTypes($this->parameters->get('type')); + $manager = $this->getManager(); // whatever is returned by the query, it must be part of these journals: - $journalIds = $this->repository->getJournalIds($linkType); + $journalIds = $this->repository->getJournalIds($linkType); /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setUser($admin) // filter on journal IDs. @@ -97,27 +95,26 @@ class ListController extends Controller // set page to retrieve ->setPage($this->parameters->get('page')) // set types of transactions to return. - ->setTypes($types) - ; + ->setTypes($types); if (null !== $this->parameters->get('start')) { $collector->setStart($this->parameters->get('start')); } if (null !== $this->parameters->get('end')) { $collector->setEnd($this->parameters->get('end')); } - $paginator = $collector->getPaginatedGroups(); - $paginator->setPath(route('api.v1.transactions.index').$this->buildParams()); + $paginator = $collector->getPaginatedGroups(); + $paginator->setPath(route('api.v1.transactions.index') . $this->buildParams()); // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); $transactions = $enrichment->enrich($paginator->getCollection()); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($transactions, $transformer, 'transactions'); + $resource = new FractalCollection($transactions, $transformer, 'transactions'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Models/TransactionLinkType/ShowController.php b/app/Api/V1/Controllers/Models/TransactionLinkType/ShowController.php index 27c7a4eb15..3fb86002ae 100644 --- a/app/Api/V1/Controllers/Models/TransactionLinkType/ShowController.php +++ b/app/Api/V1/Controllers/Models/TransactionLinkType/ShowController.php @@ -51,16 +51,14 @@ class ShowController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); - $this->repository = app(LinkTypeRepositoryInterface::class); - $this->repository->setUser($user); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); + $this->repository = app(LinkTypeRepositoryInterface::class); + $this->repository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -70,23 +68,23 @@ class ShowController extends Controller public function index(): JsonResponse { // create some objects: - $manager = $this->getManager(); - $pageSize = $this->parameters->get('limit'); + $manager = $this->getManager(); + $pageSize = $this->parameters->get('limit'); // get list of accounts. Count it and split it. - $collection = $this->repository->get(); - $count = $collection->count(); - $linkTypes = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $collection = $this->repository->get(); + $count = $collection->count(); + $linkTypes = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($linkTypes, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.link-types.index').$this->buildParams()); + $paginator = new LengthAwarePaginator($linkTypes, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.link-types.index') . $this->buildParams()); /** @var LinkTypeTransformer $transformer */ $transformer = app(LinkTypeTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($linkTypes, $transformer, 'link_types'); + $resource = new FractalCollection($linkTypes, $transformer, 'link_types'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -100,13 +98,13 @@ class ShowController extends Controller */ public function show(LinkType $linkType): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var LinkTypeTransformer $transformer */ $transformer = app(LinkTypeTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($linkType, $transformer, 'link_types'); + $resource = new Item($linkType, $transformer, 'link_types'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/TransactionLinkType/StoreController.php b/app/Api/V1/Controllers/Models/TransactionLinkType/StoreController.php index 7901c88ec0..d62100b007 100644 --- a/app/Api/V1/Controllers/Models/TransactionLinkType/StoreController.php +++ b/app/Api/V1/Controllers/Models/TransactionLinkType/StoreController.php @@ -44,7 +44,7 @@ class StoreController extends Controller use TransactionFilter; private LinkTypeRepositoryInterface $repository; - private UserRepositoryInterface $userRepository; + private UserRepositoryInterface $userRepository; /** * LinkTypeController constructor. @@ -52,17 +52,15 @@ class StoreController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); - $this->repository = app(LinkTypeRepositoryInterface::class); - $this->userRepository = app(UserRepositoryInterface::class); - $this->repository->setUser($user); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); + $this->repository = app(LinkTypeRepositoryInterface::class); + $this->userRepository = app(UserRepositoryInterface::class); + $this->repository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -76,23 +74,23 @@ class StoreController extends Controller public function store(StoreRequest $request): JsonResponse { /** @var User $admin */ - $admin = auth()->user(); - $rules = ['name' => 'required']; + $admin = auth()->user(); + $rules = ['name' => 'required']; if (!$this->userRepository->hasRole($admin, 'owner')) { // access denied: $messages = ['name' => '200005: You need the "owner" role to do this.']; Validator::make([], $rules, $messages)->validate(); } - $data = $request->getAll(); + $data = $request->getAll(); // if currency ID is 0, find the currency by the code: - $linkType = $this->repository->store($data); - $manager = $this->getManager(); + $linkType = $this->repository->store($data); + $manager = $this->getManager(); /** @var LinkTypeTransformer $transformer */ $transformer = app(LinkTypeTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($linkType, $transformer, 'link_types'); + $resource = new Item($linkType, $transformer, 'link_types'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/TransactionLinkType/UpdateController.php b/app/Api/V1/Controllers/Models/TransactionLinkType/UpdateController.php index cf964f259d..25c8fa4edc 100644 --- a/app/Api/V1/Controllers/Models/TransactionLinkType/UpdateController.php +++ b/app/Api/V1/Controllers/Models/TransactionLinkType/UpdateController.php @@ -46,7 +46,7 @@ class UpdateController extends Controller use TransactionFilter; private LinkTypeRepositoryInterface $repository; - private UserRepositoryInterface $userRepository; + private UserRepositoryInterface $userRepository; /** * LinkTypeController constructor. @@ -54,17 +54,15 @@ class UpdateController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); - $this->repository = app(LinkTypeRepositoryInterface::class); - $this->userRepository = app(UserRepositoryInterface::class); - $this->repository->setUser($user); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); + $this->repository = app(LinkTypeRepositoryInterface::class); + $this->userRepository = app(UserRepositoryInterface::class); + $this->repository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -83,23 +81,23 @@ class UpdateController extends Controller } /** @var User $admin */ - $admin = auth()->user(); - $rules = ['name' => 'required']; + $admin = auth()->user(); + $rules = ['name' => 'required']; if (!$this->userRepository->hasRole($admin, 'owner')) { $messages = ['name' => '200005: You need the "owner" role to do this.']; Validator::make([], $rules, $messages)->validate(); } - $data = $request->getAll(); + $data = $request->getAll(); $this->repository->update($linkType, $data); - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var LinkTypeTransformer $transformer */ $transformer = app(LinkTypeTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($linkType, $transformer, 'link_types'); + $resource = new Item($linkType, $transformer, 'link_types'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Models/UserGroup/IndexController.php b/app/Api/V1/Controllers/Models/UserGroup/IndexController.php index 5cdbb9023f..b0eb562b15 100644 --- a/app/Api/V1/Controllers/Models/UserGroup/IndexController.php +++ b/app/Api/V1/Controllers/Models/UserGroup/IndexController.php @@ -43,31 +43,22 @@ class IndexController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(UserGroupRepositoryInterface::class); + $this->middleware(function ($request, $next) { + $this->repository = app(UserGroupRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } public function index(PaginationRequest $request): JsonResponse { $administrations = $this->repository->get(); - [ - 'page' => $page, - 'limit' => $limit, - 'offset' => $offset, - ] = $request->attributes->all(); + ['page' => $page, 'limit' => $limit, 'offset' => $offset] = $request->attributes->all(); $count = $administrations->count(); $administrations = $administrations->slice($offset, $limit); $paginator = new LengthAwarePaginator($administrations, $count, $limit, $page); $transformer = new UserGroupTransformer(); - return response() - ->json($this->jsonApiList(self::RESOURCE_KEY, $paginator, $transformer)) - ->header('Content-Type', self::CONTENT_TYPE) - ; + return response()->json($this->jsonApiList(self::RESOURCE_KEY, $paginator, $transformer))->header('Content-Type', self::CONTENT_TYPE); } } diff --git a/app/Api/V1/Controllers/Models/UserGroup/ShowController.php b/app/Api/V1/Controllers/Models/UserGroup/ShowController.php index f8ae23d4d9..7945f2ecc1 100644 --- a/app/Api/V1/Controllers/Models/UserGroup/ShowController.php +++ b/app/Api/V1/Controllers/Models/UserGroup/ShowController.php @@ -36,19 +36,18 @@ use Illuminate\Http\JsonResponse; class ShowController extends Controller { public const string RESOURCE_KEY = 'user_groups'; + private WebhookRepositoryInterface $repository; public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(WebhookRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(WebhookRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } public function show(UserGroup $userGroup): JsonResponse @@ -56,9 +55,6 @@ class ShowController extends Controller $transformer = new UserGroupTransformer(); $transformer->setParameters($this->parameters); - return response() - ->api($this->jsonApiObject(self::RESOURCE_KEY, $userGroup, $transformer)) - ->header('Content-Type', self::CONTENT_TYPE) - ; + return response()->api($this->jsonApiObject(self::RESOURCE_KEY, $userGroup, $transformer))->header('Content-Type', self::CONTENT_TYPE); } } diff --git a/app/Api/V1/Controllers/Models/UserGroup/UpdateController.php b/app/Api/V1/Controllers/Models/UserGroup/UpdateController.php index f118a5a960..f18ac1be8e 100644 --- a/app/Api/V1/Controllers/Models/UserGroup/UpdateController.php +++ b/app/Api/V1/Controllers/Models/UserGroup/UpdateController.php @@ -45,29 +45,24 @@ class UpdateController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(UserGroupRepositoryInterface::class); + $this->middleware(function ($request, $next) { + $this->repository = app(UserGroupRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } public function update(UpdateRequest $request, UserGroup $userGroup): JsonResponse { Log::debug(sprintf('Now in %s', __METHOD__)); - $data = $request->getData(); - $userGroup = $this->repository->update($userGroup, $data); + $data = $request->getData(); + $userGroup = $this->repository->update($userGroup, $data); $userGroup->refresh(); Preferences::mark(); $transformer = new UserGroupTransformer(); $transformer->setParameters($this->parameters); - return response() - ->api($this->jsonApiObject(self::RESOURCE_KEY, $userGroup, $transformer)) - ->header('Content-Type', self::CONTENT_TYPE) - ; + return response()->api($this->jsonApiObject(self::RESOURCE_KEY, $userGroup, $transformer))->header('Content-Type', self::CONTENT_TYPE); } } diff --git a/app/Api/V1/Controllers/Search/AccountController.php b/app/Api/V1/Controllers/Search/AccountController.php index caaa0c879b..d9e43c380c 100644 --- a/app/Api/V1/Controllers/Search/AccountController.php +++ b/app/Api/V1/Controllers/Search/AccountController.php @@ -50,7 +50,7 @@ class AccountController extends Controller AccountSearch::SEARCH_ID, AccountSearch::SEARCH_NAME, AccountSearch::SEARCH_IBAN, - AccountSearch::SEARCH_NUMBER, + AccountSearch::SEARCH_NUMBER ]; public function __construct() @@ -64,41 +64,41 @@ class AccountController extends Controller */ public function search(Request $request): JsonResponse|Response { - $manager = $this->getManager(); - $query = trim((string) $request->get('query')); - $field = trim((string) $request->get('field')); - $type = $request->get('type') ?? 'all'; + $manager = $this->getManager(); + $query = trim((string) $request->get('query')); + $field = trim((string) $request->get('field')); + $type = $request->get('type') ?? 'all'; if ('' === $query || !in_array($field, $this->validFields, true)) { return response(null, 422); } Log::debug(sprintf('Now in account search("%s", "%s")', $field, $query)); - $types = $this->mapAccountTypes($type); + $types = $this->mapAccountTypes($type); /** @var AccountSearch $search */ - $search = app(AccountSearch::class); + $search = app(AccountSearch::class); $search->setUser(auth()->user()); $search->setTypes($types); $search->setField($field); $search->setQuery($query); - $accounts = $search->search(); + $accounts = $search->search(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new AccountEnrichment(); + $admin = auth()->user(); + $enrichment = new AccountEnrichment(); $enrichment->setDate($this->parameters->get('date')); $enrichment->setUser($admin); - $accounts = $enrichment->enrich($accounts); + $accounts = $enrichment->enrich($accounts); /** @var AccountTransformer $transformer */ $transformer = app(AccountTransformer::class); $transformer->setParameters($this->parameters); - $count = $accounts->count(); - $perPage = 0 === $count ? 1 : $count; - $paginator = new LengthAwarePaginator($accounts, $count, $perPage, 1); + $count = $accounts->count(); + $perPage = 0 === $count ? 1 : $count; + $paginator = new LengthAwarePaginator($accounts, $count, $perPage, 1); - $resource = new FractalCollection($accounts, $transformer, 'accounts'); + $resource = new FractalCollection($accounts, $transformer, 'accounts'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); diff --git a/app/Api/V1/Controllers/Search/TransactionController.php b/app/Api/V1/Controllers/Search/TransactionController.php index cc5768fce1..386d6cac2f 100644 --- a/app/Api/V1/Controllers/Search/TransactionController.php +++ b/app/Api/V1/Controllers/Search/TransactionController.php @@ -44,31 +44,31 @@ class TransactionController extends Controller */ public function search(TransactionSearchRequest $request, SearchInterface $searcher): JsonResponse { - $manager = $this->getManager(); - $fullQuery = (string) $request->attributes->get('query'); - $page = $request->attributes->get('page'); - $pageSize = $request->attributes->get('limit'); + $manager = $this->getManager(); + $fullQuery = (string) $request->attributes->get('query'); + $page = $request->attributes->get('page'); + $pageSize = $request->attributes->get('limit'); $searcher->parseQuery($fullQuery); $searcher->setPage($page); $searcher->setLimit($pageSize); - $groups = $searcher->searchTransactions(); - $parameters = ['search' => $fullQuery]; - $url = route('api.v1.search.transactions').'?'.http_build_query($parameters); + $groups = $searcher->searchTransactions(); + $parameters = ['search' => $fullQuery]; + $url = route('api.v1.search.transactions') . '?' . http_build_query($parameters); $groups->setPath($url); // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser(auth()->user()); $transactions = $enrichment->enrich($groups->getCollection()); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Collection($transactions, $transformer, 'transactions'); + $resource = new Collection($transactions, $transformer, 'transactions'); $resource->setPaginator(new IlluminatePaginatorAdapter($groups)); - $array = $manager->createData($resource)->toArray(); + $array = $manager->createData($resource)->toArray(); return response()->json($array)->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Summary/BasicController.php b/app/Api/V1/Controllers/Summary/BasicController.php index 6732ce589b..89c25e4946 100644 --- a/app/Api/V1/Controllers/Summary/BasicController.php +++ b/app/Api/V1/Controllers/Summary/BasicController.php @@ -53,11 +53,11 @@ use Illuminate\Support\Facades\Log; class BasicController extends Controller { private AvailableBudgetRepositoryInterface $abRepository; - private AccountRepositoryInterface $accountRepository; - private BillRepositoryInterface $billRepository; - private BudgetRepositoryInterface $budgetRepository; - private CurrencyRepositoryInterface $currencyRepos; - private OperationsRepositoryInterface $opsRepository; + private AccountRepositoryInterface $accountRepository; + private BillRepositoryInterface $billRepository; + private BudgetRepositoryInterface $budgetRepository; + private CurrencyRepositoryInterface $currencyRepos; + private OperationsRepositoryInterface $opsRepository; /** * BasicController constructor. @@ -65,48 +65,46 @@ class BasicController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - /** @var User $user */ - $user = auth()->user(); - $this->currencyRepos = app(CurrencyRepositoryInterface::class); - $this->billRepository = app(BillRepositoryInterface::class); - $this->budgetRepository = app(BudgetRepositoryInterface::class); - $this->accountRepository = app(AccountRepositoryInterface::class); - $this->abRepository = app(AvailableBudgetRepositoryInterface::class); - $this->opsRepository = app(OperationsRepositoryInterface::class); + $this->middleware(function ($request, $next) { + /** @var User $user */ + $user = auth()->user(); + $this->currencyRepos = app(CurrencyRepositoryInterface::class); + $this->billRepository = app(BillRepositoryInterface::class); + $this->budgetRepository = app(BudgetRepositoryInterface::class); + $this->accountRepository = app(AccountRepositoryInterface::class); + $this->abRepository = app(AvailableBudgetRepositoryInterface::class); + $this->opsRepository = app(OperationsRepositoryInterface::class); - $this->billRepository->setUser($user); - $this->currencyRepos->setUser($user); - $this->budgetRepository->setUser($user); - $this->accountRepository->setUser($user); - $this->abRepository->setUser($user); - $this->opsRepository->setUser($user); + $this->billRepository->setUser($user); + $this->currencyRepos->setUser($user); + $this->budgetRepository->setUser($user); + $this->accountRepository->setUser($user); + $this->abRepository->setUser($user); + $this->opsRepository->setUser($user); - return $next($request); - } - ); + return $next($request); + }); } public function basic(BasicRequest $request): JsonResponse { // parameters for boxes: - ['start' => $start, 'end' => $end, 'code' => $code] = $request->attributes->all(); + ['start' => $start, 'end' => $end, 'code' => $code] = $request->attributes->all(); // balance information: - $balanceData = $this->getBalanceInformation($start, $end); - $billData = $this->getSubscriptionInformation($start, $end); - $spentData = $this->getLeftToSpendInfo($start, $end); - $netWorthData = $this->getNetWorthInfo($end); + $balanceData = $this->getBalanceInformation($start, $end); + $billData = $this->getSubscriptionInformation($start, $end); + $spentData = $this->getLeftToSpendInfo($start, $end); + $netWorthData = $this->getNetWorthInfo($end); // $balanceData = []; // $billData = []; // $spentData = []; // $netWorthData = []; - $total = array_merge($balanceData, $billData, $spentData, $netWorthData); + $total = array_merge($balanceData, $billData, $spentData, $netWorthData); // give new keys - $return = []; + $return = []; foreach ($total as $entry) { - if ('' === $code || ($code === $entry['currency_code'])) { + if ('' === $code || $code === $entry['currency_code']) { $return[$entry['key']] = $entry; } } @@ -121,26 +119,27 @@ class BasicController extends Controller $convertToPrimary = Amount::convertToPrimary(); $primary = Amount::getPrimaryCurrency(); // prep some arrays: - $sums = []; - $return = []; - $currencies = [ - $primary->id => $primary, - ]; + $sums = []; + $return = []; + $currencies = [$primary->id => $primary]; // collect income of user using the new group collector. /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); - $summarizer = new TransactionSummarizer(); - $set = $collector->setRange($start, $end)->setTypes([TransactionTypeEnum::DEPOSIT->value])->getExtractedJournals(); - $incomes = $summarizer->groupByCurrencyId($set, 'positive', false); - + $collector = app(GroupCollectorInterface::class); + $summarizer = new TransactionSummarizer(); + $set = $collector->setRange($start, $end)->setTypes([TransactionTypeEnum::DEPOSIT->value])->getExtractedJournals(); + $incomes = $summarizer->groupByCurrencyId($set, 'positive', false); // collect expenses of user. // collect expenses of user using the new group collector. /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); - $set = $collector->setRange($start, $end)->setPage($this->parameters->get('page'))->setTypes([TransactionTypeEnum::WITHDRAWAL->value])->getExtractedJournals(); - $expenses = $summarizer->groupByCurrencyId($set, 'negative', false); + $collector = app(GroupCollectorInterface::class); + $set = $collector + ->setRange($start, $end) + ->setPage($this->parameters->get('page')) + ->setTypes([TransactionTypeEnum::WITHDRAWAL->value]) + ->getExtractedJournals(); + $expenses = $summarizer->groupByCurrencyId($set, 'negative', false); // if convert to primary, do so right now. if ($convertToPrimary) { @@ -150,35 +149,33 @@ class BasicController extends Controller 'currency_code' => $primary->code, 'currency_symbol' => $primary->symbol, 'currency_decimal_places' => $primary->decimal_places, - 'sum' => '0', - ], + 'sum' => '0' + ] ]; $newIncomes = [ - $primary->id => [ + $primary->id => [ 'currency_id' => $primary->id, 'currency_code' => $primary->code, 'currency_symbol' => $primary->symbol, 'currency_decimal_places' => $primary->decimal_places, - 'sum' => '0', - ], + 'sum' => '0' + ] ]; $sums = [ - $primary->id => [ + $primary->id => [ 'currency_id' => $primary->id, 'currency_code' => $primary->code, 'currency_symbol' => $primary->symbol, 'currency_decimal_places' => $primary->decimal_places, - 'sum' => '0', - ], + 'sum' => '0' + ] ]; - $converter = new ExchangeRateConverter(); + $converter = new ExchangeRateConverter(); // loop over income and expenses foreach ([$expenses, $incomes] as $index => $array) { - // loop over either one. foreach ($array as $entry) { - // if it is the primary currency already. if ($entry['currency_id'] === $primary->id) { $sums[$primary->id]['sum'] = bcadd((string) $entry['sum'], $sums[$primary->id]['sum']); @@ -195,7 +192,7 @@ class BasicController extends Controller } $currencies[$entry['currency_id']] ??= $this->currencyRepos->find($entry['currency_id']); - $convertedSum = $converter->convert($currencies[$entry['currency_id']], $primary, $start, $entry['sum']); + $convertedSum = $converter->convert($currencies[$entry['currency_id']], $primary, $start, $entry['sum']); $sums[$primary->id]['sum'] = bcadd($sums[$primary->id]['sum'], $convertedSum); if (0 === $index) { $newExpenses[$primary->id]['sum'] = bcadd($newExpenses[$primary->id]['sum'], $convertedSum); @@ -205,26 +202,26 @@ class BasicController extends Controller } } } - $incomes = $newIncomes; - $expenses = $newExpenses; + $incomes = $newIncomes; + $expenses = $newExpenses; } if (!$convertToPrimary) { foreach ([$expenses, $incomes] as $array) { foreach ($array as $entry) { - $currencyId = $entry['currency_id']; + $currencyId = $entry['currency_id']; $sums[$currencyId] ??= [ 'currency_id' => $entry['currency_id'], 'currency_code' => $entry['currency_code'], 'currency_symbol' => $entry['currency_symbol'], 'currency_decimal_places' => $entry['currency_decimal_places'], - 'sum' => '0', + 'sum' => '0' ]; $sums[$currencyId]['sum'] = bcadd($sums[$currencyId]['sum'], (string) $entry['sum']); } } } // format amounts: - $keys = array_keys($sums); + $keys = array_keys($sums); foreach ($keys as $currencyId) { $currency = $currencies[$currencyId] ?? $this->currencyRepos->find($currencyId); if (null === $currency) { @@ -233,7 +230,7 @@ class BasicController extends Controller // create objects for big array. $return[] = [ 'key' => sprintf('balance-in-%s', $currency->code), - 'title' => trans('firefly.box_balance_in_currency', ['currency' => $currency->symbol]), + 'title' => trans('firefly.box_balance_in_currency', ['currency' => $currency->symbol]), 'monetary_value' => $sums[$currencyId]['sum'] ?? '0', 'currency_id' => (string) $currency->id, 'currency_code' => $currency->code, @@ -242,11 +239,12 @@ class BasicController extends Controller 'value_parsed' => Amount::formatAnything($currency, $sums[$currencyId]['sum'] ?? '0', false), 'local_icon' => 'balance-scale', 'sub_title' => Amount::formatAnything($currency, $expenses[$currencyId]['sum'] ?? '0', false) - .' + '.Amount::formatAnything($currency, $incomes[$currencyId]['sum'] ?? '0', false), + . ' + ' + . Amount::formatAnything($currency, $incomes[$currencyId]['sum'] ?? '0', false) ]; $return[] = [ 'key' => sprintf('spent-in-%s', $currency->code), - 'title' => trans('firefly.box_spent_in_currency', ['currency' => $currency->symbol]), + 'title' => trans('firefly.box_spent_in_currency', ['currency' => $currency->symbol]), 'monetary_value' => $expenses[$currencyId]['sum'] ?? '0', 'currency_id' => (string) $currency->id, 'currency_code' => $currency->code, @@ -254,11 +252,11 @@ class BasicController extends Controller 'currency_decimal_places' => $currency->decimal_places, 'value_parsed' => Amount::formatAnything($currency, $expenses[$currencyId]['sum'] ?? '0', false), 'local_icon' => 'balance-scale', - 'sub_title' => '', + 'sub_title' => '' ]; $return[] = [ 'key' => sprintf('earned-in-%s', $currency->code), - 'title' => trans('firefly.box_earned_in_currency', ['currency' => $currency->symbol]), + 'title' => trans('firefly.box_earned_in_currency', ['currency' => $currency->symbol]), 'monetary_value' => $incomes[$currencyId]['sum'] ?? '0', 'currency_id' => (string) $currency->id, 'currency_code' => $currency->code, @@ -266,7 +264,7 @@ class BasicController extends Controller 'currency_decimal_places' => $currency->decimal_places, 'value_parsed' => Amount::formatAnything($currency, $incomes[$currencyId]['sum'] ?? '0', false), 'local_icon' => 'balance-scale', - 'sub_title' => '', + 'sub_title' => '' ]; } if (0 === count($return)) { @@ -274,7 +272,7 @@ class BasicController extends Controller // create objects for big array. $return[] = [ 'key' => sprintf('balance-in-%s', $currency->code), - 'title' => trans('firefly.box_balance_in_currency', ['currency' => $currency->symbol]), + 'title' => trans('firefly.box_balance_in_currency', ['currency' => $currency->symbol]), 'monetary_value' => '0', 'currency_id' => (string) $currency->id, 'currency_code' => $currency->code, @@ -282,12 +280,11 @@ class BasicController extends Controller 'currency_decimal_places' => $currency->decimal_places, 'value_parsed' => Amount::formatAnything($currency, '0', false), 'local_icon' => 'balance-scale', - 'sub_title' => Amount::formatAnything($currency, '0', false) - .' + '.Amount::formatAnything($currency, '0', false), + 'sub_title' => Amount::formatAnything($currency, '0', false) . ' + ' . Amount::formatAnything($currency, '0', false) ]; $return[] = [ 'key' => sprintf('spent-in-%s', $currency->code), - 'title' => trans('firefly.box_spent_in_currency', ['currency' => $currency->symbol]), + 'title' => trans('firefly.box_spent_in_currency', ['currency' => $currency->symbol]), 'monetary_value' => '0', 'currency_id' => (string) $currency->id, 'currency_code' => $currency->code, @@ -295,11 +292,11 @@ class BasicController extends Controller 'currency_decimal_places' => $currency->decimal_places, 'value_parsed' => Amount::formatAnything($currency, '0', false), 'local_icon' => 'balance-scale', - 'sub_title' => '', + 'sub_title' => '' ]; $return[] = [ 'key' => sprintf('earned-in-%s', $currency->code), - 'title' => trans('firefly.box_earned_in_currency', ['currency' => $currency->symbol]), + 'title' => trans('firefly.box_earned_in_currency', ['currency' => $currency->symbol]), 'monetary_value' => '0', 'currency_id' => (string) $currency->id, 'currency_code' => $currency->code, @@ -307,7 +304,7 @@ class BasicController extends Controller 'currency_decimal_places' => $currency->decimal_places, 'value_parsed' => Amount::formatAnything($currency, '0', false), 'local_icon' => 'balance-scale', - 'sub_title' => '', + 'sub_title' => '' ]; } @@ -323,19 +320,17 @@ class BasicController extends Controller */ $paidAmount = $this->billRepository->sumPaidInRange($start, $end); $unpaidAmount = $this->billRepository->sumUnpaidInRange($start, $end); - $currencies = [ - $this->primaryCurrency->id => $this->primaryCurrency, - ]; + $currencies = [$this->primaryCurrency->id => $this->primaryCurrency]; if ($this->convertToPrimary) { - $converter = new ExchangeRateConverter(); - $newPaidAmount = [[ + $converter = new ExchangeRateConverter(); + $newPaidAmount = [[ 'id' => $this->primaryCurrency->id, 'name' => $this->primaryCurrency->name, 'symbol' => $this->primaryCurrency->symbol, 'code' => $this->primaryCurrency->code, 'decimal_places' => $this->primaryCurrency->decimal_places, - 'sum' => '0', + 'sum' => '0' ]]; $newUnpaidAmount = [[ @@ -344,11 +339,11 @@ class BasicController extends Controller 'symbol' => $this->primaryCurrency->symbol, 'code' => $this->primaryCurrency->code, 'decimal_places' => $this->primaryCurrency->decimal_places, - 'sum' => '0', + 'sum' => '0' ]]; foreach ([$paidAmount, $unpaidAmount] as $index => $array) { foreach ($array as $item) { - $currencyId = (int) $item['id']; + $currencyId = (int) $item['id']; if (0 === $index) { // paid amount if ($currencyId === $this->primaryCurrency->id) { @@ -357,7 +352,7 @@ class BasicController extends Controller continue; } $currencies[$currencyId] ??= $this->currencyRepos->find($currencyId); - $convertedAmount = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $item['sum']); + $convertedAmount = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $item['sum']); $newPaidAmount[0]['sum'] = bcadd($newPaidAmount[0]['sum'], $convertedAmount); continue; @@ -369,28 +364,28 @@ class BasicController extends Controller continue; } $currencies[$currencyId] ??= $this->currencyRepos->find($currencyId); - $convertedAmount = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $item['sum']); + $convertedAmount = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $item['sum']); $newUnpaidAmount[0]['sum'] = bcadd($newUnpaidAmount[0]['sum'], $convertedAmount); } } - $paidAmount = $newPaidAmount; - $unpaidAmount = $newUnpaidAmount; + $paidAmount = $newPaidAmount; + $unpaidAmount = $newUnpaidAmount; } // var_dump($paidAmount); // var_dump($unpaidAmount); // exit; - $return = []; + $return = []; /** * @var array $info */ foreach ($paidAmount as $info) { - $amount = bcmul((string) $info['sum'], '-1'); + $amount = bcmul((string) $info['sum'], '-1'); $return[] = [ 'key' => sprintf('bills-paid-in-%s', $info['code']), - 'title' => trans('firefly.box_bill_paid_in_currency', ['currency' => $info['symbol']]), + 'title' => trans('firefly.box_bill_paid_in_currency', ['currency' => $info['symbol']]), 'monetary_value' => $amount, 'currency_id' => (string) $info['id'], 'currency_code' => $info['code'], @@ -398,7 +393,7 @@ class BasicController extends Controller 'currency_decimal_places' => $info['decimal_places'], 'value_parsed' => Amount::formatFlat($info['symbol'], $info['decimal_places'], $amount, false), 'local_icon' => 'check', - 'sub_title' => '', + 'sub_title' => '' ]; } @@ -406,10 +401,10 @@ class BasicController extends Controller * @var array $info */ foreach ($unpaidAmount as $info) { - $amount = bcmul((string) $info['sum'], '-1'); + $amount = bcmul((string) $info['sum'], '-1'); $return[] = [ 'key' => sprintf('bills-unpaid-in-%s', $info['code']), - 'title' => trans('firefly.box_bill_unpaid_in_currency', ['currency' => $info['symbol']]), + 'title' => trans('firefly.box_bill_unpaid_in_currency', ['currency' => $info['symbol']]), 'monetary_value' => $amount, 'currency_id' => (string) $info['id'], 'currency_code' => $info['code'], @@ -417,7 +412,7 @@ class BasicController extends Controller 'currency_decimal_places' => $info['decimal_places'], 'value_parsed' => Amount::formatFlat($info['symbol'], $info['decimal_places'], $amount, false), 'local_icon' => 'calendar-o', - 'sub_title' => '', + 'sub_title' => '' ]; } Log::debug(sprintf('Done with getBillInformation("%s", "%s")', $start->format('Y-m-d'), $end->format('Y-m-d-'))); @@ -428,7 +423,7 @@ class BasicController extends Controller $return[] = [ 'key' => sprintf('bills-paid-in-%s', $currency->code), - 'title' => trans('firefly.box_bill_paid_in_currency', ['currency' => $currency->symbol]), + 'title' => trans('firefly.box_bill_paid_in_currency', ['currency' => $currency->symbol]), 'monetary_value' => '0', 'currency_id' => (string) $currency->id, 'currency_code' => $currency->code, @@ -436,11 +431,11 @@ class BasicController extends Controller 'currency_decimal_places' => $currency->decimal_places, 'value_parsed' => Amount::formatFlat($currency->symbol, $currency->decimal_places, '0', false), 'local_icon' => 'check', - 'sub_title' => '', + 'sub_title' => '' ]; $return[] = [ 'key' => sprintf('bills-unpaid-in-%s', $currency->code), - 'title' => trans('firefly.box_bill_unpaid_in_currency', ['currency' => $currency->symbol]), + 'title' => trans('firefly.box_bill_unpaid_in_currency', ['currency' => $currency->symbol]), 'monetary_value' => '0', 'currency_id' => (string) $currency->id, 'currency_code' => $currency->code, @@ -448,11 +443,10 @@ class BasicController extends Controller 'currency_decimal_places' => $currency->decimal_places, 'value_parsed' => Amount::formatFlat($currency->symbol, $currency->decimal_places, '0', false), 'local_icon' => 'calendar-o', - 'sub_title' => '', + 'sub_title' => '' ]; } - return $return; } @@ -461,7 +455,6 @@ class BasicController extends Controller */ private function getLeftToSpendInfo(Carbon $start, Carbon $end): array { - Log::debug(sprintf('Now in getLeftToSpendInfo("%s", "%s")', $start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s'))); $return = []; $today = today(config('app.timezone')); @@ -477,29 +470,39 @@ class BasicController extends Controller $currencies[$currencyId] ??= $this->currencyRepos->find($currencyId); $return[$currencyId] = [ 'key' => sprintf('left-to-spend-in-%s', $currencies[$currencyId]->code), - 'title' => trans('firefly.box_left_to_spend_in_currency', ['currency' => $currencies[$currencyId]->symbol]), + 'title' => trans('firefly.box_left_to_spend_in_currency', ['currency' => $currencies[$currencyId]->symbol]), 'no_available_budgets' => false, 'monetary_value' => $availableBudget, 'currency_id' => (string) $currencies[$currencyId]->id, 'currency_code' => $currencies[$currencyId]->code, 'currency_symbol' => $currencies[$currencyId]->symbol, 'currency_decimal_places' => $currencies[$currencyId]->decimal_places, - 'value_parsed' => Amount::formatFlat($currencies[$currencyId]->symbol, $currencies[$currencyId]->decimal_places, $availableBudget, false), + 'value_parsed' => Amount::formatFlat( + $currencies[$currencyId]->symbol, + $currencies[$currencyId]->decimal_places, + $availableBudget, + false + ), 'local_icon' => 'money', - 'sub_title' => Amount::formatFlat($currencies[$currencyId]->symbol, $currencies[$currencyId]->decimal_places, bcdiv($availableBudget, (string)$days), false), + 'sub_title' => Amount::formatFlat( + $currencies[$currencyId]->symbol, + $currencies[$currencyId]->decimal_places, + bcdiv($availableBudget, (string) $days), + false + ) ]; } foreach ($spent as $row) { // either an amount was budgeted or 0 is available. - $currencyId = (int) $row['currency_id']; - $amount = (string) ($available[$currencyId] ?? '0'); + $currencyId = (int) $row['currency_id']; + $amount = (string) ($available[$currencyId] ?? '0'); if (0 === bccomp($amount, '0')) { // #9858 skip over currencies with no available budget. continue; } - $spentInCurrency = $row['sum']; - $leftToSpend = bcadd($amount, (string) $spentInCurrency); - $perDay = '0'; + $spentInCurrency = $row['sum']; + $leftToSpend = bcadd($amount, (string) $spentInCurrency); + $perDay = '0'; if (0 !== $days && bccomp($leftToSpend, '0') > -1) { $perDay = bcdiv($leftToSpend, (string) $days); } @@ -508,7 +511,7 @@ class BasicController extends Controller $return[$currencyId] = [ 'key' => sprintf('left-to-spend-in-%s', $row['currency_code']), - 'title' => trans('firefly.box_left_to_spend_in_currency', ['currency' => $row['currency_symbol']]), + 'title' => trans('firefly.box_left_to_spend_in_currency', ['currency' => $row['currency_symbol']]), 'no_available_budgets' => false, 'monetary_value' => $leftToSpend, 'currency_id' => (string) $row['currency_id'], @@ -517,19 +520,19 @@ class BasicController extends Controller 'currency_decimal_places' => $row['currency_decimal_places'], 'value_parsed' => Amount::formatFlat($row['currency_symbol'], $row['currency_decimal_places'], $leftToSpend, false), 'local_icon' => 'money', - 'sub_title' => Amount::formatFlat($row['currency_symbol'], $row['currency_decimal_places'], $perDay, false), + 'sub_title' => Amount::formatFlat($row['currency_symbol'], $row['currency_decimal_places'], $perDay, false) ]; } unset($leftToSpend); if (0 === count($return)) { - $days = (int) $start->diffInDays($end, true) + 1; + $days = (int) $start->diffInDays($end, true) + 1; // a small trick to get every expense in this period, regardless of budget. $spent = $this->opsRepository->sumExpenses($start, $end, null, new Collection()); foreach ($spent as $row) { // either an amount was budgeted or 0 is available. - $currencyId = (int) $row['currency_id']; - $spentInCurrency = $row['sum']; - $perDay = '0'; + $currencyId = (int) $row['currency_id']; + $spentInCurrency = $row['sum']; + $perDay = '0'; if (0 !== $days && -1 === bccomp((string) $spentInCurrency, '0')) { $perDay = bcdiv((string) $spentInCurrency, (string) $days); } @@ -547,7 +550,7 @@ class BasicController extends Controller 'currency_decimal_places' => $row['currency_decimal_places'], 'value_parsed' => Amount::formatFlat($row['currency_symbol'], $row['currency_decimal_places'], $spentInCurrency, false), 'local_icon' => 'money', - 'sub_title' => Amount::formatFlat($row['currency_symbol'], $row['currency_decimal_places'], $perDay, false), + 'sub_title' => Amount::formatFlat($row['currency_symbol'], $row['currency_decimal_places'], $perDay, false) ]; } @@ -581,37 +584,41 @@ class BasicController extends Controller private function getNetWorthInfo(Carbon $end): array { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); Log::debug(sprintf('getNetWorthInfo up until "%s".', $end->format('Y-m-d H:i:s'))); /** @var NetWorthInterface $netWorthHelper */ $netWorthHelper = app(NetWorthInterface::class); $netWorthHelper->setUser($user); - $allAccounts = $this->accountRepository->getActiveAccountsByType([AccountTypeEnum::ASSET->value, AccountTypeEnum::DEFAULT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::DEBT->value]); + $allAccounts = $this->accountRepository->getActiveAccountsByType([ + AccountTypeEnum::ASSET->value, + AccountTypeEnum::DEFAULT->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::MORTGAGE->value, + AccountTypeEnum::DEBT->value + ]); // filter list on preference of being included. - $filtered = $allAccounts->filter( - function (Account $account): bool { - $includeNetWorth = $this->accountRepository->getMetaValue($account, 'include_net_worth'); + $filtered = $allAccounts->filter(function (Account $account): bool { + $includeNetWorth = $this->accountRepository->getMetaValue($account, 'include_net_worth'); - return null === $includeNetWorth || '1' === $includeNetWorth; - } - ); + return null === $includeNetWorth || '1' === $includeNetWorth; + }); - $netWorthSet = $netWorthHelper->byAccounts($filtered, $end); - $return = []; + $netWorthSet = $netWorthHelper->byAccounts($filtered, $end); + $return = []; foreach ($netWorthSet as $key => $data) { if ('pc' === $key) { continue; } - $amount = $data['balance']; + $amount = $data['balance']; if (0 === bccomp((string) $amount, '0')) { continue; } // return stuff $return[] = [ 'key' => sprintf('net-worth-in-%s', $data['currency_code']), - 'title' => trans('firefly.box_net_worth_in_currency', ['currency' => $data['currency_symbol']]), + 'title' => trans('firefly.box_net_worth_in_currency', ['currency' => $data['currency_symbol']]), 'monetary_value' => $amount, 'currency_id' => (string) $data['currency_id'], 'currency_code' => $data['currency_code'], @@ -619,13 +626,13 @@ class BasicController extends Controller 'currency_decimal_places' => $data['currency_decimal_places'], 'value_parsed' => Amount::formatFlat($data['currency_symbol'], $data['currency_decimal_places'], $data['balance'], false), 'local_icon' => 'line-chart', - 'sub_title' => '', + 'sub_title' => '' ]; } if (0 === count($return)) { $return[] = [ 'key' => sprintf('net-worth-in-%s', $this->primaryCurrency->code), - 'title' => trans('firefly.box_net_worth_in_currency', ['currency' => $this->primaryCurrency->symbol]), + 'title' => trans('firefly.box_net_worth_in_currency', ['currency' => $this->primaryCurrency->symbol]), 'monetary_value' => '0', 'currency_id' => (string) $this->primaryCurrency->id, 'currency_code' => $this->primaryCurrency->code, @@ -633,11 +640,10 @@ class BasicController extends Controller 'currency_decimal_places' => $this->primaryCurrency->decimal_places, 'value_parsed' => Amount::formatFlat($this->primaryCurrency->symbol, $this->primaryCurrency->decimal_places, '0', false), 'local_icon' => 'line-chart', - 'sub_title' => '', + 'sub_title' => '' ]; } - Log::debug('End of getNetWorthInfo'); return $return; @@ -646,8 +652,8 @@ class BasicController extends Controller /** * Check if date is outside session range. */ - protected function notInDateRange(Carbon $date, Carbon $start, Carbon $end): bool // Validate a preference - { + protected function notInDateRange(Carbon $date, Carbon $start, Carbon $end): bool + { // Validate a preference if ($start->greaterThanOrEqualTo($date) && $end->greaterThanOrEqualTo($date)) { return true; } diff --git a/app/Api/V1/Controllers/System/AboutController.php b/app/Api/V1/Controllers/System/AboutController.php index c9f74933e6..e1087659e1 100644 --- a/app/Api/V1/Controllers/System/AboutController.php +++ b/app/Api/V1/Controllers/System/AboutController.php @@ -50,14 +50,13 @@ class AboutController extends Controller $phpVersion = str_replace($search, $replace, PHP_VERSION); $phpOs = str_replace($search, $replace, PHP_OS); $currentDriver = DB::getDriverName(); - $data - = [ - 'version' => config('firefly.version'), - 'api_version' => config('firefly.version'), - 'php_version' => $phpVersion, - 'os' => $phpOs, - 'driver' => $currentDriver, - ]; + $data = [ + 'version' => config('firefly.version'), + 'api_version' => config('firefly.version'), + 'php_version' => $phpVersion, + 'os' => $phpOs, + 'driver' => $currentDriver + ]; return response()->api(['data' => $data])->header('Content-Type', self::JSON_CONTENT_TYPE); } @@ -70,13 +69,13 @@ class AboutController extends Controller */ public function user(): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var UserTransformer $transformer */ $transformer = app(UserTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item(auth()->user(), $transformer, 'users'); + $resource = new Item(auth()->user(), $transformer, 'users'); return response()->api($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/System/ConfigurationController.php b/app/Api/V1/Controllers/System/ConfigurationController.php index 5902b8a343..7fea3f8058 100644 --- a/app/Api/V1/Controllers/System/ConfigurationController.php +++ b/app/Api/V1/Controllers/System/ConfigurationController.php @@ -51,13 +51,11 @@ class ConfigurationController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(UserRepositoryInterface::class); + $this->middleware(function ($request, $next) { + $this->repository = app(UserRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -79,18 +77,10 @@ class ConfigurationController extends Controller $staticData = $this->getStaticConfiguration(); $return = []; foreach ($dynamicData as $key => $value) { - $return[] = [ - 'title' => sprintf('configuration.%s', $key), - 'value' => $value, - 'editable' => true, - ]; + $return[] = ['title' => sprintf('configuration.%s', $key), 'value' => $value, 'editable' => true]; } foreach ($staticData as $key => $value) { - $return[] = [ - 'title' => $key, - 'value' => $value, - 'editable' => false, - ]; + $return[] = ['title' => $key, 'value' => $value, 'editable' => false]; } return response()->api($return); @@ -110,9 +100,9 @@ class ConfigurationController extends Controller return [ 'is_demo_site' => $isDemoSite?->data, - 'permission_update_check' => null === $updateCheck ? null : (int)$updateCheck->data, - 'last_update_check' => null === $lastCheck ? null : (int)$lastCheck->data, - 'single_user_mode' => $singleUser?->data, + 'permission_update_check' => null === $updateCheck ? null : (int) $updateCheck->data, + 'last_update_check' => null === $lastCheck ? null : (int) $lastCheck->data, + 'single_user_mode' => $singleUser?->data ]; } @@ -136,30 +126,18 @@ class ConfigurationController extends Controller $dynamic = $this->getDynamicConfiguration(); $shortKey = str_replace('configuration.', '', $configKey); if (str_starts_with($configKey, 'configuration.')) { - $data = [ - 'title' => $configKey, - 'value' => $dynamic[$shortKey], - 'editable' => true, - ]; + $data = ['title' => $configKey, 'value' => $dynamic[$shortKey], 'editable' => true]; return response()->api(['data' => $data])->header('Content-Type', self::JSON_CONTENT_TYPE); } if (str_starts_with($configKey, 'webhook.')) { - $data = [ - 'title' => $configKey, - 'value' => $this->getWebhookConfiguration($configKey), - 'editable' => false, - ]; + $data = ['title' => $configKey, 'value' => $this->getWebhookConfiguration($configKey), 'editable' => false]; return response()->api(['data' => $data])->header('Content-Type', self::JSON_CONTENT_TYPE); } // fallback - $data = [ - 'title' => $configKey, - 'value' => config($shortKey), - 'editable' => false, - ]; + $data = ['title' => $configKey, 'value' => config($shortKey), 'editable' => false]; return response()->api(['data' => $data])->header('Content-Type', self::JSON_CONTENT_TYPE); } @@ -175,7 +153,7 @@ class ConfigurationController extends Controller */ public function update(UpdateRequest $request, string $name): JsonResponse { - $rules = ['value' => 'required']; + $rules = ['value' => 'required']; if (!$this->repository->hasRole(auth()->user(), 'owner')) { $messages = ['value' => '200005: You need the "owner" role to do this.']; Validator::make([], $rules, $messages)->validate(); @@ -187,11 +165,7 @@ class ConfigurationController extends Controller // get updated config: $newConfig = $this->getDynamicConfiguration(); - $data = [ - 'title' => $name, - 'value' => $newConfig[$shortName], - 'editable' => true, - ]; + $data = ['title' => $name, 'value' => $newConfig[$shortName], 'editable' => true]; return response()->api(['data' => $data])->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/System/CronController.php b/app/Api/V1/Controllers/System/CronController.php index 5f520fad85..4a7d8bc0c6 100644 --- a/app/Api/V1/Controllers/System/CronController.php +++ b/app/Api/V1/Controllers/System/CronController.php @@ -26,10 +26,10 @@ namespace FireflyIII\Api\V1\Controllers\System; use FireflyIII\Api\V1\Controllers\Controller; use FireflyIII\Api\V1\Requests\System\CronRequest; +use FireflyIII\Support\Facades\FireflyConfig; use FireflyIII\Support\Http\Controllers\CronRunner; use Illuminate\Http\JsonResponse; use Illuminate\Support\Facades\Log; -use FireflyIII\Support\Facades\FireflyConfig; /** * Class CronController @@ -44,18 +44,18 @@ class CronController extends Controller */ public function cron(CronRequest $request): JsonResponse { - $config = $request->getAll(); + $config = $request->getAll(); Log::debug(sprintf('Now in %s', __METHOD__)); Log::debug(sprintf('Date is %s', $config['date']->toIsoString())); - $return = []; + $return = []; $return['recurring_transactions'] = $this->runRecurring($config['force'], $config['date']); - $return['auto_budgets'] = $this->runAutoBudget($config['force'], $config['date']); + $return['auto_budgets'] = $this->runAutoBudget($config['force'], $config['date']); if (true === FireflyConfig::get('enable_external_rates', config('cer.download_enabled'))->data) { $return['exchange_rates'] = $this->exchangeRatesCronJob($config['force'], $config['date']); } - $return['bill_notifications'] = $this->billWarningCronJob($config['force'], $config['date']); - $return['webhooks'] = $this->webhookCronJob($config['force'], $config['date']); + $return['bill_notifications'] = $this->billWarningCronJob($config['force'], $config['date']); + $return['webhooks'] = $this->webhookCronJob($config['force'], $config['date']); return response()->api($return); } diff --git a/app/Api/V1/Controllers/System/UserController.php b/app/Api/V1/Controllers/System/UserController.php index d08807ab52..0c0191bbde 100644 --- a/app/Api/V1/Controllers/System/UserController.php +++ b/app/Api/V1/Controllers/System/UserController.php @@ -51,13 +51,11 @@ class UserController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(UserRepositoryInterface::class); + $this->middleware(function ($request, $next) { + $this->repository = app(UserRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -94,24 +92,24 @@ class UserController extends Controller public function index(): JsonResponse { // user preferences - $pageSize = $this->parameters->get('limit'); - $manager = $this->getManager(); + $pageSize = $this->parameters->get('limit'); + $manager = $this->getManager(); // build collection - $collection = $this->repository->all(); - $count = $collection->count(); - $users = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $collection = $this->repository->all(); + $count = $collection->count(); + $users = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($users, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.users.index').$this->buildParams()); + $paginator = new LengthAwarePaginator($users, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.users.index') . $this->buildParams()); // make resource /** @var UserTransformer $transformer */ $transformer = app(UserTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($users, $transformer, 'users'); + $resource = new FractalCollection($users, $transformer, 'users'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -126,14 +124,14 @@ class UserController extends Controller public function show(User $user): JsonResponse { // make manager - $manager = $this->getManager(); + $manager = $this->getManager(); // make resource /** @var UserTransformer $transformer */ $transformer = app(UserTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($user, $transformer, 'users'); + $resource = new Item($user, $transformer, 'users'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } @@ -146,9 +144,9 @@ class UserController extends Controller */ public function store(UserStoreRequest $request): JsonResponse { - $data = $request->getAll(); - $user = $this->repository->store($data); - $manager = $this->getManager(); + $data = $request->getAll(); + $user = $this->repository->store($data); + $manager = $this->getManager(); // make resource @@ -156,7 +154,7 @@ class UserController extends Controller $transformer = app(UserTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($user, $transformer, 'users'); + $resource = new Item($user, $transformer, 'users'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } @@ -169,7 +167,7 @@ class UserController extends Controller */ public function update(UserUpdateRequest $request, User $user): JsonResponse { - $data = $request->getAll(); + $data = $request->getAll(); // can only update 'blocked' when user is admin. if (!$this->repository->hasRole(auth()->user(), 'owner')) { @@ -177,15 +175,15 @@ class UserController extends Controller unset($data['blocked'], $data['blocked_code']); } - $user = $this->repository->update($user, $data); - $manager = $this->getManager(); + $user = $this->repository->update($user, $data); + $manager = $this->getManager(); // make resource /** @var UserTransformer $transformer */ $transformer = app(UserTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($user, $transformer, 'users'); + $resource = new Item($user, $transformer, 'users'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/User/PreferencesController.php b/app/Api/V1/Controllers/User/PreferencesController.php index 9c0be7163e..107364331e 100644 --- a/app/Api/V1/Controllers/User/PreferencesController.php +++ b/app/Api/V1/Controllers/User/PreferencesController.php @@ -60,14 +60,14 @@ class PreferencesController extends Controller $preferences = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($preferences, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.preferences.index').$this->buildParams()); + $paginator = new LengthAwarePaginator($preferences, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.preferences.index') . $this->buildParams()); /** @var PreferenceTransformer $transformer */ $transformer = app(PreferenceTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($preferences, $transformer, self::RESOURCE_KEY); + $resource = new FractalCollection($preferences, $transformer, self::RESOURCE_KEY); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -81,7 +81,7 @@ class PreferencesController extends Controller */ public function show(Preference $preference): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); if ('currencyPreference' === $preference->name) { throw new FireflyException('Please use api/v1/currencies/primary instead.'); @@ -91,7 +91,7 @@ class PreferencesController extends Controller $transformer = app(PreferenceTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($preference, $transformer, 'preferences'); + $resource = new Item($preference, $transformer, 'preferences'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } @@ -104,20 +104,20 @@ class PreferencesController extends Controller */ public function store(PreferenceStoreRequest $request): JsonResponse { - $manager = $this->getManager(); - $data = $request->getAll(); + $manager = $this->getManager(); + $data = $request->getAll(); if ('currencyPreference' === $data['name']) { throw new FireflyException('Please use api/v1/currencies/default instead.'); } - $pref = Preferences::set($data['name'], $data['data']); + $pref = Preferences::set($data['name'], $data['data']); /** @var PreferenceTransformer $transformer */ $transformer = app(PreferenceTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($pref, $transformer, 'preferences'); + $resource = new Item($pref, $transformer, 'preferences'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } @@ -134,15 +134,15 @@ class PreferencesController extends Controller throw new FireflyException('Please use api/v1/currencies/primary instead.'); } - $manager = $this->getManager(); - $data = $request->getAll(); - $pref = Preferences::set($preference->name, $data['data']); + $manager = $this->getManager(); + $data = $request->getAll(); + $pref = Preferences::set($preference->name, $data['data']); /** @var PreferenceTransformer $transformer */ $transformer = app(PreferenceTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($pref, $transformer, 'preferences'); + $resource = new Item($pref, $transformer, 'preferences'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Webhook/AttemptController.php b/app/Api/V1/Controllers/Webhook/AttemptController.php index 5f0c376d2b..e958c1ad46 100644 --- a/app/Api/V1/Controllers/Webhook/AttemptController.php +++ b/app/Api/V1/Controllers/Webhook/AttemptController.php @@ -30,6 +30,7 @@ use FireflyIII\Models\Webhook; use FireflyIII\Models\WebhookAttempt; use FireflyIII\Models\WebhookMessage; use FireflyIII\Repositories\Webhook\WebhookRepositoryInterface; +use FireflyIII\Support\Facades\FireflyConfig; use FireflyIII\Transformers\WebhookAttemptTransformer; use Illuminate\Http\JsonResponse; use Illuminate\Pagination\LengthAwarePaginator; @@ -38,7 +39,6 @@ use League\Fractal\Pagination\IlluminatePaginatorAdapter; use League\Fractal\Resource\Collection as FractalCollection; use League\Fractal\Resource\Item; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; -use FireflyIII\Support\Facades\FireflyConfig; /** * Class AttemptController @@ -46,19 +46,18 @@ use FireflyIII\Support\Facades\FireflyConfig; class AttemptController extends Controller { public const string RESOURCE_KEY = 'webhook_attempts'; + private WebhookRepositoryInterface $repository; public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(WebhookRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(WebhookRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -73,27 +72,31 @@ class AttemptController extends Controller throw new FireflyException('200040: Webhook and webhook message are no match'); } if (false === FireflyConfig::get('allow_webhooks', config('firefly.allow_webhooks'))->data) { - Log::channel('audit')->warning(sprintf('User lists webhook attempts of webhook #%d and message #%d, but webhooks are DISABLED.', $webhook->id, $message->id)); + Log::channel('audit')->warning(sprintf( + 'User lists webhook attempts of webhook #%d and message #%d, but webhooks are DISABLED.', + $webhook->id, + $message->id + )); throw new NotFoundHttpException('Webhooks are not enabled.'); } Log::channel('audit')->info(sprintf('User lists webhook attempts of webhook #%d and message #%d.', $webhook->id, $message->id)); - $manager = $this->getManager(); - $pageSize = $this->parameters->get('limit'); - $collection = $this->repository->getAttempts($message); - $count = $collection->count(); - $attempts = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $manager = $this->getManager(); + $pageSize = $this->parameters->get('limit'); + $collection = $this->repository->getAttempts($message); + $count = $collection->count(); + $attempts = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($attempts, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.webhooks.attempts.index', [$webhook->id, $message->id]).$this->buildParams()); + $paginator = new LengthAwarePaginator($attempts, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.webhooks.attempts.index', [$webhook->id, $message->id]) . $this->buildParams()); /** @var WebhookAttemptTransformer $transformer */ $transformer = app(WebhookAttemptTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($attempts, $transformer, 'webhook_attempts'); + $resource = new FractalCollection($attempts, $transformer, 'webhook_attempts'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -117,19 +120,24 @@ class AttemptController extends Controller } if (false === FireflyConfig::get('allow_webhooks', config('firefly.allow_webhooks'))->data) { - Log::channel('audit')->warning(sprintf('User views single webhook attempt #%d of webhook #%d and message #%d, but webhooks are DISABLED', $attempt->id, $webhook->id, $message->id)); + Log::channel('audit')->warning(sprintf( + 'User views single webhook attempt #%d of webhook #%d and message #%d, but webhooks are DISABLED', + $attempt->id, + $webhook->id, + $message->id + )); throw new NotFoundHttpException('Webhooks are not enabled.'); } Log::channel('audit')->info(sprintf('User views single webhook attempt #%d of webhook #%d and message #%d.', $attempt->id, $webhook->id, $message->id)); - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var WebhookAttemptTransformer $transformer */ $transformer = app(WebhookAttemptTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($attempt, $transformer, self::RESOURCE_KEY); + $resource = new Item($attempt, $transformer, self::RESOURCE_KEY); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Webhook/DestroyController.php b/app/Api/V1/Controllers/Webhook/DestroyController.php index 002458fa86..5a0d3eb1b5 100644 --- a/app/Api/V1/Controllers/Webhook/DestroyController.php +++ b/app/Api/V1/Controllers/Webhook/DestroyController.php @@ -30,11 +30,11 @@ use FireflyIII\Models\Webhook; use FireflyIII\Models\WebhookAttempt; use FireflyIII\Models\WebhookMessage; use FireflyIII\Repositories\Webhook\WebhookRepositoryInterface; +use FireflyIII\Support\Facades\FireflyConfig; use FireflyIII\Support\Facades\Preferences; use Illuminate\Http\JsonResponse; use Illuminate\Support\Facades\Log; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; -use FireflyIII\Support\Facades\FireflyConfig; /** * Class DestroyController @@ -46,14 +46,12 @@ class DestroyController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(WebhookRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(WebhookRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -95,7 +93,12 @@ class DestroyController extends Controller } if (false === FireflyConfig::get('allow_webhooks', config('firefly.allow_webhooks'))->data) { - Log::channel('audit')->warning(sprintf('User tries to destroy webhook #%d, message #%d, attempt #%d, but webhooks are DISABLED.', $webhook->id, $message->id, $attempt->id)); + Log::channel('audit')->warning(sprintf( + 'User tries to destroy webhook #%d, message #%d, attempt #%d, but webhooks are DISABLED.', + $webhook->id, + $message->id, + $attempt->id + )); throw new NotFoundHttpException('Webhooks are not enabled.'); } diff --git a/app/Api/V1/Controllers/Webhook/MessageController.php b/app/Api/V1/Controllers/Webhook/MessageController.php index 48c1dd155e..893a9c75f3 100644 --- a/app/Api/V1/Controllers/Webhook/MessageController.php +++ b/app/Api/V1/Controllers/Webhook/MessageController.php @@ -29,6 +29,7 @@ use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Webhook; use FireflyIII\Models\WebhookMessage; use FireflyIII\Repositories\Webhook\WebhookRepositoryInterface; +use FireflyIII\Support\Facades\FireflyConfig; use FireflyIII\Transformers\WebhookMessageTransformer; use Illuminate\Http\JsonResponse; use Illuminate\Pagination\LengthAwarePaginator; @@ -37,7 +38,6 @@ use League\Fractal\Pagination\IlluminatePaginatorAdapter; use League\Fractal\Resource\Collection as FractalCollection; use League\Fractal\Resource\Item; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; -use FireflyIII\Support\Facades\FireflyConfig; /** * Class MessageController @@ -45,19 +45,18 @@ use FireflyIII\Support\Facades\FireflyConfig; class MessageController extends Controller { public const string RESOURCE_KEY = 'webhook_messages'; + private WebhookRepositoryInterface $repository; public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(WebhookRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(WebhookRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -72,22 +71,22 @@ class MessageController extends Controller throw new NotFoundHttpException('Webhooks are not enabled.'); } Log::channel('audit')->info(sprintf('User views messages of webhook #%d.', $webhook->id)); - $manager = $this->getManager(); - $pageSize = $this->parameters->get('limit'); - $collection = $this->repository->getMessages($webhook); + $manager = $this->getManager(); + $pageSize = $this->parameters->get('limit'); + $collection = $this->repository->getMessages($webhook); - $count = $collection->count(); - $messages = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $count = $collection->count(); + $messages = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($messages, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.webhooks.messages.index', [$webhook->id]).$this->buildParams()); + $paginator = new LengthAwarePaginator($messages, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.webhooks.messages.index', [$webhook->id]) . $this->buildParams()); /** @var WebhookMessageTransformer $transformer */ $transformer = app(WebhookMessageTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($messages, $transformer, 'webhook_messages'); + $resource = new FractalCollection($messages, $transformer, 'webhook_messages'); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -114,12 +113,12 @@ class MessageController extends Controller Log::channel('audit')->info(sprintf('User views message #%d of webhook #%d.', $message->id, $webhook->id)); - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var WebhookMessageTransformer $transformer */ $transformer = app(WebhookMessageTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($message, $transformer, self::RESOURCE_KEY); + $resource = new Item($message, $transformer, self::RESOURCE_KEY); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Webhook/ShowController.php b/app/Api/V1/Controllers/Webhook/ShowController.php index 260d26e413..d0a0d24a8d 100644 --- a/app/Api/V1/Controllers/Webhook/ShowController.php +++ b/app/Api/V1/Controllers/Webhook/ShowController.php @@ -31,6 +31,7 @@ use FireflyIII\Generator\Webhook\MessageGeneratorInterface; use FireflyIII\Models\TransactionGroup; use FireflyIII\Models\Webhook; use FireflyIII\Repositories\Webhook\WebhookRepositoryInterface; +use FireflyIII\Support\Facades\FireflyConfig; use FireflyIII\Support\JsonApi\Enrichments\WebhookEnrichment; use FireflyIII\Transformers\WebhookTransformer; use FireflyIII\User; @@ -42,7 +43,6 @@ use League\Fractal\Pagination\IlluminatePaginatorAdapter; use League\Fractal\Resource\Collection as FractalCollection; use League\Fractal\Resource\Item; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; -use FireflyIII\Support\Facades\FireflyConfig; /** * Class ShowController @@ -50,19 +50,18 @@ use FireflyIII\Support\Facades\FireflyConfig; class ShowController extends Controller { public const string RESOURCE_KEY = 'webhooks'; + private WebhookRepositoryInterface $repository; public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(WebhookRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(WebhookRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -80,28 +79,28 @@ class ShowController extends Controller } Log::channel('audit')->info('User views all webhooks.'); - $manager = $this->getManager(); - $collection = $this->repository->all(); - $pageSize = $this->parameters->get('limit'); - $count = $collection->count(); - $webhooks = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $manager = $this->getManager(); + $collection = $this->repository->all(); + $pageSize = $this->parameters->get('limit'); + $count = $collection->count(); + $webhooks = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: - $paginator = new LengthAwarePaginator($webhooks, $count, $pageSize, $this->parameters->get('page')); - $paginator->setPath(route('api.v1.webhooks.index').$this->buildParams()); + $paginator = new LengthAwarePaginator($webhooks, $count, $pageSize, $this->parameters->get('page')); + $paginator->setPath(route('api.v1.webhooks.index') . $this->buildParams()); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new WebhookEnrichment(); + $admin = auth()->user(); + $enrichment = new WebhookEnrichment(); $enrichment->setUser($admin); - $webhooks = $enrichment->enrich($webhooks); + $webhooks = $enrichment->enrich($webhooks); /** @var WebhookTransformer $transformer */ $transformer = app(WebhookTransformer::class); $transformer->setParameters($this->parameters); - $resource = new FractalCollection($webhooks, $transformer, self::RESOURCE_KEY); + $resource = new FractalCollection($webhooks, $transformer, self::RESOURCE_KEY); $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); @@ -122,19 +121,19 @@ class ShowController extends Controller } Log::channel('audit')->info(sprintf('User views webhook #%d.', $webhook->id)); - $manager = $this->getManager(); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new WebhookEnrichment(); + $admin = auth()->user(); + $enrichment = new WebhookEnrichment(); $enrichment->setUser($admin); - $webhook = $enrichment->enrichSingle($webhook); + $webhook = $enrichment->enrichSingle($webhook); /** @var WebhookTransformer $transformer */ $transformer = app(WebhookTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($webhook, $transformer, self::RESOURCE_KEY); + $resource = new Item($webhook, $transformer, self::RESOURCE_KEY); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } @@ -148,7 +147,11 @@ class ShowController extends Controller public function triggerTransaction(Webhook $webhook, TransactionGroup $group): JsonResponse { if (false === FireflyConfig::get('allow_webhooks', config('firefly.allow_webhooks'))->data) { - Log::channel('audit')->info(sprintf('User tries to trigger webhook #%d on transaction group #%d, but webhooks are DISABLED.', $webhook->id, $group->id)); + Log::channel('audit')->info(sprintf( + 'User tries to trigger webhook #%d on transaction group #%d, but webhooks are DISABLED.', + $webhook->id, + $group->id + )); throw new NotFoundHttpException('Webhooks are not enabled.'); } @@ -156,7 +159,6 @@ class ShowController extends Controller Log::debug(sprintf('Now in triggerTransaction(%d, %d)', $webhook->id, $group->id)); Log::channel('audit')->info(sprintf('User triggers webhook #%d on transaction group #%d.', $webhook->id, $group->id)); - /** @var \FireflyIII\Models\WebhookTrigger $trigger */ foreach ($webhook->webhookTriggers as $trigger) { /** @var MessageGeneratorInterface $engine */ @@ -164,7 +166,7 @@ class ShowController extends Controller $engine->setUser(auth()->user()); // tell the generator which trigger it should look for - $engine->setTrigger(WebhookTrigger::tryFrom((int)$trigger->key)); + $engine->setTrigger(WebhookTrigger::tryFrom((int) $trigger->key)); // tell the generator which objects to process $engine->setObjects(new Collection()->push($group)); // set the webhook to trigger @@ -173,7 +175,6 @@ class ShowController extends Controller $engine->generateMessages(); } - // trigger event to send them: Log::debug('send event RequestedSendWebhookMessages from ShowController::triggerTransaction()'); event(new RequestedSendWebhookMessages()); diff --git a/app/Api/V1/Controllers/Webhook/StoreController.php b/app/Api/V1/Controllers/Webhook/StoreController.php index 4f46d23ebc..88d3f74ff8 100644 --- a/app/Api/V1/Controllers/Webhook/StoreController.php +++ b/app/Api/V1/Controllers/Webhook/StoreController.php @@ -27,6 +27,7 @@ namespace FireflyIII\Api\V1\Controllers\Webhook; use FireflyIII\Api\V1\Controllers\Controller; use FireflyIII\Api\V1\Requests\Models\Webhook\CreateRequest; use FireflyIII\Repositories\Webhook\WebhookRepositoryInterface; +use FireflyIII\Support\Facades\FireflyConfig; use FireflyIII\Support\JsonApi\Enrichments\WebhookEnrichment; use FireflyIII\Transformers\WebhookTransformer; use FireflyIII\User; @@ -34,7 +35,6 @@ use Illuminate\Http\JsonResponse; use Illuminate\Support\Facades\Log; use League\Fractal\Resource\Item; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; -use FireflyIII\Support\Facades\FireflyConfig; /** * Class StoreController @@ -42,19 +42,18 @@ use FireflyIII\Support\Facades\FireflyConfig; class StoreController extends Controller { public const string RESOURCE_KEY = 'webhooks'; + private WebhookRepositoryInterface $repository; public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(WebhookRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(WebhookRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -63,24 +62,23 @@ class StoreController extends Controller */ public function store(CreateRequest $request): JsonResponse { - $data = $request->getData(); + $data = $request->getData(); if (false === FireflyConfig::get('allow_webhooks', config('firefly.allow_webhooks'))->data) { Log::channel('audit')->info('User tries to store new webhook, but webhooks are DISABLED.', $data); throw new NotFoundHttpException('Webhooks are not enabled.'); } - $webhook = $this->repository->store($data); + $webhook = $this->repository->store($data); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new WebhookEnrichment(); + $admin = auth()->user(); + $enrichment = new WebhookEnrichment(); $enrichment->setUser($admin); - $webhook = $enrichment->enrichSingle($webhook); + $webhook = $enrichment->enrichSingle($webhook); - - $manager = $this->getManager(); + $manager = $this->getManager(); Log::channel('audit')->info('User stores new webhook', $data); @@ -88,7 +86,7 @@ class StoreController extends Controller $transformer = app(WebhookTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($webhook, $transformer, 'webhooks'); + $resource = new Item($webhook, $transformer, 'webhooks'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Controllers/Webhook/SubmitController.php b/app/Api/V1/Controllers/Webhook/SubmitController.php index 0d528820bc..6edd2304c2 100644 --- a/app/Api/V1/Controllers/Webhook/SubmitController.php +++ b/app/Api/V1/Controllers/Webhook/SubmitController.php @@ -43,14 +43,12 @@ class SubmitController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(WebhookRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(WebhookRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** diff --git a/app/Api/V1/Controllers/Webhook/UpdateController.php b/app/Api/V1/Controllers/Webhook/UpdateController.php index 15e39c02f0..6fb658844f 100644 --- a/app/Api/V1/Controllers/Webhook/UpdateController.php +++ b/app/Api/V1/Controllers/Webhook/UpdateController.php @@ -28,6 +28,7 @@ use FireflyIII\Api\V1\Controllers\Controller; use FireflyIII\Api\V1\Requests\Models\Webhook\UpdateRequest; use FireflyIII\Models\Webhook; use FireflyIII\Repositories\Webhook\WebhookRepositoryInterface; +use FireflyIII\Support\Facades\FireflyConfig; use FireflyIII\Support\JsonApi\Enrichments\WebhookEnrichment; use FireflyIII\Transformers\WebhookTransformer; use FireflyIII\User; @@ -35,7 +36,6 @@ use Illuminate\Http\JsonResponse; use Illuminate\Support\Facades\Log; use League\Fractal\Resource\Item; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; -use FireflyIII\Support\Facades\FireflyConfig; /** * Class UpdateController @@ -47,14 +47,12 @@ class UpdateController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(WebhookRepositoryInterface::class); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + $this->repository = app(WebhookRepositoryInterface::class); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -63,24 +61,24 @@ class UpdateController extends Controller */ public function update(Webhook $webhook, UpdateRequest $request): JsonResponse { - $data = $request->getData(); + $data = $request->getData(); if (false === FireflyConfig::get('allow_webhooks', config('firefly.allow_webhooks'))->data) { Log::channel('audit')->info(sprintf('User tries to update webhook #%d, but webhooks are DISABLED.', $webhook->id), $data); throw new NotFoundHttpException('Webhooks are not enabled.'); } - $webhook = $this->repository->update($webhook, $data); - $manager = $this->getManager(); + $webhook = $this->repository->update($webhook, $data); + $manager = $this->getManager(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new WebhookEnrichment(); + $admin = auth()->user(); + $enrichment = new WebhookEnrichment(); $enrichment->setUser($admin); /** @var Webhook $webhook */ - $webhook = $enrichment->enrichSingle($webhook); + $webhook = $enrichment->enrichSingle($webhook); Log::channel('audit')->info(sprintf('User updates webhook #%d', $webhook->id), $data); @@ -88,7 +86,7 @@ class UpdateController extends Controller $transformer = app(WebhookTransformer::class); $transformer->setParameters($this->parameters); - $resource = new Item($webhook, $transformer, 'webhooks'); + $resource = new Item($webhook, $transformer, 'webhooks'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', self::CONTENT_TYPE); } diff --git a/app/Api/V1/Requests/AggregateFormRequest.php b/app/Api/V1/Requests/AggregateFormRequest.php index 99891a4c98..152ac7ab16 100644 --- a/app/Api/V1/Requests/AggregateFormRequest.php +++ b/app/Api/V1/Requests/AggregateFormRequest.php @@ -23,11 +23,11 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Requests; -use Override; use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; +use Override; use RuntimeException; abstract class AggregateFormRequest extends ApiRequest @@ -41,8 +41,15 @@ abstract class AggregateFormRequest extends ApiRequest abstract protected function getRequests(): array; #[Override] - public function initialize(array $query = [], array $request = [], array $attributes = [], array $cookies = [], array $files = [], array $server = [], $content = null): void - { + public function initialize( + array $query = [], + array $request = [], + array $attributes = [], + array $cookies = [], + array $files = [], + array $server = [], + $content = null + ): void { parent::initialize($query, $request, $attributes, $cookies, $files, $server, $content); // instantiate all subrequests and share current requests' bags with them @@ -50,21 +57,21 @@ abstract class AggregateFormRequest extends ApiRequest /** @var array|string $config */ foreach ($this->getRequests() as $config) { - $requestClass = is_array($config) ? array_shift($config) : $config; + $requestClass = is_array($config) ? array_shift($config) : $config; if (!is_a($requestClass, Request::class, true)) { throw new RuntimeException('getRequests() must return class-strings of subclasses of Request'); } Log::debug(sprintf('Initializing subrequest %s', $requestClass)); - $instance = $this->requests[] = new $requestClass(); - $instance->request = $this->request; - $instance->query = $this->query; + $instance = $this->requests[] = new $requestClass(); + $instance->request = $this->request; + $instance->query = $this->query; $instance->attributes = $this->attributes; - $instance->cookies = $this->cookies; - $instance->files = $this->files; - $instance->server = $this->server; - $instance->headers = $this->headers; + $instance->cookies = $this->cookies; + $instance->files = $this->files; + $instance->server = $this->server; + $instance->headers = $this->headers; if ($instance instanceof ApiRequest) { $instance->handleConfig(is_array($config) ? $config : []); @@ -78,13 +85,8 @@ abstract class AggregateFormRequest extends ApiRequest // check all subrequests for rules and combine them return array_reduce( $this->requests, - static fn (array $rules, FormRequest $request): array => $rules - + ( - method_exists($request, 'rules') - ? $request->rules() - : [] - ), - [], + static fn(array $rules, FormRequest $request): array => $rules + (method_exists($request, 'rules') ? $request->rules() : []), + [] ); } diff --git a/app/Api/V1/Requests/Autocomplete/AutocompleteApiRequest.php b/app/Api/V1/Requests/Autocomplete/AutocompleteApiRequest.php index 448d4eb895..1b1b8d7ada 100644 --- a/app/Api/V1/Requests/Autocomplete/AutocompleteApiRequest.php +++ b/app/Api/V1/Requests/Autocomplete/AutocompleteApiRequest.php @@ -1,6 +1,7 @@ Account::class], [ObjectTypeApiRequest::class, 'object_type' => Account::class], - QueryRequest::class, + QueryRequest::class ]; } } diff --git a/app/Api/V1/Requests/Autocomplete/AutocompleteRequest.php b/app/Api/V1/Requests/Autocomplete/AutocompleteRequest.php index 5dd6e8143e..df2c274cd1 100644 --- a/app/Api/V1/Requests/Autocomplete/AutocompleteRequest.php +++ b/app/Api/V1/Requests/Autocomplete/AutocompleteRequest.php @@ -50,19 +50,13 @@ class AutocompleteRequest extends FormRequest // remove 'initial balance' from allowed types. its internal $array = array_diff($array, [AccountTypeEnum::INITIAL_BALANCE->value, AccountTypeEnum::RECONCILIATION->value]); - $date = $this->getCarbonDate('date') ?? today(config('app.timezone')); + $date = $this->getCarbonDate('date') ?? today(config('app.timezone')); - return [ - 'types' => $array, - 'query' => $this->convertString('query'), - 'date' => $date->endOfDay(), - ]; + return ['types' => $array, 'query' => $this->convertString('query'), 'date' => $date->endOfDay()]; } public function rules(): array { - return [ - 'date' => 'date|after:1970-01-02|before:2038-01-17', - ]; + return ['date' => 'date|after:1970-01-02|before:2038-01-17']; } } diff --git a/app/Api/V1/Requests/Autocomplete/AutocompleteTransactionApiRequest.php b/app/Api/V1/Requests/Autocomplete/AutocompleteTransactionApiRequest.php index a6255a4595..4bf484771f 100644 --- a/app/Api/V1/Requests/Autocomplete/AutocompleteTransactionApiRequest.php +++ b/app/Api/V1/Requests/Autocomplete/AutocompleteTransactionApiRequest.php @@ -1,6 +1,7 @@ Account::class], [ObjectTypeApiRequest::class, 'object_type' => Transaction::class], - QueryRequest::class, + QueryRequest::class ]; } } diff --git a/app/Api/V1/Requests/Chart/ChartRequest.php b/app/Api/V1/Requests/Chart/ChartRequest.php index 83b666943d..e9a9bf5294 100644 --- a/app/Api/V1/Requests/Chart/ChartRequest.php +++ b/app/Api/V1/Requests/Chart/ChartRequest.php @@ -24,11 +24,11 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Requests\Chart; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Enums\UserRoleEnum; use FireflyIII\Support\Http\Api\ValidatesUserGroupTrait; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -50,7 +50,7 @@ class ChartRequest extends FormRequest 'end' => $this->convertDateTime('end')?->endOfDay(), 'preselected' => $this->convertString('preselected', 'empty'), 'period' => $this->convertString('period', '1M'), - 'accounts' => $this->arrayFromValue($this->get('accounts')), + 'accounts' => $this->arrayFromValue($this->get('accounts')) ]; } @@ -65,26 +65,23 @@ class ChartRequest extends FormRequest 'preselected' => sprintf('nullable|in:%s', implode(',', config('firefly.preselected_accounts'))), 'period' => sprintf('nullable|in:%s', implode(',', config('firefly.valid_view_ranges'))), 'accounts' => 'nullable|array', - 'accounts.*' => 'exists:accounts,id', + 'accounts.*' => 'exists:accounts,id' ]; - } public function withValidator(Validator $validator): void { - $validator->after( - static function (Validator $validator): void { - // validate transaction query data. - $data = $validator->getData(); - if (!array_key_exists('accounts', $data)) { - // $validator->errors()->add('accounts', trans('validation.filled', ['attribute' => 'accounts'])); - return; - } - if (!is_array($data['accounts'])) { - $validator->errors()->add('accounts', trans('validation.filled', ['attribute' => 'accounts'])); - } + $validator->after(static function (Validator $validator): void { + // validate transaction query data. + $data = $validator->getData(); + if (!array_key_exists('accounts', $data)) { + // $validator->errors()->add('accounts', trans('validation.filled', ['attribute' => 'accounts'])); + return; } - ); + if (!is_array($data['accounts'])) { + $validator->errors()->add('accounts', trans('validation.filled', ['attribute' => 'accounts'])); + } + }); if ($validator->fails()) { Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray()); } diff --git a/app/Api/V1/Requests/Data/Bulk/MoveTransactionsRequest.php b/app/Api/V1/Requests/Data/Bulk/MoveTransactionsRequest.php index 8731e354aa..bc02ffec68 100644 --- a/app/Api/V1/Requests/Data/Bulk/MoveTransactionsRequest.php +++ b/app/Api/V1/Requests/Data/Bulk/MoveTransactionsRequest.php @@ -24,10 +24,10 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Requests\Data\Bulk; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -41,10 +41,7 @@ class MoveTransactionsRequest extends FormRequest public function getAll(): array { - return [ - 'original_account' => $this->convertInteger('original_account'), - 'destination_account' => $this->convertInteger('destination_account'), - ]; + return ['original_account' => $this->convertInteger('original_account'), 'destination_account' => $this->convertInteger('destination_account')]; } /** @@ -54,7 +51,7 @@ class MoveTransactionsRequest extends FormRequest { return [ 'original_account' => 'required|different:destination_account|belongsToUser:accounts,id', - 'destination_account' => 'required|different:original_account|belongsToUser:accounts,id', + 'destination_account' => 'required|different:original_account|belongsToUser:accounts,id' ]; } @@ -64,15 +61,13 @@ class MoveTransactionsRequest extends FormRequest */ public function withValidator(Validator $validator): void { - $validator->after( - function (Validator $validator): void { - // validate start before end only if both are there. - $data = $validator->getData(); - if (array_key_exists('original_account', $data) && array_key_exists('destination_account', $data)) { - $this->validateMove($validator); - } + $validator->after(function (Validator $validator): void { + // validate start before end only if both are there. + $data = $validator->getData(); + if (array_key_exists('original_account', $data) && array_key_exists('destination_account', $data)) { + $this->validateMove($validator); } - ); + }); if ($validator->fails()) { Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray()); } @@ -80,11 +75,11 @@ class MoveTransactionsRequest extends FormRequest private function validateMove(Validator $validator): void { - $data = $validator->getData(); - $repository = app(AccountRepositoryInterface::class); + $data = $validator->getData(); + $repository = app(AccountRepositoryInterface::class); $repository->setUser(auth()->user()); - $original = $repository->find((int) $data['original_account']); - $destination = $repository->find((int) $data['destination_account']); + $original = $repository->find((int) $data['original_account']); + $destination = $repository->find((int) $data['destination_account']); // not the same type: if ($original->accountType->type !== $destination->accountType->type) { diff --git a/app/Api/V1/Requests/Data/Bulk/TransactionRequest.php b/app/Api/V1/Requests/Data/Bulk/TransactionRequest.php index 4be7ceb07d..3238e24f89 100644 --- a/app/Api/V1/Requests/Data/Bulk/TransactionRequest.php +++ b/app/Api/V1/Requests/Data/Bulk/TransactionRequest.php @@ -24,12 +24,12 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Requests\Data\Bulk; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Enums\ClauseType; use FireflyIII\Rules\IsValidBulkClause; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; use FireflyIII\Validation\Api\Data\Bulk\ValidatesBulkTransactionQuery; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; use JsonException; @@ -50,9 +50,7 @@ class TransactionRequest extends FormRequest $data = []; try { - $data = [ - 'query' => json_decode($this->get('query'), true, 8, JSON_THROW_ON_ERROR), - ]; + $data = ['query' => json_decode($this->get('query'), true, 8, JSON_THROW_ON_ERROR)]; } catch (JsonException $e) { // don't really care. the validation should catch invalid json. Log::error($e->getMessage()); @@ -63,19 +61,15 @@ class TransactionRequest extends FormRequest public function rules(): array { - return [ - 'query' => ['required', 'min:1', 'max:255', 'json', new IsValidBulkClause(ClauseType::TRANSACTION)], - ]; + return ['query' => ['required', 'min:1', 'max:255', 'json', new IsValidBulkClause(ClauseType::TRANSACTION)]]; } public function withValidator(Validator $validator): void { - $validator->after( - function (Validator $validator): void { - // validate transaction query data. - $this->validateTransactionQuery($validator); - } - ); + $validator->after(function (Validator $validator): void { + // validate transaction query data. + $this->validateTransactionQuery($validator); + }); if ($validator->fails()) { Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray()); } diff --git a/app/Api/V1/Requests/Data/DestroyRequest.php b/app/Api/V1/Requests/Data/DestroyRequest.php index 082fb00adb..e1c1745393 100644 --- a/app/Api/V1/Requests/Data/DestroyRequest.php +++ b/app/Api/V1/Requests/Data/DestroyRequest.php @@ -49,13 +49,11 @@ class DestroyRequest extends FormRequest */ public function rules(): array { - $valid = 'budgets,bills,piggy_banks,rules,recurring,categories,tags,object_groups' - .',accounts,asset_accounts,expense_accounts,revenue_accounts,liabilities,transactions,withdrawals,deposits,transfers' - .',not_assets_liabilities'; + $valid = + 'budgets,bills,piggy_banks,rules,recurring,categories,tags,object_groups' + . ',accounts,asset_accounts,expense_accounts,revenue_accounts,liabilities,transactions,withdrawals,deposits,transfers' + . ',not_assets_liabilities'; - return [ - 'objects' => sprintf('required|max:255|min:1|string|in:%s', $valid), - 'unused' => 'in:true,false', - ]; + return ['objects' => sprintf('required|max:255|min:1|string|in:%s', $valid), 'unused' => 'in:true,false']; } } diff --git a/app/Api/V1/Requests/Data/Export/ExportRequest.php b/app/Api/V1/Requests/Data/Export/ExportRequest.php index 541529e2ed..6d7c4f6989 100644 --- a/app/Api/V1/Requests/Data/Export/ExportRequest.php +++ b/app/Api/V1/Requests/Data/Export/ExportRequest.php @@ -41,16 +41,16 @@ class ExportRequest extends FormRequest public function getAll(): array { - $result = [ + $result = [ 'start' => $this->getCarbonDate('start') ?? today(config('app.timezone'))->subYear(), 'end' => $this->getCarbonDate('end') ?? today(config('app.timezone')), - 'type' => $this->convertString('type'), + 'type' => $this->convertString('type') ]; - $parts = explode(',', $this->convertString('accounts')); - $repository = app(AccountRepositoryInterface::class); + $parts = explode(',', $this->convertString('accounts')); + $repository = app(AccountRepositoryInterface::class); $repository->setUser(auth()->user()); - $accounts = new Collection(); + $accounts = new Collection(); foreach ($parts as $part) { $accountId = (int) $part; if (0 !== $accountId) { @@ -70,11 +70,6 @@ class ExportRequest extends FormRequest */ public function rules(): array { - return [ - 'type' => 'in:csv', - 'accounts' => 'min:1|max:32768', - 'start' => 'date|before:end', - 'end' => 'date|after:start', - ]; + return ['type' => 'in:csv', 'accounts' => 'min:1|max:32768', 'start' => 'date|before:end', 'end' => 'date|after:start']; } } diff --git a/app/Api/V1/Requests/Data/SameDateRequest.php b/app/Api/V1/Requests/Data/SameDateRequest.php index 49709b1b4d..02285dcbf4 100644 --- a/app/Api/V1/Requests/Data/SameDateRequest.php +++ b/app/Api/V1/Requests/Data/SameDateRequest.php @@ -45,10 +45,7 @@ class SameDateRequest extends FormRequest */ public function getAll(): array { - return [ - 'start' => $this->getCarbonDate('start'), - 'end' => $this->getCarbonDate('end'), - ]; + return ['start' => $this->getCarbonDate('start'), 'end' => $this->getCarbonDate('end')]; } /** @@ -56,9 +53,6 @@ class SameDateRequest extends FormRequest */ public function rules(): array { - return [ - 'start' => 'required|date', - 'end' => 'required|date|after_or_equal:start', - ]; + return ['start' => 'required|date', 'end' => 'required|date|after_or_equal:start']; } } diff --git a/app/Api/V1/Requests/DateRangeRequest.php b/app/Api/V1/Requests/DateRangeRequest.php index afaddc5bc1..f948e75b56 100644 --- a/app/Api/V1/Requests/DateRangeRequest.php +++ b/app/Api/V1/Requests/DateRangeRequest.php @@ -31,23 +31,21 @@ class DateRangeRequest extends ApiRequest { return [ 'start' => sprintf('date|after:1970-01-02|before:2038-01-17|before:end|required_with:end|%s', $this->required), - 'end' => sprintf('date|after:1970-01-02|before:2038-01-17|after:start|required_with:start|%s', $this->required), + 'end' => sprintf('date|after:1970-01-02|before:2038-01-17|after:start|required_with:start|%s', $this->required) ]; } public function withValidator(Validator $validator): void { - $validator->after( - function (Validator $validator): void { - if ($validator->failed()) { - return; - } - $start = $this->getCarbonDate('start')?->startOfDay(); - $end = $this->getCarbonDate('end')?->endOfDay(); - - $this->attributes->set('start', $start); - $this->attributes->set('end', $end); + $validator->after(function (Validator $validator): void { + if ($validator->failed()) { + return; } - ); + $start = $this->getCarbonDate('start')?->startOfDay(); + $end = $this->getCarbonDate('end')?->endOfDay(); + + $this->attributes->set('start', $start); + $this->attributes->set('end', $end); + }); } } diff --git a/app/Api/V1/Requests/DateRequest.php b/app/Api/V1/Requests/DateRequest.php index 8344164845..e60b98472b 100644 --- a/app/Api/V1/Requests/DateRequest.php +++ b/app/Api/V1/Requests/DateRequest.php @@ -23,36 +23,32 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Requests; -use Illuminate\Contracts\Validation\Validator; use Carbon\Carbon; +use Illuminate\Contracts\Validation\Validator; class DateRequest extends ApiRequest { public function rules(): array { - return [ - 'date' => 'date|after:1970-01-02|before:2038-01-17|'.$this->required, - ]; + return ['date' => 'date|after:1970-01-02|before:2038-01-17|' . $this->required]; } public function withValidator(Validator $validator): void { - $validator->after( - function (Validator $validator): void { - if ($validator->failed()) { - return; - } - $date = $this->getCarbonDate('date')?->endOfDay(); - - // if we also have a range, date must be in that range - $start = $this->attributes->get('start'); - $end = $this->attributes->get('end'); - if ($date instanceof Carbon && $start instanceof Carbon && $end instanceof Carbon && !$date->between($start, $end)) { - $validator->errors()->add('date', (string)trans('validation.between_date')); - } - - $this->attributes->set('date', $date); + $validator->after(function (Validator $validator): void { + if ($validator->failed()) { + return; } - ); + $date = $this->getCarbonDate('date')?->endOfDay(); + + // if we also have a range, date must be in that range + $start = $this->attributes->get('start'); + $end = $this->attributes->get('end'); + if ($date instanceof Carbon && $start instanceof Carbon && $end instanceof Carbon && !$date->between($start, $end)) { + $validator->errors()->add('date', (string) trans('validation.between_date')); + } + + $this->attributes->set('date', $date); + }); } } diff --git a/app/Api/V1/Requests/Generic/ObjectTypeApiRequest.php b/app/Api/V1/Requests/Generic/ObjectTypeApiRequest.php index 7780376b7f..fe2fd09e2c 100644 --- a/app/Api/V1/Requests/Generic/ObjectTypeApiRequest.php +++ b/app/Api/V1/Requests/Generic/ObjectTypeApiRequest.php @@ -1,6 +1,7 @@ objectType) { $rule = new IsValidAccountTypeList(); } if (Transaction::class === $this->objectType) { $rule = new IsValidTransactionTypeList(); } - $rules = [ - 'types' => [$rule], - ]; + $rules = ['types' => [$rule]]; if ('' !== $this->required) { $rules['types'][] = $this->required; } @@ -75,34 +74,36 @@ class ObjectTypeApiRequest extends ApiRequest public function withValidator(Validator $validator): void { - $validator->after( - function (Validator $validator): void { - if ($validator->failed()) { - return; - } - $type = $this->convertString('types', 'all'); - $this->attributes->set('type', $type); - - switch ($this->objectType) { - default: - $this->attributes->set('types', []); - - // no break - case Account::class: - $types = $this->mapAccountTypes($type); - - // remove system account types because autocomplete doesn't need them. - $types = array_values(array_diff($types, [AccountTypeEnum::INITIAL_BALANCE->value, AccountTypeEnum::RECONCILIATION->value, AccountTypeEnum::LIABILITY_CREDIT->value])); - $this->attributes->set('types', $types); - - break; - - case Transaction::class: - $this->attributes->set('types', $this->mapTransactionTypes($type)); - - break; - } + $validator->after(function (Validator $validator): void { + if ($validator->failed()) { + return; } - ); + $type = $this->convertString('types', 'all'); + $this->attributes->set('type', $type); + + switch ($this->objectType) { + default: + $this->attributes->set('types', []); + + // no break + case Account::class: + $types = $this->mapAccountTypes($type); + + // remove system account types because autocomplete doesn't need them. + $types = array_values(array_diff($types, [ + AccountTypeEnum::INITIAL_BALANCE->value, + AccountTypeEnum::RECONCILIATION->value, + AccountTypeEnum::LIABILITY_CREDIT->value + ])); + $this->attributes->set('types', $types); + + break; + + case Transaction::class: + $this->attributes->set('types', $this->mapTransactionTypes($type)); + + break; + } + }); } } diff --git a/app/Api/V1/Requests/Generic/PaginationDateRangeRequest.php b/app/Api/V1/Requests/Generic/PaginationDateRangeRequest.php index 21a50f15fb..6c3b363031 100644 --- a/app/Api/V1/Requests/Generic/PaginationDateRangeRequest.php +++ b/app/Api/V1/Requests/Generic/PaginationDateRangeRequest.php @@ -1,6 +1,7 @@ Transaction::class], - [PaginationRequest::class, 'sort_class' => Transaction::class], + [PaginationRequest::class, 'sort_class' => Transaction::class] ]; } } diff --git a/app/Api/V1/Requests/Generic/QueryRequest.php b/app/Api/V1/Requests/Generic/QueryRequest.php index 0b01399e33..51eeb8093a 100644 --- a/app/Api/V1/Requests/Generic/QueryRequest.php +++ b/app/Api/V1/Requests/Generic/QueryRequest.php @@ -1,6 +1,7 @@ sprintf('min:0|max:50|%s', $this->required), - ]; + return ['query' => sprintf('min:0|max:50|%s', $this->required)]; } public function withValidator(Validator $validator): void { - $validator->after( - function (Validator $validator): void { - if ($validator->failed()) { - return; - } - $query = $this->convertString('query'); - $this->attributes->set('query', $query); + $validator->after(function (Validator $validator): void { + if ($validator->failed()) { + return; } - ); + $query = $this->convertString('query'); + $this->attributes->set('query', $query); + }); } } diff --git a/app/Api/V1/Requests/Generic/SingleDateRequest.php b/app/Api/V1/Requests/Generic/SingleDateRequest.php index b7fe750a5f..d2fdd5076a 100644 --- a/app/Api/V1/Requests/Generic/SingleDateRequest.php +++ b/app/Api/V1/Requests/Generic/SingleDateRequest.php @@ -54,8 +54,6 @@ class SingleDateRequest extends FormRequest */ public function rules(): array { - return [ - 'date' => 'required|date|after:1970-01-02|before:2038-01-17', - ]; + return ['date' => 'required|date|after:1970-01-02|before:2038-01-17']; } } diff --git a/app/Api/V1/Requests/Insight/GenericRequest.php b/app/Api/V1/Requests/Insight/GenericRequest.php index 4e98c50b5e..edfbcd11df 100644 --- a/app/Api/V1/Requests/Insight/GenericRequest.php +++ b/app/Api/V1/Requests/Insight/GenericRequest.php @@ -56,10 +56,7 @@ class GenericRequest extends FormRequest */ public function getAll(): array { - return [ - 'start' => $this->getCarbonDate('start'), - 'end' => $this->getCarbonDate('end'), - ]; + return ['start' => $this->getCarbonDate('start'), 'end' => $this->getCarbonDate('end')]; } public function getAssetAccounts(): Collection @@ -70,7 +67,11 @@ class GenericRequest extends FormRequest /** @var Account $account */ foreach ($this->accounts as $account) { $type = $account->accountType->type; - if (in_array($type, [AccountTypeEnum::ASSET->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value], true)) { + if (in_array( + $type, + [AccountTypeEnum::ASSET->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value], + true + )) { $return->push($account); } } @@ -85,7 +86,7 @@ class GenericRequest extends FormRequest } $repository = app(AccountRepositoryInterface::class); $repository->setUser(auth()->user()); - $array = $this->get('accounts'); + $array = $this->get('accounts'); if (is_array($array)) { foreach ($array as $accountId) { $accountId = (int) $accountId; @@ -111,7 +112,7 @@ class GenericRequest extends FormRequest } $repository = app(BillRepositoryInterface::class); $repository->setUser(auth()->user()); - $array = $this->get('bills'); + $array = $this->get('bills'); if (is_array($array)) { foreach ($array as $billId) { $billId = (int) $billId; @@ -137,7 +138,7 @@ class GenericRequest extends FormRequest } $repository = app(BudgetRepositoryInterface::class); $repository->setUser(auth()->user()); - $array = $this->get('budgets'); + $array = $this->get('budgets'); if (is_array($array)) { foreach ($array as $budgetId) { $budgetId = (int) $budgetId; @@ -163,7 +164,7 @@ class GenericRequest extends FormRequest } $repository = app(CategoryRepositoryInterface::class); $repository->setUser(auth()->user()); - $array = $this->get('categories'); + $array = $this->get('categories'); if (is_array($array)) { foreach ($array as $categoryId) { $categoryId = (int) $categoryId; @@ -237,7 +238,7 @@ class GenericRequest extends FormRequest } $repository = app(TagRepositoryInterface::class); $repository->setUser(auth()->user()); - $array = $this->get('tags'); + $array = $this->get('tags'); if (is_array($array)) { foreach ($array as $tagId) { $tagId = (int) $tagId; @@ -255,15 +256,12 @@ class GenericRequest extends FormRequest public function rules(): array { // this is cheating, but it works to initialize the collections. - $this->accounts = new Collection(); - $this->budgets = new Collection(); + $this->accounts = new Collection(); + $this->budgets = new Collection(); $this->categories = new Collection(); - $this->bills = new Collection(); - $this->tags = new Collection(); + $this->bills = new Collection(); + $this->tags = new Collection(); - return [ - 'start' => 'required|date', - 'end' => 'required|date|after_or_equal:start', - ]; + return ['start' => 'required|date', 'end' => 'required|date|after_or_equal:start']; } } diff --git a/app/Api/V1/Requests/Models/Account/AccountTypeApiRequest.php b/app/Api/V1/Requests/Models/Account/AccountTypeApiRequest.php index 3261423b11..27417b239e 100644 --- a/app/Api/V1/Requests/Models/Account/AccountTypeApiRequest.php +++ b/app/Api/V1/Requests/Models/Account/AccountTypeApiRequest.php @@ -1,6 +1,7 @@ sprintf('in:%s', implode(',', array_keys($this->types))), - ]; + return ['type' => sprintf('in:%s', implode(',', array_keys($this->types)))]; } public function withValidator(Validator $validator): void { - $validator->after( - function (Validator $validator): void { - if ($validator->failed()) { - return; - } - - $type = $this->convertString('type', 'all'); - $this->attributes->add([ - 'type' => $type, - 'types' => $this->mapAccountTypes($type), - ]); + $validator->after(function (Validator $validator): void { + if ($validator->failed()) { + return; } - ); + + $type = $this->convertString('type', 'all'); + $this->attributes->add(['type' => $type, 'types' => $this->mapAccountTypes($type)]); + }); } } diff --git a/app/Api/V1/Requests/Models/Account/AccountTypesApiRequest.php b/app/Api/V1/Requests/Models/Account/AccountTypesApiRequest.php index 03710a9bf3..45780f06ca 100644 --- a/app/Api/V1/Requests/Models/Account/AccountTypesApiRequest.php +++ b/app/Api/V1/Requests/Models/Account/AccountTypesApiRequest.php @@ -1,6 +1,7 @@ types))), - return [ - 'types' => new IsValidAccountTypeList(), - ]; + return ['types' => new IsValidAccountTypeList()]; } public function withValidator(Validator $validator): void { - $validator->after( - function (Validator $validator): void { - if ($validator->failed()) { - return; - } - $types = explode(',', $this->convertString('types', 'all')); - $result = []; - // split and find all types: - foreach ($types as $type) { - $result = array_merge($result, $this->mapAccountTypes($type)); - } - $result = array_unique($result); - $this->attributes->set('types', $result); + $validator->after(function (Validator $validator): void { + if ($validator->failed()) { + return; } - ); + $types = explode(',', $this->convertString('types', 'all')); + $result = []; + // split and find all types: + foreach ($types as $type) { + $result = array_merge($result, $this->mapAccountTypes($type)); + } + $result = array_unique($result); + $this->attributes->set('types', $result); + }); } } diff --git a/app/Api/V1/Requests/Models/Account/ShowRequest.php b/app/Api/V1/Requests/Models/Account/ShowRequest.php index 5f3b11a29b..4c7aa90dd1 100644 --- a/app/Api/V1/Requests/Models/Account/ShowRequest.php +++ b/app/Api/V1/Requests/Models/Account/ShowRequest.php @@ -1,6 +1,7 @@ Account::class], DateRangeRequest::class, DateRequest::class, - AccountTypeApiRequest::class, + AccountTypeApiRequest::class // [ObjectTypeApiRequest::class, 'object_type' => Account::class], ]; } diff --git a/app/Api/V1/Requests/Models/Account/StoreRequest.php b/app/Api/V1/Requests/Models/Account/StoreRequest.php index 3d04bb7cee..b05190d7d8 100644 --- a/app/Api/V1/Requests/Models/Account/StoreRequest.php +++ b/app/Api/V1/Requests/Models/Account/StoreRequest.php @@ -53,7 +53,7 @@ class StoreRequest extends FormRequest if (null !== $this->get('include_net_worth')) { $includeNetWorth = $this->boolean('include_net_worth'); } - $data = [ + $data = [ 'name' => $this->convertString('name'), 'active' => $active, 'include_net_worth' => $includeNetWorth, @@ -73,15 +73,15 @@ class StoreRequest extends FormRequest 'cc_monthly_payment_date' => $this->convertString('monthly_payment_date'), 'notes' => $this->stringWithNewlines('notes'), 'interest' => $this->convertString('interest'), - 'interest_period' => $this->convertString('interest_period'), + 'interest_period' => $this->convertString('interest_period') ]; // append location information. - $data = $this->appendLocationData($data, null); + $data = $this->appendLocationData($data, null); if ('liability' === $data['account_type_name'] || 'liabilities' === $data['account_type_name']) { - $data['account_type_name'] = $this->convertString('liability_type'); + $data['account_type_name'] = $this->convertString('liability_type'); $data['liability_direction'] = $this->convertString('liability_direction'); - $data['account_type_id'] = null; + $data['account_type_id'] = null; } return $data; @@ -98,7 +98,7 @@ class StoreRequest extends FormRequest $type = $this->convertString('type'); $rules = [ 'name' => 'required|max:1024|min:1|uniqueAccountForUser', - 'type' => 'required|max:1024|min:1|'.sprintf('in:%s', $types), + 'type' => 'required|max:1024|min:1|' . sprintf('in:%s', $types), 'iban' => ['iban', 'nullable', new UniqueIban(null, $type)], 'bic' => 'bic|nullable', 'account_number' => ['min:1', 'max:255', 'nullable', new UniqueAccountNumber(null, $type)], @@ -119,7 +119,7 @@ class StoreRequest extends FormRequest 'liability_direction' => 'nullable|required_if:type,liability|required_if:type,liabilities|in:credit,debit', 'interest' => 'min:0|max:100|numeric', 'interest_period' => sprintf('nullable|in:%s', implode(',', config('firefly.interest_periods'))), - 'notes' => 'min:0|max:32768', + 'notes' => 'min:0|max:32768' ]; return Location::requestRules($rules); diff --git a/app/Api/V1/Requests/Models/Account/UpdateRequest.php b/app/Api/V1/Requests/Models/Account/UpdateRequest.php index 5fb31b6fc8..fbd7b48b3e 100644 --- a/app/Api/V1/Requests/Models/Account/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/Account/UpdateRequest.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Requests\Models\Account; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Models\Account; use FireflyIII\Models\Location; use FireflyIII\Repositories\Account\AccountRepositoryInterface; @@ -34,6 +33,7 @@ use FireflyIII\Rules\UniqueIban; use FireflyIII\Support\Request\AppendsLocationData; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -71,7 +71,7 @@ class UpdateRequest extends FormRequest 'currency_code' => ['currency_code', 'convertString'], 'liability_direction' => ['liability_direction', 'convertString'], 'liability_amount' => ['liability_amount', 'convertString'], - 'liability_start_date' => ['liability_start_date', 'date'], + 'liability_start_date' => ['liability_start_date', 'date'] ]; $data = $this->getAllData($fields); @@ -89,7 +89,7 @@ class UpdateRequest extends FormRequest $types = implode(',', array_keys(config('firefly.subTitlesByIdentifier'))); $ccPaymentTypes = implode(',', array_keys(config('firefly.ccTypes'))); - $rules = [ + $rules = [ 'name' => sprintf('min:1|max:1024|uniqueAccountForUser:%d', $account->id), 'type' => sprintf('in:%s', $types), 'iban' => ['iban', 'nullable', new UniqueIban($account, $this->convertString('type'))], @@ -110,7 +110,7 @@ class UpdateRequest extends FormRequest 'liability_direction' => 'required_if:type,liability|in:credit,debit', 'interest' => 'required_if:type,liability|min:0|max:100|numeric', 'interest_period' => 'required_if:type,liability|in:daily,monthly,yearly', - 'notes' => 'min:0|max:32768', + 'notes' => 'min:0|max:32768' ]; return Location::requestRules($rules); @@ -121,28 +121,26 @@ class UpdateRequest extends FormRequest */ public function withValidator(Validator $validator): void { - $validator->after( - function (Validator $validator): void { - // validate start before end only if both are there. - $data = $validator->getData(); + $validator->after(function (Validator $validator): void { + // validate start before end only if both are there. + $data = $validator->getData(); - /** @var Account $account */ - $account = $this->route()->parameter('account'); + /** @var Account $account */ + $account = $this->route()->parameter('account'); - /** @var AccountRepositoryInterface $repository */ - $repository = app(AccountRepositoryInterface::class); - $currency = $repository->getAccountCurrency($account); + /** @var AccountRepositoryInterface $repository */ + $repository = app(AccountRepositoryInterface::class); + $currency = $repository->getAccountCurrency($account); - // how many piggies are attached? - $piggyBanks = $account->piggyBanks()->count(); - if ($piggyBanks > 0 && array_key_exists('currency_code', $data) && $data['currency_code'] !== $currency->code) { - $validator->errors()->add('currency_code', (string) trans('validation.piggy_no_change_currency')); - } - if ($piggyBanks > 0 && array_key_exists('currency_id', $data) && (int) $data['currency_id'] !== $currency->id) { - $validator->errors()->add('currency_id', (string) trans('validation.piggy_no_change_currency')); - } + // how many piggies are attached? + $piggyBanks = $account->piggyBanks()->count(); + if ($piggyBanks > 0 && array_key_exists('currency_code', $data) && $data['currency_code'] !== $currency->code) { + $validator->errors()->add('currency_code', (string) trans('validation.piggy_no_change_currency')); } - ); + if ($piggyBanks > 0 && array_key_exists('currency_id', $data) && (int) $data['currency_id'] !== $currency->id) { + $validator->errors()->add('currency_id', (string) trans('validation.piggy_no_change_currency')); + } + }); if ($validator->fails()) { Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray()); } diff --git a/app/Api/V1/Requests/Models/Attachment/StoreRequest.php b/app/Api/V1/Requests/Models/Attachment/StoreRequest.php index 5c4cc9bcc7..ca320ff7f3 100644 --- a/app/Api/V1/Requests/Models/Attachment/StoreRequest.php +++ b/app/Api/V1/Requests/Models/Attachment/StoreRequest.php @@ -47,7 +47,7 @@ class StoreRequest extends FormRequest 'title' => $this->convertString('title'), 'notes' => $this->stringWithNewlines('notes'), 'attachable_type' => $this->convertString('attachable_type'), - 'attachable_id' => $this->convertInteger('attachable_id'), + 'attachable_id' => $this->convertInteger('attachable_id') ]; } @@ -57,10 +57,7 @@ class StoreRequest extends FormRequest public function rules(): array { $models = config('firefly.valid_attachment_models'); - $models = array_map( - static fn (string $className): string => str_replace('FireflyIII\Models\\', '', $className), - $models - ); + $models = array_map(static fn(string $className): string => str_replace('FireflyIII\Models\\', '', $className), $models); $models = implode(',', $models); $model = $this->convertString('attachable_type'); @@ -69,7 +66,7 @@ class StoreRequest extends FormRequest 'title' => ['min:1', 'max:255'], 'notes' => 'min:1|max:32768', 'attachable_type' => sprintf('required|in:%s', $models), - 'attachable_id' => ['required', 'numeric', new IsValidAttachmentModel($model)], + 'attachable_id' => ['required', 'numeric', new IsValidAttachmentModel($model)] ]; } } diff --git a/app/Api/V1/Requests/Models/Attachment/UpdateRequest.php b/app/Api/V1/Requests/Models/Attachment/UpdateRequest.php index 236a884419..8af6e65235 100644 --- a/app/Api/V1/Requests/Models/Attachment/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/Attachment/UpdateRequest.php @@ -47,7 +47,7 @@ class UpdateRequest extends FormRequest 'title' => ['title', 'convertString'], 'notes' => ['notes', 'stringWithNewlines'], 'attachable_type' => ['attachable_type', 'convertString'], - 'attachable_id' => ['attachable_id', 'convertInteger'], + 'attachable_id' => ['attachable_id', 'convertInteger'] ]; return $this->getAllData($fields); @@ -59,10 +59,7 @@ class UpdateRequest extends FormRequest public function rules(): array { $models = config('firefly.valid_attachment_models'); - $models = array_map( - static fn (string $className): string => str_replace('FireflyIII\Models\\', '', $className), - $models - ); + $models = array_map(static fn(string $className): string => str_replace('FireflyIII\Models\\', '', $className), $models); $models = implode(',', $models); $model = $this->convertString('attachable_type'); @@ -71,7 +68,7 @@ class UpdateRequest extends FormRequest 'title' => ['min:1', 'max:255'], 'notes' => 'min:1|max:32768', 'attachable_type' => sprintf('in:%s', $models), - 'attachable_id' => ['numeric', new IsValidAttachmentModel($model)], + 'attachable_id' => ['numeric', new IsValidAttachmentModel($model)] ]; } } diff --git a/app/Api/V1/Requests/Models/AvailableBudget/Request.php b/app/Api/V1/Requests/Models/AvailableBudget/Request.php index 93b3f732b0..1cf970ffdf 100644 --- a/app/Api/V1/Requests/Models/AvailableBudget/Request.php +++ b/app/Api/V1/Requests/Models/AvailableBudget/Request.php @@ -24,11 +24,11 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Requests\Models\AvailableBudget; -use Illuminate\Contracts\Validation\Validator; use Carbon\Carbon; use FireflyIII\Rules\IsValidPositiveAmount; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -51,7 +51,7 @@ class Request extends FormRequest 'currency_code' => ['currency_code', 'convertString'], 'amount' => ['amount', 'convertString'], 'start' => ['start', 'date'], - 'end' => ['end', 'date'], + 'end' => ['end', 'date'] ]; return $this->getAllData($fields); @@ -67,7 +67,7 @@ class Request extends FormRequest 'currency_code' => 'min:3|max:51|exists:transaction_currencies,code', 'amount' => ['nullable', new IsValidPositiveAmount()], 'start' => 'date|after:1970-01-02|before:2038-01-17', - 'end' => 'date|after:1970-01-02|before:2038-01-17', + 'end' => 'date|after:1970-01-02|before:2038-01-17' ]; } @@ -76,19 +76,17 @@ class Request extends FormRequest */ public function withValidator(Validator $validator): void { - $validator->after( - static function (Validator $validator): void { - // validate start before end only if both are there. - $data = $validator->getData(); - if (array_key_exists('start', $data) && array_key_exists('end', $data)) { - $start = new Carbon($data['start']); - $end = new Carbon($data['end']); - if ($end->isBefore($start)) { - $validator->errors()->add('end', (string) trans('validation.date_after')); - } + $validator->after(static function (Validator $validator): void { + // validate start before end only if both are there. + $data = $validator->getData(); + if (array_key_exists('start', $data) && array_key_exists('end', $data)) { + $start = new Carbon($data['start']); + $end = new Carbon($data['end']); + if ($end->isBefore($start)) { + $validator->errors()->add('end', (string) trans('validation.date_after')); } } - ); + }); if ($validator->fails()) { Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray()); } diff --git a/app/Api/V1/Requests/Models/Bill/StoreRequest.php b/app/Api/V1/Requests/Models/Bill/StoreRequest.php index 7784ea6891..0328ec21fb 100644 --- a/app/Api/V1/Requests/Models/Bill/StoreRequest.php +++ b/app/Api/V1/Requests/Models/Bill/StoreRequest.php @@ -24,11 +24,11 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Requests\Models\Bill; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Rules\IsBoolean; use FireflyIII\Rules\IsValidPositiveAmount; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; use TypeError; @@ -63,7 +63,7 @@ class StoreRequest extends FormRequest 'order' => ['order', 'convertInteger'], 'notes' => ['notes', 'stringWithNewlines'], 'object_group_id' => ['object_group_id', 'convertInteger'], - 'object_group_title' => ['object_group_title', 'convertString'], + 'object_group_title' => ['object_group_title', 'convertString'] ]; return $this->getAllData($fields); @@ -86,7 +86,7 @@ class StoreRequest extends FormRequest 'repeat_freq' => 'in:weekly,monthly,quarterly,half-year,yearly|required', 'skip' => 'min:0|max:31|numeric', 'active' => [new IsBoolean()], - 'notes' => 'nullable|min:1|max:32768', + 'notes' => 'nullable|min:1|max:32768' ]; } @@ -95,33 +95,31 @@ class StoreRequest extends FormRequest */ public function withValidator(Validator $validator): void { - $validator->after( - static function (Validator $validator): void { - $data = $validator->getData(); - $min = $data['amount_min'] ?? '0'; - $max = $data['amount_max'] ?? '0'; + $validator->after(static function (Validator $validator): void { + $data = $validator->getData(); + $min = $data['amount_min'] ?? '0'; + $max = $data['amount_max'] ?? '0'; - if (is_array($min) || is_array($max)) { - $validator->errors()->add('amount_min', (string) trans('validation.generic_invalid')); - $validator->errors()->add('amount_max', (string) trans('validation.generic_invalid')); - $min = '0'; - $max = '0'; - } - $result = false; - - try { - $result = bccomp($min, $max); - } catch (ValueError $e) { - Log::error($e->getMessage()); - $validator->errors()->add('amount_min', (string) trans('validation.generic_invalid')); - $validator->errors()->add('amount_max', (string) trans('validation.generic_invalid')); - } - - if (1 === $result) { - $validator->errors()->add('amount_min', (string) trans('validation.amount_min_over_max')); - } + if (is_array($min) || is_array($max)) { + $validator->errors()->add('amount_min', (string) trans('validation.generic_invalid')); + $validator->errors()->add('amount_max', (string) trans('validation.generic_invalid')); + $min = '0'; + $max = '0'; } - ); + $result = false; + + try { + $result = bccomp($min, $max); + } catch (ValueError $e) { + Log::error($e->getMessage()); + $validator->errors()->add('amount_min', (string) trans('validation.generic_invalid')); + $validator->errors()->add('amount_max', (string) trans('validation.generic_invalid')); + } + + if (1 === $result) { + $validator->errors()->add('amount_min', (string) trans('validation.amount_min_over_max')); + } + }); $failed = false; try { diff --git a/app/Api/V1/Requests/Models/Bill/UpdateRequest.php b/app/Api/V1/Requests/Models/Bill/UpdateRequest.php index 149f5ad4b7..2bccda208b 100644 --- a/app/Api/V1/Requests/Models/Bill/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/Bill/UpdateRequest.php @@ -24,12 +24,12 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Requests\Models\Bill; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Models\Bill; use FireflyIII\Rules\IsBoolean; use FireflyIII\Rules\IsValidPositiveAmount; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -61,7 +61,7 @@ class UpdateRequest extends FormRequest 'order' => ['order', 'convertInteger'], 'notes' => ['notes', 'stringWithNewlines'], 'object_group_id' => ['object_group_id', 'convertInteger'], - 'object_group_title' => ['object_group_title', 'convertString'], + 'object_group_title' => ['object_group_title', 'convertString'] ]; return $this->getAllData($fields); @@ -87,7 +87,7 @@ class UpdateRequest extends FormRequest 'repeat_freq' => 'in:weekly,monthly,quarterly,half-year,yearly', 'skip' => 'min:0|max:31|numeric', 'active' => [new IsBoolean()], - 'notes' => 'min:1|max:32768', + 'notes' => 'min:1|max:32768' ]; } @@ -96,19 +96,17 @@ class UpdateRequest extends FormRequest */ public function withValidator(Validator $validator): void { - $validator->after( - static function (Validator $validator): void { - $data = $validator->getData(); - if (array_key_exists('amount_min', $data) && array_key_exists('amount_max', $data)) { - $min = $data['amount_min'] ?? '0'; - $max = $data['amount_max'] ?? '0'; + $validator->after(static function (Validator $validator): void { + $data = $validator->getData(); + if (array_key_exists('amount_min', $data) && array_key_exists('amount_max', $data)) { + $min = $data['amount_min'] ?? '0'; + $max = $data['amount_max'] ?? '0'; - if (1 === bccomp($min, $max)) { - $validator->errors()->add('amount_min', (string) trans('validation.amount_min_over_max')); - } + if (1 === bccomp($min, $max)) { + $validator->errors()->add('amount_min', (string) trans('validation.amount_min_over_max')); } } - ); + }); if ($validator->fails()) { Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray()); } diff --git a/app/Api/V1/Requests/Models/Budget/StoreRequest.php b/app/Api/V1/Requests/Models/Budget/StoreRequest.php index 27fc63e405..86f0e6df03 100644 --- a/app/Api/V1/Requests/Models/Budget/StoreRequest.php +++ b/app/Api/V1/Requests/Models/Budget/StoreRequest.php @@ -24,12 +24,12 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Requests\Models\Budget; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Rules\IsBoolean; use FireflyIII\Rules\IsValidPositiveAmount; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; use FireflyIII\Validation\AutoBudget\ValidatesAutoBudgetRequest; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -48,20 +48,20 @@ class StoreRequest extends FormRequest public function getAll(): array { $fields = [ - 'name' => ['name', 'convertString'], - 'active' => ['active', 'boolean'], - 'order' => ['active', 'convertInteger'], - 'notes' => ['notes', 'convertString'], + 'name' => ['name', 'convertString'], + 'active' => ['active', 'boolean'], + 'order' => ['active', 'convertInteger'], + 'notes' => ['notes', 'convertString'], // auto budget currency: - 'currency_id' => ['auto_budget_currency_id', 'convertInteger'], - 'currency_code' => ['auto_budget_currency_code', 'convertString'], - 'auto_budget_type' => ['auto_budget_type', 'convertString'], - 'auto_budget_amount' => ['auto_budget_amount', 'convertString'], - 'auto_budget_period' => ['auto_budget_period', 'convertString'], + 'currency_id' => ['auto_budget_currency_id', 'convertInteger'], + 'currency_code' => ['auto_budget_currency_code', 'convertString'], + 'auto_budget_type' => ['auto_budget_type', 'convertString'], + 'auto_budget_amount' => ['auto_budget_amount', 'convertString'], + 'auto_budget_period' => ['auto_budget_period', 'convertString'], // webhooks - 'fire_webhooks' => ['fire_webhooks', 'boolean'], + 'fire_webhooks' => ['fire_webhooks', 'boolean'] ]; return $this->getAllData($fields); @@ -73,18 +73,23 @@ class StoreRequest extends FormRequest public function rules(): array { return [ - 'name' => 'required|min:1|max:255|uniqueObjectForUser:budgets,name', - 'active' => [new IsBoolean()], - 'currency_id' => 'exists:transaction_currencies,id', - 'currency_code' => 'exists:transaction_currencies,code', - 'notes' => 'nullable|min:1|max:32768', + 'name' => 'required|min:1|max:255|uniqueObjectForUser:budgets,name', + 'active' => [new IsBoolean()], + 'currency_id' => 'exists:transaction_currencies,id', + 'currency_code' => 'exists:transaction_currencies,code', + 'notes' => 'nullable|min:1|max:32768', // auto budget info - 'auto_budget_type' => 'in:reset,rollover,adjusted,none', - 'auto_budget_amount' => ['required_if:auto_budget_type,reset', 'required_if:auto_budget_type,rollover', 'required_if:auto_budget_type,adjusted', new IsValidPositiveAmount()], - 'auto_budget_period' => 'in:daily,weekly,monthly,quarterly,half_year,yearly|required_if:auto_budget_type,reset|required_if:auto_budget_type,rollover|required_if:auto_budget_type,adjusted', + 'auto_budget_type' => 'in:reset,rollover,adjusted,none', + 'auto_budget_amount' => [ + 'required_if:auto_budget_type,reset', + 'required_if:auto_budget_type,rollover', + 'required_if:auto_budget_type,adjusted', + new IsValidPositiveAmount() + ], + 'auto_budget_period' => 'in:daily,weekly,monthly,quarterly,half_year,yearly|required_if:auto_budget_type,reset|required_if:auto_budget_type,rollover|required_if:auto_budget_type,adjusted', // webhooks - 'fire_webhooks' => [new IsBoolean()], + 'fire_webhooks' => [new IsBoolean()] ]; } @@ -93,12 +98,10 @@ class StoreRequest extends FormRequest */ public function withValidator(Validator $validator): void { - $validator->after( - function (Validator $validator): void { - // validate all account info - $this->validateAutoBudgetAmount($validator); - } - ); + $validator->after(function (Validator $validator): void { + // validate all account info + $this->validateAutoBudgetAmount($validator); + }); if ($validator->fails()) { Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray()); } diff --git a/app/Api/V1/Requests/Models/Budget/UpdateRequest.php b/app/Api/V1/Requests/Models/Budget/UpdateRequest.php index 1048aeb3d1..a2b8286602 100644 --- a/app/Api/V1/Requests/Models/Budget/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/Budget/UpdateRequest.php @@ -24,13 +24,13 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Requests\Models\Budget; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Models\Budget; use FireflyIII\Rules\IsBoolean; use FireflyIII\Rules\IsValidPositiveAmount; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; use FireflyIII\Validation\AutoBudget\ValidatesAutoBudgetRequest; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -50,27 +50,22 @@ class UpdateRequest extends FormRequest { // this is the way: $fields = [ - 'name' => ['name', 'convertString'], - 'active' => ['active', 'boolean'], - 'order' => ['order', 'convertInteger'], - 'notes' => ['notes', 'convertString'], - 'currency_id' => ['auto_budget_currency_id', 'convertInteger'], - 'currency_code' => ['auto_budget_currency_code', 'convertString'], - 'auto_budget_type' => ['auto_budget_type', 'convertString'], - 'auto_budget_amount' => ['auto_budget_amount', 'convertString'], - 'auto_budget_period' => ['auto_budget_period', 'convertString'], + 'name' => ['name', 'convertString'], + 'active' => ['active', 'boolean'], + 'order' => ['order', 'convertInteger'], + 'notes' => ['notes', 'convertString'], + 'currency_id' => ['auto_budget_currency_id', 'convertInteger'], + 'currency_code' => ['auto_budget_currency_code', 'convertString'], + 'auto_budget_type' => ['auto_budget_type', 'convertString'], + 'auto_budget_amount' => ['auto_budget_amount', 'convertString'], + 'auto_budget_period' => ['auto_budget_period', 'convertString'], // webhooks - 'fire_webhooks' => ['fire_webhooks', 'boolean'], + 'fire_webhooks' => ['fire_webhooks', 'boolean'] ]; $allData = $this->getAllData($fields); if (array_key_exists('auto_budget_type', $allData)) { - $types = [ - 'none' => 0, - 'reset' => 1, - 'rollover' => 2, - 'adjusted' => 3, - ]; + $types = ['none' => 0, 'reset' => 1, 'rollover' => 2, 'adjusted' => 3]; $allData['auto_budget_type'] = $types[$allData['auto_budget_type']] ?? 0; } @@ -86,17 +81,17 @@ class UpdateRequest extends FormRequest $budget = $this->route()->parameter('budget'); return [ - 'name' => sprintf('min:1|max:100|uniqueObjectForUser:budgets,name,%d', $budget->id), - 'active' => [new IsBoolean()], - 'notes' => 'nullable|min:1|max:32768', - 'auto_budget_type' => 'in:reset,rollover,adjusted,none', - 'auto_budget_currency_id' => 'exists:transaction_currencies,id', - 'auto_budget_currency_code' => 'exists:transaction_currencies,code', - 'auto_budget_amount' => ['nullable', new IsValidPositiveAmount()], - 'auto_budget_period' => 'in:daily,weekly,monthly,quarterly,half_year,yearly', + 'name' => sprintf('min:1|max:100|uniqueObjectForUser:budgets,name,%d', $budget->id), + 'active' => [new IsBoolean()], + 'notes' => 'nullable|min:1|max:32768', + 'auto_budget_type' => 'in:reset,rollover,adjusted,none', + 'auto_budget_currency_id' => 'exists:transaction_currencies,id', + 'auto_budget_currency_code' => 'exists:transaction_currencies,code', + 'auto_budget_amount' => ['nullable', new IsValidPositiveAmount()], + 'auto_budget_period' => 'in:daily,weekly,monthly,quarterly,half_year,yearly', // webhooks - 'fire_webhooks' => [new IsBoolean()], + 'fire_webhooks' => [new IsBoolean()] ]; } @@ -105,12 +100,10 @@ class UpdateRequest extends FormRequest */ public function withValidator(Validator $validator): void { - $validator->after( - function (Validator $validator): void { - // validate all account info - $this->validateAutoBudgetAmount($validator); - } - ); + $validator->after(function (Validator $validator): void { + // validate all account info + $this->validateAutoBudgetAmount($validator); + }); if ($validator->fails()) { Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray()); } diff --git a/app/Api/V1/Requests/Models/BudgetLimit/StoreRequest.php b/app/Api/V1/Requests/Models/BudgetLimit/StoreRequest.php index 914df7dcf2..b02e15a6f1 100644 --- a/app/Api/V1/Requests/Models/BudgetLimit/StoreRequest.php +++ b/app/Api/V1/Requests/Models/BudgetLimit/StoreRequest.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Requests\Models\BudgetLimit; -use Illuminate\Contracts\Validation\Validator; use Carbon\Carbon; use FireflyIII\Factory\TransactionCurrencyFactory; use FireflyIII\Rules\IsBoolean; @@ -32,6 +31,7 @@ use FireflyIII\Rules\IsValidPositiveAmount; use FireflyIII\Support\Facades\Amount; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -57,7 +57,7 @@ class StoreRequest extends FormRequest 'notes' => $this->stringWithNewlines('notes'), // for webhooks: - 'fire_webhooks' => $this->boolean('fire_webhooks', true), + 'fire_webhooks' => $this->boolean('fire_webhooks', true) ]; } @@ -67,15 +67,15 @@ class StoreRequest extends FormRequest public function rules(): array { return [ - 'start' => 'required|before:end|date', - 'end' => 'required|after:start|date', - 'amount' => ['required', new IsValidPositiveAmount()], - 'currency_id' => 'numeric|exists:transaction_currencies,id', - 'currency_code' => 'min:3|max:51|exists:transaction_currencies,code', - 'notes' => 'nullable|min:0|max:32768', + 'start' => 'required|before:end|date', + 'end' => 'required|after:start|date', + 'amount' => ['required', new IsValidPositiveAmount()], + 'currency_id' => 'numeric|exists:transaction_currencies,id', + 'currency_code' => 'min:3|max:51|exists:transaction_currencies,code', + 'notes' => 'nullable|min:0|max:32768', // webhooks - 'fire_webhooks' => [new IsBoolean()], + 'fire_webhooks' => [new IsBoolean()] ]; } @@ -85,39 +85,37 @@ class StoreRequest extends FormRequest public function withValidator(Validator $validator): void { $budget = $this->route()->parameter('budget'); - $validator->after( - static function (Validator $validator) use ($budget): void { - if (0 !== count($validator->failed())) { - return; - } - $data = $validator->getData(); - - // if no currency has been provided, use the user's default currency: - /** @var TransactionCurrencyFactory $factory */ - $factory = app(TransactionCurrencyFactory::class); - $currency = $factory->find($data['currency_id'] ?? null, $data['currency_code'] ?? null); - if (null === $currency) { - $currency = Amount::getPrimaryCurrency(); - } - $currency->enabled = true; - $currency->save(); - - // validator already concluded start and end are valid dates: - $start = Carbon::parse($data['start'], config('app.timezone')); - $end = Carbon::parse($data['end'], config('app.timezone')); - - // find limit with same date range and currency. - $limit = $budget->budgetlimits() - ->where('budget_limits.start_date', $start->format('Y-m-d')) - ->where('budget_limits.end_date', $end->format('Y-m-d')) - ->where('budget_limits.transaction_currency_id', $currency->id) - ->first(['budget_limits.*']) - ; - if (null !== $limit) { - $validator->errors()->add('start', trans('validation.limit_exists')); - } + $validator->after(static function (Validator $validator) use ($budget): void { + if (0 !== count($validator->failed())) { + return; } - ); + $data = $validator->getData(); + + // if no currency has been provided, use the user's default currency: + /** @var TransactionCurrencyFactory $factory */ + $factory = app(TransactionCurrencyFactory::class); + $currency = $factory->find($data['currency_id'] ?? null, $data['currency_code'] ?? null); + if (null === $currency) { + $currency = Amount::getPrimaryCurrency(); + } + $currency->enabled = true; + $currency->save(); + + // validator already concluded start and end are valid dates: + $start = Carbon::parse($data['start'], config('app.timezone')); + $end = Carbon::parse($data['end'], config('app.timezone')); + + // find limit with same date range and currency. + $limit = $budget + ->budgetlimits() + ->where('budget_limits.start_date', $start->format('Y-m-d')) + ->where('budget_limits.end_date', $end->format('Y-m-d')) + ->where('budget_limits.transaction_currency_id', $currency->id) + ->first(['budget_limits.*']); + if (null !== $limit) { + $validator->errors()->add('start', trans('validation.limit_exists')); + } + }); if ($validator->fails()) { Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray()); } diff --git a/app/Api/V1/Requests/Models/BudgetLimit/UpdateRequest.php b/app/Api/V1/Requests/Models/BudgetLimit/UpdateRequest.php index 0448048c7e..656a96b8a2 100644 --- a/app/Api/V1/Requests/Models/BudgetLimit/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/BudgetLimit/UpdateRequest.php @@ -24,12 +24,12 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Requests\Models\BudgetLimit; -use Illuminate\Contracts\Validation\Validator; use Carbon\Carbon; use FireflyIII\Rules\IsBoolean; use FireflyIII\Rules\IsValidPositiveAmount; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -47,15 +47,15 @@ class UpdateRequest extends FormRequest public function getAll(): array { $fields = [ - 'start' => ['start', 'date'], - 'end' => ['end', 'date'], - 'amount' => ['amount', 'convertString'], - 'currency_id' => ['currency_id', 'convertInteger'], - 'currency_code' => ['currency_code', 'convertString'], - 'notes' => ['notes', 'stringWithNewlines'], + 'start' => ['start', 'date'], + 'end' => ['end', 'date'], + 'amount' => ['amount', 'convertString'], + 'currency_id' => ['currency_id', 'convertInteger'], + 'currency_code' => ['currency_code', 'convertString'], + 'notes' => ['notes', 'stringWithNewlines'], // webhooks - 'fire_webhooks' => ['fire_webhooks', 'boolean'], + 'fire_webhooks' => ['fire_webhooks', 'boolean'] ]; if (false === $this->has('notes')) { // ignore notes, not submitted. @@ -71,15 +71,15 @@ class UpdateRequest extends FormRequest public function rules(): array { return [ - 'start' => 'date|after:1970-01-02|before:2038-01-17', - 'end' => 'date|after:1970-01-02|before:2038-01-17', - 'amount' => ['nullable', new IsValidPositiveAmount()], - 'currency_id' => 'numeric|exists:transaction_currencies,id', - 'currency_code' => 'min:3|max:51|exists:transaction_currencies,code', - 'notes' => 'nullable|min:0|max:32768', + 'start' => 'date|after:1970-01-02|before:2038-01-17', + 'end' => 'date|after:1970-01-02|before:2038-01-17', + 'amount' => ['nullable', new IsValidPositiveAmount()], + 'currency_id' => 'numeric|exists:transaction_currencies,id', + 'currency_code' => 'min:3|max:51|exists:transaction_currencies,code', + 'notes' => 'nullable|min:0|max:32768', // webhooks - 'fire_webhooks' => [new IsBoolean()], + 'fire_webhooks' => [new IsBoolean()] ]; } @@ -89,19 +89,17 @@ class UpdateRequest extends FormRequest */ public function withValidator(Validator $validator): void { - $validator->after( - static function (Validator $validator): void { - // validate start before end only if both are there. - $data = $validator->getData(); - if (array_key_exists('start', $data) && array_key_exists('end', $data)) { - $start = new Carbon($data['start']); - $end = new Carbon($data['end']); - if ($end->isBefore($start)) { - $validator->errors()->add('end', (string) trans('validation.date_after')); - } + $validator->after(static function (Validator $validator): void { + // validate start before end only if both are there. + $data = $validator->getData(); + if (array_key_exists('start', $data) && array_key_exists('end', $data)) { + $start = new Carbon($data['start']); + $end = new Carbon($data['end']); + if ($end->isBefore($start)) { + $validator->errors()->add('end', (string) trans('validation.date_after')); } } - ); + }); if ($validator->fails()) { Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray()); } diff --git a/app/Api/V1/Requests/Models/Category/StoreRequest.php b/app/Api/V1/Requests/Models/Category/StoreRequest.php index ae0670a285..609f333b61 100644 --- a/app/Api/V1/Requests/Models/Category/StoreRequest.php +++ b/app/Api/V1/Requests/Models/Category/StoreRequest.php @@ -41,10 +41,7 @@ class StoreRequest extends FormRequest */ public function getAll(): array { - return [ - 'name' => $this->convertString('name'), - 'notes' => $this->stringWithNewlines('notes'), - ]; + return ['name' => $this->convertString('name'), 'notes' => $this->stringWithNewlines('notes')]; } /** @@ -52,8 +49,6 @@ class StoreRequest extends FormRequest */ public function rules(): array { - return [ - 'name' => 'required|min:1|max:100|uniqueObjectForUser:categories,name', - ]; + return ['name' => 'required|min:1|max:100|uniqueObjectForUser:categories,name']; } } diff --git a/app/Api/V1/Requests/Models/Category/UpdateRequest.php b/app/Api/V1/Requests/Models/Category/UpdateRequest.php index 3d63e64266..3ffb90ea81 100644 --- a/app/Api/V1/Requests/Models/Category/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/Category/UpdateRequest.php @@ -42,10 +42,7 @@ class UpdateRequest extends FormRequest */ public function getAll(): array { - $fields = [ - 'name' => ['name', 'convertString'], - 'notes' => ['notes', 'stringWithNewlines'], - ]; + $fields = ['name' => ['name', 'convertString'], 'notes' => ['notes', 'stringWithNewlines']]; return $this->getAllData($fields); } @@ -58,8 +55,6 @@ class UpdateRequest extends FormRequest /** @var Category $category */ $category = $this->route()->parameter('category'); - return [ - 'name' => sprintf('min:1|max:100|uniqueObjectForUser:categories,name,%d', $category->id), - ]; + return ['name' => sprintf('min:1|max:100|uniqueObjectForUser:categories,name,%d', $category->id)]; } } diff --git a/app/Api/V1/Requests/Models/CurrencyExchangeRate/DestroyRequest.php b/app/Api/V1/Requests/Models/CurrencyExchangeRate/DestroyRequest.php index 82ff8ca3de..038dd658cb 100644 --- a/app/Api/V1/Requests/Models/CurrencyExchangeRate/DestroyRequest.php +++ b/app/Api/V1/Requests/Models/CurrencyExchangeRate/DestroyRequest.php @@ -34,7 +34,7 @@ class DestroyRequest extends FormRequest use ChecksLogin; use ConvertsDataTypes; - public function getDate(): ?Carbon + public function getDate(): null|Carbon { return $this->getCarbonDate('date'); } diff --git a/app/Api/V1/Requests/Models/CurrencyExchangeRate/StoreByCurrenciesRequest.php b/app/Api/V1/Requests/Models/CurrencyExchangeRate/StoreByCurrenciesRequest.php index 14fe7f25a0..b71f0345ae 100644 --- a/app/Api/V1/Requests/Models/CurrencyExchangeRate/StoreByCurrenciesRequest.php +++ b/app/Api/V1/Requests/Models/CurrencyExchangeRate/StoreByCurrenciesRequest.php @@ -24,11 +24,11 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Requests\Models\CurrencyExchangeRate; -use Illuminate\Contracts\Validation\Validator; use Carbon\Carbon; use Carbon\Exceptions\InvalidFormatException; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; class StoreByCurrenciesRequest extends FormRequest @@ -46,31 +46,27 @@ class StoreByCurrenciesRequest extends FormRequest */ public function rules(): array { - return [ - '*' => 'required|numeric|min:0.0000000001', - ]; + return ['*' => 'required|numeric|min:0.0000000001']; } public function withValidator(Validator $validator): void { - $validator->after( - static function (Validator $validator): void { - $data = $validator->getData(); - foreach ($data as $date => $rate) { - try { - Carbon::createFromFormat('Y-m-d', $date); - } catch (InvalidFormatException) { - $validator->errors()->add('date', trans('validation.date', ['attribute' => 'date'])); + $validator->after(static function (Validator $validator): void { + $data = $validator->getData(); + foreach ($data as $date => $rate) { + try { + Carbon::createFromFormat('Y-m-d', $date); + } catch (InvalidFormatException) { + $validator->errors()->add('date', trans('validation.date', ['attribute' => 'date'])); - return; - } - if (!is_numeric($rate)) { - $validator->errors()->add('rate', trans('validation.number', ['attribute' => 'rate'])); + return; + } + if (!is_numeric($rate)) { + $validator->errors()->add('rate', trans('validation.number', ['attribute' => 'rate'])); - return; - } + return; } } - ); + }); } } diff --git a/app/Api/V1/Requests/Models/CurrencyExchangeRate/StoreByDateRequest.php b/app/Api/V1/Requests/Models/CurrencyExchangeRate/StoreByDateRequest.php index c3ec816361..e52484a3af 100644 --- a/app/Api/V1/Requests/Models/CurrencyExchangeRate/StoreByDateRequest.php +++ b/app/Api/V1/Requests/Models/CurrencyExchangeRate/StoreByDateRequest.php @@ -24,12 +24,12 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Requests\Models\CurrencyExchangeRate; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\TransactionCurrency; use FireflyIII\Support\Facades\Amount; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; class StoreByDateRequest extends FormRequest @@ -42,15 +42,12 @@ class StoreByDateRequest extends FormRequest */ public function getAll(): array { - return [ - 'from' => $this->get('from'), - 'rates' => $this->get('rates', []), - ]; + return ['from' => $this->get('from'), 'rates' => $this->get('rates', [])]; } public function getFromCurrency(): TransactionCurrency { - return Amount::getTransactionCurrencyByCode((string)$this->get('from')); + return Amount::getTransactionCurrencyByCode((string) $this->get('from')); } /** @@ -60,40 +57,34 @@ class StoreByDateRequest extends FormRequest */ public function rules(): array { - return [ - 'from' => 'required|exists:transaction_currencies,code', - 'rates' => 'required|array', - 'rates.*' => 'required|numeric|min:0.0000000001', - ]; + return ['from' => 'required|exists:transaction_currencies,code', 'rates' => 'required|array', 'rates.*' => 'required|numeric|min:0.0000000001']; } public function withValidator(Validator $validator): void { $from = $this->getFromCurrency(); - $validator->after( - static function (Validator $validator) use ($from): void { - $data = $validator->getData(); - $rates = $data['rates'] ?? []; - if (0 === count($rates)) { - $validator->errors()->add('rates', 'No rates given.'); + $validator->after(static function (Validator $validator) use ($from): void { + $data = $validator->getData(); + $rates = $data['rates'] ?? []; + if (0 === count($rates)) { + $validator->errors()->add('rates', 'No rates given.'); - return; + return; + } + foreach ($rates as $key => $entry) { + if ($key === $from->code) { + $validator->errors()->add(sprintf('rates.%s', $key), trans('validation.convert_to_itself', ['code' => $key])); + + continue; } - foreach ($rates as $key => $entry) { - if ($key === $from->code) { - $validator->errors()->add(sprintf('rates.%s', $key), trans('validation.convert_to_itself', ['code' => $key])); - continue; - } - - try { - Amount::getTransactionCurrencyByCode((string)$key); - } catch (FireflyException) { - $validator->errors()->add(sprintf('rates.%s', $key), trans('validation.invalid_currency_code', ['code' => $key])); - } + try { + Amount::getTransactionCurrencyByCode((string) $key); + } catch (FireflyException) { + $validator->errors()->add(sprintf('rates.%s', $key), trans('validation.invalid_currency_code', ['code' => $key])); } } - ); + }); } } diff --git a/app/Api/V1/Requests/Models/CurrencyExchangeRate/StoreRequest.php b/app/Api/V1/Requests/Models/CurrencyExchangeRate/StoreRequest.php index 6038a65f02..29685ec606 100644 --- a/app/Api/V1/Requests/Models/CurrencyExchangeRate/StoreRequest.php +++ b/app/Api/V1/Requests/Models/CurrencyExchangeRate/StoreRequest.php @@ -36,7 +36,7 @@ class StoreRequest extends FormRequest use ChecksLogin; use ConvertsDataTypes; - public function getDate(): ?Carbon + public function getDate(): null|Carbon { return $this->getCarbonDate('date'); } @@ -65,7 +65,7 @@ class StoreRequest extends FormRequest 'date' => 'required|date|after:1970-01-02|before:2038-01-17', 'rate' => 'required|numeric|gt:0', 'from' => 'required|exists:transaction_currencies,code', - 'to' => 'required|exists:transaction_currencies,code', + 'to' => 'required|exists:transaction_currencies,code' ]; } } diff --git a/app/Api/V1/Requests/Models/CurrencyExchangeRate/UpdateRequest.php b/app/Api/V1/Requests/Models/CurrencyExchangeRate/UpdateRequest.php index 8114b7abed..725a1701c2 100644 --- a/app/Api/V1/Requests/Models/CurrencyExchangeRate/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/CurrencyExchangeRate/UpdateRequest.php @@ -34,7 +34,7 @@ class UpdateRequest extends FormRequest use ChecksLogin; use ConvertsDataTypes; - public function getDate(): ?Carbon + public function getDate(): null|Carbon { return $this->getCarbonDate('date'); } @@ -53,7 +53,7 @@ class UpdateRequest extends FormRequest 'date' => 'date|after:1970-01-02|before:2038-01-17', 'rate' => 'required|numeric|gt:0', 'from' => 'nullable|exists:transaction_currencies,code', - 'to' => 'nullable|exists:transaction_currencies,code', + 'to' => 'nullable|exists:transaction_currencies,code' ]; } } diff --git a/app/Api/V1/Requests/Models/ObjectGroup/UpdateRequest.php b/app/Api/V1/Requests/Models/ObjectGroup/UpdateRequest.php index 17b5a41e16..898b87598e 100644 --- a/app/Api/V1/Requests/Models/ObjectGroup/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/ObjectGroup/UpdateRequest.php @@ -39,10 +39,7 @@ class UpdateRequest extends FormRequest public function getUpdateData(): array { - $fields = [ - 'title' => ['title', 'convertString'], - 'order' => ['order', 'convertInteger'], - ]; + $fields = ['title' => ['title', 'convertString'], 'order' => ['order', 'convertInteger']]; return $this->getAllData($fields); } @@ -55,9 +52,6 @@ class UpdateRequest extends FormRequest /** @var ObjectGroup $objectGroup */ $objectGroup = $this->route()->parameter('objectGroup'); - return [ - 'title' => sprintf('max:1024|min:1|uniqueObjectGroup:%d', $objectGroup->id), - 'order' => 'numeric', - ]; + return ['title' => sprintf('max:1024|min:1|uniqueObjectGroup:%d', $objectGroup->id), 'order' => 'numeric']; } } diff --git a/app/Api/V1/Requests/Models/PiggyBank/StoreRequest.php b/app/Api/V1/Requests/Models/PiggyBank/StoreRequest.php index a791f741a4..55d6d9926c 100644 --- a/app/Api/V1/Requests/Models/PiggyBank/StoreRequest.php +++ b/app/Api/V1/Requests/Models/PiggyBank/StoreRequest.php @@ -24,13 +24,13 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Requests\Models\PiggyBank; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Models\TransactionCurrency; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Rules\IsValidZeroOrMoreAmount; use FireflyIII\Support\Facades\Amount; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -47,20 +47,18 @@ class StoreRequest extends FormRequest */ public function getAll(): array { - $fields = [ - 'order' => ['order', 'convertInteger'], - ]; - $data = $this->getAllData($fields); - $data['name'] = $this->convertString('name'); - $data['accounts'] = $this->parseAccounts($this->get('accounts')); - $data['target_amount'] = $this->convertString('target_amount'); - $data['start_date'] = $this->getCarbonDate('start_date'); - $data['target_date'] = $this->getCarbonDate('target_date'); - $data['notes'] = $this->stringWithNewlines('notes'); - $data['object_group_id'] = $this->convertInteger('object_group_id'); - $data['transaction_currency_id'] = $this->convertInteger('transaction_currency_id'); + $fields = ['order' => ['order', 'convertInteger']]; + $data = $this->getAllData($fields); + $data['name'] = $this->convertString('name'); + $data['accounts'] = $this->parseAccounts($this->get('accounts')); + $data['target_amount'] = $this->convertString('target_amount'); + $data['start_date'] = $this->getCarbonDate('start_date'); + $data['target_date'] = $this->getCarbonDate('target_date'); + $data['notes'] = $this->stringWithNewlines('notes'); + $data['object_group_id'] = $this->convertInteger('object_group_id'); + $data['transaction_currency_id'] = $this->convertInteger('transaction_currency_id'); $data['transaction_currency_code'] = $this->convertString('transaction_currency_code'); - $data['object_group_title'] = $this->convertString('object_group_title'); + $data['object_group_title'] = $this->convertString('object_group_title'); return $data; } @@ -83,7 +81,7 @@ class StoreRequest extends FormRequest 'transaction_currency_id' => 'exists:transaction_currencies,id|required_without:transaction_currency_code', 'transaction_currency_code' => 'exists:transaction_currencies,code|required_without:transaction_currency_id', 'target_date' => 'date|nullable|after:start_date', - 'notes' => 'max:65000', + 'notes' => 'max:65000' ]; } @@ -92,48 +90,46 @@ class StoreRequest extends FormRequest */ public function withValidator(Validator $validator): void { - $validator->after( - function (Validator $validator): void { - // validate start before end only if both are there. - $data = $validator->getData(); - $currency = $this->getCurrencyFromData($validator, $data); - if (!$currency instanceof TransactionCurrency) { - return; - } - $targetAmount = (string) ($data['target_amount'] ?? '0'); - $currentAmount = '0'; - if (array_key_exists('accounts', $data) && is_array($data['accounts'])) { - $repository = app(AccountRepositoryInterface::class); - $types = config('firefly.piggy_bank_account_types'); - foreach ($data['accounts'] as $index => $array) { - $accountId = (int) ($array['account_id'] ?? 0); - $account = $repository->find($accountId); - if (null !== $account) { - // check currency here. - $accountCurrency = $repository->getAccountCurrency($account); - $isMultiCurrency = $repository->getMetaValue($account, 'is_multi_currency'); - $currentAmount = bcadd($currentAmount, (string) ($array['current_amount'] ?? '0')); - if ($accountCurrency->id !== $currency->id && 'true' !== $isMultiCurrency) { - $validator->errors()->add(sprintf('accounts.%d', $index), trans('validation.invalid_account_currency')); - } - $type = $account->accountType->type; - if (!in_array($type, $types, true)) { - $validator->errors()->add(sprintf('accounts.%d', $index), trans('validation.invalid_account_type')); - } + $validator->after(function (Validator $validator): void { + // validate start before end only if both are there. + $data = $validator->getData(); + $currency = $this->getCurrencyFromData($validator, $data); + if (!$currency instanceof TransactionCurrency) { + return; + } + $targetAmount = (string) ($data['target_amount'] ?? '0'); + $currentAmount = '0'; + if (array_key_exists('accounts', $data) && is_array($data['accounts'])) { + $repository = app(AccountRepositoryInterface::class); + $types = config('firefly.piggy_bank_account_types'); + foreach ($data['accounts'] as $index => $array) { + $accountId = (int) ($array['account_id'] ?? 0); + $account = $repository->find($accountId); + if (null !== $account) { + // check currency here. + $accountCurrency = $repository->getAccountCurrency($account); + $isMultiCurrency = $repository->getMetaValue($account, 'is_multi_currency'); + $currentAmount = bcadd($currentAmount, (string) ($array['current_amount'] ?? '0')); + if ($accountCurrency->id !== $currency->id && 'true' !== $isMultiCurrency) { + $validator->errors()->add(sprintf('accounts.%d', $index), trans('validation.invalid_account_currency')); + } + $type = $account->accountType->type; + if (!in_array($type, $types, true)) { + $validator->errors()->add(sprintf('accounts.%d', $index), trans('validation.invalid_account_type')); } } } - if (-1 === bccomp($targetAmount, $currentAmount) && 1 === bccomp($targetAmount, '0')) { - $validator->errors()->add('target_amount', trans('validation.current_amount_too_much')); - } } - ); + if (-1 === bccomp($targetAmount, $currentAmount) && 1 === bccomp($targetAmount, '0')) { + $validator->errors()->add('target_amount', trans('validation.current_amount_too_much')); + } + }); if ($validator->fails()) { Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray()); } } - private function getCurrencyFromData(Validator $validator, array $data): ?TransactionCurrency + private function getCurrencyFromData(Validator $validator, array $data): null|TransactionCurrency { if (array_key_exists('transaction_currency_code', $data) && '' !== (string) $data['transaction_currency_code']) { return Amount::getTransactionCurrencyByCode((string) $data['transaction_currency_code']); diff --git a/app/Api/V1/Requests/Models/PiggyBank/UpdateRequest.php b/app/Api/V1/Requests/Models/PiggyBank/UpdateRequest.php index 0a6b4debf8..949f7ecf26 100644 --- a/app/Api/V1/Requests/Models/PiggyBank/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/PiggyBank/UpdateRequest.php @@ -45,7 +45,7 @@ class UpdateRequest extends FormRequest */ public function getAll(): array { - $fields = [ + $fields = [ 'name' => ['name', 'convertString'], 'target_amount' => ['target_amount', 'convertString'], 'start_date' => ['start_date', 'convertDateTime'], @@ -55,10 +55,10 @@ class UpdateRequest extends FormRequest 'object_group_title' => ['object_group_title', 'convertString'], 'object_group_id' => ['object_group_id', 'convertInteger'], 'transaction_currency_code' => ['transaction_currency_code', 'convertString'], - 'transaction_currency_id' => ['transaction_currency_id', 'convertInteger'], + 'transaction_currency_id' => ['transaction_currency_id', 'convertInteger'] ]; - $result = $this->getAllData($fields); + $result = $this->getAllData($fields); $result['accounts'] = $this->parseAccounts($this->get('accounts')); return $result; @@ -73,7 +73,7 @@ class UpdateRequest extends FormRequest $piggyBank = $this->route()->parameter('piggyBank'); return [ - 'name' => 'min:1|max:255|uniquePiggyBankForUser:'.$piggyBank->id, + 'name' => 'min:1|max:255|uniquePiggyBankForUser:' . $piggyBank->id, 'current_amount' => ['nullable', new LessThanPiggyTarget(), new IsValidPositiveAmount()], 'target_amount' => ['nullable', new IsValidZeroOrMoreAmount()], 'start_date' => 'date|nullable', @@ -86,7 +86,7 @@ class UpdateRequest extends FormRequest 'object_group_id' => 'numeric|belongsToUser:object_groups,id', 'object_group_title' => ['min:1', 'max:255'], 'transaction_currency_id' => 'exists:transaction_currencies,id|nullable', - 'transaction_currency_code' => 'exists:transaction_currencies,code|nullable', + 'transaction_currency_code' => 'exists:transaction_currencies,code|nullable' ]; } } diff --git a/app/Api/V1/Requests/Models/Recurrence/StoreRequest.php b/app/Api/V1/Requests/Models/Recurrence/StoreRequest.php index b9f736f74f..051f7ca848 100644 --- a/app/Api/V1/Requests/Models/Recurrence/StoreRequest.php +++ b/app/Api/V1/Requests/Models/Recurrence/StoreRequest.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Requests\Models\Recurrence; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Rules\BelongsUser; use FireflyIII\Rules\IsBoolean; use FireflyIII\Rules\IsValidPositiveAmount; @@ -34,6 +33,7 @@ use FireflyIII\Support\Request\GetRecurrenceData; use FireflyIII\Validation\CurrencyValidation; use FireflyIII\Validation\RecurrenceValidation; use FireflyIII\Validation\TransactionValidation; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -63,15 +63,11 @@ class StoreRequest extends FormRequest 'nr_of_repetitions' => ['nr_of_repetitions', 'convertInteger'], 'apply_rules' => ['apply_rules', 'boolean'], 'active' => ['active', 'boolean'], - 'notes' => ['notes', 'stringWithNewlines'], + 'notes' => ['notes', 'stringWithNewlines'] ]; $recurrence = $this->getAllData($fields); - return [ - 'recurrence' => $recurrence, - 'transactions' => $this->getTransactionData(), - 'repetitions' => $this->getRepetitionData(), - ]; + return ['recurrence' => $recurrence, 'transactions' => $this->getTransactionData(), 'repetitions' => $this->getRepetitionData()]; } /** @@ -80,7 +76,7 @@ class StoreRequest extends FormRequest */ private function getTransactionData(): array { - $return = []; + $return = []; // transaction data: /** @var null|array $transactions */ @@ -102,7 +98,7 @@ class StoreRequest extends FormRequest */ private function getRepetitionData(): array { - $return = []; + $return = []; // repetition data: /** @var null|array $repetitions */ @@ -113,7 +109,7 @@ class StoreRequest extends FormRequest /** @var array $repetition */ foreach ($repetitions as $repetition) { - $current = []; + $current = []; if (array_key_exists('type', $repetition)) { $current['type'] = $repetition['type']; } @@ -139,19 +135,19 @@ class StoreRequest extends FormRequest public function rules(): array { return [ - 'type' => 'required|in:withdrawal,transfer,deposit', - 'title' => 'required|min:1|max:255|uniqueObjectForUser:recurrences,title', - 'description' => 'min:1|max:32768', - 'first_date' => 'required|date', - 'apply_rules' => [new IsBoolean()], - 'active' => [new IsBoolean()], - 'repeat_until' => 'nullable|date', - 'nr_of_repetitions' => 'nullable|numeric|min:1|max:31', + 'type' => 'required|in:withdrawal,transfer,deposit', + 'title' => 'required|min:1|max:255|uniqueObjectForUser:recurrences,title', + 'description' => 'min:1|max:32768', + 'first_date' => 'required|date', + 'apply_rules' => [new IsBoolean()], + 'active' => [new IsBoolean()], + 'repeat_until' => 'nullable|date', + 'nr_of_repetitions' => 'nullable|numeric|min:1|max:31', - 'repetitions.*.type' => 'required|in:daily,weekly,ndom,monthly,yearly', - 'repetitions.*.moment' => 'min:0|max:10', - 'repetitions.*.skip' => 'nullable|numeric|min:0|max:31', - 'repetitions.*.weekend' => 'numeric|min:1|max:4', + 'repetitions.*.type' => 'required|in:daily,weekly,ndom,monthly,yearly', + 'repetitions.*.moment' => 'min:0|max:10', + 'repetitions.*.skip' => 'nullable|numeric|min:0|max:31', + 'repetitions.*.weekend' => 'numeric|min:1|max:4', 'transactions.*.description' => 'required|min:1|max:255', 'transactions.*.amount' => ['required', new IsValidPositiveAmount()], @@ -166,13 +162,13 @@ class StoreRequest extends FormRequest 'transactions.*.destination_name' => 'min:1|max:255|nullable', // new and updated fields: - 'transactions.*.budget_id' => ['nullable', 'mustExist:budgets,id', new BelongsUser()], - 'transactions.*.budget_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], - 'transactions.*.category_id' => ['nullable', 'mustExist:categories,id', new BelongsUser()], - 'transactions.*.category_name' => 'min:1|max:255|nullable', - 'transactions.*.piggy_bank_id' => ['nullable', 'numeric', 'mustExist:piggy_banks,id', new BelongsUser()], - 'transactions.*.piggy_bank_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], - 'transactions.*.tags' => 'nullable|min:1|max:255', + 'transactions.*.budget_id' => ['nullable', 'mustExist:budgets,id', new BelongsUser()], + 'transactions.*.budget_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], + 'transactions.*.category_id' => ['nullable', 'mustExist:categories,id', new BelongsUser()], + 'transactions.*.category_name' => 'min:1|max:255|nullable', + 'transactions.*.piggy_bank_id' => ['nullable', 'numeric', 'mustExist:piggy_banks,id', new BelongsUser()], + 'transactions.*.piggy_bank_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], + 'transactions.*.tags' => 'nullable|min:1|max:255' ]; } @@ -181,17 +177,15 @@ class StoreRequest extends FormRequest */ public function withValidator(Validator $validator): void { - $validator->after( - function (Validator $validator): void { - $this->validateRecurringConfig($validator); - $this->validateOneRecurrenceTransaction($validator); - $this->validateOneRepetition($validator); - $this->validateRecurrenceRepetition($validator); - $this->validateRepetitionMoment($validator); - $this->validateForeignCurrencyInformation($validator); - $this->validateAccountInformation($validator); - } - ); + $validator->after(function (Validator $validator): void { + $this->validateRecurringConfig($validator); + $this->validateOneRecurrenceTransaction($validator); + $this->validateOneRepetition($validator); + $this->validateRecurrenceRepetition($validator); + $this->validateRepetitionMoment($validator); + $this->validateForeignCurrencyInformation($validator); + $this->validateAccountInformation($validator); + }); if ($validator->fails()) { Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray()); } diff --git a/app/Api/V1/Requests/Models/Recurrence/UpdateRequest.php b/app/Api/V1/Requests/Models/Recurrence/UpdateRequest.php index f16c521590..aa93a64951 100644 --- a/app/Api/V1/Requests/Models/Recurrence/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/Recurrence/UpdateRequest.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Requests\Models\Recurrence; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Models\Recurrence; use FireflyIII\Rules\BelongsUser; use FireflyIII\Rules\IsBoolean; @@ -35,6 +34,7 @@ use FireflyIII\Support\Request\GetRecurrenceData; use FireflyIII\Validation\CurrencyValidation; use FireflyIII\Validation\RecurrenceValidation; use FireflyIII\Validation\TransactionValidation; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -56,7 +56,7 @@ class UpdateRequest extends FormRequest public function getAll(): array { // this is the way: - $fields = [ + $fields = [ 'title' => ['title', 'convertString'], 'description' => ['description', 'convertString'], 'first_date' => ['first_date', 'convertDateTime'], @@ -64,13 +64,11 @@ class UpdateRequest extends FormRequest 'nr_of_repetitions' => ['nr_of_repetitions', 'convertInteger'], 'apply_rules' => ['apply_rules', 'boolean'], 'active' => ['active', 'boolean'], - 'notes' => ['notes', 'convertString'], - ]; - $reps = $this->getRepetitionData(); - $transactions = $this->getTransactionData(); - $return = [ - 'recurrence' => $this->getAllData($fields), + 'notes' => ['notes', 'convertString'] ]; + $reps = $this->getRepetitionData(); + $transactions = $this->getTransactionData(); + $return = ['recurrence' => $this->getAllData($fields)]; if (null !== $reps) { $return['repetitions'] = $reps; } @@ -82,9 +80,9 @@ class UpdateRequest extends FormRequest /** * Returns the repetition data as it is found in the submitted data. */ - private function getRepetitionData(): ?array + private function getRepetitionData(): null|array { - $return = []; + $return = []; // repetition data: /** @var null|array $repetitions */ @@ -95,7 +93,7 @@ class UpdateRequest extends FormRequest /** @var array $repetition */ foreach ($repetitions as $repetition) { - $current = []; + $current = []; if (array_key_exists('type', $repetition)) { $current['type'] = $repetition['type']; } @@ -126,7 +124,7 @@ class UpdateRequest extends FormRequest */ private function getTransactionData(): array { - $return = []; + $return = []; // transaction data: /** @var null|array $transactions */ @@ -152,18 +150,18 @@ class UpdateRequest extends FormRequest $recurrence = $this->route()->parameter('recurrence'); return [ - 'title' => sprintf('min:1|max:255|uniqueObjectForUser:recurrences,title,%d', $recurrence->id), - 'description' => 'min:1|max:32768', - 'first_date' => 'date|after:1970-01-02|before:2038-01-17', - 'apply_rules' => [new IsBoolean()], - 'active' => [new IsBoolean()], - 'repeat_until' => 'nullable|date', - 'nr_of_repetitions' => 'nullable|numeric|min:1|max:31', + 'title' => sprintf('min:1|max:255|uniqueObjectForUser:recurrences,title,%d', $recurrence->id), + 'description' => 'min:1|max:32768', + 'first_date' => 'date|after:1970-01-02|before:2038-01-17', + 'apply_rules' => [new IsBoolean()], + 'active' => [new IsBoolean()], + 'repeat_until' => 'nullable|date', + 'nr_of_repetitions' => 'nullable|numeric|min:1|max:31', - 'repetitions.*.type' => 'in:daily,weekly,ndom,monthly,yearly', - 'repetitions.*.moment' => 'min:0|max:10|numeric', - 'repetitions.*.skip' => 'nullable|numeric|min:0|max:31', - 'repetitions.*.weekend' => 'nullable|numeric|min:1|max:4', + 'repetitions.*.type' => 'in:daily,weekly,ndom,monthly,yearly', + 'repetitions.*.moment' => 'min:0|max:10|numeric', + 'repetitions.*.skip' => 'nullable|numeric|min:0|max:31', + 'repetitions.*.weekend' => 'nullable|numeric|min:1|max:4', 'transactions.*.description' => ['min:1', 'max:255'], 'transactions.*.amount' => [new IsValidPositiveAmount()], @@ -178,13 +176,13 @@ class UpdateRequest extends FormRequest 'transactions.*.destination_name' => 'min:1|max:255|nullable', // new and updated fields: - 'transactions.*.budget_id' => ['nullable', 'mustExist:budgets,id', new BelongsUser()], - 'transactions.*.budget_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], - 'transactions.*.category_id' => ['nullable', 'mustExist:categories,id', new BelongsUser()], - 'transactions.*.category_name' => 'min:1|max:255|nullable', - 'transactions.*.piggy_bank_id' => ['nullable', 'numeric', 'mustExist:piggy_banks,id', new BelongsUser()], - 'transactions.*.piggy_bank_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], - 'transactions.*.tags' => 'nullable|min:1|max:255', + 'transactions.*.budget_id' => ['nullable', 'mustExist:budgets,id', new BelongsUser()], + 'transactions.*.budget_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], + 'transactions.*.category_id' => ['nullable', 'mustExist:categories,id', new BelongsUser()], + 'transactions.*.category_name' => 'min:1|max:255|nullable', + 'transactions.*.piggy_bank_id' => ['nullable', 'numeric', 'mustExist:piggy_banks,id', new BelongsUser()], + 'transactions.*.piggy_bank_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], + 'transactions.*.tags' => 'nullable|min:1|max:255' ]; } @@ -193,20 +191,18 @@ class UpdateRequest extends FormRequest */ public function withValidator(Validator $validator): void { - $validator->after( - function (Validator $validator): void { - // $this->validateOneRecurrenceTransaction($validator); - // $this->validateOneRepetitionUpdate($validator); + $validator->after(function (Validator $validator): void { + // $this->validateOneRecurrenceTransaction($validator); + // $this->validateOneRepetitionUpdate($validator); - /** @var Recurrence $recurrence */ - $recurrence = $this->route()->parameter('recurrence'); - $this->validateTransactionId($recurrence, $validator); - $this->validateRecurrenceRepetition($validator); - $this->validateRepetitionMoment($validator); - $this->validateForeignCurrencyInformation($validator); - $this->valUpdateAccountInfo($validator); - } - ); + /** @var Recurrence $recurrence */ + $recurrence = $this->route()->parameter('recurrence'); + $this->validateTransactionId($recurrence, $validator); + $this->validateRecurrenceRepetition($validator); + $this->validateRepetitionMoment($validator); + $this->validateForeignCurrencyInformation($validator); + $this->valUpdateAccountInfo($validator); + }); if ($validator->fails()) { Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray()); } diff --git a/app/Api/V1/Requests/Models/Rule/StoreRequest.php b/app/Api/V1/Requests/Models/Rule/StoreRequest.php index 1a9bdc1df9..9fa4b211f5 100644 --- a/app/Api/V1/Requests/Models/Rule/StoreRequest.php +++ b/app/Api/V1/Requests/Models/Rule/StoreRequest.php @@ -24,12 +24,12 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Requests\Models\Rule; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Rules\IsBoolean; use FireflyIII\Rules\IsValidActionExpression; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; use FireflyIII\Support\Request\GetRuleConfiguration; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -47,7 +47,7 @@ class StoreRequest extends FormRequest */ public function getAll(): array { - $fields = [ + $fields = [ 'title' => ['title', 'convertString'], 'description' => ['description', 'convertString'], 'rule_group_id' => ['rule_group_id', 'convertInteger'], @@ -56,11 +56,11 @@ class StoreRequest extends FormRequest 'trigger' => ['trigger', 'convertString'], 'strict' => ['strict', 'boolean'], 'stop_processing' => ['stop_processing', 'boolean'], - 'active' => ['active', 'boolean'], + 'active' => ['active', 'boolean'] ]; - $data = $this->getAllData($fields); + $data = $this->getAllData($fields); $data['triggers'] = $this->getRuleTriggers(); - $data['actions'] = $this->getRuleActions(); + $data['actions'] = $this->getRuleActions(); return $data; } @@ -76,7 +76,7 @@ class StoreRequest extends FormRequest 'value' => $trigger['value'] ?? null, 'prohibited' => $this->convertBoolean((string) ($trigger['prohibited'] ?? 'false')), 'active' => $this->convertBoolean((string) ($trigger['active'] ?? 'true')), - 'stop_processing' => $this->convertBoolean((string) ($trigger['stop_processing'] ?? 'false')), + 'stop_processing' => $this->convertBoolean((string) ($trigger['stop_processing'] ?? 'false')) ]; } } @@ -94,7 +94,7 @@ class StoreRequest extends FormRequest 'type' => $action['type'], 'value' => $action['value'], 'active' => $this->convertBoolean((string) ($action['active'] ?? 'true')), - 'stop_processing' => $this->convertBoolean((string) ($action['stop_processing'] ?? 'false')), + 'stop_processing' => $this->convertBoolean((string) ($action['stop_processing'] ?? 'false')) ]; } } @@ -107,8 +107,8 @@ class StoreRequest extends FormRequest */ public function rules(): array { - $validTriggers = $this->getTriggers(); - $validActions = array_keys(config('firefly.rule-actions')); + $validTriggers = $this->getTriggers(); + $validActions = array_keys(config('firefly.rule-actions')); // some triggers and actions require text: $contextTriggers = implode(',', $this->getTriggersWithContext()); @@ -120,17 +120,17 @@ class StoreRequest extends FormRequest 'rule_group_id' => 'belongsToUser:rule_groups|required_without:rule_group_title', 'rule_group_title' => 'nullable|min:1|max:255|required_without:rule_group_id|belongsToUser:rule_groups,title', 'trigger' => 'required|in:store-journal,update-journal,manual-activation', - 'triggers.*.type' => 'required|in:'.implode(',', $validTriggers), - 'triggers.*.value' => 'required_if:actions.*.type,'.$contextTriggers.'|min:1|ruleTriggerValue|max:1024', + 'triggers.*.type' => 'required|in:' . implode(',', $validTriggers), + 'triggers.*.value' => 'required_if:actions.*.type,' . $contextTriggers . '|min:1|ruleTriggerValue|max:1024', 'triggers.*.stop_processing' => [new IsBoolean()], 'triggers.*.active' => [new IsBoolean()], - 'actions.*.type' => 'required|in:'.implode(',', $validActions), + 'actions.*.type' => 'required|in:' . implode(',', $validActions), 'actions.*.value' => [sprintf('required_if:actions.*.type,%s', $contextActions), new IsValidActionExpression(), 'ruleActionValue'], 'actions.*.stop_processing' => [new IsBoolean()], 'actions.*.active' => [new IsBoolean()], 'strict' => [new IsBoolean()], 'stop_processing' => [new IsBoolean()], - 'active' => [new IsBoolean()], + 'active' => [new IsBoolean()] ]; } @@ -139,14 +139,12 @@ class StoreRequest extends FormRequest */ public function withValidator(Validator $validator): void { - $validator->after( - function (Validator $validator): void { - $this->atLeastOneTrigger($validator); - $this->atLeastOneAction($validator); - $this->atLeastOneActiveTrigger($validator); - $this->atLeastOneActiveAction($validator); - } - ); + $validator->after(function (Validator $validator): void { + $this->atLeastOneTrigger($validator); + $this->atLeastOneAction($validator); + $this->atLeastOneActiveTrigger($validator); + $this->atLeastOneActiveAction($validator); + }); if ($validator->fails()) { Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray()); } @@ -183,10 +181,10 @@ class StoreRequest extends FormRequest */ protected function atLeastOneActiveTrigger(Validator $validator): void { - $data = $validator->getData(); + $data = $validator->getData(); /** @var null|array|int|string $triggers */ - $triggers = $data['triggers'] ?? []; + $triggers = $data['triggers'] ?? []; // need at least one trigger if (!is_countable($triggers) || 0 === count($triggers)) { return; @@ -212,10 +210,10 @@ class StoreRequest extends FormRequest */ protected function atLeastOneActiveAction(Validator $validator): void { - $data = $validator->getData(); + $data = $validator->getData(); /** @var null|array|int|string $actions */ - $actions = $data['actions'] ?? []; + $actions = $data['actions'] ?? []; // need at least one trigger if (!is_countable($actions) || 0 === count($actions)) { return; diff --git a/app/Api/V1/Requests/Models/Rule/TestRequest.php b/app/Api/V1/Requests/Models/Rule/TestRequest.php index ef855b9c85..b0c8e7951b 100644 --- a/app/Api/V1/Requests/Models/Rule/TestRequest.php +++ b/app/Api/V1/Requests/Models/Rule/TestRequest.php @@ -39,12 +39,7 @@ class TestRequest extends FormRequest public function getTestParameters(): array { - return [ - 'page' => $this->getPage(), - 'start' => $this->getDate('start'), - 'end' => $this->getDate('end'), - 'accounts' => $this->getAccounts(), - ]; + return ['page' => $this->getPage(), 'start' => $this->getDate('start'), 'end' => $this->getDate('end'), 'accounts' => $this->getAccounts()]; } private function getPage(): int @@ -52,7 +47,7 @@ class TestRequest extends FormRequest return 0 === (int) $this->query('page') ? 1 : (int) $this->query('page'); } - private function getDate(string $field): ?Carbon + private function getDate(string $field): null|Carbon { $value = $this->query($field); if (is_array($value)) { @@ -74,7 +69,7 @@ class TestRequest extends FormRequest 'start' => 'date|after:1970-01-02|before:2038-01-17', 'end' => 'date|after_or_equal:start|after:1970-01-02|before:2038-01-17', 'accounts' => '', - 'accounts.*' => 'required|exists:accounts,id|belongsToUser:accounts', + 'accounts.*' => 'required|exists:accounts,id|belongsToUser:accounts' ]; } } diff --git a/app/Api/V1/Requests/Models/Rule/TriggerRequest.php b/app/Api/V1/Requests/Models/Rule/TriggerRequest.php index 42f4417aca..42639af758 100644 --- a/app/Api/V1/Requests/Models/Rule/TriggerRequest.php +++ b/app/Api/V1/Requests/Models/Rule/TriggerRequest.php @@ -39,14 +39,10 @@ class TriggerRequest extends FormRequest public function getTriggerParameters(): array { - return [ - 'start' => $this->getDate('start'), - 'end' => $this->getDate('end'), - 'accounts' => $this->getAccounts(), - ]; + return ['start' => $this->getDate('start'), 'end' => $this->getDate('end'), 'accounts' => $this->getAccounts()]; } - private function getDate(string $field): ?Carbon + private function getDate(string $field): null|Carbon { $value = $this->query($field); if (is_array($value)) { @@ -68,7 +64,7 @@ class TriggerRequest extends FormRequest 'start' => 'date|after:1970-01-02|before:2038-01-17', 'end' => 'date|after_or_equal:start|after:1970-01-02|before:2038-01-17', 'accounts' => '', - 'accounts.*' => 'exists:accounts,id|belongsToUser:accounts', + 'accounts.*' => 'exists:accounts,id|belongsToUser:accounts' ]; } } diff --git a/app/Api/V1/Requests/Models/Rule/UpdateRequest.php b/app/Api/V1/Requests/Models/Rule/UpdateRequest.php index e51f81b3fe..20b90e5146 100644 --- a/app/Api/V1/Requests/Models/Rule/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/Rule/UpdateRequest.php @@ -24,13 +24,13 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Requests\Models\Rule; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Models\Rule; use FireflyIII\Rules\IsBoolean; use FireflyIII\Rules\IsValidActionExpression; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; use FireflyIII\Support\Request\GetRuleConfiguration; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -48,7 +48,7 @@ class UpdateRequest extends FormRequest */ public function getAll(): array { - $fields = [ + $fields = [ 'title' => ['title', 'convertString'], 'description' => ['description', 'stringWithNewlines'], 'rule_group_id' => ['rule_group_id', 'convertInteger'], @@ -56,7 +56,7 @@ class UpdateRequest extends FormRequest 'strict' => ['strict', 'boolean'], 'stop_processing' => ['stop_processing', 'boolean'], 'active' => ['active', 'boolean'], - 'order' => ['order', 'convertInteger'], + 'order' => ['order', 'convertInteger'] ]; $return = $this->getAllData($fields); @@ -72,7 +72,7 @@ class UpdateRequest extends FormRequest return $return; } - private function getRuleTriggers(): ?array + private function getRuleTriggers(): null|array { if (!$this->has('triggers')) { return null; @@ -84,12 +84,12 @@ class UpdateRequest extends FormRequest $active = array_key_exists('active', $trigger) ? $trigger['active'] : true; $prohibited = array_key_exists('prohibited', $trigger) ? $trigger['prohibited'] : false; $stopProcessing = array_key_exists('stop_processing', $trigger) ? $trigger['stop_processing'] : false; - $return[] = [ + $return[] = [ 'type' => $trigger['type'], 'value' => $trigger['value'], 'prohibited' => $prohibited, 'active' => $active, - 'stop_processing' => $stopProcessing, + 'stop_processing' => $stopProcessing ]; } } @@ -97,7 +97,7 @@ class UpdateRequest extends FormRequest return $return; } - private function getRuleActions(): ?array + private function getRuleActions(): null|array { if (!$this->has('actions')) { return null; @@ -110,7 +110,7 @@ class UpdateRequest extends FormRequest 'type' => $action['type'], 'value' => $action['value'], 'active' => $this->convertBoolean((string) ($action['active'] ?? 'false')), - 'stop_processing' => $this->convertBoolean((string) ($action['stop_processing'] ?? 'false')), + 'stop_processing' => $this->convertBoolean((string) ($action['stop_processing'] ?? 'false')) ]; } } @@ -123,11 +123,11 @@ class UpdateRequest extends FormRequest */ public function rules(): array { - $validTriggers = $this->getTriggers(); - $validActions = array_keys(config('firefly.rule-actions')); + $validTriggers = $this->getTriggers(); + $validActions = array_keys(config('firefly.rule-actions')); /** @var Rule $rule */ - $rule = $this->route()->parameter('rule'); + $rule = $this->route()->parameter('rule'); // some triggers and actions require text: $contextTriggers = implode(',', $this->getTriggersWithContext()); @@ -139,18 +139,18 @@ class UpdateRequest extends FormRequest 'rule_group_id' => 'belongsToUser:rule_groups', 'rule_group_title' => 'nullable|min:1|max:255|belongsToUser:rule_groups,title', 'trigger' => 'in:store-journal,update-journal.manual-activation', - 'triggers.*.type' => 'required|in:'.implode(',', $validTriggers), - 'triggers.*.value' => 'required_if:actions.*.type,'.$contextTriggers.'|min:1|ruleTriggerValue|max:1024', + 'triggers.*.type' => 'required|in:' . implode(',', $validTriggers), + 'triggers.*.value' => 'required_if:actions.*.type,' . $contextTriggers . '|min:1|ruleTriggerValue|max:1024', 'triggers.*.stop_processing' => [new IsBoolean()], 'triggers.*.active' => [new IsBoolean()], - 'actions.*.type' => 'required|in:'.implode(',', $validActions), + 'actions.*.type' => 'required|in:' . implode(',', $validActions), 'actions.*.value' => [sprintf('required_if:actions.*.type,%s', $contextActions), new IsValidActionExpression(), 'ruleActionValue'], 'actions.*.stop_processing' => [new IsBoolean()], 'actions.*.active' => [new IsBoolean()], 'strict' => [new IsBoolean()], 'stop_processing' => [new IsBoolean()], 'active' => [new IsBoolean()], - 'order' => 'numeric|min:1|max:2048', + 'order' => 'numeric|min:1|max:2048' ]; } @@ -159,14 +159,12 @@ class UpdateRequest extends FormRequest */ public function withValidator(Validator $validator): void { - $validator->after( - function (Validator $validator): void { - $this->atLeastOneTrigger($validator); - $this->atLeastOneValidTrigger($validator); - $this->atLeastOneAction($validator); - $this->atLeastOneValidAction($validator); - } - ); + $validator->after(function (Validator $validator): void { + $this->atLeastOneTrigger($validator); + $this->atLeastOneValidTrigger($validator); + $this->atLeastOneAction($validator); + $this->atLeastOneValidAction($validator); + }); if ($validator->fails()) { Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray()); } diff --git a/app/Api/V1/Requests/Models/RuleGroup/StoreRequest.php b/app/Api/V1/Requests/Models/RuleGroup/StoreRequest.php index f38be5a7e2..81d47e3b55 100644 --- a/app/Api/V1/Requests/Models/RuleGroup/StoreRequest.php +++ b/app/Api/V1/Requests/Models/RuleGroup/StoreRequest.php @@ -55,7 +55,7 @@ class StoreRequest extends FormRequest 'title' => $this->convertString('title'), 'description' => $this->convertString('description'), 'active' => $active, - 'order' => $order, + 'order' => $order ]; } @@ -67,7 +67,7 @@ class StoreRequest extends FormRequest return [ 'title' => 'required|min:1|max:100|uniqueObjectForUser:rule_groups,title', 'description' => 'min:1|max:32768|nullable', - 'active' => [new IsBoolean()], + 'active' => [new IsBoolean()] ]; } } diff --git a/app/Api/V1/Requests/Models/RuleGroup/TestRequest.php b/app/Api/V1/Requests/Models/RuleGroup/TestRequest.php index 68c7bfb219..1a181f8497 100644 --- a/app/Api/V1/Requests/Models/RuleGroup/TestRequest.php +++ b/app/Api/V1/Requests/Models/RuleGroup/TestRequest.php @@ -39,14 +39,10 @@ class TestRequest extends FormRequest public function getTestParameters(): array { - return [ - 'start' => $this->getDate('start'), - 'end' => $this->getDate('end'), - 'accounts' => $this->getAccounts(), - ]; + return ['start' => $this->getDate('start'), 'end' => $this->getDate('end'), 'accounts' => $this->getAccounts()]; } - private function getDate(string $field): ?Carbon + private function getDate(string $field): null|Carbon { $value = $this->query($field); if (is_array($value)) { @@ -68,7 +64,7 @@ class TestRequest extends FormRequest 'start' => 'date|after:1970-01-02|before:2038-01-17', 'end' => 'date|after_or_equal:start|after:1970-01-02|before:2038-01-17', 'accounts' => '', - 'accounts.*' => 'exists:accounts,id|belongsToUser:accounts', + 'accounts.*' => 'exists:accounts,id|belongsToUser:accounts' ]; } } diff --git a/app/Api/V1/Requests/Models/RuleGroup/TriggerRequest.php b/app/Api/V1/Requests/Models/RuleGroup/TriggerRequest.php index 67e7fd4e09..78c4bf9bff 100644 --- a/app/Api/V1/Requests/Models/RuleGroup/TriggerRequest.php +++ b/app/Api/V1/Requests/Models/RuleGroup/TriggerRequest.php @@ -39,14 +39,10 @@ class TriggerRequest extends FormRequest public function getTriggerParameters(): array { - return [ - 'start' => $this->getDate('start'), - 'end' => $this->getDate('end'), - 'accounts' => $this->getAccounts(), - ]; + return ['start' => $this->getDate('start'), 'end' => $this->getDate('end'), 'accounts' => $this->getAccounts()]; } - private function getDate(string $field): ?Carbon + private function getDate(string $field): null|Carbon { $value = $this->query($field); if (is_array($value)) { @@ -68,9 +64,6 @@ class TriggerRequest extends FormRequest public function rules(): array { - return [ - 'start' => 'date|after:1970-01-02|before:2038-01-17', - 'end' => 'date|after_or_equal:start|after:1970-01-02|before:2038-01-17', - ]; + return ['start' => 'date|after:1970-01-02|before:2038-01-17', 'end' => 'date|after_or_equal:start|after:1970-01-02|before:2038-01-17']; } } diff --git a/app/Api/V1/Requests/Models/RuleGroup/UpdateRequest.php b/app/Api/V1/Requests/Models/RuleGroup/UpdateRequest.php index d2cbae0cab..25f58bac70 100644 --- a/app/Api/V1/Requests/Models/RuleGroup/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/RuleGroup/UpdateRequest.php @@ -48,7 +48,7 @@ class UpdateRequest extends FormRequest 'title' => ['title', 'convertString'], 'description' => ['description', 'stringWithNewlines'], 'active' => ['active', 'boolean'], - 'order' => ['order', 'convertInteger'], + 'order' => ['order', 'convertInteger'] ]; return $this->getAllData($fields); @@ -63,9 +63,9 @@ class UpdateRequest extends FormRequest $ruleGroup = $this->route()->parameter('ruleGroup'); return [ - 'title' => 'min:1|max:100|uniqueObjectForUser:rule_groups,title,'.$ruleGroup->id, + 'title' => 'min:1|max:100|uniqueObjectForUser:rule_groups,title,' . $ruleGroup->id, 'description' => 'min:1|max:32768|nullable', - 'active' => [new IsBoolean()], + 'active' => [new IsBoolean()] ]; } } diff --git a/app/Api/V1/Requests/Models/Tag/StoreRequest.php b/app/Api/V1/Requests/Models/Tag/StoreRequest.php index aeb51632bd..ac35803c0e 100644 --- a/app/Api/V1/Requests/Models/Tag/StoreRequest.php +++ b/app/Api/V1/Requests/Models/Tag/StoreRequest.php @@ -48,7 +48,7 @@ class StoreRequest extends FormRequest 'tag' => $this->convertString('tag'), 'date' => $this->getCarbonDate('date'), 'description' => $this->convertString('description'), - 'has_location' => true, + 'has_location' => true ]; return $this->appendLocationData($data, null); @@ -62,7 +62,7 @@ class StoreRequest extends FormRequest $rules = [ 'tag' => 'required|min:1|uniqueObjectForUser:tags,tag|max:1024', 'description' => 'min:1|nullable|max:32768', - 'date' => 'date|nullable|after:1970-01-02|before:2038-01-17', + 'date' => 'date|nullable|after:1970-01-02|before:2038-01-17' ]; return Location::requestRules($rules); diff --git a/app/Api/V1/Requests/Models/Tag/UpdateRequest.php b/app/Api/V1/Requests/Models/Tag/UpdateRequest.php index 37417dfdb2..d9f2036e87 100644 --- a/app/Api/V1/Requests/Models/Tag/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/Tag/UpdateRequest.php @@ -46,11 +46,7 @@ class UpdateRequest extends FormRequest public function getAll(): array { // This is the way. - $fields = [ - 'tag' => ['tag', 'convertString'], - 'date' => ['date', 'date'], - 'description' => ['description', 'convertString'], - ]; + $fields = ['tag' => ['tag', 'convertString'], 'date' => ['date', 'date'], 'description' => ['description', 'convertString']]; $data = $this->getAllData($fields); return $this->appendLocationData($data, null); @@ -64,9 +60,9 @@ class UpdateRequest extends FormRequest /** @var Tag $tag */ $tag = $this->route()->parameter('tagOrId'); $rules = [ - 'tag' => 'min:1|max:1024|uniqueObjectForUser:tags,tag,'.$tag->id, + 'tag' => 'min:1|max:1024|uniqueObjectForUser:tags,tag,' . $tag->id, 'description' => 'min:1|nullable|max:32768', - 'date' => 'date|nullable|after:1970-01-02|before:2038-01-17', + 'date' => 'date|nullable|after:1970-01-02|before:2038-01-17' ]; return Location::requestRules($rules); diff --git a/app/Api/V1/Requests/Models/Transaction/StoreRequest.php b/app/Api/V1/Requests/Models/Transaction/StoreRequest.php index cf341ed7ac..19f924ef0f 100644 --- a/app/Api/V1/Requests/Models/Transaction/StoreRequest.php +++ b/app/Api/V1/Requests/Models/Transaction/StoreRequest.php @@ -24,13 +24,13 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Requests\Models\Transaction; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Models\Location; use FireflyIII\Rules\BelongsUser; use FireflyIII\Rules\IsBoolean; use FireflyIII\Rules\IsDateOrTime; use FireflyIII\Rules\IsValidPositiveAmount; use FireflyIII\Rules\IsValidZeroOrMoreAmount; +use FireflyIII\Support\Facades\FireflyConfig; use FireflyIII\Support\NullArrayObject; use FireflyIII\Support\Request\AppendsLocationData; use FireflyIII\Support\Request\ChecksLogin; @@ -38,9 +38,9 @@ use FireflyIII\Support\Request\ConvertsDataTypes; use FireflyIII\Validation\CurrencyValidation; use FireflyIII\Validation\GroupValidation; use FireflyIII\Validation\TransactionValidation; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; -use FireflyIII\Support\Facades\FireflyConfig; /** * Class StoreRequest @@ -66,8 +66,9 @@ class StoreRequest extends FormRequest 'error_if_duplicate_hash' => $this->boolean('error_if_duplicate_hash'), 'apply_rules' => $this->boolean('apply_rules', true), 'fire_webhooks' => $this->boolean('fire_webhooks', true), - 'transactions' => $this->getTransactionData(), + 'transactions' => $this->getTransactionData() ]; + // TODO include location and ability to process it. } @@ -82,89 +83,89 @@ class StoreRequest extends FormRequest * @var array $transaction */ foreach ($this->get('transactions') as $transaction) { - $object = new NullArrayObject($transaction); + $object = new NullArrayObject($transaction); $return[] = [ - 'type' => $this->clearString($object['type']), - 'date' => $this->dateFromValue($object['date']), - 'order' => $this->integerFromValue((string) $object['order']), + 'type' => $this->clearString($object['type']), + 'date' => $this->dateFromValue($object['date']), + 'order' => $this->integerFromValue((string) $object['order']), - 'currency_id' => $this->integerFromValue((string) $object['currency_id']), - 'currency_code' => $this->clearString((string) $object['currency_code']), + 'currency_id' => $this->integerFromValue((string) $object['currency_id']), + 'currency_code' => $this->clearString((string) $object['currency_code']), // location - 'latitude' => $this->floatFromValue((string) $object['latitude']), - 'longitude' => $this->floatFromValue((string) $object['longitude']), - 'zoom_level' => $this->integerFromValue((string) $object['zoom_level']), + 'latitude' => $this->floatFromValue((string) $object['latitude']), + 'longitude' => $this->floatFromValue((string) $object['longitude']), + 'zoom_level' => $this->integerFromValue((string) $object['zoom_level']), // foreign currency info: 'foreign_currency_id' => $this->integerFromValue((string) $object['foreign_currency_id']), 'foreign_currency_code' => $this->clearString((string) $object['foreign_currency_code']), // amount and foreign amount. Cannot be 0. - 'amount' => $this->clearString((string) $object['amount']), - 'foreign_amount' => $this->clearString((string) $object['foreign_amount']), + 'amount' => $this->clearString((string) $object['amount']), + 'foreign_amount' => $this->clearString((string) $object['foreign_amount']), // description. - 'description' => $this->clearString($object['description']), + 'description' => $this->clearString($object['description']), // source of transaction. If everything is null, assume cash account. - 'source_id' => $this->integerFromValue((string) $object['source_id']), - 'source_name' => $this->clearString((string) $object['source_name']), - 'source_iban' => $this->clearIban((string) $object['source_iban']), - 'source_number' => $this->clearString((string) $object['source_number']), - 'source_bic' => $this->clearString((string) $object['source_bic']), + 'source_id' => $this->integerFromValue((string) $object['source_id']), + 'source_name' => $this->clearString((string) $object['source_name']), + 'source_iban' => $this->clearIban((string) $object['source_iban']), + 'source_number' => $this->clearString((string) $object['source_number']), + 'source_bic' => $this->clearString((string) $object['source_bic']), // destination of transaction. If everything is null, assume cash account. - 'destination_id' => $this->integerFromValue((string) $object['destination_id']), - 'destination_name' => $this->clearString((string) $object['destination_name']), - 'destination_iban' => $this->clearIban((string) $object['destination_iban']), - 'destination_number' => $this->clearString((string) $object['destination_number']), - 'destination_bic' => $this->clearString((string) $object['destination_bic']), + 'destination_id' => $this->integerFromValue((string) $object['destination_id']), + 'destination_name' => $this->clearString((string) $object['destination_name']), + 'destination_iban' => $this->clearIban((string) $object['destination_iban']), + 'destination_number' => $this->clearString((string) $object['destination_number']), + 'destination_bic' => $this->clearString((string) $object['destination_bic']), // budget info - 'budget_id' => $this->integerFromValue((string) $object['budget_id']), - 'budget_name' => $this->clearString((string) $object['budget_name']), + 'budget_id' => $this->integerFromValue((string) $object['budget_id']), + 'budget_name' => $this->clearString((string) $object['budget_name']), // category info - 'category_id' => $this->integerFromValue((string) $object['category_id']), - 'category_name' => $this->clearString((string) $object['category_name']), + 'category_id' => $this->integerFromValue((string) $object['category_id']), + 'category_name' => $this->clearString((string) $object['category_name']), // journal bill reference. Optional. Will only work for withdrawals - 'bill_id' => $this->integerFromValue((string) $object['bill_id']), - 'bill_name' => $this->clearString((string) $object['bill_name']), + 'bill_id' => $this->integerFromValue((string) $object['bill_id']), + 'bill_name' => $this->clearString((string) $object['bill_name']), // piggy bank reference. Optional. Will only work for transfers - 'piggy_bank_id' => $this->integerFromValue((string) $object['piggy_bank_id']), - 'piggy_bank_name' => $this->clearString((string) $object['piggy_bank_name']), + 'piggy_bank_id' => $this->integerFromValue((string) $object['piggy_bank_id']), + 'piggy_bank_name' => $this->clearString((string) $object['piggy_bank_name']), // some other interesting properties - 'reconciled' => $this->convertBoolean((string) $object['reconciled']), - 'notes' => $this->clearStringKeepNewlines((string) $object['notes']), - 'tags' => $this->arrayFromValue($object['tags']), + 'reconciled' => $this->convertBoolean((string) $object['reconciled']), + 'notes' => $this->clearStringKeepNewlines((string) $object['notes']), + 'tags' => $this->arrayFromValue($object['tags']), // all custom fields: - 'internal_reference' => $this->clearString((string) $object['internal_reference']), - 'external_id' => $this->clearString((string) $object['external_id']), - 'original_source' => sprintf('ff3-v%s', config('firefly.version')), - 'recurrence_id' => $this->integerFromValue($object['recurrence_id']), - 'bunq_payment_id' => $this->clearString((string) $object['bunq_payment_id']), - 'external_url' => $this->clearString((string) $object['external_url']), + 'internal_reference' => $this->clearString((string) $object['internal_reference']), + 'external_id' => $this->clearString((string) $object['external_id']), + 'original_source' => sprintf('ff3-v%s', config('firefly.version')), + 'recurrence_id' => $this->integerFromValue($object['recurrence_id']), + 'bunq_payment_id' => $this->clearString((string) $object['bunq_payment_id']), + 'external_url' => $this->clearString((string) $object['external_url']), - 'sepa_cc' => $this->clearString((string) $object['sepa_cc']), - 'sepa_ct_op' => $this->clearString((string) $object['sepa_ct_op']), - 'sepa_ct_id' => $this->clearString((string) $object['sepa_ct_id']), - 'sepa_db' => $this->clearString((string) $object['sepa_db']), - 'sepa_country' => $this->clearString((string) $object['sepa_country']), - 'sepa_ep' => $this->clearString((string) $object['sepa_ep']), - 'sepa_ci' => $this->clearString((string) $object['sepa_ci']), - 'sepa_batch_id' => $this->clearString((string) $object['sepa_batch_id']), + 'sepa_cc' => $this->clearString((string) $object['sepa_cc']), + 'sepa_ct_op' => $this->clearString((string) $object['sepa_ct_op']), + 'sepa_ct_id' => $this->clearString((string) $object['sepa_ct_id']), + 'sepa_db' => $this->clearString((string) $object['sepa_db']), + 'sepa_country' => $this->clearString((string) $object['sepa_country']), + 'sepa_ep' => $this->clearString((string) $object['sepa_ep']), + 'sepa_ci' => $this->clearString((string) $object['sepa_ci']), + 'sepa_batch_id' => $this->clearString((string) $object['sepa_batch_id']), // custom date fields. Must be Carbon objects. Presence is optional. - 'interest_date' => $this->dateFromValue($object['interest_date']), - 'book_date' => $this->dateFromValue($object['book_date']), - 'process_date' => $this->dateFromValue($object['process_date']), - 'due_date' => $this->dateFromValue($object['due_date']), - 'payment_date' => $this->dateFromValue($object['payment_date']), - 'invoice_date' => $this->dateFromValue($object['invoice_date']), + 'interest_date' => $this->dateFromValue($object['interest_date']), + 'book_date' => $this->dateFromValue($object['book_date']), + 'process_date' => $this->dateFromValue($object['process_date']), + 'due_date' => $this->dateFromValue($object['due_date']), + 'payment_date' => $this->dateFromValue($object['payment_date']), + 'invoice_date' => $this->dateFromValue($object['invoice_date']) ]; } @@ -182,20 +183,20 @@ class StoreRequest extends FormRequest return [ // basic fields for group: - 'group_title' => 'min:1|max:1000|nullable', - 'error_if_duplicate_hash' => [new IsBoolean()], - 'fire_webhooks' => [new IsBoolean()], - 'apply_rules' => [new IsBoolean()], + 'group_title' => 'min:1|max:1000|nullable', + 'error_if_duplicate_hash' => [new IsBoolean()], + 'fire_webhooks' => [new IsBoolean()], + 'apply_rules' => [new IsBoolean()], // location rules - 'transactions.*.latitude' => $locationRules['latitude'], - 'transactions.*.longitude' => $locationRules['longitude'], - 'transactions.*.zoom_level' => $locationRules['zoom_level'], + 'transactions.*.latitude' => $locationRules['latitude'], + 'transactions.*.longitude' => $locationRules['longitude'], + 'transactions.*.zoom_level' => $locationRules['zoom_level'], // transaction rules (in array for splits): - 'transactions.*.type' => 'required|in:withdrawal,deposit,transfer,opening-balance,reconciliation', - 'transactions.*.date' => ['required', new IsDateOrTime()], - 'transactions.*.order' => 'numeric|min:0', + 'transactions.*.type' => 'required|in:withdrawal,deposit,transfer,opening-balance,reconciliation', + 'transactions.*.date' => ['required', new IsDateOrTime()], + 'transactions.*.order' => 'numeric|min:0', // currency info 'transactions.*.currency_id' => 'numeric|exists:transaction_currencies,id|nullable', @@ -204,66 +205,66 @@ class StoreRequest extends FormRequest 'transactions.*.foreign_currency_code' => 'min:3|max:51|exists:transaction_currencies,code|nullable', // amount - 'transactions.*.amount' => ['required', new IsValidPositiveAmount()], - 'transactions.*.foreign_amount' => ['nullable', new IsValidZeroOrMoreAmount()], + 'transactions.*.amount' => ['required', new IsValidPositiveAmount()], + 'transactions.*.foreign_amount' => ['nullable', new IsValidZeroOrMoreAmount()], // description - 'transactions.*.description' => 'nullable|min:1|max:1000', + 'transactions.*.description' => 'nullable|min:1|max:1000', // source of transaction - 'transactions.*.source_id' => ['numeric', 'nullable', new BelongsUser()], - 'transactions.*.source_name' => 'min:1|max:255|nullable', - 'transactions.*.source_iban' => 'min:1|max:255|nullable|iban', - 'transactions.*.source_number' => 'min:1|max:255|nullable', - 'transactions.*.source_bic' => 'min:1|max:255|nullable|bic', + 'transactions.*.source_id' => ['numeric', 'nullable', new BelongsUser()], + 'transactions.*.source_name' => 'min:1|max:255|nullable', + 'transactions.*.source_iban' => 'min:1|max:255|nullable|iban', + 'transactions.*.source_number' => 'min:1|max:255|nullable', + 'transactions.*.source_bic' => 'min:1|max:255|nullable|bic', // destination of transaction - 'transactions.*.destination_id' => ['numeric', 'nullable', new BelongsUser()], - 'transactions.*.destination_name' => 'min:1|max:255|nullable', - 'transactions.*.destination_iban' => 'min:1|max:255|nullable|iban', - 'transactions.*.destination_number' => 'min:1|max:255|nullable', - 'transactions.*.destination_bic' => 'min:1|max:255|nullable|bic', + 'transactions.*.destination_id' => ['numeric', 'nullable', new BelongsUser()], + 'transactions.*.destination_name' => 'min:1|max:255|nullable', + 'transactions.*.destination_iban' => 'min:1|max:255|nullable|iban', + 'transactions.*.destination_number' => 'min:1|max:255|nullable', + 'transactions.*.destination_bic' => 'min:1|max:255|nullable|bic', // budget, category, bill and piggy - 'transactions.*.budget_id' => ['mustExist:budgets,id', new BelongsUser()], - 'transactions.*.budget_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], - 'transactions.*.category_id' => ['mustExist:categories,id', new BelongsUser(), 'nullable'], - 'transactions.*.category_name' => 'min:1|max:255|nullable', - 'transactions.*.bill_id' => ['numeric', 'nullable', 'mustExist:bills,id', new BelongsUser()], - 'transactions.*.bill_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], - 'transactions.*.piggy_bank_id' => ['numeric', 'nullable', 'mustExist:piggy_banks,id', new BelongsUser()], - 'transactions.*.piggy_bank_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], + 'transactions.*.budget_id' => ['mustExist:budgets,id', new BelongsUser()], + 'transactions.*.budget_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], + 'transactions.*.category_id' => ['mustExist:categories,id', new BelongsUser(), 'nullable'], + 'transactions.*.category_name' => 'min:1|max:255|nullable', + 'transactions.*.bill_id' => ['numeric', 'nullable', 'mustExist:bills,id', new BelongsUser()], + 'transactions.*.bill_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], + 'transactions.*.piggy_bank_id' => ['numeric', 'nullable', 'mustExist:piggy_banks,id', new BelongsUser()], + 'transactions.*.piggy_bank_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], // other interesting fields - 'transactions.*.reconciled' => [new IsBoolean()], - 'transactions.*.notes' => 'min:1|max:32768|nullable', - 'transactions.*.tags' => 'min:0|max:255', - 'transactions.*.tags.*' => 'min:0|max:255', + 'transactions.*.reconciled' => [new IsBoolean()], + 'transactions.*.notes' => 'min:1|max:32768|nullable', + 'transactions.*.tags' => 'min:0|max:255', + 'transactions.*.tags.*' => 'min:0|max:255', // meta info fields - 'transactions.*.internal_reference' => 'min:1|max:255|nullable', - 'transactions.*.external_id' => 'min:1|max:255|nullable', - 'transactions.*.recurrence_id' => 'min:1|max:255|nullable', - 'transactions.*.bunq_payment_id' => 'min:1|max:255|nullable', - 'transactions.*.external_url' => sprintf('min:1|max:255|nullable|url:%s', $validProtocols), + 'transactions.*.internal_reference' => 'min:1|max:255|nullable', + 'transactions.*.external_id' => 'min:1|max:255|nullable', + 'transactions.*.recurrence_id' => 'min:1|max:255|nullable', + 'transactions.*.bunq_payment_id' => 'min:1|max:255|nullable', + 'transactions.*.external_url' => sprintf('min:1|max:255|nullable|url:%s', $validProtocols), // SEPA fields: - 'transactions.*.sepa_cc' => 'min:1|max:255|nullable', - 'transactions.*.sepa_ct_op' => 'min:1|max:255|nullable', - 'transactions.*.sepa_ct_id' => 'min:1|max:255|nullable', - 'transactions.*.sepa_db' => 'min:1|max:255|nullable', - 'transactions.*.sepa_country' => 'min:1|max:255|nullable', - 'transactions.*.sepa_ep' => 'min:1|max:255|nullable', - 'transactions.*.sepa_ci' => 'min:1|max:255|nullable', - 'transactions.*.sepa_batch_id' => 'min:1|max:255|nullable', + 'transactions.*.sepa_cc' => 'min:1|max:255|nullable', + 'transactions.*.sepa_ct_op' => 'min:1|max:255|nullable', + 'transactions.*.sepa_ct_id' => 'min:1|max:255|nullable', + 'transactions.*.sepa_db' => 'min:1|max:255|nullable', + 'transactions.*.sepa_country' => 'min:1|max:255|nullable', + 'transactions.*.sepa_ep' => 'min:1|max:255|nullable', + 'transactions.*.sepa_ci' => 'min:1|max:255|nullable', + 'transactions.*.sepa_batch_id' => 'min:1|max:255|nullable', // dates - 'transactions.*.interest_date' => 'date|nullable', - 'transactions.*.book_date' => 'date|nullable', - 'transactions.*.process_date' => 'date|nullable', - 'transactions.*.due_date' => 'date|nullable', - 'transactions.*.payment_date' => 'date|nullable', - 'transactions.*.invoice_date' => 'date|nullable', + 'transactions.*.interest_date' => 'date|nullable', + 'transactions.*.book_date' => 'date|nullable', + 'transactions.*.process_date' => 'date|nullable', + 'transactions.*.due_date' => 'date|nullable', + 'transactions.*.payment_date' => 'date|nullable', + 'transactions.*.invoice_date' => 'date|nullable' ]; } @@ -272,35 +273,33 @@ class StoreRequest extends FormRequest */ public function withValidator(Validator $validator): void { - $validator->after( - function (Validator $validator): void { - // must be valid array. - $this->validateTransactionArray($validator); + $validator->after(function (Validator $validator): void { + // must be valid array. + $this->validateTransactionArray($validator); - // must submit at least one transaction. - Log::debug('Now going to validateOneTransaction'); - $this->validateOneTransaction($validator); - Log::debug('Now done with validateOneTransaction'); + // must submit at least one transaction. + Log::debug('Now going to validateOneTransaction'); + $this->validateOneTransaction($validator); + Log::debug('Now done with validateOneTransaction'); - // all journals must have a description - $this->validateDescriptions($validator); + // all journals must have a description + $this->validateDescriptions($validator); - // all transaction types must be equal: - $this->validateTransactionTypes($validator); + // all transaction types must be equal: + $this->validateTransactionTypes($validator); - // validate foreign currency info - $this->validateForeignCurrencyInformation($validator); + // validate foreign currency info + $this->validateForeignCurrencyInformation($validator); - // validate all account info - $this->validateAccountInformation($validator); + // validate all account info + $this->validateAccountInformation($validator); - // validate source/destination is equal, depending on the transaction journal type. - $this->validateEqualAccounts($validator); + // validate source/destination is equal, depending on the transaction journal type. + $this->validateEqualAccounts($validator); - // the group must have a description if > 1 journal. - $this->validateGroupDescription($validator); - } - ); + // the group must have a description if > 1 journal. + $this->validateGroupDescription($validator); + }); if ($validator->fails()) { Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray()); } diff --git a/app/Api/V1/Requests/Models/Transaction/UpdateRequest.php b/app/Api/V1/Requests/Models/Transaction/UpdateRequest.php index 7ea7b26988..393630b924 100644 --- a/app/Api/V1/Requests/Models/Transaction/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/Transaction/UpdateRequest.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Requests\Models\Transaction; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\TransactionGroup; use FireflyIII\Rules\BelongsUser; @@ -32,13 +31,14 @@ use FireflyIII\Rules\IsBoolean; use FireflyIII\Rules\IsDateOrTime; use FireflyIII\Rules\IsValidPositiveAmount; use FireflyIII\Rules\IsValidZeroOrMoreAmount; +use FireflyIII\Support\Facades\FireflyConfig; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; use FireflyIII\Validation\GroupValidation; use FireflyIII\Validation\TransactionValidation; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; -use FireflyIII\Support\Facades\FireflyConfig; /** * Class UpdateRequest @@ -66,15 +66,54 @@ class UpdateRequest extends FormRequest public function getAll(): array { Log::debug(sprintf('Now in %s', __METHOD__)); - $this->integerFields = ['order', 'currency_id', 'foreign_currency_id', 'transaction_journal_id', 'source_id', 'destination_id', 'budget_id', 'category_id', 'bill_id', 'recurrence_id']; - $this->dateFields = ['date', 'interest_date', 'book_date', 'process_date', 'due_date', 'payment_date', 'invoice_date']; + $this->integerFields = [ + 'order', + 'currency_id', + 'foreign_currency_id', + 'transaction_journal_id', + 'source_id', + 'destination_id', + 'budget_id', + 'category_id', + 'bill_id', + 'recurrence_id' + ]; + $this->dateFields = ['date', 'interest_date', 'book_date', 'process_date', 'due_date', 'payment_date', 'invoice_date']; $this->textareaFields = ['notes']; // not really floats, for validation. - $this->floatFields = ['amount', 'foreign_amount']; - $this->stringFields = ['type', 'currency_code', 'foreign_currency_code', 'description', 'source_name', 'source_iban', 'source_number', 'source_bic', 'destination_name', 'destination_iban', 'destination_number', 'destination_bic', 'budget_name', 'category_name', 'bill_name', 'internal_reference', 'external_id', 'bunq_payment_id', 'sepa_cc', 'sepa_ct_op', 'sepa_ct_id', 'sepa_db', 'sepa_country', 'sepa_ep', 'sepa_ci', 'sepa_batch_id', 'external_url']; - $this->booleanFields = ['reconciled']; - $this->arrayFields = ['tags']; - $data = []; + $this->floatFields = ['amount', 'foreign_amount']; + $this->stringFields = [ + 'type', + 'currency_code', + 'foreign_currency_code', + 'description', + 'source_name', + 'source_iban', + 'source_number', + 'source_bic', + 'destination_name', + 'destination_iban', + 'destination_number', + 'destination_bic', + 'budget_name', + 'category_name', + 'bill_name', + 'internal_reference', + 'external_id', + 'bunq_payment_id', + 'sepa_cc', + 'sepa_ct_op', + 'sepa_ct_id', + 'sepa_db', + 'sepa_country', + 'sepa_ep', + 'sepa_ci', + 'sepa_batch_id', + 'external_url' + ]; + $this->booleanFields = ['reconciled']; + $this->arrayFields = ['tags']; + $data = []; if ($this->has('transactions')) { $data['transactions'] = $this->getTransactionData(); } @@ -99,7 +138,7 @@ class UpdateRequest extends FormRequest private function getTransactionData(): array { Log::debug(sprintf('Now in %s', __METHOD__)); - $return = []; + $return = []; /** @var null|array $transactions */ $transactions = $this->get('transactions'); @@ -114,14 +153,14 @@ class UpdateRequest extends FormRequest throw new FireflyException('Invalid data submitted: transaction is not array.'); } // default response is to update nothing in the transaction: - $current = []; - $current = $this->getIntegerData($current, $transaction); - $current = $this->getStringData($current, $transaction); - $current = $this->getNlStringData($current, $transaction); - $current = $this->getDateData($current, $transaction); - $current = $this->getBooleanData($current, $transaction); - $current = $this->getArrayData($current, $transaction); - $current = $this->getFloatData($current, $transaction); + $current = []; + $current = $this->getIntegerData($current, $transaction); + $current = $this->getStringData($current, $transaction); + $current = $this->getNlStringData($current, $transaction); + $current = $this->getDateData($current, $transaction); + $current = $this->getBooleanData($current, $transaction); + $current = $this->getArrayData($current, $transaction); + $current = $this->getFloatData($current, $transaction); $return[] = $current; } @@ -253,76 +292,76 @@ class UpdateRequest extends FormRequest return [ // basic fields for group: - 'group_title' => 'min:1|max:1000|nullable', - 'apply_rules' => [new IsBoolean()], + 'group_title' => 'min:1|max:1000|nullable', + 'apply_rules' => [new IsBoolean()], // transaction rules (in array for splits): - 'transactions.*.type' => 'in:withdrawal,deposit,transfer,opening-balance,reconciliation', - 'transactions.*.date' => [new IsDateOrTime()], - 'transactions.*.order' => 'numeric|min:0', + 'transactions.*.type' => 'in:withdrawal,deposit,transfer,opening-balance,reconciliation', + 'transactions.*.date' => [new IsDateOrTime()], + 'transactions.*.order' => 'numeric|min:0', // group id: 'transactions.*.transaction_journal_id' => ['nullable', 'numeric', new BelongsUser()], // currency info - 'transactions.*.currency_id' => 'numeric|exists:transaction_currencies,id|nullable', - 'transactions.*.currency_code' => 'min:3|max:51|exists:transaction_currencies,code|nullable', - 'transactions.*.foreign_currency_id' => 'nullable|numeric|exists:transaction_currencies,id', - 'transactions.*.foreign_currency_code' => 'nullable|min:3|max:51|exists:transaction_currencies,code', + 'transactions.*.currency_id' => 'numeric|exists:transaction_currencies,id|nullable', + 'transactions.*.currency_code' => 'min:3|max:51|exists:transaction_currencies,code|nullable', + 'transactions.*.foreign_currency_id' => 'nullable|numeric|exists:transaction_currencies,id', + 'transactions.*.foreign_currency_code' => 'nullable|min:3|max:51|exists:transaction_currencies,code', // amount - 'transactions.*.amount' => [new IsValidPositiveAmount()], - 'transactions.*.foreign_amount' => ['nullable', new IsValidZeroOrMoreAmount()], + 'transactions.*.amount' => [new IsValidPositiveAmount()], + 'transactions.*.foreign_amount' => ['nullable', new IsValidZeroOrMoreAmount()], // description - 'transactions.*.description' => 'nullable|min:1|max:1000', + 'transactions.*.description' => 'nullable|min:1|max:1000', // source of transaction - 'transactions.*.source_id' => ['numeric', 'nullable', new BelongsUser()], - 'transactions.*.source_name' => 'min:1|max:255|nullable', + 'transactions.*.source_id' => ['numeric', 'nullable', new BelongsUser()], + 'transactions.*.source_name' => 'min:1|max:255|nullable', // destination of transaction - 'transactions.*.destination_id' => ['numeric', 'nullable', new BelongsUser()], - 'transactions.*.destination_name' => 'min:1|max:255|nullable', + 'transactions.*.destination_id' => ['numeric', 'nullable', new BelongsUser()], + 'transactions.*.destination_name' => 'min:1|max:255|nullable', // budget, category, bill and piggy - 'transactions.*.budget_id' => ['mustExist:budgets,id', new BelongsUser(), 'nullable'], - 'transactions.*.budget_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], - 'transactions.*.category_id' => ['mustExist:categories,id', new BelongsUser(), 'nullable'], - 'transactions.*.category_name' => 'min:1|max:255|nullable', - 'transactions.*.bill_id' => ['numeric', 'nullable', 'mustExist:bills,id', new BelongsUser()], - 'transactions.*.bill_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], + 'transactions.*.budget_id' => ['mustExist:budgets,id', new BelongsUser(), 'nullable'], + 'transactions.*.budget_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], + 'transactions.*.category_id' => ['mustExist:categories,id', new BelongsUser(), 'nullable'], + 'transactions.*.category_name' => 'min:1|max:255|nullable', + 'transactions.*.bill_id' => ['numeric', 'nullable', 'mustExist:bills,id', new BelongsUser()], + 'transactions.*.bill_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], // other interesting fields - 'transactions.*.reconciled' => [new IsBoolean()], - 'transactions.*.notes' => 'min:1|max:32768|nullable', - 'transactions.*.tags' => 'min:0|max:255|nullable', - 'transactions.*.tags.*' => 'min:0|max:255', + 'transactions.*.reconciled' => [new IsBoolean()], + 'transactions.*.notes' => 'min:1|max:32768|nullable', + 'transactions.*.tags' => 'min:0|max:255|nullable', + 'transactions.*.tags.*' => 'min:0|max:255', // meta info fields - 'transactions.*.internal_reference' => 'min:1|max:255|nullable', - 'transactions.*.external_id' => 'min:1|max:255|nullable', - 'transactions.*.recurrence_id' => 'min:1|max:255|nullable', - 'transactions.*.bunq_payment_id' => 'min:1|max:255|nullable', - 'transactions.*.external_url' => sprintf('min:1|max:255|nullable|url:%s', $validProtocols), + 'transactions.*.internal_reference' => 'min:1|max:255|nullable', + 'transactions.*.external_id' => 'min:1|max:255|nullable', + 'transactions.*.recurrence_id' => 'min:1|max:255|nullable', + 'transactions.*.bunq_payment_id' => 'min:1|max:255|nullable', + 'transactions.*.external_url' => sprintf('min:1|max:255|nullable|url:%s', $validProtocols), // SEPA fields: - 'transactions.*.sepa_cc' => 'min:1|max:255|nullable', - 'transactions.*.sepa_ct_op' => 'min:1|max:255|nullable', - 'transactions.*.sepa_ct_id' => 'min:1|max:255|nullable', - 'transactions.*.sepa_db' => 'min:1|max:255|nullable', - 'transactions.*.sepa_country' => 'min:1|max:255|nullable', - 'transactions.*.sepa_ep' => 'min:1|max:255|nullable', - 'transactions.*.sepa_ci' => 'min:1|max:255|nullable', - 'transactions.*.sepa_batch_id' => 'min:1|max:255|nullable', + 'transactions.*.sepa_cc' => 'min:1|max:255|nullable', + 'transactions.*.sepa_ct_op' => 'min:1|max:255|nullable', + 'transactions.*.sepa_ct_id' => 'min:1|max:255|nullable', + 'transactions.*.sepa_db' => 'min:1|max:255|nullable', + 'transactions.*.sepa_country' => 'min:1|max:255|nullable', + 'transactions.*.sepa_ep' => 'min:1|max:255|nullable', + 'transactions.*.sepa_ci' => 'min:1|max:255|nullable', + 'transactions.*.sepa_batch_id' => 'min:1|max:255|nullable', // dates - 'transactions.*.interest_date' => 'date|nullable', - 'transactions.*.book_date' => 'date|nullable', - 'transactions.*.process_date' => 'date|nullable', - 'transactions.*.due_date' => 'date|nullable', - 'transactions.*.payment_date' => 'date|nullable', - 'transactions.*.invoice_date' => 'date|nullable', + 'transactions.*.interest_date' => 'date|nullable', + 'transactions.*.book_date' => 'date|nullable', + 'transactions.*.process_date' => 'date|nullable', + 'transactions.*.due_date' => 'date|nullable', + 'transactions.*.payment_date' => 'date|nullable', + 'transactions.*.invoice_date' => 'date|nullable' ]; } @@ -335,33 +374,31 @@ class UpdateRequest extends FormRequest /** @var TransactionGroup $transactionGroup */ $transactionGroup = $this->route()->parameter('transactionGroup'); - $validator->after( - function (Validator $validator) use ($transactionGroup): void { - // if more than one, verify that there are journal ID's present. - $this->validateJournalIds($validator, $transactionGroup); + $validator->after(function (Validator $validator) use ($transactionGroup): void { + // if more than one, verify that there are journal ID's present. + $this->validateJournalIds($validator, $transactionGroup); - // if more than one split, needs group title - $this->validateGroupDescription($validator); + // if more than one split, needs group title + $this->validateGroupDescription($validator); - // all transaction types must be equal: - $this->validateTransactionTypesForUpdate($validator); + // all transaction types must be equal: + $this->validateTransactionTypesForUpdate($validator); - // user wants to update a reconciled transaction. - // source, destination, amount + foreign_amount cannot be changed - // and must be omitted from the request. - $this->preventUpdateReconciled($validator, $transactionGroup); + // user wants to update a reconciled transaction. + // source, destination, amount + foreign_amount cannot be changed + // and must be omitted from the request. + $this->preventUpdateReconciled($validator, $transactionGroup); - // validate source/destination is equal, depending on the transaction journal type. - $this->validateEqualAccountsForUpdate($validator, $transactionGroup); + // validate source/destination is equal, depending on the transaction journal type. + $this->validateEqualAccountsForUpdate($validator, $transactionGroup); - // see method: - // $this->preventNoAccountInfo($validator, ); + // see method: + // $this->preventNoAccountInfo($validator, ); - // validate that the currency fits the source and/or destination account. - // validate all account info - $this->validateAccountInformationUpdate($validator, $transactionGroup); - } - ); + // validate that the currency fits the source and/or destination account. + // validate all account info + $this->validateAccountInformationUpdate($validator, $transactionGroup); + }); if ($validator->fails()) { Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray()); } diff --git a/app/Api/V1/Requests/Models/TransactionCurrency/CurrencyCodeRequest.php b/app/Api/V1/Requests/Models/TransactionCurrency/CurrencyCodeRequest.php index 833ce92b1e..b40d62d676 100644 --- a/app/Api/V1/Requests/Models/TransactionCurrency/CurrencyCodeRequest.php +++ b/app/Api/V1/Requests/Models/TransactionCurrency/CurrencyCodeRequest.php @@ -1,6 +1,7 @@ sprintf('exists:transaction_currencies,code|%s', $this->required), - ]; + return ['code' => sprintf('exists:transaction_currencies,code|%s', $this->required)]; } public function withValidator(Validator $validator): void { - $validator->after( - function (Validator $validator): void { - if (!$validator->valid()) { - return; - } - $code = $this->convertString('code', ''); - $this->attributes->set('code', $code); + $validator->after(function (Validator $validator): void { + if (!$validator->valid()) { + return; } - ); + $code = $this->convertString('code', ''); + $this->attributes->set('code', $code); + }); } } diff --git a/app/Api/V1/Requests/Models/TransactionCurrency/StoreRequest.php b/app/Api/V1/Requests/Models/TransactionCurrency/StoreRequest.php index d3aa5df6dc..b07ffcba95 100644 --- a/app/Api/V1/Requests/Models/TransactionCurrency/StoreRequest.php +++ b/app/Api/V1/Requests/Models/TransactionCurrency/StoreRequest.php @@ -57,7 +57,7 @@ class StoreRequest extends FormRequest 'symbol' => $this->convertString('symbol'), 'decimal_places' => $this->convertInteger('decimal_places'), 'default' => $default, - 'enabled' => $enabled, + 'enabled' => $enabled ]; } @@ -72,7 +72,7 @@ class StoreRequest extends FormRequest 'symbol' => 'required|min:1|max:32|unique:transaction_currencies,symbol', 'decimal_places' => 'numeric|min:0|max:12', 'enabled' => [new IsBoolean()], - 'default' => [new IsBoolean()], + 'default' => [new IsBoolean()] ]; } } diff --git a/app/Api/V1/Requests/Models/TransactionCurrency/UpdateRequest.php b/app/Api/V1/Requests/Models/TransactionCurrency/UpdateRequest.php index e4687c0edb..633e1f409e 100644 --- a/app/Api/V1/Requests/Models/TransactionCurrency/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/TransactionCurrency/UpdateRequest.php @@ -50,7 +50,7 @@ class UpdateRequest extends FormRequest 'symbol' => ['symbol', 'convertString'], 'decimal_places' => ['decimal_places', 'convertInteger'], 'default' => ['default', 'boolean'], - 'enabled' => ['enabled', 'boolean'], + 'enabled' => ['enabled', 'boolean'] ]; return $this->getAllData($fields); @@ -70,7 +70,7 @@ class UpdateRequest extends FormRequest 'symbol' => sprintf('min:1|max:32|unique:transaction_currencies,symbol,%d', $currency->id), 'decimal_places' => 'numeric|min:0|max:12', 'enabled' => [new IsBoolean()], - 'default' => [new IsBoolean()], + 'default' => [new IsBoolean()] ]; } } diff --git a/app/Api/V1/Requests/Models/TransactionLink/StoreRequest.php b/app/Api/V1/Requests/Models/TransactionLink/StoreRequest.php index b93334289d..93b0e09555 100644 --- a/app/Api/V1/Requests/Models/TransactionLink/StoreRequest.php +++ b/app/Api/V1/Requests/Models/TransactionLink/StoreRequest.php @@ -24,12 +24,12 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Requests\Models\TransactionLink; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Repositories\LinkType\LinkTypeRepositoryInterface; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; use FireflyIII\User; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -51,7 +51,7 @@ class StoreRequest extends FormRequest 'link_type_name' => $this->convertString('link_type_name'), 'inward_id' => $this->convertInteger('inward_id'), 'outward_id' => $this->convertInteger('outward_id'), - 'notes' => $this->stringWithNewlines('notes'), + 'notes' => $this->stringWithNewlines('notes') ]; } @@ -65,7 +65,7 @@ class StoreRequest extends FormRequest 'link_type_name' => 'exists:link_types,name|required_without:link_type_id', 'inward_id' => 'required|belongsToUser:transaction_journals,id|different:outward_id', 'outward_id' => 'required|belongsToUser:transaction_journals,id|different:inward_id', - 'notes' => 'min:1|max:32768|nullable', + 'notes' => 'min:1|max:32768|nullable' ]; } @@ -74,11 +74,9 @@ class StoreRequest extends FormRequest */ public function withValidator(Validator $validator): void { - $validator->after( - function (Validator $validator): void { - $this->validateExistingLink($validator); - } - ); + $validator->after(function (Validator $validator): void { + $this->validateExistingLink($validator); + }); if ($validator->fails()) { Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray()); } @@ -87,21 +85,21 @@ class StoreRequest extends FormRequest private function validateExistingLink(Validator $validator): void { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var LinkTypeRepositoryInterface $repository */ - $repository = app(LinkTypeRepositoryInterface::class); + $repository = app(LinkTypeRepositoryInterface::class); $repository->setUser($user); /** @var JournalRepositoryInterface $journalRepos */ $journalRepos = app(JournalRepositoryInterface::class); $journalRepos->setUser($user); - $data = $validator->getData(); - $inwardId = (int) ($data['inward_id'] ?? 0); - $outwardId = (int) ($data['outward_id'] ?? 0); - $inward = $journalRepos->find($inwardId); - $outward = $journalRepos->find($outwardId); + $data = $validator->getData(); + $inwardId = (int) ($data['inward_id'] ?? 0); + $outwardId = (int) ($data['outward_id'] ?? 0); + $inward = $journalRepos->find($inwardId); + $outward = $journalRepos->find($outwardId); if (null === $inward) { $validator->errors()->add('inward_id', 'Invalid inward ID.'); diff --git a/app/Api/V1/Requests/Models/TransactionLink/UpdateRequest.php b/app/Api/V1/Requests/Models/TransactionLink/UpdateRequest.php index ce62f5a87c..4472a72546 100644 --- a/app/Api/V1/Requests/Models/TransactionLink/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/TransactionLink/UpdateRequest.php @@ -24,12 +24,12 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Requests\Models\TransactionLink; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Models\TransactionJournalLink; use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Repositories\LinkType\LinkTypeRepositoryInterface; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -51,7 +51,7 @@ class UpdateRequest extends FormRequest 'link_type_name' => $this->convertString('link_type_name'), 'inward_id' => $this->convertInteger('inward_id'), 'outward_id' => $this->convertInteger('outward_id'), - 'notes' => $this->stringWithNewlines('notes'), + 'notes' => $this->stringWithNewlines('notes') ]; } @@ -65,7 +65,7 @@ class UpdateRequest extends FormRequest 'link_type_name' => 'exists:link_types,name', 'inward_id' => 'belongsToUser:transaction_journals,id|different:outward_id', 'outward_id' => 'belongsToUser:transaction_journals,id|different:inward_id', - 'notes' => 'min:1|max:32768|nullable', + 'notes' => 'min:1|max:32768|nullable' ]; } @@ -74,11 +74,9 @@ class UpdateRequest extends FormRequest */ public function withValidator(Validator $validator): void { - $validator->after( - function (Validator $validator): void { - $this->validateUpdate($validator); - } - ); + $validator->after(function (Validator $validator): void { + $this->validateUpdate($validator); + }); if ($validator->fails()) { Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray()); } @@ -87,21 +85,21 @@ class UpdateRequest extends FormRequest private function validateUpdate(Validator $validator): void { /** @var TransactionJournalLink $existing */ - $existing = $this->route()->parameter('journalLink'); - $data = $validator->getData(); + $existing = $this->route()->parameter('journalLink'); + $data = $validator->getData(); /** @var LinkTypeRepositoryInterface $repository */ - $repository = app(LinkTypeRepositoryInterface::class); + $repository = app(LinkTypeRepositoryInterface::class); $repository->setUser(auth()->user()); /** @var JournalRepositoryInterface $journalRepos */ $journalRepos = app(JournalRepositoryInterface::class); $journalRepos->setUser(auth()->user()); - $inwardId = $data['inward_id'] ?? $existing->source_id; - $outwardId = $data['outward_id'] ?? $existing->destination_id; - $inward = $journalRepos->find((int) $inwardId); - $outward = $journalRepos->find((int) $outwardId); + $inwardId = $data['inward_id'] ?? $existing->source_id; + $outwardId = $data['outward_id'] ?? $existing->destination_id; + $inward = $journalRepos->find((int) $inwardId); + $outward = $journalRepos->find((int) $outwardId); if (null === $inward) { $inward = $existing->source; } @@ -113,7 +111,7 @@ class UpdateRequest extends FormRequest $validator->errors()->add('outward_id', 'Inward ID must be different from outward ID.'); } - $inDB = $repository->findSpecificLink($existing->linkType, $inward, $outward); + $inDB = $repository->findSpecificLink($existing->linkType, $inward, $outward); if (null === $inDB) { return; } diff --git a/app/Api/V1/Requests/Models/TransactionLinkType/StoreRequest.php b/app/Api/V1/Requests/Models/TransactionLinkType/StoreRequest.php index d62bae1550..e0ef99a840 100644 --- a/app/Api/V1/Requests/Models/TransactionLinkType/StoreRequest.php +++ b/app/Api/V1/Requests/Models/TransactionLinkType/StoreRequest.php @@ -41,11 +41,7 @@ class StoreRequest extends FormRequest */ public function getAll(): array { - return [ - 'name' => $this->convertString('name'), - 'outward' => $this->convertString('outward'), - 'inward' => $this->convertString('inward'), - ]; + return ['name' => $this->convertString('name'), 'outward' => $this->convertString('outward'), 'inward' => $this->convertString('inward')]; } /** @@ -56,7 +52,7 @@ class StoreRequest extends FormRequest return [ 'name' => 'required|unique:link_types,name|min:1|max:1024', 'outward' => 'required|unique:link_types,outward|min:1|different:inward|max:1024', - 'inward' => 'required|unique:link_types,inward|min:1|different:outward|max:1024', + 'inward' => 'required|unique:link_types,inward|min:1|different:outward|max:1024' ]; } } diff --git a/app/Api/V1/Requests/Models/TransactionLinkType/UpdateRequest.php b/app/Api/V1/Requests/Models/TransactionLinkType/UpdateRequest.php index d924645515..292bba6898 100644 --- a/app/Api/V1/Requests/Models/TransactionLinkType/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/TransactionLinkType/UpdateRequest.php @@ -43,11 +43,7 @@ class UpdateRequest extends FormRequest */ public function getAll(): array { - return [ - 'name' => $this->convertString('name'), - 'outward' => $this->convertString('outward'), - 'inward' => $this->convertString('inward'), - ]; + return ['name' => $this->convertString('name'), 'outward' => $this->convertString('outward'), 'inward' => $this->convertString('inward')]; } /** @@ -61,7 +57,7 @@ class UpdateRequest extends FormRequest return [ 'name' => [Rule::unique('link_types', 'name')->ignore($linkType->id), 'min:1', 'max:1024'], 'outward' => ['different:inward', Rule::unique('link_types', 'outward')->ignore($linkType->id), 'min:1', 'max:1024'], - 'inward' => ['different:outward', Rule::unique('link_types', 'inward')->ignore($linkType->id), 'min:1', 'max:1024'], + 'inward' => ['different:outward', Rule::unique('link_types', 'inward')->ignore($linkType->id), 'min:1', 'max:1024'] ]; } } diff --git a/app/Api/V1/Requests/Models/UserGroup/UpdateRequest.php b/app/Api/V1/Requests/Models/UserGroup/UpdateRequest.php index 20c75a9342..e889f2b96d 100644 --- a/app/Api/V1/Requests/Models/UserGroup/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/UserGroup/UpdateRequest.php @@ -41,7 +41,7 @@ class UpdateRequest extends FormRequest $fields = [ 'title' => ['title', 'convertString'], 'primary_currency_id' => ['primary_currency_id', 'convertInteger'], - 'primary_currency_code' => ['primary_currency_code', 'convertString'], + 'primary_currency_code' => ['primary_currency_code', 'convertString'] ]; return $this->getAllData($fields); @@ -55,7 +55,7 @@ class UpdateRequest extends FormRequest return [ 'title' => ['required', 'min:1', 'max:255'], 'primary_currency_id' => 'exists:transaction_currencies,id', - 'primary_currency_code' => 'exists:transaction_currencies,code', + 'primary_currency_code' => 'exists:transaction_currencies,code' ]; } } diff --git a/app/Api/V1/Requests/Models/Webhook/CreateRequest.php b/app/Api/V1/Requests/Models/Webhook/CreateRequest.php index 586de7e348..6b38178e8b 100644 --- a/app/Api/V1/Requests/Models/Webhook/CreateRequest.php +++ b/app/Api/V1/Requests/Models/Webhook/CreateRequest.php @@ -27,11 +27,11 @@ namespace FireflyIII\Api\V1\Requests\Models\Webhook; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Webhook; use FireflyIII\Rules\IsBoolean; +use FireflyIII\Support\Facades\FireflyConfig; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; use FireflyIII\Support\Request\ValidatesWebhooks; use Illuminate\Foundation\Http\FormRequest; -use FireflyIII\Support\Facades\FireflyConfig; /** * Class CreateRequest @@ -44,23 +44,18 @@ class CreateRequest extends FormRequest public function getData(): array { - $fields = [ - 'title' => ['title', 'convertString'], - 'active' => ['active', 'boolean'], - 'url' => ['url', 'convertString'], - ]; - $triggers = $this->get('triggers', []); - $responses = $this->get('responses', []); - $deliveries = $this->get('deliveries', []); + $fields = ['title' => ['title', 'convertString'], 'active' => ['active', 'boolean'], 'url' => ['url', 'convertString']]; + $triggers = $this->get('triggers', []); + $responses = $this->get('responses', []); + $deliveries = $this->get('deliveries', []); if (in_array(0, [count($triggers), count($responses), count($deliveries)], true)) { throw new FireflyException('Unexpectedly got no responses, triggers or deliveries.'); } - - $return = $this->getAllData($fields); - $return['triggers'] = $triggers; - $return['responses'] = $responses; + $return = $this->getAllData($fields); + $return['triggers'] = $triggers; + $return['responses'] = $responses; $return['deliveries'] = $deliveries; return $return; @@ -88,7 +83,7 @@ class CreateRequest extends FormRequest 'delivery' => 'prohibited', 'deliveries' => 'required|array|min:1|max:1', 'deliveries.*' => sprintf('required|in:%s', $deliveries), - 'url' => ['required', sprintf('url:%s', $validProtocols)], + 'url' => ['required', sprintf('url:%s', $validProtocols)] ]; } } diff --git a/app/Api/V1/Requests/Models/Webhook/UpdateRequest.php b/app/Api/V1/Requests/Models/Webhook/UpdateRequest.php index f5e6d21666..ec57d9e283 100644 --- a/app/Api/V1/Requests/Models/Webhook/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/Webhook/UpdateRequest.php @@ -27,11 +27,11 @@ namespace FireflyIII\Api\V1\Requests\Models\Webhook; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Webhook; use FireflyIII\Rules\IsBoolean; +use FireflyIII\Support\Facades\FireflyConfig; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; use FireflyIII\Support\Request\ValidatesWebhooks; use Illuminate\Foundation\Http\FormRequest; -use FireflyIII\Support\Facades\FireflyConfig; /** * Class UpdateRequest @@ -44,23 +44,19 @@ class UpdateRequest extends FormRequest public function getData(): array { - $fields = [ - 'title' => ['title', 'convertString'], - 'active' => ['active', 'boolean'], - 'url' => ['url', 'convertString'], - ]; + $fields = ['title' => ['title', 'convertString'], 'active' => ['active', 'boolean'], 'url' => ['url', 'convertString']]; - $triggers = $this->get('triggers', []); - $responses = $this->get('responses', []); - $deliveries = $this->get('deliveries', []); + $triggers = $this->get('triggers', []); + $responses = $this->get('responses', []); + $deliveries = $this->get('deliveries', []); if (in_array(0, [count($triggers), count($responses), count($deliveries)], true)) { throw new FireflyException('Unexpectedly got no responses, triggers or deliveries.'); } - $return = $this->getAllData($fields); - $return['triggers'] = $triggers; - $return['responses'] = $responses; + $return = $this->getAllData($fields); + $return['triggers'] = $triggers; + $return['responses'] = $responses; $return['deliveries'] = $deliveries; return $return; @@ -77,23 +73,10 @@ class UpdateRequest extends FormRequest $validProtocols = FireflyConfig::get('valid_url_protocols', config('firefly.valid_url_protocols'))->data; /** @var Webhook $webhook */ - $webhook = $this->route()->parameter('webhook'); + $webhook = $this->route()->parameter('webhook'); - return [ - 'title' => sprintf('min:1|max:255|uniqueObjectForUser:webhooks,title,%d', $webhook->id), - 'active' => [new IsBoolean()], - - 'trigger' => 'prohibited', - 'triggers' => 'required|array|min:1|max:10', - 'triggers.*' => sprintf('required|in:%s', $triggers), - 'response' => 'prohibited', - 'responses' => 'required|array|min:1|max:1', - 'responses.*' => sprintf('required|in:%s', $responses), - 'delivery' => 'prohibited', - 'deliveries' => 'required|array|min:1|max:1', - 'deliveries.*' => sprintf('required|in:%s', $deliveries), - - 'url' => [sprintf('url:%s', $validProtocols), sprintf('uniqueExistingWebhook:%d', $webhook->id)], - ]; + return ['title' => sprintf('min:1|max:255|uniqueObjectForUser:webhooks,title,%d', $webhook->id), 'active' => [new IsBoolean()], + 'trigger' => 'prohibited', 'triggers' => 'required|array|min:1|max:10', 'triggers.*' => sprintf('required|in:%s', $triggers), 'response' => 'prohibited', 'responses' => 'required|array|min:1|max:1', 'responses.*' => sprintf('required|in:%s', $responses), 'delivery' => 'prohibited', 'deliveries' => 'required|array|min:1|max:1', 'deliveries.*' => sprintf('required|in:%s', $deliveries), + 'url' => [sprintf('url:%s', $validProtocols), sprintf('uniqueExistingWebhook:%d', $webhook->id)]]; } } diff --git a/app/Api/V1/Requests/PaginationRequest.php b/app/Api/V1/Requests/PaginationRequest.php index 1dad0ca20f..a8182083eb 100644 --- a/app/Api/V1/Requests/PaginationRequest.php +++ b/app/Api/V1/Requests/PaginationRequest.php @@ -23,16 +23,16 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Requests; -use Override; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Rules\IsValidSortInstruction; use FireflyIII\Support\Facades\Preferences; use FireflyIII\User; +use Illuminate\Contracts\Validation\Validator; +use Override; use RuntimeException; class PaginationRequest extends ApiRequest { - private ?string $sortClass = null; + private null|string $sortClass = null; #[Override] public function handleConfig(array $config): void @@ -49,36 +49,34 @@ class PaginationRequest extends ApiRequest public function rules(): array { return [ - 'sort' => ['nullable', new IsValidSortInstruction((string)$this->sortClass)], + 'sort' => ['nullable', new IsValidSortInstruction((string) $this->sortClass)], 'limit' => 'numeric|min:1|max:131337', - 'page' => 'numeric|min:1|max:131337', + 'page' => 'numeric|min:1|max:131337' ]; } public function withValidator(Validator $validator): void { - $validator->after( - function (Validator $validator): void { - if ($validator->failed()) { - return; - } - - $limit = $this->convertInteger('limit'); - if (0 === $limit) { - // get default for user: - /** @var User $user */ - $user = auth()->user(); - $limit = (int)Preferences::getForUser($user, 'listPageSize', 50)->data; - } - $page = $this->convertInteger('page'); - $page = min(max(1, $page), 2 ** 16); - $offset = ($page - 1) * $limit; - $sort = $this->sortClass ? $this->convertSortParameters('sort', $this->sortClass) : $this->get('sort'); - $this->attributes->set('limit', $limit); - $this->attributes->set('sort', $sort); - $this->attributes->set('page', $page); - $this->attributes->set('offset', $offset); + $validator->after(function (Validator $validator): void { + if ($validator->failed()) { + return; } - ); + + $limit = $this->convertInteger('limit'); + if (0 === $limit) { + // get default for user: + /** @var User $user */ + $user = auth()->user(); + $limit = (int) Preferences::getForUser($user, 'listPageSize', 50)->data; + } + $page = $this->convertInteger('page'); + $page = min(max(1, $page), 2 ** 16); + $offset = ($page - 1) * $limit; + $sort = $this->sortClass ? $this->convertSortParameters('sort', $this->sortClass) : $this->get('sort'); + $this->attributes->set('limit', $limit); + $this->attributes->set('sort', $sort); + $this->attributes->set('page', $page); + $this->attributes->set('offset', $offset); + }); } } diff --git a/app/Api/V1/Requests/Search/SearchQueryRequest.php b/app/Api/V1/Requests/Search/SearchQueryRequest.php index f3c4d9a0f3..32058afda7 100644 --- a/app/Api/V1/Requests/Search/SearchQueryRequest.php +++ b/app/Api/V1/Requests/Search/SearchQueryRequest.php @@ -1,6 +1,7 @@ sprintf('min:0|max:500|%s', $this->required), - ]; + return ['query' => sprintf('min:0|max:500|%s', $this->required)]; } public function withValidator(Validator $validator): void { - $validator->after( - function (Validator $validator): void { - if ($validator->failed()) { - return; - } - $query = $this->convertString('query'); - $this->attributes->set('query', $query); + $validator->after(function (Validator $validator): void { + if ($validator->failed()) { + return; } - ); + $query = $this->convertString('query'); + $this->attributes->set('query', $query); + }); } } diff --git a/app/Api/V1/Requests/Search/TransactionSearchRequest.php b/app/Api/V1/Requests/Search/TransactionSearchRequest.php index fa6df367b1..79d9b9a18b 100644 --- a/app/Api/V1/Requests/Search/TransactionSearchRequest.php +++ b/app/Api/V1/Requests/Search/TransactionSearchRequest.php @@ -1,6 +1,7 @@ TransactionJournal::class], - SearchQueryRequest::class, + SearchQueryRequest::class // [ObjectTypeApiRequest::class, 'object_type' => Account::class], ]; } diff --git a/app/Api/V1/Requests/Summary/BasicRequest.php b/app/Api/V1/Requests/Summary/BasicRequest.php index ce6ff670c0..a3a9b80aa2 100644 --- a/app/Api/V1/Requests/Summary/BasicRequest.php +++ b/app/Api/V1/Requests/Summary/BasicRequest.php @@ -1,6 +1,7 @@ false, - 'date' => today(config('app.timezone')), - ]; + $data = ['force' => false, 'date' => today(config('app.timezone'))]; if ($this->has('force')) { $data['force'] = $this->boolean('force'); } @@ -71,9 +68,6 @@ class CronRequest extends FormRequest */ public function rules(): array { - return [ - 'force' => 'in:true,false', - 'date' => 'nullable|date|after:1970-01-02|before:2038-01-17', - ]; + return ['force' => 'in:true,false', 'date' => 'nullable|date|after:1970-01-02|before:2038-01-17']; } } diff --git a/app/Api/V1/Requests/System/UpdateRequest.php b/app/Api/V1/Requests/System/UpdateRequest.php index ae91a4fe33..aa37e43ba9 100644 --- a/app/Api/V1/Requests/System/UpdateRequest.php +++ b/app/Api/V1/Requests/System/UpdateRequest.php @@ -37,7 +37,15 @@ class UpdateRequest extends FormRequest use ChecksLogin; use ConvertsDataTypes; - private array $booleans = ['configuration.is_demo_site', 'configuration.single_user_mode', 'configuration.enable_exchange_rates', 'configuration.use_running_balance', 'configuration.enable_external_map', 'configuration.enable_external_rates', 'configuration.allow_webhooks']; + private array $booleans = [ + 'configuration.is_demo_site', + 'configuration.single_user_mode', + 'configuration.enable_exchange_rates', + 'configuration.use_running_balance', + 'configuration.enable_external_map', + 'configuration.enable_external_rates', + 'configuration.allow_webhooks' + ]; private array $integers = ['configuration.permission_update_check', 'configuration.last_update_check']; /** diff --git a/app/Api/V1/Requests/System/UserStoreRequest.php b/app/Api/V1/Requests/System/UserStoreRequest.php index 9ca9409ec8..9de9da9d89 100644 --- a/app/Api/V1/Requests/System/UserStoreRequest.php +++ b/app/Api/V1/Requests/System/UserStoreRequest.php @@ -59,7 +59,7 @@ class UserStoreRequest extends FormRequest 'email' => $this->convertString('email'), 'blocked' => $blocked, 'blocked_code' => $this->convertString('blocked_code'), - 'role' => $this->convertString('role'), + 'role' => $this->convertString('role') ]; } @@ -72,7 +72,7 @@ class UserStoreRequest extends FormRequest 'email' => 'required|email|unique:users,email', 'blocked' => [new IsBoolean()], 'blocked_code' => 'in:email_changed', - 'role' => 'in:owner,demo', + 'role' => 'in:owner,demo' ]; } } diff --git a/app/Api/V1/Requests/System/UserUpdateRequest.php b/app/Api/V1/Requests/System/UserUpdateRequest.php index d22090ba0b..6e186a113e 100644 --- a/app/Api/V1/Requests/System/UserUpdateRequest.php +++ b/app/Api/V1/Requests/System/UserUpdateRequest.php @@ -24,11 +24,11 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Requests\System; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Rules\IsBoolean; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; use FireflyIII\User; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -62,7 +62,7 @@ class UserUpdateRequest extends FormRequest 'email' => $this->convertString('email'), 'blocked' => $blocked, 'blocked_code' => $this->convertString('blocked_code'), - 'role' => $this->convertString('role'), + 'role' => $this->convertString('role') ]; } @@ -78,7 +78,7 @@ class UserUpdateRequest extends FormRequest 'email' => sprintf('email|unique:users,email,%d', $user->id), 'blocked' => [new IsBoolean()], 'blocked_code' => 'in:email_changed', - 'role' => 'in:owner,demo,', + 'role' => 'in:owner,demo,' ]; } @@ -89,15 +89,13 @@ class UserUpdateRequest extends FormRequest { /** @var null|User $current */ $current = $this->route()->parameter('user'); - $validator->after( - static function (Validator $validator) use ($current): void { - $isAdmin = auth()->user()->hasRole('owner'); - // not admin, and not own user? - if (auth()->check() && false === $isAdmin && $current?->id !== auth()->user()->id) { - $validator->errors()->add('email', (string) trans('validation.invalid_selection')); - } + $validator->after(static function (Validator $validator) use ($current): void { + $isAdmin = auth()->user()->hasRole('owner'); + // not admin, and not own user? + if (auth()->check() && false === $isAdmin && $current?->id !== auth()->user()->id) { + $validator->errors()->add('email', (string) trans('validation.invalid_selection')); } - ); + }); if ($validator->fails()) { Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray()); } diff --git a/app/Api/V1/Requests/User/PreferenceStoreRequest.php b/app/Api/V1/Requests/User/PreferenceStoreRequest.php index 22ee8ad706..843f82505d 100644 --- a/app/Api/V1/Requests/User/PreferenceStoreRequest.php +++ b/app/Api/V1/Requests/User/PreferenceStoreRequest.php @@ -38,10 +38,7 @@ class PreferenceStoreRequest extends FormRequest public function getAll(): array { - $array = [ - 'name' => $this->convertString('name'), - 'data' => $this->get('data'), - ]; + $array = ['name' => $this->convertString('name'), 'data' => $this->get('data')]; if ('true' === $array['data']) { $array['data'] = true; } @@ -60,9 +57,6 @@ class PreferenceStoreRequest extends FormRequest */ public function rules(): array { - return [ - 'name' => 'required', - 'data' => 'required', - ]; + return ['name' => 'required', 'data' => 'required']; } } diff --git a/app/Api/V1/Requests/User/PreferenceUpdateRequest.php b/app/Api/V1/Requests/User/PreferenceUpdateRequest.php index 7489f7e2de..cc07488c89 100644 --- a/app/Api/V1/Requests/User/PreferenceUpdateRequest.php +++ b/app/Api/V1/Requests/User/PreferenceUpdateRequest.php @@ -38,10 +38,7 @@ class PreferenceUpdateRequest extends FormRequest public function getAll(): array { - $array = [ - 'name' => $this->convertString('name'), - 'data' => $this->get('data'), - ]; + $array = ['name' => $this->convertString('name'), 'data' => $this->get('data')]; if ('true' === $array['data']) { $array['data'] = true; } @@ -60,8 +57,6 @@ class PreferenceUpdateRequest extends FormRequest */ public function rules(): array { - return [ - 'data' => 'required', - ]; + return ['data' => 'required']; } } diff --git a/app/Casts/SeparateTimezoneCaster.php b/app/Casts/SeparateTimezoneCaster.php index 608f5fc1c9..4c5a6cecd3 100644 --- a/app/Casts/SeparateTimezoneCaster.php +++ b/app/Casts/SeparateTimezoneCaster.php @@ -1,6 +1,5 @@ $attributes */ - public function get(Model $model, string $key, mixed $value, array $attributes): ?Carbon + public function get(Model $model, string $key, mixed $value, array $attributes): null|Carbon { if ('' === $value || null === $value) { return null; @@ -51,6 +50,7 @@ class SeparateTimezoneCaster implements CastsAttributes $timeZone = $attributes[sprintf('%s_tz', $key)] ?? config('app.timezone'); return Carbon::parse($value, $timeZone)->setTimezone(config('app.timezone')); + // Log::debug(sprintf('SeparateTimezoneCaster: %s.%s = %s', str_replace('FireflyIII\\Models\\','',get_class($model)), $key, $result->toAtomString())); } diff --git a/app/Console/Commands/Correction/ClearsEmptyForeignAmounts.php b/app/Console/Commands/Correction/ClearsEmptyForeignAmounts.php index 958140f759..49b0fbd08e 100644 --- a/app/Console/Commands/Correction/ClearsEmptyForeignAmounts.php +++ b/app/Console/Commands/Correction/ClearsEmptyForeignAmounts.php @@ -1,6 +1,7 @@ friendlyInfo(sprintf('Converting field "%s" of model "%s" to UTC.', $field, $shortModel)); - $items->each( - static function ($item) use ($field, $timezoneField): void { - $date = Carbon::parse($item->{$field}, $item->{$timezoneField}); // @phpstan-ignore-line - $date->setTimezone('UTC'); - $item->{$field} = $date->format('Y-m-d H:i:s'); // @phpstan-ignore-line - $item->{$timezoneField} = 'UTC'; // @phpstan-ignore-line - $item->save(); - } - ); + $items->each(static function ($item) use ($field, $timezoneField): void { + $date = Carbon::parse($item->{$field}, $item->{$timezoneField}); // @phpstan-ignore-line + $date->setTimezone('UTC'); + $item->{$field} = $date->format('Y-m-d H:i:s'); // @phpstan-ignore-line + $item->{$timezoneField} = 'UTC'; // @phpstan-ignore-line + $item->save(); + }); } } diff --git a/app/Console/Commands/Correction/CorrectsAccountTypes.php b/app/Console/Commands/Correction/CorrectsAccountTypes.php index f554197c18..c37188290f 100644 --- a/app/Console/Commands/Correction/CorrectsAccountTypes.php +++ b/app/Console/Commands/Correction/CorrectsAccountTypes.php @@ -45,8 +45,8 @@ class CorrectsAccountTypes extends Command protected $description = 'Make sure all journals have the correct from/to account types.'; protected $signature = 'correction:account-types'; - private int $count; - private array $expected; + private int $count; + private array $expected; private AccountFactory $factory; private AccountRepositoryInterface $repository; @@ -58,28 +58,21 @@ class CorrectsAccountTypes extends Command public function handle(): int { $this->stupidLaravel(); - $this->factory = app(AccountFactory::class); + $this->factory = app(AccountFactory::class); $this->expected = config('firefly.source_dests'); - $expected = config('firefly.source_dests'); + $expected = config('firefly.source_dests'); - $query = TransactionJournal::leftJoin('transaction_types', 'transaction_journals.transaction_type_id', '=', 'transaction_types.id') - ->leftJoin( - 'transactions as source', - static function (JoinClause $join): void { - $join->on('transaction_journals.id', '=', 'source.transaction_journal_id')->where('source.amount', '<', 0); - } - ) - ->leftJoin( - 'transactions as destination', - static function (JoinClause $join): void { - $join->on('transaction_journals.id', '=', 'destination.transaction_journal_id')->where('destination.amount', '>', 0); - } - ) + $query = TransactionJournal::leftJoin('transaction_types', 'transaction_journals.transaction_type_id', '=', 'transaction_types.id') + ->leftJoin('transactions as source', static function (JoinClause $join): void { + $join->on('transaction_journals.id', '=', 'source.transaction_journal_id')->where('source.amount', '<', 0); + }) + ->leftJoin('transactions as destination', static function (JoinClause $join): void { + $join->on('transaction_journals.id', '=', 'destination.transaction_journal_id')->where('destination.amount', '>', 0); + }) ->leftJoin('accounts as source_account', 'source.account_id', '=', 'source_account.id') ->leftJoin('accounts as destination_account', 'destination.account_id', '=', 'destination_account.id') ->leftJoin('account_types as source_account_type', 'source_account.account_type_id', '=', 'source_account_type.id') - ->leftJoin('account_types as destination_account_type', 'destination_account.account_type_id', '=', 'destination_account_type.id') - ; + ->leftJoin('account_types as destination_account_type', 'destination_account.account_type_id', '=', 'destination_account_type.id'); // list all valid combinations, those are allowed. So we select those which are broken. $query->where(static function (Builder $q) use ($expected): void { @@ -96,21 +89,19 @@ class CorrectsAccountTypes extends Command } }); - $resultSet = $query->get( - [ - 'transaction_journals.id', - // 'transaction_type_id as type_id', - 'transaction_types.type as journal_type', - // 'source.id as source_transaction_id', - // 'source_account.id as source_account_id', - // 'source_account_type.id as source_account_type_id', - 'source_account_type.type as source_account_type', - // 'destination.id as destination_transaction_id', - // 'destination_account.id as destination_account_id', - // 'destination_account_type.id as destination_account_type_id', - 'destination_account_type.type as destination_account_type', - ] - ); + $resultSet = $query->get([ + 'transaction_journals.id', + // 'transaction_type_id as type_id', + 'transaction_types.type as journal_type', + // 'source.id as source_transaction_id', + // 'source_account.id as source_account_id', + // 'source_account_type.id as source_account_type_id', + 'source_account_type.type as source_account_type', + // 'destination.id as destination_transaction_id', + // 'destination_account.id as destination_account_id', + // 'destination_account_type.id as destination_account_type_id', + 'destination_account_type.type as destination_account_type' + ]); if ($resultSet->count() > 0) { $this->friendlyLine(sprintf('Found %d journals that need to be fixed.', $resultSet->count())); foreach ($resultSet as $entry) { @@ -139,7 +130,7 @@ class CorrectsAccountTypes extends Command private function inspectJournal(TransactionJournal $journal): void { Log::debug(sprintf('Now inspecting journal #%d', $journal->id)); - $transactions = $journal->transactions()->count(); + $transactions = $journal->transactions()->count(); if (2 !== $transactions) { Log::debug(sprintf('Journal has %d transactions, so can\'t fix.', $transactions)); $this->friendlyError(sprintf('Cannot inspect transaction journal #%d because it has %d transaction(s) instead of 2.', $journal->id, $transactions)); @@ -166,7 +157,7 @@ class CorrectsAccountTypes extends Command return; } - $expectedTypes = $this->expected[$type][$sourceAccountType]; + $expectedTypes = $this->expected[$type][$sourceAccountType]; if (!in_array($destAccountType, $expectedTypes, true)) { Log::debug(sprintf('[b] Going to fix journal #%d', $journal->id)); $this->fixJournal($journal, $type, $sourceTransaction, $destTransaction); @@ -186,13 +177,13 @@ class CorrectsAccountTypes extends Command private function fixJournal(TransactionJournal $journal, string $transactionType, Transaction $source, Transaction $dest): void { Log::debug(sprintf('Going to fix journal #%d', $journal->id)); - $this->repository = app(AccountRepositoryInterface::class); + $this->repository = app(AccountRepositoryInterface::class); $this->repository->setUser($journal->user); ++$this->count; // variables: - $sourceType = $source->account->accountType->type; - $destinationType = $dest->account->accountType->type; - $combination = sprintf('%s%s%s', $transactionType, $source->account->accountType->type, $dest->account->accountType->type); + $sourceType = $source->account->accountType->type; + $destinationType = $dest->account->accountType->type; + $combination = sprintf('%s%s%s', $transactionType, $source->account->accountType->type, $dest->account->accountType->type); Log::debug(sprintf('Combination is "%s"', $combination)); if ($this->shouldBeTransfer($transactionType, $sourceType, $destinationType)) { @@ -217,9 +208,9 @@ class CorrectsAccountTypes extends Command } // transaction has no valid source. - $validSources = array_keys($this->expected[$transactionType]); - $canCreateSource = $this->canCreateSource($validSources); - $hasValidSource = $this->hasValidAccountType($validSources, $sourceType); + $validSources = array_keys($this->expected[$transactionType]); + $canCreateSource = $this->canCreateSource($validSources); + $hasValidSource = $this->hasValidAccountType($validSources, $sourceType); if (!$hasValidSource && $canCreateSource) { $this->giveNewRevenue($journal, $source); @@ -227,7 +218,12 @@ class CorrectsAccountTypes extends Command } if (!$canCreateSource && !$hasValidSource) { Log::debug('This transaction type has no source we can create. Just give error.'); - $message = sprintf('The source account of %s #%d cannot be of type "%s". Firefly III cannot fix this. You may have to remove the transaction yourself.', $transactionType, $journal->id, $source->account->accountType->type); + $message = sprintf( + 'The source account of %s #%d cannot be of type "%s". Firefly III cannot fix this. You may have to remove the transaction yourself.', + $transactionType, + $journal->id, + $source->account->accountType->type + ); $this->friendlyError($message); Log::debug($message); @@ -246,13 +242,23 @@ class CorrectsAccountTypes extends Command } if (!$canCreateDestination && !$hasValidDestination && null === $alternativeDestination) { Log::debug('This transaction type has no destination we can create. Just give error.'); - $message = sprintf('The destination account of %s #%d cannot be of type "%s". Firefly III cannot fix this. You may have to remove the transaction yourself.', $transactionType, $journal->id, $dest->account->accountType->type); + $message = sprintf( + 'The destination account of %s #%d cannot be of type "%s". Firefly III cannot fix this. You may have to remove the transaction yourself.', + $transactionType, + $journal->id, + $dest->account->accountType->type + ); $this->friendlyError($message); Log::debug($message); } if (!$canCreateDestination && !$hasValidDestination && null !== $alternativeDestination) { Log::debug('This transaction type has no destination we can create, but found alternative with the same name.'); - $message = sprintf('The destination account of %s #%d cannot be of type "%s". Firefly III found an alternative account. Please make sure this transaction is correct.', $transactionType, $journal->transaction_group_id, $dest->account->accountType->type); + $message = sprintf( + 'The destination account of %s #%d cannot be of type "%s". Firefly III found an alternative account. Please make sure this transaction is correct.', + $transactionType, + $journal->transaction_group_id, + $dest->account->accountType->type + ); $this->friendlyInfo($message); Log::debug($message); $this->giveNewDestinationAccount($journal, $alternativeDestination); @@ -261,12 +267,20 @@ class CorrectsAccountTypes extends Command private function shouldBeTransfer(string $transactionType, string $sourceType, string $destinationType): bool { - return TransactionTypeEnum::TRANSFER->value === $transactionType && AccountTypeEnum::ASSET->value === $sourceType && $this->isLiability($destinationType); + return ( + TransactionTypeEnum::TRANSFER->value === $transactionType + && AccountTypeEnum::ASSET->value === $sourceType + && $this->isLiability($destinationType) + ); } private function isLiability(string $destinationType): bool { - return AccountTypeEnum::LOAN->value === $destinationType || AccountTypeEnum::DEBT->value === $destinationType || AccountTypeEnum::MORTGAGE->value === $destinationType; + return ( + AccountTypeEnum::LOAN->value === $destinationType + || AccountTypeEnum::DEBT->value === $destinationType + || AccountTypeEnum::MORTGAGE->value === $destinationType + ); } private function makeTransfer(TransactionJournal $journal): void @@ -275,7 +289,7 @@ class CorrectsAccountTypes extends Command $withdrawal = TransactionType::whereType(TransactionTypeEnum::WITHDRAWAL->value)->first(); $journal->transactionType()->associate($withdrawal); $journal->save(); - $message = sprintf('Converted transaction #%d from a transfer to a withdrawal.', $journal->id); + $message = sprintf('Converted transaction #%d from a transfer to a withdrawal.', $journal->id); $this->friendlyInfo($message); Log::debug($message); // check it again: @@ -284,7 +298,11 @@ class CorrectsAccountTypes extends Command private function shouldBeDeposit(string $transactionType, string $sourceType, string $destinationType): bool { - return TransactionTypeEnum::TRANSFER->value === $transactionType && $this->isLiability($sourceType) && AccountTypeEnum::ASSET->value === $destinationType; + return ( + TransactionTypeEnum::TRANSFER->value === $transactionType + && $this->isLiability($sourceType) + && AccountTypeEnum::ASSET->value === $destinationType + ); } private function makeDeposit(TransactionJournal $journal): void @@ -302,7 +320,11 @@ class CorrectsAccountTypes extends Command private function shouldGoToExpenseAccount(string $transactionType, string $sourceType, string $destinationType): bool { - return TransactionTypeEnum::WITHDRAWAL->value === $transactionType && AccountTypeEnum::ASSET->value === $sourceType && AccountTypeEnum::REVENUE->value === $destinationType; + return ( + TransactionTypeEnum::WITHDRAWAL->value === $transactionType + && AccountTypeEnum::ASSET->value === $sourceType + && AccountTypeEnum::REVENUE->value === $destinationType + ); } private function makeExpenseDestination(TransactionJournal $journal, Transaction $destination): void @@ -328,7 +350,11 @@ class CorrectsAccountTypes extends Command private function shouldComeFromRevenueAccount(string $transactionType, string $sourceType, string $destinationType): bool { - return TransactionTypeEnum::DEPOSIT->value === $transactionType && AccountTypeEnum::EXPENSE->value === $sourceType && AccountTypeEnum::ASSET->value === $destinationType; + return ( + TransactionTypeEnum::DEPOSIT->value === $transactionType + && AccountTypeEnum::EXPENSE->value === $sourceType + && AccountTypeEnum::ASSET->value === $destinationType + ); } private function makeRevenueSource(TransactionJournal $journal, Transaction $source): void @@ -340,7 +366,7 @@ class CorrectsAccountTypes extends Command $oldSource = $source->account; $source->account()->associate($result); $source->save(); - $message = sprintf( + $message = sprintf( 'Transaction journal #%d, source account changed from #%d ("%s") to #%d ("%s").', $journal->id, $oldSource->id, @@ -374,7 +400,13 @@ class CorrectsAccountTypes extends Command $newSource = $this->factory->findOrCreate($name, AccountTypeEnum::REVENUE->value); $source->account()->associate($newSource); $source->save(); - $this->friendlyPositive(sprintf('Firefly III gave transaction #%d a new source %s: #%d ("%s").', $journal->transaction_group_id, AccountTypeEnum::REVENUE->value, $newSource->id, $newSource->name)); + $this->friendlyPositive(sprintf( + 'Firefly III gave transaction #%d a new source %s: #%d ("%s").', + $journal->transaction_group_id, + AccountTypeEnum::REVENUE->value, + $newSource->id, + $newSource->name + )); Log::debug(sprintf('Associated account #%d with transaction #%d', $newSource->id, $source->id)); $this->inspectJournal($journal); } @@ -392,18 +424,24 @@ class CorrectsAccountTypes extends Command $newDestination = $this->factory->findOrCreate($name, AccountTypeEnum::EXPENSE->value); $destination->account()->associate($newDestination); $destination->save(); - $this->friendlyPositive(sprintf('Firefly III gave transaction #%d a new destination %s: #%d ("%s").', $journal->transaction_group_id, AccountTypeEnum::EXPENSE->value, $newDestination->id, $newDestination->name)); + $this->friendlyPositive(sprintf( + 'Firefly III gave transaction #%d a new destination %s: #%d ("%s").', + $journal->transaction_group_id, + AccountTypeEnum::EXPENSE->value, + $newDestination->id, + $newDestination->name + )); Log::debug(sprintf('Associated account #%d with transaction #%d', $newDestination->id, $destination->id)); $this->inspectJournal($journal); } private function giveNewDestinationAccount(TransactionJournal $journal, Account $newDestination): void { - $destTransaction = $this->getDestinationTransaction($journal); - $oldDest = $destTransaction->account; + $destTransaction = $this->getDestinationTransaction($journal); + $oldDest = $destTransaction->account; $destTransaction->account_id = $newDestination->id; $destTransaction->save(); - $message = sprintf( + $message = sprintf( 'Transaction journal #%d, destination account changed from #%d ("%s") to #%d ("%s").', $journal->id, $oldDest->id, diff --git a/app/Console/Commands/Correction/CorrectsAmounts.php b/app/Console/Commands/Correction/CorrectsAmounts.php index 74f3826dcf..b133ac8504 100644 --- a/app/Console/Commands/Correction/CorrectsAmounts.php +++ b/app/Console/Commands/Correction/CorrectsAmounts.php @@ -73,7 +73,6 @@ class CorrectsAmounts extends Command // rule_triggers must be positive or zero (amount_less, amount_more, amount_is) $this->fixRuleTriggers(); - return 0; } @@ -84,14 +83,18 @@ class CorrectsAmounts extends Command /** @var AccountRepositoryInterface $repository */ $repository = app(AccountRepositoryInterface::class); $type = TransactionType::where('type', TransactionTypeEnum::TRANSFER->value)->first(); - $journals = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')->whereNotNull('transactions.foreign_amount')->where('transaction_journals.transaction_type_id', $type->id)->distinct()->get(['transaction_journals.*']); + $journals = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') + ->whereNotNull('transactions.foreign_amount') + ->where('transaction_journals.transaction_type_id', $type->id) + ->distinct() + ->get(['transaction_journals.*']); /** @var TransactionJournal $journal */ foreach ($journals as $journal) { $repository->setUser($journal->user); - $primary = Amount::getPrimaryCurrencyByUserGroup($journal->userGroup); + $primary = Amount::getPrimaryCurrencyByUserGroup($journal->userGroup); - $valid = $this->validateJournal($journal); + $valid = $this->validateJournal($journal); if (false === $valid) { // Log::debug(sprintf('Journal #%d does not need to be fixed or is invalid (see previous messages)', $journal->id)); @@ -109,11 +112,11 @@ class CorrectsAmounts extends Command if ($sourceCurrency->id === $destCurrency->id) { Log::debug('Both accounts have the same currency. Removing foreign currency info.'); - $source->foreign_currency_id = null; - $source->foreign_amount = null; + $source->foreign_currency_id = null; + $source->foreign_amount = null; $source->save(); $destination->foreign_currency_id = null; - $destination->foreign_amount = null; + $destination->foreign_amount = null; $destination->save(); continue; @@ -121,25 +124,49 @@ class CorrectsAmounts extends Command // validate source transaction if ($destCurrency->id !== $source->foreign_currency_id) { - Log::debug(sprintf('[a] Journal #%d: transaction #%d refers to foreign currency "%s" but should refer to "%s".', $journal->id, $source->id, $source->foreignCurrency->code, $destCurrency->code)); + Log::debug(sprintf( + '[a] Journal #%d: transaction #%d refers to foreign currency "%s" but should refer to "%s".', + $journal->id, + $source->id, + $source->foreignCurrency->code, + $destCurrency->code + )); $source->foreign_currency_id = $destCurrency->id; $source->save(); } if ($sourceCurrency->id !== $source->transaction_currency_id) { - Log::debug(sprintf('[b] Journal #%d: transaction #%d refers to currency "%s" but should refer to "%s".', $journal->id, $source->id, $source->transactionCurrency->code, $sourceCurrency->code)); + Log::debug(sprintf( + '[b] Journal #%d: transaction #%d refers to currency "%s" but should refer to "%s".', + $journal->id, + $source->id, + $source->transactionCurrency->code, + $sourceCurrency->code + )); $source->transaction_currency_id = $sourceCurrency->id; $source->save(); } // validate destination: if ($sourceCurrency->id !== $destination->foreign_currency_id) { - Log::debug(sprintf('[c] Journal #%d: transaction #%d refers to foreign currency "%s" but should refer to "%s".', $journal->id, $destination->id, $destination->foreignCurrency->code, $sourceCurrency->code)); + Log::debug(sprintf( + '[c] Journal #%d: transaction #%d refers to foreign currency "%s" but should refer to "%s".', + $journal->id, + $destination->id, + $destination->foreignCurrency->code, + $sourceCurrency->code + )); $destination->foreign_currency_id = $sourceCurrency->id; $destination->save(); } if ($destCurrency->id !== $destination->transaction_currency_id) { - Log::debug(sprintf('[d] Journal #%d: transaction #%d refers to currency "%s" but should refer to "%s".', $journal->id, $destination->id, $destination->transactionCurrency->code, $destCurrency->code)); + Log::debug(sprintf( + '[d] Journal #%d: transaction #%d refers to currency "%s" but should refer to "%s".', + $journal->id, + $destination->id, + $destination->transactionCurrency->code, + $destCurrency->code + )); $destination->transaction_currency_id = $destCurrency->id; $destination->save(); } @@ -157,7 +184,6 @@ class CorrectsAmounts extends Command { $count = AutoBudget::where('amount', '<', 0)->update(['amount' => DB::raw('amount * -1')]); if (0 === $count) { - return; } $this->friendlyInfo(sprintf('Corrected %d auto budget amount(s).', $count)); @@ -167,7 +193,6 @@ class CorrectsAmounts extends Command { $count = AvailableBudget::where('amount', '<', 0)->update(['amount' => DB::raw('amount * -1')]); if (0 === $count) { - return; } $this->friendlyInfo(sprintf('Corrected %d available budget amount(s).', $count)); @@ -179,7 +204,6 @@ class CorrectsAmounts extends Command $count += Bill::where('amount_max', '<', 0)->update(['amount_max' => DB::raw('amount_max * -1')]); $count += Bill::where('amount_min', '<', 0)->update(['amount_min' => DB::raw('amount_min * -1')]); if (0 === $count) { - return; } $this->friendlyInfo(sprintf('Corrected %d bill amount(s).', $count)); @@ -189,7 +213,6 @@ class CorrectsAmounts extends Command { $count = BudgetLimit::where('amount', '<', 0)->update(['amount' => DB::raw('amount * -1')]); if (0 === $count) { - return; } $this->friendlyInfo(sprintf('Corrected %d budget limit amount(s).', $count)); @@ -199,7 +222,6 @@ class CorrectsAmounts extends Command { $count = CurrencyExchangeRate::where('rate', '<', 0)->update(['rate' => DB::raw('rate * -1')]); if (0 === $count) { - return; } $this->friendlyInfo(sprintf('Corrected %d currency exchange rate(s).', $count)); @@ -209,7 +231,6 @@ class CorrectsAmounts extends Command { $count = PiggyBank::where('target_amount', '<', 0)->update(['target_amount' => DB::raw('target_amount * -1')]); if (0 === $count) { - return; } $this->friendlyInfo(sprintf('Corrected %d piggy bank amount(s).', $count)); @@ -221,7 +242,6 @@ class CorrectsAmounts extends Command $count += RecurrenceTransaction::where('amount', '<', 0)->update(['amount' => DB::raw('amount * -1')]); $count += RecurrenceTransaction::where('foreign_amount', '<', 0)->update(['foreign_amount' => DB::raw('foreign_amount * -1')]); if (0 === $count) { - return; } $this->friendlyInfo(sprintf('Corrected %d recurring transaction amount(s).', $count)); @@ -243,7 +263,6 @@ class CorrectsAmounts extends Command } } if (0 === $fixed) { - return; } $this->friendlyInfo(sprintf('Corrected %d rule trigger amount(s).', $fixed)); @@ -252,9 +271,14 @@ class CorrectsAmounts extends Command private function fixRuleTrigger(RuleTrigger $item): bool { try { - $check = bccomp((string)$item->trigger_value, '0'); + $check = bccomp((string) $item->trigger_value, '0'); } catch (ValueError) { - $this->friendlyError(sprintf('Rule #%d contained invalid %s-trigger "%s". The trigger has been removed, and the rule is disabled.', $item->rule_id, $item->trigger_type, $item->trigger_value)); + $this->friendlyError(sprintf( + 'Rule #%d contained invalid %s-trigger "%s". The trigger has been removed, and the rule is disabled.', + $item->rule_id, + $item->trigger_type, + $item->trigger_value + )); $item->rule->active = false; $item->rule->save(); $item->forceDelete(); @@ -273,8 +297,8 @@ class CorrectsAmounts extends Command private function validateJournal(TransactionJournal $journal): bool { - $countSource = $journal->transactions()->where('amount', '<', 0)->count(); - $countDest = $journal->transactions()->where('amount', '>', 0)->count(); + $countSource = $journal->transactions()->where('amount', '<', 0)->count(); + $countDest = $journal->transactions()->where('amount', '>', 0)->count(); if (1 !== $countSource || 1 !== $countDest) { $this->friendlyError(sprintf('Transaction journal #%d has bad transaction information. Will delete.', $journal->id)); @@ -285,10 +309,10 @@ class CorrectsAmounts extends Command } /** @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 === $source || null === $destination) { $this->friendlyError(sprintf('Could not find source OR destination for journal #%d .', $journal->id)); @@ -304,7 +328,7 @@ class CorrectsAmounts extends Command } if (null === $source->foreign_amount || null === $destination->foreign_amount) { $this->friendlyError(sprintf('Transactions of journal #%d have no foreign amount, but have foreign currency info. Will reset this.', $journal->id)); - $source->foreign_currency_id = null; + $source->foreign_currency_id = null; $source->save(); $destination->foreign_currency_id = null; $source->save(); diff --git a/app/Console/Commands/Correction/CorrectsCurrencies.php b/app/Console/Commands/Correction/CorrectsCurrencies.php index 75a5583729..7e95db0558 100644 --- a/app/Console/Commands/Correction/CorrectsCurrencies.php +++ b/app/Console/Commands/Correction/CorrectsCurrencies.php @@ -32,11 +32,11 @@ use FireflyIII\Models\Transaction; use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\UserGroup; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; +use FireflyIII\Support\Facades\Amount; use Illuminate\Console\Command; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; use Symfony\Component\Console\Command\Command as CommandAlias; -use FireflyIII\Support\Facades\Amount; class CorrectsCurrencies extends Command { @@ -61,66 +61,58 @@ class CorrectsCurrencies extends Command private function correctCurrencies(UserGroup $userGroup): void { /** @var CurrencyRepositoryInterface $repos */ - $repos = app(CurrencyRepositoryInterface::class); + $repos = app(CurrencyRepositoryInterface::class); // first check if the user has any default currency (not necessarily the case, so can be forced). $primaryCurrency = Amount::getPrimaryCurrencyByUserGroup($userGroup); Log::debug(sprintf('Now correcting currencies for user group #%d', $userGroup->id)); - $found = [$primaryCurrency->id]; + $found = [$primaryCurrency->id]; // get all meta entries - $meta = AccountMeta::leftJoin('accounts', 'accounts.id', '=', 'account_meta.account_id') + $meta = AccountMeta::leftJoin('accounts', 'accounts.id', '=', 'account_meta.account_id') ->where('accounts.user_group_id', $userGroup->id) - ->where('account_meta.name', 'currency_id')->groupBy('data')->get(['data']) - ; + ->where('account_meta.name', 'currency_id') + ->groupBy('data') + ->get(['data']); foreach ($meta as $entry) { $found[] = (int) $entry->data; } // get all from journals: - $journals = TransactionJournal::where('user_group_id', $userGroup->id) - ->groupBy('transaction_currency_id')->get(['transaction_currency_id']) - ; + $journals = TransactionJournal::where('user_group_id', $userGroup->id)->groupBy('transaction_currency_id')->get(['transaction_currency_id']); foreach ($journals as $entry) { $found[] = (int) $entry->transaction_currency_id; } // get all from transactions - $transactions = Transaction::leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') + $transactions = Transaction::leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->where('transaction_journals.user_group_id', $userGroup->id) ->groupBy('transactions.transaction_currency_id', 'transactions.foreign_currency_id') - ->get(['transactions.transaction_currency_id', 'transactions.foreign_currency_id']) - ; + ->get(['transactions.transaction_currency_id', 'transactions.foreign_currency_id']); foreach ($transactions as $entry) { $found[] = (int) $entry->transaction_currency_id; $found[] = (int) $entry->foreign_currency_id; } // get all from budget limits - $limits = BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id') - ->groupBy('transaction_currency_id') - ->get(['budget_limits.transaction_currency_id']) - ; + $limits = BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id')->groupBy('transaction_currency_id')->get([ + 'budget_limits.transaction_currency_id' + ]); foreach ($limits as $entry) { $found[] = $entry->transaction_currency_id; } // also get all currencies already enabled. - $alreadyEnabled = $userGroup->currencies()->get(['transaction_currencies.id'])->pluck('id')->toArray(); + $alreadyEnabled = $userGroup->currencies()->get(['transaction_currencies.id'])->pluck('id')->toArray(); foreach ($alreadyEnabled as $currencyId) { $found[] = $currencyId; } - $found = array_values(array_unique($found)); - $found = array_values( - array_filter( - $found, - static fn (int $currencyId): bool => 0 !== $currencyId - ) - ); + $found = array_values(array_unique($found)); + $found = array_values(array_filter($found, static fn(int $currencyId): bool => 0 !== $currencyId)); - $valid = new Collection(); + $valid = new Collection(); /** @var int $currencyId */ foreach ($found as $currencyId) { @@ -129,7 +121,7 @@ class CorrectsCurrencies extends Command $valid->push($currency); } } - $ids = $valid->pluck('id')->toArray(); + $ids = $valid->pluck('id')->toArray(); Log::debug(sprintf('Found currencies for user group #%d: %s', $userGroup->id, implode(', ', $ids))); $userGroup->currencies()->sync($ids); diff --git a/app/Console/Commands/Correction/CorrectsDatabase.php b/app/Console/Commands/Correction/CorrectsDatabase.php index 89d2818f07..412cd8128b 100644 --- a/app/Console/Commands/Correction/CorrectsDatabase.php +++ b/app/Console/Commands/Correction/CorrectsDatabase.php @@ -79,7 +79,7 @@ class CorrectsDatabase extends Command 'correction:recalculate-pc-amounts', 'correction:remove-links-to-deleted-objects', 'correction:clears-empty-foreign-amounts', - 'firefly-iii:report-integrity', + 'firefly-iii:report-integrity' ]; foreach ($commands as $command) { $this->friendlyLine(sprintf('Now executing command "%s"', $command)); diff --git a/app/Console/Commands/Correction/CorrectsFrontpageAccounts.php b/app/Console/Commands/Correction/CorrectsFrontpageAccounts.php index ab2b522115..ee39d81abe 100644 --- a/app/Console/Commands/Correction/CorrectsFrontpageAccounts.php +++ b/app/Console/Commands/Correction/CorrectsFrontpageAccounts.php @@ -59,7 +59,7 @@ class CorrectsFrontpageAccounts extends Command private function fixPreference(Preference $preference): void { - $fixed = []; + $fixed = []; /** @var AccountRepositoryInterface $repository */ $repository = app(AccountRepositoryInterface::class); @@ -67,15 +67,21 @@ class CorrectsFrontpageAccounts extends Command return; } $repository->setUser($preference->user); - $data = $preference->data; + $data = $preference->data; if (is_array($data)) { /** @var string $accountId */ foreach ($data as $accountId) { $accountIdInt = (int) $accountId; $account = $repository->find($accountIdInt); - if (null !== $account - && in_array($account->accountType->type, [AccountTypeEnum::ASSET->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value], true) - && true === $account->active) { + if ( + null !== $account + && in_array( + $account->accountType->type, + [AccountTypeEnum::ASSET->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value], + true + ) + && true === $account->active + ) { $fixed[] = $account->id; } } diff --git a/app/Console/Commands/Correction/CorrectsGroupAccounts.php b/app/Console/Commands/Correction/CorrectsGroupAccounts.php index 5a836584bb..494f828a51 100644 --- a/app/Console/Commands/Correction/CorrectsGroupAccounts.php +++ b/app/Console/Commands/Correction/CorrectsGroupAccounts.php @@ -44,8 +44,8 @@ class CorrectsGroupAccounts extends Command */ public function handle(): int { - $groups = []; - $res = TransactionJournal::groupBy('transaction_group_id')->get(['transaction_group_id', DB::raw('COUNT(transaction_group_id) as the_count')]); + $groups = []; + $res = TransactionJournal::groupBy('transaction_group_id')->get(['transaction_group_id', DB::raw('COUNT(transaction_group_id) as the_count')]); /** @var TransactionJournal $journal */ foreach ($res as $journal) { diff --git a/app/Console/Commands/Correction/CorrectsGroupInformation.php b/app/Console/Commands/Correction/CorrectsGroupInformation.php index cba18e475b..17434a5220 100644 --- a/app/Console/Commands/Correction/CorrectsGroupInformation.php +++ b/app/Console/Commands/Correction/CorrectsGroupInformation.php @@ -79,7 +79,7 @@ class CorrectsGroupInformation extends Command return; } - $set = [ + $set = [ Account::class, Attachment::class, AvailableBudget::class, @@ -95,7 +95,7 @@ class CorrectsGroupInformation extends Command Tag::class, TransactionGroup::class, TransactionJournal::class, - Webhook::class, + Webhook::class ]; foreach ($set as $className) { $this->updateGroupInfoForObject($user, $group, $className); @@ -112,7 +112,12 @@ class CorrectsGroupInformation extends Command return; } if (0 !== $result) { - $this->friendlyPositive(sprintf('User #%d: Moved %d %s objects to the correct group.', $user->id, $result, str_replace('FireflyIII\Models\\', '', $className))); + $this->friendlyPositive(sprintf( + 'User #%d: Moved %d %s objects to the correct group.', + $user->id, + $result, + str_replace('FireflyIII\Models\\', '', $className) + )); } } } diff --git a/app/Console/Commands/Correction/CorrectsIbans.php b/app/Console/Commands/Correction/CorrectsIbans.php index edab4ed0c1..487052f721 100644 --- a/app/Console/Commands/Correction/CorrectsIbans.php +++ b/app/Console/Commands/Correction/CorrectsIbans.php @@ -27,9 +27,9 @@ namespace FireflyIII\Console\Commands\Correction; use FireflyIII\Console\Commands\ShowsFriendlyMessages; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Models\Account; +use FireflyIII\Support\Facades\Steam; use Illuminate\Console\Command; use Illuminate\Support\Collection; -use FireflyIII\Support\Facades\Steam; class CorrectsIbans extends Command { @@ -37,7 +37,7 @@ class CorrectsIbans extends Command protected $description = 'Removes spaces from IBANs'; protected $signature = 'correction:ibans'; - private int $count = 0; + private int $count = 0; /** * Execute the console command. @@ -55,8 +55,8 @@ class CorrectsIbans extends Command { /** @var Account $account */ foreach ($accounts as $account) { - $iban = (string) $account->iban; - $newIban = Steam::filterSpaces($iban); + $iban = (string) $account->iban; + $newIban = Steam::filterSpaces($iban); if ('' !== $iban && $iban !== $newIban) { $account->iban = $newIban; $account->save(); @@ -86,25 +86,29 @@ class CorrectsIbans extends Command foreach ($accounts as $account) { $userId = $account->user_id; $set[$userId] ??= []; - $iban = (string) $account->iban; + $iban = (string) $account->iban; if ('' === $iban) { continue; } - $type = $account->accountType->type; + $type = $account->accountType->type; if (in_array($type, [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value], true)) { $type = 'liabilities'; } // iban already in use! two exceptions exist: - if (array_key_exists($iban, $set[$userId]) && (!AccountTypeEnum::EXPENSE->value === $set[$userId][$iban] && AccountTypeEnum::REVENUE->value === $type && !(AccountTypeEnum::REVENUE->value === $set[$userId][$iban] && AccountTypeEnum::EXPENSE->value === $type))) { - $this->friendlyWarning( - sprintf( - 'IBAN "%s" is used more than once and will be removed from %s #%d ("%s")', - $iban, - $account->accountType->type, - $account->id, - $account->name - ) - ); + if ( + array_key_exists($iban, $set[$userId]) && ( + !AccountTypeEnum::EXPENSE->value === $set[$userId][$iban] + && AccountTypeEnum::REVENUE->value === $type + && !(AccountTypeEnum::REVENUE->value === $set[$userId][$iban] && AccountTypeEnum::EXPENSE->value === $type) + ) + ) { + $this->friendlyWarning(sprintf( + 'IBAN "%s" is used more than once and will be removed from %s #%d ("%s")', + $iban, + $account->accountType->type, + $account->id, + $account->name + )); $account->iban = null; $account->save(); ++$this->count; diff --git a/app/Console/Commands/Correction/CorrectsInvertedBudgetLimits.php b/app/Console/Commands/Correction/CorrectsInvertedBudgetLimits.php index 17a57b7c0b..0a441f6d26 100644 --- a/app/Console/Commands/Correction/CorrectsInvertedBudgetLimits.php +++ b/app/Console/Commands/Correction/CorrectsInvertedBudgetLimits.php @@ -1,6 +1,7 @@ ', DB::raw('end_date'))->get(); if (0 === $set->count()) { Log::debug('No inverted budget limits found.'); @@ -62,10 +62,10 @@ class CorrectsInvertedBudgetLimits extends Command /** @var BudgetLimit $budgetLimit */ foreach ($set as $budgetLimit) { - $start = $budgetLimit->start_date->copy(); - $end = $budgetLimit->end_date->copy(); + $start = $budgetLimit->start_date->copy(); + $end = $budgetLimit->end_date->copy(); $budgetLimit->start_date = $end; - $budgetLimit->end_date = $start; + $budgetLimit->end_date = $start; $budgetLimit->saveQuietly(); } if (1 === $set->count()) { diff --git a/app/Console/Commands/Correction/CorrectsLongDescriptions.php b/app/Console/Commands/Correction/CorrectsLongDescriptions.php index a5b98a3cf4..a865c39ad5 100644 --- a/app/Console/Commands/Correction/CorrectsLongDescriptions.php +++ b/app/Console/Commands/Correction/CorrectsLongDescriptions.php @@ -35,8 +35,9 @@ class CorrectsLongDescriptions extends Command use ShowsFriendlyMessages; private const int MAX_LENGTH = 1000; - protected $description = 'Fixes long descriptions in journals and groups.'; - protected $signature = 'correction:long-descriptions'; + + protected $description = 'Fixes long descriptions in journals and groups.'; + protected $signature = 'correction:long-descriptions'; /** * Execute the console command. @@ -56,7 +57,7 @@ class CorrectsLongDescriptions extends Command } } - $groups = TransactionGroup::where(DB::raw('LENGTH(title)'), '>', self::MAX_LENGTH)->get(['id', 'title']); + $groups = TransactionGroup::where(DB::raw('LENGTH(title)'), '>', self::MAX_LENGTH)->get(['id', 'title']); /** @var TransactionGroup $group */ foreach ($groups as $group) { diff --git a/app/Console/Commands/Correction/CorrectsMetaDataFields.php b/app/Console/Commands/Correction/CorrectsMetaDataFields.php index 731c5f49f7..a14071592f 100644 --- a/app/Console/Commands/Correction/CorrectsMetaDataFields.php +++ b/app/Console/Commands/Correction/CorrectsMetaDataFields.php @@ -35,7 +35,7 @@ class CorrectsMetaDataFields extends Command protected $description = 'Rename changed meta fields.'; protected $signature = 'correction:meta-fields'; - private int $count = 0; + private int $count = 0; /** * Execute the console command. @@ -54,7 +54,7 @@ class CorrectsMetaDataFields extends Command 'sepa-ep' => 'sepa_ep', 'sepa-ci' => 'sepa_ci', 'sepa-batch-id' => 'sepa_batch_id', - 'external_uri' => 'external_url', + 'external_uri' => 'external_url' ]; foreach ($changes as $original => $update) { $this->rename($original, $update); @@ -68,10 +68,7 @@ class CorrectsMetaDataFields extends Command private function rename(string $original, string $update): void { - $total = DB::table('journal_meta') - ->where('name', '=', $original) - ->update(['name' => $update]) - ; + $total = DB::table('journal_meta')->where('name', '=', $original)->update(['name' => $update]); $this->count += $total; } } diff --git a/app/Console/Commands/Correction/CorrectsOpeningBalanceCurrencies.php b/app/Console/Commands/Correction/CorrectsOpeningBalanceCurrencies.php index a59d10c805..6364bf380d 100644 --- a/app/Console/Commands/Correction/CorrectsOpeningBalanceCurrencies.php +++ b/app/Console/Commands/Correction/CorrectsOpeningBalanceCurrencies.php @@ -32,10 +32,10 @@ use FireflyIII\Models\Transaction; use FireflyIII\Models\TransactionCurrency; use FireflyIII\Models\TransactionJournal; use FireflyIII\Repositories\Account\AccountRepositoryInterface; +use FireflyIII\Support\Facades\Amount; use Illuminate\Console\Command; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; -use FireflyIII\Support\Facades\Amount; class CorrectsOpeningBalanceCurrencies extends Command { @@ -70,8 +70,8 @@ class CorrectsOpeningBalanceCurrencies extends Command /** @var Collection */ return TransactionJournal::leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id') ->whereNull('transaction_journals.deleted_at') - ->where('transaction_types.type', TransactionTypeEnum::OPENING_BALANCE->value)->get(['transaction_journals.*']) - ; + ->where('transaction_types.type', TransactionTypeEnum::OPENING_BALANCE->value) + ->get(['transaction_journals.*']); } private function correctJournal(TransactionJournal $journal): int @@ -90,7 +90,7 @@ class CorrectsOpeningBalanceCurrencies extends Command return $this->setCorrectCurrency($account, $journal); } - private function getAccount(TransactionJournal $journal): ?Account + private function getAccount(TransactionJournal $journal): null|Account { $transactions = $journal->transactions()->get(); @@ -113,7 +113,7 @@ class CorrectsOpeningBalanceCurrencies extends Command if ((int) $journal->transaction_currency_id !== $currency->id) { $journal->transaction_currency_id = $currency->id; $journal->save(); - $count = 1; + $count = 1; } /** @var Transaction $transaction */ @@ -121,7 +121,7 @@ class CorrectsOpeningBalanceCurrencies extends Command if ($transaction->transaction_currency_id !== $currency->id) { $transaction->transaction_currency_id = $currency->id; $transaction->save(); - $count = 1; + $count = 1; } } diff --git a/app/Console/Commands/Correction/CorrectsPreferences.php b/app/Console/Commands/Correction/CorrectsPreferences.php index 2de5a6dffc..76c75c8596 100644 --- a/app/Console/Commands/Correction/CorrectsPreferences.php +++ b/app/Console/Commands/Correction/CorrectsPreferences.php @@ -1,6 +1,5 @@ recalculateAvailableBudgets($userGroup, $currency); $this->recalculateBills($userGroup, $currency); $this->calculateTransactions($userGroup, $currency); - } private function recalculateAccounts(UserGroup $userGroup): void { - $set = $userGroup->accounts()->where(static function (EloquentBuilder $q): void { - $q->whereNotNull('virtual_balance'); + $set = $userGroup + ->accounts() + ->where(static function (EloquentBuilder $q): void { + $q->whereNotNull('virtual_balance'); - // this needs a different piece of code for postgres. - if ('pgsql' === config('database.default')) { - $q->orWhere(DB::raw('CAST(virtual_balance AS TEXT)'), '!=', ''); - } - if ('pgsql' !== config('database.default')) { - $q->orWhere('virtual_balance', '!=', ''); - } - })->get(); + // this needs a different piece of code for postgres. + if ('pgsql' === config('database.default')) { + $q->orWhere(DB::raw('CAST(virtual_balance AS TEXT)'), '!=', ''); + } + if ('pgsql' !== config('database.default')) { + $q->orWhere('virtual_balance', '!=', ''); + } + }) + ->get(); /** @var Account $account */ foreach ($set as $account) { @@ -124,15 +125,13 @@ class CorrectsPrimaryCurrencyAmounts extends Command private function recalculatePiggyBanks(UserGroup $userGroup, TransactionCurrency $currency): void { - $converter = new ExchangeRateConverter(); + $converter = new ExchangeRateConverter(); $converter->setUserGroup($userGroup); $converter->setIgnoreSettings(true); $repository = app(PiggyBankRepositoryInterface::class); $repository->setUserGroup($userGroup); - $set = $repository->getPiggyBanks(); - $set = $set->filter( - static fn (PiggyBank $piggyBank): bool => $currency->id !== $piggyBank->transaction_currency_id - ); + $set = $repository->getPiggyBanks(); + $set = $set->filter(static fn(PiggyBank $piggyBank): bool => $currency->id !== $piggyBank->transaction_currency_id); foreach ($set as $piggyBank) { $piggyBank->encrypted = false; $piggyBank->save(); @@ -140,24 +139,26 @@ class CorrectsPrimaryCurrencyAmounts extends Command foreach ($piggyBank->accounts as $account) { $account->pivot->native_current_amount = null; if (0 !== bccomp((string) $account->pivot->current_amount, '0')) { - $account->pivot->native_current_amount = $converter->convert($piggyBank->transactionCurrency, $currency, today(), (string) $account->pivot->current_amount); + $account->pivot->native_current_amount = $converter->convert( + $piggyBank->transactionCurrency, + $currency, + today(), + (string) $account->pivot->current_amount + ); } $account->pivot->save(); } $this->recalculatePiggyBankEvents($piggyBank); } Log::debug(sprintf('Recalculated %d piggy banks for user group #%d.', $set->count(), $userGroup->id)); - } private function recalculatePiggyBankEvents(PiggyBank $piggyBank): void { $set = $piggyBank->piggyBankEvents()->get(); - $set->each( - static function (PiggyBankEvent $event): void { // @phpstan-ignore-line - $event->touch(); - } - ); + $set->each(static function (PiggyBankEvent $event): void { // @phpstan-ignore-line + $event->touch(); + }); Log::debug(sprintf('Recalculated %d piggy bank events.', $set->count())); } @@ -223,7 +224,7 @@ class CorrectsPrimaryCurrencyAmounts extends Command private function calculateTransactions(UserGroup $userGroup, TransactionCurrency $currency): void { // custom query because of the potential size of this update. - $set = DB::table('transactions') + $set = DB::table('transactions') ->join('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->where('transaction_journals.user_group_id', $userGroup->id) ->where(static function (DatabaseBuilder $q1) use ($currency): void { @@ -233,13 +234,12 @@ class CorrectsPrimaryCurrencyAmounts extends Command $q3->whereNot('transactions.transaction_currency_id', $currency->id)->whereNot('transactions.foreign_currency_id', $currency->id); }); }) -// ->where(static function (DatabaseBuilder $q) use ($currency): void { -// $q->whereNot('transactions.transaction_currency_id', $currency->id) -// ->whereNot('transactions.foreign_currency_id', $currency->id) -// ; -// }) - ->get(['transactions.id']) - ; + // ->where(static function (DatabaseBuilder $q) use ($currency): void { + // $q->whereNot('transactions.transaction_currency_id', $currency->id) + // ->whereNot('transactions.foreign_currency_id', $currency->id) + // ; + // }) + ->get(['transactions.id']); TransactionObserver::$recalculate = false; foreach ($set as $item) { // here we are. diff --git a/app/Console/Commands/Correction/CorrectsRecurringTransactions.php b/app/Console/Commands/Correction/CorrectsRecurringTransactions.php index e47dad7236..836ac6d0de 100644 --- a/app/Console/Commands/Correction/CorrectsRecurringTransactions.php +++ b/app/Console/Commands/Correction/CorrectsRecurringTransactions.php @@ -37,11 +37,11 @@ class CorrectsRecurringTransactions extends Command { use ShowsFriendlyMessages; - protected $description = 'Fixes recurring transactions with the wrong transaction type.'; - protected $signature = 'correction:recurring-transactions'; - private int $count = 0; + protected $description = 'Fixes recurring transactions with the wrong transaction type.'; + protected $signature = 'correction:recurring-transactions'; + private int $count = 0; private RecurringRepositoryInterface $recurringRepos; - private UserRepositoryInterface $userRepos; + private UserRepositoryInterface $userRepos; /** * Execute the console command. @@ -62,7 +62,7 @@ class CorrectsRecurringTransactions extends Command private function stupidLaravel(): void { $this->recurringRepos = app(RecurringRepositoryInterface::class); - $this->userRepos = app(UserRepositoryInterface::class); + $this->userRepos = app(UserRepositoryInterface::class); } private function correctTransactions(): void @@ -101,9 +101,12 @@ class CorrectsRecurringTransactions extends Command $type = $recurrence->transactionType; $link = config(sprintf('firefly.account_to_transaction.%s.%s', $source->accountType->type, $destination->accountType->type)); if (null !== $link && strtolower((string) $type->type) !== strtolower($link)) { - $this->friendlyWarning( - sprintf('Recurring transaction #%d should be a "%s" but is a "%s" and will be corrected.', $recurrence->id, $link, $type->type) - ); + $this->friendlyWarning(sprintf( + 'Recurring transaction #%d should be a "%s" but is a "%s" and will be corrected.', + $recurrence->id, + $link, + $type->type + )); $transactionType = TransactionType::whereType($link)->first(); if (null !== $transactionType) { $recurrence->transaction_type_id = $transactionType->id; diff --git a/app/Console/Commands/Correction/CorrectsTimezoneInformation.php b/app/Console/Commands/Correction/CorrectsTimezoneInformation.php index 38dca1a0dc..f921dc354d 100644 --- a/app/Console/Commands/Correction/CorrectsTimezoneInformation.php +++ b/app/Console/Commands/Correction/CorrectsTimezoneInformation.php @@ -46,21 +46,20 @@ class CorrectsTimezoneInformation extends Command { use ShowsFriendlyMessages; - public static array $models - = [ - AccountBalance::class => ['date'], // done - AvailableBudget::class => ['start_date', 'end_date'], // done - Bill::class => ['date', 'end_date', 'extension_date'], // done - BudgetLimit::class => ['start_date', 'end_date'], // done - CurrencyExchangeRate::class => ['date'], // done - InvitedUser::class => ['expires'], - PiggyBankEvent::class => ['date'], - PiggyBankRepetition::class => ['start_date', 'target_date'], - PiggyBank::class => ['start_date', 'target_date'], // done - Recurrence::class => ['first_date', 'repeat_until', 'latest_date'], - Tag::class => ['date'], - TransactionJournal::class => ['date'], - ]; + public static array $models = [ + AccountBalance::class => ['date'], // done + AvailableBudget::class => ['start_date', 'end_date'], // done + Bill::class => ['date', 'end_date', 'extension_date'], // done + BudgetLimit::class => ['start_date', 'end_date'], // done + CurrencyExchangeRate::class => ['date'], // done + InvitedUser::class => ['expires'], + PiggyBankEvent::class => ['date'], + PiggyBankRepetition::class => ['start_date', 'target_date'], + PiggyBank::class => ['start_date', 'target_date'], // done + Recurrence::class => ['first_date', 'repeat_until', 'latest_date'], + Tag::class => ['date'], + TransactionJournal::class => ['date'] + ]; protected $description = 'Make sure all dates have a timezone.'; protected $signature = 'correction:timezones'; diff --git a/app/Console/Commands/Correction/CorrectsTransactionTypes.php b/app/Console/Commands/Correction/CorrectsTransactionTypes.php index 18d99038ed..c16afdff4b 100644 --- a/app/Console/Commands/Correction/CorrectsTransactionTypes.php +++ b/app/Console/Commands/Correction/CorrectsTransactionTypes.php @@ -72,14 +72,12 @@ class CorrectsTransactionTypes extends Command */ private function collectJournals(): Collection { - return TransactionJournal::with(['transactionType', 'transactions', 'transactions.account', 'transactions.account.accountType']) - ->get() - ; + return TransactionJournal::with(['transactionType', 'transactions', 'transactions.account', 'transactions.account.accountType'])->get(); } private function fixJournal(TransactionJournal $journal): bool { - $type = $journal->transactionType->type; + $type = $journal->transactionType->type; try { $source = $this->getSourceAccount($journal); @@ -91,16 +89,14 @@ class CorrectsTransactionTypes extends Command } $expectedType = (string) config(sprintf('firefly.account_to_transaction.%s.%s', $source->accountType->type, $destination->accountType->type)); if ($expectedType !== $type) { - $this->friendlyWarning( - sprintf( - 'Transaction journal #%d was of type "%s" but is corrected to "%s" (%s -> %s)', - $journal->id, - $type, - $expectedType, - $source->accountType->type, - $destination->accountType->type, - ) - ); + $this->friendlyWarning(sprintf( + 'Transaction journal #%d was of type "%s" but is corrected to "%s" (%s -> %s)', + $journal->id, + $type, + $expectedType, + $source->accountType->type, + $destination->accountType->type + )); $this->changeJournal($journal, $expectedType); return true; @@ -114,9 +110,7 @@ class CorrectsTransactionTypes extends Command */ private function getSourceAccount(TransactionJournal $journal): Account { - $collection = $journal->transactions->filter( - static fn (Transaction $transaction): bool => $transaction->amount < 0 - ); + $collection = $journal->transactions->filter(static fn(Transaction $transaction): bool => $transaction->amount < 0); if (0 === $collection->count()) { throw new FireflyException(sprintf('300001: Journal #%d has no source transaction.', $journal->id)); } @@ -128,7 +122,7 @@ class CorrectsTransactionTypes extends Command $transaction = $collection->first(); /** @var null|Account $account */ - $account = $transaction->account; + $account = $transaction->account; if (null === $account) { throw new FireflyException(sprintf('300003: Journal #%d, transaction #%d has no source account.', $journal->id, $transaction->id)); } @@ -141,9 +135,7 @@ class CorrectsTransactionTypes extends Command */ private function getDestinationAccount(TransactionJournal $journal): Account { - $collection = $journal->transactions->filter( - static fn (Transaction $transaction): bool => $transaction->amount > 0 - ); + $collection = $journal->transactions->filter(static fn(Transaction $transaction): bool => $transaction->amount > 0); if (0 === $collection->count()) { throw new FireflyException(sprintf('300004: Journal #%d has no destination transaction.', $journal->id)); } @@ -155,7 +147,7 @@ class CorrectsTransactionTypes extends Command $transaction = $collection->first(); /** @var null|Account $account */ - $account = $transaction->account; + $account = $transaction->account; if (null === $account) { throw new FireflyException(sprintf('300006: Journal #%d, transaction #%d has no destination account.', $journal->id, $transaction->id)); } diff --git a/app/Console/Commands/Correction/CorrectsTransferBudgets.php b/app/Console/Commands/Correction/CorrectsTransferBudgets.php index a717741833..10e10ef388 100644 --- a/app/Console/Commands/Correction/CorrectsTransferBudgets.php +++ b/app/Console/Commands/Correction/CorrectsTransferBudgets.php @@ -46,8 +46,8 @@ class CorrectsTransferBudgets extends Command ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id') ->leftJoin('budget_transaction_journal', 'transaction_journals.id', '=', 'budget_transaction_journal.transaction_journal_id') ->whereNotIn('transaction_types.type', [TransactionTypeEnum::WITHDRAWAL->value]) - ->whereNotNull('budget_transaction_journal.budget_id')->get(['transaction_journals.*']) - ; + ->whereNotNull('budget_transaction_journal.budget_id') + ->get(['transaction_journals.*']); $count = 0; /** @var TransactionJournal $entry */ diff --git a/app/Console/Commands/Correction/CorrectsUnevenAmount.php b/app/Console/Commands/Correction/CorrectsUnevenAmount.php index 1bc8505f6b..624108274b 100644 --- a/app/Console/Commands/Correction/CorrectsUnevenAmount.php +++ b/app/Console/Commands/Correction/CorrectsUnevenAmount.php @@ -79,14 +79,14 @@ class CorrectsUnevenAmount extends Command ->leftJoin('transaction_types', 'transaction_types.id', 'transaction_journals.transaction_type_id') ->where('transaction_types.type', TransactionTypeEnum::TRANSFER->value) ->whereNotNull('foreign_currency_id') - ->whereNotNull('foreign_amount')->get(['transactions.transaction_journal_id']) - ; + ->whereNotNull('foreign_amount') + ->get(['transactions.transaction_journal_id']); $count = 0; /** @var Transaction $transaction */ foreach ($transactions as $transaction) { /** @var null|TransactionJournal $journal */ - $journal = TransactionJournal::find($transaction->transaction_journal_id); + $journal = TransactionJournal::find($transaction->transaction_journal_id); if (null === $journal) { Log::debug('Found no journal, continue.'); @@ -103,7 +103,7 @@ class CorrectsUnevenAmount extends Command $destination = $journal->transactions()->where('amount', '>', 0)->first(); /** @var null|Transaction $source */ - $source = $journal->transactions()->where('amount', '<', 0)->first(); + $source = $journal->transactions()->where('amount', '<', 0)->first(); if (null === $destination || null === $source) { Log::debug('Source or destination transaction is NULL, continue.'); @@ -112,12 +112,12 @@ class CorrectsUnevenAmount extends Command } if ($source->transaction_currency_id === $destination->transaction_currency_id) { Log::debug('Ready to swap data between transactions.'); - $destination->foreign_currency_id = $source->transaction_currency_id; - $destination->foreign_amount = Steam::positive($source->amount); + $destination->foreign_currency_id = $source->transaction_currency_id; + $destination->foreign_amount = Steam::positive($source->amount); $destination->transaction_currency_id = $source->foreign_currency_id; - $destination->amount = Steam::positive($source->foreign_amount); - $destination->balance_dirty = true; - $source->balance_dirty = true; + $destination->amount = Steam::positive($source->foreign_amount); + $destination->balance_dirty = true; + $source->balance_dirty = true; $destination->save(); $source->save(); $this->friendlyWarning(sprintf('Corrected foreign amounts of transfer #%d.', $journal->id)); @@ -133,16 +133,21 @@ class CorrectsUnevenAmount extends Command private function fixUnevenAmounts(): void { Log::debug('fixUnevenAmounts()'); - $journals = DB::table('transactions')->groupBy('transaction_journal_id')->whereNull('deleted_at')->get(['transaction_journal_id', DB::raw('SUM(amount) AS the_sum')]); + $journals = DB::table('transactions') + ->groupBy('transaction_journal_id') + ->whereNull('deleted_at') + ->get(['transaction_journal_id', DB::raw('SUM(amount) AS the_sum')]); /** @var stdClass $entry */ foreach ($journals as $entry) { $sum = (string) $entry->the_sum; $sum = Steam::floatalize($sum); - if (!is_numeric($sum) + if ( + !is_numeric($sum) || '' === $sum // @phpstan-ignore-line || str_contains($sum, 'e') - || str_contains($sum, ',')) { + || str_contains($sum, ',') + ) { $message = sprintf('Journal #%d has an invalid sum ("%s"). No sure what to do.', $entry->transaction_journal_id, $entry->the_sum); $this->friendlyWarning($message); Log::warning($message); @@ -168,16 +173,20 @@ class CorrectsUnevenAmount extends Command private function fixJournal(int $param): void { // one of the transactions is bad. - $journal = TransactionJournal::find($param); + $journal = TransactionJournal::find($param); if (null === $journal) { return; } /** @var null|Transaction $source */ - $source = $journal->transactions()->where('amount', '<', 0)->first(); + $source = $journal->transactions()->where('amount', '<', 0)->first(); if (null === $source) { - $this->friendlyError(sprintf('Journal #%d ("%s") has no source transaction. It will be deleted to maintain database consistency.', $journal->id ?? 0, $journal->description ?? '')); + $this->friendlyError(sprintf( + 'Journal #%d ("%s") has no source transaction. It will be deleted to maintain database consistency.', + $journal->id ?? 0, + $journal->description ?? '' + )); Transaction::where('transaction_journal_id', $journal->id ?? 0)->forceDelete(); TransactionJournal::where('id', $journal->id ?? 0)->forceDelete(); ++$this->count; @@ -185,14 +194,18 @@ class CorrectsUnevenAmount extends Command return; } - $amount = bcmul('-1', (string) $source->amount); + $amount = bcmul('-1', (string) $source->amount); // fix amount of destination: /** @var null|Transaction $destination */ - $destination = $journal->transactions()->where('amount', '>', 0)->first(); + $destination = $journal->transactions()->where('amount', '>', 0)->first(); if (null === $destination) { - $this->friendlyError(sprintf('Journal #%d ("%s") has no destination transaction. It will be deleted to maintain database consistency.', $journal->id ?? 0, $journal->description ?? '')); + $this->friendlyError(sprintf( + 'Journal #%d ("%s") has no destination transaction. It will be deleted to maintain database consistency.', + $journal->id ?? 0, + $journal->description ?? '' + )); Transaction::where('transaction_journal_id', $journal->id ?? 0)->forceDelete(); TransactionJournal::where('id', $journal->id ?? 0)->forceDelete(); @@ -208,7 +221,7 @@ class CorrectsUnevenAmount extends Command return; } - $message = sprintf('Sum of journal #%d is not zero, journal is broken and now fixed.', $journal->id); + $message = sprintf('Sum of journal #%d is not zero, journal is broken and now fixed.', $journal->id); $this->friendlyWarning($message); Log::warning($message); @@ -216,7 +229,7 @@ class CorrectsUnevenAmount extends Command $destination->amount = $amount; $destination->save(); - $message = sprintf('Corrected amount in transaction journal #%d', $param); + $message = sprintf('Corrected amount in transaction journal #%d', $param); $this->friendlyInfo($message); ++$this->count; } @@ -231,7 +244,7 @@ class CorrectsUnevenAmount extends Command $destination = $journal->transactions()->where('amount', '>', 0)->first(); /** @var Transaction $source */ - $source = $journal->transactions()->where('amount', '<', 0)->first(); + $source = $journal->transactions()->where('amount', '<', 0)->first(); // safety catch on NULL should not be necessary, we just had that catch. // source amount = dest foreign amount @@ -242,20 +255,23 @@ class CorrectsUnevenAmount extends Command // Log::debug(sprintf('[b] %s', bccomp(\FireflyIII\Support\Facades\Steam::positive($destination->amount), \FireflyIII\Support\Facades\Steam::positive($source->foreign_amount)))); // Log::debug(sprintf('[c] %s', var_export($source->transaction_currency_id === $destination->foreign_currency_id,true))); // Log::debug(sprintf('[d] %s', var_export((int) $destination->transaction_currency_id ===(int) $source->foreign_currency_id, true))); - return 0 === bccomp(Steam::positive($source->amount), Steam::positive($destination->foreign_amount)) + return ( + 0 === bccomp(Steam::positive($source->amount), Steam::positive($destination->foreign_amount)) && $source->transaction_currency_id === $destination->foreign_currency_id && 0 === bccomp(Steam::positive($destination->amount), Steam::positive($source->foreign_amount)) - && (int) $destination->transaction_currency_id === (int) $source->foreign_currency_id; + && (int) $destination->transaction_currency_id === (int) $source->foreign_currency_id + ); } private function matchCurrencies(): void { - $journals = TransactionJournal::leftJoin('transactions', 'transaction_journals.id', 'transactions.transaction_journal_id') - ->where('transactions.transaction_currency_id', '!=', DB::raw('transaction_journals.transaction_currency_id')) - ->get(['transaction_journals.*']) - ; + $journals = TransactionJournal::leftJoin('transactions', 'transaction_journals.id', 'transactions.transaction_journal_id')->where( + 'transactions.transaction_currency_id', + '!=', + DB::raw('transaction_journals.transaction_currency_id') + )->get(['transaction_journals.*']); - $count = 0; + $count = 0; /** @var TransactionJournal $journal */ foreach ($journals as $journal) { @@ -277,7 +293,7 @@ class CorrectsUnevenAmount extends Command private function isBetweenAssetAndLiability(TransactionJournal $journal): bool { /** @var null|Transaction $sourceTransaction */ - $sourceTransaction = $journal->transactions()->where('amount', '<', 0)->first(); + $sourceTransaction = $journal->transactions()->where('amount', '<', 0)->first(); /** @var null|Transaction $destinationTransaction */ $destinationTransaction = $journal->transactions()->where('amount', '>', 0)->first(); @@ -292,15 +308,15 @@ class CorrectsUnevenAmount extends Command return false; } - $source = $sourceTransaction->account; - $destination = $destinationTransaction->account; + $source = $sourceTransaction->account; + $destination = $destinationTransaction->account; if (null === $source || null === $destination) { Log::warning('Either is false, stop.'); return false; } - $sourceTypes = [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value]; + $sourceTypes = [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value]; // source is liability, destination is asset if (in_array($source->accountType->type, $sourceTypes, true) && AccountTypeEnum::ASSET->value === $destination->accountType->type) { @@ -320,9 +336,8 @@ class CorrectsUnevenAmount extends Command private function convertOldStyleTransactions(): void { - /** @var AccountRepositoryInterface $repository */ - $repository = app(AccountRepositoryInterface::class); + $repository = app(AccountRepositoryInterface::class); Log::debug('convertOldStyleTransactions()'); $count = 0; $transactions = Transaction::distinct() @@ -333,14 +348,18 @@ class CorrectsUnevenAmount extends Command ->whereNot('transaction_types.type', TransactionTypeEnum::TRANSFER->value) ->whereNotNull('foreign_currency_id') ->whereNotNull('foreign_amount') - ->whereIn('account_types.type', [AccountTypeEnum::ASSET->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value]) - ->get(['transactions.transaction_journal_id']) - ; + ->whereIn('account_types.type', [ + AccountTypeEnum::ASSET->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::MORTGAGE->value, + AccountTypeEnum::LOAN->value + ]) + ->get(['transactions.transaction_journal_id']); /** @var Transaction $transaction */ foreach ($transactions as $transaction) { /** @var null|TransactionJournal $journal */ - $journal = TransactionJournal::find($transaction->transaction_journal_id); + $journal = TransactionJournal::find($transaction->transaction_journal_id); $repository->setUser($journal->user); if (null === $journal) { Log::debug('Found no journal, continue.'); @@ -363,7 +382,10 @@ class CorrectsUnevenAmount extends Command continue; } - if (0 === bccomp((string) $source->amount, (string) $source->foreign_amount) && 0 === bccomp((string) $source->foreign_amount, (string) $source->amount)) { + if ( + 0 === bccomp((string) $source->amount, (string) $source->foreign_amount) + && 0 === bccomp((string) $source->foreign_amount, (string) $source->amount) + ) { Log::debug('Already fixed, continue.'); continue; @@ -372,12 +394,12 @@ class CorrectsUnevenAmount extends Command if ((int) $source->transaction_currency_id !== (int) $sourceCurrency->id) { Log::debug(sprintf('Ready to swap data in transaction #%d.', $source->id)); // swap amounts. - $amount = $source->amount; - $currency = $source->transaction_currency_id; - $source->amount = $source->foreign_amount; + $amount = $source->amount; + $currency = $source->transaction_currency_id; + $source->amount = $source->foreign_amount; $source->transaction_currency_id = $source->foreign_currency_id; - $source->foreign_amount = $amount; - $source->foreign_currency_id = $currency; + $source->foreign_amount = $amount; + $source->foreign_currency_id = $currency; $source->saveQuietly(); $source->refresh(); // Log::debug(sprintf('source->amount = %s', $source->amount)); @@ -391,22 +413,22 @@ class CorrectsUnevenAmount extends Command ++$count; Log::debug(sprintf('Ready to swap data in transaction #%d.', $destination->id)); // swap amounts. - $amount = $destination->amount; - $currency = $destination->transaction_currency_id; - $destination->amount = $destination->foreign_amount; + $amount = $destination->amount; + $currency = $destination->transaction_currency_id; + $destination->amount = $destination->foreign_amount; $destination->transaction_currency_id = $destination->foreign_currency_id; - $destination->foreign_amount = $amount; - $destination->foreign_currency_id = $currency; - $destination->balance_dirty = true; + $destination->foreign_amount = $amount; + $destination->foreign_currency_id = $currency; + $destination->balance_dirty = true; $destination->saveQuietly(); $destination->refresh(); + // Log::debug(sprintf('destination->amount = %s', $destination->amount)); // Log::debug(sprintf('destination->transaction_currency_id = %s', $destination->transaction_currency_id)); // Log::debug(sprintf('destination->foreign_amount = %s', $destination->foreign_amount)); // Log::debug(sprintf('destination->foreign_currency_id = %s', $destination->foreign_currency_id)); } - // // only fix the destination transaction // $destination->foreign_currency_id = $source->transaction_currency_id; // $destination->foreign_amount = \FireflyIII\Support\Facades\Steam::positive($source->amount); diff --git a/app/Console/Commands/Correction/CreatesAccessTokens.php b/app/Console/Commands/Correction/CreatesAccessTokens.php index ef478d8da2..38b1a678c3 100644 --- a/app/Console/Commands/Correction/CreatesAccessTokens.php +++ b/app/Console/Commands/Correction/CreatesAccessTokens.php @@ -37,7 +37,7 @@ class CreatesAccessTokens extends Command protected $description = 'Creates user access tokens which are used for command line access to personal data.'; - protected $signature = 'correction:access-tokens'; + protected $signature = 'correction:access-tokens'; /** * Execute the console command. @@ -50,8 +50,8 @@ class CreatesAccessTokens extends Command /** @var UserRepositoryInterface $repository */ $repository = app(UserRepositoryInterface::class); - $count = 0; - $users = $repository->all(); + $count = 0; + $users = $repository->all(); /** @var User $user */ foreach ($users as $user) { diff --git a/app/Console/Commands/Correction/CreatesGroupMemberships.php b/app/Console/Commands/Correction/CreatesGroupMemberships.php index 92709fdad0..2823ae4156 100644 --- a/app/Console/Commands/Correction/CreatesGroupMemberships.php +++ b/app/Console/Commands/Correction/CreatesGroupMemberships.php @@ -38,8 +38,9 @@ class CreatesGroupMemberships extends Command use ShowsFriendlyMessages; public const string CONFIG_NAME = '560_create_group_memberships'; - protected $description = 'Update group memberships'; - protected $signature = 'correction:create-group-memberships'; + + protected $description = 'Update group memberships'; + protected $signature = 'correction:create-group-memberships'; /** * Execute the console command. @@ -74,28 +75,22 @@ class CreatesGroupMemberships extends Command public static function createGroupMembership(User $user): void { // check if membership exists - $userGroup = UserGroup::where('title', $user->email)->first(); + $userGroup = UserGroup::where('title', $user->email)->first(); if (null === $userGroup) { $userGroup = UserGroup::create(['title' => $user->email]); } - $userRole = UserRole::where('title', UserRoleEnum::OWNER->value)->first(); + $userRole = UserRole::where('title', UserRoleEnum::OWNER->value)->first(); if (null === $userRole) { throw new FireflyException('Firefly III could not find a user role. Please make sure all migrations have run.'); } $membership = GroupMembership::where('user_id', $user->id) ->where('user_group_id', $userGroup->id) - ->where('user_role_id', $userRole->id)->first() - ; + ->where('user_role_id', $userRole->id) + ->first(); if (null === $membership) { - GroupMembership::create( - [ - 'user_id' => $user->id, - 'user_role_id' => $userRole->id, - 'user_group_id' => $userGroup->id, - ] - ); + GroupMembership::create(['user_id' => $user->id, 'user_role_id' => $userRole->id, 'user_group_id' => $userGroup->id]); } if (null === $user->user_group_id) { $user->user_group_id = $userGroup->id; diff --git a/app/Console/Commands/Correction/CreatesLinkTypes.php b/app/Console/Commands/Correction/CreatesLinkTypes.php index 19592b03cf..097a4b88a2 100644 --- a/app/Console/Commands/Correction/CreatesLinkTypes.php +++ b/app/Console/Commands/Correction/CreatesLinkTypes.php @@ -34,7 +34,7 @@ class CreatesLinkTypes extends Command protected $description = 'Creates all link types.'; - protected $signature = 'correction:link-types'; + protected $signature = 'correction:link-types'; /** * Execute the console command. @@ -46,16 +46,14 @@ class CreatesLinkTypes extends Command 'Related' => ['relates to', 'relates to'], 'Refund' => ['(partially) refunds', 'is (partially) refunded by'], 'Paid' => ['(partially) pays for', 'is (partially) paid for by'], - 'Reimbursement' => ['(partially) reimburses', 'is (partially) reimbursed by'], + 'Reimbursement' => ['(partially) reimburses', 'is (partially) reimbursed by'] ]; foreach ($set as $name => $values) { - $link = LinkType::where('name', $name) - ->first() - ; + $link = LinkType::where('name', $name)->first(); if (null === $link) { - $link = new LinkType(); - $link->name = $name; - $link->inward = $values[1]; + $link = new LinkType(); + $link->name = $name; + $link->inward = $values[1]; $link->outward = $values[0]; ++$count; $this->friendlyInfo(sprintf('Created missing link type "%s"', $name)); diff --git a/app/Console/Commands/Correction/RemovesBills.php b/app/Console/Commands/Correction/RemovesBills.php index a47ad03fc7..9a30b25887 100644 --- a/app/Console/Commands/Correction/RemovesBills.php +++ b/app/Console/Commands/Correction/RemovesBills.php @@ -47,7 +47,7 @@ class RemovesBills extends Command if (null === $withdrawal) { return 0; } - $journals = TransactionJournal::whereNotNull('bill_id')->where('transaction_type_id', '!=', $withdrawal->id)->get(); + $journals = TransactionJournal::whereNotNull('bill_id')->where('transaction_type_id', '!=', $withdrawal->id)->get(); /** @var TransactionJournal $journal */ foreach ($journals as $journal) { diff --git a/app/Console/Commands/Correction/RemovesEmptyGroups.php b/app/Console/Commands/Correction/RemovesEmptyGroups.php index 9058b2f2ab..063ecc3988 100644 --- a/app/Console/Commands/Correction/RemovesEmptyGroups.php +++ b/app/Console/Commands/Correction/RemovesEmptyGroups.php @@ -43,10 +43,11 @@ class RemovesEmptyGroups extends Command */ public function handle(): int { - $groupIds - = TransactionGroup::leftJoin('transaction_journals', 'transaction_groups.id', '=', 'transaction_journals.transaction_group_id') - ->whereNull('transaction_journals.id')->get(['transaction_groups.id'])->pluck('id')->toArray() - ; + $groupIds = TransactionGroup::leftJoin('transaction_journals', 'transaction_groups.id', '=', 'transaction_journals.transaction_group_id') + ->whereNull('transaction_journals.id') + ->get(['transaction_groups.id']) + ->pluck('id') + ->toArray(); $total = count($groupIds); if ($total > 0) { diff --git a/app/Console/Commands/Correction/RemovesEmptyJournals.php b/app/Console/Commands/Correction/RemovesEmptyJournals.php index 1e850b4bda..127cf9db11 100644 --- a/app/Console/Commands/Correction/RemovesEmptyJournals.php +++ b/app/Console/Commands/Correction/RemovesEmptyJournals.php @@ -38,7 +38,7 @@ class RemovesEmptyJournals extends Command protected $description = 'Delete empty and uneven transaction journals.'; - protected $signature = 'correction:empty-journals'; + protected $signature = 'correction:empty-journals'; /** * Execute the console command. @@ -56,13 +56,16 @@ class RemovesEmptyJournals extends Command */ private function deleteUnevenJournals(): void { - $set = Transaction::whereNull('deleted_at')->groupBy('transactions.transaction_journal_id')->get([DB::raw('COUNT(transactions.transaction_journal_id) as the_count'), 'transaction_journal_id']); + $set = Transaction::whereNull('deleted_at')->groupBy('transactions.transaction_journal_id')->get([ + DB::raw('COUNT(transactions.transaction_journal_id) as the_count'), + 'transaction_journal_id' + ]); $total = 0; /** @var Transaction $row */ foreach ($set as $row) { $count = (int) $row->the_count; - if (1 === $count % 2) { + if (1 === ($count % 2)) { // uneven number, delete journal and transactions: try { /** @var null|TransactionJournal $journal */ @@ -74,9 +77,10 @@ class RemovesEmptyJournals extends Command } Transaction::where('transaction_journal_id', $row->transaction_journal_id)->delete(); - $this->friendlyWarning( - sprintf('Deleted transaction journal #%d because it had an uneven number of transactions.', $row->transaction_journal_id) - ); + $this->friendlyWarning(sprintf( + 'Deleted transaction journal #%d because it had an uneven number of transactions.', + $row->transaction_journal_id + )); ++$total; } } @@ -88,8 +92,7 @@ class RemovesEmptyJournals extends Command $set = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->groupBy('transaction_journals.id') ->whereNull('transactions.transaction_journal_id') - ->get(['transaction_journals.id']) - ; + ->get(['transaction_journals.id']); foreach ($set as $entry) { try { diff --git a/app/Console/Commands/Correction/RemovesLinksToDeletedObjects.php b/app/Console/Commands/Correction/RemovesLinksToDeletedObjects.php index 45882fc38f..0637143f8f 100644 --- a/app/Console/Commands/Correction/RemovesLinksToDeletedObjects.php +++ b/app/Console/Commands/Correction/RemovesLinksToDeletedObjects.php @@ -1,6 +1,7 @@ whereNotNull('deleted_at')->get('tags.id')->pluck('id')->toArray(); - $deletedJournals = TransactionJournal::withTrashed()->whereNotNull('deleted_at')->get('transaction_journals.id')->pluck('id')->toArray(); - $deletedBudgets = Budget::withTrashed()->whereNotNull('deleted_at')->get('budgets.id')->pluck('id')->toArray(); - $deletedCategories = Category::withTrashed()->whereNotNull('deleted_at')->get('categories.id')->pluck('id')->toArray(); + $deletedTags = Tag::withTrashed() + ->whereNotNull('deleted_at') + ->get('tags.id') + ->pluck('id') + ->toArray(); + $deletedJournals = TransactionJournal::withTrashed() + ->whereNotNull('deleted_at') + ->get('transaction_journals.id') + ->pluck('id') + ->toArray(); + $deletedBudgets = Budget::withTrashed() + ->whereNotNull('deleted_at') + ->get('budgets.id') + ->pluck('id') + ->toArray(); + $deletedCategories = Category::withTrashed() + ->whereNotNull('deleted_at') + ->get('categories.id') + ->pluck('id') + ->toArray(); if (count($deletedTags) > 0) { $this->cleanupTags($deletedTags); @@ -72,8 +89,6 @@ class RemovesLinksToDeletedObjects extends Command $this->cleanupCategories($deletedCategories); } $this->friendlyNeutral('Validated links to deleted objects.'); - - } private function cleanupTags(array $tags): void @@ -91,13 +106,11 @@ class RemovesLinksToDeletedObjects extends Command $countCategories = 0; // #11333 foreach (array_chunk($journals, 1337) as $set) { - $countTags += DB::table('tag_transaction_journal')->whereIn('transaction_journal_id', $set)->delete(); - $countBudgets += DB::table('budget_transaction_journal')->whereIn('transaction_journal_id', $set)->delete(); + $countTags += DB::table('tag_transaction_journal')->whereIn('transaction_journal_id', $set)->delete(); + $countBudgets += DB::table('budget_transaction_journal')->whereIn('transaction_journal_id', $set)->delete(); $countCategories += DB::table('category_transaction_journal')->whereIn('transaction_journal_id', $set)->delete(); } - - if ($countTags > 0) { $this->friendlyInfo(sprintf('Removed %d old relationship(s) between tags and transactions.', $countTags)); } diff --git a/app/Console/Commands/Correction/RemovesOrphanedTransactions.php b/app/Console/Commands/Correction/RemovesOrphanedTransactions.php index 2fd8e94dd2..f3a42f2b96 100644 --- a/app/Console/Commands/Correction/RemovesOrphanedTransactions.php +++ b/app/Console/Commands/Correction/RemovesOrphanedTransactions.php @@ -40,7 +40,7 @@ class RemovesOrphanedTransactions extends Command protected $description = 'Deletes orphaned transactions.'; - protected $signature = 'correction:orphaned-transactions'; + protected $signature = 'correction:orphaned-transactions'; /** * Execute the console command. @@ -61,8 +61,7 @@ class RemovesOrphanedTransactions extends Command $set = TransactionJournal::leftJoin('transaction_groups', 'transaction_journals.transaction_group_id', 'transaction_groups.id') ->whereNotNull('transaction_groups.deleted_at') ->whereNull('transaction_journals.deleted_at') - ->get(['transaction_journals.id', 'transaction_journals.transaction_group_id']) - ; + ->get(['transaction_journals.id', 'transaction_journals.transaction_group_id']); $count = $set->count(); if (0 === $count) { // $this->friendlyPositive('No orphaned journals.'); @@ -75,13 +74,11 @@ class RemovesOrphanedTransactions extends Command $journal = TransactionJournal::withTrashed()->find($entry->id); if (null !== $journal) { $journal->delete(); - $this->friendlyWarning( - sprintf( - 'Journal #%d (part of deleted transaction group #%d) has been deleted as well.', - $entry->id, - $entry->transaction_group_id - ) - ); + $this->friendlyWarning(sprintf( + 'Journal #%d (part of deleted transaction group #%d) has been deleted as well.', + $entry->id, + $entry->transaction_group_id + )); } } } @@ -96,26 +93,18 @@ class RemovesOrphanedTransactions extends Command ->whereNotNull('transaction_journals.deleted_at') ->whereNull('transactions.deleted_at') ->whereNotNull('transactions.id') - ->get( - [ - 'transaction_journals.id as journal_id', - 'transactions.id as transaction_id', - ] - ) - ; + ->get(['transaction_journals.id as journal_id', 'transactions.id as transaction_id']); /** @var stdClass $entry */ foreach ($set as $entry) { $transaction = Transaction::find((int) $entry->transaction_id); if (null !== $transaction) { $transaction->delete(); - $this->friendlyWarning( - sprintf( - 'Transaction #%d (part of deleted transaction journal #%d) has been deleted as well.', - $entry->transaction_id, - $entry->journal_id - ) - ); + $this->friendlyWarning(sprintf( + 'Transaction #%d (part of deleted transaction journal #%d) has been deleted as well.', + $entry->transaction_id, + $entry->journal_id + )); ++$count; } } @@ -123,11 +112,7 @@ class RemovesOrphanedTransactions extends Command private function deleteFromOrphanedAccounts(): void { - $set - = Transaction::leftJoin('accounts', 'transactions.account_id', '=', 'accounts.id') - ->whereNotNull('accounts.deleted_at') - ->get(['transactions.*']) - ; + $set = Transaction::leftJoin('accounts', 'transactions.account_id', '=', 'accounts.id')->whereNotNull('accounts.deleted_at')->get(['transactions.*']); $count = 0; /** @var Transaction $transaction */ @@ -137,13 +122,11 @@ class RemovesOrphanedTransactions extends Command $journal = TransactionJournal::find($transaction->transaction_journal_id); $journal?->delete(); Transaction::where('transaction_journal_id', $transaction->transaction_journal_id)->delete(); - $this->friendlyWarning( - sprintf( - 'Deleted transaction journal #%d because account #%d was already deleted.', - $transaction->transaction_journal_id, - $transaction->account_id - ) - ); + $this->friendlyWarning(sprintf( + 'Deleted transaction journal #%d because account #%d was already deleted.', + $transaction->transaction_journal_id, + $transaction->account_id + )); ++$count; } } diff --git a/app/Console/Commands/Correction/RemovesZeroAmount.php b/app/Console/Commands/Correction/RemovesZeroAmount.php index fd9d1c344e..77bddaaaa0 100644 --- a/app/Console/Commands/Correction/RemovesZeroAmount.php +++ b/app/Console/Commands/Correction/RemovesZeroAmount.php @@ -35,14 +35,17 @@ class RemovesZeroAmount extends Command protected $description = 'Delete transactions with zero amount.'; - protected $signature = 'correction:zero-amounts'; + protected $signature = 'correction:zero-amounts'; /** * Execute the console command. */ public function handle(): int { - $set = Transaction::where('amount', 0)->get(['transaction_journal_id'])->pluck('transaction_journal_id')->toArray(); + $set = Transaction::where('amount', 0) + ->get(['transaction_journal_id']) + ->pluck('transaction_journal_id') + ->toArray(); $set = array_unique($set); $journals = TransactionJournal::whereIn('id', $set)->get(); diff --git a/app/Console/Commands/Correction/RestoresOAuthKeys.php b/app/Console/Commands/Correction/RestoresOAuthKeys.php index dd5dd5a2e1..8d23a405f2 100644 --- a/app/Console/Commands/Correction/RestoresOAuthKeys.php +++ b/app/Console/Commands/Correction/RestoresOAuthKeys.php @@ -73,7 +73,6 @@ class RestoresOAuthKeys extends Command if (!$this->keysInDatabase() && $this->keysOnDrive()) { $this->storeKeysInDB(); $this->friendlyInfo('Stored OAuth keys in database.'); - } } diff --git a/app/Console/Commands/Correction/TriggersCreditCalculation.php b/app/Console/Commands/Correction/TriggersCreditCalculation.php index 57918d9976..f99b762cd6 100644 --- a/app/Console/Commands/Correction/TriggersCreditCalculation.php +++ b/app/Console/Commands/Correction/TriggersCreditCalculation.php @@ -45,10 +45,10 @@ class TriggersCreditCalculation extends Command private function processAccounts(): void { - $accounts = Account::leftJoin('account_types', 'accounts.account_type_id', 'account_types.id') - ->whereIn('account_types.type', config('firefly.valid_liabilities')) - ->get(['accounts.*']) - ; + $accounts = Account::leftJoin('account_types', 'accounts.account_type_id', 'account_types.id')->whereIn( + 'account_types.type', + config('firefly.valid_liabilities') + )->get(['accounts.*']); foreach ($accounts as $account) { $this->processAccount($account); } diff --git a/app/Console/Commands/Explain/ExplainAvailableBudget.php b/app/Console/Commands/Explain/ExplainAvailableBudget.php index d22935d49e..92a78af629 100644 --- a/app/Console/Commands/Explain/ExplainAvailableBudget.php +++ b/app/Console/Commands/Explain/ExplainAvailableBudget.php @@ -40,7 +40,7 @@ class ExplainAvailableBudget extends Command * * @var string */ - protected $signature = 'explain:available-budget + protected $signature = 'explain:available-budget {--date=now : A date formatted YYYY-MM-DD or the word "now"} {--user=1 : The user ID.} {--token= : The user\'s access token.} diff --git a/app/Console/Commands/Export/ExportsData.php b/app/Console/Commands/Export/ExportsData.php index 2a9b55292c..7fa6898f5e 100644 --- a/app/Console/Commands/Export/ExportsData.php +++ b/app/Console/Commands/Export/ExportsData.php @@ -50,7 +50,7 @@ class ExportsData extends Command protected $description = 'Command to export data from Firefly III.'; - protected $signature = 'firefly-iii:export-data + protected $signature = 'firefly-iii:export-data {--user=1 : The user ID that the export should run for.} {--token= : The user\'s access token.} {--start= : First transaction to export. Defaults to your very first transaction. Only applies to transaction export.} @@ -85,7 +85,7 @@ class ExportsData extends Command } // set up repositories. $this->stupidLaravel(); - $user = $this->getUser(); + $user = $this->getUser(); $this->journalRepository->setUser($user); $this->accountRepository->setUser($user); @@ -100,7 +100,7 @@ class ExportsData extends Command // make export object and configure it. /** @var ExportDataGenerator $exporter */ - $exporter = app(ExportDataGenerator::class); + $exporter = app(ExportDataGenerator::class); $exporter->setUser($user); $exporter->setStart($options['start']); @@ -115,7 +115,7 @@ class ExportsData extends Command $exporter->setExportRules($options['export']['rules']); $exporter->setExportBills($options['export']['bills']); $exporter->setExportPiggies($options['export']['piggies']); - $data = $exporter->export(); + $data = $exporter->export(); if (0 === count($data)) { $this->friendlyError('You must export *something*. Use --export-transactions or another option. See docs.firefly-iii.org'); } @@ -165,13 +165,13 @@ class ExportsData extends Command 'recurring' => $this->option('export-recurring'), 'rules' => $this->option('export-rules'), 'bills' => $this->option('export-subscriptions'), - 'piggies' => $this->option('export-piggies'), + 'piggies' => $this->option('export-piggies') ], 'start' => $start, 'end' => $end, 'accounts' => $accounts, 'directory' => $export, - 'force' => $this->option('force'), + 'force' => $this->option('force') ]; } diff --git a/app/Console/Commands/Integrity/ReportsEmptyObjects.php b/app/Console/Commands/Integrity/ReportsEmptyObjects.php index 936d8cede3..25204cd21e 100644 --- a/app/Console/Commands/Integrity/ReportsEmptyObjects.php +++ b/app/Console/Commands/Integrity/ReportsEmptyObjects.php @@ -38,7 +38,7 @@ class ReportsEmptyObjects extends Command protected $description = 'Reports on empty database objects.'; - protected $signature = 'integrity:empty-objects'; + protected $signature = 'integrity:empty-objects'; /** * Execute the console command. @@ -64,18 +64,11 @@ class ReportsEmptyObjects extends Command ->distinct() ->whereNull('budget_transaction_journal.budget_id') ->whereNull('budgets.deleted_at') - ->get(['budgets.id', 'budgets.name', 'budgets.user_id', 'users.email']) - ; + ->get(['budgets.id', 'budgets.name', 'budgets.user_id', 'users.email']); /** @var stdClass $entry */ foreach ($set as $entry) { - $line = sprintf( - 'User #%d (%s) has budget #%d ("%s") which has no transactions.', - $entry->user_id, - $entry->email, - $entry->id, - $entry->name - ); + $line = sprintf('User #%d (%s) has budget #%d ("%s") which has no transactions.', $entry->user_id, $entry->email, $entry->id, $entry->name); $this->friendlyWarning($line); } } @@ -90,18 +83,11 @@ class ReportsEmptyObjects extends Command ->distinct() ->whereNull('category_transaction_journal.category_id') ->whereNull('categories.deleted_at') - ->get(['categories.id', 'categories.name', 'categories.user_id', 'users.email']) - ; + ->get(['categories.id', 'categories.name', 'categories.user_id', 'users.email']); /** @var stdClass $entry */ foreach ($set as $entry) { - $line = sprintf( - 'User #%d (%s) has category #%d ("%s") which has no transactions.', - $entry->user_id, - $entry->email, - $entry->id, - $entry->name - ); + $line = sprintf('User #%d (%s) has category #%d ("%s") which has no transactions.', $entry->user_id, $entry->email, $entry->id, $entry->name); $this->friendlyWarning($line); } } @@ -113,18 +99,11 @@ class ReportsEmptyObjects extends Command ->distinct() ->whereNull('tag_transaction_journal.tag_id') ->whereNull('tags.deleted_at') - ->get(['tags.id', 'tags.tag', 'tags.user_id', 'users.email']) - ; + ->get(['tags.id', 'tags.tag', 'tags.user_id', 'users.email']); /** @var stdClass $entry */ foreach ($set as $entry) { - $line = sprintf( - 'User #%d (%s) has tag #%d ("%s") which has no transactions.', - $entry->user_id, - $entry->email, - $entry->id, - $entry->tag - ); + $line = sprintf('User #%d (%s) has tag #%d ("%s") which has no transactions.', $entry->user_id, $entry->email, $entry->id, $entry->tag); $this->friendlyWarning($line); } } @@ -138,10 +117,7 @@ class ReportsEmptyObjects extends Command ->leftJoin('users', 'accounts.user_id', '=', 'users.id') ->groupBy(['accounts.id', 'accounts.encrypted', 'accounts.name', 'accounts.user_id', 'users.email']) ->whereNull('transactions.account_id') - ->get( - ['accounts.id', 'accounts.encrypted', 'accounts.name', 'accounts.user_id', 'users.email'] - ) - ; + ->get(['accounts.id', 'accounts.encrypted', 'accounts.name', 'accounts.user_id', 'users.email']); /** @var stdClass $entry */ foreach ($set as $entry) { @@ -160,18 +136,11 @@ class ReportsEmptyObjects extends Command ->leftJoin('users', 'budgets.user_id', '=', 'users.id') ->groupBy(['budgets.id', 'budgets.name', 'budgets.encrypted', 'budgets.user_id', 'users.email']) ->whereNull('budget_limits.id') - ->get(['budgets.id', 'budgets.name', 'budgets.user_id', 'budgets.encrypted', 'users.email']) - ; + ->get(['budgets.id', 'budgets.name', 'budgets.user_id', 'budgets.encrypted', 'users.email']); /** @var Budget $entry */ foreach ($set as $entry) { - $line = sprintf( - 'User #%d (%s) has budget #%d ("%s") which has no budget limits.', - $entry->user_id, - $entry->email, - $entry->id, - $entry->name - ); + $line = sprintf('User #%d (%s) has budget #%d ("%s") which has no budget limits.', $entry->user_id, $entry->email, $entry->id, $entry->name); $this->friendlyWarning($line); } } diff --git a/app/Console/Commands/Integrity/ReportsIntegrity.php b/app/Console/Commands/Integrity/ReportsIntegrity.php index 4684738cc9..dabee7ebb3 100644 --- a/app/Console/Commands/Integrity/ReportsIntegrity.php +++ b/app/Console/Commands/Integrity/ReportsIntegrity.php @@ -34,7 +34,7 @@ class ReportsIntegrity extends Command protected $description = 'Will report on the integrity of your database.'; - protected $signature = 'firefly-iii:report-integrity'; + protected $signature = 'firefly-iii:report-integrity'; /** * Execute the console command. @@ -45,11 +45,7 @@ class ReportsIntegrity extends Command if (!Schema::hasTable('users')) { return 1; } - $commands = [ - 'integrity:empty-objects', - 'integrity:total-sums', - 'integrity:file-permissions', - ]; + $commands = ['integrity:empty-objects', 'integrity:total-sums', 'integrity:file-permissions']; foreach ($commands as $command) { $this->friendlyLine(sprintf('Now executing %s', $command)); $this->call($command); diff --git a/app/Console/Commands/Integrity/ValidatesEnvironmentVariables.php b/app/Console/Commands/Integrity/ValidatesEnvironmentVariables.php index 65a6fc2912..4a72b828c7 100644 --- a/app/Console/Commands/Integrity/ValidatesEnvironmentVariables.php +++ b/app/Console/Commands/Integrity/ValidatesEnvironmentVariables.php @@ -1,6 +1,5 @@ friendlyError(sprintf('DEFAULT_LANGUAGE "%s" is not a valid language for Firefly III.', $language)); @@ -97,7 +96,7 @@ class ValidatesEnvironmentVariables extends Command private function validateStaticToken(): bool { - $token = (string)config('firefly.static_cron_token'); + $token = (string) config('firefly.static_cron_token'); if ('' !== $token && 32 !== strlen($token)) { $this->friendlyError('STATIC_CRON_TOKEN must be empty or a 32-character string.'); $this->friendlyError('Please check your .env file and make sure you use a valid setting.'); diff --git a/app/Console/Commands/Integrity/ValidatesFilePermissions.php b/app/Console/Commands/Integrity/ValidatesFilePermissions.php index 8a271bea95..606c9eba0d 100644 --- a/app/Console/Commands/Integrity/ValidatesFilePermissions.php +++ b/app/Console/Commands/Integrity/ValidatesFilePermissions.php @@ -1,6 +1,7 @@ PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, - PDO::ATTR_EMULATE_PREPARES => false, + PDO::ATTR_EMULATE_PREPARES => false ]; // when it fails, display error @@ -71,7 +71,7 @@ class CreatesDatabase extends Command // only continue when no error. // with PDO, try to list DB's ( /** @var array $stmt */ - $stmt = $pdo->query('SHOW DATABASES;'); + $stmt = $pdo->query('SHOW DATABASES;'); // slightly more complex but less error-prone. foreach ($stmt as $row) { $name = $row['Database'] ?? false; diff --git a/app/Console/Commands/System/CreatesFirstUser.php b/app/Console/Commands/System/CreatesFirstUser.php index 18fa530bb8..82513efb11 100644 --- a/app/Console/Commands/System/CreatesFirstUser.php +++ b/app/Console/Commands/System/CreatesFirstUser.php @@ -36,7 +36,7 @@ class CreatesFirstUser extends Command protected $description = 'Creates a new user and gives admin rights. Outputs the password on the command line. Strictly for testing.'; - protected $signature = 'system:create-first-user {email}'; + protected $signature = 'system:create-first-user {email}'; private UserRepositoryInterface $repository; /** @@ -50,20 +50,15 @@ class CreatesFirstUser extends Command return 1; } $this->stupidLaravel(); - $count = $this->repository->count(); + $count = $this->repository->count(); if ($count > 0) { $this->friendlyError('Already have more than zero users in DB.'); return 1; } - $data = [ - 'blocked' => false, - 'blocked_code' => null, - 'email' => $this->argument('email'), - 'role' => 'owner', - ]; - $password = Str::random(24); - $user = $this->repository->store($data); + $data = ['blocked' => false, 'blocked_code' => null, 'email' => $this->argument('email'), 'role' => 'owner']; + $password = Str::random(24); + $user = $this->repository->store($data); $user->password = Hash::make($password); $user->save(); $user->setRememberToken(Str::random(60)); diff --git a/app/Console/Commands/System/ForcesDecimalSize.php b/app/Console/Commands/System/ForcesDecimalSize.php index ec6ca7fc79..75fc51149f 100644 --- a/app/Console/Commands/System/ForcesDecimalSize.php +++ b/app/Console/Commands/System/ForcesDecimalSize.php @@ -58,37 +58,35 @@ class ForcesDecimalSize extends Command protected $description = 'This command resizes DECIMAL columns in MySQL or PostgreSQL and correct amounts (only MySQL).'; protected $signature = 'firefly-iii:force-decimal-size {--force}'; private string $cast; - private array $classes - = [ - 'accounts' => Account::class, - 'auto_budgets' => AutoBudget::class, - 'available_budgets' => AvailableBudget::class, - 'bills' => Bill::class, - 'budget_limits' => BudgetLimit::class, - 'piggy_bank_events' => PiggyBankEvent::class, - 'piggy_bank_repetitions' => PiggyBankRepetition::class, - 'piggy_banks' => PiggyBank::class, - 'recurrences_transactions' => RecurrenceTransaction::class, - 'transactions' => Transaction::class, - ]; + private array $classes = [ + 'accounts' => Account::class, + 'auto_budgets' => AutoBudget::class, + 'available_budgets' => AvailableBudget::class, + 'bills' => Bill::class, + 'budget_limits' => BudgetLimit::class, + 'piggy_bank_events' => PiggyBankEvent::class, + 'piggy_bank_repetitions' => PiggyBankRepetition::class, + 'piggy_banks' => PiggyBank::class, + 'recurrences_transactions' => RecurrenceTransaction::class, + 'transactions' => Transaction::class + ]; private string $operator; private string $regularExpression; - private array $tables - = [ - 'accounts' => ['virtual_balance'], - 'auto_budgets' => ['amount'], - 'available_budgets' => ['amount'], - 'bills' => ['amount_min', 'amount_max'], - 'budget_limits' => ['amount'], - 'currency_exchange_rates' => ['rate', 'user_rate'], - 'limit_repetitions' => ['amount'], - 'piggy_bank_events' => ['amount'], - 'piggy_bank_repetitions' => ['current_amount'], - 'piggy_banks' => ['target_amount'], - 'recurrences_transactions' => ['amount', 'foreign_amount'], - 'transactions' => ['amount', 'foreign_amount'], - ]; + private array $tables = [ + 'accounts' => ['virtual_balance'], + 'auto_budgets' => ['amount'], + 'available_budgets' => ['amount'], + 'bills' => ['amount_min', 'amount_max'], + 'budget_limits' => ['amount'], + 'currency_exchange_rates' => ['rate', 'user_rate'], + 'limit_repetitions' => ['amount'], + 'piggy_bank_events' => ['amount'], + 'piggy_bank_repetitions' => ['current_amount'], + 'piggy_banks' => ['target_amount'], + 'recurrences_transactions' => ['amount', 'foreign_amount'], + 'transactions' => ['amount', 'foreign_amount'] + ]; /** * Execute the console command. @@ -117,13 +115,13 @@ class ForcesDecimalSize extends Command private function determineDatabaseType(): void { // switch stuff based on database connection: - $this->operator = 'REGEXP'; + $this->operator = 'REGEXP'; $this->regularExpression = '\'\\\.[\\\d]{%d}[1-9]+\''; - $this->cast = 'CHAR'; + $this->cast = 'CHAR'; if ('pgsql' === config('database.default')) { - $this->operator = 'SIMILAR TO'; + $this->operator = 'SIMILAR TO'; $this->regularExpression = '\'%%\.[\d]{%d}[1-9]+%%\''; - $this->cast = 'TEXT'; + $this->cast = 'TEXT'; } if ('sqlite' === config('database.default')) { $this->regularExpression = '"\.[\d]{%d}[1-9]+"'; @@ -136,17 +134,19 @@ class ForcesDecimalSize extends Command private function correctAmounts(): void { // if sqlite, add function? - if ('sqlite' === (string)config('database.default')) { - DB::connection()->getPdo()->sqliteCreateFunction('REGEXP', static function ($pattern, $value): int { - mb_regex_encoding('UTF-8'); - $pattern = trim($pattern, '"'); + if ('sqlite' === (string) config('database.default')) { + DB::connection() + ->getPdo() + ->sqliteCreateFunction('REGEXP', static function ($pattern, $value): int { + mb_regex_encoding('UTF-8'); + $pattern = trim($pattern, '"'); - return (mb_ereg($pattern, (string)$value)) ? 1 : 0; - }); + return mb_ereg($pattern, (string) $value) ? 1 : 0; + }); } - if (!in_array((string)config('database.default'), ['mysql', 'pgsql', 'sqlite'], true)) { - $this->friendlyWarning(sprintf('Skip correcting amounts, does not support "%s"...', (string)config('database.default'))); + if (!in_array((string) config('database.default'), ['mysql', 'pgsql', 'sqlite'], true)) { + $this->friendlyWarning(sprintf('Skip correcting amounts, does not support "%s"...', (string) config('database.default'))); return; } @@ -239,10 +239,9 @@ class ForcesDecimalSize extends Command $regularExpression = $this->regularExpression; /** @var Builder $query */ - $query = Account::leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id') + $query = Account::leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id') ->where('account_meta.name', 'currency_id') - ->where('account_meta.data', json_encode((string)$currency->id)) - ; + ->where('account_meta.data', json_encode((string) $currency->id)); $query->where(static function (Builder $q) use ($fields, $currency, $operator, $cast, $regularExpression): void { foreach ($fields as $field) { $q->orWhere( @@ -252,7 +251,7 @@ class ForcesDecimalSize extends Command ); } }); - $result = $query->get(['accounts.*']); + $result = $query->get(['accounts.*']); if (0 === $result->count()) { $this->friendlyPositive(sprintf('All accounts in %s are OK', $currency->code)); @@ -263,13 +262,13 @@ class ForcesDecimalSize extends Command foreach ($result as $account) { /** @var string $field */ foreach ($fields as $field) { - $value = $account->{$field}; + $value = $account->{$field}; if (null === $value) { continue; } // fix $field by rounding it down correctly. - $pow = 10 ** $currency->decimal_places; - $correct = bcdiv((string)round($value * $pow), (string)$pow, 12); + $pow = 10 ** $currency->decimal_places; + $correct = bcdiv((string) round($value * $pow), (string) $pow, 12); $this->friendlyInfo(sprintf('Account #%d has %s with value "%s", this has been corrected to "%s".', $account->id, $field, $value, $correct)); /** @var null|Account $updateAccount */ @@ -291,20 +290,15 @@ class ForcesDecimalSize extends Command $regularExpression = $this->regularExpression; /** @var Builder $query */ - $query = $class::where('transaction_currency_id', $currency->id)->where( - static function (Builder $q) use ($fields, $currency, $operator, $cast, $regularExpression): void { + $query = $class::where('transaction_currency_id', $currency->id) + ->where(static function (Builder $q) use ($fields, $currency, $operator, $cast, $regularExpression): void { /** @var string $field */ foreach ($fields as $field) { - $q->orWhere( - DB::raw(sprintf('CAST(%s AS %s)', $field, $cast)), - $operator, - DB::raw(sprintf($regularExpression, $currency->decimal_places)) - ); + $q->orWhere(DB::raw(sprintf('CAST(%s AS %s)', $field, $cast)), $operator, DB::raw(sprintf($regularExpression, $currency->decimal_places))); } - } - ); + }); - $result = $query->get(); + $result = $query->get(); if (0 === $result->count()) { $this->friendlyPositive(sprintf('All %s in %s are OK', $table, $currency->code)); @@ -315,17 +309,17 @@ class ForcesDecimalSize extends Command foreach ($result as $item) { /** @var string $field */ foreach ($fields as $field) { - $value = $item->{$field}; + $value = $item->{$field}; if (null === $value || '' === $value) { continue; } // fix $field by rounding it down correctly. $pow = 10 ** $currency->decimal_places; - $correct = bcdiv((string)round($value * $pow), (string)$pow, 12); + $correct = bcdiv((string) round($value * $pow), (string) $pow, 12); $this->friendlyWarning(sprintf('%s #%d has %s with value "%s", this has been corrected to "%s".', $table, $item->id, $field, $value, $correct)); /** @var null|Model $model */ - $model = $class::find($item->id); + $model = $class::find($item->id); $model?->update([$field => $correct]); } } @@ -341,11 +335,11 @@ class ForcesDecimalSize extends Command $regularExpression = $this->regularExpression; /** @var Builder $query */ - $query = PiggyBankEvent::leftJoin('piggy_banks', 'piggy_bank_events.piggy_bank_id', '=', 'piggy_banks.id') + $query = PiggyBankEvent::leftJoin('piggy_banks', 'piggy_bank_events.piggy_bank_id', '=', 'piggy_banks.id') ->leftJoin('accounts', 'piggy_banks.account_id', '=', 'accounts.id') ->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id') ->where('account_meta.name', 'currency_id') - ->where('account_meta.data', json_encode((string)$currency->id)) + ->where('account_meta.data', json_encode((string) $currency->id)) ->where(static function (Builder $q) use ($fields, $currency, $cast, $operator, $regularExpression): void { foreach ($fields as $field) { $q->orWhere( @@ -354,10 +348,9 @@ class ForcesDecimalSize extends Command DB::raw(sprintf($regularExpression, $currency->decimal_places)) ); } - }) - ; + }); - $result = $query->get(['piggy_bank_events.*']); + $result = $query->get(['piggy_bank_events.*']); if (0 === $result->count()) { $this->friendlyPositive(sprintf('All piggy bank events in %s are OK', $currency->code)); @@ -368,19 +361,23 @@ class ForcesDecimalSize extends Command foreach ($result as $item) { /** @var string $field */ foreach ($fields as $field) { - $value = $item->{$field}; + $value = $item->{$field}; if (null === $value) { continue; } // fix $field by rounding it down correctly. $pow = 10 ** $currency->decimal_places; - $correct = bcdiv((string)round($value * $pow), (string)$pow, 12); - $this->friendlyWarning( - sprintf('Piggy bank event #%d has %s with value "%s", this has been corrected to "%s".', $item->id, $field, $value, $correct) - ); + $correct = bcdiv((string) round($value * $pow), (string) $pow, 12); + $this->friendlyWarning(sprintf( + 'Piggy bank event #%d has %s with value "%s", this has been corrected to "%s".', + $item->id, + $field, + $value, + $correct + )); /** @var null|PiggyBankEvent $event */ - $event = PiggyBankEvent::find($item->id); + $event = PiggyBankEvent::find($item->id); $event?->update([$field => $correct]); } } @@ -397,11 +394,11 @@ class ForcesDecimalSize extends Command // select all piggy bank repetitions with this currency and issue. /** @var Builder $query */ - $query = PiggyBankRepetition::leftJoin('piggy_banks', 'piggy_bank_repetitions.piggy_bank_id', '=', 'piggy_banks.id') + $query = PiggyBankRepetition::leftJoin('piggy_banks', 'piggy_bank_repetitions.piggy_bank_id', '=', 'piggy_banks.id') ->leftJoin('accounts', 'piggy_banks.account_id', '=', 'accounts.id') ->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id') ->where('account_meta.name', 'currency_id') - ->where('account_meta.data', json_encode((string)$currency->id)) + ->where('account_meta.data', json_encode((string) $currency->id)) ->where(static function (Builder $q) use ($fields, $currency, $operator, $cast, $regularExpression): void { foreach ($fields as $field) { $q->orWhere( @@ -410,10 +407,9 @@ class ForcesDecimalSize extends Command DB::raw(sprintf($regularExpression, $currency->decimal_places)) ); } - }) - ; + }); - $result = $query->get(['piggy_bank_repetitions.*']); + $result = $query->get(['piggy_bank_repetitions.*']); if (0 === $result->count()) { $this->friendlyPositive(sprintf('All piggy bank repetitions in %s', $currency->code)); @@ -424,16 +420,20 @@ class ForcesDecimalSize extends Command foreach ($result as $item) { /** @var string $field */ foreach ($fields as $field) { - $value = $item->{$field}; + $value = $item->{$field}; if (null === $value) { continue; } // fix $field by rounding it down correctly. - $pow = 10 ** $currency->decimal_places; - $correct = bcdiv((string)round($value * $pow), (string)$pow, 12); - $this->friendlyWarning( - sprintf('Piggy bank repetition #%d has %s with value "%s", this has been corrected to "%s".', $item->id, $field, $value, $correct) - ); + $pow = 10 ** $currency->decimal_places; + $correct = bcdiv((string) round($value * $pow), (string) $pow, 12); + $this->friendlyWarning(sprintf( + 'Piggy bank repetition #%d has %s with value "%s", this has been corrected to "%s".', + $item->id, + $field, + $value, + $correct + )); /** @var null|PiggyBankRepetition $repetition */ $repetition = PiggyBankRepetition::find($item->id); @@ -452,10 +452,10 @@ class ForcesDecimalSize extends Command $regularExpression = $this->regularExpression; /** @var Builder $query */ - $query = PiggyBank::leftJoin('accounts', 'piggy_banks.account_id', '=', 'accounts.id') + $query = PiggyBank::leftJoin('accounts', 'piggy_banks.account_id', '=', 'accounts.id') ->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id') ->where('account_meta.name', 'currency_id') - ->where('account_meta.data', json_encode((string)$currency->id)) + ->where('account_meta.data', json_encode((string) $currency->id)) ->where(static function (Builder $q) use ($fields, $currency, $operator, $cast, $regularExpression): void { foreach ($fields as $field) { $q->orWhere( @@ -464,10 +464,9 @@ class ForcesDecimalSize extends Command DB::raw(sprintf($regularExpression, $currency->decimal_places)) ); } - }) - ; + }); - $result = $query->get(['piggy_banks.*']); + $result = $query->get(['piggy_banks.*']); if (0 === $result->count()) { $this->friendlyPositive(sprintf('All piggy banks in %s are OK', $currency->code)); @@ -478,13 +477,13 @@ class ForcesDecimalSize extends Command foreach ($result as $item) { /** @var string $field */ foreach ($fields as $field) { - $value = $item->{$field}; + $value = $item->{$field}; if (null === $value) { continue; } // fix $field by rounding it down correctly. - $pow = 10 ** $currency->decimal_places; - $correct = bcdiv((string)round($value * $pow), (string)$pow, 12); + $pow = 10 ** $currency->decimal_places; + $correct = bcdiv((string) round($value * $pow), (string) $pow, 12); $this->friendlyWarning(sprintf('Piggy bank #%d has %s with value "%s", this has been corrected to "%s".', $item->id, $field, $value, $correct)); /** @var null|PiggyBank $piggyBank */ @@ -501,7 +500,7 @@ class ForcesDecimalSize extends Command { // select all transactions with this currency and issue. /** @var Builder $query */ - $query = Transaction::where('transaction_currency_id', $currency->id)->where( + $query = Transaction::where('transaction_currency_id', $currency->id)->where( DB::raw(sprintf('CAST(amount as %s)', $this->cast)), $this->operator, DB::raw(sprintf($this->regularExpression, $currency->decimal_places)) @@ -514,13 +513,13 @@ class ForcesDecimalSize extends Command /** @var Transaction $item */ foreach ($result as $item) { - $value = $item->amount; + $value = $item->amount; if ('' === $value) { continue; } // fix $field by rounding it down correctly. - $pow = 10.0 ** $currency->decimal_places; - $correct = bcdiv((string)round((float)$value * $pow), (string)$pow, 12); + $pow = 10.0 ** $currency->decimal_places; + $correct = bcdiv((string) round((float) $value * $pow), (string) $pow, 12); $this->friendlyWarning(sprintf('Transaction #%d has amount with value "%s", this has been corrected to "%s".', $item->id, $value, $correct)); /** @var null|Transaction $transaction */ @@ -530,7 +529,7 @@ class ForcesDecimalSize extends Command // select all transactions with this FOREIGN currency and issue. /** @var Builder $query */ - $query = Transaction::where('foreign_currency_id', $currency->id)->where( + $query = Transaction::where('foreign_currency_id', $currency->id)->where( DB::raw(sprintf('CAST(foreign_amount as %s)', $this->cast)), $this->operator, DB::raw(sprintf($this->regularExpression, $currency->decimal_places)) @@ -545,16 +544,19 @@ class ForcesDecimalSize extends Command /** @var Transaction $item */ foreach ($result as $item) { - $value = $item->foreign_amount; + $value = $item->foreign_amount; if (null === $value) { continue; } // fix $field by rounding it down correctly. - $pow = 10.0 ** $currency->decimal_places; - $correct = bcdiv((string)round((float)$value * $pow), (string)$pow, 12); - $this->friendlyWarning( - sprintf('Transaction #%d has foreign amount with value "%s", this has been corrected to "%s".', $item->id, $value, $correct) - ); + $pow = 10.0 ** $currency->decimal_places; + $correct = bcdiv((string) round((float) $value * $pow), (string) $pow, 12); + $this->friendlyWarning(sprintf( + 'Transaction #%d has foreign amount with value "%s", this has been corrected to "%s".', + $item->id, + $value, + $correct + )); /** @var null|Transaction $transaction */ $transaction = Transaction::find($item->id); @@ -565,7 +567,7 @@ class ForcesDecimalSize extends Command private function updateDecimals(): void { $this->friendlyInfo('Going to force the size of DECIMAL columns. Please hold.'); - $type = (string)config('database.default'); + $type = (string) config('database.default'); /** * @var string $name diff --git a/app/Console/Commands/System/ForcesMigrations.php b/app/Console/Commands/System/ForcesMigrations.php index 479031c62e..0a913928cc 100644 --- a/app/Console/Commands/System/ForcesMigrations.php +++ b/app/Console/Commands/System/ForcesMigrations.php @@ -40,7 +40,7 @@ class ForcesMigrations extends Command protected $description = 'This command will force-run all database migrations.'; - protected $signature = 'firefly-iii:force-migrations + protected $signature = 'firefly-iii:force-migrations {--user=1 : The user ID.} {--token= : The user\'s access token.}'; @@ -78,7 +78,7 @@ class ForcesMigrations extends Command sleep(2); Schema::dropIfExists('migrations'); $this->friendlyLine('Re-run all migrations...'); - Artisan::call('migrate', ['--seed' => true, '--force' => true]); + Artisan::call('migrate', ['--seed' => true, '--force' => true]); sleep(2); $this->friendlyLine(''); $this->friendlyWarning('There is a good chance you just saw a lot of error messages.'); diff --git a/app/Console/Commands/System/OutputsInstructions.php b/app/Console/Commands/System/OutputsInstructions.php index 877576e4a4..c1dfda51a4 100644 --- a/app/Console/Commands/System/OutputsInstructions.php +++ b/app/Console/Commands/System/OutputsInstructions.php @@ -37,7 +37,7 @@ class OutputsInstructions extends Command protected $description = 'Instructions in case of upgrade trouble.'; - protected $signature = 'firefly-iii:instructions {task=install}'; + protected $signature = 'firefly-iii:instructions {task=install}'; /** * Execute the console command. @@ -60,26 +60,26 @@ class OutputsInstructions extends Command */ private function updateInstructions(): void { - $version = (string)config('firefly.version'); + $version = (string) config('firefly.version'); /** @var array $config */ - $config = config('upgrade.text.upgrade'); - $text = ''; + $config = config('upgrade.text.upgrade'); + $text = ''; /** @var string $compare */ foreach (array_keys($config) as $compare) { // if string starts with: if (str_starts_with($version, $compare)) { - $text = (string)$config[$compare]; + $text = (string) $config[$compare]; } } // validate some settings. - if ('' === $text && 'local' === (string)config('app.env')) { + if ('' === $text && 'local' === (string) config('app.env')) { $text = 'Please set APP_ENV=production for a safer environment.'; } - $prefix = 'v'; + $prefix = 'v'; if (str_starts_with($version, 'develop') || str_starts_with($version, 'branch')) { $prefix = ''; } @@ -116,8 +116,8 @@ class OutputsInstructions extends Command */ private function showLogo(): void { - $today = Carbon::now()->format('m-d'); - $month = Carbon::now()->format('m'); + $today = Carbon::now()->format('m-d'); + $month = Carbon::now()->format('m'); // variation in colors and effects just because I can! // default is Ukraine flag: $colors = ['blue', 'blue', 'blue', 'yellow', 'yellow', 'yellow', 'default', 'default']; @@ -166,7 +166,7 @@ class OutputsInstructions extends Command { $parts = explode("\n", wordwrap($text)); foreach ($parts as $string) { - $this->line('| '.sprintf('%-77s', $string).'|'); + $this->line('| ' . sprintf('%-77s', $string) . '|'); } } @@ -177,7 +177,7 @@ class OutputsInstructions extends Command { $parts = explode("\n", wordwrap($text)); foreach ($parts as $string) { - $this->info('| '.sprintf('%-77s', $string).'|'); + $this->info('| ' . sprintf('%-77s', $string) . '|'); } } @@ -193,26 +193,26 @@ class OutputsInstructions extends Command */ private function installInstructions(): void { - $version = (string)config('firefly.version'); + $version = (string) config('firefly.version'); /** @var array $config */ - $config = config('upgrade.text.install'); - $text = ''; + $config = config('upgrade.text.install'); + $text = ''; /** @var string $compare */ foreach (array_keys($config) as $compare) { // if string starts with: if (str_starts_with($version, $compare)) { - $text = (string)$config[$compare]; + $text = (string) $config[$compare]; } } // validate some settings. - if ('' === $text && 'local' === (string)config('app.env')) { + if ('' === $text && 'local' === (string) config('app.env')) { $text = 'Please set APP_ENV=production for a safer environment.'; } - $prefix = 'v'; + $prefix = 'v'; if (str_starts_with($version, 'develop')) { $prefix = ''; } @@ -251,7 +251,7 @@ class OutputsInstructions extends Command '"Be there or forever wonder."', '"A year from now you will wish you had started today."', '🇺🇦 Слава Україні!', - '🇺🇦 Slava Ukraini!', + '🇺🇦 Slava Ukraini!' ]; // fuck the Russian aggression in Ukraine. @@ -263,10 +263,7 @@ class OutputsInstructions extends Command // going on, to allow that to happen. if ('ru_RU' === config('firefly.default_language')) { - $lines = [ - '🇺🇦 Слава Україні!', - '🇺🇦 Slava Ukraini!', - ]; + $lines = ['🇺🇦 Слава Україні!', '🇺🇦 Slava Ukraini!']; } try { @@ -275,6 +272,5 @@ class OutputsInstructions extends Command $random = 0; } $this->line(sprintf(' %s', $lines[$random])); - } } diff --git a/app/Console/Commands/System/OutputsVersion.php b/app/Console/Commands/System/OutputsVersion.php index 56050f3cd4..86a523f364 100644 --- a/app/Console/Commands/System/OutputsVersion.php +++ b/app/Console/Commands/System/OutputsVersion.php @@ -30,7 +30,7 @@ class OutputsVersion extends Command { protected $description = 'Outputs the Firefly III version'; - protected $signature = 'firefly-iii:output-version'; + protected $signature = 'firefly-iii:output-version'; /** * Execute the console command. diff --git a/app/Console/Commands/System/RecalculatesRunningBalance.php b/app/Console/Commands/System/RecalculatesRunningBalance.php index 2f60436f0d..baa9b2c3d5 100644 --- a/app/Console/Commands/System/RecalculatesRunningBalance.php +++ b/app/Console/Commands/System/RecalculatesRunningBalance.php @@ -1,6 +1,5 @@ id, $e->getMessage())); $decryptedContent = $encryptedContent; } - $tempFileName = tempnam(sys_get_temp_dir(), 'FireflyIII'); + $tempFileName = tempnam(sys_get_temp_dir(), 'FireflyIII'); file_put_contents($tempFileName, $decryptedContent); - $attachment->md5 = md5_file($tempFileName); + $attachment->md5 = md5_file($tempFileName); $attachment->mime = mime_content_type($tempFileName); $attachment->save(); $this->friendlyInfo(sprintf('Fixed attachment #%d', $attachment->id)); diff --git a/app/Console/Commands/System/SetsLatestVersion.php b/app/Console/Commands/System/SetsLatestVersion.php index 823f69fec6..391bb59f30 100644 --- a/app/Console/Commands/System/SetsLatestVersion.php +++ b/app/Console/Commands/System/SetsLatestVersion.php @@ -34,7 +34,7 @@ class SetsLatestVersion extends Command protected $description = 'Set latest version in DB.'; - protected $signature = 'firefly-iii:set-latest-version {--james-is-cool}'; + protected $signature = 'firefly-iii:set-latest-version {--james-is-cool}'; /** * Execute the console command. diff --git a/app/Console/Commands/System/VerifySecurityAlerts.php b/app/Console/Commands/System/VerifySecurityAlerts.php index b7de7849c0..568255035a 100644 --- a/app/Console/Commands/System/VerifySecurityAlerts.php +++ b/app/Console/Commands/System/VerifySecurityAlerts.php @@ -25,13 +25,13 @@ declare(strict_types=1); namespace FireflyIII\Console\Commands\System; use FireflyIII\Console\Commands\ShowsFriendlyMessages; +use FireflyIII\Support\Facades\FireflyConfig; use Illuminate\Console\Command; use Illuminate\Database\QueryException; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Storage; use League\Flysystem\FilesystemException; use Safe\Exceptions\JsonException; -use FireflyIII\Support\Facades\FireflyConfig; use function Safe\json_decode; @@ -41,7 +41,7 @@ class VerifySecurityAlerts extends Command protected $description = 'Verify security alerts'; - protected $signature = 'firefly-iii:verify-security-alerts'; + protected $signature = 'firefly-iii:verify-security-alerts'; /** * Execute the console command. diff --git a/app/Console/Commands/Tools/ApplyRules.php b/app/Console/Commands/Tools/ApplyRules.php index 9745adbb8e..f7fad16a85 100644 --- a/app/Console/Commands/Tools/ApplyRules.php +++ b/app/Console/Commands/Tools/ApplyRules.php @@ -47,8 +47,7 @@ class ApplyRules extends Command protected $description = 'This command will apply your rules and rule groups on a selection of your transactions.'; - protected $signature - = 'firefly-iii:apply-rules + protected $signature = 'firefly-iii:apply-rules {--user=1 : The user ID.} {--token= : The user\'s access token.} {--accounts= : A comma-separated list of asset accounts or liabilities to apply your rules to.} @@ -57,16 +56,16 @@ class ApplyRules extends Command {--all_rules : If set, will overrule both settings and simply apply ALL of your rules.} {--start_date= : The date of the earliest transaction to be included (inclusive). If omitted, will be your very first transaction ever. Format: YYYY-MM-DD} {--end_date= : The date of the latest transaction to be included (inclusive). If omitted, will be your latest transaction ever. Format: YYYY-MM-DD}'; - private array $acceptedAccounts; - private Collection $accounts; - private bool $allRules; - private Carbon $endDate; - private Collection $groups; + private array $acceptedAccounts; + private Collection $accounts; + private bool $allRules; + private Carbon $endDate; + private Collection $groups; private RuleGroupRepositoryInterface $ruleGroupRepository; - private array $ruleGroupSelection; - private RuleRepositoryInterface $ruleRepository; - private array $ruleSelection; - private Carbon $startDate; + private array $ruleGroupSelection; + private RuleRepositoryInterface $ruleRepository; + private array $ruleSelection; + private Carbon $startDate; /** * Execute the console command. @@ -75,7 +74,7 @@ class ApplyRules extends Command */ public function handle(): int { - $start = microtime(true); + $start = microtime(true); $this->stupidLaravel(); if (!$this->verifyAccessToken()) { $this->friendlyError('Invalid access token.'); @@ -87,19 +86,19 @@ class ApplyRules extends Command $this->ruleRepository->setUser($this->getUser()); $this->ruleGroupRepository->setUser($this->getUser()); - $result = $this->verifyInput(); + $result = $this->verifyInput(); if (false === $result) { return 1; } - $this->allRules = $this->option('all_rules'); + $this->allRules = $this->option('all_rules'); // always get all the rules of the user. $this->grabAllRules(); // loop all groups and rules and indicate if they're included: - $rulesToApply = $this->getRulesToApply(); - $count = $rulesToApply->count(); + $rulesToApply = $this->getRulesToApply(); + $count = $rulesToApply->count(); if (0 === $count) { $this->friendlyError('No rules or rule groups have been included.'); $this->friendlyWarning('Make a selection using:'); @@ -112,7 +111,7 @@ class ApplyRules extends Command // create new rule engine: /** @var RuleEngineInterface $ruleEngine */ - $ruleEngine = app(RuleEngineInterface::class); + $ruleEngine = app(RuleEngineInterface::class); $ruleEngine->setRules($rulesToApply); $ruleEngine->setUser($this->getUser()); @@ -121,12 +120,12 @@ class ApplyRules extends Command foreach ($this->accounts as $account) { $filterAccountList[] = $account->id; } - $list = implode(',', $filterAccountList); - $ruleEngine->addOperator(['type' => 'account_id', 'value' => $list]); + $list = implode(',', $filterAccountList); + $ruleEngine->addOperator(['type' => 'account_id', 'value' => $list]); // add the date as a filter: - $ruleEngine->addOperator(['type' => 'date_after', 'value' => $this->startDate->format('Y-m-d')]); - $ruleEngine->addOperator(['type' => 'date_before', 'value' => $this->endDate->format('Y-m-d')]); + $ruleEngine->addOperator(['type' => 'date_after', 'value' => $this->startDate->format('Y-m-d')]); + $ruleEngine->addOperator(['type' => 'date_before', 'value' => $this->endDate->format('Y-m-d')]); // start running rules. $this->friendlyLine(sprintf('Will apply %d rule(s) to your transaction(s).', $count)); @@ -135,7 +134,7 @@ class ApplyRules extends Command $ruleEngine->fire(); $this->friendlyLine(''); - $end = round(microtime(true) - $start, 2); + $end = round(microtime(true) - $start, 2); $this->friendlyPositive(sprintf('Done in %s seconds!', $end)); return 0; @@ -148,14 +147,20 @@ class ApplyRules extends Command */ private function stupidLaravel(): void { - $this->allRules = false; - $this->accounts = new Collection(); - $this->ruleSelection = []; - $this->ruleGroupSelection = []; - $this->ruleRepository = app(RuleRepositoryInterface::class); + $this->allRules = false; + $this->accounts = new Collection(); + $this->ruleSelection = []; + $this->ruleGroupSelection = []; + $this->ruleRepository = app(RuleRepositoryInterface::class); $this->ruleGroupRepository = app(RuleGroupRepositoryInterface::class); - $this->acceptedAccounts = [AccountTypeEnum::DEFAULT->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::ASSET->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value]; - $this->groups = new Collection(); + $this->acceptedAccounts = [ + AccountTypeEnum::DEFAULT->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::ASSET->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::MORTGAGE->value + ]; + $this->groups = new Collection(); } /** @@ -185,32 +190,32 @@ class ApplyRules extends Command */ private function verifyInputAccounts(): bool { - $accountString = $this->option('accounts'); + $accountString = $this->option('accounts'); if (null === $accountString || '' === $accountString) { $this->friendlyError('Please use the --accounts option to indicate the accounts to apply rules to.'); return false; } - $finalList = new Collection(); - $accountList = explode(',', $accountString); + $finalList = new Collection(); + $accountList = explode(',', $accountString); /** @var AccountRepositoryInterface $accountRepository */ $accountRepository = app(AccountRepositoryInterface::class); $accountRepository->setUser($this->getUser()); foreach ($accountList as $accountId) { - $accountId = (int)$accountId; + $accountId = (int) $accountId; if (0 === $accountId) { $this->friendlyWarning('You provided an account with ID 0 (zero). It will be ignored.'); continue; } - $account = $accountRepository->find($accountId); + $account = $accountRepository->find($accountId); if (null === $account) { $this->friendlyWarning(sprintf('There is no account with ID #%d, it cannot be added.', $accountId)); continue; } - $type = $account->accountType->type; + $type = $account->accountType->type; if (!in_array($account->accountType->type, $this->acceptedAccounts, true)) { $this->friendlyWarning(sprintf('Account "%s" with ID #%d is of type "%s" and cannot be added.', $account->name, $accountId, $type)); @@ -224,7 +229,7 @@ class ApplyRules extends Command return false; } - $this->accounts = $finalList; + $this->accounts = $finalList; return true; } @@ -236,10 +241,10 @@ class ApplyRules extends Command // can be empty. return true; } - $ruleGroupList = explode(',', $ruleGroupString); + $ruleGroupList = explode(',', $ruleGroupString); foreach ($ruleGroupList as $ruleGroupId) { - $ruleGroupId = (int)$ruleGroupId; + $ruleGroupId = (int) $ruleGroupId; if (0 === $ruleGroupId) { $this->friendlyWarning('You added a rule group with ID 0 (zero). It will be skipped.'); @@ -247,7 +252,7 @@ class ApplyRules extends Command continue; } - $ruleGroup = $this->ruleGroupRepository->find($ruleGroupId); + $ruleGroup = $this->ruleGroupRepository->find($ruleGroupId); if (null === $ruleGroup) { $this->friendlyWarning(sprintf('There is no rule group with ID #%d, this ID will be ignored.', $ruleGroupId)); @@ -272,16 +277,16 @@ class ApplyRules extends Command // can be empty. return true; } - $ruleList = explode(',', $ruleString); + $ruleList = explode(',', $ruleString); foreach ($ruleList as $ruleId) { - $ruleId = (int)$ruleId; + $ruleId = (int) $ruleId; if (0 === $ruleId) { $this->friendlyWarning('You added a rule with ID 0 (zero). It will be skipped.'); continue; } - $rule = $this->ruleRepository->find($ruleId); + $rule = $this->ruleRepository->find($ruleId); if (null === $rule) { $this->friendlyWarning(sprintf('There is no rule with ID #%d, this ID will be ignored.', $ruleId)); @@ -304,13 +309,13 @@ class ApplyRules extends Command private function verifyInputDates(): void { // parse start date. - $inputStart = today(config('app.timezone'))->startOfMonth(); - $startString = $this->option('start_date'); + $inputStart = today(config('app.timezone'))->startOfMonth(); + $startString = $this->option('start_date'); if (null === $startString) { /** @var JournalRepositoryInterface $repository */ $repository = app(JournalRepositoryInterface::class); $repository->setUser($this->getUser()); - $first = $repository->firstNull(); + $first = $repository->firstNull(); if (null !== $first) { $inputStart = $first->date; } @@ -320,8 +325,8 @@ class ApplyRules extends Command } // parse end date - $inputEnd = today(config('app.timezone')); - $endString = $this->option('end_date'); + $inputEnd = today(config('app.timezone')); + $endString = $this->option('end_date'); if (null !== $endString && '' !== $endString) { $inputEnd = Carbon::createFromFormat('Y-m-d', $endString); } @@ -336,7 +341,7 @@ class ApplyRules extends Command } $this->startDate = $inputStart; - $this->endDate = $inputEnd; + $this->endDate = $inputEnd; } private function grabAllRules(): void @@ -374,8 +379,6 @@ class ApplyRules extends Command private function includeRule(Rule $rule, RuleGroup $group): bool { - return in_array((int)$group->id, $this->ruleGroupSelection, true) - || in_array((int)$rule->id, $this->ruleSelection, true) - || $this->allRules; + return in_array((int) $group->id, $this->ruleGroupSelection, true) || in_array((int) $rule->id, $this->ruleSelection, true) || $this->allRules; } } diff --git a/app/Console/Commands/Tools/Cron.php b/app/Console/Commands/Tools/Cron.php index f889e00e88..46a38852c0 100644 --- a/app/Console/Commands/Tools/Cron.php +++ b/app/Console/Commands/Tools/Cron.php @@ -33,10 +33,10 @@ use FireflyIII\Support\Cronjobs\ExchangeRatesCronjob; use FireflyIII\Support\Cronjobs\RecurringCronjob; use FireflyIII\Support\Cronjobs\UpdateCheckCronjob; use FireflyIII\Support\Cronjobs\WebhookCronjob; +use FireflyIII\Support\Facades\FireflyConfig; use Illuminate\Console\Command; use Illuminate\Support\Facades\Log; use InvalidArgumentException; -use FireflyIII\Support\Facades\FireflyConfig; class Cron extends Command { @@ -44,7 +44,7 @@ class Cron extends Command protected $description = 'Runs all Firefly III cron-job related commands. Configure a cron job according to the official Firefly III documentation.'; - protected $signature = 'firefly-iii:cron + protected $signature = 'firefly-iii:cron {--F|force : Force the cron job(s) to execute.} {--date= : Set the date in YYYY-MM-DD to make Firefly III think that\'s the current date.} {--check-version : Check if there is a new Firefly III version. Other tasks will be skipped unless also requested.} @@ -58,11 +58,11 @@ class Cron extends Command public function handle(): int { $doAll = !$this->option('download-cer') - && !$this->option('create-recurring') - && !$this->option('create-auto-budgets') - && !$this->option('send-subscription-warnings') - && !$this->option('check-version') - && !$this->option('send-webhook-messages'); + && !$this->option('create-recurring') + && !$this->option('create-auto-budgets') + && !$this->option('send-subscription-warnings') + && !$this->option('check-version') + && !$this->option('send-webhook-messages'); $date = null; try { @@ -142,7 +142,7 @@ class Cron extends Command return 0; } - private function exchangeRatesCronJob(bool $force, ?Carbon $date): void + private function exchangeRatesCronJob(bool $force, null|Carbon $date): void { Log::debug(sprintf('Created new ExchangeRateConverter in %s', __METHOD__)); $exchangeRates = new ExchangeRatesCronjob(); @@ -185,7 +185,7 @@ class Cron extends Command /** * @throws FireflyException */ - private function recurringCronJob(bool $force, ?Carbon $date): void + private function recurringCronJob(bool $force, null|Carbon $date): void { $recurring = new RecurringCronjob(); $recurring->setForce($force); @@ -207,7 +207,7 @@ class Cron extends Command } } - private function autoBudgetCronJob(bool $force, ?Carbon $date): void + private function autoBudgetCronJob(bool $force, null|Carbon $date): void { $autoBudget = new AutoBudgetCronjob(); $autoBudget->setForce($force); @@ -232,7 +232,7 @@ class Cron extends Command /** * @throws FireflyException */ - private function subscriptionWarningCronJob(bool $force, ?Carbon $date): void + private function subscriptionWarningCronJob(bool $force, null|Carbon $date): void { $subscriptionWarningJob = new BillWarningCronjob(); $subscriptionWarningJob->setForce($force); @@ -254,7 +254,7 @@ class Cron extends Command } } - private function webhookCronJob(bool $force, ?Carbon $date): void + private function webhookCronJob(bool $force, null|Carbon $date): void { $webhook = new WebhookCronjob(); $webhook->setForce($force); diff --git a/app/Console/Commands/Upgrade/AddsTransactionIdentifiers.php b/app/Console/Commands/Upgrade/AddsTransactionIdentifiers.php index bb48c3d529..5b632c210f 100644 --- a/app/Console/Commands/Upgrade/AddsTransactionIdentifiers.php +++ b/app/Console/Commands/Upgrade/AddsTransactionIdentifiers.php @@ -28,21 +28,22 @@ use FireflyIII\Console\Commands\ShowsFriendlyMessages; use FireflyIII\Models\Transaction; use FireflyIII\Models\TransactionJournal; use FireflyIII\Repositories\Journal\JournalCLIRepositoryInterface; +use FireflyIII\Support\Facades\FireflyConfig; use Illuminate\Console\Command; use Illuminate\Database\QueryException; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Schema; -use FireflyIII\Support\Facades\FireflyConfig; class AddsTransactionIdentifiers extends Command { use ShowsFriendlyMessages; public const string CONFIG_NAME = '480_transaction_identifier'; - protected $description = 'Fixes transaction identifiers.'; - protected $signature = 'upgrade:480-transaction-identifiers {--F|force : Force the execution of this command.}'; + + protected $description = 'Fixes transaction identifiers.'; + protected $signature = 'upgrade:480-transaction-identifiers {--F|force : Force the execution of this command.}'; private JournalCLIRepositoryInterface $cliRepository; - private int $count; + private int $count; /** * This method gives all transactions which are part of a split journal (so more than 2) a sort of "order" so they @@ -93,15 +94,14 @@ class AddsTransactionIdentifiers extends Command private function stupidLaravel(): void { $this->cliRepository = app(JournalCLIRepositoryInterface::class); - $this->count = 0; + $this->count = 0; } private function isExecuted(): bool { $configVar = FireflyConfig::get(self::CONFIG_NAME, false); - return (bool)$configVar?->data; - + return (bool) $configVar?->data; } /** @@ -110,8 +110,8 @@ class AddsTransactionIdentifiers extends Command */ private function updateJournalIdentifiers(TransactionJournal $transactionJournal): void { - $identifier = 0; - $exclude = []; // transactions already processed. + $identifier = 0; + $exclude = []; // transactions already processed. $transactions = $transactionJournal->transactions()->where('amount', '>', 0)->get(); /** @var Transaction $transaction */ @@ -120,18 +120,18 @@ class AddsTransactionIdentifiers extends Command if ($opposing instanceof Transaction) { // give both a new identifier: $transaction->identifier = $identifier; - $opposing->identifier = $identifier; + $opposing->identifier = $identifier; $transaction->save(); $opposing->save(); - $exclude[] = $transaction->id; - $exclude[] = $opposing->id; + $exclude[] = $transaction->id; + $exclude[] = $opposing->id; ++$this->count; } ++$identifier; } } - private function findOpposing(Transaction $transaction, array $exclude): ?Transaction + private function findOpposing(Transaction $transaction, array $exclude): null|Transaction { // find opposing: $amount = bcmul($transaction->amount, '-1'); @@ -139,10 +139,10 @@ class AddsTransactionIdentifiers extends Command try { /** @var Transaction $opposing */ $opposing = Transaction::where('transaction_journal_id', $transaction->transaction_journal_id) - ->where('amount', $amount)->where('identifier', '=', 0) + ->where('amount', $amount) + ->where('identifier', '=', 0) ->whereNotIn('id', $exclude) - ->first() - ; + ->first(); } catch (QueryException $e) { Log::error($e->getMessage()); $this->friendlyError('Firefly III could not find the "identifier" field in the "transactions" table.'); diff --git a/app/Console/Commands/Upgrade/RemovesDatabaseDecryption.php b/app/Console/Commands/Upgrade/RemovesDatabaseDecryption.php index 477ae31893..5212a172e2 100644 --- a/app/Console/Commands/Upgrade/RemovesDatabaseDecryption.php +++ b/app/Console/Commands/Upgrade/RemovesDatabaseDecryption.php @@ -27,6 +27,7 @@ namespace FireflyIII\Console\Commands\Upgrade; use FireflyIII\Console\Commands\ShowsFriendlyMessages; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Preference; +use FireflyIII\Support\Facades\FireflyConfig; use Illuminate\Console\Command; use Illuminate\Contracts\Encryption\DecryptException; use Illuminate\Support\Facades\Crypt; @@ -34,7 +35,6 @@ use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; use JsonException; use stdClass; -use FireflyIII\Support\Facades\FireflyConfig; use function Safe\json_decode; @@ -61,7 +61,7 @@ class RemovesDatabaseDecryption extends Command 'tags' => ['tag', 'description'], 'transaction_journals' => ['description'], 'transactions' => ['description'], - 'journal_links' => ['comment'], + 'journal_links' => ['comment'] ]; /** @@ -78,7 +78,6 @@ class RemovesDatabaseDecryption extends Command private function decryptTable(string $table, array $fields): void { if ($this->isDecrypted($table)) { - return; } foreach ($fields as $field) { @@ -101,8 +100,7 @@ class RemovesDatabaseDecryption extends Command Log::error($e->getMessage()); } - return (bool)$configVar?->data; - + return (bool) $configVar?->data; } private function decryptField(string $table, string $field): void @@ -121,8 +119,8 @@ class RemovesDatabaseDecryption extends Command if (null === $original) { return; } - $id = (int)$row->id; - $value = ''; + $id = (int) $row->id; + $value = ''; try { $value = $this->tryDecrypt($original); diff --git a/app/Console/Commands/Upgrade/RepairsAccountBalances.php b/app/Console/Commands/Upgrade/RepairsAccountBalances.php index 89a3e57951..48f7153a90 100644 --- a/app/Console/Commands/Upgrade/RepairsAccountBalances.php +++ b/app/Console/Commands/Upgrade/RepairsAccountBalances.php @@ -25,17 +25,18 @@ declare(strict_types=1); namespace FireflyIII\Console\Commands\Upgrade; use FireflyIII\Console\Commands\ShowsFriendlyMessages; +use FireflyIII\Support\Facades\FireflyConfig; use FireflyIII\Support\Models\AccountBalanceCalculator; use Illuminate\Console\Command; -use FireflyIII\Support\Facades\FireflyConfig; class RepairsAccountBalances extends Command { use ShowsFriendlyMessages; public const string CONFIG_NAME = '610_correct_balances'; - protected $description = 'Recalculate all account balance amounts'; - protected $signature = 'upgrade:610-account-balances {--F|force : Force the execution of this command.}'; + + protected $description = 'Recalculate all account balance amounts'; + protected $signature = 'upgrade:610-account-balances {--F|force : Force the execution of this command.}'; public function handle(): int { diff --git a/app/Console/Commands/Upgrade/RepairsPostgresSequences.php b/app/Console/Commands/Upgrade/RepairsPostgresSequences.php index b37f33afe8..ecd442868d 100644 --- a/app/Console/Commands/Upgrade/RepairsPostgresSequences.php +++ b/app/Console/Commands/Upgrade/RepairsPostgresSequences.php @@ -34,7 +34,7 @@ class RepairsPostgresSequences extends Command protected $description = 'Fixes issues with PostgreSQL sequences.'; - protected $signature = 'upgrade:600-pgsql-sequences'; + protected $signature = 'upgrade:600-pgsql-sequences'; /** * Execute the console command. @@ -45,7 +45,63 @@ class RepairsPostgresSequences extends Command return 0; } $this->friendlyLine('Going to verify PostgreSQL table sequences.'); - $tablesToCheck = ['2fa_tokens', 'account_meta', 'account_types', 'accounts', 'attachments', 'auto_budgets', 'available_budgets', 'bills', 'budget_limits', 'budget_transaction', 'budget_transaction_journal', 'budgets', 'categories', 'category_transaction', 'category_transaction_journal', 'configuration', 'currency_exchange_rates', 'failed_jobs', 'group_journals', 'jobs', 'journal_links', 'journal_meta', 'link_types', 'locations', 'migrations', 'notes', 'oauth_clients', 'oauth_personal_access_clients', 'object_groups', 'permissions', 'piggy_bank_events', 'piggy_bank_repetitions', 'piggy_banks', 'preferences', 'recurrences', 'recurrences_meta', 'recurrences_repetitions', 'recurrences_transactions', 'roles', 'rt_meta', 'rule_actions', 'rule_groups', 'rule_triggers', 'rules', 'tag_transaction_journal', 'tags', 'transaction_currencies', 'transaction_groups', 'transaction_journals', 'transaction_types', 'transactions', 'users', 'webhook_attempts', 'webhook_messages', 'webhooks']; + $tablesToCheck = [ + '2fa_tokens', + 'account_meta', + 'account_types', + 'accounts', + 'attachments', + 'auto_budgets', + 'available_budgets', + 'bills', + 'budget_limits', + 'budget_transaction', + 'budget_transaction_journal', + 'budgets', + 'categories', + 'category_transaction', + 'category_transaction_journal', + 'configuration', + 'currency_exchange_rates', + 'failed_jobs', + 'group_journals', + 'jobs', + 'journal_links', + 'journal_meta', + 'link_types', + 'locations', + 'migrations', + 'notes', + 'oauth_clients', + 'oauth_personal_access_clients', + 'object_groups', + 'permissions', + 'piggy_bank_events', + 'piggy_bank_repetitions', + 'piggy_banks', + 'preferences', + 'recurrences', + 'recurrences_meta', + 'recurrences_repetitions', + 'recurrences_transactions', + 'roles', + 'rt_meta', + 'rule_actions', + 'rule_groups', + 'rule_triggers', + 'rules', + 'tag_transaction_journal', + 'tags', + 'transaction_currencies', + 'transaction_groups', + 'transaction_journals', + 'transaction_types', + 'transactions', + 'users', + 'webhook_attempts', + 'webhook_messages', + 'webhooks' + ]; foreach ($tablesToCheck as $tableToCheck) { $this->friendlyLine(sprintf('Checking the next id sequence for table "%s".', $tableToCheck)); diff --git a/app/Console/Commands/Upgrade/UpgradesAccountCurrencies.php b/app/Console/Commands/Upgrade/UpgradesAccountCurrencies.php index 2d4570db21..89b09dc56a 100644 --- a/app/Console/Commands/Upgrade/UpgradesAccountCurrencies.php +++ b/app/Console/Commands/Upgrade/UpgradesAccountCurrencies.php @@ -33,10 +33,10 @@ use FireflyIII\Models\TransactionCurrency; use FireflyIII\Models\TransactionJournal; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\User\UserRepositoryInterface; +use FireflyIII\Support\Facades\Amount; +use FireflyIII\Support\Facades\FireflyConfig; use FireflyIII\User; use Illuminate\Console\Command; -use FireflyIII\Support\Facades\FireflyConfig; -use FireflyIII\Support\Facades\Amount; class UpgradesAccountCurrencies extends Command { @@ -44,11 +44,11 @@ class UpgradesAccountCurrencies extends Command public const string CONFIG_NAME = '480_account_currencies'; - protected $description = 'Give all accounts proper currency info.'; - protected $signature = 'upgrade:480-account-currencies {--F|force : Force the execution of this command.}'; + protected $description = 'Give all accounts proper currency info.'; + protected $signature = 'upgrade:480-account-currencies {--F|force : Force the execution of this command.}'; private AccountRepositoryInterface $accountRepos; - private int $count; - private UserRepositoryInterface $userRepos; + private int $count; + private UserRepositoryInterface $userRepos; /** * Each (asset) account must have a reference to a preferred currency. If the account does not have one, it's @@ -81,8 +81,8 @@ class UpgradesAccountCurrencies extends Command private function stupidLaravel(): void { $this->accountRepos = app(AccountRepositoryInterface::class); - $this->userRepos = app(UserRepositoryInterface::class); - $this->count = 0; + $this->userRepos = app(UserRepositoryInterface::class); + $this->count = 0; } private function isExecuted(): bool @@ -103,7 +103,7 @@ class UpgradesAccountCurrencies extends Command private function updateCurrenciesForUser(User $user): void { $this->accountRepos->setUser($user); - $accounts = $this->accountRepos->getAccountsByType([AccountTypeEnum::DEFAULT->value, AccountTypeEnum::ASSET->value]); + $accounts = $this->accountRepos->getAccountsByType([AccountTypeEnum::DEFAULT->value, AccountTypeEnum::ASSET->value]); // get user's currency preference: $primaryCurrency = Amount::getPrimaryCurrencyByUserGroup($user->userGroup); @@ -124,7 +124,7 @@ class UpgradesAccountCurrencies extends Command // both 0? set to default currency: if (0 === $accountCurrency && 0 === $obCurrency) { AccountMeta::where('account_id', $account->id)->where('name', 'currency_id')->forceDelete(); - AccountMeta::create(['account_id' => $account->id, 'name' => 'currency_id', 'data' => $currency->id]); + AccountMeta::create(['account_id' => $account->id, 'name' => 'currency_id', 'data' => $currency->id]); $this->friendlyInfo(sprintf('Account #%d ("%s") now has a currency setting (%s).', $account->id, $account->name, $currency->code)); ++$this->count; @@ -133,7 +133,7 @@ class UpgradesAccountCurrencies extends Command // account is set to 0, opening balance is not? if (0 === $accountCurrency && $obCurrency > 0) { - AccountMeta::create(['account_id' => $account->id, 'name' => 'currency_id', 'data' => $obCurrency]); + AccountMeta::create(['account_id' => $account->id, 'name' => 'currency_id', 'data' => $obCurrency]); $this->friendlyInfo(sprintf('Account #%d ("%s") now has a currency setting (#%d).', $account->id, $account->name, $obCurrency)); ++$this->count; @@ -144,12 +144,10 @@ class UpgradesAccountCurrencies extends Command // update opening balance: $openingBalance->transaction_currency_id = $accountCurrency; $openingBalance->save(); - $openingBalance->transactions->each( - static function (Transaction $transaction) use ($accountCurrency): void { - $transaction->transaction_currency_id = $accountCurrency; - $transaction->save(); - } - ); + $openingBalance->transactions->each(static function (Transaction $transaction) use ($accountCurrency): void { + $transaction->transaction_currency_id = $accountCurrency; + $transaction->save(); + }); $this->friendlyInfo(sprintf('Account #%d ("%s") now has a correct currency for opening balance.', $account->id, $account->name)); ++$this->count; } diff --git a/app/Console/Commands/Upgrade/UpgradesAccountMetaData.php b/app/Console/Commands/Upgrade/UpgradesAccountMetaData.php index 0317392225..bd00983bb3 100644 --- a/app/Console/Commands/Upgrade/UpgradesAccountMetaData.php +++ b/app/Console/Commands/Upgrade/UpgradesAccountMetaData.php @@ -27,8 +27,8 @@ namespace FireflyIII\Console\Commands\Upgrade; use FireflyIII\Console\Commands\ShowsFriendlyMessages; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\AccountMeta; -use Illuminate\Console\Command; use FireflyIII\Support\Facades\FireflyConfig; +use Illuminate\Console\Command; class UpgradesAccountMetaData extends Command { @@ -36,9 +36,9 @@ class UpgradesAccountMetaData extends Command public const string CONFIG_NAME = '480_rename_account_meta'; - protected $description = 'Rename account meta-data to new format.'; + protected $description = 'Rename account meta-data to new format.'; - protected $signature = 'upgrade:480-account-meta {--F|force : Force the execution of this command.}'; + protected $signature = 'upgrade:480-account-meta {--F|force : Force the execution of this command.}'; /** * Execute the console command. @@ -57,7 +57,7 @@ class UpgradesAccountMetaData extends Command 'accountRole' => 'account_role', 'ccType' => 'cc_type', 'accountNumber' => 'account_number', - 'ccMonthlyPaymentDate' => 'cc_monthly_payment_date', + 'ccMonthlyPaymentDate' => 'cc_monthly_payment_date' ]; $count = 0; @@ -85,8 +85,7 @@ class UpgradesAccountMetaData extends Command { $configVar = FireflyConfig::get(self::CONFIG_NAME, false); - return (bool)$configVar?->data; - + return (bool) $configVar?->data; } private function markAsExecuted(): void diff --git a/app/Console/Commands/Upgrade/UpgradesAttachments.php b/app/Console/Commands/Upgrade/UpgradesAttachments.php index 4a8b19eb04..50032f5c66 100644 --- a/app/Console/Commands/Upgrade/UpgradesAttachments.php +++ b/app/Console/Commands/Upgrade/UpgradesAttachments.php @@ -28,9 +28,9 @@ use FireflyIII\Console\Commands\ShowsFriendlyMessages; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Attachment; use FireflyIII\Models\Note; +use FireflyIII\Support\Facades\FireflyConfig; use Illuminate\Console\Command; use Illuminate\Support\Facades\Log; -use FireflyIII\Support\Facades\FireflyConfig; class UpgradesAttachments extends Command { @@ -38,9 +38,9 @@ class UpgradesAttachments extends Command public const string CONFIG_NAME = '480_migrate_attachments'; - protected $description = 'Migrates attachment meta-data.'; + protected $description = 'Migrates attachment meta-data.'; - protected $signature = 'upgrade:480-attachments {--F|force : Force the execution of this command.}'; + protected $signature = 'upgrade:480-attachments {--F|force : Force the execution of this command.}'; /** * Execute the console command. @@ -49,7 +49,7 @@ class UpgradesAttachments extends Command */ public function handle(): int { - $start = microtime(true); + $start = microtime(true); if ($this->isExecuted() && true !== $this->option('force')) { $this->friendlyInfo('This command has already been executed.'); @@ -65,12 +65,12 @@ class UpgradesAttachments extends Command $attDescription = (string) $att->description; if ('' !== $attDescription) { // find or create note: - $note = $att->notes()->first(); + $note = $att->notes()->first(); if (null === $note) { $note = new Note(); $note->noteable()->associate($att); } - $note->text = $attDescription; + $note->text = $attDescription; $note->save(); // clear description: @@ -84,7 +84,7 @@ class UpgradesAttachments extends Command if (0 !== $count) { $this->friendlyInfo(sprintf('Updated %d attachment(s).', $count)); } - $end = round(microtime(true) - $start, 2); + $end = round(microtime(true) - $start, 2); $this->friendlyInfo(sprintf('Migrated attachment notes in %s seconds.', $end)); $this->markAsExecuted(); @@ -95,8 +95,7 @@ class UpgradesAttachments extends Command { $configVar = FireflyConfig::get(self::CONFIG_NAME, false); - return (bool)$configVar?->data; - + return (bool) $configVar?->data; } private function markAsExecuted(): void diff --git a/app/Console/Commands/Upgrade/UpgradesBillsToRules.php b/app/Console/Commands/Upgrade/UpgradesBillsToRules.php index eba532e037..05c6975bab 100644 --- a/app/Console/Commands/Upgrade/UpgradesBillsToRules.php +++ b/app/Console/Commands/Upgrade/UpgradesBillsToRules.php @@ -33,10 +33,10 @@ use FireflyIII\Repositories\Bill\BillRepositoryInterface; use FireflyIII\Repositories\Rule\RuleRepositoryInterface; use FireflyIII\Repositories\RuleGroup\RuleGroupRepositoryInterface; use FireflyIII\Repositories\User\UserRepositoryInterface; +use FireflyIII\Support\Facades\FireflyConfig; use FireflyIII\Support\Facades\Preferences; use FireflyIII\User; use Illuminate\Console\Command; -use FireflyIII\Support\Facades\FireflyConfig; class UpgradesBillsToRules extends Command { @@ -44,14 +44,14 @@ class UpgradesBillsToRules extends Command public const string CONFIG_NAME = '480_bills_to_rules'; - protected $description = 'Migrate bills to rules.'; + protected $description = 'Migrate bills to rules.'; - protected $signature = 'upgrade:480-bills-to-rules {--F|force : Force the execution of this command.}'; - private BillRepositoryInterface $billRepository; - private int $count; + protected $signature = 'upgrade:480-bills-to-rules {--F|force : Force the execution of this command.}'; + private BillRepositoryInterface $billRepository; + private int $count; private RuleGroupRepositoryInterface $ruleGroupRepository; - private RuleRepositoryInterface $ruleRepository; - private UserRepositoryInterface $userRepository; + private RuleRepositoryInterface $ruleRepository; + private UserRepositoryInterface $userRepository; /** * Execute the console command. @@ -91,19 +91,18 @@ class UpgradesBillsToRules extends Command */ private function stupidLaravel(): void { - $this->count = 0; - $this->userRepository = app(UserRepositoryInterface::class); + $this->count = 0; + $this->userRepository = app(UserRepositoryInterface::class); $this->ruleGroupRepository = app(RuleGroupRepositoryInterface::class); - $this->billRepository = app(BillRepositoryInterface::class); - $this->ruleRepository = app(RuleRepositoryInterface::class); + $this->billRepository = app(BillRepositoryInterface::class); + $this->ruleRepository = app(RuleRepositoryInterface::class); } private function isExecuted(): bool { $configVar = FireflyConfig::get(self::CONFIG_NAME, false); - return (bool)$configVar?->data; - + return (bool) $configVar?->data; } /** @@ -122,15 +121,13 @@ class UpgradesBillsToRules extends Command $ruleGroup = $this->ruleGroupRepository->findByTitle($groupTitle); if (!$ruleGroup instanceof RuleGroup) { - $ruleGroup = $this->ruleGroupRepository->store( - [ - 'title' => (string) trans('firefly.rulegroup_for_bills_title', [], $language), - 'description' => (string) trans('firefly.rulegroup_for_bills_description', [], $language), - 'active' => true, - ] - ); + $ruleGroup = $this->ruleGroupRepository->store([ + 'title' => (string) trans('firefly.rulegroup_for_bills_title', [], $language), + 'description' => (string) trans('firefly.rulegroup_for_bills_description', [], $language), + 'active' => true + ]); } - $bills = $this->billRepository->getBills(); + $bills = $this->billRepository->getBills(); /** @var Bill $bill */ foreach ($bills as $bill) { @@ -146,51 +143,32 @@ class UpgradesBillsToRules extends Command $languageString = null !== $language->data && !is_array($language->data) ? (string) $language->data : 'en_US'; // get match thing: - $match = implode(' ', explode(',', $bill->match)); - $newRule = [ + $match = implode(' ', explode(',', $bill->match)); + $newRule = [ 'rule_group_id' => $ruleGroup->id, 'active' => true, 'strict' => false, 'stop_processing' => false, // field is no longer used. - 'title' => (string) trans('firefly.rule_for_bill_title', ['name' => $bill->name], $languageString), - 'description' => (string) trans('firefly.rule_for_bill_description', ['name' => $bill->name], $languageString), - 'trigger' => 'store-journal', - 'triggers' => [ - [ - 'type' => 'description_contains', - 'value' => $match, - ], - ], - 'actions' => [ - [ - 'type' => 'link_to_bill', - 'value' => $bill->name, - ], - ], + 'title' => (string) trans('firefly.rule_for_bill_title', ['name' => $bill->name], $languageString), + 'description' => (string) trans('firefly.rule_for_bill_description', ['name' => $bill->name], $languageString), + 'trigger' => 'store-journal', + 'triggers' => [['type' => 'description_contains', 'value' => $match]], + 'actions' => [['type' => 'link_to_bill', 'value' => $bill->name]] ]; // two triggers or one, depends on bill content: if ($bill->amount_max === $bill->amount_min) { - $newRule['triggers'][] = [ - 'type' => 'amount_exactly', - 'value' => $bill->amount_min, - ]; + $newRule['triggers'][] = ['type' => 'amount_exactly', 'value' => $bill->amount_min]; } if ($bill->amount_max !== $bill->amount_min) { - $newRule['triggers'][] = [ - 'type' => 'amount_less', - 'value' => $bill->amount_max, - ]; - $newRule['triggers'][] = [ - 'type' => 'amount_more', - 'value' => $bill->amount_min, - ]; + $newRule['triggers'][] = ['type' => 'amount_less', 'value' => $bill->amount_max]; + $newRule['triggers'][] = ['type' => 'amount_more', 'value' => $bill->amount_min]; } $this->ruleRepository->store($newRule); // update bill: - $newBillData = [ + $newBillData = [ 'currency_id' => $bill->transaction_currency_id, 'name' => $bill->name, 'match' => 'MIGRATED_TO_RULES', @@ -199,7 +177,7 @@ class UpgradesBillsToRules extends Command 'date' => $bill->date, 'repeat_freq' => $bill->repeat_freq, 'skip' => $bill->skip, - 'active' => $bill->active, + 'active' => $bill->active ]; $this->billRepository->update($bill, $newBillData); ++$this->count; diff --git a/app/Console/Commands/Upgrade/UpgradesBudgetLimitPeriods.php b/app/Console/Commands/Upgrade/UpgradesBudgetLimitPeriods.php index 982ad58f46..f55742ed47 100644 --- a/app/Console/Commands/Upgrade/UpgradesBudgetLimitPeriods.php +++ b/app/Console/Commands/Upgrade/UpgradesBudgetLimitPeriods.php @@ -26,9 +26,9 @@ namespace FireflyIII\Console\Commands\Upgrade; use FireflyIII\Console\Commands\ShowsFriendlyMessages; use FireflyIII\Models\BudgetLimit; +use FireflyIII\Support\Facades\FireflyConfig; use Illuminate\Console\Command; use Illuminate\Support\Facades\Log; -use FireflyIII\Support\Facades\FireflyConfig; class UpgradesBudgetLimitPeriods extends Command { @@ -36,9 +36,9 @@ class UpgradesBudgetLimitPeriods extends Command public const string CONFIG_NAME = '550_budget_limit_periods'; - protected $description = 'Append budget limits with their (estimated) timeframe.'; + protected $description = 'Append budget limits with their (estimated) timeframe.'; - protected $signature = 'upgrade:550-budget-limit-periods {--F|force : Force the execution of this command.}'; + protected $signature = 'upgrade:550-budget-limit-periods {--F|force : Force the execution of this command.}'; /** * Execute the console command. @@ -76,7 +76,7 @@ class UpgradesBudgetLimitPeriods extends Command private function fixLimit(BudgetLimit $limit): void { - $period = $this->getLimitPeriod($limit); + $period = $this->getLimitPeriod($limit); if (null === $period) { $message = sprintf( @@ -93,7 +93,7 @@ class UpgradesBudgetLimitPeriods extends Command $limit->period = $period; $limit->save(); - $msg = sprintf( + $msg = sprintf( 'Budget limit #%d (%s - %s) period is "%s".', $limit->id, $limit->start_date->format('Y-m-d'), @@ -103,14 +103,18 @@ class UpgradesBudgetLimitPeriods extends Command Log::debug($msg); } - private function getLimitPeriod(BudgetLimit $limit): ?string + private function getLimitPeriod(BudgetLimit $limit): null|string { // is daily if ($limit->end_date->isSameDay($limit->start_date)) { return 'daily'; } // is weekly - if ('1' === $limit->start_date->format('N') && '7' === $limit->end_date->format('N') && 6 === (int) $limit->end_date->diffInDays($limit->start_date, true)) { + if ( + '1' === $limit->start_date->format('N') + && '7' === $limit->end_date->format('N') + && 6 === (int) $limit->end_date->diffInDays($limit->start_date, true) + ) { return 'weekly'; } diff --git a/app/Console/Commands/Upgrade/UpgradesBudgetLimits.php b/app/Console/Commands/Upgrade/UpgradesBudgetLimits.php index 4a568024b5..5e95ff7a76 100644 --- a/app/Console/Commands/Upgrade/UpgradesBudgetLimits.php +++ b/app/Console/Commands/Upgrade/UpgradesBudgetLimits.php @@ -28,10 +28,10 @@ use FireflyIII\Console\Commands\ShowsFriendlyMessages; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Budget; use FireflyIII\Models\BudgetLimit; +use FireflyIII\Support\Facades\Amount; +use FireflyIII\Support\Facades\FireflyConfig; use FireflyIII\User; use Illuminate\Console\Command; -use FireflyIII\Support\Facades\FireflyConfig; -use FireflyIII\Support\Facades\Amount; class UpgradesBudgetLimits extends Command { @@ -39,9 +39,9 @@ class UpgradesBudgetLimits extends Command public const string CONFIG_NAME = '480_bl_currency'; - protected $description = 'Give budget limits a currency'; + protected $description = 'Give budget limits a currency'; - protected $signature = 'upgrade:480-budget-limit-currencies {--F|force : Force the execution of this command.}'; + protected $signature = 'upgrade:480-budget-limit-currencies {--F|force : Force the execution of this command.}'; /** * Execute the console command. @@ -68,12 +68,15 @@ class UpgradesBudgetLimits extends Command /** @var null|User $user */ $user = $budget->user; if (null !== $user) { - $currency = Amount::getPrimaryCurrencyByUserGroup($user->userGroup); + $currency = Amount::getPrimaryCurrencyByUserGroup($user->userGroup); $budgetLimit->transaction_currency_id = $currency->id; $budgetLimit->save(); - $this->friendlyInfo( - sprintf('Budget limit #%d (part of budget "%s") now has a currency setting (%s).', $budgetLimit->id, $budget->name, $currency->name) - ); + $this->friendlyInfo(sprintf( + 'Budget limit #%d (part of budget "%s") now has a currency setting (%s).', + $budgetLimit->id, + $budget->name, + $currency->name + )); ++$count; } } @@ -88,8 +91,7 @@ class UpgradesBudgetLimits extends Command { $configVar = FireflyConfig::get(self::CONFIG_NAME, false); - return (bool)$configVar?->data; - + return (bool) $configVar?->data; } private function markAsExecuted(): void diff --git a/app/Console/Commands/Upgrade/UpgradesCreditCardLiabilities.php b/app/Console/Commands/Upgrade/UpgradesCreditCardLiabilities.php index c7cf0a89e4..1d74564b6f 100644 --- a/app/Console/Commands/Upgrade/UpgradesCreditCardLiabilities.php +++ b/app/Console/Commands/Upgrade/UpgradesCreditCardLiabilities.php @@ -29,17 +29,18 @@ use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Account; use FireflyIII\Models\AccountType; +use FireflyIII\Support\Facades\FireflyConfig; use Illuminate\Console\Command; use Illuminate\Support\Collection; -use FireflyIII\Support\Facades\FireflyConfig; class UpgradesCreditCardLiabilities extends Command { use ShowsFriendlyMessages; public const string CONFIG_NAME = '480_cc_liabilities'; - protected $description = 'Convert old credit card liabilities.'; - protected $signature = 'upgrade:480-cc-liabilities {--F|force : Force the execution of this command.}'; + + protected $description = 'Convert old credit card liabilities.'; + protected $signature = 'upgrade:480-cc-liabilities {--F|force : Force the execution of this command.}'; /** * Execute the console command. diff --git a/app/Console/Commands/Upgrade/UpgradesCurrencyPreferences.php b/app/Console/Commands/Upgrade/UpgradesCurrencyPreferences.php index 465a18e7c7..4aaef02fea 100644 --- a/app/Console/Commands/Upgrade/UpgradesCurrencyPreferences.php +++ b/app/Console/Commands/Upgrade/UpgradesCurrencyPreferences.php @@ -30,10 +30,10 @@ use FireflyIII\Models\Preference; use FireflyIII\Models\TransactionCurrency; use FireflyIII\Models\UserGroup; use FireflyIII\Support\Facades\Amount; +use FireflyIII\Support\Facades\FireflyConfig; use FireflyIII\User; use Illuminate\Console\Command; use Illuminate\Support\Collection; -use FireflyIII\Support\Facades\FireflyConfig; class UpgradesCurrencyPreferences extends Command { @@ -41,9 +41,9 @@ class UpgradesCurrencyPreferences extends Command public const string CONFIG_NAME = '610_upgrade_currency_prefs'; - protected $description = 'Upgrade user currency preferences'; + protected $description = 'Upgrade user currency preferences'; - protected $signature = 'upgrade:610-currency-preferences {--F|force : Force the execution of this command.}'; + protected $signature = 'upgrade:610-currency-preferences {--F|force : Force the execution of this command.}'; /** * Execute the console command. @@ -68,8 +68,7 @@ class UpgradesCurrencyPreferences extends Command { $configVar = FireflyConfig::get(self::CONFIG_NAME, false); - return (bool)$configVar?->data; - + return (bool) $configVar?->data; } private function runUpgrade(): void @@ -81,7 +80,7 @@ class UpgradesCurrencyPreferences extends Command $this->upgradeGroupPreferences($group); } - $users = User::get(); + $users = User::get(); /** @var User $user */ foreach ($users as $user) { @@ -130,14 +129,16 @@ class UpgradesCurrencyPreferences extends Command private function getPreference(User $user): string { - $preference = Preference::where('user_id', $user->id)->where('name', 'currencyPreference')->first(['id', 'user_id', 'name', 'data', 'updated_at', 'created_at']); + $preference = Preference::where('user_id', $user->id) + ->where('name', 'currencyPreference') + ->first(['id', 'user_id', 'name', 'data', 'updated_at', 'created_at']); if (null === $preference) { return 'EUR'; } if (null !== $preference->data && !is_array($preference->data)) { - return (string)$preference->data; + return (string) $preference->data; } return 'EUR'; diff --git a/app/Console/Commands/Upgrade/UpgradesDatabase.php b/app/Console/Commands/Upgrade/UpgradesDatabase.php index 877232ee58..e9476c4322 100644 --- a/app/Console/Commands/Upgrade/UpgradesDatabase.php +++ b/app/Console/Commands/Upgrade/UpgradesDatabase.php @@ -76,7 +76,7 @@ class UpgradesDatabase extends Command 'upgrade:620-piggy-banks', 'upgrade:620-pc-amounts', 'upgrade:640-upgrade-webhooks', - 'firefly-iii:correct-database', + 'firefly-iii:correct-database' ]; $args = []; if ($this->option('force')) { @@ -94,7 +94,7 @@ class UpgradesDatabase extends Command private function callInitialCommands(): void { - $this->call('migrate', ['--seed' => true, '--force' => true, '--no-interaction' => true]); + $this->call('migrate', ['--seed' => true, '--force' => true, '--no-interaction' => true]); $this->call('upgrade:600-pgsql-sequences'); $this->call('upgrade:480-decrypt-all'); } diff --git a/app/Console/Commands/Upgrade/UpgradesJournalMetaData.php b/app/Console/Commands/Upgrade/UpgradesJournalMetaData.php index 4ee5d9f50b..3bf810cd00 100644 --- a/app/Console/Commands/Upgrade/UpgradesJournalMetaData.php +++ b/app/Console/Commands/Upgrade/UpgradesJournalMetaData.php @@ -29,10 +29,10 @@ use FireflyIII\Models\Budget; use FireflyIII\Models\Category; use FireflyIII\Models\Transaction; use FireflyIII\Models\TransactionJournal; +use FireflyIII\Support\Facades\FireflyConfig; use Illuminate\Console\Command; use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; -use FireflyIII\Support\Facades\FireflyConfig; class UpgradesJournalMetaData extends Command { @@ -40,9 +40,9 @@ class UpgradesJournalMetaData extends Command public const string CONFIG_NAME = '480_back_to_journals'; - protected $description = 'Move meta data back to journals, not individual transactions.'; + protected $description = 'Move meta data back to journals, not individual transactions.'; - protected $signature = 'upgrade:480-journal-meta-data {--F|force : Force the execution of this command.}'; + protected $signature = 'upgrade:480-journal-meta-data {--F|force : Force the execution of this command.}'; /** * Execute the console command. @@ -110,12 +110,18 @@ class UpgradesJournalMetaData extends Command private function getIdsForBudgets(): array { - $transactions = DB::table('budget_transaction')->distinct()->pluck('transaction_id')->toArray(); + $transactions = DB::table('budget_transaction') + ->distinct() + ->pluck('transaction_id') + ->toArray(); $array = []; $chunks = array_chunk($transactions, 500); foreach ($chunks as $chunk) { - $set = DB::table('transactions')->whereIn('transactions.id', $chunk)->pluck('transaction_journal_id')->toArray(); + $set = DB::table('transactions') + ->whereIn('transactions.id', $chunk) + ->pluck('transaction_journal_id') + ->toArray(); $array = array_merge($array, $set); } @@ -126,7 +132,7 @@ class UpgradesJournalMetaData extends Command { // grab category from first transaction /** @var null|Transaction $transaction */ - $transaction = $journal->transactions->first(); + $transaction = $journal->transactions->first(); if (null === $transaction) { $this->friendlyInfo(sprintf('Transaction journal #%d has no transactions. Will be fixed later.', $journal->id)); @@ -134,7 +140,7 @@ class UpgradesJournalMetaData extends Command } /** @var null|Budget $budget */ - $budget = $transaction->budgets->first(); + $budget = $transaction->budgets->first(); /** @var null|Budget $journalBudget */ $journalBudget = $journal->budgets->first(); @@ -159,7 +165,7 @@ class UpgradesJournalMetaData extends Command $journals = new Collection(); $allIds = $this->getIdsForCategories(); - $chunks = array_chunk($allIds, 500); + $chunks = array_chunk($allIds, 500); foreach ($chunks as $chunk) { $collected = TransactionJournal::whereIn('id', $chunk)->with(['transactions', 'categories', 'transactions.categories'])->get(); $journals = $journals->merge($collected); @@ -173,15 +179,18 @@ class UpgradesJournalMetaData extends Command private function getIdsForCategories(): array { - $transactions = DB::table('category_transaction')->distinct()->pluck('transaction_id')->toArray(); + $transactions = DB::table('category_transaction') + ->distinct() + ->pluck('transaction_id') + ->toArray(); $array = []; $chunks = array_chunk($transactions, 500); foreach ($chunks as $chunk) { $set = DB::table('transactions') ->whereIn('transactions.id', $chunk) - ->pluck('transaction_journal_id')->toArray() - ; + ->pluck('transaction_journal_id') + ->toArray(); $array = array_merge($array, $set); } @@ -192,7 +201,7 @@ class UpgradesJournalMetaData extends Command { // grab category from first transaction /** @var null|Transaction $transaction */ - $transaction = $journal->transactions->first(); + $transaction = $journal->transactions->first(); if (null === $transaction) { $this->friendlyInfo(sprintf('Transaction journal #%d has no transactions. Will be fixed later.', $journal->id)); @@ -200,7 +209,7 @@ class UpgradesJournalMetaData extends Command } /** @var null|Category $category */ - $category = $transaction->categories->first(); + $category = $transaction->categories->first(); /** @var null|Category $journalCategory */ $journalCategory = $journal->categories->first(); diff --git a/app/Console/Commands/Upgrade/UpgradesJournalNotes.php b/app/Console/Commands/Upgrade/UpgradesJournalNotes.php index 8302818752..fde7316d81 100644 --- a/app/Console/Commands/Upgrade/UpgradesJournalNotes.php +++ b/app/Console/Commands/Upgrade/UpgradesJournalNotes.php @@ -27,9 +27,9 @@ namespace FireflyIII\Console\Commands\Upgrade; use FireflyIII\Console\Commands\ShowsFriendlyMessages; use FireflyIII\Models\Note; use FireflyIII\Models\TransactionJournalMeta; +use FireflyIII\Support\Facades\FireflyConfig; use Illuminate\Console\Command; use Illuminate\Support\Facades\Log; -use FireflyIII\Support\Facades\FireflyConfig; class UpgradesJournalNotes extends Command { @@ -37,9 +37,9 @@ class UpgradesJournalNotes extends Command public const string CONFIG_NAME = '480_migrate_notes'; - protected $description = 'Migrate notes for transaction journals.'; + protected $description = 'Migrate notes for transaction journals.'; - protected $signature = 'upgrade:480-notes {--F|force : Force the execution of this command.}'; + protected $signature = 'upgrade:480-notes {--F|force : Force the execution of this command.}'; /** * Execute the console command. @@ -59,8 +59,8 @@ class UpgradesJournalNotes extends Command /** @var TransactionJournalMeta $meta */ foreach ($set as $meta) { - $journal = $meta->transactionJournal; - $note = $journal->notes()->first(); + $journal = $meta->transactionJournal; + $note = $journal->notes()->first(); if (null === $note) { $note = new Note(); $note->noteable()->associate($journal); @@ -78,7 +78,7 @@ class UpgradesJournalNotes extends Command $this->friendlyInfo(sprintf('Migrated %d note(s).', $count)); } - $end = round(microtime(true) - $start, 2); + $end = round(microtime(true) - $start, 2); $this->friendlyInfo(sprintf('Migrated notes in %s seconds.', $end)); $this->markAsExecuted(); @@ -89,8 +89,7 @@ class UpgradesJournalNotes extends Command { $configVar = FireflyConfig::get(self::CONFIG_NAME, false); - return (bool)$configVar?->data; - + return (bool) $configVar?->data; } private function markAsExecuted(): void diff --git a/app/Console/Commands/Upgrade/UpgradesLiabilities.php b/app/Console/Commands/Upgrade/UpgradesLiabilities.php index c5e811ea82..fd1b91307f 100644 --- a/app/Console/Commands/Upgrade/UpgradesLiabilities.php +++ b/app/Console/Commands/Upgrade/UpgradesLiabilities.php @@ -31,17 +31,18 @@ use FireflyIII\Models\Transaction; use FireflyIII\Models\TransactionJournal; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Services\Internal\Support\CreditRecalculateService; +use FireflyIII\Support\Facades\FireflyConfig; use FireflyIII\User; use Illuminate\Console\Command; -use FireflyIII\Support\Facades\FireflyConfig; class UpgradesLiabilities extends Command { use ShowsFriendlyMessages; public const string CONFIG_NAME = '560_upgrade_liabilities'; - protected $description = 'Upgrade liabilities to new 5.6.0 structure.'; - protected $signature = 'upgrade:560-liabilities {--F|force : Force the execution of this command.}'; + + protected $description = 'Upgrade liabilities to new 5.6.0 structure.'; + protected $signature = 'upgrade:560-liabilities {--F|force : Force the execution of this command.}'; /** * Execute the console command. @@ -64,8 +65,7 @@ class UpgradesLiabilities extends Command { $configVar = FireflyConfig::get(self::CONFIG_NAME, false); - return (bool)$configVar?->data; - + return (bool) $configVar?->data; } private function upgradeLiabilities(): void @@ -80,11 +80,11 @@ class UpgradesLiabilities extends Command private function upgradeForUser(User $user): void { - $accounts = $user->accounts() + $accounts = $user + ->accounts() ->leftJoin('account_types', 'account_types.id', '=', 'accounts.account_type_id') ->whereIn('account_types.type', config('firefly.valid_liabilities')) - ->get(['accounts.*']) - ; + ->get(['accounts.*']); /** @var Account $account */ foreach ($accounts as $account) { @@ -98,7 +98,7 @@ class UpgradesLiabilities extends Command private function upgradeLiability(Account $account): void { /** @var AccountRepositoryInterface $repository */ - $repository = app(AccountRepositoryInterface::class); + $repository = app(AccountRepositoryInterface::class); $repository->setUser($account->user); // get opening balance, and correct if necessary. @@ -109,7 +109,7 @@ class UpgradesLiabilities extends Command } // add liability direction property (if it does not yet exist!) - $value = $repository->getMetaValue($account, 'liability_direction'); + $value = $repository->getMetaValue($account, 'liability_direction'); if (null === $value) { /** @var AccountMetaFactory $factory */ $factory = app(AccountMetaFactory::class); @@ -127,21 +127,21 @@ class UpgradesLiabilities extends Command // source MUST be the liability. if ($destination->account_id === $account->id) { // so if not, switch things around: - $sourceAccountId = $source->account_id; - $source->account_id = $destination->account_id; + $sourceAccountId = $source->account_id; + $source->account_id = $destination->account_id; $destination->account_id = $sourceAccountId; $source->save(); $destination->save(); } } - private function getSourceTransaction(TransactionJournal $journal): ?Transaction + private function getSourceTransaction(TransactionJournal $journal): null|Transaction { /** @var null|Transaction */ return $journal->transactions()->where('amount', '<', 0)->first(); } - private function getDestinationTransaction(TransactionJournal $journal): ?Transaction + private function getDestinationTransaction(TransactionJournal $journal): null|Transaction { /** @var null|Transaction */ return $journal->transactions()->where('amount', '>', 0)->first(); diff --git a/app/Console/Commands/Upgrade/UpgradesLiabilitiesEight.php b/app/Console/Commands/Upgrade/UpgradesLiabilitiesEight.php index 65dc51b655..f3589195d5 100644 --- a/app/Console/Commands/Upgrade/UpgradesLiabilitiesEight.php +++ b/app/Console/Commands/Upgrade/UpgradesLiabilitiesEight.php @@ -33,18 +33,19 @@ use FireflyIII\Models\TransactionType; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Services\Internal\Destroy\TransactionGroupDestroyService; use FireflyIII\Services\Internal\Support\CreditRecalculateService; +use FireflyIII\Support\Facades\FireflyConfig; use FireflyIII\User; use Illuminate\Console\Command; use Illuminate\Support\Facades\Log; -use FireflyIII\Support\Facades\FireflyConfig; class UpgradesLiabilitiesEight extends Command { use ShowsFriendlyMessages; public const string CONFIG_NAME = '600_upgrade_liabilities'; - protected $description = 'Upgrade liabilities to new 6.0.0 structure.'; - protected $signature = 'upgrade:600-liabilities {--F|force : Force the execution of this command.}'; + + protected $description = 'Upgrade liabilities to new 6.0.0 structure.'; + protected $signature = 'upgrade:600-liabilities {--F|force : Force the execution of this command.}'; /** * Execute the console command. @@ -66,8 +67,7 @@ class UpgradesLiabilitiesEight extends Command { $configVar = FireflyConfig::get(self::CONFIG_NAME, false); - return (bool)$configVar?->data; - + return (bool) $configVar?->data; } private function upgradeLiabilities(): void @@ -82,11 +82,11 @@ class UpgradesLiabilitiesEight extends Command private function upgradeForUser(User $user): void { - $accounts = $user->accounts() + $accounts = $user + ->accounts() ->leftJoin('account_types', 'account_types.id', '=', 'accounts.account_type_id') ->whereIn('account_types.type', config('firefly.valid_liabilities')) - ->get(['accounts.*']) - ; + ->get(['accounts.*']); /** @var Account $account */ foreach ($accounts as $account) { @@ -103,7 +103,7 @@ class UpgradesLiabilitiesEight extends Command $repository = app(AccountRepositoryInterface::class); $repository->setUser($account->user); - $direction = $repository->getMetaValue($account, 'liability_direction'); + $direction = $repository->getMetaValue($account, 'liability_direction'); if ('credit' === $direction && $this->hasBadOpening($account)) { $this->deleteCreditTransaction($account); $this->reverseOpeningBalance($account); @@ -124,21 +124,19 @@ class UpgradesLiabilitiesEight extends Command $openingJournal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->where('transactions.account_id', $account->id) ->where('transaction_journals.transaction_type_id', $openingBalanceType->id) - ->first(['transaction_journals.*']) - ; + ->first(['transaction_journals.*']); if (null === $openingJournal) { return false; } - $liabilityJournal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') + $liabilityJournal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->where('transactions.account_id', $account->id) ->where('transaction_journals.transaction_type_id', $liabilityType->id) - ->first(['transaction_journals.*']) - ; + ->first(['transaction_journals.*']); if (null === $liabilityJournal) { return false; } - return (bool)$openingJournal->date->isSameDay($liabilityJournal->date); + return (bool) $openingJournal->date->isSameDay($liabilityJournal->date); } private function deleteCreditTransaction(Account $account): void @@ -147,13 +145,11 @@ class UpgradesLiabilitiesEight extends Command $liabilityJournal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->where('transactions.account_id', $account->id) ->where('transaction_journals.transaction_type_id', $liabilityType->id) - ->first(['transaction_journals.*']) - ; + ->first(['transaction_journals.*']); if (null !== $liabilityJournal && null !== $liabilityJournal->transactionGroup) { $group = $liabilityJournal->transactionGroup; $service = new TransactionGroupDestroyService(); $service->destroy($group); - } } @@ -162,21 +158,20 @@ class UpgradesLiabilitiesEight extends Command $openingBalanceType = TransactionType::whereType(TransactionTypeEnum::OPENING_BALANCE->value)->first(); /** @var TransactionJournal $openingJournal */ - $openingJournal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') + $openingJournal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->where('transactions.account_id', $account->id) ->where('transaction_journals.transaction_type_id', $openingBalanceType->id) - ->first(['transaction_journals.*']) - ; + ->first(['transaction_journals.*']); /** @var null|Transaction $source */ - $source = $openingJournal->transactions()->where('amount', '<', 0)->first(); + $source = $openingJournal->transactions()->where('amount', '<', 0)->first(); /** @var null|Transaction $dest */ - $dest = $openingJournal->transactions()->where('amount', '>', 0)->first(); + $dest = $openingJournal->transactions()->where('amount', '>', 0)->first(); if (null !== $source && null !== $dest) { - $sourceId = $source->account_id; - $destId = $dest->account_id; - $dest->account_id = $sourceId; + $sourceId = $source->account_id; + $destId = $dest->account_id; + $dest->account_id = $sourceId; $source->account_id = $destId; $source->save(); $dest->save(); @@ -189,11 +184,12 @@ class UpgradesLiabilitiesEight extends Command private function deleteTransactions(Account $account): int { $count = 0; - $journals = TransactionJournal::leftJoin('transactions', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') - ->where('transactions.account_id', $account->id)->get(['transaction_journals.*']) - ; + $journals = TransactionJournal::leftJoin('transactions', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')->where( + 'transactions.account_id', + $account->id + )->get(['transaction_journals.*']); - $service = app(TransactionGroupDestroyService::class); + $service = app(TransactionGroupDestroyService::class); /** @var TransactionJournal $journal */ foreach ($journals as $journal) { diff --git a/app/Console/Commands/Upgrade/UpgradesMultiPiggyBanks.php b/app/Console/Commands/Upgrade/UpgradesMultiPiggyBanks.php index e412c4a275..69d05194ab 100644 --- a/app/Console/Commands/Upgrade/UpgradesMultiPiggyBanks.php +++ b/app/Console/Commands/Upgrade/UpgradesMultiPiggyBanks.php @@ -1,6 +1,5 @@ data; - + return (bool) $configVar?->data; } private function upgradePiggyBanks(): void { - $this->repository = app(PiggyBankRepositoryInterface::class); + $this->repository = app(PiggyBankRepositoryInterface::class); $this->accountRepository = app(AccountRepositoryInterface::class); - $set = PiggyBank::whereNotNull('account_id')->get(); + $set = PiggyBank::whereNotNull('account_id')->get(); Log::debug(sprintf('Will update %d piggy banks(s).', $set->count())); /** @var PiggyBank $piggyBank */ @@ -95,8 +93,8 @@ class UpgradesMultiPiggyBanks extends Command } $this->repository->setUser($piggyBank->account->user); $this->accountRepository->setUser($piggyBank->account->user); - $repetition = $this->repository->getRepetition($piggyBank, true); - $currency = $this->accountRepository->getAccountCurrency($piggyBank->account) ?? Amount::getPrimaryCurrencyByUserGroup($piggyBank->account->user->userGroup); + $repetition = $this->repository->getRepetition($piggyBank, true); + $currency = $this->accountRepository->getAccountCurrency($piggyBank->account) ?? Amount::getPrimaryCurrencyByUserGroup($piggyBank->account->user->userGroup); // update piggy bank to have a currency. $piggyBank->transaction_currency_id = $currency->id; @@ -104,12 +102,11 @@ class UpgradesMultiPiggyBanks extends Command // store current amount in account association. $piggyBank->accounts()->sync([$piggyBank->account->id => ['current_amount' => $repetition->current_amount]]); - $piggyBank->account_id = null; + $piggyBank->account_id = null; $piggyBank->saveQuietly(); // remove all repetitions (no longer used) $piggyBank->piggyBankRepetitions()->delete(); - } private function markAsExecuted(): void diff --git a/app/Console/Commands/Upgrade/UpgradesPrimaryCurrencyAmounts.php b/app/Console/Commands/Upgrade/UpgradesPrimaryCurrencyAmounts.php index 6243e5f499..8c8283ff69 100644 --- a/app/Console/Commands/Upgrade/UpgradesPrimaryCurrencyAmounts.php +++ b/app/Console/Commands/Upgrade/UpgradesPrimaryCurrencyAmounts.php @@ -1,6 +1,5 @@ markAsExecuted(); - return 0; } @@ -63,8 +61,7 @@ class UpgradesPrimaryCurrencyAmounts extends Command { $configVar = FireflyConfig::get(self::CONFIG_NAME, false); - return (bool)$configVar?->data; - + return (bool) $configVar?->data; } private function markAsExecuted(): void diff --git a/app/Console/Commands/Upgrade/UpgradesRecurrenceMetaData.php b/app/Console/Commands/Upgrade/UpgradesRecurrenceMetaData.php index b063fd4ded..7bea6084c9 100644 --- a/app/Console/Commands/Upgrade/UpgradesRecurrenceMetaData.php +++ b/app/Console/Commands/Upgrade/UpgradesRecurrenceMetaData.php @@ -28,8 +28,8 @@ use FireflyIII\Console\Commands\ShowsFriendlyMessages; use FireflyIII\Models\Recurrence; use FireflyIII\Models\RecurrenceMeta; use FireflyIII\Models\RecurrenceTransactionMeta; -use Illuminate\Console\Command; use FireflyIII\Support\Facades\FireflyConfig; +use Illuminate\Console\Command; use function Safe\json_encode; @@ -39,9 +39,9 @@ class UpgradesRecurrenceMetaData extends Command public const string CONFIG_NAME = '481_migrate_recurrence_meta'; - protected $description = 'Migrate recurrence meta data'; + protected $description = 'Migrate recurrence meta data'; - protected $signature = 'upgrade:481-recurrence-meta {--F|force : Force the execution of this command.}'; + protected $signature = 'upgrade:481-recurrence-meta {--F|force : Force the execution of this command.}'; /** * Execute the console command. @@ -68,13 +68,12 @@ class UpgradesRecurrenceMetaData extends Command { $configVar = FireflyConfig::get(self::CONFIG_NAME, false); - return (bool)$configVar?->data; - + return (bool) $configVar?->data; } private function migrateMetaData(): int { - $count = 0; + $count = 0; // get all recurrence meta data: $collection = RecurrenceMeta::with('recurrence')->get(); @@ -89,7 +88,7 @@ class UpgradesRecurrenceMetaData extends Command private function migrateEntry(RecurrenceMeta $meta): int { /** @var null|Recurrence $recurrence */ - $recurrence = $meta->recurrence; + $recurrence = $meta->recurrence; if (null === $recurrence) { return 0; } @@ -97,20 +96,14 @@ class UpgradesRecurrenceMetaData extends Command if (null === $firstTransaction) { return 0; } - $value = $meta->value; + $value = $meta->value; if ('tags' === $meta->name) { $array = explode(',', $meta->value); $value = json_encode($array, JSON_THROW_ON_ERROR); } - RecurrenceTransactionMeta::create( - [ - 'rt_id' => $firstTransaction->id, - 'name' => $meta->name, - 'value' => $value, - ] - ); + RecurrenceTransactionMeta::create(['rt_id' => $firstTransaction->id, 'name' => $meta->name, 'value' => $value]); $meta->forceDelete(); return 1; diff --git a/app/Console/Commands/Upgrade/UpgradesRuleActions.php b/app/Console/Commands/Upgrade/UpgradesRuleActions.php index 54d6135a08..c5c7a7019c 100644 --- a/app/Console/Commands/Upgrade/UpgradesRuleActions.php +++ b/app/Console/Commands/Upgrade/UpgradesRuleActions.php @@ -1,6 +1,5 @@ data; - + return (bool) $configVar?->data; } private function replaceEqualSign(): void @@ -101,7 +99,7 @@ class UpgradesRuleActions extends Command 'append_descr_to_notes', 'append_notes_to_descr', 'move_descr_to_notes', - 'move_notes_to_descr', + 'move_notes_to_descr' ]; $actions = RuleAction::whereIn('action_type', $obsolete)->get(); @@ -116,7 +114,7 @@ class UpgradesRuleActions extends Command break; case 'append_description': - $action->action_type = 'set_description'; + $action->action_type = 'set_description'; $action->action_value = sprintf('=description~"%s"', str_replace('"', '\"', $action->action_value)); $action->save(); $this->friendlyInfo(sprintf('Upgraded action #%d from "%s" to "%s".', $action->id, $oldType, $action->action_type)); @@ -124,7 +122,7 @@ class UpgradesRuleActions extends Command break; case 'prepend_description': - $action->action_type = 'set_description'; + $action->action_type = 'set_description'; $action->action_value = sprintf('="%s"~description', str_replace('"', '\"', $action->action_value)); $action->save(); $this->friendlyInfo(sprintf('Upgraded action #%d from "%s" to "%s".', $action->id, $oldType, $action->action_type)); @@ -132,7 +130,7 @@ class UpgradesRuleActions extends Command break; case 'append_notes': - $action->action_type = 'set_notes'; + $action->action_type = 'set_notes'; $action->action_value = sprintf('=notes~"%s"', str_replace('"', '\"', $action->action_value)); $action->save(); $this->friendlyInfo(sprintf('Upgraded action #%d from "%s" to "%s".', $action->id, $oldType, $action->action_type)); @@ -140,7 +138,7 @@ class UpgradesRuleActions extends Command break; case 'prepend_notes': - $action->action_type = 'set_notes'; + $action->action_type = 'set_notes'; $action->action_value = sprintf('="%s"~notes', str_replace('"', '\"', $action->action_value)); $action->save(); $this->friendlyInfo(sprintf('Upgraded action #%d from "%s" to "%s".', $action->id, $oldType, $action->action_type)); @@ -148,7 +146,7 @@ class UpgradesRuleActions extends Command break; case 'append_descr_to_notes': - $action->action_type = 'set_notes'; + $action->action_type = 'set_notes'; $action->action_value = '=notes~" "~description'; $action->save(); $this->friendlyInfo(sprintf('Upgraded action #%d from "%s" to "%s".', $action->id, $oldType, $action->action_type)); @@ -156,7 +154,7 @@ class UpgradesRuleActions extends Command break; case 'append_notes_to_descr': - $action->action_type = 'set_description'; + $action->action_type = 'set_description'; $action->action_value = '=description~" "~notes'; $action->save(); $this->friendlyInfo(sprintf('Upgraded action #%d from "%s" to "%s".', $action->id, $oldType, $action->action_type)); @@ -164,7 +162,7 @@ class UpgradesRuleActions extends Command break; case 'move_descr_to_notes': - $action->action_type = 'set_notes'; + $action->action_type = 'set_notes'; $action->action_value = '=description'; $action->save(); $this->friendlyInfo(sprintf('Upgraded action #%d from "%s" to "%s".', $action->id, $oldType, $action->action_type)); @@ -172,7 +170,7 @@ class UpgradesRuleActions extends Command break; case 'move_notes_to_descr': - $action->action_type = 'set_description'; + $action->action_type = 'set_description'; $action->action_value = '=notes'; $action->save(); $this->friendlyInfo(sprintf('Upgraded action #%d from "%s" to "%s".', $action->id, $oldType, $action->action_type)); diff --git a/app/Console/Commands/Upgrade/UpgradesTagLocations.php b/app/Console/Commands/Upgrade/UpgradesTagLocations.php index 3756ec092f..94b49f4811 100644 --- a/app/Console/Commands/Upgrade/UpgradesTagLocations.php +++ b/app/Console/Commands/Upgrade/UpgradesTagLocations.php @@ -27,8 +27,8 @@ namespace FireflyIII\Console\Commands\Upgrade; use FireflyIII\Console\Commands\ShowsFriendlyMessages; use FireflyIII\Models\Location; use FireflyIII\Models\Tag; -use Illuminate\Console\Command; use FireflyIII\Support\Facades\FireflyConfig; +use Illuminate\Console\Command; class UpgradesTagLocations extends Command { @@ -36,9 +36,9 @@ class UpgradesTagLocations extends Command public const string CONFIG_NAME = '500_migrate_tag_locations'; - protected $description = 'Migrate tag locations.'; + protected $description = 'Migrate tag locations.'; - protected $signature = 'upgrade:500-tag-locations {--F|force : Force the execution of this command.}'; + protected $signature = 'upgrade:500-tag-locations {--F|force : Force the execution of this command.}'; /** * Execute the console command. @@ -60,8 +60,7 @@ class UpgradesTagLocations extends Command { $configVar = FireflyConfig::get(self::CONFIG_NAME, false); - return (bool)$configVar?->data; - + return (bool) $configVar?->data; } private function migrateTagLocations(): void @@ -83,16 +82,16 @@ class UpgradesTagLocations extends Command private function migrateLocationDetails(Tag $tag): void { - $location = new Location(); - $location->longitude = $tag->longitude; - $location->latitude = $tag->latitude; + $location = new Location(); + $location->longitude = $tag->longitude; + $location->latitude = $tag->latitude; $location->zoom_level = $tag->zoomLevel; $location->locatable()->associate($tag); $location->save(); - $tag->longitude = null; - $tag->latitude = null; - $tag->zoomLevel = null; + $tag->longitude = null; + $tag->latitude = null; + $tag->zoomLevel = null; $tag->save(); } diff --git a/app/Console/Commands/Upgrade/UpgradesToGroups.php b/app/Console/Commands/Upgrade/UpgradesToGroups.php index a3fd772afb..d8d9104cd1 100644 --- a/app/Console/Commands/Upgrade/UpgradesToGroups.php +++ b/app/Console/Commands/Upgrade/UpgradesToGroups.php @@ -35,24 +35,25 @@ use FireflyIII\Models\TransactionJournal; use FireflyIII\Repositories\Journal\JournalCLIRepositoryInterface; use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Services\Internal\Destroy\JournalDestroyService; +use FireflyIII\Support\Facades\FireflyConfig; use Illuminate\Console\Command; use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; -use FireflyIII\Support\Facades\FireflyConfig; class UpgradesToGroups extends Command { use ShowsFriendlyMessages; public const string CONFIG_NAME = '480_migrated_to_groups'; - protected $description = 'Migrates a pre-4.7.8 transaction structure to the 4.7.8+ transaction structure.'; - protected $signature = 'upgrade:480-migrate-to-groups {--F|force : Force the migration, even if it fired before.}'; + + protected $description = 'Migrates a pre-4.7.8 transaction structure to the 4.7.8+ transaction structure.'; + protected $signature = 'upgrade:480-migrate-to-groups {--F|force : Force the migration, even if it fired before.}'; private JournalCLIRepositoryInterface $cliRepository; - private int $count; - private TransactionGroupFactory $groupFactory; - private JournalRepositoryInterface $journalRepository; - private JournalDestroyService $service; + private int $count; + private TransactionGroupFactory $groupFactory; + private JournalRepositoryInterface $journalRepository; + private JournalDestroyService $service; /** * Execute the console command. @@ -89,19 +90,18 @@ class UpgradesToGroups extends Command */ private function stupidLaravel(): void { - $this->count = 0; + $this->count = 0; $this->journalRepository = app(JournalRepositoryInterface::class); - $this->service = app(JournalDestroyService::class); - $this->groupFactory = app(TransactionGroupFactory::class); - $this->cliRepository = app(JournalCLIRepositoryInterface::class); + $this->service = app(JournalDestroyService::class); + $this->groupFactory = app(TransactionGroupFactory::class); + $this->cliRepository = app(JournalCLIRepositoryInterface::class); } private function isMigrated(): bool { $configVar = FireflyConfig::get(self::CONFIG_NAME, false); - return (bool)$configVar?->data; - + return (bool) $configVar?->data; } /** @@ -140,7 +140,7 @@ class UpgradesToGroups extends Command $data = [ // mandatory fields. 'group_title' => $journal->description, - 'transactions' => [], + 'transactions' => [] ]; $destTransactions = $this->getDestinationTransactions($journal); @@ -151,7 +151,7 @@ class UpgradesToGroups extends Command $data['transactions'][] = $this->generateTransaction($journal, $transaction); } Log::debug(sprintf('Now calling transaction journal factory (%d transactions in array)', count($data['transactions']))); - $group = $this->groupFactory->create($data); + $group = $this->groupFactory->create($data); Log::debug('Done calling transaction journal factory'); // delete the old transaction journal. @@ -160,29 +160,23 @@ class UpgradesToGroups extends Command ++$this->count; // report on result: - Log::debug( - sprintf( - 'Migrated journal #%d into group #%d with these journals: #%s', - $journal->id, - $group->id, - implode(', #', $group->transactionJournals->pluck('id')->toArray()) - ) - ); - $this->friendlyInfo( - sprintf( - 'Migrated journal #%d into group #%d with these journals: #%s', - $journal->id, - $group->id, - implode(', #', $group->transactionJournals->pluck('id')->toArray()) - ) - ); + Log::debug(sprintf( + 'Migrated journal #%d into group #%d with these journals: #%s', + $journal->id, + $group->id, + implode(', #', $group->transactionJournals->pluck('id')->toArray()) + )); + $this->friendlyInfo(sprintf( + 'Migrated journal #%d into group #%d with these journals: #%s', + $journal->id, + $group->id, + implode(', #', $group->transactionJournals->pluck('id')->toArray()) + )); } private function getDestinationTransactions(TransactionJournal $journal): Collection { - return $journal->transactions->filter( - static fn (Transaction $transaction): bool => $transaction->amount > 0 - ); + return $journal->transactions->filter(static fn(Transaction $transaction): bool => $transaction->amount > 0); } /** @@ -191,16 +185,14 @@ class UpgradesToGroups extends Command private function generateTransaction(TransactionJournal $journal, Transaction $transaction): array { Log::debug(sprintf('Now going to add transaction #%d to the array.', $transaction->id)); - $opposingTr = $this->findOpposingTransaction($journal, $transaction); + $opposingTr = $this->findOpposingTransaction($journal, $transaction); if (!$opposingTr instanceof Transaction) { - $this->friendlyError( - sprintf( - 'Journal #%d has no opposing transaction for transaction #%d. Cannot upgrade this entry.', - $journal->id, - $transaction->id - ) - ); + $this->friendlyError(sprintf( + 'Journal #%d has no opposing transaction for transaction #%d. Cannot upgrade this entry.', + $journal->id, + $transaction->id + )); return []; } @@ -232,8 +224,8 @@ class UpgradesToGroups extends Command $invoiceDate = $this->cliRepository->getMetaDate($journal, 'invoice_date'); // overrule journal category with transaction category. - $budgetId = $this->getTransactionBudget($transaction, $opposingTr) ?? $budgetId; - $categoryId = $this->getTransactionCategory($transaction, $opposingTr) ?? $categoryId; + $budgetId = $this->getTransactionBudget($transaction, $opposingTr) ?? $budgetId; + $categoryId = $this->getTransactionCategory($transaction, $opposingTr) ?? $categoryId; return [ 'type' => strtolower((string) $journal->transactionType->type), @@ -272,27 +264,25 @@ class UpgradesToGroups extends Command 'process_date' => $processDate, 'due_date' => $dueDate, 'payment_date' => $paymentDate, - 'invoice_date' => $invoiceDate, + 'invoice_date' => $invoiceDate ]; } - private function findOpposingTransaction(TransactionJournal $journal, Transaction $transaction): ?Transaction + private function findOpposingTransaction(TransactionJournal $journal, Transaction $transaction): null|Transaction { - $set = $journal->transactions->filter( - static function (Transaction $subject) use ($transaction): bool { - $amount = (float) $transaction->amount * -1 === (float) $subject->amount; // intentional float - $identifier = $transaction->identifier === $subject->identifier; - Log::debug(sprintf('Amount the same? %s', var_export($amount, true))); - Log::debug(sprintf('ID the same? %s', var_export($identifier, true))); + $set = $journal->transactions->filter(static function (Transaction $subject) use ($transaction): bool { + $amount = ((float) $transaction->amount * -1) === (float) $subject->amount; // intentional float + $identifier = $transaction->identifier === $subject->identifier; + Log::debug(sprintf('Amount the same? %s', var_export($amount, true))); + Log::debug(sprintf('ID the same? %s', var_export($identifier, true))); - return $amount && $identifier; - } - ); + return $amount && $identifier; + }); return $set->first(); } - private function getTransactionBudget(Transaction $left, Transaction $right): ?int + private function getTransactionBudget(Transaction $left, Transaction $right): null|int { Log::debug('Now in getTransactionBudget()'); @@ -319,7 +309,7 @@ class UpgradesToGroups extends Command return null; } - private function getTransactionCategory(Transaction $left, Transaction $right): ?int + private function getTransactionCategory(Transaction $left, Transaction $right): null|int { Log::debug('Now in getTransactionCategory()'); @@ -366,14 +356,12 @@ class UpgradesToGroups extends Command private function giveGroup(array $array): void { - $groupId = DB::table('transaction_groups')->insertGetId( - [ - 'created_at' => Carbon::now()->format('Y-m-d H:i:s'), - 'updated_at' => Carbon::now()->format('Y-m-d H:i:s'), - 'title' => null, - 'user_id' => $array['user_id'], - ] - ); + $groupId = DB::table('transaction_groups')->insertGetId([ + 'created_at' => Carbon::now()->format('Y-m-d H:i:s'), + 'updated_at' => Carbon::now()->format('Y-m-d H:i:s'), + 'title' => null, + 'user_id' => $array['user_id'] + ]); DB::table('transaction_journals')->where('id', $array['id'])->update(['transaction_group_id' => $groupId]); ++$this->count; } diff --git a/app/Console/Commands/Upgrade/UpgradesTransferCurrencies.php b/app/Console/Commands/Upgrade/UpgradesTransferCurrencies.php index 1fbd7dbafb..b0943475cf 100644 --- a/app/Console/Commands/Upgrade/UpgradesTransferCurrencies.php +++ b/app/Console/Commands/Upgrade/UpgradesTransferCurrencies.php @@ -32,28 +32,29 @@ use FireflyIII\Models\TransactionCurrency; use FireflyIII\Models\TransactionJournal; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Journal\JournalCLIRepositoryInterface; +use FireflyIII\Support\Facades\FireflyConfig; use Illuminate\Console\Command; use Illuminate\Support\Facades\Log; -use FireflyIII\Support\Facades\FireflyConfig; class UpgradesTransferCurrencies extends Command { use ShowsFriendlyMessages; - public const string CONFIG_NAME = '480_transfer_currencies'; - protected $description = 'Updates transfer currency information.'; - protected $signature = 'upgrade:480-transfer-currencies {--F|force : Force the execution of this command.}'; - private array $accountCurrencies; - private AccountRepositoryInterface $accountRepos; - private JournalCLIRepositoryInterface $cliRepos; - private int $count; + public const string CONFIG_NAME = '480_transfer_currencies'; - private ?Account $destinationAccount = null; - private ?TransactionCurrency $destinationCurrency = null; - private ?Transaction $destinationTransaction = null; - private ?Account $sourceAccount = null; - private ?TransactionCurrency $sourceCurrency = null; - private ?Transaction $sourceTransaction = null; + protected $description = 'Updates transfer currency information.'; + protected $signature = 'upgrade:480-transfer-currencies {--F|force : Force the execution of this command.}'; + private array $accountCurrencies; + private AccountRepositoryInterface $accountRepos; + private JournalCLIRepositoryInterface $cliRepos; + private int $count; + + private null|Account $destinationAccount = null; + private null|TransactionCurrency $destinationCurrency = null; + private null|Transaction $destinationTransaction = null; + private null|Account $sourceAccount = null; + private null|TransactionCurrency $sourceCurrency = null; + private null|Transaction $sourceTransaction = null; /** * Execute the console command. @@ -84,9 +85,9 @@ class UpgradesTransferCurrencies extends Command */ private function stupidLaravel(): void { - $this->count = 0; - $this->accountRepos = app(AccountRepositoryInterface::class); - $this->cliRepos = app(JournalCLIRepositoryInterface::class); + $this->count = 0; + $this->accountRepos = app(AccountRepositoryInterface::class); + $this->cliRepos = app(JournalCLIRepositoryInterface::class); $this->accountCurrencies = []; $this->resetInformation(); } @@ -96,20 +97,19 @@ class UpgradesTransferCurrencies extends Command */ private function resetInformation(): void { - $this->sourceTransaction = null; - $this->sourceAccount = null; - $this->sourceCurrency = null; + $this->sourceTransaction = null; + $this->sourceAccount = null; + $this->sourceCurrency = null; $this->destinationTransaction = null; - $this->destinationAccount = null; - $this->destinationCurrency = null; + $this->destinationAccount = null; + $this->destinationCurrency = null; } private function isExecuted(): bool { $configVar = FireflyConfig::get(self::CONFIG_NAME, false); - return (bool)$configVar?->data; - + return (bool) $configVar?->data; } /** @@ -154,9 +154,10 @@ class UpgradesTransferCurrencies extends Command // both accounts must have currency preference: if ($this->isNoCurrencyPresent()) { - $this->friendlyError( - sprintf('Source or destination accounts for transaction journal #%d have no currency information. Cannot fix this one.', $transfer->id) - ); + $this->friendlyError(sprintf( + 'Source or destination accounts for transaction journal #%d have no currency information. Cannot fix this one.', + $transfer->id + )); return; } @@ -201,26 +202,26 @@ class UpgradesTransferCurrencies extends Command private function getSourceInformation(TransactionJournal $journal): void { $this->sourceTransaction = $this->getSourceTransaction($journal); - $this->sourceAccount = $this->sourceTransaction?->account; - $this->sourceCurrency = $this->sourceAccount instanceof Account ? $this->getCurrency($this->sourceAccount) : null; + $this->sourceAccount = $this->sourceTransaction?->account; + $this->sourceCurrency = $this->sourceAccount instanceof Account ? $this->getCurrency($this->sourceAccount) : null; } - private function getSourceTransaction(TransactionJournal $transfer): ?Transaction + private function getSourceTransaction(TransactionJournal $transfer): null|Transaction { /** @var null|Transaction */ return $transfer->transactions()->where('amount', '<', 0)->first(); } - private function getCurrency(Account $account): ?TransactionCurrency + private function getCurrency(Account $account): null|TransactionCurrency { - $accountId = $account->id; + $accountId = $account->id; if (array_key_exists($accountId, $this->accountCurrencies) && 0 === $this->accountCurrencies[$accountId]) { return null; } if (array_key_exists($accountId, $this->accountCurrencies) && $this->accountCurrencies[$accountId] instanceof TransactionCurrency) { return $this->accountCurrencies[$accountId]; } - $currency = $this->accountRepos->getAccountCurrency($account); + $currency = $this->accountRepos->getAccountCurrency($account); if (!$currency instanceof TransactionCurrency) { $this->accountCurrencies[$accountId] = 0; @@ -237,11 +238,11 @@ class UpgradesTransferCurrencies extends Command private function getDestinationInformation(TransactionJournal $journal): void { $this->destinationTransaction = $this->getDestinationTransaction($journal); - $this->destinationAccount = $this->destinationTransaction?->account; - $this->destinationCurrency = $this->destinationAccount instanceof Account ? $this->getCurrency($this->destinationAccount) : null; + $this->destinationAccount = $this->destinationTransaction?->account; + $this->destinationCurrency = $this->destinationAccount instanceof Account ? $this->getCurrency($this->destinationAccount) : null; } - private function getDestinationTransaction(TransactionJournal $transfer): ?Transaction + private function getDestinationTransaction(TransactionJournal $transfer): null|Transaction { /** @var null|Transaction */ return $transfer->transactions()->where('amount', '>', 0)->first(); @@ -252,9 +253,12 @@ class UpgradesTransferCurrencies extends Command */ private function isEmptyTransactions(): bool { - return !$this->sourceTransaction instanceof Transaction || !$this->destinationTransaction instanceof Transaction - || !$this->sourceAccount instanceof Account - || !$this->destinationAccount instanceof Account; + return ( + !$this->sourceTransaction instanceof Transaction + || !$this->destinationTransaction instanceof Transaction + || !$this->sourceAccount instanceof Account + || !$this->destinationAccount instanceof Account + ); } private function isNoCurrencyPresent(): bool @@ -291,15 +295,8 @@ class UpgradesTransferCurrencies extends Command private function fixSourceNoCurrency(): void { if (null === $this->sourceTransaction->transaction_currency_id && $this->sourceCurrency instanceof TransactionCurrency) { - $this->sourceTransaction - ->transaction_currency_id - = $this->sourceCurrency->id - ; - $message = sprintf( - 'Transaction #%d has no currency setting, now set to %s.', - $this->sourceTransaction->id, - $this->sourceCurrency->code - ); + $this->sourceTransaction->transaction_currency_id = $this->sourceCurrency->id; + $message = sprintf('Transaction #%d has no currency setting, now set to %s.', $this->sourceTransaction->id, $this->sourceCurrency->code); $this->friendlyInfo($message); ++$this->count; $this->sourceTransaction->save(); @@ -312,11 +309,12 @@ class UpgradesTransferCurrencies extends Command */ private function fixSourceUnmatchedCurrency(): void { - if ($this->sourceCurrency instanceof TransactionCurrency + if ( + $this->sourceCurrency instanceof TransactionCurrency && null === $this->sourceTransaction->foreign_amount && (int) $this->sourceTransaction->transaction_currency_id !== $this->sourceCurrency->id ) { - $message = sprintf( + $message = sprintf( 'Transaction #%d has a currency setting #%d that should be #%d. Amount remains %s, currency is changed.', $this->sourceTransaction->id, $this->sourceTransaction->transaction_currency_id, @@ -337,15 +335,8 @@ class UpgradesTransferCurrencies extends Command private function fixDestNoCurrency(): void { if (null === $this->destinationTransaction->transaction_currency_id && $this->destinationCurrency instanceof TransactionCurrency) { - $this->destinationTransaction - ->transaction_currency_id - = $this->destinationCurrency->id - ; - $message = sprintf( - 'Transaction #%d has no currency setting, now set to %s.', - $this->destinationTransaction->id, - $this->destinationCurrency->code - ); + $this->destinationTransaction->transaction_currency_id = $this->destinationCurrency->id; + $message = sprintf('Transaction #%d has no currency setting, now set to %s.', $this->destinationTransaction->id, $this->destinationCurrency->code); $this->friendlyInfo($message); ++$this->count; $this->destinationTransaction->save(); @@ -358,11 +349,12 @@ class UpgradesTransferCurrencies extends Command */ private function fixDestinationUnmatchedCurrency(): void { - if ($this->destinationCurrency instanceof TransactionCurrency + if ( + $this->destinationCurrency instanceof TransactionCurrency && null === $this->destinationTransaction->foreign_amount && (int) $this->destinationTransaction->transaction_currency_id !== $this->destinationCurrency->id ) { - $message = sprintf( + $message = sprintf( 'Transaction #%d has a currency setting #%d that should be #%d. Amount remains %s, currency is changed.', $this->destinationTransaction->id, $this->destinationTransaction->transaction_currency_id, @@ -385,10 +377,10 @@ class UpgradesTransferCurrencies extends Command { if ($this->destinationCurrency->id === $this->sourceCurrency->id) { // update both transactions to match: - $this->sourceTransaction->foreign_amount = null; - $this->sourceTransaction->foreign_currency_id = null; + $this->sourceTransaction->foreign_amount = null; + $this->sourceTransaction->foreign_currency_id = null; - $this->destinationTransaction->foreign_amount = null; + $this->destinationTransaction->foreign_amount = null; $this->destinationTransaction->foreign_currency_id = null; $this->sourceTransaction->save(); @@ -404,17 +396,19 @@ class UpgradesTransferCurrencies extends Command private function fixMismatchedForeignCurrency(): void { if ($this->sourceCurrency->id !== $this->destinationCurrency->id) { - $this->sourceTransaction->transaction_currency_id = $this->sourceCurrency->id; - $this->sourceTransaction->foreign_currency_id = $this->destinationCurrency->id; + $this->sourceTransaction->transaction_currency_id = $this->sourceCurrency->id; + $this->sourceTransaction->foreign_currency_id = $this->destinationCurrency->id; $this->destinationTransaction->transaction_currency_id = $this->sourceCurrency->id; - $this->destinationTransaction->foreign_currency_id = $this->destinationCurrency->id; + $this->destinationTransaction->foreign_currency_id = $this->destinationCurrency->id; $this->sourceTransaction->save(); $this->destinationTransaction->save(); ++$this->count; - $this->friendlyInfo( - sprintf('Verified foreign currency ID of transaction #%d and #%d', $this->sourceTransaction->id, $this->destinationTransaction->id) - ); + $this->friendlyInfo(sprintf( + 'Verified foreign currency ID of transaction #%d and #%d', + $this->sourceTransaction->id, + $this->destinationTransaction->id + )); } } @@ -428,13 +422,11 @@ class UpgradesTransferCurrencies extends Command $this->sourceTransaction->foreign_amount = bcmul($this->destinationTransaction->foreign_amount, '-1'); $this->sourceTransaction->save(); ++$this->count; - $this->friendlyInfo( - sprintf( - 'Restored foreign amount of source transaction #%d to %s', - $this->sourceTransaction->id, - $this->sourceTransaction->foreign_amount - ) - ); + $this->friendlyInfo(sprintf( + 'Restored foreign amount of source transaction #%d to %s', + $this->sourceTransaction->id, + $this->sourceTransaction->foreign_amount + )); } } @@ -448,13 +440,11 @@ class UpgradesTransferCurrencies extends Command $this->destinationTransaction->foreign_amount = bcmul($this->sourceTransaction->foreign_amount, '-1'); $this->destinationTransaction->save(); ++$this->count; - $this->friendlyInfo( - sprintf( - 'Restored foreign amount of destination transaction #%d to %s', - $this->destinationTransaction->id, - $this->destinationTransaction->foreign_amount - ) - ); + $this->friendlyInfo(sprintf( + 'Restored foreign amount of destination transaction #%d to %s', + $this->destinationTransaction->id, + $this->destinationTransaction->foreign_amount + )); } } @@ -464,9 +454,9 @@ class UpgradesTransferCurrencies extends Command private function fixTransactionJournalCurrency(TransactionJournal $journal): void { if ((int) $journal->transaction_currency_id !== $this->sourceCurrency->id) { - $oldCurrencyCode = $journal->transactionCurrency->code ?? '(nothing)'; + $oldCurrencyCode = $journal->transactionCurrency->code ?? '(nothing)'; $journal->transaction_currency_id = $this->sourceCurrency->id; - $message = sprintf( + $message = sprintf( 'Transfer #%d ("%s") has been updated to use %s instead of %s.', $journal->id, $journal->description, diff --git a/app/Console/Commands/Upgrade/UpgradesVariousCurrencyInformation.php b/app/Console/Commands/Upgrade/UpgradesVariousCurrencyInformation.php index 6b72e47e6b..95647b23fd 100644 --- a/app/Console/Commands/Upgrade/UpgradesVariousCurrencyInformation.php +++ b/app/Console/Commands/Upgrade/UpgradesVariousCurrencyInformation.php @@ -34,21 +34,22 @@ use FireflyIII\Models\TransactionJournal; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Journal\JournalCLIRepositoryInterface; use FireflyIII\Repositories\Journal\JournalRepositoryInterface; -use Illuminate\Console\Command; use FireflyIII\Support\Facades\FireflyConfig; +use Illuminate\Console\Command; class UpgradesVariousCurrencyInformation extends Command { use ShowsFriendlyMessages; public const string CONFIG_NAME = '480_other_currencies'; - protected $description = 'Update all journal currency information.'; - protected $signature = 'upgrade:480-currency-information {--F|force : Force the execution of this command.}'; - private array $accountCurrencies; - private AccountRepositoryInterface $accountRepos; + + protected $description = 'Update all journal currency information.'; + protected $signature = 'upgrade:480-currency-information {--F|force : Force the execution of this command.}'; + private array $accountCurrencies; + private AccountRepositoryInterface $accountRepos; private JournalCLIRepositoryInterface $cliRepos; - private int $count; - private JournalRepositoryInterface $journalRepos; + private int $count; + private JournalRepositoryInterface $journalRepos; /** * Execute the console command. @@ -78,19 +79,18 @@ class UpgradesVariousCurrencyInformation extends Command */ private function stupidLaravel(): void { - $this->count = 0; + $this->count = 0; $this->accountCurrencies = []; - $this->accountRepos = app(AccountRepositoryInterface::class); - $this->journalRepos = app(JournalRepositoryInterface::class); - $this->cliRepos = app(JournalCLIRepositoryInterface::class); + $this->accountRepos = app(AccountRepositoryInterface::class); + $this->journalRepos = app(JournalRepositoryInterface::class); + $this->cliRepos = app(JournalCLIRepositoryInterface::class); } private function isExecuted(): bool { $configVar = FireflyConfig::get(self::CONFIG_NAME, false); - return (bool)$configVar?->data; - + return (bool) $configVar?->data; } /** @@ -101,9 +101,12 @@ class UpgradesVariousCurrencyInformation extends Command */ private function updateOtherJournalsCurrencies(): void { - $set = $this->cliRepos->getAllJournals( - [TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::OPENING_BALANCE->value, TransactionTypeEnum::RECONCILIATION->value] - ); + $set = $this->cliRepos->getAllJournals([ + TransactionTypeEnum::WITHDRAWAL->value, + TransactionTypeEnum::DEPOSIT->value, + TransactionTypeEnum::OPENING_BALANCE->value, + TransactionTypeEnum::RECONCILIATION->value + ]); /** @var TransactionJournal $journal */ foreach ($set as $journal) { @@ -129,35 +132,31 @@ class UpgradesVariousCurrencyInformation extends Command $currency = $this->getCurrency($account); $isMultiCurrency = $this->isMultiCurrency($account); if (!$currency instanceof TransactionCurrency) { - $this->friendlyError( - sprintf( - 'Account #%d ("%s") has no currency preference, so transaction journal #%d can\'t be corrected', - $account->id, - $account->name, - $journal->id - ) - ); + $this->friendlyError(sprintf( + 'Account #%d ("%s") has no currency preference, so transaction journal #%d can\'t be corrected', + $account->id, + $account->name, + $journal->id + )); ++$this->count; return; } // fix each transaction: - $journal->transactions->each( - static function (Transaction $transaction) use ($currency, $isMultiCurrency): void { - if (null === $transaction->transaction_currency_id) { - $transaction->transaction_currency_id = $currency->id; - $transaction->save(); - } - - // when mismatch in transaction: - if ($transaction->transaction_currency_id !== $currency->id && !$isMultiCurrency) { - $transaction->foreign_currency_id = $transaction->transaction_currency_id; - $transaction->foreign_amount = $transaction->amount; - $transaction->transaction_currency_id = $currency->id; - $transaction->save(); - } + $journal->transactions->each(static function (Transaction $transaction) use ($currency, $isMultiCurrency): void { + if (null === $transaction->transaction_currency_id) { + $transaction->transaction_currency_id = $currency->id; + $transaction->save(); } - ); + + // when mismatch in transaction: + if ($transaction->transaction_currency_id !== $currency->id && !$isMultiCurrency) { + $transaction->foreign_currency_id = $transaction->transaction_currency_id; + $transaction->foreign_amount = $transaction->amount; + $transaction->transaction_currency_id = $currency->id; + $transaction->save(); + } + }); // also update the journal, of course: if (!$isMultiCurrency) { $journal->transaction_currency_id = $currency->id; @@ -170,7 +169,7 @@ class UpgradesVariousCurrencyInformation extends Command * Gets the transaction that determines the transaction that "leads" and will determine * the currency to be used by all transactions, and the journal itself. */ - private function getLeadTransaction(TransactionJournal $journal): ?Transaction + private function getLeadTransaction(TransactionJournal $journal): null|Transaction { /** @var null|Transaction $lead */ $lead = null; @@ -191,23 +190,23 @@ class UpgradesVariousCurrencyInformation extends Command case TransactionTypeEnum::OPENING_BALANCE->value: // whichever isn't an initial balance account: - $lead = $journal->transactions()->leftJoin('accounts', 'transactions.account_id', '=', 'accounts.id')->leftJoin( - 'account_types', - 'accounts.account_type_id', - '=', - 'account_types.id' - )->where('account_types.type', '!=', AccountTypeEnum::INITIAL_BALANCE->value)->first(['transactions.*']); + $lead = $journal + ->transactions() + ->leftJoin('accounts', 'transactions.account_id', '=', 'accounts.id') + ->leftJoin('account_types', 'accounts.account_type_id', '=', 'account_types.id') + ->where('account_types.type', '!=', AccountTypeEnum::INITIAL_BALANCE->value) + ->first(['transactions.*']); break; case TransactionTypeEnum::RECONCILIATION->value: // whichever isn't the reconciliation account: - $lead = $journal->transactions()->leftJoin('accounts', 'transactions.account_id', '=', 'accounts.id')->leftJoin( - 'account_types', - 'accounts.account_type_id', - '=', - 'account_types.id' - )->where('account_types.type', '!=', AccountTypeEnum::RECONCILIATION->value)->first(['transactions.*']); + $lead = $journal + ->transactions() + ->leftJoin('accounts', 'transactions.account_id', '=', 'accounts.id') + ->leftJoin('account_types', 'accounts.account_type_id', '=', 'account_types.id') + ->where('account_types.type', '!=', AccountTypeEnum::RECONCILIATION->value) + ->first(['transactions.*']); break; } @@ -215,16 +214,16 @@ class UpgradesVariousCurrencyInformation extends Command return $lead; } - private function getCurrency(Account $account): ?TransactionCurrency + private function getCurrency(Account $account): null|TransactionCurrency { - $accountId = $account->id; + $accountId = $account->id; if (array_key_exists($accountId, $this->accountCurrencies) && 0 === $this->accountCurrencies[$accountId]) { return null; } if (array_key_exists($accountId, $this->accountCurrencies) && $this->accountCurrencies[$accountId] instanceof TransactionCurrency) { return $this->accountCurrencies[$accountId]; } - $currency = $this->accountRepos->getAccountCurrency($account); + $currency = $this->accountRepos->getAccountCurrency($account); if (!$currency instanceof TransactionCurrency) { $this->accountCurrencies[$accountId] = 0; diff --git a/app/Console/Commands/Upgrade/UpgradesWebhooks.php b/app/Console/Commands/Upgrade/UpgradesWebhooks.php index 826aaa9be9..5cddf0e8b4 100644 --- a/app/Console/Commands/Upgrade/UpgradesWebhooks.php +++ b/app/Console/Commands/Upgrade/UpgradesWebhooks.php @@ -1,6 +1,5 @@ data; - + return (bool) $configVar?->data; } private function upgradeWebhooks(): void { - $set = Webhook::where('delivery', '>', 1)->orWhere('trigger', '>', 1)->orWhere('response', '>', 1)->get(); + $set = Webhook::where('delivery', '>', 1) + ->orWhere('trigger', '>', 1) + ->orWhere('response', '>', 1) + ->get(); /** @var Webhook $webhook */ foreach ($set as $webhook) { @@ -82,17 +84,17 @@ class UpgradesWebhooks extends Command private function upgradeWebhook(Webhook $webhook): void { - $delivery = WebhookDelivery::tryFrom((int)$webhook->delivery); - $response = WebhookResponse::tryFrom((int)$webhook->response); - $trigger = WebhookTrigger::tryFrom((int)$webhook->trigger); + $delivery = WebhookDelivery::tryFrom((int) $webhook->delivery); + $response = WebhookResponse::tryFrom((int) $webhook->response); + $trigger = WebhookTrigger::tryFrom((int) $webhook->trigger); if (in_array(null, [$delivery, $response, $trigger], true)) { $this->friendlyError(sprintf('[a] Webhook #%d has an invalid delivery, response or trigger value. Will not upgrade.', $webhook->id)); return; } - $deliveryModel = WebhookDeliveryModel::where('key', $delivery->value)->first(); - $responseModel = WebhookResponseModel::where('key', $response->value)->first(); - $triggerModel = WebhookTriggerModel::where('key', $trigger->value)->first(); + $deliveryModel = WebhookDeliveryModel::where('key', $delivery->value)->first(); + $responseModel = WebhookResponseModel::where('key', $response->value)->first(); + $triggerModel = WebhookTriggerModel::where('key', $trigger->value)->first(); if (in_array(null, [$deliveryModel, $responseModel, $triggerModel], true)) { $this->friendlyError(sprintf('[b] Webhook #%d has an invalid delivery, response or trigger model. Will not upgrade.', $webhook->id)); @@ -103,7 +105,7 @@ class UpgradesWebhooks extends Command $webhook->webhookTriggers()->attach([$triggerModel->id]); $webhook->delivery = 1; $webhook->response = 1; - $webhook->trigger = 1; + $webhook->trigger = 1; $webhook->save(); $this->friendlyPositive(sprintf('Webhook #%d upgraded.', $webhook->id)); } diff --git a/app/Console/Commands/VerifiesAccessToken.php b/app/Console/Commands/VerifiesAccessToken.php index 3726eb6a36..5c11ef0434 100644 --- a/app/Console/Commands/VerifiesAccessToken.php +++ b/app/Console/Commands/VerifiesAccessToken.php @@ -42,7 +42,7 @@ trait VerifiesAccessToken */ public function getUser(): User { - $userId = (int) $this->option('user'); + $userId = (int) $this->option('user'); /** @var UserRepositoryInterface $repository */ $repository = app(UserRepositoryInterface::class); @@ -68,12 +68,12 @@ trait VerifiesAccessToken */ protected function verifyAccessToken(): bool { - $userId = (int) $this->option('user'); - $token = (string) $this->option('token'); + $userId = (int) $this->option('user'); + $token = (string) $this->option('token'); /** @var UserRepositoryInterface $repository */ - $repository = app(UserRepositoryInterface::class); - $user = $repository->find($userId); + $repository = app(UserRepositoryInterface::class); + $user = $repository->find($userId); if (null === $user) { Log::error(sprintf('verifyAccessToken(): no such user for input "%d"', $userId)); diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index 071cdb65ca..82e28c88eb 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -40,7 +40,7 @@ class Kernel extends ConsoleKernel #[Override] protected function commands(): void { - $this->load(__DIR__.'/Commands'); + $this->load(__DIR__ . '/Commands'); require base_path('routes/console.php'); } @@ -51,23 +51,19 @@ class Kernel extends ConsoleKernel #[Override] protected function schedule(Schedule $schedule): void { - $schedule->call( - static function (): void { - Log::error( - 'Firefly III no longer users the Laravel scheduler to do cron jobs! Please read the instructions at https://docs.firefly-iii.org/' - ); - echo "\n"; - echo '------------'; - echo "\n"; - echo wordwrap('Firefly III no longer users the Laravel scheduler to do cron jobs! Please read the instructions here:'); - echo "\n"; - echo 'https://docs.firefly-iii.org/'; - echo "\n\n"; - echo 'Disable this cron job!'; - echo "\n"; - echo '------------'; - echo "\n"; - } - )->daily(); + $schedule->call(static function (): void { + Log::error('Firefly III no longer users the Laravel scheduler to do cron jobs! Please read the instructions at https://docs.firefly-iii.org/'); + echo "\n"; + echo '------------'; + echo "\n"; + echo wordwrap('Firefly III no longer users the Laravel scheduler to do cron jobs! Please read the instructions here:'); + echo "\n"; + echo 'https://docs.firefly-iii.org/'; + echo "\n\n"; + echo 'Disable this cron job!'; + echo "\n"; + echo '------------'; + echo "\n"; + })->daily(); } } diff --git a/app/Entities/AccountBalance.php b/app/Entities/AccountBalance.php index b7e6247126..cbc31fbd08 100644 --- a/app/Entities/AccountBalance.php +++ b/app/Entities/AccountBalance.php @@ -34,10 +34,10 @@ class AccountBalance public static function fromArray(): self { - $balance = new self(); - $balance->id = (string) random_int(1, 1000); + $balance = new self(); + $balance->id = (string) random_int(1, 1000); // $balance->name = (string) random_int(1, 1000); - $balance->amount = (string) random_int(1, 1000); + $balance->amount = (string) random_int(1, 1000); $balance->currencyId = '1'; return $balance; diff --git a/app/Enums/UserRoleEnum.php b/app/Enums/UserRoleEnum.php index 8df1fcf9af..70503f74c1 100644 --- a/app/Enums/UserRoleEnum.php +++ b/app/Enums/UserRoleEnum.php @@ -31,22 +31,22 @@ enum UserRoleEnum: string { // most basic rights, cannot see other members, can see everything else. // includes reading of metadata - case READ_ONLY = 'ro'; + case READ_ONLY = 'ro'; // required to even USE the group properly (in this order) - case MANAGE_TRANSACTIONS = 'mng_trx'; + case MANAGE_TRANSACTIONS = 'mng_trx'; // required to edit, add or change categories/tags/object-groups - case MANAGE_META = 'mng_meta'; + case MANAGE_META = 'mng_meta'; // read other objects and things. - case READ_BUDGETS = 'read_budgets'; - case READ_PIGGY_BANKS = 'read_piggies'; - case READ_SUBSCRIPTIONS = 'read_subscriptions'; - case READ_RULES = 'read_rules'; - case READ_RECURRING = 'read_recurring'; - case READ_WEBHOOKS = 'read_webhooks'; - case READ_CURRENCIES = 'read_currencies'; + case READ_BUDGETS = 'read_budgets'; + case READ_PIGGY_BANKS = 'read_piggies'; + case READ_SUBSCRIPTIONS = 'read_subscriptions'; + case READ_RULES = 'read_rules'; + case READ_RECURRING = 'read_recurring'; + case READ_WEBHOOKS = 'read_webhooks'; + case READ_CURRENCIES = 'read_currencies'; // manage other financial objects: case MANAGE_BUDGETS = 'mng_budgets'; @@ -58,14 +58,14 @@ enum UserRoleEnum: string case MANAGE_CURRENCIES = 'mng_currencies'; // view and generate reports - case VIEW_REPORTS = 'view_reports'; + case VIEW_REPORTS = 'view_reports'; // view memberships AND roles. needs FULL to manage them. - case VIEW_MEMBERSHIPS = 'view_memberships'; + case VIEW_MEMBERSHIPS = 'view_memberships'; // everything the creator can, except remove/change original creator and delete group - case FULL = 'full'; + case FULL = 'full'; // reserved for original creator - case OWNER = 'owner'; + case OWNER = 'owner'; } diff --git a/app/Events/Admin/InvitationCreated.php b/app/Events/Admin/InvitationCreated.php index dcd7cf86d3..491dda22cd 100644 --- a/app/Events/Admin/InvitationCreated.php +++ b/app/Events/Admin/InvitationCreated.php @@ -41,5 +41,7 @@ class InvitationCreated extends Event /** * Create a new event instance. */ - public function __construct(public InvitedUser $invitee) {} + public function __construct( + public InvitedUser $invitee + ) {} } diff --git a/app/Events/DestroyedTransactionGroup.php b/app/Events/DestroyedTransactionGroup.php index 80b2dbaf79..2468831129 100644 --- a/app/Events/DestroyedTransactionGroup.php +++ b/app/Events/DestroyedTransactionGroup.php @@ -38,8 +38,9 @@ class DestroyedTransactionGroup extends Event /** * Create a new event instance. */ - public function __construct(public TransactionGroup $transactionGroup) - { + public function __construct( + public TransactionGroup $transactionGroup + ) { Log::debug(sprintf('Now in %s', __METHOD__)); } } diff --git a/app/Events/Model/PiggyBank/PiggyBankAmountIsChanged.php b/app/Events/Model/PiggyBank/PiggyBankAmountIsChanged.php index 1a718714b7..0fa86a457e 100644 --- a/app/Events/Model/PiggyBank/PiggyBankAmountIsChanged.php +++ b/app/Events/Model/PiggyBank/PiggyBankAmountIsChanged.php @@ -38,16 +38,20 @@ class PiggyBankAmountIsChanged extends Event { use SerializesModels; - public string $amount; + public string $amount; public PiggyBank $piggyBank; /** * Create a new event instance. */ - public function __construct(PiggyBank $piggyBank, string $amount, public ?TransactionJournal $transactionJournal, public ?TransactionGroup $transactionGroup) - { + public function __construct( + PiggyBank $piggyBank, + string $amount, + public null|TransactionJournal $transactionJournal, + public null|TransactionGroup $transactionGroup + ) { Log::debug(sprintf('Created piggy bank event for piggy bank #%d with amount %s', $piggyBank->id, $amount)); $this->piggyBank = $piggyBank; - $this->amount = $amount; + $this->amount = $amount; } } diff --git a/app/Events/Model/PiggyBank/PiggyBankNameIsChanged.php b/app/Events/Model/PiggyBank/PiggyBankNameIsChanged.php index 48de5d088a..b02e09b0e4 100644 --- a/app/Events/Model/PiggyBank/PiggyBankNameIsChanged.php +++ b/app/Events/Model/PiggyBank/PiggyBankNameIsChanged.php @@ -1,6 +1,7 @@ ruleGroup = $ruleGroup; } } diff --git a/app/Events/Preferences/UserGroupChangedPrimaryCurrency.php b/app/Events/Preferences/UserGroupChangedPrimaryCurrency.php index 4f6fc7fbb2..866f142c69 100644 --- a/app/Events/Preferences/UserGroupChangedPrimaryCurrency.php +++ b/app/Events/Preferences/UserGroupChangedPrimaryCurrency.php @@ -33,8 +33,9 @@ class UserGroupChangedPrimaryCurrency extends Event { use SerializesModels; - public function __construct(public UserGroup $userGroup) - { + public function __construct( + public UserGroup $userGroup + ) { Log::debug('User group changed primary currency.'); } } diff --git a/app/Events/RequestedReportOnJournals.php b/app/Events/RequestedReportOnJournals.php index 94bd7e2e6a..813aae8aed 100644 --- a/app/Events/RequestedReportOnJournals.php +++ b/app/Events/RequestedReportOnJournals.php @@ -43,8 +43,10 @@ class RequestedReportOnJournals /** * Create a new event instance. */ - public function __construct(public int $userId, public Collection $groups) - { + public function __construct( + public int $userId, + public Collection $groups + ) { Log::debug('In event RequestedReportOnJournals.'); } diff --git a/app/Events/RequestedVersionCheckStatus.php b/app/Events/RequestedVersionCheckStatus.php index 63ac4df6ca..105182c19c 100644 --- a/app/Events/RequestedVersionCheckStatus.php +++ b/app/Events/RequestedVersionCheckStatus.php @@ -38,5 +38,7 @@ class RequestedVersionCheckStatus extends Event * Create a new event instance. This event is triggered when Firefly III wants to know * what the deal is with the version checker. */ - public function __construct(public User $user) {} + public function __construct( + public User $user + ) {} } diff --git a/app/Events/Security/System/NewUserRegistered.php b/app/Events/Security/System/NewUserRegistered.php index 2b6b634bf1..5d03ab63ac 100644 --- a/app/Events/Security/System/NewUserRegistered.php +++ b/app/Events/Security/System/NewUserRegistered.php @@ -33,5 +33,8 @@ class NewUserRegistered extends Event { use SerializesModels; - public function __construct(public OwnerNotifiable $owner, public User $user) {} + public function __construct( + public OwnerNotifiable $owner, + public User $user + ) {} } diff --git a/app/Events/Security/System/SystemFoundNewVersionOnline.php b/app/Events/Security/System/SystemFoundNewVersionOnline.php index d91aac5456..c4cc2f0e8e 100644 --- a/app/Events/Security/System/SystemFoundNewVersionOnline.php +++ b/app/Events/Security/System/SystemFoundNewVersionOnline.php @@ -31,6 +31,7 @@ class SystemFoundNewVersionOnline extends Event { use SerializesModels; - public function __construct(public string $message) {} + public function __construct( + public string $message + ) {} } - diff --git a/app/Events/Security/System/UnknownUserTriedLogin.php b/app/Events/Security/System/UnknownUserTriedLogin.php index 23708842e6..001675d499 100644 --- a/app/Events/Security/System/UnknownUserTriedLogin.php +++ b/app/Events/Security/System/UnknownUserTriedLogin.php @@ -1,6 +1,7 @@ user = $user; diff --git a/app/Events/Security/User/UserHasGeneratedNewBackupCodes.php b/app/Events/Security/User/UserHasGeneratedNewBackupCodes.php index 21e01fd175..c2645a15a0 100644 --- a/app/Events/Security/User/UserHasGeneratedNewBackupCodes.php +++ b/app/Events/Security/User/UserHasGeneratedNewBackupCodes.php @@ -1,6 +1,7 @@ user = $user; diff --git a/app/Events/Security/User/UserLoggedInFromNewIpAddress.php b/app/Events/Security/User/UserLoggedInFromNewIpAddress.php index d238333c6f..6621631c9d 100644 --- a/app/Events/Security/User/UserLoggedInFromNewIpAddress.php +++ b/app/Events/Security/User/UserLoggedInFromNewIpAddress.php @@ -35,5 +35,7 @@ class UserLoggedInFromNewIpAddress extends Event /** * Create a new event instance. This event is triggered when a new user registers. */ - public function __construct(public User $user) {} + public function __construct( + public User $user + ) {} } diff --git a/app/Events/Security/User/UserRequestedNewPassword.php b/app/Events/Security/User/UserRequestedNewPassword.php index f3484f7c03..3181ce870d 100644 --- a/app/Events/Security/User/UserRequestedNewPassword.php +++ b/app/Events/Security/User/UserRequestedNewPassword.php @@ -33,5 +33,10 @@ class UserRequestedNewPassword extends Event { use SerializesModels; - public function __construct(public User $user, #[SensitiveParameter] public string $token, public string $ipAddress) {} + public function __construct( + public User $user, + #[SensitiveParameter] + public string $token, + public string $ipAddress + ) {} } diff --git a/app/Events/StoredAccount.php b/app/Events/StoredAccount.php index 6dc34379ae..981a326883 100644 --- a/app/Events/StoredAccount.php +++ b/app/Events/StoredAccount.php @@ -37,5 +37,7 @@ class StoredAccount extends Event /** * Create a new event instance. */ - public function __construct(public Account $account) {} + public function __construct( + public Account $account + ) {} } diff --git a/app/Events/StoredTransactionGroup.php b/app/Events/StoredTransactionGroup.php index 15c0d42b7b..743018ea2f 100644 --- a/app/Events/StoredTransactionGroup.php +++ b/app/Events/StoredTransactionGroup.php @@ -37,5 +37,9 @@ class StoredTransactionGroup extends Event /** * Create a new event instance. */ - public function __construct(public TransactionGroup $transactionGroup, public bool $applyRules, public bool $fireWebhooks) {} + public function __construct( + public TransactionGroup $transactionGroup, + public bool $applyRules, + public bool $fireWebhooks + ) {} } diff --git a/app/Events/Test/OwnerTestsNotificationChannel.php b/app/Events/Test/OwnerTestsNotificationChannel.php index 067583a253..30d1d5358c 100644 --- a/app/Events/Test/OwnerTestsNotificationChannel.php +++ b/app/Events/Test/OwnerTestsNotificationChannel.php @@ -37,8 +37,10 @@ class OwnerTestsNotificationChannel /** * Create a new event instance. */ - public function __construct(string $channel, public OwnerNotifiable $owner) - { + public function __construct( + string $channel, + public OwnerNotifiable $owner + ) { Log::debug(sprintf('Triggered OwnerTestsNotificationChannels("%s")', $channel)); $this->channel = $channel; } diff --git a/app/Events/Test/UserTestsNotificationChannel.php b/app/Events/Test/UserTestsNotificationChannel.php index 50e5cea02e..e4bd772519 100644 --- a/app/Events/Test/UserTestsNotificationChannel.php +++ b/app/Events/Test/UserTestsNotificationChannel.php @@ -37,8 +37,10 @@ class UserTestsNotificationChannel /** * Create a new event instance. */ - public function __construct(string $channel, public User $user) - { + public function __construct( + string $channel, + public User $user + ) { Log::debug(sprintf('Triggered UserTestNotificationChannel("%s")', $channel)); $this->channel = $channel; } diff --git a/app/Events/TriggeredAuditLog.php b/app/Events/TriggeredAuditLog.php index e0472815c0..b13ee5ef03 100644 --- a/app/Events/TriggeredAuditLog.php +++ b/app/Events/TriggeredAuditLog.php @@ -39,5 +39,11 @@ class TriggeredAuditLog extends Event * * @SuppressWarnings("PHPMD.ExcessiveParameterList") */ - public function __construct(public Model $changer, public Model $auditable, public string $field, public mixed $before, public mixed $after) {} + public function __construct( + public Model $changer, + public Model $auditable, + public string $field, + public mixed $before, + public mixed $after + ) {} } diff --git a/app/Events/UpdatedAccount.php b/app/Events/UpdatedAccount.php index bf34c61348..2203915030 100644 --- a/app/Events/UpdatedAccount.php +++ b/app/Events/UpdatedAccount.php @@ -37,5 +37,7 @@ class UpdatedAccount extends Event /** * Create a new event instance. */ - public function __construct(public Account $account) {} + public function __construct( + public Account $account + ) {} } diff --git a/app/Events/UpdatedTransactionGroup.php b/app/Events/UpdatedTransactionGroup.php index 637bb99f6f..00160e97ac 100644 --- a/app/Events/UpdatedTransactionGroup.php +++ b/app/Events/UpdatedTransactionGroup.php @@ -37,5 +37,10 @@ class UpdatedTransactionGroup extends Event /** * Create a new event instance. */ - public function __construct(public TransactionGroup $transactionGroup, public bool $applyRules, public bool $fireWebhooks, public bool $runRecalculations) {} + public function __construct( + public TransactionGroup $transactionGroup, + public bool $applyRules, + public bool $fireWebhooks, + public bool $runRecalculations + ) {} } diff --git a/app/Exceptions/GracefulNotFoundHandler.php b/app/Exceptions/GracefulNotFoundHandler.php index 0251bf4f1b..9e4e8f978b 100644 --- a/app/Exceptions/GracefulNotFoundHandler.php +++ b/app/Exceptions/GracefulNotFoundHandler.php @@ -59,7 +59,7 @@ class GracefulNotFoundHandler extends ExceptionHandler if (null === $route) { return parent::render($request, $e); } - $name = $route->getName(); + $name = $route->getName(); if (!auth()->check()) { return parent::render($request, $e); } @@ -163,12 +163,12 @@ class GracefulNotFoundHandler extends ExceptionHandler if ($param instanceof Account) { $accountId = $param->id; } - if (!($param instanceof Account) && !is_object($param)) { + if (!$param instanceof Account && !is_object($param)) { $accountId = (int) $param; } /** @var null|Account $account */ - $account = $user->accounts()->withTrashed()->with(['accountType'])->find($accountId); + $account = $user->accounts()->withTrashed()->with(['accountType'])->find($accountId); if (null === $account) { Log::error(sprintf('Could not find account %d, so give big fat error.', $accountId)); @@ -197,7 +197,7 @@ class GracefulNotFoundHandler extends ExceptionHandler $groupId = is_object($param) ? 0 : (int) $param; /** @var null|TransactionGroup $group */ - $group = $user->transactionGroups()->withTrashed()->find($groupId); + $group = $user->transactionGroups()->withTrashed()->find($groupId); if (null === $group) { Log::error(sprintf('Could not find group %d, so give big fat error.', $groupId)); @@ -211,7 +211,7 @@ class GracefulNotFoundHandler extends ExceptionHandler return parent::render($request, $exception); } - $type = $journal->transactionType->type; + $type = $journal->transactionType->type; $request->session()->reflash(); if (TransactionTypeEnum::RECONCILIATION->value === $type) { @@ -237,7 +237,7 @@ class GracefulNotFoundHandler extends ExceptionHandler $attachmentId = is_object($param) ? 0 : (int) $param; /** @var null|Attachment $attachment */ - $attachment = $user->attachments()->withTrashed()->find($attachmentId); + $attachment = $user->attachments()->withTrashed()->find($attachmentId); if (null === $attachment) { Log::error(sprintf('Could not find attachment %d, so give big fat error.', $attachmentId)); diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index 3089ca41b7..75061da7d1 100644 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -28,6 +28,7 @@ use Brick\Math\Exception\NumberFormatException; use Carbon\Carbon; use ErrorException; use FireflyIII\Jobs\MailError; +use FireflyIII\Support\Facades\Steam; use Illuminate\Auth\Access\AuthorizationException; use Illuminate\Auth\AuthenticationException; use Illuminate\Database\QueryException; @@ -50,7 +51,6 @@ use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Throwable; -use FireflyIII\Support\Facades\Steam; use function Safe\json_encode; use function Safe\parse_url; @@ -62,30 +62,31 @@ use function Safe\parse_url; */ class Handler extends ExceptionHandler { - public static ?Throwable $lastError = null; + public static null|Throwable $lastError = null; /** * @var array> */ - protected $dontReport - = [ - AuthenticationException::class, - LaravelValidationException::class, - NotFoundHttpException::class, - GoneHttpException::class, - OAuthServerException::class, - LaravelOAuthException::class, - TokenMismatchException::class, - HttpException::class, - SuspiciousOperationException::class, - BadHttpHeaderException::class, - ]; + protected $dontReport = [ + AuthenticationException::class, + LaravelValidationException::class, + NotFoundHttpException::class, + GoneHttpException::class, + OAuthServerException::class, + LaravelOAuthException::class, + TokenMismatchException::class, + HttpException::class, + SuspiciousOperationException::class, + BadHttpHeaderException::class + ]; /** * Register the exception handling callbacks for the application. */ #[Override] - public function register(): void {} + public function register(): void + { + } /** * Render an exception into an HTTP response. It's complex but lucky for us, we never use it because @@ -116,75 +117,72 @@ class Handler extends ExceptionHandler // JSON error: Log::debug('Return JSON not found error.'); - return response()->json(['message' => 'Resource not found', 'exception' => 'NotFoundHttpException'], 404); + return response()->json(['message' => 'Resource not found', 'exception' => 'NotFoundHttpException'], 404); } if ($e instanceof AuthorizationException && $expectsJson) { // somehow Laravel handler does not catch this: Log::debug('Return JSON unauthorized error.'); - return response()->json(['message' => $e->getMessage(), 'exception' => 'AuthorizationException'], 401); + return response()->json(['message' => $e->getMessage(), 'exception' => 'AuthorizationException'], 401); } if ($e instanceof AuthenticationException && $expectsJson) { // somehow Laravel handler does not catch this: Log::debug('Return JSON unauthenticated error.'); - return response()->json(['message' => $e->getMessage(), 'exception' => 'AuthenticationException'], 401); + return response()->json(['message' => $e->getMessage(), 'exception' => 'AuthenticationException'], 401); } if ($e instanceof OAuthServerException && $expectsJson) { Log::debug('Return JSON OAuthServerException.'); // somehow Laravel handler does not catch this: - return response()->json(['message' => $e->getMessage(), 'exception' => 'OAuthServerException'], 401); + return response()->json(['message' => $e->getMessage(), 'exception' => 'OAuthServerException'], 401); } if ($e instanceof BadRequestHttpException) { Log::debug('Return JSON BadRequestHttpException.'); - return response()->json(['message' => $e->getMessage(), 'exception' => 'HttpException'], 400); + return response()->json(['message' => $e->getMessage(), 'exception' => 'HttpException'], 400); } if ($e instanceof BadHttpHeaderException) { // is always API exception. Log::debug('Return JSON BadHttpHeaderException.'); - return response()->json(['message' => $e->getMessage(), 'exception' => 'BadHttpHeaderException'], $e->statusCode); + return response()->json(['message' => $e->getMessage(), 'exception' => 'BadHttpHeaderException'], $e->statusCode); } if (($e instanceof ValidationException || $e instanceof NumberFormatException) && $expectsJson) { $errorCode = 422; - return response()->json( - ['message' => sprintf('Validation exception: %s', $e->getMessage()), 'errors' => ['field' => 'Field is invalid']], - $errorCode - ); + return response()->json([ + 'message' => sprintf('Validation exception: %s', $e->getMessage()), + 'errors' => ['field' => 'Field is invalid'] + ], $errorCode); } if ($expectsJson) { $errorCode = 500; $errorCode = $e instanceof MethodNotAllowedHttpException ? 405 : $errorCode; - $isDebug = (bool)config('app.debug', false); + $isDebug = (bool) config('app.debug', false); if ($isDebug) { Log::debug(sprintf('Return JSON %s with debug.', $e::class)); - return response()->json( - [ - 'message' => $e->getMessage(), - 'exception' => $e::class, - 'line' => $e->getLine(), - 'file' => $e->getFile(), - 'trace' => $e->getTrace(), - ], - $errorCode - ); + return response()->json([ + 'message' => $e->getMessage(), + 'exception' => $e::class, + 'line' => $e->getLine(), + 'file' => $e->getFile(), + 'trace' => $e->getTrace() + ], $errorCode); } Log::debug(sprintf('Return JSON %s.', $e::class)); - return response()->json( - ['message' => sprintf('Internal Firefly III Exception: %s', $e->getMessage()), 'exception' => 'UndisclosedException'], - $errorCode - ); + return response()->json([ + 'message' => sprintf('Internal Firefly III Exception: %s', $e->getMessage()), + 'exception' => 'UndisclosedException' + ], $errorCode); } if ($e instanceof NotFoundHttpException) { @@ -199,14 +197,14 @@ class Handler extends ExceptionHandler Log::debug('Return Firefly III database exception view.'); $isDebug = config('app.debug'); - return response()->view('errors.DatabaseException', ['exception' => $e, 'debug' => $isDebug], 500); + return response()->view('errors.DatabaseException', ['exception' => $e, 'debug' => $isDebug], 500); } if ($e instanceof FireflyException || $e instanceof ErrorException || $e instanceof OAuthServerException) { Log::debug('Return Firefly III error view.'); $isDebug = config('app.debug'); - return response()->view('errors.FireflyException', ['exception' => $e, 'debug' => $isDebug], 500); + return response()->view('errors.FireflyException', ['exception' => $e, 'debug' => $isDebug], 500); } Log::debug(sprintf('Error "%s" has no Firefly III treatment, parent will handle.', $e::class)); @@ -223,24 +221,21 @@ class Handler extends ExceptionHandler public function report(Throwable $e): void { self::$lastError = $e; - $doMailError = (bool)config('firefly.send_error_message'); + $doMailError = (bool) config('firefly.send_error_message'); if ($this->shouldntReportLocal($e) || !$doMailError) { parent::report($e); return; } - $userData = [ - 'id' => 0, - 'email' => 'unknown@example.com', - ]; + $userData = ['id' => 0, 'email' => 'unknown@example.com']; if (auth()->check()) { - $userData['id'] = auth()->user()->id; + $userData['id'] = auth()->user()->id; $userData['email'] = auth()->user()->email; } - $headers = request()->headers->all(); + $headers = request()->headers->all(); - $data = [ + $data = [ 'class' => $e::class, 'errorMessage' => $e->getMessage(), 'time' => Carbon::now()->format('r'), @@ -254,12 +249,12 @@ class Handler extends ExceptionHandler 'json' => request()->acceptsJson(), 'method' => request()->method(), 'headers' => $headers, - 'post' => 'POST' === request()->method() ? json_encode(request()->all()) : '', + 'post' => 'POST' === request()->method() ? json_encode(request()->all()) : '' ]; // create job that will mail. - $ipAddress = request()->ip() ?? '0.0.0.0'; - $job = new MailError($userData, (string)config('firefly.site_owner'), $ipAddress, $data); + $ipAddress = request()->ip() ?? '0.0.0.0'; + $job = new MailError($userData, (string) config('firefly.site_owner'), $ipAddress, $data); dispatch($job); parent::report($e); @@ -267,10 +262,7 @@ class Handler extends ExceptionHandler private function shouldntReportLocal(Throwable $e): bool { - return null !== Arr::first( - $this->dontReport, - static fn ($type): bool => $e instanceof $type - ); + return null !== Arr::first($this->dontReport, static fn($type): bool => $e instanceof $type); } /** @@ -287,14 +279,13 @@ class Handler extends ExceptionHandler return redirect($redirect ?? $previous) ->withInput(Arr::except($request->input(), $this->dontFlash)) - ->withErrors($exception->errors(), $request->input('_error_bag', $exception->errorBag)) - ; + ->withErrors($exception->errors(), $request->input('_error_bag', $exception->errorBag)); } /** * Only return the redirectTo property from the exception if it is a valid URL. Return NULL otherwise. */ - private function getRedirectUrl(LaravelValidationException $exception): ?string + private function getRedirectUrl(LaravelValidationException $exception): null|string { if (null === $exception->redirectTo) { return null; diff --git a/app/Exceptions/IntervalException.php b/app/Exceptions/IntervalException.php index 09ab3c6469..305aec2061 100644 --- a/app/Exceptions/IntervalException.php +++ b/app/Exceptions/IntervalException.php @@ -37,27 +37,19 @@ final class IntervalException extends Exception public Periodicity $periodicity = Periodicity::Monthly; /** @var mixed */ - protected $message = 'The periodicity %s is unknown. Choose one of available periodicity: %s'; + protected $message = 'The periodicity %s is unknown. Choose one of available periodicity: %s'; - public function __construct(string $message = '', int $code = 0, ?Throwable $previous = null) + public function __construct(string $message = '', int $code = 0, null|Throwable $previous = null) { parent::__construct($message, $code, $previous); } - public static function unavailable( - Periodicity $periodicity, - array $intervals, - int $code = 0, - ?Throwable $previous = null - ): self { - $message = sprintf( - 'The periodicity %s is unknown. Choose one of available periodicity: %s', - $periodicity->name, - implode(', ', $intervals) - ); + public static function unavailable(Periodicity $periodicity, array $intervals, int $code = 0, null|Throwable $previous = null): self + { + $message = sprintf('The periodicity %s is unknown. Choose one of available periodicity: %s', $periodicity->name, implode(', ', $intervals)); - $exception = new self($message, $code, $previous); - $exception->periodicity = $periodicity; + $exception = new self($message, $code, $previous); + $exception->periodicity = $periodicity; $exception->availableIntervals = $intervals; return $exception; diff --git a/app/Factory/AccountFactory.php b/app/Factory/AccountFactory.php index 699d02c186..eb7c558baf 100644 --- a/app/Factory/AccountFactory.php +++ b/app/Factory/AccountFactory.php @@ -47,24 +47,24 @@ class AccountFactory use LocationServiceTrait; protected AccountRepositoryInterface $accountRepository; - protected array $validAssetFields; - protected array $validCCFields; - protected array $validFields; - private array $canHaveOpeningBalance; - private array $canHaveVirtual; - private User $user; + protected array $validAssetFields; + protected array $validCCFields; + protected array $validFields; + private array $canHaveOpeningBalance; + private array $canHaveVirtual; + private User $user; /** * AccountFactory constructor. */ public function __construct() { - $this->accountRepository = app(AccountRepositoryInterface::class); - $this->canHaveVirtual = config('firefly.can_have_virtual_amounts'); + $this->accountRepository = app(AccountRepositoryInterface::class); + $this->canHaveVirtual = config('firefly.can_have_virtual_amounts'); $this->canHaveOpeningBalance = config('firefly.can_have_opening_balance'); - $this->validAssetFields = config('firefly.valid_asset_fields'); - $this->validCCFields = config('firefly.valid_cc_fields'); - $this->validFields = config('firefly.valid_account_fields'); + $this->validAssetFields = config('firefly.valid_asset_fields'); + $this->validCCFields = config('firefly.valid_cc_fields'); + $this->validFields = config('firefly.valid_account_fields'); } /** @@ -74,28 +74,30 @@ class AccountFactory { Log::debug(sprintf('findOrCreate("%s", "%s")', $accountName, $accountType)); - $type = $this->accountRepository->getAccountTypeByType($accountType); + $type = $this->accountRepository->getAccountTypeByType($accountType); if (!$type instanceof AccountType) { throw new FireflyException(sprintf('Cannot find account type "%s"', $accountType)); } /** @var null|Account $return */ - $return = $this->user->accounts->where('account_type_id', $type->id)->where('name', $accountName)->first(); + $return = $this->user + ->accounts + ->where('account_type_id', $type->id) + ->where('name', $accountName) + ->first(); if (null === $return) { Log::debug('Found nothing. Will create a new one.'); - $return = $this->create( - [ - 'user_id' => $this->user->id, - 'user_group_id' => $this->user->user_group_id, - 'name' => $accountName, - 'account_type_id' => $type->id, - 'account_type_name' => null, - 'virtual_balance' => '0', - 'iban' => null, - 'active' => true, - ] - ); + $return = $this->create([ + 'user_id' => $this->user->id, + 'user_group_id' => $this->user->user_group_id, + 'name' => $accountName, + 'account_type_id' => $type->id, + 'account_type_name' => null, + 'virtual_balance' => '0', + 'iban' => null, + 'active' => true + ]); } return $return; @@ -107,17 +109,17 @@ class AccountFactory public function create(array $data): Account { Log::debug('Now in AccountFactory::create()'); - $type = $this->getAccountType($data); + $type = $this->getAccountType($data); $data['iban'] = $this->filterIban($data['iban'] ?? null); // account may exist already: - $return = $this->find($data['name'], $type->type); + $return = $this->find($data['name'], $type->type); if ($return instanceof Account) { return $return; } - $return = $this->createAccount($type, $data); + $return = $this->createAccount($type, $data); event(new StoredAccount($return)); @@ -127,7 +129,7 @@ class AccountFactory /** * @throws FireflyException */ - protected function getAccountType(array $data): ?AccountType + protected function getAccountType(array $data): null|AccountType { $accountTypeId = array_key_exists('account_type_id', $data) ? (int) $data['account_type_id'] : 0; $accountTypeName = $data['account_type_name'] ?? null; @@ -157,13 +159,17 @@ class AccountFactory return $result; } - public function find(string $accountName, string $accountType): ?Account + public function find(string $accountName, string $accountType): null|Account { Log::debug(sprintf('Now in AccountFactory::find("%s", "%s")', $accountName, $accountType)); $type = AccountType::whereType($accountType)->first(); /** @var null|Account */ - return $this->user->accounts()->where('account_type_id', $type->id)->where('name', $accountName)->first(); + return $this->user + ->accounts() + ->where('account_type_id', $type->id) + ->where('name', $accountName) + ->first(); } /** @@ -184,7 +190,7 @@ class AccountFactory 'order' => 25000, 'virtual_balance' => $virtualBalance, 'active' => $active, - 'iban' => $data['iban'], + 'iban' => $data['iban'] ]; // fix virtual balance when it's empty if ('' === (string) $databaseData['virtual_balance']) { @@ -195,11 +201,11 @@ class AccountFactory $databaseData['virtual_balance'] = null; } // create account! - $account = Account::create($databaseData); + $account = Account::create($databaseData); Log::channel('audit')->info(sprintf('Account #%d ("%s") has been created.', $account->id, $account->name)); // update meta data: - $data = $this->cleanMetaDataArray($account, $data); + $data = $this->cleanMetaDataArray($account, $data); $this->storeMetaData($account, $data); // create opening balance (only asset accounts) @@ -219,7 +225,7 @@ class AccountFactory } // create notes - $notes = array_key_exists('notes', $data) ? $data['notes'] : ''; + $notes = array_key_exists('notes', $data) ? $data['notes'] : ''; $this->updateNote($account, $notes); // create location @@ -239,10 +245,10 @@ class AccountFactory */ private function cleanMetaDataArray(Account $account, array $data): array { - $currencyId = array_key_exists('currency_id', $data) ? (int) $data['currency_id'] : 0; - $currencyCode = array_key_exists('currency_code', $data) ? (string) $data['currency_code'] : ''; - $accountRole = array_key_exists('account_role', $data) ? (string) $data['account_role'] : null; - $currency = $this->getCurrency($currencyId, $currencyCode); + $currencyId = array_key_exists('currency_id', $data) ? (int) $data['currency_id'] : 0; + $currencyCode = array_key_exists('currency_code', $data) ? (string) $data['currency_code'] : ''; + $accountRole = array_key_exists('account_role', $data) ? (string) $data['account_role'] : null; + $currency = $this->getCurrency($currencyId, $currencyCode); // only asset account may have a role: if (AccountTypeEnum::ASSET->value !== $account->accountType->type) { @@ -253,14 +259,14 @@ class AccountFactory $data['liability_direction'] = null; } $data['account_role'] = $accountRole; - $data['currency_id'] = $currency->id; + $data['currency_id'] = $currency->id; return $data; } private function storeMetaData(Account $account, array $data): void { - $fields = $this->validFields; + $fields = $this->validFields; if (AccountTypeEnum::ASSET->value === $account->accountType->type) { $fields = $this->validAssetFields; } @@ -269,8 +275,8 @@ class AccountFactory } // remove currency_id if necessary. - $type = $account->accountType->type; - $list = config('firefly.valid_currency_account_types'); + $type = $account->accountType->type; + $list = config('firefly.valid_currency_account_types'); if (!in_array($type, $list, true)) { $pos = array_search('currency_id', $fields, true); if (false !== $pos) { @@ -347,9 +353,9 @@ class AccountFactory */ private function storeOrder(Account $account, array $data): void { - $accountType = $account->accountType->type; - $maxOrder = $this->accountRepository->maxOrder($accountType); - $order = null; + $accountType = $account->accountType->type; + $maxOrder = $this->accountRepository->maxOrder($accountType); + $order = null; if (!array_key_exists('order', $data)) { $order = $maxOrder + 1; } diff --git a/app/Factory/AccountMetaFactory.php b/app/Factory/AccountMetaFactory.php index 95bbd45955..345d05fbfb 100644 --- a/app/Factory/AccountMetaFactory.php +++ b/app/Factory/AccountMetaFactory.php @@ -36,7 +36,7 @@ class AccountMetaFactory /** * Create update or delete meta data. */ - public function crud(Account $account, string $field, string $value): ?AccountMeta + public function crud(Account $account, string $field, string $value): null|AccountMeta { /** @var null|AccountMeta $entry */ $entry = $account->accountMeta()->where('name', $field)->first(); @@ -48,10 +48,9 @@ class AccountMetaFactory } // if $data has field and $entry is null, create new one: if (null === $entry) { - return $this->create(['account_id' => $account->id, 'name' => $field, 'data' => $value]); + return $this->create(['account_id' => $account->id, 'name' => $field, 'data' => $value]); } - // if $data has field and $entry is not null, update $entry: $entry->data = $value; $entry->save(); @@ -65,7 +64,7 @@ class AccountMetaFactory return $entry; } - public function create(array $data): ?AccountMeta + public function create(array $data): null|AccountMeta { return AccountMeta::create($data); } diff --git a/app/Factory/AttachmentFactory.php b/app/Factory/AttachmentFactory.php index 64f7d245f8..b8b4cdd3d1 100644 --- a/app/Factory/AttachmentFactory.php +++ b/app/Factory/AttachmentFactory.php @@ -41,41 +41,40 @@ class AttachmentFactory /** * @throws FireflyException */ - public function create(array $data): ?Attachment + public function create(array $data): null|Attachment { // append if necessary. - $model = str_contains((string) $data['attachable_type'], 'FireflyIII') ? $data['attachable_type'] + $model = str_contains((string) $data['attachable_type'], 'FireflyIII') + ? $data['attachable_type'] : sprintf('FireflyIII\Models\%s', $data['attachable_type']); // get journal instead of transaction. if (Transaction::class === $model) { /** @var null|Transaction $transaction */ - $transaction = $this->user->transactions()->find((int) $data['attachable_id']); + $transaction = $this->user->transactions()->find((int) $data['attachable_id']); if (null === $transaction) { throw new FireflyException('Unexpectedly could not find transaction'); } $data['attachable_id'] = $transaction->transaction_journal_id; - $model = TransactionJournal::class; + $model = TransactionJournal::class; } // create attachment: - $attachment = Attachment::create( - [ - 'user_id' => $this->user->id, - 'attachable_id' => $data['attachable_id'], - 'attachable_type' => $model, - 'md5' => '', - 'filename' => $data['filename'], - 'title' => '' === $data['title'] ? null : $data['title'], - 'description' => null, - 'mime' => '', - 'size' => 0, - 'uploaded' => 0, - ] - ); + $attachment = Attachment::create([ + 'user_id' => $this->user->id, + 'attachable_id' => $data['attachable_id'], + 'attachable_type' => $model, + 'md5' => '', + 'filename' => $data['filename'], + 'title' => '' === $data['title'] ? null : $data['title'], + 'description' => null, + 'mime' => '', + 'size' => 0, + 'uploaded' => 0 + ]); $notes = (string) ($data['notes'] ?? ''); if ('' !== $notes) { - $note = new Note(); + $note = new Note(); $note->noteable()->associate($attachment); $note->text = $notes; $note->save(); diff --git a/app/Factory/BillFactory.php b/app/Factory/BillFactory.php index 4052309696..0577edd3ed 100644 --- a/app/Factory/BillFactory.php +++ b/app/Factory/BillFactory.php @@ -29,10 +29,10 @@ use FireflyIII\Models\Bill; use FireflyIII\Models\ObjectGroup; use FireflyIII\Repositories\ObjectGroup\CreatesObjectGroups; use FireflyIII\Services\Internal\Support\BillServiceTrait; +use FireflyIII\Support\Facades\Amount; use FireflyIII\User; use Illuminate\Database\QueryException; use Illuminate\Support\Facades\Log; -use FireflyIII\Support\Facades\Amount; /** * Class BillFactory @@ -47,42 +47,42 @@ class BillFactory /** * @throws FireflyException */ - public function create(array $data): ?Bill + public function create(array $data): null|Bill { Log::debug(sprintf('Now in %s', __METHOD__), $data); - $factory = app(TransactionCurrencyFactory::class); - $currency = $factory->find((int) ($data['currency_id'] ?? null), (string) ($data['currency_code'] ?? null)) - ?? Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); + $factory = app(TransactionCurrencyFactory::class); + $currency = $factory->find( + (int) ($data['currency_id'] ?? null), + (string) ($data['currency_code'] ?? null) + ) ?? Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); try { $skip = array_key_exists('skip', $data) ? $data['skip'] : 0; $active = array_key_exists('active', $data) ? $data['active'] : 0; $data['extension_date'] ??= null; - $data['end_date'] ??= null; + $data['end_date'] ??= null; /** @var Bill $bill */ - $bill = Bill::create( - [ - 'name' => $data['name'], - 'match' => 'MIGRATED_TO_RULES', - 'amount_min' => $data['amount_min'], - 'user_id' => $this->user->id, - 'user_group_id' => $this->user->user_group_id, - 'transaction_currency_id' => $currency->id, - 'amount_max' => $data['amount_max'], - 'date' => $data['date'], - 'date_tz' => $data['date']->format('e'), - 'end_date' => $data['end_date'] ?? null, - 'end_date_tz' => $data['end_date']?->format('e'), - 'extension_date' => $data['extension_date'] ?? null, - 'extension_date_tz' => $data['extension_date']?->format('e'), - 'repeat_freq' => $data['repeat_freq'], - 'skip' => $skip, - 'automatch' => true, - 'active' => $active, - ] - ); + $bill = Bill::create([ + 'name' => $data['name'], + 'match' => 'MIGRATED_TO_RULES', + 'amount_min' => $data['amount_min'], + 'user_id' => $this->user->id, + 'user_group_id' => $this->user->user_group_id, + 'transaction_currency_id' => $currency->id, + 'amount_max' => $data['amount_max'], + 'date' => $data['date'], + 'date_tz' => $data['date']->format('e'), + 'end_date' => $data['end_date'] ?? null, + 'end_date_tz' => $data['end_date']?->format('e'), + 'extension_date' => $data['extension_date'] ?? null, + 'extension_date_tz' => $data['extension_date']?->format('e'), + 'repeat_freq' => $data['repeat_freq'], + 'skip' => $skip, + 'automatch' => true, + 'active' => $active + ]); } catch (QueryException $e) { Log::error($e->getMessage()); Log::error($e->getTraceAsString()); @@ -102,7 +102,7 @@ class BillFactory } } // try also with ID: - $objectGroupId = (int) ($data['object_group_id'] ?? 0); + $objectGroupId = (int) ($data['object_group_id'] ?? 0); if (0 !== $objectGroupId) { $objectGroup = $this->findObjectGroupById($objectGroupId); if ($objectGroup instanceof ObjectGroup) { @@ -114,7 +114,7 @@ class BillFactory return $bill; } - public function find(?int $billId, ?string $billName): ?Bill + public function find(null|int $billId, null|string $billName): null|Bill { $billId = (int) $billId; $billName = (string) $billName; @@ -133,10 +133,13 @@ class BillFactory return $bill; } - public function findByName(string $name): ?Bill + public function findByName(string $name): null|Bill { /** @var null|Bill */ - return $this->user->bills()->whereLike('name', sprintf('%%%s%%', $name))->first(); + return $this->user + ->bills() + ->whereLike('name', sprintf('%%%s%%', $name)) + ->first(); } public function setUser(User $user): void diff --git a/app/Factory/BudgetFactory.php b/app/Factory/BudgetFactory.php index bbb274fa5d..731e5e8bbf 100644 --- a/app/Factory/BudgetFactory.php +++ b/app/Factory/BudgetFactory.php @@ -33,7 +33,7 @@ class BudgetFactory { private User $user; - public function find(?int $budgetId, ?string $budgetName): ?Budget + public function find(null|int $budgetId, null|string $budgetName): null|Budget { $budgetId = (int) $budgetId; $budgetName = (string) $budgetName; @@ -61,10 +61,13 @@ class BudgetFactory return null; } - public function findByName(string $name): ?Budget + public function findByName(string $name): null|Budget { /** @var null|Budget */ - return $this->user->budgets()->where('name', $name)->first(); + return $this->user + ->budgets() + ->where('name', $name) + ->first(); } public function setUser(User $user): void diff --git a/app/Factory/CategoryFactory.php b/app/Factory/CategoryFactory.php index 7b694a3e77..fbdbd45952 100644 --- a/app/Factory/CategoryFactory.php +++ b/app/Factory/CategoryFactory.php @@ -39,7 +39,7 @@ class CategoryFactory /** * @throws FireflyException */ - public function findOrCreate(?int $categoryId, ?string $categoryName): ?Category + public function findOrCreate(null|int $categoryId, null|string $categoryName): null|Category { $categoryId = (int) $categoryId; $categoryName = (string) $categoryName; @@ -65,13 +65,7 @@ class CategoryFactory } try { - return Category::create( - [ - 'user_id' => $this->user->id, - 'user_group_id' => $this->user->user_group_id, - 'name' => $categoryName, - ] - ); + return Category::create(['user_id' => $this->user->id, 'user_group_id' => $this->user->user_group_id, 'name' => $categoryName]); } catch (QueryException $e) { Log::error($e->getMessage()); Log::error($e->getTraceAsString()); @@ -83,10 +77,13 @@ class CategoryFactory return null; } - public function findByName(string $name): ?Category + public function findByName(string $name): null|Category { /** @var null|Category */ - return $this->user->categories()->where('name', $name)->first(); + return $this->user + ->categories() + ->where('name', $name) + ->first(); } public function setUser(User $user): void diff --git a/app/Factory/PiggyBankEventFactory.php b/app/Factory/PiggyBankEventFactory.php index e4635fb93c..689afa9af0 100644 --- a/app/Factory/PiggyBankEventFactory.php +++ b/app/Factory/PiggyBankEventFactory.php @@ -35,7 +35,7 @@ use Illuminate\Support\Facades\Log; */ class PiggyBankEventFactory { - public function create(TransactionJournal $journal, ?PiggyBank $piggyBank): void + public function create(TransactionJournal $journal, null|PiggyBank $piggyBank): void { Log::debug(sprintf('Now in PiggyBankEventCreate for a %s', $journal->transactionType->type)); if (!$piggyBank instanceof PiggyBank) { @@ -48,7 +48,7 @@ class PiggyBankEventFactory $piggyRepos = app(PiggyBankRepositoryInterface::class); $piggyRepos->setUser($journal->user); - $amount = $piggyRepos->getExactAmount($piggyBank, $journal); + $amount = $piggyRepos->getExactAmount($piggyBank, $journal); if (0 === bccomp($amount, '0')) { Log::debug('Amount is zero, will not create event.'); diff --git a/app/Factory/PiggyBankFactory.php b/app/Factory/PiggyBankFactory.php index 12f0b520ac..5d46ac14eb 100644 --- a/app/Factory/PiggyBankFactory.php +++ b/app/Factory/PiggyBankFactory.php @@ -33,10 +33,10 @@ use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\Repositories\ObjectGroup\CreatesObjectGroups; use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface; +use FireflyIII\Support\Facades\Amount; use FireflyIII\User; use Illuminate\Database\QueryException; use Illuminate\Support\Facades\Log; -use FireflyIII\Support\Facades\Amount; use function Safe\json_encode; @@ -54,8 +54,8 @@ class PiggyBankFactory public function __construct() { - $this->currencyRepository = app(CurrencyRepositoryInterface::class); - $this->accountRepository = app(AccountRepositoryInterface::class); + $this->currencyRepository = app(CurrencyRepositoryInterface::class); + $this->accountRepository = app(AccountRepositoryInterface::class); $this->piggyBankRepository = app(PiggyBankRepositoryInterface::class); } @@ -72,22 +72,28 @@ class PiggyBankFactory */ public function store(array $data): PiggyBank { - - $piggyBankData = $data; + $piggyBankData = $data; // unset some fields - unset($piggyBankData['object_group_title'], $piggyBankData['transaction_currency_code'], $piggyBankData['transaction_currency_id'], $piggyBankData['accounts'], $piggyBankData['object_group_id'], $piggyBankData['notes']); + unset( + $piggyBankData['object_group_title'], + $piggyBankData['transaction_currency_code'], + $piggyBankData['transaction_currency_id'], + $piggyBankData['accounts'], + $piggyBankData['object_group_id'], + $piggyBankData['notes'] + ); // validate amount: - if (array_key_exists('target_amount', $piggyBankData) && '' === (string)$piggyBankData['target_amount']) { + if (array_key_exists('target_amount', $piggyBankData) && '' === (string) $piggyBankData['target_amount']) { $piggyBankData['target_amount'] = '0'; } - $piggyBankData['start_date_tz'] = $piggyBankData['start_date']?->format('e'); - $piggyBankData['target_date_tz'] = $piggyBankData['target_date']?->format('e'); - $piggyBankData['account_id'] = null; + $piggyBankData['start_date_tz'] = $piggyBankData['start_date']?->format('e'); + $piggyBankData['target_date_tz'] = $piggyBankData['target_date']?->format('e'); + $piggyBankData['account_id'] = null; $piggyBankData['transaction_currency_id'] = $this->getCurrency($data)->id; - $piggyBankData['order'] = 131337; + $piggyBankData['order'] = 131337; try { /** @var PiggyBank $piggyBank */ @@ -97,11 +103,11 @@ class PiggyBankFactory throw new FireflyException('400005: Could not store new piggy bank.', 0, $e); } - $piggyBank = $this->setOrder($piggyBank, $data); + $piggyBank = $this->setOrder($piggyBank, $data); $this->linkToAccountIds($piggyBank, $data['accounts']); $this->piggyBankRepository->updateNote($piggyBank, $data['notes']); - $objectGroupTitle = $data['object_group_title'] ?? ''; + $objectGroupTitle = $data['object_group_title'] ?? ''; if ('' !== $objectGroupTitle) { $objectGroup = $this->findOrCreateObjectGroup($objectGroupTitle); if ($objectGroup instanceof ObjectGroup) { @@ -109,7 +115,7 @@ class PiggyBankFactory } } // try also with ID - $objectGroupId = (int)($data['object_group_id'] ?? 0); + $objectGroupId = (int) ($data['object_group_id'] ?? 0); if (0 !== $objectGroupId) { $objectGroup = $this->findObjectGroupById($objectGroupId); if ($objectGroup instanceof ObjectGroup) { @@ -117,7 +123,7 @@ class PiggyBankFactory } } Log::debug('Touch piggy bank'); - $piggyBank->encrypted = false; + $piggyBank->encrypted = false; $piggyBank->save(); $piggyBank->touch(); @@ -130,20 +136,20 @@ class PiggyBankFactory $primaryCurrency = Amount::getPrimaryCurrency(); $currency = null; if (array_key_exists('transaction_currency_code', $data)) { - $currency = $this->currencyRepository->findByCode((string)($data['transaction_currency_code'] ?? '')); + $currency = $this->currencyRepository->findByCode((string) ($data['transaction_currency_code'] ?? '')); } if (array_key_exists('transaction_currency_id', $data)) { - $currency = $this->currencyRepository->find((int)($data['transaction_currency_id'] ?? 0)); + $currency = $this->currencyRepository->find((int) ($data['transaction_currency_id'] ?? 0)); } $currency ??= $primaryCurrency; return $currency; } - public function find(?int $piggyBankId, ?string $piggyBankName): ?PiggyBank + public function find(null|int $piggyBankId, null|string $piggyBankName): null|PiggyBank { - $piggyBankId = (int)$piggyBankId; - $piggyBankName = (string)$piggyBankName; + $piggyBankId = (int) $piggyBankId; + $piggyBankName = (string) $piggyBankName; if ('' === $piggyBankName && 0 === $piggyBankId) { return null; } @@ -153,8 +159,7 @@ class PiggyBankFactory ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id') ->where('accounts.user_id', $this->user->id) ->where('piggy_banks.id', $piggyBankId) - ->first(['piggy_banks.*']) - ; + ->first(['piggy_banks.*']); if (null !== $piggyBank) { return $piggyBank; } @@ -172,20 +177,19 @@ class PiggyBankFactory return null; } - public function findByName(string $name): ?PiggyBank + public function findByName(string $name): null|PiggyBank { return PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id') ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id') ->where('accounts.user_id', $this->user->id) ->where('piggy_banks.name', $name) - ->first(['piggy_banks.*']) - ; + ->first(['piggy_banks.*']); } private function setOrder(PiggyBank $piggyBank, array $data): PiggyBank { $this->resetOrder(); - $order = $this->getMaxOrder() + 1; + $order = $this->getMaxOrder() + 1; if (array_key_exists('order', $data)) { $order = $data['order']; } @@ -193,7 +197,6 @@ class PiggyBankFactory $piggyBank->saveQuietly(); return $piggyBank; - } public function resetOrder(): void @@ -202,13 +205,9 @@ class PiggyBankFactory $set = PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id') ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id') ->where('accounts.user_id', $this->user->id) - ->with( - [ - 'objectGroups', - ] - ) - ->orderBy('piggy_banks.order', 'ASC')->get(['piggy_banks.*']) - ; + ->with(['objectGroups']) + ->orderBy('piggy_banks.order', 'ASC') + ->get(['piggy_banks.*']); $current = 1; foreach ($set as $piggyBank) { if ($piggyBank->order !== $current) { @@ -222,8 +221,7 @@ class PiggyBankFactory private function getMaxOrder(): int { - return (int)$this->piggyBankRepository->getPiggyBanks()->max('order'); - + return (int) $this->piggyBankRepository->getPiggyBanks()->max('order'); } public function linkToAccountIds(PiggyBank $piggyBank, array $accounts): void @@ -237,7 +235,7 @@ class PiggyBankFactory Log::debug(sprintf('Checking account #%d', $account->id)); foreach ($accounts as $info) { Log::debug(sprintf(' Checking other account #%d', $info['account_id'])); - if ((int)$account->id === (int)$info['account_id']) { + if ((int) $account->id === (int) $info['account_id']) { $toBeLinked[$account->id] = ['current_amount' => $account->pivot->current_amount ?? '0']; Log::debug(sprintf('Prefilled for account #%d with amount %s', $account->id, $account->pivot->current_amount ?? '0')); } @@ -247,22 +245,23 @@ class PiggyBankFactory /** @var array $info */ foreach ($accounts as $info) { - $account = $this->accountRepository->find((int)($info['account_id'] ?? 0)); + $account = $this->accountRepository->find((int) ($info['account_id'] ?? 0)); if (!$account instanceof Account) { - Log::debug(sprintf('Account #%d not found, skipping.', (int)($info['account_id'] ?? 0))); + Log::debug(sprintf('Account #%d not found, skipping.', (int) ($info['account_id'] ?? 0))); continue; } Log::debug(sprintf('Working on account #%d', $account->id)); if (array_key_exists('current_amount', $info) && null !== $info['current_amount']) { // an amount is set, first check out if there is a difference with the previous amount. - $previous = $toBeLinked[$account->id]['current_amount'] ?? '0'; - $diff = bcsub($info['current_amount'], $previous); + $previous = $toBeLinked[$account->id]['current_amount'] ?? '0'; + $diff = bcsub($info['current_amount'], $previous); // create event for difference. if (0 !== bccomp($diff, '0')) { // 2025-10-01 for issue #10990 disable this event. Log::debug(sprintf('[a] Will save event for difference %s (previous value was %s)', $diff, $previous)); + // event(new ChangedAmount($piggyBank, $diff, null, null)); } @@ -271,13 +270,14 @@ class PiggyBankFactory } if (array_key_exists('current_amount', $info) && null === $info['current_amount']) { // no amount is set, first check out if there is a difference with the previous amount. - $previous = $toBeLinked[$account->id]['current_amount'] ?? '0'; - $diff = bcsub('0', $previous); + $previous = $toBeLinked[$account->id]['current_amount'] ?? '0'; + $diff = bcsub('0', $previous); // create event for difference. if (0 !== bccomp($diff, '0')) { // 2025-10-01 for issue #10990 disable this event. Log::debug(sprintf('[b] Will save event for difference %s (previous value was %s)', $diff, $previous)); + // event(new ChangedAmount($piggyBank, $diff, null, null)); } @@ -287,6 +287,7 @@ class PiggyBankFactory // create event: Log::debug('linkToAccountIds: Trigger change for positive amount [b].'); + // 2025-10-01 for issue #10990 disable this event. // event(new ChangedAmount($piggyBank, $toBeLinked[$account->id]['current_amount'] ?? '0', null, null)); } diff --git a/app/Factory/RecurrenceFactory.php b/app/Factory/RecurrenceFactory.php index 6147bacd22..c18476462a 100644 --- a/app/Factory/RecurrenceFactory.php +++ b/app/Factory/RecurrenceFactory.php @@ -42,7 +42,7 @@ class RecurrenceFactory use TransactionTypeTrait; private MessageBag $errors; - private User $user; + private User $user; /** * Constructor. @@ -100,22 +100,20 @@ class RecurrenceFactory } $repeatUntilString = $repeatUntil?->format('Y-m-d'); - $recurrence = new Recurrence( - [ - 'user_id' => $this->user->id, - 'user_group_id' => $this->user->user_group_id, - 'transaction_type_id' => $type->id, - 'title' => $title, - 'description' => $description, - 'first_date' => $firstDate?->format('Y-m-d'), - 'first_date_tz' => $firstDate?->format('e'), - 'repeat_until' => $repetitions > 0 ? null : $repeatUntilString, - 'latest_date' => null, - 'repetitions' => $repetitions, - 'apply_rules' => $applyRules, - 'active' => $active, - ] - ); + $recurrence = new Recurrence([ + 'user_id' => $this->user->id, + 'user_group_id' => $this->user->user_group_id, + 'transaction_type_id' => $type->id, + 'title' => $title, + 'description' => $description, + 'first_date' => $firstDate?->format('Y-m-d'), + 'first_date_tz' => $firstDate?->format('e'), + 'repeat_until' => $repetitions > 0 ? null : $repeatUntilString, + 'latest_date' => null, + 'repetitions' => $repetitions, + 'apply_rules' => $applyRules, + 'active' => $active + ]); $recurrence->save(); if (array_key_exists('notes', $data['recurrence'])) { diff --git a/app/Factory/TagFactory.php b/app/Factory/TagFactory.php index e53dde916a..18c8c329f7 100644 --- a/app/Factory/TagFactory.php +++ b/app/Factory/TagFactory.php @@ -35,31 +35,32 @@ use Illuminate\Support\Facades\Log; */ class TagFactory { - private User $user; + private User $user; private UserGroup $userGroup; - public function findOrCreate(string $tag): ?Tag + public function findOrCreate(string $tag): null|Tag { - $tag = trim($tag); + $tag = trim($tag); Log::debug(sprintf('Now in TagFactory::findOrCreate("%s")', $tag)); /** @var null|Tag $dbTag */ - $dbTag = $this->user->tags()->where('tag', $tag)->first(); + $dbTag = $this->user + ->tags() + ->where('tag', $tag) + ->first(); if (null !== $dbTag) { Log::debug(sprintf('Tag exists (#%d), return it.', $dbTag->id)); return $dbTag; } - $newTag = $this->create( - [ - 'tag' => $tag, - 'date' => null, - 'description' => null, - 'latitude' => null, - 'longitude' => null, - 'zoom_level' => null, - ] - ); + $newTag = $this->create([ + 'tag' => $tag, + 'date' => null, + 'description' => null, + 'latitude' => null, + 'longitude' => null, + 'zoom_level' => null + ]); if (!$newTag instanceof Tag) { Log::error(sprintf('TagFactory::findOrCreate("%s") but tag is unexpectedly NULL!', $tag)); @@ -70,30 +71,30 @@ class TagFactory return $newTag; } - public function create(array $data): ?Tag + public function create(array $data): null|Tag { $zoomLevel = 0 === (int) $data['zoom_level'] ? null : (int) $data['zoom_level']; - $latitude = 0.0 === (float) $data['latitude'] ? null : (float) $data['latitude']; // intentional float + $latitude = 0.0 === (float) $data['latitude'] ? null : (float) $data['latitude']; // intentional float $longitude = 0.0 === (float) $data['longitude'] ? null : (float) $data['longitude']; // intentional float - $array = [ - 'user_id' => $this->user->id, - 'user_group_id' => $this->userGroup->id, - 'tag' => trim((string) $data['tag']), - 'tag_mode' => 'nothing', - 'date' => $data['date'], - 'description' => $data['description'], - 'latitude' => null, - 'longitude' => null, - 'zoomLevel' => null, + $array = [ + 'user_id' => $this->user->id, + 'user_group_id' => $this->userGroup->id, + 'tag' => trim((string) $data['tag']), + 'tag_mode' => 'nothing', + 'date' => $data['date'], + 'description' => $data['description'], + 'latitude' => null, + 'longitude' => null, + 'zoomLevel' => null ]; /** @var null|Tag $tag */ - $tag = Tag::create($array); + $tag = Tag::create($array); if (!in_array(null, [$tag, $latitude, $longitude], true)) { // create location object. - $location = new Location(); - $location->latitude = $latitude; - $location->longitude = $longitude; + $location = new Location(); + $location->latitude = $latitude; + $location->longitude = $longitude; $location->zoom_level = $zoomLevel; $location->locatable()->associate($tag); $location->save(); @@ -104,7 +105,7 @@ class TagFactory public function setUser(User $user): void { - $this->user = $user; + $this->user = $user; $this->userGroup = $user->userGroup; } diff --git a/app/Factory/TransactionCurrencyFactory.php b/app/Factory/TransactionCurrencyFactory.php index e57a90c983..4aa98da308 100644 --- a/app/Factory/TransactionCurrencyFactory.php +++ b/app/Factory/TransactionCurrencyFactory.php @@ -40,13 +40,13 @@ class TransactionCurrencyFactory */ public function create(array $data): TransactionCurrency { - $data['code'] = e($data['code']); - $data['symbol'] = e($data['symbol']); - $data['name'] = e($data['name']); - $data['decimal_places'] = (int)$data['decimal_places']; + $data['code'] = e($data['code']); + $data['symbol'] = e($data['symbol']); + $data['name'] = e($data['name']); + $data['decimal_places'] = (int) $data['decimal_places']; // if the code already exists (deleted) // force delete it and then create the transaction: - $count = TransactionCurrency::withTrashed()->whereCode($data['code'])->count(); + $count = TransactionCurrency::withTrashed()->whereCode($data['code'])->count(); if (1 === $count) { $old = TransactionCurrency::withTrashed()->whereCode($data['code'])->first(); $old->forceDelete(); @@ -55,15 +55,13 @@ class TransactionCurrencyFactory try { /** @var TransactionCurrency $result */ - $result = TransactionCurrency::create( - [ - 'name' => $data['name'], - 'code' => $data['code'], - 'symbol' => $data['symbol'], - 'decimal_places' => $data['decimal_places'], - 'enabled' => false, - ] - ); + $result = TransactionCurrency::create([ + 'name' => $data['name'], + 'code' => $data['code'], + 'symbol' => $data['symbol'], + 'decimal_places' => $data['decimal_places'], + 'enabled' => false + ]); } catch (QueryException $e) { $result = null; Log::error(sprintf('Could not create new currency: %s', $e->getMessage())); @@ -75,10 +73,10 @@ class TransactionCurrencyFactory return $result; } - public function find(?int $currencyId, ?string $currencyCode): ?TransactionCurrency + public function find(null|int $currencyId, null|string $currencyCode): null|TransactionCurrency { $currencyCode = e($currencyCode); - $currencyId = (int)$currencyId; + $currencyId = (int) $currencyId; $currency = null; if ('' === $currencyCode && 0 === $currencyId) { diff --git a/app/Factory/TransactionFactory.php b/app/Factory/TransactionFactory.php index 96fcce547f..900d7a1b12 100644 --- a/app/Factory/TransactionFactory.php +++ b/app/Factory/TransactionFactory.php @@ -31,29 +31,29 @@ use FireflyIII\Models\TransactionCurrency; use FireflyIII\Models\TransactionJournal; use FireflyIII\Rules\UniqueIban; use FireflyIII\Services\Internal\Update\AccountUpdateService; -use Illuminate\Database\QueryException; -use Illuminate\Support\Facades\Validator; -use Illuminate\Support\Facades\Log; use FireflyIII\Support\Facades\Steam; +use Illuminate\Database\QueryException; +use Illuminate\Support\Facades\Log; +use Illuminate\Support\Facades\Validator; /** * Class TransactionFactory */ class TransactionFactory { - private Account $account; - private array $accountInformation = []; - private TransactionCurrency $currency; - private ?TransactionCurrency $foreignCurrency = null; - private TransactionJournal $journal; - private bool $reconciled = false; + private Account $account; + private array $accountInformation = []; + private TransactionCurrency $currency; + private null|TransactionCurrency $foreignCurrency = null; + private TransactionJournal $journal; + private bool $reconciled = false; /** * Create transaction with negative amount (for source accounts). * * @throws FireflyException */ - public function createNegative(string $amount, ?string $foreignAmount): Transaction + public function createNegative(string $amount, null|string $foreignAmount): Transaction { if ('' === $foreignAmount) { $foreignAmount = null; @@ -68,7 +68,7 @@ class TransactionFactory /** * @throws FireflyException */ - private function create(string $amount, ?string $foreignAmount): Transaction + private function create(string $amount, null|string $foreignAmount): Transaction { if ('' === $foreignAmount) { $foreignAmount = null; @@ -82,7 +82,7 @@ class TransactionFactory 'amount' => $amount, 'foreign_amount' => null, 'foreign_currency_id' => null, - 'identifier' => 0, + 'identifier' => 0 ]; try { @@ -99,23 +99,19 @@ class TransactionFactory throw new FireflyException('Transaction is NULL.'); } - Log::debug( - sprintf( - 'Created transaction #%d (%s %s, account %s), part of journal #%d', - $result->id, - $this->currency->code, - $amount, - $this->account->name, - $this->journal->id - ) - ); + Log::debug(sprintf( + 'Created transaction #%d (%s %s, account %s), part of journal #%d', + $result->id, + $this->currency->code, + $amount, + $this->account->name, + $this->journal->id + )); // do foreign currency thing: add foreign currency info to $one and $two if necessary. - if ($this->foreignCurrency instanceof TransactionCurrency - && null !== $foreignAmount - && $this->foreignCurrency->id !== $this->currency->id) { + if ($this->foreignCurrency instanceof TransactionCurrency && null !== $foreignAmount && $this->foreignCurrency->id !== $this->currency->id) { $result->foreign_currency_id = $this->foreignCurrency->id; - $result->foreign_amount = $foreignAmount; + $result->foreign_amount = $foreignAmount; } $result->save(); @@ -146,9 +142,10 @@ class TransactionFactory return; } // validate info: - $validator = Validator::make(['iban' => $this->accountInformation['iban']], [ - 'iban' => ['required', new UniqueIban($this->account, $this->account->accountType->type)], - ]); + $validator = Validator::make(['iban' => $this->accountInformation['iban']], ['iban' => [ + 'required', + new UniqueIban($this->account, $this->account->accountType->type) + ]]); if ($validator->fails()) { Log::debug('Invalid or non-unique IBAN, will not update.'); @@ -156,7 +153,7 @@ class TransactionFactory } Log::debug('Will update account with IBAN information.'); - $service = app(AccountUpdateService::class); + $service = app(AccountUpdateService::class); $service->update($this->account, ['iban' => $this->accountInformation['iban']]); } @@ -165,7 +162,7 @@ class TransactionFactory * * @throws FireflyException */ - public function createPositive(string $amount, ?string $foreignAmount): Transaction + public function createPositive(string $amount, null|string $foreignAmount): Transaction { if ('' === $foreignAmount) { $foreignAmount = null; @@ -195,7 +192,7 @@ class TransactionFactory /** * @param null|TransactionCurrency $foreignCurrency |null */ - public function setForeignCurrency(?TransactionCurrency $foreignCurrency): void + public function setForeignCurrency(null|TransactionCurrency $foreignCurrency): void { $this->foreignCurrency = $foreignCurrency; } diff --git a/app/Factory/TransactionGroupFactory.php b/app/Factory/TransactionGroupFactory.php index 11bde5fade..a9c0e96cf7 100644 --- a/app/Factory/TransactionGroupFactory.php +++ b/app/Factory/TransactionGroupFactory.php @@ -37,8 +37,8 @@ use Illuminate\Support\Facades\Log; class TransactionGroupFactory { private readonly TransactionJournalFactory $journalFactory; - private User $user; - private UserGroup $userGroup; + private User $user; + private UserGroup $userGroup; /** * TransactionGroupFactory constructor. @@ -68,8 +68,8 @@ class TransactionGroupFactory throw new DuplicateTransactionException($e->getMessage(), 0, $e); } - $title = $data['group_title'] ?? null; - $title = '' === $title ? null : $title; + $title = $data['group_title'] ?? null; + $title = '' === $title ? null : $title; if (null !== $title) { $title = substr((string) $title, 0, 1000); @@ -78,7 +78,7 @@ class TransactionGroupFactory throw new FireflyException('Created zero transaction journals.'); } - $group = new TransactionGroup(); + $group = new TransactionGroup(); $group->user()->associate($this->user); $group->userGroup()->associate($this->userGroup); $group->title = $title; @@ -94,7 +94,7 @@ class TransactionGroupFactory */ public function setUser(User $user): void { - $this->user = $user; + $this->user = $user; $this->userGroup = $user->userGroup; } diff --git a/app/Factory/TransactionJournalFactory.php b/app/Factory/TransactionJournalFactory.php index 437042c0e0..d9d3cf17ec 100644 --- a/app/Factory/TransactionJournalFactory.php +++ b/app/Factory/TransactionJournalFactory.php @@ -48,6 +48,7 @@ use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface; use FireflyIII\Repositories\TransactionType\TransactionTypeRepositoryInterface; use FireflyIII\Services\Internal\Destroy\JournalDestroyService; use FireflyIII\Services\Internal\Support\JournalServiceTrait; +use FireflyIII\Support\Facades\Amount; use FireflyIII\Support\Facades\FireflyConfig; use FireflyIII\Support\NullArrayObject; use FireflyIII\User; @@ -55,7 +56,6 @@ use FireflyIII\Validation\AccountValidator; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; use JsonException; -use FireflyIII\Support\Facades\Amount; use function Safe\json_encode; @@ -68,17 +68,17 @@ class TransactionJournalFactory { use JournalServiceTrait; - private AccountRepositoryInterface $accountRepository; - private AccountValidator $accountValidator; - private BillRepositoryInterface $billRepository; - private CurrencyRepositoryInterface $currencyRepository; - private bool $errorOnHash = false; - private array $fields; - private PiggyBankEventFactory $piggyEventFactory; - private PiggyBankRepositoryInterface $piggyRepository; + private AccountRepositoryInterface $accountRepository; + private AccountValidator $accountValidator; + private BillRepositoryInterface $billRepository; + private CurrencyRepositoryInterface $currencyRepository; + private bool $errorOnHash = false; + private array $fields; + private PiggyBankEventFactory $piggyEventFactory; + private PiggyBankRepositoryInterface $piggyRepository; private TransactionTypeRepositoryInterface $typeRepository; - private User $user; - private UserGroup $userGroup; + private User $user; + private UserGroup $userGroup; /** * Constructor. @@ -87,17 +87,17 @@ class TransactionJournalFactory */ public function __construct() { - $this->fields = config('firefly.journal_meta_fields'); + $this->fields = config('firefly.journal_meta_fields'); $this->currencyRepository = app(CurrencyRepositoryInterface::class); - $this->typeRepository = app(TransactionTypeRepositoryInterface::class); - $this->billRepository = app(BillRepositoryInterface::class); - $this->budgetRepository = app(BudgetRepositoryInterface::class); + $this->typeRepository = app(TransactionTypeRepositoryInterface::class); + $this->billRepository = app(BillRepositoryInterface::class); + $this->budgetRepository = app(BudgetRepositoryInterface::class); $this->categoryRepository = app(CategoryRepositoryInterface::class); - $this->piggyRepository = app(PiggyBankRepositoryInterface::class); - $this->piggyEventFactory = app(PiggyBankEventFactory::class); - $this->tagFactory = app(TagFactory::class); - $this->accountValidator = app(AccountValidator::class); - $this->accountRepository = app(AccountRepositoryInterface::class); + $this->piggyRepository = app(PiggyBankRepositoryInterface::class); + $this->piggyEventFactory = app(PiggyBankEventFactory::class); + $this->tagFactory = app(TagFactory::class); + $this->accountValidator = app(AccountValidator::class); + $this->accountRepository = app(AccountRepositoryInterface::class); } /** @@ -110,7 +110,7 @@ class TransactionJournalFactory { Log::debug('Now in TransactionJournalFactory::create()'); // convert to special object. - $dataObject = new NullArrayObject($data); + $dataObject = new NullArrayObject($data); Log::debug('Start of TransactionJournalFactory::create()'); $collection = new Collection(); @@ -161,7 +161,7 @@ class TransactionJournalFactory * * @SuppressWarnings("PHPMD.ExcessiveMethodLength") */ - private function createJournal(NullArrayObject $row): ?TransactionJournal + private function createJournal(NullArrayObject $row): null|TransactionJournal { Log::debug('Now in TransactionJournalFactory::createJournal()'); $row['import_hash_v2'] = $this->hashArray($row); @@ -169,18 +169,18 @@ class TransactionJournalFactory $this->errorIfDuplicate($row['import_hash_v2']); // Some basic fields - $type = $this->typeRepository->findTransactionType(null, $row['type']); - $carbon = $row['date'] ?? today(config('app.timezone')); - $order = $row['order'] ?? 0; + $type = $this->typeRepository->findTransactionType(null, $row['type']); + $carbon = $row['date'] ?? today(config('app.timezone')); + $order = $row['order'] ?? 0; Log::debug('Find currency or return default.'); - $currency = $this->currencyRepository->findCurrency((int) $row['currency_id'], $row['currency_code']); + $currency = $this->currencyRepository->findCurrency((int) $row['currency_id'], $row['currency_code']); Log::debug('Find foreign currency or return NULL.'); - $foreignCurrency = $this->currencyRepository->findCurrencyNull($row['foreign_currency_id'], $row['foreign_currency_code']); - $bill = $this->billRepository->findBill((int) $row['bill_id'], $row['bill_name']); - $billId = TransactionTypeEnum::WITHDRAWAL->value === $type->type && $bill instanceof Bill ? $bill->id : null; - $description = (string) $row['description']; + $foreignCurrency = $this->currencyRepository->findCurrencyNull($row['foreign_currency_id'], $row['foreign_currency_code']); + $bill = $this->billRepository->findBill((int) $row['bill_id'], $row['bill_name']); + $billId = TransactionTypeEnum::WITHDRAWAL->value === $type->type && $bill instanceof Bill ? $bill->id : null; + $description = (string) $row['description']; // Manipulate basic fields $carbon->setTimezone(config('app.timezone')); @@ -202,27 +202,27 @@ class TransactionJournalFactory } /** create or get source and destination accounts */ - $sourceInfo = [ + $sourceInfo = [ 'id' => $row['source_id'], 'name' => $row['source_name'], 'iban' => $row['source_iban'], 'number' => $row['source_number'], 'bic' => $row['source_bic'], - 'currency_id' => $currency->id, + 'currency_id' => $currency->id ]; - $destInfo = [ + $destInfo = [ 'id' => $row['destination_id'], 'name' => $row['destination_name'], 'iban' => $row['destination_iban'], 'number' => $row['destination_number'], 'bic' => $row['destination_bic'], - 'currency_id' => $currency->id, + 'currency_id' => $currency->id ]; Log::debug('Source info:', $sourceInfo); Log::debug('Destination info:', $destInfo); - $destinationAccount = null; - $sourceAccount = null; + $destinationAccount = null; + $sourceAccount = null; if (TransactionTypeEnum::DEPOSIT->value === $type->type) { Log::debug('Transaction type is deposit, start with destination first.'); $destinationAccount = $this->getAccount($type->type, 'destination', $destInfo); @@ -247,34 +247,38 @@ class TransactionJournalFactory [$sourceAccount, $destinationAccount] = $this->reconciliationSanityCheck($sourceAccount, $destinationAccount); } - $currency = $this->getCurrencyByAccount($type->type, $currency, $sourceAccount, $destinationAccount); - $foreignCurrency = $this->compareCurrencies($currency, $foreignCurrency); - $foreignCurrency = $this->getForeignByAccount($type->type, $foreignCurrency, $destinationAccount); - $description = $this->getDescription($description); + $currency = $this->getCurrencyByAccount($type->type, $currency, $sourceAccount, $destinationAccount); + $foreignCurrency = $this->compareCurrencies($currency, $foreignCurrency); + $foreignCurrency = $this->getForeignByAccount($type->type, $foreignCurrency, $destinationAccount); + $description = $this->getDescription($description); - Log::debug(sprintf('Currency is #%d "%s", foreign currency is #%d "%s"', $currency->id, $currency->code, $foreignCurrency?->id, $foreignCurrency?->code)); + Log::debug(sprintf( + 'Currency is #%d "%s", foreign currency is #%d "%s"', + $currency->id, + $currency->code, + $foreignCurrency?->id, + $foreignCurrency?->code + )); Log::debug(sprintf('Date: %s (%s)', $carbon->toW3cString(), $carbon->getTimezone()->getName())); /** Create a basic journal. */ - $journal = TransactionJournal::create( - [ - 'user_id' => $this->user->id, - 'user_group_id' => $this->userGroup->id, - 'transaction_type_id' => $type->id, - 'bill_id' => $billId, - 'transaction_currency_id' => $currency->id, - 'description' => substr($description, 0, 1000), - 'date' => $carbon, - 'date_tz' => $carbon->format('e'), - 'order' => $order, - 'tag_count' => 0, - 'completed' => 0, - ] - ); + $journal = TransactionJournal::create([ + 'user_id' => $this->user->id, + 'user_group_id' => $this->userGroup->id, + 'transaction_type_id' => $type->id, + 'bill_id' => $billId, + 'transaction_currency_id' => $currency->id, + 'description' => substr($description, 0, 1000), + 'date' => $carbon, + 'date_tz' => $carbon->format('e'), + 'order' => $order, + 'tag_count' => 0, + 'completed' => 0 + ]); Log::debug(sprintf('Created new journal #%d: "%s"', $journal->id, $journal->description)); /** Create two transactions. */ - $transactionFactory = app(TransactionFactory::class); + $transactionFactory = app(TransactionFactory::class); $transactionFactory->setJournal($journal); $transactionFactory->setAccount($sourceAccount); $transactionFactory->setCurrency($currency); @@ -292,7 +296,7 @@ class TransactionJournalFactory } /** @var TransactionFactory $transactionFactory */ - $transactionFactory = app(TransactionFactory::class); + $transactionFactory = app(TransactionFactory::class); $transactionFactory->setJournal($journal); $transactionFactory->setAccount($destinationAccount); $transactionFactory->setAccountInformation($destInfo); @@ -304,9 +308,11 @@ class TransactionJournalFactory // Firefly III will save the foreign currency information in such a way that both // asset accounts can look at the "amount" and "transaction_currency_id" column and // see the currency they expect to see. - $amount = (string) $row['amount']; - $foreignAmount = (string) $row['foreign_amount']; - if ($foreignCurrency instanceof TransactionCurrency && $foreignCurrency->id !== $currency->id + $amount = (string) $row['amount']; + $foreignAmount = (string) $row['foreign_amount']; + if ( + $foreignCurrency instanceof TransactionCurrency + && $foreignCurrency->id !== $currency->id && (TransactionTypeEnum::TRANSFER->value === $type->type || $this->isBetweenAssetAndLiability($sourceAccount, $destinationAccount)) ) { $transactionFactory->setCurrency($foreignCurrency); @@ -325,7 +331,7 @@ class TransactionJournalFactory throw new FireflyException($e->getMessage(), 0, $e); } - $journal->completed = true; + $journal->completed = true; $journal->save(); $this->storeBudget($journal, $row); $this->storeCategory($journal, $row); @@ -350,7 +356,7 @@ class TransactionJournalFactory Log::error(sprintf('Could not encode dataRow: %s', $e->getMessage())); $json = microtime(); } - $hash = hash('sha256', $json); + $hash = hash('sha256', $json); Log::debug(sprintf('The hash is: %s', $hash), $dataRow); return $hash; @@ -378,8 +384,7 @@ class TransactionJournalFactory ->where('transaction_journals.user_id', $this->user->id) ->where('data', json_encode($hash, JSON_THROW_ON_ERROR)) ->with(['transactionJournal', 'transactionJournal.transactionGroup']) - ->first(['journal_meta.*']) - ; + ->first(['journal_meta.*']); if (null !== $result) { Log::warning(sprintf('Found a duplicate in errorIfDuplicate because hash %s is not unique!', $hash)); $journal = $result->transactionJournal()->withTrashed()->first(); @@ -396,18 +401,18 @@ class TransactionJournalFactory private function validateAccounts(NullArrayObject $data): void { Log::debug(sprintf('Now in %s', __METHOD__)); - $transactionType = $data['type'] ?? 'invalid'; + $transactionType = $data['type'] ?? 'invalid'; $this->accountValidator->setUser($this->user); $this->accountValidator->setTransactionType($transactionType); // validate source account. - $array = [ + $array = [ 'id' => null !== $data['source_id'] ? (int) $data['source_id'] : null, 'name' => null !== $data['source_name'] ? (string) $data['source_name'] : null, 'iban' => null !== $data['source_iban'] ? (string) $data['source_iban'] : null, - 'number' => null !== $data['source_number'] ? (string) $data['source_number'] : null, + 'number' => null !== $data['source_number'] ? (string) $data['source_number'] : null ]; - $validSource = $this->accountValidator->validateSource($array); + $validSource = $this->accountValidator->validateSource($array); // do something with result: if (false === $validSource) { @@ -416,11 +421,11 @@ class TransactionJournalFactory Log::debug('Source seems valid.'); // validate destination account - $array = [ + $array = [ 'id' => null !== $data['destination_id'] ? (int) $data['destination_id'] : null, 'name' => null !== $data['destination_name'] ? (string) $data['destination_name'] : null, 'iban' => null !== $data['destination_iban'] ? (string) $data['destination_iban'] : null, - 'number' => null !== $data['destination_number'] ? (string) $data['destination_number'] : null, + 'number' => null !== $data['destination_number'] ? (string) $data['destination_number'] : null ]; $validDestination = $this->accountValidator->validateDestination($array); @@ -435,7 +440,7 @@ class TransactionJournalFactory */ public function setUser(User $user): void { - $this->user = $user; + $this->user = $user; $this->userGroup = $user->userGroup; $this->currencyRepository->setUser($this->user); $this->tagFactory->setUser($user); @@ -446,7 +451,7 @@ class TransactionJournalFactory $this->accountRepository->setUser($this->user); } - private function reconciliationSanityCheck(?Account $sourceAccount, ?Account $destinationAccount): array + private function reconciliationSanityCheck(null|Account $sourceAccount, null|Account $destinationAccount): array { Log::debug(sprintf('Now in %s', __METHOD__)); if ($sourceAccount instanceof Account && $destinationAccount instanceof Account) { @@ -469,7 +474,7 @@ class TransactionJournalFactory return [$account, $destinationAccount]; } - Log::debug('Unused fallback'); // @phpstan-ignore-line + Log::debug('Unused fallback'); // @phpstan-ignore-line return [$sourceAccount, $destinationAccount]; } @@ -477,7 +482,7 @@ class TransactionJournalFactory /** * @throws FireflyException */ - private function getCurrencyByAccount(string $type, ?TransactionCurrency $currency, Account $source, Account $destination): TransactionCurrency + private function getCurrencyByAccount(string $type, null|TransactionCurrency $currency, Account $source, Account $destination): TransactionCurrency { Log::debug('Now in getCurrencyByAccount()'); @@ -490,12 +495,12 @@ class TransactionJournalFactory } return match ($type) { - default => $this->getCurrency($currency, $source), - TransactionTypeEnum::DEPOSIT->value => $this->getCurrency($currency, $destination), + default => $this->getCurrency($currency, $source), + TransactionTypeEnum::DEPOSIT->value => $this->getCurrency($currency, $destination) }; } - private function getCurrency(?TransactionCurrency $currency, Account $account): TransactionCurrency + private function getCurrency(null|TransactionCurrency $currency, Account $account): TransactionCurrency { Log::debug(sprintf('Now in getCurrency(#%d, "%s")', $currency?->id, $account->name)); @@ -505,7 +510,7 @@ class TransactionJournalFactory // return user's default: return Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); } - $result = $preference ?? $currency; + $result = $preference ?? $currency; Log::debug(sprintf('Currency is now #%d (%s) because of account #%d (%s)', $result->id, $result->code, $account->id, $account->name)); return $result; @@ -514,7 +519,7 @@ class TransactionJournalFactory /** * Set foreign currency to NULL if it's the same as the normal currency: */ - private function compareCurrencies(?TransactionCurrency $currency, ?TransactionCurrency $foreignCurrency): ?TransactionCurrency + private function compareCurrencies(null|TransactionCurrency $currency, null|TransactionCurrency $foreignCurrency): null|TransactionCurrency { Log::debug(sprintf('Now in compareCurrencies("%s", "%s")', $currency?->code, $foreignCurrency?->code)); if (!$currency instanceof TransactionCurrency) { @@ -530,7 +535,7 @@ class TransactionJournalFactory /** * @throws FireflyException */ - private function getForeignByAccount(string $type, ?TransactionCurrency $foreignCurrency, Account $destination): ?TransactionCurrency + private function getForeignByAccount(string $type, null|TransactionCurrency $foreignCurrency, Account $destination): null|TransactionCurrency { Log::debug(sprintf('Now in getForeignByAccount("%s", #%d, "%s")', $type, $foreignCurrency?->id, $destination->name)); if (TransactionTypeEnum::TRANSFER->value === $type) { @@ -595,11 +600,7 @@ class TransactionJournalFactory protected function storeMeta(TransactionJournal $journal, NullArrayObject $data, string $field): void { - $set = [ - 'journal' => $journal, - 'name' => $field, - 'data' => (string) ($data[$field] ?? ''), - ]; + $set = ['journal' => $journal, 'name' => $field, 'data' => (string) ($data[$field] ?? '')]; if ($data[$field] instanceof Carbon) { $data[$field]->setTimezone(config('app.timezone')); Log::debug(sprintf('%s Date: %s (%s)', $field, $data[$field], $data[$field]->timezone->getName())); @@ -616,9 +617,9 @@ class TransactionJournalFactory private function storeLocation(TransactionJournal $journal, NullArrayObject $data): void { if (!in_array(null, [$data['longitude'], $data['latitude'], $data['zoom_level']], true)) { - $location = new Location(); - $location->longitude = $data['longitude']; - $location->latitude = $data['latitude']; + $location = new Location(); + $location->longitude = $data['longitude']; + $location->latitude = $data['latitude']; $location->zoom_level = $data['zoom_level']; $location->locatable()->associate($journal); $location->save(); diff --git a/app/Factory/TransactionJournalMetaFactory.php b/app/Factory/TransactionJournalMetaFactory.php index bef9804fc3..4f3573ea06 100644 --- a/app/Factory/TransactionJournalMetaFactory.php +++ b/app/Factory/TransactionJournalMetaFactory.php @@ -33,13 +33,13 @@ use Illuminate\Support\Facades\Log; */ class TransactionJournalMetaFactory { - public function updateOrCreate(array $data): ?TransactionJournalMeta + public function updateOrCreate(array $data): null|TransactionJournalMeta { // Log::debug('In updateOrCreate()'); - $value = $data['data']; + $value = $data['data']; /** @var null|TransactionJournalMeta $entry */ - $entry = $data['journal']->transactionJournalMeta()->where('name', $data['name'])->first(); + $entry = $data['journal']->transactionJournalMeta()->where('name', $data['name'])->first(); if (null === $value && null !== $entry) { // Log::debug('Value is empty, delete meta value.'); $entry->delete(); @@ -51,7 +51,7 @@ class TransactionJournalMetaFactory Log::debug('Is a carbon object.'); $value = $data['data']->toW3cString(); } - if ('' === (string)$value) { + if ('' === (string) $value) { // Log::debug('Is an empty string.'); // don't store blank strings. if (null !== $entry) { @@ -65,7 +65,7 @@ class TransactionJournalMetaFactory if (null === $entry) { // Log::debug('Will create new object.'); Log::debug(sprintf('Going to create new meta-data entry to store "%s".', $data['name'])); - $entry = new TransactionJournalMeta(); + $entry = new TransactionJournalMeta(); $entry->transactionJournal()->associate($data['journal']); $entry->name = $data['name']; } diff --git a/app/Factory/TransactionTypeFactory.php b/app/Factory/TransactionTypeFactory.php index b7bde85c90..df0367f809 100644 --- a/app/Factory/TransactionTypeFactory.php +++ b/app/Factory/TransactionTypeFactory.php @@ -31,7 +31,7 @@ use FireflyIII\Models\TransactionType; */ class TransactionTypeFactory { - public function find(string $type): ?TransactionType + public function find(string $type): null|TransactionType { return TransactionType::whereType(ucfirst($type))->first(); } diff --git a/app/Factory/UserGroupFactory.php b/app/Factory/UserGroupFactory.php index d392b69832..ec93b97b6d 100644 --- a/app/Factory/UserGroupFactory.php +++ b/app/Factory/UserGroupFactory.php @@ -40,20 +40,20 @@ class UserGroupFactory */ public function create(array $data): UserGroup { - $userGroup = new UserGroup(); - $userGroup->title = $data['title']; + $userGroup = new UserGroup(); + $userGroup->title = $data['title']; $userGroup->save(); // grab the OWNER role: - $role = UserRole::whereTitle(UserRoleEnum::OWNER->value)->first(); + $role = UserRole::whereTitle(UserRoleEnum::OWNER->value)->first(); if (null === $role) { throw new FireflyException('Role "owner" does not exist.'); } // make user member: - $groupMembership = new GroupMembership(); + $groupMembership = new GroupMembership(); $groupMembership->user_group_id = $userGroup->id; - $groupMembership->user_id = $data['user']->id; - $groupMembership->user_role_id = $role->id; + $groupMembership->user_id = $data['user']->id; + $groupMembership->user_role_id = $role->id; $groupMembership->save(); return $userGroup; diff --git a/app/Generator/Chart/Basic/ChartJsGenerator.php b/app/Generator/Chart/Basic/ChartJsGenerator.php index d4faf4b554..b167072e5d 100644 --- a/app/Generator/Chart/Basic/ChartJsGenerator.php +++ b/app/Generator/Chart/Basic/ChartJsGenerator.php @@ -38,29 +38,24 @@ class ChartJsGenerator implements GeneratorInterface */ public function multiCurrencyPieChart(array $data): array { - $chartData = [ - 'datasets' => [ - 0 => [], - ], - 'labels' => [], - ]; + $chartData = ['datasets' => [0 => []], 'labels' => []]; - $amounts = array_column($data, 'amount'); - $next = next($amounts); - $sortFlag = SORT_ASC; + $amounts = array_column($data, 'amount'); + $next = next($amounts); + $sortFlag = SORT_ASC; if (!is_bool($next) && 1 === bccomp((string) $next, '0')) { $sortFlag = SORT_DESC; } array_multisort($amounts, $sortFlag, $data); unset($next, $sortFlag, $amounts); - $index = 0; + $index = 0; foreach ($data as $key => $valueArray) { // make larger than 0 - $chartData['datasets'][0]['data'][] = Steam::positive((string) $valueArray['amount']); + $chartData['datasets'][0]['data'][] = Steam::positive((string) $valueArray['amount']); $chartData['datasets'][0]['backgroundColor'][] = ChartColour::getColour($index); $chartData['datasets'][0]['currency_symbol'][] = $valueArray['currency_symbol']; - $chartData['labels'][] = $key; + $chartData['labels'][] = $key; ++$index; } @@ -100,25 +95,21 @@ class ChartJsGenerator implements GeneratorInterface public function multiSet(array $data): array { reset($data); - $first = current($data); + $first = current($data); if (!is_array($first)) { return []; } - $labels = is_array($first['entries']) ? array_keys($first['entries']) : []; + $labels = is_array($first['entries']) ? array_keys($first['entries']) : []; $chartData = [ - 'count' => count($data), - 'labels' => $labels, // take ALL labels from the first set. - 'datasets' => [], + 'count' => count($data), + 'labels' => $labels, // take ALL labels from the first set. + 'datasets' => [] ]; unset($first, $labels); foreach ($data as $set) { - $currentSet = [ - 'label' => $set['label'] ?? '(no label)', - 'type' => $set['type'] ?? 'line', - 'data' => array_values($set['entries']), - ]; + $currentSet = ['label' => $set['label'] ?? '(no label)', 'type' => $set['type'] ?? 'line', 'data' => array_values($set['entries'])]; if (array_key_exists('yAxisID', $set)) { $currentSet['yAxisID'] = $set['yAxisID']; } @@ -144,30 +135,25 @@ class ChartJsGenerator implements GeneratorInterface */ public function pieChart(array $data): array { - $chartData = [ - 'datasets' => [ - 0 => [], - ], - 'labels' => [], - ]; + $chartData = ['datasets' => [0 => []], 'labels' => []]; // sort by value, keep keys. // different sort when values are positive and when they're negative. asort($data); - $next = next($data); + $next = next($data); if (!is_bool($next) && 1 === bccomp((string) $next, '0')) { // next is positive, sort other way around. arsort($data); } unset($next); - $index = 0; + $index = 0; foreach ($data as $key => $value) { // make larger than 0 - $chartData['datasets'][0]['data'][] = Steam::positive((string) $value); + $chartData['datasets'][0]['data'][] = Steam::positive((string) $value); $chartData['datasets'][0]['backgroundColor'][] = ChartColour::getColour($index); - $chartData['labels'][] = $key; + $chartData['labels'][] = $key; ++$index; } @@ -182,14 +168,9 @@ class ChartJsGenerator implements GeneratorInterface public function singleSet(string $setLabel, array $data): array { return [ - 'count' => 1, - 'labels' => array_keys($data), // take ALL labels from the first set. - 'datasets' => [ - [ - 'label' => $setLabel, - 'data' => array_values($data), - ], - ], + 'count' => 1, + 'labels' => array_keys($data), // take ALL labels from the first set. + 'datasets' => [['label' => $setLabel, 'data' => array_values($data)]] ]; } } diff --git a/app/Generator/Report/Account/MonthReportGenerator.php b/app/Generator/Report/Account/MonthReportGenerator.php index 64cc958681..105c89fbc3 100644 --- a/app/Generator/Report/Account/MonthReportGenerator.php +++ b/app/Generator/Report/Account/MonthReportGenerator.php @@ -27,8 +27,8 @@ use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Generator\Report\ReportGeneratorInterface; use Illuminate\Support\Collection; -use Throwable; use Illuminate\Support\Facades\Log; +use Throwable; /** * Class MonthReportGenerator. @@ -36,9 +36,9 @@ use Illuminate\Support\Facades\Log; class MonthReportGenerator implements ReportGeneratorInterface { private Collection $accounts; - private Carbon $end; + private Carbon $end; private Collection $expense; - private Carbon $start; + private Carbon $start; /** * Generate the report. @@ -53,11 +53,16 @@ class MonthReportGenerator implements ReportGeneratorInterface $preferredPeriod = $this->preferredPeriod(); try { - $result = view('reports.double.report', ['accountIds' => $accountIds, 'reportType' => $reportType, 'doubleIds' => $doubleIds, 'preferredPeriod' => $preferredPeriod]) - ->with('start', $this->start)->with('end', $this->end) + $result = view('reports.double.report', [ + 'accountIds' => $accountIds, + 'reportType' => $reportType, + 'doubleIds' => $doubleIds, + 'preferredPeriod' => $preferredPeriod + ]) + ->with('start', $this->start) + ->with('end', $this->end) ->with('doubles', $this->expense) - ->render() - ; + ->render(); } catch (Throwable $e) { Log::error(sprintf('Cannot render reports.double.report: %s', $e->getMessage())); Log::error($e->getTraceAsString()); diff --git a/app/Generator/Report/Audit/MonthReportGenerator.php b/app/Generator/Report/Audit/MonthReportGenerator.php index 66db8cfed9..1e1c166b02 100644 --- a/app/Generator/Report/Audit/MonthReportGenerator.php +++ b/app/Generator/Report/Audit/MonthReportGenerator.php @@ -31,11 +31,11 @@ use FireflyIII\Helpers\Collector\GroupCollectorInterface; use FireflyIII\Models\Account; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Journal\JournalRepositoryInterface; +use FireflyIII\Support\Facades\Amount; use FireflyIII\Support\Facades\Steam; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; use Throwable; -use FireflyIII\Support\Facades\Amount; /** * Class MonthReportGenerator. @@ -43,8 +43,8 @@ use FireflyIII\Support\Facades\Amount; class MonthReportGenerator implements ReportGeneratorInterface { private Collection $accounts; - private Carbon $end; - private Carbon $start; + private Carbon $end; + private Carbon $start; /** * Generates the report. @@ -53,8 +53,8 @@ class MonthReportGenerator implements ReportGeneratorInterface */ public function generate(): string { - $auditData = []; - $dayBefore = clone $this->start; + $auditData = []; + $dayBefore = clone $this->start; // set date to subday + end-of-day for account balance. so it is at $date 23:59:59 $dayBefore->subDay()->endOfDay(); @@ -62,7 +62,7 @@ class MonthReportGenerator implements ReportGeneratorInterface /** @var Account $account */ foreach ($this->accounts as $account) { // balance the day before: - $id = $account->id; + $id = $account->id; $auditData[$id] = $this->getAuditReport($account, $dayBefore); } @@ -97,14 +97,21 @@ class MonthReportGenerator implements ReportGeneratorInterface 'process_date', 'due_date', 'payment_date', - 'invoice_date', + 'invoice_date' ]; try { - $result = view('reports.audit.report', ['reportType' => $reportType, 'accountIds' => $accountIds, 'auditData' => $auditData, 'hideable' => $hideable, 'defaultShow' => $defaultShow]) - ->with('start', $this->start)->with('end', $this->end)->with('accounts', $this->accounts) - ->render() - ; + $result = view('reports.audit.report', [ + 'reportType' => $reportType, + 'accountIds' => $accountIds, + 'auditData' => $auditData, + 'hideable' => $hideable, + 'defaultShow' => $defaultShow + ]) + ->with('start', $this->start) + ->with('end', $this->end) + ->with('accounts', $this->accounts) + ->render(); } catch (Throwable $e) { Log::error(sprintf('Cannot render reports.audit.report: %s', $e->getMessage())); Log::error($e->getTraceAsString()); @@ -132,25 +139,30 @@ class MonthReportGenerator implements ReportGeneratorInterface $journalRepository->setUser($account->user); /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); - $collector->setAccounts(new Collection()->push($account))->setRange($this->start, $this->end)->withAccountInformation() - ->withBudgetInformation()->withCategoryInformation()->withBillInformation()->withNotes() - ; - $journals = $collector->getExtractedJournals(); - $journals = array_reverse($journals, true); + $collector = app(GroupCollectorInterface::class); + $collector + ->setAccounts(new Collection()->push($account)) + ->setRange($this->start, $this->end) + ->withAccountInformation() + ->withBudgetInformation() + ->withCategoryInformation() + ->withBillInformation() + ->withNotes(); + $journals = $collector->getExtractedJournals(); + $journals = array_reverse($journals, true); Log::debug(sprintf('getAuditReport: Call accountsBalancesOptimized with date/time "%s"', $date->toIso8601String())); // 2025-10-08 replace with accountsBalancesOptimized. // $dayBeforeBalance = Steam::finalAccountBalance($account, $date); - $dayBeforeBalance = Steam::accountsBalancesOptimized(new Collection()->push($account), $date)[$account->id]; + $dayBeforeBalance = Steam::accountsBalancesOptimized(new Collection()->push($account), $date)[$account->id]; - $startBalance = $dayBeforeBalance['balance']; - $primaryCurrency = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup); - $currency = $accountRepository->getAccountCurrency($account) ?? $primaryCurrency; + $startBalance = $dayBeforeBalance['balance']; + $primaryCurrency = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup); + $currency = $accountRepository->getAccountCurrency($account) ?? $primaryCurrency; foreach ($journals as $index => $journal) { $journals[$index]['balance_before'] = $startBalance; - $transactionAmount = $journal['amount']; + $transactionAmount = $journal['amount']; // make sure amount is in the right "direction". if ($account->id === $journal['destination_account_id']) { @@ -164,32 +176,32 @@ class MonthReportGenerator implements ReportGeneratorInterface } } - $newBalance = bcadd((string) $startBalance, (string) $transactionAmount); - $journals[$index]['balance_after'] = $newBalance; - $startBalance = $newBalance; + $newBalance = bcadd((string) $startBalance, (string) $transactionAmount); + $journals[$index]['balance_after'] = $newBalance; + $startBalance = $newBalance; // add meta dates for each journal. - $journals[$index]['interest_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'interest_date'); - $journals[$index]['book_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'book_date'); - $journals[$index]['process_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'process_date'); - $journals[$index]['due_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'due_date'); - $journals[$index]['payment_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'payment_date'); - $journals[$index]['invoice_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'invoice_date'); + $journals[$index]['interest_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'interest_date'); + $journals[$index]['book_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'book_date'); + $journals[$index]['process_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'process_date'); + $journals[$index]['due_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'due_date'); + $journals[$index]['payment_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'payment_date'); + $journals[$index]['invoice_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'invoice_date'); } - $locale = Steam::getLocale(); + $locale = Steam::getLocale(); // call is correct. Log::debug(sprintf('getAuditReport end: Call finalAccountBalance with date/time "%s"', $this->end->toIso8601String())); // 2025-10-08 replace with accountsBalancesOptimized: return [ - 'journals' => $journals, - 'currency' => $currency, - 'exists' => 0 !== count($journals), - 'end' => $this->end->isoFormat((string) trans('config.month_and_day_moment_js', [], $locale)), + 'journals' => $journals, + 'currency' => $currency, + 'exists' => 0 !== count($journals), + 'end' => $this->end->isoFormat((string) trans('config.month_and_day_moment_js', [], $locale)), // 'endBalance' => Steam::finalAccountBalance($account, $this->end)['balance'], 'endBalance' => Steam::accountsBalancesOptimized(new Collection()->push($account), $this->end)[$account->id]['balance'], 'dayBefore' => $date->isoFormat((string) trans('config.month_and_day_moment_js', [], $locale)), - 'dayBeforeBalance' => $dayBeforeBalance, + 'dayBeforeBalance' => $dayBeforeBalance ]; } diff --git a/app/Generator/Report/Budget/MonthReportGenerator.php b/app/Generator/Report/Budget/MonthReportGenerator.php index a11697616a..5d8ea8f433 100644 --- a/app/Generator/Report/Budget/MonthReportGenerator.php +++ b/app/Generator/Report/Budget/MonthReportGenerator.php @@ -29,8 +29,8 @@ use FireflyIII\Exceptions\FireflyException; use FireflyIII\Generator\Report\ReportGeneratorInterface; use FireflyIII\Helpers\Collector\GroupCollectorInterface; use Illuminate\Support\Collection; -use Throwable; use Illuminate\Support\Facades\Log; +use Throwable; /** * Class MonthReportGenerator. @@ -40,9 +40,9 @@ class MonthReportGenerator implements ReportGeneratorInterface { private Collection $accounts; private Collection $budgets; - private Carbon $end; - private array $expenses = []; - private Carbon $start; + private Carbon $end; + private array $expenses = []; + private Carbon $start; /** * Generates the report. @@ -55,15 +55,12 @@ class MonthReportGenerator implements ReportGeneratorInterface $budgetIds = implode(',', $this->budgets->pluck('id')->toArray()); try { - $result = view( - 'reports.budget.month', - ['accountIds' => $accountIds, 'budgetIds' => $budgetIds] - ) - ->with('start', $this->start)->with('end', $this->end) + $result = view('reports.budget.month', ['accountIds' => $accountIds, 'budgetIds' => $budgetIds]) + ->with('start', $this->start) + ->with('end', $this->end) ->with('budgets', $this->budgets) ->with('accounts', $this->accounts) - ->render() - ; + ->render(); } catch (Throwable $e) { Log::error(sprintf('Cannot render reports.account.report: %s', $e->getMessage())); Log::error($e->getTraceAsString()); @@ -131,15 +128,16 @@ class MonthReportGenerator implements ReportGeneratorInterface } /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); - $collector->setAccounts($this->accounts)->setRange($this->start, $this->end) + $collector = app(GroupCollectorInterface::class); + $collector + ->setAccounts($this->accounts) + ->setRange($this->start, $this->end) ->setTypes([TransactionTypeEnum::WITHDRAWAL->value]) ->withAccountInformation() ->withBudgetInformation() - ->setBudgets($this->budgets) - ; + ->setBudgets($this->budgets); - $journals = $collector->getExtractedJournals(); + $journals = $collector->getExtractedJournals(); $this->expenses = $journals; return $journals; diff --git a/app/Generator/Report/Category/MonthReportGenerator.php b/app/Generator/Report/Category/MonthReportGenerator.php index 3bae1a373c..3f1bd84a6b 100644 --- a/app/Generator/Report/Category/MonthReportGenerator.php +++ b/app/Generator/Report/Category/MonthReportGenerator.php @@ -29,8 +29,8 @@ use FireflyIII\Exceptions\FireflyException; use FireflyIII\Generator\Report\ReportGeneratorInterface; use FireflyIII\Helpers\Collector\GroupCollectorInterface; use Illuminate\Support\Collection; -use Throwable; use Illuminate\Support\Facades\Log; +use Throwable; /** * Class MonthReportGenerator. @@ -40,10 +40,10 @@ class MonthReportGenerator implements ReportGeneratorInterface { private Collection $accounts; private Collection $categories; - private Carbon $end; - private array $expenses = []; - private array $income = []; - private Carbon $start; + private Carbon $end; + private array $expenses = []; + private array $income = []; + private Carbon $start; /** * Generates the report. @@ -58,12 +58,12 @@ class MonthReportGenerator implements ReportGeneratorInterface // render! try { - return view('reports.category.month', ['accountIds' => $accountIds, 'categoryIds' => $categoryIds, 'reportType' => $reportType]) - ->with('start', $this->start)->with('end', $this->end) + return view('reports.category.month', ['accountIds' => $accountIds, 'categoryIds' => $categoryIds, 'reportType' => $reportType]) + ->with('start', $this->start) + ->with('end', $this->end) ->with('categories', $this->categories) ->with('accounts', $this->accounts) - ->render() - ; + ->render(); } catch (Throwable $e) { Log::error(sprintf('Cannot render reports.category.month: %s', $e->getMessage())); Log::error($e->getTraceAsString()); @@ -129,13 +129,15 @@ class MonthReportGenerator implements ReportGeneratorInterface } /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); - $collector->setAccounts($this->accounts)->setRange($this->start, $this->end) + $collector = app(GroupCollectorInterface::class); + $collector + ->setAccounts($this->accounts) + ->setRange($this->start, $this->end) ->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::TRANSFER->value]) - ->setCategories($this->categories)->withAccountInformation() - ; + ->setCategories($this->categories) + ->withAccountInformation(); - $transactions = $collector->getExtractedJournals(); + $transactions = $collector->getExtractedJournals(); $this->expenses = $transactions; return $transactions; @@ -171,12 +173,14 @@ class MonthReportGenerator implements ReportGeneratorInterface } /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); - $collector->setAccounts($this->accounts)->setRange($this->start, $this->end) + $collector + ->setAccounts($this->accounts) + ->setRange($this->start, $this->end) ->setTypes([TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value]) - ->setCategories($this->categories)->withAccountInformation() - ; + ->setCategories($this->categories) + ->withAccountInformation(); $transactions = $collector->getExtractedJournals(); $this->income = $transactions; diff --git a/app/Generator/Report/ReportGeneratorFactory.php b/app/Generator/Report/ReportGeneratorFactory.php index 9d74f758ba..f0a05a9df6 100644 --- a/app/Generator/Report/ReportGeneratorFactory.php +++ b/app/Generator/Report/ReportGeneratorFactory.php @@ -49,7 +49,7 @@ class ReportGeneratorFactory $period = 'MultiYear'; } - $class = sprintf('FireflyIII\Generator\Report\%s\%sReportGenerator', $type, $period); + $class = sprintf('FireflyIII\Generator\Report\%s\%sReportGenerator', $type, $period); if (class_exists($class)) { /** @var ReportGeneratorInterface $obj */ $obj = app($class); diff --git a/app/Generator/Report/Standard/MonthReportGenerator.php b/app/Generator/Report/Standard/MonthReportGenerator.php index 54cc09855e..4475ba23da 100644 --- a/app/Generator/Report/Standard/MonthReportGenerator.php +++ b/app/Generator/Report/Standard/MonthReportGenerator.php @@ -27,8 +27,8 @@ use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Generator\Report\ReportGeneratorInterface; use Illuminate\Support\Collection; -use Throwable; use Illuminate\Support\Facades\Log; +use Throwable; /** * Class MonthReportGenerator. @@ -36,13 +36,13 @@ use Illuminate\Support\Facades\Log; class MonthReportGenerator implements ReportGeneratorInterface { /** @var Collection The accounts involved in the report. */ - private ?Collection $accounts = null; + private null|Collection $accounts = null; /** @var Carbon The end date. */ - private ?Carbon $end = null; + private null|Carbon $end = null; /** @var Carbon The start date. */ - private ?Carbon $start = null; + private null|Carbon $start = null; /** * Generates the report. @@ -55,7 +55,10 @@ class MonthReportGenerator implements ReportGeneratorInterface $reportType = 'default'; try { - return view('reports.default.month', ['accountIds' => $accountIds, 'reportType' => $reportType])->with('start', $this->start)->with('end', $this->end)->render(); + return view('reports.default.month', ['accountIds' => $accountIds, 'reportType' => $reportType]) + ->with('start', $this->start) + ->with('end', $this->end) + ->render(); } catch (Throwable $e) { Log::error(sprintf('Cannot render reports.default.month: %s', $e->getMessage())); Log::error($e->getTraceAsString()); diff --git a/app/Generator/Report/Standard/MultiYearReportGenerator.php b/app/Generator/Report/Standard/MultiYearReportGenerator.php index 10f89ea80b..13be7c51e0 100644 --- a/app/Generator/Report/Standard/MultiYearReportGenerator.php +++ b/app/Generator/Report/Standard/MultiYearReportGenerator.php @@ -27,8 +27,8 @@ use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Generator\Report\ReportGeneratorInterface; use Illuminate\Support\Collection; -use Throwable; use Illuminate\Support\Facades\Log; +use Throwable; /** * Class MonthReportGenerator. @@ -36,13 +36,13 @@ use Illuminate\Support\Facades\Log; class MultiYearReportGenerator implements ReportGeneratorInterface { /** @var Collection The accounts involved. */ - private ?Collection $accounts = null; + private null|Collection $accounts = null; /** @var Carbon The end date. */ - private ?Carbon $end = null; + private null|Carbon $end = null; /** @var Carbon The start date. */ - private ?Carbon $start = null; + private null|Carbon $start = null; /** * Generates the report. @@ -56,10 +56,10 @@ class MultiYearReportGenerator implements ReportGeneratorInterface $reportType = 'default'; try { - return view( - 'reports.default.multi-year', - ['accountIds' => $accountIds, 'reportType' => $reportType] - )->with('start', $this->start)->with('end', $this->end)->render(); + return view('reports.default.multi-year', ['accountIds' => $accountIds, 'reportType' => $reportType]) + ->with('start', $this->start) + ->with('end', $this->end) + ->render(); } catch (Throwable $e) { Log::error(sprintf('Cannot render reports.default.multi-year: %s', $e->getMessage())); Log::error($e->getTraceAsString()); diff --git a/app/Generator/Report/Standard/YearReportGenerator.php b/app/Generator/Report/Standard/YearReportGenerator.php index 8c394d4c64..2cea39525f 100644 --- a/app/Generator/Report/Standard/YearReportGenerator.php +++ b/app/Generator/Report/Standard/YearReportGenerator.php @@ -27,8 +27,8 @@ use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Generator\Report\ReportGeneratorInterface; use Illuminate\Support\Collection; -use Throwable; use Illuminate\Support\Facades\Log; +use Throwable; /** * Class MonthReportGenerator. @@ -36,13 +36,13 @@ use Illuminate\Support\Facades\Log; class YearReportGenerator implements ReportGeneratorInterface { /** @var Collection The accounts involved. */ - private ?Collection $accounts = null; + private null|Collection $accounts = null; /** @var Carbon The end date. */ - private ?Carbon $end = null; + private null|Carbon $end = null; /** @var Carbon The start date. */ - private ?Carbon $start = null; + private null|Carbon $start = null; /** * Generates the report. @@ -56,10 +56,10 @@ class YearReportGenerator implements ReportGeneratorInterface $reportType = 'default'; try { - $result = view( - 'reports.default.year', - ['accountIds' => $accountIds, 'reportType' => $reportType] - )->with('start', $this->start)->with('end', $this->end)->render(); + $result = view('reports.default.year', ['accountIds' => $accountIds, 'reportType' => $reportType]) + ->with('start', $this->start) + ->with('end', $this->end) + ->render(); } catch (Throwable $e) { Log::error(sprintf('Cannot render reports.account.report: %s', $e->getMessage())); Log::error($e->getTraceAsString()); diff --git a/app/Generator/Report/Tag/MonthReportGenerator.php b/app/Generator/Report/Tag/MonthReportGenerator.php index b7b6aad3a0..de9310775f 100644 --- a/app/Generator/Report/Tag/MonthReportGenerator.php +++ b/app/Generator/Report/Tag/MonthReportGenerator.php @@ -28,8 +28,8 @@ use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Generator\Report\ReportGeneratorInterface; use Illuminate\Support\Collection; -use Throwable; use Illuminate\Support\Facades\Log; +use Throwable; /** * Class MonthReportGenerator. @@ -37,8 +37,8 @@ use Illuminate\Support\Facades\Log; class MonthReportGenerator implements ReportGeneratorInterface { private Collection $accounts; - private Carbon $end; - private Carbon $start; + private Carbon $end; + private Carbon $start; private Collection $tags; /** @@ -46,7 +46,7 @@ class MonthReportGenerator implements ReportGeneratorInterface */ public function __construct() { - $this->tags = new Collection(); + $this->tags = new Collection(); $this->accounts = new Collection(); } @@ -63,10 +63,12 @@ class MonthReportGenerator implements ReportGeneratorInterface // render! try { - $result = view( - 'reports.tag.month', - ['accountIds' => $accountIds, 'reportType' => $reportType, 'tagIds' => $tagIds] - )->with('start', $this->start)->with('end', $this->end)->with('tags', $this->tags)->with('accounts', $this->accounts)->render(); + $result = view('reports.tag.month', ['accountIds' => $accountIds, 'reportType' => $reportType, 'tagIds' => $tagIds]) + ->with('start', $this->start) + ->with('end', $this->end) + ->with('tags', $this->tags) + ->with('accounts', $this->accounts) + ->render(); } catch (Throwable $e) { Log::error(sprintf('Cannot render reports.tag.month: %s', $e->getMessage())); Log::error($e->getTraceAsString()); diff --git a/app/Generator/Webhook/StandardMessageGenerator.php b/app/Generator/Webhook/StandardMessageGenerator.php index d23a93cf3a..ecbe711fa3 100644 --- a/app/Generator/Webhook/StandardMessageGenerator.php +++ b/app/Generator/Webhook/StandardMessageGenerator.php @@ -55,15 +55,15 @@ use Symfony\Component\HttpFoundation\ParameterBag; */ class StandardMessageGenerator implements MessageGeneratorInterface { - private Collection $objects; + private Collection $objects; private WebhookTrigger $trigger; - private User $user; - private int $version = 0; - private Collection $webhooks; + private User $user; + private int $version = 0; + private Collection $webhooks; public function __construct() { - $this->objects = new Collection(); + $this->objects = new Collection(); $this->webhooks = new Collection(); } @@ -76,19 +76,23 @@ class StandardMessageGenerator implements MessageGeneratorInterface } // do some debugging - Log::debug(sprintf('StandardMessageGenerator will generate messages for %d object(s) and %d webhook(s).', $this->objects->count(), $this->webhooks->count())); + Log::debug(sprintf( + 'StandardMessageGenerator will generate messages for %d object(s) and %d webhook(s).', + $this->objects->count(), + $this->webhooks->count() + )); $this->run(); } private function getWebhooks(): Collection { - return $this->user->webhooks() + return $this->user + ->webhooks() ->leftJoin('webhook_webhook_trigger', 'webhook_webhook_trigger.webhook_id', 'webhooks.id') ->leftJoin('webhook_triggers', 'webhook_webhook_trigger.webhook_trigger_id', 'webhook_triggers.id') ->where('active', true) ->whereIn('webhook_triggers.title', [$this->trigger->name, WebhookTrigger::ANY->name]) - ->get(['webhooks.*']) - ; + ->get(['webhooks.*']); } /** @@ -123,23 +127,23 @@ class StandardMessageGenerator implements MessageGeneratorInterface */ private function generateMessage(Webhook $webhook, Model $model): void { - $class = $model::class; + $class = $model::class; // Line is ignored because all of Firefly III's Models have an id property. Log::debug(sprintf('Now in generateMessage(#%d, %s#%d)', $webhook->id, $class, $model->id)); - $uuid = Uuid::uuid4(); + $uuid = Uuid::uuid4(); /** @var WebhookResponseModel $response */ - $response = $webhook->webhookResponses()->first(); + $response = $webhook->webhookResponses()->first(); $this->getTriggerTitles($webhook->webhookTriggers()->get()); - $basicMessage = [ + $basicMessage = [ 'uuid' => $uuid->toString(), 'user_id' => 0, 'user_group_id' => 0, 'trigger' => $this->trigger->name, 'response' => $response->title, // guess that the database is correct. - 'url' => $webhook->url, - 'version' => sprintf('v%d', $this->getVersion()), - 'content' => [], + 'url' => $webhook->url, + 'version' => sprintf('v%d', $this->getVersion()), + 'content' => [] ]; switch ($class) { @@ -151,22 +155,22 @@ class StandardMessageGenerator implements MessageGeneratorInterface case Budget::class: /** @var Budget $model */ - $basicMessage['user_id'] = $model->user_id; + $basicMessage['user_id'] = $model->user_id; $basicMessage['user_group_id'] = $model->user_group_id; - $relevantResponse = WebhookResponse::BUDGET->name; + $relevantResponse = WebhookResponse::BUDGET->name; break; case BudgetLimit::class: - $basicMessage['user_id'] = $model->budget->user_id; + $basicMessage['user_id'] = $model->budget->user_id; $basicMessage['user_group_id'] = $model->budget->user_group_id; - $relevantResponse = WebhookResponse::BUDGET->name; + $relevantResponse = WebhookResponse::BUDGET->name; break; case TransactionGroup::class: /** @var TransactionGroup $model */ - $basicMessage['user_id'] = $model->user_id; + $basicMessage['user_id'] = $model->user_id; $basicMessage['user_group_id'] = $model->user_group_id; break; @@ -175,33 +179,37 @@ class StandardMessageGenerator implements MessageGeneratorInterface switch ($responseTitle) { default: - Log::error(sprintf('The response code for webhook #%d is "%s" and the message generator cant handle it. Soft fail.', $webhook->id, $webhook->response)); + Log::error(sprintf( + 'The response code for webhook #%d is "%s" and the message generator cant handle it. Soft fail.', + $webhook->id, + $webhook->response + )); return; case WebhookResponse::BUDGET->name: $basicMessage['content'] = []; if ($model instanceof Budget) { - $enrichment = new BudgetEnrichment(); + $enrichment = new BudgetEnrichment(); $enrichment->setUser($model->user); /** @var Budget $model */ - $model = $enrichment->enrichSingle($model); - $transformer = new BudgetTransformer(); + $model = $enrichment->enrichSingle($model); + $transformer = new BudgetTransformer(); $basicMessage['content'] = $transformer->transform($model); } if ($model instanceof BudgetLimit) { - $user = $model->budget->user; - $enrichment = new BudgetLimitEnrichment(); + $user = $model->budget->user; + $enrichment = new BudgetLimitEnrichment(); $enrichment->setUser($user); - $parameters = new ParameterBag(); + $parameters = new ParameterBag(); $parameters->set('start', $model->start_date); $parameters->set('end', $model->end_date); /** @var BudgetLimit $model */ - $model = $enrichment->enrichSingle($model); - $transformer = new BudgetLimitTransformer(); + $model = $enrichment->enrichSingle($model); + $transformer = new BudgetLimitTransformer(); $transformer->setParameters($parameters); $basicMessage['content'] = $transformer->transform($model); } @@ -215,14 +223,16 @@ class StandardMessageGenerator implements MessageGeneratorInterface case WebhookResponse::TRANSACTIONS->name: /** @var TransactionGroup $model */ - $transformer = new TransactionGroupTransformer(); + $transformer = new TransactionGroupTransformer(); try { $basicMessage['content'] = $transformer->transformObject($model); } catch (FireflyException $e) { - Log::error( - sprintf('The transformer could not include the requested transaction group for webhook #%d: %s', $webhook->id, $e->getMessage()) - ); + Log::error(sprintf( + 'The transformer could not include the requested transaction group for webhook #%d: %s', + $webhook->id, + $e->getMessage() + )); Log::error($e->getTraceAsString()); return; @@ -232,13 +242,13 @@ class StandardMessageGenerator implements MessageGeneratorInterface case WebhookResponse::ACCOUNTS->name: /** @var TransactionGroup $model */ - $accounts = $this->collectAccounts($model); - $enrichment = new AccountEnrichment(); + $accounts = $this->collectAccounts($model); + $enrichment = new AccountEnrichment(); $enrichment->setDate(null); $enrichment->setUser($model->user); - $accounts = $enrichment->enrich($accounts); + $accounts = $enrichment->enrich($accounts); foreach ($accounts as $account) { - $transformer = new AccountTransformer(); + $transformer = new AccountTransformer(); $transformer->setParameters(new ParameterBag()); $basicMessage['content'][] = $transformer->transform($account); } @@ -268,11 +278,11 @@ class StandardMessageGenerator implements MessageGeneratorInterface private function storeMessage(Webhook $webhook, array $message): void { - $webhookMessage = new WebhookMessage(); + $webhookMessage = new WebhookMessage(); $webhookMessage->webhook()->associate($webhook); - $webhookMessage->sent = false; + $webhookMessage->sent = false; $webhookMessage->errored = false; - $webhookMessage->uuid = $message['uuid']; + $webhookMessage->uuid = $message['uuid']; $webhookMessage->message = $message; $webhookMessage->save(); Log::debug(sprintf('Stored new webhook message #%d', $webhookMessage->id)); diff --git a/app/Handlers/Events/APIEventHandler.php b/app/Handlers/Events/APIEventHandler.php index f9b17ab3f2..cef3151394 100644 --- a/app/Handlers/Events/APIEventHandler.php +++ b/app/Handlers/Events/APIEventHandler.php @@ -27,9 +27,9 @@ namespace FireflyIII\Handlers\Events; use Exception; use FireflyIII\Notifications\User\NewAccessToken; use FireflyIII\Repositories\User\UserRepositoryInterface; +use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Notification; use Laravel\Passport\Events\AccessTokenCreated; -use Illuminate\Support\Facades\Log; /** * Class APIEventHandler diff --git a/app/Handlers/Events/AuditEventHandler.php b/app/Handlers/Events/AuditEventHandler.php index 21e8ac56ed..9e618631d6 100644 --- a/app/Handlers/Events/AuditEventHandler.php +++ b/app/Handlers/Events/AuditEventHandler.php @@ -36,12 +36,12 @@ class AuditEventHandler { public function storeAuditEvent(TriggeredAuditLog $event): void { - $array = [ + $array = [ 'auditable' => $event->auditable, 'changer' => $event->changer, 'action' => $event->field, 'before' => $event->before, - 'after' => $event->after, + 'after' => $event->after ]; if ($event->before === $event->after) { @@ -56,7 +56,7 @@ class AuditEventHandler } if ($event->before instanceof Carbon && $event->after instanceof Carbon) { $array['before'] = $event->before->toIso8601String(); - $array['after'] = $event->after->toIso8601String(); + $array['after'] = $event->after->toIso8601String(); Log::debug(sprintf('Converted "before" to "%s".', $event->before)); Log::debug(sprintf('Converted "after" to "%s".', $event->after)); } diff --git a/app/Handlers/Events/AutomationHandler.php b/app/Handlers/Events/AutomationHandler.php index 8d2b97c38c..788d463a90 100644 --- a/app/Handlers/Events/AutomationHandler.php +++ b/app/Handlers/Events/AutomationHandler.php @@ -32,8 +32,8 @@ use FireflyIII\Notifications\User\TransactionCreation; use FireflyIII\Repositories\User\UserRepositoryInterface; use FireflyIII\Support\Facades\Preferences; use FireflyIII\Transformers\TransactionGroupTransformer; -use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\Log; +use Illuminate\Support\Facades\Notification; /** * Class AutomationHandler @@ -50,11 +50,11 @@ class AutomationHandler Log::debug('In reportJournals.'); /** @var UserRepositoryInterface $repository */ - $repository = app(UserRepositoryInterface::class); - $user = $repository->find($event->userId); + $repository = app(UserRepositoryInterface::class); + $user = $repository->find($event->userId); /** @var bool $sendReport */ - $sendReport = Preferences::getForUser($user, 'notification_transaction_creation', false)->data; + $sendReport = Preferences::getForUser($user, 'notification_transaction_creation', false)->data; if (false === $sendReport) { Log::debug('Not sending report, because config says so.'); diff --git a/app/Handlers/Events/DestroyedGroupEventHandler.php b/app/Handlers/Events/DestroyedGroupEventHandler.php index 18b4144709..49af9c93bb 100644 --- a/app/Handlers/Events/DestroyedGroupEventHandler.php +++ b/app/Handlers/Events/DestroyedGroupEventHandler.php @@ -47,8 +47,8 @@ class DestroyedGroupEventHandler private function triggerWebhooks(DestroyedTransactionGroup $destroyedGroupEvent): void { Log::debug('DestroyedTransactionGroup:triggerWebhooks'); - $group = $destroyedGroupEvent->transactionGroup; - $user = $group->user; + $group = $destroyedGroupEvent->transactionGroup; + $user = $group->user; /** @var MessageGeneratorInterface $engine */ $engine = app(MessageGeneratorInterface::class); diff --git a/app/Handlers/Events/PreferencesEventHandler.php b/app/Handlers/Events/PreferencesEventHandler.php index f816f890f9..23e2cbfc5d 100644 --- a/app/Handlers/Events/PreferencesEventHandler.php +++ b/app/Handlers/Events/PreferencesEventHandler.php @@ -47,7 +47,7 @@ class PreferencesEventHandler // !!! this array is also in the migration 'accounts' => ['native_virtual_balance'], 'available_budgets' => ['native_amount'], - 'bills' => ['native_amount_min', 'native_amount_max'], + 'bills' => ['native_amount_min', 'native_amount_max'] ]; foreach ($tables as $table => $columns) { foreach ($columns as $column) { @@ -103,7 +103,7 @@ class PreferencesEventHandler { $repository = app(BudgetRepositoryInterface::class); $repository->setUserGroup($userGroup); - $set = $repository->getBudgets(); + $set = $repository->getBudgets(); Log::debug(sprintf('Resetting %d budget(s).', $set->count())); @@ -125,7 +125,6 @@ class PreferencesEventHandler } } } - } private function resetTransactions(UserGroup $userGroup): void @@ -135,12 +134,9 @@ class PreferencesEventHandler ->join('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->where('transaction_journals.user_group_id', $userGroup->id) ->where(static function (Builder $q): void { - $q->whereNotNull('native_amount') - ->orWhereNotNull('native_foreign_amount') - ; + $q->whereNotNull('native_amount')->orWhereNotNull('native_foreign_amount'); }) - ->update(['native_amount' => null, 'native_foreign_amount' => null]) - ; + ->update(['native_amount' => null, 'native_foreign_amount' => null]); Log::debug(sprintf('Reset %d transactions.', $success)); } } diff --git a/app/Handlers/Events/StoredAccountEventHandler.php b/app/Handlers/Events/StoredAccountEventHandler.php index 574148def2..bb81b22cec 100644 --- a/app/Handlers/Events/StoredAccountEventHandler.php +++ b/app/Handlers/Events/StoredAccountEventHandler.php @@ -37,7 +37,7 @@ class StoredAccountEventHandler $account = $event->account; /** @var CreditRecalculateService $object */ - $object = app(CreditRecalculateService::class); + $object = app(CreditRecalculateService::class); $object->setAccount($account); $object->recalculate(); } diff --git a/app/Handlers/Events/StoredGroupEventHandler.php b/app/Handlers/Events/StoredGroupEventHandler.php index 30e0973a49..677e4748d6 100644 --- a/app/Handlers/Events/StoredGroupEventHandler.php +++ b/app/Handlers/Events/StoredGroupEventHandler.php @@ -62,7 +62,7 @@ class StoredGroupEventHandler /** * This method grabs all the users rules and processes them. */ - private function processRules(StoredTransactionGroup $storedGroupEvent, ?RuleGroup $ruleGroup): void + private function processRules(StoredTransactionGroup $storedGroupEvent, null|RuleGroup $ruleGroup): void { if (false === $storedGroupEvent->applyRules) { Log::info(sprintf('Will not run rules on group #%d', $storedGroupEvent->transactionGroup->id)); @@ -71,14 +71,14 @@ class StoredGroupEventHandler } Log::debug('Now in StoredGroupEventHandler::processRules()'); - $journals = $storedGroupEvent->transactionGroup->transactionJournals; - $array = []; + $journals = $storedGroupEvent->transactionGroup->transactionJournals; + $array = []; /** @var TransactionJournal $journal */ foreach ($journals as $journal) { $array[] = $journal->id; } - $journalIds = implode(',', $array); + $journalIds = implode(',', $array); Log::debug(sprintf('Add local operator for journal(s): %s', $journalIds)); // collect rules: @@ -97,16 +97,16 @@ class StoredGroupEventHandler } // create and fire rule engine. - $newRuleEngine = app(RuleEngineInterface::class); + $newRuleEngine = app(RuleEngineInterface::class); $newRuleEngine->setUser($storedGroupEvent->transactionGroup->user); - $newRuleEngine->addOperator(['type' => 'journal_id', 'value' => $journalIds]); + $newRuleEngine->addOperator(['type' => 'journal_id', 'value' => $journalIds]); $newRuleEngine->setRuleGroups($groups); $newRuleEngine->fire(); } private function recalculateCredit(StoredTransactionGroup $event): void { - $group = $event->transactionGroup; + $group = $event->transactionGroup; /** @var CreditRecalculateService $object */ $object = app(CreditRecalculateService::class); @@ -122,10 +122,10 @@ class StoredGroupEventHandler /** @var TransactionJournal $journal */ foreach ($event->transactionGroup->transactionJournals as $journal) { /** @var null|Transaction $source */ - $source = $journal->transactions()->where('amount', '<', '0')->first(); + $source = $journal->transactions()->where('amount', '<', '0')->first(); /** @var null|Transaction $dest */ - $dest = $journal->transactions()->where('amount', '>', '0')->first(); + $dest = $journal->transactions()->where('amount', '>', '0')->first(); if (null !== $source) { $repository->deleteStatisticsForModel($source->account, $journal->date); @@ -160,14 +160,14 @@ class StoredGroupEventHandler private function triggerWebhooks(StoredTransactionGroup $storedGroupEvent): void { Log::debug(__METHOD__); - $group = $storedGroupEvent->transactionGroup; + $group = $storedGroupEvent->transactionGroup; if (false === $storedGroupEvent->fireWebhooks) { Log::info(sprintf('Will not fire webhooks for transaction group #%d', $group->id)); return; } - $user = $group->user; + $user = $group->user; /** @var MessageGeneratorInterface $engine */ $engine = app(MessageGeneratorInterface::class); diff --git a/app/Handlers/Events/UpdatedAccountEventHandler.php b/app/Handlers/Events/UpdatedAccountEventHandler.php index 59c137e817..e949c02e6b 100644 --- a/app/Handlers/Events/UpdatedAccountEventHandler.php +++ b/app/Handlers/Events/UpdatedAccountEventHandler.php @@ -37,7 +37,7 @@ class UpdatedAccountEventHandler $account = $event->account; /** @var CreditRecalculateService $object */ - $object = app(CreditRecalculateService::class); + $object = app(CreditRecalculateService::class); $object->setAccount($account); $object->recalculate(); } diff --git a/app/Handlers/Events/UpdatedGroupEventHandler.php b/app/Handlers/Events/UpdatedGroupEventHandler.php index 6ff8cab4d2..f1c1eaf031 100644 --- a/app/Handlers/Events/UpdatedGroupEventHandler.php +++ b/app/Handlers/Events/UpdatedGroupEventHandler.php @@ -55,8 +55,6 @@ class UpdatedGroupEventHandler if ($event->runRecalculations) { $this->updateRunningBalance($event); } - - } /** @@ -69,8 +67,8 @@ class UpdatedGroupEventHandler /** @var TransactionJournal $journal */ foreach ($event->transactionGroup->transactionJournals as $journal) { - $source = $journal->transactions()->where('amount', '<', '0')->first(); - $dest = $journal->transactions()->where('amount', '>', '0')->first(); + $source = $journal->transactions()->where('amount', '<', '0')->first(); + $dest = $journal->transactions()->where('amount', '>', '0')->first(); if (null !== $source) { $repository->deleteStatisticsForModel($source->account, $journal->date); } @@ -105,20 +103,20 @@ class UpdatedGroupEventHandler */ public function unifyAccounts(UpdatedTransactionGroup $updatedGroupEvent): void { - $group = $updatedGroupEvent->transactionGroup; + $group = $updatedGroupEvent->transactionGroup; if (1 === $group->transactionJournals->count()) { return; } // first journal: /** @var null|TransactionJournal $first */ - $first = $group->transactionJournals() + $first = $group + ->transactionJournals() ->orderBy('transaction_journals.date', 'DESC') ->orderBy('transaction_journals.order', 'ASC') ->orderBy('transaction_journals.id', 'DESC') ->orderBy('transaction_journals.description', 'DESC') - ->first() - ; + ->first(); if (null === $first) { Log::warning(sprintf('Group #%d has no transaction journals.', $group->id)); @@ -126,26 +124,22 @@ class UpdatedGroupEventHandler return; } - $all = $group->transactionJournals()->get()->pluck('id')->toArray(); + $all = $group->transactionJournals()->get()->pluck('id')->toArray(); /** @var Account $sourceAccount */ $sourceAccount = $first->transactions()->where('amount', '<', '0')->first()->account; /** @var Account $destAccount */ - $destAccount = $first->transactions()->where('amount', '>', '0')->first()->account; + $destAccount = $first->transactions()->where('amount', '>', '0')->first()->account; - $type = $first->transactionType->type; + $type = $first->transactionType->type; if (TransactionTypeEnum::TRANSFER->value === $type || TransactionTypeEnum::WITHDRAWAL->value === $type) { // set all source transactions to source account: - Transaction::whereIn('transaction_journal_id', $all) - ->where('amount', '<', 0)->update(['account_id' => $sourceAccount->id]) - ; + Transaction::whereIn('transaction_journal_id', $all)->where('amount', '<', 0)->update(['account_id' => $sourceAccount->id]); } if (TransactionTypeEnum::TRANSFER->value === $type || TransactionTypeEnum::DEPOSIT->value === $type) { // set all destination transactions to destination account: - Transaction::whereIn('transaction_journal_id', $all) - ->where('amount', '>', 0)->update(['account_id' => $destAccount->id]) - ; + Transaction::whereIn('transaction_journal_id', $all)->where('amount', '>', 0)->update(['account_id' => $destAccount->id]); } } @@ -160,33 +154,33 @@ class UpdatedGroupEventHandler return; } - $journals = $updatedGroupEvent->transactionGroup->transactionJournals; - $array = []; + $journals = $updatedGroupEvent->transactionGroup->transactionJournals; + $array = []; /** @var TransactionJournal $journal */ foreach ($journals as $journal) { $array[] = $journal->id; } - $journalIds = implode(',', $array); + $journalIds = implode(',', $array); Log::debug(sprintf('Add local operator for journal(s): %s', $journalIds)); // collect rules: $ruleGroupRepository = app(RuleGroupRepositoryInterface::class); $ruleGroupRepository->setUser($updatedGroupEvent->transactionGroup->user); - $groups = $ruleGroupRepository->getRuleGroupsWithRules('update-journal'); + $groups = $ruleGroupRepository->getRuleGroupsWithRules('update-journal'); // file rule engine. - $newRuleEngine = app(RuleEngineInterface::class); + $newRuleEngine = app(RuleEngineInterface::class); $newRuleEngine->setUser($updatedGroupEvent->transactionGroup->user); - $newRuleEngine->addOperator(['type' => 'journal_id', 'value' => $journalIds]); + $newRuleEngine->addOperator(['type' => 'journal_id', 'value' => $journalIds]); $newRuleEngine->setRuleGroups($groups); $newRuleEngine->fire(); } private function recalculateCredit(UpdatedTransactionGroup $event): void { - $group = $event->transactionGroup; + $group = $event->transactionGroup; /** @var CreditRecalculateService $object */ $object = app(CreditRecalculateService::class); @@ -197,13 +191,13 @@ class UpdatedGroupEventHandler private function triggerWebhooks(UpdatedTransactionGroup $updatedGroupEvent): void { Log::debug(__METHOD__); - $group = $updatedGroupEvent->transactionGroup; + $group = $updatedGroupEvent->transactionGroup; if (false === $updatedGroupEvent->fireWebhooks) { Log::info(sprintf('Will not fire webhooks for transaction group #%d', $group->id)); return; } - $user = $group->user; + $user = $group->user; /** @var MessageGeneratorInterface $engine */ $engine = app(MessageGeneratorInterface::class); diff --git a/app/Handlers/Events/UserEventHandler.php b/app/Handlers/Events/UserEventHandler.php index 73cf918151..42821d354f 100644 --- a/app/Handlers/Events/UserEventHandler.php +++ b/app/Handlers/Events/UserEventHandler.php @@ -43,8 +43,6 @@ use Illuminate\Support\Facades\Mail; */ class UserEventHandler { - - /** * Fires to see if a user is admin. */ @@ -73,7 +71,6 @@ class UserEventHandler } } - /** * Set the demo user back to English. */ @@ -93,7 +90,6 @@ class UserEventHandler } } - /** * @throws FireflyException */ @@ -112,6 +108,4 @@ class UserEventHandler throw new FireflyException($e->getMessage(), 0, $e); } } - - } diff --git a/app/Handlers/Events/VersionCheckEventHandler.php b/app/Handlers/Events/VersionCheckEventHandler.php index e5a681aefc..51d47812da 100644 --- a/app/Handlers/Events/VersionCheckEventHandler.php +++ b/app/Handlers/Events/VersionCheckEventHandler.php @@ -30,10 +30,10 @@ use FireflyIII\Exceptions\FireflyException; use FireflyIII\Helpers\Update\UpdateTrait; use FireflyIII\Models\Configuration; use FireflyIII\Repositories\User\UserRepositoryInterface; +use FireflyIII\Support\Facades\FireflyConfig; use Illuminate\Support\Facades\Log; use Psr\Container\ContainerExceptionInterface; use Psr\Container\NotFoundExceptionInterface; -use FireflyIII\Support\Facades\FireflyConfig; /** * Class VersionCheckEventHandler @@ -55,8 +55,8 @@ class VersionCheckEventHandler Log::debug('Now in checkForUpdates()'); // should not check for updates: - $permission = FireflyConfig::get('permission_update_check', -1); - $value = (int) $permission->data; + $permission = FireflyConfig::get('permission_update_check', -1); + $value = (int) $permission->data; if (1 !== $value) { Log::debug('Update check is not enabled.'); $this->warnToCheckForUpdates($event); @@ -65,8 +65,8 @@ class VersionCheckEventHandler } /** @var UserRepositoryInterface $repository */ - $repository = app(UserRepositoryInterface::class); - $user = $event->user; + $repository = app(UserRepositoryInterface::class); + $user = $event->user; if (!$repository->hasRole($user, 'owner')) { Log::debug('User is not admin, done.'); @@ -85,7 +85,7 @@ class VersionCheckEventHandler } // last check time was more than a week ago. Log::debug('Have not checked for a new version in a week!'); - $release = $this->getLatestRelease(); + $release = $this->getLatestRelease(); session()->flash($release['level'], $release['message']); FireflyConfig::set('last_update_check', Carbon::now()->getTimestamp()); @@ -99,8 +99,8 @@ class VersionCheckEventHandler protected function warnToCheckForUpdates(RequestedVersionCheckStatus $event): void { /** @var UserRepositoryInterface $repository */ - $repository = app(UserRepositoryInterface::class); - $user = $event->user; + $repository = app(UserRepositoryInterface::class); + $user = $event->user; if (!$repository->hasRole($user, 'owner')) { Log::debug('User is not admin, done.'); @@ -112,8 +112,11 @@ class VersionCheckEventHandler $now = Carbon::now()->getTimestamp(); $diff = $now - $lastCheckTime->data; Log::debug(sprintf('Last warning time is %d, current time is %d, difference is %d', $lastCheckTime->data, $now, $diff)); - if ($diff < 604800 * 4) { - Log::debug(sprintf('Warned about updates less than four weeks ago (on %s).', Carbon::createFromTimestamp($lastCheckTime->data)->format('Y-m-d H:i:s'))); + if ($diff < (604800 * 4)) { + Log::debug(sprintf( + 'Warned about updates less than four weeks ago (on %s).', + Carbon::createFromTimestamp($lastCheckTime->data)->format('Y-m-d H:i:s') + )); return; } diff --git a/app/Handlers/Events/WebhookEventHandler.php b/app/Handlers/Events/WebhookEventHandler.php index 341258bfb7..f8b45b2d05 100644 --- a/app/Handlers/Events/WebhookEventHandler.php +++ b/app/Handlers/Events/WebhookEventHandler.php @@ -26,8 +26,8 @@ namespace FireflyIII\Handlers\Events; use FireflyIII\Jobs\SendWebhookMessage; use FireflyIII\Models\WebhookMessage; -use Illuminate\Support\Facades\Log; use FireflyIII\Support\Facades\FireflyConfig; +use Illuminate\Support\Facades\Log; /** * Class WebhookEventHandler @@ -49,10 +49,8 @@ class WebhookEventHandler // kick off the job! $messages = WebhookMessage::where('webhook_messages.sent', false) ->get(['webhook_messages.*']) - ->filter( - static fn (WebhookMessage $message): bool => $message->webhookAttempts()->count() <= 2 - )->splice(0, 5) - ; + ->filter(static fn(WebhookMessage $message): bool => $message->webhookAttempts()->count() <= 2) + ->splice(0, 5); Log::debug(sprintf('Found %d webhook message(s) ready to be send.', $messages->count())); /** @var WebhookMessage $message */ diff --git a/app/Handlers/Observer/AccountObserver.php b/app/Handlers/Observer/AccountObserver.php index 58fd1d50fd..4e57308f22 100644 --- a/app/Handlers/Observer/AccountObserver.php +++ b/app/Handlers/Observer/AccountObserver.php @@ -55,18 +55,23 @@ class AccountObserver $userCurrency = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup); $repository = app(AccountRepositoryInterface::class); $currency = $repository->getAccountCurrency($account); - if (null !== $currency && $currency->id !== $userCurrency->id && '' !== (string) $account->virtual_balance && 0 !== bccomp($account->virtual_balance, '0')) { - $converter = new ExchangeRateConverter(); + if ( + null !== $currency + && $currency->id !== $userCurrency->id + && '' !== (string) $account->virtual_balance + && 0 !== bccomp($account->virtual_balance, '0') + ) { + $converter = new ExchangeRateConverter(); $converter->setUserGroup($account->user->userGroup); $converter->setIgnoreSettings(true); $account->native_virtual_balance = $converter->convert($currency, $userCurrency, today(), $account->virtual_balance); - } - if ('' === (string) $account->virtual_balance || (0 === bccomp($account->virtual_balance, '0'))) { - $account->virtual_balance = null; + if ('' === (string) $account->virtual_balance || 0 === bccomp($account->virtual_balance, '0')) { + $account->virtual_balance = null; $account->native_virtual_balance = null; } $account->saveQuietly(); + // Log::debug('Account primary currency virtual balance is updated.'); } @@ -87,8 +92,14 @@ class AccountObserver $repository->destroy($attachment); } - $journalIds = Transaction::where('account_id', $account->id)->get(['transactions.transaction_journal_id'])->pluck('transaction_journal_id')->toArray(); - $groupIds = TransactionJournal::whereIn('id', $journalIds)->get(['transaction_journals.transaction_group_id'])->pluck('transaction_group_id')->toArray(); // @phpstan-ignore-line + $journalIds = Transaction::where('account_id', $account->id) + ->get(['transactions.transaction_journal_id']) + ->pluck('transaction_journal_id') + ->toArray(); + $groupIds = TransactionJournal::whereIn('id', $journalIds) + ->get(['transaction_journals.transaction_group_id']) + ->pluck('transaction_group_id') + ->toArray(); // @phpstan-ignore-line if (count($journalIds) > 0) { Transaction::whereIn('transaction_journal_id', $journalIds)->delete(); diff --git a/app/Handlers/Observer/AutoBudgetObserver.php b/app/Handlers/Observer/AutoBudgetObserver.php index fd838dcd68..deb565eeb0 100644 --- a/app/Handlers/Observer/AutoBudgetObserver.php +++ b/app/Handlers/Observer/AutoBudgetObserver.php @@ -42,10 +42,10 @@ class AutoBudgetObserver if (!Amount::convertToPrimary($autoBudget->budget->user)) { return; } - $userCurrency = Amount::getPrimaryCurrencyByUserGroup($autoBudget->budget->user->userGroup); + $userCurrency = Amount::getPrimaryCurrencyByUserGroup($autoBudget->budget->user->userGroup); $autoBudget->native_amount = null; if ($autoBudget->transactionCurrency->id !== $userCurrency->id) { - $converter = new ExchangeRateConverter(); + $converter = new ExchangeRateConverter(); $converter->setUserGroup($autoBudget->budget->user->userGroup); $converter->setIgnoreSettings(true); $autoBudget->native_amount = $converter->convert($autoBudget->transactionCurrency, $userCurrency, today(), $autoBudget->amount); diff --git a/app/Handlers/Observer/AvailableBudgetObserver.php b/app/Handlers/Observer/AvailableBudgetObserver.php index f9eb735b2f..9d60fff3de 100644 --- a/app/Handlers/Observer/AvailableBudgetObserver.php +++ b/app/Handlers/Observer/AvailableBudgetObserver.php @@ -44,10 +44,10 @@ class AvailableBudgetObserver return; } - $userCurrency = Amount::getPrimaryCurrencyByUserGroup($availableBudget->user->userGroup); + $userCurrency = Amount::getPrimaryCurrencyByUserGroup($availableBudget->user->userGroup); $availableBudget->native_amount = null; if ($availableBudget->transactionCurrency->id !== $userCurrency->id) { - $converter = new ExchangeRateConverter(); + $converter = new ExchangeRateConverter(); $converter->setUserGroup($availableBudget->user->userGroup); $converter->setIgnoreSettings(true); $availableBudget->native_amount = $converter->convert($availableBudget->transactionCurrency, $userCurrency, today(), $availableBudget->amount); diff --git a/app/Handlers/Observer/BillObserver.php b/app/Handlers/Observer/BillObserver.php index ea9c8bf4e0..8b28bc32ea 100644 --- a/app/Handlers/Observer/BillObserver.php +++ b/app/Handlers/Observer/BillObserver.php @@ -46,11 +46,11 @@ class BillObserver if (!Amount::convertToPrimary($bill->user)) { return; } - $userCurrency = Amount::getPrimaryCurrencyByUserGroup($bill->user->userGroup); + $userCurrency = Amount::getPrimaryCurrencyByUserGroup($bill->user->userGroup); $bill->native_amount_min = null; $bill->native_amount_max = null; if ($bill->transactionCurrency->id !== $userCurrency->id) { - $converter = new ExchangeRateConverter(); + $converter = new ExchangeRateConverter(); $converter->setUserGroup($bill->user->userGroup); $converter->setIgnoreSettings(true); $bill->native_amount_min = $converter->convert($bill->transactionCurrency, $userCurrency, today(), $bill->amount_min); diff --git a/app/Handlers/Observer/BudgetLimitObserver.php b/app/Handlers/Observer/BudgetLimitObserver.php index 2b07e585b1..cfe5f47130 100644 --- a/app/Handlers/Observer/BudgetLimitObserver.php +++ b/app/Handlers/Observer/BudgetLimitObserver.php @@ -45,13 +45,11 @@ class BudgetLimitObserver $this->updatePrimaryCurrencyAmount($budgetLimit); $this->updateAvailableBudget($budgetLimit); - // this is a lame trick to communicate with the observer. $singleton = PreferencesSingleton::getInstance(); if (true === $singleton->getPreference('fire_webhooks_bl_store')) { - - $user = $budgetLimit->budget->user; + $user = $budgetLimit->budget->user; /** @var MessageGeneratorInterface $engine */ $engine = app(MessageGeneratorInterface::class); @@ -72,10 +70,10 @@ class BudgetLimitObserver return; } - $userCurrency = Amount::getPrimaryCurrencyByUserGroup($budgetLimit->budget->user->userGroup); + $userCurrency = Amount::getPrimaryCurrencyByUserGroup($budgetLimit->budget->user->userGroup); $budgetLimit->native_amount = null; if ($budgetLimit->transactionCurrency->id !== $userCurrency->id) { - $converter = new ExchangeRateConverter(); + $converter = new ExchangeRateConverter(); $converter->setUserGroup($budgetLimit->budget->user->userGroup); $converter->setIgnoreSettings(true); $budgetLimit->native_amount = $converter->convert($budgetLimit->transactionCurrency, $userCurrency, today(), $budgetLimit->amount); @@ -94,7 +92,7 @@ class BudgetLimitObserver $singleton = PreferencesSingleton::getInstance(); if (true === $singleton->getPreference('fire_webhooks_bl_update')) { - $user = $budgetLimit->budget->user; + $user = $budgetLimit->budget->user; /** @var MessageGeneratorInterface $engine */ $engine = app(MessageGeneratorInterface::class); diff --git a/app/Handlers/Observer/BudgetObserver.php b/app/Handlers/Observer/BudgetObserver.php index 2a78e1f4be..f1772bf0c0 100644 --- a/app/Handlers/Observer/BudgetObserver.php +++ b/app/Handlers/Observer/BudgetObserver.php @@ -51,7 +51,7 @@ class BudgetObserver if (true === $singleton->getPreference('fire_webhooks_budget_create')) { // fire event. - $user = $budget->user; + $user = $budget->user; /** @var MessageGeneratorInterface $engine */ $engine = app(MessageGeneratorInterface::class); @@ -72,7 +72,7 @@ class BudgetObserver $singleton = PreferencesSingleton::getInstance(); if (true === $singleton->getPreference('fire_webhooks_budget_update')) { - $user = $budget->user; + $user = $budget->user; /** @var MessageGeneratorInterface $engine */ $engine = app(MessageGeneratorInterface::class); @@ -89,10 +89,10 @@ class BudgetObserver { Log::debug('Observe "deleting" of a budget.'); - $user = $budget->user; + $user = $budget->user; /** @var MessageGeneratorInterface $engine */ - $engine = app(MessageGeneratorInterface::class); + $engine = app(MessageGeneratorInterface::class); $engine->setUser($user); $engine->setObjects(new Collection()->push($budget)); $engine->setTrigger(WebhookTrigger::DESTROY_BUDGET); @@ -100,7 +100,7 @@ class BudgetObserver Log::debug(sprintf('send event RequestedSendWebhookMessages from %s', __METHOD__)); event(new RequestedSendWebhookMessages()); - $repository = app(AttachmentRepositoryInterface::class); + $repository = app(AttachmentRepositoryInterface::class); $repository->setUser($budget->user); /** @var Attachment $attachment */ @@ -112,7 +112,7 @@ class BudgetObserver /** @var BudgetLimit $budgetLimit */ foreach ($budgetLimits as $budgetLimit) { // this loop exists so several events are fired. - $copy = clone $budgetLimit; + $copy = clone $budgetLimit; $copy->id = 0; $this->updateAvailableBudget($copy); $budgetLimit->deleteQuietly(); // delete is quietly when in a loop. diff --git a/app/Handlers/Observer/PiggyBankEventObserver.php b/app/Handlers/Observer/PiggyBankEventObserver.php index 0aab702717..4295fdc676 100644 --- a/app/Handlers/Observer/PiggyBankEventObserver.php +++ b/app/Handlers/Observer/PiggyBankEventObserver.php @@ -39,7 +39,7 @@ class PiggyBankEventObserver private function updatePrimaryCurrencyAmount(PiggyBankEvent $event): void { - $user = $event->piggyBank->accounts()->first()?->user; + $user = $event->piggyBank->accounts()->first()?->user; if (null === $user) { Log::warning('Piggy bank seems to have no accounts. Break.'); @@ -48,10 +48,10 @@ class PiggyBankEventObserver if (!Amount::convertToPrimary($user)) { return; } - $userCurrency = Amount::getPrimaryCurrencyByUserGroup($event->piggyBank->accounts()->first()->user->userGroup); + $userCurrency = Amount::getPrimaryCurrencyByUserGroup($event->piggyBank->accounts()->first()->user->userGroup); $event->native_amount = null; if ($event->piggyBank->transactionCurrency->id !== $userCurrency->id) { - $converter = new ExchangeRateConverter(); + $converter = new ExchangeRateConverter(); $converter->setUserGroup($event->piggyBank->accounts()->first()->user->userGroup); $converter->setIgnoreSettings(true); $event->native_amount = $converter->convert($event->piggyBank->transactionCurrency, $userCurrency, today(), $event->amount); diff --git a/app/Handlers/Observer/PiggyBankObserver.php b/app/Handlers/Observer/PiggyBankObserver.php index 214ceed224..9a3159ceda 100644 --- a/app/Handlers/Observer/PiggyBankObserver.php +++ b/app/Handlers/Observer/PiggyBankObserver.php @@ -27,9 +27,9 @@ namespace FireflyIII\Handlers\Observer; use FireflyIII\Models\Attachment; use FireflyIII\Models\PiggyBank; use FireflyIII\Repositories\Attachment\AttachmentRepositoryInterface; +use FireflyIII\Support\Facades\Amount; use FireflyIII\Support\Http\Api\ExchangeRateConverter; use Illuminate\Support\Facades\Log; -use FireflyIII\Support\Facades\Amount; /** * Class PiggyBankObserver @@ -44,16 +44,16 @@ class PiggyBankObserver private function updatePrimaryCurrencyAmount(PiggyBank $piggyBank): void { - $group = $piggyBank->accounts()->first()?->user->userGroup; + $group = $piggyBank->accounts()->first()?->user->userGroup; if (null === $group) { Log::debug(sprintf('No account(s) yet for piggy bank #%d.', $piggyBank->id)); return; } - $userCurrency = Amount::getPrimaryCurrencyByUserGroup($group); + $userCurrency = Amount::getPrimaryCurrencyByUserGroup($group); $piggyBank->native_target_amount = null; if ($piggyBank->transactionCurrency->id !== $userCurrency->id) { - $converter = new ExchangeRateConverter(); + $converter = new ExchangeRateConverter(); $converter->setIgnoreSettings(true); $converter->setUserGroup($group); $piggyBank->native_target_amount = $converter->convert($piggyBank->transactionCurrency, $userCurrency, today(), $piggyBank->target_amount); diff --git a/app/Handlers/Observer/TransactionJournalObserver.php b/app/Handlers/Observer/TransactionJournalObserver.php index 94b7b27a33..810978f51c 100644 --- a/app/Handlers/Observer/TransactionJournalObserver.php +++ b/app/Handlers/Observer/TransactionJournalObserver.php @@ -42,7 +42,6 @@ class TransactionJournalObserver $repository = app(AttachmentRepositoryInterface::class); $repository->setUser($transactionJournal->user); - // to make sure the listener doesn't get back to use and loop TransactionJournal::withoutEvents(static function () use ($transactionJournal): void { foreach ($transactionJournal->transactions()->get() as $transaction) { @@ -79,8 +78,5 @@ class TransactionJournalObserver $transactionJournal->auditLogEntries()->delete(); // set all transactions AFTER this one to balance_dirty for recalc. - - - } } diff --git a/app/Handlers/Observer/TransactionObserver.php b/app/Handlers/Observer/TransactionObserver.php index 2f542a67c8..4bf674defb 100644 --- a/app/Handlers/Observer/TransactionObserver.php +++ b/app/Handlers/Observer/TransactionObserver.php @@ -41,7 +41,12 @@ class TransactionObserver public function created(Transaction $transaction): void { Log::debug('Observe "created" of a transaction.'); - if (true === FireflyConfig::get('use_running_balance', config('firefly.feature_flags.running_balance_column'))->data && (1 === bccomp($transaction->amount, '0') && self::$recalculate)) { + if ( + true === FireflyConfig::get('use_running_balance', config('firefly.feature_flags.running_balance_column'))->data && ( + 1 === bccomp($transaction->amount, '0') + && self::$recalculate + ) + ) { Log::debug('Trigger recalculateForJournal'); $journal = $transaction->transactionJournal; if ($journal instanceof TransactionJournal) { @@ -56,32 +61,46 @@ class TransactionObserver if (!Amount::convertToPrimary($transaction->transactionJournal->user)) { return; } - $userCurrency = Amount::getPrimaryCurrencyByUserGroup($transaction->transactionJournal->user->userGroup); - $transaction->native_amount = null; + $userCurrency = Amount::getPrimaryCurrencyByUserGroup($transaction->transactionJournal->user->userGroup); + $transaction->native_amount = null; $transaction->native_foreign_amount = null; // first normal amount - if ($transaction->transactionCurrency->id !== $userCurrency->id - && (null === $transaction->foreign_currency_id - || (null !== $transaction->foreign_currency_id - && $transaction->foreign_currency_id !== $userCurrency->id))) { - $converter = new ExchangeRateConverter(); + if ( + $transaction->transactionCurrency->id !== $userCurrency->id + && ( + null === $transaction->foreign_currency_id + || null !== $transaction->foreign_currency_id + && $transaction->foreign_currency_id !== $userCurrency->id + ) + ) { + $converter = new ExchangeRateConverter(); $converter->setUserGroup($transaction->transactionJournal->user->userGroup); $converter->setIgnoreSettings(true); - $transaction->native_amount = $converter->convert($transaction->transactionCurrency, $userCurrency, $transaction->transactionJournal->date, $transaction->amount); + $transaction->native_amount = $converter->convert( + $transaction->transactionCurrency, + $userCurrency, + $transaction->transactionJournal->date, + $transaction->amount + ); } // then foreign amount if ($transaction->foreignCurrency?->id !== $userCurrency->id && null !== $transaction->foreign_amount && null !== $transaction->foreignCurrency) { - $converter = new ExchangeRateConverter(); + $converter = new ExchangeRateConverter(); $converter->setUserGroup($transaction->transactionJournal->user->userGroup); $converter->setIgnoreSettings(true); - $transaction->native_foreign_amount = $converter->convert($transaction->foreignCurrency, $userCurrency, $transaction->transactionJournal->date, $transaction->foreign_amount); + $transaction->native_foreign_amount = $converter->convert( + $transaction->foreignCurrency, + $userCurrency, + $transaction->transactionJournal->date, + $transaction->foreign_amount + ); } $transaction->saveQuietly(); Log::debug(sprintf('Transaction #%d primary currency amounts are updated.', $transaction->id)); } - public function deleting(?Transaction $transaction): void + public function deleting(null|Transaction $transaction): void { Log::debug('Observe "deleting" of a transaction.'); $transaction?->transactionJournal?->delete(); @@ -90,7 +109,11 @@ class TransactionObserver public function updated(Transaction $transaction): void { // Log::debug('Observe "updated" of a transaction.'); - if (true === FireflyConfig::get('use_running_balance', config('firefly.feature_flags.running_balance_column'))->data && self::$recalculate && 1 === bccomp($transaction->amount, '0')) { + if ( + true === FireflyConfig::get('use_running_balance', config('firefly.feature_flags.running_balance_column'))->data + && self::$recalculate + && 1 === bccomp($transaction->amount, '0') + ) { Log::debug('Trigger recalculateForJournal'); AccountBalanceCalculator::recalculateForJournal($transaction->transactionJournal); } diff --git a/app/Helpers/Attachments/AttachmentHelper.php b/app/Helpers/Attachments/AttachmentHelper.php index 0a770a0560..beeecdb684 100644 --- a/app/Helpers/Attachments/AttachmentHelper.php +++ b/app/Helpers/Attachments/AttachmentHelper.php @@ -55,8 +55,8 @@ class AttachmentHelper implements AttachmentHelperInterface public Collection $attachments; public MessageBag $errors; public MessageBag $messages; - protected array $allowedMimes = []; - protected int $maxUploadSize = 0; + protected array $allowedMimes = []; + protected int $maxUploadSize = 0; protected Filesystem $uploadDisk; @@ -66,11 +66,11 @@ class AttachmentHelper implements AttachmentHelperInterface public function __construct() { $this->maxUploadSize = (int) config('firefly.maxUploadSize'); - $this->allowedMimes = (array) config('firefly.allowedMimes'); - $this->errors = new MessageBag(); - $this->messages = new MessageBag(); - $this->attachments = new Collection(); - $this->uploadDisk = Storage::disk('upload'); + $this->allowedMimes = (array) config('firefly.allowedMimes'); + $this->errors = new MessageBag(); + $this->messages = new MessageBag(); + $this->attachments = new Collection(); + $this->uploadDisk = Storage::disk('upload'); } /** @@ -143,7 +143,7 @@ class AttachmentHelper implements AttachmentHelperInterface return false; } - $path = stream_get_meta_data($resource)['uri']; + $path = stream_get_meta_data($resource)['uri']; Log::debug(sprintf('Path is %s', $path)); try { @@ -162,8 +162,8 @@ class AttachmentHelper implements AttachmentHelperInterface return false; } - $mime = (string) finfo_file($finfo, $path); - $allowedMime = config('firefly.allowedMimes'); + $mime = (string) finfo_file($finfo, $path); + $allowedMime = config('firefly.allowedMimes'); if (!in_array($mime, $allowedMime, true)) { Log::error(sprintf('Mime type %s is not allowed for API file upload.', $mime)); fclose($resource); @@ -172,15 +172,15 @@ class AttachmentHelper implements AttachmentHelperInterface } Log::debug(sprintf('Found mime "%s" in file "%s"', $mime, $path)); // is allowed? Save the file, without encryption. - $parts = explode('/', $attachment->fileName()); - $file = $parts[count($parts) - 1]; + $parts = explode('/', $attachment->fileName()); + $file = $parts[count($parts) - 1]; Log::debug(sprintf('Write file to disk in file named "%s"', $file)); $this->uploadDisk->put($file, $content); // update attachment. - $attachment->md5 = md5_file($path); - $attachment->mime = $mime; - $attachment->size = strlen($content); + $attachment->md5 = md5_file($path); + $attachment->mime = $mime; + $attachment->size = strlen($content); $attachment->uploaded = true; $attachment->save(); @@ -194,7 +194,7 @@ class AttachmentHelper implements AttachmentHelperInterface * * @throws FireflyException */ - public function saveAttachmentsForModel(object $model, ?array $files): bool + public function saveAttachmentsForModel(object $model, null|array $files): bool { if (!$model instanceof Model) { return false; @@ -224,30 +224,30 @@ class AttachmentHelper implements AttachmentHelperInterface * * @throws StringsException */ - protected function processFile(UploadedFile $file, Model $model): ?Attachment + protected function processFile(UploadedFile $file, Model $model): null|Attachment { Log::debug('Now in processFile()'); $validation = $this->validateUpload($file, $model); $attachment = null; if ($validation) { - $user = $model->user; + $user = $model->user; // ignore lines about polymorphic calls. if ($model instanceof PiggyBank) { $user = $model->account->user; } - $attachment = new Attachment(); // create Attachment object. + $attachment = new Attachment(); // create Attachment object. $attachment->user()->associate($user); $attachment->attachable()->associate($model); - $attachment->md5 = md5_file($file->getRealPath()); + $attachment->md5 = md5_file($file->getRealPath()); $attachment->filename = $file->getClientOriginalName(); - $attachment->mime = $file->getMimeType(); - $attachment->size = $file->getSize(); + $attachment->mime = $file->getMimeType(); + $attachment->size = $file->getSize(); $attachment->uploaded = false; $attachment->save(); Log::debug('Created attachment:', $attachment->toArray()); - $fileObject = $file->openFile(); + $fileObject = $file->openFile(); $fileObject->rewind(); if (0 === $file->getSize()) { @@ -256,7 +256,7 @@ class AttachmentHelper implements AttachmentHelperInterface return null; } - $content = (string) $fileObject->fread($file->getSize()); + $content = (string) $fileObject->fread($file->getSize()); Log::debug(sprintf('Full file length is %d and upload size is %d.', strlen($content), $file->getSize())); // store it without encryption. @@ -265,8 +265,8 @@ class AttachmentHelper implements AttachmentHelperInterface $attachment->save(); $this->attachments->push($attachment); - $name = e($file->getClientOriginalName()); // add message: - $msg = (string) trans('validation.file_attached', ['name' => $name]); + $name = e($file->getClientOriginalName()); // add message: + $msg = (string) trans('validation.file_attached', ['name' => $name]); $this->messages->add('attachments', $msg); } @@ -306,14 +306,14 @@ class AttachmentHelper implements AttachmentHelperInterface protected function validMime(UploadedFile $file): bool { Log::debug('Now in validMime()'); - $mime = e($file->getMimeType()); - $name = e($file->getClientOriginalName()); + $mime = e($file->getMimeType()); + $name = e($file->getClientOriginalName()); Log::debug(sprintf('Name is %s, and mime is %s', $name, $mime)); Log::debug('Valid mimes are', $this->allowedMimes); $result = true; if (!in_array($mime, $this->allowedMimes, true)) { - $msg = (string) trans('validation.file_invalid_mime', ['name' => $name, 'mime' => $mime]); + $msg = (string) trans('validation.file_invalid_mime', ['name' => $name, 'mime' => $mime]); $this->errors->add('attachments', $msg); Log::error($msg); @@ -332,7 +332,7 @@ class AttachmentHelper implements AttachmentHelperInterface $name = e($file->getClientOriginalName()); $result = true; if ($size > $this->maxUploadSize) { - $msg = (string) trans('validation.file_too_large', ['name' => $name]); + $msg = (string) trans('validation.file_too_large', ['name' => $name]); $this->errors->add('attachments', $msg); Log::error($msg); @@ -347,10 +347,10 @@ class AttachmentHelper implements AttachmentHelperInterface */ protected function hasFile(UploadedFile $file, Model $model): bool { - $md5 = md5_file($file->getRealPath()); - $name = $file->getClientOriginalName(); - $class = $model::class; - $count = 0; + $md5 = md5_file($file->getRealPath()); + $name = $file->getClientOriginalName(); + $class = $model::class; + $count = 0; // ignore lines about polymorphic calls. if ($model instanceof PiggyBank) { $count = $model->account->user->attachments()->where('md5', $md5)->where('attachable_id', $model->id)->where('attachable_type', $class)->count(); @@ -360,7 +360,7 @@ class AttachmentHelper implements AttachmentHelperInterface } $result = false; if ($count > 0) { - $msg = (string) trans('validation.file_already_attached', ['name' => $name]); + $msg = (string) trans('validation.file_already_attached', ['name' => $name]); $this->errors->add('attachments', $msg); Log::error($msg); $result = true; diff --git a/app/Helpers/Attachments/AttachmentHelperInterface.php b/app/Helpers/Attachments/AttachmentHelperInterface.php index 4640d5deb8..2434f75ef1 100644 --- a/app/Helpers/Attachments/AttachmentHelperInterface.php +++ b/app/Helpers/Attachments/AttachmentHelperInterface.php @@ -65,5 +65,5 @@ interface AttachmentHelperInterface /** * Save attachments that got uploaded. */ - public function saveAttachmentsForModel(object $model, ?array $files): bool; + public function saveAttachmentsForModel(object $model, null|array $files): bool; } diff --git a/app/Helpers/Collector/Extensions/AccountCollection.php b/app/Helpers/Collector/Extensions/AccountCollection.php index ba51cd07f4..4a02c20357 100644 --- a/app/Helpers/Collector/Extensions/AccountCollection.php +++ b/app/Helpers/Collector/Extensions/AccountCollection.php @@ -47,7 +47,7 @@ trait AccountCollection * * @return bool */ - $filter = static function (array $object) use ($direction, $operator, $value): bool { + $filter = static function (array $object) use ($direction, $operator, $value): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { $key = sprintf('%s_account_id', $direction); @@ -58,7 +58,7 @@ trait AccountCollection // in theory, this could lead to finding other users accounts. /** @var null|Account $account */ - $account = Account::find($accountId); + $account = Account::find($accountId); if (null === $account) { continue; } @@ -67,9 +67,14 @@ trait AccountCollection // the balance must be found BEFORE the transaction date. // so inclusive = false Log::debug(sprintf('accountBalanceIs: Call accountsBalancesOptimized with date/time "%s"', $transaction['date']->toIso8601String())); - $balance = Steam::accountsBalancesOptimized(new Collection()->push($account), $transaction['date'], convertToPrimary: null, inclusive: false)[$account->id]; + $balance = Steam::accountsBalancesOptimized( + new Collection()->push($account), + $transaction['date'], + convertToPrimary: null, + inclusive: false + )[$account->id]; // $balance = Steam::finalAccountBalance($account, $date); - $result = bccomp((string) $balance['balance'], $value); + $result = bccomp((string) $balance['balance'], $value); Log::debug(sprintf('"%s" vs "%s" is %d', $balance['balance'], $value, $result)); switch ($operator) { @@ -108,8 +113,8 @@ trait AccountCollection return 1 !== $result; } - // if($balance['balance'] $operator $value) { + // if($balance['balance'] $operator $value) { // } } @@ -173,12 +178,11 @@ trait AccountCollection { if ($accounts->count() > 0) { $accountIds = $accounts->pluck('id')->toArray(); - $this->query->where( - static function (EloquentBuilder $query) use ($accountIds): void { // @phpstan-ignore-line - $query->whereIn('source.account_id', $accountIds); - $query->orWhereIn('destination.account_id', $accountIds); - } - ); + $this->query->where(static function (EloquentBuilder $query) use ($accountIds): void { // @phpstan-ignore-line + $query->whereIn('source.account_id', $accountIds); + $query->orWhereIn('destination.account_id', $accountIds); + }); + // Log::debug(sprintf('GroupCollector: setAccounts: %s', implode(', ', $accountIds))); } @@ -192,12 +196,10 @@ trait AccountCollection { if ($accounts->count() > 0) { $accountIds = $accounts->pluck('id')->toArray(); - $this->query->where( - static function (EloquentBuilder $query) use ($accountIds): void { // @phpstan-ignore-line - $query->whereIn('source.account_id', $accountIds); - $query->whereIn('destination.account_id', $accountIds); - } - ); + $this->query->where(static function (EloquentBuilder $query) use ($accountIds): void { // @phpstan-ignore-line + $query->whereIn('source.account_id', $accountIds); + $query->whereIn('destination.account_id', $accountIds); + }); Log::debug(sprintf('GroupCollector: setBothAccounts: %s', implode(', ', $accountIds))); } @@ -226,12 +228,11 @@ trait AccountCollection { if ($accounts->count() > 0) { $accountIds = $accounts->pluck('id')->toArray(); - $this->query->where( - static function (EloquentBuilder $query) use ($accountIds): void { // @phpstan-ignore-line - $query->whereNotIn('source.account_id', $accountIds); - $query->whereNotIn('destination.account_id', $accountIds); - } - ); + $this->query->where(static function (EloquentBuilder $query) use ($accountIds): void { // @phpstan-ignore-line + $query->whereNotIn('source.account_id', $accountIds); + $query->whereNotIn('destination.account_id', $accountIds); + }); + // Log::debug(sprintf('GroupCollector: setAccounts: %s', implode(', ', $accountIds))); } @@ -260,25 +261,19 @@ trait AccountCollection { if ($accounts->count() > 0) { $accountIds = $accounts->pluck('id')->toArray(); - $this->query->where( - static function (EloquentBuilder $q1) use ($accountIds): void { // @phpstan-ignore-line - // sourceAccount is in the set, and destination is NOT. + $this->query->where(static function (EloquentBuilder $q1) use ($accountIds): void { // @phpstan-ignore-line + // sourceAccount is in the set, and destination is NOT. - $q1->where( - static function (EloquentBuilder $q2) use ($accountIds): void { - $q2->whereIn('source.account_id', $accountIds); - $q2->whereNotIn('destination.account_id', $accountIds); - } - ); - // destination is in the set, and source is NOT - $q1->orWhere( - static function (EloquentBuilder $q3) use ($accountIds): void { - $q3->whereNotIn('source.account_id', $accountIds); - $q3->whereIn('destination.account_id', $accountIds); - } - ); - } - ); + $q1->where(static function (EloquentBuilder $q2) use ($accountIds): void { + $q2->whereIn('source.account_id', $accountIds); + $q2->whereNotIn('destination.account_id', $accountIds); + }); + // destination is in the set, and source is NOT + $q1->orWhere(static function (EloquentBuilder $q3) use ($accountIds): void { + $q3->whereNotIn('source.account_id', $accountIds); + $q3->whereIn('destination.account_id', $accountIds); + }); + }); Log::debug(sprintf('GroupCollector: setXorAccounts: %s', implode(', ', $accountIds))); } @@ -298,18 +293,18 @@ trait AccountCollection $this->query->leftJoin('account_types as source_account_type', 'source_account_type.id', '=', 'source_account.account_type_id'); // add source account fields: - $this->fields[] = 'source_account.name as source_account_name'; - $this->fields[] = 'source_account.iban as source_account_iban'; - $this->fields[] = 'source_account_type.type as source_account_type'; + $this->fields[] = 'source_account.name as source_account_name'; + $this->fields[] = 'source_account.iban as source_account_iban'; + $this->fields[] = 'source_account_type.type as source_account_type'; // same for dest $this->query->leftJoin('accounts as dest_account', 'dest_account.id', '=', 'destination.account_id'); $this->query->leftJoin('account_types as dest_account_type', 'dest_account_type.id', '=', 'dest_account.account_type_id'); // and add fields: - $this->fields[] = 'dest_account.name as destination_account_name'; - $this->fields[] = 'dest_account.iban as destination_account_iban'; - $this->fields[] = 'dest_account_type.type as destination_account_type'; + $this->fields[] = 'dest_account.name as destination_account_name'; + $this->fields[] = 'dest_account.iban as destination_account_iban'; + $this->fields[] = 'dest_account_type.type as destination_account_type'; $this->hasAccountInfo = true; } diff --git a/app/Helpers/Collector/Extensions/AmountCollection.php b/app/Helpers/Collector/Extensions/AmountCollection.php index b3195be07a..2ccf598e10 100644 --- a/app/Helpers/Collector/Extensions/AmountCollection.php +++ b/app/Helpers/Collector/Extensions/AmountCollection.php @@ -25,8 +25,8 @@ declare(strict_types=1); namespace FireflyIII\Helpers\Collector\Extensions; use FireflyIII\Helpers\Collector\GroupCollectorInterface; -use Illuminate\Database\Eloquent\Builder as EloquentBuilder; use FireflyIII\Support\Facades\Steam; +use Illuminate\Database\Eloquent\Builder as EloquentBuilder; /** * Trait AmountCollection @@ -38,22 +38,18 @@ trait AmountCollection */ public function amountIs(string $amount): GroupCollectorInterface { - $this->query->where( - static function (EloquentBuilder $q) use ($amount): void { // @phpstan-ignore-line - $q->where('source.amount', Steam::negative($amount)); - } - ); + $this->query->where(static function (EloquentBuilder $q) use ($amount): void { // @phpstan-ignore-line + $q->where('source.amount', Steam::negative($amount)); + }); return $this; } public function amountIsNot(string $amount): GroupCollectorInterface { - $this->query->where( - static function (EloquentBuilder $q) use ($amount): void { // @phpstan-ignore-line - $q->where('source.amount', '!=', Steam::negative($amount)); - } - ); + $this->query->where(static function (EloquentBuilder $q) use ($amount): void { // @phpstan-ignore-line + $q->where('source.amount', '!=', Steam::negative($amount)); + }); return $this; } @@ -63,11 +59,9 @@ trait AmountCollection */ public function amountLess(string $amount): GroupCollectorInterface { - $this->query->where( - static function (EloquentBuilder $q) use ($amount): void { // @phpstan-ignore-line - $q->where('destination.amount', '<=', Steam::positive($amount)); - } - ); + $this->query->where(static function (EloquentBuilder $q) use ($amount): void { // @phpstan-ignore-line + $q->where('destination.amount', '<=', Steam::positive($amount)); + }); return $this; } @@ -77,11 +71,9 @@ trait AmountCollection */ public function amountMore(string $amount): GroupCollectorInterface { - $this->query->where( - static function (EloquentBuilder $q) use ($amount): void { // @phpstan-ignore-line - $q->where('destination.amount', '>=', Steam::positive($amount)); - } - ); + $this->query->where(static function (EloquentBuilder $q) use ($amount): void { // @phpstan-ignore-line + $q->where('destination.amount', '>=', Steam::positive($amount)); + }); return $this; } @@ -91,12 +83,10 @@ trait AmountCollection */ public function foreignAmountIs(string $amount): GroupCollectorInterface { - $this->query->where( - static function (EloquentBuilder $q) use ($amount): void { // @phpstan-ignore-line - $q->whereNotNull('source.foreign_amount'); - $q->where('source.foreign_amount', Steam::negative($amount)); - } - ); + $this->query->where(static function (EloquentBuilder $q) use ($amount): void { // @phpstan-ignore-line + $q->whereNotNull('source.foreign_amount'); + $q->where('source.foreign_amount', Steam::negative($amount)); + }); return $this; } @@ -106,12 +96,10 @@ trait AmountCollection */ public function foreignAmountIsNot(string $amount): GroupCollectorInterface { - $this->query->where( - static function (EloquentBuilder $q) use ($amount): void { // @phpstan-ignore-line - $q->whereNull('source.foreign_amount'); - $q->orWhere('source.foreign_amount', '!=', Steam::negative($amount)); - } - ); + $this->query->where(static function (EloquentBuilder $q) use ($amount): void { // @phpstan-ignore-line + $q->whereNull('source.foreign_amount'); + $q->orWhere('source.foreign_amount', '!=', Steam::negative($amount)); + }); return $this; } @@ -121,12 +109,10 @@ trait AmountCollection */ public function foreignAmountLess(string $amount): GroupCollectorInterface { - $this->query->where( - static function (EloquentBuilder $q) use ($amount): void { // @phpstan-ignore-line - $q->whereNotNull('destination.foreign_amount'); - $q->where('destination.foreign_amount', '<=', Steam::positive($amount)); - } - ); + $this->query->where(static function (EloquentBuilder $q) use ($amount): void { // @phpstan-ignore-line + $q->whereNotNull('destination.foreign_amount'); + $q->where('destination.foreign_amount', '<=', Steam::positive($amount)); + }); return $this; } @@ -136,12 +122,10 @@ trait AmountCollection */ public function foreignAmountMore(string $amount): GroupCollectorInterface { - $this->query->where( - static function (EloquentBuilder $q) use ($amount): void { // @phpstan-ignore-line - $q->whereNotNull('destination.foreign_amount'); - $q->where('destination.foreign_amount', '>=', Steam::positive($amount)); - } - ); + $this->query->where(static function (EloquentBuilder $q) use ($amount): void { // @phpstan-ignore-line + $q->whereNotNull('destination.foreign_amount'); + $q->where('destination.foreign_amount', '>=', Steam::positive($amount)); + }); return $this; } diff --git a/app/Helpers/Collector/Extensions/AttachmentCollection.php b/app/Helpers/Collector/Extensions/AttachmentCollection.php index 80e016a880..b512cd9a9c 100644 --- a/app/Helpers/Collector/Extensions/AttachmentCollection.php +++ b/app/Helpers/Collector/Extensions/AttachmentCollection.php @@ -45,15 +45,14 @@ trait AttachmentCollection * * @return bool */ - $filter = static function (array $object) use ($name): bool { + $filter = static function (array $object) use ($name): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ foreach ($transaction['attachments'] as $attachment) { - $result = str_contains(strtolower((string) $attachment['filename']), strtolower($name)) || str_contains( - strtolower((string) $attachment['title']), - strtolower($name) - ); + $result = + str_contains(strtolower((string) $attachment['filename']), strtolower($name)) + || str_contains(strtolower((string) $attachment['title']), strtolower($name)); if ($result) { return true; } @@ -88,16 +87,14 @@ trait AttachmentCollection if (false === $this->hasJoinedAttTables) { // join some extra tables: $this->hasJoinedAttTables = true; - $this->query->leftJoin('attachments', 'attachments.attachable_id', '=', 'transaction_journals.id') - ->where( - static function (EloquentBuilder $q1): void { // @phpstan-ignore-line - $q1->where('attachments.attachable_type', TransactionJournal::class); - // $q1->where('attachments.uploaded', true); - // $q1->whereNull('attachments.deleted_at'); - $q1->orWhereNull('attachments.attachable_type'); - } - ) - ; + $this->query + ->leftJoin('attachments', 'attachments.attachable_id', '=', 'transaction_journals.id') + ->where(static function (EloquentBuilder $q1): void { // @phpstan-ignore-line + $q1->where('attachments.attachable_type', TransactionJournal::class); + // $q1->where('attachments.uploaded', true); + // $q1->whereNull('attachments.deleted_at'); + $q1->orWhereNull('attachments.attachable_type'); + }); } } @@ -125,15 +122,14 @@ trait AttachmentCollection * * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - $filter = static function (array $object) use ($name): bool { + $filter = static function (array $object) use ($name): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ foreach ($transaction['attachments'] as $attachment) { - $result = !str_contains(strtolower((string) $attachment['filename']), strtolower($name)) && !str_contains( - strtolower((string) $attachment['title']), - strtolower($name) - ); + $result = + !str_contains(strtolower((string) $attachment['filename']), strtolower($name)) + && !str_contains(strtolower((string) $attachment['title']), strtolower($name)); if ($result) { return true; } @@ -159,15 +155,14 @@ trait AttachmentCollection * * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - $filter = static function (array $object) use ($name): bool { + $filter = static function (array $object) use ($name): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ foreach ($transaction['attachments'] as $attachment) { - $result = !str_ends_with(strtolower((string) $attachment['filename']), strtolower($name)) && !str_ends_with( - strtolower((string) $attachment['title']), - strtolower($name) - ); + $result = + !str_ends_with(strtolower((string) $attachment['filename']), strtolower($name)) + && !str_ends_with(strtolower((string) $attachment['title']), strtolower($name)); if ($result) { return true; } @@ -193,15 +188,14 @@ trait AttachmentCollection * * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - $filter = static function (array $object) use ($name): bool { + $filter = static function (array $object) use ($name): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ foreach ($transaction['attachments'] as $attachment) { - $result = !str_starts_with(strtolower((string) $attachment['filename']), strtolower($name)) && !str_starts_with( - strtolower((string) $attachment['title']), - strtolower($name) - ); + $result = + !str_starts_with(strtolower((string) $attachment['filename']), strtolower($name)) + && !str_starts_with(strtolower((string) $attachment['title']), strtolower($name)); if ($result) { return true; } @@ -219,15 +213,14 @@ trait AttachmentCollection { $this->hasAttachments(); $this->withAttachmentInformation(); - $filter = static function (array $object) use ($name): bool { + $filter = static function (array $object) use ($name): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ foreach ($transaction['attachments'] as $attachment) { - $result = str_ends_with(strtolower((string) $attachment['filename']), strtolower($name)) || str_ends_with( - strtolower((string) $attachment['title']), - strtolower($name) - ); + $result = + str_ends_with(strtolower((string) $attachment['filename']), strtolower($name)) + || str_ends_with(strtolower((string) $attachment['title']), strtolower($name)); if ($result) { return true; } @@ -245,7 +238,7 @@ trait AttachmentCollection { $this->hasAttachments(); $this->withAttachmentInformation(); - $filter = static function (array $object) use ($name): bool { + $filter = static function (array $object) use ($name): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ @@ -268,7 +261,7 @@ trait AttachmentCollection { $this->hasAttachments(); $this->withAttachmentInformation(); - $filter = static function (array $object) use ($name): bool { + $filter = static function (array $object) use ($name): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ @@ -291,15 +284,14 @@ trait AttachmentCollection { $this->hasAttachments(); $this->withAttachmentInformation(); - $filter = static function (array $object) use ($name): bool { + $filter = static function (array $object) use ($name): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ foreach ($transaction['attachments'] as $attachment) { - $result = str_starts_with(strtolower((string) $attachment['filename']), strtolower($name)) || str_starts_with( - strtolower((string) $attachment['title']), - strtolower($name) - ); + $result = + str_starts_with(strtolower((string) $attachment['filename']), strtolower($name)) + || str_starts_with(strtolower((string) $attachment['title']), strtolower($name)); if ($result) { return true; } @@ -317,7 +309,7 @@ trait AttachmentCollection { $this->hasAttachments(); $this->withAttachmentInformation(); - $filter = static function (array $object) use ($value): bool { + $filter = static function (array $object) use ($value): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ @@ -341,7 +333,7 @@ trait AttachmentCollection { $this->hasAttachments(); $this->withAttachmentInformation(); - $filter = static function (array $object) use ($value): bool { + $filter = static function (array $object) use ($value): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ @@ -365,7 +357,7 @@ trait AttachmentCollection { $this->hasAttachments(); $this->withAttachmentInformation(); - $filter = static function (array $object) use ($value): bool { + $filter = static function (array $object) use ($value): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ @@ -389,7 +381,7 @@ trait AttachmentCollection { $this->hasAttachments(); $this->withAttachmentInformation(); - $filter = static function (array $object) use ($value): bool { + $filter = static function (array $object) use ($value): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ @@ -413,7 +405,7 @@ trait AttachmentCollection { $this->hasAttachments(); $this->withAttachmentInformation(); - $filter = static function (array $object) use ($value): bool { + $filter = static function (array $object) use ($value): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ @@ -437,7 +429,7 @@ trait AttachmentCollection { $this->hasAttachments(); $this->withAttachmentInformation(); - $filter = static function (array $object) use ($value): bool { + $filter = static function (array $object) use ($value): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ @@ -461,7 +453,7 @@ trait AttachmentCollection { $this->hasAttachments(); $this->withAttachmentInformation(); - $filter = static function (array $object) use ($value): bool { + $filter = static function (array $object) use ($value): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ @@ -485,7 +477,7 @@ trait AttachmentCollection { $this->hasAttachments(); $this->withAttachmentInformation(); - $filter = static function (array $object) use ($value): bool { + $filter = static function (array $object) use ($value): bool { /** @var array $transaction */ foreach ($object['transactions'] as $transaction) { /** @var array $attachment */ @@ -514,17 +506,12 @@ trait AttachmentCollection $this->joinAttachmentTables(); $this->query->where(static function (EloquentBuilder $q1): void { // @phpstan-ignore-line - $q1 - ->whereNull('attachments.attachable_id') - ->orWhere(static function (EloquentBuilder $q2): void { - $q2 - ->whereNotNull('attachments.attachable_id') - ->whereNotNull('attachments.deleted_at') - ; - // id is not null - // deleted at is not null. - }) - ; + $q1->whereNull('attachments.attachable_id')->orWhere(static function (EloquentBuilder $q2): void { + $q2->whereNotNull('attachments.attachable_id')->whereNotNull('attachments.deleted_at'); + + // id is not null + // deleted at is not null. + }); }); return $this; diff --git a/app/Helpers/Collector/Extensions/CollectorProperties.php b/app/Helpers/Collector/Extensions/CollectorProperties.php index ae21d08041..8f7745e4d5 100644 --- a/app/Helpers/Collector/Extensions/CollectorProperties.php +++ b/app/Helpers/Collector/Extensions/CollectorProperties.php @@ -36,33 +36,33 @@ trait CollectorProperties public const string TEST = 'Test'; /** @var array */ - public array $sorting; - private array $booleanFields; - private ?int $endRow; - private bool $expandGroupSearch; - private array $fields; - private bool $hasAccountInfo; - private bool $hasBillInformation; - private bool $hasBudgetInformation; - private bool $hasCatInformation; - private bool $hasJoinedAttTables; - private bool $hasJoinedMetaTables; - private bool $hasJoinedTagTables; - private bool $hasNotesInformation; - private array $integerFields; - private ?int $limit; - private ?int $page; - private array $postFilters; + public array $sorting; + private array $booleanFields; + private null|int $endRow; + private bool $expandGroupSearch; + private array $fields; + private bool $hasAccountInfo; + private bool $hasBillInformation; + private bool $hasBudgetInformation; + private bool $hasCatInformation; + private bool $hasJoinedAttTables; + private bool $hasJoinedMetaTables; + private bool $hasJoinedTagTables; + private bool $hasNotesInformation; + private array $integerFields; + private null|int $limit; + private null|int $page; + private array $postFilters; private HasMany $query; - private ?int $startRow; - private array $stringFields; + private null|int $startRow; + private array $stringFields; /* * This array is used to collect ALL tags the user may search for (using 'setTags'). * This way the user can call 'setTags' multiple times and get a joined result. * */ - private array $tags; - private int $total; - private ?User $user; - private ?UserGroup $userGroup; + private array $tags; + private int $total; + private null|User $user; + private null|UserGroup $userGroup; } diff --git a/app/Helpers/Collector/Extensions/MetaCollection.php b/app/Helpers/Collector/Extensions/MetaCollection.php index bcfc737002..0a7005b91e 100644 --- a/app/Helpers/Collector/Extensions/MetaCollection.php +++ b/app/Helpers/Collector/Extensions/MetaCollection.php @@ -63,8 +63,8 @@ trait MetaCollection // join bill table $this->query->leftJoin('bills', 'bills.id', '=', 'transaction_journals.bill_id'); // add fields - $this->fields[] = 'bills.id as bill_id'; - $this->fields[] = 'bills.name as bill_name'; + $this->fields[] = 'bills.id as bill_id'; + $this->fields[] = 'bills.name as bill_name'; $this->hasBillInformation = true; } @@ -97,8 +97,8 @@ trait MetaCollection // join cat table $this->query->leftJoin('budgets', 'budget_transaction_journal.budget_id', '=', 'budgets.id'); // add fields - $this->fields[] = 'budgets.id as budget_id'; - $this->fields[] = 'budgets.name as budget_name'; + $this->fields[] = 'budgets.id as budget_id'; + $this->fields[] = 'budgets.name as budget_name'; $this->hasBudgetInformation = true; } @@ -142,8 +142,8 @@ trait MetaCollection // join cat table $this->query->leftJoin('categories', 'category_transaction_journal.category_id', '=', 'categories.id'); // add fields - $this->fields[] = 'categories.id as category_id'; - $this->fields[] = 'categories.name as category_name'; + $this->fields[] = 'categories.id as category_id'; + $this->fields[] = 'categories.name as category_name'; $this->hasCatInformation = true; } @@ -183,8 +183,8 @@ trait MetaCollection if (false === $this->hasJoinedMetaTables) { $this->hasJoinedMetaTables = true; $this->query->leftJoin('journal_meta', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id'); - $this->fields[] = 'journal_meta.name as meta_name'; - $this->fields[] = 'journal_meta.data as meta_data'; + $this->fields[] = 'journal_meta.name as meta_name'; + $this->fields[] = 'journal_meta.data as meta_data'; } } @@ -491,16 +491,13 @@ trait MetaCollection { if (false === $this->hasNotesInformation) { // join bill table - $this->query->leftJoin( - 'notes', - static function (JoinClause $join): void { - $join->on('notes.noteable_id', '=', 'transaction_journals.id'); - $join->where('notes.noteable_type', '=', TransactionJournal::class); - $join->whereNull('notes.deleted_at'); - } - ); + $this->query->leftJoin('notes', static function (JoinClause $join): void { + $join->on('notes.noteable_id', '=', 'transaction_journals.id'); + $join->where('notes.noteable_type', '=', TransactionJournal::class); + $join->whereNull('notes.deleted_at'); + }); // add fields - $this->fields[] = 'notes.text as notes'; + $this->fields[] = 'notes.text as notes'; $this->hasNotesInformation = true; } @@ -585,16 +582,16 @@ trait MetaCollection $this->query->whereNotNull('tag_transaction_journal.tag_id'); // this method adds a "postFilter" to the collector. - $list = $tags->pluck('tag')->toArray(); - $list = array_map(strtolower(...), $list); - $filter = static function (array $object) use ($list): bool|array { - $includedJournals = []; - $return = $object; + $list = $tags->pluck('tag')->toArray(); + $list = array_map(strtolower(...), $list); + $filter = static function (array $object) use ($list): bool|array { + $includedJournals = []; + $return = $object; unset($return['transactions']); $return['transactions'] = []; Log::debug(sprintf('Now in setAllTags(%s) filter', implode(', ', $list))); - $expectedTagCount = count($list); - $foundTagCount = 0; + $expectedTagCount = count($list); + $foundTagCount = 0; foreach ($object['transactions'] as $transaction) { $transactionTagCount = count($transaction['tags']); Log::debug(sprintf('Transaction #%d has %d tag(s)', $transaction['transaction_journal_id'], $transactionTagCount)); @@ -611,7 +608,7 @@ trait MetaCollection $journalId = $transaction['transaction_journal_id']; // #8377 prevent adding a transaction twice when multiple tag searches find this transaction if (!in_array($journalId, $includedJournals, true)) { - $includedJournals[] = $journalId; + $includedJournals[] = $journalId; $return['transactions'][] = $transaction; } } @@ -620,7 +617,7 @@ trait MetaCollection Log::debug(sprintf('Found %d tags, need at least %d.', $foundTagCount, $expectedTagCount)); // found at least the expected tags. - $result = $foundTagCount >= $expectedTagCount; + $result = $foundTagCount >= $expectedTagCount; if ($result) { return $return; } @@ -779,9 +776,9 @@ trait MetaCollection $this->query->whereIn('tag_transaction_journal.tag_id', $tags->pluck('id')->toArray()); // this method adds a "postFilter" to the collector. - $list = $tags->pluck('tag')->toArray(); - $list = array_map(strtolower(...), $list); - $filter = static function (array $object) use ($list): bool { + $list = $tags->pluck('tag')->toArray(); + $list = array_map(strtolower(...), $list); + $filter = static function (array $object) use ($list): bool { Log::debug(sprintf('Now in setTags(%s) filter', implode(', ', $list))); foreach ($object['transactions'] as $transaction) { $total = count($transaction['tags']); @@ -819,9 +816,9 @@ trait MetaCollection $this->withTagInformation(); // this method adds a "postFilter" to the collector. - $list = $tags->pluck('tag')->toArray(); - $list = array_map(strtolower(...), $list); - $filter = static function (array $object) use ($list): bool { + $list = $tags->pluck('tag')->toArray(); + $list = array_map(strtolower(...), $list); + $filter = static function (array $object) use ($list): bool { Log::debug(sprintf('Now in setWithoutSpecificTags(%s) filter', implode(', ', $list))); foreach ($object['transactions'] as $transaction) { Log::debug(sprintf('Transaction has %d tag(s)', count($transaction['tags']))); diff --git a/app/Helpers/Collector/Extensions/TimeCollection.php b/app/Helpers/Collector/Extensions/TimeCollection.php index b20a860e88..3e8180a742 100644 --- a/app/Helpers/Collector/Extensions/TimeCollection.php +++ b/app/Helpers/Collector/Extensions/TimeCollection.php @@ -65,12 +65,12 @@ trait TimeCollection if ($end < $start) { [$start, $end] = [$end, $start]; } - $end = clone $end; // this is so weird, but it works if $end and $start secretly point to the same object. + $end = clone $end; // this is so weird, but it works if $end and $start secretly point to the same object. $end->endOfDay(); $start->startOfDay(); $this->withMetaDate($field); - $filter = static function (array $object) use ($field, $start, $end): bool { + $filter = static function (array $object) use ($field, $start, $end): bool { foreach ($object['transactions'] as $transaction) { if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { if ($transaction[$field]->lt($start)) { @@ -125,10 +125,9 @@ trait TimeCollection public function metaDayAfter(string $day, string $field): GroupCollectorInterface { $this->withMetaDate($field); - $filter = static function (array $object) use ($field, $day): bool { + $filter = static function (array $object) use ($field, $day): bool { foreach ($object['transactions'] as $transaction) { - if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon - ) { + if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { return $transaction[$field]->day >= (int) $day; } } @@ -143,10 +142,9 @@ trait TimeCollection public function metaDayBefore(string $day, string $field): GroupCollectorInterface { $this->withMetaDate($field); - $filter = static function (array $object) use ($field, $day): bool { + $filter = static function (array $object) use ($field, $day): bool { foreach ($object['transactions'] as $transaction) { - if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon - ) { + if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { return $transaction[$field]->day <= (int) $day; } } @@ -161,10 +159,9 @@ trait TimeCollection public function metaDayIs(string $day, string $field): GroupCollectorInterface { $this->withMetaDate($field); - $filter = static function (array $object) use ($field, $day): bool { + $filter = static function (array $object) use ($field, $day): bool { foreach ($object['transactions'] as $transaction) { - if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon - ) { + if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { return (int) $day === $transaction[$field]->day; } } @@ -179,10 +176,9 @@ trait TimeCollection public function metaDayIsNot(string $day, string $field): GroupCollectorInterface { $this->withMetaDate($field); - $filter = static function (array $object) use ($field, $day): bool { + $filter = static function (array $object) use ($field, $day): bool { foreach ($object['transactions'] as $transaction) { - if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon - ) { + if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { return (int) $day !== $transaction[$field]->day; } } @@ -197,10 +193,9 @@ trait TimeCollection public function metaMonthAfter(string $month, string $field): GroupCollectorInterface { $this->withMetaDate($field); - $filter = static function (array $object) use ($field, $month): bool { + $filter = static function (array $object) use ($field, $month): bool { foreach ($object['transactions'] as $transaction) { - if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon - ) { + if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { return $transaction[$field]->month >= (int) $month; } } @@ -215,10 +210,9 @@ trait TimeCollection public function metaMonthBefore(string $month, string $field): GroupCollectorInterface { $this->withMetaDate($field); - $filter = static function (array $object) use ($field, $month): bool { + $filter = static function (array $object) use ($field, $month): bool { foreach ($object['transactions'] as $transaction) { - if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon - ) { + if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { return $transaction[$field]->month <= (int) $month; } } @@ -233,10 +227,9 @@ trait TimeCollection public function metaMonthIs(string $month, string $field): GroupCollectorInterface { $this->withMetaDate($field); - $filter = static function (array $object) use ($field, $month): bool { + $filter = static function (array $object) use ($field, $month): bool { foreach ($object['transactions'] as $transaction) { - if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon - ) { + if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { return (int) $month === $transaction[$field]->month; } } @@ -251,10 +244,9 @@ trait TimeCollection public function metaMonthIsNot(string $month, string $field): GroupCollectorInterface { $this->withMetaDate($field); - $filter = static function (array $object) use ($field, $month): bool { + $filter = static function (array $object) use ($field, $month): bool { foreach ($object['transactions'] as $transaction) { - if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon - ) { + if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { return (int) $month !== $transaction[$field]->month; } } @@ -269,10 +261,9 @@ trait TimeCollection public function metaYearAfter(string $year, string $field): GroupCollectorInterface { $this->withMetaDate($field); - $filter = static function (array $object) use ($field, $year): bool { + $filter = static function (array $object) use ($field, $year): bool { foreach ($object['transactions'] as $transaction) { - if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon - ) { + if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { return $transaction[$field]->year >= (int) $year; } } @@ -287,10 +278,9 @@ trait TimeCollection public function metaYearBefore(string $year, string $field): GroupCollectorInterface { $this->withMetaDate($field); - $filter = static function (array $object) use ($field, $year): bool { + $filter = static function (array $object) use ($field, $year): bool { foreach ($object['transactions'] as $transaction) { - if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon - ) { + if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { return $transaction[$field]->year <= (int) $year; } } @@ -305,10 +295,9 @@ trait TimeCollection public function metaYearIs(string $year, string $field): GroupCollectorInterface { $this->withMetaDate($field); - $filter = static function (array $object) use ($field, $year): bool { + $filter = static function (array $object) use ($field, $year): bool { foreach ($object['transactions'] as $transaction) { - if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon - ) { + if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { return $year === (string) $transaction[$field]->year; } } @@ -323,10 +312,9 @@ trait TimeCollection public function metaYearIsNot(string $year, string $field): GroupCollectorInterface { $this->withMetaDate($field); - $filter = static function (array $object) use ($field, $year): bool { + $filter = static function (array $object) use ($field, $year): bool { foreach ($object['transactions'] as $transaction) { - if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon - ) { + if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { return $year !== (string) $transaction[$field]->year; } } @@ -502,10 +490,9 @@ trait TimeCollection { $this->withMetaDate($field); $date->startOfDay(); - $filter = static function (array $object) use ($field, $date): bool { + $filter = static function (array $object) use ($field, $date): bool { foreach ($object['transactions'] as $transaction) { - if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon - ) { + if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { return $transaction[$field]->gte($date); } } @@ -520,10 +507,9 @@ trait TimeCollection public function setMetaBefore(Carbon $date, string $field): GroupCollectorInterface { $this->withMetaDate($field); - $filter = static function (array $object) use ($field, $date): bool { + $filter = static function (array $object) use ($field, $date): bool { foreach ($object['transactions'] as $transaction) { - if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon - ) { + if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { return $transaction[$field]->lte($date); } } @@ -540,15 +526,14 @@ trait TimeCollection if ($end < $start) { [$start, $end] = [$end, $start]; } - $end = clone $end; // this is so weird, but it works if $end and $start secretly point to the same object. + $end = clone $end; // this is so weird, but it works if $end and $start secretly point to the same object. $end->endOfDay(); $start->startOfDay(); $this->withMetaDate($field); - $filter = static function (array $object) use ($field, $start, $end): bool { + $filter = static function (array $object) use ($field, $start, $end): bool { foreach ($object['transactions'] as $transaction) { - if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon - ) { + if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon) { return $transaction[$field]->gte($start) && $transaction[$field]->lte($end); } } @@ -591,7 +576,7 @@ trait TimeCollection * * Can either or both be NULL */ - public function setRange(?Carbon $start, ?Carbon $end): GroupCollectorInterface + public function setRange(null|Carbon $start, null|Carbon $end): GroupCollectorInterface { if ($start instanceof Carbon && $end instanceof Carbon && $end < $start) { [$start, $end] = [$end, $start]; diff --git a/app/Helpers/Collector/GroupCollector.php b/app/Helpers/Collector/GroupCollector.php index 0d2b7793c4..f6ef351d7b 100644 --- a/app/Helpers/Collector/GroupCollector.php +++ b/app/Helpers/Collector/GroupCollector.php @@ -68,27 +68,27 @@ class GroupCollector implements GroupCollectorInterface */ public function __construct() { - $this->sorting = []; - $this->postFilters = []; - $this->tags = []; - $this->user = null; - $this->userGroup = null; - $this->limit = null; - $this->page = null; - $this->startRow = null; - $this->endRow = null; + $this->sorting = []; + $this->postFilters = []; + $this->tags = []; + $this->user = null; + $this->userGroup = null; + $this->limit = null; + $this->page = null; + $this->startRow = null; + $this->endRow = null; - $this->hasAccountInfo = false; - $this->hasCatInformation = false; + $this->hasAccountInfo = false; + $this->hasCatInformation = false; $this->hasBudgetInformation = false; - $this->hasBillInformation = false; - $this->hasNotesInformation = false; - $this->hasJoinedTagTables = false; - $this->hasJoinedAttTables = false; - $this->expandGroupSearch = false; - $this->hasJoinedMetaTables = false; - $this->booleanFields = ['source_balance_dirty', 'destination_balance_dirty']; - $this->integerFields = [ + $this->hasBillInformation = false; + $this->hasNotesInformation = false; + $this->hasJoinedTagTables = false; + $this->hasJoinedAttTables = false; + $this->expandGroupSearch = false; + $this->hasJoinedMetaTables = false; + $this->booleanFields = ['source_balance_dirty', 'destination_balance_dirty']; + $this->integerFields = [ 'transaction_group_id', 'user_id', 'user_group_id', @@ -104,11 +104,11 @@ class GroupCollector implements GroupCollectorInterface 'destination_transaction_id', 'destination_account_id', 'category_id', - 'budget_id', + 'budget_id' ]; - $this->stringFields = ['amount', 'foreign_amount', 'pc_amount', 'pc_foreign_amount', 'source_balance_after', 'destination_balance_after']; - $this->total = 0; - $this->fields = [ + $this->stringFields = ['amount', 'foreign_amount', 'pc_amount', 'pc_foreign_amount', 'source_balance_after', 'destination_balance_after']; + $this->total = 0; + $this->fields = [ // group 'transaction_groups.id as transaction_group_id', 'transaction_groups.user_id as user_id', @@ -158,141 +158,111 @@ class GroupCollector implements GroupCollectorInterface // destination account info (always present) 'destination.account_id as destination_account_id', 'destination.balance_after as destination_balance_after', - 'destination.balance_dirty as destination_balance_dirty', + 'destination.balance_dirty as destination_balance_dirty' ]; } public function descriptionDoesNotEnd(array $array): GroupCollectorInterface { - $this->query->where( - static function (EloquentBuilder $q) use ($array): void { - $q->where( - static function (EloquentBuilder $q1) use ($array): void { - foreach ($array as $word) { - $keyword = sprintf('%%%s', $word); - $q1->whereNotLike('transaction_journals.description', $keyword); - } - } - ); - $q->where( - static function (EloquentBuilder $q2) use ($array): void { - foreach ($array as $word) { - $keyword = sprintf('%%%s', $word); - $q2->whereNotLike('transaction_groups.title', $keyword); - $q2->orWhereNull('transaction_groups.title'); - } - } - ); - } - ); + $this->query->where(static function (EloquentBuilder $q) use ($array): void { + $q->where(static function (EloquentBuilder $q1) use ($array): void { + foreach ($array as $word) { + $keyword = sprintf('%%%s', $word); + $q1->whereNotLike('transaction_journals.description', $keyword); + } + }); + $q->where(static function (EloquentBuilder $q2) use ($array): void { + foreach ($array as $word) { + $keyword = sprintf('%%%s', $word); + $q2->whereNotLike('transaction_groups.title', $keyword); + $q2->orWhereNull('transaction_groups.title'); + } + }); + }); return $this; } public function descriptionDoesNotStart(array $array): GroupCollectorInterface { - $this->query->where( - static function (EloquentBuilder $q) use ($array): void { - $q->where( - static function (EloquentBuilder $q1) use ($array): void { - foreach ($array as $word) { - $keyword = sprintf('%s%%', $word); - $q1->whereNotLike('transaction_journals.description', $keyword); - } - } - ); - $q->where( - static function (EloquentBuilder $q2) use ($array): void { - foreach ($array as $word) { - $keyword = sprintf('%s%%', $word); - $q2->whereNotLike('transaction_groups.title', $keyword); - $q2->orWhereNull('transaction_groups.title'); - } - } - ); - } - ); + $this->query->where(static function (EloquentBuilder $q) use ($array): void { + $q->where(static function (EloquentBuilder $q1) use ($array): void { + foreach ($array as $word) { + $keyword = sprintf('%s%%', $word); + $q1->whereNotLike('transaction_journals.description', $keyword); + } + }); + $q->where(static function (EloquentBuilder $q2) use ($array): void { + foreach ($array as $word) { + $keyword = sprintf('%s%%', $word); + $q2->whereNotLike('transaction_groups.title', $keyword); + $q2->orWhereNull('transaction_groups.title'); + } + }); + }); return $this; } public function descriptionEnds(array $array): GroupCollectorInterface { - $this->query->where( - static function (EloquentBuilder $q) use ($array): void { - $q->where( - static function (EloquentBuilder $q1) use ($array): void { - foreach ($array as $word) { - $keyword = sprintf('%%%s', $word); - $q1->whereLike('transaction_journals.description', $keyword); - } - } - ); - $q->orWhere( - static function (EloquentBuilder $q2) use ($array): void { - foreach ($array as $word) { - $keyword = sprintf('%%%s', $word); - $q2->whereLike('transaction_groups.title', $keyword); - } - } - ); - } - ); + $this->query->where(static function (EloquentBuilder $q) use ($array): void { + $q->where(static function (EloquentBuilder $q1) use ($array): void { + foreach ($array as $word) { + $keyword = sprintf('%%%s', $word); + $q1->whereLike('transaction_journals.description', $keyword); + } + }); + $q->orWhere(static function (EloquentBuilder $q2) use ($array): void { + foreach ($array as $word) { + $keyword = sprintf('%%%s', $word); + $q2->whereLike('transaction_groups.title', $keyword); + } + }); + }); return $this; } public function descriptionIs(string $value): GroupCollectorInterface { - $this->query->where( - static function (EloquentBuilder $q) use ($value): void { - $q->where('transaction_journals.description', '=', $value); - $q->orWhere('transaction_groups.title', '=', $value); - } - ); + $this->query->where(static function (EloquentBuilder $q) use ($value): void { + $q->where('transaction_journals.description', '=', $value); + $q->orWhere('transaction_groups.title', '=', $value); + }); return $this; } public function descriptionIsNot(string $value): GroupCollectorInterface { - $this->query->where( - static function (EloquentBuilder $q) use ($value): void { - $q->where('transaction_journals.description', '!=', $value); - $q->where( - static function (EloquentBuilder $q2) use ($value): void { - $q2->where('transaction_groups.title', '!=', $value); - $q2->orWhereNull('transaction_groups.title'); - } - ); - } - ); + $this->query->where(static function (EloquentBuilder $q) use ($value): void { + $q->where('transaction_journals.description', '!=', $value); + $q->where(static function (EloquentBuilder $q2) use ($value): void { + $q2->where('transaction_groups.title', '!=', $value); + $q2->orWhereNull('transaction_groups.title'); + }); + }); return $this; } public function descriptionStarts(array $array): GroupCollectorInterface { - $this->query->where( - static function (EloquentBuilder $q) use ($array): void { - $q->where( - static function (EloquentBuilder $q1) use ($array): void { - foreach ($array as $word) { - $keyword = sprintf('%s%%', $word); - $q1->whereLike('transaction_journals.description', $keyword); - } - } - ); - $q->orWhere( - static function (EloquentBuilder $q2) use ($array): void { - foreach ($array as $word) { - $keyword = sprintf('%s%%', $word); - $q2->whereLike('transaction_groups.title', $keyword); - } - } - ); - } - ); + $this->query->where(static function (EloquentBuilder $q) use ($array): void { + $q->where(static function (EloquentBuilder $q1) use ($array): void { + foreach ($array as $word) { + $keyword = sprintf('%s%%', $word); + $q1->whereLike('transaction_journals.description', $keyword); + } + }); + $q->orWhere(static function (EloquentBuilder $q2) use ($array): void { + foreach ($array as $word) { + $keyword = sprintf('%s%%', $word); + $q2->whereLike('transaction_groups.title', $keyword); + } + }); + }); return $this; } @@ -304,9 +274,9 @@ class GroupCollector implements GroupCollectorInterface foreach ($params as $param) { $replace = sprintf('"%s"', $param); if (is_int($param)) { - $replace = (string)$param; + $replace = (string) $param; } - $pos = strpos($query, '?'); + $pos = strpos($query, '?'); if (false !== $pos) { $query = substr_replace($query, $replace, $pos, 1); } @@ -329,17 +299,13 @@ class GroupCollector implements GroupCollectorInterface */ public function excludeCurrency(TransactionCurrency $currency): GroupCollectorInterface { - $this->query->where( - static function (EloquentBuilder $q) use ($currency): void { - $q->where('source.transaction_currency_id', '!=', $currency->id); - $q->where( - static function (EloquentBuilder $q2) use ($currency): void { - $q2->where('source.foreign_currency_id', '!=', $currency->id); - $q2->orWhereNull('source.foreign_currency_id'); - } - ); - } - ); + $this->query->where(static function (EloquentBuilder $q) use ($currency): void { + $q->where('source.transaction_currency_id', '!=', $currency->id); + $q->where(static function (EloquentBuilder $q2) use ($currency): void { + $q2->where('source.foreign_currency_id', '!=', $currency->id); + $q2->orWhereNull('source.foreign_currency_id'); + }); + }); return $this; } @@ -390,27 +356,21 @@ class GroupCollector implements GroupCollectorInterface return $this; } Log::debug(sprintf('%d excluded search words provided.', count($array))); - $this->query->where( - static function (EloquentBuilder $q) use ($array): void { - $q->where( - static function (EloquentBuilder $q1) use ($array): void { - foreach ($array as $word) { - $keyword = sprintf('%%%s%%', $word); - $q1->whereNotLike('transaction_journals.description', $keyword); - } - } - ); - $q->where( - static function (EloquentBuilder $q2) use ($array): void { - foreach ($array as $word) { - $keyword = sprintf('%%%s%%', $word); - $q2->whereNotLike('transaction_groups.title', $keyword); - $q2->orWhereNull('transaction_groups.title'); - } - } - ); - } - ); + $this->query->where(static function (EloquentBuilder $q) use ($array): void { + $q->where(static function (EloquentBuilder $q1) use ($array): void { + foreach ($array as $word) { + $keyword = sprintf('%%%s%%', $word); + $q1->whereNotLike('transaction_journals.description', $keyword); + } + }); + $q->where(static function (EloquentBuilder $q2) use ($array): void { + foreach ($array as $word) { + $keyword = sprintf('%%%s%%', $word); + $q2->whereNotLike('transaction_groups.title', $keyword); + $q2->orWhereNull('transaction_groups.title'); + } + }); + }); return $this; } @@ -425,10 +385,11 @@ class GroupCollector implements GroupCollectorInterface public function exists(): GroupCollectorInterface { $this->query->whereNull('transaction_groups.deleted_at'); - $this->query->whereNotIn( - 'transaction_types.type', - [TransactionTypeEnum::LIABILITY_CREDIT->value, TransactionTypeEnum::OPENING_BALANCE->value, TransactionTypeEnum::RECONCILIATION->value] - ); + $this->query->whereNotIn('transaction_types.type', [ + TransactionTypeEnum::LIABILITY_CREDIT->value, + TransactionTypeEnum::OPENING_BALANCE->value, + TransactionTypeEnum::RECONCILIATION->value + ]); return $this; } @@ -458,9 +419,9 @@ class GroupCollector implements GroupCollectorInterface foreach ($selection as $group) { $count = count($group['transactions']); foreach ($group['transactions'] as $journalId => $journal) { - $journal['group_title'] = $group['title']; + $journal['group_title'] = $group['title']; $journal['journals_in_group'] = $count; - $return[$journalId] = $journal; + $return[$journalId] = $journal; } } @@ -478,15 +439,15 @@ class GroupCollector implements GroupCollectorInterface // add to query: $this->query->orWhereIn('transaction_journals.transaction_group_id', $groupIds); } - $result = $this->query->get($this->fields); + $result = $this->query->get($this->fields); // now to parse this into an array. - $collection = $this->parseArray($result); + $collection = $this->parseArray($result); // filter the array using all available post filters: - $collection = $this->postFilterCollection($collection); + $collection = $this->postFilterCollection($collection); // sort the collection, if sort instructions are present. - $collection = $this->sortCollection($collection); + $collection = $this->sortCollection($collection); // count it and continue: $this->total = $collection->count(); @@ -507,7 +468,10 @@ class GroupCollector implements GroupCollectorInterface private function getCollectedGroupIds(): array { - return $this->query->get(['transaction_journals.transaction_group_id'])->pluck('transaction_group_id')->toArray(); + return $this->query + ->get(['transaction_journals.transaction_group_id']) + ->pluck('transaction_group_id') + ->toArray(); } /** @@ -519,15 +483,15 @@ class GroupCollector implements GroupCollectorInterface /** @var TransactionJournal $augumentedJournal */ foreach ($collection as $augumentedJournal) { - $groupId = (int)$augumentedJournal->transaction_group_id; + $groupId = (int) $augumentedJournal->transaction_group_id; if (!array_key_exists($groupId, $groups)) { // make new array - $parsedGroup = $this->parseAugmentedJournal($augumentedJournal); - $groupArray = [ - 'id' => (int)$augumentedJournal->transaction_group_id, - 'user_id' => $augumentedJournal->user_id, - 'user_group_id' => $augumentedJournal->user_group_id, + $parsedGroup = $this->parseAugmentedJournal($augumentedJournal); + $groupArray = [ + 'id' => (int) $augumentedJournal->transaction_group_id, + 'user_id' => $augumentedJournal->user_id, + 'user_group_id' => $augumentedJournal->user_group_id, // Field transaction_group_title was added by the query. 'title' => $augumentedJournal->transaction_group_title, 'created_at' => new Carbon($augumentedJournal->group_created_at, config('app.timezone')), @@ -535,18 +499,18 @@ class GroupCollector implements GroupCollectorInterface 'transaction_type' => $parsedGroup['transaction_type_type'], 'count' => 1, 'sums' => [], - 'transactions' => [], + 'transactions' => [] ]; // Field transaction_journal_id was added by the query. - $journalId = (int)$augumentedJournal->transaction_journal_id; + $journalId = (int) $augumentedJournal->transaction_journal_id; $groupArray['transactions'][$journalId] = $parsedGroup; - $groups[$groupId] = $groupArray; + $groups[$groupId] = $groupArray; continue; } // or parse the rest. // Field transaction_journal_id was added by the query. - $journalId = (int)$augumentedJournal->transaction_journal_id; + $journalId = (int) $augumentedJournal->transaction_journal_id; if (array_key_exists($journalId, $groups[$groupId]['transactions'])) { // append data to existing group + journal (for multiple tags or multiple attachments) $groups[$groupId]['transactions'][$journalId] = $this->mergeTags($groups[$groupId]['transactions'][$journalId], $augumentedJournal); @@ -570,18 +534,18 @@ class GroupCollector implements GroupCollectorInterface */ private function parseAugmentedJournal(TransactionJournal $augumentedJournal): array { - $result = $augumentedJournal->toArray(); - $result['tags'] = []; - $result['attachments'] = []; + $result = $augumentedJournal->toArray(); + $result['tags'] = []; + $result['attachments'] = []; $result['interest_date'] = null; - $result['payment_date'] = null; - $result['invoice_date'] = null; - $result['book_date'] = null; - $result['due_date'] = null; - $result['process_date'] = null; + $result['payment_date'] = null; + $result['invoice_date'] = null; + $result['book_date'] = null; + $result['due_date'] = null; + $result['process_date'] = null; try { - $result['date'] = new Carbon($result['date'], 'UTC'); + $result['date'] = new Carbon($result['date'], 'UTC'); $result['created_at'] = new Carbon($result['created_at'], 'UTC'); $result['updated_at'] = new Carbon($result['updated_at'], 'UTC'); @@ -596,27 +560,27 @@ class GroupCollector implements GroupCollectorInterface } // try to process meta date value (if present) - $dates = ['interest_date', 'payment_date', 'invoice_date', 'book_date', 'due_date', 'process_date']; + $dates = ['interest_date', 'payment_date', 'invoice_date', 'book_date', 'due_date', 'process_date']; if (array_key_exists('meta_name', $result) && in_array($result['meta_name'], $dates, true)) { $name = $result['meta_name']; - if (array_key_exists('meta_data', $result) && '' !== (string)$result['meta_data']) { - $result[$name] = Carbon::createFromFormat('!Y-m-d', substr((string)json_decode((string)$result['meta_data']), 0, 10)); + if (array_key_exists('meta_data', $result) && '' !== (string) $result['meta_data']) { + $result[$name] = Carbon::createFromFormat('!Y-m-d', substr((string) json_decode((string) $result['meta_data']), 0, 10)); } } // convert values to integers: - $result = $this->convertToInteger($result); + $result = $this->convertToInteger($result); // convert to boolean - $result = $this->convertToBoolean($result); + $result = $this->convertToBoolean($result); // convert back to strings because SQLite is dumb like that. - $result = $this->convertToStrings($result); + $result = $this->convertToStrings($result); - $result['reconciled'] = 1 === (int)$result['reconciled']; + $result['reconciled'] = 1 === (int) $result['reconciled']; if (array_key_exists('tag_id', $result) && null !== $result['tag_id']) { // assume the other fields are present as well. - $tagId = (int)$augumentedJournal['tag_id']; - $tagDate = null; + $tagId = (int) $augumentedJournal['tag_id']; + $tagDate = null; try { $tagDate = Carbon::parse($augumentedJournal['tag_date']); @@ -625,32 +589,39 @@ class GroupCollector implements GroupCollectorInterface } $result['tags'][$tagId] = [ - 'id' => (int)$result['tag_id'], + 'id' => (int) $result['tag_id'], 'name' => $result['tag_name'], 'date' => $tagDate, - 'description' => $result['tag_description'], + 'description' => $result['tag_description'] ]; } // also merge attachments: if (array_key_exists('attachment_id', $result) && null !== $result['attachment_id']) { - $uploaded = 1 === (int)$result['attachment_uploaded']; - $attachmentId = (int)$augumentedJournal['attachment_id']; + $uploaded = 1 === (int) $result['attachment_uploaded']; + $attachmentId = (int) $augumentedJournal['attachment_id']; $deleted = null !== $result['attachment_deleted_at']; if (0 !== $attachmentId && $uploaded && !$deleted) { $result['attachments'][$attachmentId] = [ 'id' => $attachmentId, 'filename' => $augumentedJournal['attachment_filename'], - 'title' => $augumentedJournal['attachment_title'], + 'title' => $augumentedJournal['attachment_title'] ]; } } // unset various fields: unset( - $result['tag_id'], $result['meta_data'], $result['meta_name'], - $result['tag_name'], $result['tag_date'], $result['tag_description'], - $result['tag_latitude'], $result['tag_longitude'], $result['tag_zoom_level'], - $result['attachment_filename'], $result['attachment_id'] + $result['tag_id'], + $result['meta_data'], + $result['meta_name'], + $result['tag_name'], + $result['tag_date'], + $result['tag_description'], + $result['tag_latitude'], + $result['tag_longitude'], + $result['tag_zoom_level'], + $result['attachment_filename'], + $result['attachment_id'] ); return $result; @@ -662,7 +633,7 @@ class GroupCollector implements GroupCollectorInterface private function convertToInteger(array $array): array { foreach ($this->integerFields as $field) { - $array[$field] = array_key_exists($field, $array) && null !== $array[$field] ? (int)$array[$field] : null; + $array[$field] = array_key_exists($field, $array) && null !== $array[$field] ? (int) $array[$field] : null; } return $array; @@ -671,7 +642,7 @@ class GroupCollector implements GroupCollectorInterface private function convertToBoolean(array $array): array { foreach ($this->booleanFields as $field) { - $array[$field] = array_key_exists($field, $array) ? (bool)$array[$field] : null; + $array[$field] = array_key_exists($field, $array) ? (bool) $array[$field] : null; } return $array; @@ -680,7 +651,7 @@ class GroupCollector implements GroupCollectorInterface private function convertToStrings(array $array): array { foreach ($this->stringFields as $field) { - $array[$field] = array_key_exists($field, $array) && null !== $array[$field] ? (string)$array[$field] : null; + $array[$field] = array_key_exists($field, $array) && null !== $array[$field] ? (string) $array[$field] : null; } return $array; @@ -690,9 +661,9 @@ class GroupCollector implements GroupCollectorInterface { $newArray = $newJournal->toArray(); if (array_key_exists('tag_id', $newArray)) { // assume the other fields are present as well. - $tagId = (int)$newJournal['tag_id']; + $tagId = (int) $newJournal['tag_id']; - $tagDate = null; + $tagDate = null; try { $tagDate = Carbon::parse($newArray['tag_date']); @@ -701,10 +672,10 @@ class GroupCollector implements GroupCollectorInterface } $existingJournal['tags'][$tagId] = [ - 'id' => (int)$newArray['tag_id'], + 'id' => (int) $newArray['tag_id'], 'name' => $newArray['tag_name'], 'date' => $tagDate, - 'description' => $newArray['tag_description'], + 'description' => $newArray['tag_description'] ]; } @@ -715,11 +686,9 @@ class GroupCollector implements GroupCollectorInterface { $newArray = $newJournal->toArray(); if (array_key_exists('attachment_id', $newArray)) { - $attachmentId = (int)$newJournal['attachment_id']; + $attachmentId = (int) $newJournal['attachment_id']; - $existingJournal['attachments'][$attachmentId] = [ - 'id' => $attachmentId, - ]; + $existingJournal['attachments'][$attachmentId] = ['id' => $attachmentId]; } return $existingJournal; @@ -734,39 +703,39 @@ class GroupCollector implements GroupCollectorInterface foreach ($groups as $groudId => $group) { /** @var array $transaction */ foreach ($group['transactions'] as $transaction) { - $currencyId = (int)$transaction['currency_id']; + $currencyId = (int) $transaction['currency_id']; if (null === $transaction['amount']) { throw new FireflyException(sprintf('Amount is NULL for a transaction in group #%d, please investigate.', $groudId)); } - $pcAmount = (string)('' === $transaction['pc_amount'] ? '0' : $transaction['pc_amount']); - $pcForeignAmount = (string)('' === $transaction['pc_foreign_amount'] ? '0' : $transaction['pc_foreign_amount']); - $foreignAmount = (string)('' === $transaction['foreign_amount'] ? '0' : $transaction['foreign_amount']); + $pcAmount = (string) ('' === $transaction['pc_amount'] ? '0' : $transaction['pc_amount']); + $pcForeignAmount = (string) ('' === $transaction['pc_foreign_amount'] ? '0' : $transaction['pc_foreign_amount']); + $foreignAmount = (string) ('' === $transaction['foreign_amount'] ? '0' : $transaction['foreign_amount']); // set default: if (!array_key_exists($currencyId, $groups[$groudId]['sums'])) { - $groups[$groudId]['sums'][$currencyId]['currency_id'] = $currencyId; - $groups[$groudId]['sums'][$currencyId]['currency_code'] = $transaction['currency_code']; - $groups[$groudId]['sums'][$currencyId]['currency_symbol'] = $transaction['currency_symbol']; + $groups[$groudId]['sums'][$currencyId]['currency_id'] = $currencyId; + $groups[$groudId]['sums'][$currencyId]['currency_code'] = $transaction['currency_code']; + $groups[$groudId]['sums'][$currencyId]['currency_symbol'] = $transaction['currency_symbol']; $groups[$groudId]['sums'][$currencyId]['currency_decimal_places'] = $transaction['currency_decimal_places']; - $groups[$groudId]['sums'][$currencyId]['amount'] = '0'; - $groups[$groudId]['sums'][$currencyId]['pc_amount'] = '0'; + $groups[$groudId]['sums'][$currencyId]['amount'] = '0'; + $groups[$groudId]['sums'][$currencyId]['pc_amount'] = '0'; } - $groups[$groudId]['sums'][$currencyId]['amount'] = bcadd((string)$groups[$groudId]['sums'][$currencyId]['amount'], $transaction['amount']); - $groups[$groudId]['sums'][$currencyId]['pc_amount'] = bcadd((string)$groups[$groudId]['sums'][$currencyId]['pc_amount'], $pcAmount); + $groups[$groudId]['sums'][$currencyId]['amount'] = bcadd((string) $groups[$groudId]['sums'][$currencyId]['amount'], $transaction['amount']); + $groups[$groudId]['sums'][$currencyId]['pc_amount'] = bcadd((string) $groups[$groudId]['sums'][$currencyId]['pc_amount'], $pcAmount); if (null !== $transaction['foreign_amount'] && null !== $transaction['foreign_currency_id']) { - $currencyId = (int)$transaction['foreign_currency_id']; + $currencyId = (int) $transaction['foreign_currency_id']; // set default: if (!array_key_exists($currencyId, $groups[$groudId]['sums'])) { - $groups[$groudId]['sums'][$currencyId]['currency_id'] = $currencyId; - $groups[$groudId]['sums'][$currencyId]['currency_code'] = $transaction['foreign_currency_code']; - $groups[$groudId]['sums'][$currencyId]['currency_symbol'] = $transaction['foreign_currency_symbol']; + $groups[$groudId]['sums'][$currencyId]['currency_id'] = $currencyId; + $groups[$groudId]['sums'][$currencyId]['currency_code'] = $transaction['foreign_currency_code']; + $groups[$groudId]['sums'][$currencyId]['currency_symbol'] = $transaction['foreign_currency_symbol']; $groups[$groudId]['sums'][$currencyId]['currency_decimal_places'] = $transaction['foreign_currency_decimal_places']; - $groups[$groudId]['sums'][$currencyId]['amount'] = '0'; - $groups[$groudId]['sums'][$currencyId]['pc_amount'] = '0'; + $groups[$groudId]['sums'][$currencyId]['amount'] = '0'; + $groups[$groudId]['sums'][$currencyId]['pc_amount'] = '0'; } - $groups[$groudId]['sums'][$currencyId]['amount'] = bcadd((string)$groups[$groudId]['sums'][$currencyId]['amount'], $foreignAmount); + $groups[$groudId]['sums'][$currencyId]['amount'] = bcadd((string) $groups[$groudId]['sums'][$currencyId]['amount'], $foreignAmount); $groups[$groudId]['sums'][$currencyId]['pc_amount'] = bcadd($groups[$groudId]['sums'][$currencyId]['amount'], $pcForeignAmount); } } @@ -782,14 +751,18 @@ class GroupCollector implements GroupCollectorInterface if (0 === $countFilters) { return $currentCollection; } - Log::debug(sprintf('GroupCollector: postFilterCollection has %d filter(s) and %d transaction(s).', count($this->postFilters), count($currentCollection))); + Log::debug(sprintf( + 'GroupCollector: postFilterCollection has %d filter(s) and %d transaction(s).', + count($this->postFilters), + count($currentCollection) + )); /** * @var Closure $function */ foreach ($this->postFilters as $function) { Log::debug('Applying filter...'); - $nextCollection = new Collection(); + $nextCollection = new Collection(); // loop everything in the current collection // and save it (or not) in the new collection. @@ -853,7 +826,7 @@ class GroupCollector implements GroupCollectorInterface */ public function getPaginatedGroups(): LengthAwarePaginator { - $set = $this->getGroups(); + $set = $this->getGroups(); if (0 === $this->limit) { $this->setLimit(50); } @@ -898,12 +871,10 @@ class GroupCollector implements GroupCollectorInterface */ public function setCurrency(TransactionCurrency $currency): GroupCollectorInterface { - $this->query->where( - static function (EloquentBuilder $q) use ($currency): void { - $q->where('source.transaction_currency_id', $currency->id); - $q->orWhere('source.foreign_currency_id', $currency->id); - } - ); + $this->query->where(static function (EloquentBuilder $q) use ($currency): void { + $q->where('source.transaction_currency_id', $currency->id); + $q->orWhere('source.foreign_currency_id', $currency->id); + }); return $this; } @@ -970,7 +941,7 @@ class GroupCollector implements GroupCollectorInterface */ public function setPage(int $page): GroupCollectorInterface { - $page = 0 === $page ? 1 : $page; + $page = 0 === $page ? 1 : $page; $this->page = $page; // Log::debug(sprintf('GroupCollector: page is now %d', $page)); @@ -988,26 +959,20 @@ class GroupCollector implements GroupCollectorInterface return $this; } Log::debug(sprintf('%d word(s) in array', count($array))); - $this->query->where( - static function (EloquentBuilder $q) use ($array): void { - $q->where( - static function (EloquentBuilder $q1) use ($array): void { - foreach ($array as $word) { - $keyword = sprintf('%%%s%%', $word); - $q1->whereLike('transaction_journals.description', $keyword); - } - } - ); - $q->orWhere( - static function (EloquentBuilder $q2) use ($array): void { - foreach ($array as $word) { - $keyword = sprintf('%%%s%%', $word); - $q2->whereLike('transaction_groups.title', $keyword); - } - } - ); - } - ); + $this->query->where(static function (EloquentBuilder $q) use ($array): void { + $q->where(static function (EloquentBuilder $q1) use ($array): void { + foreach ($array as $word) { + $keyword = sprintf('%%%s%%', $word); + $q1->whereLike('transaction_journals.description', $keyword); + } + }); + $q->orWhere(static function (EloquentBuilder $q2) use ($array): void { + foreach ($array as $word) { + $keyword = sprintf('%%%s%%', $word); + $q2->whereLike('transaction_groups.title', $keyword); + } + }); + }); return $this; } @@ -1071,25 +1036,14 @@ class GroupCollector implements GroupCollectorInterface // ->leftJoin('transaction_journals', 'transaction_journals.transaction_group_id', 'transaction_groups.id') ->transactionJournals() ->leftJoin('transaction_groups', 'transaction_journals.transaction_group_id', 'transaction_groups.id') - // join source transaction. - ->leftJoin( - 'transactions as source', - static function (JoinClause $join): void { - $join->on('source.transaction_journal_id', '=', 'transaction_journals.id') - ->where('source.amount', '<', 0) - ; - } - ) + ->leftJoin('transactions as source', static function (JoinClause $join): void { + $join->on('source.transaction_journal_id', '=', 'transaction_journals.id')->where('source.amount', '<', 0); + }) // join destination transaction - ->leftJoin( - 'transactions as destination', - static function (JoinClause $join): void { - $join->on('destination.transaction_journal_id', '=', 'transaction_journals.id') - ->where('destination.amount', '>', 0) - ; - } - ) + ->leftJoin('transactions as destination', static function (JoinClause $join): void { + $join->on('destination.transaction_journal_id', '=', 'transaction_journals.id')->where('destination.amount', '>', 0); + }) // left join transaction type. ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id') ->leftJoin('transaction_currencies as currency', 'currency.id', '=', 'source.transaction_currency_id') @@ -1103,8 +1057,7 @@ class GroupCollector implements GroupCollectorInterface ->orderBy('transaction_journals.order', 'ASC') ->orderBy('transaction_journals.id', 'DESC') ->orderBy('transaction_journals.description', 'DESC') - ->orderBy('source.amount', 'DESC') - ; + ->orderBy('source.amount', 'DESC'); } /** @@ -1129,25 +1082,14 @@ class GroupCollector implements GroupCollectorInterface $this->query = $this->userGroup ->transactionJournals() ->leftJoin('transaction_groups', 'transaction_journals.transaction_group_id', 'transaction_groups.id') - // join source transaction. - ->leftJoin( - 'transactions as source', - static function (JoinClause $join): void { - $join->on('source.transaction_journal_id', '=', 'transaction_journals.id') - ->where('source.amount', '<', 0) - ; - } - ) + ->leftJoin('transactions as source', static function (JoinClause $join): void { + $join->on('source.transaction_journal_id', '=', 'transaction_journals.id')->where('source.amount', '<', 0); + }) // join destination transaction - ->leftJoin( - 'transactions as destination', - static function (JoinClause $join): void { - $join->on('destination.transaction_journal_id', '=', 'transaction_journals.id') - ->where('destination.amount', '>', 0) - ; - } - ) + ->leftJoin('transactions as destination', static function (JoinClause $join): void { + $join->on('destination.transaction_journal_id', '=', 'transaction_journals.id')->where('destination.amount', '>', 0); + }) // left join transaction type. ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id') ->leftJoin('transaction_currencies as currency', 'currency.id', '=', 'source.transaction_currency_id') @@ -1160,8 +1102,7 @@ class GroupCollector implements GroupCollectorInterface ->orderBy('transaction_journals.order', 'ASC') ->orderBy('transaction_journals.id', 'DESC') ->orderBy('transaction_journals.description', 'DESC') - ->orderBy('source.amount', 'DESC') - ; + ->orderBy('source.amount', 'DESC'); } /** @@ -1170,14 +1111,14 @@ class GroupCollector implements GroupCollectorInterface public function withAPIInformation(): GroupCollectorInterface { // include source + destination account name and type. - $this->withAccountInformation() + $this + ->withAccountInformation() // include category ID + name (if any) ->withCategoryInformation() // include budget ID + name (if any) ->withBudgetInformation() // include bill ID + name (if any) - ->withBillInformation() - ; + ->withBillInformation(); return $this; } diff --git a/app/Helpers/Fiscal/FiscalHelper.php b/app/Helpers/Fiscal/FiscalHelper.php index b8b5910f2f..1de4a90bae 100644 --- a/app/Helpers/Fiscal/FiscalHelper.php +++ b/app/Helpers/Fiscal/FiscalHelper.php @@ -79,7 +79,7 @@ class FiscalHelper implements FiscalHelperInterface $prefStartStr = '01-01'; } $prefStartStr = (string) $prefStartStr; - [$mth, $day] = explode('-', $prefStartStr); + [$mth, $day] = explode('-', $prefStartStr); $startDate->day((int) $day)->month((int) $mth); // if start date is after passed date, sub 1 year. diff --git a/app/Helpers/Report/NetWorth.php b/app/Helpers/Report/NetWorth.php index 9308f63c52..1d9b6cf784 100644 --- a/app/Helpers/Report/NetWorth.php +++ b/app/Helpers/Report/NetWorth.php @@ -45,7 +45,7 @@ use Illuminate\Support\Facades\Log; */ class NetWorth implements NetWorthInterface { - private AccountRepositoryInterface $accountRepository; + private AccountRepositoryInterface $accountRepository; /** * This method collects the user's net worth in ALL the user's currencies @@ -69,29 +69,31 @@ class NetWorth implements NetWorthInterface return $cache->get(); } Log::debug(sprintf('Now in byAccounts("%s", "%s")', $ids, $date->format('Y-m-d H:i:s'))); - $primary = Amount::getPrimaryCurrency(); - $netWorth = []; + $primary = Amount::getPrimaryCurrency(); + $netWorth = []; Log::debug(sprintf('NetWorth: accountsBalancesOptimized("%s")', $date->format('Y-m-d H:i:s'))); - $balances = Steam::accountsBalancesOptimized($accounts, $date, null, $convertToPrimary); + $balances = Steam::accountsBalancesOptimized($accounts, $date, null, $convertToPrimary); /** @var Account $account */ foreach ($accounts as $account) { // Log::debug(sprintf('Now at account #%d ("%s")', $account->id, $account->name)); - $currency = $this->accountRepository->getAccountCurrency($account) ?? $primary; - $usePrimary = $convertToPrimary && $primary->id !== $currency->id; - $currency = $usePrimary ? $primary : $currency; - $currencyCode = $currency->code; - $balance = '0'; - $primaryBalance = '0'; + $currency = $this->accountRepository->getAccountCurrency($account) ?? $primary; + $usePrimary = $convertToPrimary && $primary->id !== $currency->id; + $currency = $usePrimary ? $primary : $currency; + $currencyCode = $currency->code; + $balance = '0'; + $primaryBalance = '0'; if (array_key_exists($account->id, $balances)) { $balance = $balances[$account->id]['balance'] ?? '0'; $primaryBalance = $balances[$account->id]['pc_balance'] ?? '0'; } // Log::debug(sprintf('Balance is %s, primary balance is %s', $balance, $primaryBalance)); // always subtract virtual balance again. - $balance = '' !== (string) $account->virtual_balance ? bcsub($balance, (string) $account->virtual_balance) : $balance; - $primaryBalance = '' !== (string) $account->native_virtual_balance ? bcsub($primaryBalance, (string) $account->native_virtual_balance) : $primaryBalance; - $amountToUse = $usePrimary ? $primaryBalance : $balance; + $balance = '' !== (string) $account->virtual_balance ? bcsub($balance, (string) $account->virtual_balance) : $balance; + $primaryBalance = '' !== (string) $account->native_virtual_balance + ? bcsub($primaryBalance, (string) $account->native_virtual_balance) + : $primaryBalance; + $amountToUse = $usePrimary ? $primaryBalance : $balance; // Log::debug(sprintf('Will use %s %s', $currencyCode, $amountToUse)); $netWorth[$currencyCode] ??= [ @@ -100,7 +102,7 @@ class NetWorth implements NetWorthInterface 'currency_code' => $currency->code, 'currency_name' => $currency->name, 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => $currency->decimal_places, + 'currency_decimal_places' => $currency->decimal_places ]; $netWorth[$currencyCode]['balance'] = bcadd((string) $amountToUse, $netWorth[$currencyCode]['balance']); @@ -122,6 +124,5 @@ class NetWorth implements NetWorthInterface { $this->accountRepository = app(AccountRepositoryInterface::class); $this->accountRepository->setUserGroup($userGroup); - } } diff --git a/app/Helpers/Report/PopupReport.php b/app/Helpers/Report/PopupReport.php index d07ce12aa6..6b7ec233dd 100644 --- a/app/Helpers/Report/PopupReport.php +++ b/app/Helpers/Report/PopupReport.php @@ -45,12 +45,13 @@ class PopupReport implements PopupReportInterface { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); - $collector->setAccounts(new Collection()->push($account)) + $collector + ->setAccounts(new Collection()->push($account)) ->withAccountInformation() ->withBudgetInformation() ->withCategoryInformation() - ->setRange($attributes['startDate'], $attributes['endDate'])->setBudget($budget) - ; + ->setRange($attributes['startDate'], $attributes['endDate']) + ->setBudget($budget); return $collector->getExtractedJournals(); } @@ -66,19 +67,18 @@ class PopupReport implements PopupReportInterface if (null !== $currencyId) { /** @var CurrencyRepositoryInterface $repos */ $repos = app(CurrencyRepositoryInterface::class); - $currency = $repos->find((int)$currencyId); + $currency = $repos->find((int) $currencyId); } /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setAccounts(new Collection()->push($account)) ->setTypes([TransactionTypeEnum::WITHDRAWAL->value]) ->withAccountInformation() ->withCategoryInformation() ->setRange($attributes['startDate'], $attributes['endDate']) - ->withoutBudget() - ; + ->withoutBudget(); if (null !== $currency) { $collector->setCurrency($currency); @@ -98,18 +98,17 @@ class PopupReport implements PopupReportInterface if (null !== $currencyId) { /** @var CurrencyRepositoryInterface $repos */ $repos = app(CurrencyRepositoryInterface::class); - $currency = $repos->find((int)$currencyId); + $currency = $repos->find((int) $currencyId); } /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setAccounts($attributes['accounts']) ->withAccountInformation() ->withBudgetInformation() ->withCategoryInformation() - ->setRange($attributes['startDate'], $attributes['endDate']) - ; + ->setRange($attributes['startDate'], $attributes['endDate']); if (null !== $currency) { $collector->setCurrency($currency); @@ -127,7 +126,7 @@ class PopupReport implements PopupReportInterface /** * Collect journals by a category. */ - public function byCategory(?Category $category, array $attributes): array + public function byCategory(null|Category $category, array $attributes): array { // filter by currency, if set. $currencyId = $attributes['currencyId'] ?? null; @@ -135,19 +134,20 @@ class PopupReport implements PopupReportInterface if (null !== $currencyId) { /** @var CurrencyRepositoryInterface $repos */ $repos = app(CurrencyRepositoryInterface::class); - $currency = $repos->find((int)$currencyId); + $currency = $repos->find((int) $currencyId); } /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); - $collector->setAccounts($attributes['accounts']) + $collector + ->setAccounts($attributes['accounts']) ->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::TRANSFER->value, TransactionTypeEnum::DEPOSIT->value]) ->withAccountInformation() ->withBudgetInformation() ->withCategoryInformation() - ->setRange($attributes['startDate'], $attributes['endDate'])->withAccountInformation() - ; + ->setRange($attributes['startDate'], $attributes['endDate']) + ->withAccountInformation(); if ($category instanceof Category) { $collector->setCategory($category); @@ -169,36 +169,35 @@ class PopupReport implements PopupReportInterface public function byExpenses(Account $account, array $attributes): array { // filter by currency, if set. - $currencyId = $attributes['currencyId'] ?? null; - $currency = null; + $currencyId = $attributes['currencyId'] ?? null; + $currency = null; if (null !== $currencyId) { /** @var CurrencyRepositoryInterface $repos */ $repos = app(CurrencyRepositoryInterface::class); - $currency = $repos->find((int)$currencyId); + $currency = $repos->find((int) $currencyId); } - /** @var JournalRepositoryInterface $repository */ - $repository = app(JournalRepositoryInterface::class); + $repository = app(JournalRepositoryInterface::class); $repository->setUser($account->user); $accountRepository = app(AccountRepositoryInterface::class); $accountRepository->setUser($account->user); /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); // the source account must be in the set. - $set = $attributes['accounts'] ?? new Collection(); + $set = $attributes['accounts'] ?? new Collection(); - $collector->setDestinationAccounts(new Collection()->push($account)) + $collector + ->setDestinationAccounts(new Collection()->push($account)) ->setSourceAccounts($set) ->setRange($attributes['startDate'], $attributes['endDate']) ->withAccountInformation() ->withBudgetInformation() ->withCategoryInformation() - ->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::TRANSFER->value]) - ; + ->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::TRANSFER->value]); if (null !== $currency) { $collector->setCurrency($currency); @@ -217,7 +216,7 @@ class PopupReport implements PopupReportInterface $repository->setUser($account->user); /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setSourceAccounts(new Collection()->push($account)) ->setDestinationAccounts($attributes['accounts']) @@ -226,8 +225,7 @@ class PopupReport implements PopupReportInterface ->withAccountInformation() ->withBudgetInformation() ->withCategoryInformation() - ->withAccountInformation() - ; + ->withAccountInformation(); return $collector->getExtractedJournals(); } diff --git a/app/Helpers/Report/PopupReportInterface.php b/app/Helpers/Report/PopupReportInterface.php index 3a03cdb049..dcaac9375e 100644 --- a/app/Helpers/Report/PopupReportInterface.php +++ b/app/Helpers/Report/PopupReportInterface.php @@ -50,7 +50,7 @@ interface PopupReportInterface /** * Group by category. */ - public function byCategory(?Category $category, array $attributes): array; + public function byCategory(null|Category $category, array $attributes): array; /** * Do something with expense. Sorry, I am not very inspirational here. diff --git a/app/Helpers/Report/ReportHelper.php b/app/Helpers/Report/ReportHelper.php index 9bac6588ba..3655736cbe 100644 --- a/app/Helpers/Report/ReportHelper.php +++ b/app/Helpers/Report/ReportHelper.php @@ -23,13 +23,13 @@ declare(strict_types=1); namespace FireflyIII\Helpers\Report; -use FireflyIII\Support\Facades\Navigation; use Carbon\Carbon; use FireflyIII\Helpers\Collector\GroupCollectorInterface; use FireflyIII\Helpers\Fiscal\FiscalHelperInterface; use FireflyIII\Models\Bill; use FireflyIII\Repositories\Bill\BillRepositoryInterface; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; +use FireflyIII\Support\Facades\Navigation; use Illuminate\Support\Collection; /** @@ -56,16 +56,14 @@ class ReportHelper implements ReportHelperInterface /** @var BillRepositoryInterface $repository */ $repository = app(BillRepositoryInterface::class); $bills = $repository->getBillsForAccounts($accounts); - $report = [ - 'bills' => [], - ]; + $report = ['bills' => []]; /** @var Bill $bill */ foreach ($bills as $bill) { - $expectedDates = $repository->getPayDatesInRange($bill, $start, $end); - $billId = $bill->id; - $currency = $bill->transactionCurrency; - $current = [ + $expectedDates = $repository->getPayDatesInRange($bill, $start, $end); + $billId = $bill->id; + $currency = $bill->transactionCurrency; + $current = [ 'id' => $bill->id, 'name' => $bill->name, 'active' => $bill->active, @@ -77,16 +75,16 @@ class ReportHelper implements ReportHelperInterface 'currency_symbol' => $currency->symbol, 'currency_decimal_places' => $currency->decimal_places, 'expected_dates' => $expectedDates->toArray(), - 'paid_moments' => [], + 'paid_moments' => [] ]; /** @var Carbon $expectedStart */ foreach ($expectedDates as $expectedStart) { - $expectedEnd = Navigation::endOfX($expectedStart, $bill->repeat_freq, null); + $expectedEnd = Navigation::endOfX($expectedStart, $bill->repeat_freq, null); // is paid in this period maybe? /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setAccounts($accounts)->setRange($expectedStart, $expectedEnd)->setBill($bill); $current['paid_moments'][] = $collector->getExtractedJournals(); } @@ -107,33 +105,33 @@ class ReportHelper implements ReportHelperInterface $fiscalHelper = app(FiscalHelperInterface::class); $start = clone $date; $start->startOfMonth(); - $end = today(config('app.timezone')); + $end = today(config('app.timezone')); $end->endOfMonth(); - $months = []; + $months = []; while ($start <= $end) { - $year = $fiscalHelper->endOfFiscalYear($start)->year; // current year + $year = $fiscalHelper->endOfFiscalYear($start)->year; // current year if (!array_key_exists($year, $months)) { $months[$year] = [ 'fiscal_start' => $fiscalHelper->startOfFiscalYear($start)->format('Y-m-d'), 'fiscal_end' => $fiscalHelper->endOfFiscalYear($start)->format('Y-m-d'), 'start' => Carbon::createFromDate($year, 1, 1)->format('Y-m-d'), 'end' => Carbon::createFromDate($year, 12, 31)->format('Y-m-d'), - 'months' => [], + 'months' => [] ]; } - $currentEnd = clone $start; + $currentEnd = clone $start; $currentEnd->endOfMonth(); $months[$year]['months'][] = [ 'formatted' => $start->isoFormat((string) trans('config.month_js')), 'start' => $start->format('Y-m-d'), 'end' => $currentEnd->format('Y-m-d'), 'month' => $start->month, - 'year' => $year, + 'year' => $year ]; - $start = clone $currentEnd; // to make the hop to the next month properly + $start = clone $currentEnd; // to make the hop to the next month properly $start->addDay(); } diff --git a/app/Helpers/Update/UpdateTrait.php b/app/Helpers/Update/UpdateTrait.php index e21de39b55..2828dead4a 100644 --- a/app/Helpers/Update/UpdateTrait.php +++ b/app/Helpers/Update/UpdateTrait.php @@ -25,8 +25,8 @@ declare(strict_types=1); namespace FireflyIII\Helpers\Update; use FireflyIII\Services\FireflyIIIOrg\Update\UpdateRequestInterface; -use Illuminate\Support\Facades\Log; use FireflyIII\Support\Facades\FireflyConfig; +use Illuminate\Support\Facades\Log; /** * Trait UpdateTrait diff --git a/app/Helpers/Webhook/Sha3SignatureGenerator.php b/app/Helpers/Webhook/Sha3SignatureGenerator.php index 15e42c7d3c..26ba341ddd 100644 --- a/app/Helpers/Webhook/Sha3SignatureGenerator.php +++ b/app/Helpers/Webhook/Sha3SignatureGenerator.php @@ -27,8 +27,8 @@ namespace FireflyIII\Helpers\Webhook; use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\WebhookMessage; -use JsonException; use Illuminate\Support\Facades\Log; +use JsonException; use function Safe\json_encode; @@ -48,7 +48,7 @@ class Sha3SignatureGenerator implements SignatureGeneratorInterface if (null === $message->webhook) { throw new FireflyException('Part of a deleted webhook.'); } - $json = ''; + $json = ''; try { $json = json_encode($message->message, JSON_THROW_ON_ERROR); diff --git a/app/Http/Controllers/Account/CreateController.php b/app/Http/Controllers/Account/CreateController.php index 7411952ae9..42e96b08fd 100644 --- a/app/Http/Controllers/Account/CreateController.php +++ b/app/Http/Controllers/Account/CreateController.php @@ -24,12 +24,12 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Account; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Helpers\Attachments\AttachmentHelperInterface; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Requests\AccountFormRequest; use FireflyIII\Repositories\Account\AccountRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use FireflyIII\Support\Http\Controllers\ModelInformation; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; @@ -47,7 +47,7 @@ class CreateController extends Controller { use ModelInformation; - private AttachmentHelperInterface $attachments; + private AttachmentHelperInterface $attachments; private AccountRepositoryInterface $repository; /** @@ -58,17 +58,15 @@ class CreateController extends Controller parent::__construct(); // translations: - $this->middleware( - function ($request, $next) { - app('view')->share('mainTitleIcon', 'fa-credit-card'); - app('view')->share('title', (string) trans('firefly.accounts')); + $this->middleware(function ($request, $next) { + app('view')->share('mainTitleIcon', 'fa-credit-card'); + app('view')->share('title', (string) trans('firefly.accounts')); - $this->repository = app(AccountRepositoryInterface::class); - $this->attachments = app(AttachmentHelperInterface::class); + $this->repository = app(AccountRepositoryInterface::class); + $this->attachments = app(AttachmentHelperInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -83,35 +81,27 @@ class CreateController extends Controller $roles = $this->getRoles(); $liabilityTypes = $this->getLiabilityTypes(); $hasOldInput = null !== $request->old('_token'); - $locations = [ - 'location' => [ - 'latitude' => $hasOldInput ? old('location_latitude') : config('firefly.default_location.latitude'), - 'longitude' => $hasOldInput ? old('location_longitude') : config('firefly.default_location.longitude'), - 'zoom_level' => $hasOldInput ? old('location_zoom_level') : config('firefly.default_location.zoom_level'), - 'has_location' => $hasOldInput && 'true' === old('location_has_location'), - ], - ]; - $liabilityDirections = [ - 'debit' => trans('firefly.liability_direction_debit'), - 'credit' => trans('firefly.liability_direction_credit'), - ]; + $locations = ['location' => [ + 'latitude' => $hasOldInput ? old('location_latitude') : config('firefly.default_location.latitude'), + 'longitude' => $hasOldInput ? old('location_longitude') : config('firefly.default_location.longitude'), + 'zoom_level' => $hasOldInput ? old('location_zoom_level') : config('firefly.default_location.zoom_level'), + 'has_location' => $hasOldInput && 'true' === old('location_has_location') + ]]; + $liabilityDirections = ['debit' => trans('firefly.liability_direction_debit'), 'credit' => trans('firefly.liability_direction_credit')]; // interest calculation periods: - $interestPeriods = []; + $interestPeriods = []; foreach (config('firefly.interest_periods') as $period) { $interestPeriods[$period] = trans(sprintf('firefly.interest_calc_%s', $period)); } // pre fill some data - $request->session()->flash( - 'preFilled', - [ - 'currency_id' => $this->primaryCurrency->id, - 'include_net_worth' => !$hasOldInput || (bool)$request->old('include_net_worth'), - ] - ); + $request->session()->flash('preFilled', [ + 'currency_id' => $this->primaryCurrency->id, + 'include_net_worth' => !$hasOldInput || (bool) $request->old('include_net_worth') + ]); // issue #8321 - $showNetWorth = true; + $showNetWorth = true; if ('liabilities' !== $objectType && 'asset' !== $objectType) { $showNetWorth = false; } @@ -123,10 +113,17 @@ class CreateController extends Controller $request->session()->forget('accounts.create.fromStore'); Log::channel('audit')->info('Creating new account.'); - return view( - 'accounts.create', - ['subTitleIcon' => $subTitleIcon, 'liabilityDirections' => $liabilityDirections, 'showNetWorth' => $showNetWorth, 'locations' => $locations, 'objectType' => $objectType, 'interestPeriods' => $interestPeriods, 'subTitle' => $subTitle, 'roles' => $roles, 'liabilityTypes' => $liabilityTypes] - ); + return view('accounts.create', [ + 'subTitleIcon' => $subTitleIcon, + 'liabilityDirections' => $liabilityDirections, + 'showNetWorth' => $showNetWorth, + 'locations' => $locations, + 'objectType' => $objectType, + 'interestPeriods' => $interestPeriods, + 'subTitle' => $subTitle, + 'roles' => $roles, + 'liabilityTypes' => $liabilityTypes + ]); } /** @@ -139,8 +136,8 @@ class CreateController extends Controller */ public function store(AccountFormRequest $request) { - $data = $request->getAccountData(); - $account = $this->repository->store($data); + $data = $request->getAccountData(); + $account = $this->repository->store($data); $request->session()->flash('success', (string) trans('firefly.stored_new_account', ['name' => $account->name])); Preferences::mark(); @@ -158,7 +155,7 @@ class CreateController extends Controller // store attachment(s): /** @var null|array $files */ - $files = $request->hasFile('attachments') ? $request->file('attachments') : null; + $files = $request->hasFile('attachments') ? $request->file('attachments') : null; if (null !== $files && !auth()->user()->hasRole('demo')) { $this->attachments->saveAttachmentsForModel($account, $files); } @@ -172,7 +169,7 @@ class CreateController extends Controller } // redirect to previous URL. - $redirect = redirect($this->getPreviousUrl('accounts.create.url')); + $redirect = redirect($this->getPreviousUrl('accounts.create.url')); if (1 === (int) $request->get('create_another')) { // set value so create routine will not overwrite URL: $request->session()->put('accounts.create.fromStore', true); diff --git a/app/Http/Controllers/Account/DeleteController.php b/app/Http/Controllers/Account/DeleteController.php index 8f577d3d6d..b6bd7dc695 100644 --- a/app/Http/Controllers/Account/DeleteController.php +++ b/app/Http/Controllers/Account/DeleteController.php @@ -24,10 +24,10 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Account; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\Account; use FireflyIII\Repositories\Account\AccountRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; @@ -50,16 +50,14 @@ class DeleteController extends Controller parent::__construct(); // translations: - $this->middleware( - function ($request, $next) { - app('view')->share('mainTitleIcon', 'fa-credit-card'); - app('view')->share('title', (string) trans('firefly.accounts')); + $this->middleware(function ($request, $next) { + app('view')->share('mainTitleIcon', 'fa-credit-card'); + app('view')->share('title', (string) trans('firefly.accounts')); - $this->repository = app(AccountRepositoryInterface::class); + $this->repository = app(AccountRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -74,7 +72,7 @@ class DeleteController extends Controller } $typeName = config(sprintf('firefly.shortNamesByFullName.%s', $account->accountType->type)); - $subTitle = (string) trans(sprintf('firefly.delete_%s_account', $typeName), ['name' => $account->name]); + $subTitle = (string) trans(sprintf('firefly.delete_%s_account', $typeName), ['name' => $account->name]); $accountList = app('expandedform')->makeSelectListWithEmpty($this->repository->getAccountsByType([$account->accountType->type])); $objectType = $typeName; unset($accountList[$account->id]); @@ -82,7 +80,7 @@ class DeleteController extends Controller // put previous url in session $this->rememberPreviousUrl('accounts.delete.url'); - return view('accounts.delete', ['account' => $account, 'subTitle' => $subTitle, 'accountList' => $accountList, 'objectType' => $objectType]); + return view('accounts.delete', ['account' => $account, 'subTitle' => $subTitle, 'accountList' => $accountList, 'objectType' => $objectType]); } /** diff --git a/app/Http/Controllers/Account/EditController.php b/app/Http/Controllers/Account/EditController.php index 77310f8a6b..38e8add2c3 100644 --- a/app/Http/Controllers/Account/EditController.php +++ b/app/Http/Controllers/Account/EditController.php @@ -24,13 +24,14 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Account; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Helpers\Attachments\AttachmentHelperInterface; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Requests\AccountFormRequest; use FireflyIII\Models\Account; use FireflyIII\Models\Location; use FireflyIII\Repositories\Account\AccountRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; +use FireflyIII\Support\Facades\Steam; use FireflyIII\Support\Http\Controllers\ModelInformation; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; @@ -38,7 +39,6 @@ use Illuminate\Http\Request; use Illuminate\Routing\Redirector; use Illuminate\Support\Facades\Log; use Illuminate\View\View; -use FireflyIII\Support\Facades\Steam; /** * Class EditController @@ -47,7 +47,7 @@ class EditController extends Controller { use ModelInformation; - private AttachmentHelperInterface $attachments; + private AttachmentHelperInterface $attachments; private AccountRepositoryInterface $repository; /** @@ -58,17 +58,15 @@ class EditController extends Controller parent::__construct(); // translations: - $this->middleware( - function ($request, $next) { - app('view')->share('mainTitleIcon', 'fa-credit-card'); - app('view')->share('title', (string) trans('firefly.accounts')); + $this->middleware(function ($request, $next) { + app('view')->share('mainTitleIcon', 'fa-credit-card'); + app('view')->share('title', (string) trans('firefly.accounts')); - $this->repository = app(AccountRepositoryInterface::class); - $this->attachments = app(AttachmentHelperInterface::class); + $this->repository = app(AccountRepositoryInterface::class); + $this->attachments = app(AttachmentHelperInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -78,39 +76,37 @@ class EditController extends Controller * * @return Factory|Redirector|RedirectResponse|View */ - public function edit(Request $request, Account $account, AccountRepositoryInterface $repository): Factory|\Illuminate\Contracts\View\View|Redirector|RedirectResponse - { + public function edit( + Request $request, + Account $account, + AccountRepositoryInterface $repository + ): Factory|\Illuminate\Contracts\View\View|Redirector|RedirectResponse { if (!$this->isEditableAccount($account)) { return $this->redirectAccountToAccount($account); } - $objectType = config('firefly.shortNamesByFullName')[$account->accountType->type]; - $subTitle = (string) trans(sprintf('firefly.edit_%s_account', $objectType), ['name' => $account->name]); - $subTitleIcon = config(sprintf('firefly.subIconsByIdentifier.%s', $objectType)); - $roles = $this->getRoles(); - $liabilityTypes = $this->getLiabilityTypes(); - $location = $repository->getLocation($account); - $latitude = $location instanceof Location ? $location->latitude : config('firefly.default_location.latitude'); - $longitude = $location instanceof Location ? $location->longitude : config('firefly.default_location.longitude'); - $zoomLevel = $location instanceof Location ? $location->zoom_level : config('firefly.default_location.zoom_level'); - $canEditCurrency = 0 === $account->piggyBanks()->count(); - $hasLocation = $location instanceof Location; - $locations = [ - 'location' => [ - 'latitude' => old('location_latitude') ?? $latitude, - 'longitude' => old('location_longitude') ?? $longitude, - 'zoom_level' => old('location_zoom_level') ?? $zoomLevel, - 'has_location' => $hasLocation || 'true' === old('location_has_location'), - ], - ]; + $objectType = config('firefly.shortNamesByFullName')[$account->accountType->type]; + $subTitle = (string) trans(sprintf('firefly.edit_%s_account', $objectType), ['name' => $account->name]); + $subTitleIcon = config(sprintf('firefly.subIconsByIdentifier.%s', $objectType)); + $roles = $this->getRoles(); + $liabilityTypes = $this->getLiabilityTypes(); + $location = $repository->getLocation($account); + $latitude = $location instanceof Location ? $location->latitude : config('firefly.default_location.latitude'); + $longitude = $location instanceof Location ? $location->longitude : config('firefly.default_location.longitude'); + $zoomLevel = $location instanceof Location ? $location->zoom_level : config('firefly.default_location.zoom_level'); + $canEditCurrency = 0 === $account->piggyBanks()->count(); + $hasLocation = $location instanceof Location; + $locations = ['location' => [ + 'latitude' => old('location_latitude') ?? $latitude, + 'longitude' => old('location_longitude') ?? $longitude, + 'zoom_level' => old('location_zoom_level') ?? $zoomLevel, + 'has_location' => $hasLocation || 'true' === old('location_has_location') + ]]; - $liabilityDirections = [ - 'debit' => trans('firefly.liability_direction_debit'), - 'credit' => trans('firefly.liability_direction_credit'), - ]; + $liabilityDirections = ['debit' => trans('firefly.liability_direction_debit'), 'credit' => trans('firefly.liability_direction_credit')]; // interest calculation periods: - $interestPeriods = []; + $interestPeriods = []; foreach (config('firefly.interest_periods') as $period) { $interestPeriods[$period] = trans(sprintf('firefly.interest_calc_%s', $period)); } @@ -125,23 +121,23 @@ class EditController extends Controller if ('0' === $openingBalanceAmount) { $openingBalanceAmount = ''; } - $openingBalanceDate = $repository->getOpeningBalanceDate($account); - $currency = $this->repository->getAccountCurrency($account) ?? $this->primaryCurrency; + $openingBalanceDate = $repository->getOpeningBalanceDate($account); + $currency = $this->repository->getAccountCurrency($account) ?? $this->primaryCurrency; // include this account in net-worth charts? - $includeNetWorth = $repository->getMetaValue($account, 'include_net_worth'); - $includeNetWorth = null === $includeNetWorth ? true : '1' === $includeNetWorth; + $includeNetWorth = $repository->getMetaValue($account, 'include_net_worth'); + $includeNetWorth = null === $includeNetWorth ? true : '1' === $includeNetWorth; // issue #8321 - $showNetWorth = true; + $showNetWorth = true; if ('liabilities' !== $objectType && 'asset' !== $objectType) { $showNetWorth = false; } // code to handle active-checkboxes - $hasOldInput = null !== $request->old('_token'); - $virtualBalance = $account->virtual_balance ?? '0'; - $preFilled = [ + $hasOldInput = null !== $request->old('_token'); + $virtualBalance = $account->virtual_balance ?? '0'; + $preFilled = [ 'account_number' => $repository->getMetaValue($account, 'account_number'), 'account_role' => $repository->getMetaValue($account, 'account_role'), 'cc_type' => $repository->getMetaValue($account, 'cc_type'), @@ -157,7 +153,7 @@ class EditController extends Controller 'interest' => $repository->getMetaValue($account, 'interest'), 'interest_period' => $repository->getMetaValue($account, 'interest_period'), 'notes' => $this->repository->getNoteText($account), - 'active' => $hasOldInput ? (bool) $request->old('active') : $account->active, + 'active' => $hasOldInput ? (bool) $request->old('active') : $account->active ]; if ('' === $openingBalanceAmount) { $preFilled['opening_balance'] = ''; @@ -165,7 +161,21 @@ class EditController extends Controller $request->session()->flash('preFilled', $preFilled); - return view('accounts.edit', ['account' => $account, 'currency' => $currency, 'canEditCurrency' => $canEditCurrency, 'showNetWorth' => $showNetWorth, 'subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'locations' => $locations, 'liabilityDirections' => $liabilityDirections, 'objectType' => $objectType, 'roles' => $roles, 'preFilled' => $preFilled, 'liabilityTypes' => $liabilityTypes, 'interestPeriods' => $interestPeriods]); + return view('accounts.edit', [ + 'account' => $account, + 'currency' => $currency, + 'canEditCurrency' => $canEditCurrency, + 'showNetWorth' => $showNetWorth, + 'subTitle' => $subTitle, + 'subTitleIcon' => $subTitleIcon, + 'locations' => $locations, + 'liabilityDirections' => $liabilityDirections, + 'objectType' => $objectType, + 'roles' => $roles, + 'preFilled' => $preFilled, + 'liabilityTypes' => $liabilityTypes, + 'interestPeriods' => $interestPeriods + ]); } /** @@ -179,14 +189,14 @@ class EditController extends Controller return $this->redirectAccountToAccount($account); } - $data = $request->getAccountData(); + $data = $request->getAccountData(); $this->repository->update($account, $data); Log::channel('audit')->info(sprintf('Updated account #%d.', $account->id), $data); $request->session()->flash('success', (string) trans('firefly.updated_account', ['name' => $account->name])); // store new attachment(s): /** @var null|array $files */ - $files = $request->hasFile('attachments') ? $request->file('attachments') : null; + $files = $request->hasFile('attachments') ? $request->file('attachments') : null; if (null !== $files && !auth()->user()->hasRole('demo')) { $this->attachments->saveAttachmentsForModel($account, $files); } diff --git a/app/Http/Controllers/Account/IndexController.php b/app/Http/Controllers/Account/IndexController.php index 94951b398a..501241b359 100644 --- a/app/Http/Controllers/Account/IndexController.php +++ b/app/Http/Controllers/Account/IndexController.php @@ -23,11 +23,11 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Account; -use FireflyIII\Support\Facades\Preferences; use Carbon\Carbon; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\Account; use FireflyIII\Repositories\Account\AccountRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use FireflyIII\Support\Facades\Steam; use FireflyIII\Support\Http\Controllers\BasicDataSupport; use Illuminate\Contracts\View\Factory; @@ -55,16 +55,14 @@ class IndexController extends Controller parent::__construct(); // translations: - $this->middleware( - function ($request, $next) { - app('view')->share('mainTitleIcon', 'fa-credit-card'); - app('view')->share('title', (string) trans('firefly.accounts')); + $this->middleware(function ($request, $next) { + app('view')->share('mainTitleIcon', 'fa-credit-card'); + app('view')->share('title', (string) trans('firefly.accounts')); - $this->repository = app(AccountRepositoryInterface::class); + $this->repository = app(AccountRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -87,41 +85,42 @@ class IndexController extends Controller unset($collection); /** @var Carbon $start */ - $start = clone session('start', today(config('app.timezone'))->startOfMonth()); + $start = clone session('start', today(config('app.timezone'))->startOfMonth()); /** @var Carbon $end */ - $end = clone session('end', today(config('app.timezone'))->endOfMonth()); + $end = clone session('end', today(config('app.timezone'))->endOfMonth()); - $ids = $accounts->pluck('id')->toArray(); + $ids = $accounts->pluck('id')->toArray(); Log::debug(sprintf('inactive start: accountsBalancesInRange("%s", "%s")', $start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s'))); - [ - $startBalances, - $endBalances, - ] = Steam::accountsBalancesInRange($accounts, $start, $end, $this->primaryCurrency, $this->convertToPrimary); - $activities = Steam::getLastActivities($ids); + [$startBalances, $endBalances] = Steam::accountsBalancesInRange($accounts, $start, $end, $this->primaryCurrency, $this->convertToPrimary); + $activities = Steam::getLastActivities($ids); - - $accounts->each( - function (Account $account) use ($activities, $startBalances, $endBalances): void { - $currency = $this->repository->getAccountCurrency($account); - $account->lastActivityDate = $this->isInArrayDate($activities, $account->id); - $account->startBalances = Steam::filterAccountBalance($startBalances[$account->id] ?? [], $account, $this->convertToPrimary, $currency); - $account->endBalances = Steam::filterAccountBalance($endBalances[$account->id] ?? [], $account, $this->convertToPrimary, $currency); - $account->differences = $this->subtract($account->startBalances, $account->endBalances); - $account->interest = Steam::bcround($this->repository->getMetaValue($account, 'interest'), 4); - $account->interestPeriod = (string) trans(sprintf('firefly.interest_calc_%s', $this->repository->getMetaValue($account, 'interest_period'))); - $account->accountTypeString = (string) trans(sprintf('firefly.account_type_%s', $account->accountType->type)); - $account->current_debt = '0'; - $account->currency = $currency ?? $this->primaryCurrency; - $account->iban = implode(' ', str_split((string) $account->iban, 4)); - } - ); + $accounts->each(function (Account $account) use ($activities, $startBalances, $endBalances): void { + $currency = $this->repository->getAccountCurrency($account); + $account->lastActivityDate = $this->isInArrayDate($activities, $account->id); + $account->startBalances = Steam::filterAccountBalance($startBalances[$account->id] ?? [], $account, $this->convertToPrimary, $currency); + $account->endBalances = Steam::filterAccountBalance($endBalances[$account->id] ?? [], $account, $this->convertToPrimary, $currency); + $account->differences = $this->subtract($account->startBalances, $account->endBalances); + $account->interest = Steam::bcround($this->repository->getMetaValue($account, 'interest'), 4); + $account->interestPeriod = (string) trans(sprintf('firefly.interest_calc_%s', $this->repository->getMetaValue($account, 'interest_period'))); + $account->accountTypeString = (string) trans(sprintf('firefly.account_type_%s', $account->accountType->type)); + $account->current_debt = '0'; + $account->currency = $currency ?? $this->primaryCurrency; + $account->iban = implode(' ', str_split((string) $account->iban, 4)); + }); // make paginator: - $accounts = new LengthAwarePaginator($accounts, $total, $pageSize, $page); + $accounts = new LengthAwarePaginator($accounts, $total, $pageSize, $page); $accounts->setPath(route('accounts.inactive.index', [$objectType])); - return view('accounts.index', ['objectType' => $objectType, 'inactivePage' => $inactivePage, 'subTitleIcon' => $subTitleIcon, 'subTitle' => $subTitle, 'page' => $page, 'accounts' => $accounts]); + return view('accounts.index', [ + 'objectType' => $objectType, + 'inactivePage' => $inactivePage, + 'subTitleIcon' => $subTitleIcon, + 'subTitle' => $subTitle, + 'page' => $page, + 'accounts' => $accounts + ]); } private function subtract(array $startBalances, array $endBalances): array @@ -145,9 +144,9 @@ class IndexController extends Controller public function index(Request $request, string $objectType): Factory|\Illuminate\Contracts\View\View { Log::debug(sprintf('Now at %s', __METHOD__)); - $subTitle = (string) trans(sprintf('firefly.%s_accounts', $objectType)); - $subTitleIcon = config(sprintf('firefly.subIconsByIdentifier.%s', $objectType)); - $types = config(sprintf('firefly.accountTypesByIdentifier.%s', $objectType)); + $subTitle = (string) trans(sprintf('firefly.%s_accounts', $objectType)); + $subTitleIcon = config(sprintf('firefly.subIconsByIdentifier.%s', $objectType)); + $types = config(sprintf('firefly.accountTypesByIdentifier.%s', $objectType)); $this->repository->resetAccountOrder(); @@ -163,57 +162,56 @@ class IndexController extends Controller unset($collection); /** @var Carbon $start */ - $start = clone session('start', today(config('app.timezone'))->startOfMonth()); + $start = clone session('start', today(config('app.timezone'))->startOfMonth()); /** @var Carbon $end */ - $end = clone session('end', today(config('app.timezone'))->endOfMonth()); + $end = clone session('end', today(config('app.timezone'))->endOfMonth()); - $now = now(); + $now = now(); if ($now->gt($end) || $now->lt($start)) { $now = $end; } - $ids = $accounts->pluck('id')->toArray(); + $ids = $accounts->pluck('id')->toArray(); Log::debug(sprintf('index: accountsBalancesInRange("%s", "%s")', $start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s'))); - [ - $startBalances, - $endBalances, - ] = Steam::accountsBalancesInRange($accounts, $start, $now, $this->primaryCurrency, $this->convertToPrimary); - $activities = Steam::getLastActivities($ids); + [$startBalances, $endBalances] = Steam::accountsBalancesInRange($accounts, $start, $now, $this->primaryCurrency, $this->convertToPrimary); + $activities = Steam::getLastActivities($ids); + $accounts->each(function (Account $account) use ($activities, $startBalances, $endBalances): void { + $interest = (string) $this->repository->getMetaValue($account, 'interest'); + $interest = '' === $interest ? '0' : $interest; + $currency = $this->repository->getAccountCurrency($account); - $accounts->each( - function (Account $account) use ($activities, $startBalances, $endBalances): void { - $interest = (string) $this->repository->getMetaValue($account, 'interest'); - $interest = '' === $interest ? '0' : $interest; - $currency = $this->repository->getAccountCurrency($account); - - $account->startBalances = Steam::filterAccountBalance($startBalances[$account->id] ?? [], $account, $this->convertToPrimary, $currency); - $account->endBalances = Steam::filterAccountBalance($endBalances[$account->id] ?? [], $account, $this->convertToPrimary, $currency); - $account->differences = $this->subtract($account->startBalances, $account->endBalances); - $account->lastActivityDate = $this->isInArrayDate($activities, $account->id); - $account->interest = Steam::bcround($interest, 4); - $account->interestPeriod = (string) trans(sprintf('firefly.interest_calc_%s', $this->repository->getMetaValue($account, 'interest_period'))); - $account->accountTypeString = (string) trans(sprintf('firefly.account_type_%s', $account->accountType->type)); - $account->location = $this->repository->getLocation($account); - $account->liability_direction = $this->repository->getMetaValue($account, 'liability_direction'); - $account->current_debt = $this->repository->getMetaValue($account, 'current_debt') ?? '-'; - $account->currency = $currency ?? $this->primaryCurrency; - $account->iban = implode(' ', str_split((string) $account->iban, 4)); - - - } - ); + $account->startBalances = Steam::filterAccountBalance($startBalances[$account->id] ?? [], $account, $this->convertToPrimary, $currency); + $account->endBalances = Steam::filterAccountBalance($endBalances[$account->id] ?? [], $account, $this->convertToPrimary, $currency); + $account->differences = $this->subtract($account->startBalances, $account->endBalances); + $account->lastActivityDate = $this->isInArrayDate($activities, $account->id); + $account->interest = Steam::bcround($interest, 4); + $account->interestPeriod = (string) trans(sprintf('firefly.interest_calc_%s', $this->repository->getMetaValue($account, 'interest_period'))); + $account->accountTypeString = (string) trans(sprintf('firefly.account_type_%s', $account->accountType->type)); + $account->location = $this->repository->getLocation($account); + $account->liability_direction = $this->repository->getMetaValue($account, 'liability_direction'); + $account->current_debt = $this->repository->getMetaValue($account, 'current_debt') ?? '-'; + $account->currency = $currency ?? $this->primaryCurrency; + $account->iban = implode(' ', str_split((string) $account->iban, 4)); + }); // make paginator: Log::debug(sprintf('Count of accounts before LAP: %d', $accounts->count())); /** @var LengthAwarePaginator $accounts */ - $accounts = new LengthAwarePaginator($accounts, $total, $pageSize, $page); + $accounts = new LengthAwarePaginator($accounts, $total, $pageSize, $page); $accounts->setPath(route('accounts.index', [$objectType])); Log::debug(sprintf('Count of accounts after LAP (1): %d', $accounts->count())); Log::debug(sprintf('Count of accounts after LAP (2): %d', $accounts->getCollection()->count())); - return view('accounts.index', ['objectType' => $objectType, 'inactiveCount' => $inactiveCount, 'subTitleIcon' => $subTitleIcon, 'subTitle' => $subTitle, 'page' => $page, 'accounts' => $accounts]); + return view('accounts.index', [ + 'objectType' => $objectType, + 'inactiveCount' => $inactiveCount, + 'subTitleIcon' => $subTitleIcon, + 'subTitle' => $subTitle, + 'page' => $page, + 'accounts' => $accounts + ]); } } diff --git a/app/Http/Controllers/Account/ReconcileController.php b/app/Http/Controllers/Account/ReconcileController.php index c96cd970a6..762e24c12d 100644 --- a/app/Http/Controllers/Account/ReconcileController.php +++ b/app/Http/Controllers/Account/ReconcileController.php @@ -23,9 +23,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Account; -use FireflyIII\Support\Facades\Preferences; -use FireflyIII\Support\Facades\Navigation; -use Illuminate\Support\Facades\Log; use Carbon\Carbon; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Enums\TransactionTypeEnum; @@ -37,12 +34,15 @@ use FireflyIII\Http\Requests\ReconciliationStoreRequest; use FireflyIII\Models\Account; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Journal\JournalRepositoryInterface; +use FireflyIII\Support\Facades\Navigation; +use FireflyIII\Support\Facades\Preferences; use FireflyIII\Support\Facades\Steam; use FireflyIII\User; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Routing\Redirector; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Log; use Illuminate\View\View; /** @@ -61,16 +61,14 @@ class ReconcileController extends Controller parent::__construct(); // translations: - $this->middleware( - function ($request, $next) { - app('view')->share('mainTitleIcon', 'fa-credit-card'); - app('view')->share('title', (string) trans('firefly.accounts')); - $this->repository = app(JournalRepositoryInterface::class); - $this->accountRepos = app(AccountRepositoryInterface::class); + $this->middleware(function ($request, $next) { + app('view')->share('mainTitleIcon', 'fa-credit-card'); + app('view')->share('title', (string) trans('firefly.accounts')); + $this->repository = app(JournalRepositoryInterface::class); + $this->accountRepos = app(AccountRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -80,8 +78,11 @@ class ReconcileController extends Controller * * @throws FireflyException * */ - public function reconcile(Account $account, ?Carbon $start = null, ?Carbon $end = null): Factory|\Illuminate\Contracts\View\View|Redirector|RedirectResponse - { + public function reconcile( + Account $account, + null|Carbon $start = null, + null|Carbon $end = null + ): Factory|\Illuminate\Contracts\View\View|Redirector|RedirectResponse { if (!$this->isEditableAccount($account)) { return $this->redirectAccountToAccount($account); } @@ -90,10 +91,10 @@ class ReconcileController extends Controller return redirect(route('accounts.index', [config(sprintf('firefly.shortNamesByFullName.%s', $account->accountType->type))])); } - $currency = $this->accountRepos->getAccountCurrency($account) ?? $this->primaryCurrency; + $currency = $this->accountRepos->getAccountCurrency($account) ?? $this->primaryCurrency; // no start or end: - $range = Navigation::getViewRange(false); + $range = Navigation::getViewRange(false); // get start and end @@ -102,7 +103,7 @@ class ReconcileController extends Controller $start = clone session('start', Navigation::startOfPeriod(new Carbon(), $range)); /** @var Carbon $end */ - $end = clone session('end', Navigation::endOfPeriod(new Carbon(), $range)); + $end = clone session('end', Navigation::endOfPeriod(new Carbon(), $range)); } if (null === $end) { /** @var Carbon $end */ @@ -126,12 +127,17 @@ class ReconcileController extends Controller // 2025-10-08 replace with accountsBalancesOptimized // no longer need to do subday->endofday on $start, set inclusive = false for the same effect. - $startBalance = Steam::bcround(Steam::accountsBalancesOptimized(new Collection()->push($account), $start, convertToPrimary: null, inclusive: false)[$account->id]['balance'], $currency->decimal_places); - $endBalance = Steam::bcround(Steam::accountsBalancesOptimized(new Collection()->push($account), $end)[$account->id]['balance'], $currency->decimal_places); + $startBalance = Steam::bcround( + Steam::accountsBalancesOptimized(new Collection()->push($account), $start, convertToPrimary: null, inclusive: false)[$account->id]['balance'], + $currency->decimal_places + ); + $endBalance = Steam::bcround( + Steam::accountsBalancesOptimized(new Collection()->push($account), $end)[$account->id]['balance'], + $currency->decimal_places + ); - - $subTitleIcon = config(sprintf('firefly.subIconsByIdentifier.%s', $account->accountType->type)); - $subTitle = (string) trans('firefly.reconcile_account', ['account' => $account->name]); + $subTitleIcon = config(sprintf('firefly.subIconsByIdentifier.%s', $account->accountType->type)); + $subTitle = (string) trans('firefly.reconcile_account', ['account' => $account->name]); // various links $transactionsUrl = route('accounts.reconcile.transactions', [$account->id, '%start%', '%end%']); @@ -139,10 +145,20 @@ class ReconcileController extends Controller $indexUrl = route('accounts.reconcile', [$account->id, '%start%', '%end%']); $objectType = 'asset'; - return view( - 'accounts.reconcile.index', - ['account' => $account, 'currency' => $currency, 'objectType' => $objectType, 'subTitleIcon' => $subTitleIcon, 'start' => $start, 'end' => $end, 'subTitle' => $subTitle, 'startBalance' => $startBalance, 'endBalance' => $endBalance, 'transactionsUrl' => $transactionsUrl, 'overviewUrl' => $overviewUrl, 'indexUrl' => $indexUrl] - ); + return view('accounts.reconcile.index', [ + 'account' => $account, + 'currency' => $currency, + 'objectType' => $objectType, + 'subTitleIcon' => $subTitleIcon, + 'start' => $start, + 'end' => $end, + 'subTitle' => $subTitle, + 'startBalance' => $startBalance, + 'endBalance' => $endBalance, + 'transactionsUrl' => $transactionsUrl, + 'overviewUrl' => $overviewUrl, + 'indexUrl' => $indexUrl + ]); } /** @@ -157,7 +173,7 @@ class ReconcileController extends Controller } Log::debug('In ReconcileController::submit()'); - $data = $request->getAll(); + $data = $request->getAll(); /** @var string $journalId */ foreach ($data['journals'] as $journalId) { @@ -212,41 +228,36 @@ class ReconcileController extends Controller } // title: - $description = trans( - 'firefly.reconciliation_transaction_title', - [ - 'from' => $start->isoFormat($this->monthAndDayFormat), - 'to' => $end->isoFormat($this->monthAndDayFormat), - ] - ); - $submission = [ + $description = trans('firefly.reconciliation_transaction_title', [ + 'from' => $start->isoFormat($this->monthAndDayFormat), + 'to' => $end->isoFormat($this->monthAndDayFormat) + ]); + $submission = [ 'user' => auth()->user(), 'user_group' => auth()->user()->userGroup, 'group_title' => null, - 'transactions' => [ - [ - 'user' => auth()->user(), - 'user_group' => auth()->user()->userGroup, - 'type' => strtolower(TransactionTypeEnum::RECONCILIATION->value), - 'date' => $end, - 'order' => 0, - 'currency_id' => $currency->id, - 'foreign_currency_id' => null, - 'amount' => $difference, - 'foreign_amount' => null, - 'description' => $description, - 'source_id' => $source->id, - 'destination_id' => $destination->id, - 'reconciled' => true, - ], - ], + 'transactions' => [[ + 'user' => auth()->user(), + 'user_group' => auth()->user()->userGroup, + 'type' => strtolower(TransactionTypeEnum::RECONCILIATION->value), + 'date' => $end, + 'order' => 0, + 'currency_id' => $currency->id, + 'foreign_currency_id' => null, + 'amount' => $difference, + 'foreign_amount' => null, + 'description' => $description, + 'source_id' => $source->id, + 'destination_id' => $destination->id, + 'reconciled' => true + ]] ]; /** @var TransactionGroupFactory $factory */ - $factory = app(TransactionGroupFactory::class); + $factory = app(TransactionGroupFactory::class); /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $factory->setUser($user); try { diff --git a/app/Http/Controllers/Account/ShowController.php b/app/Http/Controllers/Account/ShowController.php index 39e5debb64..2c746880db 100644 --- a/app/Http/Controllers/Account/ShowController.php +++ b/app/Http/Controllers/Account/ShowController.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Account; -use FireflyIII\Support\Facades\Preferences; use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Helpers\Collector\GroupCollectorInterface; @@ -32,6 +31,7 @@ use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\Account; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Support\Debug\Timer; +use FireflyIII\Support\Facades\Preferences; use FireflyIII\Support\Facades\Steam; use FireflyIII\Support\Http\Controllers\PeriodOverview; use Illuminate\Contracts\View\Factory; @@ -64,16 +64,14 @@ class ShowController extends Controller app('view')->share('showCategory', true); // translations: - $this->middleware( - function ($request, $next) { - app('view')->share('mainTitleIcon', 'fa-credit-card'); - app('view')->share('title', (string) trans('firefly.accounts')); + $this->middleware(function ($request, $next) { + app('view')->share('mainTitleIcon', 'fa-credit-card'); + app('view')->share('title', (string) trans('firefly.accounts')); - $this->repository = app(AccountRepositoryInterface::class); + $this->repository = app(AccountRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -85,12 +83,16 @@ class ShowController extends Controller * @throws FireflyException * @throws NotFoundExceptionInterface */ - public function show(Request $request, Account $account, ?Carbon $start = null, ?Carbon $end = null): Factory|\Illuminate\Contracts\View\View|Redirector|RedirectResponse - { + public function show( + Request $request, + Account $account, + null|Carbon $start = null, + null|Carbon $end = null + ): Factory|\Illuminate\Contracts\View\View|Redirector|RedirectResponse { if (0 === $account->id) { throw new NotFoundHttpException(); } - $objectType = config(sprintf('firefly.shortNamesByFullName.%s', $account->accountType->type)); + $objectType = config(sprintf('firefly.shortNamesByFullName.%s', $account->accountType->type)); if (!$this->isEditableAccount($account)) { return $this->redirectAccountToAccount($account); @@ -119,21 +121,21 @@ class ShowController extends Controller $currency = $accountCurrency ?? $this->primaryCurrency; $fStart = $start->isoFormat($this->monthAndDayFormat); $fEnd = $end->isoFormat($this->monthAndDayFormat); - $subTitle = (string) trans('firefly.journals_in_period_for_account', ['name' => $account->name, 'start' => $fStart, 'end' => $fEnd]); + $subTitle = (string) trans('firefly.journals_in_period_for_account', ['name' => $account->name, 'start' => $fStart, 'end' => $fEnd]); $chartUrl = route('chart.account.period', [$account->id, $start->format('Y-m-d'), $end->format('Y-m-d')]); $firstTransaction = $this->repository->oldestJournalDate($account) ?? $start; // go back max 3 years. - $threeYearsAgo = clone $start; + $threeYearsAgo = clone $start; $threeYearsAgo->startOfYear()->subYears(3); if ($firstTransaction->lt($threeYearsAgo)) { $firstTransaction = clone $threeYearsAgo; } Log::debug('Start period overview'); - $timer = Timer::getInstance(); + $timer = Timer::getInstance(); $timer->start('period-overview'); - $periods = $this->getAccountPeriodOverview($account, $firstTransaction, $end); + $periods = $this->getAccountPeriodOverview($account, $firstTransaction, $end); Log::debug('End period overview'); $timer->stop('period-overview'); @@ -146,35 +148,49 @@ class ShowController extends Controller $timer->start('collection'); /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector ->setAccounts(new Collection()->push($account)) ->setLimit($pageSize) ->setPage($page) ->withAttachmentInformation() ->withAPIInformation() - ->setRange($start, $end) - ; + ->setRange($start, $end); // this search will not include transaction groups where this asset account (or liability) // is just part of ONE of the journals. To force this: $collector->setExpandGroupSearch(true); - $groups = $collector->getPaginatedGroups(); - + $groups = $collector->getPaginatedGroups(); Log::debug('End collect transactions'); $timer->stop('collection'); $groups->setPath(route('accounts.show', [$account->id, $start->format('Y-m-d'), $end->format('Y-m-d')])); - $showAll = false; - $now = now(); + $showAll = false; + $now = now(); if ($now->gt($end) || $now->lt($start)) { $now = $end; } // 2025-10-08 replace finalAccountBalance with accountsBalancesOptimized. - $balances = Steam::accountsBalancesOptimized(new Collection()->push($account), $now)[$account->id]; + $balances = Steam::accountsBalancesOptimized(new Collection()->push($account), $now)[$account->id]; // $balances = Steam::filterAccountBalance(Steam::finalAccountBalance($account, $now), $account, $this->convertToPrimary, $accountCurrency); - return view('accounts.show', ['account' => $account, 'showAll' => $showAll, 'objectType' => $objectType, 'currency' => $currency, 'today' => $today, 'periods' => $periods, 'subTitleIcon' => $subTitleIcon, 'groups' => $groups, 'attachments' => $attachments, 'subTitle' => $subTitle, 'start' => $start, 'end' => $end, 'chartUrl' => $chartUrl, 'location' => $location, 'balances' => $balances]); + return view('accounts.show', [ + 'account' => $account, + 'showAll' => $showAll, + 'objectType' => $objectType, + 'currency' => $currency, + 'today' => $today, + 'periods' => $periods, + 'subTitleIcon' => $subTitleIcon, + 'groups' => $groups, + 'attachments' => $attachments, + 'subTitle' => $subTitle, + 'start' => $start, + 'end' => $end, + 'chartUrl' => $chartUrl, + 'location' => $location, + 'balances' => $balances + ]); } /** @@ -190,39 +206,39 @@ class ShowController extends Controller if (!$this->isEditableAccount($account)) { return $this->redirectAccountToAccount($account); } - $location = $this->repository->getLocation($account); - $isLiability = $this->repository->isLiability($account); - $attachments = $this->repository->getAttachments($account); - $objectType = config(sprintf('firefly.shortNamesByFullName.%s', $account->accountType->type)); - $end = today(config('app.timezone')); - $today = today(config('app.timezone')); + $location = $this->repository->getLocation($account); + $isLiability = $this->repository->isLiability($account); + $attachments = $this->repository->getAttachments($account); + $objectType = config(sprintf('firefly.shortNamesByFullName.%s', $account->accountType->type)); + $end = today(config('app.timezone')); + $today = today(config('app.timezone')); $this->repository->getAccountCurrency($account); $start = $this->repository->oldestJournalDate($account) ?? today(config('app.timezone'))->startOfMonth(); - $subTitleIcon = config('firefly.subIconsByIdentifier.'.$account->accountType->type); + $subTitleIcon = config('firefly.subIconsByIdentifier.' . $account->accountType->type); $page = (int) $request->get('page'); $pageSize = (int) Preferences::get('listPageSize', 50)->data; $currency = $this->repository->getAccountCurrency($account) ?? $this->primaryCurrency; - $subTitle = (string) trans('firefly.all_journals_for_account', ['name' => $account->name]); + $subTitle = (string) trans('firefly.all_journals_for_account', ['name' => $account->name]); $periods = new Collection(); $end->endOfDay(); /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setAccounts(new Collection()->push($account))->setLimit($pageSize)->setPage($page)->withAccountInformation()->withCategoryInformation(); // this search will not include transaction groups where this asset account (or liability) // is just part of ONE of the journals. To force this: $collector->setExpandGroupSearch(true); - $groups = $collector->getPaginatedGroups(); + $groups = $collector->getPaginatedGroups(); $groups->setPath(route('accounts.show.all', [$account->id])); - $chartUrl = route('chart.account.period', [$account->id, $start->format('Y-m-d'), $end->format('Y-m-d')]); - $showAll = true; + $chartUrl = route('chart.account.period', [$account->id, $start->format('Y-m-d'), $end->format('Y-m-d')]); + $showAll = true; // correct Log::debug(sprintf('showAll: Call accountsBalancesOptimized with date/time "%s"', $end->toIso8601String())); - $now = now(); + $now = now(); if ($now->gt($end) || $now->lt($start)) { $now = $end; } @@ -230,8 +246,25 @@ class ShowController extends Controller // 2025-10-08 replace finalAccountBalance with accountsBalancesOptimized. // $balances = Steam::finalAccountBalance($account, $end); // $balances = Steam::filterAccountBalance($balances, $account, $this->convertToPrimary, $accountCurrency); - $balances = Steam::accountsBalancesOptimized(new Collection()->push($account), $now)[$account->id]; + $balances = Steam::accountsBalancesOptimized(new Collection()->push($account), $now)[$account->id]; - return view('accounts.show', ['account' => $account, 'showAll' => $showAll, 'location' => $location, 'objectType' => $objectType, 'isLiability' => $isLiability, 'attachments' => $attachments, 'currency' => $currency, 'today' => $today, 'chartUrl' => $chartUrl, 'periods' => $periods, 'subTitleIcon' => $subTitleIcon, 'groups' => $groups, 'subTitle' => $subTitle, 'start' => $start, 'end' => $end, 'balances' => $balances]); + return view('accounts.show', [ + 'account' => $account, + 'showAll' => $showAll, + 'location' => $location, + 'objectType' => $objectType, + 'isLiability' => $isLiability, + 'attachments' => $attachments, + 'currency' => $currency, + 'today' => $today, + 'chartUrl' => $chartUrl, + 'periods' => $periods, + 'subTitleIcon' => $subTitleIcon, + 'groups' => $groups, + 'subTitle' => $subTitle, + 'start' => $start, + 'end' => $end, + 'balances' => $balances + ]); } } diff --git a/app/Http/Controllers/Admin/ConfigurationController.php b/app/Http/Controllers/Admin/ConfigurationController.php index 7adb10426b..fa9e26ab81 100644 --- a/app/Http/Controllers/Admin/ConfigurationController.php +++ b/app/Http/Controllers/Admin/ConfigurationController.php @@ -45,14 +45,12 @@ class ConfigurationController extends Controller { parent::__construct(); - $this->middleware( - static function ($request, $next) { - app('view')->share('title', (string)trans('firefly.system_settings')); - app('view')->share('mainTitleIcon', 'fa-hand-spock-o'); + $this->middleware(static function ($request, $next) { + app('view')->share('title', (string) trans('firefly.system_settings')); + app('view')->share('mainTitleIcon', 'fa-hand-spock-o'); - return $next($request); - } - ); + return $next($request); + }); $this->middleware(IsDemoUser::class)->except(['index']); } @@ -63,16 +61,16 @@ class ConfigurationController extends Controller */ public function index(): Factory|\Illuminate\Contracts\View\View { - $subTitle = (string)trans('firefly.instance_configuration'); - $subTitleIcon = 'fa-wrench'; + $subTitle = (string) trans('firefly.instance_configuration'); + $subTitleIcon = 'fa-wrench'; Log::channel('audit')->info('User visits admin config index.'); // all available configuration and their default value in case // they don't exist yet. - $singleUserMode = FireflyConfig::get('single_user_mode', config('firefly.configuration.single_user_mode'))->data; - $isDemoSite = FireflyConfig::get('is_demo_site', config('firefly.configuration.is_demo_site'))->data; - $siteOwner = config('firefly.site_owner'); + $singleUserMode = FireflyConfig::get('single_user_mode', config('firefly.configuration.single_user_mode'))->data; + $isDemoSite = FireflyConfig::get('is_demo_site', config('firefly.configuration.is_demo_site'))->data; + $siteOwner = config('firefly.site_owner'); $enableExchangeRates = FireflyConfig::get('enable_exchange_rates', config('cer.enabled'))->data; $useRunningBalance = FireflyConfig::get('use_running_balance', config('firefly.feature_flags.running_balance_column'))->data; @@ -81,22 +79,19 @@ class ConfigurationController extends Controller $allowWebhooks = FireflyConfig::get('allow_webhooks', config('firefly.allow_webhooks'))->data; $validUrlProtocols = FireflyConfig::get('valid_url_protocols', config('firefly.valid_url_protocols'))->data; - return view( - 'settings.configuration.index', - [ - 'subTitle' => $subTitle, - 'subTitleIcon' => $subTitleIcon, - 'singleUserMode' => $singleUserMode, - 'isDemoSite' => $isDemoSite, - 'siteOwner' => $siteOwner, - 'enableExchangeRates' => $enableExchangeRates, - 'useRunningBalance' => $useRunningBalance, - 'enableExternalMap' => $enableExternalMap, - 'enableExternalRates' => $enableExternalRates, - 'allowWebhooks' => $allowWebhooks, - 'validUrlProtocols' => $validUrlProtocols, - ] - ); + return view('settings.configuration.index', [ + 'subTitle' => $subTitle, + 'subTitleIcon' => $subTitleIcon, + 'singleUserMode' => $singleUserMode, + 'isDemoSite' => $isDemoSite, + 'siteOwner' => $siteOwner, + 'enableExchangeRates' => $enableExchangeRates, + 'useRunningBalance' => $useRunningBalance, + 'enableExternalMap' => $enableExternalMap, + 'enableExternalRates' => $enableExternalRates, + 'allowWebhooks' => $allowWebhooks, + 'validUrlProtocols' => $validUrlProtocols + ]); } /** @@ -123,7 +118,7 @@ class ConfigurationController extends Controller FireflyConfig::set('is_demo_site', $data['is_demo_site']); // flash message - session()->flash('success', (string)trans('firefly.configuration_updated')); + session()->flash('success', (string) trans('firefly.configuration_updated')); Preferences::mark(); return redirect()->route('settings.configuration.index'); diff --git a/app/Http/Controllers/Admin/HomeController.php b/app/Http/Controllers/Admin/HomeController.php index 0c4fc3911c..4567ae256e 100644 --- a/app/Http/Controllers/Admin/HomeController.php +++ b/app/Http/Controllers/Admin/HomeController.php @@ -23,9 +23,9 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Admin; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Middleware\IsDemoUser; +use FireflyIII\Support\Facades\Preferences; use Illuminate\Contracts\View\Factory; use Illuminate\Support\Facades\Log; use Illuminate\View\View; @@ -65,6 +65,6 @@ class HomeController extends Controller $email = $pref->data; } - return view('settings.index', ['title' => $title, 'mainTitleIcon' => $mainTitleIcon, 'email' => $email]); + return view('settings.index', ['title' => $title, 'mainTitleIcon' => $mainTitleIcon, 'email' => $email]); } } diff --git a/app/Http/Controllers/Admin/LinkController.php b/app/Http/Controllers/Admin/LinkController.php index d48124d231..18dd62b881 100644 --- a/app/Http/Controllers/Admin/LinkController.php +++ b/app/Http/Controllers/Admin/LinkController.php @@ -23,12 +23,12 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Admin; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Middleware\IsDemoUser; use FireflyIII\Http\Requests\LinkTypeFormRequest; use FireflyIII\Models\LinkType; use FireflyIII\Repositories\LinkType\LinkTypeRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; @@ -50,15 +50,13 @@ class LinkController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.system_settings')); - app('view')->share('mainTitleIcon', 'fa-hand-spock-o'); - $this->repository = app(LinkTypeRepositoryInterface::class); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.system_settings')); + app('view')->share('mainTitleIcon', 'fa-hand-spock-o'); + $this->repository = app(LinkTypeRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); $this->middleware(IsDemoUser::class)->except(['index', 'show']); } @@ -79,7 +77,7 @@ class LinkController extends Controller $this->rememberPreviousUrl('link-types.create.url'); } - return view('settings.link.create', ['subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon]); + return view('settings.link.create', ['subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon]); } /** @@ -96,11 +94,11 @@ class LinkController extends Controller } Log::channel('audit')->info(sprintf('User wants to delete link type #%d', $linkType->id)); - $subTitle = (string) trans('firefly.delete_link_type', ['name' => $linkType->name]); + $subTitle = (string) trans('firefly.delete_link_type', ['name' => $linkType->name]); $otherTypes = $this->repository->get(); $count = $this->repository->countJournals($linkType); $moveTo = []; - $moveTo[0] = (string) trans('firefly.do_not_save_connection'); + $moveTo[0] = (string) trans('firefly.do_not_save_connection'); /** @var LinkType $otherType */ foreach ($otherTypes as $otherType) { @@ -112,7 +110,7 @@ class LinkController extends Controller // put previous url in session $this->rememberPreviousUrl('link-types.delete.url'); - return view('settings.link.delete', ['linkType' => $linkType, 'subTitle' => $subTitle, 'moveTo' => $moveTo, 'count' => $count]); + return view('settings.link.delete', ['linkType' => $linkType, 'subTitle' => $subTitle, 'moveTo' => $moveTo, 'count' => $count]); } /** @@ -143,7 +141,7 @@ class LinkController extends Controller return redirect(route('settings.links.index')); } - $subTitle = (string) trans('firefly.edit_link_type', ['name' => $linkType->name]); + $subTitle = (string) trans('firefly.edit_link_type', ['name' => $linkType->name]); $subTitleIcon = 'fa-link'; Log::channel('audit')->info(sprintf('User wants to edit link type #%d', $linkType->id)); @@ -154,7 +152,7 @@ class LinkController extends Controller } $request->session()->forget('link-types.edit.fromUpdate'); - return view('settings.link.edit', ['subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'linkType' => $linkType]); + return view('settings.link.edit', ['subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'linkType' => $linkType]); } /** @@ -169,13 +167,11 @@ class LinkController extends Controller $linkTypes = $this->repository->get(); Log::channel('audit')->info('User on index of link types in admin.'); - $linkTypes->each( - function (LinkType $linkType): void { - $linkType->journalCount = $this->repository->countJournals($linkType); - } - ); + $linkTypes->each(function (LinkType $linkType): void { + $linkType->journalCount = $this->repository->countJournals($linkType); + }); - return view('settings.link.index', ['subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'linkTypes' => $linkTypes]); + return view('settings.link.index', ['subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'linkTypes' => $linkTypes]); } /** @@ -185,13 +181,18 @@ class LinkController extends Controller */ public function show(LinkType $linkType): Factory|\Illuminate\Contracts\View\View { - $subTitle = (string) trans('firefly.overview_for_link', ['name' => $linkType->name]); + $subTitle = (string) trans('firefly.overview_for_link', ['name' => $linkType->name]); $subTitleIcon = 'fa-link'; $links = $this->repository->getJournalLinks($linkType); Log::channel('audit')->info(sprintf('User viewing link type #%d', $linkType->id)); - return view('settings.link.show', ['subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'linkType' => $linkType, 'links' => $links]); + return view('settings.link.show', [ + 'subTitle' => $subTitle, + 'subTitleIcon' => $subTitleIcon, + 'linkType' => $linkType, + 'links' => $links + ]); } /** @@ -204,7 +205,7 @@ class LinkController extends Controller $data = [ 'name' => $request->convertString('name'), 'inward' => $request->convertString('inward'), - 'outward' => $request->convertString('outward'), + 'outward' => $request->convertString('outward') ]; $linkType = $this->repository->store($data); @@ -236,11 +237,7 @@ class LinkController extends Controller return redirect(route('settings.links.index')); } - $data = [ - 'name' => $request->convertString('name'), - 'inward' => $request->convertString('inward'), - 'outward' => $request->convertString('outward'), - ]; + $data = ['name' => $request->convertString('name'), 'inward' => $request->convertString('inward'), 'outward' => $request->convertString('outward')]; $this->repository->update($linkType, $data); Log::channel('audit')->info(sprintf('User update link type #%d.', $linkType->id), $data); diff --git a/app/Http/Controllers/Admin/NotificationController.php b/app/Http/Controllers/Admin/NotificationController.php index 879bdfb0d6..0a8e3cd3dd 100644 --- a/app/Http/Controllers/Admin/NotificationController.php +++ b/app/Http/Controllers/Admin/NotificationController.php @@ -39,25 +39,25 @@ class NotificationController extends Controller public function index(): View { Log::channel('audit')->info('User visits notifications index.'); - $title = (string) trans('firefly.system_settings'); - $mainTitleIcon = 'fa-hand-spock-o'; - $subTitle = (string) trans('firefly.title_owner_notifications'); - $subTitleIcon = 'envelope-o'; + $title = (string) trans('firefly.system_settings'); + $mainTitleIcon = 'fa-hand-spock-o'; + $subTitle = (string) trans('firefly.title_owner_notifications'); + $subTitleIcon = 'envelope-o'; // notification settings: - $slackUrl = FireflyConfig::getEncrypted('slack_webhook_url', '')->data; - $pushoverAppToken = FireflyConfig::getEncrypted('pushover_app_token', '')->data; - $pushoverUserToken = FireflyConfig::getEncrypted('pushover_user_token', '')->data; - $ntfyServer = FireflyConfig::getEncrypted('ntfy_server', 'https://ntfy.sh')->data; - $ntfyTopic = FireflyConfig::getEncrypted('ntfy_topic', '')->data; - $ntfyAuth = FireflyConfig::get('ntfy_auth', false)->data; - $ntfyUser = FireflyConfig::getEncrypted('ntfy_user', '')->data; - $ntfyPass = FireflyConfig::getEncrypted('ntfy_pass', '')->data; - $channels = config('notifications.channels'); - $forcedAvailability = []; + $slackUrl = FireflyConfig::getEncrypted('slack_webhook_url', '')->data; + $pushoverAppToken = FireflyConfig::getEncrypted('pushover_app_token', '')->data; + $pushoverUserToken = FireflyConfig::getEncrypted('pushover_user_token', '')->data; + $ntfyServer = FireflyConfig::getEncrypted('ntfy_server', 'https://ntfy.sh')->data; + $ntfyTopic = FireflyConfig::getEncrypted('ntfy_topic', '')->data; + $ntfyAuth = FireflyConfig::get('ntfy_auth', false)->data; + $ntfyUser = FireflyConfig::getEncrypted('ntfy_user', '')->data; + $ntfyPass = FireflyConfig::getEncrypted('ntfy_pass', '')->data; + $channels = config('notifications.channels'); + $forcedAvailability = []; // admin notification settings: - $notifications = []; + $notifications = []; foreach (config('notifications.notifications.owner') as $key => $info) { if (true === $info['enabled']) { $notifications[$key] = FireflyConfig::get(sprintf('notification_%s', $key), true)->data; @@ -68,19 +68,32 @@ class NotificationController extends Controller foreach ($channels as $channel => $info) { $forcedAvailability[$channel] = true; } - $forcedAvailability['ntfy'] = '' !== $ntfyTopic; + $forcedAvailability['ntfy'] = '' !== $ntfyTopic; $forcedAvailability['pushover'] = '' !== $pushoverAppToken && '' !== $pushoverUserToken; - $forcedAvailability['slack'] = '' !== $slackUrl; + $forcedAvailability['slack'] = '' !== $slackUrl; - return view( - 'settings.notifications.index', - ['title' => $title, 'subTitle' => $subTitle, 'forcedAvailability' => $forcedAvailability, 'mainTitleIcon' => $mainTitleIcon, 'subTitleIcon' => $subTitleIcon, 'channels' => $channels, 'slackUrl' => $slackUrl, 'notifications' => $notifications, 'pushoverAppToken' => $pushoverAppToken, 'pushoverUserToken' => $pushoverUserToken, 'ntfyServer' => $ntfyServer, 'ntfyTopic' => $ntfyTopic, 'ntfyAuth' => $ntfyAuth, 'ntfyUser' => $ntfyUser, 'ntfyPass' => $ntfyPass] - ); + return view('settings.notifications.index', [ + 'title' => $title, + 'subTitle' => $subTitle, + 'forcedAvailability' => $forcedAvailability, + 'mainTitleIcon' => $mainTitleIcon, + 'subTitleIcon' => $subTitleIcon, + 'channels' => $channels, + 'slackUrl' => $slackUrl, + 'notifications' => $notifications, + 'pushoverAppToken' => $pushoverAppToken, + 'pushoverUserToken' => $pushoverUserToken, + 'ntfyServer' => $ntfyServer, + 'ntfyTopic' => $ntfyTopic, + 'ntfyAuth' => $ntfyAuth, + 'ntfyUser' => $ntfyUser, + 'ntfyPass' => $ntfyPass + ]); } public function postIndex(NotificationRequest $request): RedirectResponse { - $all = $request->getAll(); + $all = $request->getAll(); foreach (config('notifications.notifications.owner') as $key => $info) { if (array_key_exists($key, $all)) { @@ -98,7 +111,6 @@ class NotificationController extends Controller } FireflyConfig::set('ntfy_auth', $all['ntfy_auth'] ?? false); - session()->flash('success', (string) trans('firefly.notification_settings_saved')); return redirect(route('settings.notification.index')); diff --git a/app/Http/Controllers/Admin/UpdateController.php b/app/Http/Controllers/Admin/UpdateController.php index a205534ef0..ed13dec31d 100644 --- a/app/Http/Controllers/Admin/UpdateController.php +++ b/app/Http/Controllers/Admin/UpdateController.php @@ -47,14 +47,12 @@ class UpdateController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - static function ($request, $next) { - app('view')->share('title', (string) trans('firefly.system_settings')); - app('view')->share('mainTitleIcon', 'fa-hand-spock-o'); + $this->middleware(static function ($request, $next) { + app('view')->share('title', (string) trans('firefly.system_settings')); + app('view')->share('mainTitleIcon', 'fa-hand-spock-o'); - return $next($request); - } - ); + return $next($request); + }); $this->middleware(IsDemoUser::class)->except(['index']); } @@ -74,16 +72,23 @@ class UpdateController extends Controller $options = [ -1 => (string) trans('firefly.updates_ask_me_later'), 0 => (string) trans('firefly.updates_do_not_check'), - 1 => (string) trans('firefly.updates_enable_check'), + 1 => (string) trans('firefly.updates_enable_check') ]; - $channelOptions = [ + $channelOptions = [ 'stable' => (string) trans('firefly.update_channel_stable'), 'beta' => (string) trans('firefly.update_channel_beta'), - 'alpha' => (string) trans('firefly.update_channel_alpha'), + 'alpha' => (string) trans('firefly.update_channel_alpha') ]; - return view('settings.update.index', ['subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'selected' => $selected, 'options' => $options, 'channelSelected' => $channelSelected, 'channelOptions' => $channelOptions]); + return view('settings.update.index', [ + 'subTitle' => $subTitle, + 'subTitleIcon' => $subTitleIcon, + 'selected' => $selected, + 'options' => $options, + 'channelSelected' => $channelSelected, + 'channelOptions' => $channelOptions + ]); } /** diff --git a/app/Http/Controllers/Admin/UserController.php b/app/Http/Controllers/Admin/UserController.php index 1a1e96f2f9..8f76787414 100644 --- a/app/Http/Controllers/Admin/UserController.php +++ b/app/Http/Controllers/Admin/UserController.php @@ -23,8 +23,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Admin; -use FireflyIII\Support\Facades\Preferences; -use Illuminate\Support\Facades\Log; use FireflyIII\Events\Admin\InvitationCreated; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; @@ -33,23 +31,25 @@ use FireflyIII\Http\Requests\InviteUserFormRequest; use FireflyIII\Http\Requests\UserFormRequest; use FireflyIII\Models\InvitedUser; use FireflyIII\Repositories\User\UserRepositoryInterface; +use FireflyIII\Support\Facades\FireflyConfig; +use FireflyIII\Support\Facades\Preferences; use FireflyIII\User; use Illuminate\Contracts\Foundation\Application; use Illuminate\Contracts\View\Factory; use Illuminate\Http\JsonResponse; use Illuminate\Http\RedirectResponse; use Illuminate\Routing\Redirector; +use Illuminate\Support\Facades\Log; use Illuminate\View\View; use Psr\Container\ContainerExceptionInterface; use Psr\Container\NotFoundExceptionInterface; -use FireflyIII\Support\Facades\FireflyConfig; /** * Class UserController. */ class UserController extends Controller { - protected bool $externalIdentity; + protected bool $externalIdentity; private UserRepositoryInterface $repository; /** @@ -59,15 +59,13 @@ class UserController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.system_settings')); - app('view')->share('mainTitleIcon', 'fa-hand-spock-o'); - $this->repository = app(UserRepositoryInterface::class); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.system_settings')); + app('view')->share('mainTitleIcon', 'fa-hand-spock-o'); + $this->repository = app(UserRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); $this->middleware(IsDemoUser::class)->except(['index', 'show']); $this->externalIdentity = 'web' !== config('firefly.authentication_guard'); } @@ -85,7 +83,7 @@ class UserController extends Controller $subTitle = (string) trans('firefly.delete_user', ['email' => $user->email]); - return view('settings.users.delete', ['user' => $user, 'subTitle' => $subTitle]); + return view('settings.users.delete', ['user' => $user, 'subTitle' => $subTitle]); } public function deleteInvite(InvitedUser $invitedUser): JsonResponse @@ -137,18 +135,26 @@ class UserController extends Controller } session()->forget('users.edit.fromUpdate'); - $subTitle = (string) trans('firefly.edit_user', ['email' => $user->email]); - $subTitleIcon = 'fa-user-o'; - $currentUser = auth()->user(); - $isAdmin = $this->repository->hasRole($user, 'owner'); - $codes = [ + $subTitle = (string) trans('firefly.edit_user', ['email' => $user->email]); + $subTitleIcon = 'fa-user-o'; + $currentUser = auth()->user(); + $isAdmin = $this->repository->hasRole($user, 'owner'); + $codes = [ '' => (string) trans('firefly.no_block_code'), 'bounced' => (string) trans('firefly.block_code_bounced'), 'expired' => (string) trans('firefly.block_code_expired'), - 'email_changed' => (string) trans('firefly.block_code_email_changed'), + 'email_changed' => (string) trans('firefly.block_code_email_changed') ]; - return view('settings.users.edit', ['user' => $user, 'canEditDetails' => $canEditDetails, 'subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'codes' => $codes, 'currentUser' => $currentUser, 'isAdmin' => $isAdmin]); + return view('settings.users.edit', [ + 'user' => $user, + 'canEditDetails' => $canEditDetails, + 'subTitle' => $subTitle, + 'subTitleIcon' => $subTitleIcon, + 'codes' => $codes, + 'currentUser' => $currentUser, + 'isAdmin' => $isAdmin + ]); } /** @@ -172,17 +178,21 @@ class UserController extends Controller $allowInvites = true; } - $invitedUsers = $this->repository->getInvitedUsers(); + $invitedUsers = $this->repository->getInvitedUsers(); // add meta stuff. - $users->each( - function (User $user): void { - $user->isAdmin = $this->repository->hasRole($user, 'owner'); - $user->has2FA = null !== $user->mfa_secret; - } - ); + $users->each(function (User $user): void { + $user->isAdmin = $this->repository->hasRole($user, 'owner'); + $user->has2FA = null !== $user->mfa_secret; + }); - return view('settings.users.index', ['subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'users' => $users, 'allowInvites' => $allowInvites, 'invitedUsers' => $invitedUsers]); + return view('settings.users.index', [ + 'subTitle' => $subTitle, + 'subTitleIcon' => $subTitleIcon, + 'users' => $users, + 'allowInvites' => $allowInvites, + 'invitedUsers' => $invitedUsers + ]); } public function invite(InviteUserFormRequest $request): RedirectResponse @@ -206,14 +216,18 @@ class UserController extends Controller { $title = (string) trans('firefly.system_settings'); $mainTitleIcon = 'fa-hand-spock-o'; - $subTitle = (string) trans('firefly.single_user_administration', ['email' => $user->email]); + $subTitle = (string) trans('firefly.single_user_administration', ['email' => $user->email]); $subTitleIcon = 'fa-user'; $information = $this->repository->getUserData($user); - return view( - 'settings.users.show', - ['title' => $title, 'mainTitleIcon' => $mainTitleIcon, 'subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'information' => $information, 'user' => $user] - ); + return view('settings.users.show', [ + 'title' => $title, + 'mainTitleIcon' => $mainTitleIcon, + 'subTitle' => $subTitle, + 'subTitleIcon' => $subTitleIcon, + 'information' => $information, + 'user' => $user + ]); } /** @@ -224,7 +238,7 @@ class UserController extends Controller public function update(UserFormRequest $request, User $user) { Log::debug('Actually here'); - $data = $request->getUserData(); + $data = $request->getUserData(); // var_dump($data); diff --git a/app/Http/Controllers/AttachmentController.php b/app/Http/Controllers/AttachmentController.php index 4c4ff2293a..c8bf40120b 100644 --- a/app/Http/Controllers/AttachmentController.php +++ b/app/Http/Controllers/AttachmentController.php @@ -23,11 +23,11 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Requests\AttachmentFormRequest; use FireflyIII\Models\Attachment; use FireflyIII\Repositories\Attachment\AttachmentRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; @@ -50,15 +50,13 @@ class AttachmentController extends Controller parent::__construct(); // translations: - $this->middleware( - function ($request, $next) { - app('view')->share('mainTitleIcon', 'fa-paperclip'); - app('view')->share('title', (string) trans('firefly.attachments')); - $this->repository = app(AttachmentRepositoryInterface::class); + $this->middleware(function ($request, $next) { + app('view')->share('mainTitleIcon', 'fa-paperclip'); + app('view')->share('title', (string) trans('firefly.attachments')); + $this->repository = app(AttachmentRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -73,7 +71,7 @@ class AttachmentController extends Controller // put previous url in session $this->rememberPreviousUrl('attachments.delete.url'); - return view('attachments.delete', ['attachment' => $attachment, 'subTitle' => $subTitle]); + return view('attachments.delete', ['attachment' => $attachment, 'subTitle' => $subTitle]); } /** @@ -101,22 +99,21 @@ class AttachmentController extends Controller public function download(Attachment $attachment) { if ($this->repository->exists($attachment)) { - $content = $this->repository->getContent($attachment); - $quoted = sprintf('"%s"', addcslashes(basename($attachment->filename), '"\\')); + $content = $this->repository->getContent($attachment); + $quoted = sprintf('"%s"', addcslashes(basename($attachment->filename), '"\\')); /** @var LaravelResponse $response */ $response = response($content); $response ->header('Content-Description', 'File Transfer') ->header('Content-Type', 'application/octet-stream') - ->header('Content-Disposition', 'attachment; filename='.$quoted) + ->header('Content-Disposition', 'attachment; filename=' . $quoted) ->header('Content-Transfer-Encoding', 'binary') ->header('Connection', 'Keep-Alive') ->header('Expires', '0') ->header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0') ->header('Pragma', 'public') - ->header('Content-Length', (string) strlen($content)) - ; + ->header('Content-Length', (string) strlen($content)); return $response; } @@ -133,19 +130,17 @@ class AttachmentController extends Controller public function edit(Request $request, Attachment $attachment): Factory|\Illuminate\Contracts\View\View { $subTitleIcon = 'fa-pencil'; - $subTitle = (string) trans('firefly.edit_attachment', ['name' => $attachment->filename]); + $subTitle = (string) trans('firefly.edit_attachment', ['name' => $attachment->filename]); // put previous url in session if not redirect from store (not "return_to_edit"). if (true !== session('attachments.edit.fromUpdate')) { $this->rememberPreviousUrl('attachments.edit.url'); } $request->session()->forget('attachments.edit.fromUpdate'); - $preFilled = [ - 'notes' => $this->repository->getNoteText($attachment), - ]; + $preFilled = ['notes' => $this->repository->getNoteText($attachment)]; $request->session()->flash('preFilled', $preFilled); - return view('attachments.edit', ['attachment' => $attachment, 'subTitleIcon' => $subTitleIcon, 'subTitle' => $subTitle]); + return view('attachments.edit', ['attachment' => $attachment, 'subTitleIcon' => $subTitleIcon, 'subTitle' => $subTitle]); } /** @@ -156,13 +151,11 @@ class AttachmentController extends Controller public function index(): Factory|\Illuminate\Contracts\View\View { $set = $this->repository->get()->reverse(); - $set = $set->each( - function (Attachment $attachment): Attachment { - $attachment->file_exists = $this->repository->exists($attachment); + $set = $set->each(function (Attachment $attachment): Attachment { + $attachment->file_exists = $this->repository->exists($attachment); - return $attachment; - } - ); + return $attachment; + }); return view('attachments.index', ['set' => $set]); } @@ -172,7 +165,7 @@ class AttachmentController extends Controller */ public function update(AttachmentFormRequest $request, Attachment $attachment): RedirectResponse { - $data = $request->getAttachmentData(); + $data = $request->getAttachmentData(); $this->repository->update($attachment, $data); $request->session()->flash('success', (string) trans('firefly.attachment_updated', ['name' => $attachment->filename])); @@ -200,7 +193,7 @@ class AttachmentController extends Controller $content = $this->repository->getContent($attachment); // prevent XSS by adding a new secure header. - $csp = [ + $csp = [ "default-src 'none'", "object-src 'none'", "script-src 'none'", @@ -209,18 +202,14 @@ class AttachmentController extends Controller "font-src 'none'", "connect-src 'none'", "img-src 'self'", - "manifest-src 'none'", + "manifest-src 'none'" ]; - return response()->make( - $content, - 200, - [ - 'Content-Security-Policy' => implode('; ', $csp), - 'Content-Type' => $attachment->mime, - 'Content-Disposition' => 'inline; filename="'.$attachment->filename.'"', - ] - ); + return response()->make($content, 200, [ + 'Content-Security-Policy' => implode('; ', $csp), + 'Content-Type' => $attachment->mime, + 'Content-Disposition' => 'inline; filename="' . $attachment->filename . '"' + ]); } $message = 'Could not find the indicated attachment. The file is no longer there.'; diff --git a/app/Http/Controllers/Auth/ConfirmPasswordController.php b/app/Http/Controllers/Auth/ConfirmPasswordController.php index 7ff1da6abd..51232db682 100644 --- a/app/Http/Controllers/Auth/ConfirmPasswordController.php +++ b/app/Http/Controllers/Auth/ConfirmPasswordController.php @@ -35,15 +35,15 @@ use Illuminate\Foundation\Auth\ConfirmsPasswords; class ConfirmPasswordController extends Controller { /* - |-------------------------------------------------------------------------- - | Confirm Password Controller - |-------------------------------------------------------------------------- - | - | This controller is responsible for handling password confirmations and - | uses a simple trait to include the behavior. You're free to explore - | this trait and override any functions that require customization. - | - */ + |-------------------------------------------------------------------------- + | Confirm Password Controller + |-------------------------------------------------------------------------- + | + | This controller is responsible for handling password confirmations and + | uses a simple trait to include the behavior. You're free to explore + | this trait and override any functions that require customization. + | + */ use ConfirmsPasswords; diff --git a/app/Http/Controllers/Auth/ForgotPasswordController.php b/app/Http/Controllers/Auth/ForgotPasswordController.php index 14810e8e35..0c13d3e9df 100644 --- a/app/Http/Controllers/Auth/ForgotPasswordController.php +++ b/app/Http/Controllers/Auth/ForgotPasswordController.php @@ -26,6 +26,7 @@ namespace FireflyIII\Http\Controllers\Auth; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Repositories\User\UserRepositoryInterface; +use FireflyIII\Support\Facades\FireflyConfig; use FireflyIII\User; use Illuminate\Contracts\View\Factory; use Illuminate\Foundation\Auth\SendsPasswordResetEmails; @@ -36,7 +37,6 @@ use Illuminate\View\View; use Psr\Container\ContainerExceptionInterface; use Psr\Container\NotFoundExceptionInterface; use Safe\Exceptions\UrlException; -use FireflyIII\Support\Facades\FireflyConfig; use function Safe\parse_url; @@ -70,7 +70,7 @@ class ForgotPasswordController extends Controller public function sendResetLinkEmail(Request $request, UserRepositoryInterface $repository) { Log::info('Start of sendResetLinkEmail()'); - if ('web' !== config('firefly.authentication_guard')) { + if ('web' !== config('firefly.authentication_guard')) { $message = sprintf('Cannot reset password when authenticating over "%s".', config('firefly.authentication_guard')); Log::error($message); @@ -84,7 +84,7 @@ class ForgotPasswordController extends Controller // verify if the user is not a demo user. If so, we give him back an error. /** @var null|User $user */ - $user = User::where('email', $request->get('email'))->first(); + $user = User::where('email', $request->get('email'))->first(); if (null !== $user && $repository->hasRole($user, 'demo')) { return back()->withErrors(['email' => (string) trans('firefly.cannot_reset_demo_user')]); @@ -93,7 +93,7 @@ class ForgotPasswordController extends Controller // We will send the password reset link to this user. Once we have attempted // to send the link, we will examine the response then see the message we // need to show to the user. Finally, we'll send out a proper response. - $result = $this->broker()->sendResetLink($request->only('email')); + $result = $this->broker()->sendResetLink($request->only('email')); if ('passwords.throttled' === $result) { Log::error(sprintf('Cowardly refuse to send a password reset message to user #%d because the reset button has been throttled.', $user->id)); } @@ -110,7 +110,7 @@ class ForgotPasswordController extends Controller private function validateHost(): void { try { - $configuredHost = parse_url((string)config('app.url'), PHP_URL_HOST); + $configuredHost = parse_url((string) config('app.url'), PHP_URL_HOST); } catch (UrlException $e) { throw new FireflyException('Please set a valid and correct Firefly III URL in the APP_URL environment variable.', 0, $e); } @@ -121,7 +121,9 @@ class ForgotPasswordController extends Controller if ($configuredHost !== $host) { Log::error(sprintf('Host header is "%s", APP_URL is "%s".', $host, $configuredHost)); - throw new FireflyException('The Host-header does not match the host in the APP_URL environment variable. Please make sure these match. See also: https://bit.ly/FF3-host-header'); + throw new FireflyException( + 'The Host-header does not match the host in the APP_URL environment variable. Please make sure these match. See also: https://bit.ly/FF3-host-header' + ); } } @@ -151,6 +153,6 @@ class ForgotPasswordController extends Controller $allowRegistration = false; } - return view('auth.passwords.email')->with(['allowRegistration' => $allowRegistration, 'pageTitle' => $pageTitle]); + return view('auth.passwords.email')->with(['allowRegistration' => $allowRegistration, 'pageTitle' => $pageTitle]); } } diff --git a/app/Http/Controllers/Auth/LoginController.php b/app/Http/Controllers/Auth/LoginController.php index 2c7121c2e7..1d78148505 100644 --- a/app/Http/Controllers/Auth/LoginController.php +++ b/app/Http/Controllers/Auth/LoginController.php @@ -67,7 +67,7 @@ class LoginController extends Controller /** * Where to redirect users after login. */ - protected string $redirectTo = RouteServiceProvider::HOME; + protected string $redirectTo = RouteServiceProvider::HOME; private UserRepositoryInterface $repository; private string $username = 'email'; @@ -87,7 +87,7 @@ class LoginController extends Controller * * @throws ValidationException */ - public function login(Request $request): JsonResponse | RedirectResponse + public function login(Request $request): JsonResponse|RedirectResponse { $username = $request->get($this->username()); Log::channel('audit')->info(sprintf('User is trying to login using "%s"', $username)); @@ -100,11 +100,7 @@ class LoginController extends Controller // report the failed login to the user if the count is 2 or 5. // TODO here be warning. return redirect(route('login')) - ->withErrors( - [ - $this->username => trans('auth.failed'), - ] - ) + ->withErrors([$this->username => trans('auth.failed')]) ->onlyInput($this->username); } Log::debug('Login data is present.'); @@ -133,7 +129,7 @@ class LoginController extends Controller return $this->sendLoginResponse($request); } Log::warning('Login attempt failed.'); - $username = (string)$request->get($this->username()); + $username = (string) $request->get($this->username()); $user = $this->repository->findByEmail($username); if (!$user instanceof User) { // send event to owner. @@ -173,11 +169,7 @@ class LoginController extends Controller */ protected function sendFailedLoginResponse(Request $request): void { - $exception = ValidationException::withMessages( - [ - $this->username() => [trans('auth.failed')], - ] - ); + $exception = ValidationException::withMessages([$this->username() => [trans('auth.failed')]]); $exception->redirectTo = route('login'); throw $exception; @@ -186,7 +178,7 @@ class LoginController extends Controller /** * Log the user out of the application. */ - public function logout(Request $request): Redirector | RedirectResponse | Response + public function logout(Request $request): Redirector|RedirectResponse|Response { $authGuard = config('firefly.authentication_guard'); $logoutUrl = config('firefly.custom_logout_url'); @@ -209,9 +201,7 @@ class LoginController extends Controller $this->loggedOut($request); - return $request->wantsJson() - ? new Response('', ResponseAlias::HTTP_NO_CONTENT) - : redirect('/'); + return $request->wantsJson() ? new Response('', ResponseAlias::HTTP_NO_CONTENT) : redirect('/'); } /** @@ -223,13 +213,13 @@ class LoginController extends Controller * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface */ - public function showLoginForm(Request $request): Factory | Redirector | RedirectResponse | View + public function showLoginForm(Request $request): Factory|Redirector|RedirectResponse|View { Log::channel('audit')->info('Show login form (1.1).'); $count = DB::table('users')->count(); $guard = config('auth.defaults.guard'); - $title = (string)trans('firefly.login_page_title'); + $title = (string) trans('firefly.login_page_title'); if (0 === $count && 'web' === $guard) { return redirect(route('register')); @@ -259,7 +249,14 @@ class LoginController extends Controller } $usernameField = $this->username(); - return view('auth.login', ['allowRegistration' => $allowRegistration, 'email' => $email, 'remember' => $remember, 'allowReset' => $allowReset, 'title' => $title, 'usernameField' => $usernameField]); + return view('auth.login', [ + 'allowRegistration' => $allowRegistration, + 'email' => $email, + 'remember' => $remember, + 'allowReset' => $allowReset, + 'title' => $title, + 'usernameField' => $usernameField + ]); } /** diff --git a/app/Http/Controllers/Auth/RegisterController.php b/app/Http/Controllers/Auth/RegisterController.php index 741f4d81ca..949be67c86 100644 --- a/app/Http/Controllers/Auth/RegisterController.php +++ b/app/Http/Controllers/Auth/RegisterController.php @@ -83,10 +83,10 @@ class RegisterController extends Controller * @throws FireflyException * @throws ValidationException */ - public function register(Request $request): Redirector | RedirectResponse + public function register(Request $request): Redirector|RedirectResponse { $allowRegistration = $this->allowedToRegister(); - $inviteCode = (string)$request->get('invite_code'); + $inviteCode = (string) $request->get('invite_code'); $repository = app(UserRepositoryInterface::class); $validCode = $repository->validateInviteCode($inviteCode); @@ -102,7 +102,7 @@ class RegisterController extends Controller $this->guard()->login($user); - session()->flash('success', (string)trans('firefly.registered')); + session()->flash('success', (string) trans('firefly.registered')); $this->registered($request, $user); @@ -123,7 +123,7 @@ class RegisterController extends Controller try { $singleUserMode = FireflyConfig::get('single_user_mode', config('firefly.configuration.single_user_mode'))->data; - } catch (ContainerExceptionInterface | NotFoundExceptionInterface) { + } catch (ContainerExceptionInterface|NotFoundExceptionInterface) { $singleUserMode = true; } $userCount = User::count(); @@ -147,10 +147,10 @@ class RegisterController extends Controller * @throws FireflyException * @throws NotFoundExceptionInterface */ - public function showInviteForm(Request $request, string $code): Factory | \Illuminate\Contracts\View\View + public function showInviteForm(Request $request, string $code): Factory|\Illuminate\Contracts\View\View { $isDemoSite = FireflyConfig::get('is_demo_site', config('firefly.configuration.is_demo_site'))->data; - $pageTitle = (string)trans('firefly.register_page_title'); + $pageTitle = (string) trans('firefly.register_page_title'); $repository = app(UserRepositoryInterface::class); $allowRegistration = $this->allowedToRegister(); $inviteCode = $code; @@ -169,7 +169,7 @@ class RegisterController extends Controller $email = $request->old('email'); - return view('auth.register', ['isDemoSite' => $isDemoSite, 'email' => $email, 'pageTitle' => $pageTitle, 'inviteCode' => $inviteCode]); + return view('auth.register', ['isDemoSite' => $isDemoSite, 'email' => $email, 'pageTitle' => $pageTitle, 'inviteCode' => $inviteCode]); } /** @@ -181,10 +181,10 @@ class RegisterController extends Controller * @throws FireflyException * @throws NotFoundExceptionInterface */ - public function showRegistrationForm(?Request $request = null): Factory | \Illuminate\Contracts\View\View + public function showRegistrationForm(null|Request $request = null): Factory|\Illuminate\Contracts\View\View { $isDemoSite = FireflyConfig::get('is_demo_site', config('firefly.configuration.is_demo_site'))->data; - $pageTitle = (string)trans('firefly.register_page_title'); + $pageTitle = (string) trans('firefly.register_page_title'); $allowRegistration = $this->allowedToRegister(); if (false === $allowRegistration) { @@ -195,6 +195,6 @@ class RegisterController extends Controller $email = $request?->old('email'); - return view('auth.register', ['isDemoSite' => $isDemoSite, 'email' => $email, 'pageTitle' => $pageTitle]); + return view('auth.register', ['isDemoSite' => $isDemoSite, 'email' => $email, 'pageTitle' => $pageTitle]); } } diff --git a/app/Http/Controllers/Auth/ResetPasswordController.php b/app/Http/Controllers/Auth/ResetPasswordController.php index a0986ef43e..4781c763be 100644 --- a/app/Http/Controllers/Auth/ResetPasswordController.php +++ b/app/Http/Controllers/Auth/ResetPasswordController.php @@ -25,6 +25,7 @@ namespace FireflyIII\Http\Controllers\Auth; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; +use FireflyIII\Support\Facades\FireflyConfig; use FireflyIII\User; use Illuminate\Contracts\View\Factory; use Illuminate\Foundation\Auth\ResetsPasswords; @@ -36,7 +37,6 @@ use Illuminate\Validation\ValidationException; use Illuminate\View\View; use Psr\Container\ContainerExceptionInterface; use Psr\Container\NotFoundExceptionInterface; -use FireflyIII\Support\Facades\FireflyConfig; use SensitiveParameter; /** @@ -85,30 +85,21 @@ class ResetPasswordController extends Controller return view('errors.error', ['message' => $message]); } - $rules = [ - 'token' => 'required', - 'email' => 'required|email', - 'password' => 'required|confirmed|min:16|secure_password', - ]; + $rules = ['token' => 'required', 'email' => 'required|email', 'password' => 'required|confirmed|min:16|secure_password']; $this->validate($request, $rules, $this->validationErrorMessages()); // Here we will attempt to reset the user's password. If it is successful we // will update the password on an actual user model and persist it to the // database. Otherwise, we will parse the error and return the response. - $response = $this->broker()->reset( - $this->credentials($request), - function ($user, #[SensitiveParameter] $password): void { - $this->resetPassword($user, $password); - } - ); + $response = $this->broker()->reset($this->credentials($request), function ($user, #[SensitiveParameter] $password): void { + $this->resetPassword($user, $password); + }); // If the password was successfully reset, we will redirect the user back to // the application's home authenticated view. If there is an error we can // redirect them back to where they came from with their error message. - return Password::PASSWORD_RESET === $response - ? $this->sendResetResponse($request, $response) - : $this->sendResetFailedResponse($request, $response); + return Password::PASSWORD_RESET === $response ? $this->sendResetResponse($request, $response) : $this->sendResetFailedResponse($request, $response); } /** @@ -141,8 +132,11 @@ class ResetPasswordController extends Controller $allowRegistration = false; } - return view('auth.passwords.reset')->with( - ['token' => $token, 'email' => $request->email, 'allowRegistration' => $allowRegistration, 'pageTitle' => $pageTitle] - ); + return view('auth.passwords.reset')->with([ + 'token' => $token, + 'email' => $request->email, + 'allowRegistration' => $allowRegistration, + 'pageTitle' => $pageTitle + ]); } } diff --git a/app/Http/Controllers/Auth/TwoFactorController.php b/app/Http/Controllers/Auth/TwoFactorController.php index 53270d5d7d..ff4e3ee608 100644 --- a/app/Http/Controllers/Auth/TwoFactorController.php +++ b/app/Http/Controllers/Auth/TwoFactorController.php @@ -54,9 +54,9 @@ class TwoFactorController extends Controller /** @var User $user */ $user = auth()->user(); $siteOwner = config('firefly.site_owner'); - $title = (string)trans('firefly.two_factor_forgot_title'); + $title = (string) trans('firefly.two_factor_forgot_title'); - return view('auth.lost-two-factor', ['user' => $user, 'siteOwner' => $siteOwner, 'title' => $title]); + return view('auth.lost-two-factor', ['user' => $user, 'siteOwner' => $siteOwner, 'title' => $title]); } /** @@ -66,8 +66,8 @@ class TwoFactorController extends Controller public function submitMFA(Request $request): Redirector|RedirectResponse { /** @var array $mfaHistory */ - $mfaHistory = Preferences::get('mfa_history', [])->data; - $mfaCode = (string)$request->get('one_time_password'); + $mfaHistory = Preferences::get('mfa_history', [])->data; + $mfaCode = (string) $request->get('one_time_password'); // is in history? then refuse to use it. if ($this->inMFAHistory($mfaCode, $mfaHistory)) { @@ -82,7 +82,7 @@ class TwoFactorController extends Controller // if not OK, save error. if (!$authenticator->isAuthenticated()) { - $user = auth()->user(); + $user = auth()->user(); $this->addToMFAFailureCounter(); $counter = $this->getMFAFailureCounter(); if (3 === $counter || 10 === $counter) { @@ -136,7 +136,7 @@ class TwoFactorController extends Controller foreach ($mfaHistory as $entry) { $time = $entry['time']; $code = $entry['code']; - if ($code === $mfaCode && $now - $time <= 300) { + if ($code === $mfaCode && ($now - $time) <= 300) { return true; } } @@ -156,11 +156,8 @@ class TwoFactorController extends Controller foreach ($mfaHistory as $entry) { $time = $entry['time']; $code = $entry['code']; - if ($now - $time <= 300) { - $newHistory[] = [ - 'time' => $time, - 'code' => $code, - ]; + if (($now - $time) <= 300) { + $newHistory[] = ['time' => $time, 'code' => $code]; } } Preferences::set('mfa_history', $newHistory); @@ -168,7 +165,7 @@ class TwoFactorController extends Controller private function addToMFAFailureCounter(): void { - $preference = (int)Preferences::get('mfa_failure_count', 0)->data; + $preference = (int) Preferences::get('mfa_failure_count', 0)->data; ++$preference; Log::channel('audit')->info(sprintf('MFA failure count is set to %d.', $preference)); Preferences::set('mfa_failure_count', $preference); @@ -176,7 +173,7 @@ class TwoFactorController extends Controller private function getMFAFailureCounter(): int { - $value = (int)Preferences::get('mfa_failure_count', 0)->data; + $value = (int) Preferences::get('mfa_failure_count', 0)->data; Log::channel('audit')->info(sprintf('MFA failure count is %d.', $value)); return $value; @@ -185,11 +182,8 @@ class TwoFactorController extends Controller private function addToMFAHistory(string $mfaCode): void { /** @var array $mfaHistory */ - $mfaHistory = Preferences::get('mfa_history', [])->data; - $entry = [ - 'time' => Carbon::now()->getTimestamp(), - 'code' => $mfaCode, - ]; + $mfaHistory = Preferences::get('mfa_history', [])->data; + $entry = ['time' => Carbon::now()->getTimestamp(), 'code' => $mfaCode]; $mfaHistory[] = $entry; Preferences::set('mfa_history', $mfaHistory); @@ -220,7 +214,7 @@ class TwoFactorController extends Controller */ private function removeFromBackupCodes(string $mfaCode): void { - $list = Preferences::get('mfa_recovery', [])->data; + $list = Preferences::get('mfa_recovery', [])->data; if (!is_array($list)) { $list = []; } diff --git a/app/Http/Controllers/Bill/CreateController.php b/app/Http/Controllers/Bill/CreateController.php index 3d8d95fd37..ccc59968a7 100644 --- a/app/Http/Controllers/Bill/CreateController.php +++ b/app/Http/Controllers/Bill/CreateController.php @@ -24,12 +24,12 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Bill; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Helpers\Attachments\AttachmentHelperInterface; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Requests\BillStoreRequest; use FireflyIII\Repositories\Bill\BillRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use Illuminate\Contracts\View\Factory; use Illuminate\Contracts\View\View; use Illuminate\Http\RedirectResponse; @@ -42,7 +42,7 @@ use Illuminate\Support\Facades\Log; class CreateController extends Controller { private AttachmentHelperInterface $attachments; - private BillRepositoryInterface $repository; + private BillRepositoryInterface $repository; /** * BillController constructor. @@ -51,16 +51,14 @@ class CreateController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.bills')); - app('view')->share('mainTitleIcon', 'fa-calendar-o'); - $this->attachments = app(AttachmentHelperInterface::class); - $this->repository = app(BillRepositoryInterface::class); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.bills')); + app('view')->share('mainTitleIcon', 'fa-calendar-o'); + $this->attachments = app(AttachmentHelperInterface::class); + $this->repository = app(BillRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -68,14 +66,14 @@ class CreateController extends Controller */ public function create(Request $request): Factory|View { - $periods = []; + $periods = []; /** @var array $billPeriods */ $billPeriods = config('firefly.bill_periods'); foreach ($billPeriods as $current) { - $periods[$current] = (string) trans('firefly.repeat_freq_'.$current); + $periods[$current] = (string) trans('firefly.repeat_freq_' . $current); } - $subTitle = (string) trans('firefly.create_new_bill'); + $subTitle = (string) trans('firefly.create_new_bill'); // put previous url in session if not redirect from store (not "create another"). if (true !== session('bills.create.fromStore')) { @@ -83,7 +81,7 @@ class CreateController extends Controller } $request->session()->forget('bills.create.fromStore'); - return view('bills.create', ['periods' => $periods, 'subTitle' => $subTitle]); + return view('bills.create', ['periods' => $periods, 'subTitle' => $subTitle]); } /** @@ -91,7 +89,7 @@ class CreateController extends Controller */ public function store(BillStoreRequest $request): RedirectResponse { - $billData = $request->getBillData(); + $billData = $request->getBillData(); $billData['active'] = true; @@ -109,7 +107,7 @@ class CreateController extends Controller Preferences::mark(); /** @var null|array $files */ - $files = $request->hasFile('attachments') ? $request->file('attachments') : null; + $files = $request->hasFile('attachments') ? $request->file('attachments') : null; if (null !== $files && !auth()->user()->hasRole('demo')) { $this->attachments->saveAttachmentsForModel($bill, $files); } diff --git a/app/Http/Controllers/Bill/DeleteController.php b/app/Http/Controllers/Bill/DeleteController.php index 70f8d06338..76a8f4afd0 100644 --- a/app/Http/Controllers/Bill/DeleteController.php +++ b/app/Http/Controllers/Bill/DeleteController.php @@ -24,10 +24,10 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Bill; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\Bill; use FireflyIII\Repositories\Bill\BillRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; @@ -50,15 +50,13 @@ class DeleteController extends Controller app('view')->share('showBudget', true); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.bills')); - app('view')->share('mainTitleIcon', 'fa-calendar-o'); - $this->repository = app(BillRepositoryInterface::class); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.bills')); + app('view')->share('mainTitleIcon', 'fa-calendar-o'); + $this->repository = app(BillRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -72,7 +70,7 @@ class DeleteController extends Controller $this->rememberPreviousUrl('bills.delete.url'); $subTitle = (string) trans('firefly.delete_bill', ['name' => $bill->name]); - return view('bills.delete', ['bill' => $bill, 'subTitle' => $subTitle]); + return view('bills.delete', ['bill' => $bill, 'subTitle' => $subTitle]); } /** diff --git a/app/Http/Controllers/Bill/EditController.php b/app/Http/Controllers/Bill/EditController.php index 475e7c2f3f..593c3ab3f7 100644 --- a/app/Http/Controllers/Bill/EditController.php +++ b/app/Http/Controllers/Bill/EditController.php @@ -24,18 +24,18 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Bill; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Helpers\Attachments\AttachmentHelperInterface; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Requests\BillUpdateRequest; use FireflyIII\Models\Bill; use FireflyIII\Repositories\Bill\BillRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; +use FireflyIII\Support\Facades\Steam; use Illuminate\Contracts\View\Factory; use Illuminate\Contracts\View\View; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; -use FireflyIII\Support\Facades\Steam; /** * Class EditController @@ -43,7 +43,7 @@ use FireflyIII\Support\Facades\Steam; class EditController extends Controller { private AttachmentHelperInterface $attachments; - private BillRepositoryInterface $repository; + private BillRepositoryInterface $repository; /** * BillController constructor. @@ -52,16 +52,14 @@ class EditController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.bills')); - app('view')->share('mainTitleIcon', 'fa-calendar-o'); - $this->attachments = app(AttachmentHelperInterface::class); - $this->repository = app(BillRepositoryInterface::class); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.bills')); + app('view')->share('mainTitleIcon', 'fa-calendar-o'); + $this->attachments = app(AttachmentHelperInterface::class); + $this->repository = app(BillRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -69,16 +67,16 @@ class EditController extends Controller */ public function edit(Request $request, Bill $bill): Factory|View { - $periods = []; + $periods = []; /** @var array $billPeriods */ - $billPeriods = config('firefly.bill_periods'); + $billPeriods = config('firefly.bill_periods'); foreach ($billPeriods as $current) { - $periods[$current] = (string) trans('firefly.'.$current); + $periods[$current] = (string) trans('firefly.' . $current); } - $subTitle = (string) trans('firefly.edit_bill', ['name' => $bill->name]); + $subTitle = (string) trans('firefly.edit_bill', ['name' => $bill->name]); // put previous url in session if not redirect from store (not "return_to_edit"). if (true !== session('bills.edit.fromUpdate')) { @@ -87,24 +85,24 @@ class EditController extends Controller $bill->amount_min = Steam::bcround($bill->amount_min, $bill->transactionCurrency->decimal_places); $bill->amount_max = Steam::bcround($bill->amount_max, $bill->transactionCurrency->decimal_places); - $rules = $this->repository->getRulesForBill($bill); + $rules = $this->repository->getRulesForBill($bill); // code to handle active-checkboxes - $hasOldInput = null !== $request->old('_token'); + $hasOldInput = null !== $request->old('_token'); - $preFilled = [ + $preFilled = [ 'bill_end_date' => $bill->end_date, 'extension_date' => $bill->extension_date, 'notes' => $this->repository->getNoteText($bill), 'transaction_currency_id' => $bill->transaction_currency_id, 'active' => $hasOldInput ? (bool) $request->old('active') : $bill->active, - 'object_group' => null !== $bill->objectGroups->first() ? $bill->objectGroups->first()->title : '', + 'object_group' => null !== $bill->objectGroups->first() ? $bill->objectGroups->first()->title : '' ]; $request->session()->flash('preFilled', $preFilled); $request->session()->forget('bills.edit.fromUpdate'); - return view('bills.edit', ['subTitle' => $subTitle, 'periods' => $periods, 'rules' => $rules, 'bill' => $bill, 'preFilled' => $preFilled]); + return view('bills.edit', ['subTitle' => $subTitle, 'periods' => $periods, 'rules' => $rules, 'bill' => $bill, 'preFilled' => $preFilled]); } /** @@ -121,7 +119,7 @@ class EditController extends Controller Preferences::mark(); /** @var null|array $files */ - $files = $request->hasFile('attachments') ? $request->file('attachments') : null; + $files = $request->hasFile('attachments') ? $request->file('attachments') : null; if (null !== $files && !auth()->user()->hasRole('demo')) { $this->attachments->saveAttachmentsForModel($bill, $files); } diff --git a/app/Http/Controllers/Bill/IndexController.php b/app/Http/Controllers/Bill/IndexController.php index db47cdeecd..20d3027e1a 100644 --- a/app/Http/Controllers/Bill/IndexController.php +++ b/app/Http/Controllers/Bill/IndexController.php @@ -56,15 +56,13 @@ class IndexController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string)trans('firefly.bills')); - app('view')->share('mainTitleIcon', 'fa-calendar-o'); - $this->repository = app(BillRepositoryInterface::class); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.bills')); + app('view')->share('mainTitleIcon', 'fa-calendar-o'); + $this->repository = app(BillRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -75,23 +73,21 @@ class IndexController extends Controller $this->cleanupObjectGroups(); $this->repository->correctOrder(); $this->repository->correctTransfers(); - $start = session('start'); - $end = session('end'); - $collection = $this->repository->getBills(); - $total = $collection->count(); + $start = session('start'); + $end = session('end'); + $collection = $this->repository->getBills(); + $total = $collection->count(); - - $parameters = new ParameterBag(); + $parameters = new ParameterBag(); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new SubscriptionEnrichment(); + $admin = auth()->user(); + $enrichment = new SubscriptionEnrichment(); $enrichment->setUser($admin); $enrichment->setStart($start->clone()); $enrichment->setEnd($end); - $collection = $enrichment->enrich($collection); - + $collection = $enrichment->enrich($collection); $parameters->set('start', $start->clone()); $parameters->set('end', $end); @@ -103,47 +99,41 @@ class IndexController extends Controller $transformer->setParameters($parameters); // loop all bills, convert to array and add rules and stuff. - $rules = $this->repository->getRulesForBills($collection); + $rules = $this->repository->getRulesForBills($collection); // make bill groups: - $bills = [ - 0 => [ // the index is the order, not the ID. - 'object_group_id' => 0, - 'object_group_title' => (string)trans('firefly.default_group_title_name'), - 'bills' => [], - ], - ]; + $bills = [0 => ['object_group_id' => 0, 'object_group_title' => (string) trans('firefly.default_group_title_name'), 'bills' => []]]; // the index is the order, not the ID. /** @var Bill $bill */ foreach ($collection as $bill) { - $array = $transformer->transform($bill); - $groupOrder = (int)$array['object_group_order']; + $array = $transformer->transform($bill); + $groupOrder = (int) $array['object_group_order']; // make group array if necessary: $bills[$groupOrder] ??= [ 'object_group_id' => $array['object_group_id'], 'object_group_title' => $array['object_group_title'], - 'bills' => [], + 'bills' => [] ]; - $currency = $bill->transactionCurrency ?? $this->primaryCurrency; - $array['currency_id'] = $currency->id; - $array['currency_name'] = $currency->name; - $array['currency_symbol'] = $currency->symbol; - $array['currency_code'] = $currency->code; + $currency = $bill->transactionCurrency ?? $this->primaryCurrency; + $array['currency_id'] = $currency->id; + $array['currency_name'] = $currency->name; + $array['currency_symbol'] = $currency->symbol; + $array['currency_code'] = $currency->code; $array['currency_decimal_places'] = $currency->decimal_places; - $array['attachments'] = $this->repository->getAttachments($bill); - $array['rules'] = $rules[$bill['id']] ?? []; - $bills[$groupOrder]['bills'][] = $array; + $array['attachments'] = $this->repository->getAttachments($bill); + $array['rules'] = $rules[$bill['id']] ?? []; + $bills[$groupOrder]['bills'][] = $array; } // order by key ksort($bills); // summarise per currency / per group. - $sums = $this->getSums($bills); - $totals = $this->getTotals($sums); - $today = now()->startOfDay(); + $sums = $this->getSums($bills); + $totals = $this->getTotals($sums); + $today = now()->startOfDay(); - return view('bills.index', ['bills' => $bills, 'sums' => $sums, 'total' => $total, 'totals' => $totals, 'today' => $today]); + return view('bills.index', ['bills' => $bills, 'sums' => $sums, 'total' => $total, 'totals' => $totals, 'today' => $today]); } private function getSums(array $bills): array @@ -171,7 +161,7 @@ class IndexController extends Controller } Log::debug(sprintf('Now at subscription #%d.', $bill['id'])); - $currencyId = $bill['currency_id']; + $currencyId = $bill['currency_id']; $sums[$groupOrder][$currencyId] ??= [ 'currency_id' => $currencyId, 'currency_code' => $bill['currency_code'], @@ -181,14 +171,19 @@ class IndexController extends Controller 'avg' => '0', 'total_left_to_pay' => '0', 'period' => $range, - 'per_period' => '0', + 'per_period' => '0' ]; - Log::debug(sprintf('Start with avg:%s, total_left_to_pay:%s, per_period:%s', $sums[$groupOrder][$currencyId]['avg'], $sums[$groupOrder][$currencyId]['total_left_to_pay'], $sums[$groupOrder][$currencyId]['per_period'])); + Log::debug(sprintf( + 'Start with avg:%s, total_left_to_pay:%s, per_period:%s', + $sums[$groupOrder][$currencyId]['avg'], + $sums[$groupOrder][$currencyId]['total_left_to_pay'], + $sums[$groupOrder][$currencyId]['per_period'] + )); // only fill in avg when bill is active. if (null !== $bill['next_expected_match']) { - $avg = bcdiv(bcadd((string)$bill['amount_min'], (string)$bill['amount_max']), '2'); - $avg = bcmul($avg, (string)count($bill['pay_dates'])); + $avg = bcdiv(bcadd((string) $bill['amount_min'], (string) $bill['amount_max']), '2'); + $avg = bcmul($avg, (string) count($bill['pay_dates'])); $sums[$groupOrder][$currencyId]['avg'] = bcadd($sums[$groupOrder][$currencyId]['avg'], $avg); Log::debug(sprintf('next expected match is "%s", avg is now %s', $bill['next_expected_match'], $sums[$groupOrder][$currencyId]['avg'])); @@ -197,15 +192,22 @@ class IndexController extends Controller if (count($bill['paid_dates']) < count($bill['pay_dates'])) { $count = count($bill['pay_dates']) - count($bill['paid_dates']); if ($count > 0) { - $avg = bcdiv(bcadd((string)$bill['amount_min'], (string)$bill['amount_max']), '2'); - $avg = bcmul($avg, (string)$count); + $avg = bcdiv(bcadd((string) $bill['amount_min'], (string) $bill['amount_max']), '2'); + $avg = bcmul($avg, (string) $count); $sums[$groupOrder][$currencyId]['total_left_to_pay'] = bcadd($sums[$groupOrder][$currencyId]['total_left_to_pay'], $avg); - Log::debug(sprintf('Bill has %d dates that need payment, total left to pay is now %s', $count, $sums[$groupOrder][$currencyId]['total_left_to_pay']), $bill['pay_dates']); + Log::debug( + sprintf( + 'Bill has %d dates that need payment, total left to pay is now %s', + $count, + $sums[$groupOrder][$currencyId]['total_left_to_pay'] + ), + $bill['pay_dates'] + ); } } } - $perPeriod = $this->amountPerPeriod($bill, $range); + $perPeriod = $this->amountPerPeriod($bill, $range); Log::debug(sprintf('Add amount %s to per_period', $perPeriod)); // fill in per period regardless: $sums[$groupOrder][$currencyId]['per_period'] = bcadd($sums[$groupOrder][$currencyId]['per_period'], $perPeriod); @@ -217,24 +219,17 @@ class IndexController extends Controller private function amountPerPeriod(array $bill, string $range): string { - $avg = bcdiv(bcadd((string)$bill['amount_min'], (string)$bill['amount_max']), '2'); + $avg = bcdiv(bcadd((string) $bill['amount_min'], (string) $bill['amount_max']), '2'); Log::debug(sprintf('Amount per period for bill #%d "%s"', $bill['id'], $bill['name'])); Log::debug(sprintf('Average is %s', $avg)); // calculate amount per year: - $multiplies = [ - 'yearly' => '1', - 'half-year' => '2', - 'quarterly' => '4', - 'monthly' => '12', - 'weekly' => '52.17', - 'daily' => '365.24', - ]; - $yearAmount = bcmul($avg, bcdiv($multiplies[$bill['repeat_freq']], (string)($bill['skip'] + 1))); - Log::debug(sprintf('Amount per year is %s (%s * %s / %s)', $yearAmount, $avg, $multiplies[$bill['repeat_freq']], (string)($bill['skip'] + 1))); + $multiplies = ['yearly' => '1', 'half-year' => '2', 'quarterly' => '4', 'monthly' => '12', 'weekly' => '52.17', 'daily' => '365.24']; + $yearAmount = bcmul($avg, bcdiv($multiplies[$bill['repeat_freq']], (string) ($bill['skip'] + 1))); + Log::debug(sprintf('Amount per year is %s (%s * %s / %s)', $yearAmount, $avg, $multiplies[$bill['repeat_freq']], (string) ($bill['skip'] + 1))); // per period: - $division = [ + $division = [ '1Y' => '1', '6M' => '2', '3M' => '4', @@ -247,9 +242,9 @@ class IndexController extends Controller 'last7' => '52.16', 'last30' => '12', 'last90' => '4', - 'last365' => '1', + 'last365' => '1' ]; - $perPeriod = bcdiv($yearAmount, $division[$range]); + $perPeriod = bcdiv($yearAmount, $division[$range]); Log::debug(sprintf('Amount per %s is %s (%s / %s)', $range, $perPeriod, $yearAmount, $division[$range])); @@ -280,10 +275,10 @@ class IndexController extends Controller 'currency_decimal_places' => $entry['currency_decimal_places'], 'avg' => '0', 'period' => $entry['period'], - 'per_period' => '0', + 'per_period' => '0' ]; - $totals[$currencyId]['avg'] = bcadd($totals[$currencyId]['avg'], (string)$entry['avg']); - $totals[$currencyId]['per_period'] = bcadd($totals[$currencyId]['per_period'], (string)$entry['per_period']); + $totals[$currencyId]['avg'] = bcadd($totals[$currencyId]['avg'], (string) $entry['avg']); + $totals[$currencyId]['per_period'] = bcadd($totals[$currencyId]['per_period'], (string) $entry['per_period']); } } @@ -295,8 +290,8 @@ class IndexController extends Controller */ public function setOrder(Request $request, Bill $bill): JsonResponse { - $objectGroupTitle = (string)$request->get('objectGroupTitle'); - $newOrder = (int)$request->get('order'); + $objectGroupTitle = (string) $request->get('objectGroupTitle'); + $newOrder = (int) $request->get('order'); $this->repository->setOrder($bill, $newOrder); if ('' !== $objectGroupTitle) { $this->repository->setObjectGroup($bill, $objectGroupTitle); diff --git a/app/Http/Controllers/Bill/ShowController.php b/app/Http/Controllers/Bill/ShowController.php index 7dc7259f2b..3781b0e7a0 100644 --- a/app/Http/Controllers/Bill/ShowController.php +++ b/app/Http/Controllers/Bill/ShowController.php @@ -24,13 +24,13 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Bill; -use FireflyIII\Support\Facades\Preferences; -use FireflyIII\Support\Facades\Navigation; use Carbon\Carbon; use FireflyIII\Helpers\Collector\GroupCollectorInterface; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\Bill; use FireflyIII\Repositories\Bill\BillRepositoryInterface; +use FireflyIII\Support\Facades\Navigation; +use FireflyIII\Support\Facades\Preferences; use FireflyIII\Support\JsonApi\Enrichments\SubscriptionEnrichment; use FireflyIII\TransactionRules\Engine\RuleEngineInterface; use FireflyIII\Transformers\AttachmentTransformer; @@ -65,15 +65,13 @@ class ShowController extends Controller app('view')->share('showBudget', true); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.bills')); - app('view')->share('mainTitleIcon', 'fa-calendar-o'); - $this->repository = app(BillRepositoryInterface::class); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.bills')); + app('view')->share('mainTitleIcon', 'fa-calendar-o'); + $this->repository = app(BillRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -81,13 +79,13 @@ class ShowController extends Controller */ public function rescan(Request $request, Bill $bill): Redirector|RedirectResponse { - $total = 0; + $total = 0; if (false === $bill->active) { $request->session()->flash('warning', (string) trans('firefly.cannot_scan_inactive_bill')); return redirect(route('bills.show', [$bill->id])); } - $set = $this->repository->getRulesForBill($bill); + $set = $this->repository->getRulesForBill($bill); if (0 === $set->count()) { $request->session()->flash('error', (string) trans('firefly.no_rules_for_bill')); @@ -123,71 +121,77 @@ class ShowController extends Controller { $this->repository->correctTransfers(); // add info about rules: - $rules = $this->repository->getRulesForBill($bill); - $subTitle = $bill->name; + $rules = $this->repository->getRulesForBill($bill); + $subTitle = $bill->name; /** @var Carbon $start */ - $start = session('start'); + $start = session('start'); /** @var Carbon $end */ - $end = session('end'); - $year = $start->year; - $page = (int) $request->get('page'); - $pageSize = (int) Preferences::get('listPageSize', 50)->data; - $yearAverage = $this->repository->getYearAverage($bill, $start); - $overallAverage = $this->repository->getOverallAverage($bill); - $manager = new Manager(); + $end = session('end'); + $year = $start->year; + $page = (int) $request->get('page'); + $pageSize = (int) Preferences::get('listPageSize', 50)->data; + $yearAverage = $this->repository->getYearAverage($bill, $start); + $overallAverage = $this->repository->getOverallAverage($bill); + $manager = new Manager(); $manager->setSerializer(new DataArraySerializer()); $manager->parseIncludes(['attachments', 'notes']); // add another period to end, could fix 8163 - $range = Navigation::getViewRange(true); - $end = Navigation::addPeriod($end, $range); + $range = Navigation::getViewRange(true); + $end = Navigation::addPeriod($end, $range); // Make a resource out of the data and - $parameters = new ParameterBag(); + $parameters = new ParameterBag(); $parameters->set('start', $start); $parameters->set('end', $end); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new SubscriptionEnrichment(); + $admin = auth()->user(); + $enrichment = new SubscriptionEnrichment(); $enrichment->setUser($admin); $enrichment->setStart($start); $enrichment->setEnd($end); /** @var Bill $bill */ - $bill = $enrichment->enrichSingle($bill); + $bill = $enrichment->enrichSingle($bill); /** @var BillTransformer $transformer */ - $transformer = app(BillTransformer::class); + $transformer = app(BillTransformer::class); $transformer->setParameters($parameters); - $resource = new Item($bill, $transformer, 'bill'); - $object = $manager->createData($resource)->toArray(); + $resource = new Item($bill, $transformer, 'bill'); + $object = $manager->createData($resource)->toArray(); $object['data']['currency'] = $bill->transactionCurrency; /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); - $collector->setBill($bill)->setLimit($pageSize)->setPage($page)->withBudgetInformation() - ->withCategoryInformation()->withAccountInformation() - ; - $groups = $collector->getPaginatedGroups(); + $collector = app(GroupCollectorInterface::class); + $collector->setBill($bill)->setLimit($pageSize)->setPage($page)->withBudgetInformation()->withCategoryInformation()->withAccountInformation(); + $groups = $collector->getPaginatedGroups(); $groups->setPath(route('bills.show', [$bill->id])); // transform any attachments as well. - $collection = $this->repository->getAttachments($bill); - $attachments = new Collection(); + $collection = $this->repository->getAttachments($bill); + $attachments = new Collection(); if ($collection->count() > 0) { /** @var AttachmentTransformer $transformer */ $transformer = app(AttachmentTransformer::class); - $attachments = $collection->each( - $transformer->transform(...) - ); + $attachments = $collection->each($transformer->transform(...)); } - return view('bills.show', ['attachments' => $attachments, 'groups' => $groups, 'rules' => $rules, 'yearAverage' => $yearAverage, 'overallAverage' => $overallAverage, 'year' => $year, 'object' => $object, 'bill' => $bill, 'subTitle' => $subTitle]); + return view('bills.show', [ + 'attachments' => $attachments, + 'groups' => $groups, + 'rules' => $rules, + 'yearAverage' => $yearAverage, + 'overallAverage' => $overallAverage, + 'year' => $year, + 'object' => $object, + 'bill' => $bill, + 'subTitle' => $subTitle + ]); } } diff --git a/app/Http/Controllers/Budget/BudgetLimitController.php b/app/Http/Controllers/Budget/BudgetLimitController.php index 6dfa5a84cb..fa7c03432e 100644 --- a/app/Http/Controllers/Budget/BudgetLimitController.php +++ b/app/Http/Controllers/Budget/BudgetLimitController.php @@ -24,8 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Budget; -use FireflyIII\Support\Facades\Preferences; -use Illuminate\Support\Facades\Log; use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; @@ -36,6 +34,9 @@ use FireflyIII\Repositories\Budget\BudgetLimitRepositoryInterface; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Repositories\Budget\OperationsRepositoryInterface; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; +use FireflyIII\Support\Facades\Amount; +use FireflyIII\Support\Facades\Preferences; +use FireflyIII\Support\Facades\Steam; use FireflyIII\Support\Http\Controllers\DateCalculation; use Illuminate\Contracts\View\Factory; use Illuminate\Http\JsonResponse; @@ -43,9 +44,8 @@ use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Routing\Redirector; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Log; use Illuminate\View\View; -use FireflyIII\Support\Facades\Steam; -use FireflyIII\Support\Facades\Amount; /** * Class BudgetLimitController @@ -55,9 +55,9 @@ class BudgetLimitController extends Controller use DateCalculation; private BudgetLimitRepositoryInterface $blRepository; - private CurrencyRepositoryInterface $currencyRepos; - private OperationsRepositoryInterface $opsRepository; - private BudgetRepositoryInterface $repository; + private CurrencyRepositoryInterface $currencyRepos; + private OperationsRepositoryInterface $opsRepository; + private BudgetRepositoryInterface $repository; /** * AmountController constructor. @@ -65,18 +65,16 @@ class BudgetLimitController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.budgets')); - app('view')->share('mainTitleIcon', 'fa-pie-chart'); - $this->repository = app(BudgetRepositoryInterface::class); - $this->opsRepository = app(OperationsRepositoryInterface::class); - $this->blRepository = app(BudgetLimitRepositoryInterface::class); - $this->currencyRepos = app(CurrencyRepositoryInterface::class); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.budgets')); + app('view')->share('mainTitleIcon', 'fa-pie-chart'); + $this->repository = app(BudgetRepositoryInterface::class); + $this->opsRepository = app(OperationsRepositoryInterface::class); + $this->blRepository = app(BudgetLimitRepositoryInterface::class); + $this->currencyRepos = app(CurrencyRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -88,21 +86,18 @@ class BudgetLimitController extends Controller $budgetLimits = $this->blRepository->getBudgetLimits($budget, $start, $end); // remove already budgeted currencies with the same date range - $currencies = $collection->filter( - static function (TransactionCurrency $currency) use ($budgetLimits, $start, $end): bool { - /** @var BudgetLimit $limit */ - foreach ($budgetLimits as $limit) { - if ($limit->transaction_currency_id === $currency->id && $limit->start_date->isSameDay($start) && $limit->end_date->isSameDay($end) - ) { - return false; - } + $currencies = $collection->filter(static function (TransactionCurrency $currency) use ($budgetLimits, $start, $end): bool { + /** @var BudgetLimit $limit */ + foreach ($budgetLimits as $limit) { + if ($limit->transaction_currency_id === $currency->id && $limit->start_date->isSameDay($start) && $limit->end_date->isSameDay($end)) { + return false; } - - return true; } - ); - return view('budgets.budget-limits.create', ['start' => $start, 'end' => $end, 'currencies' => $currencies, 'budget' => $budget]); + return true; + }); + + return view('budgets.budget-limits.create', ['start' => $start, 'end' => $end, 'currencies' => $currencies, 'budget' => $budget]); } public function delete(BudgetLimit $budgetLimit): Redirector|RedirectResponse @@ -120,7 +115,7 @@ class BudgetLimitController extends Controller { $notes = $this->blRepository->getNoteText($budgetLimit); - return view('budgets.budget-limits.edit', ['budgetLimit' => $budgetLimit, 'notes' => $notes]); + return view('budgets.budget-limits.edit', ['budgetLimit' => $budgetLimit, 'notes' => $notes]); } /** @@ -130,7 +125,7 @@ class BudgetLimitController extends Controller { $notes = $this->blRepository->getNoteText($budgetLimit); - return view('budgets.budget-limits.show', ['budgetLimit' => $budgetLimit, 'notes' => $notes]); + return view('budgets.budget-limits.show', ['budgetLimit' => $budgetLimit, 'notes' => $notes]); } /** @@ -147,14 +142,14 @@ class BudgetLimitController extends Controller if (!$currency instanceof TransactionCurrency || !$budget instanceof Budget) { throw new FireflyException('No valid currency or budget.'); } - $start = Carbon::createFromFormat('Y-m-d', $request->get('start')); - $end = Carbon::createFromFormat('Y-m-d', $request->get('end')); + $start = Carbon::createFromFormat('Y-m-d', $request->get('start')); + $end = Carbon::createFromFormat('Y-m-d', $request->get('end')); if (!$start instanceof Carbon || !$end instanceof Carbon) { return response()->json(); } - $amount = (string) $request->get('amount'); + $amount = (string) $request->get('amount'); $start->startOfDay(); $end->startOfDay(); @@ -164,7 +159,7 @@ class BudgetLimitController extends Controller Log::debug(sprintf('Start: %s, end: %s', $start->format('Y-m-d'), $end->format('Y-m-d'))); - $limit = $this->blRepository->find($budget, $currency, $start, $end); + $limit = $this->blRepository->find($budget, $currency, $start, $end); // sanity check on amount: if (0 === bccomp($amount, '0')) { @@ -187,36 +182,36 @@ class BudgetLimitController extends Controller $limit->save(); } if (!$limit instanceof BudgetLimit) { - $limit = $this->blRepository->store( - [ - 'budget_id' => $request->get('budget_id'), - 'currency_id' => (int) $request->get('transaction_currency_id'), - 'start_date' => $start, - 'end_date' => $end, - 'amount' => $amount, - ] - ); + $limit = $this->blRepository->store([ + 'budget_id' => $request->get('budget_id'), + 'currency_id' => (int) $request->get('transaction_currency_id'), + 'start_date' => $start, + 'end_date' => $end, + 'amount' => $amount + ]); } // parse notes, if any. - $notes = (string) $request->get('notes'); + $notes = (string) $request->get('notes'); $this->blRepository->setNoteText($limit, $notes); if ($request->expectsJson()) { - $array = $limit->toArray(); + $array = $limit->toArray(); // add some extra metadata: - $spentArr = $this->opsRepository->sumExpenses($limit->start_date, $limit->end_date, null, new Collection()->push($budget), $currency); - $array['spent'] = $spentArr[$currency->id]['sum'] ?? '0'; - $array['left_formatted'] = Amount::formatAnything($limit->transactionCurrency, bcadd($array['spent'], (string) $array['amount'])); - $array['amount_formatted'] = Amount::formatAnything($limit->transactionCurrency, $limit['amount']); - $array['days_left'] = (string) $this->activeDaysLeft($start, $end); + $spentArr = $this->opsRepository->sumExpenses($limit->start_date, $limit->end_date, null, new Collection()->push($budget), $currency); + $array['spent'] = $spentArr[$currency->id]['sum'] ?? '0'; + $array['left_formatted'] = Amount::formatAnything($limit->transactionCurrency, bcadd($array['spent'], (string) $array['amount'])); + $array['amount_formatted'] = Amount::formatAnything($limit->transactionCurrency, $limit['amount']); + $array['days_left'] = (string) $this->activeDaysLeft($start, $end); // left per day: - $array['left_per_day'] = 0 === bccomp('0', $array['days_left']) ? bcadd((string) $array['spent'], (string) $array['amount']) : bcdiv(bcadd((string) $array['spent'], (string) $array['amount']), $array['days_left']); + $array['left_per_day'] = 0 === bccomp('0', $array['days_left']) + ? bcadd((string) $array['spent'], (string) $array['amount']) + : bcdiv(bcadd((string) $array['spent'], (string) $array['amount']), $array['days_left']); // left per day formatted. $array['left_per_day_formatted'] = Amount::formatAnything($limit->transactionCurrency, $array['left_per_day']); // notes: - $array['notes'] = $this->blRepository->getNoteText($limit); + $array['notes'] = $this->blRepository->getNoteText($limit); return response()->json($array); } @@ -226,7 +221,7 @@ class BudgetLimitController extends Controller public function update(Request $request, BudgetLimit $budgetLimit): JsonResponse|RedirectResponse { - $amount = (string) $request->get('amount'); + $amount = (string) $request->get('amount'); if ('' === $amount) { $amount = '0'; } @@ -238,11 +233,11 @@ class BudgetLimitController extends Controller $budgetId = $budgetLimit->budget_id; $currency = $budgetLimit->transactionCurrency; $this->blRepository->destroyBudgetLimit($budgetLimit); - $array = [ + $array = [ 'budget_id' => $budgetId, 'left_formatted' => Amount::formatAnything($currency, '0'), 'left_per_day_formatted' => Amount::formatAnything($currency, '0'), - 'transaction_currency_id' => $currency->id, + 'transaction_currency_id' => $currency->id ]; return response()->json($array); @@ -251,32 +246,33 @@ class BudgetLimitController extends Controller if (-1 === bccomp($amount, '0')) { $amount = bcmul($amount, '-1'); } - $notes = (string) $request->get('notes'); + $notes = (string) $request->get('notes'); if (strlen($notes) > 32768) { $notes = substr($notes, 0, 32768); } - - $limit = $this->blRepository->update($budgetLimit, ['amount' => $amount, 'notes' => $notes]); + $limit = $this->blRepository->update($budgetLimit, ['amount' => $amount, 'notes' => $notes]); Preferences::mark(); - $array = $limit->toArray(); + $array = $limit->toArray(); - $spentArr = $this->opsRepository->sumExpenses( + $spentArr = $this->opsRepository->sumExpenses( $limit->start_date, $limit->end_date, null, new Collection()->push($budgetLimit->budget), $budgetLimit->transactionCurrency ); - $daysLeft = $this->activeDaysLeft($limit->start_date, $limit->end_date); - $array['spent'] = $spentArr[$budgetLimit->transactionCurrency->id]['sum'] ?? '0'; - $array['left_formatted'] = Amount::formatAnything($limit->transactionCurrency, bcadd($array['spent'], (string) $array['amount'])); - $array['amount_formatted'] = Amount::formatAnything($limit->transactionCurrency, $limit['amount']); - $array['days_left'] = (string) $daysLeft; - $array['left_per_day'] = 0 === $daysLeft ? bcadd((string) $array['spent'], (string) $array['amount']) : bcdiv(bcadd((string) $array['spent'], (string) $array['amount']), $array['days_left']); + $daysLeft = $this->activeDaysLeft($limit->start_date, $limit->end_date); + $array['spent'] = $spentArr[$budgetLimit->transactionCurrency->id]['sum'] ?? '0'; + $array['left_formatted'] = Amount::formatAnything($limit->transactionCurrency, bcadd($array['spent'], (string) $array['amount'])); + $array['amount_formatted'] = Amount::formatAnything($limit->transactionCurrency, $limit['amount']); + $array['days_left'] = (string) $daysLeft; + $array['left_per_day'] = 0 === $daysLeft + ? bcadd((string) $array['spent'], (string) $array['amount']) + : bcdiv(bcadd((string) $array['spent'], (string) $array['amount']), $array['days_left']); // left per day formatted. - $array['amount'] = Steam::bcround($limit['amount'], $limit->transactionCurrency->decimal_places); + $array['amount'] = Steam::bcround($limit['amount'], $limit->transactionCurrency->decimal_places); $array['left_per_day_formatted'] = Amount::formatAnything($limit->transactionCurrency, $array['left_per_day']); if ('true' === $request->get('redirect')) { return redirect(route('budgets.index')); diff --git a/app/Http/Controllers/Budget/CreateController.php b/app/Http/Controllers/Budget/CreateController.php index de3a38ebb4..e54e59f807 100644 --- a/app/Http/Controllers/Budget/CreateController.php +++ b/app/Http/Controllers/Budget/CreateController.php @@ -24,13 +24,13 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Budget; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Enums\AutoBudgetType; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Helpers\Attachments\AttachmentHelperInterface; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Requests\BudgetFormStoreRequest; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; @@ -51,16 +51,14 @@ class CreateController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.budgets')); - app('view')->share('mainTitleIcon', 'fa-pie-chart'); - $this->repository = app(BudgetRepositoryInterface::class); - $this->attachments = app(AttachmentHelperInterface::class); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.budgets')); + app('view')->share('mainTitleIcon', 'fa-pie-chart'); + $this->repository = app(BudgetRepositoryInterface::class); + $this->attachments = app(AttachmentHelperInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -70,14 +68,14 @@ class CreateController extends Controller */ public function create(Request $request): Factory|\Illuminate\Contracts\View\View { - $hasOldInput = null !== $request->old('_token'); + $hasOldInput = null !== $request->old('_token'); // auto budget types $autoBudgetTypes = [ 0 => (string) trans('firefly.auto_budget_none'), AutoBudgetType::AUTO_BUDGET_RESET->value => (string) trans('firefly.auto_budget_reset'), AutoBudgetType::AUTO_BUDGET_ROLLOVER->value => (string) trans('firefly.auto_budget_rollover'), - AutoBudgetType::AUTO_BUDGET_ADJUSTED->value => (string) trans('firefly.auto_budget_adjusted'), + AutoBudgetType::AUTO_BUDGET_ADJUSTED->value => (string) trans('firefly.auto_budget_adjusted') ]; $autoBudgetPeriods = [ 'daily' => (string) trans('firefly.auto_budget_period_daily'), @@ -85,12 +83,12 @@ class CreateController extends Controller 'monthly' => (string) trans('firefly.auto_budget_period_monthly'), 'quarterly' => (string) trans('firefly.auto_budget_period_quarterly'), 'half_year' => (string) trans('firefly.auto_budget_period_half_year'), - 'yearly' => (string) trans('firefly.auto_budget_period_yearly'), + 'yearly' => (string) trans('firefly.auto_budget_period_yearly') ]; - $preFilled = [ + $preFilled = [ 'auto_budget_period' => $hasOldInput ? (bool) $request->old('auto_budget_period') : 'monthly', - 'auto_budget_currency_id' => $hasOldInput ? (int) $request->old('auto_budget_currency_id') : $this->primaryCurrency->id, + 'auto_budget_currency_id' => $hasOldInput ? (int) $request->old('auto_budget_currency_id') : $this->primaryCurrency->id ]; $request->session()->flash('preFilled', $preFilled); @@ -100,9 +98,9 @@ class CreateController extends Controller $this->rememberPreviousUrl('budgets.create.url'); } $request->session()->forget('budgets.create.fromStore'); - $subTitle = (string) trans('firefly.create_new_budget'); + $subTitle = (string) trans('firefly.create_new_budget'); - return view('budgets.create', ['subTitle' => $subTitle, 'autoBudgetTypes' => $autoBudgetTypes, 'autoBudgetPeriods' => $autoBudgetPeriods]); + return view('budgets.create', ['subTitle' => $subTitle, 'autoBudgetTypes' => $autoBudgetTypes, 'autoBudgetPeriods' => $autoBudgetPeriods]); } /** @@ -112,9 +110,9 @@ class CreateController extends Controller */ public function store(BudgetFormStoreRequest $request): RedirectResponse { - $data = $request->getBudgetData(); + $data = $request->getBudgetData(); - $budget = $this->repository->store($data); + $budget = $this->repository->store($data); $this->repository->cleanupBudgets(); $request->session()->flash('success', (string) trans('firefly.stored_new_budget', ['name' => $budget->name])); Preferences::mark(); @@ -123,7 +121,7 @@ class CreateController extends Controller // store attachment(s): /** @var null|array $files */ - $files = $request->hasFile('attachments') ? $request->file('attachments') : null; + $files = $request->hasFile('attachments') ? $request->file('attachments') : null; if (null !== $files && !auth()->user()->hasRole('demo')) { $this->attachments->saveAttachmentsForModel($budget, $files); } diff --git a/app/Http/Controllers/Budget/DeleteController.php b/app/Http/Controllers/Budget/DeleteController.php index b9989c45ef..9f28985b2a 100644 --- a/app/Http/Controllers/Budget/DeleteController.php +++ b/app/Http/Controllers/Budget/DeleteController.php @@ -24,10 +24,10 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Budget; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\Budget; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; @@ -49,15 +49,13 @@ class DeleteController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.budgets')); - app('view')->share('mainTitleIcon', 'fa-pie-chart'); - $this->repository = app(BudgetRepositoryInterface::class); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.budgets')); + app('view')->share('mainTitleIcon', 'fa-pie-chart'); + $this->repository = app(BudgetRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -72,7 +70,7 @@ class DeleteController extends Controller // put previous url in session $this->rememberPreviousUrl('budgets.delete.url'); - return view('budgets.delete', ['budget' => $budget, 'subTitle' => $subTitle]); + return view('budgets.delete', ['budget' => $budget, 'subTitle' => $subTitle]); } /** diff --git a/app/Http/Controllers/Budget/EditController.php b/app/Http/Controllers/Budget/EditController.php index d327f94edd..567e132aea 100644 --- a/app/Http/Controllers/Budget/EditController.php +++ b/app/Http/Controllers/Budget/EditController.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Budget; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Enums\AutoBudgetType; use FireflyIII\Helpers\Attachments\AttachmentHelperInterface; use FireflyIII\Http\Controllers\Controller; @@ -32,12 +31,13 @@ use FireflyIII\Http\Requests\BudgetFormUpdateRequest; use FireflyIII\Models\AutoBudget; use FireflyIII\Models\Budget; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; +use FireflyIII\Support\Facades\Steam; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; use Illuminate\View\View; -use FireflyIII\Support\Facades\Steam; /** * Class EditController @@ -54,16 +54,14 @@ class EditController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.budgets')); - app('view')->share('mainTitleIcon', 'fa-pie-chart'); - $this->repository = app(BudgetRepositoryInterface::class); - $this->attachments = app(AttachmentHelperInterface::class); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.budgets')); + app('view')->share('mainTitleIcon', 'fa-pie-chart'); + $this->repository = app(BudgetRepositoryInterface::class); + $this->attachments = app(AttachmentHelperInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -73,15 +71,15 @@ class EditController extends Controller */ public function edit(Request $request, Budget $budget): Factory|\Illuminate\Contracts\View\View { - $subTitle = (string) trans('firefly.edit_budget', ['name' => $budget->name]); - $autoBudget = $this->repository->getAutoBudget($budget); + $subTitle = (string) trans('firefly.edit_budget', ['name' => $budget->name]); + $autoBudget = $this->repository->getAutoBudget($budget); // auto budget types $autoBudgetTypes = [ 0 => (string) trans('firefly.auto_budget_none'), AutoBudgetType::AUTO_BUDGET_RESET->value => (string) trans('firefly.auto_budget_reset'), AutoBudgetType::AUTO_BUDGET_ROLLOVER->value => (string) trans('firefly.auto_budget_rollover'), - AutoBudgetType::AUTO_BUDGET_ADJUSTED->value => (string) trans('firefly.auto_budget_adjusted'), + AutoBudgetType::AUTO_BUDGET_ADJUSTED->value => (string) trans('firefly.auto_budget_adjusted') ]; $autoBudgetPeriods = [ 'daily' => (string) trans('firefly.auto_budget_period_daily'), @@ -89,22 +87,22 @@ class EditController extends Controller 'monthly' => (string) trans('firefly.auto_budget_period_monthly'), 'quarterly' => (string) trans('firefly.auto_budget_period_quarterly'), 'half_year' => (string) trans('firefly.auto_budget_period_half_year'), - 'yearly' => (string) trans('firefly.auto_budget_period_yearly'), + 'yearly' => (string) trans('firefly.auto_budget_period_yearly') ]; // code to handle active-checkboxes - $hasOldInput = null !== $request->old('_token'); - $preFilled = [ + $hasOldInput = null !== $request->old('_token'); + $preFilled = [ 'active' => $hasOldInput ? (bool) $request->old('active') : $budget->active, 'auto_budget_currency_id' => $hasOldInput ? (int) $request->old('auto_budget_currency_id') : $this->primaryCurrency->id, - 'notes' => $this->repository->getNoteText($budget), + 'notes' => $this->repository->getNoteText($budget) ]; if ($autoBudget instanceof AutoBudget) { - $amount = $hasOldInput ? $request->old('auto_budget_amount') : $autoBudget->amount; + $amount = $hasOldInput ? $request->old('auto_budget_amount') : $autoBudget->amount; if (is_array($amount)) { $amount = '0'; } - $amount = (string) $amount; + $amount = (string) $amount; $preFilled['auto_budget_amount'] = Steam::bcround($amount, $autoBudget->transactionCurrency->decimal_places); } @@ -115,7 +113,13 @@ class EditController extends Controller $request->session()->forget('budgets.edit.fromUpdate'); $request->session()->flash('preFilled', $preFilled); - return view('budgets.edit', ['budget' => $budget, 'subTitle' => $subTitle, 'autoBudgetTypes' => $autoBudgetTypes, 'autoBudgetPeriods' => $autoBudgetPeriods, 'autoBudget' => $autoBudget]); + return view('budgets.edit', [ + 'budget' => $budget, + 'subTitle' => $subTitle, + 'autoBudgetTypes' => $autoBudgetTypes, + 'autoBudgetPeriods' => $autoBudgetPeriods, + 'autoBudget' => $autoBudget + ]); } /** @@ -123,7 +127,7 @@ class EditController extends Controller */ public function update(BudgetFormUpdateRequest $request, Budget $budget): RedirectResponse { - $data = $request->getBudgetData(); + $data = $request->getBudgetData(); $this->repository->update($budget, $data); $request->session()->flash('success', (string) trans('firefly.updated_budget', ['name' => $budget->name])); @@ -136,7 +140,7 @@ class EditController extends Controller // store new attachment(s): /** @var null|array $files */ - $files = $request->hasFile('attachments') ? $request->file('attachments') : null; + $files = $request->hasFile('attachments') ? $request->file('attachments') : null; if (null !== $files && !auth()->user()->hasRole('demo')) { $this->attachments->saveAttachmentsForModel($budget, $files); } diff --git a/app/Http/Controllers/Budget/IndexController.php b/app/Http/Controllers/Budget/IndexController.php index 2bce5d8de3..c6884faf81 100644 --- a/app/Http/Controllers/Budget/IndexController.php +++ b/app/Http/Controllers/Budget/IndexController.php @@ -24,8 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Budget; -use FireflyIII\Support\Facades\Preferences; -use FireflyIII\Support\Facades\Navigation; use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; @@ -38,6 +36,9 @@ use FireflyIII\Repositories\Budget\BudgetLimitRepositoryInterface; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Repositories\Budget\OperationsRepositoryInterface; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; +use FireflyIII\Support\Facades\Navigation; +use FireflyIII\Support\Facades\Preferences; +use FireflyIII\Support\Facades\Steam; use FireflyIII\Support\Http\Api\ExchangeRateConverter; use FireflyIII\Support\Http\Controllers\DateCalculation; use Illuminate\Contracts\View\Factory; @@ -46,7 +47,6 @@ use Illuminate\Http\Request; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; use Illuminate\View\View; -use FireflyIII\Support\Facades\Steam; /** * Class IndexController @@ -56,10 +56,10 @@ class IndexController extends Controller use DateCalculation; private AvailableBudgetRepositoryInterface $abRepository; - private BudgetLimitRepositoryInterface $blRepository; - private CurrencyRepositoryInterface $currencyRepository; - private OperationsRepositoryInterface $opsRepository; - private BudgetRepositoryInterface $repository; + private BudgetLimitRepositoryInterface $blRepository; + private CurrencyRepositoryInterface $currencyRepository; + private OperationsRepositoryInterface $opsRepository; + private BudgetRepositoryInterface $repository; /** * IndexController constructor. @@ -68,20 +68,18 @@ class IndexController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.budgets')); - app('view')->share('mainTitleIcon', 'fa-pie-chart'); - $this->repository = app(BudgetRepositoryInterface::class); - $this->opsRepository = app(OperationsRepositoryInterface::class); - $this->abRepository = app(AvailableBudgetRepositoryInterface::class); - $this->currencyRepository = app(CurrencyRepositoryInterface::class); - $this->blRepository = app(BudgetLimitRepositoryInterface::class); - $this->repository->cleanupBudgets(); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.budgets')); + app('view')->share('mainTitleIcon', 'fa-pie-chart'); + $this->repository = app(BudgetRepositoryInterface::class); + $this->opsRepository = app(OperationsRepositoryInterface::class); + $this->abRepository = app(AvailableBudgetRepositoryInterface::class); + $this->currencyRepository = app(CurrencyRepositoryInterface::class); + $this->blRepository = app(BudgetLimitRepositoryInterface::class); + $this->repository->cleanupBudgets(); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -91,14 +89,14 @@ class IndexController extends Controller * * @throws FireflyException * */ - public function index(?Carbon $start = null, ?Carbon $end = null): Factory|\Illuminate\Contracts\View\View + public function index(null|Carbon $start = null, null|Carbon $end = null): Factory|\Illuminate\Contracts\View\View { $this->abRepository->cleanup(); Log::debug(sprintf('Start of IndexController::index("%s", "%s")', $start?->format('Y-m-d'), $end?->format('Y-m-d'))); // collect some basic vars: - $range = Navigation::getViewRange(true); - $isCustomRange = session('is_custom_range', false); + $range = Navigation::getViewRange(true); + $isCustomRange = session('is_custom_range', false); if (false === $isCustomRange) { $start ??= session('start', today(config('app.timezone'))->startOfMonth()); $end ??= Navigation::endOfPeriod($start, $range); @@ -110,23 +108,23 @@ class IndexController extends Controller $end ??= session('end', today(config('app.timezone'))->endOfMonth()); } - $currencies = $this->currencyRepository->get(); - $budgeted = '0'; - $spent = '0'; + $currencies = $this->currencyRepository->get(); + $budgeted = '0'; + $spent = '0'; // new period stuff: - $periodTitle = Navigation::periodShow($start, $range); - $prevLoop = $this->getPreviousPeriods($start, $range); - $nextLoop = $this->getNextPeriods($start, $range); + $periodTitle = Navigation::periodShow($start, $range); + $prevLoop = $this->getPreviousPeriods($start, $range); + $nextLoop = $this->getNextPeriods($start, $range); // get all available budgets: $availableBudgets = $this->getAllAvailableBudgets($start, $end); // get all active budgets: - $budgets = $this->getAllBudgets($start, $end, $currencies, $this->primaryCurrency); + $budgets = $this->getAllBudgets($start, $end, $currencies, $this->primaryCurrency); // echo '
';
         //        var_dump($budgets[0]);exit;
-        $sums             = $this->getSums($budgets);
+        $sums = $this->getSums($budgets);
 
         // get budgeted for default currency:
         if (0 === count($availableBudgets)) {
@@ -137,21 +135,33 @@ class IndexController extends Controller
         }
         // number of days for consistent budgeting.
         $activeDaysPassed = $this->activeDaysPassed($start, $end); // see method description.
-        $activeDaysLeft   = $this->activeDaysLeft($start, $end);   // see method description.
+        $activeDaysLeft = $this->activeDaysLeft($start, $end); // see method description.
 
         // get all inactive budgets, and simply list them:
-        $inactive         = $this->repository->getInactiveBudgets();
+        $inactive = $this->repository->getInactiveBudgets();
 
-        return view(
-            'budgets.index',
-            ['availableBudgets' => $availableBudgets, 'budgeted' => $budgeted, 'spent' => $spent, 'prevLoop' => $prevLoop, 'nextLoop' => $nextLoop, 'currencies' => $currencies, 'periodTitle' => $periodTitle, 'activeDaysPassed' => $activeDaysPassed, 'activeDaysLeft' => $activeDaysLeft, 'inactive' => $inactive, 'budgets' => $budgets, 'start' => $start, 'end' => $end, 'sums' => $sums]
-        );
+        return view('budgets.index', [
+            'availableBudgets' => $availableBudgets,
+            'budgeted'         => $budgeted,
+            'spent'            => $spent,
+            'prevLoop'         => $prevLoop,
+            'nextLoop'         => $nextLoop,
+            'currencies'       => $currencies,
+            'periodTitle'      => $periodTitle,
+            'activeDaysPassed' => $activeDaysPassed,
+            'activeDaysLeft'   => $activeDaysLeft,
+            'inactive'         => $inactive,
+            'budgets'          => $budgets,
+            'start'            => $start,
+            'end'              => $end,
+            'sums'             => $sums
+        ]);
     }
 
     private function getAllAvailableBudgets(Carbon $start, Carbon $end): array
     {
         Log::debug(sprintf('Start of getAllAvailableBudgets("%s", "%s")', $start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s')));
-        $converter        = new ExchangeRateConverter();
+        $converter = new ExchangeRateConverter();
         // get all available budgets.
         $ab               = $this->abRepository->get($start, $end);
         $availableBudgets = [];
@@ -159,22 +169,25 @@ class IndexController extends Controller
         // for each, complement with spent amount:
         /** @var AvailableBudget $entry */
         foreach ($ab as $entry) {
-            $array                = $entry->toArray();
-            $array['start_date']  = $entry->start_date;
-            $array['end_date']    = $entry->end_date;
+            $array = $entry->toArray();
+            $array['start_date'] = $entry->start_date;
+            $array['end_date'] = $entry->end_date;
 
             // spent in period:
-            $spentArr             = $this->opsRepository->sumExpenses($entry->start_date, $entry->end_date, null, null, $entry->transactionCurrency);
-            $array['spent']       = $spentArr[$entry->transaction_currency_id]['sum'] ?? '0';
-            $array['pc_spent']    = $this->convertToPrimary && $entry->transaction_currency_id !== $this->primaryCurrency->id ? $converter->convert($entry->transactionCurrency, $this->primaryCurrency, $entry->start_date, $array['spent']) : null;
+            $spentArr = $this->opsRepository->sumExpenses($entry->start_date, $entry->end_date, null, null, $entry->transactionCurrency);
+            $array['spent'] = $spentArr[$entry->transaction_currency_id]['sum'] ?? '0';
+            $array['pc_spent'] = $this->convertToPrimary && $entry->transaction_currency_id !== $this->primaryCurrency->id
+                ? $converter->convert($entry->transactionCurrency, $this->primaryCurrency, $entry->start_date, $array['spent'])
+                : null;
             // budgeted in period:
-            $budgeted             = $this->blRepository->budgeted($entry->start_date, $entry->end_date, $entry->transactionCurrency);
-            $array['budgeted']    = $budgeted;
-            $array['pc_budgeted'] = $this->convertToPrimary && $entry->transaction_currency_id !== $this->primaryCurrency->id ? $converter->convert($entry->transactionCurrency, $this->primaryCurrency, $entry->start_date, $budgeted) : null;
+            $budgeted = $this->blRepository->budgeted($entry->start_date, $entry->end_date, $entry->transactionCurrency);
+            $array['budgeted'] = $budgeted;
+            $array['pc_budgeted'] = $this->convertToPrimary && $entry->transaction_currency_id !== $this->primaryCurrency->id
+                ? $converter->convert($entry->transactionCurrency, $this->primaryCurrency, $entry->start_date, $budgeted)
+                : null;
             // this time, because of complex sums, use the currency converter.
 
-
-            $availableBudgets[]   = $array;
+            $availableBudgets[] = $array;
             unset($spentArr);
         }
 
@@ -192,19 +205,19 @@ class IndexController extends Controller
         /** @var Budget $current */
         foreach ($collection as $current) {
             Log::debug(sprintf('Working on budget #%d ("%s")', $current->id, $current->name));
-            $array                = $current->toArray();
-            $array['spent']       = [];
+            $array = $current->toArray();
+            $array['spent'] = [];
             $array['spent_total'] = [];
-            $array['budgeted']    = [];
+            $array['budgeted'] = [];
             $array['attachments'] = $this->repository->getAttachments($current);
             $array['auto_budget'] = $this->repository->getAutoBudget($current);
-            $budgetLimits         = $this->blRepository->getBudgetLimits($current, $start, $end);
+            $budgetLimits = $this->blRepository->getBudgetLimits($current, $start, $end);
 
             /** @var BudgetLimit $limit */
             foreach ($budgetLimits as $limit) {
                 Log::debug(sprintf('Working on budget limit #%d', $limit->id));
-                $currency            = $limit->transactionCurrency ?? $primaryCurrency;
-                $amount              = Steam::bcround($limit->amount, $currency->decimal_places);
+                $currency = $limit->transactionCurrency ?? $primaryCurrency;
+                $amount   = Steam::bcround($limit->amount, $currency->decimal_places);
                 $array['budgeted'][] = [
                     'id'                      => $limit->id,
                     'amount'                  => $amount,
@@ -216,7 +229,7 @@ class IndexController extends Controller
                     'currency_id'             => $currency->id,
                     'currency_symbol'         => $currency->symbol,
                     'currency_name'           => $currency->name,
-                    'currency_decimal_places' => $currency->decimal_places,
+                    'currency_decimal_places' => $currency->decimal_places
                 ];
                 Log::debug(sprintf('The amount budgeted for budget limit #%d is %s %s', $limit->id, $currency->code, $amount));
             }
@@ -227,13 +240,13 @@ class IndexController extends Controller
             foreach ($currencies as $currency) {
                 $spentArr = $this->opsRepository->sumExpenses($start, $end, null, new Collection()->push($current), $currency);
                 if (array_key_exists($currency->id, $spentArr) && array_key_exists('sum', $spentArr[$currency->id])) {
-                    $array['spent'][$currency->id]['spent']                   = $spentArr[$currency->id]['sum'];
-                    $array['spent'][$currency->id]['currency_id']             = $currency->id;
-                    $array['spent'][$currency->id]['currency_symbol']         = $currency->symbol;
+                    $array['spent'][$currency->id]['spent'] = $spentArr[$currency->id]['sum'];
+                    $array['spent'][$currency->id]['currency_id'] = $currency->id;
+                    $array['spent'][$currency->id]['currency_symbol'] = $currency->symbol;
                     $array['spent'][$currency->id]['currency_decimal_places'] = $currency->decimal_places;
                 }
             }
-            $budgets[]            = $array;
+            $budgets[] = $array;
         }
 
         return $budgets;
@@ -241,11 +254,7 @@ class IndexController extends Controller
 
     private function getSums(array $budgets): array
     {
-        $sums = [
-            'budgeted' => [],
-            'spent'    => [],
-            'left'     => [],
-        ];
+        $sums = ['budgeted' => [], 'spent'    => [], 'left'     => []];
 
         /** @var array $budget */
         foreach ($budgets as $budget) {
@@ -253,37 +262,34 @@ class IndexController extends Controller
 
             /** @var array $spent */
             foreach ($budget['spent'] as $spent) {
-                $currencyId                           = $spent['currency_id'];
-                $sums['spent'][$currencyId]
-                                                      ??= [
-                                                          'amount'                  => '0',
-                                                          'currency_id'             => $spent['currency_id'],
-                                                          'currency_symbol'         => $spent['currency_symbol'],
-                                                          'currency_decimal_places' => $spent['currency_decimal_places'],
-                                                      ];
+                $currencyId = $spent['currency_id'];
+                $sums['spent'][$currencyId] ??= [
+                    'amount'                  => '0',
+                    'currency_id'             => $spent['currency_id'],
+                    'currency_symbol'         => $spent['currency_symbol'],
+                    'currency_decimal_places' => $spent['currency_decimal_places']
+                ];
                 $sums['spent'][$currencyId]['amount'] = bcadd($sums['spent'][$currencyId]['amount'], (string) $spent['spent']);
             }
 
             /** @var array $budgeted */
             foreach ($budget['budgeted'] as $budgeted) {
-                $currencyId                              = $budgeted['currency_id'];
-                $sums['budgeted'][$currencyId]
-                                                         ??= [
-                                                             'amount'                  => '0',
-                                                             'currency_id'             => $budgeted['currency_id'],
-                                                             'currency_symbol'         => $budgeted['currency_symbol'],
-                                                             'currency_decimal_places' => $budgeted['currency_decimal_places'],
-                                                         ];
+                $currencyId = $budgeted['currency_id'];
+                $sums['budgeted'][$currencyId] ??= [
+                    'amount'                  => '0',
+                    'currency_id'             => $budgeted['currency_id'],
+                    'currency_symbol'         => $budgeted['currency_symbol'],
+                    'currency_decimal_places' => $budgeted['currency_decimal_places']
+                ];
                 $sums['budgeted'][$currencyId]['amount'] = bcadd($sums['budgeted'][$currencyId]['amount'], (string) $budgeted['amount']);
 
                 // also calculate how much left from budgeted:
-                $sums['left'][$currencyId]
-                                                         ??= [
-                                                             'amount'                  => '0',
-                                                             'currency_id'             => $budgeted['currency_id'],
-                                                             'currency_symbol'         => $budgeted['currency_symbol'],
-                                                             'currency_decimal_places' => $budgeted['currency_decimal_places'],
-                                                         ];
+                $sums['left'][$currencyId] ??= [
+                    'amount'                  => '0',
+                    'currency_id'             => $budgeted['currency_id'],
+                    'currency_symbol'         => $budgeted['currency_symbol'],
+                    'currency_decimal_places' => $budgeted['currency_decimal_places']
+                ];
             }
         }
 
@@ -292,8 +298,8 @@ class IndexController extends Controller
          * @var int $currencyId
          */
         foreach (array_keys($sums['budgeted']) as $currencyId) {
-            $spent                               = $sums['spent'][$currencyId]['amount'] ?? '0';
-            $budgeted                            = $sums['budgeted'][$currencyId]['amount'] ?? '0';
+            $spent    = $sums['spent'][$currencyId]['amount'] ?? '0';
+            $budgeted = $sums['budgeted'][$currencyId]['amount'] ?? '0';
             $sums['left'][$currencyId]['amount'] = bcadd($spent, $budgeted);
         }
 
diff --git a/app/Http/Controllers/Budget/ShowController.php b/app/Http/Controllers/Budget/ShowController.php
index 9325032225..13a65c6c53 100644
--- a/app/Http/Controllers/Budget/ShowController.php
+++ b/app/Http/Controllers/Budget/ShowController.php
@@ -24,7 +24,6 @@ declare(strict_types=1);
 
 namespace FireflyIII\Http\Controllers\Budget;
 
-use FireflyIII\Support\Facades\Preferences;
 use Carbon\Carbon;
 use FireflyIII\Enums\TransactionTypeEnum;
 use FireflyIII\Exceptions\FireflyException;
@@ -35,6 +34,7 @@ use FireflyIII\Models\BudgetLimit;
 use FireflyIII\Models\TransactionJournal;
 use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
 use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
+use FireflyIII\Support\Facades\Preferences;
 use FireflyIII\Support\Http\Controllers\AugumentData;
 use FireflyIII\Support\Http\Controllers\PeriodOverview;
 use Illuminate\Contracts\View\Factory;
@@ -52,7 +52,7 @@ class ShowController extends Controller
     use PeriodOverview;
 
     protected JournalRepositoryInterface $journalRepos;
-    private BudgetRepositoryInterface    $repository;
+    private BudgetRepositoryInterface $repository;
 
     /**
      * ShowController constructor.
@@ -61,16 +61,14 @@ class ShowController extends Controller
     {
         app('view')->share('showCategory', true);
         parent::__construct();
-        $this->middleware(
-            function ($request, $next) {
-                app('view')->share('title', (string) trans('firefly.budgets'));
-                app('view')->share('mainTitleIcon', 'fa-pie-chart');
-                $this->journalRepos = app(JournalRepositoryInterface::class);
-                $this->repository   = app(BudgetRepositoryInterface::class);
+        $this->middleware(function ($request, $next) {
+            app('view')->share('title', (string) trans('firefly.budgets'));
+            app('view')->share('mainTitleIcon', 'fa-pie-chart');
+            $this->journalRepos = app(JournalRepositoryInterface::class);
+            $this->repository = app(BudgetRepositoryInterface::class);
 
-                return $next($request);
-            }
-        );
+            return $next($request);
+        });
     }
 
     /**
@@ -82,17 +80,17 @@ class ShowController extends Controller
      * @throws FireflyException
      * @throws NotFoundExceptionInterface
      */
-    public function noBudget(Request $request, ?Carbon $start = null, ?Carbon $end = null): Factory|\Illuminate\Contracts\View\View
+    public function noBudget(Request $request, null|Carbon $start = null, null|Carbon $end = null): Factory|\Illuminate\Contracts\View\View
     {
         $start ??= session('start');
         $end   ??= session('end');
 
         /** @var Carbon $start */
         /** @var Carbon $end */
-        $subTitle  = trans(
-            'firefly.without_budget_between',
-            ['start' => $start->isoFormat($this->monthAndDayFormat), 'end' => $end->isoFormat($this->monthAndDayFormat)]
-        );
+        $subTitle = trans('firefly.without_budget_between', [
+            'start' => $start->isoFormat($this->monthAndDayFormat),
+            'end'   => $end->isoFormat($this->monthAndDayFormat)
+        ]);
 
         // get first journal ever to set off the budget period overview.
         $first     = $this->journalRepos->firstNull();
@@ -103,13 +101,18 @@ class ShowController extends Controller
 
         /** @var GroupCollectorInterface $collector */
         $collector = app(GroupCollectorInterface::class);
-        $collector->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value])->setLimit($pageSize)->setPage($page)
-            ->withoutBudget()->withAccountInformation()->withCategoryInformation()
-        ;
-        $groups    = $collector->getPaginatedGroups();
+        $collector
+            ->setRange($start, $end)
+            ->setTypes([TransactionTypeEnum::WITHDRAWAL->value])
+            ->setLimit($pageSize)
+            ->setPage($page)
+            ->withoutBudget()
+            ->withAccountInformation()
+            ->withCategoryInformation();
+        $groups = $collector->getPaginatedGroups();
         $groups->setPath(route('budgets.no-budget'));
 
-        return view('budgets.no-budget', ['groups' => $groups, 'subTitle' => $subTitle, 'periods' => $periods, 'start' => $start, 'end' => $end]);
+        return view('budgets.no-budget', ['groups'   => $groups, 'subTitle' => $subTitle, 'periods'  => $periods, 'start'    => $start, 'end'      => $end]);
     }
 
     /**
@@ -122,22 +125,27 @@ class ShowController extends Controller
      */
     public function noBudgetAll(Request $request): Factory|\Illuminate\Contracts\View\View
     {
-        $subTitle  = (string) trans('firefly.all_journals_without_budget');
-        $first     = $this->journalRepos->firstNull();
-        $start     = $first instanceof TransactionJournal ? $first->date : new Carbon();
-        $end       = today(config('app.timezone'));
-        $page      = (int) $request->get('page');
-        $pageSize  = (int) Preferences::get('listPageSize', 50)->data;
+        $subTitle = (string) trans('firefly.all_journals_without_budget');
+        $first    = $this->journalRepos->firstNull();
+        $start    = $first instanceof TransactionJournal ? $first->date : new Carbon();
+        $end      = today(config('app.timezone'));
+        $page     = (int) $request->get('page');
+        $pageSize = (int) Preferences::get('listPageSize', 50)->data;
 
         /** @var GroupCollectorInterface $collector */
         $collector = app(GroupCollectorInterface::class);
-        $collector->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value])->setLimit($pageSize)->setPage($page)
-            ->withoutBudget()->withAccountInformation()->withCategoryInformation()
-        ;
-        $groups    = $collector->getPaginatedGroups();
+        $collector
+            ->setRange($start, $end)
+            ->setTypes([TransactionTypeEnum::WITHDRAWAL->value])
+            ->setLimit($pageSize)
+            ->setPage($page)
+            ->withoutBudget()
+            ->withAccountInformation()
+            ->withCategoryInformation();
+        $groups = $collector->getPaginatedGroups();
         $groups->setPath(route('budgets.no-budget-all'));
 
-        return view('budgets.no-budget', ['groups' => $groups, 'subTitle' => $subTitle, 'start' => $start, 'end' => $end]);
+        return view('budgets.no-budget', ['groups'   => $groups, 'subTitle' => $subTitle, 'start'    => $start, 'end'      => $end]);
     }
 
     /**
@@ -161,17 +169,28 @@ class ShowController extends Controller
 
         // collector:
         /** @var GroupCollectorInterface $collector */
-        $collector   = app(GroupCollectorInterface::class);
-        $collector->setRange($allStart, $allEnd)->setBudget($budget)
+        $collector = app(GroupCollectorInterface::class);
+        $collector
+            ->setRange($allStart, $allEnd)
+            ->setBudget($budget)
             ->withAccountInformation()
-            ->setLimit($pageSize)->setPage($page)->withBudgetInformation()->withCategoryInformation()
-        ;
-        $groups      = $collector->getPaginatedGroups();
+            ->setLimit($pageSize)
+            ->setPage($page)
+            ->withBudgetInformation()
+            ->withCategoryInformation();
+        $groups = $collector->getPaginatedGroups();
         $groups->setPath(route('budgets.show', [$budget->id]));
 
-        $subTitle    = (string) trans('firefly.all_journals_for_budget', ['name' => $budget->name]);
+        $subTitle = (string) trans('firefly.all_journals_for_budget', ['name' => $budget->name]);
 
-        return view('budgets.show', ['limits' => $limits, 'attachments' => $attachments, 'budget' => $budget, 'repetition' => $repetition, 'groups' => $groups, 'subTitle' => $subTitle]);
+        return view('budgets.show', [
+            'limits'      => $limits,
+            'attachments' => $attachments,
+            'budget'      => $budget,
+            'repetition'  => $repetition,
+            'groups'      => $groups,
+            'subTitle'    => $subTitle
+        ]);
     }
 
     /**
@@ -192,35 +211,45 @@ class ShowController extends Controller
         $currencySymbol = $budgetLimit->transactionCurrency->symbol;
         $page           = (int) $request->get('page');
         $pageSize       = (int) Preferences::get('listPageSize', 50)->data;
-        $subTitle       = trans(
-            'firefly.budget_in_period',
-            [
-                'name'     => $budget->name,
-                'start'    => $budgetLimit->start_date->isoFormat($this->monthAndDayFormat),
-                'end'      => $budgetLimit->end_date->isoFormat($this->monthAndDayFormat),
-                'currency' => $budgetLimit->transactionCurrency->name,
-            ]
-        );
+        $subTitle       = trans('firefly.budget_in_period', [
+            'name'     => $budget->name,
+            'start'    => $budgetLimit->start_date->isoFormat($this->monthAndDayFormat),
+            'end'      => $budgetLimit->end_date->isoFormat($this->monthAndDayFormat),
+            'currency' => $budgetLimit->transactionCurrency->name
+        ]);
         if ($this->convertToPrimary) {
             $currencySymbol = $this->primaryCurrency->symbol;
         }
 
         // collector:
         /** @var GroupCollectorInterface $collector */
-        $collector      = app(GroupCollectorInterface::class);
+        $collector = app(GroupCollectorInterface::class);
 
-        $collector->setRange($budgetLimit->start_date, $budgetLimit->end_date)->withAccountInformation()
-            ->setBudget($budget)->setLimit($pageSize)->setPage($page)->withBudgetInformation()->withCategoryInformation()
-        ;
-        $groups         = $collector->getPaginatedGroups();
+        $collector
+            ->setRange($budgetLimit->start_date, $budgetLimit->end_date)
+            ->withAccountInformation()
+            ->setBudget($budget)
+            ->setLimit($pageSize)
+            ->setPage($page)
+            ->withBudgetInformation()
+            ->withCategoryInformation();
+        $groups = $collector->getPaginatedGroups();
         $groups->setPath(route('budgets.show.limit', [$budget->id, $budgetLimit->id]));
 
         /** @var Carbon $start */
-        $start          = session('first', today(config('app.timezone'))->startOfYear());
-        $end            = today(config('app.timezone'));
-        $attachments    = $this->repository->getAttachments($budget);
-        $limits         = $this->getLimits($budget, $start, $end);
+        $start       = session('first', today(config('app.timezone'))->startOfYear());
+        $end         = today(config('app.timezone'));
+        $attachments = $this->repository->getAttachments($budget);
+        $limits      = $this->getLimits($budget, $start, $end);
 
-        return view('budgets.show', ['limits' => $limits, 'attachments' => $attachments, 'budget' => $budget, 'budgetLimit' => $budgetLimit, 'groups' => $groups, 'subTitle' => $subTitle, 'currencySymbol' => $currencySymbol]);
+        return view('budgets.show', [
+            'limits'         => $limits,
+            'attachments'    => $attachments,
+            'budget'         => $budget,
+            'budgetLimit'    => $budgetLimit,
+            'groups'         => $groups,
+            'subTitle'       => $subTitle,
+            'currencySymbol' => $currencySymbol
+        ]);
     }
 }
diff --git a/app/Http/Controllers/Category/CreateController.php b/app/Http/Controllers/Category/CreateController.php
index 043cc17ea6..adbfcba7c8 100644
--- a/app/Http/Controllers/Category/CreateController.php
+++ b/app/Http/Controllers/Category/CreateController.php
@@ -24,12 +24,12 @@ declare(strict_types=1);
 
 namespace FireflyIII\Http\Controllers\Category;
 
-use FireflyIII\Support\Facades\Preferences;
 use FireflyIII\Exceptions\FireflyException;
 use FireflyIII\Helpers\Attachments\AttachmentHelperInterface;
 use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\Http\Requests\CategoryFormRequest;
 use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
+use FireflyIII\Support\Facades\Preferences;
 use Illuminate\Contracts\View\Factory;
 use Illuminate\Http\RedirectResponse;
 use Illuminate\Http\Request;
@@ -42,7 +42,7 @@ use Illuminate\View\View;
  */
 class CreateController extends Controller
 {
-    private AttachmentHelperInterface   $attachments;
+    private AttachmentHelperInterface $attachments;
     private CategoryRepositoryInterface $repository;
 
     /**
@@ -52,16 +52,14 @@ class CreateController extends Controller
     {
         parent::__construct();
 
-        $this->middleware(
-            function ($request, $next) {
-                app('view')->share('title', (string) trans('firefly.categories'));
-                app('view')->share('mainTitleIcon', 'fa-bookmark');
-                $this->repository  = app(CategoryRepositoryInterface::class);
-                $this->attachments = app(AttachmentHelperInterface::class);
+        $this->middleware(function ($request, $next) {
+            app('view')->share('title', (string) trans('firefly.categories'));
+            app('view')->share('mainTitleIcon', 'fa-bookmark');
+            $this->repository = app(CategoryRepositoryInterface::class);
+            $this->attachments = app(AttachmentHelperInterface::class);
 
-                return $next($request);
-            }
-        );
+            return $next($request);
+        });
     }
 
     /**
@@ -97,7 +95,7 @@ class CreateController extends Controller
 
         // store attachment(s):
         /** @var null|array $files */
-        $files    = $request->hasFile('attachments') ? $request->file('attachments') : null;
+        $files = $request->hasFile('attachments') ? $request->file('attachments') : null;
         if (null !== $files && !auth()->user()->hasRole('demo')) {
             $this->attachments->saveAttachmentsForModel($category, $files);
         }
diff --git a/app/Http/Controllers/Category/DeleteController.php b/app/Http/Controllers/Category/DeleteController.php
index d2e106a192..998a0fb36e 100644
--- a/app/Http/Controllers/Category/DeleteController.php
+++ b/app/Http/Controllers/Category/DeleteController.php
@@ -24,10 +24,10 @@ declare(strict_types=1);
 
 namespace FireflyIII\Http\Controllers\Category;
 
-use FireflyIII\Support\Facades\Preferences;
 use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\Models\Category;
 use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
+use FireflyIII\Support\Facades\Preferences;
 use Illuminate\Contracts\View\Factory;
 use Illuminate\Http\RedirectResponse;
 use Illuminate\Http\Request;
@@ -49,15 +49,13 @@ class DeleteController extends Controller
     {
         parent::__construct();
 
-        $this->middleware(
-            function ($request, $next) {
-                app('view')->share('title', (string) trans('firefly.categories'));
-                app('view')->share('mainTitleIcon', 'fa-bookmark');
-                $this->repository = app(CategoryRepositoryInterface::class);
+        $this->middleware(function ($request, $next) {
+            app('view')->share('title', (string) trans('firefly.categories'));
+            app('view')->share('mainTitleIcon', 'fa-bookmark');
+            $this->repository = app(CategoryRepositoryInterface::class);
 
-                return $next($request);
-            }
-        );
+            return $next($request);
+        });
     }
 
     /**
diff --git a/app/Http/Controllers/Category/EditController.php b/app/Http/Controllers/Category/EditController.php
index 2e02d8fcaa..4d8aefc958 100644
--- a/app/Http/Controllers/Category/EditController.php
+++ b/app/Http/Controllers/Category/EditController.php
@@ -24,12 +24,12 @@ declare(strict_types=1);
 
 namespace FireflyIII\Http\Controllers\Category;
 
-use FireflyIII\Support\Facades\Preferences;
 use FireflyIII\Helpers\Attachments\AttachmentHelperInterface;
 use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\Http\Requests\CategoryFormRequest;
 use FireflyIII\Models\Category;
 use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
+use FireflyIII\Support\Facades\Preferences;
 use Illuminate\Contracts\View\Factory;
 use Illuminate\Http\RedirectResponse;
 use Illuminate\Http\Request;
@@ -42,7 +42,7 @@ use Illuminate\View\View;
  */
 class EditController extends Controller
 {
-    private AttachmentHelperInterface   $attachments;
+    private AttachmentHelperInterface $attachments;
     private CategoryRepositoryInterface $repository;
 
     /**
@@ -52,16 +52,14 @@ class EditController extends Controller
     {
         parent::__construct();
 
-        $this->middleware(
-            function ($request, $next) {
-                app('view')->share('title', (string) trans('firefly.categories'));
-                app('view')->share('mainTitleIcon', 'fa-bookmark');
-                $this->repository  = app(CategoryRepositoryInterface::class);
-                $this->attachments = app(AttachmentHelperInterface::class);
+        $this->middleware(function ($request, $next) {
+            app('view')->share('title', (string) trans('firefly.categories'));
+            app('view')->share('mainTitleIcon', 'fa-bookmark');
+            $this->repository = app(CategoryRepositoryInterface::class);
+            $this->attachments = app(AttachmentHelperInterface::class);
 
-                return $next($request);
-            }
-        );
+            return $next($request);
+        });
     }
 
     /**
@@ -71,7 +69,7 @@ class EditController extends Controller
      */
     public function edit(Request $request, Category $category): Factory|\Illuminate\Contracts\View\View
     {
-        $subTitle  = (string) trans('firefly.edit_category', ['name' => $category->name]);
+        $subTitle = (string) trans('firefly.edit_category', ['name' => $category->name]);
 
         // put previous url in session if not redirect from store (not "return_to_edit").
         if (true !== session('categories.edit.fromUpdate')) {
@@ -79,11 +77,9 @@ class EditController extends Controller
         }
         $request->session()->forget('categories.edit.fromUpdate');
 
-        $preFilled = [
-            'notes' => $request->old('notes') ?? $this->repository->getNoteText($category),
-        ];
+        $preFilled = ['notes' => $request->old('notes') ?? $this->repository->getNoteText($category)];
 
-        return view('categories.edit', ['category' => $category, 'subTitle' => $subTitle, 'preFilled' => $preFilled]);
+        return view('categories.edit', ['category'  => $category, 'subTitle'  => $subTitle, 'preFilled' => $preFilled]);
     }
 
     /**
@@ -91,7 +87,7 @@ class EditController extends Controller
      */
     public function update(CategoryFormRequest $request, Category $category): Redirector|RedirectResponse
     {
-        $data     = $request->getCategoryData();
+        $data = $request->getCategoryData();
         $this->repository->update($category, $data);
 
         $request->session()->flash('success', (string) trans('firefly.updated_category', ['name' => $category->name]));
@@ -99,7 +95,7 @@ class EditController extends Controller
 
         // store new attachment(s):
         /** @var null|array $files */
-        $files    = $request->hasFile('attachments') ? $request->file('attachments') : null;
+        $files = $request->hasFile('attachments') ? $request->file('attachments') : null;
         if (null !== $files && !auth()->user()->hasRole('demo')) {
             $this->attachments->saveAttachmentsForModel($category, $files);
         }
diff --git a/app/Http/Controllers/Category/IndexController.php b/app/Http/Controllers/Category/IndexController.php
index e7cfd7816e..a4e2af50db 100644
--- a/app/Http/Controllers/Category/IndexController.php
+++ b/app/Http/Controllers/Category/IndexController.php
@@ -24,10 +24,10 @@ declare(strict_types=1);
 
 namespace FireflyIII\Http\Controllers\Category;
 
-use FireflyIII\Support\Facades\Preferences;
 use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\Models\Category;
 use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
+use FireflyIII\Support\Facades\Preferences;
 use Illuminate\Contracts\View\Factory;
 use Illuminate\Http\Request;
 use Illuminate\Pagination\LengthAwarePaginator;
@@ -51,15 +51,13 @@ class IndexController extends Controller
     {
         parent::__construct();
 
-        $this->middleware(
-            function ($request, $next) {
-                app('view')->share('title', (string) trans('firefly.categories'));
-                app('view')->share('mainTitleIcon', 'fa-bookmark');
-                $this->repository = app(CategoryRepositoryInterface::class);
+        $this->middleware(function ($request, $next) {
+            app('view')->share('title', (string) trans('firefly.categories'));
+            app('view')->share('mainTitleIcon', 'fa-bookmark');
+            $this->repository = app(CategoryRepositoryInterface::class);
 
-                return $next($request);
-            }
-        );
+            return $next($request);
+        });
     }
 
     /**
@@ -78,11 +76,9 @@ class IndexController extends Controller
         $total      = $collection->count();
         $collection = $collection->slice(($page - 1) * $pageSize, $pageSize);
 
-        $collection->each(
-            function (Category $category): void {
-                $category->lastActivity = $this->repository->lastUseDate($category, new Collection());
-            }
-        );
+        $collection->each(function (Category $category): void {
+            $category->lastActivity = $this->repository->lastUseDate($category, new Collection());
+        });
 
         // paginate categories
         $categories = new LengthAwarePaginator($collection, $total, $pageSize, $page);
diff --git a/app/Http/Controllers/Category/NoCategoryController.php b/app/Http/Controllers/Category/NoCategoryController.php
index fa03c70f08..6e26658377 100644
--- a/app/Http/Controllers/Category/NoCategoryController.php
+++ b/app/Http/Controllers/Category/NoCategoryController.php
@@ -24,7 +24,6 @@ declare(strict_types=1);
 
 namespace FireflyIII\Http\Controllers\Category;
 
-use FireflyIII\Support\Facades\Preferences;
 use Carbon\Carbon;
 use FireflyIII\Enums\TransactionTypeEnum;
 use FireflyIII\Exceptions\FireflyException;
@@ -32,6 +31,7 @@ use FireflyIII\Helpers\Collector\GroupCollectorInterface;
 use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\Models\TransactionJournal;
 use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
+use FireflyIII\Support\Facades\Preferences;
 use FireflyIII\Support\Http\Controllers\PeriodOverview;
 use Illuminate\Contracts\View\Factory;
 use Illuminate\Http\Request;
@@ -58,15 +58,13 @@ class NoCategoryController extends Controller
         parent::__construct();
         app('view')->share('showBudget', true);
 
-        $this->middleware(
-            function ($request, $next) {
-                app('view')->share('title', (string) trans('firefly.categories'));
-                app('view')->share('mainTitleIcon', 'fa-bookmark');
-                $this->journalRepos = app(JournalRepositoryInterface::class);
+        $this->middleware(function ($request, $next) {
+            app('view')->share('title', (string) trans('firefly.categories'));
+            app('view')->share('mainTitleIcon', 'fa-bookmark');
+            $this->journalRepos = app(JournalRepositoryInterface::class);
 
-                return $next($request);
-            }
-        );
+            return $next($request);
+        });
     }
 
     /**
@@ -78,7 +76,7 @@ class NoCategoryController extends Controller
      * @throws FireflyException
      * @throws NotFoundExceptionInterface
      */
-    public function show(Request $request, ?Carbon $start = null, ?Carbon $end = null): Factory|\Illuminate\Contracts\View\View
+    public function show(Request $request, null|Carbon $start = null, null|Carbon $end = null): Factory|\Illuminate\Contracts\View\View
     {
         Log::debug('Start of noCategory()');
         $start ??= session('start');
@@ -86,26 +84,38 @@ class NoCategoryController extends Controller
 
         /** @var Carbon $start */
         /** @var Carbon $end */
-        $page      = (int) $request->get('page');
-        $pageSize  = (int) Preferences::get('listPageSize', 50)->data;
-        $subTitle  = trans('firefly.without_category_between', ['start' => $start->isoFormat($this->monthAndDayFormat), 'end' => $end->isoFormat($this->monthAndDayFormat)]);
-        $first     = $this->journalRepos->firstNull()->date ?? clone $start;
-        $periods   = $this->getNoModelPeriodOverview('category', $first, $end);
+        $page     = (int) $request->get('page');
+        $pageSize = (int) Preferences::get('listPageSize', 50)->data;
+        $subTitle = trans('firefly.without_category_between', [
+            'start' => $start->isoFormat($this->monthAndDayFormat),
+            'end'   => $end->isoFormat($this->monthAndDayFormat)
+        ]);
+        $first    = $this->journalRepos->firstNull()->date ?? clone $start;
+        $periods  = $this->getNoModelPeriodOverview('category', $first, $end);
 
         Log::debug(sprintf('Start for noCategory() is %s', $start->format('Y-m-d')));
         Log::debug(sprintf('End for noCategory() is %s', $end->format('Y-m-d')));
 
         /** @var GroupCollectorInterface $collector */
         $collector = app(GroupCollectorInterface::class);
-        $collector->setRange($start, $end)
-            ->setLimit($pageSize)->setPage($page)->withoutCategory()
-            ->withAccountInformation()->withBudgetInformation()
-            ->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value])
-        ;
-        $groups    = $collector->getPaginatedGroups();
+        $collector
+            ->setRange($start, $end)
+            ->setLimit($pageSize)
+            ->setPage($page)
+            ->withoutCategory()
+            ->withAccountInformation()
+            ->withBudgetInformation()
+            ->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value]);
+        $groups = $collector->getPaginatedGroups();
         $groups->setPath(route('categories.no-category', [$start->format('Y-m-d'), $end->format('Y-m-d')]));
 
-        return view('categories.no-category', ['groups' => $groups, 'subTitle' => $subTitle, 'periods' => $periods, 'start' => $start, 'end' => $end]);
+        return view('categories.no-category', [
+            'groups'   => $groups,
+            'subTitle' => $subTitle,
+            'periods'  => $periods,
+            'start'    => $start,
+            'end'      => $end
+        ]);
     }
 
     /**
@@ -119,28 +129,38 @@ class NoCategoryController extends Controller
     public function showAll(Request $request): Factory|\Illuminate\Contracts\View\View
     {
         // default values:
-        $start     = null;
-        $end       = null;
-        $periods   = new Collection();
-        $page      = (int) $request->get('page');
-        $pageSize  = (int) Preferences::get('listPageSize', 50)->data;
+        $start    = null;
+        $end      = null;
+        $periods  = new Collection();
+        $page     = (int) $request->get('page');
+        $pageSize = (int) Preferences::get('listPageSize', 50)->data;
         Log::debug('Start of noCategory()');
-        $subTitle  = (string) trans('firefly.all_journals_without_category');
-        $first     = $this->journalRepos->firstNull();
-        $start     = $first instanceof TransactionJournal ? $first->date : new Carbon();
-        $end       = today(config('app.timezone'));
+        $subTitle = (string) trans('firefly.all_journals_without_category');
+        $first    = $this->journalRepos->firstNull();
+        $start    = $first instanceof TransactionJournal ? $first->date : new Carbon();
+        $end      = today(config('app.timezone'));
         Log::debug(sprintf('Start for noCategory() is %s', $start->format('Y-m-d')));
         Log::debug(sprintf('End for noCategory() is %s', $end->format('Y-m-d')));
 
         /** @var GroupCollectorInterface $collector */
         $collector = app(GroupCollectorInterface::class);
-        $collector->setRange($start, $end)->setLimit($pageSize)->setPage($page)->withoutCategory()
-            ->withAccountInformation()->withBudgetInformation()
-            ->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value])
-        ;
-        $groups    = $collector->getPaginatedGroups();
+        $collector
+            ->setRange($start, $end)
+            ->setLimit($pageSize)
+            ->setPage($page)
+            ->withoutCategory()
+            ->withAccountInformation()
+            ->withBudgetInformation()
+            ->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value]);
+        $groups = $collector->getPaginatedGroups();
         $groups->setPath(route('categories.no-category.all'));
 
-        return view('categories.no-category', ['groups' => $groups, 'subTitle' => $subTitle, 'periods' => $periods, 'start' => $start, 'end' => $end]);
+        return view('categories.no-category', [
+            'groups'   => $groups,
+            'subTitle' => $subTitle,
+            'periods'  => $periods,
+            'start'    => $start,
+            'end'      => $end
+        ]);
     }
 }
diff --git a/app/Http/Controllers/Category/ShowController.php b/app/Http/Controllers/Category/ShowController.php
index 1df3544c91..86665e69a1 100644
--- a/app/Http/Controllers/Category/ShowController.php
+++ b/app/Http/Controllers/Category/ShowController.php
@@ -24,13 +24,13 @@ declare(strict_types=1);
 
 namespace FireflyIII\Http\Controllers\Category;
 
-use FireflyIII\Support\Facades\Preferences;
 use Carbon\Carbon;
 use FireflyIII\Exceptions\FireflyException;
 use FireflyIII\Helpers\Collector\GroupCollectorInterface;
 use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\Models\Category;
 use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
+use FireflyIII\Support\Facades\Preferences;
 use FireflyIII\Support\Http\Controllers\PeriodOverview;
 use Illuminate\Contracts\View\Factory;
 use Illuminate\Http\Request;
@@ -57,15 +57,13 @@ class ShowController extends Controller
         parent::__construct();
         app('view')->share('showBudget', true);
 
-        $this->middleware(
-            function ($request, $next) {
-                app('view')->share('title', (string) trans('firefly.categories'));
-                app('view')->share('mainTitleIcon', 'fa-bookmark');
-                $this->repository = app(CategoryRepositoryInterface::class);
+        $this->middleware(function ($request, $next) {
+            app('view')->share('title', (string) trans('firefly.categories'));
+            app('view')->share('mainTitleIcon', 'fa-bookmark');
+            $this->repository = app(CategoryRepositoryInterface::class);
 
-                return $next($request);
-            }
-        );
+            return $next($request);
+        });
     }
 
     /**
@@ -77,7 +75,7 @@ class ShowController extends Controller
      * @throws FireflyException
      * @throws NotFoundExceptionInterface
      */
-    public function show(Request $request, Category $category, ?Carbon $start = null, ?Carbon $end = null): Factory|\Illuminate\Contracts\View\View
+    public function show(Request $request, Category $category, null|Carbon $start = null, null|Carbon $end = null): Factory|\Illuminate\Contracts\View\View
     {
         $start ??= session('start', today(config('app.timezone'))->startOfMonth());
         $end   ??= session('end', today(config('app.timezone'))->endOfMonth());
@@ -91,26 +89,36 @@ class ShowController extends Controller
         $oldest       = $this->repository->firstUseDate($category) ?? today(config('app.timezone'))->startOfYear();
         $periods      = $this->getCategoryPeriodOverview($category, $oldest, $end);
         $path         = route('categories.show', [$category->id, $start->format('Y-m-d'), $end->format('Y-m-d')]);
-        $subTitle     = trans(
-            'firefly.journals_in_period_for_category',
-            [
-                'name'  => $category->name,
-                'start' => $start->isoFormat($this->monthAndDayFormat),
-                'end'   => $end->isoFormat($this->monthAndDayFormat),
-            ]
-        );
+        $subTitle     = trans('firefly.journals_in_period_for_category', [
+            'name'  => $category->name,
+            'start' => $start->isoFormat($this->monthAndDayFormat),
+            'end'   => $end->isoFormat($this->monthAndDayFormat)
+        ]);
 
         /** @var GroupCollectorInterface $collector */
-        $collector    = app(GroupCollectorInterface::class);
-        $collector->setRange($start, $end)->setLimit($pageSize)->setPage($page)
+        $collector = app(GroupCollectorInterface::class);
+        $collector
+            ->setRange($start, $end)
+            ->setLimit($pageSize)
+            ->setPage($page)
             ->withAccountInformation()
-            ->setCategory($category)->withBudgetInformation()->withCategoryInformation()
-        ;
+            ->setCategory($category)
+            ->withBudgetInformation()
+            ->withCategoryInformation();
 
-        $groups       = $collector->getPaginatedGroups();
+        $groups = $collector->getPaginatedGroups();
         $groups->setPath($path);
 
-        return view('categories.show', ['category' => $category, 'attachments' => $attachments, 'groups' => $groups, 'periods' => $periods, 'subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'start' => $start, 'end' => $end]);
+        return view('categories.show', [
+            'category'     => $category,
+            'attachments'  => $attachments,
+            'groups'       => $groups,
+            'periods'      => $periods,
+            'subTitle'     => $subTitle,
+            'subTitleIcon' => $subTitleIcon,
+            'start'        => $start,
+            'end'          => $end
+        ]);
     }
 
     /**
@@ -131,25 +139,38 @@ class ShowController extends Controller
         $end          = null;
         $periods      = new Collection();
 
-        $subTitle     = (string) trans('firefly.all_journals_for_category', ['name' => $category->name]);
-        $first        = $this->repository->firstUseDate($category);
+        $subTitle = (string) trans('firefly.all_journals_for_category', ['name' => $category->name]);
+        $first    = $this->repository->firstUseDate($category);
 
         /** @var Carbon $start */
-        $start        = $first ?? today(config('app.timezone'));
-        $end          = today(config('app.timezone'));
-        $path         = route('categories.show.all', [$category->id]);
-        $attachments  = $this->repository->getAttachments($category);
+        $start       = $first ?? today(config('app.timezone'));
+        $end         = today(config('app.timezone'));
+        $path        = route('categories.show.all', [$category->id]);
+        $attachments = $this->repository->getAttachments($category);
 
         /** @var GroupCollectorInterface $collector */
-        $collector    = app(GroupCollectorInterface::class);
-        $collector->setRange($start, $end)->setLimit($pageSize)->setPage($page)
+        $collector = app(GroupCollectorInterface::class);
+        $collector
+            ->setRange($start, $end)
+            ->setLimit($pageSize)
+            ->setPage($page)
             ->withAccountInformation()
-            ->setCategory($category)->withBudgetInformation()->withCategoryInformation()
-        ;
+            ->setCategory($category)
+            ->withBudgetInformation()
+            ->withCategoryInformation();
 
-        $groups       = $collector->getPaginatedGroups();
+        $groups = $collector->getPaginatedGroups();
         $groups->setPath($path);
 
-        return view('categories.show', ['category' => $category, 'attachments' => $attachments, 'groups' => $groups, 'periods' => $periods, 'subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'start' => $start, 'end' => $end]);
+        return view('categories.show', [
+            'category'     => $category,
+            'attachments'  => $attachments,
+            'groups'       => $groups,
+            'periods'      => $periods,
+            'subTitle'     => $subTitle,
+            'subTitleIcon' => $subTitleIcon,
+            'start'        => $start,
+            'end'          => $end
+        ]);
     }
 }
diff --git a/app/Http/Controllers/Chart/AccountController.php b/app/Http/Controllers/Chart/AccountController.php
index 70aac51d3a..7e642bdf5a 100644
--- a/app/Http/Controllers/Chart/AccountController.php
+++ b/app/Http/Controllers/Chart/AccountController.php
@@ -23,7 +23,6 @@ declare(strict_types=1);
 
 namespace FireflyIII\Http\Controllers\Chart;
 
-use FireflyIII\Support\Facades\Navigation;
 use Carbon\Carbon;
 use FireflyIII\Enums\AccountTypeEnum;
 use FireflyIII\Enums\TransactionTypeEnum;
@@ -36,6 +35,7 @@ use FireflyIII\Models\TransactionCurrency;
 use FireflyIII\Repositories\Account\AccountRepositoryInterface;
 use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
 use FireflyIII\Support\CacheProperties;
+use FireflyIII\Support\Facades\Navigation;
 use FireflyIII\Support\Facades\Preferences;
 use FireflyIII\Support\Facades\Steam;
 use FireflyIII\Support\Http\Api\ExchangeRateConverter;
@@ -58,8 +58,8 @@ class AccountController extends Controller
     use ChartGeneration;
     use DateCalculation;
 
-    protected GeneratorInterface        $generator;
-    private AccountRepositoryInterface  $accountRepository;
+    protected GeneratorInterface $generator;
+    private AccountRepositoryInterface $accountRepository;
     private CurrencyRepositoryInterface $currencyRepository;
 
     /**
@@ -69,15 +69,13 @@ class AccountController extends Controller
     {
         parent::__construct();
 
-        $this->middleware(
-            function ($request, $next) {
-                $this->generator          = app(GeneratorInterface::class);
-                $this->accountRepository  = app(AccountRepositoryInterface::class);
-                $this->currencyRepository = app(CurrencyRepositoryInterface::class);
+        $this->middleware(function ($request, $next) {
+            $this->generator = app(GeneratorInterface::class);
+            $this->accountRepository = app(AccountRepositoryInterface::class);
+            $this->currencyRepository = app(CurrencyRepositoryInterface::class);
 
-                return $next($request);
-            }
-        );
+            return $next($request);
+        });
     }
 
     /**
@@ -91,14 +89,14 @@ class AccountController extends Controller
         Log::debug('ExpenseAccounts');
 
         /** @var Carbon $start */
-        $start         = clone session('start', today(config('app.timezone'))->startOfMonth());
+        $start = clone session('start', today(config('app.timezone'))->startOfMonth());
 
         /** @var Carbon $end */
-        $end           = clone session('end', today(config('app.timezone'))->endOfMonth());
+        $end = clone session('end', today(config('app.timezone'))->endOfMonth());
         $start->startOfDay();
         $end->endOfDay();
 
-        $cache         = new CacheProperties();
+        $cache = new CacheProperties();
         $cache->addProperty($start);
         $cache->addProperty($end);
         $cache->addProperty($this->convertToPrimary);
@@ -108,20 +106,17 @@ class AccountController extends Controller
         }
 
         // prep some vars:
-        $currencies    = [];
-        $chartData     = [];
-        $tempData      = [];
+        $currencies = [];
+        $chartData  = [];
+        $tempData   = [];
 
         // grab all accounts and names
-        $accounts      = $this->accountRepository->getAccountsByType([AccountTypeEnum::EXPENSE->value]);
-        $accountNames  = $this->extractNames($accounts);
+        $accounts     = $this->accountRepository->getAccountsByType([AccountTypeEnum::EXPENSE->value]);
+        $accountNames = $this->extractNames($accounts);
 
         // grab all balances
         Log::debug(sprintf('expenseAccounts: accountsBalancesInRange("%s", "%s")', $start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s')));
-        [
-            $startBalances,
-            $endBalances,
-        ]              = Steam::accountsBalancesInRange($accounts, $start, $end, $this->primaryCurrency, $this->convertToPrimary);
+        [$startBalances, $endBalances] = Steam::accountsBalancesInRange($accounts, $start, $end, $this->primaryCurrency, $this->convertToPrimary);
         Log::debug('Done collecting balances');
         // loop the accounts, then check for balance and currency info.
         foreach ($accounts as $account) {
@@ -149,22 +144,22 @@ class AccountController extends Controller
                     continue;
                 }
                 // Log::debug(sprintf('Will process expense array "%s" with amount %s', $key, $endBalance));
-                $searchCode   = $this->convertToPrimary ? $this->primaryCurrency->code : $key;
-                $searchCode   = 'balance' === $searchCode || 'pc_balance' === $searchCode ? $this->primaryCurrency->code : $searchCode;
+                $searchCode = $this->convertToPrimary ? $this->primaryCurrency->code : $key;
+                $searchCode = 'balance' === $searchCode || 'pc_balance' === $searchCode ? $this->primaryCurrency->code : $searchCode;
                 // Log::debug(sprintf('Search code is %s', $searchCode));
                 // see if there is an accompanying start amount.
                 // grab the difference and find the currency.
-                $startBalance = ($startBalances[$account->id][$key] ?? '0');
+                $startBalance = $startBalances[$account->id][$key] ?? '0';
                 //                Log::debug(sprintf('Start balance is %s', $startBalance));
-                $diff         = bcsub($endBalance, $startBalance);
+                $diff = bcsub($endBalance, $startBalance);
                 $currencies[$searchCode] ??= $this->currencyRepository->findByCode($searchCode);
                 if (0 !== bccomp($diff, '0')) {
                     // store the values in a temporary array.
                     $tempData[] = [
-                        'name'        => $accountNames[$account->id],
-                        'difference'  => $diff,
-                        'diff_float'  => (float)$diff, // intentional float
-                        'currency_id' => $currencies[$searchCode]->id,
+                        'name'       => $accountNames[$account->id],
+                        'difference' => $diff,
+                        'diff_float' => (float) $diff, // intentional float
+                        'currency_id' => $currencies[$searchCode]->id
                     ];
                 }
             }
@@ -174,10 +169,10 @@ class AccountController extends Controller
         foreach ($currencies as $currency) {
             $newCurrencies[$currency->id] = $currency;
         }
-        $currencies    = $newCurrencies;
+        $currencies = $newCurrencies;
 
         // sort temp array by amount.
-        $amounts       = array_column($tempData, 'diff_float');
+        $amounts = array_column($tempData, 'diff_float');
         array_multisort($amounts, SORT_DESC, $tempData);
 
         // loop all found currencies and build the data array for the chart.
@@ -186,25 +181,24 @@ class AccountController extends Controller
          * @var TransactionCurrency $currency
          */
         foreach ($currencies as $currencyId => $currency) {
-            $dataSet
-                                    = [
-                                        'label'           => (string)trans('firefly.spent'),
-                                        'type'            => 'bar',
-                                        'currency_symbol' => $currency->symbol,
-                                        'currency_code'   => $currency->code,
-                                        'entries'         => $this->expandNames($tempData),
-                                    ];
+            $dataSet = [
+                'label'           => (string) trans('firefly.spent'),
+                'type'            => 'bar',
+                'currency_symbol' => $currency->symbol,
+                'currency_code'   => $currency->code,
+                'entries'         => $this->expandNames($tempData)
+            ];
             $chartData[$currencyId] = $dataSet;
         }
 
         // loop temp data and place data in correct array:
         foreach ($tempData as $entry) {
-            $currencyId                               = $entry['currency_id'];
-            $name                                     = $entry['name'];
-            $chartData[$currencyId]['entries'][$name] = (float)$entry['difference'];
+            $currencyId = $entry['currency_id'];
+            $name       = $entry['name'];
+            $chartData[$currencyId]['entries'][$name] = (float) $entry['difference'];
         }
 
-        $data          = $this->generator->multiSet($chartData);
+        $data = $this->generator->multiSet($chartData);
         $cache->store($data);
 
         return response()->json($data);
@@ -226,7 +220,7 @@ class AccountController extends Controller
      */
     public function expenseBudget(Account $account, Carbon $start, Carbon $end): JsonResponse
     {
-        $cache     = new CacheProperties();
+        $cache = new CacheProperties();
         $cache->addProperty($account->id);
         $cache->addProperty($start);
         $cache->addProperty($this->convertToPrimary);
@@ -238,10 +232,11 @@ class AccountController extends Controller
 
         /** @var GroupCollectorInterface $collector */
         $collector = app(GroupCollectorInterface::class);
-        $collector->setAccounts(new Collection()->push($account))
+        $collector
+            ->setAccounts(new Collection()->push($account))
             ->setRange($start, $end)
-            ->withBudgetInformation()->setTypes([TransactionTypeEnum::WITHDRAWAL->value])
-        ;
+            ->withBudgetInformation()
+            ->setTypes([TransactionTypeEnum::WITHDRAWAL->value]);
         $journals  = $collector->getExtractedJournals();
         $chartData = [];
         $result    = [];
@@ -249,12 +244,12 @@ class AccountController extends Controller
 
         /** @var array $journal */
         foreach ($journals as $journal) {
-            $budgetId              = (int)$journal['budget_id'];
-            $key                   = sprintf('%d-%d', $budgetId, $journal['currency_id']);
-            $budgetIds[]           = $budgetId;
+            $budgetId = (int) $journal['budget_id'];
+            $key      = sprintf('%d-%d', $budgetId, $journal['currency_id']);
+            $budgetIds[] = $budgetId;
 
             // currency info:
-            $currencyId            = (int)$journal['currency_id'];
+            $currencyId            = (int) $journal['currency_id'];
             $currencyName          = $journal['currency_name'];
             $currencySymbol        = $journal['currency_symbol'];
             $currencyCode          = $journal['currency_code'];
@@ -266,7 +261,6 @@ class AccountController extends Controller
                 $currencySymbol        = $this->primaryCurrency->symbol;
                 $currencyCode          = $this->primaryCurrency->code;
                 $currencyDecimalPlaces = $this->primaryCurrency->decimal_places;
-
             }
 
             if (!array_key_exists($key, $result)) {
@@ -276,22 +270,22 @@ class AccountController extends Controller
                     'currency_name'           => $currencyName,
                     'currency_symbol'         => $currencySymbol,
                     'currency_code'           => $currencyCode,
-                    'currency_decimal_places' => $currencyDecimalPlaces,
+                    'currency_decimal_places' => $currencyDecimalPlaces
                 ];
             }
-            $result[$key]['total'] = bcadd((string)$journal[$field], $result[$key]['total']);
+            $result[$key]['total'] = bcadd((string) $journal[$field], $result[$key]['total']);
         }
 
-        $names     = $this->getBudgetNames($budgetIds);
+        $names = $this->getBudgetNames($budgetIds);
 
         foreach ($result as $row) {
-            $budgetId          = $row['budget_id'];
-            $name              = $names[$budgetId];
-            $label             = (string)trans('firefly.name_in_currency', ['name' => $name, 'currency' => $row['currency_name']]);
-            $chartData[$label] = ['amount' => $row['total'], 'currency_symbol' => $row['currency_symbol'], 'currency_code' => $row['currency_code']];
+            $budgetId = $row['budget_id'];
+            $name     = $names[$budgetId];
+            $label    = (string) trans('firefly.name_in_currency', ['name'     => $name, 'currency' => $row['currency_name']]);
+            $chartData[$label] = ['amount'          => $row['total'], 'currency_symbol' => $row['currency_symbol'], 'currency_code'   => $row['currency_code']];
         }
 
-        $data      = $this->generator->multiCurrencyPieChart($chartData);
+        $data = $this->generator->multiCurrencyPieChart($chartData);
         $cache->store($data);
 
         return response()->json($data);
@@ -313,7 +307,7 @@ class AccountController extends Controller
      */
     public function expenseCategory(Account $account, Carbon $start, Carbon $end): JsonResponse
     {
-        $cache     = new CacheProperties();
+        $cache = new CacheProperties();
         $cache->addProperty($account->id);
         $cache->addProperty($start);
         $cache->addProperty($end);
@@ -325,19 +319,22 @@ class AccountController extends Controller
 
         /** @var GroupCollectorInterface $collector */
         $collector = app(GroupCollectorInterface::class);
-        $collector->setAccounts(new Collection()->push($account))->setRange($start, $end)->withCategoryInformation()->setTypes([TransactionTypeEnum::WITHDRAWAL->value]);
+        $collector
+            ->setAccounts(new Collection()->push($account))
+            ->setRange($start, $end)
+            ->withCategoryInformation()
+            ->setTypes([TransactionTypeEnum::WITHDRAWAL->value]);
         $journals  = $collector->getExtractedJournals();
         $result    = [];
         $chartData = [];
 
         /** @var array $journal */
         foreach ($journals as $journal) {
-            $key                   = sprintf('%d-%d', $journal['category_id'], $journal['currency_id']);
-            $field                 = 'amount';
+            $key   = sprintf('%d-%d', $journal['category_id'], $journal['currency_id']);
+            $field = 'amount';
             if (!array_key_exists($key, $result)) {
-
                 // currency info:
-                $currencyId            = (int)$journal['currency_id'];
+                $currencyId            = (int) $journal['currency_id'];
                 $currencyName          = $journal['currency_name'];
                 $currencySymbol        = $journal['currency_symbol'];
                 $currencyCode          = $journal['currency_code'];
@@ -350,27 +347,27 @@ class AccountController extends Controller
                     $currencyDecimalPlaces = $this->primaryCurrency->decimal_places;
                 }
 
-                $result[$key]          = [
+                $result[$key] = [
                     'total'                   => '0',
-                    'category_id'             => (int)$journal['category_id'],
+                    'category_id'             => (int) $journal['category_id'],
                     'currency_name'           => $currencyName,
                     'currency_code'           => $currencyCode,
                     'currency_symbol'         => $currencySymbol,
-                    'currency_decimal_places' => $currencyDecimalPlaces,
+                    'currency_decimal_places' => $currencyDecimalPlaces
                 ];
             }
-            $result[$key]['total'] = bcadd((string)$journal[$field], $result[$key]['total']);
+            $result[$key]['total'] = bcadd((string) $journal[$field], $result[$key]['total']);
         }
-        $names     = $this->getCategoryNames(array_keys($result));
+        $names = $this->getCategoryNames(array_keys($result));
 
         foreach ($result as $row) {
-            $categoryId        = $row['category_id'];
-            $name              = $names[$categoryId] ?? '(unknown)';
-            $label             = (string)trans('firefly.name_in_currency', ['name' => $name, 'currency' => $row['currency_name']]);
-            $chartData[$label] = ['amount' => $row['total'], 'currency_symbol' => $row['currency_symbol'], 'currency_code' => $row['currency_code']];
+            $categoryId = $row['category_id'];
+            $name       = $names[$categoryId] ?? '(unknown)';
+            $label      = (string) trans('firefly.name_in_currency', ['name'     => $name, 'currency' => $row['currency_name']]);
+            $chartData[$label] = ['amount'          => $row['total'], 'currency_symbol' => $row['currency_symbol'], 'currency_code'   => $row['currency_code']];
         }
 
-        $data      = $this->generator->multiCurrencyPieChart($chartData);
+        $data = $this->generator->multiCurrencyPieChart($chartData);
         $cache->store($data);
 
         return response()->json($data);
@@ -383,9 +380,9 @@ class AccountController extends Controller
      *                                              */
     public function frontpage(AccountRepositoryInterface $repository): JsonResponse
     {
-        $start          = clone session('start', today(config('app.timezone'))->startOfMonth());
-        $end            = clone session('end', today(config('app.timezone'))->endOfMonth());
-        $defaultSet     = $repository->getAccountsByType([AccountTypeEnum::DEFAULT->value, AccountTypeEnum::ASSET->value])->pluck('id')->toArray();
+        $start      = clone session('start', today(config('app.timezone'))->startOfMonth());
+        $end        = clone session('end', today(config('app.timezone'))->endOfMonth());
+        $defaultSet = $repository->getAccountsByType([AccountTypeEnum::DEFAULT->value, AccountTypeEnum::ASSET->value])->pluck('id')->toArray();
         // Log::debug('Default set is ', $defaultSet);
         $frontpage      = Preferences::get('frontpageAccounts', $defaultSet);
         $frontpageArray = is_array($frontpage->data) ? $frontpage->data : [];
@@ -394,7 +391,7 @@ class AccountController extends Controller
             Preferences::set('frontpageAccounts', $defaultSet);
             Log::debug('frontpage set is empty!');
         }
-        $accounts       = $repository->getAccountsById($frontpageArray);
+        $accounts = $repository->getAccountsById($frontpageArray);
 
         // move to end of day for $end.
         $end->endOfDay();
@@ -418,7 +415,7 @@ class AccountController extends Controller
      */
     public function incomeCategory(Account $account, Carbon $start, Carbon $end): JsonResponse
     {
-        $cache     = new CacheProperties();
+        $cache = new CacheProperties();
         $cache->addProperty($account->id);
         $cache->addProperty($start);
         $cache->addProperty($this->convertToPrimary);
@@ -432,19 +429,22 @@ class AccountController extends Controller
         /** @var GroupCollectorInterface $collector */
         $collector = app(GroupCollectorInterface::class);
 
-        $collector->setAccounts(new Collection()->push($account))->setRange($start, $end)->withCategoryInformation()->setTypes([TransactionTypeEnum::DEPOSIT->value]);
+        $collector
+            ->setAccounts(new Collection()->push($account))
+            ->setRange($start, $end)
+            ->withCategoryInformation()
+            ->setTypes([TransactionTypeEnum::DEPOSIT->value]);
         $journals  = $collector->getExtractedJournals();
         $result    = [];
         $chartData = [];
 
         /** @var array $journal */
         foreach ($journals as $journal) {
-            $key                   = sprintf('%d-%d', $journal['category_id'], $journal['currency_id']);
-            $field                 = 'amount';
+            $key   = sprintf('%d-%d', $journal['category_id'], $journal['currency_id']);
+            $field = 'amount';
             if (!array_key_exists($key, $result)) {
-
                 // currency info:
-                $currencyId            = (int)$journal['currency_id'];
+                $currencyId            = (int) $journal['currency_id'];
                 $currencyName          = $journal['currency_name'];
                 $currencySymbol        = $journal['currency_symbol'];
                 $currencyCode          = $journal['currency_code'];
@@ -457,26 +457,26 @@ class AccountController extends Controller
                     $currencyDecimalPlaces = $this->primaryCurrency->decimal_places;
                 }
 
-                $result[$key]          = [
+                $result[$key] = [
                     'total'                   => '0',
                     'category_id'             => $journal['category_id'],
                     'currency_name'           => $currencyName,
                     'currency_code'           => $currencyCode,
                     'currency_symbol'         => $currencySymbol,
-                    'currency_decimal_places' => $currencyDecimalPlaces,
+                    'currency_decimal_places' => $currencyDecimalPlaces
                 ];
             }
-            $result[$key]['total'] = bcadd((string)$journal[$field], $result[$key]['total']);
+            $result[$key]['total'] = bcadd((string) $journal[$field], $result[$key]['total']);
         }
 
-        $names     = $this->getCategoryNames(array_keys($result));
+        $names = $this->getCategoryNames(array_keys($result));
         foreach ($result as $row) {
-            $categoryId        = $row['category_id'];
-            $name              = $names[$categoryId] ?? '(unknown)';
-            $label             = (string)trans('firefly.name_in_currency', ['name' => $name, 'currency' => $row['currency_name']]);
-            $chartData[$label] = ['amount' => $row['total'], 'currency_symbol' => $row['currency_symbol'], 'currency_code' => $row['currency_code']];
+            $categoryId = $row['category_id'];
+            $name       = $names[$categoryId] ?? '(unknown)';
+            $label      = (string) trans('firefly.name_in_currency', ['name'     => $name, 'currency' => $row['currency_name']]);
+            $chartData[$label] = ['amount'          => $row['total'], 'currency_symbol' => $row['currency_symbol'], 'currency_code'   => $row['currency_code']];
         }
-        $data      = $this->generator->multiCurrencyPieChart($chartData);
+        $data = $this->generator->multiCurrencyPieChart($chartData);
         $cache->store($data);
 
         return response()->json($data);
@@ -494,7 +494,7 @@ class AccountController extends Controller
         $end->endOfDay();
         // TODO not sure if these date ranges will work as expected.
         Log::debug(sprintf('Now in period("%s", "%s")', $start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s')));
-        $cache           = new CacheProperties();
+        $cache = new CacheProperties();
         $cache->addProperty('chart.account.period');
         $cache->addProperty($start);
         $cache->addProperty($end);
@@ -505,22 +505,22 @@ class AccountController extends Controller
         }
 
         // collect and filter balances for the entire period.
-        $step            = $this->calculateStep($start, $end);
+        $step = $this->calculateStep($start, $end);
         Log::debug(sprintf('Step is %s', $step));
-        $locale          = Steam::getLocale();
-        $return          = [];
-        $converter       = new ExchangeRateConverter();
+        $locale    = Steam::getLocale();
+        $return    = [];
+        $converter = new ExchangeRateConverter();
 
         // fix for issue https://github.com/firefly-iii/firefly-iii/issues/8041
         // have to make sure this chart is always based on the balance at the END of the period.
         // This period depends on the size of the chart
         $current         = clone $start;
         $current         = Navigation::endOfX($current, $step, null);
-        $format          = (string)trans('config.month_and_day_js', [], $locale);
+        $format          = (string) trans('config.month_and_day_js', [], $locale);
         $accountCurrency = $this->accountRepository->getAccountCurrency($account);
         Log::debug('Get and filter balance for entire range start');
-        $range           = Steam::finalAccountBalanceInRange($account, $start, $end, $this->convertToPrimary);
-        $range           = Steam::filterAccountBalances($range, $account, $this->convertToPrimary, $accountCurrency);
+        $range = Steam::finalAccountBalanceInRange($account, $start, $end, $this->convertToPrimary);
+        $range = Steam::filterAccountBalances($range, $account, $this->convertToPrimary, $accountCurrency);
         Log::debug('Get and filter balance for entire range end');
         // temp, get end balance.
         //        Log::debug(sprintf('period: Call finalAccountBalance with date/time "%s"', $end->toIso8601String()));
@@ -531,14 +531,14 @@ class AccountController extends Controller
         $accountCurrency ??= $this->primaryCurrency; // do this AFTER getting the balances.
         Log::debug('Start chart loop.');
 
-        $newRange        = [];
-        $expectedIndex   = 0;
+        $newRange      = [];
+        $expectedIndex = 0;
         Log::debug('Balances exist at:');
         foreach ($range as $key => $value) {
             $newRange[] = ['date' => $key, 'info' => $value];
             Log::debug(sprintf('%d - %s (%s)', count($newRange) - 1, $key, json_encode($value)));
         }
-        $carbon          = Carbon::createFromFormat('Y-m-d', $newRange[0]['date'])->endOfDay();
+        $carbon = Carbon::createFromFormat('Y-m-d', $newRange[0]['date'])->endOfDay();
         Log::debug(sprintf('Start of loop, $carbon is %s', $carbon->format('Y-m-d H:i:s')));
         while ($end->gte($current)) {
             $momentBalance = $previous;
@@ -547,7 +547,12 @@ class AccountController extends Controller
 
             // loop over the array with balances, find one that is earlier or on the same day.
             while ($carbon->lte($current) && array_key_exists($expectedIndex, $newRange)) {
-                Log::debug(sprintf('[a] Expected index is %d, $carbon is %s, current is %s', $expectedIndex, $carbon->format('Y-m-d H:i:s'), $current->format('Y-m-d H:i:s')));
+                Log::debug(sprintf(
+                    '[a] Expected index is %d, $carbon is %s, current is %s',
+                    $expectedIndex,
+                    $carbon->format('Y-m-d H:i:s'),
+                    $current->format('Y-m-d H:i:s')
+                ));
 
                 // grab the balance from that particular $expectedIndex
                 $momentBalance = $newRange[$expectedIndex]['info'];
@@ -562,49 +567,48 @@ class AccountController extends Controller
 
             // check, perhaps recalculate the amount in currency X if the
             if ($accountCurrency->id !== $this->primaryCurrency->id && $this->convertToPrimary && array_key_exists($accountCurrency->code, $momentBalance)) {
-                $converted                   = $converter->convert($accountCurrency, $this->primaryCurrency, $current, $momentBalance[$accountCurrency->code]);
+                $converted = $converter->convert($accountCurrency, $this->primaryCurrency, $current, $momentBalance[$accountCurrency->code]);
                 $momentBalance['pc_balance'] = $converted;
             }
 
-
-            $return        = $this->updateChartKeys($return, $momentBalance);
-            $previous      = $momentBalance;
+            $return   = $this->updateChartKeys($return, $momentBalance);
+            $previous = $momentBalance;
 
             // process each balance thing.
             foreach ($momentBalance as $key => $amount) {
-                $label                           = $current->isoFormat($format);
+                $label = $current->isoFormat($format);
                 $return[$key]['entries'][$label] = $amount;
             }
-            $current       = Navigation::addPeriod($current, $step);
+            $current = Navigation::addPeriod($current, $step);
             // here too, to fix #8041, the data is corrected to the end of the period.
-            $current       = Navigation::endOfX($current, $step, null);
+            $current = Navigation::endOfX($current, $step, null);
         }
         Log::debug('End of chart loop.');
         // second loop (yes) to create nice array with info! Yay!
-        $chartData       = [];
+        $chartData = [];
 
         foreach ($return as $key => $info) {
             if ('balance' !== $key && 'pc_balance' !== $key) {
                 // assume it's a currency:
-                $setCurrency             = $this->currencyRepository->findByCode((string)$key);
+                $setCurrency = $this->currencyRepository->findByCode((string) $key);
                 $info['currency_symbol'] = $setCurrency->symbol;
-                $info['currency_code']   = $setCurrency->code;
-                $info['label']           = sprintf('%s (%s)', $account->name, $setCurrency->symbol);
+                $info['currency_code'] = $setCurrency->code;
+                $info['label'] = sprintf('%s (%s)', $account->name, $setCurrency->symbol);
             }
             if ('balance' === $key) {
                 $info['currency_symbol'] = $accountCurrency->symbol;
-                $info['currency_code']   = $accountCurrency->code;
-                $info['label']           = sprintf('%s (%s)', $account->name, $accountCurrency->symbol);
+                $info['currency_code'] = $accountCurrency->code;
+                $info['label'] = sprintf('%s (%s)', $account->name, $accountCurrency->symbol);
             }
             if ('pc_balance' === $key) {
                 $info['currency_symbol'] = $this->primaryCurrency->symbol;
-                $info['currency_code']   = $this->primaryCurrency->code;
-                $info['label']           = sprintf('%s (%s) (%s)', $account->name, (string)trans('firefly.sum'), $this->primaryCurrency->symbol);
+                $info['currency_code'] = $this->primaryCurrency->code;
+                $info['label'] = sprintf('%s (%s) (%s)', $account->name, (string) trans('firefly.sum'), $this->primaryCurrency->symbol);
             }
             $chartData[] = $info;
         }
 
-        $data            = $this->generator->multiSet($chartData);
+        $data = $this->generator->multiSet($chartData);
         $cache->store($data);
 
         return response()->json($data);
@@ -613,9 +617,7 @@ class AccountController extends Controller
     private function updateChartKeys(array $array, array $balances): array
     {
         foreach (array_keys($balances) as $key) {
-            $array[$key] ??= [
-                'key' => $key,
-            ];
+            $array[$key] ??= ['key' => $key];
         }
 
         return $array;
@@ -641,15 +643,15 @@ class AccountController extends Controller
     public function revenueAccounts(): JsonResponse
     {
         /** @var Carbon $start */
-        $start         = clone session('start', today(config('app.timezone'))->startOfMonth());
+        $start = clone session('start', today(config('app.timezone'))->startOfMonth());
 
         /** @var Carbon $end */
-        $end           = clone session('end', today(config('app.timezone'))->endOfMonth());
+        $end = clone session('end', today(config('app.timezone'))->endOfMonth());
 
         $start->startOfDay();
         $end->endOfDay();
 
-        $cache         = new CacheProperties();
+        $cache = new CacheProperties();
         $cache->addProperty($start);
         $cache->addProperty($end);
         $cache->addProperty($this->convertToPrimary);
@@ -659,21 +661,17 @@ class AccountController extends Controller
         }
 
         // prep some vars:
-        $currencies    = [];
-        $chartData     = [];
-        $tempData      = [];
+        $currencies = [];
+        $chartData  = [];
+        $tempData   = [];
 
         // grab all accounts and names
-        $accounts      = $this->accountRepository->getAccountsByType([AccountTypeEnum::REVENUE->value]);
-        $accountNames  = $this->extractNames($accounts);
+        $accounts     = $this->accountRepository->getAccountsByType([AccountTypeEnum::REVENUE->value]);
+        $accountNames = $this->extractNames($accounts);
 
         // grab all balances
         Log::debug(sprintf('revAccounts: accountsBalancesInRange("%s", "%s")', $start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s')));
-        [
-            $startBalances,
-            $endBalances,
-        ]              = Steam::accountsBalancesInRange($accounts, $start, $end, $this->primaryCurrency, $this->convertToPrimary);
-
+        [$startBalances, $endBalances] = Steam::accountsBalancesInRange($accounts, $start, $end, $this->primaryCurrency, $this->convertToPrimary);
 
         // loop the accounts, then check for balance and currency info.
         foreach ($accounts as $account) {
@@ -701,37 +699,36 @@ class AccountController extends Controller
                     continue;
                 }
                 // Log::debug(sprintf('Will process expense array "%s" with amount %s', $key, $endBalance));
-                $searchCode   = $this->convertToPrimary ? $this->primaryCurrency->code : $key;
-                $searchCode   = 'balance' === $searchCode || 'pc_balance' === $searchCode ? $this->primaryCurrency->code : $searchCode;
+                $searchCode = $this->convertToPrimary ? $this->primaryCurrency->code : $key;
+                $searchCode = 'balance' === $searchCode || 'pc_balance' === $searchCode ? $this->primaryCurrency->code : $searchCode;
                 // Log::debug(sprintf('Search code is %s', $searchCode));
                 // see if there is an accompanying start amount.
                 // grab the difference and find the currency.
-                $startBalance = ($startBalances[$account->id][$key] ?? '0');
+                $startBalance = $startBalances[$account->id][$key] ?? '0';
                 // Log::debug(sprintf('Start balance is %s', $startBalance));
-                $diff         = bcsub($endBalance, $startBalance);
+                $diff = bcsub($endBalance, $startBalance);
                 $currencies[$searchCode] ??= $this->currencyRepository->findByCode($searchCode);
                 if (0 !== bccomp($diff, '0')) {
                     // store the values in a temporary array.
                     $tempData[] = [
-                        'name'        => $accountNames[$account->id],
-                        'difference'  => $diff,
-                        'diff_float'  => (float)$diff, // intentional float
-                        'currency_id' => $currencies[$searchCode]->id,
+                        'name'       => $accountNames[$account->id],
+                        'difference' => $diff,
+                        'diff_float' => (float) $diff, // intentional float
+                        'currency_id' => $currencies[$searchCode]->id
                     ];
                 }
             }
         }
 
-
         // recreate currencies, but on ID instead of code.
         $newCurrencies = [];
         foreach ($currencies as $currency) {
             $newCurrencies[$currency->id] = $currency;
         }
-        $currencies    = $newCurrencies;
+        $currencies = $newCurrencies;
 
         // sort temp array by amount.
-        $amounts       = array_column($tempData, 'diff_float');
+        $amounts = array_column($tempData, 'diff_float');
         array_multisort($amounts, SORT_ASC, $tempData);
 
         // loop all found currencies and build the data array for the chart.
@@ -740,25 +737,24 @@ class AccountController extends Controller
          * @var TransactionCurrency $currency
          */
         foreach ($currencies as $currencyId => $currency) {
-            $dataSet
-                                    = [
-                                        'label'           => (string)trans('firefly.earned'),
-                                        'type'            => 'bar',
-                                        'currency_symbol' => $currency->symbol,
-                                        'currency_code'   => $currency->code,
-                                        'entries'         => $this->expandNames($tempData),
-                                    ];
+            $dataSet = [
+                'label'           => (string) trans('firefly.earned'),
+                'type'            => 'bar',
+                'currency_symbol' => $currency->symbol,
+                'currency_code'   => $currency->code,
+                'entries'         => $this->expandNames($tempData)
+            ];
             $chartData[$currencyId] = $dataSet;
         }
 
         // loop temp data and place data in correct array:
         foreach ($tempData as $entry) {
-            $currencyId                               = $entry['currency_id'];
-            $name                                     = $entry['name'];
+            $currencyId = $entry['currency_id'];
+            $name       = $entry['name'];
             $chartData[$currencyId]['entries'][$name] = bcmul($entry['difference'], '-1');
         }
 
-        $data          = $this->generator->multiSet($chartData);
+        $data = $this->generator->multiSet($chartData);
         $cache->store($data);
 
         return response()->json($data);
diff --git a/app/Http/Controllers/Chart/BillController.php b/app/Http/Controllers/Chart/BillController.php
index 443a82e32c..4874795c94 100644
--- a/app/Http/Controllers/Chart/BillController.php
+++ b/app/Http/Controllers/Chart/BillController.php
@@ -30,8 +30,8 @@ use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\Models\Bill;
 use FireflyIII\Repositories\Bill\BillRepositoryInterface;
 use FireflyIII\Support\CacheProperties;
-use Illuminate\Http\JsonResponse;
 use FireflyIII\Support\Facades\Steam;
+use Illuminate\Http\JsonResponse;
 
 /**
  * Class BillController.
@@ -54,9 +54,9 @@ class BillController extends Controller
      */
     public function frontpage(BillRepositoryInterface $repository): JsonResponse
     {
-        $start     = session('start', today(config('app.timezone'))->startOfMonth());
-        $end       = session('end', today(config('app.timezone'))->endOfMonth());
-        $cache     = new CacheProperties();
+        $start = session('start', today(config('app.timezone'))->startOfMonth());
+        $end   = session('end', today(config('app.timezone'))->endOfMonth());
+        $cache = new CacheProperties();
         $cache->addProperty($start);
         $cache->addProperty($end);
         $cache->addProperty('chart.bill.frontpage');
@@ -72,29 +72,21 @@ class BillController extends Controller
          * @var array $info
          */
         foreach ($paid as $info) {
-            $amount            = $info['sum'];
-            $label             = (string) trans('firefly.paid_in_currency', ['currency' => $info['name']]);
-            $chartData[$label] = [
-                'amount'          => $amount,
-                'currency_symbol' => $info['symbol'],
-                'currency_code'   => $info['code'],
-            ];
+            $amount = $info['sum'];
+            $label  = (string) trans('firefly.paid_in_currency', ['currency'  => $info['name']]);
+            $chartData[$label] = ['amount'          => $amount, 'currency_symbol' => $info['symbol'], 'currency_code'   => $info['code']];
         }
 
         /**
          * @var array $info
          */
         foreach ($unpaid as $info) {
-            $amount            = $info['sum'];
-            $label             = (string) trans('firefly.unpaid_in_currency', ['currency' => $info['name']]);
-            $chartData[$label] = [
-                'amount'          => $amount,
-                'currency_symbol' => $info['symbol'],
-                'currency_code'   => $info['code'],
-            ];
+            $amount = $info['sum'];
+            $label  = (string) trans('firefly.unpaid_in_currency', ['currency'  => $info['name']]);
+            $chartData[$label] = ['amount'          => $amount, 'currency_symbol' => $info['symbol'], 'currency_code'   => $info['code']];
         }
 
-        $data      = $this->generator->multiCurrencyPieChart($chartData);
+        $data = $this->generator->multiCurrencyPieChart($chartData);
         $cache->store($data);
 
         return response()->json($data);
@@ -107,34 +99,31 @@ class BillController extends Controller
      */
     public function single(Bill $bill): JsonResponse
     {
-        $cache      = new CacheProperties();
+        $cache = new CacheProperties();
         $cache->addProperty('chart.bill.single');
         $cache->addProperty($bill->id);
         $cache->addProperty($this->convertToPrimary);
         if ($cache->has()) {
             return response()->json($cache->get());
         }
-        $locale     = Steam::getLocale();
+        $locale = Steam::getLocale();
 
         /** @var GroupCollectorInterface $collector */
-        $collector  = app(GroupCollectorInterface::class);
-        $journals   = $collector->setBill($bill)->getExtractedJournals();
+        $collector = app(GroupCollectorInterface::class);
+        $journals  = $collector->setBill($bill)->getExtractedJournals();
 
         // sort the other way around:
-        usort(
-            $journals,
-            static function (array $left, array $right): int {
-                if ($left['date']->gt($right['date'])) {
-                    return 1;
-                }
-                if ($left['date']->lt($right['date'])) {
-                    return -1;
-                }
-
-                return 0;
+        usort($journals, static function (array $left, array $right): int {
+            if ($left['date']->gt($right['date'])) {
+                return 1;
             }
-        );
-        $currency   = $bill->transactionCurrency;
+            if ($left['date']->lt($right['date'])) {
+                return -1;
+            }
+
+            return 0;
+        });
+        $currency = $bill->transactionCurrency;
         if ($this->convertToPrimary) {
             $currency = $this->primaryCurrency;
         }
@@ -145,22 +134,22 @@ class BillController extends Controller
                 'label'           => (string) trans('firefly.min-amount'),
                 'currency_symbol' => $currency->symbol,
                 'currency_code'   => $currency->code,
-                'entries'         => [],
+                'entries'         => []
             ],
             [
                 'type'            => 'line',
                 'label'           => (string) trans('firefly.max-amount'),
                 'currency_symbol' => $currency->symbol,
                 'currency_code'   => $currency->code,
-                'entries'         => [],
+                'entries'         => []
             ],
             [
                 'type'            => 'bar',
                 'label'           => (string) trans('firefly.journal-amount'),
                 'currency_symbol' => $currency->symbol,
                 'currency_code'   => $currency->code,
-                'entries'         => [],
-            ],
+                'entries'         => []
+            ]
         ];
         $currencyId = $bill->transaction_currency_id;
         $amountMin  = $bill->amount_min;
@@ -170,7 +159,7 @@ class BillController extends Controller
             $amountMax = $bill->native_amount_max;
         }
         foreach ($journals as $journal) {
-            $date                           = $journal['date']->isoFormat((string) trans('config.month_and_day_js', [], $locale));
+            $date = $journal['date']->isoFormat((string) trans('config.month_and_day_js', [], $locale));
             $chartData[0]['entries'][$date] = $amountMin; // minimum amount of bill
             $chartData[1]['entries'][$date] = $amountMax; // maximum amount of bill
 
@@ -178,7 +167,7 @@ class BillController extends Controller
             if (!array_key_exists($date, $chartData[2]['entries'])) {
                 $chartData[2]['entries'][$date] = '0';
             }
-            $amount                         = bcmul((string) $journal['amount'], '-1');
+            $amount = bcmul((string) $journal['amount'], '-1');
             if ($this->convertToPrimary && $currencyId !== $journal['currency_id']) {
                 $amount = bcmul($journal['pc_amount'] ?? '0', '-1');
             }
@@ -186,10 +175,10 @@ class BillController extends Controller
                 $amount = bcmul((string) $journal['pc_amount'], '-1');
             }
 
-            $chartData[2]['entries'][$date] = bcadd($chartData[2]['entries'][$date], $amount);  // amount of journal
+            $chartData[2]['entries'][$date] = bcadd($chartData[2]['entries'][$date], $amount); // amount of journal
         }
 
-        $data       = $this->generator->multiSet($chartData);
+        $data = $this->generator->multiSet($chartData);
         $cache->store($data);
 
         return response()->json($data);
diff --git a/app/Http/Controllers/Chart/BudgetController.php b/app/Http/Controllers/Chart/BudgetController.php
index a7e95c439f..8ef0492d89 100644
--- a/app/Http/Controllers/Chart/BudgetController.php
+++ b/app/Http/Controllers/Chart/BudgetController.php
@@ -39,12 +39,12 @@ use FireflyIII\Repositories\Budget\OperationsRepositoryInterface;
 use FireflyIII\Support\CacheProperties;
 use FireflyIII\Support\Chart\Budget\FrontpageChartGenerator;
 use FireflyIII\Support\Facades\Navigation;
+use FireflyIII\Support\Facades\Steam;
 use FireflyIII\Support\Http\Controllers\AugumentData;
 use FireflyIII\Support\Http\Controllers\DateCalculation;
 use Illuminate\Http\JsonResponse;
 use Illuminate\Support\Collection;
 use Illuminate\Support\Facades\Log;
-use FireflyIII\Support\Facades\Steam;
 
 /**
  * Class BudgetController.
@@ -54,11 +54,11 @@ class BudgetController extends Controller
     use AugumentData;
     use DateCalculation;
 
-    protected GeneratorInterface            $generator;
+    protected GeneratorInterface $generator;
     protected OperationsRepositoryInterface $opsRepository;
-    protected BudgetRepositoryInterface     $repository;
-    private BudgetLimitRepositoryInterface  $blRepository;
-    private NoBudgetRepositoryInterface     $nbRepository;
+    protected BudgetRepositoryInterface $repository;
+    private BudgetLimitRepositoryInterface $blRepository;
+    private NoBudgetRepositoryInterface $nbRepository;
 
     /**
      * BudgetController constructor.
@@ -67,17 +67,15 @@ class BudgetController extends Controller
     {
         parent::__construct();
 
-        $this->middleware(
-            function ($request, $next) {
-                $this->generator     = app(GeneratorInterface::class);
-                $this->repository    = app(BudgetRepositoryInterface::class);
-                $this->opsRepository = app(OperationsRepositoryInterface::class);
-                $this->blRepository  = app(BudgetLimitRepositoryInterface::class);
-                $this->nbRepository  = app(NoBudgetRepositoryInterface::class);
+        $this->middleware(function ($request, $next) {
+            $this->generator = app(GeneratorInterface::class);
+            $this->repository = app(BudgetRepositoryInterface::class);
+            $this->opsRepository = app(OperationsRepositoryInterface::class);
+            $this->blRepository = app(BudgetLimitRepositoryInterface::class);
+            $this->nbRepository = app(NoBudgetRepositoryInterface::class);
 
-                return $next($request);
-            }
-        );
+            return $next($request);
+        });
     }
 
     /**
@@ -86,11 +84,11 @@ class BudgetController extends Controller
     public function budget(Budget $budget): JsonResponse
     {
         /** @var Carbon $start */
-        $start          = $this->repository->firstUseDate($budget) ?? session('start', today(config('app.timezone')));
+        $start = $this->repository->firstUseDate($budget) ?? session('start', today(config('app.timezone')));
 
         /** @var Carbon $end */
-        $end            = session('end', today(config('app.timezone')));
-        $cache          = new CacheProperties();
+        $end   = session('end', today(config('app.timezone')));
+        $cache = new CacheProperties();
         $cache->addProperty($start);
         $cache->addProperty($end);
         $cache->addProperty($this->convertToPrimary);
@@ -100,7 +98,7 @@ class BudgetController extends Controller
         if ($cache->has()) {
             return response()->json($cache->get());
         }
-        $step           = $this->calculateStep($start, $end); // depending on diff, do something with range of chart.
+        $step = $this->calculateStep($start, $end); // depending on diff, do something with range of chart.
         $collection     = new Collection()->push($budget);
         $chartData      = [];
         $loopStart      = clone $start;
@@ -109,19 +107,19 @@ class BudgetController extends Controller
         $defaultEntries = [];
         while ($end >= $loopStart) {
             /** @var Carbon $loopEnd */
-            $loopEnd                = Navigation::endOfPeriod($loopStart, $step);
-            $spent                  = $this->opsRepository->sumExpenses($loopStart, $loopEnd, null, $collection); // this method already converts to primary currency.
-            $label                  = trim(Navigation::periodShow($loopStart, $step));
+            $loopEnd = Navigation::endOfPeriod($loopStart, $step);
+            $spent   = $this->opsRepository->sumExpenses($loopStart, $loopEnd, null, $collection); // this method already converts to primary currency.
+            $label = trim(Navigation::periodShow($loopStart, $step));
 
             foreach ($spent as $row) {
-                $currencyId                               = $row['currency_id'];
+                $currencyId = $row['currency_id'];
                 $currencies[$currencyId] ??= $row; // don't mind the field 'sum'
                 // also store this day's sum:
                 $currencies[$currencyId]['spent'][$label] = $row['sum'];
             }
             $defaultEntries[$label] = 0;
             // set loop start to the next period:
-            $loopStart              = clone $loopEnd;
+            $loopStart = clone $loopEnd;
             $loopStart->addSecond();
         }
         // loop all currencies:
@@ -131,13 +129,13 @@ class BudgetController extends Controller
                 'type'            => 'bar',
                 'currency_symbol' => $currency['currency_symbol'],
                 'currency_code'   => $currency['currency_code'],
-                'entries'         => $defaultEntries,
+                'entries'         => $defaultEntries
             ];
             foreach ($currency['spent'] as $label => $spent) {
                 $chartData[$currencyId]['entries'][$label] = bcmul((string) $spent, '-1');
             }
         }
-        $data           = $this->generator->multiSet(array_values($chartData));
+        $data = $this->generator->multiSet(array_values($chartData));
         $cache->store($data);
 
         return response()->json($data);
@@ -154,9 +152,9 @@ class BudgetController extends Controller
             throw new FireflyException('This budget limit is not part of this budget.');
         }
 
-        $start                                  = clone $budgetLimit->start_date;
-        $end                                    = clone $budgetLimit->end_date;
-        $cache                                  = new CacheProperties();
+        $start = clone $budgetLimit->start_date;
+        $end   = clone $budgetLimit->end_date;
+        $cache = new CacheProperties();
         $cache->addProperty($start);
         $cache->addProperty($end);
         $cache->addProperty($this->convertToPrimary);
@@ -167,30 +165,37 @@ class BudgetController extends Controller
         if ($cache->has()) {
             return response()->json($cache->get());
         }
-        $locale                                 = Steam::getLocale();
-        $entries                                = [];
-        $amount                                 = $budgetLimit->amount ?? '0';
-        $budgetCollection                       = new Collection()->push($budget);
-        $currency                               = $budgetLimit->transactionCurrency;
+        $locale           = Steam::getLocale();
+        $entries          = [];
+        $amount           = $budgetLimit->amount ?? '0';
+        $budgetCollection = new Collection()->push($budget);
+        $currency         = $budgetLimit->transactionCurrency;
         if ($this->convertToPrimary) {
             $amount   = $budgetLimit->native_amount ?? $amount;
             $currency = $this->primaryCurrency;
         }
 
         while ($start <= $end) {
-            $current          = clone $start;
-            $expenses         = $this->opsRepository->sumExpenses($current, $current, null, $budgetCollection, $budgetLimit->transactionCurrency, $this->convertToPrimary);
-            $spent            = $expenses[$currency->id]['sum'] ?? '0';
-            $amount           = bcadd((string) $amount, $spent);
-            $format           = $start->isoFormat((string) trans('config.month_and_day_js', [], $locale));
+            $current  = clone $start;
+            $expenses = $this->opsRepository->sumExpenses(
+                $current,
+                $current,
+                null,
+                $budgetCollection,
+                $budgetLimit->transactionCurrency,
+                $this->convertToPrimary
+            );
+            $spent    = $expenses[$currency->id]['sum'] ?? '0';
+            $amount   = bcadd((string) $amount, $spent);
+            $format   = $start->isoFormat((string) trans('config.month_and_day_js', [], $locale));
             $entries[$format] = $amount;
 
             $start->addDay();
         }
-        $data                                   = $this->generator->singleSet((string) trans('firefly.left'), $entries);
+        $data = $this->generator->singleSet((string) trans('firefly.left'), $entries);
         // add currency symbol from budget limit:
         $data['datasets'][0]['currency_symbol'] = $currency->symbol;
-        $data['datasets'][0]['currency_code']   = $currency->code;
+        $data['datasets'][0]['currency_code'] = $currency->code;
         $cache->store($data);
         // var_dump($data);exit;
 
@@ -200,7 +205,7 @@ class BudgetController extends Controller
     /**
      * Shows how much is spent per asset account.
      */
-    public function expenseAsset(Budget $budget, ?BudgetLimit $budgetLimit = null): JsonResponse
+    public function expenseAsset(Budget $budget, null|BudgetLimit $budgetLimit = null): JsonResponse
     {
         /** @var GroupCollectorInterface $collector */
         $collector     = app(GroupCollectorInterface::class);
@@ -210,8 +215,8 @@ class BudgetController extends Controller
         $cache->addProperty($this->convertToPrimary);
         $cache->addProperty($budgetLimitId);
         $cache->addProperty('chart.budget.expense-asset');
-        $start         = session('first', today(config('app.timezone'))->startOfYear());
-        $end           = today();
+        $start = session('first', today(config('app.timezone'))->startOfYear());
+        $end   = today();
 
         if ($budgetLimit instanceof BudgetLimit) {
             $start = $budgetLimit->start_date;
@@ -226,18 +231,18 @@ class BudgetController extends Controller
         }
         $collector->setRange($start, $end);
         $collector->setBudget($budget);
-        $journals      = $collector->getExtractedJournals();
-        $result        = [];
-        $chartData     = [];
+        $journals  = $collector->getExtractedJournals();
+        $result    = [];
+        $chartData = [];
 
         // group by asset account ID:
         foreach ($journals as $journal) {
-            $key                    = sprintf('%d-%d', $journal['source_account_id'], $journal['currency_id']);
-            $amount                 = $journal['amount'];
+            $key    = sprintf('%d-%d', $journal['source_account_id'], $journal['currency_id']);
+            $amount = $journal['amount'];
 
-            $symbol                 = $journal['currency_symbol'];
-            $code                   = $journal['currency_code'];
-            $name                   = $journal['currency_name'];
+            $symbol = $journal['currency_symbol'];
+            $code   = $journal['currency_code'];
+            $name   = $journal['currency_name'];
 
             // if convert to primary, use the primary things, unless it's the foreign amount which is in the primary currency.
             if ($this->convertToPrimary && $journal['currency_id'] !== $this->primaryCurrency->id) {
@@ -252,29 +257,23 @@ class BudgetController extends Controller
                 $amount = $journal['foreign_amount'];
             }
 
-            $result[$key] ??= [
-                'amount'          => '0',
-                'currency_symbol' => $symbol,
-                'currency_code'   => $code,
-                'currency_name'   => $name,
-            ];
+            $result[$key] ??= ['amount'          => '0', 'currency_symbol' => $symbol, 'currency_code'   => $code, 'currency_name'   => $name];
             $result[$key]['amount'] = bcadd((string) $amount, $result[$key]['amount']);
         }
 
-        $names         = $this->getAccountNames(array_keys($result));
+        $names = $this->getAccountNames(array_keys($result));
         foreach ($result as $combinedId => $info) {
             $parts   = explode('-', $combinedId);
             $assetId = (int) $parts[0];
             $title   = sprintf('%s (%s)', $names[$assetId] ?? '(empty)', $info['currency_name']);
-            $chartData[$title]
-                     = [
-                         'amount'          => $info['amount'],
-                         'currency_symbol' => $info['currency_symbol'],
-                         'currency_code'   => $info['currency_code'],
-                     ];
+            $chartData[$title] = [
+                'amount'          => $info['amount'],
+                'currency_symbol' => $info['currency_symbol'],
+                'currency_code'   => $info['currency_code']
+            ];
         }
 
-        $data          = $this->generator->multiCurrencyPieChart($chartData);
+        $data = $this->generator->multiCurrencyPieChart($chartData);
         $cache->store($data);
 
         return response()->json($data);
@@ -283,7 +282,7 @@ class BudgetController extends Controller
     /**
      * Shows how much is spent per category.
      */
-    public function expenseCategory(Budget $budget, ?BudgetLimit $budgetLimit = null): JsonResponse
+    public function expenseCategory(Budget $budget, null|BudgetLimit $budgetLimit = null): JsonResponse
     {
         /** @var GroupCollectorInterface $collector */
         $collector     = app(GroupCollectorInterface::class);
@@ -293,8 +292,8 @@ class BudgetController extends Controller
         $cache->addProperty($this->convertToPrimary);
         $cache->addProperty($budgetLimitId);
         $cache->addProperty('chart.budget.expense-category');
-        $start         = session('first', today(config('app.timezone'))->startOfYear());
-        $end           = today();
+        $start = session('first', today(config('app.timezone'))->startOfYear());
+        $end   = today();
         if ($budgetLimit instanceof BudgetLimit) {
             $start = $budgetLimit->start_date;
             $end   = $budgetLimit->end_date;
@@ -308,17 +307,20 @@ class BudgetController extends Controller
         }
         $collector->setRange($start, $end);
         $collector->setBudget($budget)->withCategoryInformation();
-        $journals      = $collector->getExtractedJournals();
-        $result        = [];
-        $chartData     = [];
+        $journals  = $collector->getExtractedJournals();
+        $result    = [];
+        $chartData = [];
         foreach ($journals as $journal) {
-            $key                    = sprintf('%d-%d', $journal['category_id'], $journal['currency_id']);
-            $symbol                 = $journal['currency_symbol'];
-            $code                   = $journal['currency_code'];
-            $name                   = $journal['currency_name'];
-            $amount                 = $journal['amount'];
+            $key    = sprintf('%d-%d', $journal['category_id'], $journal['currency_id']);
+            $symbol = $journal['currency_symbol'];
+            $code   = $journal['currency_code'];
+            $name   = $journal['currency_name'];
+            $amount = $journal['amount'];
             // if convert to primary, use the primary things, unless it's the foreign amount which is in the primary currency.
-            if ($this->convertToPrimary && $journal['currency_id'] !== $this->primaryCurrency->id && $journal['foreign_currency_id'] !== $this->primaryCurrency->id
+            if (
+                $this->convertToPrimary
+                && $journal['currency_id'] !== $this->primaryCurrency->id
+                && $journal['foreign_currency_id'] !== $this->primaryCurrency->id
             ) {
                 $key    = sprintf('%d-%d', $journal['category_id'], $this->primaryCurrency->id);
                 $symbol = $this->primaryCurrency->symbol;
@@ -327,7 +329,10 @@ class BudgetController extends Controller
                 $amount = $journal['pc_amount'];
             }
 
-            if ($this->convertToPrimary && $journal['currency_id'] !== $this->primaryCurrency->id && $journal['foreign_currency_id'] === $this->primaryCurrency->id
+            if (
+                $this->convertToPrimary
+                && $journal['currency_id'] !== $this->primaryCurrency->id
+                && $journal['foreign_currency_id'] === $this->primaryCurrency->id
             ) {
                 $key    = sprintf('%d-%d', $journal['category_id'], $this->primaryCurrency->id);
                 $symbol = $this->primaryCurrency->symbol;
@@ -336,27 +341,22 @@ class BudgetController extends Controller
                 $amount = $journal['foreign_amount'];
             }
 
-            $result[$key] ??= [
-                'amount'          => '0',
-                'currency_symbol' => $symbol,
-                'currency_code'   => $code,
-                'currency_name'   => $name,
-            ];
+            $result[$key] ??= ['amount'          => '0', 'currency_symbol' => $symbol, 'currency_code'   => $code, 'currency_name'   => $name];
             $result[$key]['amount'] = bcadd((string) $amount, $result[$key]['amount']);
         }
 
-        $names         = $this->getCategoryNames(array_keys($result));
+        $names = $this->getCategoryNames(array_keys($result));
         foreach ($result as $combinedId => $info) {
-            $parts             = explode('-', $combinedId);
-            $categoryId        = (int) $parts[0];
-            $title             = sprintf('%s (%s)', $names[$categoryId] ?? '(empty)', $info['currency_name']);
+            $parts      = explode('-', $combinedId);
+            $categoryId = (int) $parts[0];
+            $title      = sprintf('%s (%s)', $names[$categoryId] ?? '(empty)', $info['currency_name']);
             $chartData[$title] = [
                 'amount'          => $info['amount'],
                 'currency_symbol' => $info['currency_symbol'],
-                'currency_code'   => $info['currency_code'],
+                'currency_code'   => $info['currency_code']
             ];
         }
-        $data          = $this->generator->multiCurrencyPieChart($chartData);
+        $data = $this->generator->multiCurrencyPieChart($chartData);
         $cache->store($data);
 
         return response()->json($data);
@@ -365,7 +365,7 @@ class BudgetController extends Controller
     /**
      * Shows how much is spent per expense account.
      */
-    public function expenseExpense(Budget $budget, ?BudgetLimit $budgetLimit = null): JsonResponse
+    public function expenseExpense(Budget $budget, null|BudgetLimit $budgetLimit = null): JsonResponse
     {
         /** @var GroupCollectorInterface $collector */
         $collector     = app(GroupCollectorInterface::class);
@@ -375,8 +375,8 @@ class BudgetController extends Controller
         $cache->addProperty($budgetLimitId);
         $cache->addProperty($this->convertToPrimary);
         $cache->addProperty('chart.budget.expense-expense');
-        $start         = session('first', today(config('app.timezone'))->startOfYear());
-        $end           = today();
+        $start = session('first', today(config('app.timezone'))->startOfYear());
+        $end   = today();
         if ($budgetLimit instanceof BudgetLimit) {
             $start = $budgetLimit->start_date;
             $end   = $budgetLimit->end_date;
@@ -390,20 +390,24 @@ class BudgetController extends Controller
         }
         $collector->setRange($start, $end);
         $collector->setTypes([TransactionTypeEnum::WITHDRAWAL->value])->setBudget($budget)->withAccountInformation();
-        $journals      = $collector->getExtractedJournals();
-        $result        = [];
-        $chartData     = [];
+        $journals  = $collector->getExtractedJournals();
+        $result    = [];
+        $chartData = [];
 
         /** @var array $journal */
         foreach ($journals as $journal) {
-            $key                    = sprintf('%d-%d', $journal['destination_account_id'], $journal['currency_id']);
-            $amount                 = $journal['amount'];
-            $symbol                 = $journal['currency_symbol'];
-            $code                   = $journal['currency_code'];
-            $name                   = $journal['currency_name'];
+            $key    = sprintf('%d-%d', $journal['destination_account_id'], $journal['currency_id']);
+            $amount = $journal['amount'];
+            $symbol = $journal['currency_symbol'];
+            $code   = $journal['currency_code'];
+            $name   = $journal['currency_name'];
 
             // if convert to primary, use the primary things, unless it's the foreign amount which is in the primary currency.
-            if ($this->convertToPrimary && $journal['currency_id'] !== $this->primaryCurrency->id && $journal['foreign_currency_id'] !== $this->primaryCurrency->id) {
+            if (
+                $this->convertToPrimary
+                && $journal['currency_id'] !== $this->primaryCurrency->id
+                && $journal['foreign_currency_id'] !== $this->primaryCurrency->id
+            ) {
                 $key    = sprintf('%d-%d', $journal['destination_account_id'], $this->primaryCurrency->id);
                 $symbol = $this->primaryCurrency->symbol;
                 $code   = $this->primaryCurrency->code;
@@ -411,7 +415,11 @@ class BudgetController extends Controller
                 $amount = $journal['pc_amount'];
             }
 
-            if ($this->convertToPrimary && $journal['currency_id'] !== $this->primaryCurrency->id && $journal['foreign_currency_id'] === $this->primaryCurrency->id) {
+            if (
+                $this->convertToPrimary
+                && $journal['currency_id'] !== $this->primaryCurrency->id
+                && $journal['foreign_currency_id'] === $this->primaryCurrency->id
+            ) {
                 $key    = sprintf('%d-%d', $journal['destination_account_id'], $this->primaryCurrency->id);
                 $symbol = $this->primaryCurrency->symbol;
                 $code   = $this->primaryCurrency->code;
@@ -419,29 +427,24 @@ class BudgetController extends Controller
                 $amount = $journal['foreign_amount'];
             }
 
-            $result[$key] ??= [
-                'amount'          => '0',
-                'currency_symbol' => $symbol,
-                'currency_code'   => $code,
-                'currency_name'   => $name,
-            ];
+            $result[$key] ??= ['amount'          => '0', 'currency_symbol' => $symbol, 'currency_code'   => $code, 'currency_name'   => $name];
             $result[$key]['amount'] = bcadd((string) $amount, $result[$key]['amount']);
         }
 
-        $names         = $this->getAccountNames(array_keys($result));
+        $names = $this->getAccountNames(array_keys($result));
         foreach ($result as $combinedId => $info) {
-            $parts             = explode('-', $combinedId);
-            $opposingId        = (int) $parts[0];
-            $name              = $names[$opposingId] ?? 'no name';
-            $title             = sprintf('%s (%s)', $name, $info['currency_name']);
+            $parts      = explode('-', $combinedId);
+            $opposingId = (int) $parts[0];
+            $name       = $names[$opposingId] ?? 'no name';
+            $title      = sprintf('%s (%s)', $name, $info['currency_name']);
             $chartData[$title] = [
                 'amount'          => $info['amount'],
                 'currency_symbol' => $info['currency_symbol'],
-                'currency_code'   => $info['currency_code'],
+                'currency_code'   => $info['currency_code']
             ];
         }
 
-        $data          = $this->generator->multiCurrencyPieChart($chartData);
+        $data = $this->generator->multiCurrencyPieChart($chartData);
         $cache->store($data);
 
         return response()->json($data);
@@ -452,10 +455,10 @@ class BudgetController extends Controller
      */
     public function frontpage(): JsonResponse
     {
-        $start                            = session('start', today(config('app.timezone'))->startOfMonth());
-        $end                              = session('end', today(config('app.timezone'))->endOfMonth());
+        $start = session('start', today(config('app.timezone'))->startOfMonth());
+        $end   = session('end', today(config('app.timezone'))->endOfMonth());
         // chart properties for cache:
-        $cache                            = new CacheProperties();
+        $cache = new CacheProperties();
         $cache->addProperty($start);
         $cache->addProperty($end);
         $cache->addProperty($this->convertToPrimary);
@@ -464,15 +467,15 @@ class BudgetController extends Controller
             return response()->json($cache->get());
         }
         Log::debug('Regenerate frontpage chart from scratch.');
-        $chartGenerator                   = app(FrontpageChartGenerator::class);
+        $chartGenerator = app(FrontpageChartGenerator::class);
         $chartGenerator->setUser(auth()->user());
         $chartGenerator->setStart($start);
         $chartGenerator->setEnd($end);
         $chartGenerator->convertToPrimary = $this->convertToPrimary;
-        $chartGenerator->default          = $this->primaryCurrency;
+        $chartGenerator->default = $this->primaryCurrency;
 
-        $chartData                        = $chartGenerator->generate();
-        $data                             = $this->generator->multiSet($chartData);
+        $chartData = $chartGenerator->generate();
+        $data      = $this->generator->multiSet($chartData);
         $cache->store($data);
 
         return response()->json($data);
@@ -488,7 +491,7 @@ class BudgetController extends Controller
     public function period(Budget $budget, TransactionCurrency $currency, Collection $accounts, Carbon $start, Carbon $end): JsonResponse
     {
         // chart properties for cache:
-        $cache          = new CacheProperties();
+        $cache = new CacheProperties();
         $cache->addProperty($start);
         $cache->addProperty($end);
         $cache->addProperty($accounts);
@@ -502,26 +505,26 @@ class BudgetController extends Controller
         $preferredRange = Navigation::preferredRangeFormat($start, $end);
         $chartData      = [
             [
-                'label'           => (string) trans('firefly.box_spent_in_currency', ['currency' => $currency->name]),
+                'label'           => (string) trans('firefly.box_spent_in_currency', ['currency'           => $currency->name]),
                 'type'            => 'bar',
                 'entries'         => [],
                 'currency_symbol' => $currency->symbol,
-                'currency_code'   => $currency->code,
+                'currency_code'   => $currency->code
             ],
             [
-                'label'           => (string) trans('firefly.box_budgeted_in_currency', ['currency' => $currency->name]),
+                'label'           => (string) trans('firefly.box_budgeted_in_currency', ['currency'           => $currency->name]),
                 'type'            => 'bar',
                 'currency_symbol' => $currency->symbol,
                 'currency_code'   => $currency->code,
-                'entries'         => [],
-            ],
+                'entries'         => []
+            ]
         ];
 
-        $currentStart   = clone $start;
+        $currentStart = clone $start;
         while ($currentStart <= $end) {
-            $currentStart                    = Navigation::startOfPeriod($currentStart, $preferredRange);
-            $title                           = $currentStart->isoFormat($titleFormat);
-            $currentEnd                      = Navigation::endOfPeriod($currentStart, $preferredRange);
+            $currentStart = Navigation::startOfPeriod($currentStart, $preferredRange);
+            $title        = $currentStart->isoFormat($titleFormat);
+            $currentEnd   = Navigation::endOfPeriod($currentStart, $preferredRange);
 
             // default limit is no limit:
             $chartData[0]['entries'][$title] = 0;
@@ -530,21 +533,21 @@ class BudgetController extends Controller
             $chartData[1]['entries'][$title] = 0;
 
             // get budget limit in this period for this currency.
-            $limit                           = $this->blRepository->find($budget, $currency, $currentStart, $currentEnd);
+            $limit = $this->blRepository->find($budget, $currency, $currentStart, $currentEnd);
             if ($limit instanceof BudgetLimit) {
                 $chartData[1]['entries'][$title] = Steam::bcround($limit->amount, $currency->decimal_places);
             }
 
             // get spent amount in this period for this currency.
-            $sum                             = $this->opsRepository->sumExpenses($currentStart, $currentEnd, $accounts, new Collection()->push($budget), $currency);
-            $amount                          = Steam::positive($sum[$currency->id]['sum'] ?? '0');
+            $sum    = $this->opsRepository->sumExpenses($currentStart, $currentEnd, $accounts, new Collection()->push($budget), $currency);
+            $amount = Steam::positive($sum[$currency->id]['sum'] ?? '0');
             $chartData[0]['entries'][$title] = Steam::bcround($amount, $currency->decimal_places);
 
-            $currentStart                    = clone $currentEnd;
+            $currentStart = clone $currentEnd;
             $currentStart->addDay()->startOfDay();
         }
 
-        $data           = $this->generator->multiSet($chartData);
+        $data = $this->generator->multiSet($chartData);
         $cache->store($data);
 
         return response()->json($data);
@@ -556,7 +559,7 @@ class BudgetController extends Controller
     public function periodNoBudget(TransactionCurrency $currency, Collection $accounts, Carbon $start, Carbon $end): JsonResponse
     {
         // chart properties for cache:
-        $cache          = new CacheProperties();
+        $cache = new CacheProperties();
         $cache->addProperty($start);
         $cache->addProperty($end);
         $cache->addProperty($accounts);
@@ -572,15 +575,15 @@ class BudgetController extends Controller
         $currentStart   = clone $start;
         $preferredRange = Navigation::preferredRangeFormat($start, $end);
         while ($currentStart <= $end) {
-            $currentEnd        = Navigation::endOfPeriod($currentStart, $preferredRange);
-            $title             = $currentStart->isoFormat($titleFormat);
-            $sum               = $this->nbRepository->sumExpenses($currentStart, $currentEnd, $accounts, $currency);
-            $amount            = Steam::positive($sum[$currency->id]['sum'] ?? '0');
+            $currentEnd = Navigation::endOfPeriod($currentStart, $preferredRange);
+            $title      = $currentStart->isoFormat($titleFormat);
+            $sum        = $this->nbRepository->sumExpenses($currentStart, $currentEnd, $accounts, $currency);
+            $amount     = Steam::positive($sum[$currency->id]['sum'] ?? '0');
             $chartData[$title] = Steam::bcround($amount, $currency->decimal_places);
-            $currentStart      = Navigation::addPeriod($currentStart, $preferredRange, 0);
+            $currentStart = Navigation::addPeriod($currentStart, $preferredRange, 0);
         }
 
-        $data           = $this->generator->singleSet((string) trans('firefly.spent'), $chartData);
+        $data = $this->generator->singleSet((string) trans('firefly.spent'), $chartData);
         $cache->store($data);
 
         return response()->json($data);
diff --git a/app/Http/Controllers/Chart/BudgetReportController.php b/app/Http/Controllers/Chart/BudgetReportController.php
index 9e66271b11..6a4906b90c 100644
--- a/app/Http/Controllers/Chart/BudgetReportController.php
+++ b/app/Http/Controllers/Chart/BudgetReportController.php
@@ -58,14 +58,12 @@ class BudgetReportController extends Controller
     public function __construct()
     {
         parent::__construct();
-        $this->middleware(
-            function ($request, $next) {
-                $this->generator     = app(GeneratorInterface::class);
-                $this->opsRepository = app(OperationsRepositoryInterface::class);
+        $this->middleware(function ($request, $next) {
+            $this->generator = app(GeneratorInterface::class);
+            $this->opsRepository = app(OperationsRepositoryInterface::class);
 
-                return $next($request);
-            }
-        );
+            return $next($request);
+        });
     }
 
     /**
@@ -83,16 +81,16 @@ class BudgetReportController extends Controller
                 $result[$title] ??= [
                     'amount'          => '0',
                     'currency_symbol' => $currency['currency_symbol'],
-                    'currency_code'   => $currency['currency_code'],
+                    'currency_code'   => $currency['currency_code']
                 ];
                 foreach ($budget['transaction_journals'] as $journal) {
-                    $amount                   = Steam::positive($journal['amount']);
+                    $amount = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data   = $this->generator->multiCurrencyPieChart($result);
+        $data = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -108,21 +106,21 @@ class BudgetReportController extends Controller
         foreach ($spent as $currency) {
             foreach ($currency['budgets'] as $budget) {
                 foreach ($budget['transaction_journals'] as $journal) {
-                    $categoryName             = $journal['category_name'] ?? trans('firefly.no_category');
-                    $title                    = sprintf('%s (%s)', $categoryName, $currency['currency_name']);
+                    $categoryName = $journal['category_name'] ?? trans('firefly.no_category');
+                    $title        = sprintf('%s (%s)', $categoryName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code'],
+                        'currency_code'   => $currency['currency_code']
                     ];
 
-                    $amount                   = Steam::positive($journal['amount']);
+                    $amount = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data   = $this->generator->multiCurrencyPieChart($result);
+        $data = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -139,20 +137,20 @@ class BudgetReportController extends Controller
         foreach ($spent as $currency) {
             foreach ($currency['budgets'] as $budget) {
                 foreach ($budget['transaction_journals'] as $journal) {
-                    $title                    = sprintf('%s (%s)', $journal['destination_account_name'], $currency['currency_name']);
+                    $title = sprintf('%s (%s)', $journal['destination_account_name'], $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code'],
+                        'currency_code'   => $currency['currency_code']
                     ];
 
-                    $amount                   = Steam::positive($journal['amount']);
+                    $amount = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data   = $this->generator->multiCurrencyPieChart($result);
+        $data = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -173,27 +171,27 @@ class BudgetReportController extends Controller
             $chartData[$spentKey] ??= [
                 'label'           => sprintf(
                     '%s (%s)',
-                    (string) trans('firefly.spent_in_specific_budget', ['budget' => $budget->name]),
+                    (string) trans('firefly.spent_in_specific_budget', ['budget'           => $budget->name]),
                     $currency['currency_name']
                 ),
                 'type'            => 'bar',
                 'currency_symbol' => $currency['currency_symbol'],
                 'currency_code'   => $currency['currency_code'],
                 'currency_id'     => $currency['currency_id'],
-                'entries'         => $this->makeEntries($start, $end),
+                'entries'         => $this->makeEntries($start, $end)
             ];
 
             foreach ($currency['budgets'] as $currentBudget) {
                 foreach ($currentBudget['transaction_journals'] as $journal) {
-                    $key                                   = $journal['date']->isoFormat($format);
-                    $amount                                = Steam::positive($journal['amount']);
+                    $key    = $journal['date']->isoFormat($format);
+                    $amount = Steam::positive($journal['amount']);
                     $chartData[$spentKey]['entries'][$key] ??= '0';
                     $chartData[$spentKey]['entries'][$key] = bcadd($chartData[$spentKey]['entries'][$key], $amount);
                 }
             }
         }
 
-        $data      = $this->generator->multiSet($chartData);
+        $data = $this->generator->multiSet($chartData);
 
         return response()->json($data);
     }
@@ -205,8 +203,8 @@ class BudgetReportController extends Controller
         $preferredRange = Navigation::preferredRangeFormat($start, $end);
         $currentStart   = clone $start;
         while ($currentStart <= $end) {
-            $currentEnd   = Navigation::endOfPeriod($currentStart, $preferredRange);
-            $key          = $currentStart->isoFormat($format);
+            $currentEnd = Navigation::endOfPeriod($currentStart, $preferredRange);
+            $key        = $currentStart->isoFormat($format);
             $return[$key] = '0';
             $currentStart = clone $currentEnd;
             $currentStart->addDay()->startOfDay();
@@ -227,20 +225,20 @@ class BudgetReportController extends Controller
         foreach ($spent as $currency) {
             foreach ($currency['budgets'] as $budget) {
                 foreach ($budget['transaction_journals'] as $journal) {
-                    $title                    = sprintf('%s (%s)', $journal['source_account_name'], $currency['currency_name']);
+                    $title = sprintf('%s (%s)', $journal['source_account_name'], $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code'],
+                        'currency_code'   => $currency['currency_code']
                     ];
 
-                    $amount                   = Steam::positive($journal['amount']);
+                    $amount = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data   = $this->generator->multiCurrencyPieChart($result);
+        $data = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
diff --git a/app/Http/Controllers/Chart/CategoryController.php b/app/Http/Controllers/Chart/CategoryController.php
index 8dbd4db7d4..d3b61dad2c 100644
--- a/app/Http/Controllers/Chart/CategoryController.php
+++ b/app/Http/Controllers/Chart/CategoryController.php
@@ -23,7 +23,6 @@ declare(strict_types=1);
 
 namespace FireflyIII\Http\Controllers\Chart;
 
-use FireflyIII\Support\Facades\Navigation;
 use Carbon\Carbon;
 use FireflyIII\Generator\Chart\Basic\GeneratorInterface;
 use FireflyIII\Http\Controllers\Controller;
@@ -34,6 +33,7 @@ use FireflyIII\Repositories\Category\OperationsRepositoryInterface;
 use FireflyIII\Support\CacheProperties;
 use FireflyIII\Support\Chart\Category\FrontpageChartGenerator;
 use FireflyIII\Support\Chart\Category\WholePeriodChartGenerator;
+use FireflyIII\Support\Facades\Navigation;
 use FireflyIII\Support\Facades\Steam;
 use FireflyIII\Support\Http\Controllers\AugumentData;
 use FireflyIII\Support\Http\Controllers\ChartGeneration;
@@ -71,7 +71,7 @@ class CategoryController extends Controller
     public function all(Category $category): JsonResponse
     {
         // cache results:
-        $cache                            = new CacheProperties();
+        $cache = new CacheProperties();
         $cache->addProperty('chart.category.all');
         $cache->addProperty($category->id);
         $cache->addProperty($this->convertToPrimary);
@@ -80,18 +80,18 @@ class CategoryController extends Controller
         }
 
         /** @var CategoryRepositoryInterface $repository */
-        $repository                       = app(CategoryRepositoryInterface::class);
-        $start                            = $repository->firstUseDate($category) ?? $this->getDate();
-        $range                            = Navigation::getViewRange(false);
-        $start                            = Navigation::startOfPeriod($start, $range);
-        $end                              = $this->getDate();
+        $repository = app(CategoryRepositoryInterface::class);
+        $start      = $repository->firstUseDate($category) ?? $this->getDate();
+        $range      = Navigation::getViewRange(false);
+        $start      = Navigation::startOfPeriod($start, $range);
+        $end        = $this->getDate();
 
         /** @var WholePeriodChartGenerator $chartGenerator */
-        $chartGenerator                   = app(WholePeriodChartGenerator::class);
+        $chartGenerator = app(WholePeriodChartGenerator::class);
         $chartGenerator->convertToPrimary = $this->convertToPrimary;
 
-        $chartData                        = $chartGenerator->generate($category, $start, $end);
-        $data                             = $this->generator->multiSet($chartData);
+        $chartData = $chartGenerator->generate($category, $start, $end);
+        $data      = $this->generator->multiSet($chartData);
         $cache->store($data);
 
         return response()->json($data);
@@ -108,10 +108,10 @@ class CategoryController extends Controller
      */
     public function frontPage(): JsonResponse
     {
-        $start              = session('start', today(config('app.timezone'))->startOfMonth());
-        $end                = session('end', today(config('app.timezone'))->endOfMonth());
+        $start = session('start', today(config('app.timezone'))->startOfMonth());
+        $end   = session('end', today(config('app.timezone'))->endOfMonth());
         // chart properties for cache:
-        $cache              = new CacheProperties();
+        $cache = new CacheProperties();
         $cache->addProperty($start);
         $cache->addProperty($end);
         $cache->addProperty($this->convertToPrimary);
@@ -144,7 +144,7 @@ class CategoryController extends Controller
         if ($cache->has()) {
             return response()->json($cache->get());
         }
-        $data  = $this->reportPeriodChart($accounts, $start, $end, $category);
+        $data = $this->reportPeriodChart($accounts, $start, $end, $category);
 
         $cache->store($data);
 
@@ -154,9 +154,8 @@ class CategoryController extends Controller
     /**
      * Generate report chart for either with or without category.
      */
-    private function reportPeriodChart(Collection $accounts, Carbon $start, Carbon $end, ?Category $category): array
+    private function reportPeriodChart(Collection $accounts, Carbon $start, Carbon $end, null|Category $category): array
     {
-
         $income     = [];
         $expenses   = [];
         $categoryId = 0;
@@ -165,8 +164,8 @@ class CategoryController extends Controller
             $noCatRepository = app(NoCategoryRepositoryInterface::class);
 
             // this gives us all currencies
-            $expenses        = $noCatRepository->listExpenses($start, $end, $accounts);
-            $income          = $noCatRepository->listIncome($start, $end, $accounts);
+            $expenses = $noCatRepository->listExpenses($start, $end, $accounts);
+            $income   = $noCatRepository->listIncome($start, $end, $accounts);
         }
 
         if ($category instanceof Category) {
@@ -174,9 +173,9 @@ class CategoryController extends Controller
             $opsRepository = app(OperationsRepositoryInterface::class);
             $categoryId    = $category->id;
             // this gives us all currencies
-            $collection    = new Collection()->push($category);
-            $expenses      = $opsRepository->listExpenses($start, $end, $accounts, $collection);
-            $income        = $opsRepository->listIncome($start, $end, $accounts, $collection);
+            $collection = new Collection()->push($category);
+            $expenses   = $opsRepository->listExpenses($start, $end, $accounts, $collection);
+            $income     = $opsRepository->listIncome($start, $end, $accounts, $collection);
         }
         $currencies = array_unique(array_merge(array_keys($income), array_keys($expenses)));
         $periods    = Navigation::listOfPeriods($start, $end);
@@ -188,41 +187,39 @@ class CategoryController extends Controller
             $currencyInfo = $expenses[$currencyId] ?? $income[$currencyId];
             $outKey       = sprintf('%d-out', $currencyId);
             $inKey        = sprintf('%d-in', $currencyId);
-            $chartData[$outKey]
-                          = [
-                              'label'           => sprintf('%s (%s)', (string) trans('firefly.spent'), $currencyInfo['currency_name']),
-                              'entries'         => [],
-                              'type'            => 'bar',
-                              'backgroundColor' => 'rgba(219, 68, 55, 0.5)', // red
-                          ];
+            $chartData[$outKey] = [
+                'label'           => sprintf('%s (%s)', (string) trans('firefly.spent'), $currencyInfo['currency_name']),
+                'entries'         => [],
+                'type'            => 'bar',
+                'backgroundColor' => 'rgba(219, 68, 55, 0.5)' // red
+            ];
 
-            $chartData[$inKey]
-                          = [
-                              'label'           => sprintf('%s (%s)', (string) trans('firefly.earned'), $currencyInfo['currency_name']),
-                              'entries'         => [],
-                              'type'            => 'bar',
-                              'backgroundColor' => 'rgba(0, 141, 76, 0.5)', // green
-                          ];
+            $chartData[$inKey] = [
+                'label'           => sprintf('%s (%s)', (string) trans('firefly.earned'), $currencyInfo['currency_name']),
+                'entries'         => [],
+                'type'            => 'bar',
+                'backgroundColor' => 'rgba(0, 141, 76, 0.5)' // green
+            ];
             // loop empty periods:
             foreach (array_keys($periods) as $period) {
-                $label                                 = $periods[$period];
+                $label = $periods[$period];
                 $chartData[$outKey]['entries'][$label] = '0';
-                $chartData[$inKey]['entries'][$label]  = '0';
+                $chartData[$inKey]['entries'][$label] = '0';
             }
             // loop income and expenses for this category.:
-            $outSet       = $expenses[$currencyId]['categories'][$categoryId] ?? ['transaction_journals' => []];
+            $outSet = $expenses[$currencyId]['categories'][$categoryId] ?? ['transaction_journals' => []];
             foreach ($outSet['transaction_journals'] as $journal) {
-                $amount                               = Steam::positive($journal['amount']);
-                $date                                 = $journal['date']->isoFormat($format);
+                $amount = Steam::positive($journal['amount']);
+                $date   = $journal['date']->isoFormat($format);
                 $chartData[$outKey]['entries'][$date] ??= '0';
 
                 $chartData[$outKey]['entries'][$date] = bcadd($amount, $chartData[$outKey]['entries'][$date]);
             }
 
-            $inSet        = $income[$currencyId]['categories'][$categoryId] ?? ['transaction_journals' => []];
+            $inSet = $income[$currencyId]['categories'][$categoryId] ?? ['transaction_journals' => []];
             foreach ($inSet['transaction_journals'] as $journal) {
-                $amount                              = Steam::positive($journal['amount']);
-                $date                                = $journal['date']->isoFormat($format);
+                $amount = Steam::positive($journal['amount']);
+                $date   = $journal['date']->isoFormat($format);
                 $chartData[$inKey]['entries'][$date] ??= '0';
                 $chartData[$inKey]['entries'][$date] = bcadd($amount, $chartData[$inKey]['entries'][$date]);
             }
@@ -245,7 +242,7 @@ class CategoryController extends Controller
         if ($cache->has()) {
             return response()->json($cache->get());
         }
-        $data  = $this->reportPeriodChart($accounts, $start, $end, null);
+        $data = $this->reportPeriodChart($accounts, $start, $end, null);
 
         $cache->store($data);
 
@@ -261,14 +258,14 @@ class CategoryController extends Controller
      */
     public function specificPeriod(Category $category, Carbon $date): JsonResponse
     {
-        $range          = Navigation::getViewRange(false);
-        $start          = Navigation::startOfPeriod($date, $range);
-        $end            = session()->get('end');
+        $range = Navigation::getViewRange(false);
+        $start = Navigation::startOfPeriod($date, $range);
+        $end   = session()->get('end');
         if ($end < $start) {
             [$end, $start] = [$start, $end];
         }
 
-        $cache          = new CacheProperties();
+        $cache = new CacheProperties();
         $cache->addProperty($start);
         $cache->addProperty($end);
         $cache->addProperty($category->id);
diff --git a/app/Http/Controllers/Chart/CategoryReportController.php b/app/Http/Controllers/Chart/CategoryReportController.php
index 9cce66c5d4..67900c27b6 100644
--- a/app/Http/Controllers/Chart/CategoryReportController.php
+++ b/app/Http/Controllers/Chart/CategoryReportController.php
@@ -23,12 +23,12 @@ declare(strict_types=1);
 
 namespace FireflyIII\Http\Controllers\Chart;
 
-use FireflyIII\Support\Facades\Navigation;
 use Carbon\Carbon;
 use FireflyIII\Generator\Chart\Basic\GeneratorInterface;
 use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\Models\Category;
 use FireflyIII\Repositories\Category\OperationsRepositoryInterface;
+use FireflyIII\Support\Facades\Navigation;
 use FireflyIII\Support\Facades\Steam;
 use FireflyIII\Support\Http\Controllers\AugumentData;
 use FireflyIII\Support\Http\Controllers\TransactionCalculation;
@@ -57,14 +57,12 @@ class CategoryReportController extends Controller
     public function __construct()
     {
         parent::__construct();
-        $this->middleware(
-            function ($request, $next) {
-                $this->generator     = app(GeneratorInterface::class);
-                $this->opsRepository = app(OperationsRepositoryInterface::class);
+        $this->middleware(function ($request, $next) {
+            $this->generator = app(GeneratorInterface::class);
+            $this->opsRepository = app(OperationsRepositoryInterface::class);
 
-                return $next($request);
-            }
-        );
+            return $next($request);
+        });
     }
 
     public function budgetExpense(Collection $accounts, Collection $categories, Carbon $start, Carbon $end): JsonResponse
@@ -77,20 +75,20 @@ class CategoryReportController extends Controller
             /** @var array $category */
             foreach ($currency['categories'] as $category) {
                 foreach ($category['transaction_journals'] as $journal) {
-                    $objectName               = $journal['budget_name'] ?? trans('firefly.no_budget');
-                    $title                    = sprintf('%s (%s)', $objectName, $currency['currency_name']);
+                    $objectName = $journal['budget_name'] ?? trans('firefly.no_budget');
+                    $title      = sprintf('%s (%s)', $objectName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code'],
+                        'currency_code'   => $currency['currency_code']
                     ];
-                    $amount                   = Steam::positive($journal['amount']);
+                    $amount = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data   = $this->generator->multiCurrencyPieChart($result);
+        $data = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -108,23 +106,22 @@ class CategoryReportController extends Controller
                 $result[$title] ??= [
                     'amount'          => '0',
                     'currency_symbol' => $currency['currency_symbol'],
-                    'currency_code'   => $currency['currency_code'],
+                    'currency_code'   => $currency['currency_code']
                 ];
                 foreach ($category['transaction_journals'] as $journal) {
-                    $amount                   = Steam::positive($journal['amount']);
+                    $amount = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data   = $this->generator->multiCurrencyPieChart($result);
+        $data = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
 
     public function categoryIncome(Collection $accounts, Collection $categories, Carbon $start, Carbon $end): JsonResponse
     {
-
         $result = [];
         $earned = $this->opsRepository->listIncome($start, $end, $accounts, $categories);
 
@@ -136,16 +133,16 @@ class CategoryReportController extends Controller
                 $result[$title] ??= [
                     'amount'          => '0',
                     'currency_symbol' => $currency['currency_symbol'],
-                    'currency_code'   => $currency['currency_code'],
+                    'currency_code'   => $currency['currency_code']
                 ];
                 foreach ($category['transaction_journals'] as $journal) {
-                    $amount                   = Steam::positive($journal['amount']);
+                    $amount = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data   = $this->generator->multiCurrencyPieChart($result);
+        $data = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -160,20 +157,20 @@ class CategoryReportController extends Controller
             /** @var array $category */
             foreach ($currency['categories'] as $category) {
                 foreach ($category['transaction_journals'] as $journal) {
-                    $objectName               = $journal['destination_account_name'] ?? trans('firefly.empty');
-                    $title                    = sprintf('%s (%s)', $objectName, $currency['currency_name']);
+                    $objectName = $journal['destination_account_name'] ?? trans('firefly.empty');
+                    $title      = sprintf('%s (%s)', $objectName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code'],
+                        'currency_code'   => $currency['currency_code']
                     ];
-                    $amount                   = Steam::positive($journal['amount']);
+                    $amount = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data   = $this->generator->multiCurrencyPieChart($result);
+        $data = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -188,20 +185,20 @@ class CategoryReportController extends Controller
             /** @var array $category */
             foreach ($currency['categories'] as $category) {
                 foreach ($category['transaction_journals'] as $journal) {
-                    $objectName               = $journal['destination_account_name'] ?? trans('firefly.empty');
-                    $title                    = sprintf('%s (%s)', $objectName, $currency['currency_name']);
+                    $objectName = $journal['destination_account_name'] ?? trans('firefly.empty');
+                    $title      = sprintf('%s (%s)', $objectName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code'],
+                        'currency_code'   => $currency['currency_code']
                     ];
-                    $amount                   = Steam::positive($journal['amount']);
+                    $amount = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data   = $this->generator->multiCurrencyPieChart($result);
+        $data = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -219,20 +216,20 @@ class CategoryReportController extends Controller
             $chartData[$spentKey] ??= [
                 'label'           => sprintf(
                     '%s (%s)',
-                    (string) trans('firefly.spent_in_specific_category', ['category' => $category->name]),
+                    (string) trans('firefly.spent_in_specific_category', ['category'           => $category->name]),
                     $currency['currency_name']
                 ),
                 'type'            => 'bar',
                 'currency_symbol' => $currency['currency_symbol'],
                 'currency_code'   => $currency['currency_code'],
                 'currency_id'     => $currency['currency_id'],
-                'entries'         => $this->makeEntries($start, $end),
+                'entries'         => $this->makeEntries($start, $end)
             ];
 
             foreach ($currency['categories'] as $currentCategory) {
                 foreach ($currentCategory['transaction_journals'] as $journal) {
-                    $key                                   = $journal['date']->isoFormat($format);
-                    $amount                                = Steam::positive($journal['amount']);
+                    $key    = $journal['date']->isoFormat($format);
+                    $amount = Steam::positive($journal['amount']);
                     $chartData[$spentKey]['entries'][$key] ??= '0';
                     $chartData[$spentKey]['entries'][$key] = bcadd($chartData[$spentKey]['entries'][$key], $amount);
                 }
@@ -246,27 +243,27 @@ class CategoryReportController extends Controller
             $chartData[$spentKey] ??= [
                 'label'           => sprintf(
                     '%s (%s)',
-                    (string) trans('firefly.earned_in_specific_category', ['category' => $category->name]),
+                    (string) trans('firefly.earned_in_specific_category', ['category'           => $category->name]),
                     $currency['currency_name']
                 ),
                 'type'            => 'bar',
                 'currency_symbol' => $currency['currency_symbol'],
                 'currency_code'   => $currency['currency_code'],
                 'currency_id'     => $currency['currency_id'],
-                'entries'         => $this->makeEntries($start, $end),
+                'entries'         => $this->makeEntries($start, $end)
             ];
 
             foreach ($currency['categories'] as $currentCategory) {
                 foreach ($currentCategory['transaction_journals'] as $journal) {
-                    $key                                   = $journal['date']->isoFormat($format);
-                    $amount                                = Steam::positive($journal['amount']);
+                    $key    = $journal['date']->isoFormat($format);
+                    $amount = Steam::positive($journal['amount']);
                     $chartData[$spentKey]['entries'][$key] ??= '0';
                     $chartData[$spentKey]['entries'][$key] = bcadd($chartData[$spentKey]['entries'][$key], $amount);
                 }
             }
         }
 
-        $data      = $this->generator->multiSet($chartData);
+        $data = $this->generator->multiSet($chartData);
 
         return response()->json($data);
     }
@@ -281,8 +278,8 @@ class CategoryReportController extends Controller
         $preferredRange = Navigation::preferredRangeFormat($start, $end);
         $currentStart   = clone $start;
         while ($currentStart <= $end) {
-            $currentEnd   = Navigation::endOfPeriod($currentStart, $preferredRange);
-            $key          = $currentStart->isoFormat($format);
+            $currentEnd = Navigation::endOfPeriod($currentStart, $preferredRange);
+            $key        = $currentStart->isoFormat($format);
             $return[$key] = '0';
             $currentStart = clone $currentEnd;
             $currentStart->addDay()->startOfDay();
@@ -301,20 +298,20 @@ class CategoryReportController extends Controller
             /** @var array $category */
             foreach ($currency['categories'] as $category) {
                 foreach ($category['transaction_journals'] as $journal) {
-                    $objectName               = $journal['source_account_name'] ?? trans('firefly.empty');
-                    $title                    = sprintf('%s (%s)', $objectName, $currency['currency_name']);
+                    $objectName = $journal['source_account_name'] ?? trans('firefly.empty');
+                    $title      = sprintf('%s (%s)', $objectName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code'],
+                        'currency_code'   => $currency['currency_code']
                     ];
-                    $amount                   = Steam::positive($journal['amount']);
+                    $amount = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data   = $this->generator->multiCurrencyPieChart($result);
+        $data = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -329,20 +326,20 @@ class CategoryReportController extends Controller
             /** @var array $category */
             foreach ($currency['categories'] as $category) {
                 foreach ($category['transaction_journals'] as $journal) {
-                    $objectName               = $journal['source_account_name'] ?? trans('firefly.empty');
-                    $title                    = sprintf('%s (%s)', $objectName, $currency['currency_name']);
+                    $objectName = $journal['source_account_name'] ?? trans('firefly.empty');
+                    $title      = sprintf('%s (%s)', $objectName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code'],
+                        'currency_code'   => $currency['currency_code']
                     ];
-                    $amount                   = Steam::positive($journal['amount']);
+                    $amount = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data   = $this->generator->multiCurrencyPieChart($result);
+        $data = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
diff --git a/app/Http/Controllers/Chart/DoubleReportController.php b/app/Http/Controllers/Chart/DoubleReportController.php
index aa096abae2..fa7bead748 100644
--- a/app/Http/Controllers/Chart/DoubleReportController.php
+++ b/app/Http/Controllers/Chart/DoubleReportController.php
@@ -24,13 +24,13 @@ declare(strict_types=1);
 
 namespace FireflyIII\Http\Controllers\Chart;
 
-use FireflyIII\Support\Facades\Navigation;
 use Carbon\Carbon;
 use FireflyIII\Generator\Chart\Basic\GeneratorInterface;
 use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\Models\Account;
 use FireflyIII\Repositories\Account\AccountRepositoryInterface;
 use FireflyIII\Repositories\Account\OperationsRepositoryInterface;
+use FireflyIII\Support\Facades\Navigation;
 use FireflyIII\Support\Facades\Steam;
 use Illuminate\Http\JsonResponse;
 use Illuminate\Support\Collection;
@@ -55,15 +55,13 @@ class DoubleReportController extends Controller
     public function __construct()
     {
         parent::__construct();
-        $this->middleware(
-            function ($request, $next) {
-                $this->generator     = app(GeneratorInterface::class);
-                $this->opsRepository = app(OperationsRepositoryInterface::class);
-                $this->repository    = app(AccountRepositoryInterface::class);
+        $this->middleware(function ($request, $next) {
+            $this->generator = app(GeneratorInterface::class);
+            $this->opsRepository = app(OperationsRepositoryInterface::class);
+            $this->repository = app(AccountRepositoryInterface::class);
 
-                return $next($request);
-            }
-        );
+            return $next($request);
+        });
     }
 
     public function budgetExpense(Collection $accounts, Collection $others, Carbon $start, Carbon $end): JsonResponse
@@ -76,19 +74,19 @@ class DoubleReportController extends Controller
         // loop expenses.
         foreach ($expenses as $currency) {
             foreach ($currency['transaction_journals'] as $journal) {
-                $categoryName             = $journal['budget_name'] ?? trans('firefly.no_budget');
-                $title                    = sprintf('%s (%s)', $categoryName, $currency['currency_name']);
+                $categoryName = $journal['budget_name'] ?? trans('firefly.no_budget');
+                $title        = sprintf('%s (%s)', $categoryName, $currency['currency_name']);
                 $result[$title] ??= [
                     'amount'          => '0',
                     'currency_symbol' => $currency['currency_symbol'],
-                    'currency_code'   => $currency['currency_code'],
+                    'currency_code'   => $currency['currency_code']
                 ];
-                $amount                   = Steam::positive($journal['amount']);
+                $amount = Steam::positive($journal['amount']);
                 $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
             }
         }
 
-        $data     = $this->generator->multiCurrencyPieChart($result);
+        $data = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -103,19 +101,19 @@ class DoubleReportController extends Controller
         // loop expenses.
         foreach ($spent as $currency) {
             foreach ($currency['transaction_journals'] as $journal) {
-                $categoryName             = $journal['category_name'] ?? trans('firefly.no_category');
-                $title                    = sprintf('%s (%s)', $categoryName, $currency['currency_name']);
+                $categoryName = $journal['category_name'] ?? trans('firefly.no_category');
+                $title        = sprintf('%s (%s)', $categoryName, $currency['currency_name']);
                 $result[$title] ??= [
                     'amount'          => '0',
                     'currency_symbol' => $currency['currency_symbol'],
-                    'currency_code'   => $currency['currency_code'],
+                    'currency_code'   => $currency['currency_code']
                 ];
-                $amount                   = Steam::positive($journal['amount']);
+                $amount = Steam::positive($journal['amount']);
                 $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
             }
         }
 
-        $data     = $this->generator->multiCurrencyPieChart($result);
+        $data = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -130,19 +128,19 @@ class DoubleReportController extends Controller
         // loop income.
         foreach ($earned as $currency) {
             foreach ($currency['transaction_journals'] as $journal) {
-                $categoryName             = $journal['category_name'] ?? trans('firefly.no_category');
-                $title                    = sprintf('%s (%s)', $categoryName, $currency['currency_name']);
+                $categoryName = $journal['category_name'] ?? trans('firefly.no_category');
+                $title        = sprintf('%s (%s)', $categoryName, $currency['currency_name']);
                 $result[$title] ??= [
                     'amount'          => '0',
                     'currency_symbol' => $currency['currency_symbol'],
-                    'currency_code'   => $currency['currency_code'],
+                    'currency_code'   => $currency['currency_code']
                 ];
-                $amount                   = Steam::positive($journal['amount']);
+                $amount = Steam::positive($journal['amount']);
                 $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
             }
         }
 
-        $data     = $this->generator->multiCurrencyPieChart($result);
+        $data = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -151,11 +149,11 @@ class DoubleReportController extends Controller
     {
         $chartData = [];
 
-        $opposing  = $this->repository->expandWithDoubles(new Collection()->push($account));
-        $accounts  = $accounts->merge($opposing);
-        $spent     = $this->opsRepository->listExpenses($start, $end, $accounts);
-        $earned    = $this->opsRepository->listIncome($start, $end, $accounts);
-        $format    = Navigation::preferredCarbonLocalizedFormat($start, $end);
+        $opposing = $this->repository->expandWithDoubles(new Collection()->push($account));
+        $accounts = $accounts->merge($opposing);
+        $spent    = $this->opsRepository->listExpenses($start, $end, $accounts);
+        $earned   = $this->opsRepository->listIncome($start, $end, $accounts);
+        $format   = Navigation::preferredCarbonLocalizedFormat($start, $end);
 
         // loop expenses.
         foreach ($spent as $currency) {
@@ -166,19 +164,19 @@ class DoubleReportController extends Controller
             $chartData[$spentKey] ??= [
                 'label'           => sprintf(
                     '%s (%s)',
-                    (string) trans('firefly.spent_in_specific_double', ['account' => $name]),
+                    (string) trans('firefly.spent_in_specific_double', ['account'           => $name]),
                     $currency['currency_name']
                 ),
                 'type'            => 'bar',
                 'currency_symbol' => $currency['currency_symbol'],
                 'currency_code'   => $currency['currency_code'],
                 'currency_id'     => $currency['currency_id'],
-                'entries'         => $this->makeEntries($start, $end),
+                'entries'         => $this->makeEntries($start, $end)
             ];
 
             foreach ($currency['transaction_journals'] as $journal) {
-                $key                                   = $journal['date']->isoFormat($format);
-                $amount                                = Steam::positive($journal['amount']);
+                $key    = $journal['date']->isoFormat($format);
+                $amount = Steam::positive($journal['amount']);
                 $chartData[$spentKey]['entries'][$key] ??= '0';
                 $chartData[$spentKey]['entries'][$key] = bcadd($chartData[$spentKey]['entries'][$key], $amount);
             }
@@ -192,25 +190,25 @@ class DoubleReportController extends Controller
             $chartData[$earnedKey] ??= [
                 'label'           => sprintf(
                     '%s (%s)',
-                    (string) trans('firefly.earned_in_specific_double', ['account' => $name]),
+                    (string) trans('firefly.earned_in_specific_double', ['account'           => $name]),
                     $currency['currency_name']
                 ),
                 'type'            => 'bar',
                 'currency_symbol' => $currency['currency_symbol'],
                 'currency_code'   => $currency['currency_code'],
                 'currency_id'     => $currency['currency_id'],
-                'entries'         => $this->makeEntries($start, $end),
+                'entries'         => $this->makeEntries($start, $end)
             ];
 
             foreach ($currency['transaction_journals'] as $journal) {
-                $key                                    = $journal['date']->isoFormat($format);
-                $amount                                 = Steam::positive($journal['amount']);
+                $key    = $journal['date']->isoFormat($format);
+                $amount = Steam::positive($journal['amount']);
                 $chartData[$earnedKey]['entries'][$key] ??= '0';
                 $chartData[$earnedKey]['entries'][$key] = bcadd($chartData[$earnedKey]['entries'][$key], $amount);
             }
         }
 
-        $data      = $this->generator->multiSet($chartData);
+        $data = $this->generator->multiSet($chartData);
 
         return response()->json($data);
     }
@@ -218,7 +216,7 @@ class DoubleReportController extends Controller
     /**
      * TODO duplicate function
      */
-    private function getCounterpartName(Collection $accounts, int $id, string $name, ?string $iban): string
+    private function getCounterpartName(Collection $accounts, int $id, string $name, null|string $iban): string
     {
         /** @var Account $account */
         foreach ($accounts as $account) {
@@ -243,8 +241,8 @@ class DoubleReportController extends Controller
         $preferredRange = Navigation::preferredRangeFormat($start, $end);
         $currentStart   = clone $start;
         while ($currentStart <= $end) {
-            $currentEnd   = Navigation::endOfPeriod($currentStart, $preferredRange);
-            $key          = $currentStart->isoFormat($format);
+            $currentEnd = Navigation::endOfPeriod($currentStart, $preferredRange);
+            $key        = $currentStart->isoFormat($format);
             $return[$key] = '0';
             $currentStart = clone $currentEnd;
             $currentStart->addDay()->startOfDay();
@@ -267,16 +265,16 @@ class DoubleReportController extends Controller
 
                 // no tags? also deserves a sport
                 if (0 === count($journal['tags'])) {
-                    $includedJournals[]       = $journalId;
+                    $includedJournals[] = $journalId;
                     // do something
-                    $tagName                  = trans('firefly.no_tags');
-                    $title                    = sprintf('%s (%s)', $tagName, $currency['currency_name']);
+                    $tagName = trans('firefly.no_tags');
+                    $title   = sprintf('%s (%s)', $tagName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code'],
+                        'currency_code'   => $currency['currency_code']
                     ];
-                    $amount                   = Steam::positive($journal['amount']);
+                    $amount = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
 
@@ -286,22 +284,22 @@ class DoubleReportController extends Controller
                     if (in_array($journalId, $includedJournals, true)) {
                         continue;
                     }
-                    $includedJournals[]       = $journalId;
+                    $includedJournals[] = $journalId;
                     // do something
-                    $tagName                  = $tag['name'];
-                    $title                    = sprintf('%s (%s)', $tagName, $currency['currency_name']);
+                    $tagName = $tag['name'];
+                    $title   = sprintf('%s (%s)', $tagName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code'],
+                        'currency_code'   => $currency['currency_code']
                     ];
-                    $amount                   = Steam::positive($journal['amount']);
+                    $amount = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data             = $this->generator->multiCurrencyPieChart($result);
+        $data = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -320,16 +318,16 @@ class DoubleReportController extends Controller
 
                 // no tags? also deserves a sport
                 if (0 === count($journal['tags'])) {
-                    $includedJournals[]       = $journalId;
+                    $includedJournals[] = $journalId;
                     // do something
-                    $tagName                  = trans('firefly.no_tags');
-                    $title                    = sprintf('%s (%s)', $tagName, $currency['currency_name']);
+                    $tagName = trans('firefly.no_tags');
+                    $title   = sprintf('%s (%s)', $tagName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code'],
+                        'currency_code'   => $currency['currency_code']
                     ];
-                    $amount                   = Steam::positive($journal['amount']);
+                    $amount = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
 
@@ -339,22 +337,22 @@ class DoubleReportController extends Controller
                     if (in_array($journalId, $includedJournals, true)) {
                         continue;
                     }
-                    $includedJournals[]       = $journalId;
+                    $includedJournals[] = $journalId;
                     // do something
-                    $tagName                  = $tag['name'];
-                    $title                    = sprintf('%s (%s)', $tagName, $currency['currency_name']);
+                    $tagName = $tag['name'];
+                    $title   = sprintf('%s (%s)', $tagName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code'],
+                        'currency_code'   => $currency['currency_code']
                     ];
-                    $amount                   = Steam::positive($journal['amount']);
+                    $amount = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data             = $this->generator->multiCurrencyPieChart($result);
+        $data = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
diff --git a/app/Http/Controllers/Chart/ExpenseReportController.php b/app/Http/Controllers/Chart/ExpenseReportController.php
index cfce4a2315..3091146a03 100644
--- a/app/Http/Controllers/Chart/ExpenseReportController.php
+++ b/app/Http/Controllers/Chart/ExpenseReportController.php
@@ -24,13 +24,13 @@ declare(strict_types=1);
 
 namespace FireflyIII\Http\Controllers\Chart;
 
-use FireflyIII\Support\Facades\Navigation;
 use Carbon\Carbon;
 use FireflyIII\Generator\Chart\Basic\GeneratorInterface;
 use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\Models\Account;
 use FireflyIII\Repositories\Account\AccountRepositoryInterface;
 use FireflyIII\Support\CacheProperties;
+use FireflyIII\Support\Facades\Navigation;
 use FireflyIII\Support\Http\Controllers\AugumentData;
 use FireflyIII\Support\Http\Controllers\TransactionCalculation;
 use Illuminate\Http\JsonResponse;
@@ -47,7 +47,7 @@ class ExpenseReportController extends Controller
     use TransactionCalculation;
 
     protected AccountRepositoryInterface $accountRepository;
-    protected GeneratorInterface         $generator;
+    protected GeneratorInterface $generator;
 
     /**
      * ExpenseReportController constructor.
@@ -55,14 +55,12 @@ class ExpenseReportController extends Controller
     public function __construct()
     {
         parent::__construct();
-        $this->middleware(
-            function ($request, $next) {
-                $this->generator         = app(GeneratorInterface::class);
-                $this->accountRepository = app(AccountRepositoryInterface::class);
+        $this->middleware(function ($request, $next) {
+            $this->generator = app(GeneratorInterface::class);
+            $this->accountRepository = app(AccountRepositoryInterface::class);
 
-                return $next($request);
-            }
-        );
+            return $next($request);
+        });
     }
 
     /**
@@ -74,7 +72,7 @@ class ExpenseReportController extends Controller
      */
     public function mainChart(Collection $accounts, Collection $expense, Carbon $start, Carbon $end): JsonResponse
     {
-        $cache        = new CacheProperties();
+        $cache = new CacheProperties();
         $cache->addProperty('chart.expense.report.main');
         $cache->addProperty($accounts);
         $cache->addProperty($expense);
@@ -102,33 +100,33 @@ class ExpenseReportController extends Controller
         foreach ($combined as $name => $combination) {
             // first is always expense account:
             /** @var Account $exp */
-            $exp                              = $combination->first();
-            $chartData[$exp->id.'-in']        = [
+            $exp = $combination->first();
+            $chartData[$exp->id . '-in'] = [
                 'label'   => sprintf('%s (%s)', $name, (string) trans('firefly.income')),
                 'type'    => 'bar',
                 'yAxisID' => 'y-axis-0',
-                'entries' => [],
+                'entries' => []
             ];
-            $chartData[$exp->id.'-out']       = [
+            $chartData[$exp->id . '-out'] = [
                 'label'   => sprintf('%s (%s)', $name, (string) trans('firefly.expenses')),
                 'type'    => 'bar',
                 'yAxisID' => 'y-axis-0',
-                'entries' => [],
+                'entries' => []
             ];
             // total in, total out:
-            $chartData[$exp->id.'-total-in']  = [
+            $chartData[$exp->id . '-total-in'] = [
                 'label'   => sprintf('%s (%s)', $name, (string) trans('firefly.sum_of_income')),
                 'type'    => 'line',
                 'fill'    => false,
                 'yAxisID' => 'y-axis-1',
-                'entries' => [],
+                'entries' => []
             ];
-            $chartData[$exp->id.'-total-out'] = [
+            $chartData[$exp->id . '-total-out'] = [
                 'label'   => sprintf('%s (%s)', $name, (string) trans('firefly.sum_of_expenses')),
                 'type'    => 'line',
                 'fill'    => false,
                 'yAxisID' => 'y-axis-1',
-                'entries' => [],
+                'entries' => []
             ];
         }
 
@@ -136,35 +134,35 @@ class ExpenseReportController extends Controller
         $sumOfExpense = [];
 
         while ($currentStart < $end) {
-            $currentEnd   = clone $currentStart;
-            $currentEnd   = $currentEnd->{$function}(); // @phpstan-ignore-line
+            $currentEnd = clone $currentStart;
+            $currentEnd = $currentEnd->{$function}(); // @phpstan-ignore-line
 
             // get expenses grouped by opposing name:
-            $expenses     = $this->groupByName($this->getExpensesForOpposing($accounts, $all, $currentStart, $currentEnd));
-            $income       = $this->groupByName($this->getIncomeForOpposing($accounts, $all, $currentStart, $currentEnd));
-            $label        = $currentStart->isoFormat($format);
+            $expenses = $this->groupByName($this->getExpensesForOpposing($accounts, $all, $currentStart, $currentEnd));
+            $income   = $this->groupByName($this->getIncomeForOpposing($accounts, $all, $currentStart, $currentEnd));
+            $label    = $currentStart->isoFormat($format);
 
             foreach ($combined as $name => $combination) {
                 // first is always expense account:
                 /** @var Account $exp */
-                $exp                                        = $combination->first();
-                $labelIn                                    = $exp->id.'-in';
-                $labelOut                                   = $exp->id.'-out';
-                $labelSumIn                                 = $exp->id.'-total-in';
-                $labelSumOut                                = $exp->id.'-total-out';
-                $currentIncome                              = bcmul($income[$name] ?? '0', '-1');
-                $currentExpense                             = $expenses[$name] ?? '0';
+                $exp            = $combination->first();
+                $labelIn        = $exp->id . '-in';
+                $labelOut       = $exp->id . '-out';
+                $labelSumIn     = $exp->id . '-total-in';
+                $labelSumOut    = $exp->id . '-total-out';
+                $currentIncome  = bcmul($income[$name] ?? '0', '-1');
+                $currentExpense = $expenses[$name] ?? '0';
 
                 // add to sum:
-                $sumOfIncome[$exp->id]  ??= '0';
+                $sumOfIncome[$exp->id] ??= '0';
                 $sumOfExpense[$exp->id] ??= '0';
-                $sumOfIncome[$exp->id]                      = bcadd($sumOfIncome[$exp->id], $currentIncome);
-                $sumOfExpense[$exp->id]                     = bcadd($sumOfExpense[$exp->id], $currentExpense);
+                $sumOfIncome[$exp->id] = bcadd($sumOfIncome[$exp->id], $currentIncome);
+                $sumOfExpense[$exp->id] = bcadd($sumOfExpense[$exp->id], $currentExpense);
 
                 // add to chart:
-                $chartData[$labelIn]['entries'][$label]     = $currentIncome;
-                $chartData[$labelOut]['entries'][$label]    = $currentExpense;
-                $chartData[$labelSumIn]['entries'][$label]  = $sumOfIncome[$exp->id];
+                $chartData[$labelIn]['entries'][$label] = $currentIncome;
+                $chartData[$labelOut]['entries'][$label] = $currentExpense;
+                $chartData[$labelSumIn]['entries'][$label] = $sumOfIncome[$exp->id];
                 $chartData[$labelSumOut]['entries'][$label] = $sumOfExpense[$exp->id];
             }
 
@@ -174,7 +172,7 @@ class ExpenseReportController extends Controller
             $currentStart->startOfDay();
         }
         // remove all empty entries to prevent cluttering:
-        $newSet       = [];
+        $newSet = [];
         foreach ($chartData as $key => $entry) {
             // TODO not sure, this is a bad comparison.
             if (array_sum($entry['entries']) > 0) {
@@ -184,7 +182,7 @@ class ExpenseReportController extends Controller
         if (0 === count($newSet)) {
             $newSet = $chartData;
         }
-        $data         = $this->generator->multiSet($newSet);
+        $data = $this->generator->multiSet($newSet);
         $cache->store($data);
 
         return response()->json($data);
diff --git a/app/Http/Controllers/Chart/PiggyBankController.php b/app/Http/Controllers/Chart/PiggyBankController.php
index a0e119fa15..053680ada6 100644
--- a/app/Http/Controllers/Chart/PiggyBankController.php
+++ b/app/Http/Controllers/Chart/PiggyBankController.php
@@ -23,7 +23,6 @@ declare(strict_types=1);
 
 namespace FireflyIII\Http\Controllers\Chart;
 
-use FireflyIII\Support\Facades\Navigation;
 use Carbon\Carbon;
 use FireflyIII\Generator\Chart\Basic\GeneratorInterface;
 use FireflyIII\Http\Controllers\Controller;
@@ -31,9 +30,10 @@ use FireflyIII\Models\PiggyBank;
 use FireflyIII\Models\PiggyBankEvent;
 use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
 use FireflyIII\Support\CacheProperties;
+use FireflyIII\Support\Facades\Navigation;
+use FireflyIII\Support\Facades\Steam;
 use FireflyIII\Support\Http\Controllers\DateCalculation;
 use Illuminate\Http\JsonResponse;
-use FireflyIII\Support\Facades\Steam;
 
 /**
  * Class PiggyBankController.
@@ -63,47 +63,43 @@ class PiggyBankController extends Controller
     public function history(PiggyBankRepositoryInterface $repository, PiggyBank $piggyBank): JsonResponse
     {
         // chart properties for cache:
-        $cache                  = new CacheProperties();
+        $cache = new CacheProperties();
         $cache->addProperty('chart.piggy-bank.history');
         $cache->addProperty($piggyBank->id);
         if ($cache->has()) {
             return response()->json($cache->get());
         }
-        $set                    = $repository->getEvents($piggyBank);
-        $set                    = $set->reverse();
-        $locale                 = Steam::getLocale();
+        $set    = $repository->getEvents($piggyBank);
+        $set    = $set->reverse();
+        $locale = Steam::getLocale();
 
         // get first event or start date of piggy bank or today
-        $startDate              = $piggyBank->start_date ?? today(config('app.timezone'));
+        $startDate = $piggyBank->start_date ?? today(config('app.timezone'));
 
         /** @var null|PiggyBankEvent $firstEvent */
-        $firstEvent             = $set->first();
-        $firstDate              = null === $firstEvent ? new Carbon() : $firstEvent->date;
+        $firstEvent = $set->first();
+        $firstDate  = null === $firstEvent ? new Carbon() : $firstEvent->date;
 
         // which ever is older:
-        $oldest                 = $startDate->lt($firstDate) ? $startDate : $firstDate;
-        $today                  = today(config('app.timezone'));
+        $oldest = $startDate->lt($firstDate) ? $startDate : $firstDate;
+        $today  = today(config('app.timezone'));
         // depending on diff, do something with range of chart.
-        $step                   = $this->calculateStep($oldest, $today);
+        $step = $this->calculateStep($oldest, $today);
 
-        $chartData              = [];
+        $chartData = [];
         while ($oldest <= $today) {
-            $filtered          = $set->filter(
-                static fn (PiggyBankEvent $event) => $event->date->lte($oldest)
-            );
-            $currentSum        = $filtered->sum('amount');
-            $label             = $oldest->isoFormat((string) trans('config.month_and_day_js', [], $locale));
+            $filtered   = $set->filter(static fn(PiggyBankEvent $event) => $event->date->lte($oldest));
+            $currentSum = $filtered->sum('amount');
+            $label      = $oldest->isoFormat((string) trans('config.month_and_day_js', [], $locale));
             $chartData[$label] = $currentSum;
-            $oldest            = Navigation::addPeriod($oldest, $step);
+            $oldest = Navigation::addPeriod($oldest, $step);
         }
-        $finalFiltered          = $set->filter(
-            static fn (PiggyBankEvent $event) => $event->date->lte($today)
-        );
-        $finalSum               = $finalFiltered->sum('amount');
-        $finalLabel             = $today->isoFormat((string) trans('config.month_and_day_js', [], $locale));
+        $finalFiltered = $set->filter(static fn(PiggyBankEvent $event) => $event->date->lte($today));
+        $finalSum      = $finalFiltered->sum('amount');
+        $finalLabel    = $today->isoFormat((string) trans('config.month_and_day_js', [], $locale));
         $chartData[$finalLabel] = $finalSum;
 
-        $data                   = $this->generator->singleSet($piggyBank->name, $chartData);
+        $data = $this->generator->singleSet($piggyBank->name, $chartData);
         $cache->store($data);
 
         return response()->json($data);
diff --git a/app/Http/Controllers/Chart/ReportController.php b/app/Http/Controllers/Chart/ReportController.php
index f11c6a3df0..a07fe31322 100644
--- a/app/Http/Controllers/Chart/ReportController.php
+++ b/app/Http/Controllers/Chart/ReportController.php
@@ -23,7 +23,6 @@ declare(strict_types=1);
 
 namespace FireflyIII\Http\Controllers\Chart;
 
-use FireflyIII\Support\Facades\Navigation;
 use Carbon\Carbon;
 use FireflyIII\Enums\TransactionTypeEnum;
 use FireflyIII\Generator\Chart\Basic\GeneratorInterface;
@@ -33,6 +32,7 @@ use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\Models\Account;
 use FireflyIII\Repositories\Account\AccountRepositoryInterface;
 use FireflyIII\Support\CacheProperties;
+use FireflyIII\Support\Facades\Navigation;
 use FireflyIII\Support\Facades\Steam;
 use FireflyIII\Support\Http\Controllers\BasicDataSupport;
 use FireflyIII\Support\Http\Controllers\ChartGeneration;
@@ -67,7 +67,7 @@ class ReportController extends Controller
     public function netWorth(Collection $accounts, Carbon $start, Carbon $end): JsonResponse
     {
         // chart properties for cache:
-        $cache             = new CacheProperties();
+        $cache = new CacheProperties();
         $cache->addProperty('chart.report.net-worth');
         $cache->addProperty($start);
         $cache->addProperty(implode(',', $accounts->pluck('id')->toArray()));
@@ -75,28 +75,26 @@ class ReportController extends Controller
         if ($cache->has()) {
             return response()->json($cache->get());
         }
-        $locale            = Steam::getLocale();
-        $current           = clone $start;
-        $chartData         = [];
+        $locale    = Steam::getLocale();
+        $current   = clone $start;
+        $chartData = [];
 
         /** @var NetWorthInterface $helper */
-        $helper            = app(NetWorthInterface::class);
+        $helper = app(NetWorthInterface::class);
         $helper->setUser(auth()->user());
 
         // filter accounts on having the preference for being included.
         /** @var AccountRepositoryInterface $accountRepository */
         $accountRepository = app(AccountRepositoryInterface::class);
-        $filtered          = $accounts->filter(
-            static function (Account $account) use ($accountRepository): bool {
-                $includeNetWorth = $accountRepository->getMetaValue($account, 'include_net_worth');
-                $result          = null === $includeNetWorth ? true : '1' === $includeNetWorth;
-                if (false === $result) {
-                    Log::debug(sprintf('Will not include "%s" in net worth charts.', $account->name));
-                }
-
-                return $result;
+        $filtered          = $accounts->filter(static function (Account $account) use ($accountRepository): bool {
+            $includeNetWorth = $accountRepository->getMetaValue($account, 'include_net_worth');
+            $result          = null === $includeNetWorth ? true : '1' === $includeNetWorth;
+            if (false === $result) {
+                Log::debug(sprintf('Will not include "%s" in net worth charts.', $account->name));
             }
-        );
+
+            return $result;
+        });
 
         // TODO get liabilities and include those as well?
 
@@ -105,7 +103,7 @@ class ReportController extends Controller
             $balanceCurrent = clone $current;
             $balanceCurrent->subDay()->endOfDay(); // go to correct moment.
             Log::debug(sprintf('Call byAccounts("%s")', $balanceCurrent->format('Y-m-d H:i:s')));
-            $result         = $helper->byAccounts($filtered, $balanceCurrent);
+            $result = $helper->byAccounts($filtered, $balanceCurrent);
 
             // loop result, add to array.
             /** @var array $netWorthItem */
@@ -113,15 +111,15 @@ class ReportController extends Controller
                 if ('primary' === $key) {
                     continue;
                 }
-                $currencyId                                = $netWorthItem['currency_id'];
-                $label                                     = $current->isoFormat((string) trans('config.month_and_day_js', [], $locale));
+                $currencyId = $netWorthItem['currency_id'];
+                $label      = $current->isoFormat((string) trans('config.month_and_day_js', [], $locale));
                 if (!array_key_exists($currencyId, $chartData)) {
                     $chartData[$currencyId] = [
-                        'label'           => 'Net worth in '.$netWorthItem['currency_name'],
+                        'label'           => 'Net worth in ' . $netWorthItem['currency_name'],
                         'type'            => 'line',
                         'currency_symbol' => $netWorthItem['currency_symbol'],
                         'currency_code'   => $netWorthItem['currency_code'],
-                        'entries'         => [],
+                        'entries'         => []
                     ];
                 }
                 $chartData[$currencyId]['entries'][$label] = $netWorthItem['balance'];
@@ -129,7 +127,7 @@ class ReportController extends Controller
             $current->addDays(7);
         }
 
-        $data              = $this->generator->multiSet($chartData);
+        $data = $this->generator->multiSet($chartData);
         $cache->store($data);
 
         return response()->json($data);
@@ -144,7 +142,7 @@ class ReportController extends Controller
     {
         $end->endOfDay();
         // chart properties for cache:
-        $cache          = new CacheProperties();
+        $cache = new CacheProperties();
         $cache->addProperty('chart.report.operations');
         $cache->addProperty($start);
         $cache->addProperty($accounts);
@@ -163,50 +161,45 @@ class ReportController extends Controller
         $chartData      = [];
 
         /** @var GroupCollectorInterface $collector */
-        $collector      = app(GroupCollectorInterface::class);
+        $collector = app(GroupCollectorInterface::class);
         $collector->setRange($start, $end)->withAccountInformation();
         $collector->setXorAccounts($accounts);
-        $collector->setTypes(
-            [
-                TransactionTypeEnum::WITHDRAWAL,
-                TransactionTypeEnum::DEPOSIT,
-                TransactionTypeEnum::RECONCILIATION,
-                TransactionTypeEnum::TRANSFER,
-            ]
-        );
-        $journals       = $collector->getExtractedJournals();
+        $collector->setTypes([
+            TransactionTypeEnum::WITHDRAWAL,
+            TransactionTypeEnum::DEPOSIT,
+            TransactionTypeEnum::RECONCILIATION,
+            TransactionTypeEnum::TRANSFER
+        ]);
+        $journals = $collector->getExtractedJournals();
 
         // loop. group by currency and by period.
         /** @var array $journal */
         foreach ($journals as $journal) {
-            $period                           = $journal['date']->format($format);
-            $currencyId                       = (int) $journal['currency_id'];
-            $data[$currencyId]          ??= [
+            $period     = $journal['date']->format($format);
+            $currencyId = (int) $journal['currency_id'];
+            $data[$currencyId] ??= [
                 'currency_id'             => $currencyId,
                 'currency_symbol'         => $journal['currency_symbol'],
                 'currency_code'           => $journal['currency_code'],
                 'currency_name'           => $journal['currency_name'],
-                'currency_decimal_places' => (int) $journal['currency_decimal_places'],
-            ];
-            $data[$currencyId][$period] ??= [
-                'period' => $period,
-                'spent'  => '0',
-                'earned' => '0',
+                'currency_decimal_places' => (int) $journal['currency_decimal_places']
             ];
+            $data[$currencyId][$period] ??= ['period' => $period, 'spent'  => '0', 'earned' => '0'];
             // in our outgoing?
-            $key                              = 'spent';
-            $amount                           = Steam::positive($journal['amount']);
+            $key    = 'spent';
+            $amount = Steam::positive($journal['amount']);
 
             // deposit = incoming
             // transfer or reconcile or opening balance, and these accounts are the destination.
             if (
                 TransactionTypeEnum::DEPOSIT->value === $journal['transaction_type_type']
-                || ((
+                || (
                     TransactionTypeEnum::TRANSFER->value === $journal['transaction_type_type']
-                        || TransactionTypeEnum::RECONCILIATION->value === $journal['transaction_type_type']
-                        || TransactionTypeEnum::OPENING_BALANCE->value === $journal['transaction_type_type']
+                    || TransactionTypeEnum::RECONCILIATION->value === $journal['transaction_type_type']
+                    || TransactionTypeEnum::OPENING_BALANCE->value === $journal['transaction_type_type']
                 )
-                    && in_array($journal['destination_account_id'], $ids, true))) {
+                && in_array($journal['destination_account_id'], $ids, true)
+            ) {
                 $key = 'earned';
             }
             $data[$currencyId][$period][$key] = bcadd((string) $data[$currencyId][$period][$key], $amount);
@@ -218,23 +211,23 @@ class ReportController extends Controller
         /** @var array $currency */
         foreach ($data as $currency) {
             Log::debug(sprintf('Now processing currency "%s"', $currency['currency_name']));
-            $income       = [
-                'label'           => (string) trans('firefly.box_earned_in_currency', ['currency' => $currency['currency_name']]),
+            $income  = [
+                'label'           => (string) trans('firefly.box_earned_in_currency', ['currency'           => $currency['currency_name']]),
                 'type'            => 'bar',
                 'backgroundColor' => 'rgba(0, 141, 76, 0.5)', // green
                 'currency_id'     => $currency['currency_id'],
                 'currency_symbol' => $currency['currency_symbol'],
                 'currency_code'   => $currency['currency_code'],
-                'entries'         => [],
+                'entries'         => []
             ];
-            $expense      = [
-                'label'           => (string) trans('firefly.box_spent_in_currency', ['currency' => $currency['currency_name']]),
+            $expense = [
+                'label'           => (string) trans('firefly.box_spent_in_currency', ['currency'           => $currency['currency_name']]),
                 'type'            => 'bar',
                 'backgroundColor' => 'rgba(219, 68, 55, 0.5)', // red
                 'currency_id'     => $currency['currency_id'],
                 'currency_symbol' => $currency['currency_symbol'],
                 'currency_code'   => $currency['currency_code'],
-                'entries'         => [],
+                'entries'         => []
             ];
             // loop all possible periods between $start and $end
             $currentStart = clone $start;
@@ -248,29 +241,28 @@ class ReportController extends Controller
             Log::debug('Start of sub-loop');
             while ($currentStart <= $currentEnd) {
                 Log::debug(sprintf('Current start: %s', $currentStart->toW3cString()));
-                $key          = $currentStart->format($format);
-                $title        = $currentStart->isoFormat($titleFormat);
+                $key   = $currentStart->format($format);
+                $title = $currentStart->isoFormat($titleFormat);
                 // #8663 make sure the period exists in the data previously collected.
                 if (array_key_exists($key, $currency)) {
-                    $income['entries'][$title]  = Steam::bcround($currency[$key]['earned'] ?? '0', $currency['currency_decimal_places']);
+                    $income['entries'][$title] = Steam::bcround($currency[$key]['earned'] ?? '0', $currency['currency_decimal_places']);
                     $expense['entries'][$title] = Steam::bcround($currency[$key]['spent'] ?? '0', $currency['currency_decimal_places']);
                 }
                 // #9477 if the period is not in the data, add it with zero values.
                 if (!array_key_exists($key, $currency)) {
-                    $income['entries'][$title]  = '0';
+                    $income['entries'][$title] = '0';
                     $expense['entries'][$title] = '0';
-
                 }
                 $currentStart = Navigation::addPeriod($currentStart, $preferredRange);
             }
             Log::debug('End of sub-loop');
 
-            $chartData[]  = $income;
-            $chartData[]  = $expense;
+            $chartData[] = $income;
+            $chartData[] = $expense;
         }
         Log::debug('End of loop');
 
-        $data           = $this->generator->multiSet($chartData);
+        $data = $this->generator->multiSet($chartData);
         $cache->store($data);
 
         return response()->json($data);
diff --git a/app/Http/Controllers/Chart/TagReportController.php b/app/Http/Controllers/Chart/TagReportController.php
index 8bee1ec38d..685dadf099 100644
--- a/app/Http/Controllers/Chart/TagReportController.php
+++ b/app/Http/Controllers/Chart/TagReportController.php
@@ -23,12 +23,12 @@ declare(strict_types=1);
 
 namespace FireflyIII\Http\Controllers\Chart;
 
-use FireflyIII\Support\Facades\Navigation;
 use Carbon\Carbon;
 use FireflyIII\Generator\Chart\Basic\GeneratorInterface;
 use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\Models\Tag;
 use FireflyIII\Repositories\Tag\OperationsRepositoryInterface;
+use FireflyIII\Support\Facades\Navigation;
 use FireflyIII\Support\Facades\Steam;
 use FireflyIII\Support\Http\Controllers\AugumentData;
 use FireflyIII\Support\Http\Controllers\TransactionCalculation;
@@ -58,13 +58,11 @@ class TagReportController extends Controller
         // create chart generator:
         $this->generator = app(GeneratorInterface::class);
 
-        $this->middleware(
-            function ($request, $next) {
-                $this->opsRepository = app(OperationsRepositoryInterface::class);
+        $this->middleware(function ($request, $next) {
+            $this->opsRepository = app(OperationsRepositoryInterface::class);
 
-                return $next($request);
-            }
-        );
+            return $next($request);
+        });
     }
 
     public function budgetExpense(Collection $accounts, Collection $tags, Carbon $start, Carbon $end): JsonResponse
@@ -77,20 +75,20 @@ class TagReportController extends Controller
             /** @var array $tag */
             foreach ($currency['tags'] as $tag) {
                 foreach ($tag['transaction_journals'] as $journal) {
-                    $objectName               = $journal['budget_name'] ?? trans('firefly.no_budget');
-                    $title                    = sprintf('%s (%s)', $objectName, $currency['currency_name']);
+                    $objectName = $journal['budget_name'] ?? trans('firefly.no_budget');
+                    $title      = sprintf('%s (%s)', $objectName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code'],
+                        'currency_code'   => $currency['currency_code']
                     ];
-                    $amount                   = Steam::positive($journal['amount']);
+                    $amount = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data   = $this->generator->multiCurrencyPieChart($result);
+        $data = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -105,20 +103,20 @@ class TagReportController extends Controller
             /** @var array $tag */
             foreach ($currency['tags'] as $tag) {
                 foreach ($tag['transaction_journals'] as $journal) {
-                    $objectName               = $journal['category_name'] ?? trans('firefly.no_category');
-                    $title                    = sprintf('%s (%s)', $objectName, $currency['currency_name']);
+                    $objectName = $journal['category_name'] ?? trans('firefly.no_category');
+                    $title      = sprintf('%s (%s)', $objectName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code'],
+                        'currency_code'   => $currency['currency_code']
                     ];
-                    $amount                   = Steam::positive($journal['amount']);
+                    $amount = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data   = $this->generator->multiCurrencyPieChart($result);
+        $data = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -133,20 +131,20 @@ class TagReportController extends Controller
             /** @var array $tag */
             foreach ($currency['tags'] as $tag) {
                 foreach ($tag['transaction_journals'] as $journal) {
-                    $objectName               = $journal['category_name'] ?? trans('firefly.no_category');
-                    $title                    = sprintf('%s (%s)', $objectName, $currency['currency_name']);
+                    $objectName = $journal['category_name'] ?? trans('firefly.no_category');
+                    $title      = sprintf('%s (%s)', $objectName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code'],
+                        'currency_code'   => $currency['currency_code']
                     ];
-                    $amount                   = Steam::positive($journal['amount']);
+                    $amount = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data   = $this->generator->multiCurrencyPieChart($result);
+        $data = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -161,20 +159,20 @@ class TagReportController extends Controller
             /** @var array $tag */
             foreach ($currency['tags'] as $tag) {
                 foreach ($tag['transaction_journals'] as $journal) {
-                    $objectName               = $journal['destination_account_name'] ?? trans('firefly.empty');
-                    $title                    = sprintf('%s (%s)', $objectName, $currency['currency_name']);
+                    $objectName = $journal['destination_account_name'] ?? trans('firefly.empty');
+                    $title      = sprintf('%s (%s)', $objectName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code'],
+                        'currency_code'   => $currency['currency_code']
                     ];
-                    $amount                   = Steam::positive($journal['amount']);
+                    $amount = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data   = $this->generator->multiCurrencyPieChart($result);
+        $data = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -189,20 +187,20 @@ class TagReportController extends Controller
             /** @var array $tag */
             foreach ($currency['tags'] as $tag) {
                 foreach ($tag['transaction_journals'] as $journal) {
-                    $objectName               = $journal['destination_account_name'] ?? trans('firefly.empty');
-                    $title                    = sprintf('%s (%s)', $objectName, $currency['currency_name']);
+                    $objectName = $journal['destination_account_name'] ?? trans('firefly.empty');
+                    $title      = sprintf('%s (%s)', $objectName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code'],
+                        'currency_code'   => $currency['currency_code']
                     ];
-                    $amount                   = Steam::positive($journal['amount']);
+                    $amount = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data   = $this->generator->multiCurrencyPieChart($result);
+        $data = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -224,20 +222,20 @@ class TagReportController extends Controller
             $chartData[$spentKey] ??= [
                 'label'           => sprintf(
                     '%s (%s)',
-                    (string) trans('firefly.spent_in_specific_tag', ['tag' => $tag->tag]),
+                    (string) trans('firefly.spent_in_specific_tag', ['tag'           => $tag->tag]),
                     $currency['currency_name']
                 ),
                 'type'            => 'bar',
                 'currency_symbol' => $currency['currency_symbol'],
                 'currency_code'   => $currency['currency_code'],
                 'currency_id'     => $currency['currency_id'],
-                'entries'         => $this->makeEntries($start, $end),
+                'entries'         => $this->makeEntries($start, $end)
             ];
 
             foreach ($currency['tags'] as $currentTag) {
                 foreach ($currentTag['transaction_journals'] as $journal) {
-                    $key                                   = $journal['date']->isoFormat($format);
-                    $amount                                = Steam::positive($journal['amount']);
+                    $key    = $journal['date']->isoFormat($format);
+                    $amount = Steam::positive($journal['amount']);
                     $chartData[$spentKey]['entries'][$key] ??= '0';
                     $chartData[$spentKey]['entries'][$key] = bcadd($chartData[$spentKey]['entries'][$key], $amount);
                 }
@@ -251,27 +249,27 @@ class TagReportController extends Controller
             $chartData[$spentKey] ??= [
                 'label'           => sprintf(
                     '%s (%s)',
-                    (string) trans('firefly.earned_in_specific_tag', ['tag' => $tag->tag]),
+                    (string) trans('firefly.earned_in_specific_tag', ['tag'           => $tag->tag]),
                     $currency['currency_name']
                 ),
                 'type'            => 'bar',
                 'currency_symbol' => $currency['currency_symbol'],
                 'currency_code'   => $currency['currency_code'],
                 'currency_id'     => $currency['currency_id'],
-                'entries'         => $this->makeEntries($start, $end),
+                'entries'         => $this->makeEntries($start, $end)
             ];
 
             foreach ($currency['tags'] as $currentTag) {
                 foreach ($currentTag['transaction_journals'] as $journal) {
-                    $key                                   = $journal['date']->isoFormat($format);
-                    $amount                                = Steam::positive($journal['amount']);
+                    $key    = $journal['date']->isoFormat($format);
+                    $amount = Steam::positive($journal['amount']);
                     $chartData[$spentKey]['entries'][$key] ??= '0';
                     $chartData[$spentKey]['entries'][$key] = bcadd($chartData[$spentKey]['entries'][$key], $amount);
                 }
             }
         }
 
-        $data      = $this->generator->multiSet($chartData);
+        $data = $this->generator->multiSet($chartData);
 
         return response()->json($data);
     }
@@ -286,8 +284,8 @@ class TagReportController extends Controller
         $preferredRange = Navigation::preferredRangeFormat($start, $end);
         $currentStart   = clone $start;
         while ($currentStart <= $end) {
-            $currentEnd   = Navigation::endOfPeriod($currentStart, $preferredRange);
-            $key          = $currentStart->isoFormat($format);
+            $currentEnd = Navigation::endOfPeriod($currentStart, $preferredRange);
+            $key        = $currentStart->isoFormat($format);
             $return[$key] = '0';
             $currentStart = clone $currentEnd;
             $currentStart->addDay()->startOfDay();
@@ -306,20 +304,20 @@ class TagReportController extends Controller
             /** @var array $tag */
             foreach ($currency['tags'] as $tag) {
                 foreach ($tag['transaction_journals'] as $journal) {
-                    $objectName               = $journal['source_account_name'] ?? trans('firefly.empty');
-                    $title                    = sprintf('%s (%s)', $objectName, $currency['currency_name']);
+                    $objectName = $journal['source_account_name'] ?? trans('firefly.empty');
+                    $title      = sprintf('%s (%s)', $objectName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code'],
+                        'currency_code'   => $currency['currency_code']
                     ];
-                    $amount                   = Steam::positive($journal['amount']);
+                    $amount = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data   = $this->generator->multiCurrencyPieChart($result);
+        $data = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -334,20 +332,20 @@ class TagReportController extends Controller
             /** @var array $tag */
             foreach ($currency['tags'] as $tag) {
                 foreach ($tag['transaction_journals'] as $journal) {
-                    $objectName               = $journal['source_account_name'] ?? trans('firefly.empty');
-                    $title                    = sprintf('%s (%s)', $objectName, $currency['currency_name']);
+                    $objectName = $journal['source_account_name'] ?? trans('firefly.empty');
+                    $title      = sprintf('%s (%s)', $objectName, $currency['currency_name']);
                     $result[$title] ??= [
                         'amount'          => '0',
                         'currency_symbol' => $currency['currency_symbol'],
-                        'currency_code'   => $currency['currency_code'],
+                        'currency_code'   => $currency['currency_code']
                     ];
-                    $amount                   = Steam::positive($journal['amount']);
+                    $amount = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
 
-        $data   = $this->generator->multiCurrencyPieChart($result);
+        $data = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -365,15 +363,15 @@ class TagReportController extends Controller
                 $result[$title] ??= [
                     'amount'          => '0',
                     'currency_symbol' => $currency['currency_symbol'],
-                    'currency_code'   => $currency['currency_code'],
+                    'currency_code'   => $currency['currency_code']
                 ];
                 foreach ($tag['transaction_journals'] as $journal) {
-                    $amount                   = Steam::positive($journal['amount']);
+                    $amount = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
-        $data   = $this->generator->multiCurrencyPieChart($result);
+        $data = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
@@ -391,15 +389,15 @@ class TagReportController extends Controller
                 $result[$title] ??= [
                     'amount'          => '0',
                     'currency_symbol' => $currency['currency_symbol'],
-                    'currency_code'   => $currency['currency_code'],
+                    'currency_code'   => $currency['currency_code']
                 ];
                 foreach ($tag['transaction_journals'] as $journal) {
-                    $amount                   = Steam::positive($journal['amount']);
+                    $amount = Steam::positive($journal['amount']);
                     $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount);
                 }
             }
         }
-        $data   = $this->generator->multiCurrencyPieChart($result);
+        $data = $this->generator->multiCurrencyPieChart($result);
 
         return response()->json($data);
     }
diff --git a/app/Http/Controllers/Chart/TransactionController.php b/app/Http/Controllers/Chart/TransactionController.php
index 973af0ee54..5d151ba506 100644
--- a/app/Http/Controllers/Chart/TransactionController.php
+++ b/app/Http/Controllers/Chart/TransactionController.php
@@ -54,7 +54,7 @@ class TransactionController extends Controller
      */
     public function budgets(Carbon $start, Carbon $end)
     {
-        $cache     = new CacheProperties();
+        $cache = new CacheProperties();
         $cache->addProperty($start);
         $cache->addProperty($end);
         $cache->addProperty('chart.transactions.budgets');
@@ -68,22 +68,18 @@ class TransactionController extends Controller
         $collector->withBudgetInformation();
         $collector->setTypes([TransactionTypeEnum::WITHDRAWAL->value]);
 
-        $result    = $collector->getExtractedJournals();
-        $data      = [];
+        $result = $collector->getExtractedJournals();
+        $data   = [];
 
         // group by category.
         /** @var array $journal */
         foreach ($result as $journal) {
-            $budget                 = $journal['budget_name'] ?? (string) trans('firefly.no_budget');
-            $title                  = sprintf('%s (%s)', $budget, $journal['currency_symbol']);
-            $data[$title] ??= [
-                'amount'          => '0',
-                'currency_symbol' => $journal['currency_symbol'],
-                'currency_code'   => $journal['currency_code'],
-            ];
+            $budget = $journal['budget_name'] ?? (string) trans('firefly.no_budget');
+            $title  = sprintf('%s (%s)', $budget, $journal['currency_symbol']);
+            $data[$title] ??= ['amount'          => '0', 'currency_symbol' => $journal['currency_symbol'], 'currency_code'   => $journal['currency_code']];
             $data[$title]['amount'] = bcadd($data[$title]['amount'], (string) $journal['amount']);
         }
-        $chart     = $this->generator->multiCurrencyPieChart($data);
+        $chart = $this->generator->multiCurrencyPieChart($data);
         $cache->store($chart);
 
         return response()->json($chart);
@@ -94,7 +90,7 @@ class TransactionController extends Controller
      */
     public function categories(string $objectType, Carbon $start, Carbon $end)
     {
-        $cache     = new CacheProperties();
+        $cache = new CacheProperties();
         $cache->addProperty($start);
         $cache->addProperty($end);
         $cache->addProperty($objectType);
@@ -118,22 +114,18 @@ class TransactionController extends Controller
             $collector->setTypes([TransactionTypeEnum::TRANSFER->value]);
         }
 
-        $result    = $collector->getExtractedJournals();
-        $data      = [];
+        $result = $collector->getExtractedJournals();
+        $data   = [];
 
         // group by category.
         /** @var array $journal */
         foreach ($result as $journal) {
-            $category               = $journal['category_name'] ?? (string) trans('firefly.no_category');
-            $title                  = sprintf('%s (%s)', $category, $journal['currency_symbol']);
-            $data[$title] ??= [
-                'amount'          => '0',
-                'currency_symbol' => $journal['currency_symbol'],
-                'currency_code'   => $journal['currency_code'],
-            ];
+            $category = $journal['category_name'] ?? (string) trans('firefly.no_category');
+            $title    = sprintf('%s (%s)', $category, $journal['currency_symbol']);
+            $data[$title] ??= ['amount'          => '0', 'currency_symbol' => $journal['currency_symbol'], 'currency_code'   => $journal['currency_code']];
             $data[$title]['amount'] = bcadd($data[$title]['amount'], (string) $journal['amount']);
         }
-        $chart     = $this->generator->multiCurrencyPieChart($data);
+        $chart = $this->generator->multiCurrencyPieChart($data);
         $cache->store($chart);
 
         return response()->json($chart);
@@ -144,7 +136,7 @@ class TransactionController extends Controller
      */
     public function destinationAccounts(string $objectType, Carbon $start, Carbon $end)
     {
-        $cache     = new CacheProperties();
+        $cache = new CacheProperties();
         $cache->addProperty($start);
         $cache->addProperty($end);
         $cache->addProperty($objectType);
@@ -168,22 +160,18 @@ class TransactionController extends Controller
             $collector->setTypes([TransactionTypeEnum::TRANSFER->value]);
         }
 
-        $result    = $collector->getExtractedJournals();
-        $data      = [];
+        $result = $collector->getExtractedJournals();
+        $data   = [];
 
         // group by category.
         /** @var array $journal */
         foreach ($result as $journal) {
-            $name                   = $journal['destination_account_name'];
-            $title                  = sprintf('%s (%s)', $name, $journal['currency_symbol']);
-            $data[$title] ??= [
-                'amount'          => '0',
-                'currency_symbol' => $journal['currency_symbol'],
-                'currency_code'   => $journal['currency_code'],
-            ];
+            $name  = $journal['destination_account_name'];
+            $title = sprintf('%s (%s)', $name, $journal['currency_symbol']);
+            $data[$title] ??= ['amount'          => '0', 'currency_symbol' => $journal['currency_symbol'], 'currency_code'   => $journal['currency_code']];
             $data[$title]['amount'] = bcadd($data[$title]['amount'], (string) $journal['amount']);
         }
-        $chart     = $this->generator->multiCurrencyPieChart($data);
+        $chart = $this->generator->multiCurrencyPieChart($data);
         $cache->store($chart);
 
         return response()->json($chart);
@@ -194,7 +182,7 @@ class TransactionController extends Controller
      */
     public function sourceAccounts(string $objectType, Carbon $start, Carbon $end)
     {
-        $cache     = new CacheProperties();
+        $cache = new CacheProperties();
         $cache->addProperty($start);
         $cache->addProperty($end);
         $cache->addProperty($objectType);
@@ -218,22 +206,18 @@ class TransactionController extends Controller
             $collector->setTypes([TransactionTypeEnum::TRANSFER->value]);
         }
 
-        $result    = $collector->getExtractedJournals();
-        $data      = [];
+        $result = $collector->getExtractedJournals();
+        $data   = [];
 
         // group by category.
         /** @var array $journal */
         foreach ($result as $journal) {
-            $name                   = $journal['source_account_name'];
-            $title                  = sprintf('%s (%s)', $name, $journal['currency_symbol']);
-            $data[$title] ??= [
-                'amount'          => '0',
-                'currency_symbol' => $journal['currency_symbol'],
-                'currency_code'   => $journal['currency_code'],
-            ];
+            $name  = $journal['source_account_name'];
+            $title = sprintf('%s (%s)', $name, $journal['currency_symbol']);
+            $data[$title] ??= ['amount'          => '0', 'currency_symbol' => $journal['currency_symbol'], 'currency_code'   => $journal['currency_code']];
             $data[$title]['amount'] = bcadd($data[$title]['amount'], (string) $journal['amount']);
         }
-        $chart     = $this->generator->multiCurrencyPieChart($data);
+        $chart = $this->generator->multiCurrencyPieChart($data);
         $cache->store($chart);
 
         return response()->json($chart);
diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php
index 5da60a33ab..b5e7e422ce 100644
--- a/app/Http/Controllers/Controller.php
+++ b/app/Http/Controllers/Controller.php
@@ -26,6 +26,7 @@ namespace FireflyIII\Http\Controllers;
 use FireflyIII\Events\RequestedSendWebhookMessages;
 use FireflyIII\Models\TransactionCurrency;
 use FireflyIII\Support\Facades\Amount;
+use FireflyIII\Support\Facades\FireflyConfig;
 use FireflyIII\Support\Facades\Preferences;
 use FireflyIII\Support\Facades\Steam;
 use FireflyIII\Support\Http\Controllers\RequestInformation;
@@ -38,7 +39,6 @@ use Illuminate\Support\Facades\Config;
 use Illuminate\Support\Facades\Log;
 use Illuminate\Support\Facades\Route;
 use Illuminate\Support\Facades\View;
-use FireflyIII\Support\Facades\FireflyConfig;
 
 use function Safe\ini_get;
 use function Safe\realpath;
@@ -59,12 +59,12 @@ abstract class Controller extends BaseController
 
     // fails on PHP < 8.4
     public protected(set) string $name;
-    protected bool                 $convertToPrimary = false;
-    protected string               $dateTimeFormat;
-    protected ?TransactionCurrency $primaryCurrency;
-    protected string               $monthAndDayFormat;
-    protected string               $monthFormat;
-    protected string               $redirectUrl      = '/';
+    protected bool $convertToPrimary = false;
+    protected string $dateTimeFormat;
+    protected null|TransactionCurrency $primaryCurrency;
+    protected string $monthAndDayFormat;
+    protected string $monthFormat;
+    protected string $redirectUrl = '/';
 
     /**
      * Controller constructor.
@@ -81,11 +81,14 @@ abstract class Controller extends BaseController
         View::share('FF_BUILD_TIME', config('firefly.build_time'));
 
         // is webhooks enabled?
-        View::share('featuringWebhooks', true === config('firefly.feature_flags.webhooks') && true === FireflyConfig::get('allow_webhooks', config('firefly.allow_webhooks'))->data);
+        View::share(
+            'featuringWebhooks',
+            true === config('firefly.feature_flags.webhooks') && true === FireflyConfig::get('allow_webhooks', config('firefly.allow_webhooks'))->data
+        );
 
         // share custom auth guard info.
-        $authGuard        = config('firefly.authentication_guard');
-        $logoutUrl        = config('firefly.custom_logout_url');
+        $authGuard = config('firefly.authentication_guard');
+        $logoutUrl = config('firefly.custom_logout_url');
 
         // overrule v2 layout back to v1.
         if ('true' === request()->get('force_default_layout') && 'v2' === config('view.layout')) {
@@ -98,15 +101,15 @@ abstract class Controller extends BaseController
         View::share('logoutUrl', $logoutUrl);
 
         // upload size
-        $maxFileSize      = Steam::phpBytes(ini_get('upload_max_filesize'));
-        $maxPostSize      = Steam::phpBytes(ini_get('post_max_size'));
-        $uploadSize       = min($maxFileSize, $maxPostSize);
+        $maxFileSize = Steam::phpBytes(ini_get('upload_max_filesize'));
+        $maxPostSize = Steam::phpBytes(ini_get('post_max_size'));
+        $uploadSize  = min($maxFileSize, $maxPostSize);
         View::share('uploadSize', $uploadSize);
 
         // share is alpha, is beta
-        $isAlpha          = false;
-        $isBeta           = false;
-        $isDevelop        = false;
+        $isAlpha   = false;
+        $isBeta    = false;
+        $isDevelop = false;
         if (str_contains((string) config('firefly.version'), 'alpha')) {
             $isAlpha = true;
         }
@@ -122,45 +125,42 @@ abstract class Controller extends BaseController
         View::share('FF_IS_BETA', $isBeta);
         View::share('FF_IS_DEVELOP', $isDevelop);
 
-        $this->middleware(
-            function ($request, $next): mixed {
-                $locale                  = Steam::getLocale();
-                // translations for specific strings:
-                $this->monthFormat       = (string) trans('config.month_js', [], $locale);
-                $this->monthAndDayFormat = (string) trans('config.month_and_day_js', [], $locale);
-                $this->dateTimeFormat    = (string) trans('config.date_time_js', [], $locale);
-                $darkMode                = 'browser';
-                $this->primaryCurrency   = null;
-                // get shown-intro-preference:
-                if (auth()->check()) {
-                    View::share('anonymous', Steam::anonymous());
-                    $this->primaryCurrency  = Amount::getPrimaryCurrency();
-                    $language               = Steam::getLanguage();
-                    $locale                 = Steam::getLocale();
-                    $darkMode               = Preferences::get('darkMode', 'browser')->data;
-                    $this->convertToPrimary = Amount::convertToPrimary();
-                    $page                   = $this->getPageName();
-                    $shownDemo              = $this->hasSeenDemo();
-                    View::share('language', $language);
-                    View::share('locale', $locale);
-                    View::share('convertToPrimary', $this->convertToPrimary);
-                    View::share('primaryCurrency', $this->primaryCurrency);
-                    View::share('shownDemo', $shownDemo);
-                    View::share('current_route_name', $page);
-                    View::share('original_route_name', Route::currentRouteName());
-
-                    // lottery to send any remaining webhooks:
-                    if (7 === random_int(1, 10)) {
-                        // trigger event to send them:
-                        Log::debug('send event RequestedSendWebhookMessages through lottery');
-                        event(new RequestedSendWebhookMessages());
-                    }
+        $this->middleware(function ($request, $next): mixed {
+            $locale = Steam::getLocale();
+            // translations for specific strings:
+            $this->monthFormat = (string) trans('config.month_js', [], $locale);
+            $this->monthAndDayFormat = (string) trans('config.month_and_day_js', [], $locale);
+            $this->dateTimeFormat = (string) trans('config.date_time_js', [], $locale);
+            $darkMode = 'browser';
+            $this->primaryCurrency = null;
+            // get shown-intro-preference:
+            if (auth()->check()) {
+                View::share('anonymous', Steam::anonymous());
+                $this->primaryCurrency = Amount::getPrimaryCurrency();
+                $language = Steam::getLanguage();
+                $locale   = Steam::getLocale();
+                $darkMode = Preferences::get('darkMode', 'browser')->data;
+                $this->convertToPrimary = Amount::convertToPrimary();
+                $page      = $this->getPageName();
+                $shownDemo = $this->hasSeenDemo();
+                View::share('language', $language);
+                View::share('locale', $locale);
+                View::share('convertToPrimary', $this->convertToPrimary);
+                View::share('primaryCurrency', $this->primaryCurrency);
+                View::share('shownDemo', $shownDemo);
+                View::share('current_route_name', $page);
+                View::share('original_route_name', Route::currentRouteName());
 
+                // lottery to send any remaining webhooks:
+                if (7 === random_int(1, 10)) {
+                    // trigger event to send them:
+                    Log::debug('send event RequestedSendWebhookMessages through lottery');
+                    event(new RequestedSendWebhookMessages());
                 }
-                View::share('darkMode', $darkMode);
-
-                return $next($request);
             }
-        );
+            View::share('darkMode', $darkMode);
+
+            return $next($request);
+        });
     }
 }
diff --git a/app/Http/Controllers/DebugController.php b/app/Http/Controllers/DebugController.php
index 33f13977b1..0c30f7503b 100644
--- a/app/Http/Controllers/DebugController.php
+++ b/app/Http/Controllers/DebugController.php
@@ -34,6 +34,7 @@ use FireflyIII\Models\PeriodStatistic;
 use FireflyIII\Models\TransactionType;
 use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
 use FireflyIII\Support\Facades\Amount;
+use FireflyIII\Support\Facades\FireflyConfig;
 use FireflyIII\Support\Facades\Preferences;
 use FireflyIII\Support\Facades\Steam;
 use FireflyIII\Support\Http\Controllers\GetConfigurationData;
@@ -51,7 +52,6 @@ use Illuminate\View\View;
 use Monolog\Handler\RotatingFileHandler;
 use Safe\Exceptions\FilesystemException;
 use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
-use FireflyIII\Support\Facades\FireflyConfig;
 
 use function Safe\file_get_contents;
 use function Safe\ini_get;
@@ -119,7 +119,7 @@ class DebugController extends Controller
 
         try {
             Artisan::call('twig:clean');
-        } catch (Exception $e) {  // intentional generic exception
+        } catch (Exception $e) { // intentional generic exception
             throw new FireflyException($e->getMessage(), 0, $e);
         }
 
@@ -137,14 +137,14 @@ class DebugController extends Controller
      */
     public function index(): Factory|\Illuminate\Contracts\View\View
     {
-        $table      = $this->generateTable();
-        $table      = str_replace(["\n", "\t", '  '], '', $table);
-        $now        = now(config('app.timezone'))->format('Y-m-d H:i:s');
+        $table = $this->generateTable();
+        $table = str_replace(["\n", "\t", '  '], '', $table);
+        $now   = now(config('app.timezone'))->format('Y-m-d H:i:s');
 
         // get latest log file:
-        $logger     = Log::driver();
+        $logger = Log::driver();
         // PHPstan doesn't recognize the method because of its polymorphic nature.
-        $handlers   = $logger->getHandlers(); // @phpstan-ignore-line
+        $handlers = $logger->getHandlers(); // @phpstan-ignore-line
         $logContent = '';
         foreach ($handlers as $handler) {
             if ($handler instanceof RotatingFileHandler) {
@@ -156,10 +156,10 @@ class DebugController extends Controller
         }
         if ('' !== $logContent) {
             // last few lines
-            $logContent = 'Truncated from this point <----|'.substr($logContent, -16384);
+            $logContent = 'Truncated from this point <----|' . substr($logContent, -16384);
         }
 
-        return view('debug', ['table' => $table, 'now' => $now, 'logContent' => $logContent]);
+        return view('debug', ['table'      => $table, 'now'        => $now, 'logContent' => $logContent]);
     }
 
     public function apiTest(): View
@@ -175,7 +175,7 @@ class DebugController extends Controller
         $app    = $this->getAppInfo();
         $user   = $this->getUserInfo();
 
-        return (string) view('partials.debug-table', ['system' => $system, 'docker' => $docker, 'app' => $app, 'user' => $user]);
+        return (string) view('partials.debug-table', ['system' => $system, 'docker' => $docker, 'app'    => $app, 'user'   => $user]);
     }
 
     private function getSystemInformation(): array
@@ -198,18 +198,18 @@ class DebugController extends Controller
             'error_reporting' => $this->errorReporting((int) ini_get('error_reporting')),
             'upload_size'     => min($maxFileSize, $maxPostSize),
             'all_drivers'     => $drivers,
-            'current_driver'  => $currentDriver,
+            'current_driver'  => $currentDriver
         ];
     }
 
     private function getBuildInfo(): array
     {
         $return = [
-            'is_docker'       => env('IS_DOCKER', false), // @phpstan-ignore-line
+            'is_docker' => env('IS_DOCKER', false), // @phpstan-ignore-line
             'build'           => '(unknown)',
             'build_date'      => '(unknown)',
             'base_build'      => '(unknown)',
-            'base_build_date' => '(unknown)',
+            'base_build_date' => '(unknown)'
         ];
 
         try {
@@ -230,10 +230,10 @@ class DebugController extends Controller
             Log::debug('Could not check build date, but thats ok.');
             Log::warning($e->getMessage());
         }
-        if ('' !== (string) env('BASE_IMAGE_BUILD')) {       // @phpstan-ignore-line
+        if ('' !== (string) env('BASE_IMAGE_BUILD')) { // @phpstan-ignore-line
             $return['base_build'] = env('BASE_IMAGE_BUILD'); // @phpstan-ignore-line
         }
-        if ('' !== (string) env('BASE_IMAGE_DATE')) {            // @phpstan-ignore-line
+        if ('' !== (string) env('BASE_IMAGE_DATE')) { // @phpstan-ignore-line
             $return['base_build_date'] = env('BASE_IMAGE_DATE'); // @phpstan-ignore-line
         }
 
@@ -242,7 +242,7 @@ class DebugController extends Controller
 
     private function getAppInfo(): array
     {
-        $userGuard      = config('auth.defaults.guard');
+        $userGuard = config('auth.defaults.guard');
 
         $config         = FireflyConfig::get('last_rt_job', 0);
         $lastTime       = (int) $config->data;
@@ -267,26 +267,26 @@ class DebugController extends Controller
             // any of the cron jobs will do, they always run at the same time.
             // but this job is the oldest, so the biggest chance it ran once
 
-            'last_cronjob'       => $lastCronjob,
-            'last_cronjob_ago'   => $lastCronjobAgo,
+            'last_cronjob'     => $lastCronjob,
+            'last_cronjob_ago' => $lastCronjobAgo
         ];
     }
 
     private function getUserInfo(): array
     {
-        $userFlags      = $this->getUserFlags();
+        $userFlags = $this->getUserFlags();
 
         // user info
-        $userAgent      = request()->header('user-agent');
+        $userAgent = request()->header('user-agent');
 
         // set languages, see what happens:
         $original       = setlocale(LC_ALL, '0');
         $localeAttempts = [];
         $parts          = Steam::getLocaleArray(Steam::getLocale());
         foreach ($parts as $code) {
-            $code                  = trim($code);
+            $code = trim($code);
             Log::debug(sprintf('Trying to set %s', $code));
-            $result                = setlocale(LC_ALL, $code);
+            $result = setlocale(LC_ALL, $code);
             $localeAttempts[$code] = $result === $code;
         }
         setlocale(LC_ALL, (string) $original);
@@ -301,16 +301,16 @@ class DebugController extends Controller
             'locale_attempts'    => $localeAttempts,
             'locale'             => Steam::getLocale(),
             'language'           => Steam::getLanguage(),
-            'view_range'         => Preferences::get('viewRange', '1M')->data,
+            'view_range'         => Preferences::get('viewRange', '1M')->data
         ];
     }
 
     private function getUserFlags(): string
     {
-        $flags      = [];
+        $flags = [];
 
         /** @var User $user */
-        $user       = auth()->user();
+        $user = auth()->user();
 
         // has liabilities
         if ($user->accounts()->accountTypeIn([AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value])->count() > 0) {
@@ -326,7 +326,7 @@ class DebugController extends Controller
         }
 
         // has stored reconciliations
-        $type       = TransactionType::whereType(TransactionTypeEnum::RECONCILIATION->value)->first();
+        $type = TransactionType::whereType(TransactionTypeEnum::RECONCILIATION->value)->first();
         if ($user->transactionJournals()->where('transaction_type_id', $type->id)->count() > 0) {
             $flags[] = ':ledger:';
         }
@@ -375,8 +375,7 @@ class DebugController extends Controller
             foreach ($routes as $route) {
                 ++$i;
                 // skip API and other routes.
-                if (!str_starts_with($route->uri(), 'api/v1')
-                ) {
+                if (!str_starts_with($route->uri(), 'api/v1')) {
                     continue;
                 }
                 // skip non GET routes
@@ -387,22 +386,21 @@ class DebugController extends Controller
                 if (null === $route->getName()) {
                     var_dump($route);
 
-                    exit;
+                    exit();
                 }
 
                 echo substr($route->uri(), 3);
-                if (0 === $i % 5) {
+                if (0 === ($i % 5)) {
                     echo '"
PATHS="${PATHS},'; } - if (0 !== $i % 5) { + if (0 !== ($i % 5)) { echo ','; } } - exit; + exit(); } - $return = []; /** @var \Illuminate\Routing\Route $route */ @@ -429,34 +427,33 @@ class DebugController extends Controller if (null === $route->getName()) { var_dump($route); - exit; + exit(); } if (!str_contains($route->uri(), '{')) { - $return[$route->getName()] = route($route->getName()); continue; } - $params = []; + $params = []; foreach ($route->parameterNames() as $name) { $params[] = $this->getParameter($name); } $return[$route->getName()] = route($route->getName(), $params); } - $count = 0; + $count = 0; echo '
'; echo '

Routes

'; echo sprintf('

%s

', $count); foreach ($return as $name => $path) { - echo sprintf('%2$s
', $path, $name).PHP_EOL; + echo sprintf('%2$s
', $path, $name) . PHP_EOL; ++$count; - if (0 === $count % 10) { + if (0 === ($count % 10)) { echo '
'; echo sprintf('

%s

', $count); } } - exit; + exit(); } private function getParameter(string $name): string @@ -552,7 +549,6 @@ class DebugController extends Controller case 'transactionType': return 'withdrawal'; - } } diff --git a/app/Http/Controllers/ExchangeRates/IndexController.php b/app/Http/Controllers/ExchangeRates/IndexController.php index cb3c431ba8..cc746bcf3c 100644 --- a/app/Http/Controllers/ExchangeRates/IndexController.php +++ b/app/Http/Controllers/ExchangeRates/IndexController.php @@ -26,9 +26,9 @@ namespace FireflyIII\Http\Controllers\ExchangeRates; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\TransactionCurrency; +use FireflyIII\Support\Facades\FireflyConfig; use Illuminate\View\View; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; -use FireflyIII\Support\Facades\FireflyConfig; class IndexController extends Controller { @@ -40,14 +40,12 @@ class IndexController extends Controller parent::__construct(); // translations: - $this->middleware( - static function ($request, $next) { - app('view')->share('mainTitleIcon', 'fa-exchange'); - app('view')->share('title', (string) trans('firefly.header_exchange_rates')); + $this->middleware(static function ($request, $next) { + app('view')->share('mainTitleIcon', 'fa-exchange'); + app('view')->share('title', (string) trans('firefly.header_exchange_rates')); - return $next($request); - } - ); + return $next($request); + }); if (false === FireflyConfig::get('enable_exchange_rates', config('cer.enabled'))->data) { throw new NotFoundHttpException(); } @@ -60,6 +58,6 @@ class IndexController extends Controller public function rates(TransactionCurrency $from, TransactionCurrency $to): View { - return view('exchange-rates.rates', ['from' => $from, 'to' => $to]); + return view('exchange-rates.rates', ['from' => $from, 'to' => $to]); } } diff --git a/app/Http/Controllers/Export/IndexController.php b/app/Http/Controllers/Export/IndexController.php index 68223b0fab..b8ed8e9075 100644 --- a/app/Http/Controllers/Export/IndexController.php +++ b/app/Http/Controllers/Export/IndexController.php @@ -52,16 +52,14 @@ class IndexController extends Controller parent::__construct(); // translations: - $this->middleware( - function ($request, $next) { - app('view')->share('mainTitleIcon', 'fa-life-bouy'); - app('view')->share('title', (string) trans('firefly.export_data_title')); - $this->journalRepository = app(JournalRepositoryInterface::class); - $this->middleware(IsDemoUser::class)->except(['index']); + $this->middleware(function ($request, $next) { + app('view')->share('mainTitleIcon', 'fa-life-bouy'); + app('view')->share('title', (string) trans('firefly.export_data_title')); + $this->journalRepository = app(JournalRepositoryInterface::class); + $this->middleware(IsDemoUser::class)->except(['index']); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -85,31 +83,30 @@ class IndexController extends Controller // get first transaction in DB: $firstDate = today(config('app.timezone')); $firstDate->subYear(); - $journal = $this->journalRepository->firstNull(); + $journal = $this->journalRepository->firstNull(); if ($journal instanceof TransactionJournal) { Log::debug('First journal is NULL, using today() - 1 year.'); $firstDate = clone $journal->date; } $generator->setStart($firstDate); - $result = $generator->export(); + $result = $generator->export(); - $name = sprintf('%s_transaction_export.csv', Carbon::now()->format('Y_m_d')); - $quoted = sprintf('"%s"', addcslashes($name, '"\\')); + $name = sprintf('%s_transaction_export.csv', Carbon::now()->format('Y_m_d')); + $quoted = sprintf('"%s"', addcslashes($name, '"\\')); // headers for CSV file. /** @var LaravelResponse $response */ - $response = response($result['transactions']); + $response = response($result['transactions']); $response ->header('Content-Description', 'File Transfer') ->header('Content-Type', 'text/x-csv') - ->header('Content-Disposition', 'attachment; filename='.$quoted) + ->header('Content-Disposition', 'attachment; filename=' . $quoted) // ->header('Content-Transfer-Encoding', 'binary') ->header('Connection', 'Keep-Alive') ->header('Expires', '0') ->header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0') ->header('Pragma', 'public') - ->header('Content-Length', (string) strlen((string) $result['transactions'])) - ; + ->header('Content-Length', (string) strlen((string) $result['transactions'])); // return CSV file made from 'transactions' array. return $response; diff --git a/app/Http/Controllers/HomeController.php b/app/Http/Controllers/HomeController.php index 67118821c6..b4c36d90d0 100644 --- a/app/Http/Controllers/HomeController.php +++ b/app/Http/Controllers/HomeController.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers; -use FireflyIII\Support\Facades\Preferences; use Carbon\Carbon; use Carbon\Exceptions\InvalidFormatException; use Exception; @@ -34,6 +33,7 @@ use FireflyIII\Helpers\Collector\GroupCollectorInterface; use FireflyIII\Http\Middleware\Installer; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Bill\BillRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use FireflyIII\User; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; @@ -63,8 +63,8 @@ class HomeController extends Controller */ public function dateRange(Request $request): JsonResponse { - $stringStart = ''; - $stringEnd = ''; + $stringStart = ''; + $stringEnd = ''; try { $stringStart = e((string) $request->get('start')); @@ -91,7 +91,7 @@ class HomeController extends Controller $label = $request->get('label'); $isCustomRange = false; - Log::debug('dateRange: Received dateRange', ['start' => $stringStart, 'end' => $stringEnd, 'label' => $request->get('label')]); + Log::debug('dateRange: Received dateRange', ['start' => $stringStart, 'end' => $stringEnd, 'label' => $request->get('label')]); // check if the label is "everything" or "Custom range" which will betray // a possible problem with the budgets. if ($label === (string) trans('firefly.everything') || $label === (string) trans('firefly.customRange')) { @@ -99,7 +99,7 @@ class HomeController extends Controller Log::debug('Range is now marked as "custom".'); } - $diff = $start->diffInDays($end, true) + 1; + $diff = $start->diffInDays($end, true) + 1; if ($diff > 366) { $request->session()->flash('warning', (string) trans('firefly.warning_much_data', ['days' => (int) $diff])); @@ -154,13 +154,13 @@ class HomeController extends Controller } /** @var Carbon $start */ - $start = session('start', today(config('app.timezone'))->startOfMonth()); + $start = session('start', today(config('app.timezone'))->startOfMonth()); /** @var Carbon $end */ - $end = session('end', today(config('app.timezone'))->endOfMonth()); - $accounts = $repository->getAccountsById($frontpageArray); - $today = today(config('app.timezone')); - $accounts = $accounts->sortBy('order'); // sort frontpage accounts by order + $end = session('end', today(config('app.timezone'))->endOfMonth()); + $accounts = $repository->getAccountsById($frontpageArray); + $today = today(config('app.timezone')); + $accounts = $accounts->sortBy('order'); // sort frontpage accounts by order Log::debug('Frontpage accounts are ', $frontpageArray); @@ -170,17 +170,26 @@ class HomeController extends Controller // collect groups for each transaction. foreach ($accounts as $account) { /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setAccounts(new Collection()->push($account))->withAccountInformation()->setRange($start, $end)->setLimit(10)->setPage(1); - $set = $collector->getExtractedJournals(); - $transactions[] = ['transactions' => $set, 'account' => $account]; + $set = $collector->getExtractedJournals(); + $transactions[] = ['transactions' => $set, 'account' => $account]; } /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); event(new RequestedVersionCheckStatus($user)); - return view('index', ['count' => $count, 'subTitle' => $subTitle, 'transactions' => $transactions, 'billCount' => $billCount, 'start' => $start, 'end' => $end, 'today' => $today, 'pageTitle' => $pageTitle]); + return view('index', [ + 'count' => $count, + 'subTitle' => $subTitle, + 'transactions' => $transactions, + 'billCount' => $billCount, + 'start' => $start, + 'end' => $end, + 'today' => $today, + 'pageTitle' => $pageTitle + ]); } private function indexV2(): mixed @@ -188,13 +197,13 @@ class HomeController extends Controller $subTitle = (string) trans('firefly.welcome_back'); $pageTitle = (string) trans('firefly.main_dashboard_page_title'); - $start = session('start', today(config('app.timezone'))->startOfMonth()); - $end = session('end', today(config('app.timezone'))->endOfMonth()); + $start = session('start', today(config('app.timezone'))->startOfMonth()); + $end = session('end', today(config('app.timezone'))->endOfMonth()); /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); event(new RequestedVersionCheckStatus($user)); - return view('index', ['subTitle' => $subTitle, 'start' => $start, 'end' => $end, 'pageTitle' => $pageTitle]); + return view('index', ['subTitle' => $subTitle, 'start' => $start, 'end' => $end, 'pageTitle' => $pageTitle]); } } diff --git a/app/Http/Controllers/JavascriptController.php b/app/Http/Controllers/JavascriptController.php index 7eabd033f3..38ade39a93 100644 --- a/app/Http/Controllers/JavascriptController.php +++ b/app/Http/Controllers/JavascriptController.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers; -use FireflyIII\Support\Facades\Preferences; use Carbon\Carbon; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Exceptions\FireflyException; @@ -31,13 +30,14 @@ use FireflyIII\Models\Account; use FireflyIII\Models\TransactionCurrency; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; +use FireflyIII\Support\Facades\Amount; +use FireflyIII\Support\Facades\Preferences; use FireflyIII\Support\Facades\Steam; use FireflyIII\Support\Http\Controllers\GetConfigurationData; use Illuminate\Http\Request; use Illuminate\Http\Response; use Psr\Container\ContainerExceptionInterface; use Psr\Container\NotFoundExceptionInterface; -use FireflyIII\Support\Facades\Amount; /** * Class JavascriptController. @@ -51,24 +51,26 @@ class JavascriptController extends Controller */ public function accounts(AccountRepositoryInterface $repository): Response { - $accounts = $repository->getAccountsByType( - [AccountTypeEnum::DEFAULT->value, AccountTypeEnum::ASSET->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::CREDITCARD->value] - ); - $data = ['accounts' => []]; + $accounts = $repository->getAccountsByType([ + AccountTypeEnum::DEFAULT->value, + AccountTypeEnum::ASSET->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::MORTGAGE->value, + AccountTypeEnum::CREDITCARD->value + ]); + $data = ['accounts' => []]; /** @var Account $account */ foreach ($accounts as $account) { - $accountId = $account->id; - $currency = (int) $repository->getMetaValue($account, 'currency_id'); - $currency = 0 === $currency ? $this->primaryCurrency->id : $currency; - $entry = ['preferredCurrency' => $currency, 'name' => $account->name]; + $accountId = $account->id; + $currency = (int) $repository->getMetaValue($account, 'currency_id'); + $currency = 0 === $currency ? $this->primaryCurrency->id : $currency; + $entry = ['preferredCurrency' => $currency, 'name' => $account->name]; $data['accounts'][$accountId] = $entry; } - return response() - ->view('javascript.accounts', $data) - ->header('Content-Type', 'text/javascript') - ; + return response()->view('javascript.accounts', $data)->header('Content-Type', 'text/javascript'); } /** @@ -77,19 +79,16 @@ class JavascriptController extends Controller public function currencies(CurrencyRepositoryInterface $repository): Response { $currencies = $repository->get(); - $data = ['currencies' => []]; + $data = ['currencies' => []]; /** @var TransactionCurrency $currency */ foreach ($currencies as $currency) { - $currencyId = $currency->id; - $entry = ['name' => $currency->name, 'code' => $currency->code, 'symbol' => $currency->symbol]; + $currencyId = $currency->id; + $entry = ['name' => $currency->name, 'code' => $currency->code, 'symbol' => $currency->symbol]; $data['currencies'][$currencyId] = $entry; } - return response() - ->view('javascript.currencies', $data) - ->header('Content-Type', 'text/javascript') - ; + return response()->view('javascript.currencies', $data)->header('Content-Type', 'text/javascript'); } /** @@ -101,19 +100,19 @@ class JavascriptController extends Controller */ public function variables(Request $request, AccountRepositoryInterface $repository): Response { - $account = $repository->find((int) $request->get('account')); - $currency = $this->primaryCurrency; + $account = $repository->find((int) $request->get('account')); + $currency = $this->primaryCurrency; if ($account instanceof Account) { $currency = $repository->getAccountCurrency($account) ?? $this->primaryCurrency; } - $locale = Steam::getLocale(); - $accounting = Amount::getJsConfig(); + $locale = Steam::getLocale(); + $accounting = Amount::getJsConfig(); $accounting['frac_digits'] = $currency->decimal_places; - $pref = Preferences::get('language', config('firefly.default_language', 'en_US')); - $lang = $pref->data; - $dateRange = $this->getDateRangeConfig(); - $uid = substr(hash('sha256', sprintf('%s-%s-%s', (string) config('app.key'), auth()->user()->id, auth()->user()->email)), 0, 12); - $data = [ + $pref = Preferences::get('language', config('firefly.default_language', 'en_US')); + $lang = $pref->data; + $dateRange = $this->getDateRangeConfig(); + $uid = substr(hash('sha256', sprintf('%s-%s-%s', (string) config('app.key'), auth()->user()->id, auth()->user()->email)), 0, 12); + $data = [ 'currencyCode' => $currency->code, 'currencySymbol' => $currency->symbol, 'accountingLocaleInfo' => $accounting, @@ -122,14 +121,11 @@ class JavascriptController extends Controller 'dateRangeTitle' => $dateRange['title'], 'locale' => $locale, 'dateRangeConfig' => $dateRange['configuration'], - 'uid' => $uid, + 'uid' => $uid ]; $request->session()->keep(['two-factor-secret']); - return response() - ->view('javascript.variables', $data) - ->header('Content-Type', 'text/javascript') - ; + return response()->view('javascript.variables', $data)->header('Content-Type', 'text/javascript'); } /** @@ -141,16 +137,10 @@ class JavascriptController extends Controller $start = clone session('start', today(config('app.timezone'))->startOfMonth()); /** @var Carbon $end */ - $end = clone session('end', today(config('app.timezone'))->endOfMonth()); + $end = clone session('end', today(config('app.timezone'))->endOfMonth()); - $data = [ - 'start' => $start->format('Y-m-d'), - 'end' => $end->format('Y-m-d'), - ]; + $data = ['start' => $start->format('Y-m-d'), 'end' => $end->format('Y-m-d')]; - return response() - ->view('v2.javascript.variables', $data) - ->header('Content-Type', 'text/javascript') - ; + return response()->view('v2.javascript.variables', $data)->header('Content-Type', 'text/javascript'); } } diff --git a/app/Http/Controllers/Json/BoxController.php b/app/Http/Controllers/Json/BoxController.php index 36d0832bc9..0cf87b23d8 100644 --- a/app/Http/Controllers/Json/BoxController.php +++ b/app/Http/Controllers/Json/BoxController.php @@ -63,11 +63,11 @@ class BoxController extends Controller { // Cache result, return cache if present. /** @var Carbon $start */ - $start = session('start', today(config('app.timezone'))->startOfMonth()); + $start = session('start', today(config('app.timezone'))->startOfMonth()); /** @var Carbon $end */ - $end = session('end', today(config('app.timezone'))->endOfMonth()); - $cache = new CacheProperties(); + $end = session('end', today(config('app.timezone'))->endOfMonth()); + $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty($this->convertToPrimary); @@ -76,69 +76,61 @@ class BoxController extends Controller return response()->json($cache->get()); } // prep some arrays: - $incomes = []; - $expenses = []; - $sums = []; - $currency = $this->primaryCurrency; + $incomes = []; + $expenses = []; + $sums = []; + $currency = $this->primaryCurrency; // collect income of user: /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); - $collector->setRange($start, $end) - ->setTypes([TransactionTypeEnum::DEPOSIT->value]) - ; - $set = $collector->getExtractedJournals(); + $collector->setRange($start, $end)->setTypes([TransactionTypeEnum::DEPOSIT->value]); + $set = $collector->getExtractedJournals(); /** @var array $journal */ foreach ($set as $journal) { - $currencyId = $this->convertToPrimary && $this->primaryCurrency->id !== (int) $journal['currency_id'] ? $this->primaryCurrency->id : (int) $journal['currency_id']; - $amount = Amount::getAmountFromJournal($journal); + $currencyId = $this->convertToPrimary && $this->primaryCurrency->id !== (int) $journal['currency_id'] + ? $this->primaryCurrency->id + : (int) $journal['currency_id']; + $amount = Amount::getAmountFromJournal($journal); $incomes[$currencyId] ??= '0'; $incomes[$currencyId] = bcadd($incomes[$currencyId], Steam::positive($amount)); - $sums[$currencyId] ??= '0'; - $sums[$currencyId] = bcadd($sums[$currencyId], Steam::positive($amount)); + $sums[$currencyId] ??= '0'; + $sums[$currencyId] = bcadd($sums[$currencyId], Steam::positive($amount)); } // collect expenses /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); - $collector->setRange($start, $end) - ->setTypes([TransactionTypeEnum::WITHDRAWAL->value]) - ; - $set = $collector->getExtractedJournals(); + $collector->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value]); + $set = $collector->getExtractedJournals(); /** @var array $journal */ foreach ($set as $journal) { - $currencyId = $this->convertToPrimary ? $this->primaryCurrency->id : (int) $journal['currency_id']; - $amount = Amount::getAmountFromJournal($journal); + $currencyId = $this->convertToPrimary ? $this->primaryCurrency->id : (int) $journal['currency_id']; + $amount = Amount::getAmountFromJournal($journal); $expenses[$currencyId] ??= '0'; $expenses[$currencyId] = bcadd($expenses[$currencyId], $amount); - $sums[$currencyId] ??= '0'; - $sums[$currencyId] = bcadd($sums[$currencyId], $amount); + $sums[$currencyId] ??= '0'; + $sums[$currencyId] = bcadd($sums[$currencyId], $amount); } // format amounts: - $keys = array_keys($sums); + $keys = array_keys($sums); foreach ($keys as $currencyId) { - $currency = $repository->find($currencyId); - $sums[$currencyId] = Amount::formatAnything($currency, $sums[$currencyId], false); - $incomes[$currencyId] = Amount::formatAnything($currency, $incomes[$currencyId] ?? '0', false); + $currency = $repository->find($currencyId); + $sums[$currencyId] = Amount::formatAnything($currency, $sums[$currencyId], false); + $incomes[$currencyId] = Amount::formatAnything($currency, $incomes[$currencyId] ?? '0', false); $expenses[$currencyId] = Amount::formatAnything($currency, $expenses[$currencyId] ?? '0', false); } if (0 === count($sums)) { - $currency = $this->primaryCurrency; - $sums[$this->primaryCurrency->id] = Amount::formatAnything($this->primaryCurrency, '0', false); - $incomes[$this->primaryCurrency->id] = Amount::formatAnything($this->primaryCurrency, '0', false); + $currency = $this->primaryCurrency; + $sums[$this->primaryCurrency->id] = Amount::formatAnything($this->primaryCurrency, '0', false); + $incomes[$this->primaryCurrency->id] = Amount::formatAnything($this->primaryCurrency, '0', false); $expenses[$this->primaryCurrency->id] = Amount::formatAnything($this->primaryCurrency, '0', false); } - $response = [ - 'incomes' => $incomes, - 'expenses' => $expenses, - 'sums' => $sums, - 'size' => count($sums), - 'preferred' => $currency->id, - ]; + $response = ['incomes' => $incomes, 'expenses' => $expenses, 'sums' => $sums, 'size' => count($sums), 'preferred' => $currency->id]; $cache->store($response); return response()->json($response); @@ -149,7 +141,7 @@ class BoxController extends Controller */ public function netWorth(): JsonResponse { - $date = today(config('app.timezone'))->endOfDay(); + $date = today(config('app.timezone'))->endOfDay(); // start and end in the future? use $end if ($this->notInSessionRange($date)) { @@ -158,40 +150,40 @@ class BoxController extends Controller } /** @var NetWorthInterface $netWorthHelper */ - $netWorthHelper = app(NetWorthInterface::class); + $netWorthHelper = app(NetWorthInterface::class); $netWorthHelper->setUser(auth()->user()); /** @var AccountRepositoryInterface $accountRepository */ $accountRepository = app(AccountRepositoryInterface::class); - $allAccounts = $accountRepository->getActiveAccountsByType( - [AccountTypeEnum::DEFAULT->value, AccountTypeEnum::ASSET->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value] - ); + $allAccounts = $accountRepository->getActiveAccountsByType([ + AccountTypeEnum::DEFAULT->value, + AccountTypeEnum::ASSET->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::MORTGAGE->value + ]); Log::debug(sprintf('Found %d accounts.', $allAccounts->count())); // filter list on preference of being included. - $filtered = $allAccounts->filter( - static function (Account $account) use ($accountRepository): bool { - $includeNetWorth = $accountRepository->getMetaValue($account, 'include_net_worth'); - $result = null === $includeNetWorth || '1' === $includeNetWorth; - if (false === $result) { - Log::debug(sprintf('Will not include "%s" in net worth charts.', $account->name)); - } - - return $result; + $filtered = $allAccounts->filter(static function (Account $account) use ($accountRepository): bool { + $includeNetWorth = $accountRepository->getMetaValue($account, 'include_net_worth'); + $result = null === $includeNetWorth || '1' === $includeNetWorth; + if (false === $result) { + Log::debug(sprintf('Will not include "%s" in net worth charts.', $account->name)); } - ); - $netWorthSet = $netWorthHelper->byAccounts($filtered, $date); - $return = []; + return $result; + }); + + $netWorthSet = $netWorthHelper->byAccounts($filtered, $date); + $return = []; foreach ($netWorthSet as $key => $data) { if ('primary' === $key) { continue; } $return[$data['currency_id']] = Amount::formatFlat($data['currency_symbol'], $data['currency_decimal_places'], $data['balance'], false); } - $return = [ - 'net_worths' => array_values($return), - ]; + $return = ['net_worths' => array_values($return)]; return response()->json($return); } diff --git a/app/Http/Controllers/Json/BudgetController.php b/app/Http/Controllers/Json/BudgetController.php index dce9b244ca..c4da7bafaa 100644 --- a/app/Http/Controllers/Json/BudgetController.php +++ b/app/Http/Controllers/Json/BudgetController.php @@ -31,9 +31,9 @@ use FireflyIII\Models\TransactionCurrency; use FireflyIII\Repositories\Budget\AvailableBudgetRepositoryInterface; use FireflyIII\Repositories\Budget\BudgetLimitRepositoryInterface; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; +use FireflyIII\Support\Facades\Amount; use FireflyIII\Support\Http\Controllers\DateCalculation; use Illuminate\Http\JsonResponse; -use FireflyIII\Support\Facades\Amount; /** * Class BudgetController @@ -43,8 +43,8 @@ class BudgetController extends Controller use DateCalculation; private AvailableBudgetRepositoryInterface $abRepository; - private BudgetLimitRepositoryInterface $blRepository; - private BudgetRepositoryInterface $repository; + private BudgetLimitRepositoryInterface $blRepository; + private BudgetRepositoryInterface $repository; /** * IndexController constructor. @@ -53,18 +53,16 @@ class BudgetController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.budgets')); - app('view')->share('mainTitleIcon', 'fa-pie-chart'); - $this->repository = app(BudgetRepositoryInterface::class); - $this->abRepository = app(AvailableBudgetRepositoryInterface::class); - $this->blRepository = app(BudgetLimitRepositoryInterface::class); - $this->repository->cleanupBudgets(); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.budgets')); + app('view')->share('mainTitleIcon', 'fa-pie-chart'); + $this->repository = app(BudgetRepositoryInterface::class); + $this->abRepository = app(AvailableBudgetRepositoryInterface::class); + $this->blRepository = app(BudgetLimitRepositoryInterface::class); + $this->repository->cleanupBudgets(); - return $next($request); - } - ); + return $next($request); + }); } public function getBudgetInformation(TransactionCurrency $currency, Carbon $start, Carbon $end): JsonResponse @@ -82,19 +80,17 @@ class BudgetController extends Controller } // if available, get the AB for this period + currency, so the bar can be redrawn. - return response()->json( - [ - 'budgeted' => $budgeted, - 'budgeted_formatted' => Amount::formatAnything($currency, $budgeted, true), - 'available' => $available, - 'available_formatted' => Amount::formatAnything($currency, $available, true), - 'percentage' => $percentage, - 'currency_id' => $currency->id, - 'currency_code' => $currency->code, - 'currency_symbol' => $currency->symbol, - 'currency_name' => $currency->name, - 'currency_decimal_places' => $currency->decimal_places, - ] - ); + return response()->json([ + 'budgeted' => $budgeted, + 'budgeted_formatted' => Amount::formatAnything($currency, $budgeted, true), + 'available' => $available, + 'available_formatted' => Amount::formatAnything($currency, $available, true), + 'percentage' => $percentage, + 'currency_id' => $currency->id, + 'currency_code' => $currency->code, + 'currency_symbol' => $currency->symbol, + 'currency_name' => $currency->name, + 'currency_decimal_places' => $currency->decimal_places + ]); } } diff --git a/app/Http/Controllers/Json/FrontpageController.php b/app/Http/Controllers/Json/FrontpageController.php index e884ab789a..5c64ba6f73 100644 --- a/app/Http/Controllers/Json/FrontpageController.php +++ b/app/Http/Controllers/Json/FrontpageController.php @@ -23,12 +23,12 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Json; -use Illuminate\Support\Facades\Log; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\PiggyBank; use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface; use Illuminate\Http\JsonResponse; +use Illuminate\Support\Facades\Log; use Throwable; /** @@ -46,32 +46,30 @@ class FrontpageController extends Controller $set = $repository->getPiggyBanks(); $info = []; - /** @var PiggyBank $piggyBank */ foreach ($set as $piggyBank) { $amount = $repository->getCurrentAmount($piggyBank); $pcAmount = $repository->getCurrentPrimaryCurrencyAmount($piggyBank); if (1 === bccomp($amount, '0')) { // percentage! - $pct = 0; + $pct = 0; if (0 !== bccomp((string) $piggyBank->target_amount, '0')) { $pct = (int) bcmul(bcdiv($amount, (string) $piggyBank->target_amount), '100'); } - $entry = [ - 'id' => $piggyBank->id, - 'name' => $piggyBank->name, - 'amount' => $amount, - 'pc_amount' => $pcAmount, - 'target' => $piggyBank->target_amount, - 'pc_target' => $piggyBank->native_target_amount, - 'percentage' => $pct, + $entry = [ + 'id' => $piggyBank->id, + 'name' => $piggyBank->name, + 'amount' => $amount, + 'pc_amount' => $pcAmount, + 'target' => $piggyBank->target_amount, + 'pc_target' => $piggyBank->native_target_amount, + 'percentage' => $pct, // currency: 'currency_symbol' => $piggyBank->transactionCurrency->symbol, 'currency_decimal_places' => $piggyBank->transactionCurrency->decimal_places, 'primary_currency_symbol' => $this->primaryCurrency->symbol, - 'primary_currency_decimal_places' => $this->primaryCurrency->decimal_places, - + 'primary_currency_decimal_places' => $this->primaryCurrency->decimal_places ]; $info[] = $entry; @@ -79,17 +77,18 @@ class FrontpageController extends Controller } // sort by current percentage (lowest at the top) - uasort( - $info, - static fn (array $a, array $b): int => $a['percentage'] <=> $b['percentage'] - ); + uasort($info, static fn(array $a, array $b): int => $a['percentage'] <=> $b['percentage']); $html = ''; if (0 !== count($info)) { try { $convertToPrimary = $this->convertToPrimary; $primary = $this->primaryCurrency; - $html = view('json.piggy-banks', ['info' => $info, 'convertToPrimary' => $convertToPrimary, 'primary' => $primary])->render(); + $html = view('json.piggy-banks', [ + 'info' => $info, + 'convertToPrimary' => $convertToPrimary, + 'primary' => $primary + ])->render(); } catch (Throwable $e) { Log::error(sprintf('Cannot render json.piggy-banks: %s', $e->getMessage())); Log::error($e->getTraceAsString()); diff --git a/app/Http/Controllers/Json/IntroController.php b/app/Http/Controllers/Json/IntroController.php index 30badd5350..4af241a1d6 100644 --- a/app/Http/Controllers/Json/IntroController.php +++ b/app/Http/Controllers/Json/IntroController.php @@ -23,11 +23,11 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Json; -use FireflyIII\Support\Facades\Preferences; -use Illuminate\Support\Facades\Log; use FireflyIII\Http\Controllers\Controller; +use FireflyIII\Support\Facades\Preferences; use FireflyIII\Support\Http\Controllers\GetConfigurationData; use Illuminate\Http\JsonResponse; +use Illuminate\Support\Facades\Log; /** * Class IntroController. @@ -39,10 +39,10 @@ class IntroController extends Controller /** * Returns the introduction wizard for a page. */ - public function getIntroSteps(string $route, ?string $specificPage = null): JsonResponse + public function getIntroSteps(string $route, null|string $specificPage = null): JsonResponse { Log::debug(sprintf('getIntroSteps for route "%s" and page "%s"', $route, $specificPage)); - $specificPage ??= ''; + $specificPage ??= ''; $steps = $this->getBasicSteps($route); $specificSteps = $this->getSpecificSteps($route, $specificPage); if (0 === count($specificSteps)) { @@ -56,8 +56,8 @@ class IntroController extends Controller // remove last step: array_pop($steps); // merge arrays and add last step again - $steps = array_merge($steps, $specificSteps); - $steps[] = $lastStep; + $steps = array_merge($steps, $specificSteps); + $steps[] = $lastStep; } if (!$this->hasOutroStep($route)) { $steps = array_merge($steps, $specificSteps); @@ -78,7 +78,7 @@ class IntroController extends Controller return false; } - $hasStep = array_key_exists('outro', $elements); + $hasStep = array_key_exists('outro', $elements); Log::debug('Elements is array', $elements); Log::debug('Keys is', array_keys($elements)); @@ -90,11 +90,11 @@ class IntroController extends Controller /** * Enable the boxes for a specific page again. */ - public function postEnable(string $route, ?string $specialPage = null): JsonResponse + public function postEnable(string $route, null|string $specialPage = null): JsonResponse { $specialPage ??= ''; - $route = str_replace('.', '_', $route); - $key = sprintf('shown_demo_%s', $route); + $route = str_replace('.', '_', $route); + $key = sprintf('shown_demo_%s', $route); if ('' !== $specialPage) { $key = sprintf('%s_%s', $key, $specialPage); } @@ -108,10 +108,10 @@ class IntroController extends Controller /** * Set that you saw them. */ - public function postFinished(string $route, ?string $specialPage = null): JsonResponse + public function postFinished(string $route, null|string $specialPage = null): JsonResponse { $specialPage ??= ''; - $key = sprintf('shown_demo_%s', $route); + $key = sprintf('shown_demo_%s', $route); if ('' !== $specialPage) { $key = sprintf('%s_%s', $key, $specialPage); } diff --git a/app/Http/Controllers/Json/ReconcileController.php b/app/Http/Controllers/Json/ReconcileController.php index f68569b6d8..574cc74608 100644 --- a/app/Http/Controllers/Json/ReconcileController.php +++ b/app/Http/Controllers/Json/ReconcileController.php @@ -54,15 +54,13 @@ class ReconcileController extends Controller parent::__construct(); // translations: - $this->middleware( - function ($request, $next) { - app('view')->share('mainTitleIcon', 'fa-credit-card'); - app('view')->share('title', (string) trans('firefly.accounts')); - $this->accountRepos = app(AccountRepositoryInterface::class); + $this->middleware(function ($request, $next) { + app('view')->share('mainTitleIcon', 'fa-credit-card'); + app('view')->share('title', (string) trans('firefly.accounts')); + $this->accountRepos = app(AccountRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -70,7 +68,7 @@ class ReconcileController extends Controller * * @throws FireflyException */ - public function overview(Request $request, ?Account $account = null, ?Carbon $start = null, ?Carbon $end = null): JsonResponse + public function overview(Request $request, null|Account $account = null, null|Carbon $start = null, null|Carbon $end = null): JsonResponse { $startBalance = $request->get('startBalance'); $endBalance = $request->get('endBalance'); @@ -103,13 +101,13 @@ class ReconcileController extends Controller /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); $collector->setJournalIds($selectedIds); - $journals = $collector->getExtractedJournals(); + $journals = $collector->getExtractedJournals(); } // Collect all journals already reconciled if (count($clearedIds) > 0) { /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setJournalIds($clearedIds); $clearedJournals = $collector->getExtractedJournals(); } @@ -130,13 +128,27 @@ class ReconcileController extends Controller Log::debug(sprintf('End balance: "%s"', $endBalance)); Log::debug(sprintf('Cleared amount: "%s"', $clearedAmount)); Log::debug(sprintf('Amount: "%s"', $amount)); - $difference = bcadd(bcadd(bcsub($startBalance ?? '0', $endBalance ?? '0'), $clearedAmount), $amount); - $diffCompare = bccomp($difference, '0'); - $countCleared = count($clearedJournals); - $reconSum = bcadd(bcadd($startBalance ?? '0', $amount), $clearedAmount); + $difference = bcadd(bcadd(bcsub($startBalance ?? '0', $endBalance ?? '0'), $clearedAmount), $amount); + $diffCompare = bccomp($difference, '0'); + $countCleared = count($clearedJournals); + $reconSum = bcadd(bcadd($startBalance ?? '0', $amount), $clearedAmount); try { - $view = view('accounts.reconcile.overview', ['account' => $account, 'start' => $start, 'diffCompare' => $diffCompare, 'difference' => $difference, 'end' => $end, 'clearedAmount' => $clearedAmount, 'startBalance' => $startBalance, 'endBalance' => $endBalance, 'amount' => $amount, 'route' => $route, 'countCleared' => $countCleared, 'reconSum' => $reconSum, 'selectedIds' => $selectedIds])->render(); + $view = view('accounts.reconcile.overview', [ + 'account' => $account, + 'start' => $start, + 'diffCompare' => $diffCompare, + 'difference' => $difference, + 'end' => $end, + 'clearedAmount' => $clearedAmount, + 'startBalance' => $startBalance, + 'endBalance' => $endBalance, + 'amount' => $amount, + 'route' => $route, + 'countCleared' => $countCleared, + 'reconSum' => $reconSum, + 'selectedIds' => $selectedIds + ])->render(); } catch (Throwable $e) { Log::debug(sprintf('View error: %s', $e->getMessage())); Log::error($e->getTraceAsString()); @@ -145,14 +157,14 @@ class ReconcileController extends Controller throw new FireflyException($view, 0, $e); } - $return = ['post_url' => $route, 'html' => $view]; + $return = ['post_url' => $route, 'html' => $view]; return response()->json($return); } private function processJournal(Account $account, TransactionCurrency $currency, array $journal, string $amount): string { - $toAdd = '0'; + $toAdd = '0'; Log::debug(sprintf('User submitted %s #%d: "%s"', $journal['transaction_type_type'], $journal['transaction_journal_id'], $journal['description'])); // not much magic below we need to cover using tests. @@ -188,7 +200,7 @@ class ReconcileController extends Controller * * @throws FireflyException */ - public function transactions(Account $account, ?Carbon $start = null, ?Carbon $end = null) + public function transactions(Account $account, null|Carbon $start = null, null|Carbon $end = null) { if (!$start instanceof Carbon || !$end instanceof Carbon) { throw new FireflyException('Invalid dates submitted.'); @@ -198,10 +210,10 @@ class ReconcileController extends Controller } $start->endOfDay(); $end->endOfDay(); - $startDate = clone $start; + $startDate = clone $start; $startDate->subDay(); - $currency = $this->accountRepos->getAccountCurrency($account) ?? $this->primaryCurrency; + $currency = $this->accountRepos->getAccountCurrency($account) ?? $this->primaryCurrency; // correct Log::debug(sprintf('transactions: Call accountsBalancesOptimized with date/time "%s"', $startDate->toIso8601String())); Log::debug(sprintf('transactions2: Call accountsBalancesOptimized with date/time "%s"', $end->toIso8601String())); @@ -210,8 +222,8 @@ class ReconcileController extends Controller // $startBalance = Steam::bcround(Steam::finalAccountBalance($account, $startDate)['balance'], $currency->decimal_places); // $endBalance = Steam::bcround(Steam::finalAccountBalance($account, $end)['balance'], $currency->decimal_places); - $startBalance = Steam::accountsBalancesOptimized(new Collection()->push($account), $startDate)[$account->id]; - $endBalance = Steam::accountsBalancesOptimized(new Collection()->push($account), $end)[$account->id]; + $startBalance = Steam::accountsBalancesOptimized(new Collection()->push($account), $startDate)[$account->id]; + $endBalance = Steam::accountsBalancesOptimized(new Collection()->push($account), $end)[$account->id]; // round balances. foreach ($startBalance as $key => $value) { $startBalance[$key] = Steam::bcround($value, $currency->decimal_places); @@ -220,12 +232,11 @@ class ReconcileController extends Controller $endBalance[$key] = Steam::bcround($value, $currency->decimal_places); } - // get the transactions $selectionStart = clone $start; $selectionStart->startOfDay(); $selectionStart->subDays(3); - $selectionEnd = clone $end; + $selectionEnd = clone $end; $selectionEnd->endOfDay(); $selectionEnd->addDays(3); @@ -234,20 +245,27 @@ class ReconcileController extends Controller // grab transactions: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); - $collector->setAccounts(new Collection()->push($account)) + $collector + ->setAccounts(new Collection()->push($account)) ->setRange($selectionStart, $selectionEnd) - ->withBudgetInformation()->withCategoryInformation()->withAccountInformation() - ; - $array = $collector->getExtractedJournals(); - $journals = $this->processTransactions($account, $array); + ->withBudgetInformation() + ->withCategoryInformation() + ->withAccountInformation(); + $array = $collector->getExtractedJournals(); + $journals = $this->processTransactions($account, $array); try { - $html = view( - 'accounts.reconcile.transactions', - ['account' => $account, 'journals' => $journals, 'currency' => $currency, 'start' => $start, 'end' => $end, 'selectionStart' => $selectionStart, 'selectionEnd' => $selectionEnd] - )->render(); + $html = view('accounts.reconcile.transactions', [ + 'account' => $account, + 'journals' => $journals, + 'currency' => $currency, + 'start' => $start, + 'end' => $end, + 'selectionStart' => $selectionStart, + 'selectionEnd' => $selectionEnd + ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render: %s', $e->getMessage())); Log::error($e->getTraceAsString()); @@ -256,7 +274,7 @@ class ReconcileController extends Controller throw new FireflyException($html, 0, $e); } - return response()->json(['html' => $html, 'startBalance' => $startBalance, 'endBalance' => $endBalance]); + return response()->json(['html' => $html, 'startBalance' => $startBalance, 'endBalance' => $endBalance]); } /** @@ -268,7 +286,7 @@ class ReconcileController extends Controller /** @var array $journal */ foreach ($array as $journal) { - $inverse = false; + $inverse = false; if (TransactionTypeEnum::DEPOSIT->value === $journal['transaction_type_type']) { $inverse = true; @@ -279,8 +297,7 @@ class ReconcileController extends Controller } // opening balance into account? then positive amount: - if (TransactionTypeEnum::OPENING_BALANCE->value === $journal['transaction_type_type'] - && $account->id === $journal['destination_account_id']) { + if (TransactionTypeEnum::OPENING_BALANCE->value === $journal['transaction_type_type'] && $account->id === $journal['destination_account_id']) { $inverse = true; } diff --git a/app/Http/Controllers/Json/RecurrenceController.php b/app/Http/Controllers/Json/RecurrenceController.php index 7e2c80a3c4..84df7c15a5 100644 --- a/app/Http/Controllers/Json/RecurrenceController.php +++ b/app/Http/Controllers/Json/RecurrenceController.php @@ -24,16 +24,16 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Json; -use Illuminate\Support\Facades\Log; use Carbon\Carbon; use Carbon\Exceptions\InvalidFormatException; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\RecurrenceRepetition; use FireflyIII\Repositories\Recurring\RecurringRepositoryInterface; +use FireflyIII\Support\Facades\Steam; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; -use FireflyIII\Support\Facades\Steam; +use Illuminate\Support\Facades\Log; /** * Class RecurrenceController @@ -50,13 +50,11 @@ class RecurrenceController extends Controller parent::__construct(); // translations: - $this->middleware( - function ($request, $next) { - $this->recurring = app(RecurringRepositoryInterface::class); + $this->middleware(function ($request, $next) { + $this->recurring = app(RecurringRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -69,20 +67,20 @@ class RecurrenceController extends Controller */ public function events(Request $request): JsonResponse { - $occurrences = []; - $return = []; - $start = Carbon::createFromFormat('Y-m-d', $request->get('start')); - $end = Carbon::createFromFormat('Y-m-d', $request->get('end')); - $firstDate = Carbon::createFromFormat('Y-m-d', $request->get('first_date')); - $endDate = '' !== (string) $request->get('end_date') ? Carbon::createFromFormat('Y-m-d', $request->get('end_date')) : null; - $endsAt = (string) $request->get('ends'); - $repetitionType = explode(',', (string) $request->get('type'))[0]; - $repetitions = (int) $request->get('reps'); - $weekend = (int) $request->get('weekend'); - $repetitionMoment = ''; - $skip = (int) $request->get('skip'); - $skip = $skip < 0 || $skip > 31 ? 0 : $skip; - $weekend = $weekend < 1 || $weekend > 4 ? 1 : $weekend; + $occurrences = []; + $return = []; + $start = Carbon::createFromFormat('Y-m-d', $request->get('start')); + $end = Carbon::createFromFormat('Y-m-d', $request->get('end')); + $firstDate = Carbon::createFromFormat('Y-m-d', $request->get('first_date')); + $endDate = '' !== (string) $request->get('end_date') ? Carbon::createFromFormat('Y-m-d', $request->get('end_date')) : null; + $endsAt = (string) $request->get('ends'); + $repetitionType = explode(',', (string) $request->get('type'))[0]; + $repetitions = (int) $request->get('reps'); + $weekend = (int) $request->get('weekend'); + $repetitionMoment = ''; + $skip = (int) $request->get('skip'); + $skip = $skip < 0 || $skip > 31 ? 0 : $skip; + $weekend = $weekend < 1 || $weekend > 4 ? 1 : $weekend; if (!$endDate instanceof Carbon) { // safety catch: @@ -100,7 +98,7 @@ class RecurrenceController extends Controller return response()->json(); } // if $firstDate is beyond start, use that one: - $actualStart = clone $firstDate; + $actualStart = clone $firstDate; if ('weekly' === $repetitionType || 'monthly' === $repetitionType) { $repetitionMoment = explode(',', (string) $request->get('type'))[1] ?? '1'; @@ -112,12 +110,12 @@ class RecurrenceController extends Controller $repetitionMoment = explode(',', (string) $request->get('type'))[1] ?? '2025-01-01'; } $actualStart->startOfDay(); - $repetition = new RecurrenceRepetition(); - $repetition->repetition_type = $repetitionType; + $repetition = new RecurrenceRepetition(); + $repetition->repetition_type = $repetitionType; $repetition->repetition_moment = $repetitionMoment; - $repetition->repetition_skip = $skip; - $repetition->weekend = $weekend; - $actualEnd = clone $end; + $repetition->repetition_skip = $skip; + $repetition->weekend = $weekend; + $actualEnd = clone $end; if ('until_date' === $endsAt) { $actualEnd = $endDate; @@ -134,14 +132,14 @@ class RecurrenceController extends Controller /** @var Carbon $current */ foreach ($occurrences as $current) { if ($current->gte($start)) { - $event = [ - 'id' => $repetitionType.$firstDate->format('Ymd'), + $event = [ + 'id' => $repetitionType . $firstDate->format('Ymd'), 'title' => 'X', 'allDay' => true, 'start' => $current->format('Y-m-d'), 'end' => $current->format('Y-m-d'), 'editable' => false, - 'rendering' => 'background', + 'rendering' => 'background' ]; $return[] = $event; } @@ -155,8 +153,8 @@ class RecurrenceController extends Controller */ public function suggest(Request $request): JsonResponse { - $string = '' === (string) $request->get('date') ? Carbon::now()->format('Y-m-d') : (string) $request->get('date'); - $today = today(config('app.timezone'))->startOfDay(); + $string = '' === (string) $request->get('date') ? Carbon::now()->format('Y-m-d') : (string) $request->get('date'); + $today = today(config('app.timezone'))->startOfDay(); try { $date = Carbon::createFromFormat('Y-m-d', $string, config('app.timezone')); @@ -173,7 +171,7 @@ class RecurrenceController extends Controller Log::debug(sprintf('date = %s, today = %s. date > today? %s', $date->toAtomString(), $today->toAtomString(), var_export($date > $today, true))); Log::debug(sprintf('past = true? %s', var_export('true' === (string) $request->get('past'), true))); - $result = []; + $result = []; if ($date > $today || 'true' === (string) $request->get('past')) { Log::debug('Will fill dropdown.'); $weekly = sprintf('weekly,%s', $date->dayOfWeekIso); @@ -183,23 +181,23 @@ class RecurrenceController extends Controller $yearly = sprintf('yearly,%s', $date->format('Y-m-d')); $yearlyDate = $date->isoFormat((string) trans('config.month_and_day_no_year_js', [], $locale)); $result = [ - 'daily' => ['label' => (string) trans('firefly.recurring_daily'), 'selected' => str_starts_with($preSelected, 'daily')], + 'daily' => ['label' => (string) trans('firefly.recurring_daily'), 'selected' => str_starts_with($preSelected, 'daily')], $weekly => [ - 'label' => (string) trans('firefly.recurring_weekly', ['weekday' => $dayOfWeek]), - 'selected' => str_starts_with($preSelected, 'weekly'), + 'label' => (string) trans('firefly.recurring_weekly', ['weekday' => $dayOfWeek]), + 'selected' => str_starts_with($preSelected, 'weekly') ], $monthly => [ - 'label' => (string) trans('firefly.recurring_monthly', ['dayOfMonth' => $date->day]), - 'selected' => str_starts_with($preSelected, 'monthly'), + 'label' => (string) trans('firefly.recurring_monthly', ['dayOfMonth' => $date->day]), + 'selected' => str_starts_with($preSelected, 'monthly') ], $ndom => [ - 'label' => (string) trans('firefly.recurring_ndom', ['weekday' => $dayOfWeek, 'dayOfMonth' => $date->weekOfMonth]), - 'selected' => str_starts_with($preSelected, 'ndom'), + 'label' => (string) trans('firefly.recurring_ndom', ['weekday' => $dayOfWeek, 'dayOfMonth' => $date->weekOfMonth]), + 'selected' => str_starts_with($preSelected, 'ndom') ], $yearly => [ - 'label' => (string) trans('firefly.recurring_yearly', ['date' => $yearlyDate]), - 'selected' => str_starts_with($preSelected, 'yearly'), - ], + 'label' => (string) trans('firefly.recurring_yearly', ['date' => $yearlyDate]), + 'selected' => str_starts_with($preSelected, 'yearly') + ] ]; } Log::debug('Dropdown is', $result); diff --git a/app/Http/Controllers/Json/RuleController.php b/app/Http/Controllers/Json/RuleController.php index ed927db543..db3c8a19ce 100644 --- a/app/Http/Controllers/Json/RuleController.php +++ b/app/Http/Controllers/Json/RuleController.php @@ -24,11 +24,11 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Json; -use Illuminate\Support\Facades\Log; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; +use Illuminate\Support\Facades\Log; use Throwable; /** @@ -47,11 +47,11 @@ class RuleController extends Controller $keys = array_keys(config('firefly.rule-actions')); $actions = []; foreach ($keys as $key) { - $actions[$key] = (string) trans('firefly.rule_action_'.$key.'_choice'); + $actions[$key] = (string) trans('firefly.rule_action_' . $key . '_choice'); } try { - $view = view('rules.partials.action', ['actions' => $actions, 'count' => $count])->render(); + $view = view('rules.partials.action', ['actions' => $actions, 'count' => $count])->render(); } catch (Throwable $e) { Log::error(sprintf('Cannot render rules.partials.action: %s', $e->getMessage())); Log::error($e->getTraceAsString()); @@ -81,7 +81,7 @@ class RuleController extends Controller asort($triggers); try { - $view = view('rules.partials.trigger', ['triggers' => $triggers, 'count' => $count])->render(); + $view = view('rules.partials.trigger', ['triggers' => $triggers, 'count' => $count])->render(); } catch (Throwable $e) { Log::error(sprintf('Cannot render rules.partials.trigger: %s', $e->getMessage())); Log::error($e->getTraceAsString()); diff --git a/app/Http/Controllers/NewUserController.php b/app/Http/Controllers/NewUserController.php index 9b92f08074..05b3a8b3c6 100644 --- a/app/Http/Controllers/NewUserController.php +++ b/app/Http/Controllers/NewUserController.php @@ -23,12 +23,12 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Http\Requests\NewUserFormRequest; use FireflyIII\Models\TransactionCurrency; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use FireflyIII\Support\Http\Controllers\CreateStuff; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; @@ -51,13 +51,11 @@ class NewUserController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(AccountRepositoryInterface::class); + $this->middleware(function ($request, $next) { + $this->repository = app(AccountRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -70,8 +68,8 @@ class NewUserController extends Controller app('view')->share('title', (string) trans('firefly.welcome')); app('view')->share('mainTitleIcon', 'fa-fire'); - $types = config('firefly.accountTypesByIdentifier.asset'); - $count = $this->repository->count($types); + $types = config('firefly.accountTypesByIdentifier.asset'); + $count = $this->repository->count($types); $languages = []; @@ -87,7 +85,7 @@ class NewUserController extends Controller */ public function submit(NewUserFormRequest $request, CurrencyRepositoryInterface $currencyRepository): Redirector|RedirectResponse { - $language = $request->convertString('language'); + $language = $request->convertString('language'); if (!array_key_exists($language, config('firefly.languages'))) { $language = 'en_US'; } @@ -95,7 +93,7 @@ class NewUserController extends Controller // set language preference: Preferences::set('language', $language); // Store currency preference from input: - $currency = $currencyRepository->find((int) $request->input('amount_currency_id_bank_balance')); + $currency = $currencyRepository->find((int) $request->input('amount_currency_id_bank_balance')); // if is null, set to EUR: if (!$currency instanceof TransactionCurrency) { @@ -103,15 +101,18 @@ class NewUserController extends Controller } $currencyRepository->enable($currency); - $this->createAssetAccount($request, $currency); // create normal asset account + $this->createAssetAccount($request, $currency); // create normal asset account $this->createSavingsAccount($request, $currency, $language); // create savings account - $this->createCashWalletAccount($currency, $language); // create cash wallet account + $this->createCashWalletAccount($currency, $language); // create cash wallet account // store currency preference: $currencyRepository->makePrimary($currency); // store frontpage preferences: - $accounts = $this->repository->getAccountsByType([AccountTypeEnum::ASSET->value])->pluck('id')->toArray(); + $accounts = $this->repository + ->getAccountsByType([AccountTypeEnum::ASSET->value]) + ->pluck('id') + ->toArray(); Preferences::set('frontpageAccounts', $accounts); // mark. @@ -127,7 +128,7 @@ class NewUserController extends Controller 'invoice_date' => false, 'internal_reference' => false, 'notes' => true, - 'attachments' => true, + 'attachments' => true ]; Preferences::set('transaction_journal_optional_fields', $visibleFields); diff --git a/app/Http/Controllers/ObjectGroup/DeleteController.php b/app/Http/Controllers/ObjectGroup/DeleteController.php index 6024db89a4..3a7f8087d5 100644 --- a/app/Http/Controllers/ObjectGroup/DeleteController.php +++ b/app/Http/Controllers/ObjectGroup/DeleteController.php @@ -24,10 +24,10 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\ObjectGroup; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\ObjectGroup; use FireflyIII\Repositories\ObjectGroup\ObjectGroupRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use Illuminate\Contracts\View\Factory; use Illuminate\Contracts\View\View; use Illuminate\Http\RedirectResponse; @@ -46,16 +46,14 @@ class DeleteController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('mainTitleIcon', 'fa-envelope-o'); - app('view')->share('title', (string) trans('firefly.object_groups_page_title')); + $this->middleware(function ($request, $next) { + app('view')->share('mainTitleIcon', 'fa-envelope-o'); + app('view')->share('title', (string) trans('firefly.object_groups_page_title')); - $this->repository = app(ObjectGroupRepositoryInterface::class); + $this->repository = app(ObjectGroupRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -63,13 +61,13 @@ class DeleteController extends Controller */ public function delete(ObjectGroup $objectGroup): Factory|View { - $subTitle = (string) trans('firefly.delete_object_group', ['title' => $objectGroup->title]); + $subTitle = (string) trans('firefly.delete_object_group', ['title' => $objectGroup->title]); $piggyBanks = $objectGroup->piggyBanks()->count(); // put previous url in session $this->rememberPreviousUrl('object-groups.delete.url'); - return view('object-groups.delete', ['objectGroup' => $objectGroup, 'subTitle' => $subTitle, 'piggyBanks' => $piggyBanks]); + return view('object-groups.delete', ['objectGroup' => $objectGroup, 'subTitle' => $subTitle, 'piggyBanks' => $piggyBanks]); } /** diff --git a/app/Http/Controllers/ObjectGroup/EditController.php b/app/Http/Controllers/ObjectGroup/EditController.php index f446765aa2..f888b22070 100644 --- a/app/Http/Controllers/ObjectGroup/EditController.php +++ b/app/Http/Controllers/ObjectGroup/EditController.php @@ -24,11 +24,11 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\ObjectGroup; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Requests\ObjectGroupFormRequest; use FireflyIII\Models\ObjectGroup; use FireflyIII\Repositories\ObjectGroup\ObjectGroupRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use Illuminate\Contracts\Foundation\Application; use Illuminate\Contracts\View\Factory; use Illuminate\Contracts\View\View; @@ -49,16 +49,14 @@ class EditController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('mainTitleIcon', 'fa-envelope-o'); - app('view')->share('title', (string) trans('firefly.object_groups_page_title')); + $this->middleware(function ($request, $next) { + app('view')->share('mainTitleIcon', 'fa-envelope-o'); + app('view')->share('title', (string) trans('firefly.object_groups_page_title')); - $this->repository = app(ObjectGroupRepositoryInterface::class); + $this->repository = app(ObjectGroupRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -66,7 +64,7 @@ class EditController extends Controller */ public function edit(ObjectGroup $objectGroup): Factory|View { - $subTitle = (string) trans('firefly.edit_object_group', ['title' => $objectGroup->title]); + $subTitle = (string) trans('firefly.edit_object_group', ['title' => $objectGroup->title]); $subTitleIcon = 'fa-pencil'; if (true !== session('object-groups.edit.fromUpdate')) { @@ -74,7 +72,7 @@ class EditController extends Controller } session()->forget('object-groups.edit.fromUpdate'); - return view('object-groups.edit', ['subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'objectGroup' => $objectGroup]); + return view('object-groups.edit', ['subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'objectGroup' => $objectGroup]); } /** @@ -90,7 +88,7 @@ class EditController extends Controller session()->flash('success', (string) trans('firefly.updated_object_group', ['title' => $objectGroup->title])); Preferences::mark(); - $redirect = redirect($this->getPreviousUrl('object-groups.edit.url')); + $redirect = redirect($this->getPreviousUrl('object-groups.edit.url')); if (1 === (int) $request->get('return_to_edit')) { session()->put('object-groups.edit.fromUpdate', true); diff --git a/app/Http/Controllers/ObjectGroup/IndexController.php b/app/Http/Controllers/ObjectGroup/IndexController.php index 756d23c16a..7d5c7221f0 100644 --- a/app/Http/Controllers/ObjectGroup/IndexController.php +++ b/app/Http/Controllers/ObjectGroup/IndexController.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\ObjectGroup; -use Illuminate\Support\Facades\Log; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\ObjectGroup; use FireflyIII\Repositories\ObjectGroup\ObjectGroupRepositoryInterface; @@ -32,6 +31,7 @@ use Illuminate\Contracts\View\Factory; use Illuminate\Contracts\View\View; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; +use Illuminate\Support\Facades\Log; /** * Class IndexController @@ -48,15 +48,13 @@ class IndexController extends Controller parent::__construct(); // translations: - $this->middleware( - function ($request, $next) { - app('view')->share('mainTitleIcon', 'fa-envelope-o'); - app('view')->share('title', (string) trans('firefly.object_groups_page_title')); - $this->repository = app(ObjectGroupRepositoryInterface::class); + $this->middleware(function ($request, $next) { + app('view')->share('mainTitleIcon', 'fa-envelope-o'); + app('view')->share('title', (string) trans('firefly.object_groups_page_title')); + $this->repository = app(ObjectGroupRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } public function index(): Factory|View @@ -66,7 +64,7 @@ class IndexController extends Controller $subTitle = (string) trans('firefly.object_groups_index'); $objectGroups = $this->repository->get(); - return view('object-groups.index', ['subTitle' => $subTitle, 'objectGroups' => $objectGroups]); + return view('object-groups.index', ['subTitle' => $subTitle, 'objectGroups' => $objectGroups]); } /** diff --git a/app/Http/Controllers/PiggyBank/AmountController.php b/app/Http/Controllers/PiggyBank/AmountController.php index 5d66fffe36..b780249bbc 100644 --- a/app/Http/Controllers/PiggyBank/AmountController.php +++ b/app/Http/Controllers/PiggyBank/AmountController.php @@ -24,18 +24,18 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\PiggyBank; -use FireflyIII\Support\Facades\Preferences; use Carbon\Carbon; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\Account; use FireflyIII\Models\PiggyBank; use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface; +use FireflyIII\Support\Facades\Amount; +use FireflyIII\Support\Facades\Preferences; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; use Illuminate\View\View; -use FireflyIII\Support\Facades\Amount; /** * Class AmountController @@ -51,16 +51,14 @@ class AmountController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.piggyBanks')); - app('view')->share('mainTitleIcon', 'fa-bullseye'); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.piggyBanks')); + app('view')->share('mainTitleIcon', 'fa-bullseye'); - $this->piggyRepos = app(PiggyBankRepositoryInterface::class); + $this->piggyRepos = app(PiggyBankRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -86,21 +84,21 @@ class AmountController extends Controller $leftOnAccount, $totalSaved, $leftToSave, - $maxAmount, + $maxAmount )); - $accounts[] = [ + $accounts[] = [ 'account' => $account, 'left_on_account' => $leftOnAccount, 'total_saved' => $totalSaved, 'left_to_save' => $leftToSave, - 'max_amount' => $maxAmount, + 'max_amount' => $maxAmount ]; - $total = bcadd($total, $leftOnAccount); + $total = bcadd($total, $leftOnAccount); } - $total = (float) $total; // intentional float. + $total = (float) $total; // intentional float. - return view('piggy-banks.add', ['piggyBank' => $piggyBank, 'accounts' => $accounts, 'total' => $total]); + return view('piggy-banks.add', ['piggyBank' => $piggyBank, 'accounts' => $accounts, 'total' => $total]); } /** @@ -119,17 +117,17 @@ class AmountController extends Controller $leftOnAccount = $this->piggyRepos->leftOnAccount($piggyBank, $account, $date); $leftToSave = bcsub($piggyBank->target_amount, $totalSaved); $maxAmount = 0 === bccomp($piggyBank->target_amount, '0') ? $leftOnAccount : min($leftOnAccount, $leftToSave); - $accounts[] = [ + $accounts[] = [ 'account' => $account, 'left_on_account' => $leftOnAccount, 'total_saved' => $totalSaved, 'left_to_save' => $leftToSave, - 'max_amount' => $maxAmount, + 'max_amount' => $maxAmount ]; - $total = bcadd($total, $leftOnAccount); + $total = bcadd($total, $leftOnAccount); } - return view('piggy-banks.add-mobile', ['piggyBank' => $piggyBank, 'total' => $total, 'accounts' => $accounts]); + return view('piggy-banks.add-mobile', ['piggyBank' => $piggyBank, 'total' => $total, 'accounts' => $accounts]); } /** @@ -144,7 +142,7 @@ class AmountController extends Controller /** @var Account $account */ foreach ($piggyBank->accounts as $account) { - $amount = (string) ($amounts[$account->id] ?? '0'); + $amount = (string) ($amounts[$account->id] ?? '0'); if ('' === $amount || 0 === bccomp($amount, '0')) { continue; } @@ -160,7 +158,7 @@ class AmountController extends Controller $amount = $leftToSave; } - $canAddAmount = $this->piggyRepos->canAddAmount($piggyBank, $account, $amount); + $canAddAmount = $this->piggyRepos->canAddAmount($piggyBank, $account, $amount); if ($canAddAmount) { $this->piggyRepos->addAmount($piggyBank, $account, $amount); $total = bcadd($total, $amount); @@ -168,7 +166,13 @@ class AmountController extends Controller $piggyBank->refresh(); } if (0 !== bccomp($total, '0')) { - session()->flash('success', (string) trans('firefly.added_amount_to_piggy', ['amount' => Amount::formatAnything($piggyBank->transactionCurrency, $total, false), 'name' => $piggyBank->name])); + session()->flash( + 'success', + (string) trans('firefly.added_amount_to_piggy', [ + 'amount' => Amount::formatAnything($piggyBank->transactionCurrency, $total, false), + 'name' => $piggyBank->name + ]) + ); Preferences::mark(); return redirect(route('piggy-banks.index')); @@ -176,10 +180,10 @@ class AmountController extends Controller Log::error(sprintf('Cannot add %s because canAddAmount returned false.', $total)); session()->flash( 'error', - (string) trans( - 'firefly.cannot_add_amount_piggy', - ['amount' => Amount::formatAnything($piggyBank->transactionCurrency, $total, false), 'name' => e($piggyBank->name)] - ) + (string) trans('firefly.cannot_add_amount_piggy', [ + 'amount' => Amount::formatAnything($piggyBank->transactionCurrency, $total, false), + 'name' => e($piggyBank->name) + ]) ); return redirect(route('piggy-banks.index')); @@ -194,7 +198,7 @@ class AmountController extends Controller if (!is_array($amounts)) { $amounts = []; } - $total = '0'; + $total = '0'; /** @var Account $account */ foreach ($piggyBank->accounts as $account) { @@ -213,10 +217,10 @@ class AmountController extends Controller if (0 !== bccomp($total, '0')) { session()->flash( 'success', - (string) trans( - 'firefly.removed_amount_from_piggy', - ['amount' => Amount::formatAnything($piggyBank->transactionCurrency, $total, false), 'name' => $piggyBank->name] - ) + (string) trans('firefly.removed_amount_from_piggy', [ + 'amount' => Amount::formatAnything($piggyBank->transactionCurrency, $total, false), + 'name' => $piggyBank->name + ]) ); Preferences::mark(); @@ -225,10 +229,10 @@ class AmountController extends Controller session()->flash( 'error', - (string) trans( - 'firefly.cannot_remove_from_piggy', - ['amount' => Amount::formatAnything($piggyBank->transactionCurrency, $total, false), 'name' => e($piggyBank->name)] - ) + (string) trans('firefly.cannot_remove_from_piggy', [ + 'amount' => Amount::formatAnything($piggyBank->transactionCurrency, $total, false), + 'name' => e($piggyBank->name) + ]) ); return redirect(route('piggy-banks.index')); @@ -243,13 +247,10 @@ class AmountController extends Controller { $accounts = []; foreach ($piggyBank->accounts as $account) { - $accounts[] = [ - 'account' => $account, - 'saved_so_far' => $this->piggyRepos->getCurrentAmount($piggyBank, $account), - ]; + $accounts[] = ['account' => $account, 'saved_so_far' => $this->piggyRepos->getCurrentAmount($piggyBank, $account)]; } - return view('piggy-banks.remove', ['piggyBank' => $piggyBank, 'accounts' => $accounts]); + return view('piggy-banks.remove', ['piggyBank' => $piggyBank, 'accounts' => $accounts]); } /** @@ -261,12 +262,9 @@ class AmountController extends Controller { $accounts = []; foreach ($piggyBank->accounts as $account) { - $accounts[] = [ - 'account' => $account, - 'saved_so_far' => $this->piggyRepos->getCurrentAmount($piggyBank, $account), - ]; + $accounts[] = ['account' => $account, 'saved_so_far' => $this->piggyRepos->getCurrentAmount($piggyBank, $account)]; } - return view('piggy-banks.remove-mobile', ['piggyBank' => $piggyBank, 'accounts' => $accounts]); + return view('piggy-banks.remove-mobile', ['piggyBank' => $piggyBank, 'accounts' => $accounts]); } } diff --git a/app/Http/Controllers/PiggyBank/CreateController.php b/app/Http/Controllers/PiggyBank/CreateController.php index 6c734618ad..2c6be7d1a9 100644 --- a/app/Http/Controllers/PiggyBank/CreateController.php +++ b/app/Http/Controllers/PiggyBank/CreateController.php @@ -24,12 +24,12 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\PiggyBank; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Helpers\Attachments\AttachmentHelperInterface; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Requests\PiggyBankStoreRequest; use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; @@ -42,7 +42,7 @@ use Illuminate\View\View; */ class CreateController extends Controller { - private AttachmentHelperInterface $attachments; + private AttachmentHelperInterface $attachments; private PiggyBankRepositoryInterface $piggyRepos; /** @@ -52,17 +52,15 @@ class CreateController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.piggyBanks')); - app('view')->share('mainTitleIcon', 'fa-bullseye'); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.piggyBanks')); + app('view')->share('mainTitleIcon', 'fa-bullseye'); - $this->attachments = app(AttachmentHelperInterface::class); - $this->piggyRepos = app(PiggyBankRepositoryInterface::class); + $this->attachments = app(AttachmentHelperInterface::class); + $this->piggyRepos = app(PiggyBankRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -75,7 +73,7 @@ class CreateController extends Controller $subTitle = (string) trans('firefly.new_piggy_bank'); $subTitleIcon = 'fa-plus'; $request->old('_token'); - $preFilled = $request->old(); + $preFilled = $request->old(); if (!array_key_exists('transaction_currency_id', $preFilled)) { $preFilled['transaction_currency_id'] = $this->primaryCurrency->id; } @@ -86,7 +84,7 @@ class CreateController extends Controller } session()->forget('piggy-banks.create.fromStore'); - return view('piggy-banks.create', ['subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'preFilled' => $preFilled]); + return view('piggy-banks.create', ['subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'preFilled' => $preFilled]); } /** @@ -98,7 +96,7 @@ class CreateController extends Controller */ public function store(PiggyBankStoreRequest $request) { - $data = $request->getPiggyBankData(); + $data = $request->getPiggyBankData(); if (null === $data['start_date']) { $data['start_date'] = today(config('app.timezone')); @@ -111,7 +109,7 @@ class CreateController extends Controller // store attachment(s): /** @var null|array $files */ - $files = $request->hasFile('attachments') ? $request->file('attachments') : null; + $files = $request->hasFile('attachments') ? $request->file('attachments') : null; if (null !== $files && !auth()->user()->hasRole('demo')) { $this->attachments->saveAttachmentsForModel($piggyBank, $files); } @@ -123,7 +121,7 @@ class CreateController extends Controller if (count($this->attachments->getMessages()->get('attachments')) > 0) { $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); } - $redirect = redirect($this->getPreviousUrl('piggy-banks.create.url')); + $redirect = redirect($this->getPreviousUrl('piggy-banks.create.url')); if (1 === (int) $request->get('create_another')) { session()->put('piggy-banks.create.fromStore', true); diff --git a/app/Http/Controllers/PiggyBank/DeleteController.php b/app/Http/Controllers/PiggyBank/DeleteController.php index e2cb6caf58..6c21fe504b 100644 --- a/app/Http/Controllers/PiggyBank/DeleteController.php +++ b/app/Http/Controllers/PiggyBank/DeleteController.php @@ -24,10 +24,10 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\PiggyBank; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\PiggyBank; use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\View\View; @@ -46,16 +46,14 @@ class DeleteController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.piggyBanks')); - app('view')->share('mainTitleIcon', 'fa-bullseye'); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.piggyBanks')); + app('view')->share('mainTitleIcon', 'fa-bullseye'); - $this->piggyRepos = app(PiggyBankRepositoryInterface::class); + $this->piggyRepos = app(PiggyBankRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -70,7 +68,7 @@ class DeleteController extends Controller // put previous url in session $this->rememberPreviousUrl('piggy-banks.delete.url'); - return view('piggy-banks.delete', ['piggyBank' => $piggyBank, 'subTitle' => $subTitle]); + return view('piggy-banks.delete', ['piggyBank' => $piggyBank, 'subTitle' => $subTitle]); } /** diff --git a/app/Http/Controllers/PiggyBank/EditController.php b/app/Http/Controllers/PiggyBank/EditController.php index e426cf6658..ef4e2e4d9a 100644 --- a/app/Http/Controllers/PiggyBank/EditController.php +++ b/app/Http/Controllers/PiggyBank/EditController.php @@ -24,25 +24,25 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\PiggyBank; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Helpers\Attachments\AttachmentHelperInterface; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Requests\PiggyBankUpdateRequest; use FireflyIII\Models\PiggyBank; use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; +use FireflyIII\Support\Facades\Steam; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Routing\Redirector; use Illuminate\Support\Facades\Log; use Illuminate\View\View; -use FireflyIII\Support\Facades\Steam; /** * Class EditController */ class EditController extends Controller { - private AttachmentHelperInterface $attachments; + private AttachmentHelperInterface $attachments; private PiggyBankRepositoryInterface $piggyRepos; /** @@ -52,17 +52,15 @@ class EditController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.piggyBanks')); - app('view')->share('mainTitleIcon', 'fa-bullseye'); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.piggyBanks')); + app('view')->share('mainTitleIcon', 'fa-bullseye'); - $this->attachments = app(AttachmentHelperInterface::class); - $this->piggyRepos = app(PiggyBankRepositoryInterface::class); + $this->attachments = app(AttachmentHelperInterface::class); + $this->piggyRepos = app(PiggyBankRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } public function resetHistory(PiggyBank $piggyBank): RedirectResponse @@ -80,14 +78,14 @@ class EditController extends Controller */ public function edit(PiggyBank $piggyBank): Factory|\Illuminate\Contracts\View\View { - $subTitle = (string) trans('firefly.update_piggy_title', ['name' => $piggyBank->name]); + $subTitle = (string) trans('firefly.update_piggy_title', ['name' => $piggyBank->name]); $subTitleIcon = 'fa-pencil'; $note = $piggyBank->notes()->first(); // Flash some data to fill the form. - $targetDate = $piggyBank->target_date?->format('Y-m-d'); - $startDate = $piggyBank->start_date?->format('Y-m-d'); + $targetDate = $piggyBank->target_date?->format('Y-m-d'); + $startDate = $piggyBank->start_date?->format('Y-m-d'); - $preFilled = [ + $preFilled = [ 'name' => $piggyBank->name, 'transaction_currency_id' => (int) $piggyBank->transaction_currency_id, 'target_amount' => Steam::bcround($piggyBank->target_amount, $piggyBank->transactionCurrency->decimal_places), @@ -95,7 +93,7 @@ class EditController extends Controller 'start_date' => $startDate, 'accounts' => [], 'object_group' => null !== $piggyBank->objectGroups->first() ? $piggyBank->objectGroups->first()->title : '', - 'notes' => null === $note ? '' : $note->text, + 'notes' => null === $note ? '' : $note->text ]; foreach ($piggyBank->accounts as $account) { $preFilled['accounts'][] = $account->id; @@ -111,7 +109,12 @@ class EditController extends Controller } session()->forget('piggy-banks.edit.fromUpdate'); - return view('piggy-banks.edit', ['subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'piggyBank' => $piggyBank, 'preFilled' => $preFilled]); + return view('piggy-banks.edit', [ + 'subTitle' => $subTitle, + 'subTitleIcon' => $subTitleIcon, + 'piggyBank' => $piggyBank, + 'preFilled' => $preFilled + ]); } /** @@ -127,7 +130,7 @@ class EditController extends Controller // store new attachment(s): /** @var null|array $files */ - $files = $request->hasFile('attachments') ? $request->file('attachments') : null; + $files = $request->hasFile('attachments') ? $request->file('attachments') : null; if (null !== $files && !auth()->user()->hasRole('demo')) { $this->attachments->saveAttachmentsForModel($piggyBank, $files); } @@ -139,7 +142,7 @@ class EditController extends Controller if (count($this->attachments->getMessages()->get('attachments')) > 0) { $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); } - $redirect = redirect($this->getPreviousUrl('piggy-banks.edit.url')); + $redirect = redirect($this->getPreviousUrl('piggy-banks.edit.url')); if (1 === (int) $request->get('return_to_edit')) { session()->put('piggy-banks.edit.fromUpdate', true); diff --git a/app/Http/Controllers/PiggyBank/IndexController.php b/app/Http/Controllers/PiggyBank/IndexController.php index 76ac7477a1..3e1164dd22 100644 --- a/app/Http/Controllers/PiggyBank/IndexController.php +++ b/app/Http/Controllers/PiggyBank/IndexController.php @@ -58,16 +58,14 @@ class IndexController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.piggyBanks')); - app('view')->share('mainTitleIcon', 'fa-bullseye'); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.piggyBanks')); + app('view')->share('mainTitleIcon', 'fa-bullseye'); - $this->piggyRepos = app(PiggyBankRepositoryInterface::class); + $this->piggyRepos = app(PiggyBankRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -89,7 +87,6 @@ class IndexController extends Controller // $parameters = new ParameterBag(); // $parameters->set('end', $end); - // /** @var AccountTransformer $accountTransformer */ // $accountTransformer = app(AccountTransformer::class); // $accountTransformer->setParameters($parameters); @@ -102,7 +99,7 @@ class IndexController extends Controller ksort($piggyBanks); - return view('piggy-banks.index', ['piggyBanks' => $piggyBanks, 'accounts' => $accounts]); + return view('piggy-banks.index', ['piggyBanks' => $piggyBanks, 'accounts' => $accounts]); } private function groupPiggyBanks(Collection $collection): array @@ -110,25 +107,25 @@ class IndexController extends Controller /** @var PiggyBankTransformer $transformer */ $transformer = app(PiggyBankTransformer::class); $transformer->setParameters(new ParameterBag()); - $piggyBanks = []; + $piggyBanks = []; // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new PiggyBankEnrichment(); + $admin = auth()->user(); + $enrichment = new PiggyBankEnrichment(); $enrichment->setUser($admin); - $collection = $enrichment->enrich($collection); + $collection = $enrichment->enrich($collection); /** @var PiggyBank $piggy */ foreach ($collection as $piggy) { - $array = $transformer->transform($piggy); - $groupOrder = (int) $array['object_group_order']; + $array = $transformer->transform($piggy); + $groupOrder = (int) $array['object_group_order']; $piggyBanks[$groupOrder] ??= [ 'object_group_id' => $array['object_group_id'] ?? 0, 'object_group_title' => $array['object_group_title'] ?? trans('firefly.default_group_title_name'), - 'piggy_banks' => [], + 'piggy_banks' => [] ]; - $array['attachments'] = $this->piggyRepos->getAttachments($piggy); + $array['attachments'] = $this->piggyRepos->getAttachments($piggy); // sum the total amount for the index. $piggyBanks[$groupOrder]['piggy_banks'][] = $array; @@ -140,10 +137,10 @@ class IndexController extends Controller private function collectAccounts(Collection $collection): array { /** @var Carbon $end */ - $end = session('end', today(config('app.timezone'))->endOfMonth()); + $end = session('end', today(config('app.timezone'))->endOfMonth()); // transform piggies using the transformer: - $parameters = new ParameterBag(); + $parameters = new ParameterBag(); $parameters->set('end', $end); /** @var AccountTransformer $accountTransformer */ @@ -151,10 +148,10 @@ class IndexController extends Controller $accountTransformer->setParameters($parameters); // enrich each account. - $enrichment = new AccountEnrichment(); + $enrichment = new AccountEnrichment(); $enrichment->setUser(auth()->user()); $enrichment->setDate($end); - $return = []; + $return = []; /** @var PiggyBank $piggy */ foreach ($collection as $piggy) { @@ -167,12 +164,12 @@ class IndexController extends Controller $array = $accountTransformer->transform($account); $accountId = (int) $array['id']; if (!array_key_exists($accountId, $return)) { - $return[$accountId] = $array; + $return[$accountId] = $array; // add some interesting details: - $return[$accountId]['left'] = $return[$accountId]['current_balance']; - $return[$accountId]['saved'] = '0'; - $return[$accountId]['target'] = '0'; + $return[$accountId]['left'] = $return[$accountId]['current_balance']; + $return[$accountId]['saved'] = '0'; + $return[$accountId]['target'] = '0'; $return[$accountId]['to_save'] = '0'; } } @@ -192,10 +189,13 @@ class IndexController extends Controller foreach ($piggyBank['accounts'] as $piggyAccount) { $accountId = $piggyAccount['account_id']; if (array_key_exists($accountId, $accounts)) { - $accounts[$accountId]['left'] = bcsub((string) $accounts[$accountId]['left'], (string) $piggyAccount['current_amount']); - $accounts[$accountId]['saved'] = bcadd((string) $accounts[$accountId]['saved'], (string) $piggyAccount['current_amount']); - $accounts[$accountId]['target'] = bcadd((string) $accounts[$accountId]['target'], (string) $piggyBank['target_amount']); - $accounts[$accountId]['to_save'] = bcadd((string) $accounts[$accountId]['to_save'], bcsub((string) $piggyBank['target_amount'], (string) $piggyAccount['current_amount'])); + $accounts[$accountId]['left'] = bcsub((string) $accounts[$accountId]['left'], (string) $piggyAccount['current_amount']); + $accounts[$accountId]['saved'] = bcadd((string) $accounts[$accountId]['saved'], (string) $piggyAccount['current_amount']); + $accounts[$accountId]['target'] = bcadd((string) $accounts[$accountId]['target'], (string) $piggyBank['target_amount']); + $accounts[$accountId]['to_save'] = bcadd((string) $accounts[$accountId]['to_save'], bcsub( + (string) $piggyBank['target_amount'], + (string) $piggyAccount['current_amount'] + )); } } } @@ -210,7 +210,7 @@ class IndexController extends Controller foreach ($piggyBanks as $groupOrder => $group) { $groupId = $group['object_group_id']; foreach ($group['piggy_banks'] as $piggy) { - $currencyId = $piggy['currency_id']; + $currencyId = $piggy['currency_id']; $sums[$groupId][$currencyId] ??= [ 'target' => '0', 'saved' => '0', @@ -219,20 +219,20 @@ class IndexController extends Controller 'currency_id' => $currencyId, 'currency_code' => $piggy['currency_code'], 'currency_symbol' => $piggy['currency_symbol'], - 'currency_decimal_places' => $piggy['currency_decimal_places'], + 'currency_decimal_places' => $piggy['currency_decimal_places'] ]; // target_amount // current_amount // left_to_save // save_per_month - $sums[$groupId][$currencyId]['target'] = bcadd($sums[$groupId][$currencyId]['target'], (string) $piggy['target_amount']); - $sums[$groupId][$currencyId]['saved'] = bcadd($sums[$groupId][$currencyId]['saved'], (string) $piggy['current_amount']); - $sums[$groupId][$currencyId]['left_to_save'] = bcadd($sums[$groupId][$currencyId]['left_to_save'], (string) $piggy['left_to_save']); + $sums[$groupId][$currencyId]['target'] = bcadd($sums[$groupId][$currencyId]['target'], (string) $piggy['target_amount']); + $sums[$groupId][$currencyId]['saved'] = bcadd($sums[$groupId][$currencyId]['saved'], (string) $piggy['current_amount']); + $sums[$groupId][$currencyId]['left_to_save'] = bcadd($sums[$groupId][$currencyId]['left_to_save'], (string) $piggy['left_to_save']); $sums[$groupId][$currencyId]['save_per_month'] = bcadd($sums[$groupId][$currencyId]['save_per_month'], (string) $piggy['save_per_month']); } } foreach ($piggyBanks as $groupOrder => $group) { - $groupId = $group['object_group_id']; + $groupId = $group['object_group_id']; $piggyBanks[$groupOrder]['sums'] = $sums[$groupId] ?? []; } diff --git a/app/Http/Controllers/PiggyBank/ShowController.php b/app/Http/Controllers/PiggyBank/ShowController.php index d75769f550..1095eeb525 100644 --- a/app/Http/Controllers/PiggyBank/ShowController.php +++ b/app/Http/Controllers/PiggyBank/ShowController.php @@ -50,16 +50,14 @@ class ShowController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.piggyBanks')); - app('view')->share('mainTitleIcon', 'fa-bullseye'); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.piggyBanks')); + app('view')->share('mainTitleIcon', 'fa-bullseye'); - $this->piggyRepos = app(PiggyBankRepositoryInterface::class); + $this->piggyRepos = app(PiggyBankRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -72,19 +70,19 @@ class ShowController extends Controller public function show(PiggyBank $piggyBank): Factory|\Illuminate\Contracts\View\View { /** @var Carbon $end */ - $end = session('end', today(config('app.timezone'))->endOfMonth()); + $end = session('end', today(config('app.timezone'))->endOfMonth()); // transform piggies using the transformer: - $parameters = new ParameterBag(); + $parameters = new ParameterBag(); $parameters->set('end', $end); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new PiggyBankEnrichment(); + $admin = auth()->user(); + $enrichment = new PiggyBankEnrichment(); $enrichment->setUser($admin); /** @var PiggyBank $piggyBank */ - $piggyBank = $enrichment->enrichSingle($piggyBank); + $piggyBank = $enrichment->enrichSingle($piggyBank); /** @var PiggyBankTransformer $transformer */ $transformer = app(PiggyBankTransformer::class); @@ -94,7 +92,12 @@ class ShowController extends Controller $subTitle = $piggyBank->name; $attachments = $this->piggyRepos->getAttachments($piggyBank); - - return view('piggy-banks.show', ['piggyBank' => $piggyBank, 'events' => $events, 'subTitle' => $subTitle, 'piggy' => $piggy, 'attachments' => $attachments]); + return view('piggy-banks.show', [ + 'piggyBank' => $piggyBank, + 'events' => $events, + 'subTitle' => $subTitle, + 'piggy' => $piggy, + 'attachments' => $attachments + ]); } } diff --git a/app/Http/Controllers/Popup/ReportController.php b/app/Http/Controllers/Popup/ReportController.php index 1d4ae33507..9a760ada5e 100644 --- a/app/Http/Controllers/Popup/ReportController.php +++ b/app/Http/Controllers/Popup/ReportController.php @@ -49,13 +49,13 @@ class ReportController extends Controller app('view')->share('start', $attributes['startDate']); app('view')->share('end', $attributes['endDate']); - $html = match ($attributes['location']) { - default => sprintf('Firefly III cannot handle "%s"-popups.', $attributes['location']), + $html = match ($attributes['location']) { + default => sprintf('Firefly III cannot handle "%s"-popups.', $attributes['location']), 'budget-spent-amount' => $this->budgetSpentAmount($attributes), - 'expense-entry' => $this->expenseEntry($attributes), - 'income-entry' => $this->incomeEntry($attributes), - 'category-entry' => $this->categoryEntry($attributes), - 'budget-entry' => $this->budgetEntry($attributes), + 'expense-entry' => $this->expenseEntry($attributes), + 'income-entry' => $this->incomeEntry($attributes), + 'category-entry' => $this->categoryEntry($attributes), + 'budget-entry' => $this->budgetEntry($attributes) }; return response()->json(['html' => $html]); diff --git a/app/Http/Controllers/PreferencesController.php b/app/Http/Controllers/PreferencesController.php index f0460a2ae0..e10d306154 100644 --- a/app/Http/Controllers/PreferencesController.php +++ b/app/Http/Controllers/PreferencesController.php @@ -61,14 +61,12 @@ class PreferencesController extends Controller { parent::__construct(); - $this->middleware( - static function ($request, $next) { - app('view')->share('title', (string)trans('firefly.preferences')); - app('view')->share('mainTitleIcon', 'fa-gear'); + $this->middleware(static function ($request, $next) { + app('view')->share('title', (string) trans('firefly.preferences')); + app('view')->share('mainTitleIcon', 'fa-gear'); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -81,14 +79,20 @@ class PreferencesController extends Controller */ public function index(AccountRepositoryInterface $repository): Factory|\Illuminate\Contracts\View\View { - $accounts = $repository->getAccountsByType([AccountTypeEnum::DEFAULT->value, AccountTypeEnum::ASSET->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value]); - $isDocker = env('IS_DOCKER', false); // @phpstan-ignore-line - $groupedAccounts = []; + $accounts = $repository->getAccountsByType([ + AccountTypeEnum::DEFAULT->value, + AccountTypeEnum::ASSET->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::MORTGAGE->value + ]); + $isDocker = env('IS_DOCKER', false); // @phpstan-ignore-line + $groupedAccounts = []; /** @var Account $account */ foreach ($accounts as $account) { - $type = $account->accountType->type; - $role = sprintf('opt_group_%s', $repository->getMetaValue($account, 'account_role')); + $type = $account->accountType->type; + $role = sprintf('opt_group_%s', $repository->getMetaValue($account, 'account_role')); if (in_array($type, [AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value], true)) { $role = sprintf('opt_group_l_%s', $type); @@ -97,62 +101,61 @@ class PreferencesController extends Controller if ('opt_group_' === $role) { $role = 'opt_group_defaultAsset'; } - $groupedAccounts[(string)trans(sprintf('firefly.%s', $role))][$account->id] = $account->name; + $groupedAccounts[(string) trans(sprintf('firefly.%s', $role))][$account->id] = $account->name; } ksort($groupedAccounts); /** @var array $accountIds */ - $accountIds = $accounts->pluck('id')->toArray(); - $viewRange = Navigation::getViewRange(false); - $frontpageAccountsPref = Preferences::get('frontpageAccounts', $accountIds); - $frontpageAccounts = $frontpageAccountsPref->data; + $accountIds = $accounts->pluck('id')->toArray(); + $viewRange = Navigation::getViewRange(false); + $frontpageAccountsPref = Preferences::get('frontpageAccounts', $accountIds); + $frontpageAccounts = $frontpageAccountsPref->data; if (!is_array($frontpageAccounts)) { $frontpageAccounts = $accountIds; } - $language = Steam::getLanguage(); - $languages = config('firefly.languages'); - $locale = Preferences::get('locale', config('firefly.default_locale', 'equal'))->data; - $listPageSize = Preferences::get('listPageSize', 50)->data; - $darkMode = Preferences::get('darkMode', 'browser')->data; - $customFiscalYear = Preferences::get('customFiscalYear', 0)->data; - $fiscalYearStartStr = Preferences::get('fiscalYearStart', '01-01')->data; - $convertToPrimary = $this->convertToPrimary; + $language = Steam::getLanguage(); + $languages = config('firefly.languages'); + $locale = Preferences::get('locale', config('firefly.default_locale', 'equal'))->data; + $listPageSize = Preferences::get('listPageSize', 50)->data; + $darkMode = Preferences::get('darkMode', 'browser')->data; + $customFiscalYear = Preferences::get('customFiscalYear', 0)->data; + $fiscalYearStartStr = Preferences::get('fiscalYearStart', '01-01')->data; + $convertToPrimary = $this->convertToPrimary; if (is_array($fiscalYearStartStr)) { $fiscalYearStartStr = '01-01'; } - $fiscalYearStart = sprintf('%s-%s', Carbon::now()->format('Y'), (string)$fiscalYearStartStr); - $tjOptionalFields = Preferences::get('transaction_journal_optional_fields', [])->data; - $availableDarkModes = config('firefly.available_dark_modes'); + $fiscalYearStart = sprintf('%s-%s', Carbon::now()->format('Y'), (string) $fiscalYearStartStr); + $tjOptionalFields = Preferences::get('transaction_journal_optional_fields', [])->data; + $availableDarkModes = config('firefly.available_dark_modes'); // notifications settings - $slackUrl = Preferences::getEncrypted('slack_webhook_url', '')->data; - $pushoverAppToken = (string)Preferences::getEncrypted('pushover_app_token', '')->data; - $pushoverUserToken = (string)Preferences::getEncrypted('pushover_user_token', '')->data; - $ntfyServer = Preferences::getEncrypted('ntfy_server', 'https://ntfy.sh')->data; - $ntfyTopic = (string)Preferences::getEncrypted('ntfy_topic', '')->data; - $ntfyAuth = '1' === Preferences::get('ntfy_auth', false)->data; - $ntfyUser = Preferences::getEncrypted('ntfy_user', '')->data; - $ntfyPass = (string)Preferences::getEncrypted('ntfy_pass', '')->data; - $channels = config('notifications.channels'); - $forcedAvailability = []; - $anonymous = Steam::anonymous(); + $slackUrl = Preferences::getEncrypted('slack_webhook_url', '')->data; + $pushoverAppToken = (string) Preferences::getEncrypted('pushover_app_token', '')->data; + $pushoverUserToken = (string) Preferences::getEncrypted('pushover_user_token', '')->data; + $ntfyServer = Preferences::getEncrypted('ntfy_server', 'https://ntfy.sh')->data; + $ntfyTopic = (string) Preferences::getEncrypted('ntfy_topic', '')->data; + $ntfyAuth = '1' === Preferences::get('ntfy_auth', false)->data; + $ntfyUser = Preferences::getEncrypted('ntfy_user', '')->data; + $ntfyPass = (string) Preferences::getEncrypted('ntfy_pass', '')->data; + $channels = config('notifications.channels'); + $forcedAvailability = []; + $anonymous = Steam::anonymous(); // notification preferences - $notifications = []; + $notifications = []; foreach (config('notifications.notifications.user') as $key => $info) { if (true === $info['enabled']) { - $notifications[$key] - = [ - 'enabled' => true === Preferences::get(sprintf('notification_%s', $key), true)->data, - 'configurable' => $info['configurable'], - ]; + $notifications[$key] = [ + 'enabled' => true === Preferences::get(sprintf('notification_%s', $key), true)->data, + 'configurable' => $info['configurable'] + ]; } } // loop all channels to see if they are available. foreach ($channels as $channel => $info) { $forcedAvailability[$channel] = true; } - $forcedAvailability['ntfy'] = '' !== $ntfyTopic; + $forcedAvailability['ntfy'] = '' !== $ntfyTopic; $forcedAvailability['pushover'] = '' !== $pushoverAppToken && '' !== $pushoverUserToken; ksort($languages); @@ -165,7 +168,7 @@ class PreferencesController extends Controller Log::error($e->getMessage()); $locales = []; } - $locales = ['equal' => (string)trans('firefly.equal_to_language')] + $locales; + $locales = ['equal' => (string) trans('firefly.equal_to_language')] + $locales; // an important fallback is that the frontPageAccount array gets refilled automatically // when it turns up empty. if (0 === count($frontpageAccounts)) { @@ -185,7 +188,35 @@ class PreferencesController extends Controller $ntfyPass = ''; } - return view('preferences.index', ['anonymous' => $anonymous, 'language' => $language, 'pushoverAppToken' => $pushoverAppToken, 'pushoverUserToken' => $pushoverUserToken, 'ntfyServer' => $ntfyServer, 'ntfyTopic' => $ntfyTopic, 'ntfyAuth' => $ntfyAuth, 'channels' => $channels, 'ntfyUser' => $ntfyUser, 'forcedAvailability' => $forcedAvailability, 'ntfyPass' => $ntfyPass, 'groupedAccounts' => $groupedAccounts, 'isDocker' => $isDocker, 'frontpageAccounts' => $frontpageAccounts, 'languages' => $languages, 'darkMode' => $darkMode, 'availableDarkModes' => $availableDarkModes, 'notifications' => $notifications, 'convertToPrimary' => $convertToPrimary, 'slackUrl' => $slackUrl, 'locales' => $locales, 'locale' => $locale, 'tjOptionalFields' => $tjOptionalFields, 'viewRange' => $viewRange, 'customFiscalYear' => $customFiscalYear, 'listPageSize' => $listPageSize, 'fiscalYearStart' => $fiscalYearStart]); + return view('preferences.index', [ + 'anonymous' => $anonymous, + 'language' => $language, + 'pushoverAppToken' => $pushoverAppToken, + 'pushoverUserToken' => $pushoverUserToken, + 'ntfyServer' => $ntfyServer, + 'ntfyTopic' => $ntfyTopic, + 'ntfyAuth' => $ntfyAuth, + 'channels' => $channels, + 'ntfyUser' => $ntfyUser, + 'forcedAvailability' => $forcedAvailability, + 'ntfyPass' => $ntfyPass, + 'groupedAccounts' => $groupedAccounts, + 'isDocker' => $isDocker, + 'frontpageAccounts' => $frontpageAccounts, + 'languages' => $languages, + 'darkMode' => $darkMode, + 'availableDarkModes' => $availableDarkModes, + 'notifications' => $notifications, + 'convertToPrimary' => $convertToPrimary, + 'slackUrl' => $slackUrl, + 'locales' => $locales, + 'locale' => $locale, + 'tjOptionalFields' => $tjOptionalFields, + 'viewRange' => $viewRange, + 'customFiscalYear' => $customFiscalYear, + 'listPageSize' => $listPageSize, + 'fiscalYearStart' => $fiscalYearStart + ]); } /** @@ -203,14 +234,14 @@ class PreferencesController extends Controller $frontpageAccounts = []; if (is_array($request->get('frontpageAccounts')) && count($request->get('frontpageAccounts')) > 0) { foreach ($request->get('frontpageAccounts') as $id) { - $frontpageAccounts[] = (int)$id; + $frontpageAccounts[] = (int) $id; } Log::debug('Update frontpageAccounts', $frontpageAccounts); Preferences::set('frontpageAccounts', $frontpageAccounts); } // extract notifications: - $all = $request->all(); + $all = $request->all(); foreach (config('notifications.notifications.user') as $key => $info) { $key = sprintf('notification_%s', $key); if (array_key_exists($key, $all)) { @@ -233,7 +264,6 @@ class PreferencesController extends Controller // notification settings, cannot be set by the demo user. if (!auth()->user()->hasRole('demo')) { - $variables = ['slack_webhook_url', 'pushover_app_token', 'pushover_user_token', 'ntfy_server', 'ntfy_topic', 'ntfy_user', 'ntfy_pass']; foreach ($variables as $variable) { if ('' === $all[$variable]) { @@ -247,7 +277,7 @@ class PreferencesController extends Controller } // convert primary - $convertToPrimary = 1 === (int)$request->get('convertToPrimary'); + $convertToPrimary = 1 === (int) $request->get('convertToPrimary'); if ($convertToPrimary && !$this->convertToPrimary) { // set to true! Log::debug('User sets convertToPrimary to true.'); @@ -259,9 +289,9 @@ class PreferencesController extends Controller Preferences::set('convert_to_primary', $convertToPrimary); // custom fiscal year - $customFiscalYear = 1 === (int)$request->get('customFiscalYear'); + $customFiscalYear = 1 === (int) $request->get('customFiscalYear'); Preferences::set('customFiscalYear', $customFiscalYear); - $fiscalYearString = (string)$request->get('fiscalYearStart'); + $fiscalYearString = (string) $request->get('fiscalYearStart'); if ('' !== $fiscalYearString) { $fiscalYearStart = Carbon::parse($fiscalYearString, config('app.timezone'))->format('m-d'); Preferences::set('fiscalYearStart', $fiscalYearStart); @@ -269,15 +299,15 @@ class PreferencesController extends Controller // save page size: Preferences::set('listPageSize', 50); - $listPageSize = (int)$request->get('listPageSize'); + $listPageSize = (int) $request->get('listPageSize'); if ($listPageSize > 0 && $listPageSize < 1337) { Preferences::set('listPageSize', $listPageSize); } // language: /** @var Preference $currentLang */ - $currentLang = Preferences::get('language', 'en_US'); - $lang = $request->get('language'); + $currentLang = Preferences::get('language', 'en_US'); + $lang = $request->get('language'); if (array_key_exists($lang, config('firefly.languages'))) { Preferences::set('language', $lang); } @@ -288,14 +318,14 @@ class PreferencesController extends Controller // same for locale: if (!auth()->user()->hasRole('demo')) { - $locale = (string)$request->get('locale'); + $locale = (string) $request->get('locale'); $locale = '' === $locale ? null : $locale; Preferences::set('locale', $locale); } // optional fields for transactions: - $setOptions = $request->get('tj') ?? []; - $optionalTj = [ + $setOptions = $request->get('tj') ?? []; + $optionalTj = [ 'interest_date' => array_key_exists('interest_date', $setOptions), 'book_date' => array_key_exists('book_date', $setOptions), 'process_date' => array_key_exists('process_date', $setOptions), @@ -307,22 +337,22 @@ class PreferencesController extends Controller 'attachments' => array_key_exists('attachments', $setOptions), 'external_url' => array_key_exists('external_url', $setOptions), 'location' => array_key_exists('location', $setOptions), - 'links' => array_key_exists('links', $setOptions), + 'links' => array_key_exists('links', $setOptions) ]; Preferences::set('transaction_journal_optional_fields', $optionalTj); // dark mode - $darkMode = $request->get('darkMode') ?? 'browser'; + $darkMode = $request->get('darkMode') ?? 'browser'; if (in_array($darkMode, config('firefly.available_dark_modes'), true)) { Preferences::set('darkMode', $darkMode); } // anonymous amounts? - $anonymous = '1' === $request->get('anonymous'); + $anonymous = '1' === $request->get('anonymous'); Preferences::set('anonymous', $anonymous); // save and continue - session()->flash('success', (string)trans('firefly.saved_preferences')); + session()->flash('success', (string) trans('firefly.saved_preferences')); Preferences::mark(); Log::debug('Done saving settings.'); @@ -331,13 +361,12 @@ class PreferencesController extends Controller public function testNotification(Request $request): mixed { - $all = $request->all(); $channel = $all['channel'] ?? ''; switch ($channel) { default: - session()->flash('error', (string)trans('firefly.notification_test_failed', ['channel' => $channel])); + session()->flash('error', (string) trans('firefly.notification_test_failed', ['channel' => $channel])); break; @@ -349,7 +378,7 @@ class PreferencesController extends Controller $user = auth()->user(); Log::debug(sprintf('Now in testNotification("%s") controller.', $channel)); event(new UserTestsNotificationChannel($channel, $user)); - session()->flash('success', (string)trans('firefly.notification_test_executed', ['channel' => $channel])); + session()->flash('success', (string) trans('firefly.notification_test_executed', ['channel' => $channel])); } return ''; diff --git a/app/Http/Controllers/Profile/MfaController.php b/app/Http/Controllers/Profile/MfaController.php index 269b3318ac..6250612398 100644 --- a/app/Http/Controllers/Profile/MfaController.php +++ b/app/Http/Controllers/Profile/MfaController.php @@ -69,20 +69,17 @@ class MfaController extends Controller { parent::__construct(); - $this->middleware( - static function ($request, $next) { - app('view')->share('title', (string)trans('firefly.profile')); - app('view')->share('mainTitleIcon', 'fa-user'); + $this->middleware(static function ($request, $next) { + app('view')->share('title', (string) trans('firefly.profile')); + app('view')->share('mainTitleIcon', 'fa-user'); - return $next($request); - } - ); - $authGuard = config('firefly.authentication_guard'); + return $next($request); + }); + $authGuard = config('firefly.authentication_guard'); $this->internalAuth = 'web' === $authGuard; Log::debug(sprintf('ProfileController::__construct(). Authentication guard is "%s"', $authGuard)); $this->middleware(IsDemoUser::class)->except(['index']); - } public function backupCodes(Request $request): Factory|RedirectResponse|View @@ -109,7 +106,7 @@ class MfaController extends Controller return redirect(route('profile.index')); } - $enabledMFA = null !== auth()->user()->mfa_secret; + $enabledMFA = null !== auth()->user()->mfa_secret; if (false === $enabledMFA) { request()->session()->flash('info', trans('firefly.mfa_not_enabled')); @@ -117,24 +114,18 @@ class MfaController extends Controller } // generate recovery codes: $recovery = app(Recovery::class); - $recoveryCodes = $recovery->lowercase() - ->setCount(8) // Generate 8 codes - ->setBlocks(2) // Every code must have 2 blocks - ->setChars(6) // Each block must have 6 chars - ->toArray() - ; + $recoveryCodes = $recovery->lowercase()->setCount(8)->setBlocks(2)->setChars(6)->toArray(); // Generate 8 codes // Every code must have 2 blocks // Each block must have 6 chars $codes = implode("\r\n", $recoveryCodes); Preferences::set('mfa_recovery', $recoveryCodes); Preferences::mark(); // send user notification. - $user = auth()->user(); + $user = auth()->user(); Log::channel('audit')->info(sprintf('User "%s" has generated new backup codes.', $user->email)); event(new UserHasGeneratedNewBackupCodes($user)); return view('profile.mfa.backup-codes-post')->with(['codes' => $codes]); - } public function disableMFA(Request $request): Factory|RedirectResponse|View @@ -144,16 +135,16 @@ class MfaController extends Controller return redirect(route('profile.index')); } - $enabledMFA = null !== auth()->user()->mfa_secret; + $enabledMFA = null !== auth()->user()->mfa_secret; if (false === $enabledMFA) { request()->session()->flash('info', trans('firefly.mfa_already_disabled')); return redirect(route('profile.index')); } - $subTitle = (string)trans('firefly.mfa_index_title'); + $subTitle = (string) trans('firefly.mfa_index_title'); $subTitleIcon = 'fa-calculator'; - return view('profile.mfa.disable-mfa')->with(['subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'enabledMFA' => $enabledMFA]); + return view('profile.mfa.disable-mfa')->with(['subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'enabledMFA' => $enabledMFA]); } /** @@ -171,15 +162,15 @@ class MfaController extends Controller $repository = app(UserRepositoryInterface::class); /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); Preferences::delete('temp-mfa-secret'); Preferences::delete('temp-mfa-codes'); $repository->setMFACode($user, null); Preferences::mark(); - session()->flash('success', (string)trans('firefly.pref_two_factor_auth_disabled')); - session()->flash('info', (string)trans('firefly.pref_two_factor_auth_remove_it')); + session()->flash('success', (string) trans('firefly.pref_two_factor_auth_disabled')); + session()->flash('info', (string) trans('firefly.pref_two_factor_auth_remove_it')); // also logout current 2FA tokens. $cookieName = config('google2fa.cookie_name', 'google2fa_token'); @@ -210,20 +201,18 @@ class MfaController extends Controller // If FF3 already has a secret, just set the two-factor auth enabled to 1, // and let the user continue with the existing secret. if ($enabledMFA) { - session()->flash('info', (string)trans('firefly.2fa_already_enabled')); + session()->flash('info', (string) trans('firefly.2fa_already_enabled')); return redirect(route('profile.index')); } - $domain = $this->getDomain(); - $secret = Google2FA::generateSecretKey(); - $image = Google2FA::getQRCodeInline($domain, auth()->user()->email, $secret); + $domain = $this->getDomain(); + $secret = Google2FA::generateSecretKey(); + $image = Google2FA::getQRCodeInline($domain, auth()->user()->email, $secret); Preferences::set('temp-mfa-secret', $secret); - - return view('profile.mfa.enable-mfa', ['image' => $image, 'secret' => $secret]); - + return view('profile.mfa.enable-mfa', ['image' => $image, 'secret' => $secret]); } /** @@ -241,11 +230,11 @@ class MfaController extends Controller } /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); // verify password. - $password = $request->get('password'); - if (!auth()->validate(['email' => $user->email, 'password' => $password])) { + $password = $request->get('password'); + if (!auth()->validate(['email' => $user->email, 'password' => $password])) { session()->flash('error', 'Bad user pw, no MFA for you!'); return redirect(route('profile.mfa.index')); @@ -257,17 +246,17 @@ class MfaController extends Controller if (is_array($secret)) { $secret = null; } - $secret = (string)$secret; + $secret = (string) $secret; $repository->setMFACode($user, $secret); Preferences::delete('temp-mfa-secret'); - session()->flash('success', (string)trans('firefly.saved_preferences')); + session()->flash('success', (string) trans('firefly.saved_preferences')); Preferences::mark(); // also save the code so replay attack is prevented. - $mfaCode = $request->get('code'); + $mfaCode = $request->get('code'); $this->addToMFAHistory($mfaCode); // make sure MFA is logged out. @@ -294,11 +283,8 @@ class MfaController extends Controller private function addToMFAHistory(string $mfaCode): void { /** @var array $mfaHistory */ - $mfaHistory = Preferences::get('mfa_history', [])->data; - $entry = [ - 'time' => Carbon::now()->getTimestamp(), - 'code' => $mfaCode, - ]; + $mfaHistory = Preferences::get('mfa_history', [])->data; + $entry = ['time' => Carbon::now()->getTimestamp(), 'code' => $mfaCode]; $mfaHistory[] = $entry; Preferences::set('mfa_history', $mfaHistory); @@ -317,11 +303,8 @@ class MfaController extends Controller foreach ($mfaHistory as $entry) { $time = $entry['time']; $code = $entry['code']; - if ($now - $time <= 300) { - $newHistory[] = [ - 'time' => $time, - 'code' => $code, - ]; + if (($now - $time) <= 300) { + $newHistory[] = ['time' => $time, 'code' => $code]; } } Preferences::set('mfa_history', $newHistory); @@ -335,10 +318,10 @@ class MfaController extends Controller return redirect(route('profile.index')); } - $subTitle = (string)trans('firefly.mfa_index_title'); + $subTitle = (string) trans('firefly.mfa_index_title'); $subTitleIcon = 'fa-calculator'; $enabledMFA = null !== auth()->user()->mfa_secret; - return view('profile.mfa.index')->with(['subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'enabledMFA' => $enabledMFA]); + return view('profile.mfa.index')->with(['subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'enabledMFA' => $enabledMFA]); } } diff --git a/app/Http/Controllers/ProfileController.php b/app/Http/Controllers/ProfileController.php index d080d04f7d..8a5a812b70 100644 --- a/app/Http/Controllers/ProfileController.php +++ b/app/Http/Controllers/ProfileController.php @@ -23,10 +23,8 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers; -use FireflyIII\Events\Security\User\UserChangedEmailAddress; -use FireflyIII\Support\Facades\Preferences; -use Illuminate\Support\Facades\Log; use Exception; +use FireflyIII\Events\Security\User\UserChangedEmailAddress; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\ValidationException; use FireflyIII\Http\Middleware\IsDemoUser; @@ -35,6 +33,7 @@ use FireflyIII\Http\Requests\EmailFormRequest; use FireflyIII\Http\Requests\ProfileFormRequest; use FireflyIII\Models\Preference; use FireflyIII\Repositories\User\UserRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use FireflyIII\Support\Http\Controllers\CreateStuff; use FireflyIII\User; use Illuminate\Auth\AuthenticationException; @@ -48,6 +47,7 @@ use Illuminate\Support\Collection; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Hash; +use Illuminate\Support\Facades\Log; use Illuminate\View\View; use Laravel\Passport\ClientRepository; use Psr\Container\ContainerExceptionInterface; @@ -72,15 +72,13 @@ class ProfileController extends Controller { parent::__construct(); - $this->middleware( - static function ($request, $next) { - app('view')->share('title', (string) trans('firefly.profile')); - app('view')->share('mainTitleIcon', 'fa-user'); + $this->middleware(static function ($request, $next) { + app('view')->share('title', (string) trans('firefly.profile')); + app('view')->share('mainTitleIcon', 'fa-user'); - return $next($request); - } - ); - $authGuard = config('firefly.authentication_guard'); + return $next($request); + }); + $authGuard = config('firefly.authentication_guard'); $this->internalAuth = 'web' === $authGuard; Log::debug(sprintf('ProfileController::__construct(). Authentication guard is "%s"', $authGuard)); @@ -137,7 +135,7 @@ class ProfileController extends Controller $subTitle = (string) trans('firefly.delete_account'); $subTitleIcon = 'fa-trash'; - return view('profile.delete-account', ['title' => $title, 'subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon]); + return view('profile.delete-account', ['title' => $title, 'subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon]); } /** @@ -151,7 +149,10 @@ class ProfileController extends Controller /** @var User $user */ $user = auth()->user(); $isInternalAuth = $this->internalAuth; - $count = DB::table('oauth_clients')->where('personal_access_client', true)->whereNull('user_id')->count(); + $count = DB::table('oauth_clients') + ->where('personal_access_client', true) + ->whereNull('user_id') + ->count(); $subTitle = $user->email; $userId = $user->id; $enabled2FA = null !== $user->mfa_secret; @@ -169,16 +170,20 @@ class ProfileController extends Controller $repository->createPersonalAccessClient(null, $name, 'http://localhost'); } - $accessToken = Preferences::get('access_token'); + $accessToken = Preferences::get('access_token'); if (null === $accessToken) { $token = $user->generateAccessToken(); $accessToken = Preferences::set('access_token', $token); } - return view( - 'profile.index', - ['subTitle' => $subTitle, 'mfaBackupCount' => $mfaBackupCount, 'userId' => $userId, 'accessToken' => $accessToken, 'enabled2FA' => $enabled2FA, 'isInternalAuth' => $isInternalAuth] - ); + return view('profile.index', [ + 'subTitle' => $subTitle, + 'mfaBackupCount' => $mfaBackupCount, + 'userId' => $userId, + 'accessToken' => $accessToken, + 'enabled2FA' => $enabled2FA, + 'isInternalAuth' => $isInternalAuth + ]); } public function logoutOtherSessions(): Factory|RedirectResponse|View @@ -252,7 +257,7 @@ class ProfileController extends Controller $subTitle = (string) trans('firefly.change_your_email'); $subTitleIcon = 'fa-envelope'; - return view('profile.change-email', ['title' => $title, 'subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'email' => $email]); + return view('profile.change-email', ['title' => $title, 'subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'email' => $email]); } /** @@ -271,7 +276,7 @@ class ProfileController extends Controller $new = $request->get('new_password'); /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); try { $this->validatePassword($user, $current, $new); @@ -304,7 +309,7 @@ class ProfileController extends Controller $subTitle = (string) trans('firefly.change_your_password'); $subTitleIcon = 'fa-key'; - return view('profile.change-password', ['title' => $title, 'subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon]); + return view('profile.change-password', ['title' => $title, 'subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon]); } /** @@ -347,10 +352,7 @@ class ProfileController extends Controller return redirect(route('profile.index')); } - $creds = [ - 'email' => auth()->user()->email, - 'password' => $request->get('password'), - ]; + $creds = ['email' => auth()->user()->email, 'password' => $request->get('password')]; if (Auth::once($creds)) { Auth::logoutOtherDevices($request->get('password')); session()->flash('info', (string) trans('firefly.other_sessions_logged_out')); @@ -396,8 +398,8 @@ class ProfileController extends Controller } // find preference with this token value. - $set = Preferences::findByName('email_change_undo_token'); - $user = null; + $set = Preferences::findByName('email_change_undo_token'); + $user = null; /** @var Preference $preference */ foreach ($set as $preference) { @@ -410,7 +412,7 @@ class ProfileController extends Controller } // found user.which email address to return to? - $set = Preferences::beginsWith($user, 'previous_email_'); + $set = Preferences::beginsWith($user, 'previous_email_'); /** @var null|string $match */ $match = null; diff --git a/app/Http/Controllers/Recurring/CreateController.php b/app/Http/Controllers/Recurring/CreateController.php index abca6a0971..6a9b58c527 100644 --- a/app/Http/Controllers/Recurring/CreateController.php +++ b/app/Http/Controllers/Recurring/CreateController.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Recurring; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Enums\RecurrenceRepetitionWeekend; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Helpers\Attachments\AttachmentHelperInterface; @@ -35,6 +34,7 @@ use FireflyIII\Models\TransactionJournal; use FireflyIII\Repositories\Bill\BillRepositoryInterface; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Repositories\Recurring\RecurringRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; @@ -47,9 +47,9 @@ use Illuminate\View\View; */ class CreateController extends Controller { - private AttachmentHelperInterface $attachments; - private BillRepositoryInterface $billRepository; - private BudgetRepositoryInterface $budgetRepos; + private AttachmentHelperInterface $attachments; + private BillRepositoryInterface $billRepository; + private BudgetRepositoryInterface $budgetRepos; private RecurringRepositoryInterface $repository; /** @@ -60,20 +60,18 @@ class CreateController extends Controller parent::__construct(); // translations: - $this->middleware( - function ($request, $next) { - app('view')->share('mainTitleIcon', 'fa-paint-brush'); - app('view')->share('title', (string) trans('firefly.recurrences')); - app('view')->share('subTitle', (string) trans('firefly.create_new_recurrence')); + $this->middleware(function ($request, $next) { + app('view')->share('mainTitleIcon', 'fa-paint-brush'); + app('view')->share('title', (string) trans('firefly.recurrences')); + app('view')->share('subTitle', (string) trans('firefly.create_new_recurrence')); - $this->repository = app(RecurringRepositoryInterface::class); - $this->budgetRepos = app(BudgetRepositoryInterface::class); - $this->attachments = app(AttachmentHelperInterface::class); - $this->billRepository = app(BillRepositoryInterface::class); + $this->repository = app(RecurringRepositoryInterface::class); + $this->budgetRepos = app(BudgetRepositoryInterface::class); + $this->attachments = app(AttachmentHelperInterface::class); + $this->billRepository = app(BillRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -94,30 +92,35 @@ class CreateController extends Controller $this->rememberPreviousUrl('recurring.create.url'); } $request->session()->forget('recurring.create.fromStore'); - $repetitionEnds = [ + $repetitionEnds = [ 'forever' => (string) trans('firefly.repeat_forever'), 'until_date' => (string) trans('firefly.repeat_until_date'), - 'times' => (string) trans('firefly.repeat_times'), + 'times' => (string) trans('firefly.repeat_times') ]; - $weekendResponses = [ + $weekendResponses = [ RecurrenceRepetitionWeekend::WEEKEND_DO_NOTHING->value => (string) trans('firefly.do_nothing'), RecurrenceRepetitionWeekend::WEEKEND_SKIP_CREATION->value => (string) trans('firefly.skip_transaction'), RecurrenceRepetitionWeekend::WEEKEND_TO_FRIDAY->value => (string) trans('firefly.jump_to_friday'), - RecurrenceRepetitionWeekend::WEEKEND_TO_MONDAY->value => (string) trans('firefly.jump_to_monday'), + RecurrenceRepetitionWeekend::WEEKEND_TO_MONDAY->value => (string) trans('firefly.jump_to_monday') ]; - $hasOldInput = null !== $request->old('_token'); // flash some data - $preFilled = [ + $hasOldInput = null !== $request->old('_token'); // flash some data + $preFilled = [ 'first_date' => $tomorrow->format('Y-m-d'), 'transaction_type' => $hasOldInput ? $request->old('transaction_type') : 'withdrawal', 'active' => $hasOldInput ? (bool) $request->old('active') : true, - 'apply_rules' => $hasOldInput ? (bool) $request->old('apply_rules') : true, + 'apply_rules' => $hasOldInput ? (bool) $request->old('apply_rules') : true ]; $request->session()->flash('preFilled', $preFilled); - return view( - 'recurring.create', - ['tomorrow' => $tomorrow, 'oldRepetitionType' => $oldRepetitionType, 'bills' => $bills, 'weekendResponses' => $weekendResponses, 'preFilled' => $preFilled, 'repetitionEnds' => $repetitionEnds, 'budgets' => $budgets] - ); + return view('recurring.create', [ + 'tomorrow' => $tomorrow, + 'oldRepetitionType' => $oldRepetitionType, + 'bills' => $bills, + 'weekendResponses' => $weekendResponses, + 'preFilled' => $preFilled, + 'repetitionEnds' => $repetitionEnds, + 'budgets' => $budgets + ]); } /** @@ -136,31 +139,31 @@ class CreateController extends Controller $this->rememberPreviousUrl('recurring.create.url'); } $request->session()->forget('recurring.create.fromStore'); - $repetitionEnds = [ + $repetitionEnds = [ 'forever' => (string) trans('firefly.repeat_forever'), 'until_date' => (string) trans('firefly.repeat_until_date'), - 'times' => (string) trans('firefly.repeat_times'), + 'times' => (string) trans('firefly.repeat_times') ]; - $weekendResponses = [ + $weekendResponses = [ RecurrenceRepetitionWeekend::WEEKEND_DO_NOTHING->value => (string) trans('firefly.do_nothing'), RecurrenceRepetitionWeekend::WEEKEND_SKIP_CREATION->value => (string) trans('firefly.skip_transaction'), RecurrenceRepetitionWeekend::WEEKEND_TO_FRIDAY->value => (string) trans('firefly.jump_to_friday'), - RecurrenceRepetitionWeekend::WEEKEND_TO_MONDAY->value => (string) trans('firefly.jump_to_monday'), + RecurrenceRepetitionWeekend::WEEKEND_TO_MONDAY->value => (string) trans('firefly.jump_to_monday') ]; // fill prefilled with journal info - $type = strtolower((string) $journal->transactionType->type); + $type = strtolower((string) $journal->transactionType->type); /** @var Transaction $source */ - $source = $journal->transactions()->where('amount', '<', 0)->first(); + $source = $journal->transactions()->where('amount', '<', 0)->first(); /** @var Transaction $dest */ - $dest = $journal->transactions()->where('amount', '>', 0)->first(); - $category = null !== $journal->categories()->first() ? $journal->categories()->first()->name : ''; - $budget = null !== $journal->budgets()->first() ? $journal->budgets()->first()->id : 0; - $bill = null !== $journal->bill ? $journal->bill->id : 0; - $hasOldInput = null !== $request->old('_token'); // flash some data - $preFilled = []; + $dest = $journal->transactions()->where('amount', '>', 0)->first(); + $category = null !== $journal->categories()->first() ? $journal->categories()->first()->name : ''; + $budget = null !== $journal->budgets()->first() ? $journal->budgets()->first()->id : 0; + $bill = null !== $journal->bill ? $journal->bill->id : 0; + $hasOldInput = null !== $request->old('_token'); // flash some data + $preFilled = []; if ($hasOldInput) { $preFilled = [ 'title' => $request->old('title'), @@ -179,7 +182,7 @@ class CreateController extends Controller 'budget_id' => $request->old('budget_id'), 'bill_id' => $request->old('bill_id'), 'active' => (bool) $request->old('active'), - 'apply_rules' => (bool) $request->old('apply_rules'), + 'apply_rules' => (bool) $request->old('apply_rules') ]; } if (false === $hasOldInput) { @@ -200,12 +203,20 @@ class CreateController extends Controller 'budget_id' => $budget, 'bill_id' => $bill, 'active' => true, - 'apply_rules' => true, + 'apply_rules' => true ]; } $request->session()->flash('preFilled', $preFilled); - return view('recurring.create', ['tomorrow' => $tomorrow, 'oldRepetitionType' => $oldRepetitionType, 'bills' => $bills, 'weekendResponses' => $weekendResponses, 'preFilled' => $preFilled, 'repetitionEnds' => $repetitionEnds, 'budgets' => $budgets]); + return view('recurring.create', [ + 'tomorrow' => $tomorrow, + 'oldRepetitionType' => $oldRepetitionType, + 'bills' => $bills, + 'weekendResponses' => $weekendResponses, + 'preFilled' => $preFilled, + 'repetitionEnds' => $repetitionEnds, + 'budgets' => $budgets + ]); } /** @@ -217,7 +228,7 @@ class CreateController extends Controller */ public function store(RecurrenceFormRequest $request) { - $data = $request->getAll(); + $data = $request->getAll(); try { $recurrence = $this->repository->store($data); @@ -233,7 +244,7 @@ class CreateController extends Controller // store attachment(s): /** @var null|array $files */ - $files = $request->hasFile('attachments') ? $request->file('attachments') : null; + $files = $request->hasFile('attachments') ? $request->file('attachments') : null; if (null !== $files && !auth()->user()->hasRole('demo')) { $this->attachments->saveAttachmentsForModel($recurrence, $files); } diff --git a/app/Http/Controllers/Recurring/DeleteController.php b/app/Http/Controllers/Recurring/DeleteController.php index b542f2998e..92fa26bb6d 100644 --- a/app/Http/Controllers/Recurring/DeleteController.php +++ b/app/Http/Controllers/Recurring/DeleteController.php @@ -24,10 +24,10 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Recurring; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\Recurrence; use FireflyIII\Repositories\Recurring\RecurringRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; @@ -49,16 +49,14 @@ class DeleteController extends Controller parent::__construct(); // translations: - $this->middleware( - function ($request, $next) { - app('view')->share('mainTitleIcon', 'fa-paint-brush'); - app('view')->share('title', (string) trans('firefly.recurrences')); + $this->middleware(function ($request, $next) { + app('view')->share('mainTitleIcon', 'fa-paint-brush'); + app('view')->share('title', (string) trans('firefly.recurrences')); - $this->repository = app(RecurringRepositoryInterface::class); + $this->repository = app(RecurringRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -68,13 +66,13 @@ class DeleteController extends Controller */ public function delete(Recurrence $recurrence): Factory|\Illuminate\Contracts\View\View { - $subTitle = (string) trans('firefly.delete_recurring', ['title' => $recurrence->title]); + $subTitle = (string) trans('firefly.delete_recurring', ['title' => $recurrence->title]); // put previous url in session $this->rememberPreviousUrl('recurrences.delete.url'); $journalsCreated = $this->repository->getTransactions($recurrence)->count(); - return view('recurring.delete', ['recurrence' => $recurrence, 'subTitle' => $subTitle, 'journalsCreated' => $journalsCreated]); + return view('recurring.delete', ['recurrence' => $recurrence, 'subTitle' => $subTitle, 'journalsCreated' => $journalsCreated]); } /** diff --git a/app/Http/Controllers/Recurring/EditController.php b/app/Http/Controllers/Recurring/EditController.php index c12c8b4773..bfe5b26196 100644 --- a/app/Http/Controllers/Recurring/EditController.php +++ b/app/Http/Controllers/Recurring/EditController.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Recurring; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Enums\RecurrenceRepetitionWeekend; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Helpers\Attachments\AttachmentHelperInterface; @@ -36,6 +35,7 @@ use FireflyIII\Repositories\Bill\BillRepositoryInterface; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Repositories\Recurring\RecurringRepositoryInterface; use FireflyIII\Support\Facades\ExpandedForm; +use FireflyIII\Support\Facades\Preferences; use FireflyIII\Support\JsonApi\Enrichments\RecurringEnrichment; use FireflyIII\Transformers\RecurrenceTransformer; use FireflyIII\User; @@ -51,9 +51,9 @@ use Illuminate\View\View; */ class EditController extends Controller { - private AttachmentHelperInterface $attachments; - private BillRepositoryInterface $billRepository; - private BudgetRepositoryInterface $budgetRepos; + private AttachmentHelperInterface $attachments; + private BillRepositoryInterface $billRepository; + private BudgetRepositoryInterface $budgetRepos; private RecurringRepositoryInterface $repository; /** @@ -64,20 +64,18 @@ class EditController extends Controller parent::__construct(); // translations: - $this->middleware( - function ($request, $next) { - app('view')->share('mainTitleIcon', 'fa-paint-brush'); - app('view')->share('title', (string) trans('firefly.recurrences')); - app('view')->share('subTitle', (string) trans('firefly.recurrences')); + $this->middleware(function ($request, $next) { + app('view')->share('mainTitleIcon', 'fa-paint-brush'); + app('view')->share('title', (string) trans('firefly.recurrences')); + app('view')->share('subTitle', (string) trans('firefly.recurrences')); - $this->repository = app(RecurringRepositoryInterface::class); - $this->budgetRepos = app(BudgetRepositoryInterface::class); - $this->attachments = app(AttachmentHelperInterface::class); - $this->billRepository = app(BillRepositoryInterface::class); + $this->repository = app(RecurringRepositoryInterface::class); + $this->budgetRepos = app(BudgetRepositoryInterface::class); + $this->attachments = app(AttachmentHelperInterface::class); + $this->billRepository = app(BillRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -90,29 +88,29 @@ class EditController extends Controller public function edit(Request $request, Recurrence $recurrence): Factory|\Illuminate\Contracts\View\View { // TODO this should be in the repository. - $count = $recurrence->recurrenceTransactions()->count(); + $count = $recurrence->recurrenceTransactions()->count(); if (0 === $count) { throw new FireflyException('This recurring transaction has no meta-data. You will have to delete it and recreate it. Sorry!'); } // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new RecurringEnrichment(); + $admin = auth()->user(); + $enrichment = new RecurringEnrichment(); $enrichment->setUser($admin); /** @var Recurrence $recurrence */ - $recurrence = $enrichment->enrichSingle($recurrence); + $recurrence = $enrichment->enrichSingle($recurrence); /** @var RecurrenceTransformer $transformer */ - $transformer = app(RecurrenceTransformer::class); - $array = $transformer->transform($recurrence); - $budgets = ExpandedForm::makeSelectListWithEmpty($this->budgetRepos->getActiveBudgets()); - $bills = ExpandedForm::makeSelectListWithEmpty($this->billRepository->getActiveBills()); + $transformer = app(RecurrenceTransformer::class); + $array = $transformer->transform($recurrence); + $budgets = ExpandedForm::makeSelectListWithEmpty($this->budgetRepos->getActiveBudgets()); + $bills = ExpandedForm::makeSelectListWithEmpty($this->billRepository->getActiveBills()); /** @var RecurrenceRepetition $repetition */ - $repetition = $recurrence->recurrenceRepetitions()->first(); - $currentRepType = $repetition->repetition_type; + $repetition = $recurrence->recurrenceRepetitions()->first(); + $currentRepType = $repetition->repetition_type; if ('' !== $repetition->repetition_moment) { $currentRepType = sprintf('%s,%s', $currentRepType, $repetition->repetition_moment); } @@ -123,11 +121,11 @@ class EditController extends Controller } $request->session()->forget('recurrences.edit.fromUpdate'); - $repetitionEnd = 'forever'; - $repetitionEnds = [ + $repetitionEnd = 'forever'; + $repetitionEnds = [ 'forever' => (string) trans('firefly.repeat_forever'), 'until_date' => (string) trans('firefly.repeat_until_date'), - 'times' => (string) trans('firefly.repeat_times'), + 'times' => (string) trans('firefly.repeat_times') ]; if (null !== $recurrence->repeat_until) { $repetitionEnd = 'until_date'; @@ -136,33 +134,43 @@ class EditController extends Controller $repetitionEnd = 'times'; } - $weekendResponses = [ + $weekendResponses = [ RecurrenceRepetitionWeekend::WEEKEND_DO_NOTHING->value => (string) trans('firefly.do_nothing'), RecurrenceRepetitionWeekend::WEEKEND_SKIP_CREATION->value => (string) trans('firefly.skip_transaction'), RecurrenceRepetitionWeekend::WEEKEND_TO_FRIDAY->value => (string) trans('firefly.jump_to_friday'), - RecurrenceRepetitionWeekend::WEEKEND_TO_MONDAY->value => (string) trans('firefly.jump_to_monday'), + RecurrenceRepetitionWeekend::WEEKEND_TO_MONDAY->value => (string) trans('firefly.jump_to_monday') ]; - $hasOldInput = null !== $request->old('_token'); - $preFilled = [ + $hasOldInput = null !== $request->old('_token'); + $preFilled = [ 'transaction_type' => strtolower((string) $recurrence->transactionType->type), 'active' => $hasOldInput ? (bool) $request->old('active') : $recurrence->active, 'apply_rules' => $hasOldInput ? (bool) $request->old('apply_rules') : $recurrence->apply_rules, 'deposit_source_id' => $array['transactions'][0]['source_id'], - 'withdrawal_destination_id' => $array['transactions'][0]['destination_id'], + 'withdrawal_destination_id' => $array['transactions'][0]['destination_id'] ]; - $array['first_date'] = substr((string) $array['first_date'], 0, 10); - $array['repeat_until'] = substr((string) $array['repeat_until'], 0, 10); - $array['transactions'][0]['tags'] = implode(',', $array['transactions'][0]['tags'] ?? []); + $array['first_date'] = substr((string) $array['first_date'], 0, 10); + $array['repeat_until'] = substr((string) $array['repeat_until'], 0, 10); + $array['transactions'][0]['tags'] = implode(',', $array['transactions'][0]['tags'] ?? []); $array['transactions'][0]['amount'] = round((float) $array['transactions'][0]['amount'], $array['transactions'][0]['currency_decimal_places']); if (null !== $array['transactions'][0]['foreign_amount'] && '' !== $array['transactions'][0]['foreign_amount']) { - $array['transactions'][0]['foreign_amount'] = round((float) $array['transactions'][0]['foreign_amount'], $array['transactions'][0]['foreign_currency_decimal_places'] ?? 2); + $array['transactions'][0]['foreign_amount'] = round( + (float) $array['transactions'][0]['foreign_amount'], + $array['transactions'][0]['foreign_currency_decimal_places'] ?? 2 + ); } - return view( - 'recurring.edit', - ['recurrence' => $recurrence, 'array' => $array, 'bills' => $bills, 'weekendResponses' => $weekendResponses, 'budgets' => $budgets, 'preFilled' => $preFilled, 'currentRepType' => $currentRepType, 'repetitionEnd' => $repetitionEnd, 'repetitionEnds' => $repetitionEnds] - ); + return view('recurring.edit', [ + 'recurrence' => $recurrence, + 'array' => $array, + 'bills' => $bills, + 'weekendResponses' => $weekendResponses, + 'budgets' => $budgets, + 'preFilled' => $preFilled, + 'currentRepType' => $currentRepType, + 'repetitionEnd' => $repetitionEnd, + 'repetitionEnds' => $repetitionEnds + ]); } /** @@ -182,7 +190,7 @@ class EditController extends Controller // store new attachment(s): /** @var null|array $files */ - $files = $request->hasFile('attachments') ? $request->file('attachments') : null; + $files = $request->hasFile('attachments') ? $request->file('attachments') : null; if (null !== $files && !auth()->user()->hasRole('demo')) { $this->attachments->saveAttachmentsForModel($recurrence, $files); } @@ -195,7 +203,7 @@ class EditController extends Controller $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); } Preferences::mark(); - $redirect = redirect($this->getPreviousUrl('recurrences.edit.url')); + $redirect = redirect($this->getPreviousUrl('recurrences.edit.url')); if (1 === (int) $request->get('return_to_edit')) { // set value so edit routine will not overwrite URL: $request->session()->put('recurrences.edit.fromUpdate', true); diff --git a/app/Http/Controllers/Recurring/IndexController.php b/app/Http/Controllers/Recurring/IndexController.php index 24cc4556d8..754a13fd28 100644 --- a/app/Http/Controllers/Recurring/IndexController.php +++ b/app/Http/Controllers/Recurring/IndexController.php @@ -23,12 +23,12 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Recurring; -use FireflyIII\Support\Facades\Preferences; use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\Recurrence; use FireflyIII\Repositories\Recurring\RecurringRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use FireflyIII\Support\Http\Controllers\GetConfigurationData; use FireflyIII\Support\JsonApi\Enrichments\RecurringEnrichment; use FireflyIII\Transformers\RecurrenceTransformer; @@ -58,16 +58,14 @@ class IndexController extends Controller parent::__construct(); // translations: - $this->middleware( - function ($request, $next) { - app('view')->share('mainTitleIcon', 'fa-paint-brush'); - app('view')->share('title', (string) trans('firefly.recurrences')); + $this->middleware(function ($request, $next) { + app('view')->share('mainTitleIcon', 'fa-paint-brush'); + app('view')->share('title', (string) trans('firefly.recurrences')); - $this->repository = app(RecurringRepositoryInterface::class); + $this->repository = app(RecurringRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -82,11 +80,11 @@ class IndexController extends Controller */ public function index(Request $request): Factory|\Illuminate\Contracts\View\View { - $page = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page'); - $pageSize = (int) Preferences::get('listPageSize', 50)->data; - $collection = $this->repository->get(); - $today = today(config('app.timezone')); - $year = today(config('app.timezone')); + $page = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page'); + $pageSize = (int) Preferences::get('listPageSize', 50)->data; + $collection = $this->repository->get(); + $today = today(config('app.timezone')); + $year = today(config('app.timezone')); // split collection $total = $collection->count(); @@ -94,8 +92,8 @@ class IndexController extends Controller // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new RecurringEnrichment(); + $admin = auth()->user(); + $enrichment = new RecurringEnrichment(); $enrichment->setUser($admin); $recurrences = $enrichment->enrich($recurrences); @@ -103,7 +101,7 @@ class IndexController extends Controller $transformer = app(RecurrenceTransformer::class); $transformer->setParameters(new ParameterBag()); - $recurring = []; + $recurring = []; /** @var Recurrence $recurrence */ foreach ($recurrences as $recurrence) { @@ -113,12 +111,12 @@ class IndexController extends Controller $year = clone $today; $year->addYear(); } - $array = $transformer->transform($recurrence); - $array['first_date'] = new Carbon($array['first_date']); + $array = $transformer->transform($recurrence); + $array['first_date'] = new Carbon($array['first_date']); $array['repeat_until'] = null === $array['repeat_until'] ? null : new Carbon($array['repeat_until']); - $array['latest_date'] = null === $array['latest_date'] ? null : new Carbon($array['latest_date']); + $array['latest_date'] = null === $array['latest_date'] ? null : new Carbon($array['latest_date']); // lazy but OK - $array['attachments'] = $recurrence->attachments()->count(); + $array['attachments'] = $recurrence->attachments()->count(); // make carbon objects out of occurrences foreach ($array['repetitions'] as $repIndex => $repetition) { @@ -127,14 +125,20 @@ class IndexController extends Controller } } - $recurring[] = $array; + $recurring[] = $array; } - $paginator = new LengthAwarePaginator($recurring, $total, $pageSize, $page); + $paginator = new LengthAwarePaginator($recurring, $total, $pageSize, $page); $paginator->setPath(route('recurring.index')); - $today = today(config('app.timezone')); + $today = today(config('app.timezone')); $this->verifyRecurringCronJob(); - return view('recurring.index', ['paginator' => $paginator, 'today' => $today, 'page' => $page, 'pageSize' => $pageSize, 'total' => $total]); + return view('recurring.index', [ + 'paginator' => $paginator, + 'today' => $today, + 'page' => $page, + 'pageSize' => $pageSize, + 'total' => $total + ]); } } diff --git a/app/Http/Controllers/Recurring/ShowController.php b/app/Http/Controllers/Recurring/ShowController.php index 83dc4e2bf7..9ef2f28011 100644 --- a/app/Http/Controllers/Recurring/ShowController.php +++ b/app/Http/Controllers/Recurring/ShowController.php @@ -58,16 +58,14 @@ class ShowController extends Controller app('view')->share('showCategory', true); // translations: - $this->middleware( - function ($request, $next) { - app('view')->share('mainTitleIcon', 'fa-paint-brush'); - app('view')->share('title', (string) trans('firefly.recurrences')); + $this->middleware(function ($request, $next) { + app('view')->share('mainTitleIcon', 'fa-paint-brush'); + app('view')->share('title', (string) trans('firefly.recurrences')); - $this->repository = app(RecurringRepositoryInterface::class); + $this->repository = app(RecurringRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -79,50 +77,49 @@ class ShowController extends Controller */ public function show(Recurrence $recurrence): Factory|\Illuminate\Contracts\View\View { - $repos = app(AttachmentRepositoryInterface::class); + $repos = app(AttachmentRepositoryInterface::class); // enrich /** @var User $admin */ - $admin = auth()->user(); - $enrichment = new RecurringEnrichment(); + $admin = auth()->user(); + $enrichment = new RecurringEnrichment(); $enrichment->setUser($admin); /** @var Recurrence $recurrence */ - $recurrence = $enrichment->enrichSingle($recurrence); + $recurrence = $enrichment->enrichSingle($recurrence); /** @var RecurrenceTransformer $transformer */ - $transformer = app(RecurrenceTransformer::class); + $transformer = app(RecurrenceTransformer::class); $transformer->setParameters(new ParameterBag()); - $array = $transformer->transform($recurrence); + $array = $transformer->transform($recurrence); - $groups = $this->repository->getTransactions($recurrence); - $today = today(config('app.timezone')); - $array['repeat_until'] = null !== $array['repeat_until'] ? new Carbon($array['repeat_until']) : null; + $groups = $this->repository->getTransactions($recurrence); + $today = today(config('app.timezone')); + $array['repeat_until'] = null !== $array['repeat_until'] ? new Carbon($array['repeat_until']) : null; $array['journal_count'] = $this->repository->getJournalCount($recurrence); // transform dates back to Carbon objects and expand information foreach ($array['repetitions'] as $index => $repetition) { foreach ($repetition['occurrences'] as $item => $occurrence) { - $date = new Carbon($occurrence)->startOfDay(); - $set = [ + $date = new Carbon($occurrence)->startOfDay(); + $set = [ 'date' => $date, - 'fired' => $this->repository->createdPreviously($recurrence, $date) - || $this->repository->getJournalCount($recurrence, $date) > 0, + 'fired' => $this->repository->createdPreviously($recurrence, $date) || $this->repository->getJournalCount($recurrence, $date) > 0 ]; $array['repetitions'][$index]['occurrences'][$item] = $set; } } // add attachments to the recurrence object. - $attachments = $recurrence->attachments()->get(); - $array['attachments'] = []; - $attachmentTransformer = app(AttachmentTransformer::class); + $attachments = $recurrence->attachments()->get(); + $array['attachments'] = []; + $attachmentTransformer = app(AttachmentTransformer::class); /** @var Attachment $attachment */ foreach ($attachments as $attachment) { - $item = $attachmentTransformer->transform($attachment); - $item['file_exists'] = $repos->exists($attachment); // TODO this should be part of the transformer + $item = $attachmentTransformer->transform($attachment); + $item['file_exists'] = $repos->exists($attachment); // TODO this should be part of the transformer $array['attachments'][] = $item; } @@ -135,8 +132,14 @@ class ShowController extends Controller } } - $subTitle = (string) trans('firefly.overview_for_recurrence', ['title' => $recurrence->title]); + $subTitle = (string) trans('firefly.overview_for_recurrence', ['title' => $recurrence->title]); - return view('recurring.show', ['recurrence' => $recurrence, 'subTitle' => $subTitle, 'array' => $array, 'groups' => $groups, 'today' => $today]); + return view('recurring.show', [ + 'recurrence' => $recurrence, + 'subTitle' => $subTitle, + 'array' => $array, + 'groups' => $groups, + 'today' => $today + ]); } } diff --git a/app/Http/Controllers/Recurring/TriggerController.php b/app/Http/Controllers/Recurring/TriggerController.php index a709f038a0..e9e305e344 100644 --- a/app/Http/Controllers/Recurring/TriggerController.php +++ b/app/Http/Controllers/Recurring/TriggerController.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Recurring; -use Illuminate\Support\Facades\Log; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Requests\TriggerRecurrenceRequest; use FireflyIII\Jobs\CreateRecurringTransactions; @@ -33,6 +32,7 @@ use FireflyIII\Repositories\Recurring\RecurringRepositoryInterface; use FireflyIII\Support\Facades\Preferences; use Illuminate\Http\RedirectResponse; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Log; /** * Class TriggerController @@ -50,40 +50,38 @@ class TriggerController extends Controller app('view')->share('showCategory', true); // translations: - $this->middleware( - function ($request, $next) { - app('view')->share('mainTitleIcon', 'fa-paint-brush'); - app('view')->share('title', (string) trans('firefly.recurrences')); + $this->middleware(function ($request, $next) { + app('view')->share('mainTitleIcon', 'fa-paint-brush'); + app('view')->share('title', (string) trans('firefly.recurrences')); - $this->repository = app(RecurringRepositoryInterface::class); + $this->repository = app(RecurringRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } public function trigger(Recurrence $recurrence, TriggerRecurrenceRequest $request): RedirectResponse { - $all = $request->getAll(); - $date = $all['date']; + $all = $request->getAll(); + $date = $all['date']; // grab the date from the last time the recurrence fired: - $backupDate = $recurrence->latest_date; + $backupDate = $recurrence->latest_date; // fire the recurring cron job on the given date, then post-date the created transaction. Log::info(sprintf('Trigger: will now fire recurring cron job task for date "%s".', $date->format('Y-m-d H:i:s'))); /** @var CreateRecurringTransactions $job */ - $job = app(CreateRecurringTransactions::class); + $job = app(CreateRecurringTransactions::class); $job->setRecurrences(new Collection()->push($recurrence)); $job->setDate($date); $job->setForce(false); $job->handle(); Log::debug('Done with recurrence.'); - $groups = $job->getGroups(); + $groups = $job->getGroups(); $this->repository->markGroupsAsNow($groups); - $recurrence->latest_date = $backupDate; + $recurrence->latest_date = $backupDate; $recurrence->latest_date_tz = $backupDate?->format('e'); $recurrence->save(); Preferences::mark(); diff --git a/app/Http/Controllers/Report/AccountController.php b/app/Http/Controllers/Report/AccountController.php index b68d894a67..a76016825b 100644 --- a/app/Http/Controllers/Report/AccountController.php +++ b/app/Http/Controllers/Report/AccountController.php @@ -23,13 +23,13 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Report; -use Illuminate\Support\Facades\Log; use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Repositories\Account\AccountTaskerInterface; use FireflyIII\Support\CacheProperties; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Log; use Throwable; /** @@ -45,7 +45,7 @@ class AccountController extends Controller public function general(Collection $accounts, Carbon $start, Carbon $end): string { // chart properties for cache: - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty('account-report'); diff --git a/app/Http/Controllers/Report/BalanceController.php b/app/Http/Controllers/Report/BalanceController.php index def545cbdd..82cab48db8 100644 --- a/app/Http/Controllers/Report/BalanceController.php +++ b/app/Http/Controllers/Report/BalanceController.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Report; -use Illuminate\Support\Facades\Log; use Carbon\Carbon; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Exceptions\FireflyException; @@ -33,6 +32,7 @@ use FireflyIII\Models\Account; use FireflyIII\Models\Budget; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Log; use Throwable; /** @@ -50,13 +50,11 @@ class BalanceController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(BudgetRepositoryInterface::class); + $this->middleware(function ($request, $next) { + $this->repository = app(BudgetRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -68,54 +66,49 @@ class BalanceController extends Controller */ public function general(Collection $accounts, Carbon $start, Carbon $end) { - $report = [ - 'budgets' => [], - 'accounts' => [], - ]; + $report = ['budgets' => [], 'accounts' => []]; /** @var Account $account */ foreach ($accounts as $account) { - $report['accounts'][$account->id] = [ - 'id' => $account->id, - 'name' => $account->name, - 'iban' => $account->iban, - 'sum' => '0', - ]; + $report['accounts'][$account->id] = ['id' => $account->id, 'name' => $account->name, 'iban' => $account->iban, 'sum' => '0']; } $budgets = $this->repository->getBudgets(); /** @var Budget $budget */ foreach ($budgets as $budget) { - $budgetId = $budget->id; - $report['budgets'][$budgetId] = [ + $budgetId = $budget->id; + $report['budgets'][$budgetId] = [ 'budget_id' => $budgetId, 'budget_name' => $budget->name, 'spent' => [], // per account - 'sums' => [], // per currency + 'sums' => [] // per currency ]; - $spent = []; + $spent = []; /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); - $journals = $collector->setRange($start, $end)->setSourceAccounts($accounts)->setTypes([TransactionTypeEnum::WITHDRAWAL->value])->setBudget($budget) - ->getExtractedJournals() - ; + $collector = app(GroupCollectorInterface::class); + $journals = $collector + ->setRange($start, $end) + ->setSourceAccounts($accounts) + ->setTypes([TransactionTypeEnum::WITHDRAWAL->value]) + ->setBudget($budget) + ->getExtractedJournals(); /** @var array $journal */ foreach ($journals as $journal) { - $sourceAccount = $journal['source_account_id']; - $currencyId = $journal['currency_id']; - $spent[$sourceAccount] ??= [ + $sourceAccount = $journal['source_account_id']; + $currencyId = $journal['currency_id']; + $spent[$sourceAccount] ??= [ 'source_account_id' => $sourceAccount, 'currency_id' => $journal['currency_id'], 'currency_code' => $journal['currency_code'], 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_decimal_places' => $journal['currency_decimal_places'], - 'spent' => '0', + 'spent' => '0' ]; - $spent[$sourceAccount]['spent'] = bcadd($spent[$sourceAccount]['spent'], (string) $journal['amount']); + $spent[$sourceAccount]['spent'] = bcadd($spent[$sourceAccount]['spent'], (string) $journal['amount']); // also fix sum: $report['sums'][$budgetId][$currencyId] ??= [ @@ -124,19 +117,20 @@ class BalanceController extends Controller 'currency_code' => $journal['currency_code'], 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], - 'currency_decimal_places' => $journal['currency_decimal_places'], + 'currency_decimal_places' => $journal['currency_decimal_places'] ]; - $report['sums'][$budgetId][$currencyId]['sum'] = bcadd($report['sums'][$budgetId][$currencyId]['sum'], (string) $journal['amount']); - $report['accounts'][$sourceAccount]['sum'] = bcadd($report['accounts'][$sourceAccount]['sum'], (string) $journal['amount']); + $report['sums'][$budgetId][$currencyId]['sum'] = bcadd($report['sums'][$budgetId][$currencyId]['sum'], (string) $journal['amount']); + $report['accounts'][$sourceAccount]['sum'] = bcadd($report['accounts'][$sourceAccount]['sum'], (string) $journal['amount']); // add currency info for account sum - $report['accounts'][$sourceAccount]['currency_id'] = $journal['currency_id']; - $report['accounts'][$sourceAccount]['currency_code'] = $journal['currency_code']; - $report['accounts'][$sourceAccount]['currency_name'] = $journal['currency_name']; - $report['accounts'][$sourceAccount]['currency_symbol'] = $journal['currency_symbol']; + $report['accounts'][$sourceAccount]['currency_id'] = $journal['currency_id']; + $report['accounts'][$sourceAccount]['currency_code'] = $journal['currency_code']; + $report['accounts'][$sourceAccount]['currency_name'] = $journal['currency_name']; + $report['accounts'][$sourceAccount]['currency_symbol'] = $journal['currency_symbol']; $report['accounts'][$sourceAccount]['currency_decimal_places'] = $journal['currency_decimal_places']; } $report['budgets'][$budgetId]['spent'] = $spent; + // get transactions in budget } diff --git a/app/Http/Controllers/Report/BillController.php b/app/Http/Controllers/Report/BillController.php index 069aebbeac..b4911f7fc0 100644 --- a/app/Http/Controllers/Report/BillController.php +++ b/app/Http/Controllers/Report/BillController.php @@ -24,13 +24,13 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Report; -use Illuminate\Support\Facades\Log; use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Helpers\Report\ReportHelperInterface; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Support\CacheProperties; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Log; use Throwable; /** @@ -43,9 +43,9 @@ class BillController extends Controller * * @throws FireflyException */ - public function overview(Collection $accounts, Carbon $start, Carbon $end) // chart properties for cache: - { - $cache = new CacheProperties(); + public function overview(Collection $accounts, Carbon $start, Carbon $end) + { // chart properties for cache: + $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty('bill-report'); diff --git a/app/Http/Controllers/Report/BudgetController.php b/app/Http/Controllers/Report/BudgetController.php index 7525b4f0bc..ca7c63219e 100644 --- a/app/Http/Controllers/Report/BudgetController.php +++ b/app/Http/Controllers/Report/BudgetController.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Report; -use Illuminate\Support\Facades\Log; use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; @@ -36,6 +35,7 @@ use FireflyIII\Support\Http\Controllers\BasicDataSupport; use FireflyIII\Support\Report\Budget\BudgetReportGenerator; use Illuminate\Contracts\View\Factory; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Log; use Illuminate\View\View; use Throwable; @@ -54,13 +54,11 @@ class BudgetController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->opsRepository = app(OperationsRepositoryInterface::class); + $this->middleware(function ($request, $next) { + $this->opsRepository = app(OperationsRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -82,9 +80,9 @@ class BudgetController extends Controller $generator->setEnd($end); $generator->accountPerBudget(); - $report = $generator->getReport(); + $report = $generator->getReport(); - return view('reports.budget.partials.account-per-budget', ['report' => $report, 'budgets' => $budgets]); + return view('reports.budget.partials.account-per-budget', ['report' => $report, 'budgets' => $budgets]); } /** @@ -99,12 +97,7 @@ class BudgetController extends Controller /** @var Account $account */ foreach ($accounts as $account) { $accountId = $account->id; - $report[$accountId] ??= [ - 'name' => $account->name, - 'id' => $account->id, - 'iban' => $account->iban, - 'currencies' => [], - ]; + $report[$accountId] ??= ['name' => $account->name, 'id' => $account->id, 'iban' => $account->iban, 'currencies' => []]; } // loop expenses. @@ -115,28 +108,28 @@ class BudgetController extends Controller 'currency_symbol' => $currency['currency_symbol'], 'currency_name' => $currency['currency_name'], 'currency_decimal_places' => $currency['currency_decimal_places'], - 'sum' => '0', + 'sum' => '0' ]; foreach ($currency['budgets'] as $budget) { foreach ($budget['transaction_journals'] as $journal) { - $sourceAccountId = $journal['source_account_id']; + $sourceAccountId = $journal['source_account_id']; $report[$sourceAccountId]['currencies'][$currencyId] ??= [ 'currency_id' => $currency['currency_id'], 'currency_symbol' => $currency['currency_symbol'], 'currency_name' => $currency['currency_name'], 'currency_decimal_places' => $currency['currency_decimal_places'], - 'sum' => '0', + 'sum' => '0' ]; $report[$sourceAccountId]['currencies'][$currencyId]['sum'] = bcadd( $report[$sourceAccountId]['currencies'][$currencyId]['sum'], (string) $journal['amount'] ); - $sums[$currencyId]['sum'] = bcadd($sums[$currencyId]['sum'], (string) $journal['amount']); + $sums[$currencyId]['sum'] = bcadd($sums[$currencyId]['sum'], (string) $journal['amount']); } } } - return view('reports.budget.partials.accounts', ['sums' => $sums, 'report' => $report]); + return view('reports.budget.partials.accounts', ['sums' => $sums, 'report' => $report]); } /** @@ -146,13 +139,13 @@ class BudgetController extends Controller */ public function avgExpenses(Collection $accounts, Collection $budgets, Carbon $start, Carbon $end) { - $spent = $this->opsRepository->listExpenses($start, $end, $accounts, $budgets); - $result = []; + $spent = $this->opsRepository->listExpenses($start, $end, $accounts, $budgets); + $result = []; foreach ($spent as $currency) { foreach ($currency['budgets'] as $budget) { foreach ($budget['transaction_journals'] as $journal) { - $destinationId = $journal['destination_account_id']; - $key = sprintf('%d-%d', $destinationId, $currency['currency_id']); + $destinationId = $journal['destination_account_id']; + $key = sprintf('%d-%d', $destinationId, $currency['currency_id']); $result[$key] ??= [ 'transactions' => 0, 'sum' => '0', @@ -163,11 +156,11 @@ class BudgetController extends Controller 'currency_id' => $currency['currency_id'], 'currency_name' => $currency['currency_name'], 'currency_symbol' => $currency['currency_symbol'], - 'currency_decimal_places' => $currency['currency_decimal_places'], + 'currency_decimal_places' => $currency['currency_decimal_places'] ]; ++$result[$key]['transactions']; - $result[$key]['sum'] = bcadd((string) $journal['amount'], $result[$key]['sum']); - $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); + $result[$key]['sum'] = bcadd((string) $journal['amount'], $result[$key]['sum']); + $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); $result[$key]['avg_float'] = (float) $result[$key]['avg']; // intentional float } } @@ -202,11 +195,7 @@ class BudgetController extends Controller /** @var Budget $budget */ foreach ($budgets as $budget) { $budgetId = $budget->id; - $report[$budgetId] ??= [ - 'name' => $budget->name, - 'id' => $budget->id, - 'currencies' => [], - ]; + $report[$budgetId] ??= ['name' => $budget->name, 'id' => $budget->id, 'currencies' => []]; } foreach ($spent as $currency) { $currencyId = $currency['currency_id']; @@ -215,7 +204,7 @@ class BudgetController extends Controller 'currency_symbol' => $currency['currency_symbol'], 'currency_name' => $currency['currency_name'], 'currency_decimal_places' => $currency['currency_decimal_places'], - 'sum' => '0', + 'sum' => '0' ]; /** @var array $budget */ @@ -230,10 +219,13 @@ class BudgetController extends Controller 'currency_id' => $currency['currency_id'], 'currency_symbol' => $currency['currency_symbol'], 'currency_name' => $currency['currency_name'], - 'currency_decimal_places' => $currency['currency_decimal_places'], + 'currency_decimal_places' => $currency['currency_decimal_places'] ]; - $report[$budgetId]['currencies'][$currencyId]['sum'] = bcadd($report[$budgetId]['currencies'][$currencyId]['sum'], (string) $journal['amount']); - $sums[$currencyId]['sum'] = bcadd($sums[$currencyId]['sum'], (string) $journal['amount']); + $report[$budgetId]['currencies'][$currencyId]['sum'] = bcadd( + $report[$budgetId]['currencies'][$currencyId]['sum'], + (string) $journal['amount'] + ); + $sums[$currencyId]['sum'] = bcadd($sums[$currencyId]['sum'], (string) $journal['amount']); } } } @@ -241,9 +233,9 @@ class BudgetController extends Controller // loop again to get percentages. foreach ($report as $budgetId => $data) { foreach ($data['currencies'] as $currencyId => $dataX) { - $sum = $dataX['sum']; - $total = $sums[$currencyId]['sum'] ?? '0'; - $pct = '0'; + $sum = $dataX['sum']; + $total = $sums[$currencyId]['sum'] ?? '0'; + $pct = '0'; if (0 !== bccomp($sum, '0') && 0 !== bccomp($total, '9')) { $pct = round((float) bcmul(bcdiv($sum, $total), '100')); // intentional float } @@ -251,7 +243,7 @@ class BudgetController extends Controller } } - return view('reports.budget.partials.budgets', ['sums' => $sums, 'report' => $report]); + return view('reports.budget.partials.budgets', ['sums' => $sums, 'report' => $report]); } /** @@ -272,7 +264,7 @@ class BudgetController extends Controller $generator->setEnd($end); $generator->general(); - $report = $generator->getReport(); + $report = $generator->getReport(); return view('reports.partials.budgets', ['report' => $report])->render(); } @@ -286,7 +278,7 @@ class BudgetController extends Controller */ public function period(Collection $accounts, Carbon $start, Carbon $end) { - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty('budget-period-report'); @@ -299,9 +291,9 @@ class BudgetController extends Controller $keyFormat = Navigation::preferredCarbonFormat($start, $end); // list expenses for budgets in account(s) - $expenses = $this->opsRepository->listExpenses($start, $end, $accounts); + $expenses = $this->opsRepository->listExpenses($start, $end, $accounts); - $report = []; + $report = []; foreach ($expenses as $currency) { foreach ($currency['budgets'] as $budget) { $count = 0; @@ -315,12 +307,10 @@ class BudgetController extends Controller continue; } - - ++$count; - $key = sprintf('%d-%d', $budget['id'], $currency['currency_id']); - $dateKey = $journal['date']->format($keyFormat); - $report[$key] ??= [ + $key = sprintf('%d-%d', $budget['id'], $currency['currency_id']); + $dateKey = $journal['date']->format($keyFormat); + $report[$key] ??= [ 'id' => $budget['id'], 'name' => sprintf('%s (%s)', $budget['name'], $currency['currency_name']), 'sum' => '0', @@ -329,18 +319,18 @@ class BudgetController extends Controller 'currency_symbol' => $currency['currency_symbol'], 'currency_code' => $currency['currency_code'], 'currency_decimal_places' => $currency['currency_decimal_places'], - 'entries' => [], + 'entries' => [] ]; $report[$key]['entries'][$dateKey] ??= '0'; $report[$key]['entries'][$dateKey] = bcadd((string) $journal['amount'], $report[$key]['entries'][$dateKey]); - $report[$key]['sum'] = bcadd($report[$key]['sum'], (string) $journal['amount']); - $report[$key]['avg'] = bcdiv($report[$key]['sum'], (string) count($periods)); + $report[$key]['sum'] = bcadd($report[$key]['sum'], (string) $journal['amount']); + $report[$key]['avg'] = bcdiv($report[$key]['sum'], (string) count($periods)); } } } try { - $result = view('reports.partials.budget-period', ['report' => $report, 'periods' => $periods])->render(); + $result = view('reports.partials.budget-period', ['report' => $report, 'periods' => $periods])->render(); } catch (Throwable $e) { Log::error(sprintf('Could not render reports.partials.budget-period: %s', $e->getMessage())); Log::error($e->getTraceAsString()); @@ -361,15 +351,15 @@ class BudgetController extends Controller */ public function topExpenses(Collection $accounts, Collection $budgets, Carbon $start, Carbon $end) { - $spent = $this->opsRepository->listExpenses($start, $end, $accounts, $budgets); - $result = []; + $spent = $this->opsRepository->listExpenses($start, $end, $accounts, $budgets); + $result = []; foreach ($spent as $currency) { foreach ($currency['budgets'] as $budget) { foreach ($budget['transaction_journals'] as $journal) { $result[] = [ - 'description' => $journal['description'], - 'transaction_group_id' => $journal['transaction_group_id'], - 'amount_float' => (float) $journal['amount'], // intentional float + 'description' => $journal['description'], + 'transaction_group_id' => $journal['transaction_group_id'], + 'amount_float' => (float) $journal['amount'], // intentional float 'amount' => $journal['amount'], 'date' => $journal['date']->isoFormat($this->monthAndDayFormat), 'date_sort' => $journal['date']->format('Y-m-d'), @@ -380,7 +370,7 @@ class BudgetController extends Controller 'currency_symbol' => $currency['currency_symbol'], 'currency_decimal_places' => $currency['currency_decimal_places'], 'budget_id' => $budget['id'], - 'budget_name' => $budget['name'], + 'budget_name' => $budget['name'] ]; } } diff --git a/app/Http/Controllers/Report/CategoryController.php b/app/Http/Controllers/Report/CategoryController.php index 1d3a9058a3..fd85b063f9 100644 --- a/app/Http/Controllers/Report/CategoryController.php +++ b/app/Http/Controllers/Report/CategoryController.php @@ -23,8 +23,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Report; -use FireflyIII\Support\Facades\Navigation; -use Illuminate\Support\Facades\Log; use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; @@ -33,10 +31,12 @@ use FireflyIII\Models\Category; use FireflyIII\Repositories\Category\NoCategoryRepositoryInterface; use FireflyIII\Repositories\Category\OperationsRepositoryInterface; use FireflyIII\Support\CacheProperties; +use FireflyIII\Support\Facades\Navigation; use FireflyIII\Support\Http\Controllers\BasicDataSupport; use FireflyIII\Support\Report\Category\CategoryReportGenerator; use Illuminate\Contracts\View\Factory; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Log; use Illuminate\View\View; use Throwable; @@ -56,14 +56,12 @@ class CategoryController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->opsRepository = app(OperationsRepositoryInterface::class); - $this->noCatRepository = app(NoCategoryRepositoryInterface::class); + $this->middleware(function ($request, $next) { + $this->opsRepository = app(OperationsRepositoryInterface::class); + $this->noCatRepository = app(NoCategoryRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -78,12 +76,7 @@ class CategoryController extends Controller /** @var Account $account */ foreach ($accounts as $account) { $accountId = $account->id; - $report[$accountId] ??= [ - 'name' => $account->name, - 'id' => $account->id, - 'iban' => $account->iban, - 'currencies' => [], - ]; + $report[$accountId] ??= ['name' => $account->name, 'id' => $account->id, 'iban' => $account->iban, 'currencies' => []]; } // loop expenses. @@ -93,26 +86,21 @@ class CategoryController extends Controller /** @var array $category */ foreach ($currency['categories'] as $category) { foreach ($category['transaction_journals'] as $journal) { - $sourceAccountId = $journal['source_account_id']; - $report[$sourceAccountId]['currencies'][$currencyId] ??= [ + $sourceAccountId = $journal['source_account_id']; + $report[$sourceAccountId]['currencies'][$currencyId] ??= [ 'currency_id' => $currency['currency_id'], 'currency_symbol' => $currency['currency_symbol'], 'currency_name' => $currency['currency_name'], 'currency_decimal_places' => $currency['currency_decimal_places'], - 'categories' => [], + 'categories' => [] ]; - $report[$sourceAccountId]['currencies'][$currencyId]['categories'][$category['id']] - ??= [ - 'spent' => '0', - 'earned' => '0', - 'sum' => '0', - ]; + $report[$sourceAccountId]['currencies'][$currencyId]['categories'][$category['id']] ??= ['spent' => '0', 'earned' => '0', 'sum' => '0']; $report[$sourceAccountId]['currencies'][$currencyId]['categories'][$category['id']]['spent'] = bcadd( $report[$sourceAccountId]['currencies'][$currencyId]['categories'][$category['id']]['spent'], (string) $journal['amount'] ); - $report[$sourceAccountId]['currencies'][$currencyId]['categories'][$category['id']]['sum'] = bcadd( + $report[$sourceAccountId]['currencies'][$currencyId]['categories'][$category['id']]['sum'] = bcadd( $report[$sourceAccountId]['currencies'][$currencyId]['categories'][$category['id']]['sum'], (string) $journal['amount'] ); @@ -126,26 +114,20 @@ class CategoryController extends Controller /** @var array $category */ foreach ($currency['categories'] as $category) { foreach ($category['transaction_journals'] as $journal) { - $destinationId = $journal['destination_account_id']; - $report[$destinationId]['currencies'][$currencyId] - ??= [ - 'currency_id' => $currency['currency_id'], - 'currency_symbol' => $currency['currency_symbol'], - 'currency_name' => $currency['currency_name'], - 'currency_decimal_places' => $currency['currency_decimal_places'], - 'categories' => [], - ]; - $report[$destinationId]['currencies'][$currencyId]['categories'][$category['id']] - ??= [ - 'spent' => '0', - 'earned' => '0', - 'sum' => '0', - ]; + $destinationId = $journal['destination_account_id']; + $report[$destinationId]['currencies'][$currencyId] ??= [ + 'currency_id' => $currency['currency_id'], + 'currency_symbol' => $currency['currency_symbol'], + 'currency_name' => $currency['currency_name'], + 'currency_decimal_places' => $currency['currency_decimal_places'], + 'categories' => [] + ]; + $report[$destinationId]['currencies'][$currencyId]['categories'][$category['id']] ??= ['spent' => '0', 'earned' => '0', 'sum' => '0']; $report[$destinationId]['currencies'][$currencyId]['categories'][$category['id']]['earned'] = bcadd( $report[$destinationId]['currencies'][$currencyId]['categories'][$category['id']]['earned'], (string) $journal['amount'] ); - $report[$destinationId]['currencies'][$currencyId]['categories'][$category['id']]['sum'] = bcadd( + $report[$destinationId]['currencies'][$currencyId]['categories'][$category['id']]['sum'] = bcadd( $report[$destinationId]['currencies'][$currencyId]['categories'][$category['id']]['sum'], (string) $journal['amount'] ); @@ -153,7 +135,7 @@ class CategoryController extends Controller } } - return view('reports.category.partials.account-per-category', ['report' => $report, 'categories' => $categories]); + return view('reports.category.partials.account-per-category', ['report' => $report, 'categories' => $categories]); } /** @@ -171,12 +153,7 @@ class CategoryController extends Controller /** @var Account $account */ foreach ($accounts as $account) { $accountId = $account->id; - $report[$accountId] ??= [ - 'name' => $account->name, - 'id' => $account->id, - 'iban' => $account->iban, - 'currencies' => [], - ]; + $report[$accountId] ??= ['name' => $account->name, 'id' => $account->id, 'iban' => $account->iban, 'currencies' => []]; } // loop expenses. @@ -189,11 +166,11 @@ class CategoryController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'spent_sum' => '0', 'earned_sum' => '0', - 'total_sum' => '0', + 'total_sum' => '0' ]; foreach ($currency['categories'] as $category) { foreach ($category['transaction_journals'] as $journal) { - $sourceAccountId = $journal['source_account_id']; + $sourceAccountId = $journal['source_account_id']; $report[$sourceAccountId]['currencies'][$currencyId] ??= [ 'currency_id' => $currency['currency_id'], 'currency_symbol' => $currency['currency_symbol'], @@ -201,18 +178,18 @@ class CategoryController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'spent' => '0', 'earned' => '0', - 'sum' => '0', + 'sum' => '0' ]; $report[$sourceAccountId]['currencies'][$currencyId]['spent'] = bcadd( $report[$sourceAccountId]['currencies'][$currencyId]['spent'], (string) $journal['amount'] ); - $report[$sourceAccountId]['currencies'][$currencyId]['sum'] = bcadd( + $report[$sourceAccountId]['currencies'][$currencyId]['sum'] = bcadd( $report[$sourceAccountId]['currencies'][$currencyId]['sum'], (string) $journal['amount'] ); - $sums[$currencyId]['spent_sum'] = bcadd($sums[$currencyId]['spent_sum'], (string) $journal['amount']); - $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); + $sums[$currencyId]['spent_sum'] = bcadd($sums[$currencyId]['spent_sum'], (string) $journal['amount']); + $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); } } } @@ -227,11 +204,11 @@ class CategoryController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'spent_sum' => '0', 'earned_sum' => '0', - 'total_sum' => '0', + 'total_sum' => '0' ]; foreach ($currency['categories'] as $category) { foreach ($category['transaction_journals'] as $journal) { - $destinationAccountId = $journal['destination_account_id']; + $destinationAccountId = $journal['destination_account_id']; $report[$destinationAccountId]['currencies'][$currencyId] ??= [ 'currency_id' => $currency['currency_id'], 'currency_symbol' => $currency['currency_symbol'], @@ -239,23 +216,23 @@ class CategoryController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'spent' => '0', 'earned' => '0', - 'sum' => '0', + 'sum' => '0' ]; $report[$destinationAccountId]['currencies'][$currencyId]['earned'] = bcadd( $report[$destinationAccountId]['currencies'][$currencyId]['earned'], (string) $journal['amount'] ); - $report[$destinationAccountId]['currencies'][$currencyId]['sum'] = bcadd( + $report[$destinationAccountId]['currencies'][$currencyId]['sum'] = bcadd( $report[$destinationAccountId]['currencies'][$currencyId]['sum'], (string) $journal['amount'] ); - $sums[$currencyId]['earned_sum'] = bcadd($sums[$currencyId]['earned_sum'], (string) $journal['amount']); - $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); + $sums[$currencyId]['earned_sum'] = bcadd($sums[$currencyId]['earned_sum'], (string) $journal['amount']); + $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); } } } - return view('reports.category.partials.accounts', ['sums' => $sums, 'report' => $report]); + return view('reports.category.partials.accounts', ['sums' => $sums, 'report' => $report]); } /** @@ -265,13 +242,13 @@ class CategoryController extends Controller */ public function avgExpenses(Collection $accounts, Collection $categories, Carbon $start, Carbon $end) { - $spent = $this->opsRepository->listExpenses($start, $end, $accounts, $categories); - $result = []; + $spent = $this->opsRepository->listExpenses($start, $end, $accounts, $categories); + $result = []; foreach ($spent as $currency) { foreach ($currency['categories'] as $category) { foreach ($category['transaction_journals'] as $journal) { - $destinationId = $journal['destination_account_id']; - $key = sprintf('%d-%d', $destinationId, $currency['currency_id']); + $destinationId = $journal['destination_account_id']; + $key = sprintf('%d-%d', $destinationId, $currency['currency_id']); $result[$key] ??= [ 'transactions' => 0, 'sum' => '0', @@ -282,11 +259,11 @@ class CategoryController extends Controller 'currency_id' => $currency['currency_id'], 'currency_name' => $currency['currency_name'], 'currency_symbol' => $currency['currency_symbol'], - 'currency_decimal_places' => $currency['currency_decimal_places'], + 'currency_decimal_places' => $currency['currency_decimal_places'] ]; ++$result[$key]['transactions']; - $result[$key]['sum'] = bcadd((string) $journal['amount'], $result[$key]['sum']); - $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); + $result[$key]['sum'] = bcadd((string) $journal['amount'], $result[$key]['sum']); + $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); $result[$key]['avg_float'] = (float) $result[$key]['avg']; // intentional float } } @@ -315,13 +292,13 @@ class CategoryController extends Controller */ public function avgIncome(Collection $accounts, Collection $categories, Carbon $start, Carbon $end) { - $spent = $this->opsRepository->listIncome($start, $end, $accounts, $categories); - $result = []; + $spent = $this->opsRepository->listIncome($start, $end, $accounts, $categories); + $result = []; foreach ($spent as $currency) { foreach ($currency['categories'] as $category) { foreach ($category['transaction_journals'] as $journal) { - $sourceId = $journal['source_account_id']; - $key = sprintf('%d-%d', $sourceId, $currency['currency_id']); + $sourceId = $journal['source_account_id']; + $key = sprintf('%d-%d', $sourceId, $currency['currency_id']); $result[$key] ??= [ 'transactions' => 0, 'sum' => '0', @@ -332,11 +309,11 @@ class CategoryController extends Controller 'currency_id' => $currency['currency_id'], 'currency_name' => $currency['currency_name'], 'currency_symbol' => $currency['currency_symbol'], - 'currency_decimal_places' => $currency['currency_decimal_places'], + 'currency_decimal_places' => $currency['currency_decimal_places'] ]; ++$result[$key]['transactions']; - $result[$key]['sum'] = bcadd((string) $journal['amount'], $result[$key]['sum']); - $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); + $result[$key]['sum'] = bcadd((string) $journal['amount'], $result[$key]['sum']); + $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); $result[$key]['avg_float'] = (float) $result[$key]['avg']; } } @@ -373,11 +350,7 @@ class CategoryController extends Controller /** @var Category $category */ foreach ($categories as $category) { $categoryId = $category->id; - $report[$categoryId] ??= [ - 'name' => $category->name, - 'id' => $category->id, - 'currencies' => [], - ]; + $report[$categoryId] ??= ['name' => $category->name, 'id' => $category->id, 'currencies' => []]; } foreach ($spent as $currency) { $currencyId = $currency['currency_id']; @@ -388,7 +361,7 @@ class CategoryController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'earned_sum' => '0', 'spent_sum' => '0', - 'total_sum' => '0', + 'total_sum' => '0' ]; /** @var array $category */ @@ -404,19 +377,19 @@ class CategoryController extends Controller 'currency_id' => $currency['currency_id'], 'currency_symbol' => $currency['currency_symbol'], 'currency_name' => $currency['currency_name'], - 'currency_decimal_places' => $currency['currency_decimal_places'], + 'currency_decimal_places' => $currency['currency_decimal_places'] ]; $report[$categoryId]['currencies'][$currencyId]['spent'] = bcadd( $report[$categoryId]['currencies'][$currencyId]['spent'], (string) $journal['amount'] ); - $report[$categoryId]['currencies'][$currencyId]['sum'] = bcadd( + $report[$categoryId]['currencies'][$currencyId]['sum'] = bcadd( $report[$categoryId]['currencies'][$currencyId]['sum'], (string) $journal['amount'] ); - $sums[$currencyId]['spent_sum'] = bcadd($sums[$currencyId]['spent_sum'], (string) $journal['amount']); - $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); + $sums[$currencyId]['spent_sum'] = bcadd($sums[$currencyId]['spent_sum'], (string) $journal['amount']); + $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); } } } @@ -430,7 +403,7 @@ class CategoryController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'earned_sum' => '0', 'spent_sum' => '0', - 'total_sum' => '0', + 'total_sum' => '0' ]; /** @var array $category */ @@ -446,24 +419,24 @@ class CategoryController extends Controller 'currency_id' => $currency['currency_id'], 'currency_symbol' => $currency['currency_symbol'], 'currency_name' => $currency['currency_name'], - 'currency_decimal_places' => $currency['currency_decimal_places'], + 'currency_decimal_places' => $currency['currency_decimal_places'] ]; $report[$categoryId]['currencies'][$currencyId]['earned'] = bcadd( $report[$categoryId]['currencies'][$currencyId]['earned'], (string) $journal['amount'] ); - $report[$categoryId]['currencies'][$currencyId]['sum'] = bcadd( + $report[$categoryId]['currencies'][$currencyId]['sum'] = bcadd( $report[$categoryId]['currencies'][$currencyId]['sum'], (string) $journal['amount'] ); - $sums[$currencyId]['earned_sum'] = bcadd($sums[$currencyId]['earned_sum'], (string) $journal['amount']); - $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); + $sums[$currencyId]['earned_sum'] = bcadd($sums[$currencyId]['earned_sum'], (string) $journal['amount']); + $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); } } } - return view('reports.category.partials.categories', ['sums' => $sums, 'report' => $report]); + return view('reports.category.partials.categories', ['sums' => $sums, 'report' => $report]); } /** @@ -475,7 +448,7 @@ class CategoryController extends Controller */ public function expenses(Collection $accounts, Carbon $start, Carbon $end) { - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty('category-period-expenses-report'); @@ -486,7 +459,7 @@ class CategoryController extends Controller // depending on the carbon format (a reliable way to determine the general date difference) // change the "listOfPeriods" call so the entire period gets included correctly. - $format = Navigation::preferredCarbonFormat($start, $end); + $format = Navigation::preferredCarbonFormat($start, $end); if ('Y' === $format) { $start->startOfYear(); @@ -512,13 +485,13 @@ class CategoryController extends Controller 'currency_code' => $currencyRow['currency_code'], 'currency_decimal_places' => $currencyRow['currency_decimal_places'], 'sum' => '0', - 'entries' => [], + 'entries' => [] ]; foreach ($categoryRow['transaction_journals'] as $journal) { - $date = $journal['date']->format($format); + $date = $journal['date']->format($format); $data[$key]['entries'][$date] ??= '0'; $data[$key]['entries'][$date] = bcadd($data[$key]['entries'][$date], (string) $journal['amount']); - $data[$key]['sum'] = bcadd($data[$key]['sum'], (string) $journal['amount']); + $data[$key]['sum'] = bcadd($data[$key]['sum'], (string) $journal['amount']); } } } @@ -526,10 +499,10 @@ class CategoryController extends Controller $cache->store($data); - $report = $data; + $report = $data; try { - $result = view('reports.partials.category-period', ['report' => $report, 'periods' => $periods])->render(); + $result = view('reports.partials.category-period', ['report' => $report, 'periods' => $periods])->render(); } catch (Throwable $e) { Log::error(sprintf('Could not render category::expenses: %s', $e->getMessage())); $result = sprintf('An error prevented Firefly III from rendering: %s. Apologies.', $e->getMessage()); @@ -549,7 +522,7 @@ class CategoryController extends Controller */ public function income(Collection $accounts, Carbon $start, Carbon $end): string { - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty('category-period-income-report'); @@ -560,7 +533,7 @@ class CategoryController extends Controller // depending on the carbon format (a reliable way to determine the general date difference) // change the "listOfPeriods" call so the entire period gets included correctly. - $format = Navigation::preferredCarbonFormat($start, $end); + $format = Navigation::preferredCarbonFormat($start, $end); if ('Y' === $format) { $start->startOfYear(); @@ -586,22 +559,22 @@ class CategoryController extends Controller 'currency_code' => $currencyRow['currency_code'], 'currency_decimal_places' => $currencyRow['currency_decimal_places'], 'sum' => '0', - 'entries' => [], + 'entries' => [] ]; foreach ($categoryRow['transaction_journals'] as $journal) { - $date = $journal['date']->format($format); + $date = $journal['date']->format($format); $data[$key]['entries'][$date] ??= '0'; $data[$key]['entries'][$date] = bcadd($data[$key]['entries'][$date], (string) $journal['amount']); - $data[$key]['sum'] = bcadd($data[$key]['sum'], (string) $journal['amount']); + $data[$key]['sum'] = bcadd($data[$key]['sum'], (string) $journal['amount']); } } } } - $report = $data; + $report = $data; try { - $result = view('reports.partials.category-period', ['report' => $report, 'periods' => $periods])->render(); + $result = view('reports.partials.category-period', ['report' => $report, 'periods' => $periods])->render(); } catch (Throwable $e) { Log::error(sprintf('Could not render category::expenses: %s', $e->getMessage())); $result = sprintf('An error prevented Firefly III from rendering: %s. Apologies.', $e->getMessage()); @@ -622,7 +595,7 @@ class CategoryController extends Controller public function operations(Collection $accounts, Carbon $start, Carbon $end): string { // chart properties for cache: - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty('category-report'); @@ -637,7 +610,7 @@ class CategoryController extends Controller $generator->setStart($start); $generator->setEnd($end); $generator->operations(); - $report = $generator->getReport(); + $report = $generator->getReport(); try { $result = view('reports.partials.categories', ['report' => $report])->render(); @@ -659,8 +632,8 @@ class CategoryController extends Controller */ public function topExpenses(Collection $accounts, Collection $categories, Carbon $start, Carbon $end) { - $spent = $this->opsRepository->listExpenses($start, $end, $accounts, $categories); - $result = []; + $spent = $this->opsRepository->listExpenses($start, $end, $accounts, $categories); + $result = []; foreach ($spent as $currency) { foreach ($currency['categories'] as $category) { foreach ($category['transaction_journals'] as $journal) { @@ -678,7 +651,7 @@ class CategoryController extends Controller 'currency_symbol' => $currency['currency_symbol'], 'currency_decimal_places' => $currency['currency_decimal_places'], 'category_id' => $category['id'], - 'category_name' => $category['name'], + 'category_name' => $category['name'] ]; } } @@ -707,8 +680,8 @@ class CategoryController extends Controller */ public function topIncome(Collection $accounts, Collection $categories, Carbon $start, Carbon $end) { - $spent = $this->opsRepository->listIncome($start, $end, $accounts, $categories); - $result = []; + $spent = $this->opsRepository->listIncome($start, $end, $accounts, $categories); + $result = []; foreach ($spent as $currency) { foreach ($currency['categories'] as $category) { foreach ($category['transaction_journals'] as $journal) { @@ -726,7 +699,7 @@ class CategoryController extends Controller 'currency_symbol' => $currency['currency_symbol'], 'currency_decimal_places' => $currency['currency_decimal_places'], 'category_id' => $category['id'], - 'category_name' => $category['name'], + 'category_name' => $category['name'] ]; } } diff --git a/app/Http/Controllers/Report/DoubleController.php b/app/Http/Controllers/Report/DoubleController.php index e2593d31b9..2ed0dab55b 100644 --- a/app/Http/Controllers/Report/DoubleController.php +++ b/app/Http/Controllers/Report/DoubleController.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Report; -use Illuminate\Support\Facades\Log; use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; @@ -33,6 +32,7 @@ use FireflyIII\Repositories\Account\OperationsRepositoryInterface; use FireflyIII\Support\Http\Controllers\AugumentData; use Illuminate\Contracts\View\Factory; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Log; use Illuminate\View\View; use Throwable; @@ -43,7 +43,7 @@ class DoubleController extends Controller { use AugumentData; - protected AccountRepositoryInterface $accountRepository; + protected AccountRepositoryInterface $accountRepository; private OperationsRepositoryInterface $opsRepository; /** @@ -54,14 +54,12 @@ class DoubleController extends Controller parent::__construct(); // translations: - $this->middleware( - function ($request, $next) { - $this->accountRepository = app(AccountRepositoryInterface::class); - $this->opsRepository = app(OperationsRepositoryInterface::class); + $this->middleware(function ($request, $next) { + $this->accountRepository = app(AccountRepositoryInterface::class); + $this->opsRepository = app(OperationsRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -77,8 +75,8 @@ class DoubleController extends Controller $result = []; foreach ($spent as $currency) { foreach ($currency['transaction_journals'] as $journal) { - $sourceId = $journal['source_account_id']; - $key = sprintf('%d-%d', $sourceId, $currency['currency_id']); + $sourceId = $journal['source_account_id']; + $key = sprintf('%d-%d', $sourceId, $currency['currency_id']); $result[$key] ??= [ 'transactions' => 0, 'sum' => '0', @@ -89,17 +87,17 @@ class DoubleController extends Controller 'currency_id' => $currency['currency_id'], 'currency_name' => $currency['currency_name'], 'currency_symbol' => $currency['currency_symbol'], - 'currency_decimal_places' => $currency['currency_decimal_places'], + 'currency_decimal_places' => $currency['currency_decimal_places'] ]; ++$result[$key]['transactions']; - $result[$key]['sum'] = bcadd((string) $journal['amount'], $result[$key]['sum']); - $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); + $result[$key]['sum'] = bcadd((string) $journal['amount'], $result[$key]['sum']); + $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); $result[$key]['avg_float'] = (float) $result[$key]['avg']; } } // sort by amount_float // sort temp array by amount. - $amounts = array_column($result, 'avg_float'); + $amounts = array_column($result, 'avg_float'); array_multisort($amounts, SORT_ASC, $result); try { @@ -127,8 +125,8 @@ class DoubleController extends Controller $result = []; foreach ($spent as $currency) { foreach ($currency['transaction_journals'] as $journal) { - $destinationId = $journal['destination_account_id']; - $key = sprintf('%d-%d', $destinationId, $currency['currency_id']); + $destinationId = $journal['destination_account_id']; + $key = sprintf('%d-%d', $destinationId, $currency['currency_id']); $result[$key] ??= [ 'transactions' => 0, 'sum' => '0', @@ -139,17 +137,17 @@ class DoubleController extends Controller 'currency_id' => $currency['currency_id'], 'currency_name' => $currency['currency_name'], 'currency_symbol' => $currency['currency_symbol'], - 'currency_decimal_places' => $currency['currency_decimal_places'], + 'currency_decimal_places' => $currency['currency_decimal_places'] ]; ++$result[$key]['transactions']; - $result[$key]['sum'] = bcadd((string) $journal['amount'], $result[$key]['sum']); - $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); + $result[$key]['sum'] = bcadd((string) $journal['amount'], $result[$key]['sum']); + $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); $result[$key]['avg_float'] = (float) $result[$key]['avg']; } } // sort by amount_float // sort temp array by amount. - $amounts = array_column($result, 'avg_float'); + $amounts = array_column($result, 'avg_float'); array_multisort($amounts, SORT_DESC, $result); try { @@ -176,8 +174,8 @@ class DoubleController extends Controller $report = []; $sums = []; // see what happens when we collect transactions. - $spent = $this->opsRepository->listExpenses($start, $end, $together); - $earned = $this->opsRepository->listIncome($start, $end, $together); + $spent = $this->opsRepository->listExpenses($start, $end, $together); + $earned = $this->opsRepository->listIncome($start, $end, $together); // group and list per account name (as long as its not in accounts, only in double) /** @var array $currency */ @@ -192,16 +190,16 @@ class DoubleController extends Controller 'currency_name' => $currency['currency_name'], 'currency_symbol' => $currency['currency_symbol'], 'currency_code' => $currency['currency_code'], - 'currency_decimal_places' => $currency['currency_decimal_places'], + 'currency_decimal_places' => $currency['currency_decimal_places'] ]; /** @var array $journal */ foreach ($currency['transaction_journals'] as $journal) { - $destId = $journal['destination_account_id']; - $destName = $journal['destination_account_name']; - $destIban = $journal['destination_account_iban']; - $genericName = $this->getCounterpartName($withCounterpart, $destId, $destName, $destIban); - $objectName = sprintf('%s (%s)', $genericName, $currency['currency_name']); + $destId = $journal['destination_account_id']; + $destName = $journal['destination_account_name']; + $destIban = $journal['destination_account_iban']; + $genericName = $this->getCounterpartName($withCounterpart, $destId, $destName, $destIban); + $objectName = sprintf('%s (%s)', $genericName, $currency['currency_name']); $report[$objectName] ??= [ 'dest_name' => '', 'dest_iban' => '', @@ -214,17 +212,17 @@ class DoubleController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'spent' => '0', 'earned' => '0', - 'sum' => '0', + 'sum' => '0' ]; // set name $report[$objectName]['dest_name'] = $destName; $report[$objectName]['dest_iban'] = $destIban; // add amounts: - $report[$objectName]['spent'] = bcadd($report[$objectName]['spent'], (string) $journal['amount']); - $report[$objectName]['sum'] = bcadd($report[$objectName]['sum'], (string) $journal['amount']); - $sums[$currencyId]['spent'] = bcadd($sums[$currencyId]['spent'], (string) $journal['amount']); - $sums[$currencyId]['sum'] = bcadd($sums[$currencyId]['sum'], (string) $journal['amount']); + $report[$objectName]['spent'] = bcadd($report[$objectName]['spent'], (string) $journal['amount']); + $report[$objectName]['sum'] = bcadd($report[$objectName]['sum'], (string) $journal['amount']); + $sums[$currencyId]['spent'] = bcadd($sums[$currencyId]['spent'], (string) $journal['amount']); + $sums[$currencyId]['sum'] = bcadd($sums[$currencyId]['sum'], (string) $journal['amount']); } } @@ -240,16 +238,16 @@ class DoubleController extends Controller 'currency_name' => $currency['currency_name'], 'currency_symbol' => $currency['currency_symbol'], 'currency_code' => $currency['currency_code'], - 'currency_decimal_places' => $currency['currency_decimal_places'], + 'currency_decimal_places' => $currency['currency_decimal_places'] ]; /** @var array $journal */ foreach ($currency['transaction_journals'] as $journal) { - $sourceId = $journal['source_account_id']; - $sourceName = $journal['source_account_name']; - $sourceIban = $journal['source_account_iban']; - $genericName = $this->getCounterpartName($withCounterpart, $sourceId, $sourceName, $sourceIban); - $objectName = sprintf('%s (%s)', $genericName, $currency['currency_name']); + $sourceId = $journal['source_account_id']; + $sourceName = $journal['source_account_name']; + $sourceIban = $journal['source_account_iban']; + $genericName = $this->getCounterpartName($withCounterpart, $sourceId, $sourceName, $sourceIban); + $objectName = sprintf('%s (%s)', $genericName, $currency['currency_name']); $report[$objectName] ??= [ 'dest_name' => '', 'dest_iban' => '', @@ -262,7 +260,7 @@ class DoubleController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'spent' => '0', 'earned' => '0', - 'sum' => '0', + 'sum' => '0' ]; // set name @@ -270,20 +268,20 @@ class DoubleController extends Controller $report[$objectName]['source_iban'] = $sourceIban; // add amounts: - $report[$objectName]['earned'] = bcadd($report[$objectName]['earned'], (string) $journal['amount']); - $report[$objectName]['sum'] = bcadd($report[$objectName]['sum'], (string) $journal['amount']); - $sums[$currencyId]['earned'] = bcadd($sums[$currencyId]['earned'], (string) $journal['amount']); - $sums[$currencyId]['sum'] = bcadd($sums[$currencyId]['sum'], (string) $journal['amount']); + $report[$objectName]['earned'] = bcadd($report[$objectName]['earned'], (string) $journal['amount']); + $report[$objectName]['sum'] = bcadd($report[$objectName]['sum'], (string) $journal['amount']); + $sums[$currencyId]['earned'] = bcadd($sums[$currencyId]['earned'], (string) $journal['amount']); + $sums[$currencyId]['sum'] = bcadd($sums[$currencyId]['sum'], (string) $journal['amount']); } } - return view('reports.double.partials.accounts', ['sums' => $sums, 'report' => $report]); + return view('reports.double.partials.accounts', ['sums' => $sums, 'report' => $report]); } /** * TODO this method is duplicated. */ - private function getCounterpartName(Collection $accounts, int $id, string $name, ?string $iban): string + private function getCounterpartName(Collection $accounts, int $id, string $name, null|string $iban): string { /** @var Account $account */ foreach ($accounts as $account) { @@ -308,8 +306,8 @@ class DoubleController extends Controller $report = []; $sums = []; // see what happens when we collect transactions. - $spent = $this->opsRepository->listExpenses($start, $end, $together); - $earned = $this->opsRepository->listIncome($start, $end, $together); + $spent = $this->opsRepository->listExpenses($start, $end, $together); + $earned = $this->opsRepository->listIncome($start, $end, $together); // group and list per account name (as long as its not in accounts, only in double) /** @var array $currency */ @@ -324,12 +322,12 @@ class DoubleController extends Controller 'currency_name' => $currency['currency_name'], 'currency_symbol' => $currency['currency_symbol'], 'currency_code' => $currency['currency_code'], - 'currency_decimal_places' => $currency['currency_decimal_places'], + 'currency_decimal_places' => $currency['currency_decimal_places'] ]; /** @var array $journal */ foreach ($currency['transaction_journals'] as $journal) { - $objectName = sprintf('%s (%s)', $journal['source_account_name'], $currency['currency_name']); + $objectName = sprintf('%s (%s)', $journal['source_account_name'], $currency['currency_name']); $report[$objectName] ??= [ 'account_id' => $journal['source_account_id'], 'account_name' => $objectName, @@ -340,14 +338,14 @@ class DoubleController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'spent' => '0', 'earned' => '0', - 'sum' => '0', + 'sum' => '0' ]; // set name // add amounts: $report[$objectName]['spent'] = bcadd($report[$objectName]['spent'], (string) $journal['amount']); - $report[$objectName]['sum'] = bcadd($report[$objectName]['sum'], (string) $journal['amount']); - $sums[$currencyId]['spent'] = bcadd($sums[$currencyId]['spent'], (string) $journal['amount']); - $sums[$currencyId]['sum'] = bcadd($sums[$currencyId]['sum'], (string) $journal['amount']); + $report[$objectName]['sum'] = bcadd($report[$objectName]['sum'], (string) $journal['amount']); + $sums[$currencyId]['spent'] = bcadd($sums[$currencyId]['spent'], (string) $journal['amount']); + $sums[$currencyId]['sum'] = bcadd($sums[$currencyId]['sum'], (string) $journal['amount']); } } @@ -363,12 +361,12 @@ class DoubleController extends Controller 'currency_name' => $currency['currency_name'], 'currency_symbol' => $currency['currency_symbol'], 'currency_code' => $currency['currency_code'], - 'currency_decimal_places' => $currency['currency_decimal_places'], + 'currency_decimal_places' => $currency['currency_decimal_places'] ]; /** @var array $journal */ foreach ($currency['transaction_journals'] as $journal) { - $objectName = sprintf('%s (%s)', $journal['destination_account_name'], $currency['currency_name']); + $objectName = sprintf('%s (%s)', $journal['destination_account_name'], $currency['currency_name']); $report[$objectName] ??= [ 'account_id' => $journal['destination_account_id'], 'account_name' => $objectName, @@ -379,18 +377,18 @@ class DoubleController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'spent' => '0', 'earned' => '0', - 'sum' => '0', + 'sum' => '0' ]; // add amounts: $report[$objectName]['earned'] = bcadd($report[$objectName]['earned'], (string) $journal['amount']); - $report[$objectName]['sum'] = bcadd($report[$objectName]['sum'], (string) $journal['amount']); - $sums[$currencyId]['earned'] = bcadd($sums[$currencyId]['earned'], (string) $journal['amount']); - $sums[$currencyId]['sum'] = bcadd($sums[$currencyId]['sum'], (string) $journal['amount']); + $report[$objectName]['sum'] = bcadd($report[$objectName]['sum'], (string) $journal['amount']); + $sums[$currencyId]['earned'] = bcadd($sums[$currencyId]['earned'], (string) $journal['amount']); + $sums[$currencyId]['sum'] = bcadd($sums[$currencyId]['sum'], (string) $journal['amount']); } } - return view('reports.double.partials.accounts-per-asset', ['sums' => $sums, 'report' => $report]); + return view('reports.double.partials.accounts-per-asset', ['sums' => $sums, 'report' => $report]); } /** @@ -420,13 +418,13 @@ class DoubleController extends Controller 'currency_symbol' => $currency['currency_symbol'], 'currency_decimal_places' => $currency['currency_decimal_places'], 'source_account_name' => $journal['source_account_name'], - 'source_account_id' => $journal['source_account_id'], + 'source_account_id' => $journal['source_account_id'] ]; } } // sort by amount_float // sort temp array by amount. - $amounts = array_column($result, 'amount_float'); + $amounts = array_column($result, 'amount_float'); array_multisort($amounts, SORT_ASC, $result); try { @@ -468,13 +466,13 @@ class DoubleController extends Controller 'currency_symbol' => $currency['currency_symbol'], 'currency_decimal_places' => $currency['currency_decimal_places'], 'source_account_name' => $journal['source_account_name'], - 'source_account_id' => $journal['source_account_id'], + 'source_account_id' => $journal['source_account_id'] ]; } } // sort by amount_float // sort temp array by amount. - $amounts = array_column($result, 'amount_float'); + $amounts = array_column($result, 'amount_float'); array_multisort($amounts, SORT_DESC, $result); try { diff --git a/app/Http/Controllers/Report/OperationsController.php b/app/Http/Controllers/Report/OperationsController.php index e8a19a4357..1006868835 100644 --- a/app/Http/Controllers/Report/OperationsController.php +++ b/app/Http/Controllers/Report/OperationsController.php @@ -23,13 +23,13 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Report; -use Illuminate\Support\Facades\Log; use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Repositories\Account\AccountTaskerInterface; use FireflyIII\Support\CacheProperties; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Log; use Throwable; /** @@ -48,13 +48,11 @@ class OperationsController extends Controller parent::__construct(); // translations: - $this->middleware( - function ($request, $next) { - $this->tasker = app(AccountTaskerInterface::class); + $this->middleware(function ($request, $next) { + $this->tasker = app(AccountTaskerInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -67,7 +65,7 @@ class OperationsController extends Controller public function expenses(Collection $accounts, Carbon $start, Carbon $end) { // chart properties for cache: - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty('expense-report'); @@ -79,7 +77,7 @@ class OperationsController extends Controller $type = 'expense-entry'; try { - $result = view('reports.partials.income-expenses', ['report' => $report, 'type' => $type])->render(); + $result = view('reports.partials.income-expenses', ['report' => $report, 'type' => $type])->render(); } catch (Throwable $e) { Log::error(sprintf('Could not render reports.partials.income-expense: %s', $e->getMessage())); Log::error($e->getTraceAsString()); @@ -101,7 +99,7 @@ class OperationsController extends Controller public function income(Collection $accounts, Carbon $start, Carbon $end): string { // chart properties for cache: - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty('income-report'); @@ -113,7 +111,7 @@ class OperationsController extends Controller $type = 'income-entry'; try { - $result = view('reports.partials.income-expenses', ['report' => $report, 'type' => $type])->render(); + $result = view('reports.partials.income-expenses', ['report' => $report, 'type' => $type])->render(); } catch (Throwable $e) { Log::error(sprintf('Could not render reports.partials.income-expenses: %s', $e->getMessage())); Log::error($e->getTraceAsString()); @@ -137,7 +135,7 @@ class OperationsController extends Controller public function operations(Collection $accounts, Carbon $start, Carbon $end) { // chart properties for cache: - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); $cache->addProperty('inc-exp-report'); @@ -153,7 +151,7 @@ class OperationsController extends Controller /** @var int $currencyId */ foreach ($keys as $currencyId) { - $currencyInfo = $incomes['sums'][$currencyId] ?? $expenses['sums'][$currencyId]; + $currencyInfo = $incomes['sums'][$currencyId] ?? $expenses['sums'][$currencyId]; $sums[$currencyId] ??= [ 'currency_id' => $currencyId, 'currency_name' => $currencyInfo['currency_name'], @@ -162,7 +160,7 @@ class OperationsController extends Controller 'currency_decimal_places' => $currencyInfo['currency_decimal_places'], 'in' => $incomes['sums'][$currencyId]['sum'] ?? '0', 'out' => $expenses['sums'][$currencyId]['sum'] ?? '0', - 'sum' => '0', + 'sum' => '0' ]; $sums[$currencyId]['sum'] = bcadd($sums[$currencyId]['in'], $sums[$currencyId]['out']); } diff --git a/app/Http/Controllers/Report/TagController.php b/app/Http/Controllers/Report/TagController.php index ef3f60cdcb..cbf3e04f4d 100644 --- a/app/Http/Controllers/Report/TagController.php +++ b/app/Http/Controllers/Report/TagController.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Report; -use Illuminate\Support\Facades\Log; use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; @@ -33,6 +32,7 @@ use FireflyIII\Models\Tag; use FireflyIII\Repositories\Tag\OperationsRepositoryInterface; use Illuminate\Contracts\View\Factory; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Log; use Illuminate\View\View; use Throwable; @@ -49,13 +49,11 @@ class TagController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->opsRepository = app(OperationsRepositoryInterface::class); + $this->middleware(function ($request, $next) { + $this->opsRepository = app(OperationsRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -72,12 +70,7 @@ class TagController extends Controller /** @var Account $account */ foreach ($accounts as $account) { $accountId = $account->id; - $report[$accountId] ??= [ - 'name' => $account->name, - 'id' => $account->id, - 'iban' => $account->iban, - 'currencies' => [], - ]; + $report[$accountId] ??= ['name' => $account->name, 'id' => $account->id, 'iban' => $account->iban, 'currencies' => []]; } // loop expenses. @@ -88,26 +81,21 @@ class TagController extends Controller foreach ($currency['tags'] as $tag) { $tagId = $tag['id']; foreach ($tag['transaction_journals'] as $journal) { - $sourceAccountId = $journal['source_account_id']; - $report[$sourceAccountId]['currencies'][$currencyId] ??= [ + $sourceAccountId = $journal['source_account_id']; + $report[$sourceAccountId]['currencies'][$currencyId] ??= [ 'currency_id' => $currency['currency_id'], 'currency_symbol' => $currency['currency_symbol'], 'currency_name' => $currency['currency_name'], 'currency_decimal_places' => $currency['currency_decimal_places'], - 'tags' => [], + 'tags' => [] ]; - $report[$sourceAccountId]['currencies'][$currencyId]['tags'][$tagId] - ??= [ - 'spent' => '0', - 'earned' => '0', - 'sum' => '0', - ]; + $report[$sourceAccountId]['currencies'][$currencyId]['tags'][$tagId] ??= ['spent' => '0', 'earned' => '0', 'sum' => '0']; $report[$sourceAccountId]['currencies'][$currencyId]['tags'][$tagId]['spent'] = bcadd( $report[$sourceAccountId]['currencies'][$currencyId]['tags'][$tagId]['spent'], (string) $journal['amount'] ); - $report[$sourceAccountId]['currencies'][$currencyId]['tags'][$tagId]['sum'] = bcadd( + $report[$sourceAccountId]['currencies'][$currencyId]['tags'][$tagId]['sum'] = bcadd( $report[$sourceAccountId]['currencies'][$currencyId]['tags'][$tagId]['sum'], (string) $journal['amount'] ); @@ -122,26 +110,20 @@ class TagController extends Controller foreach ($currency['tags'] as $tag) { $tagId = $tag['id']; foreach ($tag['transaction_journals'] as $journal) { - $destinationId = $journal['destination_account_id']; - $report[$destinationId]['currencies'][$currencyId] - ??= [ - 'currency_id' => $currency['currency_id'], - 'currency_symbol' => $currency['currency_symbol'], - 'currency_name' => $currency['currency_name'], - 'currency_decimal_places' => $currency['currency_decimal_places'], - 'tags' => [], - ]; - $report[$destinationId]['currencies'][$currencyId]['tags'][$tagId] - ??= [ - 'spent' => '0', - 'earned' => '0', - 'sum' => '0', - ]; + $destinationId = $journal['destination_account_id']; + $report[$destinationId]['currencies'][$currencyId] ??= [ + 'currency_id' => $currency['currency_id'], + 'currency_symbol' => $currency['currency_symbol'], + 'currency_name' => $currency['currency_name'], + 'currency_decimal_places' => $currency['currency_decimal_places'], + 'tags' => [] + ]; + $report[$destinationId]['currencies'][$currencyId]['tags'][$tagId] ??= ['spent' => '0', 'earned' => '0', 'sum' => '0']; $report[$destinationId]['currencies'][$currencyId]['tags'][$tagId]['earned'] = bcadd( $report[$destinationId]['currencies'][$currencyId]['tags'][$tagId]['earned'], (string) $journal['amount'] ); - $report[$destinationId]['currencies'][$currencyId]['tags'][$tagId]['sum'] = bcadd( + $report[$destinationId]['currencies'][$currencyId]['tags'][$tagId]['sum'] = bcadd( $report[$destinationId]['currencies'][$currencyId]['tags'][$tagId]['sum'], (string) $journal['amount'] ); @@ -149,7 +131,7 @@ class TagController extends Controller } } - return view('reports.tag.partials.account-per-tag', ['report' => $report, 'tags' => $tags]); + return view('reports.tag.partials.account-per-tag', ['report' => $report, 'tags' => $tags]); } /** @@ -167,12 +149,7 @@ class TagController extends Controller /** @var Account $account */ foreach ($accounts as $account) { $accountId = $account->id; - $report[$accountId] ??= [ - 'name' => $account->name, - 'id' => $account->id, - 'iban' => $account->iban, - 'currencies' => [], - ]; + $report[$accountId] ??= ['name' => $account->name, 'id' => $account->id, 'iban' => $account->iban, 'currencies' => []]; } // loop expenses. @@ -185,11 +162,11 @@ class TagController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'spent_sum' => '0', 'earned_sum' => '0', - 'total_sum' => '0', + 'total_sum' => '0' ]; foreach ($currency['tags'] as $tag) { foreach ($tag['transaction_journals'] as $journal) { - $sourceAccountId = $journal['source_account_id']; + $sourceAccountId = $journal['source_account_id']; $report[$sourceAccountId]['currencies'][$currencyId] ??= [ 'currency_id' => $currency['currency_id'], 'currency_symbol' => $currency['currency_symbol'], @@ -197,18 +174,18 @@ class TagController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'spent' => '0', 'earned' => '0', - 'sum' => '0', + 'sum' => '0' ]; $report[$sourceAccountId]['currencies'][$currencyId]['spent'] = bcadd( $report[$sourceAccountId]['currencies'][$currencyId]['spent'], (string) $journal['amount'] ); - $report[$sourceAccountId]['currencies'][$currencyId]['sum'] = bcadd( + $report[$sourceAccountId]['currencies'][$currencyId]['sum'] = bcadd( $report[$sourceAccountId]['currencies'][$currencyId]['sum'], (string) $journal['amount'] ); - $sums[$currencyId]['spent_sum'] = bcadd($sums[$currencyId]['spent_sum'], (string) $journal['amount']); - $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); + $sums[$currencyId]['spent_sum'] = bcadd($sums[$currencyId]['spent_sum'], (string) $journal['amount']); + $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); } } } @@ -223,11 +200,11 @@ class TagController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'spent_sum' => '0', 'earned_sum' => '0', - 'total_sum' => '0', + 'total_sum' => '0' ]; foreach ($currency['tags'] as $tag) { foreach ($tag['transaction_journals'] as $journal) { - $destinationAccountId = $journal['destination_account_id']; + $destinationAccountId = $journal['destination_account_id']; $report[$destinationAccountId]['currencies'][$currencyId] ??= [ 'currency_id' => $currency['currency_id'], 'currency_symbol' => $currency['currency_symbol'], @@ -235,23 +212,23 @@ class TagController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'spent' => '0', 'earned' => '0', - 'sum' => '0', + 'sum' => '0' ]; $report[$destinationAccountId]['currencies'][$currencyId]['earned'] = bcadd( $report[$destinationAccountId]['currencies'][$currencyId]['earned'], (string) $journal['amount'] ); - $report[$destinationAccountId]['currencies'][$currencyId]['sum'] = bcadd( + $report[$destinationAccountId]['currencies'][$currencyId]['sum'] = bcadd( $report[$destinationAccountId]['currencies'][$currencyId]['sum'], (string) $journal['amount'] ); - $sums[$currencyId]['earned_sum'] = bcadd($sums[$currencyId]['earned_sum'], (string) $journal['amount']); - $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); + $sums[$currencyId]['earned_sum'] = bcadd($sums[$currencyId]['earned_sum'], (string) $journal['amount']); + $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); } } } - return view('reports.tag.partials.accounts', ['sums' => $sums, 'report' => $report]); + return view('reports.tag.partials.accounts', ['sums' => $sums, 'report' => $report]); } /** @@ -261,13 +238,13 @@ class TagController extends Controller */ public function avgExpenses(Collection $accounts, Collection $tags, Carbon $start, Carbon $end) { - $spent = $this->opsRepository->listExpenses($start, $end, $accounts, $tags); - $result = []; + $spent = $this->opsRepository->listExpenses($start, $end, $accounts, $tags); + $result = []; foreach ($spent as $currency) { foreach ($currency['tags'] as $tag) { foreach ($tag['transaction_journals'] as $journal) { - $destinationId = $journal['destination_account_id']; - $key = sprintf('%d-%d', $destinationId, $currency['currency_id']); + $destinationId = $journal['destination_account_id']; + $key = sprintf('%d-%d', $destinationId, $currency['currency_id']); $result[$key] ??= [ 'transactions' => 0, 'sum' => '0', @@ -278,11 +255,11 @@ class TagController extends Controller 'currency_id' => $currency['currency_id'], 'currency_name' => $currency['currency_name'], 'currency_symbol' => $currency['currency_symbol'], - 'currency_decimal_places' => $currency['currency_decimal_places'], + 'currency_decimal_places' => $currency['currency_decimal_places'] ]; ++$result[$key]['transactions']; - $result[$key]['sum'] = bcadd((string) $journal['amount'], $result[$key]['sum']); - $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); + $result[$key]['sum'] = bcadd((string) $journal['amount'], $result[$key]['sum']); + $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); $result[$key]['avg_float'] = (float) $result[$key]['avg']; } } @@ -311,13 +288,13 @@ class TagController extends Controller */ public function avgIncome(Collection $accounts, Collection $tags, Carbon $start, Carbon $end) { - $spent = $this->opsRepository->listIncome($start, $end, $accounts, $tags); - $result = []; + $spent = $this->opsRepository->listIncome($start, $end, $accounts, $tags); + $result = []; foreach ($spent as $currency) { foreach ($currency['tags'] as $tag) { foreach ($tag['transaction_journals'] as $journal) { - $sourceId = $journal['source_account_id']; - $key = sprintf('%d-%d', $sourceId, $currency['currency_id']); + $sourceId = $journal['source_account_id']; + $key = sprintf('%d-%d', $sourceId, $currency['currency_id']); $result[$key] ??= [ 'transactions' => 0, 'sum' => '0', @@ -328,11 +305,11 @@ class TagController extends Controller 'currency_id' => $currency['currency_id'], 'currency_name' => $currency['currency_name'], 'currency_symbol' => $currency['currency_symbol'], - 'currency_decimal_places' => $currency['currency_decimal_places'], + 'currency_decimal_places' => $currency['currency_decimal_places'] ]; ++$result[$key]['transactions']; - $result[$key]['sum'] = bcadd((string) $journal['amount'], $result[$key]['sum']); - $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); + $result[$key]['sum'] = bcadd((string) $journal['amount'], $result[$key]['sum']); + $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); $result[$key]['avg_float'] = (float) $result[$key]['avg']; } } @@ -369,11 +346,7 @@ class TagController extends Controller /** @var Tag $tag */ foreach ($tags as $tag) { $tagId = $tag->id; - $report[$tagId] ??= [ - 'name' => $tag->tag, - 'id' => $tag->id, - 'currencies' => [], - ]; + $report[$tagId] ??= ['name' => $tag->tag, 'id' => $tag->id, 'currencies' => []]; } foreach ($spent as $currency) { $currencyId = $currency['currency_id']; @@ -384,7 +357,7 @@ class TagController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'earned_sum' => '0', 'spent_sum' => '0', - 'total_sum' => '0', + 'total_sum' => '0' ]; /** @var array $tag */ @@ -403,12 +376,18 @@ class TagController extends Controller 'currency_id' => $currency['currency_id'], 'currency_symbol' => $currency['currency_symbol'], 'currency_name' => $currency['currency_name'], - 'currency_decimal_places' => $currency['currency_decimal_places'], + 'currency_decimal_places' => $currency['currency_decimal_places'] ]; - $report[$tagId]['currencies'][$currencyId]['spent'] = bcadd((string) $report[$tagId]['currencies'][$currencyId]['spent'], (string) $journal['amount']); - $report[$tagId]['currencies'][$currencyId]['sum'] = bcadd((string) $report[$tagId]['currencies'][$currencyId]['sum'], (string) $journal['amount']); - $sums[$currencyId]['spent_sum'] = bcadd($sums[$currencyId]['spent_sum'], (string) $journal['amount']); - $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); + $report[$tagId]['currencies'][$currencyId]['spent'] = bcadd( + (string) $report[$tagId]['currencies'][$currencyId]['spent'], + (string) $journal['amount'] + ); + $report[$tagId]['currencies'][$currencyId]['sum'] = bcadd( + (string) $report[$tagId]['currencies'][$currencyId]['sum'], + (string) $journal['amount'] + ); + $sums[$currencyId]['spent_sum'] = bcadd($sums[$currencyId]['spent_sum'], (string) $journal['amount']); + $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); } } } @@ -422,7 +401,7 @@ class TagController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], 'earned_sum' => '0', 'spent_sum' => '0', - 'total_sum' => '0', + 'total_sum' => '0' ]; /** @var array $tag */ @@ -441,17 +420,23 @@ class TagController extends Controller 'currency_id' => $currency['currency_id'], 'currency_symbol' => $currency['currency_symbol'], 'currency_name' => $currency['currency_name'], - 'currency_decimal_places' => $currency['currency_decimal_places'], + 'currency_decimal_places' => $currency['currency_decimal_places'] ]; - $report[$tagId]['currencies'][$currencyId]['earned'] = bcadd((string) $report[$tagId]['currencies'][$currencyId]['earned'], (string) $journal['amount']); - $report[$tagId]['currencies'][$currencyId]['sum'] = bcadd((string) $report[$tagId]['currencies'][$currencyId]['sum'], (string) $journal['amount']); - $sums[$currencyId]['earned_sum'] = bcadd($sums[$currencyId]['earned_sum'], (string) $journal['amount']); - $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); + $report[$tagId]['currencies'][$currencyId]['earned'] = bcadd( + (string) $report[$tagId]['currencies'][$currencyId]['earned'], + (string) $journal['amount'] + ); + $report[$tagId]['currencies'][$currencyId]['sum'] = bcadd( + (string) $report[$tagId]['currencies'][$currencyId]['sum'], + (string) $journal['amount'] + ); + $sums[$currencyId]['earned_sum'] = bcadd($sums[$currencyId]['earned_sum'], (string) $journal['amount']); + $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], (string) $journal['amount']); } } } - return view('reports.tag.partials.tags', ['sums' => $sums, 'report' => $report]); + return view('reports.tag.partials.tags', ['sums' => $sums, 'report' => $report]); } /** @@ -461,8 +446,8 @@ class TagController extends Controller */ public function topExpenses(Collection $accounts, Collection $tags, Carbon $start, Carbon $end) { - $spent = $this->opsRepository->listExpenses($start, $end, $accounts, $tags); - $result = []; + $spent = $this->opsRepository->listExpenses($start, $end, $accounts, $tags); + $result = []; foreach ($spent as $currency) { foreach ($currency['tags'] as $tag) { foreach ($tag['transaction_journals'] as $journal) { @@ -480,7 +465,7 @@ class TagController extends Controller 'currency_symbol' => $currency['currency_symbol'], 'currency_decimal_places' => $currency['currency_decimal_places'], 'tag_id' => $tag['id'], - 'tag_name' => $tag['name'], + 'tag_name' => $tag['name'] ]; } } @@ -509,15 +494,15 @@ class TagController extends Controller */ public function topIncome(Collection $accounts, Collection $tags, Carbon $start, Carbon $end) { - $spent = $this->opsRepository->listIncome($start, $end, $accounts, $tags); - $result = []; + $spent = $this->opsRepository->listIncome($start, $end, $accounts, $tags); + $result = []; foreach ($spent as $currency) { foreach ($currency['tags'] as $tag) { foreach ($tag['transaction_journals'] as $journal) { $result[] = [ - 'description' => $journal['description'], - 'transaction_group_id' => $journal['transaction_group_id'], - 'amount_float' => (float) $journal['amount'], // intentional float. + 'description' => $journal['description'], + 'transaction_group_id' => $journal['transaction_group_id'], + 'amount_float' => (float) $journal['amount'], // intentional float. 'amount' => $journal['amount'], 'date' => $journal['date']->isoFormat($this->monthAndDayFormat), 'date_sort' => $journal['date']->format('Y-m-d'), @@ -528,7 +513,7 @@ class TagController extends Controller 'currency_symbol' => $currency['currency_symbol'], 'currency_decimal_places' => $currency['currency_decimal_places'], 'tag_id' => $tag['id'], - 'tag_name' => $tag['name'], + 'tag_name' => $tag['name'] ]; } } diff --git a/app/Http/Controllers/ReportController.php b/app/Http/Controllers/ReportController.php index 02a889a320..bcc7f1900f 100644 --- a/app/Http/Controllers/ReportController.php +++ b/app/Http/Controllers/ReportController.php @@ -23,8 +23,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers; -use FireflyIII\Support\Facades\Preferences; -use Illuminate\Support\Facades\Log; use Carbon\Carbon; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Exceptions\FireflyException; @@ -34,12 +32,14 @@ use FireflyIII\Http\Requests\ReportFormRequest; use FireflyIII\Models\Account; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use FireflyIII\Support\Http\Controllers\RenderPartialViews; use Illuminate\Contracts\View\Factory; use Illuminate\Http\JsonResponse; use Illuminate\Http\RedirectResponse; use Illuminate\Routing\Redirector; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Log; use Illuminate\View\View; use Psr\Container\ContainerExceptionInterface; use Psr\Container\NotFoundExceptionInterface; @@ -51,7 +51,7 @@ class ReportController extends Controller { use RenderPartialViews; - protected ReportHelperInterface $helper; + protected ReportHelperInterface $helper; private BudgetRepositoryInterface $repository; /** @@ -61,17 +61,15 @@ class ReportController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.reports')); - app('view')->share('mainTitleIcon', 'fa-bar-chart'); - app('view')->share('subTitleIcon', 'fa-calendar'); - $this->helper = app(ReportHelperInterface::class); - $this->repository = app(BudgetRepositoryInterface::class); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.reports')); + app('view')->share('mainTitleIcon', 'fa-bar-chart'); + app('view')->share('subTitleIcon', 'fa-calendar'); + $this->helper = app(ReportHelperInterface::class); + $this->repository = app(BudgetRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -90,16 +88,10 @@ class ReportController extends Controller $start->endOfDay(); // end of day so the final balance is at the end of that day. $end->endOfDay(); - app('view')->share( - 'subTitle', - trans( - 'firefly.report_audit', - [ - 'start' => $start->isoFormat($this->monthAndDayFormat), - 'end' => $end->isoFormat($this->monthAndDayFormat), - ] - ) - ); + app('view')->share('subTitle', trans('firefly.report_audit', [ + 'start' => $start->isoFormat($this->monthAndDayFormat), + 'end' => $end->isoFormat($this->monthAndDayFormat) + ])); $generator = ReportGeneratorFactory::reportGenerator('Audit', $start, $end); $generator->setAccounts($accounts); @@ -123,16 +115,10 @@ class ReportController extends Controller $start->endOfDay(); // end of day so the final balance is at the end of that day. $end->endOfDay(); - app('view')->share( - 'subTitle', - trans( - 'firefly.report_budget', - [ - 'start' => $start->isoFormat($this->monthAndDayFormat), - 'end' => $end->isoFormat($this->monthAndDayFormat), - ] - ) - ); + app('view')->share('subTitle', trans('firefly.report_budget', [ + 'start' => $start->isoFormat($this->monthAndDayFormat), + 'end' => $end->isoFormat($this->monthAndDayFormat) + ])); $generator = ReportGeneratorFactory::reportGenerator('Budget', $start, $end); $generator->setAccounts($accounts); @@ -157,7 +143,10 @@ class ReportController extends Controller $start->endOfDay(); // end of day so the final balance is at the end of that day. $end->endOfDay(); - app('view')->share('subTitle', trans('firefly.report_category', ['start' => $start->isoFormat($this->monthAndDayFormat), 'end' => $end->isoFormat($this->monthAndDayFormat)])); + app('view')->share('subTitle', trans('firefly.report_category', [ + 'start' => $start->isoFormat($this->monthAndDayFormat), + 'end' => $end->isoFormat($this->monthAndDayFormat) + ])); $generator = ReportGeneratorFactory::reportGenerator('Category', $start, $end); $generator->setAccounts($accounts); @@ -183,7 +172,10 @@ class ReportController extends Controller $start->endOfDay(); // end of day so the final balance is at the end of that day. $end->endOfDay(); - app('view')->share('subTitle', trans('firefly.report_default', ['start' => $start->isoFormat($this->monthAndDayFormat), 'end' => $end->isoFormat($this->monthAndDayFormat)])); + app('view')->share('subTitle', trans('firefly.report_default', [ + 'start' => $start->isoFormat($this->monthAndDayFormat), + 'end' => $end->isoFormat($this->monthAndDayFormat) + ])); $generator = ReportGeneratorFactory::reportGenerator('Standard', $start, $end); $generator->setAccounts($accounts); @@ -206,7 +198,10 @@ class ReportController extends Controller $start->endOfDay(); // end of day so the final balance is at the end of that day. $end->endOfDay(); - app('view')->share('subTitle', trans('firefly.report_double', ['start' => $start->isoFormat($this->monthAndDayFormat), 'end' => $end->isoFormat($this->monthAndDayFormat)])); + app('view')->share('subTitle', trans('firefly.report_double', [ + 'start' => $start->isoFormat($this->monthAndDayFormat), + 'end' => $end->isoFormat($this->monthAndDayFormat) + ])); $generator = ReportGeneratorFactory::reportGenerator('Account', $start, $end); $generator->setAccounts($accounts); @@ -229,17 +224,21 @@ class ReportController extends Controller $start = clone session('first', today(config('app.timezone'))); $months = $this->helper->listOfMonths($start); $customFiscalYear = Preferences::get('customFiscalYear', 0)->data; - $accounts = $repository->getAccountsByType( - [AccountTypeEnum::DEFAULT->value, AccountTypeEnum::ASSET->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value] - ); + $accounts = $repository->getAccountsByType([ + AccountTypeEnum::DEFAULT->value, + AccountTypeEnum::ASSET->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::MORTGAGE->value + ]); // group accounts by role: - $groupedAccounts = []; + $groupedAccounts = []; /** @var Account $account */ foreach ($accounts as $account) { - $type = $account->accountType->type; - $role = sprintf('opt_group_%s', $repository->getMetaValue($account, 'account_role')); + $type = $account->accountType->type; + $role = sprintf('opt_group_%s', $repository->getMetaValue($account, 'account_role')); if (in_array($type, [AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value], true)) { $role = sprintf('opt_group_l_%s', $type); @@ -252,10 +251,17 @@ class ReportController extends Controller } ksort($groupedAccounts); - $accountList = implode(',', $accounts->pluck('id')->toArray()); + $accountList = implode(',', $accounts->pluck('id')->toArray()); $this->repository->cleanupBudgets(); - return view('reports.index', ['months' => $months, 'accounts' => $accounts, 'start' => $start, 'accountList' => $accountList, 'groupedAccounts' => $groupedAccounts, 'customFiscalYear' => $customFiscalYear]); + return view('reports.index', [ + 'months' => $months, + 'accounts' => $accounts, + 'start' => $start, + 'accountList' => $accountList, + 'groupedAccounts' => $groupedAccounts, + 'customFiscalYear' => $customFiscalYear + ]); } /** @@ -268,11 +274,11 @@ class ReportController extends Controller public function options(string $reportType) { $result = match ($reportType) { - default => $this->noReportOptions(), + default => $this->noReportOptions(), 'category' => $this->categoryReportOptions(), - 'budget' => $this->budgetReportOptions(), - 'tag' => $this->tagReportOptions(), - 'double' => $this->doubleReportOptions(), + 'budget' => $this->budgetReportOptions(), + 'tag' => $this->tagReportOptions(), + 'double' => $this->doubleReportOptions() }; return response()->json(['html' => $result]); @@ -330,13 +336,13 @@ class ReportController extends Controller return view('errors.error')->with('message', (string) trans('firefly.end_after_start_date')); } - $url = match ($reportType) { - default => route('reports.report.default', [$accounts, $start, $end]), + $url = match ($reportType) { + default => route('reports.report.default', [$accounts, $start, $end]), 'category' => route('reports.report.category', [$accounts, $categories, $start, $end]), - 'audit' => route('reports.report.audit', [$accounts, $start, $end]), - 'budget' => route('reports.report.budget', [$accounts, $budgets, $start, $end]), - 'tag' => route('reports.report.tag', [$accounts, $tags, $start, $end]), - 'double' => route('reports.report.double', [$accounts, $double, $start, $end]), + 'audit' => route('reports.report.audit', [$accounts, $start, $end]), + 'budget' => route('reports.report.budget', [$accounts, $budgets, $start, $end]), + 'tag' => route('reports.report.tag', [$accounts, $tags, $start, $end]), + 'double' => route('reports.report.double', [$accounts, $double, $start, $end]) }; return redirect($url); @@ -358,16 +364,10 @@ class ReportController extends Controller $start->endOfDay(); // end of day so the final balance is at the end of that day. $end->endOfDay(); - app('view')->share( - 'subTitle', - trans( - 'firefly.report_tag', - [ - 'start' => $start->isoFormat($this->monthAndDayFormat), - 'end' => $end->isoFormat($this->monthAndDayFormat), - ] - ) - ); + app('view')->share('subTitle', trans('firefly.report_tag', [ + 'start' => $start->isoFormat($this->monthAndDayFormat), + 'end' => $end->isoFormat($this->monthAndDayFormat) + ])); $generator = ReportGeneratorFactory::reportGenerator('Tag', $start, $end); $generator->setAccounts($accounts); diff --git a/app/Http/Controllers/Rule/CreateController.php b/app/Http/Controllers/Rule/CreateController.php index d70ab54921..dd45904f06 100644 --- a/app/Http/Controllers/Rule/CreateController.php +++ b/app/Http/Controllers/Rule/CreateController.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Rule; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Requests\RuleFormRequest; @@ -33,6 +32,7 @@ use FireflyIII\Models\Rule; use FireflyIII\Models\RuleGroup; use FireflyIII\Models\TransactionJournal; use FireflyIII\Repositories\Rule\RuleRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use FireflyIII\Support\Http\Controllers\ModelInformation; use FireflyIII\Support\Http\Controllers\RuleManagement; use FireflyIII\Support\Search\SearchInterface; @@ -60,16 +60,14 @@ class CreateController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.rules')); - app('view')->share('mainTitleIcon', 'fa-random'); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.rules')); + app('view')->share('mainTitleIcon', 'fa-random'); - $this->ruleRepos = app(RuleRepositoryInterface::class); + $this->ruleRepos = app(RuleRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -79,19 +77,17 @@ class CreateController extends Controller * * @throws FireflyException */ - public function create(Request $request, ?RuleGroup $ruleGroup = null): Factory|\Illuminate\Contracts\View\View + public function create(Request $request, null|RuleGroup $ruleGroup = null): Factory|\Illuminate\Contracts\View\View { $this->createDefaultRuleGroup(); - $preFilled = [ - 'strict' => true, - ]; - $oldTriggers = []; - $oldActions = []; + $preFilled = ['strict' => true]; + $oldTriggers = []; + $oldActions = []; // build triggers from query, if present. - $query = (string) $request->get('from_query'); + $query = (string) $request->get('from_query'); if ('' !== $query) { - $search = app(SearchInterface::class); + $search = app(SearchInterface::class); $search->parseQuery($query); $words = $search->getWords(); $excludedWords = $search->getExcludedWords(); @@ -99,22 +95,16 @@ class CreateController extends Controller if (count($words) > 0) { session()->flash('warning', trans('firefly.rule_from_search_words', ['string' => implode('', $words)])); foreach ($words as $word) { - $operators[] = [ - 'type' => 'description_contains', - 'value' => $word, - ]; + $operators[] = ['type' => 'description_contains', 'value' => $word]; } } if (count($excludedWords) > 0) { session()->flash('warning', trans('firefly.rule_from_search_words', ['string' => implode('', $excludedWords)])); foreach ($excludedWords as $excludedWord) { - $operators[] = [ - 'type' => '-description_contains', - 'value' => $excludedWord, - ]; + $operators[] = ['type' => '-description_contains', 'value' => $excludedWord]; } } - $oldTriggers = $this->parseFromOperators($operators); + $oldTriggers = $this->parseFromOperators($operators); } // var_dump($oldTriggers);exit; @@ -129,7 +119,7 @@ class CreateController extends Controller $subTitleIcon = 'fa-clone'; // title depends on whether or not there is a rule group: - $subTitle = (string) trans('firefly.make_new_rule_no_group'); + $subTitle = (string) trans('firefly.make_new_rule_no_group'); if ($ruleGroup instanceof RuleGroup) { $subTitle = (string) trans('firefly.make_new_rule', ['title' => $ruleGroup->title]); } @@ -143,10 +133,16 @@ class CreateController extends Controller } session()->forget('rules.create.fromStore'); - return view( - 'rules.rule.create', - ['subTitleIcon' => $subTitleIcon, 'oldTriggers' => $oldTriggers, 'preFilled' => $preFilled, 'oldActions' => $oldActions, 'triggerCount' => $triggerCount, 'actionCount' => $actionCount, 'ruleGroup' => $ruleGroup, 'subTitle' => $subTitle] - ); + return view('rules.rule.create', [ + 'subTitleIcon' => $subTitleIcon, + 'oldTriggers' => $oldTriggers, + 'preFilled' => $preFilled, + 'oldActions' => $oldActions, + 'triggerCount' => $triggerCount, + 'actionCount' => $actionCount, + 'ruleGroup' => $ruleGroup, + 'subTitle' => $subTitle + ]); } /** @@ -161,17 +157,17 @@ class CreateController extends Controller $request->session()->flash('info', (string) trans('firefly.instructions_rule_from_bill', ['name' => e($bill->name)])); $this->createDefaultRuleGroup(); - $preFilled = [ + $preFilled = [ 'strict' => true, - 'title' => (string) trans('firefly.new_rule_for_bill_title', ['name' => $bill->name]), - 'description' => (string) trans('firefly.new_rule_for_bill_description', ['name' => $bill->name]), + 'title' => (string) trans('firefly.new_rule_for_bill_title', ['name' => $bill->name]), + 'description' => (string) trans('firefly.new_rule_for_bill_description', ['name' => $bill->name]) ]; // make triggers and actions from the bill itself. // get triggers and actions for bill: - $oldTriggers = $this->getTriggersForBill($bill); - $oldActions = $this->getActionsForBill($bill); + $oldTriggers = $this->getTriggersForBill($bill); + $oldActions = $this->getActionsForBill($bill); // restore actions and triggers from old input: if (null !== $request->old() && is_array($request->old()) && count($request->old()) > 0) { @@ -184,7 +180,7 @@ class CreateController extends Controller $subTitleIcon = 'fa-clone'; // title depends on whether there is a rule group: - $subTitle = (string) trans('firefly.make_new_rule_no_group'); + $subTitle = (string) trans('firefly.make_new_rule_no_group'); // flash old data $request->session()->flash('preFilled', $preFilled); @@ -195,10 +191,15 @@ class CreateController extends Controller } session()->forget('rules.create.fromStore'); - return view( - 'rules.rule.create', - ['subTitleIcon' => $subTitleIcon, 'oldTriggers' => $oldTriggers, 'preFilled' => $preFilled, 'oldActions' => $oldActions, 'triggerCount' => $triggerCount, 'actionCount' => $actionCount, 'subTitle' => $subTitle] - ); + return view('rules.rule.create', [ + 'subTitleIcon' => $subTitleIcon, + 'oldTriggers' => $oldTriggers, + 'preFilled' => $preFilled, + 'oldActions' => $oldActions, + 'triggerCount' => $triggerCount, + 'actionCount' => $actionCount, + 'subTitle' => $subTitle + ]); } /** @@ -212,16 +213,16 @@ class CreateController extends Controller $subTitle = (string) trans('firefly.make_new_rule_no_group'); // get triggers and actions for journal. - $oldTriggers = $this->getTriggersForJournal($journal); - $oldActions = []; + $oldTriggers = $this->getTriggersForJournal($journal); + $oldActions = []; $this->createDefaultRuleGroup(); // collect pre-filled information: - $preFilled = [ + $preFilled = [ 'strict' => true, - 'title' => (string) trans('firefly.new_rule_for_journal_title', ['description' => $journal->description]), - 'description' => (string) trans('firefly.new_rule_for_journal_description', ['description' => $journal->description]), + 'title' => (string) trans('firefly.new_rule_for_journal_title', ['description' => $journal->description]), + 'description' => (string) trans('firefly.new_rule_for_journal_description', ['description' => $journal->description]) ]; // restore actions and triggers from old input: @@ -242,10 +243,15 @@ class CreateController extends Controller } session()->forget('rules.create.fromStore'); - return view( - 'rules.rule.create', - ['subTitleIcon' => $subTitleIcon, 'oldTriggers' => $oldTriggers, 'preFilled' => $preFilled, 'oldActions' => $oldActions, 'triggerCount' => $triggerCount, 'actionCount' => $actionCount, 'subTitle' => $subTitle] - ); + return view('rules.rule.create', [ + 'subTitleIcon' => $subTitleIcon, + 'oldTriggers' => $oldTriggers, + 'preFilled' => $preFilled, + 'oldActions' => $oldActions, + 'triggerCount' => $triggerCount, + 'actionCount' => $actionCount, + 'subTitle' => $subTitle + ]); } public function duplicate(Request $request): JsonResponse @@ -266,8 +272,8 @@ class CreateController extends Controller */ public function store(RuleFormRequest $request) { - $data = $request->getRuleData(); - $rule = $this->ruleRepos->store($data); + $data = $request->getRuleData(); + $rule = $this->ruleRepos->store($data); session()->flash('success_url', route('rules.select-transactions', [$rule->id])); session()->flash('success', (string) trans('firefly.stored_new_rule', ['title' => $rule->title])); Preferences::mark(); diff --git a/app/Http/Controllers/Rule/DeleteController.php b/app/Http/Controllers/Rule/DeleteController.php index 14332b7c14..d76a293f41 100644 --- a/app/Http/Controllers/Rule/DeleteController.php +++ b/app/Http/Controllers/Rule/DeleteController.php @@ -24,10 +24,10 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Rule; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\Rule; use FireflyIII\Repositories\Rule\RuleRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\View\View; @@ -47,16 +47,14 @@ class DeleteController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.rules')); - app('view')->share('mainTitleIcon', 'fa-random'); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.rules')); + app('view')->share('mainTitleIcon', 'fa-random'); - $this->ruleRepos = app(RuleRepositoryInterface::class); + $this->ruleRepos = app(RuleRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -71,7 +69,7 @@ class DeleteController extends Controller // put previous url in session $this->rememberPreviousUrl('rules.delete.url'); - return view('rules.rule.delete', ['rule' => $rule, 'subTitle' => $subTitle]); + return view('rules.rule.delete', ['rule' => $rule, 'subTitle' => $subTitle]); } /** diff --git a/app/Http/Controllers/Rule/EditController.php b/app/Http/Controllers/Rule/EditController.php index ff6b44ede7..7973aa82cc 100644 --- a/app/Http/Controllers/Rule/EditController.php +++ b/app/Http/Controllers/Rule/EditController.php @@ -24,13 +24,12 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Rule; -use FireflyIII\Support\Facades\Preferences; -use Illuminate\Support\Facades\Log; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Requests\RuleFormRequest; use FireflyIII\Models\Rule; use FireflyIII\Repositories\Rule\RuleRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use FireflyIII\Support\Http\Controllers\RenderPartialViews; use FireflyIII\Support\Http\Controllers\RuleManagement; use FireflyIII\Support\Search\OperatorQuerySearch; @@ -39,6 +38,7 @@ use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Routing\Redirector; +use Illuminate\Support\Facades\Log; use Illuminate\View\View; use Throwable; @@ -59,16 +59,14 @@ class EditController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.rules')); - app('view')->share('mainTitleIcon', 'fa-random'); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.rules')); + app('view')->share('mainTitleIcon', 'fa-random'); - $this->ruleRepos = app(RuleRepositoryInterface::class); + $this->ruleRepos = app(RuleRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -80,15 +78,15 @@ class EditController extends Controller */ public function edit(Request $request, Rule $rule): Factory|\Illuminate\Contracts\View\View { - $triggerCount = 0; - $actionCount = 0; - $oldActions = []; - $oldTriggers = []; + $triggerCount = 0; + $actionCount = 0; + $oldActions = []; + $oldTriggers = []; // build triggers from query, if present. - $query = (string) $request->get('from_query'); + $query = (string) $request->get('from_query'); if ('' !== $query) { - $search = app(SearchInterface::class); + $search = app(SearchInterface::class); $search->parseQuery($query); $words = $search->getWords(); $excludedWords = $search->getExcludedWords(); @@ -96,30 +94,24 @@ class EditController extends Controller if (count($words) > 0) { session()->flash('warning', trans('firefly.rule_from_search_words', ['string' => implode('', $words)])); foreach ($words as $word) { - $operators[] = [ - 'type' => 'description_contains', - 'value' => $word, - ]; + $operators[] = ['type' => 'description_contains', 'value' => $word]; } } if (count($excludedWords) > 0) { session()->flash('warning', trans('firefly.rule_from_search_words', ['string' => implode('', $excludedWords)])); foreach ($excludedWords as $excludedWord) { - $operators[] = [ - 'type' => '-description_contains', - 'value' => $excludedWord, - ]; + $operators[] = ['type' => '-description_contains', 'value' => $excludedWord]; } } - $oldTriggers = $this->parseFromOperators($operators); + $oldTriggers = $this->parseFromOperators($operators); } // has old input? if (null !== $request->old() && is_array($request->old()) && count($request->old()) > 0) { $oldTriggers = $this->getPreviousTriggers($request); $oldActions = $this->getPreviousActions($request); } - $triggerCount = count($oldTriggers); - $actionCount = count($oldActions); + $triggerCount = count($oldTriggers); + $actionCount = count($oldActions); // overrule old input and query data when it has no rule data: if (0 === $triggerCount && 0 === $actionCount) { @@ -129,16 +121,16 @@ class EditController extends Controller $actionCount = count($oldActions); } - $hasOldInput = null !== $request->old('_token'); - $preFilled = [ + $hasOldInput = null !== $request->old('_token'); + $preFilled = [ 'active' => $hasOldInput ? (bool) $request->old('active') : $rule->active, 'stop_processing' => $hasOldInput ? (bool) $request->old('stop_processing') : $rule->stop_processing, - 'strict' => $hasOldInput ? (bool) $request->old('strict') : $rule->strict, + 'strict' => $hasOldInput ? (bool) $request->old('strict') : $rule->strict ]; // get rule trigger for update / store-journal: $primaryTrigger = $this->ruleRepos->getPrimaryTrigger($rule); - $subTitle = (string) trans('firefly.edit_rule', ['nr' => $rule->order, 'title' => $rule->title]); + $subTitle = (string) trans('firefly.edit_rule', ['nr' => $rule->order, 'title' => $rule->title]); // put previous url in session if not redirect from store (not "return_to_edit"). if (true !== session('rules.edit.fromUpdate')) { @@ -148,7 +140,15 @@ class EditController extends Controller $request->session()->flash('preFilled', $preFilled); - return view('rules.rule.edit', ['rule' => $rule, 'subTitle' => $subTitle, 'primaryTrigger' => $primaryTrigger, 'oldTriggers' => $oldTriggers, 'oldActions' => $oldActions, 'triggerCount' => $triggerCount, 'actionCount' => $actionCount]); + return view('rules.rule.edit', [ + 'rule' => $rule, + 'subTitle' => $subTitle, + 'primaryTrigger' => $primaryTrigger, + 'oldTriggers' => $oldTriggers, + 'oldActions' => $oldActions, + 'triggerCount' => $triggerCount, + 'actionCount' => $actionCount + ]); } /** @@ -167,19 +167,16 @@ class EditController extends Controller } asort($triggers); - $index = 0; + $index = 0; foreach ($submittedOperators as $operator) { try { - $renderedEntries[] = view( - 'rules.partials.trigger', - [ - 'oldTrigger' => OperatorQuerySearch::getRootOperator($operator['type']), - 'oldValue' => $operator['value'], - 'oldChecked' => false, - 'count' => $index + 1, - 'triggers' => $triggers, - ] - )->render(); + $renderedEntries[] = view('rules.partials.trigger', [ + 'oldTrigger' => OperatorQuerySearch::getRootOperator($operator['type']), + 'oldValue' => $operator['value'], + 'oldChecked' => false, + 'count' => $index + 1, + 'triggers' => $triggers + ])->render(); } catch (Throwable $e) { $message = sprintf('Throwable was thrown in getPreviousTriggers(): %s', $e->getMessage()); Log::debug($message); @@ -200,7 +197,7 @@ class EditController extends Controller */ public function update(RuleFormRequest $request, Rule $rule) { - $data = $request->getRuleData(); + $data = $request->getRuleData(); $this->ruleRepos->update($rule, $data); diff --git a/app/Http/Controllers/Rule/IndexController.php b/app/Http/Controllers/Rule/IndexController.php index e95c5c459c..72a6cceb0d 100644 --- a/app/Http/Controllers/Rule/IndexController.php +++ b/app/Http/Controllers/Rule/IndexController.php @@ -43,7 +43,7 @@ class IndexController extends Controller use RuleManagement; private RuleGroupRepositoryInterface $ruleGroupRepos; - private RuleRepositoryInterface $ruleRepos; + private RuleRepositoryInterface $ruleRepos; /** * RuleController constructor. @@ -51,16 +51,14 @@ class IndexController extends Controller public function __construct() { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.rules')); - app('view')->share('mainTitleIcon', 'fa-random'); - $this->ruleGroupRepos = app(RuleGroupRepositoryInterface::class); - $this->ruleRepos = app(RuleRepositoryInterface::class); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.rules')); + app('view')->share('mainTitleIcon', 'fa-random'); + $this->ruleGroupRepos = app(RuleGroupRepositoryInterface::class); + $this->ruleRepos = app(RuleRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -89,7 +87,7 @@ class IndexController extends Controller { $route = route('search.index'); $query = $this->ruleRepos->getSearchQuery($rule); - $route = sprintf('%s?%s', $route, http_build_query(['search' => $query, 'rule' => $rule->id])); + $route = sprintf('%s?%s', $route, http_build_query(['search' => $query, 'rule' => $rule->id])); return redirect($route); } diff --git a/app/Http/Controllers/Rule/SelectController.php b/app/Http/Controllers/Rule/SelectController.php index dc3744ce4a..f338f64fcb 100644 --- a/app/Http/Controllers/Rule/SelectController.php +++ b/app/Http/Controllers/Rule/SelectController.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Rule; -use Illuminate\Support\Facades\Log; use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; @@ -39,6 +38,7 @@ use Illuminate\Contracts\View\Factory; use Illuminate\Http\JsonResponse; use Illuminate\Http\RedirectResponse; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Log; use Illuminate\View\View; use Throwable; @@ -56,14 +56,12 @@ class SelectController extends Controller { parent::__construct(); - $this->middleware( - static function ($request, $next) { - app('view')->share('title', (string)trans('firefly.rules')); - app('view')->share('mainTitleIcon', 'fa-random'); + $this->middleware(static function ($request, $next) { + app('view')->share('title', (string) trans('firefly.rules')); + app('view')->share('mainTitleIcon', 'fa-random'); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -73,8 +71,8 @@ class SelectController extends Controller { // Get parameters specified by the user /** @var User $user */ - $user = auth()->user(); - $accounts = implode(',', $request->get('accounts')); + $user = auth()->user(); + $accounts = implode(',', $request->get('accounts')); // create new rule engine: $newRuleEngine = app(RuleEngineInterface::class); $newRuleEngine->setUser($user); @@ -82,20 +80,20 @@ class SelectController extends Controller // add date operators. if (null !== $request->get('start')) { $startDate = new Carbon($request->get('start')); - $newRuleEngine->addOperator(['type' => 'date_after', 'value' => $startDate->format('Y-m-d')]); + $newRuleEngine->addOperator(['type' => 'date_after', 'value' => $startDate->format('Y-m-d')]); } if (null !== $request->get('end')) { $endDate = new Carbon($request->get('end')); - $newRuleEngine->addOperator(['type' => 'date_before', 'value' => $endDate->format('Y-m-d')]); + $newRuleEngine->addOperator(['type' => 'date_before', 'value' => $endDate->format('Y-m-d')]); } // add extra operators: - $newRuleEngine->addOperator(['type' => 'account_id', 'value' => $accounts]); + $newRuleEngine->addOperator(['type' => 'account_id', 'value' => $accounts]); // set rules: $newRuleEngine->setRules(new Collection()->push($rule)); $newRuleEngine->fire(); - $resultCount = $newRuleEngine->getResults(); + $resultCount = $newRuleEngine->getResults(); session()->flash('success', trans_choice('firefly.applied_rule_selection', $resultCount, ['title' => $rule->title])); @@ -113,9 +111,9 @@ class SelectController extends Controller return redirect(route('rules.index')); } // does the user have shared accounts? - $subTitle = (string)trans('firefly.apply_rule_selection', ['title' => $rule->title]); + $subTitle = (string) trans('firefly.apply_rule_selection', ['title' => $rule->title]); - return view('rules.rule.select-transactions', ['rule' => $rule, 'subTitle' => $subTitle]); + return view('rules.rule.select-transactions', ['rule' => $rule, 'subTitle' => $subTitle]); } /** @@ -127,25 +125,25 @@ class SelectController extends Controller public function testTriggers(TestRuleFormRequest $request): JsonResponse { // build fake rule - $rule = new Rule(); + $rule = new Rule(); /** @var \Illuminate\Database\Eloquent\Collection $triggers */ - $triggers = new Collection(); - $rule->strict = '1' === $request->get('strict'); + $triggers = new Collection(); + $rule->strict = '1' === $request->get('strict'); // build trigger array from response - $textTriggers = $this->getValidTriggerList($request); + $textTriggers = $this->getValidTriggerList($request); // warn if nothing. if (0 === count($textTriggers)) { - return response()->json(['html' => '', 'warning' => (string)trans('firefly.warning_no_valid_triggers')]); + return response()->json(['html' => '', 'warning' => (string) trans('firefly.warning_no_valid_triggers')]); } foreach ($textTriggers as $textTrigger) { - $needsContext = config(sprintf('search.operators.%s.needs_context', $textTrigger['type'])) ?? true; - $trigger = new RuleTrigger(); - $trigger->trigger_type = $textTrigger['type']; - $trigger->trigger_value = $textTrigger['value']; + $needsContext = config(sprintf('search.operators.%s.needs_context', $textTrigger['type'])) ?? true; + $trigger = new RuleTrigger(); + $trigger->trigger_type = $textTrigger['type']; + $trigger->trigger_value = $textTrigger['value']; if (false === $needsContext) { $trigger->trigger_value = 'true'; } @@ -160,22 +158,22 @@ class SelectController extends Controller // create new rule engine: /** @var RuleEngineInterface $newRuleEngine */ - $newRuleEngine = app(RuleEngineInterface::class); + $newRuleEngine = app(RuleEngineInterface::class); // set rules: $newRuleEngine->setRules(new Collection()->push($rule)); $newRuleEngine->setRefreshTriggers(false); - $collection = $newRuleEngine->find(); - $collection = $collection->slice(0, 20); + $collection = $newRuleEngine->find(); + $collection = $collection->slice(0, 20); // Warn the user if only a subset of transactions is returned - $warning = ''; + $warning = ''; if (0 === count($collection)) { - $warning = (string)trans('firefly.warning_no_matching_transactions'); + $warning = (string) trans('firefly.warning_no_matching_transactions'); } // Return json response - $view = 'ERROR, see logs.'; + $view = 'ERROR, see logs.'; try { $view = view('list.journals-array-tiny', ['groups' => $collection])->render(); @@ -187,7 +185,7 @@ class SelectController extends Controller throw new FireflyException($view, 0, $exception); } - return response()->json(['html' => $view, 'warning' => $warning]); + return response()->json(['html' => $view, 'warning' => $warning]); } /** @@ -198,26 +196,26 @@ class SelectController extends Controller */ public function testTriggersByRule(Rule $rule): JsonResponse { - $triggers = $rule->ruleTriggers; + $triggers = $rule->ruleTriggers; if (0 === count($triggers)) { - return response()->json(['html' => '', 'warning' => (string)trans('firefly.warning_no_valid_triggers')]); + return response()->json(['html' => '', 'warning' => (string) trans('firefly.warning_no_valid_triggers')]); } // create new rule engine: $newRuleEngine = app(RuleEngineInterface::class); // set rules: $newRuleEngine->setRules(new Collection()->push($rule)); - $collection = $newRuleEngine->find(); - $collection = $collection->slice(0, 20); + $collection = $newRuleEngine->find(); + $collection = $collection->slice(0, 20); - $warning = ''; + $warning = ''; if (0 === count($collection)) { - $warning = (string)trans('firefly.warning_no_matching_transactions'); + $warning = (string) trans('firefly.warning_no_matching_transactions'); } // Return json response - $view = 'ERROR, see logs.'; + $view = 'ERROR, see logs.'; try { $view = view('list.journals-array-tiny', ['groups' => $collection])->render(); @@ -229,6 +227,6 @@ class SelectController extends Controller throw new FireflyException($message, 0, $exception); } - return response()->json(['html' => $view, 'warning' => $warning]); + return response()->json(['html' => $view, 'warning' => $warning]); } } diff --git a/app/Http/Controllers/RuleGroup/CreateController.php b/app/Http/Controllers/RuleGroup/CreateController.php index dfe919246b..3ca5107b60 100644 --- a/app/Http/Controllers/RuleGroup/CreateController.php +++ b/app/Http/Controllers/RuleGroup/CreateController.php @@ -24,10 +24,10 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\RuleGroup; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Requests\RuleGroupFormRequest; use FireflyIII\Repositories\RuleGroup\RuleGroupRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Routing\Redirector; @@ -48,16 +48,14 @@ class CreateController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.rules')); - app('view')->share('mainTitleIcon', 'fa-random'); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.rules')); + app('view')->share('mainTitleIcon', 'fa-random'); - $this->repository = app(RuleGroupRepositoryInterface::class); + $this->repository = app(RuleGroupRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -76,7 +74,7 @@ class CreateController extends Controller } session()->forget('rule-groups.create.fromStore'); - return view('rules.rule-group.create', ['subTitleIcon' => $subTitleIcon, 'subTitle' => $subTitle]); + return view('rules.rule-group.create', ['subTitleIcon' => $subTitleIcon, 'subTitle' => $subTitle]); } /** @@ -92,7 +90,7 @@ class CreateController extends Controller session()->flash('success', (string) trans('firefly.created_new_rule_group', ['title' => $ruleGroup->title])); Preferences::mark(); - $redirect = redirect($this->getPreviousUrl('rule-groups.create.url')); + $redirect = redirect($this->getPreviousUrl('rule-groups.create.url')); if (1 === (int) $request->get('create_another')) { session()->put('rule-groups.create.fromStore', true); diff --git a/app/Http/Controllers/RuleGroup/DeleteController.php b/app/Http/Controllers/RuleGroup/DeleteController.php index d788955054..c026131365 100644 --- a/app/Http/Controllers/RuleGroup/DeleteController.php +++ b/app/Http/Controllers/RuleGroup/DeleteController.php @@ -24,10 +24,10 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\RuleGroup; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\RuleGroup; use FireflyIII\Repositories\RuleGroup\RuleGroupRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; @@ -49,16 +49,14 @@ class DeleteController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.rules')); - app('view')->share('mainTitleIcon', 'fa-random'); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.rules')); + app('view')->share('mainTitleIcon', 'fa-random'); - $this->repository = app(RuleGroupRepositoryInterface::class); + $this->repository = app(RuleGroupRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -73,7 +71,7 @@ class DeleteController extends Controller // put previous url in session $this->rememberPreviousUrl('rule-groups.delete.url'); - return view('rules.rule-group.delete', ['ruleGroup' => $ruleGroup, 'subTitle' => $subTitle]); + return view('rules.rule-group.delete', ['ruleGroup' => $ruleGroup, 'subTitle' => $subTitle]); } /** @@ -81,7 +79,7 @@ class DeleteController extends Controller */ public function destroy(Request $request, RuleGroup $ruleGroup): Redirector|RedirectResponse { - $title = $ruleGroup->title; + $title = $ruleGroup->title; /** @var RuleGroup $moveTo */ $moveTo = $this->repository->find((int) $request->get('move_rules_before_delete')); diff --git a/app/Http/Controllers/RuleGroup/EditController.php b/app/Http/Controllers/RuleGroup/EditController.php index 637b004aac..ab1e2308cb 100644 --- a/app/Http/Controllers/RuleGroup/EditController.php +++ b/app/Http/Controllers/RuleGroup/EditController.php @@ -24,11 +24,11 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\RuleGroup; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Requests\RuleGroupFormRequest; use FireflyIII\Models\RuleGroup; use FireflyIII\Repositories\RuleGroup\RuleGroupRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use Illuminate\Contracts\View\Factory; use Illuminate\Http\JsonResponse; use Illuminate\Http\RedirectResponse; @@ -50,16 +50,14 @@ class EditController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.rules')); - app('view')->share('mainTitleIcon', 'fa-random'); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.rules')); + app('view')->share('mainTitleIcon', 'fa-random'); - $this->repository = app(RuleGroupRepositoryInterface::class); + $this->repository = app(RuleGroupRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -69,12 +67,10 @@ class EditController extends Controller */ public function edit(Request $request, RuleGroup $ruleGroup): Factory|\Illuminate\Contracts\View\View { - $subTitle = (string) trans('firefly.edit_rule_group', ['title' => $ruleGroup->title]); + $subTitle = (string) trans('firefly.edit_rule_group', ['title' => $ruleGroup->title]); $hasOldInput = null !== $request->old('_token'); - $preFilled = [ - 'active' => $hasOldInput ? (bool) $request->old('active') : $ruleGroup->active, - ]; + $preFilled = ['active' => $hasOldInput ? (bool) $request->old('active') : $ruleGroup->active]; // put previous url in session if not redirect from store (not "return_to_edit"). if (true !== session('rule-groups.edit.fromUpdate')) { $this->rememberPreviousUrl('rule-groups.edit.url'); @@ -82,7 +78,7 @@ class EditController extends Controller session()->forget('rule-groups.edit.fromUpdate'); session()->flash('preFilled', $preFilled); - return view('rules.rule-group.edit', ['ruleGroup' => $ruleGroup, 'subTitle' => $subTitle]); + return view('rules.rule-group.edit', ['ruleGroup' => $ruleGroup, 'subTitle' => $subTitle]); } /** @@ -121,10 +117,10 @@ class EditController extends Controller */ public function update(RuleGroupFormRequest $request, RuleGroup $ruleGroup) { - $data = [ + $data = [ 'title' => $request->convertString('title'), 'description' => $request->stringWithNewlines('description'), - 'active' => 1 === (int) $request->input('active'), + 'active' => 1 === (int) $request->input('active') ]; $this->repository->update($ruleGroup, $data); diff --git a/app/Http/Controllers/RuleGroup/ExecutionController.php b/app/Http/Controllers/RuleGroup/ExecutionController.php index ecf02825a1..ec4b950215 100644 --- a/app/Http/Controllers/RuleGroup/ExecutionController.php +++ b/app/Http/Controllers/RuleGroup/ExecutionController.php @@ -53,15 +53,13 @@ class ExecutionController extends Controller { parent::__construct(); $this->repository = app(AccountRepositoryInterface::class); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string)trans('firefly.rules')); - app('view')->share('mainTitleIcon', 'fa-random'); - $this->repository->setUser(auth()->user()); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.rules')); + app('view')->share('mainTitleIcon', 'fa-random'); + $this->repository->setUser(auth()->user()); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -73,8 +71,8 @@ class ExecutionController extends Controller { Log::debug(sprintf('You have selected rule group #%d', $ruleGroup->id)); // Get parameters specified by the user - $accounts = $request->get('accounts'); - $set = new Collection(); + $accounts = $request->get('accounts'); + $set = new Collection(); if (is_array($accounts)) { $set = $this->repository->getAccountsById($accounts); } @@ -94,8 +92,8 @@ class ExecutionController extends Controller $endDate = new Carbon($request->get('end')); $collector->setEnd($endDate); } - $final = $collector->getGroups(); - $ids = $final->pluck('id')->toArray(); + $final = $collector->getGroups(); + $ids = $final->pluck('id')->toArray(); Log::debug(sprintf('Found %d groups collected from %d account(s)', $final->count(), $set->count())); foreach (array_chunk($ids, 1337) as $setOfIds) { Log::debug(sprintf('Now processing %d groups', count($setOfIds))); @@ -109,7 +107,7 @@ class ExecutionController extends Controller } // Tell the user that the job is queued - session()->flash('success', (string)trans('firefly.applied_rule_group_selection', ['title' => $ruleGroup->title])); + session()->flash('success', (string) trans('firefly.applied_rule_group_selection', ['title' => $ruleGroup->title])); return redirect()->route('rules.index'); } @@ -121,8 +119,8 @@ class ExecutionController extends Controller */ public function selectTransactions(RuleGroup $ruleGroup): Factory|\Illuminate\Contracts\View\View { - $subTitle = (string)trans('firefly.apply_rule_group_selection', ['title' => $ruleGroup->title]); + $subTitle = (string) trans('firefly.apply_rule_group_selection', ['title' => $ruleGroup->title]); - return view('rules.rule-group.select-transactions', ['ruleGroup' => $ruleGroup, 'subTitle' => $subTitle]); + return view('rules.rule-group.select-transactions', ['ruleGroup' => $ruleGroup, 'subTitle' => $subTitle]); } } diff --git a/app/Http/Controllers/SearchController.php b/app/Http/Controllers/SearchController.php index 67d3762f5d..cc2e776a6c 100644 --- a/app/Http/Controllers/SearchController.php +++ b/app/Http/Controllers/SearchController.php @@ -23,13 +23,13 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers; -use Illuminate\Support\Facades\Log; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Repositories\Rule\RuleRepositoryInterface; use FireflyIII\Support\Search\SearchInterface; use Illuminate\Contracts\View\Factory; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; +use Illuminate\Support\Facades\Log; use Illuminate\View\View; use Throwable; @@ -45,14 +45,12 @@ class SearchController extends Controller { parent::__construct(); app('view')->share('showCategory', true); - $this->middleware( - static function ($request, $next) { - app('view')->share('mainTitleIcon', 'fa-search'); - app('view')->share('title', (string) trans('firefly.search')); + $this->middleware(static function ($request, $next) { + app('view')->share('mainTitleIcon', 'fa-search'); + app('view')->share('title', (string) trans('firefly.search')); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -63,18 +61,18 @@ class SearchController extends Controller public function index(Request $request, SearchInterface $searcher): Factory|\Illuminate\Contracts\View\View { // search params: - $fullQuery = $request->get('search'); + $fullQuery = $request->get('search'); if (is_array($request->get('search'))) { $fullQuery = ''; } - $fullQuery = (string) $fullQuery; - $page = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page'); - $ruleId = (int) $request->get('rule'); - $ruleChanged = false; + $fullQuery = (string) $fullQuery; + $page = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page'); + $ruleId = (int) $request->get('rule'); + $ruleChanged = false; // find rule, check if query is different, offer to update. - $ruleRepository = app(RuleRepositoryInterface::class); - $rule = $ruleRepository->find($ruleId); + $ruleRepository = app(RuleRepositoryInterface::class); + $rule = $ruleRepository->find($ruleId); if (null !== $rule) { $originalQuery = $ruleRepository->getSearchQuery($rule); if ($originalQuery !== $fullQuery) { @@ -89,9 +87,20 @@ class SearchController extends Controller $excludedWords = $searcher->getExcludedWords(); $operators = $searcher->getOperators(); $invalidOperators = $searcher->getInvalidOperators(); - $subTitle = (string) trans('breadcrumbs.search_result', ['query' => $fullQuery]); + $subTitle = (string) trans('breadcrumbs.search_result', ['query' => $fullQuery]); - return view('search.index', ['words' => $words, 'excludedWords' => $excludedWords, 'operators' => $operators, 'page' => $page, 'rule' => $rule, 'fullQuery' => $fullQuery, 'subTitle' => $subTitle, 'ruleId' => $ruleId, 'ruleChanged' => $ruleChanged, 'invalidOperators' => $invalidOperators]); + return view('search.index', [ + 'words' => $words, + 'excludedWords' => $excludedWords, + 'operators' => $operators, + 'page' => $page, + 'rule' => $rule, + 'fullQuery' => $fullQuery, + 'subTitle' => $subTitle, + 'ruleId' => $ruleId, + 'ruleChanged' => $ruleChanged, + 'invalidOperators' => $invalidOperators + ]); } /** @@ -101,12 +110,12 @@ class SearchController extends Controller */ public function search(Request $request, SearchInterface $searcher): JsonResponse { - $entry = $request->get('query'); + $entry = $request->get('query'); if (!is_scalar($entry)) { $entry = ''; } - $fullQuery = (string) $entry; - $page = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page'); + $fullQuery = (string) $entry; + $page = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page'); $searcher->parseQuery($fullQuery); @@ -115,11 +124,11 @@ class SearchController extends Controller $hasPages = $groups->hasPages(); $searchTime = round($searcher->searchTime(), 3); // in seconds $parameters = ['search' => $fullQuery]; - $url = route('search.index').'?'.http_build_query($parameters); + $url = route('search.index') . '?' . http_build_query($parameters); $groups->setPath($url); try { - $html = view('search.search', ['groups' => $groups, 'hasPages' => $hasPages, 'searchTime' => $searchTime])->render(); + $html = view('search.search', ['groups' => $groups, 'hasPages' => $hasPages, 'searchTime' => $searchTime])->render(); } catch (Throwable $e) { Log::error(sprintf('Cannot render search.search: %s', $e->getMessage())); Log::error($e->getTraceAsString()); @@ -128,6 +137,6 @@ class SearchController extends Controller throw new FireflyException($html, 0, $e); } - return response()->json(['count' => $groups->count(), 'html' => $html]); + return response()->json(['count' => $groups->count(), 'html' => $html]); } } diff --git a/app/Http/Controllers/System/CronController.php b/app/Http/Controllers/System/CronController.php index eeb3cf9baf..95317da085 100644 --- a/app/Http/Controllers/System/CronController.php +++ b/app/Http/Controllers/System/CronController.php @@ -24,10 +24,10 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\System; -use Illuminate\Support\Facades\Log; use Illuminate\Contracts\Foundation\Application; use Illuminate\Contracts\Routing\ResponseFactory; use Illuminate\Http\Response; +use Illuminate\Support\Facades\Log; /** * Class CronController diff --git a/app/Http/Controllers/System/InstallController.php b/app/Http/Controllers/System/InstallController.php index 94b6c9771d..302effafc1 100644 --- a/app/Http/Controllers/System/InstallController.php +++ b/app/Http/Controllers/System/InstallController.php @@ -24,11 +24,11 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\System; -use FireflyIII\Support\Facades\Preferences; use Exception; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Support\Facades\FireflyConfig; +use FireflyIII\Support\Facades\Preferences; use FireflyIII\Support\Http\Controllers\GetConfigurationData; use Illuminate\Contracts\View\Factory; use Illuminate\Http\JsonResponse; @@ -52,16 +52,17 @@ class InstallController extends Controller public const string BASEDIR_ERROR = 'Firefly III cannot execute the upgrade commands. It is not allowed to because of an open_basedir restriction.'; public const string FORBIDDEN_ERROR = 'Internal PHP function "proc_close" is disabled for your installation. Auto-migration is not possible.'; public const string OTHER_ERROR = 'An unknown error prevented Firefly III from executing the upgrade commands. Sorry.'; - private string $lastError = ''; + + private string $lastError = ''; // empty on purpose. - private array $upgradeCommands = [ + private array $upgradeCommands = [ // there are 5 initial commands // Check 4 places: InstallController, Docker image, UpgradeDatabase, composer.json - 'migrate' => ['--seed' => true, '--force' => true], - 'generate-keys' => [], // an exception :( + 'migrate' => ['--seed' => true, '--force' => true], + 'generate-keys' => [], // an exception :( 'firefly-iii:upgrade-database' => [], - 'firefly-iii:set-latest-version' => ['--james-is-cool' => true], - 'firefly-iii:verify-security-alerts' => [], + 'firefly-iii:set-latest-version' => ['--james-is-cool' => true], + 'firefly-iii:verify-security-alerts' => [] ]; /** @@ -91,19 +92,13 @@ class InstallController extends Controller public function runCommand(Request $request): JsonResponse { $requestIndex = (int) $request->get('index'); - $response = [ - 'hasNextCommand' => false, - 'done' => true, - 'previous' => null, - 'error' => false, - 'errorMessage' => null, - ]; + $response = ['hasNextCommand' => false, 'done' => true, 'previous' => null, 'error' => false, 'errorMessage' => null]; Log::debug(sprintf('Will now run commands. Request index is %d', $requestIndex)); - $indexes = array_keys($this->upgradeCommands); + $indexes = array_keys($this->upgradeCommands); if (array_key_exists($requestIndex, $indexes)) { - $command = $indexes[$requestIndex]; - $parameters = $this->upgradeCommands[$command]; + $command = $indexes[$requestIndex]; + $parameters = $this->upgradeCommands[$command]; Log::debug(sprintf('Will now execute command "%s" with parameters', $command), $parameters); try { @@ -114,17 +109,17 @@ class InstallController extends Controller if (str_contains($e->getMessage(), 'open_basedir restriction in effect')) { $this->lastError = self::BASEDIR_ERROR; } - $result = false; + $result = false; $this->lastError = sprintf('%s %s', self::OTHER_ERROR, $e->getMessage()); } if (false === $result) { $response['errorMessage'] = $this->lastError; - $response['error'] = true; + $response['error'] = true; return response()->json($response); } $response['hasNextCommand'] = array_key_exists($requestIndex + 1, $indexes); - $response['previous'] = $command; + $response['previous'] = $command; } return response()->json($response); @@ -160,12 +155,9 @@ class InstallController extends Controller */ public function keys(): void { - $key = RSA::createKey(4096); + $key = RSA::createKey(4096); - [$publicKey, $privateKey] = [ - Passport::keyPath('oauth-public.key'), - Passport::keyPath('oauth-private.key'), - ]; + [$publicKey, $privateKey] = [Passport::keyPath('oauth-public.key'), Passport::keyPath('oauth-private.key')]; if (file_exists($publicKey) || file_exists($privateKey)) { return; diff --git a/app/Http/Controllers/TagController.php b/app/Http/Controllers/TagController.php index 0ed269e73d..14975b601d 100644 --- a/app/Http/Controllers/TagController.php +++ b/app/Http/Controllers/TagController.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers; -use FireflyIII\Support\Facades\Preferences; use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Helpers\Attachments\AttachmentHelperInterface; @@ -32,6 +31,7 @@ use FireflyIII\Http\Requests\TagFormRequest; use FireflyIII\Models\Location; use FireflyIII\Models\Tag; use FireflyIII\Repositories\Tag\TagRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use FireflyIII\Support\Http\Controllers\PeriodOverview; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; @@ -48,7 +48,7 @@ class TagController extends Controller { use PeriodOverview; - protected TagRepositoryInterface $repository; + protected TagRepositoryInterface $repository; private AttachmentHelperInterface $attachmentsHelper; /** @@ -59,17 +59,15 @@ class TagController extends Controller parent::__construct(); $this->redirectUrl = route('tags.index'); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.tags')); - app('view')->share('mainTitleIcon', 'fa-tag'); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.tags')); + app('view')->share('mainTitleIcon', 'fa-tag'); - $this->attachmentsHelper = app(AttachmentHelperInterface::class); - $this->repository = app(TagRepositoryInterface::class); + $this->attachmentsHelper = app(AttachmentHelperInterface::class); + $this->repository = app(TagRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -83,15 +81,13 @@ class TagController extends Controller $subTitleIcon = 'fa-tag'; // location info: - $hasOldInput = null !== $request->old('_token'); - $locations = [ - 'location' => [ - 'latitude' => $hasOldInput ? old('location_latitude') : config('firefly.default_location.latitude'), - 'longitude' => $hasOldInput ? old('location_longitude') : config('firefly.default_location.longitude'), - 'zoom_level' => $hasOldInput ? old('location_zoom_level') : config('firefly.default_location.zoom_level'), - 'has_location' => $hasOldInput && 'true' === old('location_has_location'), - ], - ]; + $hasOldInput = null !== $request->old('_token'); + $locations = ['location' => [ + 'latitude' => $hasOldInput ? old('location_latitude') : config('firefly.default_location.latitude'), + 'longitude' => $hasOldInput ? old('location_longitude') : config('firefly.default_location.longitude'), + 'zoom_level' => $hasOldInput ? old('location_zoom_level') : config('firefly.default_location.zoom_level'), + 'has_location' => $hasOldInput && 'true' === old('location_has_location') + ]]; // put previous url in session if not redirect from store (not "create another"). if (true !== session('tags.create.fromStore')) { @@ -99,7 +95,7 @@ class TagController extends Controller } session()->forget('tags.create.fromStore'); - return view('tags.create', ['subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'locations' => $locations]); + return view('tags.create', ['subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'locations' => $locations]); } /** @@ -114,7 +110,7 @@ class TagController extends Controller // put previous url in session $this->rememberPreviousUrl('tags.delete.url'); - return view('tags.delete', ['tag' => $tag, 'subTitle' => $subTitle]); + return view('tags.delete', ['tag' => $tag, 'subTitle' => $subTitle]); } /** @@ -124,22 +120,20 @@ class TagController extends Controller */ public function edit(Tag $tag): Factory|\Illuminate\Contracts\View\View { - $subTitle = (string) trans('firefly.edit_tag', ['tag' => $tag->tag]); + $subTitle = (string) trans('firefly.edit_tag', ['tag' => $tag->tag]); $subTitleIcon = 'fa-tag'; - $location = $this->repository->getLocation($tag); - $latitude = $location instanceof Location ? $location->latitude : config('firefly.default_location.latitude'); - $longitude = $location instanceof Location ? $location->longitude : config('firefly.default_location.longitude'); - $zoomLevel = $location instanceof Location ? $location->zoom_level : config('firefly.default_location.zoom_level'); - $hasLocation = $location instanceof Location; - $locations = [ - 'location' => [ - 'latitude' => old('location_latitude') ?? $latitude, - 'longitude' => old('location_longitude') ?? $longitude, - 'zoom_level' => old('location_zoom_level') ?? $zoomLevel, - 'has_location' => $hasLocation || 'true' === old('location_has_location'), - ], - ]; + $location = $this->repository->getLocation($tag); + $latitude = $location instanceof Location ? $location->latitude : config('firefly.default_location.latitude'); + $longitude = $location instanceof Location ? $location->longitude : config('firefly.default_location.longitude'); + $zoomLevel = $location instanceof Location ? $location->zoom_level : config('firefly.default_location.zoom_level'); + $hasLocation = $location instanceof Location; + $locations = ['location' => [ + 'latitude' => old('location_latitude') ?? $latitude, + 'longitude' => old('location_longitude') ?? $longitude, + 'zoom_level' => old('location_zoom_level') ?? $zoomLevel, + 'has_location' => $hasLocation || 'true' === old('location_has_location') + ]]; // put previous url in session if not redirect from store (not "return_to_edit"). if (true !== session('tags.edit.fromUpdate')) { @@ -147,7 +141,7 @@ class TagController extends Controller } session()->forget('tags.edit.fromUpdate'); - return view('tags.edit', ['tag' => $tag, 'subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'locations' => $locations]); + return view('tags.edit', ['tag' => $tag, 'subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'locations' => $locations]); } /** @@ -158,9 +152,9 @@ class TagController extends Controller public function index(TagRepositoryInterface $repository): Factory|\Illuminate\Contracts\View\View { // start with the oldest tag - $first = session('first', today()) ?? today(); - $oldestTagDate = $repository->oldestTag() instanceof Tag ? $repository->oldestTag()->date : clone $first; - $newestTagDate = $repository->newestTag() instanceof Tag ? $repository->newestTag()->date : today(); + $first = session('first', today()) ?? today(); + $oldestTagDate = $repository->oldestTag() instanceof Tag ? $repository->oldestTag()->date : clone $first; + $newestTagDate = $repository->newestTag() instanceof Tag ? $repository->newestTag()->date : today(); $oldestTagDate->startOfYear(); $newestTagDate->endOfYear(); @@ -169,22 +163,22 @@ class TagController extends Controller request()->session()->flash('error', trans('firefly.bad_date_transaction')); } - $tags = []; + $tags = []; $tags['no-date'] = $repository->getTagsInYear(null); while ($newestTagDate > $oldestTagDate) { - $year = $newestTagDate->year; + $year = $newestTagDate->year; $tags[$year] = $repository->getTagsInYear($year); $newestTagDate->subYear(); } - $count = $repository->count(); + $count = $repository->count(); - return view('tags.index', ['tags' => $tags, 'count' => $count]); + return view('tags.index', ['tags' => $tags, 'count' => $count]); } public function massDestroy(Request $request): RedirectResponse { - $tags = $request->get('tags'); + $tags = $request->get('tags'); if (null === $tags || !is_array($tags)) { session()->flash('info', (string) trans('firefly.select_tags_to_delete')); @@ -227,40 +221,56 @@ class TagController extends Controller * @throws FireflyException * @throws NotFoundExceptionInterface */ - public function show(Request $request, Tag $tag, ?Carbon $start = null, ?Carbon $end = null): Factory|\Illuminate\Contracts\View\View + public function show(Request $request, Tag $tag, null|Carbon $start = null, null|Carbon $end = null): Factory|\Illuminate\Contracts\View\View { // default values: $subTitleIcon = 'fa-tag'; $page = (int) $request->get('page'); $pageSize = (int) Preferences::get('listPageSize', 50)->data; - $start ??= session('start'); - $end ??= session('end'); + $start ??= session('start'); + $end ??= session('end'); $location = $this->repository->getLocation($tag); $attachments = $this->repository->getAttachments($tag); - $subTitle = trans( - 'firefly.journals_in_period_for_tag', - [ - 'tag' => $tag->tag, - 'start' => $start->isoFormat($this->monthAndDayFormat), - 'end' => $end->isoFormat($this->monthAndDayFormat), - ] - ); + $subTitle = trans('firefly.journals_in_period_for_tag', [ + 'tag' => $tag->tag, + 'start' => $start->isoFormat($this->monthAndDayFormat), + 'end' => $end->isoFormat($this->monthAndDayFormat) + ]); - $startPeriod = $this->repository->firstUseDate($tag); + $startPeriod = $this->repository->firstUseDate($tag); $startPeriod ??= today(config('app.timezone')); - $endPeriod = clone $end; - $periods = $this->getTagPeriodOverview($tag, $startPeriod, $endPeriod); - $path = route('tags.show', [$tag->id, $start->format('Y-m-d'), $end->format('Y-m-d')]); + $endPeriod = clone $end; + $periods = $this->getTagPeriodOverview($tag, $startPeriod, $endPeriod); + $path = route('tags.show', [$tag->id, $start->format('Y-m-d'), $end->format('Y-m-d')]); /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); - $collector->setRange($start, $end)->setLimit($pageSize)->setPage($page)->withAccountInformation()->setTag($tag)->withBudgetInformation()->withCategoryInformation()->withAttachmentInformation(); - $groups = $collector->getPaginatedGroups(); + $collector + ->setRange($start, $end) + ->setLimit($pageSize) + ->setPage($page) + ->withAccountInformation() + ->setTag($tag) + ->withBudgetInformation() + ->withCategoryInformation() + ->withAttachmentInformation(); + $groups = $collector->getPaginatedGroups(); $groups->setPath($path); - $sums = $this->repository->sumsOfTag($tag, $start, $end); + $sums = $this->repository->sumsOfTag($tag, $start, $end); - return view('tags.show', ['tag' => $tag, 'attachments' => $attachments, 'sums' => $sums, 'periods' => $periods, 'subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'groups' => $groups, 'start' => $start, 'end' => $end, 'location' => $location]); + return view('tags.show', [ + 'tag' => $tag, + 'attachments' => $attachments, + 'sums' => $sums, + 'periods' => $periods, + 'subTitle' => $subTitle, + 'subTitleIcon' => $subTitleIcon, + 'groups' => $groups, + 'start' => $start, + 'end' => $end, + 'location' => $location + ]); } /** @@ -278,7 +288,7 @@ class TagController extends Controller $page = (int) $request->get('page'); $pageSize = (int) Preferences::get('listPageSize', 50)->data; $periods = []; - $subTitle = (string) trans('firefly.all_journals_for_tag', ['tag' => $tag->tag]); + $subTitle = (string) trans('firefly.all_journals_for_tag', ['tag' => $tag->tag]); $start = $this->repository->firstUseDate($tag) ?? today(config('app.timezone')); $end = $this->repository->lastUseDate($tag) ?? today(config('app.timezone')); $attachments = $this->repository->getAttachments($tag); @@ -286,16 +296,32 @@ class TagController extends Controller $location = $this->repository->getLocation($tag); /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); - $collector->setRange($start, $end)->setLimit($pageSize)->setPage($page)->withAccountInformation() - ->setTag($tag)->withBudgetInformation()->withCategoryInformation() - ->withAttachmentInformation() - ; - $groups = $collector->getPaginatedGroups(); + $collector = app(GroupCollectorInterface::class); + $collector + ->setRange($start, $end) + ->setLimit($pageSize) + ->setPage($page) + ->withAccountInformation() + ->setTag($tag) + ->withBudgetInformation() + ->withCategoryInformation() + ->withAttachmentInformation(); + $groups = $collector->getPaginatedGroups(); $groups->setPath($path); - $sums = $this->repository->sumsOfTag($tag, $start, $end); + $sums = $this->repository->sumsOfTag($tag, $start, $end); - return view('tags.show', ['tag' => $tag, 'attachments' => $attachments, 'sums' => $sums, 'periods' => $periods, 'subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'groups' => $groups, 'start' => $start, 'end' => $end, 'location' => $location]); + return view('tags.show', [ + 'tag' => $tag, + 'attachments' => $attachments, + 'sums' => $sums, + 'periods' => $periods, + 'subTitle' => $subTitle, + 'subTitleIcon' => $subTitleIcon, + 'groups' => $groups, + 'start' => $start, + 'end' => $end, + 'location' => $location + ]); } /** @@ -303,10 +329,10 @@ class TagController extends Controller */ public function store(TagFormRequest $request): RedirectResponse { - $data = $request->collectTagData(); + $data = $request->collectTagData(); Log::debug('Data from request', $data); - $result = $this->repository->store($data); + $result = $this->repository->store($data); Log::debug('Data after storage', $result->toArray()); session()->flash('success', (string) trans('firefly.created_tag', ['tag' => $data['tag']])); @@ -314,7 +340,7 @@ class TagController extends Controller // store attachment(s): /** @var null|array $files */ - $files = $request->hasFile('attachments') ? $request->file('attachments') : null; + $files = $request->hasFile('attachments') ? $request->file('attachments') : null; if (null !== $files && !auth()->user()->hasRole('demo')) { $this->attachmentsHelper->saveAttachmentsForModel($result, $files); } @@ -344,15 +370,15 @@ class TagController extends Controller */ public function update(TagFormRequest $request, Tag $tag): RedirectResponse { - $data = $request->collectTagData(); - $tag = $this->repository->update($tag, $data); + $data = $request->collectTagData(); + $tag = $this->repository->update($tag, $data); session()->flash('success', (string) trans('firefly.updated_tag', ['tag' => $data['tag']])); Preferences::mark(); // store new attachment(s): /** @var null|array $files */ - $files = $request->hasFile('attachments') ? $request->file('attachments') : null; + $files = $request->hasFile('attachments') ? $request->file('attachments') : null; if (null !== $files && !auth()->user()->hasRole('demo')) { $this->attachmentsHelper->saveAttachmentsForModel($tag, $files); } diff --git a/app/Http/Controllers/Transaction/BulkController.php b/app/Http/Controllers/Transaction/BulkController.php index 0e4e79bf00..d09f059e35 100644 --- a/app/Http/Controllers/Transaction/BulkController.php +++ b/app/Http/Controllers/Transaction/BulkController.php @@ -24,19 +24,19 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Transaction; -use FireflyIII\Support\Facades\Preferences; -use Illuminate\Support\Facades\Log; use FireflyIII\Events\UpdatedTransactionGroup; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Requests\BulkEditJournalRequest; use FireflyIII\Models\TransactionJournal; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Repositories\Journal\JournalRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use Illuminate\Contracts\Foundation\Application; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Routing\Redirector; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Log; use Illuminate\View\View; /** @@ -54,15 +54,13 @@ class BulkController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(JournalRepositoryInterface::class); - app('view')->share('title', (string) trans('firefly.transactions')); - app('view')->share('mainTitleIcon', 'fa-exchange'); + $this->middleware(function ($request, $next) { + $this->repository = app(JournalRepositoryInterface::class); + app('view')->share('title', (string) trans('firefly.transactions')); + app('view')->share('mainTitleIcon', 'fa-exchange'); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -74,7 +72,7 @@ class BulkController extends Controller */ public function edit(array $journals): Factory|\Illuminate\Contracts\View\View { - $subTitle = (string) trans('firefly.mass_bulk_journals'); + $subTitle = (string) trans('firefly.mass_bulk_journals'); $this->rememberPreviousUrl('transactions.bulk-edit.url'); @@ -85,7 +83,7 @@ class BulkController extends Controller $budgetRepos = app(BudgetRepositoryInterface::class); $budgetList = app('expandedform')->makeSelectListWithEmpty($budgetRepos->getActiveBudgets()); - return view('transactions.bulk.edit', ['journals' => $journals, 'subTitle' => $subTitle, 'budgetList' => $budgetList]); + return view('transactions.bulk.edit', ['journals' => $journals, 'subTitle' => $subTitle, 'budgetList' => $budgetList]); } /** diff --git a/app/Http/Controllers/Transaction/ConvertController.php b/app/Http/Controllers/Transaction/ConvertController.php index 603f622469..a1cf19e0ce 100644 --- a/app/Http/Controllers/Transaction/ConvertController.php +++ b/app/Http/Controllers/Transaction/ConvertController.php @@ -69,15 +69,13 @@ class ConvertController extends Controller parent::__construct(); // some useful repositories: - $this->middleware( - function ($request, $next) { - $this->accountRepository = app(AccountRepositoryInterface::class); - app('view')->share('title', (string) trans('firefly.transactions')); - app('view')->share('mainTitleIcon', 'fa-exchange'); + $this->middleware(function ($request, $next) { + $this->accountRepository = app(AccountRepositoryInterface::class); + app('view')->share('title', (string) trans('firefly.transactions')); + app('view')->share('mainTitleIcon', 'fa-exchange'); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -94,16 +92,16 @@ class ConvertController extends Controller } /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); /** @var TransactionJournal $first */ - $first = $group->transactionJournals()->first(); - $sourceType = $first->transactionType; + $first = $group->transactionJournals()->first(); + $sourceType = $first->transactionType; - $groupTitle = $group->title ?? $first->description; - $groupArray = $transformer->transformObject($group); - $subTitle = (string) trans('firefly.convert_to_'.$destinationType->type, ['description' => $groupTitle]); - $subTitleIcon = 'fa-exchange'; + $groupTitle = $group->title ?? $first->description; + $groupArray = $transformer->transformObject($group); + $subTitle = (string) trans('firefly.convert_to_' . $destinationType->type, ['description' => $groupTitle]); + $subTitleIcon = 'fa-exchange'; // get a list of asset accounts and liabilities and stuff, in various combinations: $validDepositSources = $this->getValidDepositSources(); @@ -112,44 +110,56 @@ class ConvertController extends Controller $assets = $this->getAssetAccounts(); // old input variables: - $preFilled = [ - 'source_name' => old('source_name'), - ]; + $preFilled = ['source_name' => old('source_name')]; if ($sourceType->type === $destinationType->type) { // cannot convert to its own type. Log::debug('This is already a transaction of the expected type..'); - session()->flash('info', (string) trans('firefly.convert_is_already_type_'.$destinationType->type)); + session()->flash('info', (string) trans('firefly.convert_is_already_type_' . $destinationType->type)); return redirect(route('transactions.show', [$group->id])); } - return view( - 'transactions.convert', - ['sourceType' => $sourceType, 'destinationType' => $destinationType, 'group' => $group, 'groupTitle' => $groupTitle, 'groupArray' => $groupArray, 'assets' => $assets, 'validDepositSources' => $validDepositSources, 'liabilities' => $liabilities, 'validWithdrawalDests' => $validWithdrawalDests, 'preFilled' => $preFilled, 'subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon] - ); + return view('transactions.convert', [ + 'sourceType' => $sourceType, + 'destinationType' => $destinationType, + 'group' => $group, + 'groupTitle' => $groupTitle, + 'groupArray' => $groupArray, + 'assets' => $assets, + 'validDepositSources' => $validDepositSources, + 'liabilities' => $liabilities, + 'validWithdrawalDests' => $validWithdrawalDests, + 'preFilled' => $preFilled, + 'subTitle' => $subTitle, + 'subTitleIcon' => $subTitleIcon + ]); } private function getValidDepositSources(): array { // make repositories $liabilityTypes = [AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::CREDITCARD->value, AccountTypeEnum::LOAN->value]; - $accountList = $this->accountRepository - ->getActiveAccountsByType([AccountTypeEnum::REVENUE->value, AccountTypeEnum::CASH->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value]) - ; + $accountList = $this->accountRepository->getActiveAccountsByType([ + AccountTypeEnum::REVENUE->value, + AccountTypeEnum::CASH->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::MORTGAGE->value + ]); $grouped = []; // group accounts: /** @var Account $account */ foreach ($accountList as $account) { - $role = (string) $this->accountRepository->getMetaValue($account, 'account_role'); - $name = $account->name; + $role = (string) $this->accountRepository->getMetaValue($account, 'account_role'); + $name = $account->name; if ('' === $role) { $role = 'no_account_type'; } // maybe it's a liability thing: if (in_array($account->accountType->type, $liabilityTypes, true)) { - $role = 'l_'.$account->accountType->type; + $role = 'l_' . $account->accountType->type; } if (AccountTypeEnum::CASH->value === $account->accountType->type) { $role = 'cash_account'; @@ -159,7 +169,7 @@ class ConvertController extends Controller $role = 'revenue_account'; } - $key = (string) trans('firefly.opt_group_'.$role); + $key = (string) trans('firefly.opt_group_' . $role); $grouped[$key][$account->id] = $name; } @@ -170,23 +180,27 @@ class ConvertController extends Controller { // make repositories $liabilityTypes = [AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::CREDITCARD->value, AccountTypeEnum::LOAN->value]; - $accountList = $this->accountRepository->getActiveAccountsByType( - [AccountTypeEnum::EXPENSE->value, AccountTypeEnum::CASH->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value] - ); + $accountList = $this->accountRepository->getActiveAccountsByType([ + AccountTypeEnum::EXPENSE->value, + AccountTypeEnum::CASH->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::MORTGAGE->value + ]); $grouped = []; // group accounts: /** @var Account $account */ foreach ($accountList as $account) { - $role = (string) $this->accountRepository->getMetaValue($account, 'account_role'); - $name = $account->name; + $role = (string) $this->accountRepository->getMetaValue($account, 'account_role'); + $name = $account->name; if ('' === $role) { $role = 'no_account_type'; } // maybe it's a liability thing: if (in_array($account->accountType->type, $liabilityTypes, true)) { - $role = 'l_'.$account->accountType->type; + $role = 'l_' . $account->accountType->type; } if (AccountTypeEnum::CASH->value === $account->accountType->type) { $role = 'cash_account'; @@ -196,7 +210,7 @@ class ConvertController extends Controller $role = 'expense_account'; } - $key = (string) trans('firefly.opt_group_'.$role); + $key = (string) trans('firefly.opt_group_' . $role); $grouped[$key][$account->id] = $name; } @@ -209,20 +223,24 @@ class ConvertController extends Controller private function getLiabilities(): array { // make repositories - $accountList = $this->accountRepository->getActiveAccountsByType([AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value]); + $accountList = $this->accountRepository->getActiveAccountsByType([ + AccountTypeEnum::LOAN->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::MORTGAGE->value + ]); $grouped = []; // group accounts: /** @var Account $account */ foreach ($accountList as $account) { - $date = today()->endOfDay(); + $date = today()->endOfDay(); Log::debug(sprintf('getLiabilities: Call finalAccountBalance with date/time "%s"', $date->toIso8601String())); // 2025-10-08 replace finalAccountBalance with accountsBalancesOptimized. // $balance = Steam::finalAccountBalance($account, $date)['balance']; - $balance = Steam::accountsBalancesOptimized(new Collection()->push($account), $date)[$account->id]['balance'] ?? '0'; - $currency = $this->accountRepository->getAccountCurrency($account) ?? $this->primaryCurrency; - $role = sprintf('l_%s', $account->accountType->type); - $key = (string) trans(sprintf('firefly.opt_group_%s', $role)); + $balance = Steam::accountsBalancesOptimized(new Collection()->push($account), $date)[$account->id]['balance'] ?? '0'; + $currency = $this->accountRepository->getAccountCurrency($account) ?? $this->primaryCurrency; + $role = sprintf('l_%s', $account->accountType->type); + $key = (string) trans(sprintf('firefly.opt_group_%s', $role)); $grouped[$key][$account->id] = sprintf('%s (%s)', $account->name, Amount::formatAnything($currency, $balance, false)); } @@ -241,19 +259,19 @@ class ConvertController extends Controller // group accounts: /** @var Account $account */ foreach ($accountList as $account) { - $date = today()->endOfDay(); + $date = today()->endOfDay(); Log::debug(sprintf('getAssetAccounts: Call finalAccountBalance with date/time "%s"', $date->toIso8601String())); // 2025-10-08 replace finalAccountBalance with accountsBalancesOptimized. // $balance = Steam::finalAccountBalance($account, $date)['balance']; - $balance = Steam::accountsBalancesOptimized(new Collection()->push($account), $date)[$account->id]['balance'] ?? '0'; + $balance = Steam::accountsBalancesOptimized(new Collection()->push($account), $date)[$account->id]['balance'] ?? '0'; - $currency = $this->accountRepository->getAccountCurrency($account) ?? $this->primaryCurrency; - $role = (string) $this->accountRepository->getMetaValue($account, 'account_role'); + $currency = $this->accountRepository->getAccountCurrency($account) ?? $this->primaryCurrency; + $role = (string) $this->accountRepository->getMetaValue($account, 'account_role'); if ('' === $role) { $role = 'no_account_type'; } - $key = (string) trans(sprintf('firefly.opt_group_%s', $role)); + $key = (string) trans(sprintf('firefly.opt_group_%s', $role)); $grouped[$key][$account->id] = sprintf('%s (%s)', $account->name, Amount::formatAnything($currency, $balance, false)); } @@ -286,7 +304,7 @@ class ConvertController extends Controller // correct transfers: $group->refresh(); - session()->flash('success', (string) trans('firefly.converted_to_'.$destinationType->type)); + session()->flash('success', (string) trans('firefly.converted_to_' . $destinationType->type)); event(new UpdatedTransactionGroup($group, true, true, true)); return redirect(route('transactions.show', [$group->id])); @@ -298,22 +316,22 @@ class ConvertController extends Controller private function convertJournal(TransactionJournal $journal, TransactionType $transactionType, array $data): TransactionJournal { /** @var AccountValidator $validator */ - $validator = app(AccountValidator::class); + $validator = app(AccountValidator::class); $validator->setUser(auth()->user()); $validator->setTransactionType($transactionType->type); - $sourceId = $data['source_id'][$journal->id] ?? null; - $sourceName = $data['source_name'][$journal->id] ?? null; - $destinationId = $data['destination_id'][$journal->id] ?? null; - $destinationName = $data['destination_name'][$journal->id] ?? null; + $sourceId = $data['source_id'][$journal->id] ?? null; + $sourceName = $data['source_name'][$journal->id] ?? null; + $destinationId = $data['destination_id'][$journal->id] ?? null; + $destinationName = $data['destination_name'][$journal->id] ?? null; // double check it's not an empty string. - $sourceId = '' === $sourceId || null === $sourceId ? null : (int) $sourceId; - $sourceName = '' === $sourceName ? null : (string) $sourceName; - $destinationId = '' === $destinationId || null === $destinationId ? null : (int) $destinationId; - $destinationName = '' === $destinationName ? null : (string) $destinationName; - $validSource = $validator->validateSource(['id' => $sourceId, 'name' => $sourceName]); - $validDestination = $validator->validateDestination(['id' => $destinationId, 'name' => $destinationName]); + $sourceId = '' === $sourceId || null === $sourceId ? null : (int) $sourceId; + $sourceName = '' === $sourceName ? null : (string) $sourceName; + $destinationId = '' === $destinationId || null === $destinationId ? null : (int) $destinationId; + $destinationName = '' === $destinationName ? null : (string) $destinationName; + $validSource = $validator->validateSource(['id' => $sourceId, 'name' => $sourceName]); + $validDestination = $validator->validateDestination(['id' => $destinationId, 'name' => $destinationName]); if (false === $validSource) { throw new FireflyException(sprintf(trans('firefly.convert_invalid_source'), $journal->id)); @@ -324,12 +342,12 @@ class ConvertController extends Controller // TODO typeOverrule: the account validator may have another opinion on the transaction type. - $update = [ + $update = [ 'source_id' => $sourceId, 'source_name' => $sourceName, 'destination_id' => $destinationId, 'destination_name' => $destinationName, - 'type' => $transactionType->type, + 'type' => $transactionType->type ]; /** @var null|Transaction $sourceTransaction */ @@ -342,10 +360,14 @@ class ConvertController extends Controller $sourceCurrency = $this->accountRepository->getAccountCurrency($source); $dest = $this->accountRepository->find((int) $destinationId); $destCurrency = $this->accountRepository->getAccountCurrency($dest); - if ($sourceCurrency instanceof TransactionCurrency && $destCurrency instanceof TransactionCurrency && $sourceCurrency->code !== $destCurrency->code) { - $update['currency_id'] = $sourceCurrency->id; + if ( + $sourceCurrency instanceof TransactionCurrency + && $destCurrency instanceof TransactionCurrency + && $sourceCurrency->code !== $destCurrency->code + ) { + $update['currency_id'] = $sourceCurrency->id; $update['foreign_currency_id'] = $destCurrency->id; - $update['foreign_amount'] = Steam::positive($amount); // not the best solution but at this point the amount is hard to get. + $update['foreign_amount'] = Steam::positive($amount); // not the best solution but at this point the amount is hard to get. } } @@ -355,15 +377,19 @@ class ConvertController extends Controller $sourceCurrency = $this->accountRepository->getAccountCurrency($source); $dest = $this->accountRepository->find((int) $destinationId); $destCurrency = $this->accountRepository->getAccountCurrency($dest); - if ($sourceCurrency instanceof TransactionCurrency && $destCurrency instanceof TransactionCurrency && $sourceCurrency->code !== $destCurrency->code) { - $update['currency_id'] = $sourceCurrency->id; + if ( + $sourceCurrency instanceof TransactionCurrency + && $destCurrency instanceof TransactionCurrency + && $sourceCurrency->code !== $destCurrency->code + ) { + $update['currency_id'] = $sourceCurrency->id; $update['foreign_currency_id'] = $destCurrency->id; - $update['foreign_amount'] = Steam::positive($amount); // not the best solution but at this point the amount is hard to get. + $update['foreign_amount'] = Steam::positive($amount); // not the best solution but at this point the amount is hard to get. } } /** @var JournalUpdateService $service */ - $service = app(JournalUpdateService::class); + $service = app(JournalUpdateService::class); $service->setTransactionJournal($journal); $service->setData($update); $service->update(); diff --git a/app/Http/Controllers/Transaction/CreateController.php b/app/Http/Controllers/Transaction/CreateController.php index 499c033008..2fa4748b53 100644 --- a/app/Http/Controllers/Transaction/CreateController.php +++ b/app/Http/Controllers/Transaction/CreateController.php @@ -30,6 +30,7 @@ use FireflyIII\Models\TransactionGroup; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\TransactionGroup\TransactionGroupRepositoryInterface; use FireflyIII\Services\Internal\Update\GroupCloneService; +use FireflyIII\Support\Facades\FireflyConfig; use FireflyIII\Support\Facades\Preferences; use Illuminate\Contracts\View\Factory; use Illuminate\Contracts\View\View; @@ -38,7 +39,6 @@ use Illuminate\Http\Request; use Psr\Container\ContainerExceptionInterface; use Psr\Container\NotFoundExceptionInterface; use Safe\Exceptions\UrlException; -use FireflyIII\Support\Facades\FireflyConfig; use function Safe\parse_url; @@ -56,15 +56,13 @@ class CreateController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.transactions')); - app('view')->share('mainTitleIcon', 'fa-exchange'); - $this->repository = app(TransactionGroupRepositoryInterface::class); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.transactions')); + app('view')->share('mainTitleIcon', 'fa-exchange'); + $this->repository = app(TransactionGroupRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } public function cloneGroup(Request $request): JsonResponse @@ -82,8 +80,8 @@ class CreateController extends Controller Preferences::mark(); - $title = $newGroup->title ?? $newGroup->transactionJournals->first()->description; - $link = route('transactions.show', [$newGroup->id]); + $title = $newGroup->title ?? $newGroup->transactionJournals->first()->description; + $link = route('transactions.show', [$newGroup->id]); session()->flash('success', trans('firefly.stored_journal', ['description' => $title])); session()->flash('success_url', $link); @@ -105,51 +103,68 @@ class CreateController extends Controller * @throws NotFoundExceptionInterface * @throws UrlException */ - public function create(?string $objectType): Factory|View + public function create(null|string $objectType): Factory|View { Preferences::mark(); - $sourceId = (int) request()->get('source'); - $destinationId = (int) request()->get('destination'); + $sourceId = (int) request()->get('source'); + $destinationId = (int) request()->get('destination'); /** @var AccountRepositoryInterface $accountRepository */ - $accountRepository = app(AccountRepositoryInterface::class); - $cash = $accountRepository->getCashAccount(); - $preFilled = session()->has('preFilled') ? session('preFilled') : []; - $subTitle = (string) trans(sprintf('breadcrumbs.create_%s', strtolower((string) $objectType))); - $subTitleIcon = 'fa-plus'; + $accountRepository = app(AccountRepositoryInterface::class); + $cash = $accountRepository->getCashAccount(); + $preFilled = session()->has('preFilled') ? session('preFilled') : []; + $subTitle = (string) trans(sprintf('breadcrumbs.create_%s', strtolower((string) $objectType))); + $subTitleIcon = 'fa-plus'; /** @var null|array $optionalFields */ - $optionalFields = Preferences::get('transaction_journal_optional_fields', [])->data; - $allowedOpposingTypes = config('firefly.allowed_opposing_types'); - $accountToTypes = config('firefly.account_to_transaction'); - $previousUrl = $this->rememberPreviousUrl('transactions.create.url'); - $parts = parse_url((string) $previousUrl); - $search = sprintf('?%s', $parts['query'] ?? ''); - $previousUrl = str_replace($search, '', $previousUrl); + $optionalFields = Preferences::get('transaction_journal_optional_fields', [])->data; + $allowedOpposingTypes = config('firefly.allowed_opposing_types'); + $accountToTypes = config('firefly.account_to_transaction'); + $previousUrl = $this->rememberPreviousUrl('transactions.create.url'); + $parts = parse_url((string) $previousUrl); + $search = sprintf('?%s', $parts['query'] ?? ''); + $previousUrl = str_replace($search, '', $previousUrl); if (!is_array($optionalFields)) { $optionalFields = []; } // not really a fan of this, but meh. - $optionalDateFields = [ + $optionalDateFields = [ 'interest_date' => $optionalFields['interest_date'] ?? false, 'book_date' => $optionalFields['book_date'] ?? false, 'process_date' => $optionalFields['process_date'] ?? false, 'due_date' => $optionalFields['due_date'] ?? false, 'payment_date' => $optionalFields['payment_date'] ?? false, - 'invoice_date' => $optionalFields['invoice_date'] ?? false, + 'invoice_date' => $optionalFields['invoice_date'] ?? false ]; $optionalFields['external_url'] ??= false; - $optionalFields['location'] ??= false; - $optionalFields['location'] = $optionalFields['location'] && true === FireflyConfig::get('enable_external_map', config('firefly.enable_external_map'))->data; + $optionalFields['location'] ??= false; + $optionalFields['location'] = + $optionalFields['location'] && true === FireflyConfig::get('enable_external_map', config('firefly.enable_external_map'))->data; // map info: - $longitude = config('firefly.default_location.longitude'); - $latitude = config('firefly.default_location.latitude'); - $zoomLevel = config('firefly.default_location.zoom_level'); + $longitude = config('firefly.default_location.longitude'); + $latitude = config('firefly.default_location.latitude'); + $zoomLevel = config('firefly.default_location.zoom_level'); session()->put('preFilled', $preFilled); - return view('transactions.create', ['subTitleIcon' => $subTitleIcon, 'cash' => $cash, 'longitude' => $longitude, 'latitude' => $latitude, 'zoomLevel' => $zoomLevel, 'objectType' => $objectType, 'optionalDateFields' => $optionalDateFields, 'subTitle' => $subTitle, 'previousUrl' => $previousUrl, 'optionalFields' => $optionalFields, 'preFilled' => $preFilled, 'allowedOpposingTypes' => $allowedOpposingTypes, 'accountToTypes' => $accountToTypes, 'sourceId' => $sourceId, 'destinationId' => $destinationId]); + return view('transactions.create', [ + 'subTitleIcon' => $subTitleIcon, + 'cash' => $cash, + 'longitude' => $longitude, + 'latitude' => $latitude, + 'zoomLevel' => $zoomLevel, + 'objectType' => $objectType, + 'optionalDateFields' => $optionalDateFields, + 'subTitle' => $subTitle, + 'previousUrl' => $previousUrl, + 'optionalFields' => $optionalFields, + 'preFilled' => $preFilled, + 'allowedOpposingTypes' => $allowedOpposingTypes, + 'accountToTypes' => $accountToTypes, + 'sourceId' => $sourceId, + 'destinationId' => $destinationId + ]); } } diff --git a/app/Http/Controllers/Transaction/DeleteController.php b/app/Http/Controllers/Transaction/DeleteController.php index b43bcf4249..702d58c6f2 100644 --- a/app/Http/Controllers/Transaction/DeleteController.php +++ b/app/Http/Controllers/Transaction/DeleteController.php @@ -24,8 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Transaction; -use FireflyIII\Support\Facades\Preferences; -use Illuminate\Support\Facades\Log; use FireflyIII\Events\UpdatedAccount; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\Account; @@ -33,12 +31,14 @@ use FireflyIII\Models\Transaction; use FireflyIII\Models\TransactionGroup; use FireflyIII\Models\TransactionJournal; use FireflyIII\Repositories\TransactionGroup\TransactionGroupRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; +use FireflyIII\Support\Facades\Steam; use Illuminate\Contracts\View\Factory; use Illuminate\Contracts\View\View; use Illuminate\Http\RedirectResponse; use Illuminate\Routing\Redirector; +use Illuminate\Support\Facades\Log; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; -use FireflyIII\Support\Facades\Steam; /** * Class DeleteController @@ -55,16 +55,14 @@ class DeleteController extends Controller parent::__construct(); // translations: - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.transactions')); - app('view')->share('mainTitleIcon', 'fa-exchange'); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.transactions')); + app('view')->share('mainTitleIcon', 'fa-exchange'); - $this->repository = app(TransactionGroupRepositoryInterface::class); + $this->repository = app(TransactionGroupRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -78,18 +76,24 @@ class DeleteController extends Controller Log::debug(sprintf('Start of delete view for group #%d', $group->id)); - $journal = $group->transactionJournals->first(); + $journal = $group->transactionJournals->first(); if (null === $journal) { throw new NotFoundHttpException(); } $objectType = strtolower($journal->transaction_type_type ?? $journal->transactionType->type); - $subTitle = (string) trans('firefly.delete_'.$objectType, ['description' => $group->title ?? $journal->description]); + $subTitle = (string) trans('firefly.delete_' . $objectType, ['description' => $group->title ?? $journal->description]); $previous = Steam::getSafePreviousUrl(); // put previous url in session Log::debug('Will try to remember previous URL'); $this->rememberPreviousUrl('transactions.delete.url'); - return view('transactions.delete', ['group' => $group, 'journal' => $journal, 'subTitle' => $subTitle, 'objectType' => $objectType, 'previous' => $previous]); + return view('transactions.delete', [ + 'group' => $group, + 'journal' => $journal, + 'subTitle' => $subTitle, + 'objectType' => $objectType, + 'previous' => $previous + ]); } /** @@ -102,15 +106,15 @@ class DeleteController extends Controller return $this->redirectGroupToAccount($group); } - $journal = $group->transactionJournals->first(); + $journal = $group->transactionJournals->first(); if (null === $journal) { throw new NotFoundHttpException(); } $objectType = strtolower($journal->transaction_type_type ?? $journal->transactionType->type); - session()->flash('success', (string) trans('firefly.deleted_'.strtolower($objectType), ['description' => $group->title ?? $journal->description])); + session()->flash('success', (string) trans('firefly.deleted_' . strtolower($objectType), ['description' => $group->title ?? $journal->description])); // grab asset account(s) from group: - $accounts = []; + $accounts = []; /** @var TransactionJournal $currentJournal */ foreach ($group->transactionJournals as $currentJournal) { diff --git a/app/Http/Controllers/Transaction/EditController.php b/app/Http/Controllers/Transaction/EditController.php index c7064c8459..0314470867 100644 --- a/app/Http/Controllers/Transaction/EditController.php +++ b/app/Http/Controllers/Transaction/EditController.php @@ -24,12 +24,13 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Transaction; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\TransactionGroup; use FireflyIII\Models\TransactionJournal; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Journal\JournalRepositoryInterface; +use FireflyIII\Support\Facades\FireflyConfig; +use FireflyIII\Support\Facades\Preferences; use Illuminate\Contracts\View\Factory; use Illuminate\Http\JsonResponse; use Illuminate\Http\RedirectResponse; @@ -38,7 +39,6 @@ use Illuminate\View\View; use Psr\Container\ContainerExceptionInterface; use Psr\Container\NotFoundExceptionInterface; use Safe\Exceptions\UrlException; -use FireflyIII\Support\Facades\FireflyConfig; use function Safe\parse_url; @@ -57,16 +57,14 @@ class EditController extends Controller parent::__construct(); // translations: - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.transactions')); - app('view')->share('mainTitleIcon', 'fa-exchange'); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.transactions')); + app('view')->share('mainTitleIcon', 'fa-exchange'); - $this->repository = app(JournalRepositoryInterface::class); + $this->repository = app(JournalRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -85,44 +83,62 @@ class EditController extends Controller } /** @var AccountRepositoryInterface $repository */ - $repository = app(AccountRepositoryInterface::class); - $allowedOpposingTypes = config('firefly.allowed_opposing_types'); - $accountToTypes = config('firefly.account_to_transaction'); - $expectedSourceTypes = config('firefly.expected_source_types'); - $allowedSourceDests = config('firefly.source_dests'); - $title = $transactionGroup->transactionJournals()->count() > 1 ? $transactionGroup->title : $transactionGroup->transactionJournals()->first()->description; - $subTitle = (string) trans('firefly.edit_transaction_title', ['description' => $title]); - $subTitleIcon = 'fa-plus'; - $cash = $repository->getCashAccount(); - $previousUrl = $this->rememberPreviousUrl('transactions.edit.url'); - $parts = parse_url((string) $previousUrl); - $search = sprintf('?%s', $parts['query'] ?? ''); - $previousUrl = str_replace($search, '', $previousUrl); + $repository = app(AccountRepositoryInterface::class); + $allowedOpposingTypes = config('firefly.allowed_opposing_types'); + $accountToTypes = config('firefly.account_to_transaction'); + $expectedSourceTypes = config('firefly.expected_source_types'); + $allowedSourceDests = config('firefly.source_dests'); + $title = $transactionGroup->transactionJournals()->count() > 1 + ? $transactionGroup->title + : $transactionGroup->transactionJournals()->first()->description; + $subTitle = (string) trans('firefly.edit_transaction_title', ['description' => $title]); + $subTitleIcon = 'fa-plus'; + $cash = $repository->getCashAccount(); + $previousUrl = $this->rememberPreviousUrl('transactions.edit.url'); + $parts = parse_url((string) $previousUrl); + $search = sprintf('?%s', $parts['query'] ?? ''); + $previousUrl = str_replace($search, '', $previousUrl); // settings necessary for v2 - $optionalFields = Preferences::get('transaction_journal_optional_fields', [])->data; + $optionalFields = Preferences::get('transaction_journal_optional_fields', [])->data; if (!is_array($optionalFields)) { $optionalFields = []; } // not really a fan of this, but meh. - $optionalDateFields = [ + $optionalDateFields = [ 'interest_date' => $optionalFields['interest_date'] ?? false, 'book_date' => $optionalFields['book_date'] ?? false, 'process_date' => $optionalFields['process_date'] ?? false, 'due_date' => $optionalFields['due_date'] ?? false, 'payment_date' => $optionalFields['payment_date'] ?? false, - 'invoice_date' => $optionalFields['invoice_date'] ?? false, + 'invoice_date' => $optionalFields['invoice_date'] ?? false ]; $optionalFields['external_url'] ??= false; - $optionalFields['location'] ??= false; - $optionalFields['location'] = $optionalFields['location'] && true === FireflyConfig::get('enable_external_map', config('firefly.enable_external_map'))->data; + $optionalFields['location'] ??= false; + $optionalFields['location'] = + $optionalFields['location'] && true === FireflyConfig::get('enable_external_map', config('firefly.enable_external_map'))->data; // map info voor v2: - $longitude = config('firefly.default_location.longitude'); - $latitude = config('firefly.default_location.latitude'); - $zoomLevel = config('firefly.default_location.zoom_level'); + $longitude = config('firefly.default_location.longitude'); + $latitude = config('firefly.default_location.latitude'); + $zoomLevel = config('firefly.default_location.zoom_level'); - return view('transactions.edit', ['cash' => $cash, 'allowedSourceDests' => $allowedSourceDests, 'expectedSourceTypes' => $expectedSourceTypes, 'optionalDateFields' => $optionalDateFields, 'longitude' => $longitude, 'latitude' => $latitude, 'zoomLevel' => $zoomLevel, 'optionalFields' => $optionalFields, 'subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon, 'transactionGroup' => $transactionGroup, 'allowedOpposingTypes' => $allowedOpposingTypes, 'accountToTypes' => $accountToTypes, 'previousUrl' => $previousUrl]); + return view('transactions.edit', [ + 'cash' => $cash, + 'allowedSourceDests' => $allowedSourceDests, + 'expectedSourceTypes' => $expectedSourceTypes, + 'optionalDateFields' => $optionalDateFields, + 'longitude' => $longitude, + 'latitude' => $latitude, + 'zoomLevel' => $zoomLevel, + 'optionalFields' => $optionalFields, + 'subTitle' => $subTitle, + 'subTitleIcon' => $subTitleIcon, + 'transactionGroup' => $transactionGroup, + 'allowedOpposingTypes' => $allowedOpposingTypes, + 'accountToTypes' => $accountToTypes, + 'previousUrl' => $previousUrl + ]); } public function unreconcile(TransactionJournal $journal): JsonResponse diff --git a/app/Http/Controllers/Transaction/IndexController.php b/app/Http/Controllers/Transaction/IndexController.php index dfb3672429..c65681dc2b 100644 --- a/app/Http/Controllers/Transaction/IndexController.php +++ b/app/Http/Controllers/Transaction/IndexController.php @@ -55,16 +55,14 @@ class IndexController extends Controller parent::__construct(); app('view')->share('showCategory', true); // translations: - $this->middleware( - function ($request, $next) { - app('view')->share('mainTitleIcon', 'fa-exchange'); - app('view')->share('title', (string)trans('firefly.transactions')); + $this->middleware(function ($request, $next) { + app('view')->share('mainTitleIcon', 'fa-exchange'); + app('view')->share('title', (string) trans('firefly.transactions')); - $this->repository = app(JournalRepositoryInterface::class); + $this->repository = app(JournalRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -76,16 +74,16 @@ class IndexController extends Controller * @throws FireflyException * @throws NotFoundExceptionInterface */ - public function index(Request $request, string $objectType, ?Carbon $start = null, ?Carbon $end = null): Factory|\Illuminate\Contracts\View\View + public function index(Request $request, string $objectType, null|Carbon $start = null, null|Carbon $end = null): Factory|\Illuminate\Contracts\View\View { if ('transfers' === $objectType) { $objectType = 'transfer'; } - $subTitleIcon = config('firefly.transactionIconsByType.'.$objectType); - $types = config('firefly.transactionTypesByType.'.$objectType); - $page = (int)$request->get('page'); - $pageSize = (int)Preferences::get('listPageSize', 50)->data; + $subTitleIcon = config('firefly.transactionIconsByType.' . $objectType); + $types = config('firefly.transactionTypesByType.' . $objectType); + $page = (int) $request->get('page'); + $pageSize = (int) Preferences::get('listPageSize', 50)->data; if (!$start instanceof Carbon) { $start = session('start'); @@ -98,37 +96,45 @@ class IndexController extends Controller } [$start, $end] = $end < $start ? [$end, $start] : [$start, $end]; - $startStr = $start->isoFormat($this->monthAndDayFormat); - $endStr = $end->isoFormat($this->monthAndDayFormat); - $subTitle = (string)trans(sprintf('firefly.title_%s_between', $objectType), ['start' => $startStr, 'end' => $endStr]); - $path = route('transactions.index', [$objectType, $start->format('Y-m-d'), $end->format('Y-m-d')]); - $firstJournal = $this->repository->firstNull(); - $startPeriod = $firstJournal instanceof TransactionJournal ? $firstJournal->date : new Carbon(); - $endPeriod = clone $end; + $startStr = $start->isoFormat($this->monthAndDayFormat); + $endStr = $end->isoFormat($this->monthAndDayFormat); + $subTitle = (string) trans(sprintf('firefly.title_%s_between', $objectType), ['start' => $startStr, 'end' => $endStr]); + $path = route('transactions.index', [$objectType, $start->format('Y-m-d'), $end->format('Y-m-d')]); + $firstJournal = $this->repository->firstNull(); + $startPeriod = $firstJournal instanceof TransactionJournal ? $firstJournal->date : new Carbon(); + $endPeriod = clone $end; // limit to 3 years for the time being. if (now()->diffInYears($startPeriod, true) > 3) { $startPeriod = now()->subYears(3); } - $periods = $this->getTransactionPeriodOverview($objectType, $startPeriod, $endPeriod); + $periods = $this->getTransactionPeriodOverview($objectType, $startPeriod, $endPeriod); /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); - $collector->setRange($start, $end) + $collector + ->setRange($start, $end) ->setTypes($types) ->setLimit($pageSize) ->setPage($page) ->withBudgetInformation() ->withCategoryInformation() ->withAccountInformation() - ->withAttachmentInformation() - ; - $groups = $collector->getPaginatedGroups(); + ->withAttachmentInformation(); + $groups = $collector->getPaginatedGroups(); $groups->setPath($path); - return view('transactions.index', ['subTitle' => $subTitle, 'objectType' => $objectType, 'subTitleIcon' => $subTitleIcon, 'groups' => $groups, 'periods' => $periods, 'start' => $start, 'end' => $end]); + return view('transactions.index', [ + 'subTitle' => $subTitle, + 'objectType' => $objectType, + 'subTitleIcon' => $subTitleIcon, + 'groups' => $groups, + 'periods' => $periods, + 'start' => $start, + 'end' => $end + ]); } /** @@ -141,32 +147,39 @@ class IndexController extends Controller */ public function indexAll(Request $request, string $objectType): Factory|\Illuminate\Contracts\View\View { - $subTitleIcon = config('firefly.transactionIconsByType.'.$objectType); - $types = config('firefly.transactionTypesByType.'.$objectType); - $page = (int)$request->get('page'); - $pageSize = (int)Preferences::get('listPageSize', 50)->data; + $subTitleIcon = config('firefly.transactionIconsByType.' . $objectType); + $types = config('firefly.transactionTypesByType.' . $objectType); + $page = (int) $request->get('page'); + $pageSize = (int) Preferences::get('listPageSize', 50)->data; $path = route('transactions.index.all', [$objectType]); $first = $this->repository->firstNull(); $start = $first instanceof TransactionJournal ? $first->date : new Carbon(); $last = $this->repository->getLast(); $end = $last instanceof TransactionJournal ? $last->date : today(config('app.timezone')); - $subTitle = (string)trans('firefly.all_'.$objectType); + $subTitle = (string) trans('firefly.all_' . $objectType); /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); - $collector->setRange($start, $end) + $collector + ->setRange($start, $end) ->setTypes($types) ->setLimit($pageSize) ->setPage($page) ->withAccountInformation() ->withBudgetInformation() ->withCategoryInformation() - ->withAttachmentInformation() - ; - $groups = $collector->getPaginatedGroups(); + ->withAttachmentInformation(); + $groups = $collector->getPaginatedGroups(); $groups->setPath($path); - return view('transactions.index', ['subTitle' => $subTitle, 'objectType' => $objectType, 'subTitleIcon' => $subTitleIcon, 'groups' => $groups, 'start' => $start, 'end' => $end]); + return view('transactions.index', [ + 'subTitle' => $subTitle, + 'objectType' => $objectType, + 'subTitleIcon' => $subTitleIcon, + 'groups' => $groups, + 'start' => $start, + 'end' => $end + ]); } } diff --git a/app/Http/Controllers/Transaction/LinkController.php b/app/Http/Controllers/Transaction/LinkController.php index e2913308b7..7474558f83 100644 --- a/app/Http/Controllers/Transaction/LinkController.php +++ b/app/Http/Controllers/Transaction/LinkController.php @@ -23,27 +23,27 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Transaction; -use FireflyIII\Support\Facades\Preferences; -use Illuminate\Support\Facades\Log; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Requests\JournalLinkRequest; use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionJournalLink; use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Repositories\LinkType\LinkTypeRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; +use FireflyIII\Support\Facades\Steam; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Routing\Redirector; +use Illuminate\Support\Facades\Log; use Illuminate\View\View; -use FireflyIII\Support\Facades\Steam; /** * Class LinkController. */ class LinkController extends Controller { - private JournalRepositoryInterface $journalRepository; + private JournalRepositoryInterface $journalRepository; private LinkTypeRepositoryInterface $repository; /** @@ -53,17 +53,15 @@ class LinkController extends Controller { parent::__construct(); // some useful repositories: - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.transactions')); - app('view')->share('mainTitleIcon', 'fa-exchange'); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.transactions')); + app('view')->share('mainTitleIcon', 'fa-exchange'); - $this->journalRepository = app(JournalRepositoryInterface::class); - $this->repository = app(LinkTypeRepositoryInterface::class); + $this->journalRepository = app(JournalRepositoryInterface::class); + $this->repository = app(LinkTypeRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -77,7 +75,7 @@ class LinkController extends Controller $subTitle = (string) trans('breadcrumbs.delete_journal_link'); $this->rememberPreviousUrl('journal_links.delete.url'); - return view('transactions.links.delete', ['link' => $link, 'subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon]); + return view('transactions.links.delete', ['link' => $link, 'subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon]); } /** @@ -100,7 +98,7 @@ class LinkController extends Controller { $linkTypes = $this->repository->get(); - return view('transactions.links.modal', ['journal' => $journal, 'linkTypes' => $linkTypes]); + return view('transactions.links.modal', ['journal' => $journal, 'linkTypes' => $linkTypes]); } /** @@ -108,10 +106,10 @@ class LinkController extends Controller */ public function store(JournalLinkRequest $request, TransactionJournal $journal): Redirector|RedirectResponse { - $linkInfo = $request->getLinkInfo(); + $linkInfo = $request->getLinkInfo(); Log::debug('We are here (store)'); - $other = $this->journalRepository->find($linkInfo['transaction_journal_id']); + $other = $this->journalRepository->find($linkInfo['transaction_journal_id']); if (!$other instanceof TransactionJournal) { session()->flash('error', (string) trans('firefly.invalid_link_selection')); diff --git a/app/Http/Controllers/Transaction/MassController.php b/app/Http/Controllers/Transaction/MassController.php index 063e743b67..492fed7021 100644 --- a/app/Http/Controllers/Transaction/MassController.php +++ b/app/Http/Controllers/Transaction/MassController.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Transaction; -use FireflyIII\Support\Facades\Preferences; use Carbon\Carbon; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Enums\TransactionTypeEnum; @@ -37,13 +36,14 @@ use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Services\Internal\Update\JournalUpdateService; +use FireflyIII\Support\Facades\Preferences; +use FireflyIII\Support\Facades\Steam; use Illuminate\Contracts\Foundation\Application; use Illuminate\Http\RedirectResponse; use Illuminate\Routing\Redirector; use Illuminate\Support\Facades\Log; use Illuminate\View\View as IlluminateView; use InvalidArgumentException; -use FireflyIII\Support\Facades\Steam; /** * Class MassController. @@ -59,15 +59,13 @@ class MassController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.transactions')); - app('view')->share('mainTitleIcon', 'fa-exchange'); - $this->repository = app(JournalRepositoryInterface::class); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.transactions')); + app('view')->share('mainTitleIcon', 'fa-exchange'); + $this->repository = app(JournalRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -124,33 +122,38 @@ class MassController extends Controller */ public function edit(array $journals): IlluminateView { - $subTitle = (string) trans('firefly.mass_edit_journals'); + $subTitle = (string) trans('firefly.mass_edit_journals'); /** @var AccountRepositoryInterface $accountRepository */ - $accountRepository = app(AccountRepositoryInterface::class); + $accountRepository = app(AccountRepositoryInterface::class); // valid withdrawal sources: - $array = array_keys(config(sprintf('firefly.source_dests.%s', TransactionTypeEnum::WITHDRAWAL->value))); - $withdrawalSources = $accountRepository->getAccountsByType($array); + $array = array_keys(config(sprintf('firefly.source_dests.%s', TransactionTypeEnum::WITHDRAWAL->value))); + $withdrawalSources = $accountRepository->getAccountsByType($array); // valid deposit destinations: $array = config(sprintf('firefly.source_dests.%s.%s', TransactionTypeEnum::DEPOSIT->value, AccountTypeEnum::REVENUE->value)); $depositDestinations = $accountRepository->getAccountsByType($array); /** @var BudgetRepositoryInterface $budgetRepository */ - $budgetRepository = app(BudgetRepositoryInterface::class); - $budgets = $budgetRepository->getBudgets(); + $budgetRepository = app(BudgetRepositoryInterface::class); + $budgets = $budgetRepository->getBudgets(); // reverse amounts foreach ($journals as $index => $journal) { - $journals[$index]['amount'] = Steam::bcround(Steam::positive($journal['amount']), $journal['currency_decimal_places']); - $journals[$index]['foreign_amount'] = null === $journal['foreign_amount'] - ? null : Steam::positive($journal['foreign_amount']); + $journals[$index]['amount'] = Steam::bcround(Steam::positive($journal['amount']), $journal['currency_decimal_places']); + $journals[$index]['foreign_amount'] = null === $journal['foreign_amount'] ? null : Steam::positive($journal['foreign_amount']); } $this->rememberPreviousUrl('transactions.mass-edit.url'); - return view('transactions.mass.edit', ['journals' => $journals, 'subTitle' => $subTitle, 'withdrawalSources' => $withdrawalSources, 'depositDestinations' => $depositDestinations, 'budgets' => $budgets]); + return view('transactions.mass.edit', [ + 'journals' => $journals, + 'subTitle' => $subTitle, + 'withdrawalSources' => $withdrawalSources, + 'depositDestinations' => $depositDestinations, + 'budgets' => $budgets + ]); } /** @@ -165,7 +168,7 @@ class MassController extends Controller // TODO this is a weird error, should be caught. throw new FireflyException('This is not an array.'); } - $count = 0; + $count = 0; /** @var string $journalId */ foreach ($journalIds as $journalId) { @@ -191,15 +194,15 @@ class MassController extends Controller */ private function updateJournal(int $journalId, MassEditJournalRequest $request): void { - $journal = $this->repository->find($journalId); + $journal = $this->repository->find($journalId); if (!$journal instanceof TransactionJournal) { throw new FireflyException(sprintf('Trying to edit non-existent or deleted journal #%d', $journalId)); } - $service = app(JournalUpdateService::class); + $service = app(JournalUpdateService::class); // for each field, call the update service. $service->setTransactionJournal($journal); - $data = [ + $data = [ 'date' => $this->getDateFromRequest($request, $journal->id, 'date'), 'description' => $this->getStringFromRequest($request, $journal->id, 'description'), 'source_id' => $this->getIntFromRequest($request, $journal->id, 'source_id'), @@ -209,7 +212,7 @@ class MassController extends Controller 'budget_id' => $this->getIntFromRequest($request, $journal->id, 'budget_id'), 'category_name' => $this->getStringFromRequest($request, $journal->id, 'category'), 'amount' => $this->getStringFromRequest($request, $journal->id, 'amount'), - 'foreign_amount' => $this->getStringFromRequest($request, $journal->id, 'foreign_amount'), + 'foreign_amount' => $this->getStringFromRequest($request, $journal->id, 'foreign_amount') ]; Log::debug(sprintf('Will update journal #%d with data.', $journal->id), $data); @@ -221,7 +224,7 @@ class MassController extends Controller event(new UpdatedTransactionGroup($journal->transactionGroup, true, true, $runRecalculations)); } - private function getDateFromRequest(MassEditJournalRequest $request, int $journalId, string $key): ?Carbon + private function getDateFromRequest(MassEditJournalRequest $request, int $journalId, string $key): null|Carbon { $value = $request->get($key); if (!is_array($value)) { @@ -243,7 +246,7 @@ class MassController extends Controller return $carbon; } - private function getStringFromRequest(MassEditJournalRequest $request, int $journalId, string $string): ?string + private function getStringFromRequest(MassEditJournalRequest $request, int $journalId, string $string): null|string { $value = $request->get($string); if (!is_array($value)) { @@ -256,7 +259,7 @@ class MassController extends Controller return (string) $value[$journalId]; } - private function getIntFromRequest(MassEditJournalRequest $request, int $journalId, string $string): ?int + private function getIntFromRequest(MassEditJournalRequest $request, int $journalId, string $string): null|int { $value = $request->get($string); if (!is_array($value)) { diff --git a/app/Http/Controllers/Transaction/ShowController.php b/app/Http/Controllers/Transaction/ShowController.php index fe77236857..6ff71d9534 100644 --- a/app/Http/Controllers/Transaction/ShowController.php +++ b/app/Http/Controllers/Transaction/ShowController.php @@ -45,7 +45,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; */ class ShowController extends Controller { - private ALERepositoryInterface $aleRepository; + private ALERepositoryInterface $aleRepository; private TransactionGroupRepositoryInterface $repository; /** @@ -56,17 +56,15 @@ class ShowController extends Controller parent::__construct(); // some useful repositories: - $this->middleware( - function ($request, $next) { - $this->repository = app(TransactionGroupRepositoryInterface::class); - $this->aleRepository = app(ALERepositoryInterface::class); + $this->middleware(function ($request, $next) { + $this->repository = app(TransactionGroupRepositoryInterface::class); + $this->aleRepository = app(ALERepositoryInterface::class); - app('view')->share('title', (string)trans('firefly.transactions')); - app('view')->share('mainTitleIcon', 'fa-exchange'); + app('view')->share('title', (string) trans('firefly.transactions')); + app('view')->share('mainTitleIcon', 'fa-exchange'); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -85,55 +83,56 @@ class ShowController extends Controller public function show(TransactionGroup $transactionGroup): Factory|\Illuminate\Contracts\View\View { /** @var User $admin */ - $admin = auth()->user(); + $admin = auth()->user(); // use new group collector: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setUser($admin)->setTransactionGroup($transactionGroup)->withAPIInformation(); /** @var null|TransactionGroup $selectedGroup */ - $selectedGroup = $collector->getGroups()->first(); + $selectedGroup = $collector->getGroups()->first(); if (null === $selectedGroup) { throw new NotFoundHttpException(); } // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); - $selectedGroup = $enrichment->enrichSingle($selectedGroup); + $selectedGroup = $enrichment->enrichSingle($selectedGroup); - - $splits = count($selectedGroup['transactions']); - $keys = array_keys($selectedGroup['transactions']); - $first = $selectedGroup['transactions'][array_shift($keys)]; + $splits = count($selectedGroup['transactions']); + $keys = array_keys($selectedGroup['transactions']); + $first = $selectedGroup['transactions'][array_shift($keys)]; unset($keys); if (null === $first) { throw new FireflyException('This transaction is broken :(.'); } - $type = (string)trans(sprintf('firefly.%s', $first['transaction_type_type'])); - $title = 1 === $splits ? $first['description'] : $selectedGroup['title']; - $subTitle = sprintf('%s: "%s"', $type, $title); + $type = (string) trans(sprintf('firefly.%s', $first['transaction_type_type'])); + $title = 1 === $splits ? $first['description'] : $selectedGroup['title']; + $subTitle = sprintf('%s: "%s"', $type, $title); // enrich - $enrichment = new TransactionGroupEnrichment(); + $enrichment = new TransactionGroupEnrichment(); $enrichment->setUser($admin); /** @var array $selectedGroup */ - $selectedGroup = $enrichment->enrichSingle($selectedGroup); + $selectedGroup = $enrichment->enrichSingle($selectedGroup); /** @var TransactionGroupTransformer $transformer */ - $transformer = app(TransactionGroupTransformer::class); + $transformer = app(TransactionGroupTransformer::class); $transformer->setParameters(new ParameterBag()); - $groupArray = $transformer->transformObject($transactionGroup); + $groupArray = $transformer->transformObject($transactionGroup); // do some calculations: - $amounts = $this->getAmounts($selectedGroup); - $accounts = $this->getAccounts($selectedGroup); + $amounts = $this->getAmounts($selectedGroup); + $accounts = $this->getAccounts($selectedGroup); foreach (array_keys($selectedGroup['transactions']) as $index) { - $selectedGroup['transactions'][$index]['tags'] = $this->repository->getTagObjects((int)$selectedGroup['transactions'][$index]['transaction_journal_id']); + $selectedGroup['transactions'][$index]['tags'] = $this->repository->getTagObjects( + (int) $selectedGroup['transactions'][$index]['transaction_journal_id'] + ); } // get audit log entries: $groupLogEntries = $this->aleRepository->getForObject($transactionGroup); @@ -142,11 +141,26 @@ class ShowController extends Controller $logEntries[$journal['transaction_journal_id']] = $this->aleRepository->getForId(TransactionJournal::class, $journal['transaction_journal_id']); } - $events = $this->repository->getPiggyEvents($transactionGroup); - $attachments = $this->repository->getAttachments($transactionGroup); - $links = $this->repository->getLinks($transactionGroup); + $events = $this->repository->getPiggyEvents($transactionGroup); + $attachments = $this->repository->getAttachments($transactionGroup); + $links = $this->repository->getLinks($transactionGroup); - return view('transactions.show', ['transactionGroup' => $transactionGroup, 'amounts' => $amounts, 'first' => $first, 'type' => $type, 'logEntries' => $logEntries, 'groupLogEntries' => $groupLogEntries, 'subTitle' => $subTitle, 'splits' => $splits, 'selectedGroup' => $selectedGroup, 'groupArray' => $groupArray, 'events' => $events, 'attachments' => $attachments, 'links' => $links, 'accounts' => $accounts]); + return view('transactions.show', [ + 'transactionGroup' => $transactionGroup, + 'amounts' => $amounts, + 'first' => $first, + 'type' => $type, + 'logEntries' => $logEntries, + 'groupLogEntries' => $groupLogEntries, + 'subTitle' => $subTitle, + 'splits' => $splits, + 'selectedGroup' => $selectedGroup, + 'groupArray' => $groupArray, + 'events' => $events, + 'attachments' => $attachments, + 'links' => $links, + 'accounts' => $accounts + ]); } private function getAmounts(array $group): array @@ -154,37 +168,36 @@ class ShowController extends Controller $amounts = []; foreach ($group['transactions'] as $transaction) { // add normal amount: - $symbol = $transaction['currency_symbol']; - $amounts[$symbol] ??= [ - 'amount' => '0', - 'symbol' => $symbol, - 'decimal_places' => $transaction['currency_decimal_places'], - ]; - $amounts[$symbol]['amount'] = bcadd($amounts[$symbol]['amount'], (string)$transaction['amount']); + $symbol = $transaction['currency_symbol']; + $amounts[$symbol] ??= ['amount' => '0', 'symbol' => $symbol, 'decimal_places' => $transaction['currency_decimal_places']]; + $amounts[$symbol]['amount'] = bcadd($amounts[$symbol]['amount'], (string) $transaction['amount']); // add foreign amount: - if (null !== $transaction['foreign_amount'] && '' !== $transaction['foreign_amount'] && 0 !== bccomp('0', (string)$transaction['foreign_amount'])) { + if ( + null !== $transaction['foreign_amount'] + && '' !== $transaction['foreign_amount'] + && 0 !== bccomp('0', (string) $transaction['foreign_amount']) + ) { // same for foreign currency: - $foreignSymbol = $transaction['foreign_currency_symbol']; + $foreignSymbol = $transaction['foreign_currency_symbol']; $amounts[$foreignSymbol] ??= [ 'amount' => '0', 'symbol' => $foreignSymbol, - 'decimal_places' => $transaction['foreign_currency_decimal_places'], + 'decimal_places' => $transaction['foreign_currency_decimal_places'] ]; - $amounts[$foreignSymbol]['amount'] = bcadd($amounts[$foreignSymbol]['amount'], (string)$transaction['foreign_amount']); + $amounts[$foreignSymbol]['amount'] = bcadd($amounts[$foreignSymbol]['amount'], (string) $transaction['foreign_amount']); } // add primary currency amount if (null !== $transaction['pc_amount'] && $transaction['currency_id'] !== $this->primaryCurrency->id) { // same for foreign currency: - $primarySymbol = $this->primaryCurrency->symbol; + $primarySymbol = $this->primaryCurrency->symbol; $amounts[$primarySymbol] ??= [ 'amount' => '0', 'symbol' => $this->primaryCurrency->symbol, - 'decimal_places' => $this->primaryCurrency->decimal_places, + 'decimal_places' => $this->primaryCurrency->decimal_places ]; - $amounts[$primarySymbol]['amount'] = bcadd($amounts[$primarySymbol]['amount'], (string)$transaction['pc_amount']); + $amounts[$primarySymbol]['amount'] = bcadd($amounts[$primarySymbol]['amount'], (string) $transaction['pc_amount']); } - } return $amounts; @@ -192,27 +205,24 @@ class ShowController extends Controller private function getAccounts(array $group): array { - $accounts = [ - 'source' => [], - 'destination' => [], - ]; + $accounts = ['source' => [], 'destination' => []]; foreach ($group['transactions'] as $transaction) { - $accounts['source'][] = [ + $accounts['source'][] = [ 'type' => $transaction['source_account_type'], 'id' => $transaction['source_account_id'], 'name' => $transaction['source_account_name'], - 'iban' => $transaction['source_account_iban'], + 'iban' => $transaction['source_account_iban'] ]; $accounts['destination'][] = [ 'type' => $transaction['destination_account_type'], 'id' => $transaction['destination_account_id'], 'name' => $transaction['destination_account_name'], - 'iban' => $transaction['destination_account_iban'], + 'iban' => $transaction['destination_account_iban'] ]; } - $accounts['source'] = array_unique($accounts['source'], SORT_REGULAR); + $accounts['source'] = array_unique($accounts['source'], SORT_REGULAR); $accounts['destination'] = array_unique($accounts['destination'], SORT_REGULAR); return $accounts; diff --git a/app/Http/Controllers/TransactionCurrency/CreateController.php b/app/Http/Controllers/TransactionCurrency/CreateController.php index 057089b5da..967a9e47ba 100644 --- a/app/Http/Controllers/TransactionCurrency/CreateController.php +++ b/app/Http/Controllers/TransactionCurrency/CreateController.php @@ -44,7 +44,7 @@ use Illuminate\View\View; class CreateController extends Controller { protected CurrencyRepositoryInterface $repository; - protected UserRepositoryInterface $userRepository; + protected UserRepositoryInterface $userRepository; /** * CurrencyController constructor. @@ -53,16 +53,14 @@ class CreateController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.currencies')); - app('view')->share('mainTitleIcon', 'fa-usd'); - $this->repository = app(CurrencyRepositoryInterface::class); - $this->userRepository = app(UserRepositoryInterface::class); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.currencies')); + app('view')->share('mainTitleIcon', 'fa-usd'); + $this->repository = app(CurrencyRepositoryInterface::class); + $this->userRepository = app(UserRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -73,7 +71,7 @@ class CreateController extends Controller public function create(Request $request): Factory|\Illuminate\Contracts\View\View|Redirector|RedirectResponse { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); if (!$this->userRepository->hasRole($user, 'owner')) { $request->session()->flash('error', (string) trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))])); @@ -91,7 +89,7 @@ class CreateController extends Controller Log::channel('audit')->info('Create new currency.'); - return view('currencies.create', ['subTitleIcon' => $subTitleIcon, 'subTitle' => $subTitle]); + return view('currencies.create', ['subTitleIcon' => $subTitleIcon, 'subTitle' => $subTitle]); } /** @@ -102,10 +100,10 @@ class CreateController extends Controller public function store(CurrencyFormRequest $request) { /** @var User $user */ - $user = auth()->user(); - $data = $request->getCurrencyData(); + $user = auth()->user(); + $data = $request->getCurrencyData(); if (!$this->userRepository->hasRole($user, 'owner')) { - Log::error('User '.auth()->user()->id.' is not admin, but tried to store a currency.'); + Log::error('User ' . auth()->user()->id . ' is not admin, but tried to store a currency.'); Log::channel('audit')->warning('Tried to create (POST) currency without admin rights.', $data); return redirect($this->getPreviousUrl('currencies.create.url'))->withInput(); @@ -121,7 +119,7 @@ class CreateController extends Controller $request->session()->flash('error', (string) trans('firefly.could_not_store_currency')); $currency = null; } - $redirect = redirect($this->getPreviousUrl('currencies.create.url')); + $redirect = redirect($this->getPreviousUrl('currencies.create.url')); if ($currency instanceof TransactionCurrency) { $request->session()->flash('success', (string) trans('firefly.created_currency', ['name' => $currency->name])); diff --git a/app/Http/Controllers/TransactionCurrency/DeleteController.php b/app/Http/Controllers/TransactionCurrency/DeleteController.php index b9364f98e1..2e4b698ebd 100644 --- a/app/Http/Controllers/TransactionCurrency/DeleteController.php +++ b/app/Http/Controllers/TransactionCurrency/DeleteController.php @@ -43,7 +43,7 @@ use Illuminate\View\View; class DeleteController extends Controller { protected CurrencyRepositoryInterface $repository; - protected UserRepositoryInterface $userRepository; + protected UserRepositoryInterface $userRepository; /** * CurrencyController constructor. @@ -52,16 +52,14 @@ class DeleteController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.currencies')); - app('view')->share('mainTitleIcon', 'fa-usd'); - $this->repository = app(CurrencyRepositoryInterface::class); - $this->userRepository = app(UserRepositoryInterface::class); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.currencies')); + app('view')->share('mainTitleIcon', 'fa-usd'); + $this->repository = app(CurrencyRepositoryInterface::class); + $this->userRepository = app(UserRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -74,7 +72,7 @@ class DeleteController extends Controller public function delete(Request $request, TransactionCurrency $currency): Factory|\Illuminate\Contracts\View\View|Redirector|RedirectResponse { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); if (!$this->userRepository->hasRole($user, 'owner')) { $request->session()->flash('error', (string) trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))])); Log::channel('audit')->warning(sprintf('Tried to visit page to delete currency %s but is not site owner.', $currency->code)); @@ -84,7 +82,7 @@ class DeleteController extends Controller if ($this->repository->currencyInUse($currency)) { $location = $this->repository->currencyInUseAt($currency); - $message = (string) trans(sprintf('firefly.cannot_disable_currency_%s', $location), ['name' => e($currency->name)]); + $message = (string) trans(sprintf('firefly.cannot_disable_currency_%s', $location), ['name' => e($currency->name)]); $request->session()->flash('error', $message); Log::channel('audit')->warning(sprintf('Tried to visit page to delete currency %s but currency is in use.', $currency->code)); diff --git a/app/Http/Controllers/TransactionCurrency/EditController.php b/app/Http/Controllers/TransactionCurrency/EditController.php index b2e9a1ff86..8c79dbc887 100644 --- a/app/Http/Controllers/TransactionCurrency/EditController.php +++ b/app/Http/Controllers/TransactionCurrency/EditController.php @@ -24,13 +24,13 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\TransactionCurrency; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Requests\CurrencyFormRequest; use FireflyIII\Models\TransactionCurrency; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\Repositories\User\UserRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use FireflyIII\User; use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; @@ -42,7 +42,7 @@ use Illuminate\View\View; class EditController extends Controller { protected CurrencyRepositoryInterface $repository; - protected UserRepositoryInterface $userRepository; + protected UserRepositoryInterface $userRepository; /** * CurrencyController constructor. @@ -51,16 +51,14 @@ class EditController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.currencies')); - app('view')->share('mainTitleIcon', 'fa-usd'); - $this->repository = app(CurrencyRepositoryInterface::class); - $this->userRepository = app(UserRepositoryInterface::class); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.currencies')); + app('view')->share('mainTitleIcon', 'fa-usd'); + $this->repository = app(CurrencyRepositoryInterface::class); + $this->userRepository = app(UserRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -71,7 +69,7 @@ class EditController extends Controller public function edit(Request $request, TransactionCurrency $currency): Factory|\Illuminate\Contracts\View\View|Redirector|RedirectResponse { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); if (!$this->userRepository->hasRole($user, 'owner')) { $request->session()->flash('error', (string) trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))])); Log::channel('audit')->warning(sprintf('Tried to edit currency %s but is not owner.', $currency->code)); @@ -79,19 +77,20 @@ class EditController extends Controller return redirect(route('currencies.index')); } - $subTitleIcon = 'fa-pencil'; - $subTitle = (string) trans('breadcrumbs.edit_currency', ['name' => $currency->name]); + $subTitleIcon = 'fa-pencil'; + $subTitle = (string) trans('breadcrumbs.edit_currency', ['name' => $currency->name]); $currency->symbol = htmlentities($currency->symbol); // is currently enabled (for this user?) - $userCurrencies = $this->repository->get()->pluck('id')->toArray(); - $enabled = in_array($currency->id, $userCurrencies, true); + $userCurrencies = $this->repository + ->get() + ->pluck('id') + ->toArray(); + $enabled = in_array($currency->id, $userCurrencies, true); // code to handle active-checkboxes - $hasOldInput = null !== $request->old('_token'); - $preFilled = [ - 'enabled' => $hasOldInput ? (bool) $request->old('enabled') : $enabled, - ]; + $hasOldInput = null !== $request->old('_token'); + $preFilled = ['enabled' => $hasOldInput ? (bool) $request->old('enabled') : $enabled]; $request->session()->flash('preFilled', $preFilled); Log::channel('audit')->info('Edit currency.', $currency->toArray()); @@ -102,7 +101,7 @@ class EditController extends Controller } $request->session()->forget('currencies.edit.fromUpdate'); - return view('currencies.edit', ['currency' => $currency, 'subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon]); + return view('currencies.edit', ['currency' => $currency, 'subTitle' => $subTitle, 'subTitleIcon' => $subTitleIcon]); } /** @@ -113,8 +112,8 @@ class EditController extends Controller public function update(CurrencyFormRequest $request, TransactionCurrency $currency): Redirector|RedirectResponse { /** @var User $user */ - $user = auth()->user(); - $data = $request->getCurrencyData(); + $user = auth()->user(); + $data = $request->getCurrencyData(); if (false === $data['enabled'] && $this->repository->currencyInUse($currency)) { $data['enabled'] = true; diff --git a/app/Http/Controllers/TransactionCurrency/IndexController.php b/app/Http/Controllers/TransactionCurrency/IndexController.php index f2c264fd6f..ffd2ff5ba4 100644 --- a/app/Http/Controllers/TransactionCurrency/IndexController.php +++ b/app/Http/Controllers/TransactionCurrency/IndexController.php @@ -24,11 +24,11 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\TransactionCurrency; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\TransactionCurrency; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\Repositories\User\UserRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use FireflyIII\User; use Illuminate\Contracts\View\Factory; use Illuminate\Http\Request; @@ -40,7 +40,7 @@ use Psr\Container\NotFoundExceptionInterface; class IndexController extends Controller { protected CurrencyRepositoryInterface $repository; - protected UserRepositoryInterface $userRepository; + protected UserRepositoryInterface $userRepository; /** * CurrencyController constructor. @@ -49,16 +49,14 @@ class IndexController extends Controller { parent::__construct(); - $this->middleware( - function ($request, $next) { - app('view')->share('title', (string) trans('firefly.currencies')); - app('view')->share('mainTitleIcon', 'fa-usd'); - $this->repository = app(CurrencyRepositoryInterface::class); - $this->userRepository = app(UserRepositoryInterface::class); + $this->middleware(function ($request, $next) { + app('view')->share('title', (string) trans('firefly.currencies')); + app('view')->share('mainTitleIcon', 'fa-usd'); + $this->repository = app(CurrencyRepositoryInterface::class); + $this->userRepository = app(UserRepositoryInterface::class); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -78,25 +76,23 @@ class IndexController extends Controller $collection = $this->repository->getAll(); // order so default and enabled are on top: - $collection = $collection->sortBy( - static function (TransactionCurrency $currency): string { - $primary = true === $currency->userGroupNative ? 0 : 1; - $enabled = true === $currency->userGroupEnabled ? 0 : 1; + $collection = $collection->sortBy(static function (TransactionCurrency $currency): string { + $primary = true === $currency->userGroupNative ? 0 : 1; + $enabled = true === $currency->userGroupEnabled ? 0 : 1; - return sprintf('%s-%s-%s', $primary, $enabled, $currency->code); - } - ); + return sprintf('%s-%s-%s', $primary, $enabled, $currency->code); + }); $total = $collection->count(); $collection = $collection->slice(($page - 1) * $pageSize, $pageSize); $currencies = new LengthAwarePaginator($collection, $total, $pageSize, $page); $currencies->setPath(route('currencies.index')); - $isOwner = true; + $isOwner = true; if (!$this->userRepository->hasRole($user, 'owner')) { $request->session()->flash('info', (string) trans('firefly.ask_site_owner', ['owner' => config('firefly.site_owner')])); $isOwner = false; } - return view('currencies.index', ['currencies' => $currencies, 'isOwner' => $isOwner]); + return view('currencies.index', ['currencies' => $currencies, 'isOwner' => $isOwner]); } } diff --git a/app/Http/Controllers/UserGroup/CreateController.php b/app/Http/Controllers/UserGroup/CreateController.php index 8ec1487e8c..253e0f293d 100644 --- a/app/Http/Controllers/UserGroup/CreateController.php +++ b/app/Http/Controllers/UserGroup/CreateController.php @@ -24,11 +24,11 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\UserGroup; -use Illuminate\Support\Facades\Log; use FireflyIII\Http\Controllers\Controller; use Illuminate\Contracts\View\Factory; use Illuminate\Contracts\View\View; use Illuminate\Foundation\Application; +use Illuminate\Support\Facades\Log; class CreateController extends Controller { @@ -42,8 +42,6 @@ class CreateController extends Controller $mainTitleIcon = 'fa-book'; Log::debug(sprintf('Now at %s', __METHOD__)); - return view('administrations.create') // @phpstan-ignore-line - ->with(['title' => $title, 'subTitle' => $subTitle, 'mainTitleIcon' => $mainTitleIcon]) - ; + return view('administrations.create')->with(['title' => $title, 'subTitle' => $subTitle, 'mainTitleIcon' => $mainTitleIcon]); // @phpstan-ignore-line } } diff --git a/app/Http/Controllers/UserGroup/EditController.php b/app/Http/Controllers/UserGroup/EditController.php index a8b7c8a2b2..ee38cefce1 100644 --- a/app/Http/Controllers/UserGroup/EditController.php +++ b/app/Http/Controllers/UserGroup/EditController.php @@ -24,12 +24,12 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\UserGroup; -use Illuminate\Support\Facades\Log; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\UserGroup; use Illuminate\Contracts\View\Factory; use Illuminate\Contracts\View\View; use Illuminate\Foundation\Application; +use Illuminate\Support\Facades\Log; class EditController extends Controller { @@ -39,10 +39,10 @@ class EditController extends Controller public function edit(UserGroup $userGroup) { $title = (string) trans('firefly.administrations_page_title'); - $subTitle = (string) trans('firefly.administrations_page_edit_sub_title', ['title' => $userGroup->title]); + $subTitle = (string) trans('firefly.administrations_page_edit_sub_title', ['title' => $userGroup->title]); $mainTitleIcon = 'fa-book'; Log::debug(sprintf('Now at %s', __METHOD__)); - return view('administrations.edit')->with(['title' => $title, 'subTitle' => $subTitle, 'mainTitleIcon' => $mainTitleIcon]); + return view('administrations.edit')->with(['title' => $title, 'subTitle' => $subTitle, 'mainTitleIcon' => $mainTitleIcon]); } } diff --git a/app/Http/Controllers/UserGroup/IndexController.php b/app/Http/Controllers/UserGroup/IndexController.php index 199400babd..b782463c2f 100644 --- a/app/Http/Controllers/UserGroup/IndexController.php +++ b/app/Http/Controllers/UserGroup/IndexController.php @@ -24,10 +24,10 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\UserGroup; -use Illuminate\Support\Facades\Log; use FireflyIII\Http\Controllers\Controller; use Illuminate\Contracts\View\Factory; use Illuminate\Http\Request; +use Illuminate\Support\Facades\Log; use Illuminate\View\View; class IndexController extends Controller @@ -44,6 +44,6 @@ class IndexController extends Controller $mainTitleIcon = 'fa-book'; Log::debug(sprintf('Now at %s', __METHOD__)); - return view('administrations.index')->with(['title' => $title, 'subTitle' => $subTitle, 'mainTitleIcon' => $mainTitleIcon]); + return view('administrations.index')->with(['title' => $title, 'subTitle' => $subTitle, 'mainTitleIcon' => $mainTitleIcon]); } } diff --git a/app/Http/Controllers/Webhooks/CreateController.php b/app/Http/Controllers/Webhooks/CreateController.php index bdae300496..1f39976a2e 100644 --- a/app/Http/Controllers/Webhooks/CreateController.php +++ b/app/Http/Controllers/Webhooks/CreateController.php @@ -25,11 +25,11 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Webhooks; use FireflyIII\Http\Controllers\Controller; +use FireflyIII\Support\Facades\FireflyConfig; use Illuminate\Contracts\View\Factory; use Illuminate\Support\Facades\Log; use Illuminate\View\View; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; -use FireflyIII\Support\Facades\FireflyConfig; /** * Class CreateController @@ -41,16 +41,14 @@ class CreateController extends Controller parent::__construct(); // translations: - $this->middleware( - static function ($request, $next) { - app('view')->share('mainTitleIcon', 'fa-bolt'); - app('view')->share('subTitleIcon', 'fa-plus'); - app('view')->share('title', (string) trans('firefly.webhooks')); - app('view')->share('subTitle', (string) trans('firefly.create_new_webhook')); + $this->middleware(static function ($request, $next) { + app('view')->share('mainTitleIcon', 'fa-bolt'); + app('view')->share('subTitleIcon', 'fa-plus'); + app('view')->share('title', (string) trans('firefly.webhooks')); + app('view')->share('subTitle', (string) trans('firefly.create_new_webhook')); - return $next($request); - } - ); + return $next($request); + }); } /** diff --git a/app/Http/Controllers/Webhooks/DeleteController.php b/app/Http/Controllers/Webhooks/DeleteController.php index c8b399879a..32072fde5a 100644 --- a/app/Http/Controllers/Webhooks/DeleteController.php +++ b/app/Http/Controllers/Webhooks/DeleteController.php @@ -26,12 +26,12 @@ namespace FireflyIII\Http\Controllers\Webhooks; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\Webhook; +use FireflyIII\Support\Facades\FireflyConfig; use Illuminate\Contracts\Foundation\Application; use Illuminate\Contracts\View\Factory; use Illuminate\Contracts\View\View; use Illuminate\Support\Facades\Log; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; -use FireflyIII\Support\Facades\FireflyConfig; /** * Class DeleteController @@ -46,16 +46,14 @@ class DeleteController extends Controller parent::__construct(); // translations: - $this->middleware( - static function ($request, $next) { - app('view')->share('mainTitleIcon', 'fa-bolt'); - app('view')->share('subTitleIcon', 'fa-trash'); - app('view')->share('title', (string) trans('firefly.webhooks')); - app('view')->share('subTitle', (string) trans('firefly.delete_webhook')); + $this->middleware(static function ($request, $next) { + app('view')->share('mainTitleIcon', 'fa-bolt'); + app('view')->share('subTitleIcon', 'fa-trash'); + app('view')->share('title', (string) trans('firefly.webhooks')); + app('view')->share('subTitle', (string) trans('firefly.delete_webhook')); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -74,6 +72,6 @@ class DeleteController extends Controller $subTitle = (string) trans('firefly.delete_webhook', ['title' => $webhook->title]); $this->rememberPreviousUrl('webhooks.delete.url'); - return view('webhooks.delete', ['webhook' => $webhook, 'subTitle' => $subTitle]); + return view('webhooks.delete', ['webhook' => $webhook, 'subTitle' => $subTitle]); } } diff --git a/app/Http/Controllers/Webhooks/EditController.php b/app/Http/Controllers/Webhooks/EditController.php index a00497b7de..553d0dbf28 100644 --- a/app/Http/Controllers/Webhooks/EditController.php +++ b/app/Http/Controllers/Webhooks/EditController.php @@ -26,12 +26,12 @@ namespace FireflyIII\Http\Controllers\Webhooks; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\Webhook; +use FireflyIII\Support\Facades\FireflyConfig; use Illuminate\Contracts\Foundation\Application; use Illuminate\Contracts\View\Factory; use Illuminate\Contracts\View\View; use Illuminate\Support\Facades\Log; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; -use FireflyIII\Support\Facades\FireflyConfig; /** * Class EditController @@ -46,15 +46,13 @@ class EditController extends Controller parent::__construct(); // translations: - $this->middleware( - static function ($request, $next) { - app('view')->share('mainTitleIcon', 'fa-bolt'); - app('view')->share('subTitleIcon', 'fa-pencil'); - app('view')->share('title', (string) trans('firefly.webhooks')); + $this->middleware(static function ($request, $next) { + app('view')->share('mainTitleIcon', 'fa-bolt'); + app('view')->share('subTitleIcon', 'fa-pencil'); + app('view')->share('title', (string) trans('firefly.webhooks')); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -73,6 +71,6 @@ class EditController extends Controller $subTitle = (string) trans('firefly.edit_webhook', ['title' => $webhook->title]); $this->rememberPreviousUrl('webhooks.edit.url'); - return view('webhooks.edit', ['webhook' => $webhook, 'subTitle' => $subTitle]); + return view('webhooks.edit', ['webhook' => $webhook, 'subTitle' => $subTitle]); } } diff --git a/app/Http/Controllers/Webhooks/IndexController.php b/app/Http/Controllers/Webhooks/IndexController.php index 5211a3a89b..efed505c43 100644 --- a/app/Http/Controllers/Webhooks/IndexController.php +++ b/app/Http/Controllers/Webhooks/IndexController.php @@ -25,11 +25,11 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Webhooks; use FireflyIII\Http\Controllers\Controller; +use FireflyIII\Support\Facades\FireflyConfig; use Illuminate\Contracts\View\Factory; use Illuminate\Support\Facades\Log; use Illuminate\View\View; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; -use FireflyIII\Support\Facades\FireflyConfig; /** * Class IndexController @@ -41,14 +41,12 @@ class IndexController extends Controller parent::__construct(); // translations: - $this->middleware( - static function ($request, $next) { - app('view')->share('mainTitleIcon', 'fa-bolt'); - app('view')->share('title', (string) trans('firefly.webhooks')); + $this->middleware(static function ($request, $next) { + app('view')->share('mainTitleIcon', 'fa-bolt'); + app('view')->share('title', (string) trans('firefly.webhooks')); - return $next($request); - } - ); + return $next($request); + }); } /** diff --git a/app/Http/Controllers/Webhooks/ShowController.php b/app/Http/Controllers/Webhooks/ShowController.php index f0bc69a4cb..1fb696a585 100644 --- a/app/Http/Controllers/Webhooks/ShowController.php +++ b/app/Http/Controllers/Webhooks/ShowController.php @@ -26,12 +26,12 @@ namespace FireflyIII\Http\Controllers\Webhooks; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\Webhook; +use FireflyIII\Support\Facades\FireflyConfig; use Illuminate\Contracts\Foundation\Application; use Illuminate\Contracts\View\Factory; use Illuminate\Contracts\View\View; use Illuminate\Support\Facades\Log; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; -use FireflyIII\Support\Facades\FireflyConfig; /** * Class ShowController @@ -46,15 +46,13 @@ class ShowController extends Controller parent::__construct(); // translations: - $this->middleware( - static function ($request, $next) { - app('view')->share('mainTitleIcon', 'fa-bolt'); - app('view')->share('subTitleIcon', 'fa-bolt'); - app('view')->share('title', (string) trans('firefly.webhooks')); + $this->middleware(static function ($request, $next) { + app('view')->share('mainTitleIcon', 'fa-bolt'); + app('view')->share('subTitleIcon', 'fa-bolt'); + app('view')->share('title', (string) trans('firefly.webhooks')); - return $next($request); - } - ); + return $next($request); + }); } /** @@ -72,6 +70,6 @@ class ShowController extends Controller Log::channel('audit')->info(sprintf('User visits webhook #%d page.', $webhook->id)); $subTitle = (string) trans('firefly.show_webhook', ['title' => $webhook->title]); - return view('webhooks.show', ['webhook' => $webhook, 'subTitle' => $subTitle]); + return view('webhooks.show', ['webhook' => $webhook, 'subTitle' => $subTitle]); } } diff --git a/app/Http/Kernel.php b/app/Http/Kernel.php index 139547582c..0841c78bf7 100644 --- a/app/Http/Kernel.php +++ b/app/Http/Kernel.php @@ -57,142 +57,119 @@ use PragmaRX\Google2FALaravel\Middleware as MFAMiddleware; */ class Kernel extends HttpKernel { - protected $middleware - = [ - SecureHeaders::class, - CheckForMaintenanceMode::class, - ValidatePostSize::class, - TrimStrings::class, - ConvertEmptyStringsToNull::class, - TrustProxies::class, - InstallationId::class, - ]; - protected $middlewareAliases - = [ - 'auth' => Authenticate::class, - 'auth.basic' => AuthenticateWithBasicAuth::class, - 'bindings' => Binder::class, - 'can' => Authorize::class, - 'guest' => RedirectIfAuthenticated::class, - 'throttle' => ThrottleRequests::class, - ]; - protected $middlewareGroups - = [ - // does not check login - // does not check 2fa - // does not check activation - 'web' => [ - EncryptCookies::class, - AddQueuedCookiesToResponse::class, - StartFireflySession::class, - ShareErrorsFromSession::class, - VerifyCsrfToken::class, - AuthenticateSession::class, - CreateFreshApiToken::class, - ], - - // only the basic variable binders. - 'binders-only' => [ - Installer::class, - EncryptCookies::class, - AddQueuedCookiesToResponse::class, - Binder::class, - ], - - // MUST NOT be logged in. Does not care about 2FA or confirmation. - 'user-not-logged-in' => [ - Installer::class, - EncryptCookies::class, - AddQueuedCookiesToResponse::class, - StartFireflySession::class, - ShareErrorsFromSession::class, - VerifyCsrfToken::class, - Binder::class, - RedirectIfAuthenticated::class, - ], - // MUST be logged in. - // MUST NOT have 2FA - // don't care about confirmation: - 'user-logged-in-no-2fa' => [ - Installer::class, - EncryptCookies::class, - AddQueuedCookiesToResponse::class, - StartFireflySession::class, - ShareErrorsFromSession::class, - VerifyCsrfToken::class, - Binder::class, - Authenticate::class, - // RedirectIfTwoFactorAuthenticated::class, - ], - - // MUST be logged in - // don't care about 2fa - // don't care about confirmation. - 'user-simple-auth' => [ - EncryptCookies::class, - AddQueuedCookiesToResponse::class, - StartFireflySession::class, - ShareErrorsFromSession::class, - VerifyCsrfToken::class, - Binder::class, - Authenticate::class, - ], - - // MUST be logged in - // MUST have 2fa - // MUST be confirmed. - // (this group includes the other Firefly III middleware) - 'user-full-auth' => [ - EncryptCookies::class, - AddQueuedCookiesToResponse::class, - StartFireflySession::class, - ShareErrorsFromSession::class, - VerifyCsrfToken::class, - Authenticate::class, - MFAMiddleware::class, - Range::class, - Binder::class, - InterestingMessage::class, - CreateFreshApiToken::class, - ], - // MUST be logged in - // MUST have 2fa - // MUST be confirmed. - // MUST have owner role - // (this group includes the other Firefly III middleware) - 'admin' => [ - EncryptCookies::class, - AddQueuedCookiesToResponse::class, - StartFireflySession::class, - ShareErrorsFromSession::class, - VerifyCsrfToken::class, - Authenticate::class, - // AuthenticateTwoFactor::class, - IsAdmin::class, - Range::class, - Binder::class, - CreateFreshApiToken::class, - ], - - // full API authentication - 'api' => [ - AcceptHeaders::class, - EnsureFrontendRequestsAreStateful::class, - 'auth:api,sanctum', - 'bindings', - ], - // do only bindings, no auth - 'api_basic' => [ - AcceptHeaders::class, - 'bindings', - ], - ]; - protected $middlewarePriority - = [ + protected $middleware = [ + SecureHeaders::class, + CheckForMaintenanceMode::class, + ValidatePostSize::class, + TrimStrings::class, + ConvertEmptyStringsToNull::class, + TrustProxies::class, + InstallationId::class + ]; + protected $middlewareAliases = [ + 'auth' => Authenticate::class, + 'auth.basic' => AuthenticateWithBasicAuth::class, + 'bindings' => Binder::class, + 'can' => Authorize::class, + 'guest' => RedirectIfAuthenticated::class, + 'throttle' => ThrottleRequests::class + ]; + protected $middlewareGroups = [ + // does not check login + // does not check 2fa + // does not check activation + 'web' => [ + EncryptCookies::class, + AddQueuedCookiesToResponse::class, StartFireflySession::class, ShareErrorsFromSession::class, - Authenticate::class, + VerifyCsrfToken::class, + AuthenticateSession::class, + CreateFreshApiToken::class + ], + + // only the basic variable binders. + 'binders-only' => [Installer::class, EncryptCookies::class, AddQueuedCookiesToResponse::class, Binder::class], + + // MUST NOT be logged in. Does not care about 2FA or confirmation. + 'user-not-logged-in' => [ + Installer::class, + EncryptCookies::class, + AddQueuedCookiesToResponse::class, + StartFireflySession::class, + ShareErrorsFromSession::class, + VerifyCsrfToken::class, Binder::class, - Authorize::class, - ]; + RedirectIfAuthenticated::class + ], + // MUST be logged in. + // MUST NOT have 2FA + // don't care about confirmation: + 'user-logged-in-no-2fa' => [ + Installer::class, + EncryptCookies::class, + AddQueuedCookiesToResponse::class, + StartFireflySession::class, + ShareErrorsFromSession::class, + VerifyCsrfToken::class, + Binder::class, + Authenticate::class + // RedirectIfTwoFactorAuthenticated::class, + ], + + // MUST be logged in + // don't care about 2fa + // don't care about confirmation. + 'user-simple-auth' => [ + EncryptCookies::class, + AddQueuedCookiesToResponse::class, + StartFireflySession::class, + ShareErrorsFromSession::class, + VerifyCsrfToken::class, + Binder::class, + Authenticate::class + ], + + // MUST be logged in + // MUST have 2fa + // MUST be confirmed. + // (this group includes the other Firefly III middleware) + 'user-full-auth' => [ + EncryptCookies::class, + AddQueuedCookiesToResponse::class, + StartFireflySession::class, + ShareErrorsFromSession::class, + VerifyCsrfToken::class, + Authenticate::class, + MFAMiddleware::class, + Range::class, + Binder::class, + InterestingMessage::class, + CreateFreshApiToken::class + ], + // MUST be logged in + // MUST have 2fa + // MUST be confirmed. + // MUST have owner role + // (this group includes the other Firefly III middleware) + 'admin' => [ + EncryptCookies::class, + AddQueuedCookiesToResponse::class, + StartFireflySession::class, + ShareErrorsFromSession::class, + VerifyCsrfToken::class, + Authenticate::class, + // AuthenticateTwoFactor::class, + IsAdmin::class, + Range::class, + Binder::class, + CreateFreshApiToken::class + ], + + // full API authentication + 'api' => [AcceptHeaders::class, EnsureFrontendRequestsAreStateful::class, 'auth:api,sanctum', 'bindings'], + // do only bindings, no auth + 'api_basic' => [AcceptHeaders::class, 'bindings'] + ]; + protected $middlewarePriority = [StartFireflySession::class, ShareErrorsFromSession::class, Authenticate::class, Binder::class, Authorize::class]; } diff --git a/app/Http/Middleware/AcceptHeaders.php b/app/Http/Middleware/AcceptHeaders.php index 8a7528864a..e441487f21 100644 --- a/app/Http/Middleware/AcceptHeaders.php +++ b/app/Http/Middleware/AcceptHeaders.php @@ -56,27 +56,28 @@ class AcceptHeaders // if bad 'Content-Type' header, refuse service. // some routes are exempt from this. - $exempt = [ - 'api.v1.data.bulk.transactions', - 'api.v1.attachments.upload', - ]; + $exempt = ['api.v1.data.bulk.transactions', 'api.v1.attachments.upload']; if (('POST' === $method || 'PUT' === $method) && !$request->hasHeader('Content-Type') && !in_array($request->route()->getName(), $exempt, true)) { - $error = new BadHttpHeaderException('Content-Type header cannot be empty.'); + $error = new BadHttpHeaderException('Content-Type header cannot be empty.'); $error->statusCode = 415; throw $error; } - if (('POST' === $method || 'PUT' === $method) && !$this->acceptsHeader($submitted, $contentTypes) && !in_array($request->route()->getName(), $exempt, true)) { - $error = new BadHttpHeaderException(sprintf('Content-Type cannot be "%s"', $submitted)); + if ( + ('POST' === $method || 'PUT' === $method) + && !$this->acceptsHeader($submitted, $contentTypes) + && !in_array($request->route()->getName(), $exempt, true) + ) { + $error = new BadHttpHeaderException(sprintf('Content-Type cannot be "%s"', $submitted)); $error->statusCode = 415; throw $error; } // throw bad request if trace id is not a UUID - $uuid = $request->header('X-Trace-Id'); - if (is_string($uuid) && '' !== trim($uuid) && (1 !== preg_match('/^[a-f\d]{8}(-[a-f\d]{4}){4}[a-f\d]{8}$/i', trim($uuid)))) { + $uuid = $request->header('X-Trace-Id'); + if (is_string($uuid) && '' !== trim($uuid) && 1 !== preg_match('/^[a-f\d]{8}(-[a-f\d]{4}){4}[a-f\d]{8}$/i', trim($uuid))) { throw new BadRequestHttpException('Bad X-Trace-Id header.'); } diff --git a/app/Http/Middleware/Authenticate.php b/app/Http/Middleware/Authenticate.php index 57c3d74c9c..346e5e1316 100644 --- a/app/Http/Middleware/Authenticate.php +++ b/app/Http/Middleware/Authenticate.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Middleware; -use Illuminate\Support\Facades\Log; use Closure; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\Handler; @@ -32,6 +31,7 @@ use FireflyIII\User; use Illuminate\Auth\AuthenticationException; use Illuminate\Contracts\Auth\Factory as Auth; use Illuminate\Http\Request; +use Illuminate\Support\Facades\Log; use League\OAuth2\Server\Exception\OAuthServerException; /** @@ -124,7 +124,7 @@ class Authenticate /** * @throws AuthenticationException */ - private function validateBlockedUser(?User $user, array $guards): void + private function validateBlockedUser(null|User $user, array $guards): void { if (!$user instanceof User) { Log::warning('User is null, throw exception?'); diff --git a/app/Http/Middleware/Binder.php b/app/Http/Middleware/Binder.php index 0dfc35e433..07a80af026 100644 --- a/app/Http/Middleware/Binder.php +++ b/app/Http/Middleware/Binder.php @@ -42,9 +42,10 @@ class Binder /** * Binder constructor. */ - public function __construct(/** - * The authentication factory instance. - */ + public function __construct( + /** + * The authentication factory instance. + */ protected Auth $auth ) { $this->binders = Domain::getBindables(); diff --git a/app/Http/Middleware/InterestingMessage.php b/app/Http/Middleware/InterestingMessage.php index 4c84751eaf..e1b938c331 100644 --- a/app/Http/Middleware/InterestingMessage.php +++ b/app/Http/Middleware/InterestingMessage.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Middleware; -use FireflyIII\Support\Facades\Preferences; use Closure; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Account; @@ -35,6 +34,7 @@ use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\UserGroup; use FireflyIII\Models\Webhook; use FireflyIII\Support\Facades\Amount; +use FireflyIII\Support\Facades\Preferences; use FireflyIII\User; use Illuminate\Http\Request; @@ -105,33 +105,33 @@ class InterestingMessage // send message about newly created transaction group. /** @var null|TransactionGroup $group */ - $group = auth()->user()->transactionGroups()->with(['transactionJournals', 'transactionJournals.transactionType'])->find((int)$transactionGroupId); + $group = auth()->user()->transactionGroups()->with(['transactionJournals', 'transactionJournals.transactionType'])->find((int) $transactionGroupId); if (null === $group) { return; } - $count = $group->transactionJournals->count(); + $count = $group->transactionJournals->count(); /** @var null|TransactionJournal $journal */ - $journal = $group->transactionJournals->first(); + $journal = $group->transactionJournals->first(); if (null === $journal) { return; } - $title = $count > 1 ? $group->title : $journal->description; + $title = $count > 1 ? $group->title : $journal->description; if ('created' === $message) { session()->flash('success_url', route('transactions.show', [$transactionGroupId])); - session()->flash('success', (string)trans('firefly.stored_journal', ['description' => $title])); + session()->flash('success', (string) trans('firefly.stored_journal', ['description' => $title])); } if ('updated' === $message) { - $type = strtolower((string)$journal->transactionType->type); + $type = strtolower((string) $journal->transactionType->type); session()->flash('success_url', route('transactions.show', [$transactionGroupId])); - session()->flash('success', (string)trans(sprintf('firefly.updated_%s', $type), ['description' => $title])); + session()->flash('success', (string) trans(sprintf('firefly.updated_%s', $type), ['description' => $title])); } if ('no_change' === $message) { - $type = strtolower((string)$journal->transactionType->type); + $type = strtolower((string) $journal->transactionType->type); session()->flash('warning_url', route('transactions.show', [$transactionGroupId])); - session()->flash('warning', (string)trans(sprintf('firefly.no_changes_%s', $type), ['description' => $title])); + session()->flash('warning', (string) trans(sprintf('firefly.no_changes_%s', $type), ['description' => $title])); } } @@ -151,7 +151,7 @@ class InterestingMessage $message = $request->get('message'); /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|UserGroup $userGroup */ $userGroup = UserGroup::find($userGroupId); @@ -170,15 +170,14 @@ class InterestingMessage return; } - if ('deleted' === $message) { - session()->flash('success', (string)trans('firefly.flash_administration_deleted', ['title' => $userGroup->title])); + session()->flash('success', (string) trans('firefly.flash_administration_deleted', ['title' => $userGroup->title])); } if ('created' === $message) { - session()->flash('success', (string)trans('firefly.flash_administration_created', ['title' => $userGroup->title])); + session()->flash('success', (string) trans('firefly.flash_administration_created', ['title' => $userGroup->title])); } if ('updated' === $message) { - session()->flash('success', (string)trans('firefly.flash_administration_updated', ['title' => $userGroup->title])); + session()->flash('success', (string) trans('firefly.flash_administration_updated', ['title' => $userGroup->title])); } } @@ -198,22 +197,22 @@ class InterestingMessage $message = $request->get('message'); /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|Account $account */ - $account = $user->accounts()->withTrashed()->find($accountId); + $account = $user->accounts()->withTrashed()->find($accountId); if (null === $account) { return; } if ('deleted' === $message) { - session()->flash('success', (string)trans('firefly.account_deleted', ['name' => $account->name])); + session()->flash('success', (string) trans('firefly.account_deleted', ['name' => $account->name])); } if ('created' === $message) { - session()->flash('success', (string)trans('firefly.stored_new_account', ['name' => $account->name])); + session()->flash('success', (string) trans('firefly.stored_new_account', ['name' => $account->name])); } if ('updated' === $message) { - session()->flash('success', (string)trans('firefly.updated_account', ['name' => $account->name])); + session()->flash('success', (string) trans('firefly.updated_account', ['name' => $account->name])); } } @@ -233,16 +232,16 @@ class InterestingMessage $message = $request->get('message'); /** @var null|Bill $bill */ - $bill = auth()->user()->bills()->withTrashed()->find($billId); + $bill = auth()->user()->bills()->withTrashed()->find($billId); if (null === $bill) { return; } if ('deleted' === $message) { - session()->flash('success', (string)trans('firefly.deleted_bill', ['name' => $bill->name])); + session()->flash('success', (string) trans('firefly.deleted_bill', ['name' => $bill->name])); } if ('created' === $message) { - session()->flash('success', (string)trans('firefly.stored_new_bill', ['name' => $bill->name])); + session()->flash('success', (string) trans('firefly.stored_new_bill', ['name' => $bill->name])); } } @@ -262,19 +261,19 @@ class InterestingMessage $message = $request->get('message'); /** @var null|Webhook $webhook */ - $webhook = auth()->user()->webhooks()->withTrashed()->find($webhookId); + $webhook = auth()->user()->webhooks()->withTrashed()->find($webhookId); if (null === $webhook) { return; } if ('deleted' === $message) { - session()->flash('success', (string)trans('firefly.deleted_webhook', ['title' => $webhook->title])); + session()->flash('success', (string) trans('firefly.deleted_webhook', ['title' => $webhook->title])); } if ('updated' === $message) { - session()->flash('success', (string)trans('firefly.updated_webhook', ['title' => $webhook->title])); + session()->flash('success', (string) trans('firefly.updated_webhook', ['title' => $webhook->title])); } if ('created' === $message) { - session()->flash('success', (string)trans('firefly.stored_new_webhook', ['title' => $webhook->title])); + session()->flash('success', (string) trans('firefly.stored_new_webhook', ['title' => $webhook->title])); } } @@ -301,22 +300,22 @@ class InterestingMessage } if ('enabled' === $message) { - session()->flash('success', (string)trans('firefly.currency_is_now_enabled', ['name' => $currency->name])); + session()->flash('success', (string) trans('firefly.currency_is_now_enabled', ['name' => $currency->name])); } if ('enable_failed' === $message) { - session()->flash('error', (string)trans('firefly.could_not_enable_currency', ['name' => $currency->name])); + session()->flash('error', (string) trans('firefly.could_not_enable_currency', ['name' => $currency->name])); } if ('disabled' === $message) { - session()->flash('success', (string)trans('firefly.currency_is_now_disabled', ['name' => $currency->name])); + session()->flash('success', (string) trans('firefly.currency_is_now_disabled', ['name' => $currency->name])); } if ('disable_failed' === $message) { - session()->flash('error', (string)trans('firefly.could_not_disable_currency', ['name' => $currency->name])); + session()->flash('error', (string) trans('firefly.could_not_disable_currency', ['name' => $currency->name])); } if ('default' === $message) { - session()->flash('success', (string)trans('firefly.new_default_currency', ['name' => $currency->name])); + session()->flash('success', (string) trans('firefly.new_default_currency', ['name' => $currency->name])); } if ('default_failed' === $message) { - session()->flash('error', (string)trans('firefly.default_currency_failed', ['name' => $currency->name])); + session()->flash('error', (string) trans('firefly.default_currency_failed', ['name' => $currency->name])); } } } diff --git a/app/Http/Middleware/IsAdmin.php b/app/Http/Middleware/IsAdmin.php index 2412e607b7..bda0f9ae6e 100644 --- a/app/Http/Middleware/IsAdmin.php +++ b/app/Http/Middleware/IsAdmin.php @@ -52,7 +52,7 @@ class IsAdmin } /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var UserRepositoryInterface $repository */ $repository = app(UserRepositoryInterface::class); diff --git a/app/Http/Middleware/IsDemoUser.php b/app/Http/Middleware/IsDemoUser.php index 13f004674c..80d9173872 100644 --- a/app/Http/Middleware/IsDemoUser.php +++ b/app/Http/Middleware/IsDemoUser.php @@ -23,11 +23,11 @@ declare(strict_types=1); namespace FireflyIII\Http\Middleware; -use Illuminate\Support\Facades\Log; use Closure; use FireflyIII\Repositories\User\UserRepositoryInterface; use FireflyIII\User; use Illuminate\Http\Request; +use Illuminate\Support\Facades\Log; /** * Class IsDemoUser. @@ -42,7 +42,7 @@ class IsDemoUser public function handle(Request $request, Closure $next) { /** @var null|User $user */ - $user = $request->user(); + $user = $request->user(); if (null === $user) { return $next($request); } diff --git a/app/Http/Middleware/Range.php b/app/Http/Middleware/Range.php index 3f8c30d595..24bdf491c4 100644 --- a/app/Http/Middleware/Range.php +++ b/app/Http/Middleware/Range.php @@ -23,18 +23,18 @@ declare(strict_types=1); namespace FireflyIII\Http\Middleware; -use FireflyIII\Support\Facades\Preferences; -use FireflyIII\Support\Facades\Navigation; use Carbon\Carbon; use Closure; use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Support\Facades\Amount; +use FireflyIII\Support\Facades\FireflyConfig; +use FireflyIII\Support\Facades\Navigation; +use FireflyIII\Support\Facades\Preferences; use FireflyIII\Support\Facades\Steam; use FireflyIII\Support\Http\Controllers\RequestInformation; use Illuminate\Http\Request; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Log; -use FireflyIII\Support\Facades\FireflyConfig; /** * Class SessionFilter. @@ -77,9 +77,9 @@ class Range $viewRange = '1M'; } - $today = today(config('app.timezone')); - $start = Navigation::updateStartDate((string) $viewRange, $today); - $end = Navigation::updateEndDate((string) $viewRange, $start); + $today = today(config('app.timezone')); + $start = Navigation::updateStartDate((string) $viewRange, $today); + $end = Navigation::updateEndDate((string) $viewRange, $start); app('session')->put('start', $start); app('session')->put('end', $end); @@ -105,15 +105,15 @@ class Range private function configureView(): void { // get locale preference: - $language = Steam::getLanguage(); - $locale = Steam::getLocale(); + $language = Steam::getLanguage(); + $locale = Steam::getLocale(); App::setLocale($language); Carbon::setLocale(substr($locale, 0, 2)); - $localeArray = Steam::getLocaleArray($locale); + $localeArray = Steam::getLocaleArray($locale); setlocale(LC_TIME, $localeArray); - $moneyResult = setlocale(LC_MONETARY, $localeArray); + $moneyResult = setlocale(LC_MONETARY, $localeArray); // send error to view, if it could not set money format if (false === $moneyResult) { @@ -127,7 +127,7 @@ class Range $primaryCurrency = Amount::getPrimaryCurrency(); // also format for moment JS: - $madMomentJS = (string) trans('config.month_and_day_moment_js', [], $locale); + $madMomentJS = (string) trans('config.month_and_day_moment_js', [], $locale); app('view')->share('madMomentJS', $madMomentJS); app('view')->share('monthAndDayFormat', $monthAndDayFormat); @@ -144,10 +144,7 @@ class Range app('view')->share('listLength', $pref); // share security message: - if ( - FireflyConfig::has('upgrade_security_message') - && FireflyConfig::has('upgrade_security_level') - ) { + if (FireflyConfig::has('upgrade_security_message') && FireflyConfig::has('upgrade_security_level')) { app('view')->share('upgrade_security_message', FireflyConfig::get('upgrade_security_message')->data); app('view')->share('upgrade_security_level', FireflyConfig::get('upgrade_security_level')->data); } diff --git a/app/Http/Middleware/SecureHeaders.php b/app/Http/Middleware/SecureHeaders.php index 246a9bf4a3..235bb5ef9c 100644 --- a/app/Http/Middleware/SecureHeaders.php +++ b/app/Http/Middleware/SecureHeaders.php @@ -45,16 +45,16 @@ class SecureHeaders public function handle(Request $request, Closure $next) { // generate and share nonce. - $nonce = base64_encode(random_bytes(16)); + $nonce = base64_encode(random_bytes(16)); Vite::useCspNonce($nonce); if (class_exists(Debugbar::class)) { Debugbar::getJavascriptRenderer()->setCspNonce($nonce); } app('view')->share('JS_NONCE', $nonce); - $response = $next($request); - $trackingScriptSrc = $this->getTrackingScriptSource(); - $csp = [ + $response = $next($request); + $trackingScriptSrc = $this->getTrackingScriptSource(); + $csp = [ "default-src 'none'", "object-src 'none'", sprintf("script-src 'unsafe-eval' 'strict-dynamic' 'nonce-%1s'", $nonce), @@ -63,7 +63,7 @@ class SecureHeaders "font-src 'self' data:", sprintf("connect-src 'self' %s", $trackingScriptSrc), sprintf("img-src 'self' data: 'nonce-%1s' ", $nonce), - "manifest-src 'self'", + "manifest-src 'self'" ]; // overrule in development mode @@ -77,14 +77,14 @@ class SecureHeaders "font-src 'self' data: https://10.0.0.15:5173/", sprintf("connect-src 'self' %s https://10.0.0.15:5173/ wss://10.0.0.15:5173/", $trackingScriptSrc), sprintf("img-src 'self' data: 'nonce-%1s'", $nonce), - "manifest-src 'self'", + "manifest-src 'self'" ]; } - $route = $request->route(); - $customUrl = ''; - $authGuard = (string) config('firefly.authentication_guard'); - $logoutUrl = (string) config('firefly.custom_logout_url'); + $route = $request->route(); + $customUrl = ''; + $authGuard = (string) config('firefly.authentication_guard'); + $logoutUrl = (string) config('firefly.custom_logout_url'); if ('remote_user_guard' === $authGuard && '' !== $logoutUrl) { $customUrl = $logoutUrl; } @@ -93,7 +93,7 @@ class SecureHeaders $csp[] = sprintf("form-action 'self' %s", $customUrl); } - $featurePolicies = [ + $featurePolicies = [ "geolocation 'none'", "midi 'none'", // "notifications 'none'", @@ -106,7 +106,7 @@ class SecureHeaders // "speaker 'none'", // "vibrate 'none'", "fullscreen 'self'", - "payment 'none'", + "payment 'none'" ]; $disableFrameHeader = config('firefly.disable_frame_header'); diff --git a/app/Http/Middleware/StartFireflySession.php b/app/Http/Middleware/StartFireflySession.php index 04847efef9..823702bffd 100644 --- a/app/Http/Middleware/StartFireflySession.php +++ b/app/Http/Middleware/StartFireflySession.php @@ -23,11 +23,11 @@ declare(strict_types=1); namespace FireflyIII\Http\Middleware; +use FireflyIII\Support\Facades\Steam; use Illuminate\Contracts\Session\Session; use Illuminate\Http\Request; use Illuminate\Session\Middleware\StartSession; use Override; -use FireflyIII\Support\Facades\Steam; /** * Class StartFireflySession. diff --git a/app/Http/Middleware/TrimStrings.php b/app/Http/Middleware/TrimStrings.php index d0362148b9..568446ced0 100644 --- a/app/Http/Middleware/TrimStrings.php +++ b/app/Http/Middleware/TrimStrings.php @@ -30,9 +30,5 @@ use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware; */ class TrimStrings extends Middleware { - protected $except - = [ - 'password', - 'password_confirmation', - ]; + protected $except = ['password', 'password_confirmation']; } diff --git a/app/Http/Middleware/TrustHosts.php b/app/Http/Middleware/TrustHosts.php index e41086a8db..5a370e0fe6 100644 --- a/app/Http/Middleware/TrustHosts.php +++ b/app/Http/Middleware/TrustHosts.php @@ -37,8 +37,6 @@ class TrustHosts extends Middleware #[Override] public function hosts(): array { - return [ - $this->allSubdomainsOfApplicationUrl(), - ]; + return [$this->allSubdomainsOfApplicationUrl()]; } } diff --git a/app/Http/Middleware/TrustProxies.php b/app/Http/Middleware/TrustProxies.php index a973d14e83..86741fd95c 100644 --- a/app/Http/Middleware/TrustProxies.php +++ b/app/Http/Middleware/TrustProxies.php @@ -32,13 +32,13 @@ use Symfony\Component\HttpFoundation\Request; class TrustProxies extends Middleware { // After... - protected $headers - = Request::HEADER_X_FORWARDED_FOR - | Request::HEADER_X_FORWARDED_HOST - | Request::HEADER_X_FORWARDED_PORT - | Request::HEADER_X_FORWARDED_PROTO - | Request::HEADER_X_FORWARDED_PREFIX - | Request::HEADER_X_FORWARDED_AWS_ELB; + protected $headers = + Request::HEADER_X_FORWARDED_FOR + | Request::HEADER_X_FORWARDED_HOST + | Request::HEADER_X_FORWARDED_PORT + | Request::HEADER_X_FORWARDED_PROTO + | Request::HEADER_X_FORWARDED_PREFIX + | Request::HEADER_X_FORWARDED_AWS_ELB; /** * TrustProxies constructor. diff --git a/app/Http/Middleware/VerifyCsrfToken.php b/app/Http/Middleware/VerifyCsrfToken.php index 748eae98b9..f6afc8d32d 100644 --- a/app/Http/Middleware/VerifyCsrfToken.php +++ b/app/Http/Middleware/VerifyCsrfToken.php @@ -30,8 +30,5 @@ use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware; */ class VerifyCsrfToken extends Middleware { - protected $except - = [ - 'oauth/token', - ]; + protected $except = ['oauth/token']; } diff --git a/app/Http/Requests/AccountFormRequest.php b/app/Http/Requests/AccountFormRequest.php index fc39adada9..cbff7df16d 100644 --- a/app/Http/Requests/AccountFormRequest.php +++ b/app/Http/Requests/AccountFormRequest.php @@ -23,18 +23,18 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Enums\UserRoleEnum; use FireflyIII\Models\Account; use FireflyIII\Models\Location; use FireflyIII\Rules\IsValidAmount; use FireflyIII\Rules\UniqueIban; +use FireflyIII\Support\Facades\Steam; use FireflyIII\Support\Request\AppendsLocationData; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; -use FireflyIII\Support\Facades\Steam; /** * Class AccountFormRequest. @@ -70,7 +70,7 @@ class AccountFormRequest extends FormRequest 'interest' => $this->convertString('interest'), 'interest_period' => $this->convertString('interest_period'), 'include_net_worth' => '1', - 'liability_direction' => $this->convertString('liability_direction'), + 'liability_direction' => $this->convertString('liability_direction') ]; $data = $this->appendLocationData($data, 'location'); @@ -85,7 +85,7 @@ class AccountFormRequest extends FormRequest // that could have been selected. if ('liabilities' === $data['account_type_name']) { $data['account_type_name'] = null; - $data['account_type_id'] = $this->convertInteger('liability_type_id'); + $data['account_type_id'] = $this->convertInteger('liability_type_id'); if ('' !== $data['opening_balance']) { // opening balance is always positive for liabilities $data['opening_balance'] = Steam::positive($data['opening_balance']); @@ -112,23 +112,23 @@ class AccountFormRequest extends FormRequest 'virtual_balance' => ['nullable', new IsValidAmount()], 'currency_id' => 'exists:transaction_currencies,id', 'account_number' => 'min:1|max:255|uniqueAccountNumberForUser|nullable', - 'account_role' => 'in:'.$accountRoles, + 'account_role' => 'in:' . $accountRoles, 'active' => 'boolean', - 'cc_type' => 'in:'.$ccPaymentTypes, + 'cc_type' => 'in:' . $ccPaymentTypes, 'amount_currency_id_opening_balance' => 'exists:transaction_currencies,id', 'amount_currency_id_virtual_balance' => 'exists:transaction_currencies,id', - 'what' => 'in:'.$types, + 'what' => 'in:' . $types, 'interest_period' => 'in:daily,monthly,yearly', - 'notes' => 'min:1|max:32768|nullable', + 'notes' => 'min:1|max:32768|nullable' ]; $rules = Location::requestRules($rules); /** @var null|Account $account */ - $account = $this->route()->parameter('account'); + $account = $this->route()->parameter('account'); if (null !== $account) { // add rules: - $rules['id'] = 'belongsToUser:accounts'; - $rules['name'] = 'required|max:1024|min:1|uniqueAccountForUser:'.$account->id; + $rules['id'] = 'belongsToUser:accounts'; + $rules['name'] = 'required|max:1024|min:1|uniqueAccountForUser:' . $account->id; $rules['iban'] = ['iban', 'nullable', new UniqueIban($account, $account->accountType->type)]; } diff --git a/app/Http/Requests/AttachmentFormRequest.php b/app/Http/Requests/AttachmentFormRequest.php index 2da2240168..2170e78388 100644 --- a/app/Http/Requests/AttachmentFormRequest.php +++ b/app/Http/Requests/AttachmentFormRequest.php @@ -23,9 +23,9 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -42,10 +42,7 @@ class AttachmentFormRequest extends FormRequest */ public function getAttachmentData(): array { - return [ - 'title' => $this->convertString('title'), - 'notes' => $this->convertString('notes'), - ]; + return ['title' => $this->convertString('title'), 'notes' => $this->convertString('notes')]; } /** @@ -54,10 +51,7 @@ class AttachmentFormRequest extends FormRequest public function rules(): array { // fixed - return [ - 'title' => 'min:1|max:255|nullable', - 'notes' => 'min:1|max:32768|nullable', - ]; + return ['title' => 'min:1|max:255|nullable', 'notes' => 'min:1|max:32768|nullable']; } public function withValidator(Validator $validator): void diff --git a/app/Http/Requests/BillStoreRequest.php b/app/Http/Requests/BillStoreRequest.php index 0f530a2191..a221687c9b 100644 --- a/app/Http/Requests/BillStoreRequest.php +++ b/app/Http/Requests/BillStoreRequest.php @@ -23,10 +23,10 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Rules\IsValidPositiveAmount; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -56,7 +56,7 @@ class BillStoreRequest extends FormRequest 'skip' => $this->convertInteger('skip'), 'notes' => $this->stringWithNewlines('notes'), 'active' => $this->boolean('active'), - 'object_group_title' => $this->convertString('object_group'), + 'object_group_title' => $this->convertString('object_group') ]; } @@ -76,7 +76,7 @@ class BillStoreRequest extends FormRequest 'extension_date' => 'nullable|date', 'repeat_freq' => sprintf('required|in:%s', implode(',', config('firefly.bill_periods'))), 'skip' => 'required|integer|gte:0|lte:31', - 'active' => 'boolean', + 'active' => 'boolean' ]; } diff --git a/app/Http/Requests/BillUpdateRequest.php b/app/Http/Requests/BillUpdateRequest.php index f4376c00b4..8ffabe5137 100644 --- a/app/Http/Requests/BillUpdateRequest.php +++ b/app/Http/Requests/BillUpdateRequest.php @@ -23,11 +23,11 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Models\Bill; use FireflyIII\Rules\IsValidPositiveAmount; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -57,7 +57,7 @@ class BillUpdateRequest extends FormRequest 'skip' => $this->convertInteger('skip'), 'notes' => $this->stringWithNewlines('notes'), 'active' => $this->boolean('active'), - 'object_group_title' => $this->convertString('object_group'), + 'object_group_title' => $this->convertString('object_group') ]; } @@ -80,7 +80,7 @@ class BillUpdateRequest extends FormRequest 'repeat_freq' => sprintf('required|in:%s', implode(',', config('firefly.bill_periods'))), 'skip' => 'required|integer|gte:0|lte:31', 'active' => 'boolean', - 'notes' => 'min:1|max:32768|nullable', + 'notes' => 'min:1|max:32768|nullable' ]; } diff --git a/app/Http/Requests/BudgetFormStoreRequest.php b/app/Http/Requests/BudgetFormStoreRequest.php index cb6c99f037..af3386067d 100644 --- a/app/Http/Requests/BudgetFormStoreRequest.php +++ b/app/Http/Requests/BudgetFormStoreRequest.php @@ -23,11 +23,11 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Rules\IsValidPositiveAmount; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; use FireflyIII\Validation\AutoBudget\ValidatesAutoBudgetRequest; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -51,7 +51,7 @@ class BudgetFormStoreRequest extends FormRequest 'auto_budget_type' => $this->convertInteger('auto_budget_type'), 'currency_id' => $this->convertInteger('auto_budget_currency_id'), 'auto_budget_amount' => $this->convertString('auto_budget_amount'), - 'auto_budget_period' => $this->convertString('auto_budget_period'), + 'auto_budget_period' => $this->convertString('auto_budget_period') ]; } @@ -67,7 +67,7 @@ class BudgetFormStoreRequest extends FormRequest 'auto_budget_currency_id' => 'exists:transaction_currencies,id', 'auto_budget_amount' => ['required_if:auto_budget_type,1', 'required_if:auto_budget_type,2', new IsValidPositiveAmount()], 'auto_budget_period' => 'in:daily,weekly,monthly,quarterly,half_year,yearly', - 'notes' => 'min:1|max:32768|nullable', + 'notes' => 'min:1|max:32768|nullable' ]; } @@ -76,12 +76,10 @@ class BudgetFormStoreRequest extends FormRequest */ public function withValidator(Validator $validator): void { - $validator->after( - function (Validator $validator): void { - // validate all account info - $this->validateAutoBudgetAmount($validator); - } - ); + $validator->after(function (Validator $validator): void { + // validate all account info + $this->validateAutoBudgetAmount($validator); + }); if ($validator->fails()) { Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray()); diff --git a/app/Http/Requests/BudgetFormUpdateRequest.php b/app/Http/Requests/BudgetFormUpdateRequest.php index 459665e50f..925278f5e2 100644 --- a/app/Http/Requests/BudgetFormUpdateRequest.php +++ b/app/Http/Requests/BudgetFormUpdateRequest.php @@ -23,12 +23,12 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Models\Budget; use FireflyIII\Rules\IsValidPositiveAmount; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; use FireflyIII\Validation\AutoBudget\ValidatesAutoBudgetRequest; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -47,13 +47,13 @@ class BudgetFormUpdateRequest extends FormRequest public function getBudgetData(): array { return [ - 'name' => $this->convertString('name'), - 'active' => $this->boolean('active'), - 'auto_budget_type' => $this->convertInteger('auto_budget_type'), - 'currency_id' => $this->convertInteger('auto_budget_currency_id'), - 'auto_budget_amount' => $this->convertString('auto_budget_amount'), - 'auto_budget_period' => $this->convertString('auto_budget_period'), - 'notes' => $this->stringWithNewlines('notes'), + 'name' => $this->convertString('name'), + 'active' => $this->boolean('active'), + 'auto_budget_type' => $this->convertInteger('auto_budget_type'), + 'currency_id' => $this->convertInteger('auto_budget_currency_id'), + 'auto_budget_amount' => $this->convertString('auto_budget_amount'), + 'auto_budget_period' => $this->convertString('auto_budget_period'), + 'notes' => $this->stringWithNewlines('notes') ]; } @@ -65,10 +65,10 @@ class BudgetFormUpdateRequest extends FormRequest $nameRule = 'required|min:1|max:255|uniqueObjectForUser:budgets,name'; /** @var null|Budget $budget */ - $budget = $this->route()->parameter('budget'); + $budget = $this->route()->parameter('budget'); if (null !== $budget) { - $nameRule = 'required|min:1|max:255|uniqueObjectForUser:budgets,name,'.$budget->id; + $nameRule = 'required|min:1|max:255|uniqueObjectForUser:budgets,name,' . $budget->id; } return [ @@ -78,7 +78,7 @@ class BudgetFormUpdateRequest extends FormRequest 'auto_budget_currency_id' => 'exists:transaction_currencies,id', 'auto_budget_amount' => ['required_if:auto_budget_type,1', 'required_if:auto_budget_type,2|numeric', new IsValidPositiveAmount()], 'auto_budget_period' => 'in:daily,weekly,monthly,quarterly,half_year,yearly', - 'notes' => 'min:1|max:32768|nullable', + 'notes' => 'min:1|max:32768|nullable' ]; } @@ -87,12 +87,10 @@ class BudgetFormUpdateRequest extends FormRequest */ public function withValidator(Validator $validator): void { - $validator->after( - function (Validator $validator): void { - // validate all account info - $this->validateAutoBudgetAmount($validator); - } - ); + $validator->after(function (Validator $validator): void { + // validate all account info + $this->validateAutoBudgetAmount($validator); + }); if ($validator->fails()) { Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray()); } diff --git a/app/Http/Requests/BudgetIncomeRequest.php b/app/Http/Requests/BudgetIncomeRequest.php index d0a2b96b17..7147bf572c 100644 --- a/app/Http/Requests/BudgetIncomeRequest.php +++ b/app/Http/Requests/BudgetIncomeRequest.php @@ -23,9 +23,9 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Rules\IsValidPositiveAmount; use FireflyIII\Support\Request\ChecksLogin; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -42,11 +42,7 @@ class BudgetIncomeRequest extends FormRequest public function rules(): array { // fixed - return [ - 'amount' => ['required', new IsValidPositiveAmount()], - 'start' => 'required|date|before:end', - 'end' => 'required|date|after:start', - ]; + return ['amount' => ['required', new IsValidPositiveAmount()], 'start' => 'required|date|before:end', 'end' => 'required|date|after:start']; } public function withValidator(Validator $validator): void diff --git a/app/Http/Requests/BulkEditJournalRequest.php b/app/Http/Requests/BulkEditJournalRequest.php index bcbbf533ca..089027b95a 100644 --- a/app/Http/Requests/BulkEditJournalRequest.php +++ b/app/Http/Requests/BulkEditJournalRequest.php @@ -23,9 +23,9 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -43,10 +43,7 @@ class BulkEditJournalRequest extends FormRequest public function rules(): array { // fixed - return [ - 'journals.*' => 'required|belongsToUser:transaction_journals,id', - 'tags_action' => 'in:no_nothing,do_replace,do_append', - ]; + return ['journals.*' => 'required|belongsToUser:transaction_journals,id', 'tags_action' => 'in:no_nothing,do_replace,do_append']; } public function withValidator(Validator $validator): void diff --git a/app/Http/Requests/CategoryFormRequest.php b/app/Http/Requests/CategoryFormRequest.php index 53e25c7be3..20227fb9dd 100644 --- a/app/Http/Requests/CategoryFormRequest.php +++ b/app/Http/Requests/CategoryFormRequest.php @@ -23,10 +23,10 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Models\Category; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -43,10 +43,7 @@ class CategoryFormRequest extends FormRequest */ public function getCategoryData(): array { - return [ - 'name' => $this->convertString('name'), - 'notes' => $this->stringWithNewlines('notes'), - ]; + return ['name' => $this->convertString('name'), 'notes' => $this->stringWithNewlines('notes')]; } /** @@ -60,14 +57,11 @@ class CategoryFormRequest extends FormRequest $category = $this->route()->parameter('category'); if (null !== $category) { - $nameRule = 'required|min:1|max:255|uniqueObjectForUser:categories,name,'.$category->id; + $nameRule = 'required|min:1|max:255|uniqueObjectForUser:categories,name,' . $category->id; } // fixed - return [ - 'name' => $nameRule, - 'notes' => 'min:1|max:32768|nullable', - ]; + return ['name' => $nameRule, 'notes' => 'min:1|max:32768|nullable']; } public function withValidator(Validator $validator): void diff --git a/app/Http/Requests/ConfigurationRequest.php b/app/Http/Requests/ConfigurationRequest.php index 1ac957a441..04a0f0fb40 100644 --- a/app/Http/Requests/ConfigurationRequest.php +++ b/app/Http/Requests/ConfigurationRequest.php @@ -40,19 +40,12 @@ class ConfigurationRequest extends FormRequest */ public function getConfigurationData(): array { - return [ - 'single_user_mode' => $this->boolean('single_user_mode'), - - 'enable_exchange_rates' => $this->boolean('enable_exchange_rates'), - 'use_running_balance' => $this->boolean('use_running_balance'), - - 'enable_external_map' => $this->boolean('enable_external_map'), - 'enable_external_rates' => $this->boolean('enable_external_rates'), - 'allow_webhooks' => $this->boolean('allow_webhooks'), - - 'valid_url_protocols' => $this->string('valid_url_protocols'), - 'is_demo_site' => $this->boolean('is_demo_site'), - ]; + return ['single_user_mode' => $this->boolean('single_user_mode'), + 'enable_exchange_rates' => $this->boolean('enable_exchange_rates'), 'use_running_balance' => $this->boolean('use_running_balance'), + 'enable_external_map' => $this->boolean( + 'enable_external_map' + ), 'enable_external_rates' => $this->boolean('enable_external_rates'), 'allow_webhooks' => $this->boolean('allow_webhooks'), + 'valid_url_protocols' => $this->string('valid_url_protocols'), 'is_demo_site' => $this->boolean('is_demo_site')]; } /** @@ -61,21 +54,10 @@ class ConfigurationRequest extends FormRequest public function rules(): array { // fixed - return [ - 'single_user_mode' => 'min:0|max:1|numeric', - - 'enable_exchange_rates' => 'min:0|max:1|numeric', - 'use_running_balance' => 'min:0|max:1|numeric', - - 'enable_external_map' => 'min:0|max:1|numeric', - 'enable_external_rates' => 'min:0|max:1|numeric', - 'allow_webhooks' => 'min:0|max:1|numeric', - - 'valid_url_protocols' => 'min:0|max:255', - 'is_demo_site' => 'min:0|max:1|numeric', - - - ]; + return ['single_user_mode' => 'min:0|max:1|numeric', + 'enable_exchange_rates' => 'min:0|max:1|numeric', 'use_running_balance' => 'min:0|max:1|numeric', + 'enable_external_map' => 'min:0|max:1|numeric', 'enable_external_rates' => 'min:0|max:1|numeric', 'allow_webhooks' => 'min:0|max:1|numeric', + 'valid_url_protocols' => 'min:0|max:255', 'is_demo_site' => 'min:0|max:1|numeric']; } public function withValidator(Validator $validator): void diff --git a/app/Http/Requests/CurrencyFormRequest.php b/app/Http/Requests/CurrencyFormRequest.php index 9a4f49672c..82a7c3b717 100644 --- a/app/Http/Requests/CurrencyFormRequest.php +++ b/app/Http/Requests/CurrencyFormRequest.php @@ -23,10 +23,10 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Models\TransactionCurrency; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -48,7 +48,7 @@ class CurrencyFormRequest extends FormRequest 'code' => $this->convertString('code'), 'symbol' => $this->convertString('symbol'), 'decimal_places' => $this->convertInteger('decimal_places'), - 'enabled' => $this->boolean('enabled'), + 'enabled' => $this->boolean('enabled') ]; } @@ -58,12 +58,12 @@ class CurrencyFormRequest extends FormRequest public function rules(): array { // fixed - $rules = [ + $rules = [ 'name' => 'required|max:48|min:1|uniqueCurrencyName', 'code' => 'required|min:3|max:51|uniqueCurrencyCode', 'symbol' => 'required|min:1|max:51|uniqueCurrencySymbol', 'decimal_places' => 'required|min:0|max:12|numeric', - 'enabled' => 'in:0,1', + 'enabled' => 'in:0,1' ]; /** @var null|TransactionCurrency $currency */ @@ -75,7 +75,7 @@ class CurrencyFormRequest extends FormRequest 'code' => 'required|min:3|max:51', 'symbol' => 'required|min:1|max:51', 'decimal_places' => 'required|min:0|max:12|numeric', - 'enabled' => 'in:0,1', + 'enabled' => 'in:0,1' ]; } diff --git a/app/Http/Requests/DeleteAccountFormRequest.php b/app/Http/Requests/DeleteAccountFormRequest.php index c06cba8b51..137e3fc8cc 100644 --- a/app/Http/Requests/DeleteAccountFormRequest.php +++ b/app/Http/Requests/DeleteAccountFormRequest.php @@ -23,8 +23,8 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Support\Request\ChecksLogin; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -41,9 +41,7 @@ class DeleteAccountFormRequest extends FormRequest public function rules(): array { // fixed - return [ - 'password' => 'required', - ]; + return ['password' => 'required']; } public function withValidator(Validator $validator): void diff --git a/app/Http/Requests/EmailFormRequest.php b/app/Http/Requests/EmailFormRequest.php index 26f2c66750..ef9b5fc17c 100644 --- a/app/Http/Requests/EmailFormRequest.php +++ b/app/Http/Requests/EmailFormRequest.php @@ -23,9 +23,9 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -43,9 +43,7 @@ class EmailFormRequest extends FormRequest public function rules(): array { // fixed - return [ - 'email' => 'required|email', - ]; + return ['email' => 'required|email']; } public function withValidator(Validator $validator): void diff --git a/app/Http/Requests/ExistingTokenFormRequest.php b/app/Http/Requests/ExistingTokenFormRequest.php index 37f7eb7867..844e0deafa 100644 --- a/app/Http/Requests/ExistingTokenFormRequest.php +++ b/app/Http/Requests/ExistingTokenFormRequest.php @@ -23,8 +23,8 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Support\Request\ChecksLogin; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -41,10 +41,7 @@ class ExistingTokenFormRequest extends FormRequest public function rules(): array { // fixed - return [ - 'password' => 'required|currentPassword', - 'code' => 'required|existingMfaCode', - ]; + return ['password' => 'required|currentPassword', 'code' => 'required|existingMfaCode']; } public function withValidator(Validator $validator): void diff --git a/app/Http/Requests/InviteUserFormRequest.php b/app/Http/Requests/InviteUserFormRequest.php index 5c71175d81..a217629017 100644 --- a/app/Http/Requests/InviteUserFormRequest.php +++ b/app/Http/Requests/InviteUserFormRequest.php @@ -24,9 +24,9 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -43,9 +43,7 @@ class InviteUserFormRequest extends FormRequest */ public function rules(): array { - return [ - 'invited_user' => 'required|email|unique:invited_users,email', - ]; + return ['invited_user' => 'required|email|unique:invited_users,email']; } public function withValidator(Validator $validator): void diff --git a/app/Http/Requests/JournalLinkRequest.php b/app/Http/Requests/JournalLinkRequest.php index f924a24ee6..9965393c00 100644 --- a/app/Http/Requests/JournalLinkRequest.php +++ b/app/Http/Requests/JournalLinkRequest.php @@ -23,10 +23,10 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Models\LinkType; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -43,13 +43,13 @@ class JournalLinkRequest extends FormRequest */ public function getLinkInfo(): array { - $return = []; - $linkType = $this->get('link_type'); - $parts = explode('_', (string) $linkType); - $return['link_type_id'] = (int) $parts[0]; + $return = []; + $linkType = $this->get('link_type'); + $parts = explode('_', (string) $linkType); + $return['link_type_id'] = (int) $parts[0]; $return['transaction_journal_id'] = $this->convertInteger('opposing'); - $return['notes'] = $this->convertString('notes'); - $return['direction'] = $parts[1]; + $return['notes'] = $this->convertString('notes'); + $return['direction'] = $parts[1]; return $return; } @@ -68,13 +68,10 @@ class JournalLinkRequest extends FormRequest $combinations[] = sprintf('%d_inward', $type->id); $combinations[] = sprintf('%d_outward', $type->id); } - $string = implode(',', $combinations); + $string = implode(',', $combinations); // fixed - return [ - 'link_type' => sprintf('required|in:%s', $string), - 'opposing' => 'belongsToUser:transaction_journals', - ]; + return ['link_type' => sprintf('required|in:%s', $string), 'opposing' => 'belongsToUser:transaction_journals']; } public function withValidator(Validator $validator): void diff --git a/app/Http/Requests/LinkTypeFormRequest.php b/app/Http/Requests/LinkTypeFormRequest.php index 202b3fe3b8..d865d30f47 100644 --- a/app/Http/Requests/LinkTypeFormRequest.php +++ b/app/Http/Requests/LinkTypeFormRequest.php @@ -23,9 +23,9 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -47,7 +47,7 @@ class LinkTypeFormRequest extends FormRequest $idRule = ''; // get parameter link: - $link = $this->route()->parameter('linkType'); + $link = $this->route()->parameter('linkType'); if (null !== $link) { $idRule = 'exists:link_types,id'; @@ -58,7 +58,7 @@ class LinkTypeFormRequest extends FormRequest 'id' => $idRule, 'name' => $nameRule, 'inward' => 'required|max:255|min:1|different:outward', - 'outward' => 'required|max:255|min:1|different:inward', + 'outward' => 'required|max:255|min:1|different:inward' ]; } diff --git a/app/Http/Requests/MassDeleteJournalRequest.php b/app/Http/Requests/MassDeleteJournalRequest.php index 5700ac4224..ce17bb8849 100644 --- a/app/Http/Requests/MassDeleteJournalRequest.php +++ b/app/Http/Requests/MassDeleteJournalRequest.php @@ -23,8 +23,8 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Support\Request\ChecksLogin; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -41,9 +41,7 @@ class MassDeleteJournalRequest extends FormRequest public function rules(): array { // fixed - return [ - 'confirm_mass_delete.*' => 'required|belongsToUser:transaction_journals,id', - ]; + return ['confirm_mass_delete.*' => 'required|belongsToUser:transaction_journals,id']; } public function withValidator(Validator $validator): void diff --git a/app/Http/Requests/MassEditJournalRequest.php b/app/Http/Requests/MassEditJournalRequest.php index d236c3abc0..ee758ea202 100644 --- a/app/Http/Requests/MassEditJournalRequest.php +++ b/app/Http/Requests/MassEditJournalRequest.php @@ -23,8 +23,8 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Support\Request\ChecksLogin; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -48,7 +48,7 @@ class MassEditJournalRequest extends FormRequest 'destination_id.*' => 'numeric|belongsToUser:accounts,id', 'journals.*' => 'numeric|belongsToUser:transaction_journals,id', 'revenue_account' => 'max:255', - 'expense_account' => 'max:255', + 'expense_account' => 'max:255' ]; } diff --git a/app/Http/Requests/NewUserFormRequest.php b/app/Http/Requests/NewUserFormRequest.php index 1d0da88187..96dc44f82e 100644 --- a/app/Http/Requests/NewUserFormRequest.php +++ b/app/Http/Requests/NewUserFormRequest.php @@ -23,10 +23,10 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Rules\IsValidAmount; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -51,7 +51,7 @@ class NewUserFormRequest extends FormRequest 'credit_card_limit' => ['nullable', new IsValidAmount()], 'amount_currency_id_bank_balance' => 'exists:transaction_currencies,id', 'amount_currency_id_savings_balance' => 'exists:transaction_currencies,id', - 'amount_currency_id_credit_card_limit' => 'exists:transaction_currencies,id', + 'amount_currency_id_credit_card_limit' => 'exists:transaction_currencies,id' ]; } diff --git a/app/Http/Requests/NotificationRequest.php b/app/Http/Requests/NotificationRequest.php index 9ac3569206..ed34eee513 100644 --- a/app/Http/Requests/NotificationRequest.php +++ b/app/Http/Requests/NotificationRequest.php @@ -36,24 +36,24 @@ class NotificationRequest extends FormRequest public function getAll(): array { - $return = []; + $return = []; foreach (config('notifications.notifications.owner') as $key => $info) { - $value = false; + $value = false; if ($this->has(sprintf('notification_%s', $key))) { $value = true; } $return[$key] = $value; } - $return['slack_webhook_url'] = $this->convertString('slack_webhook_url'); + $return['slack_webhook_url'] = $this->convertString('slack_webhook_url'); - $return['pushover_app_token'] = $this->convertString('pushover_app_token'); + $return['pushover_app_token'] = $this->convertString('pushover_app_token'); $return['pushover_user_token'] = $this->convertString('pushover_user_token'); - $return['ntfy_server'] = $this->convertString('ntfy_server'); - $return['ntfy_topic'] = $this->convertString('ntfy_topic'); - $return['ntfy_auth'] = $this->convertBoolean($this->get('ntfy_auth')); - $return['ntfy_user'] = $this->convertString('ntfy_user'); - $return['ntfy_pass'] = $this->convertString('ntfy_pass'); + $return['ntfy_server'] = $this->convertString('ntfy_server'); + $return['ntfy_topic'] = $this->convertString('ntfy_topic'); + $return['ntfy_auth'] = $this->convertBoolean($this->get('ntfy_auth')); + $return['ntfy_user'] = $this->convertString('ntfy_user'); + $return['ntfy_pass'] = $this->convertString('ntfy_pass'); return $return; } @@ -67,7 +67,7 @@ class NotificationRequest extends FormRequest 'slack_webhook_url' => ['nullable', 'url', 'min:1', new IsValidSlackOrDiscordUrl()], 'ntfy_server' => ['nullable', 'url', 'min:1'], 'ntfy_user' => ['required_with:ntfy_pass,ntfy_auth', 'nullable', 'string', 'min:1'], - 'ntfy_pass' => ['required_with:ntfy_user,ntfy_auth', 'nullable', 'string', 'min:1'], + 'ntfy_pass' => ['required_with:ntfy_user,ntfy_auth', 'nullable', 'string', 'min:1'] ]; foreach (config('notifications.notifications.owner') as $key => $info) { $rules[sprintf('notification_%s', $key)] = 'in:0,1'; diff --git a/app/Http/Requests/ObjectGroupFormRequest.php b/app/Http/Requests/ObjectGroupFormRequest.php index 5febc46231..3c01066593 100644 --- a/app/Http/Requests/ObjectGroupFormRequest.php +++ b/app/Http/Requests/ObjectGroupFormRequest.php @@ -23,10 +23,10 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Models\ObjectGroup; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -43,9 +43,7 @@ class ObjectGroupFormRequest extends FormRequest */ public function getObjectGroupData(): array { - return [ - 'title' => $this->convertString('title'), - ]; + return ['title' => $this->convertString('title')]; } /** @@ -61,9 +59,7 @@ class ObjectGroupFormRequest extends FormRequest $titleRule = sprintf('required|min:1|max:255|uniqueObjectGroup:%d', $objectGroup->id); } - return [ - 'title' => $titleRule, - ]; + return ['title' => $titleRule]; } public function withValidator(Validator $validator): void diff --git a/app/Http/Requests/PiggyBankStoreRequest.php b/app/Http/Requests/PiggyBankStoreRequest.php index 9a1daf4a83..cf30d262c0 100644 --- a/app/Http/Requests/PiggyBankStoreRequest.php +++ b/app/Http/Requests/PiggyBankStoreRequest.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\TransactionCurrency; use FireflyIII\Repositories\Account\AccountRepositoryInterface; @@ -31,6 +30,7 @@ use FireflyIII\Rules\IsValidPositiveAmount; use FireflyIII\Support\Facades\Amount; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -55,13 +55,13 @@ class PiggyBankStoreRequest extends FormRequest 'transaction_currency_id' => $this->convertInteger('transaction_currency_id'), 'target_date' => $this->getCarbonDate('target_date'), 'notes' => $this->stringWithNewlines('notes'), - 'object_group_title' => $this->convertString('object_group'), + 'object_group_title' => $this->convertString('object_group') ]; if (!is_array($accounts)) { $accounts = []; } foreach ($accounts as $item) { - $data['accounts'][] = ['account_id' => (int)$item]; + $data['accounts'][] = ['account_id' => (int) $item]; } return $data; @@ -81,7 +81,7 @@ class PiggyBankStoreRequest extends FormRequest 'target_date' => 'date|nullable', 'order' => 'integer|min:1', 'object_group' => 'min:0|max:255', - 'notes' => 'min:1|max:32768|nullable', + 'notes' => 'min:1|max:32768|nullable' ]; } @@ -89,33 +89,31 @@ class PiggyBankStoreRequest extends FormRequest { // need to have more than one account. // accounts need to have the same currency or be multi-currency(?). - $validator->after( - function (Validator $validator): void { - // validate start before end only if both are there. - $data = $validator->getData(); - $currency = $this->getCurrencyFromData($data); - if (array_key_exists('accounts', $data) && is_array($data['accounts'])) { - $repository = app(AccountRepositoryInterface::class); - $types = config('firefly.piggy_bank_account_types'); - foreach ($data['accounts'] as $value) { - $accountId = (int)$value; - $account = $repository->find($accountId); - if (null !== $account) { - // check currency here. - $accountCurrency = $repository->getAccountCurrency($account); - $isMultiCurrency = $repository->getMetaValue($account, 'is_multi_currency'); - if ($accountCurrency->id !== $currency->id && 'true' !== $isMultiCurrency) { - $validator->errors()->add('accounts', trans('validation.invalid_account_currency')); - } - $type = $account->accountType->type; - if (!in_array($type, $types, true)) { - $validator->errors()->add('accounts', trans('validation.invalid_account_type')); - } + $validator->after(function (Validator $validator): void { + // validate start before end only if both are there. + $data = $validator->getData(); + $currency = $this->getCurrencyFromData($data); + if (array_key_exists('accounts', $data) && is_array($data['accounts'])) { + $repository = app(AccountRepositoryInterface::class); + $types = config('firefly.piggy_bank_account_types'); + foreach ($data['accounts'] as $value) { + $accountId = (int) $value; + $account = $repository->find($accountId); + if (null !== $account) { + // check currency here. + $accountCurrency = $repository->getAccountCurrency($account); + $isMultiCurrency = $repository->getMetaValue($account, 'is_multi_currency'); + if ($accountCurrency->id !== $currency->id && 'true' !== $isMultiCurrency) { + $validator->errors()->add('accounts', trans('validation.invalid_account_currency')); + } + $type = $account->accountType->type; + if (!in_array($type, $types, true)) { + $validator->errors()->add('accounts', trans('validation.invalid_account_type')); } } } } - ); + }); if ($validator->fails()) { Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray()); @@ -124,7 +122,7 @@ class PiggyBankStoreRequest extends FormRequest private function getCurrencyFromData(array $data): TransactionCurrency { - $currencyId = (int)($data['transaction_currency_id'] ?? 0); + $currencyId = (int) ($data['transaction_currency_id'] ?? 0); try { $currency = Amount::getTransactionCurrencyById($currencyId); diff --git a/app/Http/Requests/PiggyBankUpdateRequest.php b/app/Http/Requests/PiggyBankUpdateRequest.php index 0657f63a9a..8f6755523f 100644 --- a/app/Http/Requests/PiggyBankUpdateRequest.php +++ b/app/Http/Requests/PiggyBankUpdateRequest.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\PiggyBank; use FireflyIII\Models\TransactionCurrency; @@ -32,6 +31,7 @@ use FireflyIII\Rules\IsValidPositiveAmount; use FireflyIII\Support\Facades\Amount; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -56,7 +56,7 @@ class PiggyBankUpdateRequest extends FormRequest 'target_date' => $this->getCarbonDate('target_date'), 'transaction_currency_id' => $this->convertInteger('transaction_currency_id'), 'notes' => $this->stringWithNewlines('notes'), - 'object_group_title' => $this->convertString('object_group'), + 'object_group_title' => $this->convertString('object_group') ]; if (!is_array($accounts)) { $accounts = []; @@ -86,41 +86,38 @@ class PiggyBankUpdateRequest extends FormRequest 'target_date' => 'date|nullable', 'order' => 'integer|max:32768|min:1', 'object_group' => 'min:0|max:255', - 'notes' => 'min:1|max:32768|nullable', + 'notes' => 'min:1|max:32768|nullable' ]; } public function withValidator(Validator $validator): void - { // need to have more than one account. + { // need to have more than one account. // accounts need to have the same currency or be multi-currency(?). - $validator->after( - function (Validator $validator): void { - // validate start before end only if both are there. - $data = $validator->getData(); - $currency = $this->getCurrencyFromData($data); - if (array_key_exists('accounts', $data) && is_array($data['accounts'])) { - $repository = app(AccountRepositoryInterface::class); - $types = config('firefly.piggy_bank_account_types'); - foreach ($data['accounts'] as $value) { - $accountId = (int) $value; - $account = $repository->find($accountId); - if (null !== $account) { - // check currency here. - $accountCurrency = $repository->getAccountCurrency($account); - $isMultiCurrency = $repository->getMetaValue($account, 'is_multi_currency'); - if ($accountCurrency->id !== $currency->id && 'true' !== $isMultiCurrency) { - $validator->errors()->add('accounts', trans('validation.invalid_account_currency')); - } - $type = $account->accountType->type; - if (!in_array($type, $types, true)) { - $validator->errors()->add('accounts', trans('validation.invalid_account_type')); - } + $validator->after(function (Validator $validator): void { + // validate start before end only if both are there. + $data = $validator->getData(); + $currency = $this->getCurrencyFromData($data); + if (array_key_exists('accounts', $data) && is_array($data['accounts'])) { + $repository = app(AccountRepositoryInterface::class); + $types = config('firefly.piggy_bank_account_types'); + foreach ($data['accounts'] as $value) { + $accountId = (int) $value; + $account = $repository->find($accountId); + if (null !== $account) { + // check currency here. + $accountCurrency = $repository->getAccountCurrency($account); + $isMultiCurrency = $repository->getMetaValue($account, 'is_multi_currency'); + if ($accountCurrency->id !== $currency->id && 'true' !== $isMultiCurrency) { + $validator->errors()->add('accounts', trans('validation.invalid_account_currency')); + } + $type = $account->accountType->type; + if (!in_array($type, $types, true)) { + $validator->errors()->add('accounts', trans('validation.invalid_account_type')); } } } } - ); - + }); if ($validator->fails()) { Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray()); diff --git a/app/Http/Requests/PreferencesRequest.php b/app/Http/Requests/PreferencesRequest.php index ca8236c464..120dcc8c57 100644 --- a/app/Http/Requests/PreferencesRequest.php +++ b/app/Http/Requests/PreferencesRequest.php @@ -41,7 +41,7 @@ class PreferencesRequest extends FormRequest 'slack_webhook_url' => ['nullable', 'url', 'min:1', new IsValidSlackOrDiscordUrl()], 'ntfy_server' => ['nullable', 'url', 'min:1'], 'ntfy_user' => ['required_with:ntfy_pass,ntfy_auth', 'nullable', 'string', 'min:1'], - 'ntfy_pass' => ['required_with:ntfy_user,ntfy_auth', 'nullable', 'string', 'min:1'], + 'ntfy_pass' => ['required_with:ntfy_user,ntfy_auth', 'nullable', 'string', 'min:1'] ]; foreach (config('notifications.notifications.user') as $key => $info) { $rules[sprintf('notification_%s', $key)] = 'in:0,1'; diff --git a/app/Http/Requests/ProfileFormRequest.php b/app/Http/Requests/ProfileFormRequest.php index 65034257b9..8531582a5f 100644 --- a/app/Http/Requests/ProfileFormRequest.php +++ b/app/Http/Requests/ProfileFormRequest.php @@ -23,8 +23,8 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Support\Request\ChecksLogin; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -44,7 +44,7 @@ class ProfileFormRequest extends FormRequest return [ 'current_password' => 'required', 'new_password' => 'required|confirmed|secure_password|min:16', - 'new_password_confirmation' => 'required', + 'new_password_confirmation' => 'required' ]; } diff --git a/app/Http/Requests/ReconciliationStoreRequest.php b/app/Http/Requests/ReconciliationStoreRequest.php index d3f8645888..b106f8601c 100644 --- a/app/Http/Requests/ReconciliationStoreRequest.php +++ b/app/Http/Requests/ReconciliationStoreRequest.php @@ -24,11 +24,11 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Rules\IsValidAmount; use FireflyIII\Rules\ValidJournals; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -49,14 +49,14 @@ class ReconciliationStoreRequest extends FormRequest if (!is_array($transactions)) { $transactions = []; } - $data = [ + $data = [ 'start' => $this->getCarbonDate('start'), 'end' => $this->getCarbonDate('end'), 'start_balance' => $this->convertString('startBalance'), 'end_balance' => $this->convertString('endBalance'), 'difference' => $this->convertString('difference'), 'journals' => $transactions, - 'reconcile' => $this->convertString('reconcile'), + 'reconcile' => $this->convertString('reconcile') ]; Log::debug('In ReconciliationStoreRequest::getAll(). Will now return data.'); @@ -75,7 +75,7 @@ class ReconciliationStoreRequest extends FormRequest 'endBalance' => ['nullable', new IsValidAmount()], 'difference' => ['required', new IsValidAmount()], 'journals' => [new ValidJournals()], - 'reconcile' => 'required|in:create,nothing', + 'reconcile' => 'required|in:create,nothing' ]; } diff --git a/app/Http/Requests/RecurrenceFormRequest.php b/app/Http/Requests/RecurrenceFormRequest.php index 0a3f0a9c1c..f919c0e4b5 100644 --- a/app/Http/Requests/RecurrenceFormRequest.php +++ b/app/Http/Requests/RecurrenceFormRequest.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Factory\CategoryFactory; @@ -35,6 +34,7 @@ use FireflyIII\Rules\ValidRecurrenceRepetitionValue; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; use FireflyIII\Validation\AccountValidator; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -55,8 +55,8 @@ class RecurrenceFormRequest extends FormRequest */ public function getAll(): array { - $repetitionData = $this->parseRepetitionData(); - $return = [ + $repetitionData = $this->parseRepetitionData(); + $return = [ 'recurrence' => [ 'type' => $this->convertString('transaction_type'), 'title' => $this->convertString('title'), @@ -66,64 +66,60 @@ class RecurrenceFormRequest extends FormRequest 'nr_of_repetitions' => $this->convertInteger('repetitions'), 'apply_rules' => $this->boolean('apply_rules'), 'active' => $this->boolean('active'), - 'repetition_end' => $this->convertString('repetition_end'), - ], - 'transactions' => [ - [ - 'currency_id' => $this->convertInteger('transaction_currency_id'), - 'currency_code' => null, - 'type' => $this->convertString('transaction_type'), - 'description' => $this->convertString('transaction_description'), - 'amount' => $this->convertString('amount'), - 'foreign_amount' => null, - 'foreign_currency_id' => null, - 'foreign_currency_code' => null, - 'budget_id' => $this->convertInteger('budget_id'), - 'budget_name' => null, - 'bill_id' => $this->convertInteger('bill_id'), - 'bill_name' => null, - 'category_id' => null, - 'category_name' => $this->convertString('category'), - 'tags' => '' !== $this->convertString('tags') ? explode(',', $this->convertString('tags')) : [], - 'piggy_bank_id' => $this->convertInteger('piggy_bank_id'), - 'piggy_bank_name' => null, - ], - ], - 'repetitions' => [ - [ - 'type' => $repetitionData['type'], - 'moment' => $repetitionData['moment'], - 'skip' => $this->convertInteger('skip'), - 'weekend' => $this->convertInteger('weekend'), - ], + 'repetition_end' => $this->convertString('repetition_end') ], + 'transactions' => [[ + 'currency_id' => $this->convertInteger('transaction_currency_id'), + 'currency_code' => null, + 'type' => $this->convertString('transaction_type'), + 'description' => $this->convertString('transaction_description'), + 'amount' => $this->convertString('amount'), + 'foreign_amount' => null, + 'foreign_currency_id' => null, + 'foreign_currency_code' => null, + 'budget_id' => $this->convertInteger('budget_id'), + 'budget_name' => null, + 'bill_id' => $this->convertInteger('bill_id'), + 'bill_name' => null, + 'category_id' => null, + 'category_name' => $this->convertString('category'), + 'tags' => '' !== $this->convertString('tags') ? explode(',', $this->convertString('tags')) : [], + 'piggy_bank_id' => $this->convertInteger('piggy_bank_id'), + 'piggy_bank_name' => null + ]], + 'repetitions' => [[ + 'type' => $repetitionData['type'], + 'moment' => $repetitionData['moment'], + 'skip' => $this->convertInteger('skip'), + 'weekend' => $this->convertInteger('weekend') + ]] ]; // fill in foreign currency data if (null !== $this->convertFloat('foreign_amount')) { // intentional float, used because it defaults to null. - $return['transactions'][0]['foreign_amount'] = $this->convertString('foreign_amount'); + $return['transactions'][0]['foreign_amount'] = $this->convertString('foreign_amount'); $return['transactions'][0]['foreign_currency_id'] = $this->convertInteger('foreign_currency_id'); } // default values: - $return['transactions'][0]['source_id'] = null; - $return['transactions'][0]['source_name'] = null; - $return['transactions'][0]['destination_id'] = null; + $return['transactions'][0]['source_id'] = null; + $return['transactions'][0]['source_name'] = null; + $return['transactions'][0]['destination_id'] = null; $return['transactions'][0]['destination_name'] = null; - $throwError = true; - $type = $this->convertString('transaction_type'); + $throwError = true; + $type = $this->convertString('transaction_type'); if ('withdrawal' === $type) { - $throwError = false; - $return['transactions'][0]['source_id'] = $this->convertInteger('source_id'); + $throwError = false; + $return['transactions'][0]['source_id'] = $this->convertInteger('source_id'); $return['transactions'][0]['destination_id'] = $this->convertInteger('withdrawal_destination_id'); } if ('deposit' === $type) { - $throwError = false; - $return['transactions'][0]['source_id'] = $this->convertInteger('deposit_source_id'); + $throwError = false; + $return['transactions'][0]['source_id'] = $this->convertInteger('deposit_source_id'); $return['transactions'][0]['destination_id'] = $this->convertInteger('destination_id'); } if ('transfer' === $type) { - $throwError = false; - $return['transactions'][0]['source_id'] = $this->convertInteger('source_id'); + $throwError = false; + $return['transactions'][0]['source_id'] = $this->convertInteger('source_id'); $return['transactions'][0]['destination_id'] = $this->convertInteger('destination_id'); } if ($throwError) { @@ -131,7 +127,7 @@ class RecurrenceFormRequest extends FormRequest } // replace category name with a new category: - $factory = app(CategoryFactory::class); + $factory = app(CategoryFactory::class); $factory->setUser(auth()->user()); /** @@ -157,10 +153,7 @@ class RecurrenceFormRequest extends FormRequest private function parseRepetitionData(): array { $value = $this->convertString('repetition_type'); - $return = [ - 'type' => '', - 'moment' => '', - ]; + $return = ['type' => '', 'moment' => '']; if ('daily' === $value) { $return['type'] = $value; @@ -168,15 +161,15 @@ class RecurrenceFormRequest extends FormRequest // monthly,17 // ndom,3,7 if (in_array(substr($value, 0, 6), ['yearly', 'weekly'], true)) { - $return['type'] = substr($value, 0, 6); + $return['type'] = substr($value, 0, 6); $return['moment'] = substr($value, 7); } if (str_starts_with($value, 'monthly')) { - $return['type'] = substr($value, 0, 7); + $return['type'] = substr($value, 0, 7); $return['moment'] = substr($value, 8); } if (str_starts_with($value, 'ndom')) { - $return['type'] = substr($value, 0, 4); + $return['type'] = substr($value, 0, 4); $return['moment'] = substr($value, 5); } @@ -188,20 +181,20 @@ class RecurrenceFormRequest extends FormRequest */ public function rules(): array { - $today = today(config('app.timezone')); - $tomorrow = today(config('app.timezone'))->addDay(); - $before = today(config('app.timezone'))->addYears(25); - $rules = [ + $today = today(config('app.timezone')); + $tomorrow = today(config('app.timezone'))->addDay(); + $before = today(config('app.timezone'))->addYears(25); + $rules = [ // mandatory info for recurrence. - 'title' => 'required|min:1|max:255|uniqueObjectForUser:recurrences,title', - 'first_date' => sprintf('required|date|before:%s|after:%s', $before->format('Y-m-d'), $today->format('Y-m-d')), - 'repetition_type' => ['required', new ValidRecurrenceRepetitionValue(), new ValidRecurrenceRepetitionType(), 'min:1', 'max:32'], - 'skip' => 'required|numeric|integer|gte:0|lte:31', - 'notes' => 'min:1|max:32768|nullable', + 'title' => 'required|min:1|max:255|uniqueObjectForUser:recurrences,title', + 'first_date' => sprintf('required|date|before:%s|after:%s', $before->format('Y-m-d'), $today->format('Y-m-d')), + 'repetition_type' => ['required', new ValidRecurrenceRepetitionValue(), new ValidRecurrenceRepetitionType(), 'min:1', 'max:32'], + 'skip' => 'required|numeric|integer|gte:0|lte:31', + 'notes' => 'min:1|max:32768|nullable', // optional for recurrence: - 'recurring_description' => 'min:0|max:32768', - 'active' => 'numeric|min:0|max:1', - 'apply_rules' => 'numeric|min:0|max:1', + 'recurring_description' => 'min:0|max:32768', + 'active' => 'numeric|min:0|max:1', + 'apply_rules' => 'numeric|min:0|max:1', // mandatory for transaction: 'transaction_description' => 'required|min:1|max:255', @@ -209,19 +202,19 @@ class RecurrenceFormRequest extends FormRequest 'transaction_currency_id' => 'required|exists:transaction_currencies,id', 'amount' => ['required', new IsValidPositiveAmount()], // mandatory account info: - 'source_id' => 'numeric|belongsToUser:accounts,id|nullable', - 'source_name' => 'min:1|max:255|nullable', - 'destination_id' => 'numeric|belongsToUser:accounts,id|nullable', - 'destination_name' => 'min:1|max:255|nullable', + 'source_id' => 'numeric|belongsToUser:accounts,id|nullable', + 'source_name' => 'min:1|max:255|nullable', + 'destination_id' => 'numeric|belongsToUser:accounts,id|nullable', + 'destination_name' => 'min:1|max:255|nullable', // foreign amount data: - 'foreign_amount' => ['nullable', new IsValidPositiveAmount()], + 'foreign_amount' => ['nullable', new IsValidPositiveAmount()], // optional fields: - 'budget_id' => 'mustExist:budgets,id|belongsToUser:budgets,id|nullable', - 'bill_id' => 'mustExist:bills,id|belongsToUser:bills,id|nullable', - 'category' => 'min:1|max:255|nullable', - 'tags' => 'min:1|max:255|nullable', + 'budget_id' => 'mustExist:budgets,id|belongsToUser:budgets,id|nullable', + 'bill_id' => 'mustExist:bills,id|belongsToUser:bills,id|nullable', + 'category' => 'min:1|max:255|nullable', + 'tags' => 'min:1|max:255|nullable' ]; if ($this->convertInteger('foreign_currency_id') > 0) { $rules['foreign_currency_id'] = 'exists:transaction_currencies,id'; @@ -238,22 +231,22 @@ class RecurrenceFormRequest extends FormRequest // if ends at date X, set another rule. if ('until_date' === $this->convertString('repetition_end')) { - $rules['repeat_until'] = 'required|date|after:'.$tomorrow->format('Y-m-d'); + $rules['repeat_until'] = 'required|date|after:' . $tomorrow->format('Y-m-d'); } // switch on type to expand rules for source and destination accounts: - $type = strtolower($this->convertString('transaction_type')); + $type = strtolower($this->convertString('transaction_type')); if (strtolower(TransactionTypeEnum::WITHDRAWAL->value) === $type) { - $rules['source_id'] = 'required|exists:accounts,id|belongsToUser:accounts'; + $rules['source_id'] = 'required|exists:accounts,id|belongsToUser:accounts'; $rules['destination_name'] = 'min:1|max:255|nullable'; } if (strtolower(TransactionTypeEnum::DEPOSIT->value) === $type) { - $rules['source_name'] = 'min:1|max:255|nullable'; + $rules['source_name'] = 'min:1|max:255|nullable'; $rules['destination_id'] = 'required|exists:accounts,id|belongsToUser:accounts'; } if (strtolower(TransactionTypeEnum::TRANSFER->value) === $type) { // this may not work: - $rules['source_id'] = 'required|exists:accounts,id|belongsToUser:accounts|different:destination_id'; + $rules['source_id'] = 'required|exists:accounts,id|belongsToUser:accounts|different:destination_id'; $rules['destination_id'] = 'required|exists:accounts,id|belongsToUser:accounts|different:source_id'; } @@ -261,8 +254,8 @@ class RecurrenceFormRequest extends FormRequest /** @var null|Recurrence $recurrence */ $recurrence = $this->route()->parameter('recurrence'); if ($recurrence instanceof Recurrence) { - $rules['id'] = 'required|numeric|exists:recurrences,id'; - $rules['title'] = 'required|min:1|max:255|uniqueObjectForUser:recurrences,title,'.$recurrence->id; + $rules['id'] = 'required|numeric|exists:recurrences,id'; + $rules['title'] = 'required|min:1|max:255|uniqueObjectForUser:recurrences,title,' . $recurrence->id; $rules['first_date'] = 'required|date'; } @@ -274,12 +267,10 @@ class RecurrenceFormRequest extends FormRequest */ public function withValidator(Validator $validator): void { - $validator->after( - function (Validator $validator): void { - // validate all account info - $this->validateAccountInformation($validator); - } - ); + $validator->after(function (Validator $validator): void { + // validate all account info + $this->validateAccountInformation($validator); + }); if ($validator->fails()) { Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray()); } @@ -302,13 +293,13 @@ class RecurrenceFormRequest extends FormRequest $accountValidator->setTransactionType($transactionType); // default values: - $sourceId = null; - $destinationId = null; + $sourceId = null; + $destinationId = null; // TODO typeOverrule: the account validator may have another opinion the transaction type. // TODO either use 'withdrawal' or the strtolower() variant, not both. - $type = $this->convertString('transaction_type'); - $throwError = true; + $type = $this->convertString('transaction_type'); + $throwError = true; if ('withdrawal' === $type) { $throwError = false; $sourceId = (int) $data['source_id']; @@ -329,7 +320,7 @@ class RecurrenceFormRequest extends FormRequest } // validate source account. - $validSource = $accountValidator->validateSource(['id' => $sourceId]); + $validSource = $accountValidator->validateSource(['id' => $sourceId]); // do something with result: if (false === $validSource) { diff --git a/app/Http/Requests/ReportFormRequest.php b/app/Http/Requests/ReportFormRequest.php index 344a95a70b..0ce0e165f8 100644 --- a/app/Http/Requests/ReportFormRequest.php +++ b/app/Http/Requests/ReportFormRequest.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use Carbon\Carbon; use Exception; use FireflyIII\Exceptions\FireflyException; @@ -32,6 +31,7 @@ use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Repositories\Category\CategoryRepositoryInterface; use FireflyIII\Repositories\Tag\TagRepositoryInterface; use FireflyIII\Support\Request\ChecksLogin; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; @@ -143,7 +143,7 @@ class ReportFormRequest extends FormRequest $range = $this->get('daterange'); $parts = explode(' - ', (string) $range); if (2 === count($parts)) { - $string = $parts[1]; + $string = $parts[1]; // validate as date // if regex for YYYY-MM-DD: $pattern = '/^(19|20)\d\d-(0[1-9]|1[012])-(0[1-9]|[12][\d]|3[01])$/'; @@ -161,7 +161,7 @@ class ReportFormRequest extends FormRequest return $date; } - $error = sprintf('"%s" is not a valid date range: %s', $range, 'invalid format :('); + $error = sprintf('"%s" is not a valid date range: %s', $range, 'invalid format :('); Log::error($error); throw new FireflyException($error, 0); @@ -182,7 +182,7 @@ class ReportFormRequest extends FormRequest $range = $this->get('daterange'); $parts = explode(' - ', (string) $range); if (2 === count($parts)) { - $string = $parts[0]; + $string = $parts[0]; // validate as date // if regex for YYYY-MM-DD: $pattern = '/^(19|20)\d\d-(0[1-9]|1[012])-(0[1-9]|[12][\d]|3[01])$/'; @@ -200,7 +200,7 @@ class ReportFormRequest extends FormRequest return $date; } - $error = sprintf('"%s" is not a valid date range: %s', $range, 'invalid format :('); + $error = sprintf('"%s" is not a valid date range: %s', $range, 'invalid format :('); Log::error($error); throw new FireflyException($error, 0); @@ -248,9 +248,7 @@ class ReportFormRequest extends FormRequest */ public function rules(): array { - return [ - 'report_type' => 'in:audit,default,category,budget,tag,double', - ]; + return ['report_type' => 'in:audit,default,category,budget,tag,double']; } public function withValidator(Validator $validator): void diff --git a/app/Http/Requests/RuleFormRequest.php b/app/Http/Requests/RuleFormRequest.php index 7698156a5a..8da4c55e8c 100644 --- a/app/Http/Requests/RuleFormRequest.php +++ b/app/Http/Requests/RuleFormRequest.php @@ -23,12 +23,12 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Models\Rule; use FireflyIII\Rules\IsValidActionExpression; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; use FireflyIII\Support\Request\GetRuleConfiguration; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -56,7 +56,7 @@ class RuleFormRequest extends FormRequest 'strict' => $this->boolean('strict'), 'run_after_form' => $this->boolean('run_after_form'), 'triggers' => $this->getRuleTriggerData(), - 'actions' => $this->getRuleActionData(), + 'actions' => $this->getRuleActionData() ]; } @@ -72,10 +72,10 @@ class RuleFormRequest extends FormRequest 'type' => $trigger['type'] ?? 'invalid', 'value' => $trigger['value'] ?? '', 'stop_processing' => 1 === (int) $stopProcessing, - 'prohibited' => 1 === (int) $prohibited, + 'prohibited' => 1 === (int) $prohibited ]; $set = self::replaceAmountTrigger($set); - $return[] = $set; + $return[] = $set; } } @@ -98,7 +98,7 @@ class RuleFormRequest extends FormRequest 'foreign_amount_less', 'foreign_amount_max', 'foreign_amount_more', - 'foreign_amount_min', + 'foreign_amount_min' ]; if (in_array($array['type'], $amountFields, true) && '0' === $array['value']) { $array['value'] = '0.00'; @@ -114,10 +114,10 @@ class RuleFormRequest extends FormRequest if (is_array($actionData)) { foreach ($actionData as $action) { $stopProcessing = $action['stop_processing'] ?? '0'; - $return[] = [ + $return[] = [ 'type' => $action['type'] ?? 'invalid', 'value' => $action['value'] ?? '', - 'stop_processing' => 1 === (int) $stopProcessing, + 'stop_processing' => 1 === (int) $stopProcessing ]; } } @@ -130,35 +130,35 @@ class RuleFormRequest extends FormRequest */ public function rules(): array { - $validTriggers = $this->getTriggers(); - $validActions = array_keys(config('firefly.rule-actions')); + $validTriggers = $this->getTriggers(); + $validActions = array_keys(config('firefly.rule-actions')); // some actions require text (aka context): - $contextActions = implode(',', config('firefly.context-rule-actions')); + $contextActions = implode(',', config('firefly.context-rule-actions')); // some triggers require text (aka context): $contextTriggers = implode(',', $this->getTriggersWithContext()); // initial set of rules: - $rules = [ - 'title' => 'required|min:1|max:255|uniqueObjectForUser:rules,title', - 'description' => 'min:1|max:32768|nullable', - 'stop_processing' => 'boolean', - 'rule_group_id' => 'required|belongsToUser:rule_groups', - 'trigger' => 'required|in:store-journal,update-journal,manual-activation', - 'triggers.*.type' => 'required|in:'.implode(',', $validTriggers), - 'triggers.*.value' => sprintf('required_if:triggers.*.type,%s|max:1024|min:1|ruleTriggerValue', $contextTriggers), - 'actions.*.type' => 'required|in:'.implode(',', $validActions), - 'actions.*.value' => [sprintf('required_if:actions.*.type,%s|min:0|max:1024', $contextActions), new IsValidActionExpression(), 'ruleActionValue'], - 'strict' => 'in:0,1', - 'run_after_form' => 'in:0,1', + $rules = [ + 'title' => 'required|min:1|max:255|uniqueObjectForUser:rules,title', + 'description' => 'min:1|max:32768|nullable', + 'stop_processing' => 'boolean', + 'rule_group_id' => 'required|belongsToUser:rule_groups', + 'trigger' => 'required|in:store-journal,update-journal,manual-activation', + 'triggers.*.type' => 'required|in:' . implode(',', $validTriggers), + 'triggers.*.value' => sprintf('required_if:triggers.*.type,%s|max:1024|min:1|ruleTriggerValue', $contextTriggers), + 'actions.*.type' => 'required|in:' . implode(',', $validActions), + 'actions.*.value' => [sprintf('required_if:actions.*.type,%s|min:0|max:1024', $contextActions), new IsValidActionExpression(), 'ruleActionValue'], + 'strict' => 'in:0,1', + 'run_after_form' => 'in:0,1' ]; /** @var null|Rule $rule */ - $rule = $this->route()->parameter('rule'); + $rule = $this->route()->parameter('rule'); if (null !== $rule) { - $rules['title'] = 'required|min:1|max:255|uniqueObjectForUser:rules,title,'.$rule->id; + $rules['title'] = 'required|min:1|max:255|uniqueObjectForUser:rules,title,' . $rule->id; } return $rules; diff --git a/app/Http/Requests/RuleGroupFormRequest.php b/app/Http/Requests/RuleGroupFormRequest.php index f73cff0b74..e24c00cc19 100644 --- a/app/Http/Requests/RuleGroupFormRequest.php +++ b/app/Http/Requests/RuleGroupFormRequest.php @@ -23,11 +23,11 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Models\RuleGroup; use FireflyIII\Rules\IsBoolean; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -49,11 +49,7 @@ class RuleGroupFormRequest extends FormRequest $active = $this->boolean('active'); } - return [ - 'title' => $this->convertString('title'), - 'description' => $this->stringWithNewlines('description'), - 'active' => $active, - ]; + return ['title' => $this->convertString('title'), 'description' => $this->stringWithNewlines('description'), 'active' => $active]; } /** @@ -67,14 +63,10 @@ class RuleGroupFormRequest extends FormRequest $ruleGroup = $this->route()->parameter('ruleGroup'); if (null !== $ruleGroup) { - $titleRule = 'required|min:1|max:255|uniqueObjectForUser:rule_groups,title,'.$ruleGroup->id; + $titleRule = 'required|min:1|max:255|uniqueObjectForUser:rule_groups,title,' . $ruleGroup->id; } - return [ - 'title' => $titleRule, - 'description' => 'min:1|max:32768|nullable', - 'active' => [new IsBoolean()], - ]; + return ['title' => $titleRule, 'description' => 'min:1|max:32768|nullable', 'active' => [new IsBoolean()]]; } public function withValidator(Validator $validator): void diff --git a/app/Http/Requests/SelectTransactionsRequest.php b/app/Http/Requests/SelectTransactionsRequest.php index d5564d7bc4..b46ee656a9 100644 --- a/app/Http/Requests/SelectTransactionsRequest.php +++ b/app/Http/Requests/SelectTransactionsRequest.php @@ -23,8 +23,8 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Support\Request\ChecksLogin; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -40,10 +40,7 @@ class SelectTransactionsRequest extends FormRequest */ public function rules(): array { - return [ - 'accounts' => 'required', - 'accounts.*' => 'required|exists:accounts,id|belongsToUser:accounts', - ]; + return ['accounts' => 'required', 'accounts.*' => 'required|exists:accounts,id|belongsToUser:accounts']; } public function withValidator(Validator $validator): void diff --git a/app/Http/Requests/TagFormRequest.php b/app/Http/Requests/TagFormRequest.php index 069ffd5ef3..a2330e02c0 100644 --- a/app/Http/Requests/TagFormRequest.php +++ b/app/Http/Requests/TagFormRequest.php @@ -23,12 +23,12 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Models\Location; use FireflyIII\Models\Tag; use FireflyIII\Support\Request\AppendsLocationData; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -49,7 +49,7 @@ class TagFormRequest extends FormRequest $data = [ 'tag' => $this->convertString('tag'), 'date' => $this->getCarbonDate('date'), - 'description' => $this->convertString('description'), + 'description' => $this->convertString('description') ]; return $this->appendLocationData($data, 'location'); @@ -60,21 +60,21 @@ class TagFormRequest extends FormRequest */ public function rules(): array { - $idRule = ''; + $idRule = ''; /** @var null|Tag $tag */ $tag = $this->route()->parameter('tag'); $tagRule = 'required|max:1024|min:1|uniqueObjectForUser:tags,tag'; if (null !== $tag) { $idRule = 'belongsToUser:tags'; - $tagRule = 'required|max:1024|min:1|uniqueObjectForUser:tags,tag,'.$tag->id; + $tagRule = 'required|max:1024|min:1|uniqueObjectForUser:tags,tag,' . $tag->id; } - $rules = [ + $rules = [ 'tag' => $tagRule, 'id' => $idRule, 'description' => 'max:32768|min:1|nullable', - 'date' => 'date|nullable|after:1970-01-02|before:2038-01-17', + 'date' => 'date|nullable|after:1970-01-02|before:2038-01-17' ]; return Location::requestRules($rules); diff --git a/app/Http/Requests/TestRuleFormRequest.php b/app/Http/Requests/TestRuleFormRequest.php index fa4e289e4e..4c9125025b 100644 --- a/app/Http/Requests/TestRuleFormRequest.php +++ b/app/Http/Requests/TestRuleFormRequest.php @@ -23,9 +23,9 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\GetRuleConfiguration; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -47,8 +47,8 @@ class TestRuleFormRequest extends FormRequest $validTriggers = $this->getTriggers(); return [ - 'rule-trigger.*' => 'required|max:1024|min:1|in:'.implode(',', $validTriggers), - 'rule-trigger-value.*' => 'required|max:1024|min:1|ruleTriggerValue', + 'rule-trigger.*' => 'required|max:1024|min:1|in:' . implode(',', $validTriggers), + 'rule-trigger-value.*' => 'required|max:1024|min:1|ruleTriggerValue' ]; } diff --git a/app/Http/Requests/TokenFormRequest.php b/app/Http/Requests/TokenFormRequest.php index 19c0f3bc06..814a3bd037 100644 --- a/app/Http/Requests/TokenFormRequest.php +++ b/app/Http/Requests/TokenFormRequest.php @@ -23,8 +23,8 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Support\Request\ChecksLogin; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -41,10 +41,7 @@ class TokenFormRequest extends FormRequest public function rules(): array { // fixed - return [ - 'password' => 'required|currentPassword', - 'code' => 'required|2faCode', - ]; + return ['password' => 'required|currentPassword', 'code' => 'required|2faCode']; } public function withValidator(Validator $validator): void diff --git a/app/Http/Requests/TriggerRecurrenceRequest.php b/app/Http/Requests/TriggerRecurrenceRequest.php index 36d16331d6..a919053c15 100644 --- a/app/Http/Requests/TriggerRecurrenceRequest.php +++ b/app/Http/Requests/TriggerRecurrenceRequest.php @@ -24,9 +24,9 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -43,9 +43,7 @@ class TriggerRecurrenceRequest extends FormRequest */ public function getAll(): array { - return [ - 'date' => $this->getCarbonDate('date'), - ]; + return ['date' => $this->getCarbonDate('date')]; } /** @@ -53,9 +51,7 @@ class TriggerRecurrenceRequest extends FormRequest */ public function rules(): array { - return [ - 'date' => 'required|date', - ]; + return ['date' => 'required|date']; } public function withValidator(Validator $validator): void diff --git a/app/Http/Requests/UserFormRequest.php b/app/Http/Requests/UserFormRequest.php index cc89dff35b..4bcde99dd4 100644 --- a/app/Http/Requests/UserFormRequest.php +++ b/app/Http/Requests/UserFormRequest.php @@ -23,9 +23,9 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -47,7 +47,7 @@ class UserFormRequest extends FormRequest 'blocked' => 1 === $this->convertInteger('blocked'), 'blocked_code' => $this->convertString('blocked_code'), 'password' => $this->convertString('password'), - 'is_owner' => 1 === $this->convertInteger('is_owner'), + 'is_owner' => 1 === $this->convertInteger('is_owner') ]; } @@ -62,7 +62,7 @@ class UserFormRequest extends FormRequest 'password' => 'confirmed|secure_password', 'blocked_code' => 'min:0|max:32|nullable', 'blocked' => 'min:0|max:1|numeric', - 'is_owner' => 'min:0|max:1|numeric', + 'is_owner' => 'min:0|max:1|numeric' ]; } diff --git a/app/Http/Requests/UserRegistrationRequest.php b/app/Http/Requests/UserRegistrationRequest.php index 8bd3504ea3..70ef9ac79e 100644 --- a/app/Http/Requests/UserRegistrationRequest.php +++ b/app/Http/Requests/UserRegistrationRequest.php @@ -23,8 +23,8 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Support\Request\ChecksLogin; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Log; @@ -50,10 +50,7 @@ class UserRegistrationRequest extends FormRequest public function rules(): array { // fixed - return [ - 'email' => 'email|required', - 'password' => 'confirmed|secure_password', - ]; + return ['email' => 'email|required', 'password' => 'confirmed|secure_password']; } public function withValidator(Validator $validator): void diff --git a/app/Jobs/CreateAutoBudgetLimits.php b/app/Jobs/CreateAutoBudgetLimits.php index e645306a99..9639082839 100644 --- a/app/Jobs/CreateAutoBudgetLimits.php +++ b/app/Jobs/CreateAutoBudgetLimits.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Jobs; -use FireflyIII\Support\Facades\Navigation; use Carbon\Carbon; use FireflyIII\Enums\AutoBudgetType; use FireflyIII\Exceptions\FireflyException; @@ -32,6 +31,7 @@ use FireflyIII\Models\AutoBudget; use FireflyIII\Models\Budget; use FireflyIII\Models\BudgetLimit; use FireflyIII\Repositories\Budget\OperationsRepositoryInterface; +use FireflyIII\Support\Facades\Navigation; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; @@ -55,10 +55,10 @@ class CreateAutoBudgetLimits implements ShouldQueue /** * Create a new job instance. */ - public function __construct(?Carbon $date) + public function __construct(null|Carbon $date) { if ($date instanceof Carbon) { - $newDate = clone $date; + $newDate = clone $date; $newDate->startOfDay(); $this->date = $newDate; Log::debug(sprintf('Created new CreateAutoBudgetLimits("%s")', $this->date->format('Y-m-d'))); @@ -97,34 +97,30 @@ class CreateAutoBudgetLimits implements ShouldQueue return; } if (!$this->isMagicDay($autoBudget)) { - Log::info( - sprintf( - 'Today (%s) is not a magic day for %s auto-budget #%d (part of budget #%d "%s")', - $this->date->format('Y-m-d'), - $autoBudget->period, - $autoBudget->id, - $autoBudget->budget->id, - $autoBudget->budget->name - ) - ); - Log::debug(sprintf('Done with auto budget #%d', $autoBudget->id)); - - return; - } - Log::info( - sprintf( - 'Today (%s) is a magic day for %s auto-budget #%d (part of budget #%d "%s")', + Log::info(sprintf( + 'Today (%s) is not a magic day for %s auto-budget #%d (part of budget #%d "%s")', $this->date->format('Y-m-d'), $autoBudget->period, $autoBudget->id, $autoBudget->budget->id, $autoBudget->budget->name - ) - ); + )); + Log::debug(sprintf('Done with auto budget #%d', $autoBudget->id)); + + return; + } + Log::info(sprintf( + 'Today (%s) is a magic day for %s auto-budget #%d (part of budget #%d "%s")', + $this->date->format('Y-m-d'), + $autoBudget->period, + $autoBudget->id, + $autoBudget->budget->id, + $autoBudget->budget->name + )); // get date range for budget limit, based on range in auto-budget - $start = Navigation::startOfPeriod($this->date, $autoBudget->period); - $end = Navigation::endOfPeriod($start, $autoBudget->period); + $start = Navigation::startOfPeriod($this->date, $autoBudget->period); + $end = Navigation::endOfPeriod($start, $autoBudget->period); // find budget limit: $budgetLimit = $this->findBudgetLimit($autoBudget->budget, $start, $end); @@ -193,39 +189,34 @@ class CreateAutoBudgetLimits implements ShouldQueue throw new FireflyException(sprintf('isMagicDay() can\'t handle period "%s"', $autoBudget->period)); } - private function findBudgetLimit(Budget $budget, Carbon $start, Carbon $end): ?BudgetLimit + private function findBudgetLimit(Budget $budget, Carbon $start, Carbon $end): null|BudgetLimit { - Log::debug( - sprintf( - 'Going to find a budget limit for budget #%d ("%s") between %s and %s', - $budget->id, - $budget->name, - $start->format('Y-m-d'), - $end->format('Y-m-d') - ) - ); + Log::debug(sprintf( + 'Going to find a budget limit for budget #%d ("%s") between %s and %s', + $budget->id, + $budget->name, + $start->format('Y-m-d'), + $end->format('Y-m-d') + )); /** @var null|BudgetLimit */ - return $budget->budgetlimits() - ->where('start_date', $start->format('Y-m-d')) - ->where('end_date', $end->format('Y-m-d'))->first() - ; + return $budget->budgetlimits()->where('start_date', $start->format('Y-m-d'))->where('end_date', $end->format('Y-m-d'))->first(); } - private function createBudgetLimit(AutoBudget $autoBudget, Carbon $start, Carbon $end, ?string $amount = null): void + private function createBudgetLimit(AutoBudget $autoBudget, Carbon $start, Carbon $end, null|string $amount = null): void { Log::debug(sprintf('No budget limit exist. Must create one for auto-budget #%d', $autoBudget->id)); if (null !== $amount) { Log::debug(sprintf('Amount is overruled and will be set to %s', $amount)); } - $budgetLimit = new BudgetLimit(); + $budgetLimit = new BudgetLimit(); $budgetLimit->budget()->associate($autoBudget->budget); $budgetLimit->transactionCurrency()->associate($autoBudget->transactionCurrency); $budgetLimit->start_date = clone $start; - $budgetLimit->end_date = clone $end; - $budgetLimit->amount = $amount ?? $autoBudget->amount; - $budgetLimit->period = $autoBudget->period; - $budgetLimit->generated = 1; + $budgetLimit->end_date = clone $end; + $budgetLimit->amount = $amount ?? $autoBudget->amount; + $budgetLimit->period = $autoBudget->period; + $budgetLimit->generated = 1; $budgetLimit->save(); Log::debug(sprintf('Created budget limit #%d.', $budgetLimit->id)); @@ -238,25 +229,23 @@ class CreateAutoBudgetLimits implements ShouldQueue { Log::debug(sprintf('Will now manage rollover for auto budget #%d', $autoBudget->id)); // current period: - $start = Navigation::startOfPeriod($this->date, $autoBudget->period); - $end = Navigation::endOfPeriod($start, $autoBudget->period); + $start = Navigation::startOfPeriod($this->date, $autoBudget->period); + $end = Navigation::endOfPeriod($start, $autoBudget->period); // which means previous period: $previousStart = Navigation::subtractPeriod($start, $autoBudget->period); $previousEnd = Navigation::endOfPeriod($previousStart, $autoBudget->period); - Log::debug( - sprintf( - 'Current period is %s-%s, so previous period is %s-%s', - $start->format('Y-m-d'), - $end->format('Y-m-d'), - $previousStart->format('Y-m-d'), - $previousEnd->format('Y-m-d') - ) - ); + Log::debug(sprintf( + 'Current period is %s-%s, so previous period is %s-%s', + $start->format('Y-m-d'), + $end->format('Y-m-d'), + $previousStart->format('Y-m-d'), + $previousEnd->format('Y-m-d') + )); // has budget limit in previous period? - $budgetLimit = $this->findBudgetLimit($autoBudget->budget, $previousStart, $previousEnd); + $budgetLimit = $this->findBudgetLimit($autoBudget->budget, $previousStart, $previousEnd); if (!$budgetLimit instanceof BudgetLimit) { Log::debug('No budget limit exists in previous period, so create one.'); @@ -268,17 +257,23 @@ class CreateAutoBudgetLimits implements ShouldQueue } Log::debug('Budget limit exists for previous period.'); // if has one, calculate expenses and use that as a base. - $repository = app(OperationsRepositoryInterface::class); + $repository = app(OperationsRepositoryInterface::class); $repository->setUser($autoBudget->budget->user); - $spent = $repository->sumExpenses($previousStart, $previousEnd, null, new Collection()->push($autoBudget->budget), $autoBudget->transactionCurrency); - $currencyId = $autoBudget->transaction_currency_id; - $spentAmount = $spent[$currencyId]['sum'] ?? '0'; + $spent = $repository->sumExpenses( + $previousStart, + $previousEnd, + null, + new Collection()->push($autoBudget->budget), + $autoBudget->transactionCurrency + ); + $currencyId = $autoBudget->transaction_currency_id; + $spentAmount = $spent[$currencyId]['sum'] ?? '0'; Log::debug(sprintf('Spent in previous budget period (%s-%s) is %s', $previousStart->format('Y-m-d'), $previousEnd->format('Y-m-d'), $spentAmount)); // if you spent more in previous budget period, than whatever you had previous budget period, the amount resets // previous budget limit + spent - $budgetLeft = bcadd($budgetLimit->amount, $spentAmount); - $totalAmount = $autoBudget->amount; + $budgetLeft = bcadd($budgetLimit->amount, $spentAmount); + $totalAmount = $autoBudget->amount; Log::debug(sprintf('Total amount left for previous budget period is %s', $budgetLeft)); if (-1 !== bccomp('0', $budgetLeft)) { @@ -298,25 +293,23 @@ class CreateAutoBudgetLimits implements ShouldQueue { Log::debug(sprintf('Will now manage rollover for auto budget #%d', $autoBudget->id)); // current period: - $start = Navigation::startOfPeriod($this->date, $autoBudget->period); - $end = Navigation::endOfPeriod($start, $autoBudget->period); + $start = Navigation::startOfPeriod($this->date, $autoBudget->period); + $end = Navigation::endOfPeriod($start, $autoBudget->period); // which means previous period: - $previousStart = Navigation::subtractPeriod($start, $autoBudget->period); - $previousEnd = Navigation::endOfPeriod($previousStart, $autoBudget->period); + $previousStart = Navigation::subtractPeriod($start, $autoBudget->period); + $previousEnd = Navigation::endOfPeriod($previousStart, $autoBudget->period); - Log::debug( - sprintf( - 'Current period is %s-%s, so previous period is %s-%s', - $start->format('Y-m-d'), - $end->format('Y-m-d'), - $previousStart->format('Y-m-d'), - $previousEnd->format('Y-m-d') - ) - ); + Log::debug(sprintf( + 'Current period is %s-%s, so previous period is %s-%s', + $start->format('Y-m-d'), + $end->format('Y-m-d'), + $previousStart->format('Y-m-d'), + $previousEnd->format('Y-m-d') + )); // has budget limit in previous period? - $budgetLimit = $this->findBudgetLimit($autoBudget->budget, $previousStart, $previousEnd); + $budgetLimit = $this->findBudgetLimit($autoBudget->budget, $previousStart, $previousEnd); if (!$budgetLimit instanceof BudgetLimit) { Log::debug('No budget limit exists in previous period, so create one.'); @@ -328,11 +321,17 @@ class CreateAutoBudgetLimits implements ShouldQueue Log::debug('Budget limit exists for previous period.'); // if has one, calculate expenses and use that as a base. - $repository = app(OperationsRepositoryInterface::class); + $repository = app(OperationsRepositoryInterface::class); $repository->setUser($autoBudget->budget->user); - $spent = $repository->sumExpenses($previousStart, $previousEnd, null, new Collection()->push($autoBudget->budget), $autoBudget->transactionCurrency); - $currencyId = $autoBudget->transaction_currency_id; - $spentAmount = $spent[$currencyId]['sum'] ?? '0'; + $spent = $repository->sumExpenses( + $previousStart, + $previousEnd, + null, + new Collection()->push($autoBudget->budget), + $autoBudget->transactionCurrency + ); + $currencyId = $autoBudget->transaction_currency_id; + $spentAmount = $spent[$currencyId]['sum'] ?? '0'; Log::debug(sprintf('Spent in previous budget period (%s-%s) is %s', $previousStart->format('Y-m-d'), $previousEnd->format('Y-m-d'), $spentAmount)); // what you spent in previous period PLUS the amount for the current period, @@ -362,7 +361,7 @@ class CreateAutoBudgetLimits implements ShouldQueue public function setDate(Carbon $date): void { - $newDate = clone $date; + $newDate = clone $date; $newDate->startOfDay(); $this->date = $newDate; } diff --git a/app/Jobs/CreateRecurringTransactions.php b/app/Jobs/CreateRecurringTransactions.php index 73324ac830..7559492c1d 100644 --- a/app/Jobs/CreateRecurringTransactions.php +++ b/app/Jobs/CreateRecurringTransactions.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Jobs; -use FireflyIII\Support\Facades\Preferences; use Carbon\Carbon; use FireflyIII\Events\RequestedReportOnJournals; use FireflyIII\Events\StoredTransactionGroup; @@ -37,6 +36,7 @@ use FireflyIII\Models\TransactionGroup; use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Repositories\Recurring\RecurringRepositoryInterface; use FireflyIII\Repositories\TransactionGroup\TransactionGroupRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; @@ -55,40 +55,40 @@ class CreateRecurringTransactions implements ShouldQueue use Queueable; use SerializesModels; - public int $created; - public int $executed; - public int $submitted; - private Carbon $date; - private bool $force; + public int $created; + public int $executed; + public int $submitted; + private Carbon $date; + private bool $force; private TransactionGroupRepositoryInterface $groupRepository; - private Collection $groups; - private JournalRepositoryInterface $journalRepository; - private Collection $recurrences; - private RecurringRepositoryInterface $repository; + private Collection $groups; + private JournalRepositoryInterface $journalRepository; + private Collection $recurrences; + private RecurringRepositoryInterface $repository; /** * Create a new job instance. */ - public function __construct(?Carbon $date) + public function __construct(null|Carbon $date) { - $newDate = new Carbon(); + $newDate = new Carbon(); $newDate->startOfDay(); - $this->date = $newDate; + $this->date = $newDate; if ($date instanceof Carbon) { - $newDate = clone $date; + $newDate = clone $date; $newDate->startOfDay(); $this->date = $newDate; } - $this->repository = app(RecurringRepositoryInterface::class); + $this->repository = app(RecurringRepositoryInterface::class); $this->journalRepository = app(JournalRepositoryInterface::class); - $this->groupRepository = app(TransactionGroupRepositoryInterface::class); - $this->force = false; - $this->submitted = 0; - $this->executed = 0; - $this->created = 0; - $this->recurrences = new Collection(); - $this->groups = new Collection(); + $this->groupRepository = app(TransactionGroupRepositoryInterface::class); + $this->force = false; + $this->submitted = 0; + $this->executed = 0; + $this->created = 0; + $this->recurrences = new Collection(); + $this->groups = new Collection(); Log::debug(sprintf('Created new CreateRecurringTransactions("%s")', $this->date->format('Y-m-d'))); } @@ -114,13 +114,13 @@ class CreateRecurringTransactions implements ShouldQueue $this->recurrences = $this->repository->getAll(); } - $result = []; - $count = $this->recurrences->count(); + $result = []; + $count = $this->recurrences->count(); $this->submitted = $count; Log::debug(sprintf('Count of collection is %d', $count)); // filter recurrences: - $filtered = $this->filterRecurrences($this->recurrences); + $filtered = $this->filterRecurrences($this->recurrences); Log::debug(sprintf('Left after filtering is %d', $filtered->count())); /** @var Recurrence $recurrence */ @@ -136,7 +136,7 @@ class CreateRecurringTransactions implements ShouldQueue Preferences::setForUser($recurrence->user, 'lastActivity', microtime()); Log::debug(sprintf('Now at recurrence #%d of user #%d', $recurrence->id, $recurrence->user_id)); - $createdReps = $this->handleRepetitions($recurrence); + $createdReps = $this->handleRepetitions($recurrence); Log::debug(sprintf('Done with recurrence #%d', $recurrence->id)); $result[$recurrence->user_id] = $result[$recurrence->user_id]->merge($createdReps); ++$this->executed; @@ -156,9 +156,7 @@ class CreateRecurringTransactions implements ShouldQueue private function filterRecurrences(Collection $recurrences): Collection { - return $recurrences->filter( - $this->validRecurrence(...) - ); + return $recurrences->filter($this->validRecurrence(...)); } /** @@ -185,28 +183,24 @@ class CreateRecurringTransactions implements ShouldQueue // is no longer running if ($this->repeatUntilHasPassed($recurrence)) { - Log::info( - sprintf( - 'Recurrence #%d was set to run until %s, and today\'s date is %s. Skipped.', - $recurrence->id, - $recurrence->repeat_until->format('Y-m-d'), - $this->date->format('Y-m-d') - ) - ); + Log::info(sprintf( + 'Recurrence #%d was set to run until %s, and today\'s date is %s. Skipped.', + $recurrence->id, + $recurrence->repeat_until->format('Y-m-d'), + $this->date->format('Y-m-d') + )); return false; } // first_date is in the future if ($this->hasNotStartedYet($recurrence)) { - Log::info( - sprintf( - 'Recurrence #%d is set to run on %s, and today\'s date is %s. Skipped.', - $recurrence->id, - $recurrence->first_date->format('Y-m-d H:i:s'), - $this->date->format('Y-m-d H:i:s') - ) - ); + Log::info(sprintf( + 'Recurrence #%d is set to run on %s, and today\'s date is %s. Skipped.', + $recurrence->id, + $recurrence->first_date->format('Y-m-d H:i:s'), + $this->date->format('Y-m-d H:i:s') + )); return false; } @@ -285,25 +279,23 @@ class CreateRecurringTransactions implements ShouldQueue /** @var RecurrenceRepetition $repetition */ foreach ($recurrence->recurrenceRepetitions as $repetition) { - Log::debug( - sprintf( - 'Now repeating %s with value "%s", skips every %d time(s)', - $repetition->repetition_type, - $repetition->repetition_moment, - $repetition->repetition_skip - ) - ); + Log::debug(sprintf( + 'Now repeating %s with value "%s", skips every %d time(s)', + $repetition->repetition_type, + $repetition->repetition_moment, + $repetition->repetition_skip + )); // start looping from $startDate to today perhaps we have a hit? // add two days to $this->date, so we always include the weekend. $includeWeekend = clone $this->date; $includeWeekend->addDays(2); - $occurrences = $this->repository->getOccurrencesInRange($repetition, $recurrence->first_date, $includeWeekend); + $occurrences = $this->repository->getOccurrencesInRange($repetition, $recurrence->first_date, $includeWeekend); unset($includeWeekend); - $result = $this->handleOccurrences($recurrence, $repetition, $occurrences); - $collection = $collection->merge($result); + $result = $this->handleOccurrences($recurrence, $repetition, $occurrences); + $collection = $collection->merge($result); } return $collection; @@ -334,7 +326,7 @@ class CreateRecurringTransactions implements ShouldQueue * @throws DuplicateTransactionException * @throws FireflyException */ - private function handleOccurrence(Recurrence $recurrence, RecurrenceRepetition $repetition, Carbon $date): ?TransactionGroup + private function handleOccurrence(Recurrence $recurrence, RecurrenceRepetition $repetition, Carbon $date): null|TransactionGroup { $date->startOfDay(); if ($date->ne($this->date)) { @@ -343,7 +335,7 @@ class CreateRecurringTransactions implements ShouldQueue Log::debug(sprintf('%s IS today (%s)', $date->format('Y-m-d'), $this->date->format('Y-m-d'))); // count created journals on THIS day. - $journalCount = $this->repository->getJournalCount($recurrence, $date, $date); + $journalCount = $this->repository->getJournalCount($recurrence, $date, $date); if ($journalCount > 0 && false === $this->force) { Log::info(sprintf('Already created %d journal(s) for date %s', $journalCount, $date->format('Y-m-d'))); @@ -361,11 +353,11 @@ class CreateRecurringTransactions implements ShouldQueue } // create transaction array and send to factory. - $groupTitle = null; - $count = $recurrence->recurrenceTransactions->count(); + $groupTitle = null; + $count = $recurrence->recurrenceTransactions->count(); // #8844, if there is one recurrence transaction, use the first title as the title. // #9305, if there is one recurrence transaction, group title must be NULL. - $groupTitle = null; + $groupTitle = null; // #8844, if there are more, use the recurrence transaction itself. if ($count > 1) { @@ -378,15 +370,15 @@ class CreateRecurringTransactions implements ShouldQueue return null; } - $array = [ + $array = [ 'user' => $recurrence->user, 'user_group' => $recurrence->user->userGroup, 'group_title' => $groupTitle, - 'transactions' => $this->getTransactionData($recurrence, $repetition, $date), + 'transactions' => $this->getTransactionData($recurrence, $repetition, $date) ]; /** @var TransactionGroup $group */ - $group = $this->groupRepository->store($array); + $group = $this->groupRepository->store($array); ++$this->created; Log::info(sprintf('Created new transaction group #%d', $group->id)); @@ -395,7 +387,7 @@ class CreateRecurringTransactions implements ShouldQueue $this->groups->push($group); // update recurring thing: - $recurrence->latest_date = $date; + $recurrence->latest_date = $date; $recurrence->latest_date_tz = $date->format('e'); $recurrence->save(); @@ -413,15 +405,14 @@ class CreateRecurringTransactions implements ShouldQueue $transactions = $recurrence->recurrenceTransactions()->get(); $transactions->first(); - $return = []; - - - + $return = []; /** @var RecurrenceTransaction $transaction */ foreach ($transactions as $index => $transaction) { - $single = [ - 'type' => null === $transaction?->transactionType?->type ? strtolower((string) $recurrence->transactionType->type) : strtolower($transaction->transactionType->type), // @phpstan-ignore-line + $single = [ + 'type' => null === $transaction?->transactionType?->type + ? strtolower((string) $recurrence->transactionType->type) + : strtolower($transaction->transactionType->type), // @phpstan-ignore-line 'date' => $date, 'user' => $recurrence->user, 'user_group' => $recurrence->user->userGroup, @@ -444,7 +435,7 @@ class CreateRecurringTransactions implements ShouldQueue 'identifier' => $index, 'recurrence_id' => $recurrence->id, 'order' => $index, - 'notes' => (string) trans('firefly.created_from_recurrence', ['id' => $recurrence->id, 'title' => $recurrence->title]), + 'notes' => (string) trans('firefly.created_from_recurrence', ['id' => $recurrence->id, 'title' => $recurrence->title]), 'tags' => $this->repository->getTags($transaction), 'piggy_bank_id' => $this->repository->getPiggyBank($transaction), 'piggy_bank_name' => null, @@ -452,7 +443,7 @@ class CreateRecurringTransactions implements ShouldQueue 'bill_name' => null, 'recurrence_total' => $total, 'recurrence_count' => $count, - 'recurrence_date' => $date, + 'recurrence_date' => $date ]; $return[] = $single; } @@ -462,7 +453,7 @@ class CreateRecurringTransactions implements ShouldQueue public function setDate(Carbon $date): void { - $newDate = clone $date; + $newDate = clone $date; $newDate->startOfDay(); Log::debug(sprintf('Overruled date to "%s', $newDate->format('Y-m-d H:i:s'))); $this->date = $newDate; diff --git a/app/Jobs/DownloadExchangeRates.php b/app/Jobs/DownloadExchangeRates.php index fbfef25a9e..6c86be6d82 100644 --- a/app/Jobs/DownloadExchangeRates.php +++ b/app/Jobs/DownloadExchangeRates.php @@ -54,25 +54,25 @@ class DownloadExchangeRates implements ShouldQueue use Queueable; use SerializesModels; - private array $active = []; - private Carbon $date; + private array $active = []; + private Carbon $date; private CurrencyRepositoryInterface $repository; - private Collection $users; + private Collection $users; /** * Create a new job instance. */ - public function __construct(?Carbon $date) + public function __construct(null|Carbon $date) { $this->repository = app(CurrencyRepositoryInterface::class); // get all users: /** @var UserRepositoryInterface $userRepository */ - $userRepository = app(UserRepositoryInterface::class); - $this->users = $userRepository->all(); + $userRepository = app(UserRepositoryInterface::class); + $this->users = $userRepository->all(); if ($date instanceof Carbon) { - $newDate = clone $date; + $newDate = clone $date; $newDate->startOfDay(); $this->date = $newDate; Log::debug(sprintf('Created new DownloadExchangeRates("%s")', $this->date->format('Y-m-d'))); @@ -100,9 +100,9 @@ class DownloadExchangeRates implements ShouldQueue private function downloadRates(TransactionCurrency $currency): void { Log::debug(sprintf('Now downloading new exchange rates for currency %s.', $currency->code)); - $base = sprintf('%s/%s/%s', (string) config('cer.url'), $this->date->year, $this->date->isoWeek); - $client = new Client(); - $url = sprintf('%s/%s.json', $base, $currency->code); + $base = sprintf('%s/%s/%s', (string) config('cer.url'), $this->date->year, $this->date->isoWeek); + $client = new Client(); + $url = sprintf('%s/%s.json', $base, $currency->code); try { $res = $client->get($url); @@ -117,14 +117,14 @@ class DownloadExchangeRates implements ShouldQueue return; } - $body = (string) $res->getBody(); - $json = json_decode($body, true); + $body = (string) $res->getBody(); + $json = json_decode($body, true); if (false === $json || null === $json) { Log::warning(sprintf('Trying to grab "%s" resulted in bad JSON.', $url)); return; } - $date = Carbon::createFromFormat('Y-m-d', $json['date'], config('app.timezone')); + $date = Carbon::createFromFormat('Y-m-d', $json['date'], config('app.timezone')); if (!$date instanceof Carbon) { return; } @@ -145,7 +145,7 @@ class DownloadExchangeRates implements ShouldQueue } } - private function getCurrency(string $code): ?TransactionCurrency + private function getCurrency(string $code): null|TransactionCurrency { // if we have it already, don't bother searching for it again. if (array_key_exists($code, $this->active)) { @@ -154,7 +154,7 @@ class DownloadExchangeRates implements ShouldQueue return $this->active[$code]; } // find it in the database. - $currency = $this->repository->findByCode($code); + $currency = $this->repository->findByCode($code); if (!$currency instanceof TransactionCurrency) { Log::debug(sprintf('Did not find currency %s.', $code)); $this->active[$code] = null; @@ -187,7 +187,7 @@ class DownloadExchangeRates implements ShouldQueue public function setDate(Carbon $date): void { - $newDate = clone $date; + $newDate = clone $date; $newDate->startOfDay(); $this->date = $newDate; } diff --git a/app/Jobs/MailError.php b/app/Jobs/MailError.php index 6420ac67fd..48dd43f72f 100644 --- a/app/Jobs/MailError.php +++ b/app/Jobs/MailError.php @@ -51,8 +51,12 @@ class MailError extends Job implements ShouldQueue /** * MailError constructor. */ - public function __construct(protected array $userData, protected string $destination, protected string $ipAddress, protected array $exception) - { + public function __construct( + protected array $userData, + protected string $destination, + protected string $ipAddress, + protected array $exception + ) { $debug = $this->exception; unset($debug['stackTrace'], $debug['headers']); @@ -64,12 +68,12 @@ class MailError extends Job implements ShouldQueue */ public function handle(): void { - $email = (string) config('firefly.site_owner'); - $args = $this->exception; + $email = (string) config('firefly.site_owner'); + $args = $this->exception; $args['loggedIn'] = $this->userData['id'] > 0; - $args['user'] = $this->userData; - $args['ip'] = $this->ipAddress; - $args['token'] = config('firefly.ipinfo_token'); + $args['user'] = $this->userData; + $args['ip'] = $this->ipAddress; + $args['token'] = config('firefly.ipinfo_token'); // limit number of error mails that can be sent. if ($this->reachedLimit()) { @@ -80,15 +84,11 @@ class MailError extends Job implements ShouldQueue if ($this->attempts() < 3 && '' !== $email) { try { - Mail::send( - ['emails.error-html', 'emails.error-text'], - $args, - static function (Message $message) use ($email): void { - if ('mail@example.com' !== $email) { - $message->to($email, $email)->subject((string) trans('email.error_subject')); - } + Mail::send(['emails.error-html', 'emails.error-text'], $args, static function (Message $message) use ($email): void { + if ('mail@example.com' !== $email) { + $message->to($email, $email)->subject((string) trans('email.error_subject')); } - ); + }); } catch (Exception|TransportException $e) { $message = $e->getMessage(); if (str_contains($message, 'Bcc')) { @@ -113,7 +113,7 @@ class MailError extends Job implements ShouldQueue $types = [ '5m' => ['limit' => 5, 'reset' => 5 * 60], '1h' => ['limit' => 15, 'reset' => 60 * 60], - '24h' => ['limit' => 15, 'reset' => 24 * 60 * 60], + '24h' => ['limit' => 15, 'reset' => 24 * 60 * 60] ]; $file = storage_path('framework/cache/error-count.json'); $directory = storage_path('framework/cache'); @@ -152,18 +152,16 @@ class MailError extends Job implements ShouldQueue Log::debug(sprintf('Now checking limit "%s"', $type), $info); if (!array_key_exists($type, $limits)) { Log::debug(sprintf('Limit "%s" reset to zero, did not exist yet.', $type)); - $limits[$type] = [ - 'time' => Carbon::now()->getTimestamp(), - 'sent' => 0, - ]; + $limits[$type] = ['time' => Carbon::now()->getTimestamp(), 'sent' => 0]; } - if (Carbon::now()->getTimestamp() - $limits[$type]['time'] > $info['reset']) { - Log::debug(sprintf('Time past for this limit is %d seconds, exceeding %d seconds. Reset to zero.', Carbon::now()->getTimestamp() - $limits[$type]['time'], $info['reset'])); - $limits[$type] = [ - 'time' => Carbon::now()->getTimestamp(), - 'sent' => 0, - ]; + if ((Carbon::now()->getTimestamp() - $limits[$type]['time']) > $info['reset']) { + Log::debug(sprintf( + 'Time past for this limit is %d seconds, exceeding %d seconds. Reset to zero.', + Carbon::now()->getTimestamp() - $limits[$type]['time'], + $info['reset'] + )); + $limits[$type] = ['time' => Carbon::now()->getTimestamp(), 'sent' => 0]; } if ($limits[$type]['sent'] > $info['limit']) { diff --git a/app/Jobs/SendWebhookMessage.php b/app/Jobs/SendWebhookMessage.php index de1e87bf5e..e2d5864c36 100644 --- a/app/Jobs/SendWebhookMessage.php +++ b/app/Jobs/SendWebhookMessage.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Jobs; -use Illuminate\Support\Facades\Log; use FireflyIII\Models\WebhookMessage; use FireflyIII\Services\Webhook\WebhookSenderInterface; use Illuminate\Bus\Queueable; @@ -32,6 +31,7 @@ use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; +use Illuminate\Support\Facades\Log; /** * Class SendWebhookMessage @@ -46,14 +46,15 @@ class SendWebhookMessage implements ShouldQueue /** * Create a new job instance. */ - public function __construct(private WebhookMessage $message) {} + public function __construct( + private WebhookMessage $message + ) {} /** * Execute the job. */ public function handle(): void { - Log::debug(sprintf('Now handling webhook message #%d', $this->message->id)); // send job! $sender = app(WebhookSenderInterface::class); diff --git a/app/Jobs/WarnAboutBills.php b/app/Jobs/WarnAboutBills.php index e80e793653..b4bfa063bb 100644 --- a/app/Jobs/WarnAboutBills.php +++ b/app/Jobs/WarnAboutBills.php @@ -49,19 +49,19 @@ class WarnAboutBills implements ShouldQueue use SerializesModels; private Carbon $date; - private bool $force; + private bool $force; /** * Create a new job instance. */ - public function __construct(?Carbon $date) + public function __construct(null|Carbon $date) { - $newDate = new Carbon(); + $newDate = new Carbon(); $newDate->startOfDay(); - $this->date = $newDate; + $this->date = $newDate; if ($date instanceof Carbon) { - $newDate = clone $date; + $newDate = clone $date; $newDate->startOfDay(); $this->date = $newDate; } @@ -86,7 +86,7 @@ class WarnAboutBills implements ShouldQueue Log::debug(sprintf('Now checking bill #%d ("%s")', $bill->id, $bill->name)); $dates = $this->getDates($bill); if ($this->needsOverdueAlert($dates)) { - $overdue[] = ['bill' => $bill, 'dates' => $dates]; + $overdue[] = ['bill' => $bill, 'dates' => $dates]; } if ($this->hasDateFields($bill)) { if ($this->needsWarning($bill, 'end_date')) { @@ -100,7 +100,6 @@ class WarnAboutBills implements ShouldQueue $this->sendOverdueAlerts($user, $overdue); } Log::debug('Done with handle()'); - } private function hasDateFields(Bill $bill): bool @@ -136,7 +135,7 @@ class WarnAboutBills implements ShouldQueue $today = clone $this->date; $carbon = clone $bill->{$field}; - return (int)$today->diffInDays($carbon); + return (int) $today->diffInDays($carbon); } private function sendWarning(Bill $bill, string $field): void @@ -148,7 +147,7 @@ class WarnAboutBills implements ShouldQueue public function setDate(Carbon $date): void { - $newDate = clone $date; + $newDate = clone $date; $newDate->startOfDay(); $this->date = $newDate; } @@ -170,17 +169,14 @@ class WarnAboutBills implements ShouldQueue $enrichment->setEnd($end); /** @var Bill $single */ - $single = $enrichment->enrichSingle($bill); + $single = $enrichment->enrichSingle($bill); - return [ - 'pay_dates' => $single->meta['pay_dates'] ?? [], - 'paid_dates' => $single->meta['paid_dates'] ?? [], - ]; + return ['pay_dates' => $single->meta['pay_dates'] ?? [], 'paid_dates' => $single->meta['paid_dates'] ?? []]; } private function needsOverdueAlert(array $dates): bool { - $count = count($dates['pay_dates']) - count($dates['paid_dates']); + $count = count($dates['pay_dates']) - count($dates['paid_dates']); if (0 === $count || 0 === count($dates['pay_dates'])) { return false; } @@ -188,7 +184,7 @@ class WarnAboutBills implements ShouldQueue $earliest = new Carbon($dates['pay_dates'][0]); $earliest->startOfDay(); Log::debug(sprintf('Earliest expected pay date is %s', $earliest->toAtomString())); - $diff = $earliest->diffInDays($this->date); + $diff = $earliest->diffInDays($this->date); Log::debug(sprintf('Difference in days is %s', $diff)); return $diff >= 6; // FIXME hard coded value. diff --git a/app/Listeners/Model/PiggyBank/CreatesPiggyBankEventForChangedAmount.php b/app/Listeners/Model/PiggyBank/CreatesPiggyBankEventForChangedAmount.php index ee72a19c62..31ae67768c 100644 --- a/app/Listeners/Model/PiggyBank/CreatesPiggyBankEventForChangedAmount.php +++ b/app/Listeners/Model/PiggyBank/CreatesPiggyBankEventForChangedAmount.php @@ -1,6 +1,7 @@ transactionGroup instanceof TransactionGroup) { $journal = $event->transactionGroup->transactionJournals()->first(); } - $date = $journal->date ?? today(config('app.timezone')); + $date = $journal->date ?? today(config('app.timezone')); // sanity check: event must not already exist for this journal and piggy bank. if (null !== $journal) { - $exists = PiggyBankEvent::where('piggy_bank_id', $event->piggyBank->id) - ->where('transaction_journal_id', $journal->id) - ->exists() - ; + $exists = PiggyBankEvent::where('piggy_bank_id', $event->piggyBank->id)->where('transaction_journal_id', $journal->id)->exists(); if ($exists) { Log::warning('Already have event for this journal and piggy, will not create another.'); @@ -52,14 +50,12 @@ class CreatesPiggyBankEventForChangedAmount implements ShouldQueue } } - PiggyBankEvent::create( - [ - 'piggy_bank_id' => $event->piggyBank->id, - 'transaction_journal_id' => $journal?->id, - 'date' => $date->format('Y-m-d'), - 'date_tz' => $date->format('e'), - 'amount' => $event->amount, - ] - ); + PiggyBankEvent::create([ + 'piggy_bank_id' => $event->piggyBank->id, + 'transaction_journal_id' => $journal?->id, + 'date' => $date->format('Y-m-d'), + 'date_tz' => $date->format('e'), + 'amount' => $event->amount + ]); } } diff --git a/app/Listeners/Model/PiggyBank/UpdatesRulesForChangedPiggyBankName.php b/app/Listeners/Model/PiggyBank/UpdatesRulesForChangedPiggyBankName.php index e64701cbc6..9e5c8ba40c 100644 --- a/app/Listeners/Model/PiggyBank/UpdatesRulesForChangedPiggyBankName.php +++ b/app/Listeners/Model/PiggyBank/UpdatesRulesForChangedPiggyBankName.php @@ -1,6 +1,7 @@ ruleAction; - $rule = $ruleAction->rule; + $ruleAction = $event->ruleAction; + $rule = $ruleAction->rule; /** @var bool $preference */ - $preference = Preferences::getForUser($rule->user, 'notification_rule_action_failures', true)->data; + $preference = Preferences::getForUser($rule->user, 'notification_rule_action_failures', true)->data; if (false === $preference) { return; } Log::debug('Now in ruleActionFailedOnArray'); - $journal = $event->journal; - $error = $event->error; - $user = $ruleAction->rule->user; + $journal = $event->journal; + $error = $event->error; + $user = $ruleAction->rule->user; - $groupId = is_array($journal) ? $journal['transaction_group_id'] : $journal->transaction_group_id; - $groupTitle = is_array($journal) ? ($journal['description'] ?? '') : ($journal->description ?? ''); + $groupId = is_array($journal) ? $journal['transaction_group_id'] : $journal->transaction_group_id; + $groupTitle = is_array($journal) ? $journal['description'] ?? '' : $journal->description ?? ''; - - $mainMessage = trans('rules.main_message', ['rule' => $rule->title, 'action' => $ruleAction->action_type, 'group' => $groupId, 'error' => $error]); + $mainMessage = trans('rules.main_message', ['rule' => $rule->title, 'action' => $ruleAction->action_type, 'group' => $groupId, 'error' => $error]); $groupLink = route('transactions.show', [$groupId]); $ruleTitle = $rule->title; $ruleLink = route('rules.edit', [$rule->id]); diff --git a/app/Listeners/Model/Subscription/NotifiesAboutExtensionOrRenewal.php b/app/Listeners/Model/Subscription/NotifiesAboutExtensionOrRenewal.php index debd603f41..74148cf9bd 100644 --- a/app/Listeners/Model/Subscription/NotifiesAboutExtensionOrRenewal.php +++ b/app/Listeners/Model/Subscription/NotifiesAboutExtensionOrRenewal.php @@ -1,6 +1,7 @@ subscription; /** @var bool $preference */ - $preference = Preferences::getForUser($subscription->user, 'notification_bill_reminder', true)->data; + $preference = Preferences::getForUser($subscription->user, 'notification_bill_reminder', true)->data; if (true === $preference) { Log::debug('Subscription reminder is true!'); diff --git a/app/Listeners/Model/Subscription/NotifiesAboutOverdueSubscriptions.php b/app/Listeners/Model/Subscription/NotifiesAboutOverdueSubscriptions.php index e5ee36b65c..d9f8609c96 100644 --- a/app/Listeners/Model/Subscription/NotifiesAboutOverdueSubscriptions.php +++ b/app/Listeners/Model/Subscription/NotifiesAboutOverdueSubscriptions.php @@ -1,6 +1,7 @@ overdue; - $user = $event->user; - $toBeWarned = []; + $overdue = $event->overdue; + $user = $event->user; + $toBeWarned = []; Log::debug(sprintf('%d subscriptions to warn about.', count($overdue))); foreach ($overdue as $item) { /** @var Bill $bill */ - $bill = $item['bill']; - $key = sprintf('bill_overdue_%s_%s', $bill->id, substr(hash('sha256', json_encode($item['dates']['pay_dates'], JSON_THROW_ON_ERROR)), 0, 10)); - $pref = Preferences::getForUser($bill->user, $key, false); + $bill = $item['bill']; + $key = sprintf('bill_overdue_%s_%s', $bill->id, substr(hash('sha256', json_encode($item['dates']['pay_dates'], JSON_THROW_ON_ERROR)), 0, 10)); + $pref = Preferences::getForUser($bill->user, $key, false); if (true === $pref->data) { Log::debug(sprintf('User #%d has already been warned about overdue subscription #%d.', $bill->user->id, $bill->id)); @@ -95,7 +96,5 @@ class NotifiesAboutOverdueSubscriptions implements ShouldQueue Log::error($e->getMessage()); Log::error($e->getTraceAsString()); } - - } } diff --git a/app/Listeners/Security/System/HandlesNewUserRegistration.php b/app/Listeners/Security/System/HandlesNewUserRegistration.php index 0a0faf88e0..8bf796522d 100644 --- a/app/Listeners/Security/System/HandlesNewUserRegistration.php +++ b/app/Listeners/Security/System/HandlesNewUserRegistration.php @@ -52,7 +52,6 @@ class HandlesNewUserRegistration $this->createExchangeRates(); } - private function attachUserRole(User $user): void { /** @var UserRepositoryInterface $repository */ @@ -97,18 +96,11 @@ class HandlesNewUserRegistration if (null === $role) { throw new FireflyException('The user role is unexpectedly empty. Did you run all migrations?'); } - GroupMembership::create( - [ - 'user_id' => $user->id, - 'user_group_id' => $group->id, - 'user_role_id' => $role->id, - ] - ); + GroupMembership::create(['user_id' => $user->id, 'user_group_id' => $group->id, 'user_role_id' => $role->id]); $user->user_group_id = $group->id; $user->save(); } - /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ @@ -120,7 +112,7 @@ class HandlesNewUserRegistration private function sendAdminRegistrationNotification(User $user, OwnerNotifiable $owner): void { - $sendMail = (bool)FireflyConfig::get('notification_admin_new_reg', true)->data; + $sendMail = (bool) FireflyConfig::get('notification_admin_new_reg', true)->data; if (!$sendMail) { return; } @@ -143,10 +135,9 @@ class HandlesNewUserRegistration } } - private function sendRegistrationMail(User $user): void { - $sendMail = (bool)FireflyConfig::get('notification_user_new_reg', true)->data; + $sendMail = (bool) FireflyConfig::get('notification_user_new_reg', true)->data; if (!$sendMail) { return; } diff --git a/app/Listeners/Security/System/NotifiesOwnerAboutNewVersion.php b/app/Listeners/Security/System/NotifiesOwnerAboutNewVersion.php index 036e741b27..4df0d8842d 100644 --- a/app/Listeners/Security/System/NotifiesOwnerAboutNewVersion.php +++ b/app/Listeners/Security/System/NotifiesOwnerAboutNewVersion.php @@ -60,5 +60,4 @@ class NotifiesOwnerAboutNewVersion Log::error($e->getTraceAsString()); } } - } diff --git a/app/Listeners/Security/System/NotifiesOwnerAboutUnknownUser.php b/app/Listeners/Security/System/NotifiesOwnerAboutUnknownUser.php index d1763e6c48..72e849da16 100644 --- a/app/Listeners/Security/System/NotifiesOwnerAboutUnknownUser.php +++ b/app/Listeners/Security/System/NotifiesOwnerAboutUnknownUser.php @@ -1,6 +1,7 @@ sendEmailChangeUndoMail($event); } - /** * Send email to confirm email change. Will not be made into a notification, because * this requires some custom fields from the user and not just the "user" object. @@ -78,7 +77,7 @@ class HandlesChangeOfUserEmailAddress $oldEmail = $event->oldEmail; $user = $event->user; $token = Preferences::getForUser($user, 'email_change_undo_token', 'invalid'); - $hashed = hash('sha256', sprintf('%s%s', (string)config('app.key'), $oldEmail)); + $hashed = hash('sha256', sprintf('%s%s', (string) config('app.key'), $oldEmail)); $url = route('profile.undo-email-change', [$token->data, $hashed]); try { @@ -90,5 +89,4 @@ class HandlesChangeOfUserEmailAddress throw new FireflyException($e->getMessage(), 0, $e); } } - } diff --git a/app/Listeners/Security/User/NotifiesUserAboutDisabledMFA.php b/app/Listeners/Security/User/NotifiesUserAboutDisabledMFA.php index e8cca7580e..b15722d29c 100644 --- a/app/Listeners/Security/User/NotifiesUserAboutDisabledMFA.php +++ b/app/Listeners/Security/User/NotifiesUserAboutDisabledMFA.php @@ -1,6 +1,7 @@ user; + public function handle(UserLoggedInFromNewIpAddress $event): void + { + $user = $event->user; - if ($user->hasRole('demo')) { - return; // do not email demo user. - } - - $list = Preferences::getForUser($user, 'login_ip_history', [])->data; - if (!is_array($list)) { - $list = []; - } - - /** @var array $entry */ - foreach ($list as $index => $entry) { - if (false === $entry['notified']) { - try { - Notification::send($user, new UserLogin()); - } catch (Exception $e) { - $message = $e->getMessage(); - if (str_contains($message, 'Bcc')) { - Log::warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); - - return; - } - if (str_contains($message, 'RFC 2822')) { - Log::warning('[RFC] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); - - return; - } - Log::error($e->getMessage()); - Log::error($e->getTraceAsString()); - } + if ($user->hasRole('demo')) { + return; // do not email demo user. } - $list[$index]['notified'] = true; - } - Preferences::setForUser($user, 'login_ip_history', $list); -} + $list = Preferences::getForUser($user, 'login_ip_history', [])->data; + if (!is_array($list)) { + $list = []; + } + + /** @var array $entry */ + foreach ($list as $index => $entry) { + if (false === $entry['notified']) { + try { + Notification::send($user, new UserLogin()); + } catch (Exception $e) { + $message = $e->getMessage(); + if (str_contains($message, 'Bcc')) { + Log::warning('[Bcc] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); + + return; + } + if (str_contains($message, 'RFC 2822')) { + Log::warning('[RFC] Could not send notification. Please validate your email settings, use the .env.example file as a guide.'); + + return; + } + Log::error($e->getMessage()); + Log::error($e->getTraceAsString()); + } + } + $list[$index]['notified'] = true; + } + + Preferences::setForUser($user, 'login_ip_history', $list); + } } diff --git a/app/Listeners/Security/User/NotifiesUserAboutNoCodesLeft.php b/app/Listeners/Security/User/NotifiesUserAboutNoCodesLeft.php index 9a1792e0a7..c79cc4c059 100644 --- a/app/Listeners/Security/User/NotifiesUserAboutNoCodesLeft.php +++ b/app/Listeners/Security/User/NotifiesUserAboutNoCodesLeft.php @@ -1,6 +1,7 @@ getTraceAsString()); } } - } diff --git a/app/Listeners/Security/User/StoresNewIpAddress.php b/app/Listeners/Security/User/StoresNewIpAddress.php index e745ff6bc0..2d31a6e020 100644 --- a/app/Listeners/Security/User/StoresNewIpAddress.php +++ b/app/Listeners/Security/User/StoresNewIpAddress.php @@ -53,7 +53,7 @@ class StoresNewIpAddress if ($row['ip'] === $ip) { Log::debug('Found IP in array, refresh time.'); $preference[$index]['time'] = now(config('app.timezone'))->format('Y-m-d H:i:s'); - $inArray = true; + $inArray = true; } // clean up old entries (6 months) $carbon = Carbon::createFromFormat('Y-m-d H:i:s', $preference[$index]['time']); @@ -64,11 +64,7 @@ class StoresNewIpAddress } // add to array if not the case: if (false === $inArray) { - $preference[] = [ - 'ip' => $ip, - 'time' => now(config('app.timezone'))->format('Y-m-d H:i:s'), - 'notified' => false, - ]; + $preference[] = ['ip' => $ip, 'time' => now(config('app.timezone'))->format('Y-m-d H:i:s'), 'notified' => false]; } $preference = array_values($preference); @@ -80,5 +76,4 @@ class StoresNewIpAddress event(new UserLoggedInFromNewIpAddress($user)); } } - } diff --git a/app/Listeners/Test/SendsTestNotification.php b/app/Listeners/Test/SendsTestNotification.php index 3d1cebcb76..0a3fcc958e 100644 --- a/app/Listeners/Test/SendsTestNotification.php +++ b/app/Listeners/Test/SendsTestNotification.php @@ -38,7 +38,7 @@ use Illuminate\Support\Facades\Notification; class SendsTestNotification { - public function handle(OwnerTestsNotificationChannel | UserTestsNotificationChannel $event): void + public function handle(OwnerTestsNotificationChannel|UserTestsNotificationChannel $event): void { Log::debug(sprintf('Now in SendsTestNotification::handle(%s->"%s")', get_class($event), $event->channel)); diff --git a/app/Mail/AccessTokenCreatedMail.php b/app/Mail/AccessTokenCreatedMail.php index 12deb375c4..23be024eb5 100644 --- a/app/Mail/AccessTokenCreatedMail.php +++ b/app/Mail/AccessTokenCreatedMail.php @@ -48,9 +48,6 @@ class AccessTokenCreatedMail extends Mailable */ public function build(): self { - return $this - ->markdown('emails.token-created') - ->subject((string) trans('email.access_token_created_subject')) - ; + return $this->markdown('emails.token-created')->subject((string) trans('email.access_token_created_subject')); } } diff --git a/app/Mail/AdminTestMail.php b/app/Mail/AdminTestMail.php index a24f87d214..b2c07e383c 100644 --- a/app/Mail/AdminTestMail.php +++ b/app/Mail/AdminTestMail.php @@ -51,9 +51,6 @@ class AdminTestMail extends Mailable */ public function build(): self { - return $this - ->markdown('emails.admin-test') - ->subject((string) trans('email.admin_test_subject')) - ; + return $this->markdown('emails.admin-test')->subject((string) trans('email.admin_test_subject')); } } diff --git a/app/Mail/BillWarningMail.php b/app/Mail/BillWarningMail.php index 8b438091d5..50d9afce5e 100644 --- a/app/Mail/BillWarningMail.php +++ b/app/Mail/BillWarningMail.php @@ -40,7 +40,11 @@ class BillWarningMail extends Mailable /** * ConfirmEmailChangeMail constructor. */ - public function __construct(public Bill $bill, public string $field, public int $diff) {} + public function __construct( + public Bill $bill, + public string $field, + public int $diff + ) {} /** * Build the message. @@ -54,9 +58,6 @@ class BillWarningMail extends Mailable $subject = (string) trans(sprintf('email.bill_warning_subject_now_%s', $this->field), ['diff' => $this->diff, 'name' => $this->bill->name]); } - return $this - ->markdown('emails.bill-warning') - ->subject($subject) - ; + return $this->markdown('emails.bill-warning')->subject($subject); } } diff --git a/app/Mail/ConfirmEmailChangeMail.php b/app/Mail/ConfirmEmailChangeMail.php index de4153e21c..7f5a99aa2f 100644 --- a/app/Mail/ConfirmEmailChangeMail.php +++ b/app/Mail/ConfirmEmailChangeMail.php @@ -40,7 +40,11 @@ class ConfirmEmailChangeMail extends Mailable /** * ConfirmEmailChangeMail constructor. */ - public function __construct(public string $newEmail, public string $oldEmail, public string $url) {} + public function __construct( + public string $newEmail, + public string $oldEmail, + public string $url + ) {} /** * Build the message. @@ -53,7 +57,6 @@ class ConfirmEmailChangeMail extends Mailable // ->view('emails.confirm-email-change-html') // ->text('emails.confirm-email-change-text') ->markdown('emails.confirm-email-change') - ->subject((string) trans('email.email_change_subject')) - ; + ->subject((string) trans('email.email_change_subject')); } } diff --git a/app/Mail/InvitationMail.php b/app/Mail/InvitationMail.php index 14ad8821b5..ca7951f301 100644 --- a/app/Mail/InvitationMail.php +++ b/app/Mail/InvitationMail.php @@ -43,9 +43,12 @@ class InvitationMail extends Mailable /** * OAuthTokenCreatedMail constructor. */ - public function __construct(public string $invitee, public string $admin, public string $url) - { - $host = parse_url($this->url, PHP_URL_HOST); + public function __construct( + public string $invitee, + public string $admin, + public string $url + ) { + $host = parse_url($this->url, PHP_URL_HOST); if (is_array($host)) { $host = ''; } @@ -59,9 +62,6 @@ class InvitationMail extends Mailable */ public function build(): self { - return $this - ->markdown('emails.invitation') - ->subject((string) trans('email.invite_user_subject')) - ; + return $this->markdown('emails.invitation')->subject((string) trans('email.invite_user_subject')); } } diff --git a/app/Mail/NewIPAddressWarningMail.php b/app/Mail/NewIPAddressWarningMail.php index b7e5919445..eb5100cd68 100644 --- a/app/Mail/NewIPAddressWarningMail.php +++ b/app/Mail/NewIPAddressWarningMail.php @@ -24,12 +24,12 @@ declare(strict_types=1); namespace FireflyIII\Mail; -use Illuminate\Support\Facades\Log; use FireflyIII\Exceptions\FireflyException; +use FireflyIII\Support\Facades\Steam; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; -use FireflyIII\Support\Facades\Steam; +use Illuminate\Support\Facades\Log; /** * Class NewIPAddressWarningMail @@ -45,7 +45,9 @@ class NewIPAddressWarningMail extends Mailable /** * OAuthTokenCreatedMail constructor. */ - public function __construct(public string $ipAddress) {} + public function __construct( + public string $ipAddress + ) {} /** * Build the message. @@ -67,9 +69,6 @@ class NewIPAddressWarningMail extends Mailable $this->host = $hostName; } - return $this - ->markdown('emails.new-ip') - ->subject((string) trans('email.login_from_new_ip')) - ; + return $this->markdown('emails.new-ip')->subject((string) trans('email.login_from_new_ip')); } } diff --git a/app/Mail/OAuthTokenCreatedMail.php b/app/Mail/OAuthTokenCreatedMail.php index 4f68259546..92eb7a07db 100644 --- a/app/Mail/OAuthTokenCreatedMail.php +++ b/app/Mail/OAuthTokenCreatedMail.php @@ -40,7 +40,9 @@ class OAuthTokenCreatedMail extends Mailable /** * OAuthTokenCreatedMail constructor. */ - public function __construct(public Client $client) {} + public function __construct( + public Client $client + ) {} /** * Build the message. @@ -49,9 +51,6 @@ class OAuthTokenCreatedMail extends Mailable */ public function build(): self { - return $this - ->markdown('emails.oauth-client-created') - ->subject((string) trans('email.oauth_created_subject')) - ; + return $this->markdown('emails.oauth-client-created')->subject((string) trans('email.oauth_created_subject')); } } diff --git a/app/Mail/RegisteredUser.php b/app/Mail/RegisteredUser.php index 991d64d26f..95da79eaa4 100644 --- a/app/Mail/RegisteredUser.php +++ b/app/Mail/RegisteredUser.php @@ -40,7 +40,9 @@ class RegisteredUser extends Mailable /** * Create a new message instance. */ - public function __construct(public string $address) {} + public function __construct( + public string $address + ) {} /** * Build the message. @@ -49,9 +51,6 @@ class RegisteredUser extends Mailable */ public function build(): self { - return $this - ->markdown('emails.registered') - ->subject((string) trans('email.registered_subject')) - ; + return $this->markdown('emails.registered')->subject((string) trans('email.registered_subject')); } } diff --git a/app/Mail/ReportNewJournalsMail.php b/app/Mail/ReportNewJournalsMail.php index c8b51a782d..4af9d40f25 100644 --- a/app/Mail/ReportNewJournalsMail.php +++ b/app/Mail/ReportNewJournalsMail.php @@ -46,7 +46,9 @@ class ReportNewJournalsMail extends Mailable /** * ConfirmEmailChangeMail constructor. */ - public function __construct(public Collection $groups) {} + public function __construct( + public Collection $groups + ) {} /** * Build the message. @@ -59,10 +61,7 @@ class ReportNewJournalsMail extends Mailable { $this->transform(); - return $this - ->markdown('emails.report-new-journals') - ->subject(trans_choice('email.new_journals_subject', $this->groups->count())) - ; + return $this->markdown('emails.report-new-journals')->subject(trans_choice('email.new_journals_subject', $this->groups->count())); } /** diff --git a/app/Mail/RequestedNewPassword.php b/app/Mail/RequestedNewPassword.php index fb5202d6f2..f481844f04 100644 --- a/app/Mail/RequestedNewPassword.php +++ b/app/Mail/RequestedNewPassword.php @@ -39,7 +39,9 @@ class RequestedNewPassword extends Mailable /** * RequestedNewPassword constructor. */ - public function __construct(public string $url) {} + public function __construct( + public string $url + ) {} /** * Build the message. @@ -48,9 +50,6 @@ class RequestedNewPassword extends Mailable */ public function build(): self { - return $this - ->markdown('emails.password') - ->subject((string) trans('email.reset_pw_subject')) - ; + return $this->markdown('emails.password')->subject((string) trans('email.reset_pw_subject')); } } diff --git a/app/Mail/UndoEmailChangeMail.php b/app/Mail/UndoEmailChangeMail.php index 98c55721e7..ad8592ec17 100644 --- a/app/Mail/UndoEmailChangeMail.php +++ b/app/Mail/UndoEmailChangeMail.php @@ -38,7 +38,11 @@ class UndoEmailChangeMail extends Mailable /** * UndoEmailChangeMail constructor. */ - public function __construct(public string $newEmail, public string $oldEmail, public string $url) {} + public function __construct( + public string $newEmail, + public string $oldEmail, + public string $url + ) {} /** * Build the message. @@ -47,9 +51,6 @@ class UndoEmailChangeMail extends Mailable */ public function build(): self { - return $this - ->markdown('emails.undo-email-change') - ->subject((string) trans('email.email_change_subject')) - ; + return $this->markdown('emails.undo-email-change')->subject((string) trans('email.email_change_subject')); } } diff --git a/app/Models/Account.php b/app/Models/Account.php index c59ad0317a..c6d6e30440 100644 --- a/app/Models/Account.php +++ b/app/Models/Account.php @@ -50,9 +50,9 @@ class Account extends Model use ReturnsIntegerUserIdTrait; use SoftDeletes; - protected $fillable = ['user_id', 'user_group_id', 'account_type_id', 'name', 'active', 'virtual_balance', 'iban', 'native_virtual_balance']; + protected $fillable = ['user_id', 'user_group_id', 'account_type_id', 'name', 'active', 'virtual_balance', 'iban', 'native_virtual_balance']; - protected $hidden = ['encrypted']; + protected $hidden = ['encrypted']; private bool $joinedAccountTypes = false; /** @@ -63,13 +63,13 @@ class Account extends Model public static function routeBinder(string $value): self { if (auth()->check()) { - $accountId = (int)$value; + $accountId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|Account $account */ - $account = $user->accounts()->with(['accountType'])->find($accountId); + $account = $user->accounts()->with(['accountType'])->find($accountId); if (null !== $account) { return $account; } @@ -126,7 +126,7 @@ class Account extends Model public function setVirtualBalanceAttribute(mixed $value): void { - $value = (string)$value; + $value = (string) $value; if ('' === $value) { $value = null; } @@ -145,9 +145,7 @@ class Account extends Model protected function accountId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } /** @@ -157,10 +155,7 @@ class Account extends Model { return Attribute::make(get: function () { /** @var null|AccountMeta $metaValue */ - $metaValue = $this->accountMeta() - ->where('name', 'account_number') - ->first() - ; + $metaValue = $this->accountMeta()->where('name', 'account_number')->first(); return null !== $metaValue ? $metaValue->data : ''; }); @@ -176,9 +171,7 @@ class Account extends Model */ protected function accountTypeId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } #[Scope] @@ -202,7 +195,7 @@ class Account extends Model 'active' => 'boolean', 'encrypted' => 'boolean', 'virtual_balance' => 'string', - 'native_virtual_balance' => 'string', + 'native_virtual_balance' => 'string' ]; } @@ -220,16 +213,12 @@ class Account extends Model protected function iban(): Attribute { - return Attribute::make( - get: static fn ($value): ?string => null === $value ? null : trim(str_replace(' ', '', (string)$value)), - ); + return Attribute::make(get: static fn($value): null|string => null === $value ? null : trim(str_replace(' ', '', (string) $value))); } protected function order(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } /** @@ -237,15 +226,11 @@ class Account extends Model */ protected function virtualBalance(): Attribute { - return Attribute::make( - get: static fn ($value): string => (string)$value, - ); + return Attribute::make(get: static fn($value): string => (string) $value); } public function primaryPeriodStatistics(): MorphMany { - return $this->morphMany(PeriodStatistic::class, 'primary_statable'); - } } diff --git a/app/Models/AccountBalance.php b/app/Models/AccountBalance.php index e7eaf361ce..297698f42b 100644 --- a/app/Models/AccountBalance.php +++ b/app/Models/AccountBalance.php @@ -1,6 +1,5 @@ SeparateTimezoneCaster::class, - 'balance' => 'string', - ]; + return ['date' => SeparateTimezoneCaster::class, 'balance' => 'string']; } } diff --git a/app/Models/AccountMeta.php b/app/Models/AccountMeta.php index 4f52be9dd9..cea01fb792 100644 --- a/app/Models/AccountMeta.php +++ b/app/Models/AccountMeta.php @@ -45,14 +45,14 @@ class AccountMeta extends Model protected function casts(): array { - return [ - 'created_at' => 'datetime', - 'updated_at' => 'datetime', - ]; + return ['created_at' => 'datetime', 'updated_at' => 'datetime']; } protected function data(): Attribute { - return Attribute::make(get: static fn (mixed $value): string => (string)json_decode((string)$value, true), set: static fn (mixed $value): array => ['data' => json_encode($value)]); + return Attribute::make( + get: static fn(mixed $value): string => (string) json_decode((string) $value, true), + set: static fn(mixed $value): array => ['data' => json_encode($value)] + ); } } diff --git a/app/Models/AccountType.php b/app/Models/AccountType.php index d4b82b45fd..1d80a53546 100644 --- a/app/Models/AccountType.php +++ b/app/Models/AccountType.php @@ -32,69 +32,65 @@ class AccountType extends Model { use ReturnsIntegerIdTrait; - #[Deprecated] /** @deprecated */ - public const string ASSET = 'Asset account'; + #[Deprecated] + public const string ASSET = 'Asset account'; - #[Deprecated] /** @deprecated */ - public const string BENEFICIARY = 'Beneficiary account'; + #[Deprecated] + public const string BENEFICIARY = 'Beneficiary account'; - #[Deprecated] /** @deprecated */ - public const string CASH = 'Cash account'; + #[Deprecated] + public const string CASH = 'Cash account'; - #[Deprecated] /** @deprecated */ - public const string CREDITCARD = 'Credit card'; + #[Deprecated] + public const string CREDITCARD = 'Credit card'; - #[Deprecated] /** @deprecated */ - public const string DEBT = 'Debt'; + #[Deprecated] + public const string DEBT = 'Debt'; - #[Deprecated] /** @deprecated */ - public const string DEFAULT = 'Default account'; + #[Deprecated] + public const string DEFAULT = 'Default account'; - #[Deprecated] /** @deprecated */ - public const string EXPENSE = 'Expense account'; + #[Deprecated] + public const string EXPENSE = 'Expense account'; - #[Deprecated] /** @deprecated */ - public const string IMPORT = 'Import account'; + #[Deprecated] + public const string IMPORT = 'Import account'; - #[Deprecated] /** @deprecated */ - public const string INITIAL_BALANCE = 'Initial balance account'; + #[Deprecated] + public const string INITIAL_BALANCE = 'Initial balance account'; - #[Deprecated] /** @deprecated */ + #[Deprecated] public const string LIABILITY_CREDIT = 'Liability credit account'; - #[Deprecated] /** @deprecated */ - public const string LOAN = 'Loan'; - #[Deprecated] - /** @deprecated */ - public const string MORTGAGE = 'Mortgage'; + public const string LOAN = 'Loan'; + /** @deprecated */ #[Deprecated] - /** @deprecated */ - public const string RECONCILIATION = 'Reconciliation account'; + public const string MORTGAGE = 'Mortgage'; + /** @deprecated */ #[Deprecated] + public const string RECONCILIATION = 'Reconciliation account'; + /** @deprecated */ - public const string REVENUE = 'Revenue account'; + #[Deprecated] + public const string REVENUE = 'Revenue account'; - protected $casts - = [ - 'created_at' => 'datetime', - 'updated_at' => 'datetime', - ]; + protected $casts = ['created_at' => 'datetime', 'updated_at' => 'datetime']; - protected $fillable = ['type']; + protected $fillable = ['type']; public function accounts(): HasMany { diff --git a/app/Models/Attachment.php b/app/Models/Attachment.php index 2ec45246a8..bbb2dfa145 100644 --- a/app/Models/Attachment.php +++ b/app/Models/Attachment.php @@ -43,7 +43,19 @@ class Attachment extends Model use ReturnsIntegerUserIdTrait; use SoftDeletes; - protected $fillable = ['attachable_id', 'attachable_type', 'user_id', 'user_group_id', 'md5', 'filename', 'mime', 'title', 'description', 'size', 'uploaded']; + protected $fillable = [ + 'attachable_id', + 'attachable_type', + 'user_id', + 'user_group_id', + 'md5', + 'filename', + 'mime', + 'title', + 'description', + 'size', + 'uploaded' + ]; /** * Route binder. Converts the key in the URL to the specified object (or throw 404). @@ -53,13 +65,13 @@ class Attachment extends Model public static function routeBinder(string $value): self { if (auth()->check()) { - $attachmentId = (int)$value; + $attachmentId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|Attachment $attachment */ - $attachment = $user->attachments()->find($attachmentId); + $attachment = $user->attachments()->find($attachmentId); if (null !== $attachment) { return $attachment; } @@ -86,7 +98,7 @@ class Attachment extends Model */ public function fileName(): string { - return sprintf('at-%s.data', (string)$this->id); + return sprintf('at-%s.data', (string) $this->id); } /** @@ -99,9 +111,7 @@ class Attachment extends Model protected function attachableId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } protected function casts(): array @@ -112,7 +122,7 @@ class Attachment extends Model 'deleted_at' => 'datetime', 'uploaded' => 'boolean', 'user_id' => 'integer', - 'user_group_id' => 'integer', + 'user_group_id' => 'integer' ]; } } diff --git a/app/Models/AuditLogEntry.php b/app/Models/AuditLogEntry.php index 818b2c8d20..31019cb5bc 100644 --- a/app/Models/AuditLogEntry.php +++ b/app/Models/AuditLogEntry.php @@ -47,26 +47,16 @@ class AuditLogEntry extends Model protected function auditableId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } protected function casts(): array { - return [ - 'before' => 'array', - 'after' => 'array', - 'created_at' => 'datetime', - 'updated_at' => 'datetime', - 'deleted_at' => 'datetime', - ]; + return ['before' => 'array', 'after' => 'array', 'created_at' => 'datetime', 'updated_at' => 'datetime', 'deleted_at' => 'datetime']; } protected function changerId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } } diff --git a/app/Models/AutoBudget.php b/app/Models/AutoBudget.php index 925928448d..aa827786e9 100644 --- a/app/Models/AutoBudget.php +++ b/app/Models/AutoBudget.php @@ -39,23 +39,20 @@ class AutoBudget extends Model use ReturnsIntegerIdTrait; use SoftDeletes; - #[Deprecated] /** @deprecated */ + #[Deprecated] public const int AUTO_BUDGET_ADJUSTED = 3; - #[Deprecated] /** @deprecated */ - public const int AUTO_BUDGET_RESET = 1; + #[Deprecated] + public const int AUTO_BUDGET_RESET = 1; - #[Deprecated] /** @deprecated */ + #[Deprecated] public const int AUTO_BUDGET_ROLLOVER = 2; - protected $casts - = [ - 'amount' => 'string', - 'native_amount' => 'string', - ]; - protected $fillable = ['budget_id', 'amount', 'period', 'native_amount']; + + protected $casts = ['amount' => 'string', 'native_amount' => 'string']; + protected $fillable = ['budget_id', 'amount', 'period', 'native_amount']; public function budget(): BelongsTo { @@ -69,16 +66,12 @@ class AutoBudget extends Model protected function amount(): Attribute { - return Attribute::make( - get: static fn ($value): string => (string)$value, - ); + return Attribute::make(get: static fn($value): string => (string) $value); } protected function budgetId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } protected function casts(): array @@ -90,8 +83,6 @@ class AutoBudget extends Model protected function transactionCurrencyId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } } diff --git a/app/Models/AvailableBudget.php b/app/Models/AvailableBudget.php index db806fd472..db06c14b7a 100644 --- a/app/Models/AvailableBudget.php +++ b/app/Models/AvailableBudget.php @@ -42,7 +42,17 @@ class AvailableBudget extends Model use ReturnsIntegerUserIdTrait; use SoftDeletes; - protected $fillable = ['user_id', 'user_group_id', 'transaction_currency_id', 'amount', 'start_date', 'end_date', 'start_date_tz', 'end_date_tz', 'native_amount']; + protected $fillable = [ + 'user_id', + 'user_group_id', + 'transaction_currency_id', + 'amount', + 'start_date', + 'end_date', + 'start_date_tz', + 'end_date_tz', + 'native_amount' + ]; /** * Route binder. Converts the key in the URL to the specified object (or throw 404). @@ -52,13 +62,13 @@ class AvailableBudget extends Model public static function routeBinder(string $value): self { if (auth()->check()) { - $availableBudgetId = (int)$value; + $availableBudgetId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|AvailableBudget $availableBudget */ - $availableBudget = $user->availableBudgets()->find($availableBudgetId); + $availableBudget = $user->availableBudgets()->find($availableBudgetId); if (null !== $availableBudget) { return $availableBudget; } @@ -79,9 +89,7 @@ class AvailableBudget extends Model protected function amount(): Attribute { - return Attribute::make( - get: static fn ($value): string => (string)$value, - ); + return Attribute::make(get: static fn($value): string => (string) $value); } protected function casts(): array @@ -96,30 +104,28 @@ class AvailableBudget extends Model 'amount' => 'string', 'native_amount' => 'string', 'user_id' => 'integer', - 'user_group_id' => 'integer', + 'user_group_id' => 'integer' ]; } protected function endDate(): Attribute { return Attribute::make( - get: static fn (string $value): Carbon => Carbon::parse($value), - set: static fn (Carbon $value): string => $value->format('Y-m-d'), + get: static fn(string $value): Carbon => Carbon::parse($value), + set: static fn(Carbon $value): string => $value->format('Y-m-d') ); } protected function startDate(): Attribute { return Attribute::make( - get: static fn (string $value): Carbon => Carbon::parse($value), - set: static fn (Carbon $value): string => $value->format('Y-m-d'), + get: static fn(string $value): Carbon => Carbon::parse($value), + set: static fn(Carbon $value): string => $value->format('Y-m-d') ); } protected function transactionCurrencyId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } } diff --git a/app/Models/Bill.php b/app/Models/Bill.php index 79420fed6e..5e40c718bb 100644 --- a/app/Models/Bill.php +++ b/app/Models/Bill.php @@ -45,28 +45,27 @@ class Bill extends Model use ReturnsIntegerUserIdTrait; use SoftDeletes; - protected $fillable - = [ - 'name', - 'match', - 'amount_min', - 'user_id', - 'user_group_id', - 'amount_max', - 'date', - 'date_tz', - 'repeat_freq', - 'skip', - 'automatch', - 'active', - 'transaction_currency_id', - 'end_date', - 'extension_date', - 'end_date_tz', - 'extension_date_tz', - 'native_amount_min', - 'native_amount_max', - ]; + protected $fillable = [ + 'name', + 'match', + 'amount_min', + 'user_id', + 'user_group_id', + 'amount_max', + 'date', + 'date_tz', + 'repeat_freq', + 'skip', + 'automatch', + 'active', + 'transaction_currency_id', + 'end_date', + 'extension_date', + 'end_date_tz', + 'extension_date_tz', + 'native_amount_min', + 'native_amount_max' + ]; protected $hidden = ['amount_min_encrypted', 'amount_max_encrypted', 'name_encrypted', 'match_encrypted']; @@ -78,13 +77,13 @@ class Bill extends Model public static function routeBinder(string $value): self { if (auth()->check()) { - $billId = (int)$value; + $billId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|Bill $bill */ - $bill = $user->bills()->find($billId); + $bill = $user->bills()->find($billId); if (null !== $bill) { return $bill; } @@ -124,7 +123,7 @@ class Bill extends Model */ public function setAmountMaxAttribute($value): void { - $this->attributes['amount_max'] = (string)$value; + $this->attributes['amount_max'] = (string) $value; } /** @@ -132,7 +131,7 @@ class Bill extends Model */ public function setAmountMinAttribute($value): void { - $this->attributes['amount_min'] = (string)$value; + $this->attributes['amount_min'] = (string) $value; } public function transactionCurrency(): BelongsTo @@ -150,9 +149,7 @@ class Bill extends Model */ protected function amountMax(): Attribute { - return Attribute::make( - get: static fn ($value): string => (string)$value, - ); + return Attribute::make(get: static fn($value): string => (string) $value); } /** @@ -160,9 +157,7 @@ class Bill extends Model */ protected function amountMin(): Attribute { - return Attribute::make( - get: static fn ($value): string => (string)$value, - ); + return Attribute::make(get: static fn($value): string => (string) $value); } protected function casts(): array @@ -182,15 +177,13 @@ class Bill extends Model 'amount_min' => 'string', 'amount_max' => 'string', 'native_amount_min' => 'string', - 'native_amount_max' => 'string', + 'native_amount_max' => 'string' ]; } protected function order(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } /** @@ -198,15 +191,11 @@ class Bill extends Model */ protected function skip(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } protected function transactionCurrencyId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } } diff --git a/app/Models/Budget.php b/app/Models/Budget.php index e49885b1f0..f11b96c13d 100644 --- a/app/Models/Budget.php +++ b/app/Models/Budget.php @@ -46,7 +46,7 @@ class Budget extends Model protected $fillable = ['user_id', 'user_group_id', 'name', 'active', 'order', 'user_group_id']; - protected $hidden = ['encrypted']; + protected $hidden = ['encrypted']; /** * Route binder. Converts the key in the URL to the specified object (or throw 404). @@ -56,13 +56,13 @@ class Budget extends Model public static function routeBinder(string $value): self { if (auth()->check()) { - $budgetId = (int)$value; + $budgetId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|Budget $budget */ - $budget = $user->budgets()->find($budgetId); + $budget = $user->budgets()->find($budgetId); if (null !== $budget) { return $budget; } @@ -118,15 +118,13 @@ class Budget extends Model 'active' => 'boolean', 'encrypted' => 'boolean', 'user_id' => 'integer', - 'user_group_id' => 'integer', + 'user_group_id' => 'integer' ]; } protected function order(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } public function primaryPeriodStatistics(): MorphMany diff --git a/app/Models/BudgetLimit.php b/app/Models/BudgetLimit.php index 3c76514cbd..c76cf1b849 100644 --- a/app/Models/BudgetLimit.php +++ b/app/Models/BudgetLimit.php @@ -56,12 +56,11 @@ class BudgetLimit extends Model public static function routeBinder(string $value): self { if (auth()->check()) { - $budgetLimitId = (int)$value; + $budgetLimitId = (int) $value; $budgetLimit = self::where('budget_limits.id', $budgetLimitId) ->leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id') ->where('budgets.user_id', auth()->user()->id) - ->first(['budget_limits.*']) - ; + ->first(['budget_limits.*']); if (null !== $budgetLimit) { return $budgetLimit; } @@ -93,16 +92,12 @@ class BudgetLimit extends Model */ protected function amount(): Attribute { - return Attribute::make( - get: static fn ($value): string => (string)$value, - ); + return Attribute::make(get: static fn($value): string => (string) $value); } protected function budgetId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } protected function casts(): array @@ -114,14 +109,12 @@ class BudgetLimit extends Model 'end_date' => SeparateTimezoneCaster::class, 'auto_budget' => 'boolean', 'amount' => 'string', - 'native_amount' => 'string', + 'native_amount' => 'string' ]; } protected function transactionCurrencyId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } } diff --git a/app/Models/Category.php b/app/Models/Category.php index 5eb63dbcba..5494fb06af 100644 --- a/app/Models/Category.php +++ b/app/Models/Category.php @@ -45,7 +45,7 @@ class Category extends Model protected $fillable = ['user_id', 'user_group_id', 'name']; - protected $hidden = ['encrypted']; + protected $hidden = ['encrypted']; /** * Route binder. Converts the key in the URL to the specified object (or throw 404). @@ -55,13 +55,13 @@ class Category extends Model public static function routeBinder(string $value): self { if (auth()->check()) { - $categoryId = (int)$value; + $categoryId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|Category $category */ - $category = $user->categories()->find($categoryId); + $category = $user->categories()->find($categoryId); if (null !== $category) { return $category; } @@ -106,7 +106,7 @@ class Category extends Model 'deleted_at' => 'datetime', 'encrypted' => 'boolean', 'user_id' => 'integer', - 'user_group_id' => 'integer', + 'user_group_id' => 'integer' ]; } diff --git a/app/Models/Configuration.php b/app/Models/Configuration.php index 98216193e1..0ae972e12c 100644 --- a/app/Models/Configuration.php +++ b/app/Models/Configuration.php @@ -40,11 +40,7 @@ class Configuration extends Model protected function casts(): array { - return [ - 'created_at' => 'datetime', - 'updated_at' => 'datetime', - 'deleted_at' => 'datetime', - ]; + return ['created_at' => 'datetime', 'updated_at' => 'datetime', 'deleted_at' => 'datetime']; } /** @@ -52,6 +48,6 @@ class Configuration extends Model */ protected function data(): Attribute { - return Attribute::make(get: static fn ($value): mixed => json_decode((string)$value), set: static fn ($value): array => ['data' => json_encode($value)]); + return Attribute::make(get: static fn($value): mixed => json_decode((string) $value), set: static fn($value): array => ['data' => json_encode($value)]); } } diff --git a/app/Models/CurrencyExchangeRate.php b/app/Models/CurrencyExchangeRate.php index ce0f0973a7..eb9472c533 100644 --- a/app/Models/CurrencyExchangeRate.php +++ b/app/Models/CurrencyExchangeRate.php @@ -66,35 +66,27 @@ class CurrencyExchangeRate extends Model 'to_currency_id' => 'integer', 'date' => SeparateTimezoneCaster::class, 'rate' => 'string', - 'user_rate' => 'string', + 'user_rate' => 'string' ]; } protected function fromCurrencyId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } protected function rate(): Attribute { - return Attribute::make( - get: static fn ($value): string => (string)$value, - ); + return Attribute::make(get: static fn($value): string => (string) $value); } protected function toCurrencyId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } protected function userRate(): Attribute { - return Attribute::make( - get: static fn ($value): string => (string)$value, - ); + return Attribute::make(get: static fn($value): string => (string) $value); } } diff --git a/app/Models/GroupMembership.php b/app/Models/GroupMembership.php index 443f4e7654..365bc28944 100644 --- a/app/Models/GroupMembership.php +++ b/app/Models/GroupMembership.php @@ -55,18 +55,11 @@ class GroupMembership extends Model protected function casts(): array { - return [ - 'created_at' => 'datetime', - 'updated_at' => 'datetime', - 'user_id' => 'integer', - 'user_group_id' => 'integer', - ]; + return ['created_at' => 'datetime', 'updated_at' => 'datetime', 'user_id' => 'integer', 'user_group_id' => 'integer']; } protected function userRoleId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } } diff --git a/app/Models/InvitedUser.php b/app/Models/InvitedUser.php index 81e945b5e9..3ee792e92c 100644 --- a/app/Models/InvitedUser.php +++ b/app/Models/InvitedUser.php @@ -45,10 +45,10 @@ class InvitedUser extends Model public static function routeBinder(string $value): self { if (auth()->check()) { - $attemptId = (int)$value; + $attemptId = (int) $value; /** @var null|InvitedUser $attempt */ - $attempt = self::find($attemptId); + $attempt = self::find($attemptId); if (null !== $attempt) { return $attempt; } @@ -64,11 +64,6 @@ class InvitedUser extends Model protected function casts(): array { - return [ - 'expires' => SeparateTimezoneCaster::class, - 'redeemed' => 'boolean', - 'user_id' => 'integer', - 'user_group_id' => 'integer', - ]; + return ['expires' => SeparateTimezoneCaster::class, 'redeemed' => 'boolean', 'user_id' => 'integer', 'user_group_id' => 'integer']; } } diff --git a/app/Models/LinkType.php b/app/Models/LinkType.php index e399ad2e9a..cd3e06a8f0 100644 --- a/app/Models/LinkType.php +++ b/app/Models/LinkType.php @@ -44,7 +44,7 @@ class LinkType extends Model public static function routeBinder(string $value): self { if (auth()->check()) { - $linkTypeId = (int)$value; + $linkTypeId = (int) $value; $linkType = self::find($linkTypeId); if (null !== $linkType) { return $linkType; @@ -61,11 +61,6 @@ class LinkType extends Model protected function casts(): array { - return [ - 'created_at' => 'datetime', - 'updated_at' => 'datetime', - 'deleted_at' => 'datetime', - 'editable' => 'boolean', - ]; + return ['created_at' => 'datetime', 'updated_at' => 'datetime', 'deleted_at' => 'datetime', 'editable' => 'boolean']; } } diff --git a/app/Models/Location.php b/app/Models/Location.php index 14812341e0..4ed86a0dcb 100644 --- a/app/Models/Location.php +++ b/app/Models/Location.php @@ -41,8 +41,8 @@ class Location extends Model */ public static function requestRules(array $rules): array { - $rules['latitude'] = 'numeric|min:-90|max:90|nullable|required_with:longitude'; - $rules['longitude'] = 'numeric|min:-180|max:180|nullable|required_with:latitude'; + $rules['latitude'] = 'numeric|min:-90|max:90|nullable|required_with:longitude'; + $rules['longitude'] = 'numeric|min:-180|max:180|nullable|required_with:latitude'; $rules['zoom_level'] = 'numeric|min:0|max:80|nullable|required_with:latitude'; return $rules; @@ -74,14 +74,12 @@ class Location extends Model 'deleted_at' => 'datetime', 'zoomLevel' => 'int', 'latitude' => 'float', - 'longitude' => 'float', + 'longitude' => 'float' ]; } protected function locatableId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } } diff --git a/app/Models/Note.php b/app/Models/Note.php index 372406f58a..8c739a4580 100644 --- a/app/Models/Note.php +++ b/app/Models/Note.php @@ -46,17 +46,11 @@ class Note extends Model protected function casts(): array { - return [ - 'created_at' => 'datetime', - 'updated_at' => 'datetime', - 'deleted_at' => 'datetime', - ]; + return ['created_at' => 'datetime', 'updated_at' => 'datetime', 'deleted_at' => 'datetime']; } protected function noteableId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } } diff --git a/app/Models/ObjectGroup.php b/app/Models/ObjectGroup.php index 046e909261..b7961d1e8a 100644 --- a/app/Models/ObjectGroup.php +++ b/app/Models/ObjectGroup.php @@ -48,12 +48,10 @@ class ObjectGroup extends Model public static function routeBinder(string $value): self { if (auth()->check()) { - $objectGroupId = (int)$value; + $objectGroupId = (int) $value; /** @var null|ObjectGroup $objectGroup */ - $objectGroup = self::where('object_groups.id', $objectGroupId) - ->where('object_groups.user_id', auth()->user()->id)->first() - ; + $objectGroup = self::where('object_groups.id', $objectGroupId)->where('object_groups.user_id', auth()->user()->id)->first(); if (null !== $objectGroup) { return $objectGroup; } @@ -98,14 +96,12 @@ class ObjectGroup extends Model 'updated_at' => 'datetime', 'user_id' => 'integer', 'user_group_id' => 'integer', - 'deleted_at' => 'datetime', + 'deleted_at' => 'datetime' ]; } protected function order(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } } diff --git a/app/Models/PeriodStatistic.php b/app/Models/PeriodStatistic.php index d9407ef4a0..145c208f82 100644 --- a/app/Models/PeriodStatistic.php +++ b/app/Models/PeriodStatistic.php @@ -18,10 +18,10 @@ class PeriodStatistic extends Model protected function casts(): array { return [ - 'created_at' => 'datetime', - 'updated_at' => 'datetime', - 'start' => SeparateTimezoneCaster::class, - 'end' => SeparateTimezoneCaster::class, + 'created_at' => 'datetime', + 'updated_at' => 'datetime', + 'start' => SeparateTimezoneCaster::class, + 'end' => SeparateTimezoneCaster::class ]; } @@ -32,29 +32,21 @@ class PeriodStatistic extends Model protected function count(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } public function primaryStatable(): MorphTo { - return $this->morphTo(); - } public function secondaryStatable(): MorphTo { - return $this->morphTo(); - } public function tertiaryStatable(): MorphTo { - return $this->morphTo(); - } } diff --git a/app/Models/PiggyBank.php b/app/Models/PiggyBank.php index 29da6024f2..c8429d5f0c 100644 --- a/app/Models/PiggyBank.php +++ b/app/Models/PiggyBank.php @@ -42,7 +42,18 @@ class PiggyBank extends Model use ReturnsIntegerIdTrait; use SoftDeletes; - protected $fillable = ['name', 'order', 'target_amount', 'start_date', 'start_date_tz', 'target_date', 'target_date_tz', 'active', 'transaction_currency_id', 'native_target_amount']; + protected $fillable = [ + 'name', + 'order', + 'target_amount', + 'start_date', + 'start_date_tz', + 'target_date', + 'target_date_tz', + 'active', + 'transaction_currency_id', + 'native_target_amount' + ]; /** * Route binder. Converts the key in the URL to the specified object (or throw 404). @@ -52,12 +63,12 @@ class PiggyBank extends Model public static function routeBinder(string $value): self { if (auth()->check()) { - $piggyBankId = (int)$value; + $piggyBankId = (int) $value; $piggyBank = self::where('piggy_banks.id', $piggyBankId) ->leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id') ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id') - ->where('accounts.user_id', auth()->user()->id)->first(['piggy_banks.*']) - ; + ->where('accounts.user_id', auth()->user()->id) + ->first(['piggy_banks.*']); if (null !== $piggyBank) { return $piggyBank; } @@ -112,7 +123,7 @@ class PiggyBank extends Model */ public function setTargetAmountAttribute($value): void { - $this->attributes['target_amount'] = (string)$value; + $this->attributes['target_amount'] = (string) $value; } public function transactionCurrency(): BelongsTo @@ -122,9 +133,7 @@ class PiggyBank extends Model protected function accountId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } protected function casts(): array @@ -139,15 +148,13 @@ class PiggyBank extends Model 'active' => 'boolean', 'encrypted' => 'boolean', 'target_amount' => 'string', - 'native_target_amount' => 'string', + 'native_target_amount' => 'string' ]; } protected function order(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } /** @@ -155,8 +162,6 @@ class PiggyBank extends Model */ protected function targetAmount(): Attribute { - return Attribute::make( - get: static fn ($value): string => (string)$value, - ); + return Attribute::make(get: static fn($value): string => (string) $value); } } diff --git a/app/Models/PiggyBankEvent.php b/app/Models/PiggyBankEvent.php index 6c5375b5e4..9208d8a829 100644 --- a/app/Models/PiggyBankEvent.php +++ b/app/Models/PiggyBankEvent.php @@ -38,7 +38,7 @@ class PiggyBankEvent extends Model protected $fillable = ['piggy_bank_id', 'transaction_journal_id', 'date', 'date_tz', 'amount', 'native_amount']; - protected $hidden = ['amount_encrypted']; + protected $hidden = ['amount_encrypted']; public function piggyBank(): BelongsTo { @@ -50,7 +50,7 @@ class PiggyBankEvent extends Model */ public function setAmountAttribute($value): void { - $this->attributes['amount'] = (string)$value; + $this->attributes['amount'] = (string) $value; } public function transactionJournal(): BelongsTo @@ -63,9 +63,7 @@ class PiggyBankEvent extends Model */ protected function amount(): Attribute { - return Attribute::make( - get: static fn ($value): string => (string)$value, - ); + return Attribute::make(get: static fn($value): string => (string) $value); } protected function casts(): array @@ -75,14 +73,12 @@ class PiggyBankEvent extends Model 'updated_at' => 'datetime', 'date' => SeparateTimezoneCaster::class, 'amount' => 'string', - 'native_amount' => 'string', + 'native_amount' => 'string' ]; } protected function piggyBankId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } } diff --git a/app/Models/PiggyBankRepetition.php b/app/Models/PiggyBankRepetition.php index 71b9a554ca..20127d3d6d 100644 --- a/app/Models/PiggyBankRepetition.php +++ b/app/Models/PiggyBankRepetition.php @@ -48,7 +48,7 @@ class PiggyBankRepetition extends Model */ public function setCurrentAmountAttribute($value): void { - $this->attributes['current_amount'] = (string)$value; + $this->attributes['current_amount'] = (string) $value; } protected function casts(): array @@ -58,7 +58,7 @@ class PiggyBankRepetition extends Model 'updated_at' => 'datetime', 'start_date' => SeparateTimezoneCaster::class, 'target_date' => SeparateTimezoneCaster::class, - 'virtual_balance' => 'string', + 'virtual_balance' => 'string' ]; } @@ -67,9 +67,7 @@ class PiggyBankRepetition extends Model */ protected function currentAmount(): Attribute { - return Attribute::make( - get: static fn ($value): string => (string)$value, - ); + return Attribute::make(get: static fn($value): string => (string) $value); } #[Scope] @@ -80,9 +78,7 @@ class PiggyBankRepetition extends Model protected function piggyBankId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } /** @@ -91,18 +87,12 @@ class PiggyBankRepetition extends Model #[Scope] protected function relevantOnDate(EloquentBuilder $query, Carbon $date) { - return $query->where( - static function (EloquentBuilder $q) use ($date): void { - $q->where('start_date', '<=', $date->format('Y-m-d 00:00:00')); - $q->orWhereNull('start_date'); - } - ) - ->where( - static function (EloquentBuilder $q) use ($date): void { - $q->where('target_date', '>=', $date->format('Y-m-d 00:00:00')); - $q->orWhereNull('target_date'); - } - ) - ; + return $query->where(static function (EloquentBuilder $q) use ($date): void { + $q->where('start_date', '<=', $date->format('Y-m-d 00:00:00')); + $q->orWhereNull('start_date'); + })->where(static function (EloquentBuilder $q) use ($date): void { + $q->where('target_date', '>=', $date->format('Y-m-d 00:00:00')); + $q->orWhereNull('target_date'); + }); } } diff --git a/app/Models/Preference.php b/app/Models/Preference.php index 151e5bbd35..a7a6a5297f 100644 --- a/app/Models/Preference.php +++ b/app/Models/Preference.php @@ -46,16 +46,16 @@ class Preference extends Model { if (auth()->check()) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); // some preferences do not have an administration ID. // some need it, to make sure the correct one is selected. - $userGroupId = (int)$user->user_group_id; + $userGroupId = (int) $user->user_group_id; $userGroupId = 0 === $userGroupId ? null : $userGroupId; /** @var null|Preference $preference */ - $preference = null; - $items = config('firefly.admin_specific_prefs'); + $preference = null; + $items = config('firefly.admin_specific_prefs'); if (null !== $userGroupId && in_array($value, $items, true)) { // find a preference with a specific user_group_id $preference = $user->preferences()->where('user_group_id', $userGroupId)->where('name', $value)->first(); @@ -67,18 +67,18 @@ class Preference extends Model // try again with ID, but this time don't care about the preferred user_group_id if (null === $preference) { - $preference = $user->preferences()->where('id', (int)$value)->first(); + $preference = $user->preferences()->where('id', (int) $value)->first(); } if (null !== $preference) { /** @var Preference $preference */ return $preference; } - $default = config('firefly.default_preferences'); + $default = config('firefly.default_preferences'); if (array_key_exists($value, $default)) { - $preference = new self(); - $preference->name = $value; - $preference->data = $default[$value]; - $preference->user_id = (int)$user->id; + $preference = new self(); + $preference->name = $value; + $preference->data = $default[$value]; + $preference->user_id = (int) $user->id; $preference->user_group_id = in_array($value, $items, true) ? $userGroupId : null; $preference->save(); @@ -101,7 +101,7 @@ class Preference extends Model 'updated_at' => 'datetime', 'data' => 'array', 'user_id' => 'integer', - 'user_group_id' => 'integer', + 'user_group_id' => 'integer' ]; } } diff --git a/app/Models/Recurrence.php b/app/Models/Recurrence.php index 42f5cad07b..d40b2cce8e 100644 --- a/app/Models/Recurrence.php +++ b/app/Models/Recurrence.php @@ -50,8 +50,22 @@ class Recurrence extends Model use ReturnsIntegerUserIdTrait; use SoftDeletes; - protected $fillable - = ['user_id', 'user_group_id', 'transaction_type_id', 'title', 'description', 'first_date', 'first_date_tz', 'repeat_until', 'repeat_until_tz', 'latest_date', 'latest_date_tz', 'repetitions', 'apply_rules', 'active']; + protected $fillable = [ + 'user_id', + 'user_group_id', + 'transaction_type_id', + 'title', + 'description', + 'first_date', + 'first_date_tz', + 'repeat_until', + 'repeat_until_tz', + 'latest_date', + 'latest_date_tz', + 'repetitions', + 'apply_rules', + 'active' + ]; protected $table = 'recurrences'; @@ -63,13 +77,13 @@ class Recurrence extends Model public static function routeBinder(string $value): self { if (auth()->check()) { - $recurrenceId = (int)$value; + $recurrenceId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|Recurrence $recurrence */ - $recurrence = $user->recurrences()->find($recurrenceId); + $recurrence = $user->recurrences()->find($recurrenceId); if (null !== $recurrence) { return $recurrence; } @@ -137,14 +151,12 @@ class Recurrence extends Model 'active' => 'bool', 'apply_rules' => 'bool', 'user_id' => 'integer', - 'user_group_id' => 'integer', + 'user_group_id' => 'integer' ]; } protected function transactionTypeId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } } diff --git a/app/Models/RecurrenceMeta.php b/app/Models/RecurrenceMeta.php index 0dbf376184..a1e2e1a127 100644 --- a/app/Models/RecurrenceMeta.php +++ b/app/Models/RecurrenceMeta.php @@ -37,7 +37,7 @@ class RecurrenceMeta extends Model protected $fillable = ['recurrence_id', 'name', 'value']; - protected $table = 'recurrences_meta'; + protected $table = 'recurrences_meta'; public function recurrence(): BelongsTo { @@ -46,19 +46,11 @@ class RecurrenceMeta extends Model protected function casts(): array { - return [ - 'created_at' => 'datetime', - 'updated_at' => 'datetime', - 'deleted_at' => 'datetime', - 'name' => 'string', - 'value' => 'string', - ]; + return ['created_at' => 'datetime', 'updated_at' => 'datetime', 'deleted_at' => 'datetime', 'name' => 'string', 'value' => 'string']; } protected function recurrenceId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } } diff --git a/app/Models/RecurrenceRepetition.php b/app/Models/RecurrenceRepetition.php index 3e11acc67e..e21c945de8 100644 --- a/app/Models/RecurrenceRepetition.php +++ b/app/Models/RecurrenceRepetition.php @@ -36,36 +36,35 @@ class RecurrenceRepetition extends Model use ReturnsIntegerIdTrait; use SoftDeletes; - #[Deprecated] /** @deprecated */ - public const int WEEKEND_DO_NOTHING = 1; + #[Deprecated] + public const int WEEKEND_DO_NOTHING = 1; - #[Deprecated] /** @deprecated */ + #[Deprecated] public const int WEEKEND_SKIP_CREATION = 2; - #[Deprecated] /** @deprecated */ - public const int WEEKEND_TO_FRIDAY = 3; - #[Deprecated] + public const int WEEKEND_TO_FRIDAY = 3; + /** @deprecated */ - public const int WEEKEND_TO_MONDAY = 4; + #[Deprecated] + public const int WEEKEND_TO_MONDAY = 4; - protected $casts - = [ - 'created_at' => 'datetime', - 'updated_at' => 'datetime', - 'deleted_at' => 'datetime', - 'repetition_type' => 'string', - 'repetition_moment' => 'string', - 'repetition_skip' => 'int', - 'weekend' => 'int', - ]; + protected $casts = [ + 'created_at' => 'datetime', + 'updated_at' => 'datetime', + 'deleted_at' => 'datetime', + 'repetition_type' => 'string', + 'repetition_moment' => 'string', + 'repetition_skip' => 'int', + 'weekend' => 'int' + ]; - protected $fillable = ['recurrence_id', 'weekend', 'repetition_type', 'repetition_moment', 'repetition_skip']; + protected $fillable = ['recurrence_id', 'weekend', 'repetition_type', 'repetition_moment', 'repetition_skip']; - protected $table = 'recurrences_repetitions'; + protected $table = 'recurrences_repetitions'; public function recurrence(): BelongsTo { @@ -81,22 +80,16 @@ class RecurrenceRepetition extends Model protected function recurrenceId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } protected function repetitionSkip(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } protected function weekend(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } } diff --git a/app/Models/RecurrenceTransaction.php b/app/Models/RecurrenceTransaction.php index c1a1892b83..8f78d9f4e2 100644 --- a/app/Models/RecurrenceTransaction.php +++ b/app/Models/RecurrenceTransaction.php @@ -39,17 +39,16 @@ class RecurrenceTransaction extends Model use ReturnsIntegerIdTrait; use SoftDeletes; - protected $fillable - = [ - 'recurrence_id', - 'transaction_currency_id', - 'foreign_currency_id', - 'source_id', - 'destination_id', - 'amount', - 'foreign_amount', - 'description', - ]; + protected $fillable = [ + 'recurrence_id', + 'transaction_currency_id', + 'foreign_currency_id', + 'source_id', + 'destination_id', + 'amount', + 'foreign_amount', + 'description' + ]; protected $table = 'recurrences_transactions'; @@ -90,9 +89,7 @@ class RecurrenceTransaction extends Model protected function amount(): Attribute { - return Attribute::make( - get: static fn ($value): string => (string)$value, - ); + return Attribute::make(get: static fn($value): string => (string) $value); } protected function casts(): array @@ -103,49 +100,37 @@ class RecurrenceTransaction extends Model 'deleted_at' => 'datetime', 'amount' => 'string', 'foreign_amount' => 'string', - 'description' => 'string', + 'description' => 'string' ]; } protected function destinationId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } protected function foreignAmount(): Attribute { - return Attribute::make( - get: static fn ($value): string => (string)$value, - ); + return Attribute::make(get: static fn($value): string => (string) $value); } protected function recurrenceId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } protected function sourceId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } protected function transactionCurrencyId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } protected function userId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } } diff --git a/app/Models/RecurrenceTransactionMeta.php b/app/Models/RecurrenceTransactionMeta.php index 5ced2d13ae..a70f63c8a0 100644 --- a/app/Models/RecurrenceTransactionMeta.php +++ b/app/Models/RecurrenceTransactionMeta.php @@ -37,7 +37,7 @@ class RecurrenceTransactionMeta extends Model protected $fillable = ['rt_id', 'name', 'value']; - protected $table = 'rt_meta'; + protected $table = 'rt_meta'; public function recurrenceTransaction(): BelongsTo { @@ -46,19 +46,11 @@ class RecurrenceTransactionMeta extends Model protected function casts(): array { - return [ - 'created_at' => 'datetime', - 'updated_at' => 'datetime', - 'deleted_at' => 'datetime', - 'name' => 'string', - 'value' => 'string', - ]; + return ['created_at' => 'datetime', 'updated_at' => 'datetime', 'deleted_at' => 'datetime', 'name' => 'string', 'value' => 'string']; } protected function rtId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } } diff --git a/app/Models/Role.php b/app/Models/Role.php index b1b3476ca4..d6409f435a 100644 --- a/app/Models/Role.php +++ b/app/Models/Role.php @@ -41,9 +41,6 @@ class Role extends Model protected function casts(): array { - return [ - 'created_at' => 'datetime', - 'updated_at' => 'datetime', - ]; + return ['created_at' => 'datetime', 'updated_at' => 'datetime']; } } diff --git a/app/Models/Rule.php b/app/Models/Rule.php index 71c126cf9a..3a45389db3 100644 --- a/app/Models/Rule.php +++ b/app/Models/Rule.php @@ -55,13 +55,13 @@ class Rule extends Model public static function routeBinder(string $value): self { if (auth()->check()) { - $ruleId = (int)$value; + $ruleId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|Rule $rule */ - $rule = $user->rules()->find($ruleId); + $rule = $user->rules()->find($ruleId); if (null !== $rule) { return $rule; } @@ -107,26 +107,22 @@ class Rule extends Model 'id' => 'int', 'strict' => 'boolean', 'user_id' => 'integer', - 'user_group_id' => 'integer', + 'user_group_id' => 'integer' ]; } protected function description(): Attribute { - return Attribute::make(set: static fn ($value): array => ['description' => e($value)]); + return Attribute::make(set: static fn($value): array => ['description' => e($value)]); } protected function order(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } protected function ruleGroupId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } } diff --git a/app/Models/RuleAction.php b/app/Models/RuleAction.php index 3b706470b8..7406b2d1b3 100644 --- a/app/Models/RuleAction.php +++ b/app/Models/RuleAction.php @@ -42,7 +42,7 @@ class RuleAction extends Model if (false === config('firefly.feature_flags.expression_engine')) { Log::debug('Expression engine is disabled, returning action value as string.'); - return (string)$this->action_value; + return (string) $this->action_value; } if (true === config('firefly.feature_flags.expression_engine') && str_starts_with($this->action_value, '\=')) { // return literal string. @@ -54,7 +54,7 @@ class RuleAction extends Model $result = $expr->evaluate($journal); } catch (SyntaxError $e) { Log::error(sprintf('Expression engine failed to evaluate expression "%s" with error "%s".', $this->action_value, $e->getMessage())); - $result = (string)$this->action_value; + $result = (string) $this->action_value; } Log::debug(sprintf('Expression engine is enabled, result of expression "%s" is "%s".', $this->action_value, $result)); @@ -73,21 +73,17 @@ class RuleAction extends Model 'updated_at' => 'datetime', 'active' => 'boolean', 'order' => 'int', - 'stop_processing' => 'boolean', + 'stop_processing' => 'boolean' ]; } protected function order(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } protected function ruleId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } } diff --git a/app/Models/RuleGroup.php b/app/Models/RuleGroup.php index 2236efbf1a..a1781758e1 100644 --- a/app/Models/RuleGroup.php +++ b/app/Models/RuleGroup.php @@ -57,13 +57,13 @@ class RuleGroup extends Model public static function routeBinder(string $value): self { if (auth()->check()) { - $ruleGroupId = (int)$value; + $ruleGroupId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|RuleGroup $ruleGroup */ - $ruleGroup = $user->ruleGroups()->find($ruleGroupId); + $ruleGroup = $user->ruleGroups()->find($ruleGroupId); if (null !== $ruleGroup) { return $ruleGroup; } @@ -92,14 +92,12 @@ class RuleGroup extends Model 'stop_processing' => 'boolean', 'order' => 'int', 'user_id' => 'integer', - 'user_group_id' => 'integer', + 'user_group_id' => 'integer' ]; } protected function order(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } } diff --git a/app/Models/RuleTrigger.php b/app/Models/RuleTrigger.php index 303ca028bb..228b305f00 100644 --- a/app/Models/RuleTrigger.php +++ b/app/Models/RuleTrigger.php @@ -46,21 +46,17 @@ class RuleTrigger extends Model 'updated_at' => 'datetime', 'active' => 'boolean', 'order' => 'int', - 'stop_processing' => 'boolean', + 'stop_processing' => 'boolean' ]; } protected function order(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } protected function ruleId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } } diff --git a/app/Models/Tag.php b/app/Models/Tag.php index f348bea48a..1d0f3cce50 100644 --- a/app/Models/Tag.php +++ b/app/Models/Tag.php @@ -45,7 +45,7 @@ class Tag extends Model protected $fillable = ['user_id', 'user_group_id', 'tag', 'date', 'date_tz', 'description', 'tag_mode']; - protected $hidden = ['zoomLevel', 'zoom_level', 'latitude', 'longitude']; + protected $hidden = ['zoomLevel', 'zoom_level', 'latitude', 'longitude']; /** * Route binder. Converts the key in the URL to the specified object (or throw 404). @@ -55,13 +55,13 @@ class Tag extends Model public static function routeBinder(string $value): self { if (auth()->check()) { - $tagId = (int)$value; + $tagId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|Tag $tag */ - $tag = $user->tags()->find($tagId); + $tag = $user->tags()->find($tagId); if (null !== $tag) { return $tag; } @@ -101,7 +101,7 @@ class Tag extends Model 'latitude' => 'float', 'longitude' => 'float', 'user_id' => 'integer', - 'user_group_id' => 'integer', + 'user_group_id' => 'integer' ]; } diff --git a/app/Models/Transaction.php b/app/Models/Transaction.php index 90faba82d4..e026ca456f 100644 --- a/app/Models/Transaction.php +++ b/app/Models/Transaction.php @@ -43,20 +43,19 @@ class Transaction extends Model use ReturnsIntegerIdTrait; use SoftDeletes; - protected $fillable - = [ - 'account_id', - 'transaction_journal_id', - 'description', - 'amount', - 'native_amount', - 'native_foreign_amount', - 'identifier', - 'transaction_currency_id', - 'foreign_currency_id', - 'foreign_amount', - 'reconciled', - ]; + protected $fillable = [ + 'account_id', + 'transaction_journal_id', + 'description', + 'amount', + 'native_amount', + 'native_foreign_amount', + 'identifier', + 'transaction_currency_id', + 'foreign_currency_id', + 'foreign_amount', + 'reconciled' + ]; protected $hidden = ['encrypted']; @@ -97,7 +96,7 @@ class Transaction extends Model */ public function setAmountAttribute($value): void { - $this->attributes['amount'] = (string)$value; + $this->attributes['amount'] = (string) $value; } public function transactionCurrency(): BelongsTo @@ -112,9 +111,7 @@ class Transaction extends Model protected function accountId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } /** @@ -150,16 +147,12 @@ class Transaction extends Model */ protected function amount(): Attribute { - return Attribute::make( - get: static fn ($value): string => (string)$value, - ); + return Attribute::make(get: static fn($value): string => (string) $value); } protected function balanceDirty(): Attribute { - return Attribute::make( - get: static fn ($value): bool => 1 === (int)$value, - ); + return Attribute::make(get: static fn($value): bool => 1 === (int) $value); } /** @@ -177,11 +170,11 @@ class Transaction extends Model protected function casts(): array { return [ - 'created_at' => 'datetime', - 'updated_at' => 'datetime', - 'deleted_at' => 'datetime', - 'identifier' => 'int', - 'encrypted' => 'boolean', // model does not have these fields though + 'created_at' => 'datetime', + 'updated_at' => 'datetime', + 'deleted_at' => 'datetime', + 'identifier' => 'int', + 'encrypted' => 'boolean', // model does not have these fields though 'bill_name_encrypted' => 'boolean', 'reconciled' => 'boolean', 'balance_dirty' => 'boolean', @@ -191,7 +184,7 @@ class Transaction extends Model 'amount' => 'string', 'foreign_amount' => 'string', 'native_amount' => 'string', - 'native_foreign_amount' => 'string', + 'native_foreign_amount' => 'string' ]; } @@ -200,16 +193,12 @@ class Transaction extends Model */ protected function foreignAmount(): Attribute { - return Attribute::make( - get: static fn ($value): string => (string)$value, - ); + return Attribute::make(get: static fn($value): string => (string) $value); } protected function transactionJournalId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } #[Scope] diff --git a/app/Models/TransactionCurrency.php b/app/Models/TransactionCurrency.php index 7c8f6814c1..6a1e92adbf 100644 --- a/app/Models/TransactionCurrency.php +++ b/app/Models/TransactionCurrency.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Models; +use FireflyIII\Support\Facades\Amount; use FireflyIII\Support\Models\ReturnsIntegerIdTrait; use FireflyIII\User; use Illuminate\Database\Eloquent\Casts\Attribute; @@ -31,17 +32,16 @@ use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\SoftDeletes; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; -use FireflyIII\Support\Facades\Amount; class TransactionCurrency extends Model { use ReturnsIntegerIdTrait; use SoftDeletes; - public ?bool $userGroupEnabled = null; - public ?bool $userGroupNative = null; + public null|bool $userGroupEnabled = null; + public null|bool $userGroupNative = null; - protected $fillable = ['name', 'code', 'symbol', 'decimal_places', 'enabled']; + protected $fillable = ['name', 'code', 'symbol', 'decimal_places', 'enabled']; /** * Route binder. Converts the key in the URL to the specified object (or throw 404). @@ -51,7 +51,7 @@ class TransactionCurrency extends Model public static function routeBinder(string $value): self { if (auth()->check()) { - $currencyId = (int)$value; + $currencyId = (int) $value; $currency = self::find($currencyId); if (null !== $currency) { $currency->refreshForUser(auth()->user()); @@ -65,9 +65,9 @@ class TransactionCurrency extends Model public function refreshForUser(User $user): void { - $current = $user->userGroup->currencies()->where('transaction_currencies.id', $this->id)->first(); - $native = Amount::getPrimaryCurrencyByUserGroup($user->userGroup); - $this->userGroupNative = $native->id === $this->id; + $current = $user->userGroup->currencies()->where('transaction_currencies.id', $this->id)->first(); + $native = Amount::getPrimaryCurrencyByUserGroup($user->userGroup); + $this->userGroupNative = $native->id === $this->id; $this->userGroupEnabled = null !== $current; } @@ -109,14 +109,12 @@ class TransactionCurrency extends Model 'updated_at' => 'datetime', 'deleted_at' => 'datetime', 'decimal_places' => 'int', - 'enabled' => 'bool', + 'enabled' => 'bool' ]; } protected function decimalPlaces(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } } diff --git a/app/Models/TransactionGroup.php b/app/Models/TransactionGroup.php index ee6911ee37..5315593ae9 100644 --- a/app/Models/TransactionGroup.php +++ b/app/Models/TransactionGroup.php @@ -59,17 +59,18 @@ class TransactionGroup extends Model { Log::debug(sprintf('Now in %s("%s")', __METHOD__, $value)); if (auth()->check()) { - $groupId = (int)$value; + $groupId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); Log::debug(sprintf('User authenticated as %s', $user->email)); /** @var null|TransactionGroup $group */ - $group = $user->transactionGroups() + $group = $user + ->transactionGroups() ->with(['transactionJournals', 'transactionJournals.transactions']) - ->where('transaction_groups.id', $groupId)->first(['transaction_groups.*']) - ; + ->where('transaction_groups.id', $groupId) + ->first(['transaction_groups.*']); if (null !== $group) { Log::debug(sprintf('Found group #%d.', $group->id)); @@ -106,7 +107,7 @@ class TransactionGroup extends Model 'title' => 'string', 'date' => 'datetime', 'user_id' => 'integer', - 'user_group_id' => 'integer', + 'user_group_id' => 'integer' ]; } } diff --git a/app/Models/TransactionJournal.php b/app/Models/TransactionJournal.php index 6cab9c4e52..f4ff88e26f 100644 --- a/app/Models/TransactionJournal.php +++ b/app/Models/TransactionJournal.php @@ -58,20 +58,19 @@ class TransactionJournal extends Model use ReturnsIntegerUserIdTrait; use SoftDeletes; - protected $fillable - = [ - 'user_id', - 'user_group_id', - 'transaction_type_id', - 'bill_id', - 'tag_count', - 'transaction_currency_id', - 'description', - 'completed', - 'order', - 'date', - 'date_tz', - ]; + protected $fillable = [ + 'user_id', + 'user_group_id', + 'transaction_type_id', + 'bill_id', + 'tag_count', + 'transaction_currency_id', + 'description', + 'completed', + 'order', + 'date', + 'date_tz' + ]; protected $hidden = ['encrypted']; @@ -83,13 +82,13 @@ class TransactionJournal extends Model public static function routeBinder(string $value): self { if (auth()->check()) { - $journalId = (int)$value; + $journalId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|TransactionJournal $journal */ - $journal = $user->transactionJournals()->where('transaction_journals.id', $journalId)->first(['transaction_journals.*']); + $journal = $user->transactionJournals()->where('transaction_journals.id', $journalId)->first(['transaction_journals.*']); if (null !== $journal) { return $journal; } @@ -225,22 +224,18 @@ class TransactionJournal extends Model 'encrypted' => 'boolean', 'completed' => 'boolean', 'user_id' => 'integer', - 'user_group_id' => 'integer', + 'user_group_id' => 'integer' ]; } protected function order(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } protected function transactionTypeId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } #[Scope] diff --git a/app/Models/TransactionJournalLink.php b/app/Models/TransactionJournalLink.php index 2bb5738c87..9babd6649f 100644 --- a/app/Models/TransactionJournalLink.php +++ b/app/Models/TransactionJournalLink.php @@ -44,14 +44,13 @@ class TransactionJournalLink extends Model public static function routeBinder(string $value): self { if (auth()->check()) { - $linkId = (int)$value; + $linkId = (int) $value; $link = self::where('journal_links.id', $linkId) ->leftJoin('transaction_journals as t_a', 't_a.id', '=', 'source_id') ->leftJoin('transaction_journals as t_b', 't_b.id', '=', 'destination_id') ->where('t_a.user_id', auth()->user()->id) ->where('t_b.user_id', auth()->user()->id) - ->first(['journal_links.*']) - ; + ->first(['journal_links.*']); if (null !== $link) { return $link; } @@ -85,30 +84,21 @@ class TransactionJournalLink extends Model protected function casts(): array { - return [ - 'created_at' => 'datetime', - 'updated_at' => 'datetime', - ]; + return ['created_at' => 'datetime', 'updated_at' => 'datetime']; } protected function destinationId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } protected function linkTypeId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } protected function sourceId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } } diff --git a/app/Models/TransactionJournalMeta.php b/app/Models/TransactionJournalMeta.php index 01eca70642..71e29259c5 100644 --- a/app/Models/TransactionJournalMeta.php +++ b/app/Models/TransactionJournalMeta.php @@ -39,7 +39,7 @@ class TransactionJournalMeta extends Model protected $fillable = ['transaction_journal_id', 'name', 'data', 'hash']; - protected $table = 'journal_meta'; + protected $table = 'journal_meta'; public function transactionJournal(): BelongsTo { @@ -48,16 +48,12 @@ class TransactionJournalMeta extends Model protected function casts(): array { - return [ - 'created_at' => 'datetime', - 'updated_at' => 'datetime', - 'deleted_at' => 'datetime', - ]; + return ['created_at' => 'datetime', 'updated_at' => 'datetime', 'deleted_at' => 'datetime']; } protected function data(): Attribute { - return Attribute::make(get: static fn ($value): mixed => json_decode((string)$value, false), set: static function ($value): array { + return Attribute::make(get: static fn($value): mixed => json_decode((string) $value, false), set: static function ($value): array { $data = json_encode($value); return ['data' => $data, 'hash' => hash('sha256', $data)]; @@ -66,8 +62,6 @@ class TransactionJournalMeta extends Model protected function transactionJournalId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } } diff --git a/app/Models/TransactionType.php b/app/Models/TransactionType.php index cac754f110..247eb22de8 100644 --- a/app/Models/TransactionType.php +++ b/app/Models/TransactionType.php @@ -36,41 +36,36 @@ class TransactionType extends Model use ReturnsIntegerIdTrait; use SoftDeletes; - #[Deprecated] /** @deprecated */ - public const string DEPOSIT = 'Deposit'; + #[Deprecated] + public const string DEPOSIT = 'Deposit'; - #[Deprecated] /** @deprecated */ - public const string INVALID = 'Invalid'; + #[Deprecated] + public const string INVALID = 'Invalid'; - #[Deprecated] /** @deprecated */ + #[Deprecated] public const string LIABILITY_CREDIT = 'Liability credit'; - #[Deprecated] /** @deprecated */ - public const string OPENING_BALANCE = 'Opening balance'; - #[Deprecated] - /** @deprecated */ - public const string RECONCILIATION = 'Reconciliation'; + public const string OPENING_BALANCE = 'Opening balance'; + /** @deprecated */ #[Deprecated] - /** @deprecated */ - public const string TRANSFER = 'Transfer'; + public const string RECONCILIATION = 'Reconciliation'; + /** @deprecated */ #[Deprecated] - /** @deprecated */ - public const string WITHDRAWAL = 'Withdrawal'; + public const string TRANSFER = 'Transfer'; - protected $casts - = [ - 'created_at' => 'datetime', - 'updated_at' => 'datetime', - 'deleted_at' => 'datetime', - ]; - protected $fillable = ['type']; + /** @deprecated */ + #[Deprecated] + public const string WITHDRAWAL = 'Withdrawal'; + + protected $casts = ['created_at' => 'datetime', 'updated_at' => 'datetime', 'deleted_at' => 'datetime']; + protected $fillable = ['type']; /** * Route binder. Converts the key in the URL to the specified object (or throw 404). diff --git a/app/Models/UserGroup.php b/app/Models/UserGroup.php index e0ff63268a..31242c3d94 100644 --- a/app/Models/UserGroup.php +++ b/app/Models/UserGroup.php @@ -47,19 +47,19 @@ class UserGroup extends Model public static function routeBinder(string $value): self { if (auth()->check()) { - $userGroupId = (int)$value; + $userGroupId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|UserGroup $userGroup */ - $userGroup = self::find($userGroupId); + $userGroup = self::find($userGroupId); if (null === $userGroup) { throw new NotFoundHttpException(); } // need at least ready only to be aware of the user group's existence, // but owner/full role (in the group) or global owner role may overrule this. - $access = $user->hasRoleInGroupOrOwner($userGroup, UserRoleEnum::READ_ONLY) || $user->hasRole('owner'); + $access = $user->hasRoleInGroupOrOwner($userGroup, UserRoleEnum::READ_ONLY) || $user->hasRole('owner'); if ($access) { return $userGroup; } diff --git a/app/Models/Webhook.php b/app/Models/Webhook.php index ab7e477e37..1120318754 100644 --- a/app/Models/Webhook.php +++ b/app/Models/Webhook.php @@ -46,15 +46,14 @@ class Webhook extends Model use ReturnsIntegerUserIdTrait; use SoftDeletes; - protected $casts - = [ - 'active' => 'boolean', - 'trigger' => 'integer', - 'response' => 'integer', - 'delivery' => 'integer', - 'user_id' => 'integer', - 'user_group_id' => 'integer', - ]; + protected $casts = [ + 'active' => 'boolean', + 'trigger' => 'integer', + 'response' => 'integer', + 'delivery' => 'integer', + 'user_id' => 'integer', + 'user_group_id' => 'integer' + ]; protected $fillable = ['active', 'trigger', 'response', 'delivery', 'user_id', 'user_group_id', 'url', 'title', 'secret']; public static function getDeliveries(): array @@ -73,7 +72,7 @@ class Webhook extends Model $array = []; $set = WebhookDeliveryEnum::cases(); foreach ($set as $item) { - $array[$item->name] = $item->value; + $array[$item->name] = $item->value; $array[$item->value] = $item->value; } @@ -96,7 +95,7 @@ class Webhook extends Model $array = []; $set = WebhookResponseEnum::cases(); foreach ($set as $item) { - $array[$item->name] = $item->value; + $array[$item->name] = $item->value; $array[$item->value] = $item->value; } @@ -119,7 +118,7 @@ class Webhook extends Model $array = []; $set = WebhookTriggerEnum::cases(); foreach ($set as $item) { - $array[$item->name] = $item->value; + $array[$item->name] = $item->value; $array[$item->value] = $item->value; } @@ -134,13 +133,13 @@ class Webhook extends Model public static function routeBinder(string $value): self { if (auth()->check()) { - $webhookId = (int)$value; + $webhookId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|Webhook $webhook */ - $webhook = $user->webhooks()->find($webhookId); + $webhook = $user->webhooks()->find($webhookId); if (null !== $webhook) { return $webhook; } diff --git a/app/Models/WebhookAttempt.php b/app/Models/WebhookAttempt.php index bd3f2b7866..6263b48306 100644 --- a/app/Models/WebhookAttempt.php +++ b/app/Models/WebhookAttempt.php @@ -45,13 +45,13 @@ class WebhookAttempt extends Model public static function routeBinder(string $value): self { if (auth()->check()) { - $attemptId = (int)$value; + $attemptId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|WebhookAttempt $attempt */ - $attempt = self::find($attemptId); + $attempt = self::find($attemptId); if (null !== $attempt && $attempt->webhookMessage->webhook->user_id === $user->id) { return $attempt; } @@ -67,8 +67,6 @@ class WebhookAttempt extends Model protected function webhookMessageId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } } diff --git a/app/Models/WebhookDelivery.php b/app/Models/WebhookDelivery.php index 8ac1514a0a..bde7589abb 100644 --- a/app/Models/WebhookDelivery.php +++ b/app/Models/WebhookDelivery.php @@ -1,6 +1,5 @@ (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } } diff --git a/app/Models/WebhookMessage.php b/app/Models/WebhookMessage.php index 0209109c7d..f052219b7d 100644 --- a/app/Models/WebhookMessage.php +++ b/app/Models/WebhookMessage.php @@ -47,13 +47,13 @@ class WebhookMessage extends Model public static function routeBinder(string $value): self { if (auth()->check()) { - $messageId = (int)$value; + $messageId = (int) $value; /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var null|WebhookMessage $message */ - $message = self::find($messageId); + $message = self::find($messageId); if (null !== $message && $message->webhook->user_id === $user->id) { return $message; } @@ -74,13 +74,7 @@ class WebhookMessage extends Model protected function casts(): array { - return [ - 'sent' => 'boolean', - 'errored' => 'boolean', - 'uuid' => 'string', - 'message' => 'json', - 'logs' => 'json', - ]; + return ['sent' => 'boolean', 'errored' => 'boolean', 'uuid' => 'string', 'message' => 'json', 'logs' => 'json']; } /** @@ -88,15 +82,11 @@ class WebhookMessage extends Model */ protected function sent(): Attribute { - return Attribute::make( - get: static fn ($value): bool => (bool)$value, - ); + return Attribute::make(get: static fn($value): bool => (bool) $value); } protected function webhookId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } } diff --git a/app/Models/WebhookResponse.php b/app/Models/WebhookResponse.php index 1cc885f9ef..0d5aed1146 100644 --- a/app/Models/WebhookResponse.php +++ b/app/Models/WebhookResponse.php @@ -1,6 +1,5 @@ (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } } diff --git a/app/Models/WebhookTrigger.php b/app/Models/WebhookTrigger.php index 7608d43d93..2b6a09282a 100644 --- a/app/Models/WebhookTrigger.php +++ b/app/Models/WebhookTrigger.php @@ -1,6 +1,5 @@ (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } } diff --git a/app/Notifications/Admin/UnknownUserLoginAttempt.php b/app/Notifications/Admin/UnknownUserLoginAttempt.php index 86015ac892..d9963a3a2f 100644 --- a/app/Notifications/Admin/UnknownUserLoginAttempt.php +++ b/app/Notifications/Admin/UnknownUserLoginAttempt.php @@ -39,15 +39,16 @@ class UnknownUserLoginAttempt extends Notification { use Queueable; - public function __construct(private string $address) {} + public function __construct( + private string $address + ) {} /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ public function toArray(OwnerNotifiable $notifiable): array { - return [ - ]; + return []; } /** @@ -61,9 +62,14 @@ class UnknownUserLoginAttempt extends Notification $time = now(config('app.timezone'))->isoFormat((string) trans('config.date_time_js')); return new MailMessage() - ->markdown('emails.owner.unknown-user', ['address' => $this->address, 'ip' => $ip, 'host' => $host, 'userAgent' => $userAgent, 'time' => $time]) - ->subject((string) trans('email.unknown_user_subject')) - ; + ->markdown('emails.owner.unknown-user', [ + 'address' => $this->address, + 'ip' => $ip, + 'host' => $host, + 'userAgent' => $userAgent, + 'time' => $time + ]) + ->subject((string) trans('email.unknown_user_subject')); } // /** @@ -89,9 +95,9 @@ class UnknownUserLoginAttempt extends Notification { $ip = Request::ip(); - return PushoverMessage::create((string) trans('email.unknown_user_message', ['address' => $this->address, 'ip' => $ip])) - ->title((string) trans('email.unknown_user_subject')) - ; + return PushoverMessage::create((string) trans('email.unknown_user_message', ['address' => $this->address, 'ip' => $ip]))->title((string) trans( + 'email.unknown_user_subject' + )); } /** @@ -101,9 +107,7 @@ class UnknownUserLoginAttempt extends Notification { $ip = Request::ip(); - return new SlackMessage()->content( - (string) trans('email.unknown_user_body', ['address' => $this->address, 'ip' => $ip]) - ); + return new SlackMessage()->content((string) trans('email.unknown_user_body', ['address' => $this->address, 'ip' => $ip])); } /** diff --git a/app/Notifications/Admin/UserInvitation.php b/app/Notifications/Admin/UserInvitation.php index 0ea2f8023f..ad29a9d75a 100644 --- a/app/Notifications/Admin/UserInvitation.php +++ b/app/Notifications/Admin/UserInvitation.php @@ -43,15 +43,16 @@ class UserInvitation extends Notification { use Queueable; - public function __construct(private InvitedUser $invitee) {} + public function __construct( + private InvitedUser $invitee + ) {} /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ public function toArray(OwnerNotifiable $notifiable): array { - return [ - ]; + return []; } /** @@ -64,11 +65,16 @@ class UserInvitation extends Notification $userAgent = Request::userAgent(); $time = now(config('app.timezone'))->isoFormat((string) trans('config.date_time_js')); - return new MailMessage() - ->markdown('emails.invitation-created', ['email' => $this->invitee->user->email, 'invitee' => $this->invitee->email, 'ip' => $ip, 'host' => $host, 'userAgent' => $userAgent, 'time' => $time]) - ->subject((string) trans('email.invitation_created_subject')) - ; + ->markdown('emails.invitation-created', [ + 'email' => $this->invitee->user->email, + 'invitee' => $this->invitee->email, + 'ip' => $ip, + 'host' => $host, + 'userAgent' => $userAgent, + 'time' => $time + ]) + ->subject((string) trans('email.invitation_created_subject')); } // /** @@ -93,9 +99,10 @@ class UserInvitation extends Notification { Log::debug('Now in toPushover() for UserInvitation'); - return PushoverMessage::create((string) trans('email.invitation_created_body', ['email' => $this->invitee->user->email, 'invitee' => $this->invitee->email])) - ->title((string) trans('email.invitation_created_subject')) - ; + return PushoverMessage::create((string) trans('email.invitation_created_body', [ + 'email' => $this->invitee->user->email, + 'invitee' => $this->invitee->email + ]))->title((string) trans('email.invitation_created_subject')); } /** @@ -103,9 +110,10 @@ class UserInvitation extends Notification */ public function toSlack(OwnerNotifiable $notifiable): SlackMessage { - return new SlackMessage()->content( - (string) trans('email.invitation_created_body', ['email' => $this->invitee->user->email, 'invitee' => $this->invitee->email]) - ); + return new SlackMessage()->content((string) trans('email.invitation_created_body', [ + 'email' => $this->invitee->user->email, + 'invitee' => $this->invitee->email + ])); } /** diff --git a/app/Notifications/Admin/UserRegistration.php b/app/Notifications/Admin/UserRegistration.php index 9847201d61..17e6875812 100644 --- a/app/Notifications/Admin/UserRegistration.php +++ b/app/Notifications/Admin/UserRegistration.php @@ -43,15 +43,16 @@ class UserRegistration extends Notification { use Queueable; - public function __construct(private User $user) {} + public function __construct( + private User $user + ) {} /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ public function toArray(OwnerNotifiable $notifiable): array { - return [ - ]; + return []; } /** @@ -65,9 +66,15 @@ class UserRegistration extends Notification $time = now(config('app.timezone'))->isoFormat((string) trans('config.date_time_js')); return new MailMessage() - ->markdown('emails.registered-admin', ['email' => $this->user->email, 'id' => $this->user->id, 'ip' => $ip, 'host' => $host, 'userAgent' => $userAgent, 'time' => $time]) - ->subject((string) trans('email.registered_subject_admin')) - ; + ->markdown('emails.registered-admin', [ + 'email' => $this->user->email, + 'id' => $this->user->id, + 'ip' => $ip, + 'host' => $host, + 'userAgent' => $userAgent, + 'time' => $time + ]) + ->subject((string) trans('email.registered_subject_admin')); } // /** @@ -92,9 +99,10 @@ class UserRegistration extends Notification { Log::debug('Now in toPushover() for UserRegistration'); - return PushoverMessage::create((string) trans('email.admin_new_user_registered', ['email' => $this->user->email, 'invitee' => $this->user->email])) - ->title((string) trans('email.registered_subject_admin')) - ; + return PushoverMessage::create((string) trans('email.admin_new_user_registered', [ + 'email' => $this->user->email, + 'invitee' => $this->user->email + ]))->title((string) trans('email.registered_subject_admin')); } /** @@ -102,7 +110,7 @@ class UserRegistration extends Notification */ public function toSlack(OwnerNotifiable $notifiable): SlackMessage { - return new SlackMessage()->content((string) trans('email.admin_new_user_registered', ['email' => $this->user->email, 'id' => $this->user->id])); + return new SlackMessage()->content((string) trans('email.admin_new_user_registered', ['email' => $this->user->email, 'id' => $this->user->id])); } /** diff --git a/app/Notifications/Admin/VersionCheckResult.php b/app/Notifications/Admin/VersionCheckResult.php index 39f449f9bd..76ed284d2e 100644 --- a/app/Notifications/Admin/VersionCheckResult.php +++ b/app/Notifications/Admin/VersionCheckResult.php @@ -40,15 +40,16 @@ class VersionCheckResult extends Notification { use Queueable; - public function __construct(private string $message) {} + public function __construct( + private string $message + ) {} /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ public function toArray(OwnerNotifiable $notifiable): array { - return [ - ]; + return []; } /** @@ -58,8 +59,7 @@ class VersionCheckResult extends Notification { return new MailMessage() ->markdown('emails.new-version', ['message' => $this->message]) - ->subject((string) trans('email.new_version_email_subject')) - ; + ->subject((string) trans('email.new_version_email_subject')); } // /** @@ -84,9 +84,7 @@ class VersionCheckResult extends Notification { Log::debug('Now in toPushover() for VersionCheckResult'); - return PushoverMessage::create($this->message) - ->title((string) trans('email.new_version_email_subject')) - ; + return PushoverMessage::create($this->message)->title((string) trans('email.new_version_email_subject')); } /** @@ -94,11 +92,11 @@ class VersionCheckResult extends Notification */ public function toSlack(OwnerNotifiable $notifiable): SlackMessage { - return new SlackMessage()->content($this->message) + return new SlackMessage() + ->content($this->message) ->attachment(static function ($attachment): void { $attachment->title('Firefly III @ GitHub', 'https://github.com/firefly-iii/firefly-iii/releases'); - }) - ; + }); } /** diff --git a/app/Notifications/Notifiables/OwnerNotifiable.php b/app/Notifications/Notifiables/OwnerNotifiable.php index 9216c19015..a32cf10cff 100644 --- a/app/Notifications/Notifiables/OwnerNotifiable.php +++ b/app/Notifications/Notifiables/OwnerNotifiable.php @@ -24,11 +24,11 @@ declare(strict_types=1); namespace FireflyIII\Notifications\Notifiables; +use FireflyIII\Support\Facades\FireflyConfig; use Illuminate\Notifications\Notification; use Illuminate\Support\Facades\Log; use Illuminate\Support\Str; use NotificationChannels\Pushover\PushoverReceiver; -use FireflyIII\Support\Facades\FireflyConfig; class OwnerNotifiable { @@ -42,7 +42,7 @@ class OwnerNotifiable */ public function routeNotificationFor($driver, $notification = null) { - $method = 'routeNotificationFor'.Str::studly($driver); + $method = 'routeNotificationFor' . Str::studly($driver); if (method_exists($this, $method)) { Log::debug(sprintf('Redirect for settings to "%s".', $method)); @@ -51,8 +51,8 @@ class OwnerNotifiable Log::debug(sprintf('No method "%s" found, return generic settings.', $method)); return match ($driver) { - 'mail' => (string) config('firefly.site_owner'), - default => null, + 'mail' => (string) config('firefly.site_owner'), + default => null }; } @@ -62,9 +62,7 @@ class OwnerNotifiable $pushoverAppToken = (string) FireflyConfig::getEncrypted('pushover_app_token', '')->data; $pushoverUserToken = (string) FireflyConfig::getEncrypted('pushover_user_token', '')->data; - return PushoverReceiver::withUserKey($pushoverUserToken) - ->withApplicationToken($pushoverAppToken) - ; + return PushoverReceiver::withUserKey($pushoverUserToken)->withApplicationToken($pushoverAppToken); } public function routeNotificationForSlack(): string diff --git a/app/Notifications/ReturnsAvailableChannels.php b/app/Notifications/ReturnsAvailableChannels.php index 2ca7f0e0b6..f2f5876f82 100644 --- a/app/Notifications/ReturnsAvailableChannels.php +++ b/app/Notifications/ReturnsAvailableChannels.php @@ -24,18 +24,18 @@ declare(strict_types=1); namespace FireflyIII\Notifications; +use FireflyIII\Support\Facades\FireflyConfig; use FireflyIII\Support\Facades\Preferences; use FireflyIII\Support\Notifications\UrlValidator; use FireflyIII\User; use Illuminate\Support\Facades\Log; use NotificationChannels\Pushover\PushoverChannel; -use FireflyIII\Support\Facades\FireflyConfig; // use Wijourdil\NtfyNotificationChannel\Channels\NtfyChannel; class ReturnsAvailableChannels { - public static function returnChannels(string $type, ?User $user = null): array + public static function returnChannels(string $type, null|User $user = null): array { $channels = ['mail']; @@ -46,13 +46,11 @@ class ReturnsAvailableChannels return self::returnUserChannels($user); } - return $channels; } private static function returnOwnerChannels(): array { - $channels = ['mail']; if (true === config('notifications.channels.slack.enabled', false)) { $slackUrl = FireflyConfig::getEncrypted('slack_webhook_url', '')->data; diff --git a/app/Notifications/ReturnsSettings.php b/app/Notifications/ReturnsSettings.php index 1d3d763fb3..b7d6f69c08 100644 --- a/app/Notifications/ReturnsSettings.php +++ b/app/Notifications/ReturnsSettings.php @@ -32,7 +32,7 @@ use Illuminate\Support\Facades\Log; class ReturnsSettings { - public static function getSettings(string $channel, string $type, ?User $user): array + public static function getSettings(string $channel, string $type, null|User $user): array { if ('ntfy' === $channel) { return self::getNtfySettings($type, $user); @@ -41,31 +41,24 @@ class ReturnsSettings throw new FireflyException(sprintf('Cannot handle channel "%s"', $channel)); } - private static function getNtfySettings(string $type, ?User $user): array + private static function getNtfySettings(string $type, null|User $user): array { Log::debug(sprintf('Getting Ntfy settings for %s and user #%d', $type, $user?->id)); - $settings = [ - 'ntfy_server' => 'https://ntfy.sh', - 'ntfy_topic' => '', - 'ntfy_auth' => false, - 'ntfy_user' => '', - 'ntfy_pass' => '', - - ]; + $settings = ['ntfy_server' => 'https://ntfy.sh', 'ntfy_topic' => '', 'ntfy_auth' => false, 'ntfy_user' => '', 'ntfy_pass' => '']; if ('user' === $type && $user instanceof User) { $settings['ntfy_server'] = Preferences::getEncryptedForUser($user, 'ntfy_server', 'https://ntfy.sh')->data; - $settings['ntfy_topic'] = Preferences::getEncryptedForUser($user, 'ntfy_topic', '')->data; - $settings['ntfy_auth'] = '1' === Preferences::getForUser($user, 'ntfy_auth', false)->data; - $settings['ntfy_user'] = Preferences::getEncryptedForUser($user, 'ntfy_user', '')->data; - $settings['ntfy_pass'] = Preferences::getEncryptedForUser($user, 'ntfy_pass', '')->data; + $settings['ntfy_topic'] = Preferences::getEncryptedForUser($user, 'ntfy_topic', '')->data; + $settings['ntfy_auth'] = '1' === Preferences::getForUser($user, 'ntfy_auth', false)->data; + $settings['ntfy_user'] = Preferences::getEncryptedForUser($user, 'ntfy_user', '')->data; + $settings['ntfy_pass'] = Preferences::getEncryptedForUser($user, 'ntfy_pass', '')->data; Log::debug(sprintf('Auth is %s, user = "%s"', var_export($settings['ntfy_auth'], true), $settings['ntfy_user'])); } if ('owner' === $type) { $settings['ntfy_server'] = FireflyConfig::getEncrypted('ntfy_server', 'https://ntfy.sh')->data; - $settings['ntfy_topic'] = FireflyConfig::getEncrypted('ntfy_topic', '')->data; - $settings['ntfy_auth'] = FireflyConfig::get('ntfy_auth', false)->data; - $settings['ntfy_user'] = FireflyConfig::getEncrypted('ntfy_user', '')->data; - $settings['ntfy_pass'] = FireflyConfig::getEncrypted('ntfy_pass', '')->data; + $settings['ntfy_topic'] = FireflyConfig::getEncrypted('ntfy_topic', '')->data; + $settings['ntfy_auth'] = FireflyConfig::get('ntfy_auth', false)->data; + $settings['ntfy_user'] = FireflyConfig::getEncrypted('ntfy_user', '')->data; + $settings['ntfy_pass'] = FireflyConfig::getEncrypted('ntfy_pass', '')->data; Log::debug(sprintf('Auth is %s, user = "%s"', var_export($settings['ntfy_auth'], true), $settings['ntfy_user'])); } diff --git a/app/Notifications/Security/DisabledMFANotification.php b/app/Notifications/Security/DisabledMFANotification.php index 2d7fb02922..60835c5a51 100644 --- a/app/Notifications/Security/DisabledMFANotification.php +++ b/app/Notifications/Security/DisabledMFANotification.php @@ -38,15 +38,16 @@ class DisabledMFANotification extends Notification { use Queueable; - public function __construct(private User $user) {} + public function __construct( + private User $user + ) {} /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ public function toArray(User $notifiable): array { - return [ - ]; + return []; } /** @@ -60,7 +61,15 @@ class DisabledMFANotification extends Notification $userAgent = Request::userAgent(); $time = now(config('app.timezone'))->isoFormat((string) trans('config.date_time_js')); - return new MailMessage()->markdown('emails.security.disabled-mfa', ['user' => $this->user, 'ip' => $ip, 'host' => $host, 'userAgent' => $userAgent, 'time' => $time])->subject($subject); + return new MailMessage() + ->markdown('emails.security.disabled-mfa', [ + 'user' => $this->user, + 'ip' => $ip, + 'host' => $host, + 'userAgent' => $userAgent, + 'time' => $time + ]) + ->subject($subject); } // public function toNtfy(User $notifiable): Message @@ -79,9 +88,9 @@ class DisabledMFANotification extends Notification */ public function toPushover(User $notifiable): PushoverMessage { - return PushoverMessage::create((string) trans('email.disabled_mfa_slack', ['email' => $this->user->email])) - ->title((string) trans('email.disabled_mfa_subject')) - ; + return PushoverMessage::create((string) trans('email.disabled_mfa_slack', ['email' => $this->user->email]))->title((string) trans( + 'email.disabled_mfa_subject' + )); } /** diff --git a/app/Notifications/Security/EnabledMFANotification.php b/app/Notifications/Security/EnabledMFANotification.php index d661aec9bb..280d8b2ace 100644 --- a/app/Notifications/Security/EnabledMFANotification.php +++ b/app/Notifications/Security/EnabledMFANotification.php @@ -38,15 +38,16 @@ class EnabledMFANotification extends Notification { use Queueable; - public function __construct(private User $user) {} + public function __construct( + private User $user + ) {} /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ public function toArray(User $notifiable): array { - return [ - ]; + return []; } /** @@ -60,7 +61,15 @@ class EnabledMFANotification extends Notification $userAgent = Request::userAgent(); $time = now(config('app.timezone'))->isoFormat((string) trans('config.date_time_js')); - return new MailMessage()->markdown('emails.security.enabled-mfa', ['user' => $this->user, 'ip' => $ip, 'host' => $host, 'userAgent' => $userAgent, 'time' => $time])->subject($subject); + return new MailMessage() + ->markdown('emails.security.enabled-mfa', [ + 'user' => $this->user, + 'ip' => $ip, + 'host' => $host, + 'userAgent' => $userAgent, + 'time' => $time + ]) + ->subject($subject); } // public function toNtfy(User $notifiable): Message @@ -79,9 +88,9 @@ class EnabledMFANotification extends Notification */ public function toPushover(User $notifiable): PushoverMessage { - return PushoverMessage::create((string) trans('email.enabled_mfa_slack', ['email' => $this->user->email])) - ->title((string) trans('email.enabled_mfa_subject')) - ; + return PushoverMessage::create((string) trans('email.enabled_mfa_slack', ['email' => $this->user->email]))->title((string) trans( + 'email.enabled_mfa_subject' + )); } /** diff --git a/app/Notifications/Security/MFABackupFewLeftNotification.php b/app/Notifications/Security/MFABackupFewLeftNotification.php index 8f691e3dd0..f432ccdd7e 100644 --- a/app/Notifications/Security/MFABackupFewLeftNotification.php +++ b/app/Notifications/Security/MFABackupFewLeftNotification.php @@ -38,15 +38,17 @@ class MFABackupFewLeftNotification extends Notification { use Queueable; - public function __construct(private User $user, private int $count) {} + public function __construct( + private User $user, + private int $count + ) {} /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ public function toArray(User $notifiable): array { - return [ - ]; + return []; } /** @@ -54,13 +56,22 @@ class MFABackupFewLeftNotification extends Notification */ public function toMail(User $notifiable): MailMessage { - $subject = (string) trans('email.mfa_few_backups_left_subject', ['count' => $this->count]); + $subject = (string) trans('email.mfa_few_backups_left_subject', ['count' => $this->count]); $ip = Request::ip(); $host = Steam::getHostName($ip); $userAgent = Request::userAgent(); $time = now(config('app.timezone'))->isoFormat((string) trans('config.date_time_js')); - return new MailMessage()->markdown('emails.security.few-backup-codes', ['user' => $this->user, 'count' => $this->count, 'ip' => $ip, 'host' => $host, 'userAgent' => $userAgent, 'time' => $time])->subject($subject); + return new MailMessage() + ->markdown('emails.security.few-backup-codes', [ + 'user' => $this->user, + 'count' => $this->count, + 'ip' => $ip, + 'host' => $host, + 'userAgent' => $userAgent, + 'time' => $time + ]) + ->subject($subject); } // public function toNtfy(User $notifiable): Message @@ -79,9 +90,10 @@ class MFABackupFewLeftNotification extends Notification */ public function toPushover(User $notifiable): PushoverMessage { - return PushoverMessage::create((string) trans('email.mfa_few_backups_left_slack', ['email' => $this->user->email, 'count' => $this->count])) - ->title((string) trans('email.mfa_few_backups_left_subject')) - ; + return PushoverMessage::create((string) trans('email.mfa_few_backups_left_slack', [ + 'email' => $this->user->email, + 'count' => $this->count + ]))->title((string) trans('email.mfa_few_backups_left_subject')); } /** diff --git a/app/Notifications/Security/MFABackupNoLeftNotification.php b/app/Notifications/Security/MFABackupNoLeftNotification.php index 0c1fe520a6..1015fd5a15 100644 --- a/app/Notifications/Security/MFABackupNoLeftNotification.php +++ b/app/Notifications/Security/MFABackupNoLeftNotification.php @@ -38,15 +38,16 @@ class MFABackupNoLeftNotification extends Notification { use Queueable; - public function __construct(private User $user) {} + public function __construct( + private User $user + ) {} /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ public function toArray(User $notifiable): array { - return [ - ]; + return []; } /** @@ -60,7 +61,15 @@ class MFABackupNoLeftNotification extends Notification $userAgent = Request::userAgent(); $time = now(config('app.timezone'))->isoFormat((string) trans('config.date_time_js')); - return new MailMessage()->markdown('emails.security.no-backup-codes', ['user' => $this->user, 'ip' => $ip, 'host' => $host, 'userAgent' => $userAgent, 'time' => $time])->subject($subject); + return new MailMessage() + ->markdown('emails.security.no-backup-codes', [ + 'user' => $this->user, + 'ip' => $ip, + 'host' => $host, + 'userAgent' => $userAgent, + 'time' => $time + ]) + ->subject($subject); } // public function toNtfy(User $notifiable): Message @@ -79,9 +88,9 @@ class MFABackupNoLeftNotification extends Notification */ public function toPushover(User $notifiable): PushoverMessage { - return PushoverMessage::create((string) trans('email.mfa_few_backups_left_slack', ['email' => $this->user->email])) - ->title((string) trans('email.mfa_no_backups_left_slack')) - ; + return PushoverMessage::create((string) trans('email.mfa_few_backups_left_slack', ['email' => $this->user->email]))->title((string) trans( + 'email.mfa_no_backups_left_slack' + )); } /** diff --git a/app/Notifications/Security/MFAManyFailedAttemptsNotification.php b/app/Notifications/Security/MFAManyFailedAttemptsNotification.php index a235fcbd28..aa669ea758 100644 --- a/app/Notifications/Security/MFAManyFailedAttemptsNotification.php +++ b/app/Notifications/Security/MFAManyFailedAttemptsNotification.php @@ -38,12 +38,14 @@ class MFAManyFailedAttemptsNotification extends Notification { use Queueable; - public function __construct(private User $user, private int $count) {} + public function __construct( + private User $user, + private int $count + ) {} public function toArray(User $notifiable): array { - return [ - ]; + return []; } /** @@ -51,13 +53,22 @@ class MFAManyFailedAttemptsNotification extends Notification */ public function toMail(User $notifiable): MailMessage { - $subject = (string) trans('email.mfa_many_failed_subject', ['count' => $this->count]); + $subject = (string) trans('email.mfa_many_failed_subject', ['count' => $this->count]); $ip = Request::ip(); $host = Steam::getHostName($ip); $userAgent = Request::userAgent(); $time = now(config('app.timezone'))->isoFormat((string) trans('config.date_time_js')); - return new MailMessage()->markdown('emails.security.many-failed-attempts', ['user' => $this->user, 'count' => $this->count, 'ip' => $ip, 'host' => $host, 'userAgent' => $userAgent, 'time' => $time])->subject($subject); + return new MailMessage() + ->markdown('emails.security.many-failed-attempts', [ + 'user' => $this->user, + 'count' => $this->count, + 'ip' => $ip, + 'host' => $host, + 'userAgent' => $userAgent, + 'time' => $time + ]) + ->subject($subject); } // public function toNtfy(User $notifiable): Message @@ -76,9 +87,10 @@ class MFAManyFailedAttemptsNotification extends Notification */ public function toPushover(User $notifiable): PushoverMessage { - return PushoverMessage::create((string) trans('email.mfa_many_failed_slack', ['email' => $this->user->email, 'count' => $this->count])) - ->title((string) trans('email.mfa_many_failed_subject')) - ; + return PushoverMessage::create((string) trans('email.mfa_many_failed_slack', [ + 'email' => $this->user->email, + 'count' => $this->count + ]))->title((string) trans('email.mfa_many_failed_subject')); } /** diff --git a/app/Notifications/Security/MFAUsedBackupCodeNotification.php b/app/Notifications/Security/MFAUsedBackupCodeNotification.php index 3c0d61739f..aadaa3c122 100644 --- a/app/Notifications/Security/MFAUsedBackupCodeNotification.php +++ b/app/Notifications/Security/MFAUsedBackupCodeNotification.php @@ -38,15 +38,16 @@ class MFAUsedBackupCodeNotification extends Notification { use Queueable; - public function __construct(private User $user) {} + public function __construct( + private User $user + ) {} /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ public function toArray(User $notifiable): array { - return [ - ]; + return []; } /** @@ -60,7 +61,15 @@ class MFAUsedBackupCodeNotification extends Notification $userAgent = Request::userAgent(); $time = now(config('app.timezone'))->isoFormat((string) trans('config.date_time_js')); - return new MailMessage()->markdown('emails.security.used-backup-code', ['user' => $this->user, 'ip' => $ip, 'host' => $host, 'userAgent' => $userAgent, 'time' => $time])->subject($subject); + return new MailMessage() + ->markdown('emails.security.used-backup-code', [ + 'user' => $this->user, + 'ip' => $ip, + 'host' => $host, + 'userAgent' => $userAgent, + 'time' => $time + ]) + ->subject($subject); } // public function toNtfy(User $notifiable): Message @@ -79,9 +88,9 @@ class MFAUsedBackupCodeNotification extends Notification */ public function toPushover(User $notifiable): PushoverMessage { - return PushoverMessage::create((string) trans('email.used_backup_code_slack', ['email' => $this->user->email])) - ->title((string) trans('email.used_backup_code_subject')) - ; + return PushoverMessage::create((string) trans('email.used_backup_code_slack', ['email' => $this->user->email]))->title((string) trans( + 'email.used_backup_code_subject' + )); } /** diff --git a/app/Notifications/Security/NewBackupCodesNotification.php b/app/Notifications/Security/NewBackupCodesNotification.php index a07d4282d3..717f4ff22e 100644 --- a/app/Notifications/Security/NewBackupCodesNotification.php +++ b/app/Notifications/Security/NewBackupCodesNotification.php @@ -38,15 +38,16 @@ class NewBackupCodesNotification extends Notification { use Queueable; - public function __construct(private User $user) {} + public function __construct( + private User $user + ) {} /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ public function toArray(User $notifiable): array { - return [ - ]; + return []; } /** @@ -60,7 +61,15 @@ class NewBackupCodesNotification extends Notification $userAgent = Request::userAgent(); $time = now(config('app.timezone'))->isoFormat((string) trans('config.date_time_js')); - return new MailMessage()->markdown('emails.security.new-backup-codes', ['user' => $this->user, 'ip' => $ip, 'host' => $host, 'userAgent' => $userAgent, 'time' => $time])->subject($subject); + return new MailMessage() + ->markdown('emails.security.new-backup-codes', [ + 'user' => $this->user, + 'ip' => $ip, + 'host' => $host, + 'userAgent' => $userAgent, + 'time' => $time + ]) + ->subject($subject); } // public function toNtfy(User $notifiable): Message @@ -79,9 +88,9 @@ class NewBackupCodesNotification extends Notification */ public function toPushover(User $notifiable): PushoverMessage { - return PushoverMessage::create((string) trans('email.new_backup_codes_slack', ['email' => $this->user->email])) - ->title((string) trans('email.new_backup_codes_subject')) - ; + return PushoverMessage::create((string) trans('email.new_backup_codes_slack', ['email' => $this->user->email]))->title((string) trans( + 'email.new_backup_codes_subject' + )); } /** diff --git a/app/Notifications/Security/UserFailedLoginAttempt.php b/app/Notifications/Security/UserFailedLoginAttempt.php index 8f9362d76f..69f626db1b 100644 --- a/app/Notifications/Security/UserFailedLoginAttempt.php +++ b/app/Notifications/Security/UserFailedLoginAttempt.php @@ -39,12 +39,13 @@ class UserFailedLoginAttempt extends Notification { use Queueable; - public function __construct(private User $user) {} + public function __construct( + private User $user + ) {} public function toArray(User $notifiable): array { - return [ - ]; + return []; } /** @@ -58,7 +59,15 @@ class UserFailedLoginAttempt extends Notification $userAgent = Request::userAgent(); $time = now(config('app.timezone'))->isoFormat((string) trans('config.date_time_js')); - return new MailMessage()->markdown('emails.security.failed-login', ['user' => $this->user, 'ip' => $ip, 'host' => $host, 'userAgent' => $userAgent, 'time' => $time])->subject($subject); + return new MailMessage() + ->markdown('emails.security.failed-login', [ + 'user' => $this->user, + 'ip' => $ip, + 'host' => $host, + 'userAgent' => $userAgent, + 'time' => $time + ]) + ->subject($subject); } // public function toNtfy(User $notifiable): Message @@ -80,9 +89,9 @@ class UserFailedLoginAttempt extends Notification { $ip = Request::ip(); - return PushoverMessage::create((string) trans('email.failed_login_message', ['ip' => $ip, 'email' => $this->user->email])) - ->title((string) trans('email.failed_login_subject')) - ; + return PushoverMessage::create((string) trans('email.failed_login_message', ['ip' => $ip, 'email' => $this->user->email]))->title((string) trans( + 'email.failed_login_subject' + )); } /** @@ -91,7 +100,7 @@ class UserFailedLoginAttempt extends Notification public function toSlack(User $notifiable): SlackMessage { $ip = Request::ip(); - $message = (string) trans('email.failed_login_message', ['ip' => $ip, 'email' => $this->user->email]); + $message = (string) trans('email.failed_login_message', ['ip' => $ip, 'email' => $this->user->email]); return new SlackMessage()->content($message); } diff --git a/app/Notifications/Test/OwnerTestNotificationEmail.php b/app/Notifications/Test/OwnerTestNotificationEmail.php index 498e7e3baa..859850261b 100644 --- a/app/Notifications/Test/OwnerTestNotificationEmail.php +++ b/app/Notifications/Test/OwnerTestNotificationEmail.php @@ -42,8 +42,7 @@ class OwnerTestNotificationEmail extends Notification */ public function toArray(OwnerNotifiable $notifiable): array { - return [ - ]; + return []; } /** @@ -55,8 +54,7 @@ class OwnerTestNotificationEmail extends Notification return new MailMessage() ->markdown('emails.admin-test', ['email' => $address]) - ->subject((string) trans('email.admin_test_subject')) - ; + ->subject((string) trans('email.admin_test_subject')); } /** diff --git a/app/Notifications/Test/OwnerTestNotificationNtfy.php b/app/Notifications/Test/OwnerTestNotificationNtfy.php index 6edae32817..2ee9eed09c 100644 --- a/app/Notifications/Test/OwnerTestNotificationNtfy.php +++ b/app/Notifications/Test/OwnerTestNotificationNtfy.php @@ -42,8 +42,7 @@ class OwnerTestNotificationNtfy extends Notification */ public function toArray(OwnerNotifiable $notifiable): array { - return [ - ]; + return []; } // public function toNtfy(OwnerNotifiable $notifiable): Message @@ -57,7 +56,6 @@ class OwnerTestNotificationNtfy extends Notification // // return $message; // } - // public function via(OwnerNotifiable $notifiable): array // { // return [NtfyChannel::class]; diff --git a/app/Notifications/Test/OwnerTestNotificationPushover.php b/app/Notifications/Test/OwnerTestNotificationPushover.php index 0e2c444f01..6d9ce70dd2 100644 --- a/app/Notifications/Test/OwnerTestNotificationPushover.php +++ b/app/Notifications/Test/OwnerTestNotificationPushover.php @@ -45,8 +45,7 @@ class OwnerTestNotificationPushover extends Notification */ public function toArray(OwnerNotifiable $notifiable): array { - return [ - ]; + return []; } /** @@ -56,9 +55,9 @@ class OwnerTestNotificationPushover extends Notification { Log::debug('Now in toPushover()'); - return PushoverMessage::create((string) trans('email.admin_test_message', ['channel' => 'Pushover'])) - ->title((string) trans('email.admin_test_subject')) - ; + return PushoverMessage::create((string) trans('email.admin_test_message', ['channel' => 'Pushover']))->title((string) trans( + 'email.admin_test_subject' + )); } /** diff --git a/app/Notifications/Test/OwnerTestNotificationSlack.php b/app/Notifications/Test/OwnerTestNotificationSlack.php index 7a0a6e40de..ba91f7c506 100644 --- a/app/Notifications/Test/OwnerTestNotificationSlack.php +++ b/app/Notifications/Test/OwnerTestNotificationSlack.php @@ -43,8 +43,7 @@ class OwnerTestNotificationSlack extends Notification */ public function toArray(OwnerNotifiable $notifiable): array { - return [ - ]; + return []; } /** @@ -53,6 +52,7 @@ class OwnerTestNotificationSlack extends Notification public function toSlack(OwnerNotifiable $notifiable): SlackMessage { return new SlackMessage()->content((string) trans('email.admin_test_subject')); + // return new SlackMessage()->text((string) trans('email.admin_test_subject'))->to($url); } diff --git a/app/Notifications/Test/UserTestNotificationEmail.php b/app/Notifications/Test/UserTestNotificationEmail.php index 2fbc0dd293..dc8eeaeb9c 100644 --- a/app/Notifications/Test/UserTestNotificationEmail.php +++ b/app/Notifications/Test/UserTestNotificationEmail.php @@ -42,8 +42,7 @@ class UserTestNotificationEmail extends Notification */ public function toArray(User $notifiable): array { - return [ - ]; + return []; } public function toMail(User $notifiable): MailMessage @@ -52,8 +51,7 @@ class UserTestNotificationEmail extends Notification return new MailMessage() ->markdown('emails.admin-test', ['email' => $address]) - ->subject((string) trans('email.admin_test_subject')) - ; + ->subject((string) trans('email.admin_test_subject')); } /** diff --git a/app/Notifications/Test/UserTestNotificationNtfy.php b/app/Notifications/Test/UserTestNotificationNtfy.php index 7517e962c7..09bc14c0bd 100644 --- a/app/Notifications/Test/UserTestNotificationNtfy.php +++ b/app/Notifications/Test/UserTestNotificationNtfy.php @@ -42,8 +42,7 @@ class UserTestNotificationNtfy extends Notification */ public function toArray(User $notifiable): array { - return [ - ]; + return []; } // public function toNtfy(User $user): Message @@ -57,7 +56,6 @@ class UserTestNotificationNtfy extends Notification // // return $message; // } - // public function via(User $user): array // { // return [NtfyChannel::class]; diff --git a/app/Notifications/Test/UserTestNotificationPushover.php b/app/Notifications/Test/UserTestNotificationPushover.php index e963b4bca9..5268180811 100644 --- a/app/Notifications/Test/UserTestNotificationPushover.php +++ b/app/Notifications/Test/UserTestNotificationPushover.php @@ -45,8 +45,7 @@ class UserTestNotificationPushover extends Notification */ public function toArray(User $notifiable): array { - return [ - ]; + return []; } /** @@ -56,9 +55,9 @@ class UserTestNotificationPushover extends Notification { Log::debug('Now in (user) toPushover()'); - return PushoverMessage::create((string) trans('email.admin_test_message', ['channel' => 'Pushover'])) - ->title((string) trans('email.admin_test_subject')) - ; + return PushoverMessage::create((string) trans('email.admin_test_message', ['channel' => 'Pushover']))->title((string) trans( + 'email.admin_test_subject' + )); } /** diff --git a/app/Notifications/Test/UserTestNotificationSlack.php b/app/Notifications/Test/UserTestNotificationSlack.php index 59cedc0b4c..689870012f 100644 --- a/app/Notifications/Test/UserTestNotificationSlack.php +++ b/app/Notifications/Test/UserTestNotificationSlack.php @@ -43,8 +43,7 @@ class UserTestNotificationSlack extends Notification */ public function toArray(User $user): array { - return [ - ]; + return []; } /** @@ -53,6 +52,7 @@ class UserTestNotificationSlack extends Notification public function toSlack(User $user): SlackMessage { return new SlackMessage()->content((string) trans('email.admin_test_subject')); + // return new SlackMessage()->text((string) trans('email.admin_test_subject'))->to($url); } diff --git a/app/Notifications/User/BillReminder.php b/app/Notifications/User/BillReminder.php index 6765545d92..35154270f6 100644 --- a/app/Notifications/User/BillReminder.php +++ b/app/Notifications/User/BillReminder.php @@ -40,15 +40,18 @@ class BillReminder extends Notification { use Queueable; - public function __construct(private Bill $bill, private string $field, private int $diff) {} + public function __construct( + private Bill $bill, + private string $field, + private int $diff + ) {} /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ public function toArray(User $notifiable): array { - return [ - ]; + return []; } /** @@ -57,9 +60,8 @@ class BillReminder extends Notification public function toMail(User $notifiable): MailMessage { return new MailMessage() - ->markdown('emails.bill-warning', ['field' => $this->field, 'diff' => $this->diff, 'bill' => $this->bill]) - ->subject($this->getSubject()) - ; + ->markdown('emails.bill-warning', ['field' => $this->field, 'diff' => $this->diff, 'bill' => $this->bill]) + ->subject($this->getSubject()); } private function getSubject(): string @@ -87,9 +89,7 @@ class BillReminder extends Notification */ public function toPushover(User $notifiable): PushoverMessage { - return PushoverMessage::create((string) trans('email.bill_warning_please_action')) - ->title($this->getSubject()) - ; + return PushoverMessage::create((string) trans('email.bill_warning_please_action'))->title($this->getSubject()); } /** @@ -105,8 +105,7 @@ class BillReminder extends Notification ->attachment(static function ($attachment) use ($bill, $url): void { $attachment->title((string) trans('firefly.visit_bill', ['name' => $bill->name]), $url); }) - ->content($this->getSubject()) - ; + ->content($this->getSubject()); } /** diff --git a/app/Notifications/User/NewAccessToken.php b/app/Notifications/User/NewAccessToken.php index 4c360da056..b0d5f2a373 100644 --- a/app/Notifications/User/NewAccessToken.php +++ b/app/Notifications/User/NewAccessToken.php @@ -44,8 +44,7 @@ class NewAccessToken extends Notification public function toArray(User $notifiable): array { - return [ - ]; + return []; } /** @@ -59,9 +58,8 @@ class NewAccessToken extends Notification $time = now(config('app.timezone'))->isoFormat((string) trans('config.date_time_js')); return new MailMessage() - ->markdown('emails.token-created', ['ip' => $ip, 'host' => $host, 'userAgent' => $userAgent, 'time' => $time]) - ->subject((string) trans('email.access_token_created_subject')) - ; + ->markdown('emails.token-created', ['ip' => $ip, 'host' => $host, 'userAgent' => $userAgent, 'time' => $time]) + ->subject((string) trans('email.access_token_created_subject')); } // public function toNtfy(User $notifiable): Message @@ -80,9 +78,7 @@ class NewAccessToken extends Notification */ public function toPushover(User $notifiable): PushoverMessage { - return PushoverMessage::create((string) trans('email.access_token_created_body')) - ->title((string) trans('email.access_token_created_subject')) - ; + return PushoverMessage::create((string) trans('email.access_token_created_body'))->title((string) trans('email.access_token_created_subject')); } /** diff --git a/app/Notifications/User/RuleActionFailed.php b/app/Notifications/User/RuleActionFailed.php index 4a2cd4fd75..186b207c7d 100644 --- a/app/Notifications/User/RuleActionFailed.php +++ b/app/Notifications/User/RuleActionFailed.php @@ -47,11 +47,11 @@ class RuleActionFailed extends Notification public function __construct(array $params) { [$mainMessage, $groupTitle, $groupLink, $ruleTitle, $ruleLink] = $params; - $this->message = $mainMessage; - $this->groupTitle = $groupTitle; - $this->groupLink = $groupLink; - $this->ruleTitle = $ruleTitle; - $this->ruleLink = $ruleLink; + $this->message = $mainMessage; + $this->groupTitle = $groupTitle; + $this->groupLink = $groupLink; + $this->ruleTitle = $ruleTitle; + $this->ruleLink = $ruleLink; } /** @@ -59,8 +59,7 @@ class RuleActionFailed extends Notification */ public function toArray(User $notifiable): array { - return [ - ]; + return []; } // public function toNtfy(User $notifiable): Message @@ -91,11 +90,14 @@ class RuleActionFailed extends Notification $ruleTitle = $this->ruleTitle; $ruleLink = $this->ruleLink; - return new SlackMessage()->content($this->message)->attachment(static function ($attachment) use ($groupTitle, $groupLink): void { - $attachment->title((string) trans('rules.inspect_transaction', ['title' => $groupTitle]), $groupLink); - })->attachment(static function ($attachment) use ($ruleTitle, $ruleLink): void { - $attachment->title((string) trans('rules.inspect_rule', ['title' => $ruleTitle]), $ruleLink); - }); + return new SlackMessage() + ->content($this->message) + ->attachment(static function ($attachment) use ($groupTitle, $groupLink): void { + $attachment->title((string) trans('rules.inspect_transaction', ['title' => $groupTitle]), $groupLink); + }) + ->attachment(static function ($attachment) use ($ruleTitle, $ruleLink): void { + $attachment->title((string) trans('rules.inspect_rule', ['title' => $ruleTitle]), $ruleLink); + }); } /** diff --git a/app/Notifications/User/SubscriptionsOverdueReminder.php b/app/Notifications/User/SubscriptionsOverdueReminder.php index 7f46a333ae..f73af0b480 100644 --- a/app/Notifications/User/SubscriptionsOverdueReminder.php +++ b/app/Notifications/User/SubscriptionsOverdueReminder.php @@ -1,6 +1,5 @@ overdue as $item) { - $current = [ - 'bill' => $item['bill'], - ]; - $current['pay_dates'] = array_map( - static fn (string $date): string => new Carbon($date)->isoFormat((string)trans('config.month_and_day_moment_js')), - $item['dates']['pay_dates'] - ); - $info[] = $current; + $current = ['bill' => $item['bill']]; + $current['pay_dates'] = array_map(static fn(string $date): string => new Carbon($date)->isoFormat((string) trans( + 'config.month_and_day_moment_js' + )), $item['dates']['pay_dates']); + $info[] = $current; ++$count; } return new MailMessage() - ->markdown('emails.subscriptions-overdue-warning', ['info' => $info, 'count' => $count]) - ->subject($this->getSubject()) - ; + ->markdown('emails.subscriptions-overdue-warning', ['info' => $info, 'count' => $count]) + ->subject($this->getSubject()); } private function getSubject(): string { if (count($this->overdue) > 1) { - return (string)trans('email.subscriptions_overdue_subject_multi', ['count' => count($this->overdue)]); + return (string) trans('email.subscriptions_overdue_subject_multi', ['count' => count($this->overdue)]); } - return (string)trans('email.subscriptions_overdue_subject_single'); + return (string) trans('email.subscriptions_overdue_subject_single'); } // public function toNtfy(User $notifiable): Message @@ -100,9 +96,7 @@ class SubscriptionsOverdueReminder extends Notification */ public function toPushover(User $notifiable): PushoverMessage { - return PushoverMessage::create((string)trans('email.bill_warning_please_action')) - ->title($this->getSubject()) - ; + return PushoverMessage::create((string) trans('email.bill_warning_please_action'))->title($this->getSubject()); } /** @@ -115,10 +109,9 @@ class SubscriptionsOverdueReminder extends Notification return new SlackMessage() ->warning() ->attachment(static function ($attachment) use ($url): void { - $attachment->title((string)trans('firefly.visit_bills'), $url); + $attachment->title((string) trans('firefly.visit_bills'), $url); }) - ->content($this->getSubject()) - ; + ->content($this->getSubject()); } /** diff --git a/app/Notifications/User/TransactionCreation.php b/app/Notifications/User/TransactionCreation.php index 9a09d82a6c..20d180ffb1 100644 --- a/app/Notifications/User/TransactionCreation.php +++ b/app/Notifications/User/TransactionCreation.php @@ -36,15 +36,16 @@ class TransactionCreation extends Notification { use Queueable; - public function __construct(private array $collection) {} + public function __construct( + private array $collection + ) {} /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ public function toArray(User $notifiable): array { - return [ - ]; + return []; } /** @@ -54,8 +55,7 @@ class TransactionCreation extends Notification { return new MailMessage() ->markdown('emails.report-new-journals', ['transformed' => $this->collection]) - ->subject(trans_choice('email.new_journals_subject', count($this->collection))) - ; + ->subject(trans_choice('email.new_journals_subject', count($this->collection))); } /** diff --git a/app/Notifications/User/UserLogin.php b/app/Notifications/User/UserLogin.php index fc49a102f3..ed975a6cb9 100644 --- a/app/Notifications/User/UserLogin.php +++ b/app/Notifications/User/UserLogin.php @@ -43,8 +43,7 @@ class UserLogin extends Notification public function toArray(User $notifiable): array { - return [ - ]; + return []; } /** @@ -58,9 +57,8 @@ class UserLogin extends Notification $time = now(config('app.timezone'))->isoFormat((string) trans('config.date_time_js')); return new MailMessage() - ->markdown('emails.new-ip', ['ip' => $ip, 'host' => $host, 'userAgent' => $userAgent, 'time' => $time]) - ->subject((string) trans('email.login_from_new_ip')) - ; + ->markdown('emails.new-ip', ['ip' => $ip, 'host' => $host, 'userAgent' => $userAgent, 'time' => $time]) + ->subject((string) trans('email.login_from_new_ip')); } // public function toNtfy(User $notifiable): Message @@ -84,9 +82,9 @@ class UserLogin extends Notification $ip = Request::ip(); $host = Steam::getHostName($ip); - return PushoverMessage::create((string) trans('email.slack_login_from_new_ip', ['ip' => $ip, 'host' => $host])) - ->title((string) trans('email.login_from_new_ip')) - ; + return PushoverMessage::create((string) trans('email.slack_login_from_new_ip', ['ip' => $ip, 'host' => $host]))->title((string) trans( + 'email.login_from_new_ip' + )); } /** @@ -97,7 +95,7 @@ class UserLogin extends Notification $ip = Request::ip(); $host = Steam::getHostName($ip); - return new SlackMessage()->content((string) trans('email.slack_login_from_new_ip', ['ip' => $ip, 'host' => $host])); + return new SlackMessage()->content((string) trans('email.slack_login_from_new_ip', ['ip' => $ip, 'host' => $host])); } /** diff --git a/app/Notifications/User/UserNewPassword.php b/app/Notifications/User/UserNewPassword.php index b9d708b698..9bc77baa5e 100644 --- a/app/Notifications/User/UserNewPassword.php +++ b/app/Notifications/User/UserNewPassword.php @@ -41,15 +41,16 @@ class UserNewPassword extends Notification { use Queueable; - public function __construct(private string $url) {} + public function __construct( + private string $url + ) {} /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ public function toArray(User $notifiable): array { - return [ - ]; + return []; } /** @@ -63,9 +64,14 @@ class UserNewPassword extends Notification $time = now(config('app.timezone'))->isoFormat((string) trans('config.date_time_js')); return new MailMessage() - ->markdown('emails.password', ['url' => $this->url, 'ip' => $ip, 'host' => $host, 'userAgent' => $userAgent, 'time' => $time]) - ->subject((string) trans('email.reset_pw_subject')) - ; + ->markdown('emails.password', [ + 'url' => $this->url, + 'ip' => $ip, + 'host' => $host, + 'userAgent' => $userAgent, + 'time' => $time + ]) + ->subject((string) trans('email.reset_pw_subject')); } // public function toNtfy(User $notifiable): Message diff --git a/app/Notifications/User/UserRegistration.php b/app/Notifications/User/UserRegistration.php index f00366f585..4c8c66ae01 100644 --- a/app/Notifications/User/UserRegistration.php +++ b/app/Notifications/User/UserRegistration.php @@ -41,8 +41,7 @@ class UserRegistration extends Notification */ public function toArray(User $notifiable): array { - return [ - ]; + return []; } /** @@ -52,8 +51,7 @@ class UserRegistration extends Notification { return new MailMessage() ->markdown('emails.registered', ['address' => route('index')]) - ->subject((string) trans('email.registered_subject')) - ; + ->subject((string) trans('email.registered_subject')); } /** diff --git a/app/Policies/UserPolicy.php b/app/Policies/UserPolicy.php index 169efb8109..872ce31fc3 100644 --- a/app/Policies/UserPolicy.php +++ b/app/Policies/UserPolicy.php @@ -34,12 +34,14 @@ class UserPolicy public function view(User $user, User $user1): bool { return true; + // return auth()->check() && $user->id === $account->user_id; } public function viewAccounts(User $user): bool { return true; + // return auth()->check(); } @@ -51,6 +53,7 @@ class UserPolicy public function viewAny(): bool { return true; + // return auth()->check(); } } diff --git a/app/Providers/AccountServiceProvider.php b/app/Providers/AccountServiceProvider.php index caa4ffe49f..bc03120c1d 100644 --- a/app/Providers/AccountServiceProvider.php +++ b/app/Providers/AccountServiceProvider.php @@ -41,7 +41,9 @@ class AccountServiceProvider extends ServiceProvider /** * Bootstrap the application services. */ - public function boot(): void {} + public function boot(): void + { + } /** * Register the application services. @@ -58,33 +60,29 @@ class AccountServiceProvider extends ServiceProvider */ private function registerRepository(): void { - $this->app->bind( - static function (Application $app): AccountRepositoryInterface { - /** @var AccountRepositoryInterface $repository */ - $repository = app(AccountRepository::class); + $this->app->bind(static function (Application $app): AccountRepositoryInterface { + /** @var AccountRepositoryInterface $repository */ + $repository = app(AccountRepository::class); - // phpstan thinks auth does not exist. - if ($app->auth->check()) { // @phpstan-ignore-line - $repository->setUser(auth()->user()); - } - - return $repository; + // phpstan thinks auth does not exist. + if ($app->auth->check()) { // @phpstan-ignore-line + $repository->setUser(auth()->user()); } - ); - $this->app->bind( - static function (Application $app): OperationsRepositoryInterface { - /** @var OperationsRepository $repository */ - $repository = app(OperationsRepository::class); + return $repository; + }); - // phpstan thinks auth does not exist. - if ($app->auth->check()) { // @phpstan-ignore-line - $repository->setUser(auth()->user()); - } + $this->app->bind(static function (Application $app): OperationsRepositoryInterface { + /** @var OperationsRepository $repository */ + $repository = app(OperationsRepository::class); - return $repository; + // phpstan thinks auth does not exist. + if ($app->auth->check()) { // @phpstan-ignore-line + $repository->setUser(auth()->user()); } - ); + + return $repository; + }); } /** @@ -92,18 +90,16 @@ class AccountServiceProvider extends ServiceProvider */ private function registerTasker(): void { - $this->app->bind( - static function (Application $app): AccountTaskerInterface { - /** @var AccountTaskerInterface $tasker */ - $tasker = app(AccountTasker::class); + $this->app->bind(static function (Application $app): AccountTaskerInterface { + /** @var AccountTaskerInterface $tasker */ + $tasker = app(AccountTasker::class); - // phpstan thinks auth does not exist. - if ($app->auth->check()) { // @phpstan-ignore-line - $tasker->setUser(auth()->user()); - } - - return $tasker; + // phpstan thinks auth does not exist. + if ($app->auth->check()) { // @phpstan-ignore-line + $tasker->setUser(auth()->user()); } - ); + + return $tasker; + }); } } diff --git a/app/Providers/AdminServiceProvider.php b/app/Providers/AdminServiceProvider.php index a775515130..00e176e52e 100644 --- a/app/Providers/AdminServiceProvider.php +++ b/app/Providers/AdminServiceProvider.php @@ -37,7 +37,9 @@ class AdminServiceProvider extends ServiceProvider /** * Bootstrap the application services. */ - public function boot(): void {} + public function boot(): void + { + } /** * Register the application services. @@ -53,17 +55,15 @@ class AdminServiceProvider extends ServiceProvider */ private function linkType(): void { - $this->app->bind( - static function (Application $app): LinkTypeRepositoryInterface { - /** @var LinkTypeRepository $repository */ - $repository = app(LinkTypeRepository::class); - // reference to auth is not understood by phpstan. - if ($app->auth->check()) { // @phpstan-ignore-line - $repository->setUser(auth()->user()); - } - - return $repository; + $this->app->bind(static function (Application $app): LinkTypeRepositoryInterface { + /** @var LinkTypeRepository $repository */ + $repository = app(LinkTypeRepository::class); + // reference to auth is not understood by phpstan. + if ($app->auth->check()) { // @phpstan-ignore-line + $repository->setUser(auth()->user()); } - ); + + return $repository; + }); } } diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index b5b45adee4..4242dbea51 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -46,18 +46,13 @@ class AppServiceProvider extends ServiceProvider Schema::defaultStringLength(191); // Passport::$clientUuids = false; Response::macro('api', function (array $value) { - $headers = [ - 'Cache-Control' => 'no-store', - ]; - $uuid = (string)request()->header('X-Trace-Id'); - if ('' !== trim($uuid) && (1 === preg_match('/^[a-f\d]{8}(-[a-f\d]{4}){4}[a-f\d]{8}$/i', trim($uuid)))) { + $headers = ['Cache-Control' => 'no-store']; + $uuid = (string) request()->header('X-Trace-Id'); + if ('' !== trim($uuid) && 1 === preg_match('/^[a-f\d]{8}(-[a-f\d]{4}){4}[a-f\d]{8}$/i', trim($uuid))) { $headers['X-Trace-Id'] = $uuid; } - return response() - ->json($value) - ->withHeaders($headers) - ; + return response()->json($value)->withHeaders($headers); }); // blade extension @@ -70,14 +65,14 @@ class AppServiceProvider extends ServiceProvider return ''; }); Blade::if('partialroute', function (string $route, string $firstParam = ''): bool { - $name = Route::getCurrentRoute()->getName() ?? ''; + $name = Route::getCurrentRoute()->getName() ?? ''; if ('' === $firstParam && str_contains($name, $route)) { return true; } /** @var null|array $params */ $params = Route::getCurrentRoute()->parameters(); - $params ??= []; + $params ??= []; $objectType = $params['objectType'] ?? ''; return $objectType === $firstParam && str_contains($name, $route); @@ -91,6 +86,7 @@ class AppServiceProvider extends ServiceProvider public function register(): void { Passport::ignoreRoutes(); + // Passport::ignoreMigrations(); // Sanctum::ignoreMigrations(); } diff --git a/app/Providers/AttachmentServiceProvider.php b/app/Providers/AttachmentServiceProvider.php index 4b653f5b69..4c50ac41b9 100644 --- a/app/Providers/AttachmentServiceProvider.php +++ b/app/Providers/AttachmentServiceProvider.php @@ -37,7 +37,9 @@ class AttachmentServiceProvider extends ServiceProvider /** * Bootstrap the application services. */ - public function boot(): void {} + public function boot(): void + { + } /** * Register the application services. @@ -45,17 +47,15 @@ class AttachmentServiceProvider extends ServiceProvider #[Override] public function register(): void { - $this->app->bind( - static function (Application $app): AttachmentRepositoryInterface { - /** @var AttachmentRepositoryInterface $repository */ - $repository = app(AttachmentRepository::class); - // reference to auth is not understood by phpstan. - if ($app->auth->check()) { // @phpstan-ignore-line - $repository->setUser(auth()->user()); - } - - return $repository; + $this->app->bind(static function (Application $app): AttachmentRepositoryInterface { + /** @var AttachmentRepositoryInterface $repository */ + $repository = app(AttachmentRepository::class); + // reference to auth is not understood by phpstan. + if ($app->auth->check()) { // @phpstan-ignore-line + $repository->setUser(auth()->user()); } - ); + + return $repository; + }); } } diff --git a/app/Providers/AuthServiceProvider.php b/app/Providers/AuthServiceProvider.php index 621ed90117..35ea287f73 100644 --- a/app/Providers/AuthServiceProvider.php +++ b/app/Providers/AuthServiceProvider.php @@ -34,10 +34,9 @@ use Laravel\Passport\Passport; */ class AuthServiceProvider extends ServiceProvider { - protected $policies - = [ - // 'FireflyIII\Model' => 'FireflyIII\Policies\ModelPolicy', - ]; + protected $policies = [ + // 'FireflyIII\Model' => 'FireflyIII\Policies\ModelPolicy', + ]; /** * Register any authentication / authorization services. @@ -46,14 +45,11 @@ class AuthServiceProvider extends ServiceProvider */ public function boot(): void { - Auth::provider( - 'remote_user_provider', - static fn ($app, array $config): RemoteUserProvider => new RemoteUserProvider() - ); + Auth::provider('remote_user_provider', static fn($app, array $config): RemoteUserProvider => new RemoteUserProvider()); Auth::extend( 'remote_user_guard', - static fn ($app, string $name, array $config): RemoteUserGuard => new RemoteUserGuard(Auth::createUserProvider($config['provider']), $app) + static fn($app, string $name, array $config): RemoteUserGuard => new RemoteUserGuard(Auth::createUserProvider($config['provider']), $app) ); Passport::tokensExpireIn(now()->addDays(14)); diff --git a/app/Providers/BillServiceProvider.php b/app/Providers/BillServiceProvider.php index 0a5472304d..b268d28b6d 100644 --- a/app/Providers/BillServiceProvider.php +++ b/app/Providers/BillServiceProvider.php @@ -37,7 +37,9 @@ class BillServiceProvider extends ServiceProvider /** * Bootstrap the application services. */ - public function boot(): void {} + public function boot(): void + { + } /** * Register the application services. @@ -45,19 +47,16 @@ class BillServiceProvider extends ServiceProvider #[Override] public function register(): void { - $this->app->bind( - static function (Application $app): BillRepositoryInterface { - /** @var BillRepositoryInterface $repository */ - $repository = app(BillRepository::class); + $this->app->bind(static function (Application $app): BillRepositoryInterface { + /** @var BillRepositoryInterface $repository */ + $repository = app(BillRepository::class); - // reference to auth is not understood by phpstan. - if ($app->auth->check()) { // @phpstan-ignore-line - $repository->setUser(auth()->user()); - } - - return $repository; + // reference to auth is not understood by phpstan. + if ($app->auth->check()) { // @phpstan-ignore-line + $repository->setUser(auth()->user()); } - ); + return $repository; + }); } } diff --git a/app/Providers/BudgetServiceProvider.php b/app/Providers/BudgetServiceProvider.php index a6bc575d31..d2c94bf659 100644 --- a/app/Providers/BudgetServiceProvider.php +++ b/app/Providers/BudgetServiceProvider.php @@ -45,7 +45,9 @@ class BudgetServiceProvider extends ServiceProvider /** * Bootstrap the application services. */ - public function boot(): void {} + public function boot(): void + { + } /** * Register the application services. @@ -56,68 +58,58 @@ class BudgetServiceProvider extends ServiceProvider public function register(): void { // reference to auth is not understood by phpstan. - $this->app->bind( - static function (Application $app): BudgetRepositoryInterface { - /** @var BudgetRepositoryInterface $repository */ - $repository = app(BudgetRepository::class); - if ($app->auth->check()) { // @phpstan-ignore-line - $repository->setUser(auth()->user()); - } - - return $repository; + $this->app->bind(static function (Application $app): BudgetRepositoryInterface { + /** @var BudgetRepositoryInterface $repository */ + $repository = app(BudgetRepository::class); + if ($app->auth->check()) { // @phpstan-ignore-line + $repository->setUser(auth()->user()); } - ); + + return $repository; + }); // available budget repos - $this->app->bind( - static function (Application $app): AvailableBudgetRepositoryInterface { - /** @var AvailableBudgetRepositoryInterface $repository */ - $repository = app(AvailableBudgetRepository::class); - if ($app->auth->check()) { // @phpstan-ignore-line - $repository->setUser(auth()->user()); - } - - return $repository; + $this->app->bind(static function (Application $app): AvailableBudgetRepositoryInterface { + /** @var AvailableBudgetRepositoryInterface $repository */ + $repository = app(AvailableBudgetRepository::class); + if ($app->auth->check()) { // @phpstan-ignore-line + $repository->setUser(auth()->user()); } - ); + + return $repository; + }); // budget limit repository. - $this->app->bind( - static function (Application $app): BudgetLimitRepositoryInterface { - /** @var BudgetLimitRepositoryInterface $repository */ - $repository = app(BudgetLimitRepository::class); - if ($app->auth->check()) { // @phpstan-ignore-line - $repository->setUser(auth()->user()); - } - - return $repository; + $this->app->bind(static function (Application $app): BudgetLimitRepositoryInterface { + /** @var BudgetLimitRepositoryInterface $repository */ + $repository = app(BudgetLimitRepository::class); + if ($app->auth->check()) { // @phpstan-ignore-line + $repository->setUser(auth()->user()); } - ); + + return $repository; + }); // no budget repos - $this->app->bind( - static function (Application $app): NoBudgetRepositoryInterface { - /** @var NoBudgetRepositoryInterface $repository */ - $repository = app(NoBudgetRepository::class); - if ($app->auth->check()) { // @phpstan-ignore-line - $repository->setUser(auth()->user()); - } - - return $repository; + $this->app->bind(static function (Application $app): NoBudgetRepositoryInterface { + /** @var NoBudgetRepositoryInterface $repository */ + $repository = app(NoBudgetRepository::class); + if ($app->auth->check()) { // @phpstan-ignore-line + $repository->setUser(auth()->user()); } - ); + + return $repository; + }); // operations repos - $this->app->bind( - static function (Application $app): OperationsRepositoryInterface { - /** @var OperationsRepositoryInterface $repository */ - $repository = app(OperationsRepository::class); - if ($app->auth->check()) { // @phpstan-ignore-line - $repository->setUser(auth()->user()); - } - - return $repository; + $this->app->bind(static function (Application $app): OperationsRepositoryInterface { + /** @var OperationsRepositoryInterface $repository */ + $repository = app(OperationsRepository::class); + if ($app->auth->check()) { // @phpstan-ignore-line + $repository->setUser(auth()->user()); } - ); + + return $repository; + }); } } diff --git a/app/Providers/CategoryServiceProvider.php b/app/Providers/CategoryServiceProvider.php index 6346fea046..6c1c1f9495 100644 --- a/app/Providers/CategoryServiceProvider.php +++ b/app/Providers/CategoryServiceProvider.php @@ -41,7 +41,9 @@ class CategoryServiceProvider extends ServiceProvider /** * Bootstrap the application services. */ - public function boot(): void {} + public function boot(): void + { + } /** * Register the application services. @@ -50,40 +52,34 @@ class CategoryServiceProvider extends ServiceProvider public function register(): void { // phpstan does not understand reference to 'auth'. - $this->app->bind( - static function (Application $app): CategoryRepositoryInterface { - /** @var CategoryRepository $repository */ - $repository = app(CategoryRepository::class); - if ($app->auth->check()) { // @phpstan-ignore-line - $repository->setUser(auth()->user()); - } - - return $repository; + $this->app->bind(static function (Application $app): CategoryRepositoryInterface { + /** @var CategoryRepository $repository */ + $repository = app(CategoryRepository::class); + if ($app->auth->check()) { // @phpstan-ignore-line + $repository->setUser(auth()->user()); } - ); - $this->app->bind( - static function (Application $app): OperationsRepositoryInterface { - /** @var OperationsRepository $repository */ - $repository = app(OperationsRepository::class); - if ($app->auth->check()) { // @phpstan-ignore-line - $repository->setUser(auth()->user()); - } + return $repository; + }); - return $repository; + $this->app->bind(static function (Application $app): OperationsRepositoryInterface { + /** @var OperationsRepository $repository */ + $repository = app(OperationsRepository::class); + if ($app->auth->check()) { // @phpstan-ignore-line + $repository->setUser(auth()->user()); } - ); - $this->app->bind( - static function (Application $app): NoCategoryRepositoryInterface { - /** @var NoCategoryRepository $repository */ - $repository = app(NoCategoryRepository::class); - if ($app->auth->check()) { // @phpstan-ignore-line - $repository->setUser(auth()->user()); - } + return $repository; + }); - return $repository; + $this->app->bind(static function (Application $app): NoCategoryRepositoryInterface { + /** @var NoCategoryRepository $repository */ + $repository = app(NoCategoryRepository::class); + if ($app->auth->check()) { // @phpstan-ignore-line + $repository->setUser(auth()->user()); } - ); + + return $repository; + }); } } diff --git a/app/Providers/CurrencyServiceProvider.php b/app/Providers/CurrencyServiceProvider.php index dbb917d293..5eeb52269c 100644 --- a/app/Providers/CurrencyServiceProvider.php +++ b/app/Providers/CurrencyServiceProvider.php @@ -40,7 +40,9 @@ class CurrencyServiceProvider extends ServiceProvider /** * Bootstrap the application services. */ - public function boot(): void {} + public function boot(): void + { + } /** * Register the application services. @@ -48,43 +50,36 @@ class CurrencyServiceProvider extends ServiceProvider #[Override] public function register(): void { - $this->app->bind( - static function (Application $app): GroupCurrencyRepositoryInterface { - /** @var CurrencyRepository $repository */ - $repository = app(GroupCurrencyRepository::class); - // phpstan does not get the reference to auth - if ($app->auth->check()) { // @phpstan-ignore-line - $repository->setUser(auth()->user()); - } - - return $repository; + $this->app->bind(static function (Application $app): GroupCurrencyRepositoryInterface { + /** @var CurrencyRepository $repository */ + $repository = app(GroupCurrencyRepository::class); + // phpstan does not get the reference to auth + if ($app->auth->check()) { // @phpstan-ignore-line + $repository->setUser(auth()->user()); } - ); - $this->app->bind( - static function (Application $app): GroupCurrencyRepositoryInterface { - /** @var GroupCurrencyRepository $repository */ - $repository = app(GroupCurrencyRepository::class); - // phpstan does not get the reference to auth - if ($app->auth->check()) { // @phpstan-ignore-line - $repository->setUser(auth()->user()); - } - return $repository; + return $repository; + }); + $this->app->bind(static function (Application $app): GroupCurrencyRepositoryInterface { + /** @var GroupCurrencyRepository $repository */ + $repository = app(GroupCurrencyRepository::class); + // phpstan does not get the reference to auth + if ($app->auth->check()) { // @phpstan-ignore-line + $repository->setUser(auth()->user()); } - ); - $this->app->bind( - static function (Application $app): ExchangeRateRepositoryInterface { - /** @var ExchangeRateRepository $repository */ - $repository = app(ExchangeRateRepository::class); - // phpstan does not get the reference to auth - if ($app->auth->check()) { // @phpstan-ignore-line - $repository->setUserGroup(auth()->user()->userGroup); - } + return $repository; + }); - return $repository; + $this->app->bind(static function (Application $app): ExchangeRateRepositoryInterface { + /** @var ExchangeRateRepository $repository */ + $repository = app(ExchangeRateRepository::class); + // phpstan does not get the reference to auth + if ($app->auth->check()) { // @phpstan-ignore-line + $repository->setUserGroup(auth()->user()->userGroup); } - ); + return $repository; + }); } } diff --git a/app/Providers/EventServiceProvider.php b/app/Providers/EventServiceProvider.php index 547c6d2f04..721cc0456e 100644 --- a/app/Providers/EventServiceProvider.php +++ b/app/Providers/EventServiceProvider.php @@ -47,127 +47,104 @@ use Override; */ class EventServiceProvider extends ServiceProvider { - protected $listen - = [ - // is a User related event. - // RegisteredUser::class => [ - // 'FireflyIII\Handlers\Events\UserEventHandler@createExchangeRates', - // ], - // UserAttemptedLogin::class => [ - // 'FireflyIII\Handlers\Events\UserEventHandler@sendLoginAttemptNotification', - // ], - // is a User related event. - Login::class => [ - 'FireflyIII\Handlers\Events\UserEventHandler@checkSingleUserIsAdmin', - 'FireflyIII\Handlers\Events\UserEventHandler@demoUserBackToEnglish', - ], - // DetectedNewIPAddress::class => [ - // 'FireflyIII\Handlers\Events\UserEventHandler@notifyNewIPAddress', - // ], - RequestedVersionCheckStatus::class => [ - 'FireflyIII\Handlers\Events\VersionCheckEventHandler@checkForUpdates', - ], - RequestedReportOnJournals::class => [ - 'FireflyIII\Handlers\Events\AutomationHandler@reportJournals', - ], + protected $listen = [ + // is a User related event. + // RegisteredUser::class => [ + // 'FireflyIII\Handlers\Events\UserEventHandler@createExchangeRates', + // ], + // UserAttemptedLogin::class => [ + // 'FireflyIII\Handlers\Events\UserEventHandler@sendLoginAttemptNotification', + // ], + // is a User related event. + Login::class => [ + 'FireflyIII\Handlers\Events\UserEventHandler@checkSingleUserIsAdmin', + 'FireflyIII\Handlers\Events\UserEventHandler@demoUserBackToEnglish' + ], + // DetectedNewIPAddress::class => [ + // 'FireflyIII\Handlers\Events\UserEventHandler@notifyNewIPAddress', + // ], + RequestedVersionCheckStatus::class => ['FireflyIII\Handlers\Events\VersionCheckEventHandler@checkForUpdates'], + RequestedReportOnJournals::class => ['FireflyIII\Handlers\Events\AutomationHandler@reportJournals'], - // is a User related event. - InvitationCreated::class => [ - 'FireflyIII\Handlers\Events\AdminEventHandler@sendInvitationNotification', - 'FireflyIII\Handlers\Events\UserEventHandler@sendRegistrationInvite', - ], + // is a User related event. + InvitationCreated::class => [ + 'FireflyIII\Handlers\Events\AdminEventHandler@sendInvitationNotification', + 'FireflyIII\Handlers\Events\UserEventHandler@sendRegistrationInvite' + ], - // is a Transaction Journal related event. - StoredTransactionGroup::class => [ - 'FireflyIII\Handlers\Events\StoredGroupEventHandler@runAllHandlers', - ], - TriggeredStoredTransactionGroup::class => [ - 'FireflyIII\Handlers\Events\StoredGroupEventHandler@triggerRulesManually', - ], - // is a Transaction Journal related event. - UpdatedTransactionGroup::class => [ - 'FireflyIII\Handlers\Events\UpdatedGroupEventHandler@runAllHandlers', - ], - DestroyedTransactionGroup::class => [ - 'FireflyIII\Handlers\Events\DestroyedGroupEventHandler@runAllHandlers', - ], - // API related events: - AccessTokenCreated::class => [ - 'FireflyIII\Handlers\Events\APIEventHandler@accessTokenCreated', - ], + // is a Transaction Journal related event. + StoredTransactionGroup::class => ['FireflyIII\Handlers\Events\StoredGroupEventHandler@runAllHandlers'], + TriggeredStoredTransactionGroup::class => ['FireflyIII\Handlers\Events\StoredGroupEventHandler@triggerRulesManually'], + // is a Transaction Journal related event. + UpdatedTransactionGroup::class => ['FireflyIII\Handlers\Events\UpdatedGroupEventHandler@runAllHandlers'], + DestroyedTransactionGroup::class => ['FireflyIII\Handlers\Events\DestroyedGroupEventHandler@runAllHandlers'], + // API related events: + AccessTokenCreated::class => ['FireflyIII\Handlers\Events\APIEventHandler@accessTokenCreated'], - // Webhook related event: - RequestedSendWebhookMessages::class => [ - 'FireflyIII\Handlers\Events\WebhookEventHandler@sendWebhookMessages', - ], + // Webhook related event: + RequestedSendWebhookMessages::class => ['FireflyIII\Handlers\Events\WebhookEventHandler@sendWebhookMessages'], - // account related events: - StoredAccount::class => [ - 'FireflyIII\Handlers\Events\StoredAccountEventHandler@recalculateCredit', - ], - UpdatedAccount::class => [ - 'FireflyIII\Handlers\Events\UpdatedAccountEventHandler@recalculateCredit', - ], + // account related events: + StoredAccount::class => ['FireflyIII\Handlers\Events\StoredAccountEventHandler@recalculateCredit'], + UpdatedAccount::class => ['FireflyIII\Handlers\Events\UpdatedAccountEventHandler@recalculateCredit'], - // subscription related events: - // SubscriptionNeedsExtensionOrRenewal::class => [ - // 'FireflyIII\Handlers\Events\BillEventHandler@warnAboutBill', - // ], - // WarnUserAboutOverdueSubscriptions::class => [ - // 'FireflyIII\Handlers\Events\BillEventHandler@warnAboutOverdueSubscriptions', - // ], + // subscription related events: + // SubscriptionNeedsExtensionOrRenewal::class => [ + // 'FireflyIII\Handlers\Events\BillEventHandler@warnAboutBill', + // ], + // WarnUserAboutOverdueSubscriptions::class => [ + // 'FireflyIII\Handlers\Events\BillEventHandler@warnAboutOverdueSubscriptions', + // ], - // audit log events: - TriggeredAuditLog::class => [ - 'FireflyIII\Handlers\Events\AuditEventHandler@storeAuditEvent', - ], - // piggy bank related events: - // PiggyBankAmountIsChanged::class => [ - // 'FireflyIII\Handlers\Events\Model\PiggyBankEventHandler@changePiggyAmount', - // ], - // ChangedName::class => [ - // 'FireflyIII\Handlers\Events\Model\PiggyBankEventHandler@changedPiggyBankName', - // ], + // audit log events: + TriggeredAuditLog::class => ['FireflyIII\Handlers\Events\AuditEventHandler@storeAuditEvent'], + // piggy bank related events: + // PiggyBankAmountIsChanged::class => [ + // 'FireflyIII\Handlers\Events\Model\PiggyBankEventHandler@changePiggyAmount', + // ], + // ChangedName::class => [ + // 'FireflyIII\Handlers\Events\Model\PiggyBankEventHandler@changedPiggyBankName', + // ], - // rule actions - // RuleActionFailedOnArray::class => [ - // 'FireflyIII\Handlers\Events\Model\RuleHandler@ruleActionFailedOnArray', - // ], - // RuleActionFailedOnObject::class => [ - // 'FireflyIII\Handlers\Events\Model\RuleHandler@ruleActionFailedOnObject', - // ], + // rule actions + // RuleActionFailedOnArray::class => [ + // 'FireflyIII\Handlers\Events\Model\RuleHandler@ruleActionFailedOnArray', + // ], + // RuleActionFailedOnObject::class => [ + // 'FireflyIII\Handlers\Events\Model\RuleHandler@ruleActionFailedOnObject', + // ], - // security related - // EnabledMFA::class => [ - // 'FireflyIII\Handlers\Events\Security\MFAHandler@sendMFAEnabledMail', - // ], - // DisabledMFA::class => [ - // 'FireflyIII\Handlers\Events\Security\MFAHandler@sendMFADisabledMail', - // ], - // MFANewBackupCodes::class => [ - // 'FireflyIII\Handlers\Events\Security\MFAHandler@sendNewMFABackupCodesMail', - // ], - // MFAUsedBackupCode::class => [ - // 'FireflyIII\Handlers\Events\Security\MFAHandler@sendUsedBackupCodeMail', - // ], - // MFABackupFewLeft::class => [ - // 'FireflyIII\Handlers\Events\Security\MFAHandler@sendBackupFewLeftMail', - // ], - // MFABackupNoLeft::class => [ - // 'FireflyIII\Handlers\Events\Security\MFAHandler@sendBackupNoLeftMail', - // ], - // MFAManyFailedAttempts::class => [ - // 'FireflyIII\Handlers\Events\Security\MFAHandler@sendMFAFailedAttemptsMail', - // ], - // preferences - UserGroupChangedPrimaryCurrency::class => [ - 'FireflyIII\Handlers\Events\PreferencesEventHandler@resetPrimaryCurrencyAmounts', - ], - ]; + // security related + // EnabledMFA::class => [ + // 'FireflyIII\Handlers\Events\Security\MFAHandler@sendMFAEnabledMail', + // ], + // DisabledMFA::class => [ + // 'FireflyIII\Handlers\Events\Security\MFAHandler@sendMFADisabledMail', + // ], + // MFANewBackupCodes::class => [ + // 'FireflyIII\Handlers\Events\Security\MFAHandler@sendNewMFABackupCodesMail', + // ], + // MFAUsedBackupCode::class => [ + // 'FireflyIII\Handlers\Events\Security\MFAHandler@sendUsedBackupCodeMail', + // ], + // MFABackupFewLeft::class => [ + // 'FireflyIII\Handlers\Events\Security\MFAHandler@sendBackupFewLeftMail', + // ], + // MFABackupNoLeft::class => [ + // 'FireflyIII\Handlers\Events\Security\MFAHandler@sendBackupNoLeftMail', + // ], + // MFAManyFailedAttempts::class => [ + // 'FireflyIII\Handlers\Events\Security\MFAHandler@sendMFAFailedAttemptsMail', + // ], + // preferences + UserGroupChangedPrimaryCurrency::class => ['FireflyIII\Handlers\Events\PreferencesEventHandler@resetPrimaryCurrencyAmounts'] + ]; /** * Register any events for your application. */ #[Override] - public function boot(): void {} + public function boot(): void + { + } } diff --git a/app/Providers/FireflyServiceProvider.php b/app/Providers/FireflyServiceProvider.php index 7cd545d40f..7d73f997b2 100644 --- a/app/Providers/FireflyServiceProvider.php +++ b/app/Providers/FireflyServiceProvider.php @@ -92,9 +92,7 @@ class FireflyServiceProvider extends ServiceProvider */ public function boot(): void { - Validator::resolver( - static fn ($translator, $data, $rules, $messages): FireflyValidator => new FireflyValidator($translator, $data, $rules, $messages) - ); + Validator::resolver(static fn($translator, $data, $rules, $messages): FireflyValidator => new FireflyValidator($translator, $data, $rules, $messages)); } /** @@ -105,55 +103,22 @@ class FireflyServiceProvider extends ServiceProvider #[Override] public function register(): void { - $this->app->bind( - 'preferences', - static fn (): Preferences => new Preferences() - ); + $this->app->bind('preferences', static fn(): Preferences => new Preferences()); - $this->app->bind( - 'fireflyconfig', - static fn (): FireflyConfig => new FireflyConfig() - ); - $this->app->bind( - 'navigation', - static fn (): Navigation => new Navigation() - ); - $this->app->bind( - 'amount', - static fn (): Amount => new Amount() - ); + $this->app->bind('fireflyconfig', static fn(): FireflyConfig => new FireflyConfig()); + $this->app->bind('navigation', static fn(): Navigation => new Navigation()); + $this->app->bind('amount', static fn(): Amount => new Amount()); - $this->app->bind( - 'steam', - static fn (): Steam => new Steam() - ); - $this->app->bind( - 'balance', - static fn (): Balance => new Balance() - ); - $this->app->bind( - 'expandedform', - static fn (): ExpandedForm => new ExpandedForm() - ); + $this->app->bind('steam', static fn(): Steam => new Steam()); + $this->app->bind('balance', static fn(): Balance => new Balance()); + $this->app->bind('expandedform', static fn(): ExpandedForm => new ExpandedForm()); - $this->app->bind( - 'accountform', - static fn (): AccountForm => new AccountForm() - ); - $this->app->bind( - 'currencyform', - static fn (): CurrencyForm => new CurrencyForm() - ); + $this->app->bind('accountform', static fn(): AccountForm => new AccountForm()); + $this->app->bind('currencyform', static fn(): CurrencyForm => new CurrencyForm()); - $this->app->bind( - 'piggybankform', - static fn (): PiggyBankForm => new PiggyBankForm() - ); + $this->app->bind('piggybankform', static fn(): PiggyBankForm => new PiggyBankForm()); - $this->app->bind( - 'ruleform', - static fn (): RuleForm => new RuleForm() - ); + $this->app->bind('ruleform', static fn(): RuleForm => new RuleForm()); // chart generator: $this->app->bind(GeneratorInterface::class, ChartJsGenerator::class); @@ -164,75 +129,63 @@ class FireflyServiceProvider extends ServiceProvider $this->app->bind(AttachmentHelperInterface::class, AttachmentHelper::class); $this->app->bind(ALERepositoryInterface::class, ALERepository::class); - $this->app->bind( - static function (Application $app): ObjectGroupRepositoryInterface { - /** @var ObjectGroupRepository $repository */ - $repository = app(ObjectGroupRepository::class); - if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) - $repository->setUser(auth()->user()); - } - - return $repository; + $this->app->bind(static function (Application $app): ObjectGroupRepositoryInterface { + /** @var ObjectGroupRepository $repository */ + $repository = app(ObjectGroupRepository::class); + if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) + $repository->setUser(auth()->user()); } - ); - $this->app->bind( - static function (Application $app): PeriodStatisticRepositoryInterface { - /** @var PeriodStatisticRepository $repository */ - $repository = app(PeriodStatisticRepository::class); - if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) - $repository->setUser(auth()->user()); - } + return $repository; + }); - return $repository; + $this->app->bind(static function (Application $app): PeriodStatisticRepositoryInterface { + /** @var PeriodStatisticRepository $repository */ + $repository = app(PeriodStatisticRepository::class); + if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) + $repository->setUser(auth()->user()); } - ); - $this->app->bind( - static function (Application $app): WebhookRepositoryInterface { - /** @var WebhookRepository $repository */ - $repository = app(WebhookRepository::class); - if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) - $repository->setUser(auth()->user()); - } + return $repository; + }); - return $repository; + $this->app->bind(static function (Application $app): WebhookRepositoryInterface { + /** @var WebhookRepository $repository */ + $repository = app(WebhookRepository::class); + if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) + $repository->setUser(auth()->user()); } - ); + + return $repository; + }); // rule expression language - $this->app->singleton( - static function (): ExpressionLanguage { - $expressionLanguage = new ExpressionLanguage(); - $expressionLanguage->registerProvider(new ActionExpressionLanguageProvider()); + $this->app->singleton(static function (): ExpressionLanguage { + $expressionLanguage = new ExpressionLanguage(); + $expressionLanguage->registerProvider(new ActionExpressionLanguageProvider()); - return $expressionLanguage; + return $expressionLanguage; + }); + + $this->app->bind(static function (Application $app): RuleEngineInterface { + /** @var SearchRuleEngine $engine */ + $engine = app(SearchRuleEngine::class); + if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) + $engine->setUser(auth()->user()); } - ); - $this->app->bind( - static function (Application $app): RuleEngineInterface { - /** @var SearchRuleEngine $engine */ - $engine = app(SearchRuleEngine::class); - if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) - $engine->setUser(auth()->user()); - } + return $engine; + }); - return $engine; + $this->app->bind(static function (Application $app): UserGroupRepositoryInterface { + /** @var UserGroupRepository $repository */ + $repository = app(UserGroupRepository::class); + if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) + $repository->setUser(auth()->user()); } - ); - $this->app->bind( - static function (Application $app): UserGroupRepositoryInterface { - /** @var UserGroupRepository $repository */ - $repository = app(UserGroupRepository::class); - if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) - $repository->setUser(auth()->user()); - } - - return $repository; - } - ); + return $repository; + }); // more generators: $this->app->bind(PopupReportInterface::class, PopupReport::class); diff --git a/app/Providers/FireflySessionProvider.php b/app/Providers/FireflySessionProvider.php index 6912eb254a..d25f068068 100644 --- a/app/Providers/FireflySessionProvider.php +++ b/app/Providers/FireflySessionProvider.php @@ -51,10 +51,7 @@ class FireflySessionProvider extends ServiceProvider */ protected function registerSessionManager(): void { - $this->app->singleton( - 'session', - static fn ($app): SessionManager => new SessionManager($app) - ); + $this->app->singleton('session', static fn($app): SessionManager => new SessionManager($app)); } /** @@ -62,13 +59,11 @@ class FireflySessionProvider extends ServiceProvider */ protected function registerSessionDriver(): void { - $this->app->singleton( - 'session.store', - static fn ($app) - // First, we will create the session manager which is responsible for the - // creation of the various session drivers when they are needed by the - // application instance, and will resolve them on a lazy load basis. - => $app->make('session')->driver() - ); + $this->app->singleton('session.store', static fn($app) => ( + // First, we will create the session manager which is responsible for the + // creation of the various session drivers when they are needed by the + // application instance, and will resolve them on a lazy load basis. + $app->make('session')->driver() + )); } } diff --git a/app/Providers/JournalServiceProvider.php b/app/Providers/JournalServiceProvider.php index ac27b169ba..b6044e13ff 100644 --- a/app/Providers/JournalServiceProvider.php +++ b/app/Providers/JournalServiceProvider.php @@ -45,7 +45,9 @@ class JournalServiceProvider extends ServiceProvider /** * Bootstrap the application services. */ - public function boot(): void {} + public function boot(): void + { + } /** * Register the application services. @@ -63,43 +65,37 @@ class JournalServiceProvider extends ServiceProvider */ private function registerRepository(): void { - $this->app->bind( - static function (Application $app): JournalRepositoryInterface { - /** @var JournalRepositoryInterface $repository */ - $repository = app(JournalRepository::class); - if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) - $repository->setUser(auth()->user()); - } - - return $repository; + $this->app->bind(static function (Application $app): JournalRepositoryInterface { + /** @var JournalRepositoryInterface $repository */ + $repository = app(JournalRepository::class); + if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) + $repository->setUser(auth()->user()); } - ); + + return $repository; + }); // also bind new API repository - $this->app->bind( - static function (Application $app): JournalAPIRepositoryInterface { - /** @var JournalAPIRepositoryInterface $repository */ - $repository = app(JournalAPIRepository::class); - if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) - $repository->setUser(auth()->user()); - } - - return $repository; + $this->app->bind(static function (Application $app): JournalAPIRepositoryInterface { + /** @var JournalAPIRepositoryInterface $repository */ + $repository = app(JournalAPIRepository::class); + if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) + $repository->setUser(auth()->user()); } - ); + + return $repository; + }); // also bind new CLI repository - $this->app->bind( - static function (Application $app): JournalCLIRepositoryInterface { - /** @var JournalCLIRepositoryInterface $repository */ - $repository = app(JournalCLIRepository::class); - if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) - $repository->setUser(auth()->user()); - } - - return $repository; + $this->app->bind(static function (Application $app): JournalCLIRepositoryInterface { + /** @var JournalCLIRepositoryInterface $repository */ + $repository = app(JournalCLIRepository::class); + if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) + $repository->setUser(auth()->user()); } - ); + + return $repository; + }); } /** @@ -107,31 +103,27 @@ class JournalServiceProvider extends ServiceProvider */ private function registerGroupRepository(): void { - $this->app->bind( - static function (Application $app): TransactionGroupRepositoryInterface { - /** @var TransactionGroupRepositoryInterface $repository */ - $repository = app(TransactionGroupRepository::class); - if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) - $repository->setUser(auth()->user()); - } - - return $repository; + $this->app->bind(static function (Application $app): TransactionGroupRepositoryInterface { + /** @var TransactionGroupRepositoryInterface $repository */ + $repository = app(TransactionGroupRepository::class); + if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) + $repository->setUser(auth()->user()); } - ); + + return $repository; + }); } private function registerGroupCollector(): void { - $this->app->bind( - static function (Application $app): GroupCollectorInterface { - /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollector::class); - if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) - $collector->setUser(auth()->user()); - } - - return $collector; + $this->app->bind(static function (Application $app): GroupCollectorInterface { + /** @var GroupCollectorInterface $collector */ + $collector = app(GroupCollector::class); + if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) + $collector->setUser(auth()->user()); } - ); + + return $collector; + }); } } diff --git a/app/Providers/PiggyBankServiceProvider.php b/app/Providers/PiggyBankServiceProvider.php index 99020bc2e3..21b3ffcad6 100644 --- a/app/Providers/PiggyBankServiceProvider.php +++ b/app/Providers/PiggyBankServiceProvider.php @@ -37,7 +37,9 @@ class PiggyBankServiceProvider extends ServiceProvider /** * Bootstrap the application services. */ - public function boot(): void {} + public function boot(): void + { + } /** * Register the application services. @@ -45,16 +47,14 @@ class PiggyBankServiceProvider extends ServiceProvider #[Override] public function register(): void { - $this->app->bind( - static function (Application $app): PiggyBankRepositoryInterface { - /** @var PiggyBankRepository $repository */ - $repository = app(PiggyBankRepository::class); - if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) - $repository->setUser(auth()->user()); - } - - return $repository; + $this->app->bind(static function (Application $app): PiggyBankRepositoryInterface { + /** @var PiggyBankRepository $repository */ + $repository = app(PiggyBankRepository::class); + if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) + $repository->setUser(auth()->user()); } - ); + + return $repository; + }); } } diff --git a/app/Providers/RecurringServiceProvider.php b/app/Providers/RecurringServiceProvider.php index a8184d735f..157d56dc35 100644 --- a/app/Providers/RecurringServiceProvider.php +++ b/app/Providers/RecurringServiceProvider.php @@ -37,7 +37,9 @@ class RecurringServiceProvider extends ServiceProvider /** * Bootstrap the application services. */ - public function boot(): void {} + public function boot(): void + { + } /** * Register the application services. @@ -45,17 +47,15 @@ class RecurringServiceProvider extends ServiceProvider #[Override] public function register(): void { - $this->app->bind( - static function (Application $app): RecurringRepositoryInterface { - /** @var RecurringRepositoryInterface $repository */ - $repository = app(RecurringRepository::class); + $this->app->bind(static function (Application $app): RecurringRepositoryInterface { + /** @var RecurringRepositoryInterface $repository */ + $repository = app(RecurringRepository::class); - if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) - $repository->setUser(auth()->user()); - } - - return $repository; + if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) + $repository->setUser(auth()->user()); } - ); + + return $repository; + }); } } diff --git a/app/Providers/RouteServiceProvider.php b/app/Providers/RouteServiceProvider.php index caec293d3d..2002ff2302 100644 --- a/app/Providers/RouteServiceProvider.php +++ b/app/Providers/RouteServiceProvider.php @@ -32,8 +32,9 @@ use Override; */ class RouteServiceProvider extends ServiceProvider { - public const string HOME = '/'; - protected $namespace = ''; + public const string HOME = '/'; + + protected $namespace = ''; /** * Define the routes for the application. @@ -45,19 +46,14 @@ class RouteServiceProvider extends ServiceProvider Route::prefix('api') ->middleware('api') ->namespace($this->namespace) - ->group(base_path('routes/api.php')) - ; + ->group(base_path('routes/api.php')); Route::prefix('api/v1/cron') ->middleware('api_basic') ->namespace($this->namespace) - ->group(base_path('routes/api-noauth.php')) - ; + ->group(base_path('routes/api-noauth.php')); - Route::middleware('web') - ->namespace($this->namespace) - ->group(base_path('routes/web.php')) - ; + Route::middleware('web')->namespace($this->namespace)->group(base_path('routes/web.php')); }); } } diff --git a/app/Providers/RuleGroupServiceProvider.php b/app/Providers/RuleGroupServiceProvider.php index 32fa85b17e..634ffc0630 100644 --- a/app/Providers/RuleGroupServiceProvider.php +++ b/app/Providers/RuleGroupServiceProvider.php @@ -37,7 +37,9 @@ class RuleGroupServiceProvider extends ServiceProvider /** * Bootstrap the application services. */ - public function boot(): void {} + public function boot(): void + { + } /** * Register the application services. @@ -45,16 +47,14 @@ class RuleGroupServiceProvider extends ServiceProvider #[Override] public function register(): void { - $this->app->bind( - static function (Application $app): RuleGroupRepositoryInterface { - /** @var RuleGroupRepository $repository */ - $repository = app(RuleGroupRepository::class); - if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) - $repository->setUser(auth()->user()); - } - - return $repository; + $this->app->bind(static function (Application $app): RuleGroupRepositoryInterface { + /** @var RuleGroupRepository $repository */ + $repository = app(RuleGroupRepository::class); + if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) + $repository->setUser(auth()->user()); } - ); + + return $repository; + }); } } diff --git a/app/Providers/RuleServiceProvider.php b/app/Providers/RuleServiceProvider.php index e7b235588f..9e913340e4 100644 --- a/app/Providers/RuleServiceProvider.php +++ b/app/Providers/RuleServiceProvider.php @@ -37,7 +37,9 @@ class RuleServiceProvider extends ServiceProvider /** * Bootstrap the application services. */ - public function boot(): void {} + public function boot(): void + { + } /** * Register the application services. @@ -45,16 +47,14 @@ class RuleServiceProvider extends ServiceProvider #[Override] public function register(): void { - $this->app->bind( - static function (Application $app): RuleRepositoryInterface { - /** @var RuleRepository $repository */ - $repository = app(RuleRepository::class); - if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) - $repository->setUser(auth()->user()); - } - - return $repository; + $this->app->bind(static function (Application $app): RuleRepositoryInterface { + /** @var RuleRepository $repository */ + $repository = app(RuleRepository::class); + if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) + $repository->setUser(auth()->user()); } - ); + + return $repository; + }); } } diff --git a/app/Providers/SearchServiceProvider.php b/app/Providers/SearchServiceProvider.php index 7425d1cbc9..8afeefa9de 100644 --- a/app/Providers/SearchServiceProvider.php +++ b/app/Providers/SearchServiceProvider.php @@ -39,7 +39,9 @@ class SearchServiceProvider extends ServiceProvider /** * Bootstrap the application services. */ - public function boot(): void {} + public function boot(): void + { + } /** * Register the application services. @@ -47,20 +49,16 @@ class SearchServiceProvider extends ServiceProvider #[Override] public function register(): void { - $this->app->bind( - static fn (): QueryParserInterface => app(QueryParser::class) - ); + $this->app->bind(static fn(): QueryParserInterface => app(QueryParser::class)); - $this->app->bind( - static function (Application $app): SearchInterface { - /** @var OperatorQuerySearch $search */ - $search = app(OperatorQuerySearch::class); - if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) - $search->setUser(auth()->user()); - } - - return $search; + $this->app->bind(static function (Application $app): SearchInterface { + /** @var OperatorQuerySearch $search */ + $search = app(OperatorQuerySearch::class); + if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) + $search->setUser(auth()->user()); } - ); + + return $search; + }); } } diff --git a/app/Providers/TagServiceProvider.php b/app/Providers/TagServiceProvider.php index 85b9b85cfe..843a801e9b 100644 --- a/app/Providers/TagServiceProvider.php +++ b/app/Providers/TagServiceProvider.php @@ -39,7 +39,9 @@ class TagServiceProvider extends ServiceProvider /** * Bootstrap the application services. */ - public function boot(): void {} + public function boot(): void + { + } /** * Register the application services. @@ -47,30 +49,26 @@ class TagServiceProvider extends ServiceProvider #[Override] public function register(): void { - $this->app->bind( - static function (Application $app): TagRepositoryInterface { - /** @var TagRepository $repository */ - $repository = app(TagRepository::class); + $this->app->bind(static function (Application $app): TagRepositoryInterface { + /** @var TagRepository $repository */ + $repository = app(TagRepository::class); - if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) - $repository->setUser(auth()->user()); - } - - return $repository; + if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) + $repository->setUser(auth()->user()); } - ); - $this->app->bind( - static function (Application $app): OperationsRepositoryInterface { - /** @var OperationsRepository $repository */ - $repository = app(OperationsRepository::class); + return $repository; + }); - if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) - $repository->setUser(auth()->user()); - } + $this->app->bind(static function (Application $app): OperationsRepositoryInterface { + /** @var OperationsRepository $repository */ + $repository = app(OperationsRepository::class); - return $repository; + if ($app->auth->check()) { // @phpstan-ignore-line (phpstan does not understand the reference to auth) + $repository->setUser(auth()->user()); } - ); + + return $repository; + }); } } diff --git a/app/Repositories/Account/AccountRepository.php b/app/Repositories/Account/AccountRepository.php index f41f2bf590..228df9b904 100644 --- a/app/Repositories/Account/AccountRepository.php +++ b/app/Repositories/Account/AccountRepository.php @@ -61,7 +61,7 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac /** * Moved here from account CRUD. */ - public function destroy(Account $account, ?Account $moveTo): bool + public function destroy(Account $account, null|Account $moveTo): bool { /** @var AccountDestroyService $service */ $service = app(AccountDestroyService::class); @@ -79,9 +79,11 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac /** @var Account $account */ foreach ($accounts as $account) { - $byName = $this->user->accounts()->where('name', $account->name) - ->where('id', '!=', $account->id)->first() - ; + $byName = $this->user + ->accounts() + ->where('name', $account->name) + ->where('id', '!=', $account->id) + ->first(); if (null !== $byName) { $result->push($account); $result->push($byName); @@ -89,9 +91,11 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac continue; } if (null !== $account->iban) { - $byIban = $this->user->accounts()->where('iban', $account->iban) - ->where('id', '!=', $account->id)->first() - ; + $byIban = $this->user + ->accounts() + ->where('iban', $account->iban) + ->where('id', '!=', $account->id) + ->first(); if (null !== $byIban) { $result->push($account); $result->push($byIban); @@ -105,20 +109,17 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac return $result; } - public function findByAccountNumber(string $number, array $types): ?Account + public function findByAccountNumber(string $number, array $types): null|Account { $dbQuery = $this->user ->accounts() ->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id') ->where('accounts.active', true) - ->where( - static function (EloquentBuilder $q1) use ($number): void { - $json = json_encode($number); - $q1->where('account_meta.name', '=', 'account_number'); - $q1->where('account_meta.data', '=', $json); - } - ) - ; + ->where(static function (EloquentBuilder $q1) use ($number): void { + $json = json_encode($number); + $q1->where('account_meta.name', '=', 'account_number'); + $q1->where('account_meta.data', '=', $json); + }); if (0 !== count($types)) { $dbQuery->leftJoin('account_types', 'accounts.account_type_id', '=', 'account_types.id'); @@ -129,10 +130,13 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac return $dbQuery->first(['accounts.*']); } - public function findByIbanNull(string $iban, array $types): ?Account + public function findByIbanNull(string $iban, array $types): null|Account { $iban = Steam::filterSpaces($iban); - $query = $this->user->accounts()->where('iban', '!=', '')->whereNotNull('iban'); + $query = $this->user + ->accounts() + ->where('iban', '!=', '') + ->whereNotNull('iban'); if (0 !== count($types)) { $query->leftJoin('account_types', 'accounts.account_type_id', '=', 'account_types.id'); @@ -143,9 +147,9 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac return $query->where('iban', $iban)->first(['accounts.*']); } - public function findByName(string $name, array $types): ?Account + public function findByName(string $name, array $types): null|Account { - $query = $this->user->accounts(); + $query = $this->user->accounts(); if (0 !== count($types)) { $query->leftJoin('account_types', 'accounts.account_type_id', '=', 'account_types.id'); @@ -170,7 +174,7 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac /** * Return account type or null if not found. */ - public function getAccountTypeByType(string $type): ?AccountType + public function getAccountTypeByType(string $type): null|AccountType { return AccountType::whereType(ucfirst($type))->first(); } @@ -191,14 +195,14 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac public function getActiveAccountsByType(array $types): Collection { - $query = $this->user->accounts()->with( - [ // @phpstan-ignore-line + $query = $this->user + ->accounts() + ->with([ // @phpstan-ignore-line 'accountmeta' => static function (HasMany $query): void { $query->where('name', 'account_role'); }, - 'attachments', - ] - ); + 'attachments' + ]); if (0 !== count($types)) { $query->accountTypeIn($types); } @@ -212,20 +216,18 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac public function getAttachments(Account $account): Collection { - $set = $account->attachments()->get(); + $set = $account->attachments()->get(); /** @var Storage $disk */ $disk = Storage::disk('upload'); - return $set->each( - static function (Attachment $attachment) use ($disk): Attachment { // @phpstan-ignore-line - $notes = $attachment->notes()->first(); - $attachment->file_exists = $disk->exists($attachment->fileName()); - $attachment->notes_text = null !== $notes ? $notes->text : ''; + return $set->each(static function (Attachment $attachment) use ($disk): Attachment { // @phpstan-ignore-line + $notes = $attachment->notes()->first(); + $attachment->file_exists = $disk->exists($attachment->fileName()); + $attachment->notes_text = null !== $notes ? $notes->text : ''; - return $attachment; - } - ); + return $attachment; + }); } /** @@ -234,7 +236,7 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac public function getCashAccount(): Account { /** @var AccountType $type */ - $type = AccountType::where('type', AccountTypeEnum::CASH->value)->first(); + $type = AccountType::where('type', AccountTypeEnum::CASH->value)->first(); /** @var AccountFactory $factory */ $factory = app(AccountFactory::class); @@ -243,26 +245,23 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac return $factory->findOrCreate('Cash account', $type->type); } - public function getCreditTransactionGroup(Account $account): ?TransactionGroup + public function getCreditTransactionGroup(Account $account): null|TransactionGroup { $journal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->where('transactions.account_id', $account->id) ->transactionTypes([TransactionTypeEnum::LIABILITY_CREDIT->value]) - ->first(['transaction_journals.*']) - ; + ->first(['transaction_journals.*']); return $journal?->transactionGroup; } public function getInactiveAccountsByType(array $types): Collection { - $query = $this->user->accounts()->with( - [ // @phpstan-ignore-line - 'accountmeta' => static function (HasMany $query): void { - $query->where('name', 'account_role'); - }, - ] - ); + $query = $this->user + ->accounts() + ->with(['accountmeta' => static function (HasMany $query): void { // @phpstan-ignore-line + $query->where('name', 'account_role'); + }]); if (0 !== count($types)) { $query->accountTypeIn($types); } @@ -274,7 +273,7 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac return $query->get(['accounts.*']); } - public function getLocation(Account $account): ?Location + public function getLocation(Account $account): null|Location { /** @var null|Location */ return $account->locations()->first(); @@ -283,7 +282,7 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac /** * Get note text or null. */ - public function getNoteText(Account $account): ?string + public function getNoteText(Account $account): null|string { return $account->notes()->first()?->text; } @@ -291,13 +290,12 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac /** * Returns the amount of the opening balance for this account. */ - public function getOpeningBalanceAmount(Account $account, bool $convertToPrimary): ?string + public function getOpeningBalanceAmount(Account $account, bool $convertToPrimary): null|string { - $journal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') + $journal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->where('transactions.account_id', $account->id) ->transactionTypes([TransactionTypeEnum::OPENING_BALANCE->value, TransactionTypeEnum::LIABILITY_CREDIT->value]) - ->first(['transaction_journals.*']) - ; + ->first(['transaction_journals.*']); if (null === $journal) { return null; } @@ -315,29 +313,28 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac /** * Return date of opening balance as string or null. */ - public function getOpeningBalanceDate(Account $account): ?string + public function getOpeningBalanceDate(Account $account): null|string { return TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->where('transactions.account_id', $account->id) ->transactionTypes([TransactionTypeEnum::OPENING_BALANCE->value, TransactionTypeEnum::LIABILITY_CREDIT->value]) - ->first(['transaction_journals.*'])?->date->format('Y-m-d H:i:s') - ; + ->first(['transaction_journals.*']) + ?->date->format('Y-m-d H:i:s'); } - public function getOpeningBalanceGroup(Account $account): ?TransactionGroup + public function getOpeningBalanceGroup(Account $account): null|TransactionGroup { $journal = $this->getOpeningBalance($account); return $journal?->transactionGroup; } - public function getOpeningBalance(Account $account): ?TransactionJournal + public function getOpeningBalance(Account $account): null|TransactionJournal { return TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->where('transactions.account_id', $account->id) ->transactionTypes([TransactionTypeEnum::OPENING_BALANCE->value]) - ->first(['transaction_journals.*']) - ; + ->first(['transaction_journals.*']); } public function getPiggyBanks(Account $account): Collection @@ -348,47 +345,48 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac /** * @throws FireflyException */ - public function getReconciliation(Account $account): ?Account + public function getReconciliation(Account $account): null|Account { if (AccountTypeEnum::ASSET->value !== $account->accountType->type) { throw new FireflyException(sprintf('%s is not an asset account.', $account->name)); } $currency = $this->getAccountCurrency($account) ?? Amount::getPrimaryCurrency(); - $name = trans('firefly.reconciliation_account_name', ['name' => $account->name, 'currency' => $currency->code]); + $name = trans('firefly.reconciliation_account_name', ['name' => $account->name, 'currency' => $currency->code]); /** @var AccountType $type */ - $type = AccountType::where('type', AccountTypeEnum::RECONCILIATION->value)->first(); + $type = AccountType::where('type', AccountTypeEnum::RECONCILIATION->value)->first(); /** @var null|Account $current */ - $current = $this->user->accounts()->where('account_type_id', $type->id) + $current = $this->user + ->accounts() + ->where('account_type_id', $type->id) ->where('name', $name) - ->first() - ; + ->first(); if (null !== $current) { return $current; } - $data = [ + $data = [ 'account_type_id' => null, 'account_type_name' => AccountTypeEnum::RECONCILIATION->value, 'active' => true, 'name' => $name, 'currency_id' => $currency->id, - 'currency_code' => $currency->code, + 'currency_code' => $currency->code ]; /** @var AccountFactory $factory */ - $factory = app(AccountFactory::class); + $factory = app(AccountFactory::class); $factory->setUser($account->user); return $factory->create($data); } - public function getAccountCurrency(Account $account): ?TransactionCurrency + public function getAccountCurrency(Account $account): null|TransactionCurrency { - $type = $account->accountType->type; - $list = config('firefly.valid_currency_account_types'); + $type = $account->accountType->type; + $list = config('firefly.valid_currency_account_types'); // return null if not in this list. if (!in_array($type, $list, true)) { @@ -405,11 +403,9 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac /** * Return meta value for account. Null if not found. */ - public function getMetaValue(Account $account, string $field): ?string + public function getMetaValue(Account $account, string $field): null|string { - $result = $account->accountMeta->filter( - static fn (AccountMeta $meta): bool => strtolower($meta->name) === strtolower($field) - ); + $result = $account->accountMeta->filter(static fn(AccountMeta $meta): bool => strtolower($meta->name) === strtolower($field)); if (0 === $result->count()) { return null; } @@ -422,10 +418,13 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac public function count(array $types): int { - return $this->user->accounts()->accountTypeIn($types)->count(); + return $this->user + ->accounts() + ->accountTypeIn($types) + ->count(); } - public function find(int $accountId): ?Account + public function find(int $accountId): null|Account { /** @var null|Account */ return $this->user->accounts()->find($accountId); @@ -445,18 +444,37 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac public function isLiability(Account $account): bool { - return in_array($account->accountType->type, [AccountTypeEnum::CREDITCARD->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value], true); + return in_array( + $account->accountType->type, + [AccountTypeEnum::CREDITCARD->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value], + true + ); } public function maxOrder(string $type): int { - $sets = [ + $sets = [ AccountTypeEnum::ASSET->value => [AccountTypeEnum::DEFAULT->value, AccountTypeEnum::ASSET->value], AccountTypeEnum::EXPENSE->value => [AccountTypeEnum::EXPENSE->value, AccountTypeEnum::BENEFICIARY->value], AccountTypeEnum::REVENUE->value => [AccountTypeEnum::REVENUE->value], - AccountTypeEnum::LOAN->value => [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::CREDITCARD->value, AccountTypeEnum::MORTGAGE->value], - AccountTypeEnum::DEBT->value => [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::CREDITCARD->value, AccountTypeEnum::MORTGAGE->value], - AccountTypeEnum::MORTGAGE->value => [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::CREDITCARD->value, AccountTypeEnum::MORTGAGE->value], + AccountTypeEnum::LOAN->value => [ + AccountTypeEnum::LOAN->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::CREDITCARD->value, + AccountTypeEnum::MORTGAGE->value + ], + AccountTypeEnum::DEBT->value => [ + AccountTypeEnum::LOAN->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::CREDITCARD->value, + AccountTypeEnum::MORTGAGE->value + ], + AccountTypeEnum::MORTGAGE->value => [ + AccountTypeEnum::LOAN->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::CREDITCARD->value, + AccountTypeEnum::MORTGAGE->value + ] ]; if (array_key_exists(ucfirst($type), $sets)) { $order = (int) $this->getAccountsByType($sets[ucfirst($type)])->max('order'); @@ -464,18 +482,28 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac return $order; } - $specials = [AccountTypeEnum::CASH->value, AccountTypeEnum::INITIAL_BALANCE->value, AccountTypeEnum::IMPORT->value, AccountTypeEnum::RECONCILIATION->value]; + $specials = [ + AccountTypeEnum::CASH->value, + AccountTypeEnum::INITIAL_BALANCE->value, + AccountTypeEnum::IMPORT->value, + AccountTypeEnum::RECONCILIATION->value + ]; - $order = (int) $this->getAccountsByType($specials)->max('order'); + $order = (int) $this->getAccountsByType($specials)->max('order'); Log::debug(sprintf('Return max order of "%s" set (specials!): %d', $type, $order)); return $order; } - public function getAccountsByType(array $types, ?array $sort = []): Collection + public function getAccountsByType(array $types, null|array $sort = []): Collection { - $res = array_intersect([AccountTypeEnum::ASSET->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value], $types); - $query = $this->user->accounts(); + $res = array_intersect([ + AccountTypeEnum::ASSET->value, + AccountTypeEnum::MORTGAGE->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::DEBT->value + ], $types); + $query = $this->user->accounts(); if (0 !== count($types)) { $query->accountTypeIn($types); } @@ -508,7 +536,7 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac /** * Returns the date of the very first transaction in this account. */ - public function oldestJournalDate(Account $account): ?Carbon + public function oldestJournalDate(Account $account): null|Carbon { $journal = $this->oldestJournal($account); @@ -518,17 +546,17 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac /** * Returns the date of the very first transaction in this account. */ - public function oldestJournal(Account $account): ?TransactionJournal + public function oldestJournal(Account $account): null|TransactionJournal { /** @var null|TransactionJournal $first */ - $first = $account->transactions() + $first = $account + ->transactions() ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->orderBy('transaction_journals.date', 'ASC') ->orderBy('transaction_journals.order', 'DESC') ->where('transaction_journals.user_id', $this->user->id) ->orderBy('transaction_journals.id', 'ASC') - ->first(['transaction_journals.id']) - ; + ->first(['transaction_journals.id']); if (null !== $first) { /** @var null|TransactionJournal */ return TransactionJournal::find($first->id); @@ -542,7 +570,8 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac { Log::debug(sprintf('periodCollection(#%d, %s, %s)', $account->id, $start->format('Y-m-d'), $end->format('Y-m-d'))); - return $account->transactions() + return $account + ->transactions() ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id') ->leftJoin('transaction_currencies', 'transaction_currencies.id', '=', 'transactions.transaction_currency_id') @@ -570,11 +599,9 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac 'transaction_journals.transaction_currency_id', 'transactions.amount', 'transactions.native_amount as pc_amount', - 'transactions.foreign_amount', + 'transactions.foreign_amount' ]) - ->toArray() - ; - + ->toArray(); } public function resetAccountOrder(): void @@ -583,7 +610,7 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac [AccountTypeEnum::DEFAULT->value, AccountTypeEnum::ASSET->value], // [AccountTypeEnum::EXPENSE->value, AccountTypeEnum::BENEFICIARY->value], // [AccountTypeEnum::REVENUE->value], - [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::CREDITCARD->value, AccountTypeEnum::MORTGAGE->value], + [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::CREDITCARD->value, AccountTypeEnum::MORTGAGE->value] // [AccountTypeEnum::CASH->value, AccountTypeEnum::INITIAL_BALANCE->value, AccountTypeEnum::IMPORT->value, AccountTypeEnum::RECONCILIATION->value], ]; foreach ($sets as $set) { @@ -604,11 +631,19 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac } } // reset the rest to zero. - $all = [AccountTypeEnum::DEFAULT->value, AccountTypeEnum::ASSET->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::CREDITCARD->value, AccountTypeEnum::MORTGAGE->value]; - $this->user->accounts()->leftJoin('account_types', 'account_types.id', '=', 'accounts.account_type_id') + $all = [ + AccountTypeEnum::DEFAULT->value, + AccountTypeEnum::ASSET->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::CREDITCARD->value, + AccountTypeEnum::MORTGAGE->value + ]; + $this->user + ->accounts() + ->leftJoin('account_types', 'account_types.id', '=', 'accounts.account_type_id') ->whereNotIn('account_types.type', $all) - ->update(['order' => 0]) - ; + ->update(['order' => 0]); } /** @@ -624,13 +659,13 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac public function searchAccount(string $query, array $types, int $limit): Collection { - $dbQuery = $this->user->accounts() + $dbQuery = $this->user + ->accounts() ->where('active', true) ->orderBy('accounts.order', 'ASC') ->orderBy('accounts.account_type_id', 'ASC') ->orderBy('accounts.name', 'ASC') - ->with(['accountType']) - ; + ->with(['accountType']); if ('' !== $query) { // split query on spaces just in case: $parts = explode(' ', $query); @@ -649,30 +684,27 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac public function searchAccountNr(string $query, array $types, int $limit): Collection { - $dbQuery = $this->user->accounts()->distinct() + $dbQuery = $this->user + ->accounts() + ->distinct() ->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id') ->where('accounts.active', true) ->orderBy('accounts.order', 'ASC') ->orderBy('accounts.account_type_id', 'ASC') ->orderBy('accounts.name', 'ASC') - ->with(['accountType', 'accountMeta']) - ; + ->with(['accountType', 'accountMeta']); if ('' !== $query) { // split query on spaces just in case: $parts = explode(' ', $query); foreach ($parts as $part) { $search = sprintf('%%%s%%', $part); - $dbQuery->where( - static function (EloquentBuilder $q1) use ($search): void { - $q1->whereLike('accounts.iban', $search); - $q1->orWhere( - static function (EloquentBuilder $q2) use ($search): void { - $q2->where('account_meta.name', '=', 'account_number'); - $q2->whereLike('account_meta.data', $search); - } - ); - } - ); + $dbQuery->where(static function (EloquentBuilder $q1) use ($search): void { + $q1->whereLike('accounts.iban', $search); + $q1->orWhere(static function (EloquentBuilder $q2) use ($search): void { + $q2->where('account_meta.name', '=', 'account_number'); + $q2->whereLike('account_meta.data', $search); + }); + }); } } if (0 !== count($types)) { diff --git a/app/Repositories/Account/AccountRepositoryInterface.php b/app/Repositories/Account/AccountRepositoryInterface.php index 43b3334f15..262e583b82 100644 --- a/app/Repositories/Account/AccountRepositoryInterface.php +++ b/app/Repositories/Account/AccountRepositoryInterface.php @@ -56,34 +56,34 @@ interface AccountRepositoryInterface /** * Moved here from account CRUD. */ - public function destroy(Account $account, ?Account $moveTo): bool; + public function destroy(Account $account, null|Account $moveTo): bool; /** * Find account with same name OR same IBAN or both, but not the same type or ID. */ public function expandWithDoubles(Collection $accounts): Collection; - public function find(int $accountId): ?Account; + public function find(int $accountId): null|Account; - public function findByAccountNumber(string $number, array $types): ?Account; + public function findByAccountNumber(string $number, array $types): null|Account; - public function findByIbanNull(string $iban, array $types): ?Account; + public function findByIbanNull(string $iban, array $types): null|Account; - public function findByName(string $name, array $types): ?Account; + public function findByName(string $name, array $types): null|Account; - public function getAccountCurrency(Account $account): ?TransactionCurrency; + public function getAccountCurrency(Account $account): null|TransactionCurrency; /** * Return account type or null if not found. */ - public function getAccountTypeByType(string $type): ?AccountType; + public function getAccountTypeByType(string $type): null|AccountType; public function getAccountsById(array $accountIds): Collection; /** * @param array $types */ - public function getAccountsByType(array $types, ?array $sort = []): Collection; + public function getAccountsByType(array $types, null|array $sort = []): Collection; public function getActiveAccountsByType(array $types): Collection; @@ -91,45 +91,45 @@ interface AccountRepositoryInterface public function getCashAccount(): Account; - public function getCreditTransactionGroup(Account $account): ?TransactionGroup; + public function getCreditTransactionGroup(Account $account): null|TransactionGroup; public function getInactiveAccountsByType(array $types): Collection; /** * Get account location, if any. */ - public function getLocation(Account $account): ?Location; + public function getLocation(Account $account): null|Location; /** * Return meta value for account. Null if not found. */ - public function getMetaValue(Account $account, string $field): ?string; + public function getMetaValue(Account $account, string $field): null|string; /** * Get note text or null. */ - public function getNoteText(Account $account): ?string; + public function getNoteText(Account $account): null|string; - public function getOpeningBalance(Account $account): ?TransactionJournal; + public function getOpeningBalance(Account $account): null|TransactionJournal; /** * Returns the amount of the opening balance for this account. */ - public function getOpeningBalanceAmount(Account $account, bool $convertToPrimary): ?string; + public function getOpeningBalanceAmount(Account $account, bool $convertToPrimary): null|string; /** * Return date of opening balance as string or null. */ - public function getOpeningBalanceDate(Account $account): ?string; + public function getOpeningBalanceDate(Account $account): null|string; - public function getOpeningBalanceGroup(Account $account): ?TransactionGroup; + public function getOpeningBalanceGroup(Account $account): null|TransactionGroup; public function getPiggyBanks(Account $account): Collection; /** * Find or create the opposing reconciliation account. */ - public function getReconciliation(Account $account): ?Account; + public function getReconciliation(Account $account): null|Account; public function getUsedCurrencies(Account $account): Collection; @@ -140,12 +140,12 @@ interface AccountRepositoryInterface /** * Returns the date of the very first transaction in this account. */ - public function oldestJournal(Account $account): ?TransactionJournal; + public function oldestJournal(Account $account): null|TransactionJournal; /** * Returns the date of the very first transaction in this account. */ - public function oldestJournalDate(Account $account): ?Carbon; + public function oldestJournalDate(Account $account): null|Carbon; public function periodCollection(Account $account, Carbon $start, Carbon $end): array; diff --git a/app/Repositories/Account/AccountTasker.php b/app/Repositories/Account/AccountTasker.php index 5c190ae18a..9461468db2 100644 --- a/app/Repositories/Account/AccountTasker.php +++ b/app/Repositories/Account/AccountTasker.php @@ -29,12 +29,12 @@ use FireflyIII\Exceptions\FireflyException; use FireflyIII\Helpers\Collector\GroupCollectorInterface; use FireflyIII\Models\Account; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; +use FireflyIII\Support\Facades\Amount; use FireflyIII\Support\Facades\Steam; use FireflyIII\Support\Repositories\UserGroup\UserGroupInterface; use FireflyIII\Support\Repositories\UserGroup\UserGroupTrait; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; -use FireflyIII\Support\Facades\Amount; /** * Class AccountTasker. @@ -48,29 +48,23 @@ class AccountTasker implements AccountTaskerInterface, UserGroupInterface */ public function getAccountReport(Collection $accounts, Carbon $start, Carbon $end): array { - $yesterday = clone $start; + $yesterday = clone $start; $yesterday->subDay()->endOfDay(); // exactly up until $start but NOT including. - $end->endOfDay(); // needs to be end of day to be correct. + $end->endOfDay(); // needs to be end of day to be correct. Log::debug(sprintf('getAccountReport: accountsBalancesInRange("%s", "%s")', $yesterday->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s'))); - [ - $startSet, - $endSet, - ] = Steam::accountsBalancesInRange($accounts, $yesterday, $end); + [$startSet, $endSet] = Steam::accountsBalancesInRange($accounts, $yesterday, $end); Log::debug('Start of accountreport'); /** @var AccountRepositoryInterface $repository */ $repository = app(AccountRepositoryInterface::class); $primaryCurrency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); - $return = [ - 'accounts' => [], - 'sums' => [], - ]; + $return = ['accounts' => [], 'sums' => []]; /** @var Account $account */ foreach ($accounts as $account) { - $id = $account->id; - $currency = $repository->getAccountCurrency($account) ?? $primaryCurrency; + $id = $account->id; + $currency = $repository->getAccountCurrency($account) ?? $primaryCurrency; $return['sums'][$currency->id] ??= [ 'start' => '0', 'end' => '0', @@ -79,32 +73,37 @@ class AccountTasker implements AccountTaskerInterface, UserGroupInterface 'currency_code' => $currency->code, 'currency_symbol' => $currency->symbol, 'currency_name' => $currency->name, - 'currency_decimal_places' => $currency->decimal_places, + 'currency_decimal_places' => $currency->decimal_places ]; - $entry = [ + $entry = [ 'name' => $account->name, 'id' => $account->id, 'currency_id' => $currency->id, 'currency_code' => $currency->code, 'currency_symbol' => $currency->symbol, 'currency_name' => $currency->name, - 'currency_decimal_places' => $currency->decimal_places, + 'currency_decimal_places' => $currency->decimal_places ]; // get first journal date: - $first = $repository->oldestJournal($account); - $entry['start_balance'] = $startSet[$account->id]['balance'] ?? '0'; - $entry['end_balance'] = $endSet[$account->id]['balance'] ?? '0'; + $first = $repository->oldestJournal($account); + $entry['start_balance'] = $startSet[$account->id]['balance'] ?? '0'; + $entry['end_balance'] = $endSet[$account->id]['balance'] ?? '0'; // first journal exists, and is on start, then this is the actual opening balance: if (null !== $first && $first->date->isSameDay($yesterday) && TransactionTypeEnum::OPENING_BALANCE->value === $first->transactionType->type) { Log::debug(sprintf('Date of first journal for %s is %s', $account->name, $first->date->format('Y-m-d'))); $entry['start_balance'] = $first->transactions()->where('account_id', $account->id)->first()->amount; - Log::debug(sprintf('Account %s was opened on %s, so opening balance is %f', $account->name, $yesterday->format('Y-m-d'), $entry['start_balance'])); + Log::debug(sprintf( + 'Account %s was opened on %s, so opening balance is %f', + $account->name, + $yesterday->format('Y-m-d'), + $entry['start_balance'] + )); } $return['sums'][$currency->id]['start'] = bcadd($return['sums'][$currency->id]['start'], (string) $entry['start_balance']); - $return['sums'][$currency->id]['end'] = bcadd($return['sums'][$currency->id]['end'], $entry['end_balance']); - $return['accounts'][$id] = $entry; + $return['sums'][$currency->id]['end'] = bcadd($return['sums'][$currency->id]['end'], $entry['end_balance']); + $return['accounts'][$id] = $entry; } foreach (array_keys($return['sums']) as $index) { @@ -129,13 +128,13 @@ class AccountTasker implements AccountTaskerInterface, UserGroupInterface $collector->setSourceAccounts($accounts)->setRange($start, $end); $collector->excludeDestinationAccounts($accounts); $collector->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::TRANSFER->value])->withAccountInformation(); - $journals = $collector->getExtractedJournals(); + $journals = $collector->getExtractedJournals(); - $report = $this->groupExpenseByDestination($journals); + $report = $this->groupExpenseByDestination($journals); // sort the result // Obtain a list of columns - $sum = []; + $sum = []; foreach ($report['accounts'] as $accountId => $row) { $sum[$accountId] = (float) $row['sum']; // intentional float } @@ -150,19 +149,16 @@ class AccountTasker implements AccountTaskerInterface, UserGroupInterface $primaryCurrency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); /** @var CurrencyRepositoryInterface $currencyRepos */ - $currencyRepos = app(CurrencyRepositoryInterface::class); - $currencies = [$primaryCurrency->id => $primaryCurrency]; - $report = [ - 'accounts' => [], - 'sums' => [], - ]; + $currencyRepos = app(CurrencyRepositoryInterface::class); + $currencies = [$primaryCurrency->id => $primaryCurrency]; + $report = ['accounts' => [], 'sums' => []]; /** @var array $journal */ foreach ($array as $journal) { - $sourceId = (int) $journal['destination_account_id']; - $currencyId = (int) $journal['currency_id']; - $key = sprintf('%s-%s', $sourceId, $currencyId); - $currencies[$currencyId] ??= $currencyRepos->find($currencyId); + $sourceId = (int) $journal['destination_account_id']; + $currencyId = (int) $journal['currency_id']; + $key = sprintf('%s-%s', $sourceId, $currencyId); + $currencies[$currencyId] ??= $currencyRepos->find($currencyId); $report['accounts'][$key] ??= [ 'id' => $sourceId, 'name' => $journal['destination_account_name'], @@ -173,7 +169,7 @@ class AccountTasker implements AccountTaskerInterface, UserGroupInterface 'currency_name' => $currencies[$currencyId]->name, 'currency_symbol' => $currencies[$currencyId]->symbol, 'currency_code' => $currencies[$currencyId]->code, - 'currency_decimal_places' => $currencies[$currencyId]->decimal_places, + 'currency_decimal_places' => $currencies[$currencyId]->decimal_places ]; $report['accounts'][$key]['sum'] = bcadd($report['accounts'][$key]['sum'], (string) $journal['amount']); @@ -187,14 +183,14 @@ class AccountTasker implements AccountTaskerInterface, UserGroupInterface if ($report['accounts'][$key]['count'] > 1) { $report['accounts'][$key]['average'] = bcdiv($report['accounts'][$key]['sum'], (string) $report['accounts'][$key]['count']); } - $currencyId = $report['accounts'][$key]['currency_id']; + $currencyId = $report['accounts'][$key]['currency_id']; $report['sums'][$currencyId] ??= [ 'sum' => '0', 'currency_id' => $report['accounts'][$key]['currency_id'], 'currency_name' => $report['accounts'][$key]['currency_name'], 'currency_symbol' => $report['accounts'][$key]['currency_symbol'], 'currency_code' => $report['accounts'][$key]['currency_code'], - 'currency_decimal_places' => $report['accounts'][$key]['currency_decimal_places'], + 'currency_decimal_places' => $report['accounts'][$key]['currency_decimal_places'] ]; $report['sums'][$currencyId]['sum'] = bcadd($report['sums'][$currencyId]['sum'], $report['accounts'][$key]['sum']); } @@ -216,11 +212,11 @@ class AccountTasker implements AccountTaskerInterface, UserGroupInterface $collector->setDestinationAccounts($accounts)->setRange($start, $end); $collector->excludeSourceAccounts($accounts); $collector->setTypes([TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value])->withAccountInformation(); - $report = $this->groupIncomeBySource($collector->getExtractedJournals()); + $report = $this->groupIncomeBySource($collector->getExtractedJournals()); // sort the result // Obtain a list of columns - $sum = []; + $sum = []; foreach ($report['accounts'] as $accountId => $row) { $sum[$accountId] = (float) $row['sum']; // intentional float } @@ -235,18 +231,15 @@ class AccountTasker implements AccountTaskerInterface, UserGroupInterface $primaryCurrency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); /** @var CurrencyRepositoryInterface $currencyRepos */ - $currencyRepos = app(CurrencyRepositoryInterface::class); - $currencies = [$primaryCurrency->id => $primaryCurrency]; - $report = [ - 'accounts' => [], - 'sums' => [], - ]; + $currencyRepos = app(CurrencyRepositoryInterface::class); + $currencies = [$primaryCurrency->id => $primaryCurrency]; + $report = ['accounts' => [], 'sums' => []]; /** @var array $journal */ foreach ($array as $journal) { - $sourceId = (int) $journal['source_account_id']; - $currencyId = (int) $journal['currency_id']; - $key = sprintf('%s-%s', $sourceId, $currencyId); + $sourceId = (int) $journal['source_account_id']; + $currencyId = (int) $journal['currency_id']; + $key = sprintf('%s-%s', $sourceId, $currencyId); if (!array_key_exists($key, $report['accounts'])) { $currencies[$currencyId] ??= $currencyRepos->find($currencyId); $report['accounts'][$key] = [ @@ -259,7 +252,7 @@ class AccountTasker implements AccountTaskerInterface, UserGroupInterface 'currency_name' => $currencies[$currencyId]->name, 'currency_symbol' => $currencies[$currencyId]->symbol, 'currency_code' => $currencies[$currencyId]->code, - 'currency_decimal_places' => $currencies[$currencyId]->decimal_places, + 'currency_decimal_places' => $currencies[$currencyId]->decimal_places ]; } $report['accounts'][$key]['sum'] = bcadd($report['accounts'][$key]['sum'], bcmul((string) $journal['amount'], '-1')); @@ -271,14 +264,14 @@ class AccountTasker implements AccountTaskerInterface, UserGroupInterface if ($report['accounts'][$key]['count'] > 1) { $report['accounts'][$key]['average'] = bcdiv($report['accounts'][$key]['sum'], (string) $report['accounts'][$key]['count']); } - $currencyId = $report['accounts'][$key]['currency_id']; + $currencyId = $report['accounts'][$key]['currency_id']; $report['sums'][$currencyId] ??= [ 'sum' => '0', 'currency_id' => $report['accounts'][$key]['currency_id'], 'currency_name' => $report['accounts'][$key]['currency_name'], 'currency_symbol' => $report['accounts'][$key]['currency_symbol'], 'currency_code' => $report['accounts'][$key]['currency_code'], - 'currency_decimal_places' => $report['accounts'][$key]['currency_decimal_places'], + 'currency_decimal_places' => $report['accounts'][$key]['currency_decimal_places'] ]; $report['sums'][$currencyId]['sum'] = bcadd($report['sums'][$currencyId]['sum'], $report['accounts'][$key]['sum']); } diff --git a/app/Repositories/Account/OperationsRepository.php b/app/Repositories/Account/OperationsRepository.php index 71aebb11a3..e1e6814042 100644 --- a/app/Repositories/Account/OperationsRepository.php +++ b/app/Repositories/Account/OperationsRepository.php @@ -71,19 +71,19 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn { $array = []; foreach ($journals as $journal) { - $currencyId = (int) $journal['currency_id']; - $journalId = (int) $journal['transaction_journal_id']; + $currencyId = (int) $journal['currency_id']; + $journalId = (int) $journal['transaction_journal_id']; $array[$currencyId] ??= [ 'currency_id' => $journal['currency_id'], 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_code' => $journal['currency_code'], 'currency_decimal_places' => $journal['currency_decimal_places'], - 'transaction_journals' => [], + 'transaction_journals' => [] ]; $array[$currencyId]['transaction_journals'][$journalId] = [ - 'amount' => Steam::{$direction}((string) $journal['amount']), // @phpstan-ignore-line + 'amount' => Steam::{$direction}((string) $journal['amount']), // @phpstan-ignore-line 'date' => $journal['date'], 'transaction_journal_id' => $journalId, 'budget_name' => $journal['budget_name'], @@ -96,7 +96,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'destination_account_iban' => $journal['destination_account_iban'], 'tags' => $journal['tags'], 'description' => $journal['description'], - 'transaction_group_id' => $journal['transaction_group_id'], + 'transaction_group_id' => $journal['transaction_group_id'] ]; } @@ -108,7 +108,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn * which have the specified accounts. It's grouped per currency, with as few details in the array * as possible. Amounts are always positive. */ - public function listIncome(Carbon $start, Carbon $end, ?Collection $accounts = null): array + public function listIncome(Carbon $start, Carbon $end, null|Collection $accounts = null): array { $journals = $this->getTransactions($start, $end, $accounts, TransactionTypeEnum::DEPOSIT->value); @@ -119,11 +119,11 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn * @SuppressWarnings("PHPMD.ExcessiveParameterList") */ public function sumExpenses( - Carbon $start, - Carbon $end, - ?Collection $accounts = null, - ?Collection $expense = null, - ?TransactionCurrency $currency = null + Carbon $start, + Carbon $end, + null|Collection $accounts = null, + null|Collection $expense = null, + null|TransactionCurrency $currency = null ): array { $journals = $this->getTransactionsForSum(TransactionTypeEnum::WITHDRAWAL->value, $start, $end, $accounts, $expense, $currency); @@ -135,12 +135,12 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn * @SuppressWarnings("PHPMD.NPathComplexity") */ private function getTransactionsForSum( - string $type, - Carbon $start, - Carbon $end, - ?Collection $accounts = null, - ?Collection $opposing = null, - ?TransactionCurrency $currency = null + string $type, + Carbon $start, + Carbon $end, + null|Collection $accounts = null, + null|Collection $opposing = null, + null|TransactionCurrency $currency = null ): array { $start->startOfDay(); $end->endOfDay(); @@ -174,15 +174,13 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn if ($currency instanceof TransactionCurrency) { $collector->setCurrency($currency); } - $journals = $collector->getExtractedJournals(); + $journals = $collector->getExtractedJournals(); // same but for foreign currencies: if ($currency instanceof TransactionCurrency) { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); - $collector->setUser($this->user)->setRange($start, $end)->setTypes([$type])->withAccountInformation() - ->setForeignCurrency($currency) - ; + $collector->setUser($this->user)->setRange($start, $end)->setTypes([$type])->withAccountInformation()->setForeignCurrency($currency); if (TransactionTypeEnum::WITHDRAWAL->value === $type) { if ($accounts instanceof Collection) { $collector->setSourceAccounts($accounts); @@ -200,10 +198,10 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn } } - $result = $collector->getExtractedJournals(); + $result = $collector->getExtractedJournals(); // do not use array_merge because you want keys to overwrite (otherwise you get double results): - $journals = $result + $journals; + $journals = $result + $journals; } return $journals; @@ -220,11 +218,11 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn * @SuppressWarnings("PHPMD.ExcessiveParameterList") */ public function sumExpensesByDestination( - Carbon $start, - Carbon $end, - ?Collection $accounts = null, - ?Collection $expense = null, - ?TransactionCurrency $currency = null + Carbon $start, + Carbon $end, + null|Collection $accounts = null, + null|Collection $expense = null, + null|TransactionCurrency $currency = null ): array { $journals = $this->getTransactionsForSum(TransactionTypeEnum::WITHDRAWAL->value, $start, $end, $accounts, $expense, $currency); @@ -242,11 +240,11 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn * @SuppressWarnings("PHPMD.ExcessiveParameterList") */ public function sumExpensesBySource( - Carbon $start, - Carbon $end, - ?Collection $accounts = null, - ?Collection $expense = null, - ?TransactionCurrency $currency = null + Carbon $start, + Carbon $end, + null|Collection $accounts = null, + null|Collection $expense = null, + null|TransactionCurrency $currency = null ): array { $journals = $this->getTransactionsForSum(TransactionTypeEnum::WITHDRAWAL->value, $start, $end, $accounts, $expense, $currency); @@ -257,11 +255,11 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn * @SuppressWarnings("PHPMD.ExcessiveParameterList") */ public function sumIncome( - Carbon $start, - Carbon $end, - ?Collection $accounts = null, - ?Collection $revenue = null, - ?TransactionCurrency $currency = null + Carbon $start, + Carbon $end, + null|Collection $accounts = null, + null|Collection $revenue = null, + null|TransactionCurrency $currency = null ): array { $journals = $this->getTransactionsForSum(TransactionTypeEnum::DEPOSIT->value, $start, $end, $accounts, $revenue, $currency); @@ -272,11 +270,11 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn * @SuppressWarnings("PHPMD.ExcessiveParameterList") */ public function sumIncomeByDestination( - Carbon $start, - Carbon $end, - ?Collection $accounts = null, - ?Collection $revenue = null, - ?TransactionCurrency $currency = null + Carbon $start, + Carbon $end, + null|Collection $accounts = null, + null|Collection $revenue = null, + null|TransactionCurrency $currency = null ): array { $journals = $this->getTransactionsForSum(TransactionTypeEnum::DEPOSIT->value, $start, $end, $accounts, $revenue, $currency); @@ -287,18 +285,18 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn * @SuppressWarnings("PHPMD.ExcessiveParameterList") */ public function sumIncomeBySource( - Carbon $start, - Carbon $end, - ?Collection $accounts = null, - ?Collection $revenue = null, - ?TransactionCurrency $currency = null + Carbon $start, + Carbon $end, + null|Collection $accounts = null, + null|Collection $revenue = null, + null|TransactionCurrency $currency = null ): array { $journals = $this->getTransactionsForSum(TransactionTypeEnum::DEPOSIT->value, $start, $end, $accounts, $revenue, $currency); return $this->groupByDirection($journals, 'source', 'positive'); } - public function sumTransfers(Carbon $start, Carbon $end, ?Collection $accounts = null, ?TransactionCurrency $currency = null): array + public function sumTransfers(Carbon $start, Carbon $end, null|Collection $accounts = null, null|TransactionCurrency $currency = null): array { $journals = $this->getTransactionsForSum(TransactionTypeEnum::TRANSFER->value, $start, $end, $accounts, null, $currency); @@ -313,12 +311,12 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn foreach ($journals as $journal) { $return = $this->groupByEitherJournal($return, $journal); } - $final = []; + $final = []; foreach ($return as $array) { $array['difference_float'] = (float) $array['difference']; - $array['in_float'] = (float) $array['in']; - $array['out_float'] = (float) $array['out']; - $final[] = $array; + $array['in_float'] = (float) $array['in']; + $array['out_float'] = (float) $array['out']; + $final[] = $array; } return $final; @@ -326,12 +324,12 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn private function groupByEitherJournal(array $return, array $journal): array { - $sourceId = $journal['source_account_id']; - $destinationId = $journal['destination_account_id']; - $currencyId = $journal['currency_id']; - $sourceKey = sprintf('%d-%d', $currencyId, $sourceId); - $destKey = sprintf('%d-%d', $currencyId, $destinationId); - $amount = Steam::positive($journal['amount']); + $sourceId = $journal['source_account_id']; + $destinationId = $journal['destination_account_id']; + $currencyId = $journal['currency_id']; + $sourceKey = sprintf('%d-%d', $currencyId, $sourceId); + $destKey = sprintf('%d-%d', $currencyId, $destinationId); + $amount = Steam::positive($journal['amount']); // source first $return[$sourceKey] ??= [ @@ -344,11 +342,11 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'out' => '0', 'out_float' => 0, 'currency_id' => (string) $currencyId, - 'currency_code' => $journal['currency_code'], + 'currency_code' => $journal['currency_code'] ]; // dest next: - $return[$destKey] ??= [ + $return[$destKey] ??= [ 'id' => (string) $destinationId, 'name' => $journal['destination_account_name'], 'difference' => '0', @@ -358,23 +356,23 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'out' => '0', 'out_float' => 0, 'currency_id' => (string) $currencyId, - 'currency_code' => $journal['currency_code'], + 'currency_code' => $journal['currency_code'] ]; // source account? money goes out! - $return[$sourceKey]['out'] = bcadd((string) $return[$sourceKey]['out'], Steam::negative($amount)); + $return[$sourceKey]['out'] = bcadd((string) $return[$sourceKey]['out'], Steam::negative($amount)); $return[$sourceKey]['difference'] = bcadd($return[$sourceKey]['out'], (string) $return[$sourceKey]['in']); // destination account? money comes in: - $return[$destKey]['in'] = bcadd((string) $return[$destKey]['in'], $amount); - $return[$destKey]['difference'] = bcadd((string) $return[$destKey]['out'], $return[$destKey]['in']); + $return[$destKey]['in'] = bcadd((string) $return[$destKey]['in'], $amount); + $return[$destKey]['difference'] = bcadd((string) $return[$destKey]['out'], $return[$destKey]['in']); // foreign currency if (null !== $journal['foreign_currency_id'] && null !== $journal['foreign_amount']) { - $currencyId = $journal['foreign_currency_id']; - $sourceKey = sprintf('%d-%d', $currencyId, $sourceId); - $destKey = sprintf('%d-%d', $currencyId, $destinationId); - $amount = Steam::positive($journal['foreign_amount']); + $currencyId = $journal['foreign_currency_id']; + $sourceKey = sprintf('%d-%d', $currencyId, $sourceId); + $destKey = sprintf('%d-%d', $currencyId, $destinationId); + $amount = Steam::positive($journal['foreign_amount']); // same as above: // source first @@ -388,11 +386,11 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'out' => '0', 'out_float' => 0, 'currency_id' => (string) $currencyId, - 'currency_code' => $journal['foreign_currency_code'], + 'currency_code' => $journal['foreign_currency_code'] ]; // dest next: - $return[$destKey] ??= [ + $return[$destKey] ??= [ 'id' => (string) $destinationId, 'name' => $journal['destination_account_name'], 'difference' => '0', @@ -402,15 +400,15 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'out' => '0', 'out_float' => 0, 'currency_id' => (string) $currencyId, - 'currency_code' => $journal['foreign_currency_code'], + 'currency_code' => $journal['foreign_currency_code'] ]; // source account? money goes out! (same as above) - $return[$sourceKey]['out'] = bcadd((string) $return[$sourceKey]['out'], Steam::negative($amount)); + $return[$sourceKey]['out'] = bcadd((string) $return[$sourceKey]['out'], Steam::negative($amount)); $return[$sourceKey]['difference'] = bcadd($return[$sourceKey]['out'], (string) $return[$sourceKey]['in']); // destination account? money comes in: - $return[$destKey]['in'] = bcadd((string) $return[$destKey]['in'], $amount); - $return[$destKey]['difference'] = bcadd((string) $return[$destKey]['out'], $return[$destKey]['in']); + $return[$destKey]['in'] = bcadd((string) $return[$destKey]['in'], $amount); + $return[$destKey]['difference'] = bcadd((string) $return[$destKey]['out'], $return[$destKey]['in']); } return $return; diff --git a/app/Repositories/Account/OperationsRepositoryInterface.php b/app/Repositories/Account/OperationsRepositoryInterface.php index 3d8b973a6a..3989e2c659 100644 --- a/app/Repositories/Account/OperationsRepositoryInterface.php +++ b/app/Repositories/Account/OperationsRepositoryInterface.php @@ -56,7 +56,7 @@ interface OperationsRepositoryInterface * which have the specified accounts. It's grouped per currency, with as few details in the array * as possible. Amounts are always positive. */ - public function listIncome(Carbon $start, Carbon $end, ?Collection $accounts = null): array; + public function listIncome(Carbon $start, Carbon $end, null|Collection $accounts = null): array; /** * Sum of withdrawal journals in period for a set of accounts, grouped per currency. Amounts are always negative. @@ -64,11 +64,11 @@ interface OperationsRepositoryInterface * @SuppressWarnings("PHPMD.ExcessiveParameterList") */ public function sumExpenses( - Carbon $start, - Carbon $end, - ?Collection $accounts = null, - ?Collection $expense = null, - ?TransactionCurrency $currency = null + Carbon $start, + Carbon $end, + null|Collection $accounts = null, + null|Collection $expense = null, + null|TransactionCurrency $currency = null ): array; /** @@ -78,11 +78,11 @@ interface OperationsRepositoryInterface * @SuppressWarnings("PHPMD.ExcessiveParameterList") */ public function sumExpensesByDestination( - Carbon $start, - Carbon $end, - ?Collection $accounts = null, - ?Collection $expense = null, - ?TransactionCurrency $currency = null + Carbon $start, + Carbon $end, + null|Collection $accounts = null, + null|Collection $expense = null, + null|TransactionCurrency $currency = null ): array; /** @@ -92,11 +92,11 @@ interface OperationsRepositoryInterface * @SuppressWarnings("PHPMD.ExcessiveParameterList") */ public function sumExpensesBySource( - Carbon $start, - Carbon $end, - ?Collection $accounts = null, - ?Collection $expense = null, - ?TransactionCurrency $currency = null + Carbon $start, + Carbon $end, + null|Collection $accounts = null, + null|Collection $expense = null, + null|TransactionCurrency $currency = null ): array; /** @@ -105,11 +105,11 @@ interface OperationsRepositoryInterface * @SuppressWarnings("PHPMD.ExcessiveParameterList") */ public function sumIncome( - Carbon $start, - Carbon $end, - ?Collection $accounts = null, - ?Collection $revenue = null, - ?TransactionCurrency $currency = null + Carbon $start, + Carbon $end, + null|Collection $accounts = null, + null|Collection $revenue = null, + null|TransactionCurrency $currency = null ): array; /** @@ -119,11 +119,11 @@ interface OperationsRepositoryInterface * @SuppressWarnings("PHPMD.ExcessiveParameterList") */ public function sumIncomeByDestination( - Carbon $start, - Carbon $end, - ?Collection $accounts = null, - ?Collection $revenue = null, - ?TransactionCurrency $currency = null + Carbon $start, + Carbon $end, + null|Collection $accounts = null, + null|Collection $revenue = null, + null|TransactionCurrency $currency = null ): array; /** @@ -133,15 +133,15 @@ interface OperationsRepositoryInterface * @SuppressWarnings("PHPMD.ExcessiveParameterList") */ public function sumIncomeBySource( - Carbon $start, - Carbon $end, - ?Collection $accounts = null, - ?Collection $revenue = null, - ?TransactionCurrency $currency = null + Carbon $start, + Carbon $end, + null|Collection $accounts = null, + null|Collection $revenue = null, + null|TransactionCurrency $currency = null ): array; /** * Sum of transfers in period for a set of accounts, grouped per currency. Amounts are always positive. */ - public function sumTransfers(Carbon $start, Carbon $end, ?Collection $accounts = null, ?TransactionCurrency $currency = null): array; + public function sumTransfers(Carbon $start, Carbon $end, null|Collection $accounts = null, null|TransactionCurrency $currency = null): array; } diff --git a/app/Repositories/Attachment/AttachmentRepository.php b/app/Repositories/Attachment/AttachmentRepository.php index 079b4b61dd..08241fe624 100644 --- a/app/Repositories/Attachment/AttachmentRepository.php +++ b/app/Repositories/Attachment/AttachmentRepository.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace FireflyIII\Repositories\Attachment; -use Illuminate\Support\Facades\Log; use Exception; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Factory\AttachmentFactory; @@ -35,6 +34,7 @@ use FireflyIII\Support\Repositories\UserGroup\UserGroupTrait; use Illuminate\Contracts\Encryption\DecryptException; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Crypt; +use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Storage; use League\Flysystem\UnableToDeleteFile; use LogicException; @@ -54,7 +54,7 @@ class AttachmentRepository implements AttachmentRepositoryInterface, UserGroupIn /** @var AttachmentHelperInterface $helper */ $helper = app(AttachmentHelperInterface::class); - $path = $helper->getAttachmentLocation($attachment); + $path = $helper->getAttachmentLocation($attachment); try { Storage::disk('upload')->delete($path); @@ -103,7 +103,7 @@ class AttachmentRepository implements AttachmentRepositoryInterface, UserGroupIn /** * Get attachment note text or empty string. */ - public function getNoteText(Attachment $attachment): ?string + public function getNoteText(Attachment $attachment): null|string { $note = $attachment->notes()->first(); if (null !== $note) { @@ -121,7 +121,7 @@ class AttachmentRepository implements AttachmentRepositoryInterface, UserGroupIn /** @var AttachmentFactory $factory */ $factory = app(AttachmentFactory::class); $factory->setUser($this->user); - $result = $factory->create($data); + $result = $factory->create($data); if (null === $result) { throw new FireflyException('Could not store attachment.'); } @@ -141,7 +141,7 @@ class AttachmentRepository implements AttachmentRepositoryInterface, UserGroupIn // update model (move attachment) // should be validated already: if (array_key_exists('attachable_type', $data) && array_key_exists('attachable_id', $data)) { - $attachment->attachable_id = (int) $data['attachable_id']; + $attachment->attachable_id = (int) $data['attachable_id']; $attachment->attachable_type = sprintf('FireflyIII\Models\%s', $data['attachable_type']); } @@ -168,7 +168,7 @@ class AttachmentRepository implements AttachmentRepositoryInterface, UserGroupIn return true; } - $dbNote = $attachment->notes()->first(); + $dbNote = $attachment->notes()->first(); if (null === $dbNote) { $dbNote = new Note(); $dbNote->noteable()->associate($attachment); diff --git a/app/Repositories/Attachment/AttachmentRepositoryInterface.php b/app/Repositories/Attachment/AttachmentRepositoryInterface.php index 56078984e2..df4635811d 100644 --- a/app/Repositories/Attachment/AttachmentRepositoryInterface.php +++ b/app/Repositories/Attachment/AttachmentRepositoryInterface.php @@ -51,7 +51,7 @@ interface AttachmentRepositoryInterface /** * Get attachment note text or empty string. */ - public function getNoteText(Attachment $attachment): ?string; + public function getNoteText(Attachment $attachment): null|string; /** * @throws FireflyException diff --git a/app/Repositories/AuditLogEntry/ALERepository.php b/app/Repositories/AuditLogEntry/ALERepository.php index 50e4adaf08..e5e804ac41 100644 --- a/app/Repositories/AuditLogEntry/ALERepository.php +++ b/app/Repositories/AuditLogEntry/ALERepository.php @@ -41,13 +41,13 @@ class ALERepository implements ALERepositoryInterface public function store(array $data): AuditLogEntry { - $auditLogEntry = new AuditLogEntry(); + $auditLogEntry = new AuditLogEntry(); $auditLogEntry->auditable()->associate($data['auditable']); $auditLogEntry->changer()->associate($data['changer']); $auditLogEntry->action = $data['action']; $auditLogEntry->before = $data['before']; - $auditLogEntry->after = $data['after']; + $auditLogEntry->after = $data['after']; $auditLogEntry->save(); return $auditLogEntry; diff --git a/app/Repositories/Bill/BillRepository.php b/app/Repositories/Bill/BillRepository.php index ec736d04f1..2904143f52 100644 --- a/app/Repositories/Bill/BillRepository.php +++ b/app/Repositories/Bill/BillRepository.php @@ -66,9 +66,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface if ('' !== $query) { $search->whereLike('name', sprintf('%%%s', $query)); } - $search->orderBy('name', 'ASC') - ->where('active', true) - ; + $search->orderBy('name', 'ASC')->where('active', true); return $search->take($limit)->get(); } @@ -79,9 +77,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface if ('' !== $query) { $search->whereLike('name', sprintf('%s%%', $query)); } - $search->orderBy('name', 'ASC') - ->where('active', true) - ; + $search->orderBy('name', 'ASC')->where('active', true); return $search->take($limit)->get(); } @@ -91,7 +87,10 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface */ public function correctOrder(): void { - $set = $this->user->bills()->orderBy('order', 'ASC')->get(); + $set = $this->user + ->bills() + ->orderBy('order', 'ASC') + ->get(); $current = 1; foreach ($set as $bill) { if ($bill->order !== $current) { @@ -120,7 +119,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface /** * Find bill by parameters. */ - public function findBill(?int $billId, ?string $billName): ?Bill + public function findBill(null|int $billId, null|string $billName): null|Bill { if (null !== $billId) { $searchResult = $this->find($billId); @@ -146,7 +145,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface /** * Find a bill by ID. */ - public function find(int $billId): ?Bill + public function find(int $billId): null|Bill { /** @var null|Bill */ return $this->user->bills()->find($billId); @@ -155,10 +154,13 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface /** * Find a bill by name. */ - public function findByName(string $name): ?Bill + public function findByName(string $name): null|Bill { /** @var null|Bill */ - return $this->user->bills()->where('name', $name)->first(['bills.*']); + return $this->user + ->bills() + ->where('name', $name) + ->first(['bills.*']); } /** @@ -169,24 +171,23 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface $set = $bill->attachments()->get(); $disk = Storage::disk('upload'); - return $set->each( - static function (Attachment $attachment) use ($disk): Attachment { // @phpstan-ignore-line - $notes = $attachment->notes()->first(); - $attachment->file_exists = $disk->exists($attachment->fileName()); - $attachment->notes_text = null !== $notes ? $notes->text : ''; + return $set->each(static function (Attachment $attachment) use ($disk): Attachment { // @phpstan-ignore-line + $notes = $attachment->notes()->first(); + $attachment->file_exists = $disk->exists($attachment->fileName()); + $attachment->notes_text = null !== $notes ? $notes->text : ''; - return $attachment; - } - ); + return $attachment; + }); } public function getBills(): Collection { - return $this->user->bills() + return $this->user + ->bills() ->orderBy('order', 'ASC') ->orderBy('active', 'DESC') - ->orderBy('name', 'ASC')->get() - ; + ->orderBy('name', 'ASC') + ->get(); } public function getBillsForAccounts(Collection $accounts): Collection @@ -205,30 +206,24 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface 'bills.repeat_freq', 'bills.skip', 'bills.automatch', - 'bills.active', + 'bills.active' ]; $ids = $accounts->pluck('id')->toArray(); - return $this->user->bills() - ->leftJoin( - 'transaction_journals', - static function (JoinClause $join): void { - $join->on('transaction_journals.bill_id', '=', 'bills.id')->whereNull('transaction_journals.deleted_at'); - } - ) - ->leftJoin( - 'transactions', - static function (JoinClause $join): void { - $join->on('transaction_journals.id', '=', 'transactions.transaction_journal_id')->where('transactions.amount', '<', 0); - } - ) + return $this->user + ->bills() + ->leftJoin('transaction_journals', static function (JoinClause $join): void { + $join->on('transaction_journals.bill_id', '=', 'bills.id')->whereNull('transaction_journals.deleted_at'); + }) + ->leftJoin('transactions', static function (JoinClause $join): void { + $join->on('transaction_journals.id', '=', 'transactions.transaction_journal_id')->where('transactions.amount', '<', 0); + }) ->whereIn('transactions.account_id', $ids) ->whereNull('transaction_journals.deleted_at') ->orderBy('bills.active', 'DESC') ->orderBy('bills.name', 'ASC') ->groupBy($fields) - ->get($fields) - ; + ->get($fields); } /** @@ -236,7 +231,10 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface */ public function getByIds(array $billIds): Collection { - return $this->user->bills()->whereIn('id', $billIds)->get(); + return $this->user + ->bills() + ->whereIn('id', $billIds) + ->get(); } /** @@ -247,13 +245,13 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface /** @var null|Note $note */ $note = $bill->notes()->first(); - return (string)$note?->text; + return (string) $note?->text; } public function getOverallAverage(Bill $bill): array { /** @var JournalRepositoryInterface $repos */ - $repos = app(JournalRepositoryInterface::class); + $repos = app(JournalRepositoryInterface::class); $repos->setUser($this->user); // get and sort on currency @@ -263,9 +261,9 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface /** @var TransactionJournal $journal */ foreach ($journals as $journal) { /** @var Transaction $transaction */ - $transaction = $journal->transactions()->where('amount', '<', 0)->first(); - $currencyId = (int)$journal->transaction_currency_id; - $currency = $journal->transactionCurrency; + $transaction = $journal->transactions()->where('amount', '<', 0)->first(); + $currencyId = (int) $journal->transaction_currency_id; + $currency = $journal->transactionCurrency; $result[$currencyId] ??= [ 'sum' => '0', 'pc_sum' => '0', @@ -275,12 +273,12 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface 'currency_id' => $currency->id, 'currency_code' => $currency->code, 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => $currency->decimal_places, + 'currency_decimal_places' => $currency->decimal_places ]; - $result[$currencyId]['sum'] = bcadd($result[$currencyId]['sum'], (string)$transaction->amount); + $result[$currencyId]['sum'] = bcadd($result[$currencyId]['sum'], (string) $transaction->amount); $result[$currencyId]['pc_sum'] = bcadd($result[$currencyId]['pc_sum'], $transaction->native_amount ?? '0'); if ($journal->foreign_currency_id === Amount::getPrimaryCurrency()->id) { - $result[$currencyId]['pc_sum'] = bcadd($result[$currencyId]['pc_sum'], (string)$transaction->amount); + $result[$currencyId]['pc_sum'] = bcadd($result[$currencyId]['pc_sum'], (string) $transaction->amount); } ++$result[$currencyId]['count']; } @@ -291,8 +289,8 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface * @var array $arr */ foreach ($result as $currencyId => $arr) { - $result[$currencyId]['avg'] = bcdiv((string)$arr['sum'], (string)$arr['count']); - $result[$currencyId]['pc_avg'] = bcdiv((string)$arr['pc_sum'], (string)$arr['count']); + $result[$currencyId]['avg'] = bcdiv((string) $arr['sum'], (string) $arr['count']); + $result[$currencyId]['pc_avg'] = bcdiv((string) $arr['pc_sum'], (string) $arr['count']); } return $result; @@ -300,10 +298,11 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface public function getPaginator(int $size): LengthAwarePaginator { - return $this->user->bills() + return $this->user + ->bills() ->orderBy('active', 'DESC') - ->orderBy('name', 'ASC')->paginate($size) - ; + ->orderBy('name', 'ASC') + ->paginate($size); } /** @@ -315,27 +314,27 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface Log::debug(sprintf('Search for linked journals between %s and %s', $start->toW3cString(), $end->toW3cString())); - return $bill->transactionJournals() + return $bill + ->transactionJournals() ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->leftJoin('transaction_currencies AS currency', 'currency.id', '=', 'transactions.transaction_currency_id') ->leftJoin('transaction_currencies AS foreign_currency', 'foreign_currency.id', '=', 'transactions.foreign_currency_id') ->where('transactions.amount', '>', 0) - ->before($end)->after($start)->get( - [ - 'transaction_journals.id', - 'transaction_journals.date', - 'transaction_journals.transaction_group_id', - 'transactions.transaction_currency_id', - 'currency.code AS transaction_currency_code', - 'currency.decimal_places AS transaction_currency_decimal_places', - 'transactions.foreign_currency_id', - 'foreign_currency.code AS foreign_currency_code', - 'foreign_currency.decimal_places AS foreign_currency_decimal_places', - 'transactions.amount', - 'transactions.foreign_amount', - ] - ) - ; + ->before($end) + ->after($start) + ->get([ + 'transaction_journals.id', + 'transaction_journals.date', + 'transaction_journals.transaction_group_id', + 'transactions.transaction_currency_id', + 'currency.code AS transaction_currency_code', + 'currency.decimal_places AS transaction_currency_decimal_places', + 'transactions.foreign_currency_id', + 'foreign_currency.code AS foreign_currency_code', + 'foreign_currency.decimal_places AS foreign_currency_decimal_places', + 'transactions.amount', + 'transactions.foreign_amount' + ]); } /** @@ -343,12 +342,12 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface */ public function getRulesForBill(Bill $bill): Collection { - return $this->user->rules() + return $this->user + ->rules() ->leftJoin('rule_actions', 'rule_actions.rule_id', '=', 'rules.id') ->where('rule_actions.action_type', 'link_to_bill') ->where('rule_actions.action_value', $bill->name) - ->get(['rules.*']) - ; + ->get(['rules.*']); } /** @@ -359,17 +358,17 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface */ public function getRulesForBills(Collection $collection): array { - $rules = $this->user->rules() + $rules = $this->user + ->rules() ->leftJoin('rule_actions', 'rule_actions.rule_id', '=', 'rules.id') ->where('rule_actions.action_type', 'link_to_bill') - ->get(['rules.id', 'rules.title', 'rule_actions.action_value', 'rules.active']) - ; - $array = []; + ->get(['rules.id', 'rules.title', 'rule_actions.action_value', 'rules.active']); + $array = []; /** @var Rule $rule */ foreach ($rules as $rule) { $array[$rule->action_value] ??= []; - $array[$rule->action_value][] = ['id' => $rule->id, 'title' => $rule->title, 'active' => $rule->active]; + $array[$rule->action_value][] = ['id' => $rule->id, 'title' => $rule->title, 'active' => $rule->active]; } $return = []; foreach ($collection as $bill) { @@ -382,27 +381,27 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface public function getYearAverage(Bill $bill, Carbon $date): array { /** @var JournalRepositoryInterface $repos */ - $repos = app(JournalRepositoryInterface::class); + $repos = app(JournalRepositoryInterface::class); $repos->setUser($this->user); // get and sort on currency - $result = []; + $result = []; - $journals = $bill->transactionJournals() - ->where('date', '>=', $date->year.'-01-01 00:00:00') - ->where('date', '<=', $date->year.'-12-31 23:59:59') - ->get() - ; + $journals = $bill + ->transactionJournals() + ->where('date', '>=', $date->year . '-01-01 00:00:00') + ->where('date', '<=', $date->year . '-12-31 23:59:59') + ->get(); /** @var TransactionJournal $journal */ foreach ($journals as $journal) { /** @var null|Transaction $transaction */ - $transaction = $journal->transactions()->where('amount', '<', 0)->first(); + $transaction = $journal->transactions()->where('amount', '<', 0)->first(); if (null === $transaction) { continue; } - $currencyId = (int)$journal->transaction_currency_id; - $currency = $journal->transactionCurrency; + $currencyId = (int) $journal->transaction_currency_id; + $currency = $journal->transactionCurrency; $result[$currencyId] ??= [ 'sum' => '0', 'pc_sum' => '0', @@ -411,12 +410,12 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface 'currency_id' => $currency->id, 'currency_code' => $currency->code, 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => $currency->decimal_places, + 'currency_decimal_places' => $currency->decimal_places ]; - $result[$currencyId]['sum'] = bcadd($result[$currencyId]['sum'], (string)$transaction->amount); + $result[$currencyId]['sum'] = bcadd($result[$currencyId]['sum'], (string) $transaction->amount); $result[$currencyId]['pc_sum'] = bcadd($result[$currencyId]['pc_sum'], $transaction->native_amount ?? '0'); if ($journal->foreign_currency_id === Amount::getPrimaryCurrency()->id) { - $result[$currencyId]['pc_sum'] = bcadd($result[$currencyId]['pc_sum'], (string)$transaction->amount); + $result[$currencyId]['pc_sum'] = bcadd($result[$currencyId]['pc_sum'], (string) $transaction->amount); } ++$result[$currencyId]['count']; } @@ -427,8 +426,8 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface * @var array $arr */ foreach ($result as $currencyId => $arr) { - $result[$currencyId]['avg'] = bcdiv((string)$arr['sum'], (string)$arr['count']); - $result[$currencyId]['pc_avg'] = bcdiv((string)$arr['pc_sum'], (string)$arr['count']); + $result[$currencyId]['avg'] = bcdiv((string) $arr['sum'], (string) $arr['count']); + $result[$currencyId]['pc_avg'] = bcdiv((string) $arr['pc_sum'], (string) $arr['count']); } return $result; @@ -441,7 +440,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface { /** @var Transaction $transaction */ foreach ($transactions as $transaction) { - $journal = $bill->user->transactionJournals()->find((int)$transaction['transaction_journal_id']); + $journal = $bill->user->transactionJournals()->find((int) $transaction['transaction_journal_id']); $journal->bill_id = $bill->id; $journal->save(); Log::debug(sprintf('Linked journal #%d to bill #%d', $journal->id, $bill->id)); @@ -453,7 +452,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface */ public function nextExpectedMatch(Bill $bill, Carbon $date): Carbon { - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($bill->id); $cache->addProperty('nextExpectedMatch'); $cache->addProperty($date); @@ -461,17 +460,17 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface return $cache->get(); } // find the most recent date for this bill NOT in the future. Cache this date: - $start = clone $bill->date; + $start = clone $bill->date; $start->startOfDay(); - Log::debug('nextExpectedMatch: Start is '.$start->format('Y-m-d')); + Log::debug('nextExpectedMatch: Start is ' . $start->format('Y-m-d')); while ($start < $date) { Log::debug(sprintf('$start (%s) < $date (%s)', $start->format('Y-m-d H:i:s'), $date->format('Y-m-d H:i:s'))); $start = Navigation::addPeriod($start, $bill->repeat_freq, $bill->skip); - Log::debug('Start is now '.$start->format('Y-m-d H:i:s')); + Log::debug('Start is now ' . $start->format('Y-m-d H:i:s')); } - $end = Navigation::addPeriod($start, $bill->repeat_freq, $bill->skip); + $end = Navigation::addPeriod($start, $bill->repeat_freq, $bill->skip); $end->endOfDay(); // see if the bill was paid in this period. @@ -483,8 +482,8 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface $start = clone $end; $end = Navigation::addPeriod($start, $bill->repeat_freq, $bill->skip); } - Log::debug('nextExpectedMatch: Final start is '.$start->format('Y-m-d')); - Log::debug('nextExpectedMatch: Matching end is '.$end->format('Y-m-d')); + Log::debug('nextExpectedMatch: Final start is ' . $start->format('Y-m-d')); + Log::debug('nextExpectedMatch: Matching end is ' . $end->format('Y-m-d')); $cache->store($start); @@ -514,7 +513,12 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface { $query = sprintf('%%%s%%', $query); - return $this->user->bills()->orderBy('name', 'ASC')->whereLike('name', $query)->take($limit)->get(); + return $this->user + ->bills() + ->orderBy('name', 'ASC') + ->whereLike('name', $query) + ->take($limit) + ->get(); } public function setObjectGroup(Bill $bill, string $objectGroupTitle): Bill @@ -543,43 +547,47 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface /** @var Bill $bill */ foreach ($bills as $bill) { - /** @var Collection $set */ - $set = $bill->transactionJournals()->after($start)->before($end)->get(['transaction_journals.*']); - $currency = $convertToPrimary && $bill->transactionCurrency->id !== $primary->id ? $primary : $bill->transactionCurrency; - $return[(int)$currency->id] ??= [ - 'id' => (string)$currency->id, + $set = $bill->transactionJournals()->after($start)->before($end)->get(['transaction_journals.*']); + $currency = $convertToPrimary && $bill->transactionCurrency->id !== $primary->id ? $primary : $bill->transactionCurrency; + $return[(int) $currency->id] ??= [ + 'id' => (string) $currency->id, 'name' => $currency->name, 'symbol' => $currency->symbol, 'code' => $currency->code, 'decimal_places' => $currency->decimal_places, - 'sum' => '0', + 'sum' => '0' ]; $setAmount = '0'; /** @var TransactionJournal $transactionJournal */ foreach ($set as $transactionJournal) { // grab currency from transaction. - $transactionCurrency = $transactionJournal->transactionCurrency; - $return[(int)$transactionCurrency->id] ??= [ - 'id' => (string)$transactionCurrency->id, + $transactionCurrency = $transactionJournal->transactionCurrency; + $return[(int) $transactionCurrency->id] ??= [ + 'id' => (string) $transactionCurrency->id, 'name' => $transactionCurrency->name, 'symbol' => $transactionCurrency->symbol, 'code' => $transactionCurrency->code, 'decimal_places' => $transactionCurrency->decimal_places, - 'sum' => '0', + 'sum' => '0' ]; // get currency from transaction as well. - $return[(int)$transactionCurrency->id]['sum'] = bcadd($return[(int)$transactionCurrency->id]['sum'], Amount::getAmountFromJournalObject($transactionJournal)); + $return[(int) $transactionCurrency->id]['sum'] = bcadd( + $return[(int) $transactionCurrency->id]['sum'], + Amount::getAmountFromJournalObject($transactionJournal) + ); + // $setAmount = bcadd($setAmount, Amount::getAmountFromJournalObject($transactionJournal)); } + // Log::debug(sprintf('Bill #%d ("%s") with %d transaction(s) and sum %s %s', $bill->id, $bill->name, $set->count(), $currency->code, $setAmount)); // $return[$currency->id]['sum'] = bcadd($return[$currency->id]['sum'], $setAmount); // Log::debug(sprintf('Total sum is now %s', $return[$currency->id]['sum'])); } // remove empty sets - $final = []; + $final = []; foreach ($return as $entry) { if (0 === bccomp($entry['sum'], '0')) { continue; @@ -592,11 +600,11 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface public function getActiveBills(): Collection { - return $this->user->bills() + return $this->user + ->bills() ->where('active', true) ->orderBy('bills.name', 'ASC') - ->get(['bills.*', DB::raw('((bills.amount_min + bills.amount_max) / 2) AS expectedAmount')]) // @phpstan-ignore-line - ; + ->get(['bills.*', DB::raw('((bills.amount_min + bills.amount_max) / 2) AS expectedAmount')]); // @phpstan-ignore-line } public function sumUnpaidInRange(Carbon $start, Carbon $end): array @@ -610,9 +618,9 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface /** @var Bill $bill */ foreach ($bills as $bill) { // \Illuminate\Support\Facades\Log::debug(sprintf('Processing bill #%d ("%s")', $bill->id, $bill->name)); - $dates = $this->getPayDatesInRange($bill, $start, $end); - $count = $bill->transactionJournals()->after($start)->before($end)->count(); - $total = $dates->count() - $count; + $dates = $this->getPayDatesInRange($bill, $start, $end); + $count = $bill->transactionJournals()->after($start)->before($end)->count(); + $total = $dates->count() - $count; // \Illuminate\Support\Facades\Log::debug(sprintf('Pay dates: %d, count: %d, left: %d', $dates->count(), $count, $total)); // \Illuminate\Support\Facades\Log::debug('dates', $dates->toArray()); @@ -621,18 +629,18 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface // Log::debug(sprintf('min field is %s, max field is %s', $minField, $maxField)); if ($total > 0) { - $currency = $convertToPrimary && $bill->transactionCurrency->id !== $primary->id ? $primary : $bill->transactionCurrency; - $average = bcdiv(bcadd($bill->{$maxField} ?? '0', $bill->{$minField} ?? '0'), '2'); + $currency = $convertToPrimary && $bill->transactionCurrency->id !== $primary->id ? $primary : $bill->transactionCurrency; + $average = bcdiv(bcadd($bill->{$maxField} ?? '0', $bill->{$minField} ?? '0'), '2'); Log::debug(sprintf('Amount to pay is %s %s (%d times)', $currency->code, $average, $total)); $return[$currency->id] ??= [ - 'id' => (string)$currency->id, + 'id' => (string) $currency->id, 'name' => $currency->name, 'symbol' => $currency->symbol, 'code' => $currency->code, 'decimal_places' => $currency->decimal_places, - 'sum' => '0', + 'sum' => '0' ]; - $return[$currency->id]['sum'] = bcadd($return[$currency->id]['sum'], bcmul($average, (string)$total)); + $return[$currency->id]['sum'] = bcadd($return[$currency->id]['sum'], bcmul($average, (string) $total)); } } @@ -653,7 +661,8 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface // \Illuminate\Support\Facades\Log::debug(sprintf('Currentstart is now %s.', $currentStart->format('Y-m-d'))); $nextExpectedMatch = $this->nextDateMatch($bill, $currentStart); // \Illuminate\Support\Facades\Log::debug(sprintf('Next Date match after %s is %s', $currentStart->format('Y-m-d'), $nextExpectedMatch->format('Y-m-d'))); - if ($nextExpectedMatch > $end) {// If nextExpectedMatch is after end, we continue + if ($nextExpectedMatch > $end) { + // If nextExpectedMatch is after end, we continue break; } $set->push(clone $nextExpectedMatch); @@ -662,7 +671,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface // \Illuminate\Support\Facades\Log::debug(sprintf('Currentstart (%s) has become %s.', $currentStart->format('Y-m-d'), $nextExpectedMatch->format('Y-m-d'))); - $currentStart = clone $nextExpectedMatch; + $currentStart = clone $nextExpectedMatch; } return $set; @@ -694,7 +703,10 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface public function unlinkAll(Bill $bill): void { - $this->user->transactionJournals()->where('bill_id', $bill->id)->update(['bill_id' => null]); + $this->user + ->transactionJournals() + ->where('bill_id', $bill->id) + ->update(['bill_id' => null]); } /** @@ -720,7 +732,6 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface ->transactionJournals() ->whereNotNull('bill_id') ->where('transaction_type_id', '!=', $withdrawal->id) - ->update(['bill_id' => null]) - ; + ->update(['bill_id' => null]); } } diff --git a/app/Repositories/Bill/BillRepositoryInterface.php b/app/Repositories/Bill/BillRepositoryInterface.php index 4c021b9684..f6b1f287f5 100644 --- a/app/Repositories/Bill/BillRepositoryInterface.php +++ b/app/Repositories/Bill/BillRepositoryInterface.php @@ -63,17 +63,17 @@ interface BillRepositoryInterface /** * Find a bill by ID. */ - public function find(int $billId): ?Bill; + public function find(int $billId): null|Bill; /** * Find bill by parameters. */ - public function findBill(?int $billId, ?string $billName): ?Bill; + public function findBill(null|int $billId, null|string $billName): null|Bill; /** * Find a bill by name. */ - public function findByName(string $name): ?Bill; + public function findByName(string $name): null|Bill; public function getActiveBills(): Collection; diff --git a/app/Repositories/Budget/AvailableBudgetRepository.php b/app/Repositories/Budget/AvailableBudgetRepository.php index 1e1e7ed017..d0a751b5f4 100644 --- a/app/Repositories/Budget/AvailableBudgetRepository.php +++ b/app/Repositories/Budget/AvailableBudgetRepository.php @@ -49,11 +49,17 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U /** @var AvailableBudget $availableBudget */ foreach ($availableBudgets as $availableBudget) { - $start = $availableBudget->start_date->format('Y-m-d'); - $end = $availableBudget->end_date->format('Y-m-d'); - $key = sprintf('%s-%s-%s', $availableBudget->transaction_currency_id, $start, $end); + $start = $availableBudget->start_date->format('Y-m-d'); + $end = $availableBudget->end_date->format('Y-m-d'); + $key = sprintf('%s-%s-%s', $availableBudget->transaction_currency_id, $start, $end); if (array_key_exists($key, $exists)) { - Log::debug(sprintf('Found duplicate AB: %s %s, %s-%s. Has been deleted', $availableBudget->transaction_currency_id, $availableBudget->amount, $start, $end)); + Log::debug(sprintf( + 'Found duplicate AB: %s %s, %s-%s. Has been deleted', + $availableBudget->transaction_currency_id, + $availableBudget->amount, + $start, + $end + )); $availableBudget->delete(); } $exists[$key] = true; @@ -63,16 +69,14 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U /** * Return a list of all available budgets (in all currencies) (for the selected period). */ - public function get(?Carbon $start = null, ?Carbon $end = null): Collection + public function get(null|Carbon $start = null, null|Carbon $end = null): Collection { - $query = $this->user->availableBudgets()->with(['transactionCurrency']); + $query = $this->user->availableBudgets()->with(['transactionCurrency']); if ($start instanceof Carbon && $end instanceof Carbon) { - $query->where( - static function (Builder $q1) use ($start, $end): void { - $q1->where('start_date', '=', $start->format('Y-m-d')); - $q1->where('end_date', '=', $end->format('Y-m-d')); - } - ); + $query->where(static function (Builder $q1) use ($start, $end): void { + $q1->where('start_date', '=', $start->format('Y-m-d')); + $q1->where('end_date', '=', $end->format('Y-m-d')); + }); } $result = $query->get(['available_budgets.*']); Log::debug(sprintf('Found %d available budgets between %s and %s', $result->count(), $start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s'))); @@ -94,7 +98,7 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U $availableBudget->delete(); } - public function findById(int $id): ?AvailableBudget + public function findById(int $id): null|AvailableBudget { return $this->user->availableBudgets->find($id); } @@ -102,28 +106,29 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U /** * Find existing AB. */ - public function find(TransactionCurrency $currency, Carbon $start, Carbon $end): ?AvailableBudget + public function find(TransactionCurrency $currency, Carbon $start, Carbon $end): null|AvailableBudget { /** @var null|AvailableBudget */ - return $this->user->availableBudgets() + return $this->user + ->availableBudgets() ->where('transaction_currency_id', $currency->id) ->where('start_date', $start->format('Y-m-d')) ->where('end_date', $end->format('Y-m-d')) - ->first() - ; + ->first(); } #[Deprecated] public function getAvailableBudget(TransactionCurrency $currency, Carbon $start, Carbon $end): string { - $amount = '0'; + $amount = '0'; /** @var null|AvailableBudget $availableBudget */ - $availableBudget = $this->user->availableBudgets() + $availableBudget = $this->user + ->availableBudgets() ->where('transaction_currency_id', $currency->id) ->where('start_date', $start->format('Y-m-d')) - ->where('end_date', $end->format('Y-m-d'))->first() - ; + ->where('end_date', $end->format('Y-m-d')) + ->first(); if (null !== $availableBudget) { return $availableBudget->amount; } @@ -135,10 +140,11 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U { Log::debug(sprintf('Now in %s(%s, %s)', __METHOD__, $start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s'))); $return = []; - $availableBudgets = $this->user->availableBudgets() + $availableBudgets = $this->user + ->availableBudgets() ->where('start_date', $start->format('Y-m-d')) - ->where('end_date', $end->format('Y-m-d'))->get() - ; + ->where('end_date', $end->format('Y-m-d')) + ->get(); Log::debug(sprintf('Found %d available budgets (already converted)', $availableBudgets->count())); @@ -148,10 +154,12 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U /** @var AvailableBudget $availableBudget */ foreach ($availableBudgets as $availableBudget) { - $currencyId = $convertToPrimary && $availableBudget->transaction_currency_id !== $primary->id ? $primary->id : $availableBudget->transaction_currency_id; - $field = $convertToPrimary && $availableBudget->transaction_currency_id !== $primary->id ? 'native_amount' : 'amount'; + $currencyId = $convertToPrimary && $availableBudget->transaction_currency_id !== $primary->id + ? $primary->id + : $availableBudget->transaction_currency_id; + $field = $convertToPrimary && $availableBudget->transaction_currency_id !== $primary->id ? 'native_amount' : 'amount'; $return[$currencyId] ??= '0'; - $amount = '' === (string) $availableBudget->{$field} ? '0' : (string) $availableBudget->{$field}; + $amount = '' === (string) $availableBudget->{$field} ? '0' : (string) $availableBudget->{$field}; $return[$currencyId] = bcadd($return[$currencyId], $amount); Log::debug(sprintf('Add #%d %s (%s) for a total of %s', $currencyId, $amount, $field, $return[$currencyId])); } @@ -164,13 +172,16 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U */ public function getAvailableBudgetsByCurrency(TransactionCurrency $currency): Collection { - return $this->user->availableBudgets()->where('transaction_currency_id', $currency->id)->get(); + return $this->user + ->availableBudgets() + ->where('transaction_currency_id', $currency->id) + ->get(); } /** * Returns all available budget objects. */ - public function getAvailableBudgetsByDate(?Carbon $start, ?Carbon $end): Collection + public function getAvailableBudgetsByDate(null|Carbon $start, null|Carbon $end): Collection { $query = $this->user->availableBudgets(); @@ -189,41 +200,42 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U */ public function getAvailableBudgetsByExactDate(Carbon $start, Carbon $end): Collection { - return $this->user->availableBudgets() + return $this->user + ->availableBudgets() ->where('start_date', '=', $start->format('Y-m-d')) ->where('end_date', '=', $end->format('Y-m-d')) - ->get() - ; + ->get(); } - public function getByCurrencyDate(Carbon $start, Carbon $end, TransactionCurrency $currency): ?AvailableBudget + public function getByCurrencyDate(Carbon $start, Carbon $end, TransactionCurrency $currency): null|AvailableBudget { /** @var null|AvailableBudget */ return $this->user ->availableBudgets() ->where('transaction_currency_id', $currency->id) ->where('start_date', $start->format('Y-m-d')) - ->where('end_date', $end->format('Y-m-d'))->first() - ; + ->where('end_date', $end->format('Y-m-d')) + ->first(); } #[Deprecated] public function setAvailableBudget(TransactionCurrency $currency, Carbon $start, Carbon $end, string $amount): AvailableBudget { /** @var null|AvailableBudget $availableBudget */ - $availableBudget = $this->user->availableBudgets() + $availableBudget = $this->user + ->availableBudgets() ->where('transaction_currency_id', $currency->id) ->where('start_date', $start->format('Y-m-d')) - ->where('end_date', $end->format('Y-m-d'))->first() - ; + ->where('end_date', $end->format('Y-m-d')) + ->first(); if (null === $availableBudget) { - $availableBudget = new AvailableBudget(); + $availableBudget = new AvailableBudget(); $availableBudget->user()->associate($this->user); $availableBudget->transactionCurrency()->associate($currency); - $availableBudget->start_date = $start->startOfDay(); + $availableBudget->start_date = $start->startOfDay(); $availableBudget->start_date_tz = $start->format('e'); - $availableBudget->end_date = $end->endOfDay(); - $availableBudget->end_date_tz = $end->format('e'); + $availableBudget->end_date = $end->endOfDay(); + $availableBudget->end_date_tz = $end->format('e'); } $availableBudget->amount = $amount; $availableBudget->save(); @@ -231,29 +243,27 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U return $availableBudget; } - public function store(array $data): ?AvailableBudget + public function store(array $data): null|AvailableBudget { $start = $data['start']; if ($start instanceof Carbon) { $start = $data['start']->startOfDay(); } - $end = $data['end']; + $end = $data['end']; if ($end instanceof Carbon) { $end = $data['end']->endOfDay(); } - return AvailableBudget::create( - [ - 'user_id' => $this->user->id, - 'user_group_id' => $this->user->user_group_id, - 'transaction_currency_id' => $data['currency_id'], - 'amount' => $data['amount'], - 'start_date' => $start, - 'start_date_tz' => $start->format('e'), - 'end_date' => $end, - 'end_date_tz' => $end->format('e'), - ] - ); + return AvailableBudget::create([ + 'user_id' => $this->user->id, + 'user_group_id' => $this->user->user_group_id, + 'transaction_currency_id' => $data['currency_id'], + 'amount' => $data['amount'], + 'start_date' => $start, + 'start_date_tz' => $start->format('e'), + 'end_date' => $end, + 'end_date_tz' => $end->format('e') + ]); } public function update(AvailableBudget $availableBudget, array $data): AvailableBudget @@ -271,8 +281,8 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U if (array_key_exists('start', $data)) { $start = $data['start']; if ($start instanceof Carbon) { - $start = $data['start']->startOfDay(); - $availableBudget->start_date = $start; + $start = $data['start']->startOfDay(); + $availableBudget->start_date = $start; $availableBudget->start_date_tz = $start->format('e'); $availableBudget->save(); } @@ -281,8 +291,8 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U if (array_key_exists('end', $data)) { $end = $data['end']; if ($end instanceof Carbon) { - $end = $data['end']->endOfDay(); - $availableBudget->end_date = $end; + $end = $data['end']->endOfDay(); + $availableBudget->end_date = $end; $availableBudget->end_date_tz = $end->format('e'); $availableBudget->save(); } diff --git a/app/Repositories/Budget/AvailableBudgetRepositoryInterface.php b/app/Repositories/Budget/AvailableBudgetRepositoryInterface.php index 46251e79d2..a356b88509 100644 --- a/app/Repositories/Budget/AvailableBudgetRepositoryInterface.php +++ b/app/Repositories/Budget/AvailableBudgetRepositoryInterface.php @@ -58,14 +58,14 @@ interface AvailableBudgetRepositoryInterface /** * Find existing AB. */ - public function find(TransactionCurrency $currency, Carbon $start, Carbon $end): ?AvailableBudget; + public function find(TransactionCurrency $currency, Carbon $start, Carbon $end): null|AvailableBudget; - public function findById(int $id): ?AvailableBudget; + public function findById(int $id): null|AvailableBudget; /** * Return a list of all available budgets (in all currencies) (for the selected period). */ - public function get(?Carbon $start = null, ?Carbon $end = null): Collection; + public function get(null|Carbon $start = null, null|Carbon $end = null): Collection; #[Deprecated] public function getAvailableBudget(TransactionCurrency $currency, Carbon $start, Carbon $end): string; @@ -80,19 +80,19 @@ interface AvailableBudgetRepositoryInterface /** * Returns all available budget objects. */ - public function getAvailableBudgetsByDate(?Carbon $start, ?Carbon $end): Collection; + public function getAvailableBudgetsByDate(null|Carbon $start, null|Carbon $end): Collection; public function getAvailableBudgetsByExactDate(Carbon $start, Carbon $end): Collection; /** * Get by transaction currency and date. Should always result in one entry or NULL. */ - public function getByCurrencyDate(Carbon $start, Carbon $end, TransactionCurrency $currency): ?AvailableBudget; + public function getByCurrencyDate(Carbon $start, Carbon $end, TransactionCurrency $currency): null|AvailableBudget; #[Deprecated] public function setAvailableBudget(TransactionCurrency $currency, Carbon $start, Carbon $end, string $amount): AvailableBudget; - public function store(array $data): ?AvailableBudget; + public function store(array $data): null|AvailableBudget; public function update(AvailableBudget $availableBudget, array $data): AvailableBudget; diff --git a/app/Repositories/Budget/BudgetLimitRepository.php b/app/Repositories/Budget/BudgetLimitRepository.php index 443f25677c..edb4825514 100644 --- a/app/Repositories/Budget/BudgetLimitRepository.php +++ b/app/Repositories/Budget/BudgetLimitRepository.php @@ -51,45 +51,29 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup * Tells you which amount has been budgeted (for the given budgets) * in the selected query. Returns a positive amount as a string. */ - public function budgeted(Carbon $start, Carbon $end, TransactionCurrency $currency, ?Collection $budgets = null): string + public function budgeted(Carbon $start, Carbon $end, TransactionCurrency $currency, null|Collection $budgets = null): string { - $query = BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id') - + $query = BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id') // same complex where query as below. - ->where( - static function (Builder $q5) use ($start, $end): void { - $q5->where( - static function (Builder $q1) use ($start, $end): void { - $q1->where( - static function (Builder $q2) use ($start, $end): void { - $q2->where('budget_limits.end_date', '>=', $start->format('Y-m-d')); - $q2->where('budget_limits.end_date', '<=', $end->format('Y-m-d')); - } - ) - ->orWhere( - static function (Builder $q3) use ($start, $end): void { - $q3->where('budget_limits.start_date', '>=', $start->format('Y-m-d')); - $q3->where('budget_limits.start_date', '<=', $end->format('Y-m-d')); - } - ) - ; - } - ) - ->orWhere( - static function (Builder $q4) use ($start, $end): void { - // or start is before start AND end is after end. - $q4->where('budget_limits.start_date', '<=', $start->format('Y-m-d')); - $q4->where('budget_limits.end_date', '>=', $end->format('Y-m-d')); - } - ) - ; - } - ) + ->where(static function (Builder $q5) use ($start, $end): void { + $q5->where(static function (Builder $q1) use ($start, $end): void { + $q1->where(static function (Builder $q2) use ($start, $end): void { + $q2->where('budget_limits.end_date', '>=', $start->format('Y-m-d')); + $q2->where('budget_limits.end_date', '<=', $end->format('Y-m-d')); + })->orWhere(static function (Builder $q3) use ($start, $end): void { + $q3->where('budget_limits.start_date', '>=', $start->format('Y-m-d')); + $q3->where('budget_limits.start_date', '<=', $end->format('Y-m-d')); + }); + })->orWhere(static function (Builder $q4) use ($start, $end): void { + // or start is before start AND end is after end. + $q4->where('budget_limits.start_date', '<=', $start->format('Y-m-d')); + $q4->where('budget_limits.end_date', '>=', $end->format('Y-m-d')); + }); + }) ->where('budget_limits.transaction_currency_id', $currency->id) ->whereNull('budgets.deleted_at') ->where('budgets.active', true) - ->where('budgets.user_id', $this->user->id) - ; + ->where('budgets.user_id', $this->user->id); if ($budgets instanceof Collection && $budgets->count() > 0) { $query->whereIn('budget_limits.budget_id', $budgets->pluck('id')->toArray()); } @@ -127,14 +111,14 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup $budgetLimit->delete(); } - public function getAllBudgetLimitsByCurrency(TransactionCurrency $currency, ?Carbon $start = null, ?Carbon $end = null): Collection + public function getAllBudgetLimitsByCurrency(TransactionCurrency $currency, null|Carbon $start = null, null|Carbon $end = null): Collection { return $this->getAllBudgetLimits($start, $end)->filter( - static fn (BudgetLimit $budgetLimit): bool => $budgetLimit->transaction_currency_id === $currency->id + static fn(BudgetLimit $budgetLimit): bool => $budgetLimit->transaction_currency_id === $currency->id ); } - public function getAllBudgetLimits(?Carbon $start = null, ?Carbon $end = null): Collection + public function getAllBudgetLimits(null|Carbon $start = null, null|Carbon $end = null): Collection { // both are NULL: if (!$start instanceof Carbon && !$end instanceof Carbon) { @@ -142,16 +126,14 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup ->with(['budget']) ->where('budgets.user_id', $this->user->id) ->whereNull('budgets.deleted_at') - ->get(['budget_limits.*']) - ; + ->get(['budget_limits.*']); } // one of the two is NULL. if (!$start instanceof Carbon xor !$end instanceof Carbon) { $query = BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id') ->with(['budget']) ->whereNull('budgets.deleted_at') - ->where('budgets.user_id', $this->user->id) - ; + ->where('budgets.user_id', $this->user->id); if ($end instanceof Carbon) { // end date must be before $end. $query->where('end_date', '<=', $end->format('Y-m-d 00:00:00')); @@ -169,39 +151,25 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup ->with(['budget']) ->where('budgets.user_id', $this->user->id) ->whereNull('budgets.deleted_at') - ->where( - static function (Builder $q5) use ($start, $end): void { - $q5->where( - static function (Builder $q1) use ($start, $end): void { - $q1->where( - static function (Builder $q2) use ($start, $end): void { - $q2->where('budget_limits.end_date', '>=', $start->format('Y-m-d')); - $q2->where('budget_limits.end_date', '<=', $end->format('Y-m-d')); - } - ) - ->orWhere( - static function (Builder $q3) use ($start, $end): void { - $q3->where('budget_limits.start_date', '>=', $start->format('Y-m-d')); - $q3->where('budget_limits.start_date', '<=', $end->format('Y-m-d')); - } - ) - ; - } - ) - ->orWhere( - static function (Builder $q4) use ($start, $end): void { - // or start is before start AND end is after end. - $q4->where('budget_limits.start_date', '<=', $start->format('Y-m-d')); - $q4->where('budget_limits.end_date', '>=', $end->format('Y-m-d')); - } - ) - ; - } - )->get(['budget_limits.*']) - ; + ->where(static function (Builder $q5) use ($start, $end): void { + $q5->where(static function (Builder $q1) use ($start, $end): void { + $q1->where(static function (Builder $q2) use ($start, $end): void { + $q2->where('budget_limits.end_date', '>=', $start->format('Y-m-d')); + $q2->where('budget_limits.end_date', '<=', $end->format('Y-m-d')); + })->orWhere(static function (Builder $q3) use ($start, $end): void { + $q3->where('budget_limits.start_date', '>=', $start->format('Y-m-d')); + $q3->where('budget_limits.start_date', '<=', $end->format('Y-m-d')); + }); + })->orWhere(static function (Builder $q4) use ($start, $end): void { + // or start is before start AND end is after end. + $q4->where('budget_limits.start_date', '<=', $start->format('Y-m-d')); + $q4->where('budget_limits.end_date', '>=', $end->format('Y-m-d')); + }); + }) + ->get(['budget_limits.*']); } - public function getBudgetLimits(Budget $budget, ?Carbon $start = null, ?Carbon $end = null): Collection + public function getBudgetLimits(Budget $budget, null|Carbon $start = null, null|Carbon $end = null): Collection { if (!$end instanceof Carbon && !$start instanceof Carbon) { return $budget->budgetlimits()->with(['transactionCurrency'])->orderBy('budget_limits.start_date', 'DESC')->get(['budget_limits.*']); @@ -222,39 +190,29 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup } // when both dates are set: - return $budget->budgetlimits() - ->where( - static function (Builder $q5) use ($start, $end): void { - $q5->where( - static function (Builder $q1) use ($start, $end): void { - // budget limit ends within period - $q1->where( - static function (Builder $q2) use ($start, $end): void { - $q2->where('budget_limits.end_date', '>=', $start->format('Y-m-d 00:00:00')); - $q2->where('budget_limits.end_date', '<=', $end->format('Y-m-d 23:59:59')); - } - ) - // budget limit start within period - ->orWhere( - static function (Builder $q3) use ($start, $end): void { - $q3->where('budget_limits.start_date', '>=', $start->format('Y-m-d 00:00:00')); - $q3->where('budget_limits.start_date', '<=', $end->format('Y-m-d 23:59:59')); - } - ) - ; - } - ) - ->orWhere( - static function (Builder $q4) use ($start, $end): void { - // or start is before start AND end is after end. - $q4->where('budget_limits.start_date', '<=', $start->format('Y-m-d 23:59:59')); - $q4->where('budget_limits.end_date', '>=', $end->format('Y-m-d 00:00:00')); - } - ) - ; - } - )->orderBy('budget_limits.start_date', 'DESC')->get(['budget_limits.*']) - ; + return $budget + ->budgetlimits() + ->where(static function (Builder $q5) use ($start, $end): void { + $q5->where(static function (Builder $q1) use ($start, $end): void { + // budget limit ends within period + $q1 + ->where(static function (Builder $q2) use ($start, $end): void { + $q2->where('budget_limits.end_date', '>=', $start->format('Y-m-d 00:00:00')); + $q2->where('budget_limits.end_date', '<=', $end->format('Y-m-d 23:59:59')); + }) + // budget limit start within period + ->orWhere(static function (Builder $q3) use ($start, $end): void { + $q3->where('budget_limits.start_date', '>=', $start->format('Y-m-d 00:00:00')); + $q3->where('budget_limits.start_date', '<=', $end->format('Y-m-d 23:59:59')); + }); + })->orWhere(static function (Builder $q4) use ($start, $end): void { + // or start is before start AND end is after end. + $q4->where('budget_limits.start_date', '<=', $start->format('Y-m-d 23:59:59')); + $q4->where('budget_limits.end_date', '>=', $end->format('Y-m-d 00:00:00')); + }); + }) + ->orderBy('budget_limits.start_date', 'DESC') + ->get(['budget_limits.*']); } #[Override] @@ -270,47 +228,47 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup { // if no currency has been provided, use the user's default currency: /** @var TransactionCurrencyFactory $factory */ - $factory = app(TransactionCurrencyFactory::class); - $currency = $factory->find($data['currency_id'] ?? null, $data['currency_code'] ?? null); + $factory = app(TransactionCurrencyFactory::class); + $currency = $factory->find($data['currency_id'] ?? null, $data['currency_code'] ?? null); if (null === $currency) { $currency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); } - $currency->enabled = true; + $currency->enabled = true; $currency->save(); // find the budget: /** @var null|Budget $budget */ - $budget = $this->user->budgets()->find((int) $data['budget_id']); + $budget = $this->user->budgets()->find((int) $data['budget_id']); if (null === $budget) { throw new FireflyException('200004: Budget does not exist.'); } // find limit with same date range and currency. - $limit = $budget->budgetlimits() + $limit = $budget + ->budgetlimits() ->where('budget_limits.start_date', $data['start_date']->format('Y-m-d')) ->where('budget_limits.end_date', $data['end_date']->format('Y-m-d')) ->where('budget_limits.transaction_currency_id', $currency->id) - ->first(['budget_limits.*']) - ; + ->first(['budget_limits.*']); if (null !== $limit) { throw new FireflyException('200027: Budget limit already exists.'); } Log::debug('No existing budget limit, create a new one'); // this is a lame trick to communicate with the observer. - $singleton = PreferencesSingleton::getInstance(); + $singleton = PreferencesSingleton::getInstance(); $singleton->setPreference('fire_webhooks_bl_store', $data['fire_webhooks'] ?? true); // or create one and return it. - $limit = new BudgetLimit(); + $limit = new BudgetLimit(); $limit->budget()->associate($budget); - $limit->start_date = $data['start_date']->format('Y-m-d'); - $limit->end_date = $data['end_date']->format('Y-m-d'); - $limit->amount = $data['amount']; + $limit->start_date = $data['start_date']->format('Y-m-d'); + $limit->end_date = $data['end_date']->format('Y-m-d'); + $limit->amount = $data['amount']; $limit->transaction_currency_id = $currency->id; $limit->save(); - $noteText = (string) ($data['notes'] ?? ''); + $noteText = (string) ($data['notes'] ?? ''); if ('' !== $noteText) { $this->setNoteText($limit, $noteText); } @@ -320,14 +278,15 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup return $limit; } - public function find(Budget $budget, TransactionCurrency $currency, Carbon $start, Carbon $end): ?BudgetLimit + public function find(Budget $budget, TransactionCurrency $currency, Carbon $start, Carbon $end): null|BudgetLimit { /** @var null|BudgetLimit */ - return $budget->budgetlimits() + return $budget + ->budgetlimits() ->where('transaction_currency_id', $currency->id) ->where('start_date', $start->format('Y-m-d')) - ->where('end_date', $end->format('Y-m-d'))->first() - ; + ->where('end_date', $end->format('Y-m-d')) + ->first(); } #[Override] @@ -352,20 +311,20 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup */ public function update(BudgetLimit $budgetLimit, array $data): BudgetLimit { - $budgetLimit->amount = array_key_exists('amount', $data) ? $data['amount'] : $budgetLimit->amount; - $budgetLimit->budget_id = array_key_exists('budget_id', $data) ? $data['budget_id'] : $budgetLimit->budget_id; + $budgetLimit->amount = array_key_exists('amount', $data) ? $data['amount'] : $budgetLimit->amount; + $budgetLimit->budget_id = array_key_exists('budget_id', $data) ? $data['budget_id'] : $budgetLimit->budget_id; if (array_key_exists('start', $data)) { - $budgetLimit->start_date = $data['start']->startOfDay(); + $budgetLimit->start_date = $data['start']->startOfDay(); $budgetLimit->start_date_tz = $data['start']->format('e'); } if (array_key_exists('end', $data)) { - $budgetLimit->end_date = $data['end']->endOfDay(); + $budgetLimit->end_date = $data['end']->endOfDay(); $budgetLimit->end_date_tz = $data['end']->format('e'); } // if no currency has been provided, use the user's default currency: - $currency = null; + $currency = null; // update if relevant: if (array_key_exists('currency_id', $data) || array_key_exists('currency_code', $data)) { @@ -377,11 +336,11 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup if (null === $currency) { $currency = $budgetLimit->transactionCurrency ?? Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); } - $currency->enabled = true; + $currency->enabled = true; $currency->save(); // this is a lame trick to communicate with the observer. - $singleton = PreferencesSingleton::getInstance(); + $singleton = PreferencesSingleton::getInstance(); $singleton->setPreference('fire_webhooks_bl_update', $data['fire_webhooks'] ?? true); $budgetLimit->transaction_currency_id = $currency->id; diff --git a/app/Repositories/Budget/BudgetLimitRepositoryInterface.php b/app/Repositories/Budget/BudgetLimitRepositoryInterface.php index defb1c7d49..8592254128 100644 --- a/app/Repositories/Budget/BudgetLimitRepositoryInterface.php +++ b/app/Repositories/Budget/BudgetLimitRepositoryInterface.php @@ -50,7 +50,7 @@ interface BudgetLimitRepositoryInterface * Tells you which amount has been budgeted (for the given budgets) * in the selected query. Returns a positive amount as a string. */ - public function budgeted(Carbon $start, Carbon $end, TransactionCurrency $currency, ?Collection $budgets = null): string; + public function budgeted(Carbon $start, Carbon $end, TransactionCurrency $currency, null|Collection $budgets = null): string; /** * Destroy all budget limits. @@ -62,16 +62,16 @@ interface BudgetLimitRepositoryInterface */ public function destroyBudgetLimit(BudgetLimit $budgetLimit): void; - public function find(Budget $budget, TransactionCurrency $currency, Carbon $start, Carbon $end): ?BudgetLimit; + public function find(Budget $budget, TransactionCurrency $currency, Carbon $start, Carbon $end): null|BudgetLimit; /** * TODO this method is not multi currency aware. */ - public function getAllBudgetLimits(?Carbon $start = null, ?Carbon $end = null): Collection; + public function getAllBudgetLimits(null|Carbon $start = null, null|Carbon $end = null): Collection; - public function getAllBudgetLimitsByCurrency(TransactionCurrency $currency, ?Carbon $start = null, ?Carbon $end = null): Collection; + public function getAllBudgetLimitsByCurrency(TransactionCurrency $currency, null|Carbon $start = null, null|Carbon $end = null): Collection; - public function getBudgetLimits(Budget $budget, ?Carbon $start = null, ?Carbon $end = null): Collection; + public function getBudgetLimits(Budget $budget, null|Carbon $start = null, null|Carbon $end = null): Collection; public function getNoteText(BudgetLimit $budgetLimit): string; diff --git a/app/Repositories/Budget/BudgetRepository.php b/app/Repositories/Budget/BudgetRepository.php index 3f6018c3ff..984aca4251 100644 --- a/app/Repositories/Budget/BudgetRepository.php +++ b/app/Repositories/Budget/BudgetRepository.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace FireflyIII\Repositories\Budget; -use FireflyIII\Support\Facades\Navigation; use Carbon\Carbon; use FireflyIII\Enums\AutoBudgetType; use FireflyIII\Enums\TransactionTypeEnum; @@ -41,6 +40,8 @@ use FireflyIII\Models\RuleTrigger; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\Services\Internal\Destroy\BudgetDestroyService; +use FireflyIII\Support\Facades\Amount; +use FireflyIII\Support\Facades\Navigation; use FireflyIII\Support\Facades\Steam; use FireflyIII\Support\Http\Api\ExchangeRateConverter; use FireflyIII\Support\Repositories\UserGroup\UserGroupInterface; @@ -51,7 +52,6 @@ use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Storage; -use FireflyIII\Support\Facades\Amount; /** * Class BudgetRepository. @@ -66,9 +66,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface if ('' !== $query) { $search->whereLike('name', sprintf('%%%s', $query)); } - $search->orderBy('order', 'ASC') - ->orderBy('name', 'ASC')->where('active', true) - ; + $search->orderBy('order', 'ASC')->orderBy('name', 'ASC')->where('active', true); return $search->take($limit)->get(); } @@ -79,9 +77,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface if ('' !== $query) { $search->whereLike('name', sprintf('%s%%', $query)); } - $search->orderBy('order', 'ASC') - ->orderBy('name', 'ASC')->where('active', true) - ; + $search->orderBy('order', 'ASC')->orderBy('name', 'ASC')->where('active', true); return $search->take($limit)->get(); } @@ -89,7 +85,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface public function budgetedInPeriod(Carbon $start, Carbon $end): array { Log::debug(sprintf('Now in budgetedInPeriod("%s", "%s")', $start->format('Y-m-d'), $end->format('Y-m-d'))); - $return = []; + $return = []; /** @var BudgetLimitRepository $limitRepository */ $limitRepository = app(BudgetLimitRepository::class); @@ -106,9 +102,9 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface /** @var BudgetLimit $limit */ foreach ($limits as $limit) { Log::debug(sprintf('Budget limit #%d', $limit->id)); - $currency = $limit->transactionCurrency; - $rate = $converter->getCurrencyRate($currency, $primaryCurrency, $end); - $currencyCode = $currency->code; + $currency = $limit->transactionCurrency; + $rate = $converter->getCurrencyRate($currency, $primaryCurrency, $end); + $currencyCode = $currency->code; $return[$currencyCode] ??= [ 'currency_id' => (string) $currency->id, 'currency_name' => $currency->name, @@ -121,11 +117,11 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface 'primary_currency_code' => $primaryCurrency->code, 'primary_currency_decimal_places' => $primaryCurrency->decimal_places, 'sum' => '0', - 'pc_sum' => '0', + 'pc_sum' => '0' ]; // same period if ($limit->start_date->isSameDay($start) && $limit->end_date->isSameDay($end)) { - $return[$currencyCode]['sum'] = bcadd($return[$currencyCode]['sum'], (string) $limit->amount); + $return[$currencyCode]['sum'] = bcadd($return[$currencyCode]['sum'], (string) $limit->amount); $return[$currencyCode]['pc_sum'] = bcmul($rate, $return[$currencyCode]['sum']); Log::debug(sprintf('Add full amount [1]: %s', $limit->amount)); @@ -133,27 +129,25 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface } // limit is inside of date range if ($start->lte($limit->start_date) && $end->gte($limit->end_date)) { - $return[$currencyCode]['sum'] = bcadd($return[$currencyCode]['sum'], (string) $limit->amount); + $return[$currencyCode]['sum'] = bcadd($return[$currencyCode]['sum'], (string) $limit->amount); $return[$currencyCode]['pc_sum'] = bcmul($rate, $return[$currencyCode]['sum']); Log::debug(sprintf('Add full amount [2]: %s', $limit->amount)); continue; } - $total = $limit->start_date->diffInDays($limit->end_date, true) + 1; // include the day itself. - $days = $this->daysInOverlap($limit, $start, $end); - $amount = bcmul(bcdiv((string) $limit->amount, (string) $total), (string) $days); - $return[$currencyCode]['sum'] = bcadd($return[$currencyCode]['sum'], $amount); + $total = $limit->start_date->diffInDays($limit->end_date, true) + 1; // include the day itself. + $days = $this->daysInOverlap($limit, $start, $end); + $amount = bcmul(bcdiv((string) $limit->amount, (string) $total), (string) $days); + $return[$currencyCode]['sum'] = bcadd($return[$currencyCode]['sum'], $amount); $return[$currencyCode]['pc_sum'] = bcmul($rate, $return[$currencyCode]['sum']); - Log::debug( - sprintf( - 'Amount per day: %s (%s over %d days). Total amount for %d days: %s', - bcdiv((string) $limit->amount, (string) $total), - $limit->amount, - $total, - $days, - $amount - ) - ); + Log::debug(sprintf( + 'Amount per day: %s (%s over %d days). Total amount for %d days: %s', + bcdiv((string) $limit->amount, (string) $total), + $limit->amount, + $total, + $days, + $amount + )); } } @@ -162,11 +156,12 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface public function getActiveBudgets(): Collection { - return $this->user->budgets()->where('active', true) + return $this->user + ->budgets() + ->where('active', true) ->orderBy('order', 'ASC') ->orderBy('name', 'ASC') - ->get() - ; + ->get(); } /** @@ -206,26 +201,26 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface public function budgetedInPeriodForBudget(Budget $budget, Carbon $start, Carbon $end): array { Log::debug(sprintf('Now in budgetedInPeriod(#%d, "%s", "%s")', $budget->id, $start->format('Y-m-d'), $end->format('Y-m-d'))); - $return = []; + $return = []; /** @var BudgetLimitRepository $limitRepository */ $limitRepository = app(BudgetLimitRepository::class); $limitRepository->setUser($this->user); Log::debug(sprintf('Budget #%d: "%s"', $budget->id, $budget->name)); - $limits = $limitRepository->getBudgetLimits($budget, $start, $end); + $limits = $limitRepository->getBudgetLimits($budget, $start, $end); /** @var BudgetLimit $limit */ foreach ($limits as $limit) { Log::debug(sprintf('Budget limit #%d', $limit->id)); - $currency = $limit->transactionCurrency; + $currency = $limit->transactionCurrency; $return[$currency->id] ??= [ 'id' => (string) $currency->id, 'name' => $currency->name, 'symbol' => $currency->symbol, 'code' => $currency->code, 'decimal_places' => $currency->decimal_places, - 'sum' => '0', + 'sum' => '0' ]; // same period if ($limit->start_date->isSameDay($start) && $limit->end_date->isSameDay($end)) { @@ -241,20 +236,18 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface continue; } - $total = $limit->start_date->diffInDays($limit->end_date) + 1; // include the day itself. - $days = $this->daysInOverlap($limit, $start, $end); - $amount = bcmul(bcdiv((string) $limit->amount, (string) $total), (string) $days); + $total = $limit->start_date->diffInDays($limit->end_date) + 1; // include the day itself. + $days = $this->daysInOverlap($limit, $start, $end); + $amount = bcmul(bcdiv((string) $limit->amount, (string) $total), (string) $days); $return[$currency->id]['sum'] = bcadd($return[$currency->id]['sum'], $amount); - Log::debug( - sprintf( - 'Amount per day: %s (%s over %d days). Total amount for %d days: %s', - bcdiv((string) $limit->amount, (string) $total), - $limit->amount, - $total, - $days, - $amount - ) - ); + Log::debug(sprintf( + 'Amount per day: %s (%s over %d days). Total amount for %d days: %s', + bcdiv((string) $limit->amount, (string) $total), + $limit->amount, + $total, + $days, + $amount + )); } return $return; @@ -275,7 +268,10 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface $budget->saveQuietly(); } // other budgets, set to 0. - $this->user->budgets()->where('active', 0)->update(['order' => 0]); + $this->user + ->budgets() + ->where('active', 0) + ->update(['order' => 0]); return true; } @@ -288,10 +284,10 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface Log::debug('Now in update()'); // this is a lame trick to communicate with the observer. - $singleton = PreferencesSingleton::getInstance(); + $singleton = PreferencesSingleton::getInstance(); $singleton->setPreference('fire_webhooks_budget_update', $data['fire_webhooks'] ?? true); - $oldName = $budget->name; + $oldName = $budget->name; if (array_key_exists('name', $data)) { $budget->name = $data['name']; $this->updateRuleActions($oldName, $budget->name); @@ -306,7 +302,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface $budget->save(); // update or create auto-budget: - $autoBudget = $this->getAutoBudget($budget); + $autoBudget = $this->getAutoBudget($budget); // first things first: delete when no longer required: $autoBudgetType = $data['auto_budget_type'] ?? null; @@ -335,8 +331,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface ->where('rules.user_id', $this->user->id) ->whereIn('rule_actions.action_type', $types) ->where('rule_actions.action_value', $oldName) - ->get(['rule_actions.*']) - ; + ->get(['rule_actions.*']); Log::debug(sprintf('Found %d actions to update.', $actions->count())); /** @var RuleAction $action */ @@ -354,8 +349,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface ->where('rules.user_id', $this->user->id) ->whereIn('rule_triggers.trigger_type', $types) ->where('rule_triggers.trigger_value', $oldName) - ->get(['rule_triggers.*']) - ; + ->get(['rule_triggers.*']); Log::debug(sprintf('Found %d triggers to update.', $triggers->count())); /** @var RuleTrigger $trigger */ @@ -382,7 +376,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface $dbNote?->delete(); } - public function getAutoBudget(Budget $budget): ?AutoBudget + public function getAutoBudget(Budget $budget): null|AutoBudget { /** @var null|AutoBudget */ return $budget->autoBudgets()->first(); @@ -394,13 +388,13 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface $autoBudget = $this->getAutoBudget($budget); // grab default currency: - $currency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); + $currency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); if (!$autoBudget instanceof AutoBudget) { // at this point it's a blind assumption auto_budget_type is 1 or 2. - $autoBudget = new AutoBudget(); - $autoBudget->auto_budget_type = $data['auto_budget_type']; - $autoBudget->budget_id = $budget->id; + $autoBudget = new AutoBudget(); + $autoBudget->auto_budget_type = $data['auto_budget_type']; + $autoBudget->budget_id = $budget->id; $autoBudget->transaction_currency_id = $currency->id; } @@ -438,7 +432,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface * * @param null|int $budgetId |null */ - public function find(?int $budgetId = null): ?Budget + public function find(null|int $budgetId = null): null|Budget { /** @var null|Budget */ return $this->user->budgets()->find($budgetId); @@ -473,9 +467,11 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface public function getBudgets(): Collection { - return $this->user->budgets()->orderBy('order', 'ASC') - ->orderBy('name', 'ASC')->get() - ; + return $this->user + ->budgets() + ->orderBy('order', 'ASC') + ->orderBy('name', 'ASC') + ->get(); } public function destroyAutoBudget(Budget $budget): void @@ -486,7 +482,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface } } - public function findBudget(?int $budgetId, ?string $budgetName): ?Budget + public function findBudget(null|int $budgetId, null|string $budgetName): null|Budget { Log::debug('Now in findBudget()'); Log::debug(sprintf('Searching for budget with ID #%d...', $budgetId)); @@ -506,7 +502,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface /** * Find budget by name. */ - public function findByName(?string $name): ?Budget + public function findByName(null|string $name): null|Budget { if (null === $name) { return null; @@ -514,36 +510,36 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface $query = sprintf('%%%s%%', $name); /** @var null|Budget */ - return $this->user->budgets()->whereLike('name', $query)->first(); + return $this->user + ->budgets() + ->whereLike('name', $query) + ->first(); } /** * This method returns the oldest journal or transaction date known to this budget. * Will cache result. */ - public function firstUseDate(Budget $budget): ?Carbon + public function firstUseDate(Budget $budget): null|Carbon { $journal = $budget->transactionJournals()->orderBy('date', 'ASC')->first(); return $journal?->date; - } public function getAttachments(Budget $budget): Collection { - $set = $budget->attachments()->get(); + $set = $budget->attachments()->get(); $disk = Storage::disk('upload'); - return $set->each( - static function (Attachment $attachment) use ($disk): Attachment { // @phpstan-ignore-line - $notes = $attachment->notes()->first(); - $attachment->file_exists = $disk->exists($attachment->fileName()); - $attachment->notes_text = null !== $notes ? $notes->text : ''; + return $set->each(static function (Attachment $attachment) use ($disk): Attachment { // @phpstan-ignore-line + $notes = $attachment->notes()->first(); + $attachment->file_exists = $disk->exists($attachment->fileName()); + $attachment->notes_text = null !== $notes ? $notes->text : ''; - return $attachment; - } - ); + return $attachment; + }); } /** @@ -551,23 +547,27 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface */ public function getByIds(array $budgetIds): Collection { - return $this->user->budgets()->whereIn('id', $budgetIds)->get(); + return $this->user + ->budgets() + ->whereIn('id', $budgetIds) + ->get(); } public function getInactiveBudgets(): Collection { - return $this->user->budgets() + return $this->user + ->budgets() ->orderBy('order', 'ASC') - ->orderBy('name', 'ASC')->where('active', 0)->get() - ; + ->orderBy('name', 'ASC') + ->where('active', 0) + ->get(); } - public function getNoteText(Budget $budget): ?string + public function getNoteText(Budget $budget): null|string { $note = $budget->notes()->first(); return $note?->text; - } public function searchBudget(string $query, int $limit): Collection @@ -576,9 +576,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface if ('' !== $query) { $search->whereLike('name', sprintf('%%%s%%', $query)); } - $search->orderBy('order', 'ASC') - ->orderBy('name', 'ASC')->where('active', true) - ; + $search->orderBy('order', 'ASC')->orderBy('name', 'ASC')->where('active', true); return $search->take($limit)->get(); } @@ -598,8 +596,8 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface // exclude specific liabilities $repository = app(AccountRepositoryInterface::class); $repository->setUser($this->user); - $subset = $repository->getAccountsByType(config('firefly.valid_liabilities')); - $selection = new Collection(); + $subset = $repository->getAccountsByType(config('firefly.valid_liabilities')); + $selection = new Collection(); /** @var Account $account */ foreach ($subset as $account) { @@ -610,31 +608,31 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface // start collecting: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); - $collector->setUser($this->user) + $collector = app(GroupCollectorInterface::class); + $collector + ->setUser($this->user) ->setRange($start, $end) ->excludeDestinationAccounts($selection) ->setTypes([TransactionTypeEnum::WITHDRAWAL->value]) - ->setBudgets($this->getActiveBudgets()) - ; + ->setBudgets($this->getActiveBudgets()); - $journals = $collector->getExtractedJournals(); - $array = []; + $journals = $collector->getExtractedJournals(); + $array = []; foreach ($journals as $journal) { - $currencyId = (int) $journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $array[$currencyId] ??= [ 'id' => (string) $currencyId, 'name' => $journal['currency_name'], 'symbol' => $journal['currency_symbol'], 'code' => $journal['currency_code'], 'decimal_places' => $journal['currency_decimal_places'], - 'sum' => '0', + 'sum' => '0' ]; $array[$currencyId]['sum'] = bcadd($array[$currencyId]['sum'], Steam::negative($journal['amount'])); // also do foreign amount: - $foreignId = (int) $journal['foreign_currency_id']; + $foreignId = (int) $journal['foreign_currency_id']; if (0 !== $foreignId) { $array[$foreignId] ??= [ 'id' => (string) $foreignId, @@ -642,7 +640,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface 'symbol' => $journal['foreign_currency_symbol'], 'code' => $journal['foreign_currency_code'], 'decimal_places' => $journal['foreign_currency_decimal_places'], - 'sum' => '0', + 'sum' => '0' ]; $array[$foreignId]['sum'] = bcadd($array[$foreignId]['sum'], Steam::negative($journal['foreign_amount'])); } @@ -660,8 +658,8 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface // exclude specific liabilities $repository = app(AccountRepositoryInterface::class); $repository->setUser($this->user); - $subset = $repository->getAccountsByType(config('firefly.valid_liabilities')); - $selection = new Collection(); + $subset = $repository->getAccountsByType(config('firefly.valid_liabilities')); + $selection = new Collection(); /** @var Account $account */ foreach ($subset as $account) { @@ -672,31 +670,31 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface // start collecting: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); - $collector->setUser($this->user) + $collector = app(GroupCollectorInterface::class); + $collector + ->setUser($this->user) ->setRange($start, $end) ->excludeDestinationAccounts($selection) ->setTypes([TransactionTypeEnum::WITHDRAWAL->value]) - ->setBudget($budget) - ; + ->setBudget($budget); - $journals = $collector->getExtractedJournals(); - $array = []; + $journals = $collector->getExtractedJournals(); + $array = []; foreach ($journals as $journal) { - $currencyId = (int) $journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $array[$currencyId] ??= [ 'id' => (string) $currencyId, 'name' => $journal['currency_name'], 'symbol' => $journal['currency_symbol'], 'code' => $journal['currency_code'], 'decimal_places' => $journal['currency_decimal_places'], - 'sum' => '0', + 'sum' => '0' ]; $array[$currencyId]['sum'] = bcadd($array[$currencyId]['sum'], Steam::negative($journal['amount'])); // also do foreign amount: - $foreignId = (int) $journal['foreign_currency_id']; + $foreignId = (int) $journal['foreign_currency_id']; if (0 !== $foreignId) { $array[$foreignId] ??= [ 'id' => (string) $foreignId, @@ -704,7 +702,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface 'symbol' => $journal['foreign_currency_symbol'], 'code' => $journal['foreign_currency_code'], 'decimal_places' => $journal['foreign_currency_decimal_places'], - 'sum' => '0', + 'sum' => '0' ]; $array[$foreignId]['sum'] = bcadd($array[$foreignId]['sum'], Steam::negative($journal['foreign_amount'])); } @@ -720,22 +718,20 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface */ public function store(array $data): Budget { - $order = $this->getMaxOrder(); + $order = $this->getMaxOrder(); // this is a lame trick to communicate with the observer. - $singleton = PreferencesSingleton::getInstance(); + $singleton = PreferencesSingleton::getInstance(); $singleton->setPreference('fire_webhooks_budget_create', $data['fire_webhooks'] ?? true); try { - $newBudget = Budget::create( - [ - 'user_id' => $this->user->id, - 'user_group_id' => $this->user->user_group_id, - 'name' => $data['name'], - 'order' => $order + 1, - 'active' => array_key_exists('active', $data) ? $data['active'] : true, - ] - ); + $newBudget = Budget::create([ + 'user_id' => $this->user->id, + 'user_group_id' => $this->user->user_group_id, + 'name' => $data['name'], + 'order' => $order + 1, + 'active' => array_key_exists('active', $data) ? $data['active'] : true + ]); } catch (QueryException $e) { Log::error($e->getMessage()); Log::error($e->getTraceAsString()); @@ -751,7 +747,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface if (!array_key_exists('auto_budget_type', $data) || !array_key_exists('auto_budget_amount', $data) || !array_key_exists('auto_budget_period', $data)) { return $newBudget; } - $type = $data['auto_budget_type']; + $type = $data['auto_budget_type']; if ('none' === $type) { return $newBudget; } @@ -770,8 +766,8 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface } /** @var CurrencyRepositoryInterface $repos */ - $repos = app(CurrencyRepositoryInterface::class); - $currency = null; + $repos = app(CurrencyRepositoryInterface::class); + $currency = null; if (array_key_exists('currency_id', $data)) { $currency = $repos->find((int) $data['currency_id']); } @@ -782,30 +778,28 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface $currency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); } - $autoBudget = new AutoBudget(); + $autoBudget = new AutoBudget(); $autoBudget->budget()->associate($newBudget); $autoBudget->transaction_currency_id = $currency->id; - $autoBudget->auto_budget_type = $type; - $autoBudget->amount = $data['auto_budget_amount'] ?? '1'; - $autoBudget->period = $data['auto_budget_period'] ?? 'monthly'; + $autoBudget->auto_budget_type = $type; + $autoBudget->amount = $data['auto_budget_amount'] ?? '1'; + $autoBudget->period = $data['auto_budget_period'] ?? 'monthly'; $autoBudget->save(); // create initial budget limit. - $today = today(config('app.timezone')); - $start = Navigation::startOfPeriod($today, $autoBudget->period); - $end = Navigation::endOfPeriod($start, $autoBudget->period); + $today = today(config('app.timezone')); + $start = Navigation::startOfPeriod($today, $autoBudget->period); + $end = Navigation::endOfPeriod($start, $autoBudget->period); - $limitRepos = app(BudgetLimitRepositoryInterface::class); + $limitRepos = app(BudgetLimitRepositoryInterface::class); $limitRepos->setUser($this->user); - $limitRepos->store( - [ - 'budget_id' => $newBudget->id, - 'currency_id' => $autoBudget->transaction_currency_id, - 'start_date' => $start, - 'end_date' => $end, - 'amount' => $autoBudget->amount, - ] - ); + $limitRepos->store([ + 'budget_id' => $newBudget->id, + 'currency_id' => $autoBudget->transaction_currency_id, + 'start_date' => $start, + 'end_date' => $end, + 'amount' => $autoBudget->amount + ]); return $newBudget; } diff --git a/app/Repositories/Budget/BudgetRepositoryInterface.php b/app/Repositories/Budget/BudgetRepositoryInterface.php index b12aed2796..767691eebd 100644 --- a/app/Repositories/Budget/BudgetRepositoryInterface.php +++ b/app/Repositories/Budget/BudgetRepositoryInterface.php @@ -70,26 +70,26 @@ interface BudgetRepositoryInterface public function destroyAutoBudget(Budget $budget): void; - public function find(?int $budgetId = null): ?Budget; + public function find(null|int $budgetId = null): null|Budget; - public function findBudget(?int $budgetId, ?string $budgetName): ?Budget; + public function findBudget(null|int $budgetId, null|string $budgetName): null|Budget; /** * Find budget by name. */ - public function findByName(?string $name): ?Budget; + public function findByName(null|string $name): null|Budget; /** * This method returns the oldest journal or transaction date known to this budget. * Will cache result. */ - public function firstUseDate(Budget $budget): ?Carbon; + public function firstUseDate(Budget $budget): null|Carbon; public function getActiveBudgets(): Collection; public function getAttachments(Budget $budget): Collection; - public function getAutoBudget(Budget $budget): ?AutoBudget; + public function getAutoBudget(Budget $budget): null|AutoBudget; public function getBudgets(): Collection; @@ -102,7 +102,7 @@ interface BudgetRepositoryInterface public function getMaxOrder(): int; - public function getNoteText(Budget $budget): ?string; + public function getNoteText(Budget $budget): null|string; public function searchBudget(string $query, int $limit): Collection; diff --git a/app/Repositories/Budget/NoBudgetRepository.php b/app/Repositories/Budget/NoBudgetRepository.php index 6d53f9c243..ef5e8e6e60 100644 --- a/app/Repositories/Budget/NoBudgetRepository.php +++ b/app/Repositories/Budget/NoBudgetRepository.php @@ -24,17 +24,17 @@ declare(strict_types=1); namespace FireflyIII\Repositories\Budget; -use FireflyIII\Support\Facades\Navigation; use Carbon\Carbon; +use Deprecated; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Helpers\Collector\GroupCollectorInterface; use FireflyIII\Models\TransactionCurrency; +use FireflyIII\Support\Facades\Navigation; use FireflyIII\Support\Report\Summarizer\TransactionSummarizer; use FireflyIII\Support\Repositories\UserGroup\UserGroupInterface; use FireflyIII\Support\Repositories\UserGroup\UserGroupTrait; use Illuminate\Support\Collection; use Override; -use Deprecated; /** * Class NoBudgetRepository @@ -49,17 +49,17 @@ class NoBudgetRepository implements NoBudgetRepositoryInterface, UserGroupInterf $carbonFormat = Navigation::preferredCarbonFormat($start, $end); /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setAccounts($accounts)->setRange($start, $end); $collector->setTypes([TransactionTypeEnum::WITHDRAWAL->value]); $collector->withoutBudget(); - $journals = $collector->getExtractedJournals(); - $data = []; + $journals = $collector->getExtractedJournals(); + $data = []; /** @var array $journal */ foreach ($journals as $journal) { - $currencyId = (int) $journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $data[$currencyId] ??= [ 'id' => 0, @@ -70,9 +70,9 @@ class NoBudgetRepository implements NoBudgetRepositoryInterface, UserGroupInterf 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_decimal_places' => $journal['currency_decimal_places'], - 'entries' => [], + 'entries' => [] ]; - $date = $journal['date']->format($carbonFormat); + $date = $journal['date']->format($carbonFormat); if (!array_key_exists($date, $data[$currencyId]['entries'])) { $data[$currencyId]['entries'][$date] = '0'; @@ -83,10 +83,10 @@ class NoBudgetRepository implements NoBudgetRepositoryInterface, UserGroupInterf return $data; } - public function sumExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?TransactionCurrency $currency = null): array + public function sumExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|TransactionCurrency $currency = null): array { /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value]); if ($accounts instanceof Collection && $accounts->count() > 0) { @@ -104,7 +104,7 @@ class NoBudgetRepository implements NoBudgetRepositoryInterface, UserGroupInterf } #[Override] - public function collectExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?TransactionCurrency $currency = null): array + public function collectExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|TransactionCurrency $currency = null): array { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); diff --git a/app/Repositories/Budget/NoBudgetRepositoryInterface.php b/app/Repositories/Budget/NoBudgetRepositoryInterface.php index 13d12a1122..af2a734b00 100644 --- a/app/Repositories/Budget/NoBudgetRepositoryInterface.php +++ b/app/Repositories/Budget/NoBudgetRepositoryInterface.php @@ -48,7 +48,7 @@ interface NoBudgetRepositoryInterface #[Deprecated] public function getNoBudgetPeriodReport(Collection $accounts, Carbon $start, Carbon $end): array; - public function sumExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?TransactionCurrency $currency = null): array; + public function sumExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|TransactionCurrency $currency = null): array; - public function collectExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?TransactionCurrency $currency = null): array; + public function collectExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|TransactionCurrency $currency = null): array; } diff --git a/app/Repositories/Budget/OperationsRepository.php b/app/Repositories/Budget/OperationsRepository.php index e3dc0e1e19..c178926027 100644 --- a/app/Repositories/Budget/OperationsRepository.php +++ b/app/Repositories/Budget/OperationsRepository.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Repositories\Budget; -use FireflyIII\Support\Facades\Navigation; use Carbon\Carbon; use Deprecated; use FireflyIII\Enums\TransactionTypeEnum; @@ -34,6 +33,8 @@ use FireflyIII\Models\Budget; use FireflyIII\Models\TransactionCurrency; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Support\Facades\Amount; +use FireflyIII\Support\Facades\Navigation; +use FireflyIII\Support\Facades\Steam; use FireflyIII\Support\Http\Api\ExchangeRateConverter; use FireflyIII\Support\Report\Summarizer\TransactionSummarizer; use FireflyIII\Support\Repositories\UserGroup\UserGroupInterface; @@ -41,7 +42,6 @@ use FireflyIII\Support\Repositories\UserGroup\UserGroupTrait; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; use Override; -use FireflyIII\Support\Facades\Steam; /** * Class OperationsRepository @@ -68,7 +68,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn ++$count; Log::debug(sprintf('Found %d budget limits. Per day is %s, total is %s', $count, $perDay, $total)); } - $avg = $total; + $avg = $total; if ($count > 0) { $avg = bcdiv($total, (string) $count); } @@ -89,19 +89,19 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn // get all transactions: /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setAccounts($accounts)->setRange($start, $end); $collector->setBudgets($budgets); - $journals = $collector->getExtractedJournals(); + $journals = $collector->getExtractedJournals(); // loop transactions: /** @var array $journal */ foreach ($journals as $journal) { // prep data array for currency: - $budgetId = (int) $journal['budget_id']; - $budgetName = $journal['budget_name']; - $currencyId = (int) $journal['currency_id']; - $key = sprintf('%d-%d', $budgetId, $currencyId); + $budgetId = (int) $journal['budget_id']; + $budgetName = $journal['budget_name']; + $currencyId = (int) $journal['currency_id']; + $key = sprintf('%d-%d', $budgetId, $currencyId); $data[$key] ??= [ 'id' => $budgetId, @@ -112,9 +112,9 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_decimal_places' => $journal['currency_decimal_places'], - 'entries' => [], + 'entries' => [] ]; - $date = $journal['date']->format($carbonFormat); + $date = $journal['date']->format($carbonFormat); $data[$key]['entries'][$date] = bcadd($data[$key]['entries'][$date] ?? '0', (string) $journal['amount']); } @@ -126,10 +126,10 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn * which have the specified budget set to them. It's grouped per currency, with as few details in the array * as possible. Amounts are always negative. */ - public function listExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $budgets = null): array + public function listExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $budgets = null): array { /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value]); if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); @@ -141,8 +141,8 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $collector->setBudgets($this->getBudgets()); } $collector->withBudgetInformation()->withAccountInformation()->withCategoryInformation(); - $journals = $collector->getExtractedJournals(); - $array = []; + $journals = $collector->getExtractedJournals(); + $array = []; // if needs conversion to primary. $convertToPrimary = Amount::convertToPrimary($this->user); @@ -153,13 +153,11 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $currencySymbol = $primaryCurrency->symbol; $currencyDecimalPlaces = $primaryCurrency->decimal_places; $converter = new ExchangeRateConverter(); - $currencies = [ - $currencyId => $primaryCurrency, - ]; + $currencies = [$currencyId => $primaryCurrency]; foreach ($journals as $journal) { - $amount = Steam::negative($journal['amount']); - $journalCurrencyId = (int) $journal['currency_id']; + $amount = Steam::negative($journal['amount']); + $journalCurrencyId = (int) $journal['currency_id']; if (false === $convertToPrimary) { $currencyId = $journalCurrencyId; $currencyName = $journal['currency_name']; @@ -172,8 +170,8 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $amount = $converter->convert($currencies[$journalCurrencyId], $primaryCurrency, $journal['date'], $amount); } - $budgetId = (int) $journal['budget_id']; - $budgetName = (string) $journal['budget_name']; + $budgetId = (int) $journal['budget_id']; + $budgetName = (string) $journal['budget_name']; // catch "no budget" entries. if (0 === $budgetId) { @@ -181,25 +179,25 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn } // info about the currency: - $array[$currencyId] ??= [ + $array[$currencyId] ??= [ 'budgets' => [], 'currency_id' => $currencyId, 'currency_name' => $currencyName, 'currency_symbol' => $currencySymbol, 'currency_code' => $currencyCode, - 'currency_decimal_places' => $currencyDecimalPlaces, + 'currency_decimal_places' => $currencyDecimalPlaces ]; // info about the categories: $array[$currencyId]['budgets'][$budgetId] ??= [ 'id' => $budgetId, 'name' => $budgetName, - 'transaction_journals' => [], + 'transaction_journals' => [] ]; // add journal to array: // only a subset of the fields. - $journalId = (int) $journal['transaction_journal_id']; + $journalId = (int) $journal['transaction_journal_id']; $array[$currencyId]['budgets'][$budgetId]['transaction_journals'][$journalId] = [ 'amount' => $amount, 'destination_account_id' => $journal['destination_account_id'], @@ -212,7 +210,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'category_name' => $journal['category_name'], 'description' => $journal['description'], 'transaction_group_id' => $journal['transaction_group_id'], - 'date' => $journal['date'], + 'date' => $journal['date'] ]; } @@ -231,12 +229,12 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn * @SuppressWarnings("PHPMD.ExcessiveParameterList") */ public function sumExpenses( - Carbon $start, - Carbon $end, - ?Collection $accounts = null, - ?Collection $budgets = null, - ?TransactionCurrency $currency = null, - bool $convertToPrimary = false + Carbon $start, + Carbon $end, + null|Collection $accounts = null, + null|Collection $budgets = null, + null|TransactionCurrency $currency = null, + bool $convertToPrimary = false ): array { Log::debug(sprintf('Start of %s(date, date, array, array, "%s", %s).', __METHOD__, $currency?->code, var_export($convertToPrimary, true))); // this collector excludes all transfers TO liabilities (which are also withdrawals) @@ -245,8 +243,8 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $repository = app(AccountRepositoryInterface::class); $repository->setUser($this->user); - $subset = $repository->getAccountsByType(config('firefly.valid_liabilities')); - $selection = new Collection(); + $subset = $repository->getAccountsByType(config('firefly.valid_liabilities')); + $selection = new Collection(); /** @var Account $account */ foreach ($subset as $account) { @@ -256,12 +254,12 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn } /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); - $collector->setUser($this->user) + $collector = app(GroupCollectorInterface::class); + $collector + ->setUser($this->user) ->setRange($start, $end) // ->excludeDestinationAccounts($selection) - ->setTypes([TransactionTypeEnum::WITHDRAWAL->value]) - ; + ->setTypes([TransactionTypeEnum::WITHDRAWAL->value]); if ($accounts instanceof Collection) { $collector->setAccounts($accounts); @@ -276,7 +274,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn if ($budgets->count() > 0) { $collector->setBudgets($budgets); } - $journals = $collector->getExtractedJournals(); + $journals = $collector->getExtractedJournals(); // same but for transactions in the foreign currency: if ($currency instanceof TransactionCurrency) { @@ -289,14 +287,22 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn return $summarizer->groupByCurrencyId($journals, 'negative', false); } - public function sumCollectedExpenses(array $expenses, Carbon $start, Carbon $end, TransactionCurrency $transactionCurrency, bool $convertToPrimary = false): array - { + public function sumCollectedExpenses( + array $expenses, + Carbon $start, + Carbon $end, + TransactionCurrency $transactionCurrency, + bool $convertToPrimary = false + ): array { Log::debug(sprintf('Start of %s.', __METHOD__)); $summarizer = new TransactionSummarizer($this->user); $summarizer->setConvertToPrimary($convertToPrimary); // filter $journals by range AND currency if it is present. - $expenses = array_filter($expenses, static fn (array $expense): bool => $expense['date']->between($start, $end) && $expense['currency_id'] === $transactionCurrency->id); + $expenses = array_filter( + $expenses, + static fn(array $expense): bool => $expense['date']->between($start, $end) && $expense['currency_id'] === $transactionCurrency->id + ); return $summarizer->groupByCurrencyId($expenses, 'negative', false); } @@ -308,14 +314,19 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $summarizer->setConvertToPrimary($convertToPrimary); // filter $journals by range AND currency if it is present. - $expenses = array_filter($expenses, static fn (array $expense): bool => $expense['budget_id'] === $budget->id); + $expenses = array_filter($expenses, static fn(array $expense): bool => $expense['budget_id'] === $budget->id); return $summarizer->groupByCurrencyId($expenses, 'negative', false); } #[Override] - public function collectExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $budgets = null, ?TransactionCurrency $currency = null): array - { + public function collectExpenses( + Carbon $start, + Carbon $end, + null|Collection $accounts = null, + null|Collection $budgets = null, + null|TransactionCurrency $currency = null + ): array { Log::debug(sprintf('Start of %s(%s, %s, array, array, "%s").', __METHOD__, $start->toW3cString(), $end->toW3cString(), $currency?->code)); // this collector excludes all transfers TO liabilities (which are also withdrawals) // because those expenses only become expenses once they move from the liability to the friend. @@ -323,8 +334,8 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $repository = app(AccountRepositoryInterface::class); $repository->setUser($this->user); - $subset = $repository->getAccountsByType(config('firefly.valid_liabilities')); - $selection = new Collection(); + $subset = $repository->getAccountsByType(config('firefly.valid_liabilities')); + $selection = new Collection(); /** @var Account $account */ foreach ($subset as $account) { @@ -334,12 +345,12 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn } /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); - $collector->setUser($this->user) + $collector = app(GroupCollectorInterface::class); + $collector + ->setUser($this->user) ->setRange($start, $end) // ->excludeDestinationAccounts($selection) - ->setTypes([TransactionTypeEnum::WITHDRAWAL->value]) - ; + ->setTypes([TransactionTypeEnum::WITHDRAWAL->value]); if ($accounts instanceof Collection) { $collector->setAccounts($accounts); diff --git a/app/Repositories/Budget/OperationsRepositoryInterface.php b/app/Repositories/Budget/OperationsRepositoryInterface.php index 01cce862d3..d3bf640541 100644 --- a/app/Repositories/Budget/OperationsRepositoryInterface.php +++ b/app/Repositories/Budget/OperationsRepositoryInterface.php @@ -60,23 +60,35 @@ interface OperationsRepositoryInterface * which have the specified budget set to them. It's grouped per currency, with as few details in the array * as possible. Amounts are always negative. */ - public function listExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $budgets = null): array; + public function listExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $budgets = null): array; /** * @SuppressWarnings("PHPMD.ExcessiveParameterList") */ public function sumExpenses( - Carbon $start, - Carbon $end, - ?Collection $accounts = null, - ?Collection $budgets = null, - ?TransactionCurrency $currency = null, - bool $convertToPrimary = false + Carbon $start, + Carbon $end, + null|Collection $accounts = null, + null|Collection $budgets = null, + null|TransactionCurrency $currency = null, + bool $convertToPrimary = false ): array; - public function sumCollectedExpenses(array $expenses, Carbon $start, Carbon $end, TransactionCurrency $transactionCurrency, bool $convertToPrimary = false): array; + public function sumCollectedExpenses( + array $expenses, + Carbon $start, + Carbon $end, + TransactionCurrency $transactionCurrency, + bool $convertToPrimary = false + ): array; public function sumCollectedExpensesByBudget(array $expenses, Budget $budget, bool $convertToPrimary = false): array; - public function collectExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $budgets = null, ?TransactionCurrency $currency = null): array; + public function collectExpenses( + Carbon $start, + Carbon $end, + null|Collection $accounts = null, + null|Collection $budgets = null, + null|TransactionCurrency $currency = null + ): array; } diff --git a/app/Repositories/Category/CategoryRepository.php b/app/Repositories/Category/CategoryRepository.php index a2db39b8a5..b5cf291396 100644 --- a/app/Repositories/Category/CategoryRepository.php +++ b/app/Repositories/Category/CategoryRepository.php @@ -100,13 +100,17 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf */ public function getCategories(): Collection { - return $this->user->categories()->with(['attachments'])->orderBy('name', 'ASC')->get(); + return $this->user + ->categories() + ->with(['attachments']) + ->orderBy('name', 'ASC') + ->get(); } /** * @throws FireflyException */ - public function findCategory(?int $categoryId, ?string $categoryName): ?Category + public function findCategory(null|int $categoryId, null|string $categoryName): null|Category { Log::debug('Now in findCategory()'); Log::debug(sprintf('Searching for category with ID #%d...', $categoryId)); @@ -130,7 +134,7 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf /** * Find a category or return NULL */ - public function find(int $categoryId): ?Category + public function find(int $categoryId): null|Category { /** @var null|Category */ return $this->user->categories()->find($categoryId); @@ -139,10 +143,13 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf /** * Find a category. */ - public function findByName(string $name): ?Category + public function findByName(string $name): null|Category { /** @var null|Category */ - return $this->user->categories()->where('name', $name)->first(['categories.*']); + return $this->user + ->categories() + ->where('name', $name) + ->first(['categories.*']); } /** @@ -151,7 +158,7 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf public function store(array $data): Category { /** @var CategoryFactory $factory */ - $factory = app(CategoryFactory::class); + $factory = app(CategoryFactory::class); $factory->setUser($this->user); $category = $factory->findOrCreate(null, $data['name']); @@ -177,7 +184,7 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf public function updateNotes(Category $category, string $notes): void { - $dbNote = $category->notes()->first(); + $dbNote = $category->notes()->first(); if (null === $dbNote) { $dbNote = new Note(); $dbNote->noteable()->associate($category); @@ -186,7 +193,7 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf $dbNote->save(); } - public function firstUseDate(Category $category): ?Carbon + public function firstUseDate(Category $category): null|Carbon { $firstJournalDate = $this->getFirstJournalDate($category); $firstTransactionDate = $this->getFirstTransactionDate($category); @@ -208,22 +215,21 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf return $firstJournalDate; } - private function getFirstJournalDate(Category $category): ?Carbon + private function getFirstJournalDate(Category $category): null|Carbon { $query = $category->transactionJournals()->orderBy('date', 'ASC'); $result = $query->first(['transaction_journals.*']); return $result?->date; - } - private function getFirstTransactionDate(Category $category): ?Carbon + private function getFirstTransactionDate(Category $category): null|Carbon { // check transactions: - $query = $category->transactions() + $query = $category + ->transactions() ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') - ->orderBy('transaction_journals.date', 'ASC') - ; + ->orderBy('transaction_journals.date', 'ASC'); $lastTransaction = $query->first(['transaction_journals.*']); if (null !== $lastTransaction) { @@ -235,19 +241,17 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf public function getAttachments(Category $category): Collection { - $set = $category->attachments()->get(); + $set = $category->attachments()->get(); $disk = Storage::disk('upload'); - return $set->each( - static function (Attachment $attachment) use ($disk): Attachment { // @phpstan-ignore-line - $notes = $attachment->notes()->first(); - $attachment->file_exists = $disk->exists($attachment->fileName()); - $attachment->notes_text = null !== $notes ? $notes->text : ''; + return $set->each(static function (Attachment $attachment) use ($disk): Attachment { // @phpstan-ignore-line + $notes = $attachment->notes()->first(); + $attachment->file_exists = $disk->exists($attachment->fileName()); + $attachment->notes_text = null !== $notes ? $notes->text : ''; - return $attachment; - } - ); + return $attachment; + }); } /** @@ -255,21 +259,23 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf */ public function getByIds(array $categoryIds): Collection { - return $this->user->categories()->whereIn('id', $categoryIds)->get(); + return $this->user + ->categories() + ->whereIn('id', $categoryIds) + ->get(); } - public function getNoteText(Category $category): ?string + public function getNoteText(Category $category): null|string { $dbNote = $category->notes()->first(); return $dbNote?->text; - } /** * @throws Exception */ - public function lastUseDate(Category $category, Collection $accounts): ?Carbon + public function lastUseDate(Category $category, Collection $accounts): null|Carbon { $lastJournalDate = $this->getLastJournalDate($category, $accounts); $lastTransactionDate = $this->getLastTransactionDate($category, $accounts); @@ -291,9 +297,9 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf return $lastJournalDate; } - private function getLastJournalDate(Category $category, Collection $accounts): ?Carbon + private function getLastJournalDate(Category $category, Collection $accounts): null|Carbon { - $query = $category->transactionJournals()->orderBy('date', 'DESC'); + $query = $category->transactionJournals()->orderBy('date', 'DESC'); if ($accounts->count() > 0) { $query->leftJoin('transactions as t', 't.transaction_journal_id', '=', 'transaction_journals.id'); @@ -303,19 +309,18 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf $result = $query->first(['transaction_journals.*']); return $result?->date; - } /** * @throws Exception */ - private function getLastTransactionDate(Category $category, Collection $accounts): ?Carbon + private function getLastTransactionDate(Category $category, Collection $accounts): null|Carbon { // check transactions: - $query = $category->transactions() + $query = $category + ->transactions() ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') - ->orderBy('transaction_journals.date', 'DESC') - ; + ->orderBy('transaction_journals.date', 'DESC'); if ($accounts->count() > 0) { // filter journals: $query->whereIn('transactions.account_id', $accounts->pluck('id')->toArray()); @@ -355,7 +360,8 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf { Log::debug(sprintf('periodCollection(#%d, %s, %s)', $category->id, $start->format('Y-m-d'), $end->format('Y-m-d'))); - return $category->transactionJournals() + return $category + ->transactionJournals() ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id') ->leftJoin('transaction_currencies', 'transaction_currencies.id', '=', 'transactions.transaction_currency_id') @@ -384,9 +390,8 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf 'transaction_journals.transaction_currency_id', 'transactions.amount', 'transactions.native_amount as pc_amount', - 'transactions.foreign_amount', + 'transactions.foreign_amount' ]) - ->toArray() - ; + ->toArray(); } } diff --git a/app/Repositories/Category/CategoryRepositoryInterface.php b/app/Repositories/Category/CategoryRepositoryInterface.php index cef58d2d17..c411df7b5c 100644 --- a/app/Repositories/Category/CategoryRepositoryInterface.php +++ b/app/Repositories/Category/CategoryRepositoryInterface.php @@ -60,16 +60,16 @@ interface CategoryRepositoryInterface /** * Find a category or return NULL */ - public function find(int $categoryId): ?Category; + public function find(int $categoryId): null|Category; /** * Find a category. */ - public function findByName(string $name): ?Category; + public function findByName(string $name): null|Category; - public function findCategory(?int $categoryId, ?string $categoryName): ?Category; + public function findCategory(null|int $categoryId, null|string $categoryName): null|Category; - public function firstUseDate(Category $category): ?Carbon; + public function firstUseDate(Category $category): null|Carbon; public function getAttachments(Category $category): Collection; @@ -83,12 +83,12 @@ interface CategoryRepositoryInterface */ public function getCategories(): Collection; - public function getNoteText(Category $category): ?string; + public function getNoteText(Category $category): null|string; /** * Return most recent transaction(journal) date or null when never used before. */ - public function lastUseDate(Category $category, Collection $accounts): ?Carbon; + public function lastUseDate(Category $category, Collection $accounts): null|Carbon; /** * Remove notes. diff --git a/app/Repositories/Category/NoCategoryRepository.php b/app/Repositories/Category/NoCategoryRepository.php index 9326df43a7..64b7b5fee7 100644 --- a/app/Repositories/Category/NoCategoryRepository.php +++ b/app/Repositories/Category/NoCategoryRepository.php @@ -45,7 +45,7 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface, UserGroupIn * which have no category set to them. It's grouped per currency, with as few details in the array * as possible. Amounts are always negative. */ - public function listExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null): array + public function listExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null): array { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); @@ -53,34 +53,33 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface, UserGroupIn if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); } - $journals = $collector->getExtractedJournals(); - $array = []; + $journals = $collector->getExtractedJournals(); + $array = []; foreach ($journals as $journal) { $currencyId = (int) $journal['currency_id']; - $array[$currencyId] ??= [ + $array[$currencyId] ??= [ 'categories' => [], 'currency_id' => $currencyId, 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_code' => $journal['currency_code'], - 'currency_decimal_places' => $journal['currency_decimal_places'], + 'currency_decimal_places' => $journal['currency_decimal_places'] ]; // info about the non-existent category: $array[$currencyId]['categories'][0] ??= [ 'id' => 0, 'name' => (string) trans('firefly.noCategory'), - 'transaction_journals' => [], + 'transaction_journals' => [] ]; // add journal to array: // only a subset of the fields. - $journalId = (int) $journal['transaction_journal_id']; - $array[$currencyId]['categories'][0]['transaction_journals'][$journalId] - = [ - 'amount' => Steam::negative($journal['amount']), - 'date' => $journal['date'], - ]; + $journalId = (int) $journal['transaction_journal_id']; + $array[$currencyId]['categories'][0]['transaction_journals'][$journalId] = [ + 'amount' => Steam::negative($journal['amount']), + 'date' => $journal['date'] + ]; } return $array; @@ -91,7 +90,7 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface, UserGroupIn * which have no category set to them. It's grouped per currency, with as few details in the array * as possible. Amounts are always positive. */ - public function listIncome(Carbon $start, Carbon $end, ?Collection $accounts = null): array + public function listIncome(Carbon $start, Carbon $end, null|Collection $accounts = null): array { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); @@ -99,34 +98,33 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface, UserGroupIn if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); } - $journals = $collector->getExtractedJournals(); - $array = []; + $journals = $collector->getExtractedJournals(); + $array = []; foreach ($journals as $journal) { $currencyId = (int) $journal['currency_id']; - $array[$currencyId] ??= [ + $array[$currencyId] ??= [ 'categories' => [], 'currency_id' => $currencyId, 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_code' => $journal['currency_code'], - 'currency_decimal_places' => $journal['currency_decimal_places'], + 'currency_decimal_places' => $journal['currency_decimal_places'] ]; // info about the non-existent category: $array[$currencyId]['categories'][0] ??= [ 'id' => 0, 'name' => (string) trans('firefly.noCategory'), - 'transaction_journals' => [], + 'transaction_journals' => [] ]; // add journal to array: // only a subset of the fields. - $journalId = (int) $journal['transaction_journal_id']; - $array[$currencyId]['categories'][0]['transaction_journals'][$journalId] - = [ - 'amount' => Steam::positive($journal['amount']), - 'date' => $journal['date'], - ]; + $journalId = (int) $journal['transaction_journal_id']; + $array[$currencyId]['categories'][0]['transaction_journals'][$journalId] = [ + 'amount' => Steam::positive($journal['amount']), + 'date' => $journal['date'] + ]; } return $array; @@ -135,10 +133,10 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface, UserGroupIn /** * Sum of withdrawal journals in period without a category, grouped per currency. Amounts are always negative. */ - public function sumExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null): array + public function sumExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null): array { /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value])->withoutCategory(); if ($accounts instanceof Collection && $accounts->count() > 0) { @@ -153,7 +151,7 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface, UserGroupIn /** * Sum of income journals in period without a category, grouped per currency. Amounts are always positive. */ - public function sumIncome(Carbon $start, Carbon $end, ?Collection $accounts = null): array + public function sumIncome(Carbon $start, Carbon $end, null|Collection $accounts = null): array { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); @@ -162,18 +160,18 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface, UserGroupIn if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); } - $journals = $collector->getExtractedJournals(); - $array = []; + $journals = $collector->getExtractedJournals(); + $array = []; foreach ($journals as $journal) { - $currencyId = (int) $journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $array[$currencyId] ??= [ 'sum' => '0', 'currency_id' => $currencyId, 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_code' => $journal['currency_code'], - 'currency_decimal_places' => $journal['currency_decimal_places'], + 'currency_decimal_places' => $journal['currency_decimal_places'] ]; $array[$currencyId]['sum'] = bcadd($array[$currencyId]['sum'], Steam::positive($journal['amount'])); } @@ -181,7 +179,7 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface, UserGroupIn return $array; } - public function sumTransfers(Carbon $start, Carbon $end, ?Collection $accounts = null): array + public function sumTransfers(Carbon $start, Carbon $end, null|Collection $accounts = null): array { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); @@ -190,18 +188,18 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface, UserGroupIn if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); } - $journals = $collector->getExtractedJournals(); - $array = []; + $journals = $collector->getExtractedJournals(); + $array = []; foreach ($journals as $journal) { - $currencyId = (int) $journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $array[$currencyId] ??= [ 'sum' => '0', 'currency_id' => $currencyId, 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_code' => $journal['currency_code'], - 'currency_decimal_places' => $journal['currency_decimal_places'], + 'currency_decimal_places' => $journal['currency_decimal_places'] ]; $array[$currencyId]['sum'] = bcadd($array[$currencyId]['sum'], Steam::positive($journal['amount'])); } diff --git a/app/Repositories/Category/NoCategoryRepositoryInterface.php b/app/Repositories/Category/NoCategoryRepositoryInterface.php index 58b25504f8..e2e37d94a6 100644 --- a/app/Repositories/Category/NoCategoryRepositoryInterface.php +++ b/app/Repositories/Category/NoCategoryRepositoryInterface.php @@ -48,27 +48,27 @@ interface NoCategoryRepositoryInterface * which have no category set to them. It's grouped per currency, with as few details in the array * as possible. Amounts are always negative. */ - public function listExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null): array; + public function listExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null): array; /** * This method returns a list of all the deposit transaction journals (as arrays) set in that period * which have no category set to them. It's grouped per currency, with as few details in the array * as possible. Amounts are always positive. */ - public function listIncome(Carbon $start, Carbon $end, ?Collection $accounts = null): array; + public function listIncome(Carbon $start, Carbon $end, null|Collection $accounts = null): array; /** * Sum of withdrawal journals in period without a category, grouped per currency. Amounts are always negative. */ - public function sumExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null): array; + public function sumExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null): array; /** * Sum of income journals in period without a category, grouped per currency. Amounts are always positive. */ - public function sumIncome(Carbon $start, Carbon $end, ?Collection $accounts = null): array; + public function sumIncome(Carbon $start, Carbon $end, null|Collection $accounts = null): array; /** * Sum of transfers in period without a category, grouped per currency. Amounts are always positive. */ - public function sumTransfers(Carbon $start, Carbon $end, ?Collection $accounts = null): array; + public function sumTransfers(Carbon $start, Carbon $end, null|Collection $accounts = null): array; } diff --git a/app/Repositories/Category/OperationsRepository.php b/app/Repositories/Category/OperationsRepository.php index 8a67bdcde5..a9af7df3a1 100644 --- a/app/Repositories/Category/OperationsRepository.php +++ b/app/Repositories/Category/OperationsRepository.php @@ -50,7 +50,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn * * First currency, then categories. */ - public function listExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array + public function listExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); @@ -66,13 +66,13 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $collector->setCategories($this->getCategories()); } $collector->withCategoryInformation()->withAccountInformation()->withBudgetInformation(); - $journals = $collector->getExtractedJournals(); - $array = []; + $journals = $collector->getExtractedJournals(); + $array = []; foreach ($journals as $journal) { - $currencyId = (int) $journal['currency_id']; - $categoryId = (int) $journal['category_id']; - $categoryName = (string) $journal['category_name']; + $currencyId = (int) $journal['currency_id']; + $categoryId = (int) $journal['category_id']; + $categoryName = (string) $journal['category_name']; // catch "no category" entries. if (0 === $categoryId) { @@ -80,25 +80,25 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn } // info about the currency: - $array[$currencyId] ??= [ + $array[$currencyId] ??= [ 'categories' => [], 'currency_id' => (string) $currencyId, 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_code' => $journal['currency_code'], - 'currency_decimal_places' => $journal['currency_decimal_places'], + 'currency_decimal_places' => $journal['currency_decimal_places'] ]; // info about the categories: $array[$currencyId]['categories'][$categoryId] ??= [ 'id' => (string) $categoryId, 'name' => $categoryName, - 'transaction_journals' => [], + 'transaction_journals' => [] ]; // add journal to array: // only a subset of the fields. - $journalId = (int) $journal['transaction_journal_id']; + $journalId = (int) $journal['transaction_journal_id']; $array[$currencyId]['categories'][$categoryId]['transaction_journals'][$journalId] = [ 'amount' => Steam::negative($journal['amount']), 'date' => $journal['date'], @@ -108,7 +108,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'destination_account_id' => (string) $journal['destination_account_id'], 'destination_account_name' => $journal['destination_account_name'], 'description' => $journal['description'], - 'transaction_group_id' => (string) $journal['transaction_group_id'], + 'transaction_group_id' => (string) $journal['transaction_group_id'] ]; } @@ -128,7 +128,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn * which have the specified category set to them. It's grouped per currency, with as few details in the array * as possible. Amounts are always positive. */ - public function listIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array + public function listIncome(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); @@ -144,13 +144,13 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $collector->setCategories($this->getCategories()); } $collector->withCategoryInformation()->withAccountInformation(); - $journals = $collector->getExtractedJournals(); - $array = []; + $journals = $collector->getExtractedJournals(); + $array = []; foreach ($journals as $journal) { - $currencyId = (int) $journal['currency_id']; - $categoryId = (int) $journal['category_id']; - $categoryName = (string) $journal['category_name']; + $currencyId = (int) $journal['currency_id']; + $categoryId = (int) $journal['category_id']; + $categoryName = (string) $journal['category_name']; // catch "no category" entries. if (0 === $categoryId) { @@ -158,25 +158,25 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn } // info about the currency: - $array[$currencyId] ??= [ + $array[$currencyId] ??= [ 'categories' => [], 'currency_id' => (string) $currencyId, 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_code' => $journal['currency_code'], - 'currency_decimal_places' => $journal['currency_decimal_places'], + 'currency_decimal_places' => $journal['currency_decimal_places'] ]; // info about the categories: $array[$currencyId]['categories'][$categoryId] ??= [ 'id' => (string) $categoryId, 'name' => $categoryName, - 'transaction_journals' => [], + 'transaction_journals' => [] ]; // add journal to array: // only a subset of the fields. - $journalId = (int) $journal['transaction_journal_id']; + $journalId = (int) $journal['transaction_journal_id']; $array[$currencyId]['categories'][$categoryId]['transaction_journals'][$journalId] = [ 'amount' => Steam::positive($journal['amount']), 'date' => $journal['date'], @@ -185,20 +185,23 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'source_account_name' => $journal['source_account_name'], 'destination_account_name' => $journal['destination_account_name'], 'description' => $journal['description'], - 'transaction_group_id' => (string) $journal['transaction_group_id'], + 'transaction_group_id' => (string) $journal['transaction_group_id'] ]; } return $array; } - public function listTransferredIn(Carbon $start, Carbon $end, Collection $accounts, ?Collection $categories = null): array + public function listTransferredIn(Carbon $start, Carbon $end, Collection $accounts, null|Collection $categories = null): array { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); - $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::TRANSFER->value]) - ->setDestinationAccounts($accounts)->excludeSourceAccounts($accounts) - ; + $collector + ->setUser($this->user) + ->setRange($start, $end) + ->setTypes([TransactionTypeEnum::TRANSFER->value]) + ->setDestinationAccounts($accounts) + ->excludeSourceAccounts($accounts); if ($categories instanceof Collection && $categories->count() > 0) { $collector->setCategories($categories); } @@ -206,13 +209,13 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $collector->setCategories($this->getCategories()); } $collector->withCategoryInformation()->withAccountInformation()->withBudgetInformation(); - $journals = $collector->getExtractedJournals(); - $array = []; + $journals = $collector->getExtractedJournals(); + $array = []; foreach ($journals as $journal) { - $currencyId = (int) $journal['currency_id']; - $categoryId = (int) $journal['category_id']; - $categoryName = (string) $journal['category_name']; + $currencyId = (int) $journal['currency_id']; + $categoryId = (int) $journal['category_id']; + $categoryName = (string) $journal['category_name']; // catch "no category" entries. if (0 === $categoryId) { @@ -220,25 +223,25 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn } // info about the currency: - $array[$currencyId] ??= [ + $array[$currencyId] ??= [ 'categories' => [], 'currency_id' => (string) $currencyId, 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_code' => $journal['currency_code'], - 'currency_decimal_places' => $journal['currency_decimal_places'], + 'currency_decimal_places' => $journal['currency_decimal_places'] ]; // info about the categories: $array[$currencyId]['categories'][$categoryId] ??= [ 'id' => (string) $categoryId, 'name' => $categoryName, - 'transaction_journals' => [], + 'transaction_journals' => [] ]; // add journal to array: // only a subset of the fields. - $journalId = (int) $journal['transaction_journal_id']; + $journalId = (int) $journal['transaction_journal_id']; $array[$currencyId]['categories'][$categoryId]['transaction_journals'][$journalId] = [ 'amount' => Steam::positive($journal['amount']), 'date' => $journal['date'], @@ -248,20 +251,23 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'destination_account_id' => (string) $journal['destination_account_id'], 'destination_account_name' => $journal['destination_account_name'], 'description' => $journal['description'], - 'transaction_group_id' => (string) $journal['transaction_group_id'], + 'transaction_group_id' => (string) $journal['transaction_group_id'] ]; } return $array; } - public function listTransferredOut(Carbon $start, Carbon $end, Collection $accounts, ?Collection $categories = null): array + public function listTransferredOut(Carbon $start, Carbon $end, Collection $accounts, null|Collection $categories = null): array { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); - $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::TRANSFER->value]) - ->setSourceAccounts($accounts)->excludeDestinationAccounts($accounts) - ; + $collector + ->setUser($this->user) + ->setRange($start, $end) + ->setTypes([TransactionTypeEnum::TRANSFER->value]) + ->setSourceAccounts($accounts) + ->excludeDestinationAccounts($accounts); if ($categories instanceof Collection && $categories->count() > 0) { $collector->setCategories($categories); } @@ -269,13 +275,13 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $collector->setCategories($this->getCategories()); } $collector->withCategoryInformation()->withAccountInformation()->withBudgetInformation(); - $journals = $collector->getExtractedJournals(); - $array = []; + $journals = $collector->getExtractedJournals(); + $array = []; foreach ($journals as $journal) { - $currencyId = (int) $journal['currency_id']; - $categoryId = (int) $journal['category_id']; - $categoryName = (string) $journal['category_name']; + $currencyId = (int) $journal['currency_id']; + $categoryId = (int) $journal['category_id']; + $categoryName = (string) $journal['category_name']; // catch "no category" entries. if (0 === $categoryId) { @@ -283,25 +289,25 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn } // info about the currency: - $array[$currencyId] ??= [ + $array[$currencyId] ??= [ 'categories' => [], 'currency_id' => (string) $currencyId, 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_code' => $journal['currency_code'], - 'currency_decimal_places' => $journal['currency_decimal_places'], + 'currency_decimal_places' => $journal['currency_decimal_places'] ]; // info about the categories: $array[$currencyId]['categories'][$categoryId] ??= [ 'id' => (string) $categoryId, 'name' => $categoryName, - 'transaction_journals' => [], + 'transaction_journals' => [] ]; // add journal to array: // only a subset of the fields. - $journalId = (int) $journal['transaction_journal_id']; + $journalId = (int) $journal['transaction_journal_id']; $array[$currencyId]['categories'][$categoryId]['transaction_journals'][$journalId] = [ 'amount' => Steam::negative($journal['amount']), 'date' => $journal['date'], @@ -311,7 +317,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'destination_account_id' => (string) $journal['destination_account_id'], 'destination_account_name' => $journal['destination_account_name'], 'description' => $journal['description'], - 'transaction_group_id' => (string) $journal['transaction_group_id'], + 'transaction_group_id' => (string) $journal['transaction_group_id'] ]; } @@ -321,10 +327,10 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn /** * Sum of withdrawal journals in period for a set of categories, grouped per currency. Amounts are always negative. */ - public function sumExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array + public function sumExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array { /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value]); if ($accounts instanceof Collection && $accounts->count() > 0) { @@ -344,13 +350,11 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn /** * Sum of income journals in period for a set of categories, grouped per currency. Amounts are always positive. */ - public function sumIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array + public function sumIncome(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array { /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); - $collector->setUser($this->user)->setRange($start, $end) - ->setTypes([TransactionTypeEnum::DEPOSIT->value]) - ; + $collector = app(GroupCollectorInterface::class); + $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::DEPOSIT->value]); if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); @@ -366,12 +370,12 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn foreach ($journals as $journal) { // Almost the same as in \FireflyIII\Repositories\Budget\OperationsRepository::sumExpenses - $amount = '0'; - $currencyId = (int) $journal['currency_id']; - $currencyName = $journal['currency_name']; - $currencySymbol = $journal['currency_symbol']; - $currencyCode = $journal['currency_code']; - $currencyDecimalPlaces = $journal['currency_decimal_places']; + $amount = '0'; + $currencyId = (int) $journal['currency_id']; + $currencyName = $journal['currency_name']; + $currencySymbol = $journal['currency_symbol']; + $currencyCode = $journal['currency_code']; + $currencyDecimalPlaces = $journal['currency_decimal_places']; if ($convertToPrimary) { $amount = Amount::getAmountFromJournal($journal); if ($primary->id !== (int) $journal['currency_id'] && $primary->id !== (int) $journal['foreign_currency_id']) { @@ -402,7 +406,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'currency_name' => $currencyName, 'currency_symbol' => $currencySymbol, 'currency_code' => $currencyCode, - 'currency_decimal_places' => $currencyDecimalPlaces, + 'currency_decimal_places' => $currencyDecimalPlaces ]; $array[$currencyId]['sum'] = bcadd($array[$currencyId]['sum'], Steam::positive($amount)); } @@ -413,13 +417,11 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn /** * Sum of income journals in period for a set of categories, grouped per currency. Amounts are always positive. */ - public function sumTransfers(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array + public function sumTransfers(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); - $collector->setUser($this->user)->setRange($start, $end) - ->setTypes([TransactionTypeEnum::TRANSFER->value]) - ; + $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::TRANSFER->value]); if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); @@ -428,18 +430,18 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $categories = $this->getCategories(); } $collector->setCategories($categories); - $journals = $collector->getExtractedJournals(); - $array = []; + $journals = $collector->getExtractedJournals(); + $array = []; foreach ($journals as $journal) { - $currencyId = (int) $journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $array[$currencyId] ??= [ 'sum' => '0', 'currency_id' => (string) $currencyId, 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_code' => $journal['currency_code'], - 'currency_decimal_places' => $journal['currency_decimal_places'], + 'currency_decimal_places' => $journal['currency_decimal_places'] ]; $array[$currencyId]['sum'] = bcadd($array[$currencyId]['sum'], Steam::positive($journal['amount'])); } @@ -447,7 +449,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn return $array; } - public function collectExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array + public function collectExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); @@ -465,13 +467,11 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn return $collector->getExtractedJournals(); } - public function collectIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array + public function collectIncome(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); - $collector->setUser($this->user)->setRange($start, $end) - ->setTypes([TransactionTypeEnum::DEPOSIT->value]) - ; + $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::DEPOSIT->value]); if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); @@ -484,13 +484,11 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn return $collector->getExtractedJournals(); } - public function collectTransfers(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array + public function collectTransfers(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); - $collector->setUser($this->user)->setRange($start, $end) - ->setTypes([TransactionTypeEnum::TRANSFER->value]) - ; + $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::TRANSFER->value]); if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); @@ -510,7 +508,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $summarizer->setConvertToPrimary($convertToPrimary); // filter $journals by range AND currency if it is present. - $expenses = array_filter($expenses, static fn (array $expense): bool => $expense['category_id'] === $category->id); + $expenses = array_filter($expenses, static fn(array $expense): bool => $expense['category_id'] === $category->id); return $summarizer->groupByCurrencyId($expenses, $method, false); } diff --git a/app/Repositories/Category/OperationsRepositoryInterface.php b/app/Repositories/Category/OperationsRepositoryInterface.php index e8fcdab41b..89db4b2ff9 100644 --- a/app/Repositories/Category/OperationsRepositoryInterface.php +++ b/app/Repositories/Category/OperationsRepositoryInterface.php @@ -49,14 +49,14 @@ interface OperationsRepositoryInterface * which have the specified category set to them. It's grouped per currency, with as few details in the array * as possible. Amounts are always negative. */ - public function listExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array; + public function listExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array; /** * This method returns a list of all the deposit transaction journals (as arrays) set in that period * which have the specified category set to them. It's grouped per currency, with as few details in the array * as possible. Amounts are always positive. */ - public function listIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array; + public function listIncome(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array; /** * This method returns a list of all the transfer transaction journals (as arrays) set in that period @@ -64,7 +64,7 @@ interface OperationsRepositoryInterface * It excludes any transfers between the listed accounts. * It's grouped per currency, with as few details in the array as possible. Amounts are always negative. */ - public function listTransferredIn(Carbon $start, Carbon $end, Collection $accounts, ?Collection $categories = null): array; + public function listTransferredIn(Carbon $start, Carbon $end, Collection $accounts, null|Collection $categories = null): array; /** * This method returns a list of all the transfer transaction journals (as arrays) set in that period @@ -72,28 +72,28 @@ interface OperationsRepositoryInterface * It excludes any transfers between the listed accounts. * It's grouped per currency, with as few details in the array as possible. Amounts are always negative. */ - public function listTransferredOut(Carbon $start, Carbon $end, Collection $accounts, ?Collection $categories = null): array; + public function listTransferredOut(Carbon $start, Carbon $end, Collection $accounts, null|Collection $categories = null): array; /** * Sum of withdrawal journals in period for a set of categories, grouped per currency. Amounts are always negative. */ - public function sumExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array; + public function sumExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array; - public function collectExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array; + public function collectExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array; - public function collectIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array; + public function collectIncome(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array; - public function collectTransfers(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array; + public function collectTransfers(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array; public function sumCollectedTransactionsByCategory(array $expenses, Category $category, string $method, bool $convertToPrimary = false): array; /** * Sum of income journals in period for a set of categories, grouped per currency. Amounts are always positive. */ - public function sumIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array; + public function sumIncome(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array; /** * Sum of transfers in period for a set of categories, grouped per currency. Amounts are always positive. */ - public function sumTransfers(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array; + public function sumTransfers(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $categories = null): array; } diff --git a/app/Repositories/Currency/CurrencyRepository.php b/app/Repositories/Currency/CurrencyRepository.php index ffcc802d89..e321ae0731 100644 --- a/app/Repositories/Currency/CurrencyRepository.php +++ b/app/Repositories/Currency/CurrencyRepository.php @@ -68,10 +68,10 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf /** * @throws JsonException */ - public function currencyInUseAt(TransactionCurrency $currency): ?string + public function currencyInUseAt(TransactionCurrency $currency): null|string { Log::debug(sprintf('Now in currencyInUse() for #%d ("%s")', $currency->id, $currency->code)); - $countJournals = $this->countJournals($currency); + $countJournals = $this->countJournals($currency); if ($countJournals > 0) { Log::info(sprintf('Count journals is %d, return true.', $countJournals)); @@ -86,7 +86,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf } // is being used in accounts: - $meta = AccountMeta::where('name', 'currency_id')->where('data', json_encode((string)$currency->id))->count(); + $meta = AccountMeta::where('name', 'currency_id')->where('data', json_encode((string) $currency->id))->count(); if ($meta > 0) { Log::info(sprintf('Used in %d accounts as currency_id, return true. ', $meta)); @@ -94,7 +94,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf } // second search using integer check. - $meta = AccountMeta::where('name', 'currency_id')->where('data', json_encode((int)$currency->id))->count(); + $meta = AccountMeta::where('name', 'currency_id')->where('data', json_encode((int) $currency->id))->count(); if ($meta > 0) { Log::info(sprintf('Used in %d accounts as currency_id, return true. ', $meta)); @@ -102,7 +102,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf } // is being used in bills: - $bills = Bill::where('transaction_currency_id', $currency->id)->count(); + $bills = Bill::where('transaction_currency_id', $currency->id)->count(); if ($bills > 0) { Log::info(sprintf('Used in %d bills as currency, return true. ', $bills)); @@ -120,10 +120,11 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf } // is being used in accounts (as integer) - $meta = AccountMeta::leftJoin('accounts', 'accounts.id', '=', 'account_meta.account_id') + $meta = AccountMeta::leftJoin('accounts', 'accounts.id', '=', 'account_meta.account_id') ->whereNull('accounts.deleted_at') - ->where('account_meta.name', 'currency_id')->where('account_meta.data', json_encode($currency->id))->count() - ; + ->where('account_meta.name', 'currency_id') + ->where('account_meta.data', json_encode($currency->id)) + ->count(); if ($meta > 0) { Log::info(sprintf('Used in %d accounts as currency_id, return true. ', $meta)); @@ -139,7 +140,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf } // is being used in budget limits - $budgetLimit = BudgetLimit::where('transaction_currency_id', $currency->id)->count(); + $budgetLimit = BudgetLimit::where('transaction_currency_id', $currency->id)->count(); if ($budgetLimit > 0) { Log::info(sprintf('Used in %d budget limits as currency, return true. ', $budgetLimit)); @@ -147,7 +148,11 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf } // is the default currency for the user or the system - $count = $this->userGroup->currencies()->where('transaction_currencies.id', $currency->id)->wherePivot('group_default', 1)->count(); + $count = $this->userGroup + ->currencies() + ->where('transaction_currencies.id', $currency->id) + ->wherePivot('group_default', 1) + ->count(); if ($count > 0) { Log::info('Is the default currency of the user, return true.'); @@ -155,7 +160,11 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf } // is the default currency for the user or the system - $count = $this->userGroup->currencies()->where('transaction_currencies.id', $currency->id)->wherePivot('group_default', 1)->count(); + $count = $this->userGroup + ->currencies() + ->where('transaction_currencies.id', $currency->id) + ->wherePivot('group_default', 1) + ->count(); if ($count > 0) { Log::info('Is the default currency of the user group, return true.'); @@ -184,10 +193,12 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf $local = $this->get(); return $all->map(static function (TransactionCurrency $current) use ($local): TransactionCurrency { - $hasId = $local->contains(static fn (TransactionCurrency $entry): bool => $entry->id === $current->id); - $isPrimary = $local->contains(static fn (TransactionCurrency $entry): bool => 1 === (int)$entry->pivot->group_default && $entry->id === $current->id); + $hasId = $local->contains(static fn(TransactionCurrency $entry): bool => $entry->id === $current->id); + $isPrimary = $local->contains( + static fn(TransactionCurrency $entry): bool => 1 === (int) $entry->pivot->group_default && $entry->id === $current->id + ); $current->userGroupEnabled = $hasId; - $current->userGroupNative = $isPrimary; + $current->userGroupNative = $isPrimary; return $current; }); @@ -195,10 +206,14 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf public function get(): Collection { - $all = $this->userGroup->currencies()->orderBy('code', 'ASC')->withPivot(['group_default'])->get(); + $all = $this->userGroup + ->currencies() + ->orderBy('code', 'ASC') + ->withPivot(['group_default']) + ->get(); $all->map(static function (TransactionCurrency $current): TransactionCurrency { // @phpstan-ignore-line $current->userGroupEnabled = true; - $current->userGroupNative = 1 === (int)$current->pivot->group_default; + $current->userGroupNative = 1 === (int) $current->pivot->group_default; return $current; }); @@ -226,7 +241,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf $currency->save(); } - public function findByName(string $name): ?TransactionCurrency + public function findByName(string $name): null|TransactionCurrency { return TransactionCurrency::where('name', $name)->first(); } @@ -234,7 +249,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf /** * Find by object, ID or code. Returns user default or system default. */ - public function findCurrency(?int $currencyId, ?string $currencyCode): TransactionCurrency + public function findCurrency(null|int $currencyId, null|string $currencyCode): TransactionCurrency { $result = $this->findCurrencyNull($currencyId, $currencyCode); @@ -257,11 +272,11 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf /** * Find by object, ID or code. Returns NULL if nothing found. */ - public function findCurrencyNull(?int $currencyId, ?string $currencyCode): ?TransactionCurrency + public function findCurrencyNull(null|int $currencyId, null|string $currencyCode): null|TransactionCurrency { Log::debug(sprintf('Now in findCurrencyNull(%s, "%s")', var_export($currencyId, true), $currencyCode)); if (null !== $currencyId && 0 !== $currencyId) { - $result = $this->find((int)$currencyId); + $result = $this->find((int) $currencyId); if ($result instanceof TransactionCurrency) { Log::debug(sprintf('Found currency by ID: %s', $result->code)); @@ -285,7 +300,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf } #[Override] - public function find(int $currencyId): ?TransactionCurrency + public function find(int $currencyId): null|TransactionCurrency { try { $result = Amount::getTransactionCurrencyById($currencyId); @@ -299,7 +314,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf /** * Find by currency code, return NULL if unfound. */ - public function findByCode(string $currencyCode): ?TransactionCurrency + public function findByCode(string $currencyCode): null|TransactionCurrency { try { $result = Amount::getTransactionCurrencyByCode($currencyCode); @@ -329,22 +344,23 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf /** * Get currency exchange rate. */ - public function getExchangeRate(TransactionCurrency $fromCurrency, TransactionCurrency $toCurrency, Carbon $date): ?CurrencyExchangeRate + public function getExchangeRate(TransactionCurrency $fromCurrency, TransactionCurrency $toCurrency, Carbon $date): null|CurrencyExchangeRate { if ($fromCurrency->id === $toCurrency->id) { - $rate = new CurrencyExchangeRate(); + $rate = new CurrencyExchangeRate(); $rate->rate = '1'; - $rate->id = 0; + $rate->id = 0; return $rate; } /** @var null|CurrencyExchangeRate $rate */ - $rate = $this->user->currencyExchangeRates() + $rate = $this->user + ->currencyExchangeRates() ->where('from_currency_id', $fromCurrency->id) ->where('to_currency_id', $toCurrency->id) - ->where('date', $date->format('Y-m-d'))->first() - ; + ->where('date', $date->format('Y-m-d')) + ->first(); if (null !== $rate) { Log::debug(sprintf('Found cached exchange rate in database for %s to %s on %s', $fromCurrency->code, $toCurrency->code, $date->format('Y-m-d'))); @@ -374,17 +390,15 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf */ public function setExchangeRate(TransactionCurrency $fromCurrency, TransactionCurrency $toCurrency, Carbon $date, float $rate): CurrencyExchangeRate { - return CurrencyExchangeRate::create( - [ - 'user_id' => $this->user->id, - 'user_group_id' => $this->userGroup->id, - 'from_currency_id' => $fromCurrency->id, - 'to_currency_id' => $toCurrency->id, - 'date' => $date, - 'date_tz' => $date->format('e'), - 'rate' => $rate, - ] - ); + return CurrencyExchangeRate::create([ + 'user_id' => $this->user->id, + 'user_group_id' => $this->userGroup->id, + 'from_currency_id' => $fromCurrency->id, + 'to_currency_id' => $toCurrency->id, + 'date' => $date, + 'date_tz' => $date->format('e'), + 'rate' => $rate + ]); } /** diff --git a/app/Repositories/Currency/CurrencyRepositoryInterface.php b/app/Repositories/Currency/CurrencyRepositoryInterface.php index 820b57c73c..fdcfc91705 100644 --- a/app/Repositories/Currency/CurrencyRepositoryInterface.php +++ b/app/Repositories/Currency/CurrencyRepositoryInterface.php @@ -53,7 +53,7 @@ interface CurrencyRepositoryInterface /** * @throws FireflyException */ - public function currencyInUseAt(TransactionCurrency $currency): ?string; + public function currencyInUseAt(TransactionCurrency $currency): null|string; public function destroy(TransactionCurrency $currency): bool; @@ -61,20 +61,20 @@ interface CurrencyRepositoryInterface public function enable(TransactionCurrency $currency): void; - public function find(int $currencyId): ?TransactionCurrency; + public function find(int $currencyId): null|TransactionCurrency; /** * Find by currency code, return NULL if unfound. * * Used in the download exchange rates cron job. Does not require user object. */ - public function findByCode(string $currencyCode): ?TransactionCurrency; + public function findByCode(string $currencyCode): null|TransactionCurrency; - public function findByName(string $name): ?TransactionCurrency; + public function findByName(string $name): null|TransactionCurrency; - public function findCurrency(?int $currencyId, ?string $currencyCode): TransactionCurrency; + public function findCurrency(null|int $currencyId, null|string $currencyCode): TransactionCurrency; - public function findCurrencyNull(?int $currencyId, ?string $currencyCode): ?TransactionCurrency; + public function findCurrencyNull(null|int $currencyId, null|string $currencyCode): null|TransactionCurrency; /** * Get the user group's currencies. @@ -98,7 +98,7 @@ interface CurrencyRepositoryInterface * * Used in the download exchange rate cron job. Needs the user object! */ - public function getExchangeRate(TransactionCurrency $fromCurrency, TransactionCurrency $toCurrency, Carbon $date): ?CurrencyExchangeRate; + public function getExchangeRate(TransactionCurrency $fromCurrency, TransactionCurrency $toCurrency, Carbon $date): null|CurrencyExchangeRate; public function isFallbackCurrency(TransactionCurrency $currency): bool; diff --git a/app/Repositories/ExchangeRate/ExchangeRateRepository.php b/app/Repositories/ExchangeRate/ExchangeRateRepository.php index dc77777069..5ae8c4b0a4 100644 --- a/app/Repositories/ExchangeRate/ExchangeRateRepository.php +++ b/app/Repositories/ExchangeRate/ExchangeRateRepository.php @@ -40,69 +40,68 @@ class ExchangeRateRepository implements ExchangeRateRepositoryInterface, UserGro #[Override] public function deleteRate(CurrencyExchangeRate $rate): void { - $this->userGroup->currencyExchangeRates()->where('id', $rate->id)->delete(); + $this->userGroup + ->currencyExchangeRates() + ->where('id', $rate->id) + ->delete(); } #[Override] public function getAll(): Collection { - return $this->userGroup->currencyExchangeRates()->orderBy('date', 'ASC')->get(); + return $this->userGroup + ->currencyExchangeRates() + ->orderBy('date', 'ASC') + ->get(); } #[Override] public function getRates(TransactionCurrency $from, TransactionCurrency $to): Collection { // orderBy('date', 'DESC')->toRawSql(); - return - $this->userGroup->currencyExchangeRates() - ->where(static function (Builder $q1) use ($from, $to): void { - $q1->where(static function (Builder $q) use ($from, $to): void { - $q->where('from_currency_id', $from->id) - ->where('to_currency_id', $to->id) - ; - })->orWhere(static function (Builder $q) use ($from, $to): void { - $q->where('from_currency_id', $to->id) - ->where('to_currency_id', $from->id) - ; - }); - }) - ->orderBy('date', 'DESC') - ->get(['currency_exchange_rates.*']) - ; - + return $this->userGroup + ->currencyExchangeRates() + ->where(static function (Builder $q1) use ($from, $to): void { + $q1->where(static function (Builder $q) use ($from, $to): void { + $q->where('from_currency_id', $from->id)->where('to_currency_id', $to->id); + })->orWhere(static function (Builder $q) use ($from, $to): void { + $q->where('from_currency_id', $to->id)->where('to_currency_id', $from->id); + }); + }) + ->orderBy('date', 'DESC') + ->get(['currency_exchange_rates.*']); } #[Override] - public function getSpecificRateOnDate(TransactionCurrency $from, TransactionCurrency $to, Carbon $date): ?CurrencyExchangeRate + public function getSpecificRateOnDate(TransactionCurrency $from, TransactionCurrency $to, Carbon $date): null|CurrencyExchangeRate { /** @var null|CurrencyExchangeRate */ - return - $this->userGroup->currencyExchangeRates() - ->where('from_currency_id', $from->id) - ->where('to_currency_id', $to->id) - ->where('date', $date->format('Y-m-d')) - ->first() - ; + return $this->userGroup + ->currencyExchangeRates() + ->where('from_currency_id', $from->id) + ->where('to_currency_id', $to->id) + ->where('date', $date->format('Y-m-d')) + ->first(); } #[Override] public function storeExchangeRate(TransactionCurrency $from, TransactionCurrency $to, string $rate, Carbon $date): CurrencyExchangeRate { - $object = new CurrencyExchangeRate(); - $object->user_id = auth()->user()->id; - $object->user_group_id = $this->userGroup->id; + $object = new CurrencyExchangeRate(); + $object->user_id = auth()->user()->id; + $object->user_group_id = $this->userGroup->id; $object->from_currency_id = $from->id; - $object->to_currency_id = $to->id; - $object->rate = $rate; - $object->date = $date; - $object->date_tz = $date->format('e'); + $object->to_currency_id = $to->id; + $object->rate = $rate; + $object->date = $date; + $object->date_tz = $date->format('e'); $object->save(); return $object; } #[Override] - public function updateExchangeRate(CurrencyExchangeRate $object, string $rate, ?Carbon $date = null): CurrencyExchangeRate + public function updateExchangeRate(CurrencyExchangeRate $object, string $rate, null|Carbon $date = null): CurrencyExchangeRate { $object->rate = $rate; if ($date instanceof Carbon) { @@ -115,10 +114,10 @@ class ExchangeRateRepository implements ExchangeRateRepositoryInterface, UserGro public function deleteRates(TransactionCurrency $from, TransactionCurrency $to): void { - $this->userGroup->currencyExchangeRates() + $this->userGroup + ->currencyExchangeRates() ->where('from_currency_id', $from->id) ->where('to_currency_id', $to->id) - ->delete() - ; + ->delete(); } } diff --git a/app/Repositories/ExchangeRate/ExchangeRateRepositoryInterface.php b/app/Repositories/ExchangeRate/ExchangeRateRepositoryInterface.php index 04f8ac1072..7b76aaf862 100644 --- a/app/Repositories/ExchangeRate/ExchangeRateRepositoryInterface.php +++ b/app/Repositories/ExchangeRate/ExchangeRateRepositoryInterface.php @@ -53,9 +53,9 @@ interface ExchangeRateRepositoryInterface public function getRates(TransactionCurrency $from, TransactionCurrency $to): Collection; - public function getSpecificRateOnDate(TransactionCurrency $from, TransactionCurrency $to, Carbon $date): ?CurrencyExchangeRate; + public function getSpecificRateOnDate(TransactionCurrency $from, TransactionCurrency $to, Carbon $date): null|CurrencyExchangeRate; public function storeExchangeRate(TransactionCurrency $from, TransactionCurrency $to, string $rate, Carbon $date): CurrencyExchangeRate; - public function updateExchangeRate(CurrencyExchangeRate $object, string $rate, ?Carbon $date = null): CurrencyExchangeRate; + public function updateExchangeRate(CurrencyExchangeRate $object, string $rate, null|Carbon $date = null): CurrencyExchangeRate; } diff --git a/app/Repositories/Journal/JournalAPIRepository.php b/app/Repositories/Journal/JournalAPIRepository.php index 5a6dccdb64..97336d237c 100644 --- a/app/Repositories/Journal/JournalAPIRepository.php +++ b/app/Repositories/Journal/JournalAPIRepository.php @@ -44,13 +44,12 @@ class JournalAPIRepository implements JournalAPIRepositoryInterface, UserGroupIn /** * Returns transaction by ID. Used to validate attachments. */ - public function findTransaction(int $transactionId): ?Transaction + public function findTransaction(int $transactionId): null|Transaction { return Transaction::leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->where('transaction_journals.user_id', $this->user->id) ->where('transactions.id', $transactionId) - ->first(['transactions.*']) - ; + ->first(['transactions.*']); } /** @@ -60,19 +59,17 @@ class JournalAPIRepository implements JournalAPIRepositoryInterface, UserGroupIn */ public function getAttachments(TransactionJournal $journal): Collection { - $set = $journal->attachments; + $set = $journal->attachments; $disk = Storage::disk('upload'); - return $set->each( - static function (Attachment $attachment) use ($disk): Attachment { - $notes = $attachment->notes()->first(); - $attachment->file_exists = $disk->exists($attachment->fileName()); - $attachment->notes_text = null !== $notes ? $notes->text : ''; // TODO should not set notes like this. + return $set->each(static function (Attachment $attachment) use ($disk): Attachment { + $notes = $attachment->notes()->first(); + $attachment->file_exists = $disk->exists($attachment->fileName()); + $attachment->notes_text = null !== $notes ? $notes->text : ''; // TODO should not set notes like this. - return $attachment; - } - ); + return $attachment; + }); } public function getJournalLinks(TransactionJournal $journal): Collection @@ -88,11 +85,9 @@ class JournalAPIRepository implements JournalAPIRepositoryInterface, UserGroupIn public function getPiggyBankEvents(TransactionJournal $journal): Collection { $events = $journal->piggyBankEvents()->get(); - $events->each( - static function (PiggyBankEvent $event): void { // @phpstan-ignore-line - $event->piggyBank = PiggyBank::withTrashed()->find($event->piggy_bank_id); - } - ); + $events->each(static function (PiggyBankEvent $event): void { // @phpstan-ignore-line + $event->piggyBank = PiggyBank::withTrashed()->find($event->piggy_bank_id); + }); return $events; } diff --git a/app/Repositories/Journal/JournalAPIRepositoryInterface.php b/app/Repositories/Journal/JournalAPIRepositoryInterface.php index 454250c8e4..7bc226caba 100644 --- a/app/Repositories/Journal/JournalAPIRepositoryInterface.php +++ b/app/Repositories/Journal/JournalAPIRepositoryInterface.php @@ -47,7 +47,7 @@ interface JournalAPIRepositoryInterface /** * Returns transaction by ID. Used to validate attachments. */ - public function findTransaction(int $transactionId): ?Transaction; + public function findTransaction(int $transactionId): null|Transaction; /** * Return all attachments for journal. diff --git a/app/Repositories/Journal/JournalCLIRepository.php b/app/Repositories/Journal/JournalCLIRepository.php index eaaaf600b4..70eedf240b 100644 --- a/app/Repositories/Journal/JournalCLIRepository.php +++ b/app/Repositories/Journal/JournalCLIRepository.php @@ -49,8 +49,7 @@ class JournalCLIRepository implements JournalCLIRepositoryInterface, UserGroupIn return TransactionJournal::leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id') ->whereIn('transaction_types.type', $types) ->with(['user', 'transactionType', 'transactionCurrency', 'transactions', 'transactions.account']) - ->get(['transaction_journals.*']) - ; + ->get(['transaction_journals.*']); } /** @@ -58,7 +57,7 @@ class JournalCLIRepository implements JournalCLIRepositoryInterface, UserGroupIn */ public function getJournalBudgetId(TransactionJournal $journal): int { - $budget = $journal->budgets()->first(); + $budget = $journal->budgets()->first(); if (null !== $budget) { return $budget->id; } @@ -78,7 +77,7 @@ class JournalCLIRepository implements JournalCLIRepositoryInterface, UserGroupIn */ public function getJournalCategoryId(TransactionJournal $journal): int { - $category = $journal->categories()->first(); + $category = $journal->categories()->first(); if (null !== $category) { return $category->id; } @@ -104,7 +103,7 @@ class JournalCLIRepository implements JournalCLIRepositoryInterface, UserGroupIn /** * Return Carbon value of a meta field (or NULL). */ - public function getMetaDate(TransactionJournal $journal, string $field): ?Carbon + public function getMetaDate(TransactionJournal $journal, string $field): null|Carbon { $cache = new CacheProperties(); $cache->addProperty('journal-meta-updated'); @@ -128,9 +127,9 @@ class JournalCLIRepository implements JournalCLIRepositoryInterface, UserGroupIn /** * Return value of a meta field (or NULL) as a string. */ - public function getMetaField(TransactionJournal $journal, string $field): ?string + public function getMetaField(TransactionJournal $journal, string $field): null|string { - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty('journal-meta-updated'); $cache->addProperty($journal->id); $cache->addProperty($field); @@ -139,12 +138,12 @@ class JournalCLIRepository implements JournalCLIRepositoryInterface, UserGroupIn return $cache->get(); } - $entry = $journal->transactionJournalMeta()->where('name', $field)->first(); + $entry = $journal->transactionJournalMeta()->where('name', $field)->first(); if (null === $entry) { return null; } - $value = $entry->data; + $value = $entry->data; if (is_array($value)) { $return = implode(',', $value); @@ -163,12 +162,11 @@ class JournalCLIRepository implements JournalCLIRepositoryInterface, UserGroupIn /** * Return text of a note attached to journal, or NULL */ - public function getNoteText(TransactionJournal $journal): ?string + public function getNoteText(TransactionJournal $journal): null|string { $note = $journal->notes()->first(); return $note?->text; - } /** @@ -177,9 +175,9 @@ class JournalCLIRepository implements JournalCLIRepositoryInterface, UserGroupIn */ public function getSplitJournals(): Collection { - $query = TransactionJournal::leftJoin('transactions', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') - ->groupBy('transaction_journals.id') - ; + $query = TransactionJournal::leftJoin('transactions', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')->groupBy( + 'transaction_journals.id' + ); $result = $query->get(['transaction_journals.id as id', DB::raw('count(transactions.id) as transaction_count')]); $journalIds = []; @@ -191,9 +189,7 @@ class JournalCLIRepository implements JournalCLIRepositoryInterface, UserGroupIn } $journalIds = array_unique($journalIds); - return TransactionJournal::with(['transactions']) - ->whereIn('id', $journalIds)->get() - ; + return TransactionJournal::with(['transactions'])->whereIn('id', $journalIds)->get(); } /** diff --git a/app/Repositories/Journal/JournalCLIRepositoryInterface.php b/app/Repositories/Journal/JournalCLIRepositoryInterface.php index 4a43340142..10e3da2922 100644 --- a/app/Repositories/Journal/JournalCLIRepositoryInterface.php +++ b/app/Repositories/Journal/JournalCLIRepositoryInterface.php @@ -67,17 +67,17 @@ interface JournalCLIRepositoryInterface /** * Return Carbon value of a meta field (or NULL). */ - public function getMetaDate(TransactionJournal $journal, string $field): ?Carbon; + public function getMetaDate(TransactionJournal $journal, string $field): null|Carbon; /** * Return value of a meta field (or NULL). */ - public function getMetaField(TransactionJournal $journal, string $field): ?string; + public function getMetaField(TransactionJournal $journal, string $field): null|string; /** * Return text of a note attached to journal, or NULL */ - public function getNoteText(TransactionJournal $journal): ?string; + public function getNoteText(TransactionJournal $journal): null|string; /** * Returns all journals with more than 2 transactions. Should only return empty collections diff --git a/app/Repositories/Journal/JournalRepository.php b/app/Repositories/Journal/JournalRepository.php index 6340d048b7..4f7748d37e 100644 --- a/app/Repositories/Journal/JournalRepository.php +++ b/app/Repositories/Journal/JournalRepository.php @@ -67,16 +67,18 @@ class JournalRepository implements JournalRepositoryInterface, UserGroupInterfac ->transactionJournals() ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id') ->whereIn('transaction_types.type', $types) - ->get(['transaction_journals.*']) - ; + ->get(['transaction_journals.*']); } /** * Get users first transaction journal or NULL. */ - public function firstNull(): ?TransactionJournal + public function firstNull(): null|TransactionJournal { - return $this->user->transactionJournals()->orderBy('date', 'ASC')->first(['transaction_journals.*']); + return $this->user + ->transactionJournals() + ->orderBy('date', 'ASC') + ->first(['transaction_journals.*']); } public function getDestinationAccount(TransactionJournal $journal): Account @@ -95,7 +97,7 @@ class JournalRepository implements JournalRepositoryInterface, UserGroupInterfac */ public function getJournalTotal(TransactionJournal $journal): string { - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($journal->id); $cache->addProperty('amount-positive'); if ($cache->has()) { @@ -110,9 +112,12 @@ class JournalRepository implements JournalRepositoryInterface, UserGroupInterfac return $amount; } - public function getLast(): ?TransactionJournal + public function getLast(): null|TransactionJournal { - return $this->user->transactionJournals()->orderBy('date', 'DESC')->first(['transaction_journals.*']); + return $this->user + ->transactionJournals() + ->orderBy('date', 'DESC') + ->first(['transaction_journals.*']); } public function getLinkNoteText(TransactionJournalLink $link): string @@ -126,7 +131,7 @@ class JournalRepository implements JournalRepositoryInterface, UserGroupInterfac /** * Return Carbon value of a meta field (or NULL). */ - public function getMetaDateById(int $journalId, string $field): ?Carbon + public function getMetaDateById(int $journalId, string $field): null|Carbon { $cache = new CacheProperties(); $cache->addProperty('journal-meta-updated'); @@ -136,9 +141,7 @@ class JournalRepository implements JournalRepositoryInterface, UserGroupInterfac if ($cache->has()) { return new Carbon($cache->get()); } - $entry = TransactionJournalMeta::where('transaction_journal_id', $journalId) - ->where('name', $field)->first() - ; + $entry = TransactionJournalMeta::where('transaction_journal_id', $journalId)->where('name', $field)->first(); if (null === $entry) { return null; } @@ -169,7 +172,7 @@ class JournalRepository implements JournalRepositoryInterface, UserGroupInterfac /** * Find a specific journal. */ - public function find(int $journalId): ?TransactionJournal + public function find(int $journalId): null|TransactionJournal { /** @var null|TransactionJournal */ return $this->user->transactionJournals()->find($journalId); @@ -180,10 +183,10 @@ class JournalRepository implements JournalRepositoryInterface, UserGroupInterfac */ public function searchJournalDescriptions(string $search, int $limit): Collection { - $query = $this->user->transactionJournals() + $query = $this->user + ->transactionJournals() ->orderBy('date', 'DESC') - ->orderBy('description', 'ASC') - ; + ->orderBy('description', 'ASC'); if ('' !== $search) { $query->whereLike('description', sprintf('%%%s%%', $search)); } @@ -207,11 +210,7 @@ class JournalRepository implements JournalRepositoryInterface, UserGroupInterfac $service = app(JournalUpdateService::class); $service->setTransactionJournal($journal); - $service->setData( - [ - 'budget_id' => $budgetId, - ] - ); + $service->setData(['budget_id' => $budgetId]); $service->update(); $journal->refresh(); @@ -226,11 +225,7 @@ class JournalRepository implements JournalRepositoryInterface, UserGroupInterfac /** @var JournalUpdateService $service */ $service = app(JournalUpdateService::class); $service->setTransactionJournal($journal); - $service->setData( - [ - 'category_name' => $category, - ] - ); + $service->setData(['category_name' => $category]); $service->update(); $journal->refresh(); @@ -245,11 +240,7 @@ class JournalRepository implements JournalRepositoryInterface, UserGroupInterfac /** @var JournalUpdateService $service */ $service = app(JournalUpdateService::class); $service->setTransactionJournal($journal); - $service->setData( - [ - 'tags' => $tags, - ] - ); + $service->setData(['tags' => $tags]); $service->update(); $journal->refresh(); diff --git a/app/Repositories/Journal/JournalRepositoryInterface.php b/app/Repositories/Journal/JournalRepositoryInterface.php index 8971bf9234..f5bc93f8e5 100644 --- a/app/Repositories/Journal/JournalRepositoryInterface.php +++ b/app/Repositories/Journal/JournalRepositoryInterface.php @@ -60,14 +60,14 @@ interface JournalRepositoryInterface /** * Find a specific journal. */ - public function find(int $journalId): ?TransactionJournal; + public function find(int $journalId): null|TransactionJournal; public function findByType(array $types): Collection; /** * Get users very first transaction journal. */ - public function firstNull(): ?TransactionJournal; + public function firstNull(): null|TransactionJournal; /** * Returns the destination account of the journal. @@ -81,14 +81,14 @@ interface JournalRepositoryInterface */ public function getJournalTotal(TransactionJournal $journal): string; - public function getLast(): ?TransactionJournal; + public function getLast(): null|TransactionJournal; public function getLinkNoteText(TransactionJournalLink $link): string; /** * Return Carbon value of a meta field (or NULL). */ - public function getMetaDateById(int $journalId, string $field): ?Carbon; + public function getMetaDateById(int $journalId, string $field): null|Carbon; /** * Returns the source account of the journal. diff --git a/app/Repositories/LinkType/LinkTypeRepository.php b/app/Repositories/LinkType/LinkTypeRepository.php index e978381255..6e787b26cc 100644 --- a/app/Repositories/LinkType/LinkTypeRepository.php +++ b/app/Repositories/LinkType/LinkTypeRepository.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace FireflyIII\Repositories\LinkType; -use Illuminate\Support\Facades\Log; use Exception; use FireflyIII\Models\LinkType; use FireflyIII\Models\Note; @@ -32,6 +31,7 @@ use FireflyIII\Models\TransactionJournalLink; use FireflyIII\Support\Repositories\UserGroup\UserGroupInterface; use FireflyIII\Support\Repositories\UserGroup\UserGroupTrait; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Log; /** * Class LinkTypeRepository. @@ -45,7 +45,7 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf return $linkType->transactionJournalLinks()->count(); } - public function destroy(LinkType $linkType, ?LinkType $moveTo = null): bool + public function destroy(LinkType $linkType, null|LinkType $moveTo = null): bool { if ($moveTo instanceof LinkType) { TransactionJournalLink::where('link_type_id', $linkType->id)->update(['link_type_id' => $moveTo->id]); @@ -57,13 +57,13 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf public function update(LinkType $linkType, array $data): LinkType { - if (array_key_exists('name', $data) && '' !== (string)$data['name']) { + if (array_key_exists('name', $data) && '' !== (string) $data['name']) { $linkType->name = $data['name']; } - if (array_key_exists('inward', $data) && '' !== (string)$data['inward']) { + if (array_key_exists('inward', $data) && '' !== (string) $data['inward']) { $linkType->inward = $data['inward']; } - if (array_key_exists('outward', $data) && '' !== (string)$data['outward']) { + if (array_key_exists('outward', $data) && '' !== (string) $data['outward']) { $linkType->outward = $data['outward']; } $linkType->save(); @@ -90,7 +90,7 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf $count = TransactionJournalLink::whereDestinationId($one->id)->whereSourceId($two->id)->count(); $opposingCount = TransactionJournalLink::whereDestinationId($two->id)->whereSourceId($one->id)->count(); - return $count + $opposingCount > 0; + return ($count + $opposingCount) > 0; } /** @@ -113,7 +113,7 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf /** * Returns all the journal links (of a specific type). */ - public function getJournalLinks(?LinkType $linkType = null): Collection + public function getJournalLinks(null|LinkType $linkType = null): Collection { $query = TransactionJournalLink::with(['source', 'destination']) ->leftJoin('transaction_journals as source_journals', 'journal_links.source_id', '=', 'source_journals.id') @@ -121,8 +121,7 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf ->where('source_journals.user_id', $this->user->id) ->where('dest_journals.user_id', $this->user->id) ->whereNull('source_journals.deleted_at') - ->whereNull('dest_journals.deleted_at') - ; + ->whereNull('dest_journals.deleted_at'); if ($linkType instanceof LinkType) { $query->where('journal_links.link_type_id', $linkType->id); @@ -131,7 +130,7 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf return $query->get(['journal_links.*']); } - public function getLink(TransactionJournal $one, TransactionJournal $two): ?TransactionJournalLink + public function getLink(TransactionJournal $one, TransactionJournal $two): null|TransactionJournalLink { $left = TransactionJournalLink::whereDestinationId($one->id)->whereSourceId($two->id)->first(); if (null !== $left) { @@ -150,17 +149,15 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf $inward = TransactionJournalLink::whereDestinationId($journal->id)->get(); $merged = $outward->merge($inward); - return $merged->filter( - static fn (TransactionJournalLink $link): bool => null !== $link->source && null !== $link->destination - ); + return $merged->filter(static fn(TransactionJournalLink $link): bool => null !== $link->source && null !== $link->destination); } public function store(array $data): LinkType { - $linkType = new LinkType(); - $linkType->name = $data['name']; - $linkType->inward = $data['inward']; - $linkType->outward = $data['outward']; + $linkType = new LinkType(); + $linkType->name = $data['name']; + $linkType->inward = $data['inward']; + $linkType->outward = $data['outward']; $linkType->editable = true; $linkType->save(); @@ -172,9 +169,9 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf * * @throws Exception */ - public function storeLink(array $information, TransactionJournal $inward, TransactionJournal $outward): ?TransactionJournalLink + public function storeLink(array $information, TransactionJournal $inward, TransactionJournal $outward): null|TransactionJournalLink { - $linkType = $this->find((int)($information['link_type_id'] ?? 0)); + $linkType = $this->find((int) ($information['link_type_id'] ?? 0)); if (!$linkType instanceof LinkType) { $linkType = $this->findByName($information['link_type_name']); @@ -190,7 +187,7 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf return $existing; } - $link = new TransactionJournalLink(); + $link = new TransactionJournalLink(); $link->linkType()->associate($linkType); if ('inward' === $information['direction']) { Log::debug(sprintf('Link type is inwards ("%s"), so %d is source and %d is destination.', $linkType->inward, $inward->id, $outward->id)); @@ -206,17 +203,17 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf $link->save(); // make note in noteable: - $this->setNoteText($link, (string)$information['notes']); + $this->setNoteText($link, (string) $information['notes']); return $link; } - public function find(int $linkTypeId): ?LinkType + public function find(int $linkTypeId): null|LinkType { return LinkType::find($linkTypeId); } - public function findByName(?string $name = null): ?LinkType + public function findByName(null|string $name = null): null|LinkType { if (null === $name) { return null; @@ -228,12 +225,12 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf /** * See if such a link already exists (and get it). */ - public function findSpecificLink(LinkType $linkType, TransactionJournal $inward, TransactionJournal $outward): ?TransactionJournalLink + public function findSpecificLink(LinkType $linkType, TransactionJournal $inward, TransactionJournal $outward): null|TransactionJournalLink { return TransactionJournalLink::where('link_type_id', $linkType->id) ->where('source_id', $inward->id) - ->where('destination_id', $outward->id)->first() - ; + ->where('destination_id', $outward->id) + ->first(); } /** @@ -268,8 +265,8 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf public function switchLink(TransactionJournalLink $link): bool { - $source = $link->source_id; - $link->source_id = $link->destination_id; + $source = $link->source_id; + $link->source_id = $link->destination_id; $link->destination_id = $source; $link->save(); @@ -283,7 +280,7 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf */ public function updateLink(TransactionJournalLink $journalLink, array $data): TransactionJournalLink { - $journalLink->source_id = $data['inward_id'] ?? $journalLink->source_id; + $journalLink->source_id = $data['inward_id'] ?? $journalLink->source_id; $journalLink->destination_id = $data['outward_id'] ?? $journalLink->destination_id; $journalLink->save(); if (array_key_exists('link_type_name', $data)) { @@ -295,7 +292,7 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf $journalLink->refresh(); } - $journalLink->link_type_id = $data['link_type_id'] ?? $journalLink->link_type_id; + $journalLink->link_type_id = $data['link_type_id'] ?? $journalLink->link_type_id; $journalLink->save(); if (array_key_exists('notes', $data) && null !== $data['notes']) { $this->setNoteText($journalLink, $data['notes']); diff --git a/app/Repositories/LinkType/LinkTypeRepositoryInterface.php b/app/Repositories/LinkType/LinkTypeRepositoryInterface.php index 23cdeca825..87ef87c8ec 100644 --- a/app/Repositories/LinkType/LinkTypeRepositoryInterface.php +++ b/app/Repositories/LinkType/LinkTypeRepositoryInterface.php @@ -46,16 +46,16 @@ interface LinkTypeRepositoryInterface { public function countJournals(LinkType $linkType): int; - public function destroy(LinkType $linkType, ?LinkType $moveTo = null): bool; + public function destroy(LinkType $linkType, null|LinkType $moveTo = null): bool; public function destroyLink(TransactionJournalLink $link): bool; - public function find(int $linkTypeId): ?LinkType; + public function find(int $linkTypeId): null|LinkType; /** * Find link type by name. */ - public function findByName(?string $name = null): ?LinkType; + public function findByName(null|string $name = null): null|LinkType; /** * Check if link exists between journals. @@ -65,7 +65,7 @@ interface LinkTypeRepositoryInterface /** * See if such a link already exists (and get it). */ - public function findSpecificLink(LinkType $linkType, TransactionJournal $inward, TransactionJournal $outward): ?TransactionJournalLink; + public function findSpecificLink(LinkType $linkType, TransactionJournal $inward, TransactionJournal $outward): null|TransactionJournalLink; public function get(): Collection; @@ -74,7 +74,7 @@ interface LinkTypeRepositoryInterface */ public function getJournalIds(LinkType $linkType): array; - public function getJournalLinks(?LinkType $linkType = null): Collection; + public function getJournalLinks(null|LinkType $linkType = null): Collection; /** * Return list of existing connections. @@ -86,7 +86,7 @@ interface LinkTypeRepositoryInterface /** * Store link between two journals. */ - public function storeLink(array $information, TransactionJournal $inward, TransactionJournal $outward): ?TransactionJournalLink; + public function storeLink(array $information, TransactionJournal $inward, TransactionJournal $outward): null|TransactionJournalLink; public function switchLink(TransactionJournalLink $link): bool; diff --git a/app/Repositories/ObjectGroup/CreatesObjectGroups.php b/app/Repositories/ObjectGroup/CreatesObjectGroups.php index 5835a32f11..a480551687 100644 --- a/app/Repositories/ObjectGroup/CreatesObjectGroups.php +++ b/app/Repositories/ObjectGroup/CreatesObjectGroups.php @@ -31,25 +31,26 @@ use FireflyIII\Models\ObjectGroup; */ trait CreatesObjectGroups { - protected function findObjectGroupById(int $groupId): ?ObjectGroup + protected function findObjectGroupById(int $groupId): null|ObjectGroup { /** @var null|ObjectGroup */ - return $this->user->objectGroups()->where('id', $groupId)->first(); + return $this->user + ->objectGroups() + ->where('id', $groupId) + ->first(); } - protected function findOrCreateObjectGroup(string $title): ?ObjectGroup + protected function findOrCreateObjectGroup(string $title): null|ObjectGroup { $title = substr($title, 0, 255); $maxOrder = $this->getObjectGroupMaxOrder(); if (!$this->hasObjectGroup($title)) { - return ObjectGroup::create( - [ - 'user_id' => $this->user->id, - 'user_group_id' => $this->user->user_group_id, - 'title' => $title, - 'order' => $maxOrder + 1, - ] - ); + return ObjectGroup::create([ + 'user_id' => $this->user->id, + 'user_group_id' => $this->user->user_group_id, + 'title' => $title, + 'order' => $maxOrder + 1 + ]); } return $this->findObjectGroup($title); @@ -62,12 +63,18 @@ trait CreatesObjectGroups protected function hasObjectGroup(string $title): bool { - return 1 === $this->user->objectGroups()->where('title', $title)->count(); + return 1 === $this->user + ->objectGroups() + ->where('title', $title) + ->count(); } - protected function findObjectGroup(string $title): ?ObjectGroup + protected function findObjectGroup(string $title): null|ObjectGroup { /** @var null|ObjectGroup */ - return $this->user->objectGroups()->where('title', $title)->first(); + return $this->user + ->objectGroups() + ->where('title', $title) + ->first(); } } diff --git a/app/Repositories/ObjectGroup/ObjectGroupRepository.php b/app/Repositories/ObjectGroup/ObjectGroupRepository.php index cd996dea24..a69c0fae31 100644 --- a/app/Repositories/ObjectGroup/ObjectGroupRepository.php +++ b/app/Repositories/ObjectGroup/ObjectGroupRepository.php @@ -24,13 +24,13 @@ declare(strict_types=1); namespace FireflyIII\Repositories\ObjectGroup; -use Illuminate\Support\Facades\Log; use FireflyIII\Models\ObjectGroup; use FireflyIII\Models\PiggyBank; use FireflyIII\Support\Repositories\UserGroup\UserGroupInterface; use FireflyIII\Support\Repositories\UserGroup\UserGroupTrait; use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Log; /** * Class ObjectGroupRepository @@ -53,11 +53,12 @@ class ObjectGroupRepository implements ObjectGroupRepositoryInterface, UserGroup public function get(): Collection { - return $this->user->objectGroups() + return $this->user + ->objectGroups() ->with(['piggyBanks', 'bills']) ->orderBy('order', 'ASC') - ->orderBy('title', 'ASC')->get() - ; + ->orderBy('title', 'ASC') + ->get(); } public function deleteEmpty(): void @@ -104,9 +105,13 @@ class ObjectGroupRepository implements ObjectGroupRepositoryInterface, UserGroup /** @var ObjectGroup $objectGroup */ foreach ($list as $objectGroup) { if ($index !== $objectGroup->order) { - Log::debug( - sprintf('objectGroup #%d ("%s"): order should %d be but is %d.', $objectGroup->id, $objectGroup->title, $index, $objectGroup->order) - ); + Log::debug(sprintf( + 'objectGroup #%d ("%s"): order should %d be but is %d.', + $objectGroup->id, + $objectGroup->title, + $index, + $objectGroup->order + )); $objectGroup->order = $index; $objectGroup->save(); } @@ -116,7 +121,10 @@ class ObjectGroupRepository implements ObjectGroupRepositoryInterface, UserGroup public function search(string $query, int $limit): Collection { - $dbQuery = $this->user->objectGroups()->orderBy('order', 'ASC')->orderBy('title', 'ASC'); + $dbQuery = $this->user + ->objectGroups() + ->orderBy('order', 'ASC') + ->orderBy('title', 'ASC'); if ('' !== $query) { // split query on spaces just in case: $parts = explode(' ', $query); @@ -149,19 +157,23 @@ class ObjectGroupRepository implements ObjectGroupRepositoryInterface, UserGroup $oldOrder = $objectGroup->order; if ($newOrder > $oldOrder) { - $this->user->objectGroups()->where('object_groups.order', '<=', $newOrder)->where('object_groups.order', '>', $oldOrder) + $this->user + ->objectGroups() + ->where('object_groups.order', '<=', $newOrder) + ->where('object_groups.order', '>', $oldOrder) ->where('object_groups.id', '!=', $objectGroup->id) - ->decrement('object_groups.order') - ; + ->decrement('object_groups.order'); $objectGroup->order = $newOrder; $objectGroup->save(); } if ($newOrder < $oldOrder) { - $this->user->objectGroups()->where('object_groups.order', '>=', $newOrder)->where('object_groups.order', '<', $oldOrder) + $this->user + ->objectGroups() + ->where('object_groups.order', '>=', $newOrder) + ->where('object_groups.order', '<', $oldOrder) ->where('object_groups.id', '!=', $objectGroup->id) - ->increment('object_groups.order') - ; + ->increment('object_groups.order'); $objectGroup->order = $newOrder; $objectGroup->save(); diff --git a/app/Repositories/PeriodStatistic/PeriodStatisticRepository.php b/app/Repositories/PeriodStatistic/PeriodStatisticRepository.php index e2d6649064..616f07944b 100644 --- a/app/Repositories/PeriodStatistic/PeriodStatisticRepository.php +++ b/app/Repositories/PeriodStatistic/PeriodStatisticRepository.php @@ -1,6 +1,7 @@ primaryPeriodStatistics() - ->where('start', $start) - ->where('end', $end) - ->whereIn('type', $types) - ->get() - ; + return $model->primaryPeriodStatistics()->where('start', $start)->where('end', $end)->whereIn('type', $types)->get(); } public function findPeriodStatistic(Model $model, Carbon $start, Carbon $end, string $type): Collection { - return $model->primaryPeriodStatistics() - ->where('start', $start) - ->where('end', $end) - ->where('type', $type) - ->get() - ; + return $model->primaryPeriodStatistics()->where('start', $start)->where('end', $end)->where('type', $type)->get(); } public function saveStatistic(Model $model, int $currencyId, Carbon $start, Carbon $end, string $type, int $count, string $amount): PeriodStatistic { - $stat = new PeriodStatistic(); + $stat = new PeriodStatistic(); $stat->primaryStatable()->associate($model); $stat->transaction_currency_id = $currencyId; - $stat->user_group_id = $this->getUserGroup()->id; - $stat->start = $start; - $stat->start_tz = $start->format('e'); - $stat->end = $end; - $stat->end_tz = $end->format('e'); - $stat->amount = $amount; - $stat->count = $count; - $stat->type = $type; + $stat->user_group_id = $this->getUserGroup()->id; + $stat->start = $start; + $stat->start_tz = $start->format('e'); + $stat->end = $end; + $stat->end_tz = $end->format('e'); + $stat->amount = $amount; + $stat->count = $count; + $stat->type = $type; $stat->save(); Log::debug(sprintf( @@ -100,25 +91,34 @@ class PeriodStatisticRepository implements PeriodStatisticRepositoryInterface, U #[Override] public function allInRangeForPrefix(string $prefix, Carbon $start, Carbon $end): Collection { - return $this->userGroup->periodStatistics() + return $this->userGroup + ->periodStatistics() ->where('type', 'LIKE', sprintf('%s%%', $prefix)) - ->where('start', '>=', $start)->where('end', '<=', $end)->get() - ; + ->where('start', '>=', $start) + ->where('end', '<=', $end) + ->get(); } #[Override] - public function savePrefixedStatistic(string $prefix, int $currencyId, Carbon $start, Carbon $end, string $type, int $count, string $amount): PeriodStatistic - { - $stat = new PeriodStatistic(); + public function savePrefixedStatistic( + string $prefix, + int $currencyId, + Carbon $start, + Carbon $end, + string $type, + int $count, + string $amount + ): PeriodStatistic { + $stat = new PeriodStatistic(); $stat->transaction_currency_id = $currencyId; - $stat->user_group_id = $this->getUserGroup()->id; - $stat->start = $start; - $stat->start_tz = $start->format('e'); - $stat->end = $end; - $stat->end_tz = $end->format('e'); - $stat->amount = $amount; - $stat->count = $count; - $stat->type = sprintf('%s_%s', $prefix, $type); + $stat->user_group_id = $this->getUserGroup()->id; + $stat->start = $start; + $stat->start_tz = $start->format('e'); + $stat->end = $end; + $stat->end_tz = $end->format('e'); + $stat->amount = $amount; + $stat->count = $count; + $stat->type = sprintf('%s_%s', $prefix, $type); $stat->save(); Log::debug(sprintf( diff --git a/app/Repositories/PeriodStatistic/PeriodStatisticRepositoryInterface.php b/app/Repositories/PeriodStatistic/PeriodStatisticRepositoryInterface.php index c4a9574d29..063fa6fdb2 100644 --- a/app/Repositories/PeriodStatistic/PeriodStatisticRepositoryInterface.php +++ b/app/Repositories/PeriodStatistic/PeriodStatisticRepositoryInterface.php @@ -1,6 +1,7 @@ getCurrentAmount($piggyBank, $account); - $pivot = $piggyBank->accounts()->where('accounts.id', $account->id)->first()->pivot; - $pivot->current_amount = bcsub((string)$currentAmount, $amount); + $currentAmount = $this->getCurrentAmount($piggyBank, $account); + $pivot = $piggyBank->accounts()->where('accounts.id', $account->id)->first()->pivot; + $pivot->current_amount = bcsub((string) $currentAmount, $amount); $pivot->native_current_amount = null; // also update native_current_amount. - $userCurrency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); + $userCurrency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); if ($userCurrency->id !== $piggyBank->transaction_currency_id) { - $converter = new ExchangeRateConverter(); + $converter = new ExchangeRateConverter(); $converter->setIgnoreSettings(true); $pivot->native_current_amount = $converter->convert($piggyBank->transactionCurrency, $userCurrency, today(), $pivot->current_amount); } @@ -87,17 +87,17 @@ trait ModifiesPiggyBanks return true; } - public function addAmount(PiggyBank $piggyBank, Account $account, string $amount, ?TransactionJournal $journal = null): bool + public function addAmount(PiggyBank $piggyBank, Account $account, string $amount, null|TransactionJournal $journal = null): bool { - $currentAmount = $this->getCurrentAmount($piggyBank, $account); - $pivot = $piggyBank->accounts()->where('accounts.id', $account->id)->first()->pivot; - $pivot->current_amount = bcadd((string)$currentAmount, $amount); + $currentAmount = $this->getCurrentAmount($piggyBank, $account); + $pivot = $piggyBank->accounts()->where('accounts.id', $account->id)->first()->pivot; + $pivot->current_amount = bcadd((string) $currentAmount, $amount); $pivot->native_current_amount = null; // also update native_current_amount. - $userCurrency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); + $userCurrency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); if ($userCurrency->id !== $piggyBank->transaction_currency_id) { - $converter = new ExchangeRateConverter(); + $converter = new ExchangeRateConverter(); $converter->setIgnoreSettings(true); $pivot->native_current_amount = $converter->convert($piggyBank->transactionCurrency, $userCurrency, today(), $pivot->current_amount); } @@ -121,16 +121,15 @@ trait ModifiesPiggyBanks Log::debug(sprintf('Left on account: %s on %s', $leftOnAccount, $today->format('Y-m-d H:i:s'))); Log::debug(sprintf('Saved so far: %s', $savedSoFar)); - if (0 !== bccomp($piggyBank->target_amount, '0')) { - $leftToSave = bcsub($piggyBank->target_amount, (string)$savedSoFar); - $maxAmount = 1 === bccomp((string)$leftOnAccount, $leftToSave) ? $leftToSave : $leftOnAccount; + $leftToSave = bcsub($piggyBank->target_amount, (string) $savedSoFar); + $maxAmount = 1 === bccomp((string) $leftOnAccount, $leftToSave) ? $leftToSave : $leftOnAccount; Log::debug(sprintf('Left to save: %s', $leftToSave)); Log::debug(sprintf('Maximum amount: %s', $maxAmount)); } - $compare = bccomp($amount, (string)$maxAmount); - $result = $compare <= 0; + $compare = bccomp($amount, (string) $maxAmount); + $result = $compare <= 0; Log::debug(sprintf('Compare <= 0? %d, so canAddAmount is %s', $compare, var_export($result, true))); @@ -141,7 +140,7 @@ trait ModifiesPiggyBanks { $savedSoFar = $this->getCurrentAmount($piggyBank, $account); - return bccomp($amount, (string)$savedSoFar) <= 0; + return bccomp($amount, (string) $savedSoFar) <= 0; } /** @@ -164,15 +163,15 @@ trait ModifiesPiggyBanks public function setCurrentAmount(PiggyBank $piggyBank, string $amount): PiggyBank { - $repetition = $this->getRepetition($piggyBank); + $repetition = $this->getRepetition($piggyBank); if (null === $repetition) { return $piggyBank; } - $max = $piggyBank->target_amount; + $max = $piggyBank->target_amount; if (1 === bccomp($amount, $max) && 0 !== bccomp($piggyBank->target_amount, '0')) { $amount = $max; } - $difference = bcsub($amount, (string)$repetition->current_amount); + $difference = bcsub($amount, (string) $repetition->current_amount); $repetition->current_amount = $amount; $repetition->save(); @@ -203,7 +202,7 @@ trait ModifiesPiggyBanks */ public function store(array $data): PiggyBank { - $factory = new PiggyBankFactory(); + $factory = new PiggyBankFactory(); $factory->user = $this->user; return $factory->store($data); @@ -211,32 +210,31 @@ trait ModifiesPiggyBanks public function update(PiggyBank $piggyBank, array $data): PiggyBank { - $piggyBank = $this->updateProperties($piggyBank, $data); + $piggyBank = $this->updateProperties($piggyBank, $data); if (array_key_exists('notes', $data)) { - $this->updateNote($piggyBank, (string)$data['notes']); + $this->updateNote($piggyBank, (string) $data['notes']); } // update the order of the piggy bank: - $oldOrder = $piggyBank->order; - $newOrder = (int)($data['order'] ?? $oldOrder); + $oldOrder = $piggyBank->order; + $newOrder = (int) ($data['order'] ?? $oldOrder); if ($oldOrder !== $newOrder) { $this->setOrder($piggyBank, $newOrder); } // update the accounts - $factory = new PiggyBankFactory(); + $factory = new PiggyBankFactory(); $factory->user = $this->user; // the piggy bank currency is set or updated FIRST, if it exists. $factory->linkToAccountIds($piggyBank, $data['accounts'] ?? []); - // if the piggy bank is now smaller than the sum of the money saved, // remove money from all accounts until the piggy bank is the right amount. $currentAmount = $this->getCurrentAmount($piggyBank); - if (1 === bccomp((string)$currentAmount, (string)$piggyBank->target_amount) && 0 !== bccomp((string)$piggyBank->target_amount, '0')) { + if (1 === bccomp((string) $currentAmount, (string) $piggyBank->target_amount) && 0 !== bccomp((string) $piggyBank->target_amount, '0')) { Log::debug(sprintf('Current amount is %s, target amount is %s', $currentAmount, $piggyBank->target_amount)); - $difference = bcsub((string)$piggyBank->target_amount, (string)$currentAmount); + $difference = bcsub((string) $piggyBank->target_amount, (string) $currentAmount); // an amount will be removed, create "negative" event: // Log::debug(sprintf('ChangedAmount: is triggered with difference "%s"', $difference)); @@ -249,7 +247,7 @@ trait ModifiesPiggyBanks // update using name: if (array_key_exists('object_group_title', $data)) { - $objectGroupTitle = (string)$data['object_group_title']; + $objectGroupTitle = (string) $data['object_group_title']; if ('' !== $objectGroupTitle) { $objectGroup = $this->findOrCreateObjectGroup($objectGroupTitle); if (null !== $objectGroup) { @@ -265,7 +263,7 @@ trait ModifiesPiggyBanks // try also with ID: if (array_key_exists('object_group_id', $data)) { - $objectGroupId = (int)($data['object_group_id'] ?? 0); + $objectGroupId = (int) ($data['object_group_id'] ?? 0); if (0 !== $objectGroupId) { $objectGroup = $this->findObjectGroupById($objectGroupId); if (null !== $objectGroup) { @@ -287,7 +285,7 @@ trait ModifiesPiggyBanks $piggyBank->name = $data['name']; } if (array_key_exists('transaction_currency_id', $data) && is_int($data['transaction_currency_id'])) { - $currency = Amount::getTransactionCurrencyById($data['transaction_currency_id']); + $currency = Amount::getTransactionCurrencyById($data['transaction_currency_id']); $piggyBank->transaction_currency_id = $currency->id; } @@ -298,11 +296,11 @@ trait ModifiesPiggyBanks $piggyBank->target_amount = '0'; } if (array_key_exists('target_date', $data) && '' !== $data['target_date']) { - $piggyBank->target_date = $data['target_date']; + $piggyBank->target_date = $data['target_date']; $piggyBank->target_date_tz = $data['target_date']?->format('e'); } if (array_key_exists('start_date', $data)) { - $piggyBank->start_date = $data['start_date']; + $piggyBank->start_date = $data['start_date']; $piggyBank->start_date_tz = $data['target_date']?->format('e'); } $piggyBank->save(); @@ -318,7 +316,7 @@ trait ModifiesPiggyBanks return; } - $dbNote = $piggyBank->notes()->first(); + $dbNote = $piggyBank->notes()->first(); if (null === $dbNote) { $dbNote = new Note(); $dbNote->noteable()->associate($piggyBank); @@ -329,16 +327,17 @@ trait ModifiesPiggyBanks public function setOrder(PiggyBank $piggyBank, int $newOrder): bool { - $oldOrder = $piggyBank->order; + $oldOrder = $piggyBank->order; // Log::debug(sprintf('Will move piggy bank #%d ("%s") from %d to %d', $piggyBank->id, $piggyBank->name, $oldOrder, $newOrder)); if ($newOrder > $oldOrder) { PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id') ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id') ->where('accounts.user_id', $this->user->id) - ->where('piggy_banks.order', '<=', $newOrder)->where('piggy_banks.order', '>', $oldOrder) + ->where('piggy_banks.order', '<=', $newOrder) + ->where('piggy_banks.order', '>', $oldOrder) ->where('piggy_banks.id', '!=', $piggyBank->id) - ->distinct()->decrement('piggy_banks.order') - ; + ->distinct() + ->decrement('piggy_banks.order'); $piggyBank->order = $newOrder; Log::debug(sprintf('[1] Order of piggy #%d ("%s") from %d to %d', $piggyBank->id, $piggyBank->name, $oldOrder, $newOrder)); @@ -349,10 +348,11 @@ trait ModifiesPiggyBanks PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id') ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id') ->where('accounts.user_id', $this->user->id) - ->where('piggy_banks.order', '>=', $newOrder)->where('piggy_banks.order', '<', $oldOrder) + ->where('piggy_banks.order', '>=', $newOrder) + ->where('piggy_banks.order', '<', $oldOrder) ->where('piggy_banks.id', '!=', $piggyBank->id) - ->distinct()->increment('piggy_banks.order') - ; + ->distinct() + ->increment('piggy_banks.order'); $piggyBank->order = $newOrder; Log::debug(sprintf('[2] Order of piggy #%d ("%s") from %d to %d', $piggyBank->id, $piggyBank->name, $oldOrder, $newOrder)); @@ -366,14 +366,14 @@ trait ModifiesPiggyBanks foreach ($piggyBank->accounts as $account) { $current = $account->pivot->current_amount; // if this account contains more than the amount, remove the amount and return. - if (1 === bccomp((string)$current, $amount)) { + if (1 === bccomp((string) $current, $amount)) { $this->removeAmount($piggyBank, $account, $amount); return; } // if this account contains less than the amount, remove the current amount, update the amount and continue. $this->removeAmount($piggyBank, $account, $current); - $amount = bcsub($amount, (string)$current); + $amount = bcsub($amount, (string) $current); } } } diff --git a/app/Repositories/PiggyBank/PiggyBankRepository.php b/app/Repositories/PiggyBank/PiggyBankRepository.php index f2d30417a4..b251f8ce37 100644 --- a/app/Repositories/PiggyBank/PiggyBankRepository.php +++ b/app/Repositories/PiggyBank/PiggyBankRepository.php @@ -36,6 +36,7 @@ use FireflyIII\Models\Transaction; use FireflyIII\Models\TransactionJournal; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Journal\JournalRepositoryInterface; +use FireflyIII\Support\Facades\Amount; use FireflyIII\Support\Facades\Steam; use FireflyIII\Support\Repositories\UserGroup\UserGroupInterface; use FireflyIII\Support\Repositories\UserGroup\UserGroupTrait; @@ -44,7 +45,6 @@ use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Storage; use Override; -use FireflyIII\Support\Facades\Amount; /** * Class PiggyBankRepository. @@ -62,11 +62,10 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id') ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id') ->where('accounts.user_id', $this->user->id) - ->delete() - ; + ->delete(); } - public function findPiggyBank(?int $piggyBankId, ?string $piggyBankName): ?PiggyBank + public function findPiggyBank(null|int $piggyBankId, null|string $piggyBankName): null|PiggyBank { Log::debug('Searching for piggy information.'); @@ -91,48 +90,46 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte return null; } - public function find(int $piggyBankId): ?PiggyBank + public function find(int $piggyBankId): null|PiggyBank { return PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id') ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id') ->where('accounts.user_id', $this->user->id) - ->where('piggy_banks.id', $piggyBankId)->first(['piggy_banks.*']) - ; + ->where('piggy_banks.id', $piggyBankId) + ->first(['piggy_banks.*']); } /** * Find by name or return NULL. */ - public function findByName(string $name): ?PiggyBank + public function findByName(string $name): null|PiggyBank { return PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id') ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id') ->where('accounts.user_id', $this->user->id) - ->where('piggy_banks.name', $name)->first(['piggy_banks.*']) - ; + ->where('piggy_banks.name', $name) + ->first(['piggy_banks.*']); } public function getAttachments(PiggyBank $piggyBank): Collection { - $set = $piggyBank->attachments()->get(); + $set = $piggyBank->attachments()->get(); $disk = Storage::disk('upload'); - return $set->each( - static function (Attachment $attachment) use ($disk): Attachment { // @phpstan-ignore-line - $notes = $attachment->notes()->first(); - $attachment->file_exists = $disk->exists($attachment->fileName()); - $attachment->notes_text = null !== $notes ? $notes->text : ''; + return $set->each(static function (Attachment $attachment) use ($disk): Attachment { // @phpstan-ignore-line + $notes = $attachment->notes()->first(); + $attachment->file_exists = $disk->exists($attachment->fileName()); + $attachment->notes_text = null !== $notes ? $notes->text : ''; - return $attachment; - } - ); + return $attachment; + }); } /** * Get current amount saved in piggy bank. */ - public function getCurrentPrimaryCurrencyAmount(PiggyBank $piggyBank, ?Account $account = null): string + public function getCurrentPrimaryCurrencyAmount(PiggyBank $piggyBank, null|Account $account = null): string { $sum = '0'; foreach ($piggyBank->accounts as $current) { @@ -161,15 +158,15 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte { Log::debug(sprintf('Now in getExactAmount(%d, %d)', $piggyBank->id, $journal->id)); - $operator = null; - $currency = null; + $operator = null; + $currency = null; /** @var JournalRepositoryInterface $journalRepost */ - $journalRepost = app(JournalRepositoryInterface::class); + $journalRepost = app(JournalRepositoryInterface::class); $journalRepost->setUser($this->user); /** @var AccountRepositoryInterface $accountRepos */ - $accountRepos = app(AccountRepositoryInterface::class); + $accountRepos = app(AccountRepositoryInterface::class); $accountRepos->setUser($this->user); $primaryCurrency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); @@ -177,13 +174,12 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte Log::debug(sprintf('Piggy bank #%d currency is %s', $piggyBank->id, $piggyBank->transactionCurrency->code)); /** @var Transaction $source */ - $source = $journal->transactions()->with(['account'])->where('amount', '<', 0)->first(); + $source = $journal->transactions()->with(['account'])->where('amount', '<', 0)->first(); /** @var Transaction $destination */ - $destination = $journal->transactions()->with(['account'])->where('amount', '>', 0)->first(); - $hits = 0; + $destination = $journal->transactions()->with(['account'])->where('amount', '>', 0)->first(); + $hits = 0; foreach ($piggyBank->accounts as $account) { - // matches source, which means amount will be removed from piggy: if ($account->id === $source->account_id) { $operator = 'negative'; @@ -205,7 +201,6 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte return '0'; } - if (null === $operator || null === $currency) { Log::debug('Currency is NULL and operator is NULL, return "0".'); @@ -213,7 +208,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte } // currency of the account + the piggy bank currency are almost the same. // which amount from the transaction matches? - $amount = null; + $amount = null; if ((int) $source->transaction_currency_id === $currency->id) { Log::debug('Use normal amount'); $amount = Steam::{$operator}($source->amount); // @phpstan-ignore-line @@ -229,9 +224,9 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte } Log::debug(sprintf('The currency is %s and the amount is %s', $currency->code, $amount)); - $currentAmount = $this->getCurrentAmount($piggyBank); - $room = bcsub($piggyBank->target_amount, $currentAmount); - $compare = bcmul($currentAmount, '-1'); + $currentAmount = $this->getCurrentAmount($piggyBank); + $room = bcsub($piggyBank->target_amount, $currentAmount); + $compare = bcmul($currentAmount, '-1'); if (0 === bccomp($piggyBank->target_amount, '0')) { // amount is zero? then the "room" is positive amount of we wish to add or remove. @@ -266,7 +261,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte /** * Get current amount saved in piggy bank. */ - public function getCurrentAmount(PiggyBank $piggyBank, ?Account $account = null): string + public function getCurrentAmount(PiggyBank $piggyBank, null|Account $account = null): string { $sum = '0'; foreach ($piggyBank->accounts as $current) { @@ -303,7 +298,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte /** @var PiggyBank $piggy */ foreach ($set as $piggy) { $currentAmount = $this->getCurrentAmount($piggy); - $piggy->name = sprintf('%s (%s)', $piggy->name, Amount::formatAnything($piggy->transactionCurrency, $currentAmount, false)); + $piggy->name = sprintf('%s (%s)', $piggy->name, Amount::formatAnything($piggy->transactionCurrency, $currentAmount, false)); } return $set; @@ -311,9 +306,12 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte public function getPiggyBanks(): Collection { - $query = PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id') - ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id') - ; + $query = PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id')->leftJoin( + 'accounts', + 'accounts.id', + '=', + 'account_piggy_bank.account_id' + ); if (!$this->user instanceof User) { $query->where('accounts.user_group_id', $this->userGroup->id); } @@ -322,16 +320,13 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte } return $query - ->with( - [ - 'objectGroups', - ] - ) - ->orderBy('piggy_banks.order', 'ASC')->distinct()->get(['piggy_banks.*']) - ; + ->with(['objectGroups']) + ->orderBy('piggy_banks.order', 'ASC') + ->distinct() + ->get(['piggy_banks.*']); } - public function getRepetition(PiggyBank $piggyBank, bool $overrule = false): ?PiggyBankRepetition + public function getRepetition(PiggyBank $piggyBank, bool $overrule = false): null|PiggyBankRepetition { if (false === $overrule) { throw new FireflyException('[b] Piggy bank repetitions are EOL.'); @@ -404,19 +399,14 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte ->leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id') ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id') ->where('accounts.user_id', $this->user->id) - ->with( - [ - 'objectGroups', - ] - ) - ->delete() - ; + ->with(['objectGroups']) + ->delete(); } #[Override] public function resetOrder(): void { - $factory = new PiggyBankFactory(); + $factory = new PiggyBankFactory(); $factory->user = $this->user; $factory->resetOrder(); } @@ -426,19 +416,14 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte $search = PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id') ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id') ->where('accounts.user_id', $this->user->id) - ->with( - [ - 'objectGroups', - ] - ) - ->orderBy('piggy_banks.order', 'ASC')->orderBy('piggy_banks.name', 'ASC')->distinct() - ; + ->with(['objectGroups']) + ->orderBy('piggy_banks.order', 'ASC') + ->orderBy('piggy_banks.name', 'ASC') + ->distinct(); if ('' !== $query) { $search->whereLike('piggy_banks.name', sprintf('%%%s%%', $query)); } - $search->orderBy('piggy_banks.order', 'ASC') - ->orderBy('piggy_banks.name', 'ASC') - ; + $search->orderBy('piggy_banks.order', 'ASC')->orderBy('piggy_banks.name', 'ASC'); return $search->take($limit)->get(['piggy_banks.*']); } diff --git a/app/Repositories/PiggyBank/PiggyBankRepositoryInterface.php b/app/Repositories/PiggyBank/PiggyBankRepositoryInterface.php index 7be09f5fb3..97d30b9eeb 100644 --- a/app/Repositories/PiggyBank/PiggyBankRepositoryInterface.php +++ b/app/Repositories/PiggyBank/PiggyBankRepositoryInterface.php @@ -49,7 +49,7 @@ interface PiggyBankRepositoryInterface { public function resetHistory(PiggyBank $piggyBank): void; - public function addAmount(PiggyBank $piggyBank, Account $account, string $amount, ?TransactionJournal $journal = null): bool; + public function addAmount(PiggyBank $piggyBank, Account $account, string $amount, null|TransactionJournal $journal = null): bool; public function addAmountToPiggyBank(PiggyBank $piggyBank, string $amount, TransactionJournal $journal): void; @@ -64,28 +64,29 @@ interface PiggyBankRepositoryInterface public function destroyAll(): void; - public function find(int $piggyBankId): ?PiggyBank; + public function find(int $piggyBankId): null|PiggyBank; /** * Find by name or return NULL. */ - public function findByName(string $name): ?PiggyBank; + public function findByName(string $name): null|PiggyBank; - public function findPiggyBank(?int $piggyBankId, ?string $piggyBankName): ?PiggyBank; + public function findPiggyBank(null|int $piggyBankId, null|string $piggyBankName): null|PiggyBank; public function getAttachments(PiggyBank $piggyBank): Collection; /** * Get current amount saved in piggy bank. */ - public function getCurrentAmount(PiggyBank $piggyBank, ?Account $account = null): string; + public function getCurrentAmount(PiggyBank $piggyBank, null|Account $account = null): string; - public function getCurrentPrimaryCurrencyAmount(PiggyBank $piggyBank, ?Account $account = null): string; + public function getCurrentPrimaryCurrencyAmount(PiggyBank $piggyBank, null|Account $account = null): string; /** * Get all events. */ public function getEvents(PiggyBank $piggyBank): Collection; + /** * Get current amount saved in piggy bank. */ @@ -110,7 +111,7 @@ interface PiggyBankRepositoryInterface */ public function getPiggyBanksWithAmount(): Collection; - public function getRepetition(PiggyBank $piggyBank, bool $overrule = false): ?PiggyBankRepetition; + public function getRepetition(PiggyBank $piggyBank, bool $overrule = false): null|PiggyBankRepetition; /** * Returns the suggested amount the user should save per month, or "". @@ -124,7 +125,7 @@ interface PiggyBankRepositoryInterface public function purgeAll(): void; - public function removeAmount(PiggyBank $piggyBank, Account $account, string $amount, ?TransactionJournal $journal = null): bool; + public function removeAmount(PiggyBank $piggyBank, Account $account, string $amount, null|TransactionJournal $journal = null): bool; public function removeAmountFromAll(PiggyBank $piggyBank, string $amount): void; diff --git a/app/Repositories/Recurring/RecurringRepository.php b/app/Repositories/Recurring/RecurringRepository.php index 468abca8ad..106843ae5a 100644 --- a/app/Repositories/Recurring/RecurringRepository.php +++ b/app/Repositories/Recurring/RecurringRepository.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Repositories\Recurring; -use FireflyIII\Support\Facades\Preferences; use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Factory\RecurrenceFactory; @@ -41,6 +40,7 @@ use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionJournalMeta; use FireflyIII\Services\Internal\Destroy\RecurrenceDestroyService; use FireflyIII\Services\Internal\Update\RecurrenceUpdateService; +use FireflyIII\Support\Facades\Preferences; use FireflyIII\Support\Repositories\Recurring\CalculateRangeOccurrences; use FireflyIII\Support\Repositories\Recurring\CalculateXOccurrences; use FireflyIII\Support\Repositories\Recurring\CalculateXOccurrencesSince; @@ -70,11 +70,10 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte public function createdPreviously(Recurrence $recurrence, Carbon $date): bool { // if not, loop set and try to read the recurrence_date. If it matches start or end, return it as well. - $set - = TransactionJournalMeta::where(static function (Builder $q1) use ($recurrence): void { - $q1->where('name', 'recurrence_id'); - $q1->where('data', json_encode((string) $recurrence->id)); - })->get(['journal_meta.transaction_journal_id']); + $set = TransactionJournalMeta::where(static function (Builder $q1) use ($recurrence): void { + $q1->where('name', 'recurrence_id'); + $q1->where('data', json_encode((string) $recurrence->id)); + })->get(['journal_meta.transaction_journal_id']); // there are X journals made for this recurrence. Any of them meant for today? foreach ($set as $journalMeta) { @@ -83,10 +82,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte Log::debug(sprintf('Search for date: %s', json_encode($string))); $q2->where('name', 'recurrence_date'); $q2->where('data', json_encode($string)); - }) - ->where('transaction_journal_id', $journalMeta->transaction_journal_id) - ->count() - ; + })->where('transaction_journal_id', $journalMeta->transaction_journal_id)->count(); if ($count > 0) { Log::debug(sprintf('Looks like journal #%d was already created', $journalMeta->transaction_journal_id)); @@ -102,13 +98,13 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte */ public function get(): Collection { - return $this->user->recurrences() + return $this->user + ->recurrences() ->with(['TransactionCurrency', 'TransactionType', 'RecurrenceRepetitions', 'RecurrenceTransactions']) ->orderBy('active', 'DESC') ->orderBy('transaction_type_id', 'ASC') ->orderBy('title', 'ASC') - ->get() - ; + ->get(); } /** @@ -136,11 +132,10 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte return Recurrence::with(['TransactionCurrency', 'TransactionType', 'RecurrenceRepetitions', 'RecurrenceTransactions']) ->orderBy('active', 'DESC') ->orderBy('title', 'ASC') - ->get() - ; + ->get(); } - public function getBillId(RecurrenceTransaction $recTransaction): ?int + public function getBillId(RecurrenceTransaction $recTransaction): null|int { $return = null; @@ -157,7 +152,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte /** * Get the budget ID from a recurring transaction transaction. */ - public function getBudget(RecurrenceTransaction $recTransaction): ?int + public function getBudget(RecurrenceTransaction $recTransaction): null|int { $return = 0; @@ -174,7 +169,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte /** * Get the category from a recurring transaction transaction. */ - public function getCategoryId(RecurrenceTransaction $recTransaction): ?int + public function getCategoryId(RecurrenceTransaction $recTransaction): null|int { $return = ''; @@ -191,7 +186,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte /** * Get the category from a recurring transaction transaction. */ - public function getCategoryName(RecurrenceTransaction $recTransaction): ?string + public function getCategoryName(RecurrenceTransaction $recTransaction): null|string { $return = ''; @@ -208,15 +203,14 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte /** * Returns the journals created for this recurrence, possibly limited by time. */ - public function getJournalCount(Recurrence $recurrence, ?Carbon $start = null, ?Carbon $end = null): int + public function getJournalCount(Recurrence $recurrence, null|Carbon $start = null, null|Carbon $end = null): int { Log::debug(sprintf('Now in getJournalCount(#%d, "%s", "%s")', $recurrence->id, $start?->format('Y-m-d H:i:s'), $end?->format('Y-m-d H:i:s'))); $query = TransactionJournal::leftJoin('journal_meta', 'journal_meta.transaction_journal_id', '=', 'transaction_journals.id') ->where('transaction_journals.user_id', $recurrence->user_id) ->whereNull('transaction_journals.deleted_at') ->where('journal_meta.name', 'recurrence_id') - ->where('journal_meta.data', '"'.$recurrence->id.'"') - ; + ->where('journal_meta.data', '"' . $recurrence->id . '"'); if ($start instanceof Carbon) { $query->where('transaction_journals.date', '>=', $start->format('Y-m-d 00:00:00')); } @@ -238,8 +232,9 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte ->where('transaction_journals.user_id', $this->user->id) ->where('journal_meta.name', '=', 'recurrence_id') ->where('journal_meta.data', '=', json_encode((string) $recurrence->id)) - ->get(['journal_meta.transaction_journal_id'])->pluck('transaction_journal_id')->toArray() - ; + ->get(['journal_meta.transaction_journal_id']) + ->pluck('transaction_journal_id') + ->toArray(); } /** @@ -253,7 +248,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte return (string) $note?->text; } - public function getPiggyBank(RecurrenceTransaction $transaction): ?int + public function getPiggyBank(RecurrenceTransaction $transaction): null|int { $meta = $transaction->recurrenceTransactionMeta; @@ -291,20 +286,19 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte ->where('transaction_journals.user_id', $this->user->id) ->where('name', 'recurrence_id') ->where('data', json_encode((string) $recurrence->id)) - ->get()->pluck('transaction_journal_id')->toArray() - ; + ->get() + ->pluck('transaction_journal_id') + ->toArray(); $search = []; foreach ($journalMeta as $journalId) { $search[] = (int) $journalId; } /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setUser($recurrence->user); - $collector->withCategoryInformation()->withBudgetInformation()->setLimit($pageSize)->setPage($page) - ->withAccountInformation() - ; + $collector->withCategoryInformation()->withBudgetInformation()->setLimit($pageSize)->setPage($page)->withAccountInformation(); $collector->setJournalIds($search); return $collector->getPaginatedGroups(); @@ -317,8 +311,9 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte ->where('transaction_journals.user_id', $this->user->id) ->where('name', 'recurrence_id') ->where('data', json_encode((string) $recurrence->id)) - ->get()->pluck('transaction_journal_id')->toArray() - ; + ->get() + ->pluck('transaction_journal_id') + ->toArray(); $search = []; foreach ($journalMeta as $journalId) { @@ -329,7 +324,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte } /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setUser($recurrence->user); $collector->withCategoryInformation()->withBudgetInformation()->withAccountInformation(); @@ -408,7 +403,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte return $this->filterMaxDate($repeatUntil, $occurrences); } - private function filterMaxDate(?Carbon $max, array $occurrences): array + private function filterMaxDate(null|Carbon $max, array $occurrences): array { $filtered = []; if (!$max instanceof Carbon) { @@ -449,7 +444,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte if ('weekly' === $repetition->repetition_type) { $dayOfWeek = trans(sprintf('config.dow_%s', $repetition->repetition_moment), [], $language); if ($repetition->repetition_skip > 0) { - return (string) trans('firefly.recurring_weekly_skip', ['weekday' => $dayOfWeek, 'skip' => $repetition->repetition_skip + 1], $language); + return (string) trans('firefly.recurring_weekly_skip', ['weekday' => $dayOfWeek, 'skip' => $repetition->repetition_skip + 1], $language); } return (string) trans('firefly.recurring_weekly', ['weekday' => $dayOfWeek], $language); @@ -458,33 +453,33 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte if ($repetition->repetition_skip > 0) { return (string) trans( 'firefly.recurring_monthly_skip', - ['dayOfMonth' => $repetition->repetition_moment, 'skip' => $repetition->repetition_skip + 1], + ['dayOfMonth' => $repetition->repetition_moment, 'skip' => $repetition->repetition_skip + 1], $language ); } return (string) trans( 'firefly.recurring_monthly', - ['dayOfMonth' => $repetition->repetition_moment, 'skip' => $repetition->repetition_skip - 1], + ['dayOfMonth' => $repetition->repetition_moment, 'skip' => $repetition->repetition_skip - 1], $language ); } if ('ndom' === $repetition->repetition_type) { - $parts = explode(',', $repetition->repetition_moment); + $parts = explode(',', $repetition->repetition_moment); // first part is number of week, second is weekday. $dayOfWeek = trans(sprintf('config.dow_%s', $parts[1]), [], $language); - return (string) trans('firefly.recurring_ndom', ['weekday' => $dayOfWeek, 'dayOfMonth' => $parts[0]], $language); + return (string) trans('firefly.recurring_ndom', ['weekday' => $dayOfWeek, 'dayOfMonth' => $parts[0]], $language); } if ('yearly' === $repetition->repetition_type) { - $today = today(config('app.timezone'))->endOfYear(); - $repDate = Carbon::createFromFormat('Y-m-d', $repetition->repetition_moment); + $today = today(config('app.timezone'))->endOfYear(); + $repDate = Carbon::createFromFormat('Y-m-d', $repetition->repetition_moment); if (!$repDate instanceof Carbon) { $repDate = clone $today; } $diffInYears = (int) $today->diffInYears($repDate, true); $repDate->addYears($diffInYears); // technically not necessary. - $string = $repDate->isoFormat((string) trans('config.month_and_day_no_year_js')); + $string = $repDate->isoFormat((string) trans('config.month_and_day_no_year_js')); return (string) trans('firefly.recurring_yearly', ['date' => $string], $language); } @@ -498,9 +493,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte if ('' !== $query) { $search->whereLike('recurrences.title', sprintf('%%%s%%', $query)); } - $search - ->orderBy('recurrences.title', 'ASC') - ; + $search->orderBy('recurrences.title', 'ASC'); return $search->take($limit)->get(['id', 'title', 'description']); } @@ -546,7 +539,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte $occurrences = []; $mutator = clone $start; $mutator->startOfDay(); - $skipMod = $repetition->repetition_skip + 1; + $skipMod = $repetition->repetition_skip + 1; Log::debug(sprintf('Calculating occurrences for rep type "%s"', $repetition->repetition_type)); Log::debug(sprintf('Mutator is now: %s', $mutator->format('Y-m-d'))); diff --git a/app/Repositories/Recurring/RecurringRepositoryInterface.php b/app/Repositories/Recurring/RecurringRepositoryInterface.php index 9fb715e545..23e7608d6b 100644 --- a/app/Repositories/Recurring/RecurringRepositoryInterface.php +++ b/app/Repositories/Recurring/RecurringRepositoryInterface.php @@ -73,27 +73,27 @@ interface RecurringRepositoryInterface /** * Get the category from a recurring transaction transaction. */ - public function getBillId(RecurrenceTransaction $recTransaction): ?int; + public function getBillId(RecurrenceTransaction $recTransaction): null|int; /** * Get the budget ID from a recurring transaction transaction. */ - public function getBudget(RecurrenceTransaction $recTransaction): ?int; + public function getBudget(RecurrenceTransaction $recTransaction): null|int; /** * Get the category from a recurring transaction transaction. */ - public function getCategoryId(RecurrenceTransaction $recTransaction): ?int; + public function getCategoryId(RecurrenceTransaction $recTransaction): null|int; /** * Get the category from a recurring transaction transaction. */ - public function getCategoryName(RecurrenceTransaction $recTransaction): ?string; + public function getCategoryName(RecurrenceTransaction $recTransaction): null|string; /** * Returns the count of journals created for this recurrence, possibly limited by time. */ - public function getJournalCount(Recurrence $recurrence, ?Carbon $start = null, ?Carbon $end = null): int; + public function getJournalCount(Recurrence $recurrence, null|Carbon $start = null, null|Carbon $end = null): int; /** * Get journal ID's for journals created by this recurring transaction. @@ -110,7 +110,7 @@ interface RecurringRepositoryInterface */ public function getOccurrencesInRange(RecurrenceRepetition $repetition, Carbon $start, Carbon $end): array; - public function getPiggyBank(RecurrenceTransaction $transaction): ?int; + public function getPiggyBank(RecurrenceTransaction $transaction): null|int; /** * Get the tags from the recurring transaction. diff --git a/app/Repositories/Rule/RuleRepository.php b/app/Repositories/Rule/RuleRepository.php index 7954bacf39..8242bae0f2 100644 --- a/app/Repositories/Rule/RuleRepository.php +++ b/app/Repositories/Rule/RuleRepository.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace FireflyIII\Repositories\Rule; -use Illuminate\Support\Facades\Log; use Exception; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Rule; @@ -35,6 +34,7 @@ use FireflyIII\Support\Repositories\UserGroup\UserGroupInterface; use FireflyIII\Support\Repositories\UserGroup\UserGroupTrait; use FireflyIII\Support\Search\OperatorQuerySearch; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Log; /** * Class RuleRepository. @@ -61,14 +61,14 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface public function duplicate(Rule $rule): Rule { - $newRule = $rule->replicate(); + $newRule = $rule->replicate(); $newRule->title = (string) trans('firefly.rule_copy_of', ['title' => $rule->title]); $newRule->save(); // replicate all triggers /** @var RuleTrigger $trigger */ foreach ($rule->ruleTriggers as $trigger) { - $newTrigger = $trigger->replicate(); + $newTrigger = $trigger->replicate(); $newTrigger->rule_id = $newRule->id; $newTrigger->save(); } @@ -76,7 +76,7 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface // replicate all actions /** @var RuleAction $action */ foreach ($rule->ruleActions as $action) { - $newAction = $action->replicate(); + $newAction = $action->replicate(); $newAction->rule_id = $newRule->id; $newAction->save(); } @@ -89,7 +89,10 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface */ public function getAll(): Collection { - return $this->user->rules()->with(['ruleGroup'])->get(); + return $this->user + ->rules() + ->with(['ruleGroup']) + ->get(); } /** @@ -113,7 +116,7 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface { $count = $rule->ruleTriggers()->count(); if (0 === $count) { - throw new FireflyException('Rules should have more than zero triggers, rule #'.$rule->id.' has none!'); + throw new FireflyException('Rules should have more than zero triggers, rule #' . $rule->id . ' has none!'); } return $rule->ruleTriggers()->where('trigger_type', 'user_action')->first()->trigger_value; @@ -143,7 +146,7 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface if ('user_action' === $trigger->trigger_type) { continue; } - $triggerType = $trigger->trigger_type; + $triggerType = $trigger->trigger_type; if (str_starts_with((string) $trigger->trigger_type, '-')) { $triggerType = substr((string) $trigger->trigger_type, 1); } @@ -161,15 +164,16 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface public function getStoreRules(): Collection { - $collection = $this->user->rules() + $collection = $this->user + ->rules() ->leftJoin('rule_groups', 'rule_groups.id', '=', 'rules.rule_group_id') ->where('rules.active', true) ->where('rule_groups.active', true) ->orderBy('rule_groups.order', 'ASC') ->orderBy('rules.order', 'ASC') ->orderBy('rules.id', 'ASC') - ->with(['ruleGroup', 'ruleTriggers'])->get(['rules.*']) - ; + ->with(['ruleGroup', 'ruleTriggers']) + ->get(['rules.*']); $filtered = new Collection(); /** @var Rule $rule */ @@ -187,15 +191,16 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface public function getUpdateRules(): Collection { - $collection = $this->user->rules() + $collection = $this->user + ->rules() ->leftJoin('rule_groups', 'rule_groups.id', '=', 'rules.rule_group_id') ->where('rules.active', true) ->where('rule_groups.active', true) ->orderBy('rule_groups.order', 'ASC') ->orderBy('rules.order', 'ASC') ->orderBy('rules.id', 'ASC') - ->with(['ruleGroup', 'ruleTriggers'])->get() - ; + ->with(['ruleGroup', 'ruleTriggers']) + ->get(); $filtered = new Collection(); /** @var Rule $rule */ @@ -217,9 +222,7 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface if ('' !== $query) { $search->whereLike('rules.title', sprintf('%%%s%%', $query)); } - $search->orderBy('rules.order', 'ASC') - ->orderBy('rules.title', 'ASC') - ; + $search->orderBy('rules.order', 'ASC')->orderBy('rules.title', 'ASC'); return $search->take($limit)->get(['id', 'title', 'description']); } @@ -229,12 +232,15 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface */ public function store(array $data): Rule { - $ruleGroup = null; + $ruleGroup = null; if (array_key_exists('rule_group_id', $data)) { $ruleGroup = $this->user->ruleGroups()->find($data['rule_group_id']); } if (array_key_exists('rule_group_title', $data)) { - $ruleGroup = $this->user->ruleGroups()->where('title', $data['rule_group_title'])->first(); + $ruleGroup = $this->user + ->ruleGroups() + ->where('title', $data['rule_group_title']) + ->first(); } if (null === $ruleGroup) { throw new FireflyException('No such rule group.'); @@ -243,17 +249,17 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface /** @var RuleGroup $ruleGroup */ // start by creating a new rule: - $rule = new Rule(); + $rule = new Rule(); $rule->user()->associate($this->user); $rule->userGroup()->associate($this->user->userGroup); - $rule->rule_group_id = $ruleGroup->id; - $rule->order = 31337; - $rule->active = array_key_exists('active', $data) ? $data['active'] : true; - $rule->strict = array_key_exists('strict', $data) ? $data['strict'] : false; + $rule->rule_group_id = $ruleGroup->id; + $rule->order = 31337; + $rule->active = array_key_exists('active', $data) ? $data['active'] : true; + $rule->strict = array_key_exists('strict', $data) ? $data['strict'] : false; $rule->stop_processing = array_key_exists('stop_processing', $data) ? $data['stop_processing'] : false; - $rule->title = array_key_exists('title', $data) ? $data['title'] : ''; - $rule->description = array_key_exists('description', $data) ? $data['description'] : ''; + $rule->title = array_key_exists('title', $data) ? $data['title'] : ''; + $rule->description = array_key_exists('description', $data) ? $data['description'] : ''; $rule->save(); $rule->refresh(); @@ -278,7 +284,7 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface return $rule; } - public function find(int $ruleId): ?Rule + public function find(int $ruleId): null|Rule { /** @var null|Rule */ return $this->user->rules()->find($ruleId); @@ -287,19 +293,19 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface private function setRuleTrigger(string $moment, Rule $rule): void { /** @var null|RuleTrigger $trigger */ - $trigger = $rule->ruleTriggers()->where('trigger_type', 'user_action')->first(); + $trigger = $rule->ruleTriggers()->where('trigger_type', 'user_action')->first(); if (null !== $trigger) { $trigger->trigger_value = $moment; $trigger->save(); return; } - $trigger = new RuleTrigger(); - $trigger->order = 0; - $trigger->trigger_type = 'user_action'; - $trigger->trigger_value = $moment; - $trigger->rule_id = $rule->id; - $trigger->active = true; + $trigger = new RuleTrigger(); + $trigger->order = 0; + $trigger->trigger_type = 'user_action'; + $trigger->trigger_value = $moment; + $trigger->rule_id = $rule->id; + $trigger->active = true; $trigger->stop_processing = false; $trigger->save(); } @@ -315,20 +321,20 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface public function setOrder(Rule $rule, int $newOrder): void { - $oldOrder = $rule->order; - $groupId = $rule->rule_group_id; - $maxOrder = $this->maxOrder($rule->ruleGroup); - $newOrder = $newOrder > $maxOrder ? $maxOrder + 1 : $newOrder; + $oldOrder = $rule->order; + $groupId = $rule->rule_group_id; + $maxOrder = $this->maxOrder($rule->ruleGroup); + $newOrder = $newOrder > $maxOrder ? $maxOrder + 1 : $newOrder; Log::debug(sprintf('New order will be %d', $newOrder)); if ($newOrder > $oldOrder) { - $this->user->rules() + $this->user + ->rules() ->where('rules.rule_group_id', $groupId) ->where('rules.order', '<=', $newOrder) ->where('rules.order', '>', $oldOrder) ->where('rules.id', '!=', $rule->id) - ->decrement('rules.order') - ; + ->decrement('rules.order'); $rule->order = $newOrder; Log::debug(sprintf('Order of rule #%d ("%s") is now %d', $rule->id, $rule->title, $newOrder)); $rule->save(); @@ -336,13 +342,13 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface return; } - $this->user->rules() + $this->user + ->rules() ->where('rules.rule_group_id', $groupId) ->where('rules.order', '>=', $newOrder) ->where('rules.order', '<', $oldOrder) ->where('rules.id', '!=', $rule->id) - ->increment('rules.order') - ; + ->increment('rules.order'); $rule->order = $newOrder; Log::debug(sprintf('Order of rule #%d ("%s") is now %d', $rule->id, $rule->title, $newOrder)); $rule->save(); @@ -367,7 +373,7 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface // empty the value in case the rule needs no context // TODO create a helper to automatically return these. - $needTrue = [ + $needTrue = [ 'reconciled', 'has_attachments', 'has_any_category', @@ -388,18 +394,18 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface 'account_is_cash', 'exists', 'no_external_id', - 'any_external_id', + 'any_external_id' ]; if (in_array($type, $needTrue, true)) { $value = ''; } - $triggerValues = [ + $triggerValues = [ 'action' => $type, 'value' => $value, 'stop_processing' => $stopProcessing, 'order' => $order, - 'active' => $active, + 'active' => $active ]; $this->storeTrigger($rule, $triggerValues); ++$order; @@ -408,13 +414,13 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface public function storeTrigger(Rule $rule, array $values): RuleTrigger { - $ruleTrigger = new RuleTrigger(); + $ruleTrigger = new RuleTrigger(); $ruleTrigger->rule()->associate($rule); - $ruleTrigger->order = $values['order']; - $ruleTrigger->active = $values['active']; + $ruleTrigger->order = $values['order']; + $ruleTrigger->active = $values['active']; $ruleTrigger->stop_processing = $values['stop_processing']; - $ruleTrigger->trigger_type = $values['action']; - $ruleTrigger->trigger_value = $values['value'] ?? ''; + $ruleTrigger->trigger_type = $values['action']; + $ruleTrigger->trigger_value = $values['value'] ?? ''; $ruleTrigger->save(); return $ruleTrigger; @@ -432,7 +438,7 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface 'value' => $value, 'stop_processing' => $stopProcessing, 'order' => $order, - 'active' => $active, + 'active' => $active ]; $this->storeAction($rule, $actionValues); ++$order; @@ -441,13 +447,13 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface public function storeAction(Rule $rule, array $values): RuleAction { - $ruleAction = new RuleAction(); + $ruleAction = new RuleAction(); $ruleAction->rule()->associate($rule); - $ruleAction->order = $values['order']; - $ruleAction->active = $values['active']; + $ruleAction->order = $values['order']; + $ruleAction->active = $values['active']; $ruleAction->stop_processing = $values['stop_processing']; - $ruleAction->action_type = $values['action']; - $ruleAction->action_value = $values['value'] ?? ''; + $ruleAction->action_type = $values['action']; + $ruleAction->action_value = $values['value'] ?? ''; $ruleAction->save(); return $ruleAction; @@ -456,14 +462,7 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface public function update(Rule $rule, array $data): Rule { // update rule: - $fields = [ - 'title', - 'description', - 'strict', - 'rule_group_id', - 'active', - 'stop_processing', - ]; + $fields = ['title', 'description', 'strict', 'rule_group_id', 'active', 'stop_processing']; foreach ($fields as $field) { if (array_key_exists($field, $data)) { $rule->{$field} = $data[$field]; @@ -471,7 +470,7 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface } $rule->save(); $rule->refresh(); - $group = $rule->ruleGroup; + $group = $rule->ruleGroup; // update the order: $this->resetRuleOrder($group); if (array_key_exists('order', $data)) { diff --git a/app/Repositories/Rule/RuleRepositoryInterface.php b/app/Repositories/Rule/RuleRepositoryInterface.php index e4d8e53394..dcd35730a4 100644 --- a/app/Repositories/Rule/RuleRepositoryInterface.php +++ b/app/Repositories/Rule/RuleRepositoryInterface.php @@ -51,7 +51,7 @@ interface RuleRepositoryInterface public function duplicate(Rule $rule): Rule; - public function find(int $ruleId): ?Rule; + public function find(int $ruleId): null|Rule; /** * Get all the users rules. diff --git a/app/Repositories/RuleGroup/RuleGroupRepository.php b/app/Repositories/RuleGroup/RuleGroupRepository.php index ead89a1b91..48211deefa 100644 --- a/app/Repositories/RuleGroup/RuleGroupRepository.php +++ b/app/Repositories/RuleGroup/RuleGroupRepository.php @@ -48,8 +48,7 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte ->orderBy('order', 'ASC') ->orderBy('active', 'DESC') ->orderBy('title', 'ASC') - ->get(['rule_groups.id']) - ; + ->get(['rule_groups.id']); $index = 1; /** @var RuleGroup $ruleGroup */ @@ -64,7 +63,10 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte public function get(): Collection { - return $this->user->ruleGroups()->orderBy('order', 'ASC')->get(); + return $this->user + ->ruleGroups() + ->orderBy('order', 'ASC') + ->get(); } public function count(): int @@ -75,7 +77,7 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte /** * @throws Exception */ - public function destroy(RuleGroup $ruleGroup, ?RuleGroup $moveTo): bool + public function destroy(RuleGroup $ruleGroup, null|RuleGroup $moveTo): bool { /** @var Rule $rule */ foreach ($ruleGroup->rules as $rule) { @@ -106,8 +108,7 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte ->whereNull('deleted_at') ->orderBy('order', 'ASC') ->orderBy('title', 'DESC') - ->get() - ; + ->get(); $count = 1; /** @var RuleGroup $entry */ @@ -128,12 +129,7 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte public function resetRuleOrder(RuleGroup $ruleGroup): bool { - $set = $ruleGroup->rules() - ->orderBy('order', 'ASC') - ->orderBy('title', 'DESC') - ->orderBy('updated_at', 'DESC') - ->get(['rules.*']) - ; + $set = $ruleGroup->rules()->orderBy('order', 'ASC')->orderBy('title', 'DESC')->orderBy('updated_at', 'DESC')->get(['rules.*']); $count = 1; /** @var Rule $entry */ @@ -154,12 +150,7 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte private function resetRuleActionOrder(Rule $rule): void { - $actions = $rule->ruleActions() - ->orderBy('order', 'ASC') - ->orderBy('active', 'DESC') - ->orderBy('action_type', 'ASC') - ->get() - ; + $actions = $rule->ruleActions()->orderBy('order', 'ASC')->orderBy('active', 'DESC')->orderBy('action_type', 'ASC')->get(); $index = 1; /** @var RuleAction $action */ @@ -175,12 +166,7 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte private function resetRuleTriggerOrder(Rule $rule): void { - $triggers = $rule->ruleTriggers() - ->orderBy('order', 'ASC') - ->orderBy('active', 'DESC') - ->orderBy('trigger_type', 'ASC') - ->get() - ; + $triggers = $rule->ruleTriggers()->orderBy('order', 'ASC')->orderBy('active', 'DESC')->orderBy('trigger_type', 'ASC')->get(); $index = 1; /** @var RuleTrigger $trigger */ @@ -207,101 +193,102 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte } } - public function find(int $ruleGroupId): ?RuleGroup + public function find(int $ruleGroupId): null|RuleGroup { /** @var null|RuleGroup */ return $this->user->ruleGroups()->find($ruleGroupId); } - public function findByTitle(string $title): ?RuleGroup + public function findByTitle(string $title): null|RuleGroup { /** @var null|RuleGroup */ - return $this->user->ruleGroups()->where('title', $title)->first(); + return $this->user + ->ruleGroups() + ->where('title', $title) + ->first(); } public function getActiveGroups(): Collection { - return $this->user->ruleGroups()->with(['rules'])->where('rule_groups.active', true)->orderBy('order', 'ASC')->get(['rule_groups.*']); + return $this->user + ->ruleGroups() + ->with(['rules']) + ->where('rule_groups.active', true) + ->orderBy('order', 'ASC') + ->get(['rule_groups.*']); } public function getActiveRules(RuleGroup $group): Collection { - return $group->rules() - ->where('rules.active', true) - ->get(['rules.*']) - ; + return $group->rules()->where('rules.active', true)->get(['rules.*']); } public function getActiveStoreRules(RuleGroup $group): Collection { - return $group->rules() + return $group + ->rules() ->orderBy('rules.order', 'ASC') ->leftJoin('rule_triggers', 'rules.id', '=', 'rule_triggers.rule_id') ->where('rule_triggers.trigger_type', 'user_action') ->where('rule_triggers.trigger_value', 'store-journal') ->where('rules.active', true) - ->get(['rules.*']) - ; + ->get(['rules.*']); } public function getActiveUpdateRules(RuleGroup $group): Collection { - return $group->rules() + return $group + ->rules() ->leftJoin('rule_triggers', 'rules.id', '=', 'rule_triggers.rule_id') ->where('rule_triggers.trigger_type', 'user_action') ->where('rule_triggers.trigger_value', 'update-journal') ->where('rules.active', true) - ->get(['rules.*']) - ; + ->get(['rules.*']); } - public function getAllRuleGroupsWithRules(?string $filter): Collection + public function getAllRuleGroupsWithRules(null|string $filter): Collection { - $groups = $this->user->ruleGroups() + $groups = $this->user + ->ruleGroups() ->orderBy('order', 'ASC') - ->with( - [ // @phpstan-ignore-line - 'rules' => static function (HasMany $query): void { - $query->orderBy('order', 'ASC'); - // $query->where('rules.active', true); - }, - 'rules.ruleTriggers' => static function (HasMany $query): void { - $query->orderBy('order', 'ASC'); - }, - 'rules.ruleActions' => static function (HasMany $query): void { - $query->orderBy('order', 'ASC'); - }, - ] - )->get() - ; + ->with([ // @phpstan-ignore-line + 'rules' => static function (HasMany $query): void { + $query->orderBy('order', 'ASC'); + + // $query->where('rules.active', true); + }, + 'rules.ruleTriggers' => static function (HasMany $query): void { + $query->orderBy('order', 'ASC'); + }, + 'rules.ruleActions' => static function (HasMany $query): void { + $query->orderBy('order', 'ASC'); + } + ]) + ->get(); if (null === $filter) { return $groups; } Log::debug(sprintf('Will filter getRuleGroupsWithRules on "%s".', $filter)); - return $groups->map( - static function (RuleGroup $group) use ($filter): RuleGroup { // @phpstan-ignore-line - Log::debug(sprintf('Now filtering group #%d', $group->id)); - // filter the rules in the rule group: - $group->rules = $group->rules->filter( - static function (Rule $rule) use ($filter, $group): bool { - Log::debug(sprintf('Now filtering rule #%d', $rule->id)); - foreach ($rule->ruleTriggers as $trigger) { - if ('user_action' === $trigger->trigger_type && $filter === $trigger->trigger_value) { - Log::debug(sprintf('Rule #%d triggers on %s, include it in rule group #%d.', $rule->id, $filter, $group->id)); + return $groups->map(static function (RuleGroup $group) use ($filter): RuleGroup { // @phpstan-ignore-line + Log::debug(sprintf('Now filtering group #%d', $group->id)); + // filter the rules in the rule group: + $group->rules = $group->rules->filter(static function (Rule $rule) use ($filter, $group): bool { + Log::debug(sprintf('Now filtering rule #%d', $rule->id)); + foreach ($rule->ruleTriggers as $trigger) { + if ('user_action' === $trigger->trigger_type && $filter === $trigger->trigger_value) { + Log::debug(sprintf('Rule #%d triggers on %s, include it in rule group #%d.', $rule->id, $filter, $group->id)); - return true; - } - } - Log::debug(sprintf('Rule #%d does not trigger on %s, do not include it.', $rule->id, $filter)); - - return false; + return true; } - ); + } + Log::debug(sprintf('Rule #%d does not trigger on %s, do not include it.', $rule->id, $filter)); - return $group; - } - ); + return false; + }); + + return $group; + }); } public function getHighestOrderRuleGroup(): int @@ -311,66 +298,62 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte return (int) $entry; } - public function getRuleGroupsWithRules(?string $filter): Collection + public function getRuleGroupsWithRules(null|string $filter): Collection { - $groups = $this->user->ruleGroups() + $groups = $this->user + ->ruleGroups() ->orderBy('order', 'ASC') ->where('active', true) - ->with( - [ // @phpstan-ignore-line - 'rules' => static function (HasMany $query): void { - $query->orderBy('order', 'ASC'); - $query->where('rules.active', true); - }, - 'rules.ruleTriggers' => static function (HasMany $query): void { - $query->orderBy('order', 'ASC'); - }, - 'rules.ruleActions' => static function (HasMany $query): void { - $query->orderBy('order', 'ASC'); - }, - ] - )->get() - ; + ->with([ // @phpstan-ignore-line + 'rules' => static function (HasMany $query): void { + $query->orderBy('order', 'ASC'); + $query->where('rules.active', true); + }, + 'rules.ruleTriggers' => static function (HasMany $query): void { + $query->orderBy('order', 'ASC'); + }, + 'rules.ruleActions' => static function (HasMany $query): void { + $query->orderBy('order', 'ASC'); + } + ]) + ->get(); if (null === $filter) { return $groups; } Log::debug(sprintf('Will filter getRuleGroupsWithRules on "%s".', $filter)); - return $groups->map( - static function (RuleGroup $group) use ($filter): RuleGroup { // @phpstan-ignore-line - Log::debug(sprintf('Now filtering group #%d', $group->id)); - // filter the rules in the rule group: - $group->rules = $group->rules->filter( - static function (Rule $rule) use ($filter, $group): bool { - Log::debug(sprintf('Now filtering rule #%d', $rule->id)); - foreach ($rule->ruleTriggers as $trigger) { - if ('user_action' === $trigger->trigger_type && $filter === $trigger->trigger_value) { - Log::debug(sprintf('Rule #%d triggers on %s, include it in rule group #%d.', $rule->id, $filter, $group->id)); + return $groups->map(static function (RuleGroup $group) use ($filter): RuleGroup { // @phpstan-ignore-line + Log::debug(sprintf('Now filtering group #%d', $group->id)); + // filter the rules in the rule group: + $group->rules = $group->rules->filter(static function (Rule $rule) use ($filter, $group): bool { + Log::debug(sprintf('Now filtering rule #%d', $rule->id)); + foreach ($rule->ruleTriggers as $trigger) { + if ('user_action' === $trigger->trigger_type && $filter === $trigger->trigger_value) { + Log::debug(sprintf('Rule #%d triggers on %s, include it in rule group #%d.', $rule->id, $filter, $group->id)); - return true; - } - } - Log::debug(sprintf('Rule #%d does not trigger on %s, do not include it.', $rule->id, $filter)); - - return false; + return true; } - ); + } + Log::debug(sprintf('Rule #%d does not trigger on %s, do not include it.', $rule->id, $filter)); - return $group; - } - ); + return false; + }); + + return $group; + }); } public function getRules(RuleGroup $group): Collection { - return $group->rules() - ->get(['rules.*']) - ; + return $group->rules()->get(['rules.*']); } public function maxOrder(): int { - return (int) $this->user->ruleGroups()->where('active', true)->max('order'); + return (int) $this->user + ->ruleGroups() + ->where('active', true) + ->max('order'); } public function searchRuleGroup(string $query, int $limit): Collection @@ -379,25 +362,21 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte if ('' !== $query) { $search->whereLike('rule_groups.title', sprintf('%%%s%%', $query)); } - $search->orderBy('rule_groups.order', 'ASC') - ->orderBy('rule_groups.title', 'ASC') - ; + $search->orderBy('rule_groups.order', 'ASC')->orderBy('rule_groups.title', 'ASC'); return $search->take($limit)->get(['id', 'title', 'description']); } public function store(array $data): RuleGroup { - $newRuleGroup = new RuleGroup( - [ - 'user_id' => $this->user->id, - 'user_group_id' => $this->user->user_group_id, - 'title' => $data['title'], - 'description' => $data['description'], - 'order' => 31337, - 'active' => array_key_exists('active', $data) ? $data['active'] : true, - ] - ); + $newRuleGroup = new RuleGroup([ + 'user_id' => $this->user->id, + 'user_group_id' => $this->user->user_group_id, + 'title' => $data['title'], + 'description' => $data['description'], + 'order' => 31337, + 'active' => array_key_exists('active', $data) ? $data['active'] : true + ]); $newRuleGroup->save(); $this->resetOrder(); if (array_key_exists('order', $data)) { @@ -409,13 +388,15 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte public function setOrder(RuleGroup $ruleGroup, int $newOrder): void { - $oldOrder = $ruleGroup->order; + $oldOrder = $ruleGroup->order; if ($newOrder > $oldOrder) { - $this->user->ruleGroups()->where('rule_groups.order', '<=', $newOrder)->where('rule_groups.order', '>', $oldOrder) + $this->user + ->ruleGroups() + ->where('rule_groups.order', '<=', $newOrder) + ->where('rule_groups.order', '>', $oldOrder) ->where('rule_groups.id', '!=', $ruleGroup->id) - ->decrement('order') - ; + ->decrement('order'); $ruleGroup->order = $newOrder; Log::debug(sprintf('Order of group #%d ("%s") is now %d', $ruleGroup->id, $ruleGroup->title, $newOrder)); $ruleGroup->save(); @@ -423,10 +404,12 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte return; } - $this->user->ruleGroups()->where('rule_groups.order', '>=', $newOrder)->where('rule_groups.order', '<', $oldOrder) + $this->user + ->ruleGroups() + ->where('rule_groups.order', '>=', $newOrder) + ->where('rule_groups.order', '<', $oldOrder) ->where('rule_groups.id', '!=', $ruleGroup->id) - ->increment('order') - ; + ->increment('order'); $ruleGroup->order = $newOrder; Log::debug(sprintf('Order of group #%d ("%s") is now %d', $ruleGroup->id, $ruleGroup->title, $newOrder)); $ruleGroup->save(); diff --git a/app/Repositories/RuleGroup/RuleGroupRepositoryInterface.php b/app/Repositories/RuleGroup/RuleGroupRepositoryInterface.php index 54b24c1adb..552de07dd9 100644 --- a/app/Repositories/RuleGroup/RuleGroupRepositoryInterface.php +++ b/app/Repositories/RuleGroup/RuleGroupRepositoryInterface.php @@ -49,16 +49,16 @@ interface RuleGroupRepositoryInterface public function count(): int; - public function destroy(RuleGroup $ruleGroup, ?RuleGroup $moveTo): bool; + public function destroy(RuleGroup $ruleGroup, null|RuleGroup $moveTo): bool; /** * Delete everything. */ public function destroyAll(): void; - public function find(int $ruleGroupId): ?RuleGroup; + public function find(int $ruleGroupId): null|RuleGroup; - public function findByTitle(string $title): ?RuleGroup; + public function findByTitle(string $title): null|RuleGroup; /** * Get all rule groups. @@ -76,11 +76,11 @@ interface RuleGroupRepositoryInterface /** * Also inactive groups. */ - public function getAllRuleGroupsWithRules(?string $filter): Collection; + public function getAllRuleGroupsWithRules(null|string $filter): Collection; public function getHighestOrderRuleGroup(): int; - public function getRuleGroupsWithRules(?string $filter): Collection; + public function getRuleGroupsWithRules(null|string $filter): Collection; public function getRules(RuleGroup $group): Collection; diff --git a/app/Repositories/Tag/OperationsRepository.php b/app/Repositories/Tag/OperationsRepository.php index 441ffd3fa0..c69d8301cd 100644 --- a/app/Repositories/Tag/OperationsRepository.php +++ b/app/Repositories/Tag/OperationsRepository.php @@ -28,10 +28,10 @@ use Carbon\Carbon; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Helpers\Collector\GroupCollectorInterface; +use FireflyIII\Support\Facades\Steam; use FireflyIII\Support\Repositories\UserGroup\UserGroupInterface; use FireflyIII\Support\Repositories\UserGroup\UserGroupTrait; use Illuminate\Support\Collection; -use FireflyIII\Support\Facades\Steam; /** * Class OperationsRepository @@ -45,12 +45,12 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn * which have the specified tag(s) set to them. It's grouped per currency, with as few details in the array * as possible. Amounts are always negative. */ - public function listExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $tags = null): array + public function listExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $tags = null): array { /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value]); - $tagIds = []; + $tagIds = []; if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); } @@ -74,14 +74,14 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_code' => $journal['currency_code'], - 'currency_decimal_places' => $journal['currency_decimal_places'], + 'currency_decimal_places' => $journal['currency_decimal_places'] ]; // may have multiple tags: foreach ($journal['tags'] as $tag) { - $tagId = (int) $tag['id']; - $tagName = (string) $tag['name']; - $journalId = (int) $journal['transaction_journal_id']; + $tagId = (int) $tag['id']; + $tagName = (string) $tag['name']; + $journalId = (int) $journal['transaction_journal_id']; if (!in_array($tagId, $tagIds, true)) { continue; } @@ -90,12 +90,8 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn if (in_array($journalId, $listedJournals, true)) { continue; } - $listedJournals[] = $journalId; - $array[$currencyId]['tags'][$tagId] ??= [ - 'id' => $tagId, - 'name' => $tagName, - 'transaction_journals' => [], - ]; + $listedJournals[] = $journalId; + $array[$currencyId]['tags'][$tagId] ??= ['id' => $tagId, 'name' => $tagName, 'transaction_journals' => []]; $array[$currencyId]['tags'][$tagId]['transaction_journals'][$journalId] = [ 'amount' => Steam::negative($journal['amount']), @@ -107,7 +103,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'destination_account_id' => $journal['destination_account_id'], 'destination_account_name' => $journal['destination_account_name'], 'description' => $journal['description'], - 'transaction_group_id' => $journal['transaction_group_id'], + 'transaction_group_id' => $journal['transaction_group_id'] ]; } } @@ -128,12 +124,12 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn * which have the specified tag(s) set to them. It's grouped per currency, with as few details in the array * as possible. Amounts are always positive. */ - public function listIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $tags = null): array + public function listIncome(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $tags = null): array { /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionTypeEnum::DEPOSIT->value]); - $tagIds = []; + $tagIds = []; if ($accounts instanceof Collection && $accounts->count() > 0) { $collector->setAccounts($accounts); } @@ -158,14 +154,14 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_code' => $journal['currency_code'], - 'currency_decimal_places' => $journal['currency_decimal_places'], + 'currency_decimal_places' => $journal['currency_decimal_places'] ]; // may have multiple tags: foreach ($journal['tags'] as $tag) { - $tagId = (int) $tag['id']; - $tagName = (string) $tag['name']; - $journalId = (int) $journal['transaction_journal_id']; + $tagId = (int) $tag['id']; + $tagName = (string) $tag['name']; + $journalId = (int) $journal['transaction_journal_id']; if (!in_array($tagId, $tagIds, true)) { continue; @@ -174,14 +170,10 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn if (in_array($journalId, $listedJournals, true)) { continue; } - $listedJournals[] = $journalId; + $listedJournals[] = $journalId; - $array[$currencyId]['tags'][$tagId] ??= [ - 'id' => $tagId, - 'name' => $tagName, - 'transaction_journals' => [], - ]; - $journalId = (int) $journal['transaction_journal_id']; + $array[$currencyId]['tags'][$tagId] ??= ['id' => $tagId, 'name' => $tagName, 'transaction_journals' => []]; + $journalId = (int) $journal['transaction_journal_id']; $array[$currencyId]['tags'][$tagId]['transaction_journals'][$journalId] = [ 'amount' => Steam::positive($journal['amount']), 'date' => $journal['date'], @@ -191,7 +183,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn 'destination_account_id' => $journal['destination_account_id'], 'destination_account_name' => $journal['destination_account_name'], 'description' => $journal['description'], - 'transaction_group_id' => $journal['transaction_group_id'], + 'transaction_group_id' => $journal['transaction_group_id'] ]; } } @@ -204,7 +196,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn * * @throws FireflyException */ - public function sumExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $tags = null): array + public function sumExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $tags = null): array { throw new FireflyException(sprintf('%s is not yet implemented.', __METHOD__)); } @@ -214,7 +206,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn * * @throws FireflyException */ - public function sumIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $tags = null): array + public function sumIncome(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $tags = null): array { throw new FireflyException(sprintf('%s is not yet implemented.', __METHOD__)); } diff --git a/app/Repositories/Tag/OperationsRepositoryInterface.php b/app/Repositories/Tag/OperationsRepositoryInterface.php index b7cd50c57c..a96f48e09c 100644 --- a/app/Repositories/Tag/OperationsRepositoryInterface.php +++ b/app/Repositories/Tag/OperationsRepositoryInterface.php @@ -48,22 +48,22 @@ interface OperationsRepositoryInterface * which have the specified tag(s) set to them. It's grouped per currency, with as few details in the array * as possible. Amounts are always negative. */ - public function listExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $tags = null): array; + public function listExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $tags = null): array; /** * This method returns a list of all the deposit transaction journals (as arrays) set in that period * which have the specified tag(s) set to them. It's grouped per currency, with as few details in the array * as possible. Amounts are always positive. */ - public function listIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $tags = null): array; + public function listIncome(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $tags = null): array; /** * Sum of withdrawal journals in period for a set of tags, grouped per currency. Amounts are always negative. */ - public function sumExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $tags = null): array; + public function sumExpenses(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $tags = null): array; /** * Sum of income journals in period for a set of tags, grouped per currency. Amounts are always positive. */ - public function sumIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $tags = null): array; + public function sumIncome(Carbon $start, Carbon $end, null|Collection $accounts = null, null|Collection $tags = null): array; } diff --git a/app/Repositories/Tag/TagRepository.php b/app/Repositories/Tag/TagRepository.php index c7a51f7ef7..b46ff63ccb 100644 --- a/app/Repositories/Tag/TagRepository.php +++ b/app/Repositories/Tag/TagRepository.php @@ -82,7 +82,10 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface public function get(): Collection { - return $this->user->tags()->orderBy('tag', 'ASC')->get(['tags.*']); + return $this->user + ->tags() + ->orderBy('tag', 'ASC') + ->get(['tags.*']); } public function expenseInPeriod(Tag $tag, Carbon $start, Carbon $end): array @@ -96,19 +99,22 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface return $collector->getExtractedJournals(); } - public function find(int $tagId): ?Tag + public function find(int $tagId): null|Tag { /** @var null|Tag */ return $this->user->tags()->find($tagId); } - public function findByTag(string $tag): ?Tag + public function findByTag(string $tag): null|Tag { /** @var null|Tag */ - return $this->user->tags()->where('tag', $tag)->first(); + return $this->user + ->tags() + ->where('tag', $tag) + ->first(); } - public function firstUseDate(Tag $tag): ?Carbon + public function firstUseDate(Tag $tag): null|Carbon { return $tag->transactionJournals()->orderBy('date', 'ASC')->first()?->date; } @@ -118,21 +124,22 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface $set = $tag->attachments()->get(); $disk = Storage::disk('upload'); - return $set->each( - static function (Attachment $attachment) use ($disk): void { // @phpstan-ignore-line - /** @var null|Note $note */ - $note = $attachment->notes()->first(); - // only used in v1 view of tags - $attachment->file_exists = $disk->exists($attachment->fileName()); - $attachment->notes_text = null === $note ? '' : $note->text; - } - ); + return $set->each(static function (Attachment $attachment) use ($disk): void { // @phpstan-ignore-line + /** @var null|Note $note */ + $note = $attachment->notes()->first(); + // only used in v1 view of tags + $attachment->file_exists = $disk->exists($attachment->fileName()); + $attachment->notes_text = null === $note ? '' : $note->text; + }); } - public function getTagsInYear(?int $year): array + public function getTagsInYear(null|int $year): array { // get all tags in the year (if present): - $tagQuery = $this->user->tags()->with(['locations', 'attachments'])->orderBy('tags.tag'); + $tagQuery = $this->user + ->tags() + ->with(['locations', 'attachments']) + ->orderBy('tags.tag'); // add date range (or not): if (null === $year) { @@ -156,7 +163,7 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface 'id' => $tag->id, 'created_at' => $tag->created_at, 'location' => $tag->locations->first(), - 'attachments' => $tag->attachments, + 'attachments' => $tag->attachments ]; } @@ -174,7 +181,7 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface return $collector->getExtractedJournals(); } - public function lastUseDate(Tag $tag): ?Carbon + public function lastUseDate(Tag $tag): null|Carbon { return $tag->transactionJournals()->orderBy('date', 'DESC')->first()?->date; } @@ -182,16 +189,24 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface /** * Will return the newest tag (if known) or NULL. */ - public function newestTag(): ?Tag + public function newestTag(): null|Tag { /** @var null|Tag */ - return $this->user->tags()->whereNotNull('date')->orderBy('date', 'DESC')->first(); + return $this->user + ->tags() + ->whereNotNull('date') + ->orderBy('date', 'DESC') + ->first(); } - public function oldestTag(): ?Tag + public function oldestTag(): null|Tag { /** @var null|Tag */ - return $this->user->tags()->whereNotNull('date')->orderBy('date', 'ASC')->first(); + return $this->user + ->tags() + ->whereNotNull('date') + ->orderBy('date', 'ASC') + ->first(); } /** @@ -201,7 +216,10 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface { $search = sprintf('%%%s%%', $query); - return $this->user->tags()->whereLike('tag', $search)->get(['tags.*']); + return $this->user + ->tags() + ->whereLike('tag', $search) + ->get(['tags.*']); } /** @@ -227,7 +245,7 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface return $factory->create($data); } - public function sumsOfTag(Tag $tag, ?Carbon $start, ?Carbon $end): array + public function sumsOfTag(Tag $tag, null|Carbon $start, null|Carbon $end): array { /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); @@ -237,13 +255,13 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface } $collector->setTag($tag)->withAccountInformation(); - $journals = $collector->getExtractedJournals(); + $journals = $collector->getExtractedJournals(); - $sums = []; + $sums = []; /** @var array $journal */ foreach ($journals as $journal) { - $found = false; + $found = false; /** @var array $localTag */ foreach ($journal['tags'] as $localTag) { @@ -254,7 +272,7 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface if (false === $found) { continue; } - $currencyId = (int) $journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $sums[$currencyId] ??= [ 'currency_id' => $currencyId, 'currency_name' => $journal['currency_name'], @@ -264,18 +282,18 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface TransactionTypeEnum::DEPOSIT->value => '0', TransactionTypeEnum::TRANSFER->value => '0', TransactionTypeEnum::RECONCILIATION->value => '0', - TransactionTypeEnum::OPENING_BALANCE->value => '0', + TransactionTypeEnum::OPENING_BALANCE->value => '0' ]; // add amount to correct type: - $amount = Steam::positive((string) $journal['amount']); - $type = $journal['transaction_type_type']; + $amount = Steam::positive((string) $journal['amount']); + $type = $journal['transaction_type_type']; if (TransactionTypeEnum::WITHDRAWAL->value === $type) { $amount = bcmul($amount, '-1'); } $sums[$currencyId][$type] = bcadd((string) $sums[$currencyId][$type], $amount); - $foreignCurrencyId = $journal['foreign_currency_id']; + $foreignCurrencyId = $journal['foreign_currency_id']; if (null !== $foreignCurrencyId && 0 !== $foreignCurrencyId) { $sums[$foreignCurrencyId] ??= [ 'currency_id' => $foreignCurrencyId, @@ -286,10 +304,10 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface TransactionTypeEnum::DEPOSIT->value => '0', TransactionTypeEnum::TRANSFER->value => '0', TransactionTypeEnum::RECONCILIATION->value => '0', - TransactionTypeEnum::OPENING_BALANCE->value => '0', + TransactionTypeEnum::OPENING_BALANCE->value => '0' ]; // add foreign amount to correct type: - $amount = Steam::positive((string) $journal['foreign_amount']); + $amount = Steam::positive((string) $journal['foreign_amount']); if (TransactionTypeEnum::WITHDRAWAL->value === $type) { $amount = bcmul($amount, '-1'); } @@ -304,14 +322,20 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface { $search = sprintf('%%%s', $query); - return $this->user->tags()->whereLike('tag', $search)->get(['tags.*']); + return $this->user + ->tags() + ->whereLike('tag', $search) + ->get(['tags.*']); } public function tagStartsWith(string $query): Collection { $search = sprintf('%s%%', $query); - return $this->user->tags()->whereLike('tag', $search)->get(['tags.*']); + return $this->user + ->tags() + ->whereLike('tag', $search) + ->get(['tags.*']); } public function transferredInPeriod(Tag $tag, Carbon $start, Carbon $end): array @@ -336,7 +360,7 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface $tag->description = $data['description']; } - $tag->latitude = null; + $tag->latitude = null; $tag->longitude = null; $tag->zoomLevel = null; $tag->save(); @@ -354,14 +378,14 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface // otherwise, update or create. if (!(null === $data['latitude'] && null === $data['longitude'] && null === $data['zoom_level'])) { - $location = $this->getLocation($tag); + $location = $this->getLocation($tag); if (!$location instanceof Location) { $location = new Location(); $location->locatable()->associate($tag); } - $location->latitude = $data['latitude'] ?? config('firefly.default_location.latitude'); - $location->longitude = $data['longitude'] ?? config('firefly.default_location.longitude'); + $location->latitude = $data['latitude'] ?? config('firefly.default_location.latitude'); + $location->longitude = $data['longitude'] ?? config('firefly.default_location.longitude'); $location->zoom_level = $data['zoom_level'] ?? config('firefly.default_location.zoom_level'); $location->save(); } @@ -373,7 +397,7 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface return $tag; } - public function getLocation(Tag $tag): ?Location + public function getLocation(Tag $tag): null|Location { /** @var null|Location */ return $tag->locations()->first(); @@ -384,7 +408,8 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface { Log::debug(sprintf('periodCollection(#%d, %s, %s)', $tag->id, $start->format('Y-m-d'), $end->format('Y-m-d'))); - return $tag->transactionJournals() + return $tag + ->transactionJournals() ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id') ->leftJoin('transaction_currencies', 'transaction_currencies.id', '=', 'transactions.transaction_currency_id') @@ -413,9 +438,8 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface 'transaction_journals.transaction_currency_id', 'transactions.amount', 'transactions.native_amount as pc_amount', - 'transactions.foreign_amount', + 'transactions.foreign_amount' ]) - ->toArray() - ; + ->toArray(); } } diff --git a/app/Repositories/Tag/TagRepositoryInterface.php b/app/Repositories/Tag/TagRepositoryInterface.php index 5a53efe7fe..89f5099b31 100644 --- a/app/Repositories/Tag/TagRepositoryInterface.php +++ b/app/Repositories/Tag/TagRepositoryInterface.php @@ -60,11 +60,11 @@ interface TagRepositoryInterface public function expenseInPeriod(Tag $tag, Carbon $start, Carbon $end): array; - public function find(int $tagId): ?Tag; + public function find(int $tagId): null|Tag; - public function findByTag(string $tag): ?Tag; + public function findByTag(string $tag): null|Tag; - public function firstUseDate(Tag $tag): ?Carbon; + public function firstUseDate(Tag $tag): null|Carbon; /** * This method returns all the user's tags. @@ -76,23 +76,23 @@ interface TagRepositoryInterface /** * Return location, or NULL. */ - public function getLocation(Tag $tag): ?Location; + public function getLocation(Tag $tag): null|Location; - public function getTagsInYear(?int $year): array; + public function getTagsInYear(null|int $year): array; public function incomeInPeriod(Tag $tag, Carbon $start, Carbon $end): array; - public function lastUseDate(Tag $tag): ?Carbon; + public function lastUseDate(Tag $tag): null|Carbon; /** * Will return the newest tag (if known) or NULL. */ - public function newestTag(): ?Tag; + public function newestTag(): null|Tag; /** * Will return the newest tag (if known) or NULL. */ - public function oldestTag(): ?Tag; + public function oldestTag(): null|Tag; /** * Find one or more tags based on the query. @@ -112,7 +112,7 @@ interface TagRepositoryInterface /** * Calculates various amounts in tag. */ - public function sumsOfTag(Tag $tag, ?Carbon $start, ?Carbon $end): array; + public function sumsOfTag(Tag $tag, null|Carbon $start, null|Carbon $end): array; /** * Find one or more tags that start with the string in the query diff --git a/app/Repositories/TransactionGroup/TransactionGroupRepository.php b/app/Repositories/TransactionGroup/TransactionGroupRepository.php index b05f20ec83..18d2393996 100644 --- a/app/Repositories/TransactionGroup/TransactionGroupRepository.php +++ b/app/Repositories/TransactionGroup/TransactionGroupRepository.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Repositories\TransactionGroup; -use Illuminate\Support\Facades\Log; use Carbon\Carbon; use Exception; use FireflyIII\Enums\TransactionTypeEnum; @@ -44,13 +43,14 @@ use FireflyIII\Repositories\Attachment\AttachmentRepositoryInterface; use FireflyIII\Services\Internal\Destroy\TransactionGroupDestroyService; use FireflyIII\Services\Internal\Update\GroupUpdateService; use FireflyIII\Support\Facades\Amount; +use FireflyIII\Support\Facades\Steam; use FireflyIII\Support\NullArrayObject; use FireflyIII\Support\Repositories\UserGroup\UserGroupInterface; use FireflyIII\Support\Repositories\UserGroup\UserGroupTrait; use Illuminate\Database\Eloquent\Builder; use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; -use FireflyIII\Support\Facades\Steam; +use Illuminate\Support\Facades\Log; use function Safe\json_decode; @@ -72,7 +72,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, /** * Find a transaction group by its ID. */ - public function find(int $groupId): ?TransactionGroup + public function find(int $groupId): null|TransactionGroup { /** @var null|TransactionGroup */ return $this->user->transactionGroups()->find($groupId); @@ -87,7 +87,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, public function expandGroup(TransactionGroup $group): array { - $result = $group->toArray(); + $result = $group->toArray(); $result['transaction_journals'] = []; /** @var TransactionJournal $journal */ @@ -100,16 +100,16 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, private function expandJournal(TransactionJournal $journal): array { - $array = $journal->toArray(); - $array['transactions'] = []; - $array['meta'] = $journal->transactionJournalMeta->toArray(); - $array['tags'] = $journal->tags->toArray(); - $array['categories'] = $journal->categories->toArray(); - $array['budgets'] = $journal->budgets->toArray(); - $array['notes'] = $journal->notes->toArray(); - $array['locations'] = []; - $array['attachments'] = $journal->attachments->toArray(); - $array['links'] = []; + $array = $journal->toArray(); + $array['transactions'] = []; + $array['meta'] = $journal->transactionJournalMeta->toArray(); + $array['tags'] = $journal->tags->toArray(); + $array['categories'] = $journal->categories->toArray(); + $array['budgets'] = $journal->budgets->toArray(); + $array['notes'] = $journal->notes->toArray(); + $array['locations'] = []; + $array['attachments'] = $journal->attachments->toArray(); + $array['links'] = []; $array['piggy_bank_events'] = $journal->piggyBankEvents->toArray(); /** @var Transaction $transaction */ @@ -122,9 +122,9 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, private function expandTransaction(Transaction $transaction): array { - $array = $transaction->toArray(); - $array['account'] = $transaction->account->toArray(); - $array['budgets'] = []; + $array = $transaction->toArray(); + $array['account'] = $transaction->account->toArray(); + $array['budgets'] = []; $array['categories'] = []; foreach ($transaction->categories as $category) { @@ -145,25 +145,25 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, { $repository = app(AttachmentRepositoryInterface::class); $repository->setUser($this->user); - $journals = $group->transactionJournals->pluck('id')->toArray(); - $set = Attachment::whereIn('attachable_id', $journals) + $journals = $group->transactionJournals->pluck('id')->toArray(); + $set = Attachment::whereIn('attachable_id', $journals) ->where('attachable_type', TransactionJournal::class) ->where('uploaded', true) - ->whereNull('deleted_at')->get() - ; + ->whereNull('deleted_at') + ->get(); - $result = []; + $result = []; /** @var Attachment $attachment */ foreach ($set as $attachment) { - $journalId = $attachment->attachable_id; + $journalId = $attachment->attachable_id; $result[$journalId] ??= []; - $current = $attachment->toArray(); - $current['file_exists'] = true; - $current['notes'] = $repository->getNoteText($attachment); + $current = $attachment->toArray(); + $current['file_exists'] = true; + $current['notes'] = $repository->getNoteText($attachment); // already determined that this attachable is a TransactionJournal. $current['journal_title'] = $attachment->attachable->description; - $result[$journalId][] = $current; + $result[$journalId][] = $current; } return $result; @@ -172,16 +172,12 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, /** * Get the note text for a journal (by ID). */ - public function getNoteText(int $journalId): ?string + public function getNoteText(int $journalId): null|string { /** @var null|Note $note */ - $note = Note::where('noteable_id', $journalId) - ->where('noteable_type', TransactionJournal::class) - ->first() - ; + $note = Note::where('noteable_id', $journalId)->where('noteable_type', TransactionJournal::class)->first(); return $note?->text; - } /** @@ -191,16 +187,15 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, { $return = []; $journals = $group->transactionJournals->pluck('id')->toArray(); - $set = TransactionJournalLink::where( - static function (Builder $q) use ($journals): void { - $q->whereIn('source_id', $journals); - $q->orWhereIn('destination_id', $journals); - } - ) - ->with(['source', 'destination', 'source.transactions']) - ->leftJoin('link_types', 'link_types.id', '=', 'journal_links.link_type_id') - ->get(['journal_links.*', 'link_types.inward', 'link_types.outward', 'link_types.editable']) - ; + $set = TransactionJournalLink::where(static function (Builder $q) use ($journals): void { + $q->whereIn('source_id', $journals); + $q->orWhereIn('destination_id', $journals); + })->with(['source', 'destination', 'source.transactions'])->leftJoin('link_types', 'link_types.id', '=', 'journal_links.link_type_id')->get([ + 'journal_links.*', + 'link_types.inward', + 'link_types.outward', + 'link_types.editable' + ]); /** @var TransactionJournalLink $entry */ foreach ($set as $entry) { @@ -210,29 +205,29 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, // phpstan: the editable field is provided by the query. if ($journalId === $entry->source_id) { - $amount = $this->getFormattedAmount($entry->destination); - $foreignAmount = $this->getFormattedForeignAmount($entry->destination); + $amount = $this->getFormattedAmount($entry->destination); + $foreignAmount = $this->getFormattedForeignAmount($entry->destination); $return[$journalId][] = [ 'id' => $entry->id, 'link' => $entry->outward, 'group' => $entry->destination->transaction_group_id, 'description' => $entry->destination->description, - 'editable' => 1 === (int)$entry->editable, + 'editable' => 1 === (int) $entry->editable, 'amount' => $amount, - 'foreign_amount' => $foreignAmount, + 'foreign_amount' => $foreignAmount ]; } if ($journalId === $entry->destination_id) { - $amount = $this->getFormattedAmount($entry->source); - $foreignAmount = $this->getFormattedForeignAmount($entry->source); + $amount = $this->getFormattedAmount($entry->source); + $foreignAmount = $this->getFormattedForeignAmount($entry->source); $return[$journalId][] = [ 'id' => $entry->id, 'link' => $entry->inward, 'group' => $entry->source->transaction_group_id, 'description' => $entry->source->description, - 'editable' => 1 === (int)$entry->editable, + 'editable' => 1 === (int) $entry->editable, 'amount' => $amount, - 'foreign_amount' => $foreignAmount, + 'foreign_amount' => $foreignAmount ]; } } @@ -262,13 +257,13 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, return ''; } - if (0 === bccomp('0', (string)$transaction->foreign_amount)) { + if (0 === bccomp('0', (string) $transaction->foreign_amount)) { return ''; } - $currency = $transaction->foreignCurrency; - $type = $journal->transactionType->type; - $amount = Steam::positive($transaction->foreign_amount); + $currency = $transaction->foreignCurrency; + $type = $journal->transactionType->type; + $amount = Steam::positive($transaction->foreign_amount); if (TransactionTypeEnum::WITHDRAWAL->value === $type) { return Amount::formatAnything($currency, Steam::negative($amount)); } @@ -276,7 +271,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, return Amount::formatAnything($currency, $amount); } - public function getLocation(int $journalId): ?Location + public function getLocation(int $journalId): null|Location { /** @var TransactionJournal $journal */ $journal = $this->user->transactionJournals()->find($journalId); @@ -296,12 +291,11 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, ->where('transaction_journal_id', $journalId) ->whereIn('name', $fields) ->whereNull('deleted_at') - ->get(['name', 'data']) - ; + ->get(['name', 'data']); $return = []; foreach ($query as $row) { - $return[$row->name] = new Carbon(json_decode((string)$row->data, true, 512, JSON_THROW_ON_ERROR)); + $return[$row->name] = new Carbon(json_decode((string) $row->data, true, 512, JSON_THROW_ON_ERROR)); } return new NullArrayObject($return); @@ -316,12 +310,11 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, ->where('transaction_journal_id', $journalId) ->whereIn('name', $fields) ->whereNull('deleted_at') - ->get(['name', 'data']) - ; + ->get(['name', 'data']); $return = []; foreach ($query as $row) { - $return[$row->name] = json_decode((string)$row->data); + $return[$row->name] = json_decode((string) $row->data); } return new NullArrayObject($return); @@ -337,10 +330,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, $return = []; $journals = $group->transactionJournals->pluck('id')->toArray(); $currency = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); - $data = PiggyBankEvent::whereIn('transaction_journal_id', $journals) - ->with('piggyBank', 'piggyBank.account') - ->get(['piggy_bank_events.*']) - ; + $data = PiggyBankEvent::whereIn('transaction_journal_id', $journals)->with('piggyBank', 'piggyBank.account')->get(['piggy_bank_events.*']); /** @var PiggyBankEvent $row */ foreach ($data as $row) { @@ -348,20 +338,17 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, continue; } // get currency preference. - $currencyPreference = AccountMeta::where('account_id', $row->piggyBank->account_id) - ->where('name', 'currency_id') - ->first() - ; + $currencyPreference = AccountMeta::where('account_id', $row->piggyBank->account_id)->where('name', 'currency_id')->first(); if (null !== $currencyPreference) { $currency = Amount::getTransactionCurrencyById((int) $currencyPreference->data); } - $journalId = $row->transaction_journal_id; + $journalId = $row->transaction_journal_id; $return[$journalId] ??= []; $return[$journalId][] = [ 'piggy' => $row->piggyBank->name, 'piggy_id' => $row->piggy_bank_id, - 'amount' => Amount::formatAnything($currency, $row->amount), + 'amount' => Amount::formatAnything($currency, $row->amount) ]; } @@ -388,8 +375,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, ->leftJoin('tags', 'tag_transaction_journal.tag_id', '=', 'tags.id') ->where('tag_transaction_journal.transaction_journal_id', $journalId) ->orderBy('tags.tag', 'ASC') - ->get(['tags.tag']) - ; + ->get(['tags.tag']); return $result->pluck('tag')->toArray(); } @@ -443,8 +429,8 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, /** @var Transaction $transaction */ foreach ($journal->transactions as $transaction) { - if (-1 === bccomp('0', (string)$transaction->amount)) { - $sum = bcadd($sum, (string)$transaction->amount); + if (-1 === bccomp('0', (string) $transaction->amount)) { + $sum = bcadd($sum, (string) $transaction->amount); $names = sprintf('%s%s', $names, $transaction->account->name); } } diff --git a/app/Repositories/TransactionGroup/TransactionGroupRepositoryInterface.php b/app/Repositories/TransactionGroup/TransactionGroupRepositoryInterface.php index e95cd68f75..bcbc4da9f5 100644 --- a/app/Repositories/TransactionGroup/TransactionGroupRepositoryInterface.php +++ b/app/Repositories/TransactionGroup/TransactionGroupRepositoryInterface.php @@ -64,7 +64,7 @@ interface TransactionGroupRepositoryInterface /** * Find a transaction group by its ID. */ - public function find(int $groupId): ?TransactionGroup; + public function find(int $groupId): null|TransactionGroup; /** * Return all attachments for all journals in the group. @@ -79,7 +79,7 @@ interface TransactionGroupRepositoryInterface /** * Get the location of a journal or NULL. */ - public function getLocation(int $journalId): ?Location; + public function getLocation(int $journalId): null|Location; /** * Return object with all found meta field things as Carbon objects. @@ -94,7 +94,7 @@ interface TransactionGroupRepositoryInterface /** * Get the note text for a journal (by ID). */ - public function getNoteText(int $journalId): ?string; + public function getNoteText(int $journalId): null|string; /** * Return all piggy bank events for all journals in the group. diff --git a/app/Repositories/TransactionType/TransactionTypeRepository.php b/app/Repositories/TransactionType/TransactionTypeRepository.php index ffd2860e1e..041314f605 100644 --- a/app/Repositories/TransactionType/TransactionTypeRepository.php +++ b/app/Repositories/TransactionType/TransactionTypeRepository.php @@ -24,17 +24,17 @@ declare(strict_types=1); namespace FireflyIII\Repositories\TransactionType; -use Illuminate\Support\Facades\Log; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Models\TransactionType; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Log; /** * Class TransactionTypeRepository */ class TransactionTypeRepository implements TransactionTypeRepositoryInterface { - public function findTransactionType(?TransactionType $type, ?string $typeString): TransactionType + public function findTransactionType(null|TransactionType $type, null|string $typeString): TransactionType { Log::debug('Now looking for a transaction type.'); if ($type instanceof TransactionType) { @@ -43,7 +43,7 @@ class TransactionTypeRepository implements TransactionTypeRepositoryInterface return $type; } $typeString ??= TransactionTypeEnum::WITHDRAWAL->value; - $search = $this->findByType($typeString); + $search = $this->findByType($typeString); if (!$search instanceof TransactionType) { $search = $this->findByType(TransactionTypeEnum::WITHDRAWAL->value); } @@ -52,7 +52,7 @@ class TransactionTypeRepository implements TransactionTypeRepositoryInterface return $search; } - public function findByType(string $type): ?TransactionType + public function findByType(string $type): null|TransactionType { $search = ucfirst($type); diff --git a/app/Repositories/TransactionType/TransactionTypeRepositoryInterface.php b/app/Repositories/TransactionType/TransactionTypeRepositoryInterface.php index dfc8681fba..78ef7c64a9 100644 --- a/app/Repositories/TransactionType/TransactionTypeRepositoryInterface.php +++ b/app/Repositories/TransactionType/TransactionTypeRepositoryInterface.php @@ -43,9 +43,9 @@ use Illuminate\Support\Collection; */ interface TransactionTypeRepositoryInterface { - public function findByType(string $type): ?TransactionType; + public function findByType(string $type): null|TransactionType; - public function findTransactionType(?TransactionType $type, ?string $typeString): TransactionType; + public function findTransactionType(null|TransactionType $type, null|string $typeString): TransactionType; public function searchTypes(string $query, int $limit): Collection; } diff --git a/app/Repositories/User/UserRepository.php b/app/Repositories/User/UserRepository.php index a4b5d098a0..4eafaaa928 100644 --- a/app/Repositories/User/UserRepository.php +++ b/app/Repositories/User/UserRepository.php @@ -23,8 +23,6 @@ declare(strict_types=1); namespace FireflyIII\Repositories\User; -use FireflyIII\Support\Facades\Preferences; -use Illuminate\Support\Facades\Log; use Carbon\Carbon; use Exception; use FireflyIII\Exceptions\FireflyException; @@ -33,10 +31,12 @@ use FireflyIII\Models\GroupMembership; use FireflyIII\Models\InvitedUser; use FireflyIII\Models\Role; use FireflyIII\Models\UserGroup; +use FireflyIII\Support\Facades\Preferences; use FireflyIII\User; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Database\QueryException; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Log; use Illuminate\Support\Str; use Override; use SensitiveParameter; @@ -56,19 +56,19 @@ class UserRepository implements UserRepositoryInterface */ public function changeEmail(User $user, string $newEmail): bool { - $oldEmail = $user->email; + $oldEmail = $user->email; // save old email as pref Preferences::setForUser($user, 'previous_email_latest', $oldEmail); - Preferences::setForUser($user, 'previous_email_'.Carbon::now()->format('Y-m-d-H-i-s'), $oldEmail); + Preferences::setForUser($user, 'previous_email_' . Carbon::now()->format('Y-m-d-H-i-s'), $oldEmail); // set undo and confirm token: Preferences::setForUser($user, 'email_change_undo_token', bin2hex(random_bytes(16))); Preferences::setForUser($user, 'email_change_confirm_token', bin2hex(random_bytes(16))); // update user - $user->email = $newEmail; - $user->blocked = true; + $user->email = $newEmail; + $user->blocked = true; $user->blocked_code = 'email_changed'; $user->save(); @@ -86,7 +86,7 @@ class UserRepository implements UserRepositoryInterface public function changeStatus(User $user, bool $isBlocked, string $code): bool { // change blocked status and code: - $user->blocked = $isBlocked; + $user->blocked = $isBlocked; $user->blocked_code = $code; $user->save(); @@ -95,7 +95,7 @@ class UserRepository implements UserRepositoryInterface public function createRole(string $name, string $displayName, string $description): Role { - return Role::create(['name' => $name, 'display_name' => $displayName, 'description' => $description]); + return Role::create(['name' => $name, 'display_name' => $displayName, 'description' => $description]); } public function deleteInvite(InvitedUser $invite): void @@ -142,7 +142,7 @@ class UserRepository implements UserRepositoryInterface return User::orderBy('id', 'DESC')->get(['users.*']); } - public function findByEmail(string $email): ?User + public function findByEmail(string $email): null|User { return User::where('email', $email)->first(); } @@ -150,7 +150,7 @@ class UserRepository implements UserRepositoryInterface /** * Returns the first user in the DB. Generally only works when there is just one. */ - public function first(): ?User + public function first(): null|User { return User::orderBy('id', 'ASC')->first(); } @@ -160,13 +160,12 @@ class UserRepository implements UserRepositoryInterface return InvitedUser::with('user')->get(); } - public function getRoleByUser(User $user): ?string + public function getRoleByUser(User $user): null|string { /** @var null|Role $role */ $role = $user->roles()->first(); return $role?->name; - } /** @@ -175,7 +174,7 @@ class UserRepository implements UserRepositoryInterface public function getRolesInGroup(User $user, int $groupId): array { /** @var null|UserGroup $group */ - $group = UserGroup::find($groupId); + $group = UserGroup::find($groupId); if (null === $group) { throw new FireflyException(sprintf('Could not find group #%d', $groupId)); } @@ -184,14 +183,14 @@ class UserRepository implements UserRepositoryInterface /** @var GroupMembership $membership */ foreach ($memberships as $membership) { - $role = $membership->userRole; + $role = $membership->userRole; $roles[] = $role->title; } return $roles; } - public function find(int $userId): ?User + public function find(int $userId): null|User { return User::find($userId); } @@ -201,12 +200,29 @@ class UserRepository implements UserRepositoryInterface */ public function getUserData(User $user): array { - return ['has_2fa' => null !== $user->mfa_secret, 'is_admin' => $this->hasRole($user, 'owner'), 'blocked' => 1 === (int) $user->blocked, 'blocked_code' => $user->blocked_code, 'accounts' => $user->accounts()->count(), 'journals' => $user->transactionJournals()->count(), 'transactions' => $user->transactions()->count(), 'attachments' => $user->attachments()->count(), 'attachments_size' => $user->attachments()->sum('size'), 'bills' => $user->bills()->count(), 'categories' => $user->categories()->count(), 'budgets' => $user->budgets()->count(), 'budgets_with_limits' => BudgetLimit::distinct() - ->leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id') - ->where('amount', '>', 0) - ->whereNull('budgets.deleted_at') - ->where('budgets.user_id', $user->id) - ->count('budget_limits.budget_id'), 'rule_groups' => $user->ruleGroups()->count(), 'rules' => $user->rules()->count(), 'tags' => $user->tags()->count()]; + return [ + 'has_2fa' => null !== $user->mfa_secret, + 'is_admin' => $this->hasRole($user, 'owner'), + 'blocked' => 1 === (int) $user->blocked, + 'blocked_code' => $user->blocked_code, + 'accounts' => $user->accounts()->count(), + 'journals' => $user->transactionJournals()->count(), + 'transactions' => $user->transactions()->count(), + 'attachments' => $user->attachments()->count(), + 'attachments_size' => $user->attachments()->sum('size'), + 'bills' => $user->bills()->count(), + 'categories' => $user->categories()->count(), + 'budgets' => $user->budgets()->count(), + 'budgets_with_limits' => BudgetLimit::distinct() + ->leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id') + ->where('amount', '>', 0) + ->whereNull('budgets.deleted_at') + ->where('budgets.user_id', $user->id) + ->count('budget_limits.budget_id'), + 'rule_groups' => $user->ruleGroups()->count(), + 'rules' => $user->rules()->count(), + 'tags' => $user->tags()->count() + ]; } public function hasRole(Authenticatable|User|null $user, string $role): bool @@ -238,7 +254,7 @@ class UserRepository implements UserRepositoryInterface /** @var null|UserGroup $group */ $group = $membership->userGroup()->first(); if (null !== $group) { - $groupId = $group->id; + $groupId = $group->id; if (in_array($groupId, array_keys($set), true)) { continue; } @@ -255,15 +271,15 @@ class UserRepository implements UserRepositoryInterface if (!$user instanceof User) { throw new FireflyException('User is not a User object.'); } - $now = now(config('app.timezone')); + $now = now(config('app.timezone')); $now->addDays(2); - $invitee = new InvitedUser(); + $invitee = new InvitedUser(); $invitee->user()->associate($user); $invitee->invite_code = Str::random(64); - $invitee->email = $email; - $invitee->redeemed = false; - $invitee->expires = $now; - $invitee->expires_tz = $now->format('e'); + $invitee->email = $email; + $invitee->redeemed = false; + $invitee->expires = $now; + $invitee->expires_tz = $now->format('e'); $invitee->save(); return $invitee; @@ -281,7 +297,7 @@ class UserRepository implements UserRepositoryInterface /** * Set MFA code. */ - public function setMFACode(User $user, ?string $code): void + public function setMFACode(User $user, null|string $code): void { $user->mfa_secret = $code; $user->save(); @@ -289,14 +305,12 @@ class UserRepository implements UserRepositoryInterface public function store(array $data): User { - $user = User::create( - [ - 'blocked' => $data['blocked'] ?? false, - 'blocked_code' => $data['blocked_code'] ?? null, - 'email' => $data['email'], - 'password' => Str::random(24), - ] - ); + $user = User::create([ + 'blocked' => $data['blocked'] ?? false, + 'blocked_code' => $data['blocked_code'] ?? null, + 'email' => $data['email'], + 'password' => Str::random(24) + ]); $role = $data['role'] ?? ''; if ('' !== $role) { $this->attachRole($user, $role); @@ -326,7 +340,7 @@ class UserRepository implements UserRepositoryInterface public function unblockUser(User $user): void { - $user->blocked = false; + $user->blocked = false; $user->blocked_code = ''; $user->save(); } @@ -366,11 +380,11 @@ class UserRepository implements UserRepositoryInterface if ('' === $newEmail) { return true; } - $oldEmail = $user->email; + $oldEmail = $user->email; // save old email as pref Preferences::setForUser($user, 'admin_previous_email_latest', $oldEmail); - Preferences::setForUser($user, 'admin_previous_email_'.Carbon::now()->format('Y-m-d-H-i-s'), $oldEmail); + Preferences::setForUser($user, 'admin_previous_email_' . Carbon::now()->format('Y-m-d-H-i-s'), $oldEmail); $user->email = $newEmail; $user->save(); @@ -390,7 +404,7 @@ class UserRepository implements UserRepositoryInterface $user->roles()->detach($roleObj->id); } - public function getRole(string $role): ?Role + public function getRole(string $role): null|Role { return Role::where('name', $role)->first(); } @@ -398,7 +412,10 @@ class UserRepository implements UserRepositoryInterface public function validateInviteCode(string $code): bool { $now = today(config('app.timezone')); - $invitee = InvitedUser::where('invite_code', $code)->where('expires', '>', $now->format('Y-m-d H:i:s'))->where('redeemed', 0)->first(); + $invitee = InvitedUser::where('invite_code', $code) + ->where('expires', '>', $now->format('Y-m-d H:i:s')) + ->where('redeemed', 0) + ->first(); return null !== $invitee; } diff --git a/app/Repositories/User/UserRepositoryInterface.php b/app/Repositories/User/UserRepositoryInterface.php index 392ee2f7dc..4bb898e8a0 100644 --- a/app/Repositories/User/UserRepositoryInterface.php +++ b/app/Repositories/User/UserRepositoryInterface.php @@ -82,20 +82,20 @@ interface UserRepositoryInterface public function destroy(User $user): bool; - public function find(int $userId): ?User; + public function find(int $userId): null|User; - public function findByEmail(string $email): ?User; + public function findByEmail(string $email): null|User; /** * Returns the first user in the DB. Generally only works when there is just one. */ - public function first(): ?User; + public function first(): null|User; public function getInvitedUsers(): Collection; - public function getRole(string $role): ?Role; + public function getRole(string $role): null|Role; - public function getRoleByUser(User $user): ?string; + public function getRoleByUser(User $user): null|string; public function getRolesInGroup(User $user, int $groupId): array; @@ -120,7 +120,7 @@ interface UserRepositoryInterface /** * Set MFA code. */ - public function setMFACode(User $user, ?string $code): void; + public function setMFACode(User $user, null|string $code): void; public function store(array $data): User; diff --git a/app/Repositories/UserGroup/UserGroupRepository.php b/app/Repositories/UserGroup/UserGroupRepository.php index 273b74eccf..3b52b001ee 100644 --- a/app/Repositories/UserGroup/UserGroupRepository.php +++ b/app/Repositories/UserGroup/UserGroupRepository.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Repositories\UserGroup; -use Illuminate\Support\Facades\Log; use FireflyIII\Enums\UserRoleEnum; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Factory\UserGroupFactory; @@ -36,6 +35,7 @@ use FireflyIII\Support\Repositories\UserGroup\UserGroupInterface; use FireflyIII\Support\Repositories\UserGroup\UserGroupTrait; use FireflyIII\User; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Log; use Override; use ValueError; @@ -54,7 +54,7 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte /** @var GroupMembership $membership */ foreach ($memberships as $membership) { /** @var null|User $user */ - $user = $membership->user()->first(); + $user = $membership->user()->first(); if (null === $user) { continue; } @@ -63,7 +63,7 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte $count = $user->groupMemberships()->where('user_group_id', '!=', $userGroup->id)->count(); if (0 === $count) { Log::debug('User has no other memberships and needs a new user group.'); - $newUserGroup = $this->createNewUserGroup($user); + $newUserGroup = $this->createNewUserGroup($user); $user->user_group_id = $newUserGroup->id; $user->save(); Log::debug(sprintf('Make new group #%d ("%s")', $newUserGroup->id, $newUserGroup->title)); @@ -73,7 +73,7 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte Log::debug('User has other memberships and will be assigned a new administration.'); /** @var GroupMembership $first */ - $first = $user->groupMemberships()->where('user_group_id', '!=', $userGroup->id)->inRandomOrder()->first(); + $first = $user->groupMemberships()->where('user_group_id', '!=', $userGroup->id)->inRandomOrder()->first(); $user->user_group_id = $first->id; $user->save(); } @@ -83,8 +83,22 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte // all users are now moved away from user group. // time to DESTROY all objects. // we have to do this one by one to trigger the necessary observers :( - $objects = ['availableBudgets', 'bills', 'budgets', 'categories', 'currencyExchangeRates', 'objectGroups', - 'recurrences', 'rules', 'ruleGroups', 'tags', 'transactionGroups', 'transactionJournals', 'piggyBanks', 'accounts', 'webhooks', + $objects = [ + 'availableBudgets', + 'bills', + 'budgets', + 'categories', + 'currencyExchangeRates', + 'objectGroups', + 'recurrences', + 'rules', + 'ruleGroups', + 'tags', + 'transactionGroups', + 'transactionJournals', + 'piggyBanks', + 'accounts', + 'webhooks' ]; foreach ($objects as $object) { foreach ($userGroup->{$object}()->get() as $item) { // @phpstan-ignore-line @@ -109,7 +123,7 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte /** @var null|UserGroup $group */ $group = $membership->userGroup()->first(); if (null !== $group) { - $groupId = $group->id; + $groupId = $group->id; if (in_array($groupId, array_keys($set), true)) { continue; } @@ -134,18 +148,18 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte while ($exists && $loop < 10) { $existingGroup = $this->findByName($groupName); if (!$existingGroup instanceof UserGroup) { - $exists = false; + $exists = false; - $existingGroup = $this->store(['user' => $user, 'title' => $groupName]); + $existingGroup = $this->store(['user' => $user, 'title' => $groupName]); } - $groupName = sprintf('%s-%s', $user->email, substr(sha1(random_int(1000, 9999).microtime()), 0, 4)); + $groupName = sprintf('%s-%s', $user->email, substr(sha1(random_int(1000, 9999) . microtime()), 0, 4)); ++$loop; } return $existingGroup; } - public function findByName(string $title): ?UserGroup + public function findByName(string $title): null|UserGroup { return UserGroup::whereTitle($title)->first(); } @@ -158,7 +172,7 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte $data['user'] = $this->user; /** @var UserGroupFactory $factory */ - $factory = app(UserGroupFactory::class); + $factory = app(UserGroupFactory::class); return $factory->create($data); } @@ -172,7 +186,7 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte } #[Override] - public function getById(int $id): ?UserGroup + public function getById(int $id): null|UserGroup { return UserGroup::find($id); } @@ -180,17 +194,20 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte #[Override] public function getMembershipsFromGroupId(int $groupId): Collection { - return $this->user->groupMemberships()->where('user_group_id', $groupId)->get(); + return $this->user + ->groupMemberships() + ->where('user_group_id', $groupId) + ->get(); } public function update(UserGroup $userGroup, array $data): UserGroup { $userGroup->title = $data['title']; $userGroup->save(); - $currency = null; + $currency = null; /** @var CurrencyRepositoryInterface $repository */ - $repository = app(CurrencyRepositoryInterface::class); + $repository = app(CurrencyRepositoryInterface::class); if (array_key_exists('primary_currency_code', $data)) { $repository->setUser($this->user); @@ -199,13 +216,12 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte if (array_key_exists('primary_currency_id', $data) && null === $currency) { $repository->setUser($this->user); - $currency = $repository->find((int)$data['primary_currency_id']); + $currency = $repository->find((int) $data['primary_currency_id']); } if (null !== $currency) { $repository->makePrimary($currency); } - return $userGroup; } @@ -216,17 +232,17 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte */ public function updateMembership(UserGroup $userGroup, array $data): UserGroup { - $owner = UserRole::whereTitle(UserRoleEnum::OWNER)->first(); + $owner = UserRole::whereTitle(UserRoleEnum::OWNER)->first(); Log::debug('in update membership'); /** @var null|User $user */ - $user = null; + $user = null; if (array_key_exists('id', $data)) { /** @var null|User $user */ $user = User::find($data['id']); Log::debug('Found user by ID'); } - if (array_key_exists('email', $data) && '' !== (string)$data['email']) { + if (array_key_exists('email', $data) && '' !== (string) $data['email']) { /** @var null|User $user */ $user = User::whereEmail($data['email'])->first(); Log::debug('Found user by email'); @@ -244,13 +260,13 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte if (1 === $membershipCount) { $lastUserId = $userGroup->groupMemberships()->distinct()->first(['group_memberships.user_id'])->user_id; // if this is also the user we're editing right now, and we remove all of their roles: - if ($lastUserId === (int)$user->id && 0 === count($data['roles'])) { + if ($lastUserId === (int) $user->id && 0 === count($data['roles'])) { Log::debug('User is last in this group, refuse to act'); throw new FireflyException('You cannot remove the last member from this user group. Delete the user group instead.'); } // if this is also the user we're editing right now, and do not grant them the owner role: - if ($lastUserId === (int)$user->id && count($data['roles']) > 0 && !in_array(UserRoleEnum::OWNER->value, $data['roles'], true)) { + if ($lastUserId === (int) $user->id && count($data['roles']) > 0 && !in_array(UserRoleEnum::OWNER->value, $data['roles'], true)) { Log::debug('User needs to have owner role in this group, refuse to act'); throw new FireflyException('The last member in this user group must get or keep the "owner" role.'); @@ -258,16 +274,16 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte } if ($membershipCount > 1) { // group has multiple members. How many are owner, except the user we're editing now? - $ownerCount = $userGroup->groupMemberships() - ->where('user_role_id', $owner->id) - ->where('user_id', '!=', $user->id)->count() - ; + $ownerCount = $userGroup->groupMemberships()->where('user_role_id', $owner->id)->where('user_id', '!=', $user->id)->count(); // if there are no other owners and the current users does not get or keep the owner role, refuse. if ( 0 === $ownerCount - && (0 === count($data['roles']) - || (count($data['roles']) > 0 // @phpstan-ignore-line - && !in_array(UserRoleEnum::OWNER->value, $data['roles'], true)))) { + && ( + 0 === count($data['roles']) + || count($data['roles']) > 0 // @phpstan-ignore-line + && !in_array(UserRoleEnum::OWNER->value, $data['roles'], true) + ) + ) { Log::debug('User needs to keep owner role in this group, refuse to act'); throw new FireflyException('The last owner in this user group must keep the "owner" role.'); @@ -286,7 +302,7 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte continue; } $userRole = UserRole::whereTitle($enum->value)->first(); - $user->groupMemberships()->create(['user_group_id' => $userGroup->id, 'user_role_id' => $userRole->id]); + $user->groupMemberships()->create(['user_group_id' => $userGroup->id, 'user_role_id' => $userRole->id]); } return $userGroup; diff --git a/app/Repositories/UserGroup/UserGroupRepositoryInterface.php b/app/Repositories/UserGroup/UserGroupRepositoryInterface.php index c1a6152ab0..ce28fc1f6e 100644 --- a/app/Repositories/UserGroup/UserGroupRepositoryInterface.php +++ b/app/Repositories/UserGroup/UserGroupRepositoryInterface.php @@ -48,7 +48,7 @@ interface UserGroupRepositoryInterface public function getAll(): Collection; - public function getById(int $id): ?UserGroup; + public function getById(int $id): null|UserGroup; public function getMembershipsFromGroupId(int $groupId): Collection; diff --git a/app/Repositories/Webhook/WebhookRepository.php b/app/Repositories/Webhook/WebhookRepository.php index 0e787a3a75..b2862876d0 100644 --- a/app/Repositories/Webhook/WebhookRepository.php +++ b/app/Repositories/Webhook/WebhookRepository.php @@ -45,13 +45,13 @@ class WebhookRepository implements WebhookRepositoryInterface, UserGroupInterfac public function all(): Collection { - return $this->user->webhooks() + return $this->user + ->webhooks() // only get upgraded webhooks ->where('delivery', 1) ->where('response', 1) ->where('trigger', 1) - ->get() - ; + ->get(); } public function destroy(Webhook $webhook): void @@ -79,29 +79,24 @@ class WebhookRepository implements WebhookRepositoryInterface, UserGroupInterfac public function getMessages(Webhook $webhook): Collection { - return $webhook->webhookMessages() - ->orderBy('created_at', 'DESC') - ->get(['webhook_messages.*']) - ; + return $webhook->webhookMessages()->orderBy('created_at', 'DESC')->get(['webhook_messages.*']); } public function getReadyMessages(Webhook $webhook): Collection { - return $webhook->webhookMessages() + return $webhook + ->webhookMessages() ->where('webhook_messages.sent', 0) ->where('webhook_messages.errored', 0) ->get(['webhook_messages.*']) - ->filter( - static fn (WebhookMessage $message): bool // @phpstan-ignore-line - => $message->webhookAttempts()->count() <= 2 - )->splice(0, 3) - ; + ->filter(static fn(WebhookMessage $message): bool => $message->webhookAttempts()->count() <= 2) // @phpstan-ignore-line + ->splice(0, 3); } public function store(array $data): Webhook { - $secret = Str::random(24); - $fullData = [ + $secret = Str::random(24); + $fullData = [ 'user_id' => $this->user->id, 'user_group_id' => $this->user->user_group_id, 'active' => $data['active'] ?? false, @@ -109,11 +104,11 @@ class WebhookRepository implements WebhookRepositoryInterface, UserGroupInterfac // 'trigger' => $data['trigger'], // 'response' => $data['response'], // 'delivery' => $data['delivery'], - 'trigger' => 1, - 'response' => 1, - 'delivery' => 1, - 'secret' => $secret, - 'url' => $data['url'], + 'trigger' => 1, + 'response' => 1, + 'delivery' => 1, + 'secret' => $secret, + 'url' => $data['url'] ]; /** @var Webhook $webhook */ @@ -158,19 +153,19 @@ class WebhookRepository implements WebhookRepositoryInterface, UserGroupInterfac public function update(Webhook $webhook, array $data): Webhook { $webhook->active = $data['active'] ?? $webhook->active; - $webhook->title = $data['title'] ?? $webhook->title; - $webhook->url = $data['url'] ?? $webhook->url; + $webhook->title = $data['title'] ?? $webhook->title; + $webhook->url = $data['url'] ?? $webhook->url; if (array_key_exists('secret', $data) && true === $data['secret']) { - $secret = Str::random(24); + $secret = Str::random(24); $webhook->secret = $secret; } $webhook->save(); - $triggers = new Collection(); - $responses = new Collection(); - $deliveries = new Collection(); + $triggers = new Collection(); + $responses = new Collection(); + $deliveries = new Collection(); foreach ($data['triggers'] as $trigger) { // get the relevant ID: diff --git a/app/Rules/Account/IsValidAccountType.php b/app/Rules/Account/IsValidAccountType.php index d2ac0603cf..e22d8a5951 100644 --- a/app/Rules/Account/IsValidAccountType.php +++ b/app/Rules/Account/IsValidAccountType.php @@ -38,7 +38,7 @@ class IsValidAccountType implements ValidationRule { // only check the type. if (array_key_exists('type', $value)) { - $value = $value['type']; + $value = $value['type']; if (!is_array($value)) { $value = [$value]; } diff --git a/app/Rules/Account/IsValidAccountTypeList.php b/app/Rules/Account/IsValidAccountTypeList.php index c1ee33da73..277afab291 100644 --- a/app/Rules/Account/IsValidAccountTypeList.php +++ b/app/Rules/Account/IsValidAccountTypeList.php @@ -36,7 +36,6 @@ class IsValidAccountTypeList implements ValidationRule #[Override] public function validate(string $attribute, mixed $value, Closure $fail): void { - // only check the type. $values = []; if (is_string($value)) { @@ -45,7 +44,7 @@ class IsValidAccountTypeList implements ValidationRule if (!is_array($values)) { $fail('validation.invalid_account_list')->translate(); } - $keys = array_keys($this->types); + $keys = array_keys($this->types); foreach ($values as $entry) { if (!in_array($entry, $keys, true)) { $fail('validation.invalid_account_list')->translate(['value' => $entry]); diff --git a/app/Rules/Admin/IsValidDiscordUrl.php b/app/Rules/Admin/IsValidDiscordUrl.php index a45bb12a4f..1947029b29 100644 --- a/app/Rules/Admin/IsValidDiscordUrl.php +++ b/app/Rules/Admin/IsValidDiscordUrl.php @@ -1,6 +1,5 @@ $this->validatePiggyBankId((int) $value), - 'piggy_bank_name' => $this->validatePiggyBankName($value), - 'bill_id' => $this->validateBillId((int) $value), - 'transaction_journal_id' => $this->validateJournalId((int) $value), - 'bill_name' => $this->validateBillName($value), - 'budget_id' => $this->validateBudgetId((int) $value), - 'category_id' => $this->validateCategoryId((int) $value), - 'budget_name' => $this->validateBudgetName($value), + $result = match ($attribute) { + 'piggy_bank_id' => $this->validatePiggyBankId((int) $value), + 'piggy_bank_name' => $this->validatePiggyBankName($value), + 'bill_id' => $this->validateBillId((int) $value), + 'transaction_journal_id' => $this->validateJournalId((int) $value), + 'bill_name' => $this->validateBillName($value), + 'budget_id' => $this->validateBudgetId((int) $value), + 'category_id' => $this->validateCategoryId((int) $value), + 'budget_name' => $this->validateBudgetName($value), 'source_id', 'destination_id' => $this->validateAccountId((int) $value), - default => throw new FireflyException(sprintf('Rule BelongsUser cannot handle "%s"', $attribute)), + default => throw new FireflyException(sprintf('Rule BelongsUser cannot handle "%s"', $attribute)) }; if (false === $result) { $fail('validation.belongs_user')->translate(); @@ -82,13 +82,11 @@ class BelongsUser implements ValidationRule private function validatePiggyBankId(int $value): bool { - - $count = PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id') ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id') ->where('piggy_banks.id', '=', $value) - ->where('accounts.user_id', '=', auth()->user()->id)->count() - ; + ->where('accounts.user_id', '=', auth()->user()->id) + ->count(); return $count > 0; } @@ -98,8 +96,8 @@ class BelongsUser implements ValidationRule $count = PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id') ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id') ->where('piggy_banks.name', '=', $value) - ->where('accounts.user_id', '=', auth()->user()->id)->count() - ; + ->where('accounts.user_id', '=', auth()->user()->id) + ->count(); return $count > 0; } @@ -138,14 +136,14 @@ class BelongsUser implements ValidationRule $objects = []; // get all objects belonging to user: if (PiggyBank::class === $class) { - $objects = PiggyBank::leftJoin('accounts', 'accounts.id', '=', 'piggy_banks.account_id') - ->where('accounts.user_id', '=', auth()->user()->id)->get(['piggy_banks.*']) - ; + $objects = PiggyBank::leftJoin('accounts', 'accounts.id', '=', 'piggy_banks.account_id')->where('accounts.user_id', '=', auth()->user()->id)->get([ + 'piggy_banks.*' + ]); } if (PiggyBank::class !== $class) { $objects = $class::where('user_id', '=', auth()->user()->id)->get(); } - $count = 0; + $count = 0; foreach ($objects as $object) { $objectValue = trim((string) $object->{$field}); // @phpstan-ignore-line Log::debug(sprintf('Comparing object "%s" with value "%s"', $objectValue, $value)); diff --git a/app/Rules/BelongsUserGroup.php b/app/Rules/BelongsUserGroup.php index 58d4fea871..c11615f187 100644 --- a/app/Rules/BelongsUserGroup.php +++ b/app/Rules/BelongsUserGroup.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Rules; -use Illuminate\Support\Facades\Log; use Closure; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Account; @@ -35,6 +34,7 @@ use FireflyIII\Models\PiggyBank; use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\UserGroup; use Illuminate\Contracts\Validation\ValidationRule; +use Illuminate\Support\Facades\Log; /** * Class BelongsUserGroup @@ -47,7 +47,9 @@ class BelongsUserGroup implements ValidationRule /** * Create a new rule instance. */ - public function __construct(private readonly UserGroup $userGroup) {} + public function __construct( + private readonly UserGroup $userGroup + ) {} public function validate(string $attribute, mixed $value, Closure $fail): void { @@ -59,17 +61,17 @@ class BelongsUserGroup implements ValidationRule } Log::debug(sprintf('Group: Going to validate "%s"', $attribute)); - $result = match ($attribute) { - 'piggy_bank_id' => $this->validatePiggyBankId((int) $value), - 'piggy_bank_name' => $this->validatePiggyBankName($value), - 'bill_id' => $this->validateBillId((int) $value), - 'transaction_journal_id' => $this->validateJournalId((int) $value), - 'bill_name' => $this->validateBillName($value), - 'budget_id' => $this->validateBudgetId((int) $value), - 'category_id' => $this->validateCategoryId((int) $value), - 'budget_name' => $this->validateBudgetName($value), + $result = match ($attribute) { + 'piggy_bank_id' => $this->validatePiggyBankId((int) $value), + 'piggy_bank_name' => $this->validatePiggyBankName($value), + 'bill_id' => $this->validateBillId((int) $value), + 'transaction_journal_id' => $this->validateJournalId((int) $value), + 'bill_name' => $this->validateBillName($value), + 'budget_id' => $this->validateBudgetId((int) $value), + 'category_id' => $this->validateCategoryId((int) $value), + 'budget_name' => $this->validateBudgetName($value), 'source_id', 'destination_id' => $this->validateAccountId((int) $value), - default => throw new FireflyException(sprintf('Rule BelongsUser cannot handle "%s"', $attribute)), + default => throw new FireflyException(sprintf('Rule BelongsUser cannot handle "%s"', $attribute)) }; if (false === $result) { $fail('validation.belongs_user_or_user_group')->translate(); @@ -93,8 +95,8 @@ class BelongsUserGroup implements ValidationRule { $count = PiggyBank::leftJoin('accounts', 'accounts.id', '=', 'piggy_banks.account_id') ->where('piggy_banks.id', '=', $value) - ->where('accounts.user_group_id', '=', $this->userGroup->id)->count() - ; + ->where('accounts.user_group_id', '=', $this->userGroup->id) + ->count(); return 1 === $count; } @@ -112,14 +114,16 @@ class BelongsUserGroup implements ValidationRule $objects = []; // get all objects belonging to user: if (PiggyBank::class === $class) { - $objects = PiggyBank::leftJoin('accounts', 'accounts.id', '=', 'piggy_banks.account_id') - ->where('accounts.user_group_id', '=', $this->userGroup->id)->get(['piggy_banks.*']) - ; + $objects = PiggyBank::leftJoin('accounts', 'accounts.id', '=', 'piggy_banks.account_id')->where( + 'accounts.user_group_id', + '=', + $this->userGroup->id + )->get(['piggy_banks.*']); } if (PiggyBank::class !== $class) { $objects = $class::where('user_group_id', '=', $this->userGroup->id)->get(); } - $count = 0; + $count = 0; foreach ($objects as $object) { $objectValue = trim((string) $object->{$field}); // @phpstan-ignore-line Log::debug(sprintf('Comparing object "%s" with value "%s"', $objectValue, $value)); diff --git a/app/Rules/IsAllowedGroupAction.php b/app/Rules/IsAllowedGroupAction.php index d9bbf8c3da..da6168b7cb 100644 --- a/app/Rules/IsAllowedGroupAction.php +++ b/app/Rules/IsAllowedGroupAction.php @@ -36,9 +36,12 @@ use Override; class IsAllowedGroupAction implements ValidationRule { // you need these roles to do anything with any endpoint. - private array $acceptedRoles = [UserRoleEnum::OWNER, UserRoleEnum::FULL]; + private array $acceptedRoles = [UserRoleEnum::OWNER, UserRoleEnum::FULL]; - public function __construct(private readonly string $className, private readonly string $methodName) {} + public function __construct( + private readonly string $className, + private readonly string $methodName + ) {} /** * @throws AuthorizationException diff --git a/app/Rules/IsAssetAccountId.php b/app/Rules/IsAssetAccountId.php index eadc485442..c9497554f9 100644 --- a/app/Rules/IsAssetAccountId.php +++ b/app/Rules/IsAssetAccountId.php @@ -41,7 +41,7 @@ class IsAssetAccountId implements ValidationRule $accountId = (int) $value; /** @var null|Account $account */ - $account = Account::with('accountType')->find($accountId); + $account = Account::with('accountType')->find($accountId); if (null === $account) { $fail('validation.no_asset_account')->translate(); diff --git a/app/Rules/IsDateOrTime.php b/app/Rules/IsDateOrTime.php index 309c894c32..6aa54ad1a0 100644 --- a/app/Rules/IsDateOrTime.php +++ b/app/Rules/IsDateOrTime.php @@ -24,12 +24,12 @@ declare(strict_types=1); namespace FireflyIII\Rules; -use Illuminate\Support\Facades\Log; use Carbon\Carbon; use Carbon\Exceptions\InvalidDateException; use Carbon\Exceptions\InvalidFormatException; use Closure; use Illuminate\Contracts\Validation\ValidationRule; +use Illuminate\Support\Facades\Log; /** * Class IsDateOrTime diff --git a/app/Rules/IsDefaultUserGroupName.php b/app/Rules/IsDefaultUserGroupName.php index 5ad43e323f..8bb4513fe7 100644 --- a/app/Rules/IsDefaultUserGroupName.php +++ b/app/Rules/IsDefaultUserGroupName.php @@ -24,19 +24,21 @@ declare(strict_types=1); namespace FireflyIII\Rules; -use Illuminate\Support\Facades\Log; use Closure; use FireflyIII\Models\UserGroup; use FireflyIII\Repositories\User\UserRepositoryInterface; use FireflyIII\User; use Illuminate\Contracts\Validation\ValidationRule; +use Illuminate\Support\Facades\Log; /** * Class IsDefaultUserGroupName */ class IsDefaultUserGroupName implements ValidationRule { - public function __construct(private readonly UserGroup $userGroup) {} + public function __construct( + private readonly UserGroup $userGroup + ) {} /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") @@ -47,12 +49,12 @@ class IsDefaultUserGroupName implements ValidationRule // are you owner of this group and the name is the same? fail. /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); /** @var UserRepositoryInterface $userRepos */ $userRepos = app(UserRepositoryInterface::class); - $roles = $userRepos->getRolesInGroup($user, $this->userGroup->id); + $roles = $userRepos->getRolesInGroup($user, $this->userGroup->id); if ($this->userGroup->title === $user->email && in_array('owner', $roles, true)) { $fail('validation.administration_owner_rename')->translate(); } diff --git a/app/Rules/IsFilterValueIn.php b/app/Rules/IsFilterValueIn.php index f7f41eb545..958f58d4df 100644 --- a/app/Rules/IsFilterValueIn.php +++ b/app/Rules/IsFilterValueIn.php @@ -29,7 +29,10 @@ use Illuminate\Contracts\Validation\ValidationRule; class IsFilterValueIn implements ValidationRule { - public function __construct(private readonly string $key, private readonly array $values) {} + public function __construct( + private readonly string $key, + private readonly array $values + ) {} /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") @@ -50,6 +53,7 @@ class IsFilterValueIn implements ValidationRule if (!in_array($value, $this->values, true)) { $fail('validation.filter_must_be_in')->translate(['filter' => $this->key, 'values' => implode(', ', $this->values)]); } + // $fail('validation.filter_not_string')->translate(['filter' => $this->key]); } } diff --git a/app/Rules/IsTransferAccount.php b/app/Rules/IsTransferAccount.php index 069f92715c..a7abb9dfe5 100644 --- a/app/Rules/IsTransferAccount.php +++ b/app/Rules/IsTransferAccount.php @@ -24,11 +24,11 @@ declare(strict_types=1); namespace FireflyIII\Rules; -use Illuminate\Support\Facades\Log; use Closure; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Validation\AccountValidator; use Illuminate\Contracts\Validation\ValidationRule; +use Illuminate\Support\Facades\Log; /** * Class IsTransferAccount @@ -43,7 +43,7 @@ class IsTransferAccount implements ValidationRule Log::debug(sprintf('Now in %s(%s)', __METHOD__, $value)); /** @var AccountValidator $validator */ - $validator = app(AccountValidator::class); + $validator = app(AccountValidator::class); $validator->setTransactionType(TransactionTypeEnum::TRANSFER->value); $validator->setUser(auth()->user()); diff --git a/app/Rules/IsValidActionExpression.php b/app/Rules/IsValidActionExpression.php index f6080a0903..772af79b46 100644 --- a/app/Rules/IsValidActionExpression.php +++ b/app/Rules/IsValidActionExpression.php @@ -45,14 +45,10 @@ class IsValidActionExpression implements ValidationRule return; } $value ??= ''; - $expr = new ActionExpression($value); + $expr = new ActionExpression($value); if (!$expr->isValid()) { - $fail('validation.rule_action_expression')->translate( - [ - 'error' => $expr->getValidationError()->getMessage(), - ] - ); + $fail('validation.rule_action_expression')->translate(['error' => $expr->getValidationError()->getMessage()]); } } } diff --git a/app/Rules/IsValidAmount.php b/app/Rules/IsValidAmount.php index 26b06c8ac0..2d2ec7b2a5 100644 --- a/app/Rules/IsValidAmount.php +++ b/app/Rules/IsValidAmount.php @@ -1,6 +1,5 @@ lessThanLots($value)) { - $amount = bcmul('-1', self::BIG_AMOUNT); + $amount = bcmul('-1', self::BIG_AMOUNT); $fail('validation.gte.numeric')->translate(['value' => $amount]); $message = sprintf('IsValidAmount: "%s" must be more than %s.', $value, $amount); Log::debug($message); diff --git a/app/Rules/IsValidAttachmentModel.php b/app/Rules/IsValidAttachmentModel.php index 69d09b708c..4d8e02ed16 100644 --- a/app/Rules/IsValidAttachmentModel.php +++ b/app/Rules/IsValidAttachmentModel.php @@ -55,7 +55,7 @@ class IsValidAttachmentModel implements ValidationRule */ public function __construct(string $model) { - $model = $this->normalizeModel($model); + $model = $this->normalizeModel($model); $this->model = $model; } @@ -79,15 +79,15 @@ class IsValidAttachmentModel implements ValidationRule return; } $result = match ($this->model) { - Account::class => $this->validateAccount((int) $value), - Bill::class => $this->validateBill((int) $value), - Budget::class => $this->validateBudget((int) $value), - Category::class => $this->validateCategory((int) $value), - PiggyBank::class => $this->validatePiggyBank((int) $value), - Tag::class => $this->validateTag((int) $value), - Transaction::class => $this->validateTransaction((int) $value), + Account::class => $this->validateAccount((int) $value), + Bill::class => $this->validateBill((int) $value), + Budget::class => $this->validateBudget((int) $value), + Category::class => $this->validateCategory((int) $value), + PiggyBank::class => $this->validatePiggyBank((int) $value), + Tag::class => $this->validateTag((int) $value), + Transaction::class => $this->validateTransaction((int) $value), TransactionJournal::class => $this->validateJournal((int) $value), - default => false, + default => false }; if (false === $result) { diff --git a/app/Rules/IsValidBulkClause.php b/app/Rules/IsValidBulkClause.php index df93b82a50..c43e178cec 100644 --- a/app/Rules/IsValidBulkClause.php +++ b/app/Rules/IsValidBulkClause.php @@ -37,7 +37,7 @@ use function Safe\json_decode; class IsValidBulkClause implements ValidationRule { private string $error; - private array $rules; + private array $rules; public function __construct(string $type) { @@ -92,9 +92,7 @@ class IsValidBulkClause implements ValidationRule return false; } // validate! - $validator = Validator::make(['value' => $arrayValue], [ - 'value' => $this->rules[$clause][$arrayKey], - ]); + $validator = Validator::make(['value' => $arrayValue], ['value' => $this->rules[$clause][$arrayKey]]); if ($validator->fails()) { $this->error = sprintf('%s: %s: %s', $clause, $arrayKey, implode(', ', $validator->errors()->get('value'))); // @phpstan-ignore-line diff --git a/app/Rules/IsValidDateRange.php b/app/Rules/IsValidDateRange.php index d396076dc4..ada4f2da62 100644 --- a/app/Rules/IsValidDateRange.php +++ b/app/Rules/IsValidDateRange.php @@ -24,12 +24,12 @@ declare(strict_types=1); namespace FireflyIII\Rules; -use Illuminate\Support\Facades\Log; use Carbon\Carbon; use Carbon\Exceptions\InvalidDateException; use Carbon\Exceptions\InvalidFormatException; use Closure; use Illuminate\Contracts\Validation\ValidationRule; +use Illuminate\Support\Facades\Log; class IsValidDateRange implements ValidationRule { @@ -38,13 +38,13 @@ class IsValidDateRange implements ValidationRule */ public function validate(string $attribute, mixed $value, Closure $fail): void { - $value = (string) $value; + $value = (string) $value; if ('' === $value) { $fail('validation.date_or_time')->translate(); return; } - $other = 'startPeriod'; + $other = 'startPeriod'; if ('startPeriod' === $attribute) { $other = 'endPeriod'; } diff --git a/app/Rules/IsValidPositiveAmount.php b/app/Rules/IsValidPositiveAmount.php index 157307a3f8..af3c77d8d7 100644 --- a/app/Rules/IsValidPositiveAmount.php +++ b/app/Rules/IsValidPositiveAmount.php @@ -1,6 +1,5 @@ class); + $shortClass = str_replace('FireflyIII\Models\\', '', $this->class); if (!is_string($value)) { $fail('validation.invalid_sort_instruction')->translate(['object' => $shortClass]); @@ -49,11 +52,11 @@ class IsValidSortInstruction implements ValidationRule return; } - $parts = explode(',', $value); + $parts = explode(',', $value); foreach ($parts as $i => $part) { $part = trim($part); if (strlen($part) < 2) { - $fail('validation.invalid_sort_instruction_index')->translate(['index' => $i, 'object' => $shortClass]); + $fail('validation.invalid_sort_instruction_index')->translate(['index' => $i, 'object' => $shortClass]); return; } @@ -61,7 +64,7 @@ class IsValidSortInstruction implements ValidationRule $part = substr($part, 1); } if (!in_array($part, $validParameters, true)) { - $fail('validation.invalid_sort_instruction_index')->translate(['index' => $i, 'object' => $shortClass]); + $fail('validation.invalid_sort_instruction_index')->translate(['index' => $i, 'object' => $shortClass]); return; } diff --git a/app/Rules/IsValidZeroOrMoreAmount.php b/app/Rules/IsValidZeroOrMoreAmount.php index eb10a43147..c373ff0382 100644 --- a/app/Rules/IsValidZeroOrMoreAmount.php +++ b/app/Rules/IsValidZeroOrMoreAmount.php @@ -1,6 +1,5 @@ translate(); } - $keys = array_keys($this->transactionTypes); + $keys = array_keys($this->transactionTypes); foreach ($values as $entry) { if (!in_array($entry, $keys, true)) { $fail('validation.invalid_transaction_type_list')->translate(); diff --git a/app/Rules/UniqueAccountNumber.php b/app/Rules/UniqueAccountNumber.php index 48d7310697..66efd637a1 100644 --- a/app/Rules/UniqueAccountNumber.php +++ b/app/Rules/UniqueAccountNumber.php @@ -24,12 +24,12 @@ declare(strict_types=1); namespace FireflyIII\Rules; -use Illuminate\Support\Facades\Log; use Closure; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Models\Account; use FireflyIII\Models\AccountMeta; use Illuminate\Contracts\Validation\ValidationRule; +use Illuminate\Support\Facades\Log; use function Safe\json_encode; @@ -41,11 +41,11 @@ class UniqueAccountNumber implements ValidationRule /** * Create a new rule instance. */ - public function __construct(private readonly ?Account $account, private ?string $expectedType) - { - app('log') - ->debug('Constructed UniqueAccountNumber') - ; + public function __construct( + private readonly null|Account $account, + private null|string $expectedType + ) { + app('log')->debug('Constructed UniqueAccountNumber'); // a very basic fix to make sure we get the correct account type: if ('expense' === $this->expectedType) { $this->expectedType = AccountTypeEnum::EXPENSE->value; @@ -90,15 +90,13 @@ class UniqueAccountNumber implements ValidationRule $count = $this->countHits($type, $value); Log::debug(sprintf('Count for "%s" and account number "%s" is %d', $type, $value, $count)); if ($count > $max) { - Log::debug( - sprintf( - 'account number "%s" is in use with %d account(s) of type "%s", which is too much for expected type "%s"', - $value, - $count, - $type, - $this->expectedType - ) - ); + Log::debug(sprintf( + 'account number "%s" is in use with %d account(s) of type "%s", which is too much for expected type "%s"', + $value, + $count, + $type, + $this->expectedType + )); $fail('validation.unique_account_number_for_user')->translate(); @@ -110,11 +108,7 @@ class UniqueAccountNumber implements ValidationRule private function getMaxOccurrences(): array { - $maxCounts = [ - AccountTypeEnum::ASSET->value => 0, - AccountTypeEnum::EXPENSE->value => 0, - AccountTypeEnum::REVENUE->value => 0, - ]; + $maxCounts = [AccountTypeEnum::ASSET->value => 0, AccountTypeEnum::EXPENSE->value => 0, AccountTypeEnum::REVENUE->value => 0]; if ('expense' === $this->expectedType || AccountTypeEnum::EXPENSE->value === $this->expectedType) { // IBAN should be unique amongst expense and asset accounts. @@ -137,8 +131,7 @@ class UniqueAccountNumber implements ValidationRule ->where('accounts.user_id', auth()->user()->id) ->where('account_types.type', $type) ->where('account_meta.name', '=', 'account_number') - ->where('account_meta.data', json_encode($accountNumber)) - ; + ->where('account_meta.data', json_encode($accountNumber)); if ($this->account instanceof Account) { $query->where('accounts.id', '!=', $this->account->id); diff --git a/app/Rules/UniqueIban.php b/app/Rules/UniqueIban.php index 761d8eb641..2ecb51648f 100644 --- a/app/Rules/UniqueIban.php +++ b/app/Rules/UniqueIban.php @@ -24,12 +24,12 @@ declare(strict_types=1); namespace FireflyIII\Rules; -use Illuminate\Support\Facades\Log; use Closure; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Models\Account; use FireflyIII\Support\Facades\Steam; use Illuminate\Contracts\Validation\ValidationRule; +use Illuminate\Support\Facades\Log; /** * Class UniqueIban @@ -41,8 +41,10 @@ class UniqueIban implements ValidationRule /** * Create a new rule instance. */ - public function __construct(private readonly ?Account $account, ?string $expectedType) - { + public function __construct( + private readonly null|Account $account, + null|string $expectedType + ) { if (null === $expectedType) { return; } @@ -106,15 +108,13 @@ class UniqueIban implements ValidationRule $count = $this->countHits($type, $value); Log::debug(sprintf('Count for "%s" and IBAN "%s" is %d', $type, $value, $count)); if ($count > $max) { - Log::debug( - sprintf( - 'IBAN "%s" is in use with %d account(s) of type "%s", which is too much for expected types "%s"', - $value, - $count, - $type, - implode(', ', $this->expectedTypes) - ) - ); + Log::debug(sprintf( + 'IBAN "%s" is in use with %d account(s) of type "%s", which is too much for expected types "%s"', + $value, + $count, + $type, + implode(', ', $this->expectedTypes) + )); return false; } @@ -129,7 +129,7 @@ class UniqueIban implements ValidationRule AccountTypeEnum::ASSET->value => 0, AccountTypeEnum::EXPENSE->value => 0, AccountTypeEnum::REVENUE->value => 0, - 'liabilities' => 0, + 'liabilities' => 0 ]; if (in_array('expense', $this->expectedTypes, true) || in_array(AccountTypeEnum::EXPENSE->value, $this->expectedTypes, true)) { @@ -152,13 +152,12 @@ class UniqueIban implements ValidationRule if ('liabilities' === $type) { $typesArray = [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value]; } - $query - = auth()->user() - ->accounts() - ->leftJoin('account_types', 'account_types.id', '=', 'accounts.account_type_id') - ->where('accounts.iban', $iban) - ->whereIn('account_types.type', $typesArray) - ; + $query = auth() + ->user() + ->accounts() + ->leftJoin('account_types', 'account_types.id', '=', 'accounts.account_type_id') + ->where('accounts.iban', $iban) + ->whereIn('account_types.type', $typesArray); if ($this->account instanceof Account) { $query->where('accounts.id', '!=', $this->account->id); diff --git a/app/Rules/ValidJournals.php b/app/Rules/ValidJournals.php index 463a3fe7f6..f7f462360b 100644 --- a/app/Rules/ValidJournals.php +++ b/app/Rules/ValidJournals.php @@ -24,10 +24,10 @@ declare(strict_types=1); namespace FireflyIII\Rules; -use Illuminate\Support\Facades\Log; use Closure; use FireflyIII\Models\TransactionJournal; use Illuminate\Contracts\Validation\ValidationRule; +use Illuminate\Support\Facades\Log; /** * Class ValidJournals diff --git a/app/Rules/ValidRecurrenceRepetitionValue.php b/app/Rules/ValidRecurrenceRepetitionValue.php index ec770c6b9d..07c504c3b0 100644 --- a/app/Rules/ValidRecurrenceRepetitionValue.php +++ b/app/Rules/ValidRecurrenceRepetitionValue.php @@ -24,10 +24,10 @@ declare(strict_types=1); namespace FireflyIII\Rules; -use Illuminate\Support\Facades\Log; use Carbon\Carbon; use Closure; use Illuminate\Contracts\Validation\ValidationRule; +use Illuminate\Support\Facades\Log; use InvalidArgumentException; /** @@ -82,8 +82,8 @@ class ValidRecurrenceRepetitionValue implements ValidationRule if (2 !== count($parameters)) { return false; } - $nthDay = (int) $parameters[0]; - $dayOfWeek = (int) $parameters[1]; + $nthDay = (int) $parameters[0]; + $dayOfWeek = (int) $parameters[1]; if ($nthDay < 1 || $nthDay > 5) { return false; } diff --git a/app/Services/FireflyIIIOrg/Update/UpdateRequest.php b/app/Services/FireflyIIIOrg/Update/UpdateRequest.php index 24a9f55ba6..ab3f7da296 100644 --- a/app/Services/FireflyIIIOrg/Update/UpdateRequest.php +++ b/app/Services/FireflyIIIOrg/Update/UpdateRequest.php @@ -44,13 +44,10 @@ class UpdateRequest implements UpdateRequestInterface public function getUpdateInformation(string $channel): array { Log::debug(sprintf('Now in getUpdateInformation(%s)', $channel)); - $information = [ - 'level' => 'error', - 'message' => (string) trans('firefly.unknown_error'), - ]; + $information = ['level' => 'error', 'message' => (string) trans('firefly.unknown_error')]; // try to get array from update server: - $updateInfo = $this->contactServer($channel); + $updateInfo = $this->contactServer($channel); if ('error' === $updateInfo['level']) { Log::error('Update information contains an error.'); Log::error($updateInfo['message']); @@ -67,24 +64,19 @@ class UpdateRequest implements UpdateRequestInterface { Log::debug(sprintf('Now in contactServer(%s)', $channel)); // always fall back to current version: - $return = [ + $return = [ 'version' => config('firefly.version'), 'date' => today(config('app.timezone'))->startOfDay(), 'level' => 'error', - 'message' => (string) trans('firefly.unknown_error'), + 'message' => (string) trans('firefly.unknown_error') ]; - $url = config('firefly.update_endpoint'); + $url = config('firefly.update_endpoint'); Log::debug(sprintf('Going to call %s', $url)); try { $client = new Client(); - $options = [ - 'headers' => [ - 'User-Agent' => sprintf('FireflyIII/%s/%s', config('firefly.version'), $channel), - ], - 'timeout' => 3.1415, - ]; + $options = ['headers' => ['User-Agent' => sprintf('FireflyIII/%s/%s', config('firefly.version'), $channel)], 'timeout' => 3.1415]; $res = $client->request('GET', $url, $options); } catch (GuzzleException $e) { Log::error('Ran into Guzzle error.'); @@ -102,7 +94,7 @@ class UpdateRequest implements UpdateRequestInterface return $return; } - $body = (string) $res->getBody(); + $body = (string) $res->getBody(); try { $json = json_decode($body, true, 512, JSON_THROW_ON_ERROR); @@ -121,14 +113,14 @@ class UpdateRequest implements UpdateRequestInterface } // parse response a bit. No message yet. - $response = $json['firefly_iii'][$channel]; - $date = Carbon::createFromFormat('Y-m-d', $response['date']); + $response = $json['firefly_iii'][$channel]; + $date = Carbon::createFromFormat('Y-m-d', $response['date']); if (!$date instanceof Carbon) { $date = today(config('app.timezone')); } $return['version'] = $response['version']; - $return['level'] = 'success'; - $return['date'] = $date->startOfDay(); + $return['level'] = 'success'; + $return['date'] = $date->startOfDay(); Log::info('Response from update server', $response); @@ -141,8 +133,8 @@ class UpdateRequest implements UpdateRequestInterface private function parseResult(array $information): array { Log::debug('Now in parseResult()', $information); - $current = (string) config('firefly.version'); - $latest = (string) $information['version']; + $current = (string) config('firefly.version'); + $latest = (string) $information['version']; // strip the 'v' from the version if it's there. if (str_starts_with($latest, 'v')) { @@ -152,7 +144,7 @@ class UpdateRequest implements UpdateRequestInterface return $this->parseResultDevelop($current, $latest); } - $compare = version_compare($latest, $current); + $compare = version_compare($latest, $current); Log::debug(sprintf('Current version is "%s", latest is "%s", result is: %d', $current, $latest, $compare)); @@ -186,17 +178,17 @@ class UpdateRequest implements UpdateRequestInterface private function parseResultDevelop(string $current, string $latest): array { Log::debug(sprintf('User is running develop version "%s"', $current)); - $compare = $this->compareDevelopVersions($current, $latest); - $return = []; + $compare = $this->compareDevelopVersions($current, $latest); + $return = []; if (-1 === $compare) { - $return['level'] = 'info'; - $return['message'] = (string) trans('firefly.update_current_dev_older', ['version' => $current, 'new_version' => $latest]); + $return['level'] = 'info'; + $return['message'] = (string) trans('firefly.update_current_dev_older', ['version' => $current, 'new_version' => $latest]); return $return; } - $return['level'] = 'info'; - $return['message'] = (string) trans('firefly.update_current_dev_newer', ['version' => $current, 'new_version' => $latest]); + $return['level'] = 'info'; + $return['message'] = (string) trans('firefly.update_current_dev_newer', ['version' => $current, 'new_version' => $latest]); return $return; } @@ -205,7 +197,7 @@ class UpdateRequest implements UpdateRequestInterface { $return = [ 'level' => 'info', - 'message' => (string) trans('firefly.update_newer_version_alert', ['your_version' => $current, 'new_version' => $latest]), + 'message' => (string) trans('firefly.update_newer_version_alert', ['your_version' => $current, 'new_version' => $latest]) ]; Log::debug('User is running a newer version', $return); @@ -214,10 +206,7 @@ class UpdateRequest implements UpdateRequestInterface private function runsSameVersion(string $current): array { - $return = [ - 'level' => 'info', - 'message' => (string) trans('firefly.update_current_version_alert', ['version' => $current]), - ]; + $return = ['level' => 'info', 'message' => (string) trans('firefly.update_current_version_alert', ['version' => $current])]; Log::debug('User is the current version.', $return); return $return; @@ -226,56 +215,38 @@ class UpdateRequest implements UpdateRequestInterface private function releasedNewAlpha(string $current, string $latest, Carbon $date): array { Log::debug('New release is also a alpha!'); - $message = (string) trans( - 'firefly.update_new_version_alert', - [ - 'your_version' => $current, - 'new_version' => $latest, - 'date' => $date->isoFormat((string) trans('config.month_and_day_js')), - ] - ); + $message = (string) trans('firefly.update_new_version_alert', [ + 'your_version' => $current, + 'new_version' => $latest, + 'date' => $date->isoFormat((string) trans('config.month_and_day_js')) + ]); - return [ - 'level' => 'success', - 'message' => sprintf('%s %s', $message, trans('firefly.update_version_alpha')), - ]; + return ['level' => 'success', 'message' => sprintf('%s %s', $message, trans('firefly.update_version_alpha'))]; } private function releasedNewBeta(string $current, string $latest, Carbon $date): array { Log::debug('New release is also a beta!'); - $message = (string) trans( - 'firefly.update_new_version_alert', - [ - 'your_version' => $current, - 'new_version' => $latest, - 'date' => $date->isoFormat((string) trans('config.month_and_day_js')), - ] - ); + $message = (string) trans('firefly.update_new_version_alert', [ + 'your_version' => $current, + 'new_version' => $latest, + 'date' => $date->isoFormat((string) trans('config.month_and_day_js')) + ]); - return [ - 'level' => 'success', - 'message' => sprintf('%s %s', $message, trans('firefly.update_version_beta')), - ]; + return ['level' => 'success', 'message' => sprintf('%s %s', $message, trans('firefly.update_version_beta'))]; } private function releasedNewVersion(string $current, string $latest, Carbon $date): array { Log::debug('New release is old enough.'); - $message = (string) trans( - 'firefly.update_new_version_alert', - [ - 'your_version' => $current, - 'new_version' => $latest, - 'date' => $date->isoFormat((string) trans('config.month_and_day_js')), - ] - ); + $message = (string) trans('firefly.update_new_version_alert', [ + 'your_version' => $current, + 'new_version' => $latest, + 'date' => $date->isoFormat((string) trans('config.month_and_day_js')) + ]); Log::debug('New release is here!', [$message]); event(new SystemFoundNewVersionOnline($message)); - return [ - 'level' => 'success', - 'message' => $message, - ]; + return ['level' => 'success', 'message' => $message]; } } diff --git a/app/Services/Internal/Destroy/AccountDestroyService.php b/app/Services/Internal/Destroy/AccountDestroyService.php index 5e6ec04144..9fa2d41032 100644 --- a/app/Services/Internal/Destroy/AccountDestroyService.php +++ b/app/Services/Internal/Destroy/AccountDestroyService.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Services\Internal\Destroy; -use Illuminate\Support\Facades\Log; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Models\Account; use FireflyIII\Models\PiggyBank; @@ -33,6 +32,7 @@ use FireflyIII\Models\Transaction; use FireflyIII\Models\TransactionJournal; use Illuminate\Database\Eloquent\Builder; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Log; use stdClass; /** @@ -40,7 +40,7 @@ use stdClass; */ class AccountDestroyService { - public function destroy(Account $account, ?Account $moveTo): void + public function destroy(Account $account, null|Account $moveTo): void { // find and delete opening balance journal + opposing account $this->destroyOpeningBalance($account); @@ -67,21 +67,18 @@ class AccountDestroyService private function destroyOpeningBalance(Account $account): void { Log::debug(sprintf('Searching for opening balance for account #%d "%s"', $account->id, $account->name)); - $set = $account->transactions() + $set = $account + ->transactions() ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id') ->where('transaction_types.type', TransactionTypeEnum::OPENING_BALANCE->value) - ->get(['transactions.transaction_journal_id']) - ; + ->get(['transactions.transaction_journal_id']); if ($set->count() > 0) { - $journalId = $set->first()->transaction_journal_id; + $journalId = $set->first()->transaction_journal_id; Log::debug(sprintf('Found opening balance journal with ID #%d', $journalId)); // get transactions with this journal (should be just one): - $transactions = Transaction::where('transaction_journal_id', $journalId) - ->where('account_id', '!=', $account->id) - ->get() - ; + $transactions = Transaction::where('transaction_journal_id', $journalId)->where('account_id', '!=', $account->id)->get(); /** @var Transaction $transaction */ foreach ($transactions as $transaction) { @@ -95,7 +92,7 @@ class AccountDestroyService } /** @var null|TransactionJournal $journal */ - $journal = TransactionJournal::find($journalId); + $journal = TransactionJournal::find($journalId); if (null !== $journal) { /** @var JournalDestroyService $service */ $service = app(JournalDestroyService::class); @@ -109,14 +106,18 @@ class AccountDestroyService Log::debug(sprintf('Move from account #%d to #%d', $account->id, $moveTo->id)); DB::table('transactions')->where('account_id', $account->id)->update(['account_id' => $moveTo->id]); - $collection = Transaction::groupBy('transaction_journal_id', 'account_id')->where('account_id', $moveTo->id)->get(['transaction_journal_id', 'account_id', DB::raw('count(*) as the_count')]); + $collection = Transaction::groupBy('transaction_journal_id', 'account_id')->where('account_id', $moveTo->id)->get([ + 'transaction_journal_id', + 'account_id', + DB::raw('count(*) as the_count') + ]); if (0 === $collection->count()) { return; } /** @var JournalDestroyService $service */ - $service = app(JournalDestroyService::class); - $user = $account->user; + $service = app(JournalDestroyService::class); + $user = $account->user; /** @var stdClass $row */ foreach ($collection as $row) { @@ -139,12 +140,10 @@ class AccountDestroyService private function destroyRecurrences(Account $account): void { - $recurrences = RecurrenceTransaction::where( - static function (Builder $q) use ($account): void { - $q->where('source_id', $account->id); - $q->orWhere('destination_id', $account->id); - } - )->get(['recurrence_id'])->pluck('recurrence_id')->toArray(); + $recurrences = RecurrenceTransaction::where(static function (Builder $q) use ($account): void { + $q->where('source_id', $account->id); + $q->orWhere('destination_id', $account->id); + })->get(['recurrence_id'])->pluck('recurrence_id')->toArray(); /** @var RecurrenceDestroyService $destroyService */ $destroyService = app(RecurrenceDestroyService::class); diff --git a/app/Services/Internal/Destroy/CategoryDestroyService.php b/app/Services/Internal/Destroy/CategoryDestroyService.php index 04b6fb3873..55e3d97292 100644 --- a/app/Services/Internal/Destroy/CategoryDestroyService.php +++ b/app/Services/Internal/Destroy/CategoryDestroyService.php @@ -43,6 +43,9 @@ class CategoryDestroyService DB::table('category_transaction')->where('category_id', $category->id)->delete(); // delete references to category from recurring transactions. - DB::table('rt_meta')->where('name', 'category_id')->where('value', $category->id)->delete(); + DB::table('rt_meta') + ->where('name', 'category_id') + ->where('value', $category->id) + ->delete(); } } diff --git a/app/Services/Internal/Destroy/JournalDestroyService.php b/app/Services/Internal/Destroy/JournalDestroyService.php index 8f4263f47d..0313be5aff 100644 --- a/app/Services/Internal/Destroy/JournalDestroyService.php +++ b/app/Services/Internal/Destroy/JournalDestroyService.php @@ -24,8 +24,8 @@ declare(strict_types=1); namespace FireflyIII\Services\Internal\Destroy; -use Illuminate\Support\Facades\Log; use FireflyIII\Models\TransactionJournal; +use Illuminate\Support\Facades\Log; /** * Class JournalDestroyService diff --git a/app/Services/Internal/Destroy/TransactionGroupDestroyService.php b/app/Services/Internal/Destroy/TransactionGroupDestroyService.php index 159fca52e1..a0928237da 100644 --- a/app/Services/Internal/Destroy/TransactionGroupDestroyService.php +++ b/app/Services/Internal/Destroy/TransactionGroupDestroyService.php @@ -24,9 +24,9 @@ declare(strict_types=1); namespace FireflyIII\Services\Internal\Destroy; -use Illuminate\Support\Facades\Log; use FireflyIII\Events\DestroyedTransactionGroup; use FireflyIII\Models\TransactionGroup; +use Illuminate\Support\Facades\Log; /** * Class TransactionGroupDestroyService diff --git a/app/Services/Internal/Support/AccountServiceTrait.php b/app/Services/Internal/Support/AccountServiceTrait.php index ec75b0de50..6bdaecadd8 100644 --- a/app/Services/Internal/Support/AccountServiceTrait.php +++ b/app/Services/Internal/Support/AccountServiceTrait.php @@ -24,8 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Services\Internal\Support; -use FireflyIII\Support\Facades\Preferences; -use Illuminate\Support\Facades\Log; use Carbon\Carbon; use Deprecated; use FireflyIII\Enums\AccountTypeEnum; @@ -42,9 +40,11 @@ use FireflyIII\Models\TransactionGroup; use FireflyIII\Models\TransactionJournal; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Services\Internal\Destroy\TransactionGroupDestroyService; -use Illuminate\Support\Facades\Validator; -use FireflyIII\Support\Facades\Steam; use FireflyIII\Support\Facades\Amount; +use FireflyIII\Support\Facades\Preferences; +use FireflyIII\Support\Facades\Steam; +use Illuminate\Support\Facades\Log; +use Illuminate\Support\Facades\Validator; /** * Trait AccountServiceTrait @@ -53,13 +53,13 @@ trait AccountServiceTrait { protected AccountRepositoryInterface $accountRepository; - public function filterIban(?string $iban): ?string + public function filterIban(null|string $iban): null|string { if (null === $iban) { return null; } - $data = ['iban' => $iban]; - $rules = ['iban' => 'required|iban']; + $data = ['iban' => $iban]; + $rules = ['iban' => 'required|iban']; $validator = Validator::make($data, $rules); if ($validator->fails()) { Log::info(sprintf('Detected invalid IBAN ("%s"). Return NULL instead.', $iban)); @@ -75,16 +75,18 @@ trait AccountServiceTrait */ public function isEmptyOBData(array $data): bool { - if (!array_key_exists('opening_balance', $data) - && !array_key_exists('opening_balance_date', $data) - ) { + if (!array_key_exists('opening_balance', $data) && !array_key_exists('opening_balance_date', $data)) { // not set, so false. return false; } // if is set, but is empty: - return (array_key_exists('opening_balance', $data) && '' === $data['opening_balance']) - || (array_key_exists('opening_balance_date', $data) && '' === $data['opening_balance_date']); + return ( + array_key_exists('opening_balance', $data) + && '' === $data['opening_balance'] + || array_key_exists('opening_balance_date', $data) + && '' === $data['opening_balance_date'] + ); } /** @@ -96,14 +98,14 @@ trait AccountServiceTrait */ public function updateMetaData(Account $account, array $data): void { - $fields = $this->validFields; + $fields = $this->validFields; if (AccountTypeEnum::ASSET->value === $account->accountType->type) { $fields = $this->validAssetFields; } // remove currency_id if necessary. - $type = $account->accountType->type; - $list = config('firefly.valid_currency_account_types'); + $type = $account->accountType->type; + $list = config('firefly.valid_currency_account_types'); if (!in_array($type, $list, true)) { $pos = array_search('currency_id', $fields, true); if (false !== $pos) { @@ -152,7 +154,7 @@ trait AccountServiceTrait public function updateNote(Account $account, string $note): bool { - $dbNote = $account->notes()->first(); + $dbNote = $account->notes()->first(); if ('' === $note) { $dbNote?->delete(); @@ -177,8 +179,12 @@ trait AccountServiceTrait if ('' !== $data['opening_balance'] && 0 === bccomp($data['opening_balance'], '0')) { $data['opening_balance'] = ''; } - if ('' !== $data['opening_balance'] && array_key_exists('opening_balance_date', $data) && '' !== $data['opening_balance_date'] - && $data['opening_balance_date'] instanceof Carbon) { + if ( + '' !== $data['opening_balance'] + && array_key_exists('opening_balance_date', $data) + && '' !== $data['opening_balance_date'] + && $data['opening_balance_date'] instanceof Carbon + ) { Log::debug('Array has valid opening balance data.'); return true; @@ -196,7 +202,7 @@ trait AccountServiceTrait protected function createOBGroup(Account $account, array $data): TransactionGroup { Log::debug('Now going to create an OB group.'); - $language = Preferences::getForUser($account->user, 'language', 'en_US')->data; + $language = Preferences::getForUser($account->user, 'language', 'en_US')->data; if (is_array($language)) { $language = 'en_US'; } @@ -227,10 +233,10 @@ trait AccountServiceTrait } // make amount positive, regardless: - $amount = Steam::positive($amount); + $amount = Steam::positive($amount); // get or grab currency: - $currency = $this->accountRepository->getAccountCurrency($account); + $currency = $this->accountRepository->getAccountCurrency($account); if (null === $currency) { $currency = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup); } @@ -240,37 +246,35 @@ trait AccountServiceTrait 'group_title' => null, 'user' => $account->user, 'user_group' => $account->user->userGroup, - 'transactions' => [ - [ - 'type' => 'Opening balance', - 'date' => $data['opening_balance_date'], - 'source_id' => $sourceId, - 'source_name' => $sourceName, - 'destination_id' => $destId, - 'destination_name' => $destName, - 'user' => $account->user, - 'user_group' => $account->user->userGroup, - 'currency_id' => $currency->id, - 'order' => 0, - 'amount' => $amount, - 'foreign_amount' => null, - 'description' => trans('firefly.initial_balance_description', ['account' => $account->name]), - 'budget_id' => null, - 'budget_name' => null, - 'category_id' => null, - 'category_name' => null, - 'piggy_bank_id' => null, - 'piggy_bank_name' => null, - 'reconciled' => false, - 'notes' => null, - 'tags' => [], - ], - ], + 'transactions' => [[ + 'type' => 'Opening balance', + 'date' => $data['opening_balance_date'], + 'source_id' => $sourceId, + 'source_name' => $sourceName, + 'destination_id' => $destId, + 'destination_name' => $destName, + 'user' => $account->user, + 'user_group' => $account->user->userGroup, + 'currency_id' => $currency->id, + 'order' => 0, + 'amount' => $amount, + 'foreign_amount' => null, + 'description' => trans('firefly.initial_balance_description', ['account' => $account->name]), + 'budget_id' => null, + 'budget_name' => null, + 'category_id' => null, + 'category_name' => null, + 'piggy_bank_id' => null, + 'piggy_bank_name' => null, + 'reconciled' => false, + 'notes' => null, + 'tags' => [] + ]] ]; Log::debug('Going for submission in createOBGroup', $submission); /** @var TransactionGroupFactory $factory */ - $factory = app(TransactionGroupFactory::class); + $factory = app(TransactionGroupFactory::class); $factory->setUser($account->user); try { @@ -305,7 +309,7 @@ trait AccountServiceTrait /** * Returns the credit transaction group, or NULL if it does not exist. */ - protected function getCreditTransaction(Account $account): ?TransactionGroup + protected function getCreditTransaction(Account $account): null|TransactionGroup { Log::debug(sprintf('Now at %s', __METHOD__)); @@ -333,7 +337,7 @@ trait AccountServiceTrait /** * Returns the opening balance group, or NULL if it does not exist. */ - protected function getOBGroup(Account $account): ?TransactionGroup + protected function getOBGroup(Account $account): null|TransactionGroup { return $this->accountRepository->getOpeningBalanceGroup($account); } @@ -342,10 +346,10 @@ trait AccountServiceTrait { // find currency, or use default currency instead. /** @var TransactionCurrencyFactory $factory */ - $factory = app(TransactionCurrencyFactory::class); + $factory = app(TransactionCurrencyFactory::class); /** @var null|TransactionCurrency $currency */ - $currency = $factory->find($currencyId, $currencyCode); + $currency = $factory->find($currencyId, $currencyCode); if (null === $currency) { // use default currency: @@ -373,7 +377,7 @@ trait AccountServiceTrait } // if direction is "debit" (I owe this debt), amount is negative. // which means the liability will have a negative balance which the user must fill. - $openingBalance = Steam::negative($openingBalance); + $openingBalance = Steam::negative($openingBalance); // if direction is "credit" (I am owed this debt), amount is positive. // which means the liability will have a positive balance which is drained when its paid back into any asset. @@ -382,30 +386,30 @@ trait AccountServiceTrait } // create if not exists: - $clGroup = $this->getCreditTransaction($account); + $clGroup = $this->getCreditTransaction($account); if (null === $clGroup) { return $this->createCreditTransaction($account, $openingBalance, $openingBalanceDate); } // if exists, update: - $currency = $this->accountRepository->getAccountCurrency($account); + $currency = $this->accountRepository->getAccountCurrency($account); if (null === $currency) { $currency = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup); } // simply grab the first journal and change it: - $journal = $this->getObJournal($clGroup); - $clTransaction = $this->getOBTransaction($journal, $account); - $accountTransaction = $this->getNotOBTransaction($journal, $account); - $journal->date = $openingBalanceDate; + $journal = $this->getObJournal($clGroup); + $clTransaction = $this->getOBTransaction($journal, $account); + $accountTransaction = $this->getNotOBTransaction($journal, $account); + $journal->date = $openingBalanceDate; $journal->transactionCurrency()->associate($currency); // account always gains money: - $accountTransaction->amount = Steam::positive($openingBalance); + $accountTransaction->amount = Steam::positive($openingBalance); $accountTransaction->transaction_currency_id = $currency->id; // CL account always loses money: - $clTransaction->amount = Steam::negative($openingBalance); - $clTransaction->transaction_currency_id = $currency->id; + $clTransaction->amount = Steam::negative($openingBalance); + $clTransaction->transaction_currency_id = $currency->id; // save both $accountTransaction->save(); $clTransaction->save(); @@ -428,11 +432,11 @@ trait AccountServiceTrait throw new FireflyException('Amount for new liability credit was unexpectedly 0.'); } - $language = Preferences::getForUser($account->user, 'language', 'en_US')->data; + $language = Preferences::getForUser($account->user, 'language', 'en_US')->data; if (is_array($language)) { $language = 'en_US'; } - $language = (string) $language; + $language = (string) $language; // set source and/or destination based on whether the amount is positive or negative. // first, assume the amount is positive and go from there: @@ -446,14 +450,14 @@ trait AccountServiceTrait $sourceId = $account->id; $sourceName = null; $destId = null; - $destName = trans('firefly.liability_credit_description', ['account' => $account->name], $language); + $destName = trans('firefly.liability_credit_description', ['account' => $account->name], $language); } // amount must be positive for the transaction to work. - $amount = Steam::positive($openingBalance); + $amount = Steam::positive($openingBalance); // get or grab currency: - $currency = $this->accountRepository->getAccountCurrency($account); + $currency = $this->accountRepository->getAccountCurrency($account); if (null === $currency) { $currency = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup); } @@ -462,37 +466,35 @@ trait AccountServiceTrait 'group_title' => null, 'user' => $account->user, 'user_group' => $account->user->userGroup, - 'transactions' => [ - [ - 'type' => 'Liability credit', - 'date' => $openingBalanceDate, - 'source_id' => $sourceId, - 'source_name' => $sourceName, - 'destination_id' => $destId, - 'destination_name' => $destName, - 'user' => $account->user, - 'user_group' => $account->user->userGroup, - 'currency_id' => $currency->id, - 'order' => 0, - 'amount' => $amount, - 'foreign_amount' => null, - 'description' => trans('firefly.liability_credit_description', ['account' => $account->name]), - 'budget_id' => null, - 'budget_name' => null, - 'category_id' => null, - 'category_name' => null, - 'piggy_bank_id' => null, - 'piggy_bank_name' => null, - 'reconciled' => false, - 'notes' => null, - 'tags' => [], - ], - ], + 'transactions' => [[ + 'type' => 'Liability credit', + 'date' => $openingBalanceDate, + 'source_id' => $sourceId, + 'source_name' => $sourceName, + 'destination_id' => $destId, + 'destination_name' => $destName, + 'user' => $account->user, + 'user_group' => $account->user->userGroup, + 'currency_id' => $currency->id, + 'order' => 0, + 'amount' => $amount, + 'foreign_amount' => null, + 'description' => trans('firefly.liability_credit_description', ['account' => $account->name]), + 'budget_id' => null, + 'budget_name' => null, + 'category_id' => null, + 'category_name' => null, + 'piggy_bank_id' => null, + 'piggy_bank_name' => null, + 'reconciled' => false, + 'notes' => null, + 'tags' => [] + ]] ]; Log::debug('Going for submission in createCreditTransaction', $submission); /** @var TransactionGroupFactory $factory */ - $factory = app(TransactionGroupFactory::class); + $factory = app(TransactionGroupFactory::class); $factory->setUser($account->user); try { @@ -563,14 +565,14 @@ trait AccountServiceTrait { Log::debug(sprintf('Now in %s', __METHOD__)); // create if not exists: - $obGroup = $this->getOBGroup($account); + $obGroup = $this->getOBGroup($account); if (null === $obGroup) { return $this->createOBGroupV2($account, $openingBalance, $openingBalanceDate); } Log::debug('Update OB group'); // if exists, update: - $currency = $this->accountRepository->getAccountCurrency($account); + $currency = $this->accountRepository->getAccountCurrency($account); if (null === $currency) { $currency = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup); } @@ -579,29 +581,29 @@ trait AccountServiceTrait $journal = $this->getObJournal($obGroup); $obTransaction = $this->getOBTransaction($journal, $account); $accountTransaction = $this->getNotOBTransaction($journal, $account); - $journal->date = $openingBalanceDate; + $journal->date = $openingBalanceDate; $journal->transactionCurrency()->associate($currency); // if amount is negative: if (1 === bccomp('0', $openingBalance)) { Log::debug('Amount is negative.'); // account transaction loses money: - $accountTransaction->amount = Steam::negative($openingBalance); + $accountTransaction->amount = Steam::negative($openingBalance); $accountTransaction->transaction_currency_id = $currency->id; // OB account transaction gains money - $obTransaction->amount = Steam::positive($openingBalance); - $obTransaction->transaction_currency_id = $currency->id; + $obTransaction->amount = Steam::positive($openingBalance); + $obTransaction->transaction_currency_id = $currency->id; } if (-1 === bccomp('0', $openingBalance)) { Log::debug('Amount is positive.'); // account gains money: - $accountTransaction->amount = Steam::positive($openingBalance); + $accountTransaction->amount = Steam::positive($openingBalance); $accountTransaction->transaction_currency_id = $currency->id; // OB account loses money: - $obTransaction->amount = Steam::negative($openingBalance); - $obTransaction->transaction_currency_id = $currency->id; + $obTransaction->amount = Steam::negative($openingBalance); + $obTransaction->transaction_currency_id = $currency->id; } // save both $accountTransaction->save(); @@ -618,7 +620,7 @@ trait AccountServiceTrait protected function createOBGroupV2(Account $account, string $openingBalance, Carbon $openingBalanceDate): TransactionGroup { Log::debug('Now going to create an OB group.'); - $language = Preferences::getForUser($account->user, 'language', 'en_US')->data; + $language = Preferences::getForUser($account->user, 'language', 'en_US')->data; if (is_array($language)) { $language = 'en_US'; } @@ -648,10 +650,10 @@ trait AccountServiceTrait } // make amount positive, regardless: - $amount = Steam::positive($openingBalance); + $amount = Steam::positive($openingBalance); // get or grab currency: - $currency = $this->accountRepository->getAccountCurrency($account); + $currency = $this->accountRepository->getAccountCurrency($account); if (null === $currency) { $currency = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup); } @@ -661,37 +663,35 @@ trait AccountServiceTrait 'group_title' => null, 'user' => $account->user, 'user_group' => $account->user->userGroup, - 'transactions' => [ - [ - 'type' => 'Opening balance', - 'date' => $openingBalanceDate, - 'source_id' => $sourceId, - 'source_name' => $sourceName, - 'destination_id' => $destId, - 'destination_name' => $destName, - 'user' => $account->user, - 'user_group' => $account->user->userGroup, - 'currency_id' => $currency->id, - 'order' => 0, - 'amount' => $amount, - 'foreign_amount' => null, - 'description' => trans('firefly.initial_balance_description', ['account' => $account->name]), - 'budget_id' => null, - 'budget_name' => null, - 'category_id' => null, - 'category_name' => null, - 'piggy_bank_id' => null, - 'piggy_bank_name' => null, - 'reconciled' => false, - 'notes' => null, - 'tags' => [], - ], - ], + 'transactions' => [[ + 'type' => 'Opening balance', + 'date' => $openingBalanceDate, + 'source_id' => $sourceId, + 'source_name' => $sourceName, + 'destination_id' => $destId, + 'destination_name' => $destName, + 'user' => $account->user, + 'user_group' => $account->user->userGroup, + 'currency_id' => $currency->id, + 'order' => 0, + 'amount' => $amount, + 'foreign_amount' => null, + 'description' => trans('firefly.initial_balance_description', ['account' => $account->name]), + 'budget_id' => null, + 'budget_name' => null, + 'category_id' => null, + 'category_name' => null, + 'piggy_bank_id' => null, + 'piggy_bank_name' => null, + 'reconciled' => false, + 'notes' => null, + 'tags' => [] + ]] ]; Log::debug('Going for submission in createOBGroupV2', $submission); /** @var TransactionGroupFactory $factory */ - $factory = app(TransactionGroupFactory::class); + $factory = app(TransactionGroupFactory::class); $factory->setUser($account->user); try { diff --git a/app/Services/Internal/Support/BillServiceTrait.php b/app/Services/Internal/Support/BillServiceTrait.php index 79fa463b86..16c7389096 100644 --- a/app/Services/Internal/Support/BillServiceTrait.php +++ b/app/Services/Internal/Support/BillServiceTrait.php @@ -24,10 +24,10 @@ declare(strict_types=1); namespace FireflyIII\Services\Internal\Support; -use Illuminate\Support\Facades\Log; use FireflyIII\Models\Bill; use FireflyIII\Models\Note; use FireflyIII\Models\RuleAction; +use Illuminate\Support\Facades\Log; /** * Trait BillServiceTrait @@ -42,8 +42,8 @@ trait BillServiceTrait $ruleIds = $bill->user->rules()->get(['id'])->pluck('id')->toArray(); $set = RuleAction::whereIn('rule_id', $ruleIds) ->where('action_type', 'link_to_bill') - ->where('action_value', $oldName)->get() - ; + ->where('action_value', $oldName) + ->get(); /** @var RuleAction $ruleAction */ foreach ($set as $ruleAction) { @@ -61,7 +61,7 @@ trait BillServiceTrait return true; } - $dbNote = $bill->notes()->first(); + $dbNote = $bill->notes()->first(); if (null === $dbNote) { $dbNote = new Note(); $dbNote->noteable()->associate($bill); diff --git a/app/Services/Internal/Support/CreditRecalculateService.php b/app/Services/Internal/Support/CreditRecalculateService.php index feb0f9f0dc..2ec39113b4 100644 --- a/app/Services/Internal/Support/CreditRecalculateService.php +++ b/app/Services/Internal/Support/CreditRecalculateService.php @@ -33,18 +33,18 @@ use FireflyIII\Models\TransactionCurrency; use FireflyIII\Models\TransactionGroup; use FireflyIII\Models\TransactionJournal; use FireflyIII\Repositories\Account\AccountRepositoryInterface; -use Illuminate\Support\Facades\Log; use FireflyIII\Support\Facades\Steam; +use Illuminate\Support\Facades\Log; /** * Class CreditRecalculateService */ class CreditRecalculateService { - private ?Account $account = null; - private ?TransactionGroup $group = null; + private null|Account $account = null; + private null|TransactionGroup $group = null; private AccountRepositoryInterface $repository; - private array $work = []; + private array $work = []; public function recalculate(): void { @@ -86,7 +86,7 @@ class CreditRecalculateService $destination = $this->getDestinationAccount($journal); // destination or source must be liability. - $valid = config('firefly.valid_liabilities'); + $valid = config('firefly.valid_liabilities'); if (in_array($destination->accountType->type, $valid, true)) { $this->work[] = $destination; } @@ -109,7 +109,7 @@ class CreditRecalculateService private function getAccountByDirection(TransactionJournal $journal, string $direction): Account { /** @var null|Transaction $transaction */ - $transaction = $journal->transactions()->where('amount', $direction, '0')->first(); + $transaction = $journal->transactions()->where('amount', $direction, '0')->first(); if (null === $transaction) { throw new FireflyException(sprintf('Cannot find "%s"-transaction of journal #%d', $direction, $journal->id)); } @@ -159,12 +159,12 @@ class CreditRecalculateService if ($openingBalance instanceof TransactionJournal && 'debit' === $direction) { $this->validateOpeningBalance($account, $openingBalance); } - $startOfDebt = $this->repository->getOpeningBalanceAmount($account, false) ?? '0'; - $leftOfDebt = Steam::positive($startOfDebt); + $startOfDebt = $this->repository->getOpeningBalanceAmount($account, false) ?? '0'; + $leftOfDebt = Steam::positive($startOfDebt); // Log::debug(sprintf('Start of debt is "%s", so initial left of debt is "%s"', \FireflyIII\Support\Facades\Steam::bcround($startOfDebt, 2), \FireflyIII\Support\Facades\Steam::bcround($leftOfDebt, 2))); /** @var AccountMetaFactory $factory */ - $factory = app(AccountMetaFactory::class); + $factory = app(AccountMetaFactory::class); // amount is positive or negative, doesn't matter. $factory->crud($account, 'start_of_debt', $startOfDebt); @@ -172,11 +172,11 @@ class CreditRecalculateService // Log::debug(sprintf('Debt direction is "%s"', $direction)); // now loop all transactions (except opening balance and credit thing) - $transactions = $account->transactions() + $transactions = $account + ->transactions() ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->orderBy('transaction_journals.date', 'ASC') - ->get(['transactions.*']) - ; + ->get(['transactions.*']); $transactions->count(); // Log::debug(sprintf('Found %d transaction(s) to process.', $total)); @@ -198,13 +198,13 @@ class CreditRecalculateService $source = $openingBalance->transactions()->where('amount', '<', 0)->first(); /** @var Transaction $dest */ - $dest = $openingBalance->transactions()->where('amount', '>', 0)->first(); + $dest = $openingBalance->transactions()->where('amount', '>', 0)->first(); if ($source->account_id !== $account->id) { Log::info(sprintf('Liability #%d has a reversed opening balance. Will fix this now.', $account->id)); Log::debug(sprintf('Source amount "%s" is now "%s"', $source->amount, Steam::positive($source->amount))); Log::debug(sprintf('Destination amount "%s" is now "%s"', $dest->amount, Steam::negative($dest->amount))); $source->amount = Steam::positive($source->amount); - $dest->amount = Steam::negative($source->amount); + $dest->amount = Steam::negative($source->amount); if (null !== $source->foreign_amount && '' !== $source->foreign_amount) { $source->foreign_amount = Steam::positive($source->foreign_amount); Log::debug(sprintf('Source foreign amount "%s" is now "%s"', $source->foreign_amount, Steam::positive($source->foreign_amount))); @@ -215,8 +215,8 @@ class CreditRecalculateService } $source->save(); $dest->save(); - } + // Log::debug('Opening balance is valid'); } @@ -229,7 +229,7 @@ class CreditRecalculateService */ private function processTransaction(Account $account, string $direction, Transaction $transaction, string $leftOfDebt): string { - $journal = $transaction->transactionJournal; + $journal = $transaction->transactionJournal; // here be null pointers. if (null === $journal) { @@ -238,7 +238,6 @@ class CreditRecalculateService return $leftOfDebt; } - $foreignCurrency = $transaction->foreignCurrency; $accountCurrency = $this->repository->getAccountCurrency($account); $type = $journal->transactionType->type; @@ -257,15 +256,16 @@ class CreditRecalculateService // Log::debug(sprintf('Liability direction is "%s"', $direction)); // amount to use depends on the currency: - $usedAmount = $this->getAmountToUse($transaction, $accountCurrency, $foreignCurrency); - $isSameAccount = $account->id === $transaction->account_id; - $isDebit = 'debit' === $direction; - $isCredit = 'credit' === $direction; + $usedAmount = $this->getAmountToUse($transaction, $accountCurrency, $foreignCurrency); + $isSameAccount = $account->id === $transaction->account_id; + $isDebit = 'debit' === $direction; + $isCredit = 'credit' === $direction; if ($isSameAccount && $isCredit && $this->isWithdrawalIn($usedAmount, $type)) { // case 1 $usedAmount = Steam::positive($usedAmount); return bcadd($leftOfDebt, (string) $usedAmount); + // Log::debug(sprintf('Case 1 (withdrawal into credit liability): %s + %s = %s', \FireflyIII\Support\Facades\Steam::bcround($leftOfDebt, 2), \FireflyIII\Support\Facades\Steam::bcround($usedAmount, 2), \FireflyIII\Support\Facades\Steam::bcround($result, 2))); } @@ -273,6 +273,7 @@ class CreditRecalculateService $usedAmount = Steam::positive($usedAmount); return bcsub($leftOfDebt, (string) $usedAmount); + // Log::debug(sprintf('Case 2 (withdrawal away from liability): %s - %s = %s', \FireflyIII\Support\Facades\Steam::bcround($leftOfDebt, 2), \FireflyIII\Support\Facades\Steam::bcround($usedAmount, 2), \FireflyIII\Support\Facades\Steam::bcround($result, 2))); } @@ -280,6 +281,7 @@ class CreditRecalculateService $usedAmount = Steam::positive($usedAmount); return bcsub($leftOfDebt, (string) $usedAmount); + // Log::debug(sprintf('Case 3 (deposit away from liability): %s - %s = %s', \FireflyIII\Support\Facades\Steam::bcround($leftOfDebt, 2), \FireflyIII\Support\Facades\Steam::bcround($usedAmount, 2), \FireflyIII\Support\Facades\Steam::bcround($result, 2))); } @@ -287,30 +289,35 @@ class CreditRecalculateService $usedAmount = Steam::positive($usedAmount); return bcadd($leftOfDebt, (string) $usedAmount); + // Log::debug(sprintf('Case 4 (deposit into credit liability): %s + %s = %s', \FireflyIII\Support\Facades\Steam::bcround($leftOfDebt, 2), \FireflyIII\Support\Facades\Steam::bcround($usedAmount, 2), \FireflyIII\Support\Facades\Steam::bcround($result, 2))); } if ($isSameAccount && $isCredit && $this->isTransferIn($usedAmount, $type)) { // case 5 $usedAmount = Steam::positive($usedAmount); return bcadd($leftOfDebt, (string) $usedAmount); + // Log::debug(sprintf('Case 5 (transfer into credit liability): %s + %s = %s', \FireflyIII\Support\Facades\Steam::bcround($leftOfDebt, 2), \FireflyIII\Support\Facades\Steam::bcround($usedAmount, 2), \FireflyIII\Support\Facades\Steam::bcround($result, 2))); } if ($isSameAccount && $isDebit && $this->isWithdrawalIn($usedAmount, $type)) { // case 6 $usedAmount = Steam::positive($usedAmount); return bcsub($leftOfDebt, (string) $usedAmount); + // Log::debug(sprintf('Case 6 (withdrawal into debit liability): %s - %s = %s', \FireflyIII\Support\Facades\Steam::bcround($leftOfDebt, 2), \FireflyIII\Support\Facades\Steam::bcround($usedAmount, 2), \FireflyIII\Support\Facades\Steam::bcround($result, 2))); } if ($isSameAccount && $isDebit && $this->isDepositOut($usedAmount, $type)) { // case 7 $usedAmount = Steam::positive($usedAmount); return bcadd($leftOfDebt, (string) $usedAmount); + // Log::debug(sprintf('Case 7 (deposit away from liability): %s + %s = %s', \FireflyIII\Support\Facades\Steam::bcround($leftOfDebt, 2), \FireflyIII\Support\Facades\Steam::bcround($usedAmount, 2), \FireflyIII\Support\Facades\Steam::bcround($result, 2))); } if ($isSameAccount && $isDebit && $this->isWithdrawalOut($usedAmount, $type)) { // case 8 $usedAmount = Steam::positive($usedAmount); return bcadd($leftOfDebt, (string) $usedAmount); + // Log::debug(sprintf('Case 8 (withdrawal away from liability): %s + %s = %s', \FireflyIII\Support\Facades\Steam::bcround($leftOfDebt, 2), \FireflyIII\Support\Facades\Steam::bcround($usedAmount, 2), \FireflyIII\Support\Facades\Steam::bcround($result, 2))); } @@ -318,6 +325,7 @@ class CreditRecalculateService $usedAmount = Steam::positive($usedAmount); return bcsub($leftOfDebt, (string) $usedAmount); + // 2024-10-05, #9225 this used to say you would owe more, but a transfer INTO a debit from wherever means you owe LESS. // Log::debug(sprintf('Case 9 (transfer into debit liability, means you owe LESS): %s - %s = %s', \FireflyIII\Support\Facades\Steam::bcround($leftOfDebt, 2), \FireflyIII\Support\Facades\Steam::bcround($usedAmount, 2), \FireflyIII\Support\Facades\Steam::bcround($result, 2))); } @@ -325,6 +333,7 @@ class CreditRecalculateService $usedAmount = Steam::positive($usedAmount); return bcadd($leftOfDebt, (string) $usedAmount); + // 2024-10-05, #9225 this used to say you would owe less, but a transfer OUT OF a debit from wherever means you owe MORE. // Log::debug(sprintf('Case 10 (transfer out of debit liability, means you owe MORE): %s + %s = %s', \FireflyIII\Support\Facades\Steam::bcround($leftOfDebt, 2), \FireflyIII\Support\Facades\Steam::bcround($usedAmount, 2), \FireflyIII\Support\Facades\Steam::bcround($result, 2))); } @@ -334,6 +343,7 @@ class CreditRecalculateService $usedAmount = Steam::negative($usedAmount); return bcadd($leftOfDebt, (string) $usedAmount); + // Log::debug(sprintf('Case X (all other cases): %s + %s = %s', \FireflyIII\Support\Facades\Steam::bcround($leftOfDebt, 2), \FireflyIII\Support\Facades\Steam::bcround($usedAmount, 2), \FireflyIII\Support\Facades\Steam::bcround($result, 2))); } @@ -342,12 +352,13 @@ class CreditRecalculateService return $leftOfDebt; } - private function getAmountToUse(Transaction $transaction, TransactionCurrency $accountCurrency, ?TransactionCurrency $foreignCurrency): string + private function getAmountToUse(Transaction $transaction, TransactionCurrency $accountCurrency, null|TransactionCurrency $foreignCurrency): string { $usedAmount = $transaction->amount; // Log::debug(sprintf('Amount of transaction is %s', \FireflyIII\Support\Facades\Steam::bcround($usedAmount, 2))); if ($foreignCurrency instanceof TransactionCurrency && $foreignCurrency->id === $accountCurrency->id) { $usedAmount = $transaction->foreign_amount; + // Log::debug(sprintf('Overruled by foreign amount. Amount of transaction is now %s', \FireflyIII\Support\Facades\Steam::bcround($usedAmount, 2))); } @@ -439,7 +450,7 @@ class CreditRecalculateService return TransactionTypeEnum::TRANSFER->value === $transactionType && -1 === bccomp($amount, '0'); } - public function setAccount(?Account $account): void + public function setAccount(null|Account $account): void { $this->account = $account; } diff --git a/app/Services/Internal/Support/JournalServiceTrait.php b/app/Services/Internal/Support/JournalServiceTrait.php index 94f6c46e33..5039387026 100644 --- a/app/Services/Internal/Support/JournalServiceTrait.php +++ b/app/Services/Internal/Support/JournalServiceTrait.php @@ -47,15 +47,15 @@ use function Safe\json_encode; */ trait JournalServiceTrait { - private AccountRepositoryInterface $accountRepository; - private BudgetRepositoryInterface $budgetRepository; + private AccountRepositoryInterface $accountRepository; + private BudgetRepositoryInterface $budgetRepository; private CategoryRepositoryInterface $categoryRepository; - private TagFactory $tagFactory; + private TagFactory $tagFactory; /** * @throws FireflyException */ - protected function getAccount(string $transactionType, string $direction, array $data, ?Account $opposite = null): ?Account + protected function getAccount(string $transactionType, string $direction, array $data, null|Account $opposite = null): null|Account { // some debug logging: Log::debug(sprintf('Now in getAccount(%s)', $direction), $data); @@ -67,23 +67,23 @@ trait JournalServiceTrait unset($array); // and now try to find it, based on the type of transaction. - $message = 'Transaction = %s, %s account should be in: %s. Direction is %s.'; + $message = 'Transaction = %s, %s account should be in: %s. Direction is %s.'; Log::debug(sprintf($message, $transactionType, $direction, implode(', ', $expectedTypes[$transactionType] ?? ['UNKNOWN']), $direction)); - $result = $this->findAccountById($data, $expectedTypes[$transactionType], $opposite); - $result = $this->findAccountByIban($result, $data, $expectedTypes[$transactionType], $opposite); - $ibanResult = $result; - $result = $this->findAccountByNumber($result, $data, $expectedTypes[$transactionType], $opposite); - $numberResult = $result; - $result = $this->findAccountByName($result, $data, $expectedTypes[$transactionType], $opposite); - $nameResult = $result; + $result = $this->findAccountById($data, $expectedTypes[$transactionType], $opposite); + $result = $this->findAccountByIban($result, $data, $expectedTypes[$transactionType], $opposite); + $ibanResult = $result; + $result = $this->findAccountByNumber($result, $data, $expectedTypes[$transactionType], $opposite); + $numberResult = $result; + $result = $this->findAccountByName($result, $data, $expectedTypes[$transactionType], $opposite); + $nameResult = $result; // if $result (find by name) is NULL, but IBAN is set, any result of the search by NAME can't overrule // this account. In such a case, the name search must be retried with a new name. if (null !== $nameResult && null === $numberResult && null === $ibanResult && '' !== (string) $data['iban'] && '' !== (string) $nameResult->iban) { $data['name'] = sprintf('%s (%s)', $data['name'], $data['iban']); Log::debug(sprintf('Search again using the new name, "%s".', $data['name'])); - $result = $this->findAccountByName(null, $data, $expectedTypes[$transactionType], $opposite); + $result = $this->findAccountByName(null, $data, $expectedTypes[$transactionType], $opposite); } // the account that Firefly III creates must be "creatable", aka select the one we can create from the list just in case @@ -96,12 +96,7 @@ trait JournalServiceTrait Log::debug(sprintf('Account #%d may exist and be of the wrong type, use data to create one of the right type.', $data['id'])); $temp = $this->findAccountById(['id' => $data['id']], []); if (null !== $temp) { - $tempData = [ - 'name' => $temp->name, - 'iban' => $temp->iban, - 'number' => null, - 'bic' => null, - ]; + $tempData = ['name' => $temp->name, 'iban' => $temp->iban, 'number' => null, 'bic' => null]; $result = $this->createAccount(null, $tempData, $creatableType); } } @@ -117,7 +112,7 @@ trait JournalServiceTrait return $result; } - private function findAccountById(array $data, array $types, ?Account $opposite = null): ?Account + private function findAccountById(array $data, array $types, null|Account $opposite = null): null|Account { // first attempt, find by ID. if (null !== $data['id']) { @@ -134,9 +129,7 @@ trait JournalServiceTrait return $search; } if (null !== $search && 0 === count($types)) { - Log::debug( - sprintf('Found "account_id" object: #%d, "%s" of type %s (2)', $search->id, $search->name, $search->accountType->type) - ); + Log::debug(sprintf('Found "account_id" object: #%d, "%s" of type %s (2)', $search->id, $search->name, $search->accountType->type)); return $search; } @@ -146,7 +139,7 @@ trait JournalServiceTrait return null; } - private function findAccountByIban(?Account $account, array $data, array $types, ?Account $opposite = null): ?Account + private function findAccountByIban(null|Account $account, array $data, array $types, null|Account $opposite = null): null|Account { if ($account instanceof Account) { Log::debug(sprintf('Already have account #%d ("%s"), return that.', $account->id, $account->name)); @@ -179,7 +172,7 @@ trait JournalServiceTrait return null; } - private function findAccountByNumber(?Account $account, array $data, array $types, ?Account $opposite = null): ?Account + private function findAccountByNumber(null|Account $account, array $data, array $types, null|Account $opposite = null): null|Account { if ($account instanceof Account) { Log::debug(sprintf('Already have account #%d ("%s"), return that.', $account->id, $account->name)); @@ -214,7 +207,7 @@ trait JournalServiceTrait return null; } - private function findAccountByName(?Account $account, array $data, array $types, ?Account $opposite = null): ?Account + private function findAccountByName(null|Account $account, array $data, array $types, null|Account $opposite = null): null|Account { if ($account instanceof Account) { Log::debug(sprintf('Already have account #%d ("%s"), return that.', $account->id, $account->name)); @@ -251,7 +244,7 @@ trait JournalServiceTrait return null; } - private function getCreatableType(array $types): ?string + private function getCreatableType(array $types): null|string { $result = null; $list = config('firefly.dynamic_creation_allowed'); @@ -272,19 +265,12 @@ trait JournalServiceTrait * @throws FireflyException * @throws JsonException */ - private function createAccount(?Account $account, array $data, string $preferredType): ?Account + private function createAccount(null|Account $account, array $data, string $preferredType): null|Account { Log::debug('Now in createAccount()', $data); // return new account. if ($account instanceof Account) { - Log::debug( - sprintf( - 'Was given %s account #%d ("%s") so will simply return that.', - $account->accountType->type, - $account->id, - $account->name - ) - ); + Log::debug(sprintf('Was given %s account #%d ("%s") so will simply return that.', $account->accountType->type, $account->id, $account->name)); } if (!$account instanceof Account) { // final attempt, create it. @@ -314,43 +300,39 @@ trait JournalServiceTrait $data['iban'] = null; } - // $data['name'] = $data['name'] ?? '(no name)'; - $account = $this->accountRepository->store( - [ - 'account_type_id' => null, - 'account_type_name' => $preferredType, - 'name' => $data['name'], - 'virtual_balance' => null, - 'active' => true, - 'iban' => $data['iban'], - 'currency_id' => $data['currency_id'] ?? null, - 'order' => $this->accountRepository->maxOrder($preferredType), - ] - ); + $account = $this->accountRepository->store([ + 'account_type_id' => null, + 'account_type_name' => $preferredType, + 'name' => $data['name'], + 'virtual_balance' => null, + 'active' => true, + 'iban' => $data['iban'], + 'currency_id' => $data['currency_id'] ?? null, + 'order' => $this->accountRepository->maxOrder($preferredType) + ]); // store BIC if (null !== $data['bic']) { /** @var AccountMetaFactory $metaFactory */ $metaFactory = app(AccountMetaFactory::class); - $metaFactory->create(['account_id' => $account->id, 'name' => 'BIC', 'data' => $data['bic']]); + $metaFactory->create(['account_id' => $account->id, 'name' => 'BIC', 'data' => $data['bic']]); } // store account number if (null !== $data['number']) { /** @var AccountMetaFactory $metaFactory */ $metaFactory = app(AccountMetaFactory::class); - $metaFactory->create(['account_id' => $account->id, 'name' => 'account_number', 'data' => $data['number']]); + $metaFactory->create(['account_id' => $account->id, 'name' => 'account_number', 'data' => $data['number']]); } } return $account; } - private function getCashAccount(?Account $account, array $data, array $types): ?Account + private function getCashAccount(null|Account $account, array $data, array $types): null|Account { // return cash account. - if (!$account instanceof Account && '' === (string) $data['name'] - && in_array(AccountTypeEnum::CASH->value, $types, true)) { + if (!$account instanceof Account && '' === (string) $data['name'] && in_array(AccountTypeEnum::CASH->value, $types, true)) { $account = $this->accountRepository->getCashAccount(); } Log::debug('Cannot return cash account, return input instead.'); @@ -374,7 +356,7 @@ trait JournalServiceTrait return $amount; } - protected function getForeignAmount(?string $amount): ?string + protected function getForeignAmount(null|string $amount): null|string { if (null === $amount) { Log::debug('No foreign amount info in array. Return NULL'); @@ -427,7 +409,7 @@ trait JournalServiceTrait $journal->categories()->sync([]); } - protected function storeNotes(TransactionJournal $journal, ?string $notes): void + protected function storeNotes(TransactionJournal $journal, null|string $notes): void { $notes = (string) $notes; $note = $journal->notes()->first(); @@ -449,7 +431,7 @@ trait JournalServiceTrait /** * Link tags to journal. */ - protected function storeTags(TransactionJournal $journal, ?array $tags): void + protected function storeTags(TransactionJournal $journal, null|array $tags): void { Log::debug('Now in storeTags()', $tags ?? []); $this->tagFactory->setUser($journal->user); diff --git a/app/Services/Internal/Support/LocationServiceTrait.php b/app/Services/Internal/Support/LocationServiceTrait.php index 38b63f963d..06338d9662 100644 --- a/app/Services/Internal/Support/LocationServiceTrait.php +++ b/app/Services/Internal/Support/LocationServiceTrait.php @@ -32,13 +32,13 @@ use Illuminate\Database\Eloquent\Model; */ trait LocationServiceTrait { - protected function storeNewLocation(Model $model, array $data): ?Location + protected function storeNewLocation(Model $model, array $data): null|Location { $data['store_location'] ??= false; if ($data['store_location']) { - $location = new Location(); - $location->latitude = $data['latitude'] ?? config('firefly.default_location.latitude'); - $location->longitude = $data['longitude'] ?? config('firefly.default_location.longitude'); + $location = new Location(); + $location->latitude = $data['latitude'] ?? config('firefly.default_location.latitude'); + $location->longitude = $data['longitude'] ?? config('firefly.default_location.longitude'); $location->zoom_level = $data['zoom_level'] ?? config('firefly.default_location.zoom_level'); $location->locatable()->associate($model); $location->save(); diff --git a/app/Services/Internal/Support/RecurringTransactionTrait.php b/app/Services/Internal/Support/RecurringTransactionTrait.php index bba3f5019b..c6c2b87dd8 100644 --- a/app/Services/Internal/Support/RecurringTransactionTrait.php +++ b/app/Services/Internal/Support/RecurringTransactionTrait.php @@ -40,9 +40,9 @@ use FireflyIII\Models\RecurrenceRepetition; use FireflyIII\Models\RecurrenceTransaction; use FireflyIII\Models\RecurrenceTransactionMeta; use FireflyIII\Repositories\Account\AccountRepositoryInterface; +use FireflyIII\Support\Facades\Amount; use FireflyIII\Validation\AccountValidator; use Illuminate\Support\Facades\Log; -use FireflyIII\Support\Facades\Amount; use function Safe\json_encode; @@ -59,7 +59,7 @@ trait RecurringTransactionTrait return true; } - $dbNote = $recurrence->notes()->first(); + $dbNote = $recurrence->notes()->first(); if (null === $dbNote) { $dbNote = new Note(); $dbNote->noteable()->associate($recurrence); @@ -74,15 +74,13 @@ trait RecurringTransactionTrait { /** @var array $array */ foreach ($repetitions as $array) { - RecurrenceRepetition::create( - [ - 'recurrence_id' => $recurrence->id, - 'repetition_type' => $array['type'], - 'repetition_moment' => $array['moment'] ?? '', - 'repetition_skip' => $array['skip'] ?? 0, - 'weekend' => $array['weekend'] ?? 1, - ] - ); + RecurrenceRepetition::create([ + 'recurrence_id' => $recurrence->id, + 'repetition_type' => $array['type'], + 'repetition_moment' => $array['moment'] ?? '', + 'repetition_skip' => $array['skip'] ?? 0, + 'weekend' => $array['weekend'] ?? 1 + ]); } } @@ -98,10 +96,10 @@ trait RecurringTransactionTrait Log::debug('Now in createTransactions()'); foreach ($transactions as $index => $array) { Log::debug(sprintf('Now at transaction #%d', $index)); - $sourceTypes = config(sprintf('firefly.expected_source_types.source.%s', $recurrence->transactionType->type)); - $destTypes = config(sprintf('firefly.expected_source_types.destination.%s', $recurrence->transactionType->type)); - $source = $this->findAccount($sourceTypes, $array['source_id'], null); - $destination = $this->findAccount($destTypes, $array['destination_id'], null); + $sourceTypes = config(sprintf('firefly.expected_source_types.source.%s', $recurrence->transactionType->type)); + $destTypes = config(sprintf('firefly.expected_source_types.destination.%s', $recurrence->transactionType->type)); + $source = $this->findAccount($sourceTypes, $array['source_id'], null); + $destination = $this->findAccount($destTypes, $array['destination_id'], null); /** @var TransactionCurrencyFactory $factory */ $factory = app(TransactionCurrencyFactory::class); @@ -111,13 +109,15 @@ trait RecurringTransactionTrait $currency = Amount::getPrimaryCurrencyByUserGroup($recurrence->user->userGroup); } - Log::debug( - sprintf('Will set the validator type to %s based on the type of the recurrence (#%d).', $recurrence->transactionType->type, $recurrence->id) - ); + Log::debug(sprintf( + 'Will set the validator type to %s based on the type of the recurrence (#%d).', + $recurrence->transactionType->type, + $recurrence->id + )); // once the accounts have been determined, we still verify their validity: /** @var AccountValidator $validator */ - $validator = app(AccountValidator::class); + $validator = app(AccountValidator::class); $validator->setUser($recurrence->user); $validator->setTransactionType($recurrence->transactionType->type); @@ -132,18 +132,16 @@ trait RecurringTransactionTrait unset($array['foreign_amount']); } // TODO typeOverrule. The account validator may have a different opinion on the type of the transaction. - $transaction = new RecurrenceTransaction( - [ - 'recurrence_id' => $recurrence->id, - 'transaction_currency_id' => $currency->id, - 'foreign_currency_id' => $foreignCurrency?->id, - 'source_id' => $source->id, - 'destination_id' => $destination->id, - 'amount' => $array['amount'], - 'foreign_amount' => array_key_exists('foreign_amount', $array) ? (string) $array['foreign_amount'] : null, - 'description' => $array['description'], - ] - ); + $transaction = new RecurrenceTransaction([ + 'recurrence_id' => $recurrence->id, + 'transaction_currency_id' => $currency->id, + 'foreign_currency_id' => $foreignCurrency?->id, + 'source_id' => $source->id, + 'destination_id' => $destination->id, + 'amount' => $array['amount'], + 'foreign_amount' => array_key_exists('foreign_amount', $array) ? (string) $array['foreign_amount'] : null, + 'description' => $array['description'] + ]); $transaction->save(); if (array_key_exists('budget_id', $array)) { @@ -167,33 +165,39 @@ trait RecurringTransactionTrait } } - protected function findAccount(array $expectedTypes, ?int $accountId, ?string $accountName): Account + protected function findAccount(array $expectedTypes, null|int $accountId, null|string $accountName): Account { - $result = null; - $accountId = (int) $accountId; - $accountName = (string) $accountName; + $result = null; + $accountId = (int) $accountId; + $accountName = (string) $accountName; /** @var AccountRepositoryInterface $repository */ - $repository = app(AccountRepositoryInterface::class); + $repository = app(AccountRepositoryInterface::class); $repository->setUser($this->user); // if user has submitted an account ID, search for it. - $result = $repository->find($accountId); + $result = $repository->find($accountId); if (null !== $result) { return $result; } // if user has submitted a name, search for it: - $result = $repository->findByName($accountName, $expectedTypes); + $result = $repository->findByName($accountName, $expectedTypes); if (null !== $result) { return $result; } // maybe we can create it? Try to avoid LOAN and other asset types. - $cannotCreate = [AccountTypeEnum::ASSET->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::CREDITCARD->value]; + $cannotCreate = [ + AccountTypeEnum::ASSET->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::MORTGAGE->value, + AccountTypeEnum::CREDITCARD->value + ]; /** @var AccountFactory $factory */ - $factory = app(AccountFactory::class); + $factory = app(AccountFactory::class); $factory->setUser($this->user); /** @var string $expectedType */ @@ -218,7 +222,7 @@ trait RecurringTransactionTrait Log::debug(sprintf('Now in %s', __METHOD__)); $budgetFactory = app(BudgetFactory::class); $budgetFactory->setUser($transaction->recurrence->user); - $budget = $budgetFactory->find($budgetId, null); + $budget = $budgetFactory->find($budgetId, null); if (null === $budget) { // remove budget from recurring transaction: $transaction->recurrenceTransactionMeta()->where('name', 'budget_id')->delete(); @@ -226,13 +230,13 @@ trait RecurringTransactionTrait return; } - $meta = $transaction->recurrenceTransactionMeta()->where('name', 'budget_id')->first(); + $meta = $transaction->recurrenceTransactionMeta()->where('name', 'budget_id')->first(); if (null === $meta) { - $meta = new RecurrenceTransactionMeta(); + $meta = new RecurrenceTransactionMeta(); $meta->rt_id = $transaction->id; - $meta->name = 'budget_id'; + $meta->name = 'budget_id'; } - $meta->value = $budget->id; + $meta->value = $budget->id; $meta->save(); } @@ -240,7 +244,7 @@ trait RecurringTransactionTrait { $billFactory = app(BillFactory::class); $billFactory->setUser($transaction->recurrence->user); - $bill = $billFactory->find($billId, null); + $bill = $billFactory->find($billId, null); if (null === $bill) { // remove bill from recurring transaction: $transaction->recurrenceTransactionMeta()->where('name', 'bill_id')->delete(); @@ -248,11 +252,11 @@ trait RecurringTransactionTrait return; } - $meta = $transaction->recurrenceTransactionMeta()->where('name', 'bill_id')->first(); + $meta = $transaction->recurrenceTransactionMeta()->where('name', 'bill_id')->first(); if (null === $meta) { - $meta = new RecurrenceTransactionMeta(); + $meta = new RecurrenceTransactionMeta(); $meta->rt_id = $transaction->id; - $meta->name = 'bill_id'; + $meta->name = 'bill_id'; } $meta->value = $bill->id; $meta->save(); @@ -262,7 +266,7 @@ trait RecurringTransactionTrait { $categoryFactory = app(CategoryFactory::class); $categoryFactory->setUser($transaction->recurrence->user); - $category = $categoryFactory->findOrCreate($categoryId, null); + $category = $categoryFactory->findOrCreate($categoryId, null); if (null === $category) { // remove category: $transaction->recurrenceTransactionMeta()->where('name', 'category_id')->delete(); @@ -271,27 +275,27 @@ trait RecurringTransactionTrait return; } $transaction->recurrenceTransactionMeta()->where('name', 'category_name')->delete(); - $meta = $transaction->recurrenceTransactionMeta()->where('name', 'category_id')->first(); + $meta = $transaction->recurrenceTransactionMeta()->where('name', 'category_id')->first(); if (null === $meta) { - $meta = new RecurrenceTransactionMeta(); + $meta = new RecurrenceTransactionMeta(); $meta->rt_id = $transaction->id; - $meta->name = 'category_id'; + $meta->name = 'category_id'; } - $meta->value = $category->id; + $meta->value = $category->id; $meta->save(); } protected function updatePiggyBank(RecurrenceTransaction $transaction, int $piggyId): void { /** @var PiggyBankFactory $factory */ - $factory = app(PiggyBankFactory::class); + $factory = app(PiggyBankFactory::class); $factory->user = $transaction->recurrence->user; - $piggyBank = $factory->find($piggyId, null); + $piggyBank = $factory->find($piggyId, null); if (null !== $piggyBank) { /** @var null|RecurrenceMeta $entry */ - $entry = $transaction->recurrenceTransactionMeta()->where('name', 'piggy_bank_id')->first(); + $entry = $transaction->recurrenceTransactionMeta()->where('name', 'piggy_bank_id')->first(); if (null === $entry) { - $entry = RecurrenceTransactionMeta::create(['rt_id' => $transaction->id, 'name' => 'piggy_bank_id', 'value' => $piggyBank->id]); + $entry = RecurrenceTransactionMeta::create(['rt_id' => $transaction->id, 'name' => 'piggy_bank_id', 'value' => $piggyBank->id]); } $entry->value = $piggyBank->id; $entry->save(); @@ -306,9 +310,9 @@ trait RecurringTransactionTrait { if (0 !== count($tags)) { /** @var null|RecurrenceMeta $entry */ - $entry = $transaction->recurrenceTransactionMeta()->where('name', 'tags')->first(); + $entry = $transaction->recurrenceTransactionMeta()->where('name', 'tags')->first(); if (null === $entry) { - $entry = RecurrenceTransactionMeta::create(['rt_id' => $transaction->id, 'name' => 'tags', 'value' => json_encode($tags)]); + $entry = RecurrenceTransactionMeta::create(['rt_id' => $transaction->id, 'name' => 'tags', 'value' => json_encode($tags)]); } $entry->value = json_encode($tags); $entry->save(); diff --git a/app/Services/Internal/Support/TransactionTypeTrait.php b/app/Services/Internal/Support/TransactionTypeTrait.php index e16bfd87f7..6d96b8d7f0 100644 --- a/app/Services/Internal/Support/TransactionTypeTrait.php +++ b/app/Services/Internal/Support/TransactionTypeTrait.php @@ -24,10 +24,10 @@ declare(strict_types=1); namespace FireflyIII\Services\Internal\Support; -use Illuminate\Support\Facades\Log; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Factory\TransactionTypeFactory; use FireflyIII\Models\TransactionType; +use Illuminate\Support\Facades\Log; /** * Trait TransactionTypeTrait diff --git a/app/Services/Internal/Update/AccountUpdateService.php b/app/Services/Internal/Update/AccountUpdateService.php index 67fe8b0bb3..81c74fde67 100644 --- a/app/Services/Internal/Update/AccountUpdateService.php +++ b/app/Services/Internal/Update/AccountUpdateService.php @@ -24,8 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Services\Internal\Update; -use FireflyIII\Support\Facades\Preferences; -use Illuminate\Support\Facades\Log; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Events\UpdatedAccount; use FireflyIII\Exceptions\FireflyException; @@ -34,8 +32,10 @@ use FireflyIII\Models\AccountType; use FireflyIII\Models\Location; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Services\Internal\Support\AccountServiceTrait; -use FireflyIII\User; +use FireflyIII\Support\Facades\Preferences; use FireflyIII\Support\Facades\Steam; +use FireflyIII\User; +use Illuminate\Support\Facades\Log; /** * Class AccountUpdateService @@ -46,11 +46,11 @@ class AccountUpdateService use AccountServiceTrait; protected AccountRepositoryInterface $accountRepository; - protected array $validAssetFields; - protected array $validCCFields; - protected array $validFields; - private array $canHaveOpeningBalance; - private User $user; + protected array $validAssetFields; + protected array $validCCFields; + protected array $validFields; + private array $canHaveOpeningBalance; + private User $user; /** * Constructor. @@ -58,10 +58,10 @@ class AccountUpdateService public function __construct() { $this->canHaveOpeningBalance = config('firefly.can_have_opening_balance'); - $this->validAssetFields = config('firefly.valid_asset_fields'); - $this->validCCFields = config('firefly.valid_cc_fields'); - $this->validFields = config('firefly.valid_account_fields'); - $this->accountRepository = app(AccountRepositoryInterface::class); + $this->validAssetFields = config('firefly.valid_asset_fields'); + $this->validCCFields = config('firefly.valid_cc_fields'); + $this->validFields = config('firefly.valid_account_fields'); + $this->accountRepository = app(AccountRepositoryInterface::class); } /** @@ -74,12 +74,12 @@ class AccountUpdateService Log::debug(sprintf('Now in %s', __METHOD__)); $this->accountRepository->setUser($account->user); $this->user = $account->user; - $account = $this->updateAccount($account, $data); - $account = $this->updateAccountOrder($account, $data); + $account = $this->updateAccount($account, $data); + $account = $this->updateAccountOrder($account, $data); // find currency, or use default currency instead. if (array_key_exists('currency_id', $data) || array_key_exists('currency_code', $data)) { - $currency = $this->getCurrency((int) ($data['currency_id'] ?? null), (string) ($data['currency_code'] ?? null)); + $currency = $this->getCurrency((int) ($data['currency_id'] ?? null), (string) ($data['currency_code'] ?? null)); unset($data['currency_code'], $data['currency_id']); $data['currency_id'] = $currency->id; } @@ -130,7 +130,7 @@ class AccountUpdateService // set liability, but account must already be a liability. // $liabilityType = $data['liability_type'] ?? ''; if ($this->isLiability($account) && array_key_exists('liability_type', $data)) { - $type = $this->getAccountType($data['liability_type']); + $type = $this->getAccountType($data['liability_type']); $account->account_type_id = $type->id; } // set liability, alternative method used in v1 layout: @@ -174,27 +174,33 @@ class AccountUpdateService return $account; } // skip if not of orderable type. - $type = $account->accountType->type; - if (!in_array($type, [AccountTypeEnum::ASSET->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value], true)) { + $type = $account->accountType->type; + if (!in_array( + $type, + [AccountTypeEnum::ASSET->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value], + true + )) { Log::debug('Will not change order of this account.'); return $account; } // get account type ID's because a join and an update is hard: - $oldOrder = $account->order; - $newOrder = $data['order']; + $oldOrder = $account->order; + $newOrder = $data['order']; Log::debug(sprintf('Order is set to be updated from %s to %s', $oldOrder, $newOrder)); - $list = $this->getTypeIds([AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value]); + $list = $this->getTypeIds([AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value]); if (AccountTypeEnum::ASSET->value === $type) { $list = $this->getTypeIds([AccountTypeEnum::ASSET->value]); } if ($newOrder > $oldOrder) { - $this->user->accounts()->where('accounts.order', '<=', $newOrder)->where('accounts.order', '>', $oldOrder) + $this->user + ->accounts() + ->where('accounts.order', '<=', $newOrder) + ->where('accounts.order', '>', $oldOrder) ->where('accounts.id', '!=', $account->id) ->whereIn('accounts.account_type_id', $list) - ->decrement('order') - ; + ->decrement('order'); $account->order = $newOrder; Log::debug(sprintf('Order of account #%d ("%s") is now %d', $account->id, $account->name, $newOrder)); $account->save(); @@ -202,11 +208,13 @@ class AccountUpdateService return $account; } - $this->user->accounts()->where('accounts.order', '>=', $newOrder)->where('accounts.order', '<', $oldOrder) + $this->user + ->accounts() + ->where('accounts.order', '>=', $newOrder) + ->where('accounts.order', '<', $oldOrder) ->where('accounts.id', '!=', $account->id) ->whereIn('accounts.account_type_id', $list) - ->increment('order') - ; + ->increment('order'); $account->order = $newOrder; Log::debug(sprintf('Order of account #%d ("%s") is now %d', $account->id, $account->name, $newOrder)); $account->save(); @@ -221,7 +229,7 @@ class AccountUpdateService /** @var string $type */ foreach ($array as $type) { /** @var AccountType $type */ - $type = AccountType::whereType($type)->first(); + $type = AccountType::whereType($type)->first(); $return[] = $type->id; } @@ -240,14 +248,14 @@ class AccountUpdateService // otherwise, update or create. if (!(null === $data['latitude'] && null === $data['longitude'] && null === $data['zoom_level'])) { - $location = $this->accountRepository->getLocation($account); + $location = $this->accountRepository->getLocation($account); if (!$location instanceof Location) { $location = new Location(); $location->locatable()->associate($account); } - $location->latitude = $data['latitude'] ?? config('firefly.default_location.latitude'); - $location->longitude = $data['longitude'] ?? config('firefly.default_location.longitude'); + $location->latitude = $data['latitude'] ?? config('firefly.default_location.latitude'); + $location->longitude = $data['longitude'] ?? config('firefly.default_location.longitude'); $location->zoom_level = $data['zoom_level'] ?? config('firefly.default_location.zoom_level'); $location->save(); } @@ -270,9 +278,7 @@ class AccountUpdateService // if liability, make sure the amount is positive for a credit, and negative for a debit. if ($this->isLiability($account)) { - $openingBalance = 'credit' === $data['liability_direction'] ? Steam::positive($openingBalance) : Steam::negative( - $openingBalance - ); + $openingBalance = 'credit' === $data['liability_direction'] ? Steam::positive($openingBalance) : Steam::negative($openingBalance); } $this->updateOBGroupV2($account, $openingBalance, $openingBalanceDate); } @@ -293,11 +299,11 @@ class AccountUpdateService if (true === $account->active) { return; } - $preference = Preferences::getForUser($account->user, 'frontpageAccounts'); + $preference = Preferences::getForUser($account->user, 'frontpageAccounts'); if (null === $preference) { return; } - $array = $preference->data; + $array = $preference->data; if (!is_array($array)) { $array = [$array]; } diff --git a/app/Services/Internal/Update/BillUpdateService.php b/app/Services/Internal/Update/BillUpdateService.php index a13a0707be..2c70f7f5fb 100644 --- a/app/Services/Internal/Update/BillUpdateService.php +++ b/app/Services/Internal/Update/BillUpdateService.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Services\Internal\Update; -use Illuminate\Support\Facades\Log; use FireflyIII\Factory\TransactionCurrencyFactory; use FireflyIII\Models\Bill; use FireflyIII\Models\ObjectGroup; @@ -33,9 +32,10 @@ use FireflyIII\Models\RuleTrigger; use FireflyIII\Repositories\Bill\BillRepositoryInterface; use FireflyIII\Repositories\ObjectGroup\CreatesObjectGroups; use FireflyIII\Services\Internal\Support\BillServiceTrait; +use FireflyIII\Support\Facades\Amount; use FireflyIII\User; use Illuminate\Support\Collection; -use FireflyIII\Support\Facades\Amount; +use Illuminate\Support\Facades\Log; /** * Class BillUpdateService @@ -52,26 +52,28 @@ class BillUpdateService $this->user = $bill->user; if (array_key_exists('currency_id', $data) || array_key_exists('currency_code', $data)) { - $factory = app(TransactionCurrencyFactory::class); - $currency = $factory->find((int) ($data['currency_id'] ?? null), $data['currency_code'] ?? null) - ?? Amount::getPrimaryCurrencyByUserGroup($bill->user->userGroup); + $factory = app(TransactionCurrencyFactory::class); + $currency = $factory->find( + (int) ($data['currency_id'] ?? null), + $data['currency_code'] ?? null + ) ?? Amount::getPrimaryCurrencyByUserGroup($bill->user->userGroup); // enable the currency if it isn't. - $currency->enabled = true; + $currency->enabled = true; $currency->save(); $bill->transaction_currency_id = $currency->id; $bill->save(); } // update bill properties: - $bill = $this->updateBillProperties($bill, $data); + $bill = $this->updateBillProperties($bill, $data); $bill->save(); $bill->refresh(); // old values - $oldData = [ + $oldData = [ 'name' => $bill->name, 'amount_min' => $bill->amount_min, 'amount_max' => $bill->amount_max, - 'transaction_currency_name' => $bill->transactionCurrency->name, + 'transaction_currency_name' => $bill->transactionCurrency->name ]; // update note: if (array_key_exists('notes', $data)) { @@ -145,7 +147,7 @@ class BillUpdateService $bill->amount_max = $data['amount_max']; } if (array_key_exists('date', $data) && '' !== (string) $data['date']) { - $bill->date = $data['date']; + $bill->date = $data['date']; $bill->date_tz = $data['date']->format('e'); } if (array_key_exists('repeat_freq', $data) && '' !== (string) $data['repeat_freq']) { @@ -158,15 +160,15 @@ class BillUpdateService $bill->active = $data['active']; } if (array_key_exists('end_date', $data)) { - $bill->end_date = $data['end_date']; + $bill->end_date = $data['end_date']; $bill->end_date_tz = $data['end_date']?->format('e'); } if (array_key_exists('extension_date', $data)) { - $bill->extension_date = $data['extension_date']; + $bill->extension_date = $data['extension_date']; $bill->extension_date_tz = $data['extension_date']?->format('e'); } - $bill->match = 'EMPTY'; + $bill->match = 'EMPTY'; $bill->automatch = true; $bill->save(); @@ -176,18 +178,22 @@ class BillUpdateService private function updateOrder(Bill $bill, int $oldOrder, int $newOrder): void { if ($newOrder > $oldOrder) { - $this->user->bills()->where('order', '<=', $newOrder)->where('order', '>', $oldOrder) + $this->user + ->bills() + ->where('order', '<=', $newOrder) + ->where('order', '>', $oldOrder) ->where('bills.id', '!=', $bill->id) - ->decrement('bills.order') - ; + ->decrement('bills.order'); $bill->order = $newOrder; $bill->save(); } if ($newOrder < $oldOrder) { - $this->user->bills()->where('order', '>=', $newOrder)->where('order', '<', $oldOrder) + $this->user + ->bills() + ->where('order', '>=', $newOrder) + ->where('order', '<', $oldOrder) ->where('bills.id', '!=', $bill->id) - ->increment('bills.order') - ; + ->increment('bills.order'); $bill->order = $newOrder; $bill->save(); } @@ -200,18 +206,18 @@ class BillUpdateService /** @var BillRepositoryInterface $repository */ $repository = app(BillRepositoryInterface::class); $repository->setUser($bill->user); - $rules = $repository->getRulesForBill($bill); + $rules = $repository->getRulesForBill($bill); if (0 === $rules->count()) { Log::debug('Found no rules.'); return; } Log::debug(sprintf('Found %d rules', $rules->count())); - $fields = [ + $fields = [ 'name' => 'description_contains', 'amount_min' => 'amount_more', 'amount_max' => 'amount_less', - 'transaction_currency_name' => 'currency_is', + 'transaction_currency_name' => 'currency_is' ]; foreach ($fields as $field => $ruleTriggerKey) { if (!array_key_exists($field, $newData)) { @@ -238,8 +244,12 @@ class BillUpdateService continue; } - if ($trigger instanceof RuleTrigger && $trigger->trigger_value !== $oldValue && in_array($key, ['amount_more', 'amount_less'], true) - && 0 === bccomp($trigger->trigger_value, $oldValue)) { + if ( + $trigger instanceof RuleTrigger + && $trigger->trigger_value !== $oldValue + && in_array($key, ['amount_more', 'amount_less'], true) + && 0 === bccomp($trigger->trigger_value, $oldValue) + ) { Log::debug(sprintf('Updated rule trigger #%d from value "%s" to value "%s"', $trigger->id, $oldValue, $newValue)); $trigger->trigger_value = $newValue; $trigger->save(); @@ -247,7 +257,7 @@ class BillUpdateService } } - private function getRuleTrigger(Rule $rule, string $key): ?RuleTrigger + private function getRuleTrigger(Rule $rule, string $key): null|RuleTrigger { /** @var null|RuleTrigger */ return $rule->ruleTriggers()->where('trigger_type', $key)->first(); diff --git a/app/Services/Internal/Update/CategoryUpdateService.php b/app/Services/Internal/Update/CategoryUpdateService.php index 1561dcd6ce..1763042a61 100644 --- a/app/Services/Internal/Update/CategoryUpdateService.php +++ b/app/Services/Internal/Update/CategoryUpdateService.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Services\Internal\Update; -use Illuminate\Support\Facades\Log; use Exception; use FireflyIII\Models\Category; use FireflyIII\Models\Note; @@ -32,6 +31,7 @@ use FireflyIII\Models\RecurrenceTransactionMeta; use FireflyIII\Models\RuleAction; use FireflyIII\Models\RuleTrigger; use FireflyIII\User; +use Illuminate\Support\Facades\Log; /** * Class CategoryUpdateService @@ -47,7 +47,7 @@ class CategoryUpdateService { if (auth()->check()) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->user = $user; } } @@ -87,8 +87,7 @@ class CategoryUpdateService ->where('rules.user_id', $this->user->id) ->whereIn('rule_triggers.trigger_type', $types) ->where('rule_triggers.trigger_value', $oldName) - ->get(['rule_triggers.*']) - ; + ->get(['rule_triggers.*']); Log::debug(sprintf('Found %d triggers to update.', $triggers->count())); /** @var RuleTrigger $trigger */ @@ -106,8 +105,7 @@ class CategoryUpdateService ->where('rules.user_id', $this->user->id) ->whereIn('rule_actions.action_type', $types) ->where('rule_actions.action_value', $oldName) - ->get(['rule_actions.*']) - ; + ->get(['rule_actions.*']); Log::debug(sprintf('Found %d actions to update.', $actions->count())); /** @var RuleAction $action */ @@ -125,8 +123,7 @@ class CategoryUpdateService ->where('recurrences.user_id', $this->user->id) ->where('rt_meta.name', 'category_name') ->where('rt_meta.value', $oldName) - ->update(['rt_meta.value' => $newName]) - ; + ->update(['rt_meta.value' => $newName]); } /** @@ -134,7 +131,7 @@ class CategoryUpdateService */ private function updateNotes(Category $category, array $data): void { - $note = $data['notes'] ?? null; + $note = $data['notes'] ?? null; if (null === $note) { return; } @@ -144,7 +141,7 @@ class CategoryUpdateService return; } - $dbNote = $category->notes()->first(); + $dbNote = $category->notes()->first(); if (null === $dbNote) { $dbNote = new Note(); $dbNote->noteable()->associate($category); diff --git a/app/Services/Internal/Update/CurrencyUpdateService.php b/app/Services/Internal/Update/CurrencyUpdateService.php index 445b82ac63..7c019351e1 100644 --- a/app/Services/Internal/Update/CurrencyUpdateService.php +++ b/app/Services/Internal/Update/CurrencyUpdateService.php @@ -45,13 +45,13 @@ class CurrencyUpdateService $currency->name = e($data['name']); } - $currency->enabled = false; + $currency->enabled = false; if (array_key_exists('decimal_places', $data) && is_int($data['decimal_places'])) { $currency->decimal_places = $data['decimal_places']; } $currency->userGroupEnabled = null; - $currency->userGroupNative = null; + $currency->userGroupNative = null; $currency->save(); return $currency; diff --git a/app/Services/Internal/Update/GroupCloneService.php b/app/Services/Internal/Update/GroupCloneService.php index db78b5092b..107b38edde 100644 --- a/app/Services/Internal/Update/GroupCloneService.php +++ b/app/Services/Internal/Update/GroupCloneService.php @@ -53,9 +53,9 @@ class GroupCloneService private function cloneJournal(TransactionJournal $journal, TransactionGroup $newGroup, int $originalGroup): void { - $newJournal = $journal->replicate(); + $newJournal = $journal->replicate(); $newJournal->transaction_group_id = $newGroup->id; - $newJournal->date = now(); + $newJournal->date = now(); $newJournal->save(); foreach ($journal->transactions as $transaction) { @@ -98,7 +98,7 @@ class GroupCloneService // add relation. // TODO clone ALL linked piggy banks /** @var null|PiggyBankEvent $event */ - $event = $journal->piggyBankEvents()->first(); + $event = $journal->piggyBankEvents()->first(); if (null !== $event) { $piggyBank = $event->piggyBank; $factory = app(PiggyBankEventFactory::class); @@ -108,23 +108,26 @@ class GroupCloneService private function cloneTransaction(Transaction $transaction, TransactionJournal $newJournal): void { - $newTransaction = $transaction->replicate(); + $newTransaction = $transaction->replicate(); $newTransaction->transaction_journal_id = $newJournal->id; - $newTransaction->reconciled = false; + $newTransaction->reconciled = false; $newTransaction->save(); } private function cloneNote(Note $note, TransactionJournal $newJournal, int $oldGroupId): void { - $newNote = $note->replicate(); - $newNote->text = sprintf("%s\n\n%s", $newNote->text, trans('firefly.clones_journal_x', ['description' => $newJournal->description, 'id' => $oldGroupId])); + $newNote = $note->replicate(); + $newNote->text = sprintf("%s\n\n%s", $newNote->text, trans('firefly.clones_journal_x', [ + 'description' => $newJournal->description, + 'id' => $oldGroupId + ])); $newNote->noteable_id = $newJournal->id; $newNote->save(); } private function cloneMeta(TransactionJournalMeta $meta, TransactionJournal $newJournal): void { - $newMeta = $meta->replicate(); + $newMeta = $meta->replicate(); $newMeta->transaction_journal_id = $newJournal->id; if ('recurrence_id' !== $newMeta->name) { $newMeta->save(); diff --git a/app/Services/Internal/Update/GroupUpdateService.php b/app/Services/Internal/Update/GroupUpdateService.php index 1b5e8f53f9..cabea63fc7 100644 --- a/app/Services/Internal/Update/GroupUpdateService.php +++ b/app/Services/Internal/Update/GroupUpdateService.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Services\Internal\Update; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Exceptions\DuplicateTransactionException; use FireflyIII\Exceptions\FireflyException; @@ -32,6 +31,7 @@ use FireflyIII\Factory\TransactionJournalFactory; use FireflyIII\Models\TransactionGroup; use FireflyIII\Models\TransactionJournal; use FireflyIII\Services\Internal\Destroy\JournalDestroyService; +use FireflyIII\Support\Facades\Preferences; use Illuminate\Support\Facades\Log; /** @@ -55,18 +55,10 @@ class GroupUpdateService // update group name. if (array_key_exists('group_title', $data)) { Log::debug(sprintf('Update transaction group #%d title.', $transactionGroup->id)); - $oldTitle = $transactionGroup->title; + $oldTitle = $transactionGroup->title; $transactionGroup->title = $data['group_title']; $transactionGroup->save(); - event( - new TriggeredAuditLog( - $transactionGroup->user, - $transactionGroup, - 'update_group_title', - $oldTitle, - $data['group_title'] - ) - ); + event(new TriggeredAuditLog($transactionGroup->user, $transactionGroup, 'update_group_title', $oldTitle, $data['group_title'])); } if (0 === count($transactions)) { @@ -89,8 +81,8 @@ class GroupUpdateService Log::debug('Going to update split group.'); - $existing = $transactionGroup->transactionJournals->pluck('id')->toArray(); - $updated = $this->updateTransactions($transactionGroup, $transactions); + $existing = $transactionGroup->transactionJournals->pluck('id')->toArray(); + $updated = $this->updateTransactions($transactionGroup, $transactions); Log::debug('Array of updated IDs: ', $updated); if (0 === count($updated)) { @@ -102,7 +94,7 @@ class GroupUpdateService return $transactionGroup; } - $result = array_diff($existing, $updated); + $result = array_diff($existing, $updated); Log::debug('Result of DIFF: ', $result); /** @var string $deletedId */ @@ -125,11 +117,8 @@ class GroupUpdateService /** * Update single journal. */ - private function updateTransactionJournal( - TransactionGroup $transactionGroup, - TransactionJournal $journal, - array $data - ): void { + private function updateTransactionJournal(TransactionGroup $transactionGroup, TransactionJournal $journal, array $data): void + { Log::debug(sprintf('Now in %s', __METHOD__)); if (0 === count($data)) { return; @@ -165,7 +154,7 @@ class GroupUpdateService $journalId = (int) ($transaction['transaction_journal_id'] ?? 0); /** @var null|TransactionJournal $journal */ - $journal = $transactionGroup->transactionJournals()->find($journalId); + $journal = $transactionGroup->transactionJournals()->find($journalId); if (null === $journal) { Log::debug('This entry has no existing journal: make a new split.'); // force the transaction type on the transaction data. @@ -174,9 +163,7 @@ class GroupUpdateService Log::debug('No transaction type is indicated.'); /** @var null|TransactionJournal $randomJournal */ - $randomJournal = $transactionGroup->transactionJournals()->inRandomOrder()->with( - ['transactionType'] - )->first(); + $randomJournal = $transactionGroup->transactionJournals()->inRandomOrder()->with(['transactionType'])->first(); if (null !== $randomJournal) { $transaction['type'] = $randomJournal->transactionType->type; Log::debug(sprintf('Transaction type set to %s.', $transaction['type'])); @@ -207,16 +194,12 @@ class GroupUpdateService * @throws DuplicateTransactionException * @throws FireflyException */ - private function createTransactionJournal(TransactionGroup $transactionGroup, array $data): ?TransactionJournal + private function createTransactionJournal(TransactionGroup $transactionGroup, array $data): null|TransactionJournal { - $submission = [ - 'transactions' => [ - $data, - ], - ]; + $submission = ['transactions' => [$data]]; /** @var TransactionJournalFactory $factory */ - $factory = app(TransactionJournalFactory::class); + $factory = app(TransactionJournalFactory::class); $factory->setUser($transactionGroup->user); try { @@ -225,17 +208,11 @@ class GroupUpdateService Log::error($e->getMessage()); Log::error($e->getTraceAsString()); - throw new FireflyException( - sprintf('Could not create new transaction journal: %s', $e->getMessage()), - 0, - $e - ); + throw new FireflyException(sprintf('Could not create new transaction journal: %s', $e->getMessage()), 0, $e); } - $collection->each( - static function (TransactionJournal $journal) use ($transactionGroup): void { - $transactionGroup->transactionJournals()->save($journal); - } - ); + $collection->each(static function (TransactionJournal $journal) use ($transactionGroup): void { + $transactionGroup->transactionJournals()->save($journal); + }); if (0 === $collection->count()) { return null; } diff --git a/app/Services/Internal/Update/JournalUpdateService.php b/app/Services/Internal/Update/JournalUpdateService.php index dba341b606..d84c946557 100644 --- a/app/Services/Internal/Update/JournalUpdateService.php +++ b/app/Services/Internal/Update/JournalUpdateService.php @@ -61,47 +61,53 @@ class JournalUpdateService { use JournalServiceTrait; - private BillRepositoryInterface $billRepository; - private CurrencyRepositoryInterface $currencyRepository; + private BillRepositoryInterface $billRepository; + private CurrencyRepositoryInterface $currencyRepository; private TransactionGroupRepositoryInterface $transactionGroupRepository; - private array $data; - private ?Account $destinationAccount = null; - private ?Transaction $destinationTransaction = null; - private array $metaDate - = ['interest_date', 'book_date', 'process_date', 'due_date', 'payment_date', 'invoice_date', '_internal_previous_date']; - private array $metaString - = [ - 'sepa_cc', - 'sepa_ct_op', - 'sepa_ct_id', - 'sepa_db', - 'sepa_country', - 'sepa_ep', - 'sepa_ci', - 'sepa_batch_id', - 'recurrence_id', - 'internal_reference', - 'bunq_payment_id', - 'external_id', - 'external_url', - ]; - private ?Account $sourceAccount = null; - private ?Transaction $sourceTransaction = null; - private ?TransactionGroup $transactionGroup = null; - private ?TransactionJournal $transactionJournal = null; - private string $startCompareHash = ''; + private array $data; + private null|Account $destinationAccount = null; + private null|Transaction $destinationTransaction = null; + private array $metaDate = [ + 'interest_date', + 'book_date', + 'process_date', + 'due_date', + 'payment_date', + 'invoice_date', + '_internal_previous_date' + ]; + private array $metaString = [ + 'sepa_cc', + 'sepa_ct_op', + 'sepa_ct_id', + 'sepa_db', + 'sepa_country', + 'sepa_ep', + 'sepa_ci', + 'sepa_batch_id', + 'recurrence_id', + 'internal_reference', + 'bunq_payment_id', + 'external_id', + 'external_url' + ]; + private null|Account $sourceAccount = null; + private null|Transaction $sourceTransaction = null; + private null|TransactionGroup $transactionGroup = null; + private null|TransactionJournal $transactionJournal = null; + private string $startCompareHash = ''; /** * JournalUpdateService constructor. */ public function __construct() { - $this->billRepository = app(BillRepositoryInterface::class); - $this->categoryRepository = app(CategoryRepositoryInterface::class); - $this->budgetRepository = app(BudgetRepositoryInterface::class); - $this->tagFactory = app(TagFactory::class); - $this->accountRepository = app(AccountRepositoryInterface::class); - $this->currencyRepository = app(CurrencyRepositoryInterface::class); + $this->billRepository = app(BillRepositoryInterface::class); + $this->categoryRepository = app(CategoryRepositoryInterface::class); + $this->budgetRepository = app(BudgetRepositoryInterface::class); + $this->tagFactory = app(TagFactory::class); + $this->accountRepository = app(AccountRepositoryInterface::class); + $this->currencyRepository = app(CurrencyRepositoryInterface::class); $this->transactionGroupRepository = app(TransactionGroupRepositoryInterface::class); } @@ -112,18 +118,18 @@ class JournalUpdateService public function setTransactionGroup(TransactionGroup $transactionGroup): void { - $this->transactionGroup = $transactionGroup; + $this->transactionGroup = $transactionGroup; $this->billRepository->setUser($transactionGroup->user); $this->categoryRepository->setUser($transactionGroup->user); $this->budgetRepository->setUser($transactionGroup->user); $this->tagFactory->setUser($transactionGroup->user); $this->accountRepository->setUser($transactionGroup->user); $this->transactionGroupRepository->setUser($transactionGroup->user); - $this->destinationAccount = null; + $this->destinationAccount = null; $this->destinationTransaction = null; - $this->sourceAccount = null; - $this->sourceTransaction = null; - $this->startCompareHash = $this->transactionGroupRepository->getCompareHash($transactionGroup); + $this->sourceAccount = null; + $this->sourceTransaction = null; + $this->startCompareHash = $this->transactionGroupRepository->getCompareHash($transactionGroup); } public function setTransactionJournal(TransactionJournal $transactionJournal): void @@ -183,8 +189,8 @@ class JournalUpdateService private function hasValidSourceAccount(): bool { - $sourceId = $this->data['source_id'] ?? null; - $sourceName = $this->data['source_name'] ?? null; + $sourceId = $this->data['source_id'] ?? null; + $sourceName = $this->data['source_name'] ?? null; Log::debug(sprintf('Now in hasValidSourceAccount("%s","%s").', $sourceId, $sourceName)); if (!$this->hasFields(['source_id', 'source_name'])) { @@ -199,11 +205,11 @@ class JournalUpdateService // make a new validator. /** @var AccountValidator $validator */ - $validator = app(AccountValidator::class); + $validator = app(AccountValidator::class); $validator->setTransactionType($expectedType); $validator->setUser($this->transactionJournal->user); - $result = $validator->validateSource(['id' => $sourceId, 'name' => $sourceName]); + $result = $validator->validateSource(['id' => $sourceId, 'name' => $sourceName]); Log::debug(sprintf('hasValidSourceAccount(%d, "%s") will return %s', $sourceId, $sourceName, var_export($result, true))); // TODO type overrule the account validator may have a different opinion on the transaction type. @@ -214,13 +220,13 @@ class JournalUpdateService private function hasFields(array $fields): bool { - return array_any($fields, fn ($field): bool => array_key_exists($field, $this->data)); + return array_any($fields, fn($field): bool => array_key_exists($field, $this->data)); } private function getOriginalSourceAccount(): Account { if (!$this->sourceAccount instanceof Account) { - $source = $this->getSourceTransaction(); + $source = $this->getSourceTransaction(); $this->sourceAccount = $source->account; } @@ -231,7 +237,11 @@ class JournalUpdateService { if (!$this->sourceTransaction instanceof Transaction) { /** @var null|Transaction $result */ - $result = $this->transactionJournal->transactions()->with(['account'])->where('amount', '<', 0)->first(); + $result = $this->transactionJournal + ->transactions() + ->with(['account']) + ->where('amount', '<', 0) + ->first(); $this->sourceTransaction = $result; } Log::debug(sprintf('getSourceTransaction: %s', $this->sourceTransaction->amount)); @@ -259,8 +269,8 @@ class JournalUpdateService private function hasValidDestinationAccount(): bool { Log::debug('Now in hasValidDestinationAccount().'); - $destId = $this->data['destination_id'] ?? null; - $destName = $this->data['destination_name'] ?? null; + $destId = $this->data['destination_id'] ?? null; + $destName = $this->data['destination_name'] ?? null; if (!$this->hasFields(['destination_id', 'destination_name'])) { Log::debug('No destination info submitted, grab the original data.'); @@ -270,16 +280,16 @@ class JournalUpdateService } // make new account validator. - $expectedType = $this->getExpectedType(); + $expectedType = $this->getExpectedType(); Log::debug(sprintf('(b) Expected type (new or unchanged) is %s', $expectedType)); // make a new validator. /** @var AccountValidator $validator */ - $validator = app(AccountValidator::class); + $validator = app(AccountValidator::class); $validator->setTransactionType($expectedType); $validator->setUser($this->transactionJournal->user); $validator->source = $this->getValidSourceAccount(); - $result = $validator->validateDestination(['id' => $destId, 'name' => $destName]); + $result = $validator->validateDestination(['id' => $destId, 'name' => $destName]); Log::debug(sprintf('hasValidDestinationAccount(%d, "%s") will return %s', $destId, $destName, var_export($result, true))); // TODO typeOverrule: the account validator may have another opinion on the transaction type. @@ -291,7 +301,7 @@ class JournalUpdateService private function getOriginalDestinationAccount(): Account { if (!$this->destinationAccount instanceof Account) { - $destination = $this->getDestinationTransaction(); + $destination = $this->getDestinationTransaction(); $this->destinationAccount = $destination->account; } @@ -305,7 +315,10 @@ class JournalUpdateService { if (!$this->destinationTransaction instanceof Transaction) { /** @var null|Transaction $result */ - $result = $this->transactionJournal->transactions()->where('amount', '>', 0)->first(); + $result = $this->transactionJournal + ->transactions() + ->where('amount', '>', 0) + ->first(); $this->destinationTransaction = $result; } @@ -323,12 +336,12 @@ class JournalUpdateService return $this->getOriginalSourceAccount(); } - $sourceInfo = [ - 'id' => (int)($this->data['source_id'] ?? null), + $sourceInfo = [ + 'id' => (int) ($this->data['source_id'] ?? null), 'name' => $this->data['source_name'] ?? null, 'iban' => $this->data['source_iban'] ?? null, 'number' => $this->data['source_number'] ?? null, - 'bic' => $this->data['source_bic'] ?? null, + 'bic' => $this->data['source_bic'] ?? null ]; $expectedType = $this->getExpectedType(); @@ -351,8 +364,8 @@ class JournalUpdateService */ private function updateAccounts(): void { - $source = $this->getValidSourceAccount(); - $destination = $this->getValidDestinationAccount(); + $source = $this->getValidSourceAccount(); + $destination = $this->getValidDestinationAccount(); // cowardly refuse to update if both accounts are the same. if ($source->id === $destination->id) { @@ -365,7 +378,7 @@ class JournalUpdateService $origSourceTransaction->account()->associate($source); $origSourceTransaction->save(); - $destTransaction = $this->getDestinationTransaction(); + $destTransaction = $this->getDestinationTransaction(); $destTransaction->account()->associate($destination); $destTransaction->save(); @@ -387,12 +400,12 @@ class JournalUpdateService return $this->getOriginalDestinationAccount(); } - $destInfo = [ - 'id' => (int)($this->data['destination_id'] ?? null), + $destInfo = [ + 'id' => (int) ($this->data['destination_id'] ?? null), 'name' => $this->data['destination_name'] ?? null, 'iban' => $this->data['destination_iban'] ?? null, 'number' => $this->data['destination_number'] ?? null, - 'bic' => $this->data['destination_bic'] ?? null, + 'bic' => $this->data['destination_bic'] ?? null ]; // make new account validator. @@ -416,15 +429,13 @@ class JournalUpdateService { Log::debug('Now in updateType()'); if ($this->hasFields(['type'])) { - $type = 'opening-balance' === $this->data['type'] ? 'opening balance' : $this->data['type']; - Log::debug( - sprintf( - 'Trying to change journal #%d from a %s to a %s.', - $this->transactionJournal->id, - $this->transactionJournal->transactionType->type, - $type - ) - ); + $type = 'opening-balance' === $this->data['type'] ? 'opening balance' : $this->data['type']; + Log::debug(sprintf( + 'Trying to change journal #%d from a %s to a %s.', + $this->transactionJournal->id, + $this->transactionJournal->transactionType->type, + $type + )); /** @var TransactionTypeFactory $typeFactory */ $typeFactory = app(TransactionTypeFactory::class); @@ -448,15 +459,10 @@ class JournalUpdateService private function updateBill(): void { $type = $this->transactionJournal->transactionType->type; - if (( - array_key_exists('bill_id', $this->data) - || array_key_exists('bill_name', $this->data) - ) - && TransactionTypeEnum::WITHDRAWAL->value === $type - ) { - $billId = (int)($this->data['bill_id'] ?? 0); - $billName = (string)($this->data['bill_name'] ?? ''); - $bill = $this->billRepository->findBill($billId, $billName); + if ((array_key_exists('bill_id', $this->data) || array_key_exists('bill_name', $this->data)) && TransactionTypeEnum::WITHDRAWAL->value === $type) { + $billId = (int) ($this->data['bill_id'] ?? 0); + $billName = (string) ($this->data['bill_name'] ?? ''); + $bill = $this->billRepository->findBill($billId, $billName); $this->transactionJournal->bill_id = $bill?->id; Log::debug('Updated bill ID'); } @@ -467,8 +473,8 @@ class JournalUpdateService */ private function updateField(string $fieldName): void { - if (array_key_exists($fieldName, $this->data) && '' !== (string)$this->data[$fieldName]) { - $value = $this->data[$fieldName]; + if (array_key_exists($fieldName, $this->data) && '' !== (string) $this->data[$fieldName]) { + $value = $this->data[$fieldName]; if ('date' === $fieldName) { if (!$value instanceof Carbon) { @@ -484,16 +490,12 @@ class JournalUpdateService // do some parsing. Log::debug(sprintf('Create date value from string "%s".', $value)); $this->transactionJournal->date_tz = $value->format('e'); - $res = $value->gt($this->transactionJournal->date); + $res = $value->gt($this->transactionJournal->date); Log::debug(sprintf('Old date: %s, new date: %s', $this->transactionJournal->date->toW3cString(), $value->toW3cString())); /** @var TransactionJournalMetaFactory $factory */ - $factory = app(TransactionJournalMetaFactory::class); - $set = [ - 'journal' => $this->transactionJournal, - 'name' => '_internal_previous_date', - 'data' => null, - ]; + $factory = app(TransactionJournalMetaFactory::class); + $set = ['journal' => $this->transactionJournal, 'name' => '_internal_previous_date', 'data' => null]; if ($res) { Log::debug('Transaction is set to be AFTER its current date. Save also the "_internal_previous_date"-field.'); $set['data'] = clone $this->transactionJournal->date; @@ -503,7 +505,15 @@ class JournalUpdateService } $factory->updateOrCreate($set); } - event(new TriggeredAuditLog($this->transactionJournal->user, $this->transactionJournal, sprintf('update_%s', $fieldName), $this->transactionJournal->{$fieldName}, $value)); + event( + new TriggeredAuditLog( + $this->transactionJournal->user, + $this->transactionJournal, + sprintf('update_%s', $fieldName), + $this->transactionJournal->{$fieldName}, + $value + ) + ); $this->transactionJournal->{$fieldName} = $value; // @phpstan-ignore-line Log::debug(sprintf('Updated %s', $fieldName)); @@ -553,7 +563,7 @@ class JournalUpdateService { // update notes. if ($this->hasFields(['notes'])) { - $notes = '' === (string)$this->data['notes'] ? null : $this->data['notes']; + $notes = '' === (string) $this->data['notes'] ? null : $this->data['notes']; $this->storeNotes($this->transactionJournal, $notes); } } @@ -583,11 +593,7 @@ class JournalUpdateService if ($this->hasFields([$field])) { $value = '' === $this->data[$field] ? null : $this->data[$field]; Log::debug(sprintf('Field "%s" is present ("%s"), try to update it.', $field, $value)); - $set = [ - 'journal' => $this->transactionJournal, - 'name' => $field, - 'data' => $value, - ]; + $set = ['journal' => $this->transactionJournal, 'name' => $field, 'data' => $value]; $factory->updateOrCreate($set); } } @@ -601,25 +607,17 @@ class JournalUpdateService foreach ($this->metaDate as $field) { if ($this->hasFields([$field])) { try { - $value = '' === (string)$this->data[$field] ? null : new Carbon($this->data[$field]); + $value = '' === (string) $this->data[$field] ? null : new Carbon($this->data[$field]); } catch (InvalidDateException|InvalidFormatException $e) { // @phpstan-ignore-line Log::debug(sprintf('%s is not a valid date value: %s', $this->data[$field], $e->getMessage())); return; } Log::debug(sprintf('Field "%s" is present ("%s"), try to update it.', $field, $value)); - $set = [ - 'journal' => $this->transactionJournal, - 'name' => $field, - 'data' => $value, - ]; + $set = ['journal' => $this->transactionJournal, 'name' => $field, 'data' => $value]; $factory->updateOrCreate($set); // also set date with timezone. - $set = [ - 'journal' => $this->transactionJournal, - 'name' => sprintf('%s_tz', $field), - 'data' => $value?->format('e'), - ]; + $set = ['journal' => $this->transactionJournal, 'name' => sprintf('%s_tz', $field), 'data' => $value?->format('e')]; $factory->updateOrCreate($set); } } @@ -631,19 +629,19 @@ class JournalUpdateService if (!$this->hasFields(['currency_id', 'currency_code'])) { return; } - $currencyId = $this->data['currency_id'] ?? null; - $currencyCode = $this->data['currency_code'] ?? null; - $currency = $this->currencyRepository->findCurrency($currencyId, $currencyCode); + $currencyId = $this->data['currency_id'] ?? null; + $currencyCode = $this->data['currency_code'] ?? null; + $currency = $this->currencyRepository->findCurrency($currencyId, $currencyCode); // update currency everywhere. $this->transactionJournal->transaction_currency_id = $currency->id; $this->transactionJournal->save(); - $source = $this->getSourceTransaction(); - $source->transaction_currency_id = $currency->id; + $source = $this->getSourceTransaction(); + $source->transaction_currency_id = $currency->id; $source->save(); - $dest = $this->getDestinationTransaction(); - $dest->transaction_currency_id = $currency->id; + $dest = $this->getDestinationTransaction(); + $dest->transaction_currency_id = $currency->id; $dest->save(); // refresh transactions. @@ -659,7 +657,7 @@ class JournalUpdateService return; } - $value = $this->data['amount'] ?? ''; + $value = $this->data['amount'] ?? ''; Log::debug(sprintf('[a] Amount is now "%s"', $value)); try { @@ -670,14 +668,14 @@ class JournalUpdateService return; } Log::debug(sprintf('[b] Amount is now "%s"', $value)); - $origSourceTransaction = $this->getSourceTransaction(); - $destTransaction = $this->getDestinationTransaction(); - $originalSourceAmount = $origSourceTransaction->amount; + $origSourceTransaction = $this->getSourceTransaction(); + $destTransaction = $this->getDestinationTransaction(); + $originalSourceAmount = $origSourceTransaction->amount; // $originalDestAmount = $destTransaction->amount; - $origSourceTransaction->amount = Steam::negative($amount); + $origSourceTransaction->amount = Steam::negative($amount); $origSourceTransaction->balance_dirty = true; - $destTransaction->amount = Steam::positive($amount); - $destTransaction->balance_dirty = true; + $destTransaction->amount = Steam::positive($amount); + $destTransaction->balance_dirty = true; $destTransaction->save(); $origSourceTransaction->save(); @@ -686,7 +684,7 @@ class JournalUpdateService $this->destinationTransaction->refresh(); Log::debug(sprintf('Updated amount to "%s"', $amount)); - $group = $this->transactionGroup; + $group = $this->transactionGroup; if (null === $group) { $group = $this->transactionJournal?->transactionGroup; } @@ -699,30 +697,28 @@ class JournalUpdateService return; } Log::debug('Amount was changed, needs audit log entry.'); - $transfer = TransactionTypeEnum::TRANSFER->value === $this->transactionJournal->transactionType->type; + $transfer = TransactionTypeEnum::TRANSFER->value === $this->transactionJournal->transactionType->type; // $withdrawal = TransactionTypeEnum::WITHDRAWAL->value === $this->transactionJournal->transactionType->type; - $deposit = TransactionTypeEnum::DEPOSIT->value === $this->transactionJournal->transactionType->type; - $makePositive = $transfer || $deposit ? true : false; - $recordCurrency = $origSourceTransaction->transactionCurrency; - $originalSourceAmount = $makePositive ? Steam::positive($originalSourceAmount) : Steam::negative($originalSourceAmount); - $value = $makePositive ? Steam::positive($value) : Steam::negative($value); + $deposit = TransactionTypeEnum::DEPOSIT->value === $this->transactionJournal->transactionType->type; + $makePositive = $transfer || $deposit ? true : false; + $recordCurrency = $origSourceTransaction->transactionCurrency; + $originalSourceAmount = $makePositive ? Steam::positive($originalSourceAmount) : Steam::negative($originalSourceAmount); + $value = $makePositive ? Steam::positive($value) : Steam::negative($value); // should not return in NULL but seems to do. - event(new TriggeredAuditLog( - $group->user, - $group, - 'update_amount', - [ - 'currency_symbol' => $recordCurrency->symbol, - 'decimal_places' => $recordCurrency->decimal_places, - 'amount' => $originalSourceAmount, - ], - [ - 'currency_symbol' => $recordCurrency->symbol, - 'decimal_places' => $recordCurrency->decimal_places, - 'amount' => $value, - ] - )); + event( + new TriggeredAuditLog( + $group->user, + $group, + 'update_amount', + [ + 'currency_symbol' => $recordCurrency->symbol, + 'decimal_places' => $recordCurrency->decimal_places, + 'amount' => $originalSourceAmount + ], + ['currency_symbol' => $recordCurrency->symbol, 'decimal_places' => $recordCurrency->decimal_places, 'amount' => $value] + ) + ); } private function updateForeignAmount(): void @@ -740,10 +736,9 @@ class JournalUpdateService $originalSourceAmount = $source->foreign_amount; // find currency in data array - $newForeignId = $this->data['foreign_currency_id'] ?? null; - $newForeignCode = $this->data['foreign_currency_code'] ?? null; - $foreignCurrency = $this->currencyRepository->findCurrencyNull($newForeignId, $newForeignCode) - ?? $foreignCurrency; + $newForeignId = $this->data['foreign_currency_id'] ?? null; + $newForeignCode = $this->data['foreign_currency_code'] ?? null; + $foreignCurrency = $this->currencyRepository->findCurrencyNull($newForeignId, $newForeignCode) ?? $foreignCurrency; // not the same as normal currency if (null !== $foreignCurrency && $foreignCurrency->id === $this->transactionJournal->transaction_currency_id) { @@ -755,26 +750,26 @@ class JournalUpdateService // add foreign currency info to source and destination if possible. if (null !== $foreignCurrency && null !== $foreignAmount) { $source->foreign_currency_id = $foreignCurrency->id; - $source->foreign_amount = Steam::negative($foreignAmount); + $source->foreign_amount = Steam::negative($foreignAmount); $source->save(); // if the transaction is a TRANSFER, and the foreign amount and currency are set (like they seem to be) // the correct fields to update in the destination transaction are NOT the foreign amount and currency // but rather the normal amount and currency. This is new behavior. - $isTransfer = TransactionTypeEnum::TRANSFER->value === $this->transactionJournal->transactionType->type; + $isTransfer = TransactionTypeEnum::TRANSFER->value === $this->transactionJournal->transactionType->type; // also check if it is not between an asset account and a liability, because then the same rule applies. - $isBetween = $this->isBetweenAssetAndLiability(); + $isBetween = $this->isBetweenAssetAndLiability(); if ($isTransfer || $isBetween) { Log::debug('Switch amounts, store in amount and not foreign_amount'); $dest->transaction_currency_id = $foreignCurrency->id; - $dest->amount = Steam::positive($foreignAmount); - $dest->foreign_amount = Steam::positive($source->amount); - $dest->foreign_currency_id = $source->transaction_currency_id; + $dest->amount = Steam::positive($foreignAmount); + $dest->foreign_amount = Steam::positive($source->amount); + $dest->foreign_currency_id = $source->transaction_currency_id; } if (!$isTransfer && !$isBetween) { $dest->foreign_currency_id = $foreignCurrency->id; - $dest->foreign_amount = Steam::positive($foreignAmount); + $dest->foreign_amount = Steam::positive($foreignAmount); } $dest->save(); @@ -785,11 +780,10 @@ class JournalUpdateService $this->sourceTransaction->refresh(); $this->destinationTransaction->refresh(); - // add audit log entry. Log::debug(sprintf('Updated foreign amount to "%s"', $foreignAmount)); - $group = $this->transactionGroup; + $group = $this->transactionGroup; if (null === $group) { $group = $this->transactionJournal?->transactionGroup; } @@ -802,42 +796,36 @@ class JournalUpdateService return; } Log::debug('Amount was changed, needs audit log entry.'); - $transfer = TransactionTypeEnum::TRANSFER->value === $this->transactionJournal->transactionType->type; + $transfer = TransactionTypeEnum::TRANSFER->value === $this->transactionJournal->transactionType->type; // $withdrawal = TransactionTypeEnum::WITHDRAWAL->value === $this->transactionJournal->transactionType->type; - $deposit = TransactionTypeEnum::DEPOSIT->value === $this->transactionJournal->transactionType->type; - $makePositive = $transfer || $deposit ? true : false; - $recordCurrency = $source->foreignCurrency; - $originalSourceAmount = $makePositive ? Steam::positive($originalSourceAmount) : Steam::negative($originalSourceAmount); - $value = $makePositive ? Steam::positive($foreignAmount) : Steam::negative($foreignAmount); + $deposit = TransactionTypeEnum::DEPOSIT->value === $this->transactionJournal->transactionType->type; + $makePositive = $transfer || $deposit ? true : false; + $recordCurrency = $source->foreignCurrency; + $originalSourceAmount = $makePositive ? Steam::positive($originalSourceAmount) : Steam::negative($originalSourceAmount); + $value = $makePositive ? Steam::positive($foreignAmount) : Steam::negative($foreignAmount); // should not return in NULL but seems to do. - event(new TriggeredAuditLog( - $group->user, - $group, - 'update_foreign_amount', - [ - 'currency_symbol' => $recordCurrency->symbol, - 'decimal_places' => $recordCurrency->decimal_places, - 'amount' => $originalSourceAmount, - ], - [ - 'currency_symbol' => $recordCurrency->symbol, - 'decimal_places' => $recordCurrency->decimal_places, - 'amount' => $value, - ] - )); - - - - + event( + new TriggeredAuditLog( + $group->user, + $group, + 'update_foreign_amount', + [ + 'currency_symbol' => $recordCurrency->symbol, + 'decimal_places' => $recordCurrency->decimal_places, + 'amount' => $originalSourceAmount + ], + ['currency_symbol' => $recordCurrency->symbol, 'decimal_places' => $recordCurrency->decimal_places, 'amount' => $value] + ) + ); } if ('0' === $amount) { $source->foreign_currency_id = null; - $source->foreign_amount = null; + $source->foreign_amount = null; $source->save(); - $dest->foreign_currency_id = null; - $dest->foreign_amount = null; + $dest->foreign_currency_id = null; + $dest->foreign_amount = null; $dest->save(); Log::debug(sprintf('Foreign amount is "%s" so remove foreign amount info.', $amount)); @@ -853,10 +841,16 @@ class JournalUpdateService private function isBetweenAssetAndLiability(): bool { /** @var null|Transaction $sourceTransaction */ - $sourceTransaction = $this->transactionJournal->transactions()->where('amount', '<', 0)->first(); + $sourceTransaction = $this->transactionJournal + ->transactions() + ->where('amount', '<', 0) + ->first(); /** @var null|Transaction $destinationTransaction */ - $destinationTransaction = $this->transactionJournal->transactions()->where('amount', '>', 0)->first(); + $destinationTransaction = $this->transactionJournal + ->transactions() + ->where('amount', '>', 0) + ->first(); if (null === $sourceTransaction || null === $destinationTransaction) { Log::warning('Either transaction is false, stop.'); @@ -868,15 +862,15 @@ class JournalUpdateService return false; } - $source = $sourceTransaction->account; - $destination = $destinationTransaction->account; + $source = $sourceTransaction->account; + $destination = $destinationTransaction->account; if (null === $source || null === $destination) { Log::warning('Either is false, stop.'); return false; } - $sourceTypes = [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value]; + $sourceTypes = [AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value]; // source is liability, destination is asset if (in_array($source->accountType->type, $sourceTypes, true) && AccountTypeEnum::ASSET->value === $destination->accountType->type) { diff --git a/app/Services/Internal/Update/RecurrenceUpdateService.php b/app/Services/Internal/Update/RecurrenceUpdateService.php index 83c3856e29..b720b7678a 100644 --- a/app/Services/Internal/Update/RecurrenceUpdateService.php +++ b/app/Services/Internal/Update/RecurrenceUpdateService.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Services\Internal\Update; -use Illuminate\Support\Facades\Log; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Factory\TransactionCurrencyFactory; use FireflyIII\Models\Note; @@ -34,6 +33,7 @@ use FireflyIII\Models\RecurrenceTransaction; use FireflyIII\Services\Internal\Support\RecurringTransactionTrait; use FireflyIII\Services\Internal\Support\TransactionTypeTrait; use FireflyIII\User; +use Illuminate\Support\Facades\Log; /** * Class RecurrenceUpdateService @@ -66,13 +66,13 @@ class RecurrenceUpdateService $recurrence->description = $info['description']; } if (array_key_exists('first_date', $info)) { - $recurrence->first_date = $info['first_date']; + $recurrence->first_date = $info['first_date']; $recurrence->first_date_tz = $info['first_date']?->format('e'); } if (array_key_exists('repeat_until', $info)) { - $recurrence->repeat_until = $info['repeat_until']; + $recurrence->repeat_until = $info['repeat_until']; $recurrence->repeat_until_tz = $info['repeat_until']?->format('e'); - $recurrence->repetitions = 0; + $recurrence->repetitions = 0; } if (array_key_exists('nr_of_repetitions', $info)) { if (0 !== (int) $info['nr_of_repetitions']) { @@ -145,16 +145,11 @@ class RecurrenceUpdateService // loop all and try to match them: Log::debug('Loop and find'); foreach ($repetitions as $current) { - $match = $this->matchRepetition($recurrence, $current); + $match = $this->matchRepetition($recurrence, $current); if (!$match instanceof RecurrenceRepetition) { throw new FireflyException('Cannot match recurring repetition to existing repetition. Not sure what to do. Break.'); } - $fields = [ - 'type' => 'repetition_type', - 'moment' => 'repetition_moment', - 'skip' => 'repetition_skip', - 'weekend' => 'weekend', - ]; + $fields = ['type' => 'repetition_type', 'moment' => 'repetition_moment', 'skip' => 'repetition_skip', 'weekend' => 'weekend']; foreach ($fields as $field => $column) { if (array_key_exists($field, $current)) { $match->{$column} = $current[$field]; @@ -164,7 +159,7 @@ class RecurrenceUpdateService } } - private function matchRepetition(Recurrence $recurrence, array $data): ?RecurrenceRepetition + private function matchRepetition(Recurrence $recurrence, array $data): null|RecurrenceRepetition { $originalCount = $recurrence->recurrenceRepetitions()->count(); if (1 === $originalCount) { @@ -174,14 +169,8 @@ class RecurrenceUpdateService return $recurrence->recurrenceRepetitions()->first(); } // find it: - $fields = [ - 'id' => 'id', - 'type' => 'repetition_type', - 'moment' => 'repetition_moment', - 'skip' => 'repetition_skip', - 'weekend' => 'weekend', - ]; - $query = $recurrence->recurrenceRepetitions(); + $fields = ['id' => 'id', 'type' => 'repetition_type', 'moment' => 'repetition_moment', 'skip' => 'repetition_skip', 'weekend' => 'weekend']; + $query = $recurrence->recurrenceRepetitions(); foreach ($fields as $field => $column) { if (array_key_exists($field, $data)) { $query->where($column, $data[$field]); @@ -200,7 +189,7 @@ class RecurrenceUpdateService private function updateTransactions(Recurrence $recurrence, array $transactions): void { Log::debug('Now in updateTransactions()'); - $originalCount = $recurrence->recurrenceTransactions()->count(); + $originalCount = $recurrence->recurrenceTransactions()->count(); Log::debug(sprintf('Original count is %d', $originalCount)); if (0 === count($transactions)) { // won't drop transactions, rather avoid. @@ -215,22 +204,16 @@ class RecurrenceUpdateService foreach ($transactions as $ii => $submittedTransaction) { if (array_key_exists('id', $submittedTransaction) && (int) $originalTransaction['id'] === (int) $submittedTransaction['id']) { Log::debug(sprintf('Match original transaction #%d with an entry in the submitted array.', $originalTransaction['id'])); - $combinations[] = [ - 'original' => $originalTransaction, - 'submitted' => $submittedTransaction, - ]; + $combinations[] = ['original' => $originalTransaction, 'submitted' => $submittedTransaction]; unset($originalTransactions[$i], $transactions[$ii]); } } } // If one left of both we can match those as well and presto. if (1 === count($originalTransactions) && 1 === count($transactions)) { - $first = array_shift($originalTransactions); + $first = array_shift($originalTransactions); Log::debug(sprintf('One left of each, link them (ID is #%d)', $first['id'])); - $combinations[] = [ - 'original' => $first, - 'submitted' => array_shift($transactions), - ]; + $combinations[] = ['original' => $first, 'submitted' => array_shift($transactions)]; unset($first); } // if they are both empty, we can safely loop all combinations and update them. @@ -261,7 +244,7 @@ class RecurrenceUpdateService $currencyFactory = app(TransactionCurrencyFactory::class); /** @var RecurrenceTransaction $transaction */ - $transaction = $recurrence->recurrenceTransactions()->find($original['id']); + $transaction = $recurrence->recurrenceTransactions()->find($original['id']); Log::debug(sprintf('Now in updateCombination(#%d)', $original['id'])); // loop all and try to match them: @@ -293,14 +276,14 @@ class RecurrenceUpdateService } // update fields that are part of the recurring transaction itself. - $fields = [ + $fields = [ 'source_id' => 'source_id', 'destination_id' => 'destination_id', 'amount' => 'amount', 'foreign_amount' => 'foreign_amount', 'description' => 'description', 'currency_id' => 'transaction_currency_id', - 'foreign_currency_id' => 'foreign_currency_id', + 'foreign_currency_id' => 'foreign_currency_id' ]; foreach ($fields as $field => $column) { if (array_key_exists($field, $submitted)) { @@ -320,7 +303,7 @@ class RecurrenceUpdateService if (array_key_exists('category_name', $submitted) && '' === (string) $submitted['category_name']) { Log::debug('Category name is submitted but is empty. Set category to be empty.'); $submitted['category_name'] = null; - $submitted['category_id'] = 0; + $submitted['category_id'] = 0; } if (array_key_exists('category_id', $submitted)) { diff --git a/app/Services/Password/PwndVerifierV2.php b/app/Services/Password/PwndVerifierV2.php index cc6b0c6381..d915d926d9 100644 --- a/app/Services/Password/PwndVerifierV2.php +++ b/app/Services/Password/PwndVerifierV2.php @@ -23,10 +23,10 @@ declare(strict_types=1); namespace FireflyIII\Services\Password; -use Illuminate\Support\Facades\Log; use GuzzleHttp\Client; use GuzzleHttp\Exception\GuzzleException; use GuzzleHttp\Exception\RequestException; +use Illuminate\Support\Facades\Log; use SensitiveParameter; /** @@ -44,13 +44,7 @@ class PwndVerifierV2 implements Verifier $prefix = substr($hash, 0, 5); $rest = substr($hash, 5); $url = sprintf('https://api.pwnedpasswords.com/range/%s', $prefix); - $opt = [ - 'headers' => [ - 'User-Agent' => sprintf('Firefly III v%s', config('firefly.version')), - 'Add-Padding' => 'true', - ], - 'timeout' => 3.1415, - ]; + $opt = ['headers' => ['User-Agent' => sprintf('Firefly III v%s', config('firefly.version')), 'Add-Padding' => 'true'], 'timeout' => 3.1415]; Log::debug(sprintf('hash prefix is %s', $prefix)); Log::debug(sprintf('rest is %s', $rest)); diff --git a/app/Services/Webhook/StandardWebhookSender.php b/app/Services/Webhook/StandardWebhookSender.php index ab9a82108a..44b025bccf 100644 --- a/app/Services/Webhook/StandardWebhookSender.php +++ b/app/Services/Webhook/StandardWebhookSender.php @@ -43,7 +43,7 @@ use function Safe\json_encode; class StandardWebhookSender implements WebhookSenderInterface { private WebhookMessage $message; - private int $version = 1; + private int $version = 1; public function getVersion(): int { @@ -59,7 +59,7 @@ class StandardWebhookSender implements WebhookSenderInterface { // have the signature generator generate a signature. If it fails, the error thrown will // end up in send() to be caught. - $signatureGenerator = app(SignatureGeneratorInterface::class); + $signatureGenerator = app(SignatureGeneratorInterface::class); $this->message->sent = true; $this->message->save(); @@ -69,13 +69,13 @@ class StandardWebhookSender implements WebhookSenderInterface Log::error('Did not send message because of a Firefly III Exception.'); Log::error($e->getMessage()); Log::error($e->getTraceAsString()); - $attempt = new WebhookAttempt(); + $attempt = new WebhookAttempt(); $attempt->webhookMessage()->associate($this->message); - $attempt->status_code = 0; - $attempt->logs = sprintf('Exception: %s', $e->getMessage()); + $attempt->status_code = 0; + $attempt->logs = sprintf('Exception: %s', $e->getMessage()); $attempt->save(); $this->message->errored = true; - $this->message->sent = false; + $this->message->sent = false; $this->message->save(); return; @@ -89,18 +89,18 @@ class StandardWebhookSender implements WebhookSenderInterface Log::error('Did not send message because of a JSON error.'); Log::error($e->getMessage()); Log::error($e->getTraceAsString()); - $attempt = new WebhookAttempt(); + $attempt = new WebhookAttempt(); $attempt->webhookMessage()->associate($this->message); - $attempt->status_code = 0; - $attempt->logs = sprintf('Json error: %s', $e->getMessage()); + $attempt->status_code = 0; + $attempt->logs = sprintf('Json error: %s', $e->getMessage()); $attempt->save(); $this->message->errored = true; - $this->message->sent = false; + $this->message->sent = false; $this->message->save(); return; } - $options = [ + $options = [ 'body' => $json, 'headers' => [ 'Content-Type' => 'application/json', @@ -108,10 +108,10 @@ class StandardWebhookSender implements WebhookSenderInterface 'Signature' => $signature, 'connect_timeout' => 3.14, 'User-Agent' => sprintf('FireflyIII/%s', config('firefly.version')), - 'timeout' => 10, - ], + 'timeout' => 10 + ] ]; - $client = new Client(); + $client = new Client(); try { $res = $client->request('POST', $this->message->webhook->url, $options); @@ -120,22 +120,22 @@ class StandardWebhookSender implements WebhookSenderInterface Log::error($e->getMessage()); Log::error($e->getTraceAsString()); - $logs = sprintf("%s\n%s", $e->getMessage(), $e->getTraceAsString()); + $logs = sprintf("%s\n%s", $e->getMessage(), $e->getTraceAsString()); $this->message->errored = true; - $this->message->sent = false; + $this->message->sent = false; $this->message->save(); - $attempt = new WebhookAttempt(); + $attempt = new WebhookAttempt(); $attempt->webhookMessage()->associate($this->message); - $attempt->status_code = 0; + $attempt->status_code = 0; if (method_exists($e, 'hasResponse') && method_exists($e, 'getResponse')) { $attempt->status_code = $e->hasResponse() ? $e->getResponse()->getStatusCode() : 0; Log::error(sprintf('The status code of the error response is: %d', $attempt->status_code)); - $body = (string) ($e->hasResponse() ? $e->getResponse()->getBody() : ''); + $body = (string) ($e->hasResponse() ? $e->getResponse()->getBody() : ''); Log::error(sprintf('The body of the error response is: %s', $body)); } - $attempt->logs = $logs; + $attempt->logs = $logs; $attempt->save(); return; diff --git a/app/Support/Amount.php b/app/Support/Amount.php index ce5e0942fe..83214af1d2 100644 --- a/app/Support/Amount.php +++ b/app/Support/Amount.php @@ -28,6 +28,7 @@ use FireflyIII\Models\Transaction; use FireflyIII\Models\TransactionCurrency; use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\UserGroup; +use FireflyIII\Support\Facades\FireflyConfig; use FireflyIII\Support\Facades\Preferences; use FireflyIII\Support\Facades\Steam; use FireflyIII\Support\Singleton\PreferencesSingleton; @@ -35,7 +36,6 @@ use FireflyIII\User; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; use NumberFormatter; -use FireflyIII\Support\Facades\FireflyConfig; /** * Class Amount. @@ -60,11 +60,11 @@ class Amount // there are five possible positions for the "+" or "-" sign (if it is even used) // pos_a and pos_e could be the ( and ) symbol. - $posA = ''; // before everything - $posB = ''; // before currency symbol - $posC = ''; // after currency symbol - $posD = ''; // before amount - $posE = ''; // after everything + $posA = ''; // before everything + $posB = ''; // before currency symbol + $posC = ''; // after currency symbol + $posD = ''; // before amount + $posE = ''; // after everything // format would be (currency before amount) // AB%sC_D%vE @@ -106,19 +106,21 @@ class Amount } if ($csPrecedes) { - return $posA.$posB.'%s'.$posC.$space.$posD.'%v'.$posE; + return $posA . $posB . '%s' . $posC . $space . $posD . '%v' . $posE; } - return $posA.$posD.'%v'.$space.$posB.'%s'.$posC.$posE; + return $posA . $posD . '%v' . $space . $posB . '%s' . $posC . $posE; } - public function convertToPrimary(?User $user = null): bool + public function convertToPrimary(null|User $user = null): bool { $instance = PreferencesSingleton::getInstance(); if (!$user instanceof User) { $pref = $instance->getPreference('convert_to_primary_no_user'); if (null === $pref) { - $res = true === Preferences::get('convert_to_primary', false)->data && true === FireflyConfig::get('enable_exchange_rates', config('cer.enabled'))->data; + $res = + true === Preferences::get('convert_to_primary', false)->data + && true === FireflyConfig::get('enable_exchange_rates', config('cer.enabled'))->data; $instance->setPreference('convert_to_primary_no_user', $res); return $res; @@ -126,10 +128,12 @@ class Amount return $pref; } - $key = sprintf('convert_to_primary_%d', $user->id); - $pref = $instance->getPreference($key); + $key = sprintf('convert_to_primary_%d', $user->id); + $pref = $instance->getPreference($key); if (null === $pref) { - $res = true === Preferences::getForUser($user, 'convert_to_primary', false)->data && true === FireflyConfig::get('enable_exchange_rates', config('cer.enabled'))->data; + $res = + true === Preferences::getForUser($user, 'convert_to_primary', false)->data + && true === FireflyConfig::get('enable_exchange_rates', config('cer.enabled'))->data; $instance->setPreference($key, $res); return $res; @@ -144,12 +148,12 @@ class Amount * * @throws FireflyException */ - public function formatAnything(TransactionCurrency $format, string $amount, ?bool $coloured = null): string + public function formatAnything(TransactionCurrency $format, string $amount, null|bool $coloured = null): string { return $this->formatFlat($format->symbol, $format->decimal_places, $amount, $coloured); } - public function formatByCurrencyId(int $currencyId, string $amount, ?bool $coloured = null): string + public function formatByCurrencyId(int $currencyId, string $amount, null|bool $coloured = null): string { $format = $this->getTransactionCurrencyById($currencyId); @@ -162,18 +166,18 @@ class Amount * * @throws FireflyException */ - public function formatFlat(string $symbol, int $decimalPlaces, string $amount, ?bool $coloured = null): string + public function formatFlat(string $symbol, int $decimalPlaces, string $amount, null|bool $coloured = null): string { - $amount = Steam::anonymous() ? '0' : $amount; - $locale = Steam::getLocale(); - $rounded = Steam::bcround($amount, $decimalPlaces); + $amount = Steam::anonymous() ? '0' : $amount; + $locale = Steam::getLocale(); + $rounded = Steam::bcround($amount, $decimalPlaces); $coloured ??= true; - $fmt = new NumberFormatter($locale, NumberFormatter::CURRENCY); + $fmt = new NumberFormatter($locale, NumberFormatter::CURRENCY); $fmt->setSymbol(NumberFormatter::CURRENCY_SYMBOL, $symbol); $fmt->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, $decimalPlaces); $fmt->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $decimalPlaces); - $result = (string)$fmt->format((float)$rounded); // intentional float + $result = (string) $fmt->format((float) $rounded); // intentional float if ($coloured) { if (1 === bccomp($rounded, '0')) { @@ -206,12 +210,13 @@ class Amount $amount = $journal[$field] ?? '0'; // Log::debug(sprintf('Field is %s, amount is %s', $field, $amount)); // fallback, the transaction has a foreign amount in $currency. - if ($convertToPrimary && null !== $journal['foreign_amount'] && $currency->id === (int)$journal['foreign_currency_id']) { + if ($convertToPrimary && null !== $journal['foreign_amount'] && $currency->id === (int) $journal['foreign_currency_id']) { $amount = $journal['foreign_amount']; + // Log::debug(sprintf('Overruled, amount is now %s', $amount)); } - return (string)$amount; + return (string) $amount; } /** @@ -220,19 +225,19 @@ class Amount */ public function getAmountFromJournalObject(TransactionJournal $journal): string { - $convertToPrimary = $this->convertToPrimary(); - $currency = $this->getPrimaryCurrency(); - $field = $convertToPrimary && $currency->id !== $journal->transaction_currency_id ? 'pc_amount' : 'amount'; + $convertToPrimary = $this->convertToPrimary(); + $currency = $this->getPrimaryCurrency(); + $field = $convertToPrimary && $currency->id !== $journal->transaction_currency_id ? 'pc_amount' : 'amount'; /** @var null|Transaction $sourceTransaction */ $sourceTransaction = $journal->transactions()->where('amount', '<', 0)->first(); if (null === $sourceTransaction) { return '0'; } - $amount = $sourceTransaction->{$field} ?? '0'; - if ((int)$sourceTransaction->foreign_currency_id === $currency->id) { + $amount = $sourceTransaction->{$field} ?? '0'; + if ((int) $sourceTransaction->foreign_currency_id === $currency->id) { // use foreign amount instead! - $amount = (string)$sourceTransaction->foreign_amount; // hard coded to be foreign amount. + $amount = (string) $sourceTransaction->foreign_amount; // hard coded to be foreign amount. } return $amount; @@ -263,11 +268,7 @@ class Amount return [ 'mon_decimal_point' => $config['mon_decimal_point'], 'mon_thousands_sep' => $config['mon_thousands_sep'], - 'format' => [ - 'pos' => $positive, - 'neg' => $negative, - 'zero' => $positive, - ], + 'format' => ['pos' => $positive, 'neg' => $negative, 'zero' => $positive] ]; } @@ -286,7 +287,7 @@ class Amount public function getPrimaryCurrencyByUserGroup(UserGroup $userGroup): TransactionCurrency { - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty('getPrimaryCurrencyByGroup'); $cache->addProperty($userGroup->id); if ($cache->has()) { @@ -316,7 +317,7 @@ class Amount $key = sprintf('transaction_currency_%s', $code); /** @var null|TransactionCurrency $pref */ - $pref = $instance->getPreference($key); + $pref = $instance->getPreference($key); if (null !== $pref) { return $pref; } @@ -343,7 +344,7 @@ class Amount $key = sprintf('transaction_currency_%d', $currencyId); /** @var null|TransactionCurrency $pref */ - $pref = $instance->getPreference($key); + $pref = $instance->getPreference($key); if (null !== $pref) { return $pref; } @@ -361,8 +362,7 @@ class Amount private function getLocaleField(array $info, string $field): bool { - return (is_bool($info[$field]) && $info[$field]) - || (is_int($info[$field]) && 1 === $info[$field]); + return is_bool($info[$field]) && $info[$field] || is_int($info[$field]) && 1 === $info[$field]; } /** @@ -371,20 +371,20 @@ class Amount private function getLocaleInfo(): array { // get config from preference, not from translation: - $locale = Steam::getLocale(); - $array = Steam::getLocaleArray($locale); + $locale = Steam::getLocale(); + $array = Steam::getLocaleArray($locale); setlocale(LC_MONETARY, $array); - $info = localeconv(); + $info = localeconv(); // correct variables - $info['n_cs_precedes'] = $this->getLocaleField($info, 'n_cs_precedes'); - $info['p_cs_precedes'] = $this->getLocaleField($info, 'p_cs_precedes'); + $info['n_cs_precedes'] = $this->getLocaleField($info, 'n_cs_precedes'); + $info['p_cs_precedes'] = $this->getLocaleField($info, 'p_cs_precedes'); - $info['n_sep_by_space'] = $this->getLocaleField($info, 'n_sep_by_space'); - $info['p_sep_by_space'] = $this->getLocaleField($info, 'p_sep_by_space'); + $info['n_sep_by_space'] = $this->getLocaleField($info, 'n_sep_by_space'); + $info['p_sep_by_space'] = $this->getLocaleField($info, 'p_sep_by_space'); - $fmt = new NumberFormatter($locale, NumberFormatter::CURRENCY); + $fmt = new NumberFormatter($locale, NumberFormatter::CURRENCY); $info['mon_decimal_point'] = $fmt->getSymbol(NumberFormatter::MONETARY_SEPARATOR_SYMBOL); $info['mon_thousands_sep'] = $fmt->getSymbol(NumberFormatter::MONETARY_GROUPING_SEPARATOR_SYMBOL); diff --git a/app/Support/Authentication/RemoteUserGuard.php b/app/Support/Authentication/RemoteUserGuard.php index 2d74a0d8c5..81f4fa7464 100644 --- a/app/Support/Authentication/RemoteUserGuard.php +++ b/app/Support/Authentication/RemoteUserGuard.php @@ -39,13 +39,15 @@ use Illuminate\Support\Facades\Log; class RemoteUserGuard implements Guard { protected Application $application; - protected ?User $user = null; + protected null|User $user = null; /** * Create a new authentication guard. */ - public function __construct(protected UserProvider $provider, Application $app) - { + public function __construct( + protected UserProvider $provider, + Application $app + ) { $app->get('request'); // Log::debug(sprintf('Created RemoteUserGuard for %s "%s"', $request?->getMethod(), $request?->getRequestUri())); $this->application = $app; @@ -60,8 +62,8 @@ class RemoteUserGuard implements Guard return; } // Get the user identifier from $_SERVER or apache filtered headers - $header = config('auth.guard_header', 'REMOTE_USER'); - $userID = request()->server($header) ?? null; + $header = config('auth.guard_header', 'REMOTE_USER'); + $userID = request()->server($header) ?? null; if (function_exists('apache_request_headers')) { Log::debug('Use apache_request_headers to find user ID.'); @@ -80,10 +82,10 @@ class RemoteUserGuard implements Guard $retrievedUser = $this->provider->retrieveById($userID); // store email address if present in header and not already set. - $header = config('auth.guard_email'); + $header = config('auth.guard_email'); if (null !== $header) { - $emailAddress = (string)(request()->server($header) ?? apache_request_headers()[$header] ?? null); + $emailAddress = (string) (request()->server($header) ?? apache_request_headers()[$header] ?? null); $preference = Preferences::getForUser($retrievedUser, 'remote_guard_alt_email'); if ('' !== $emailAddress && null === $preference && $emailAddress !== $userID) { @@ -96,7 +98,7 @@ class RemoteUserGuard implements Guard } Log::debug(sprintf('Result of getting user from provider: %s', $retrievedUser->email)); - $this->user = $retrievedUser; + $this->user = $retrievedUser; } public function check(): bool @@ -141,7 +143,7 @@ class RemoteUserGuard implements Guard Log::error(sprintf('Did not set user at %s', __METHOD__)); } - public function user(): ?User + public function user(): null|User { // Log::debug(sprintf('Now at %s', __METHOD__)); $user = $this->user; diff --git a/app/Support/Authentication/RemoteUserProvider.php b/app/Support/Authentication/RemoteUserProvider.php index 4dc6681460..8149ed3b13 100644 --- a/app/Support/Authentication/RemoteUserProvider.php +++ b/app/Support/Authentication/RemoteUserProvider.php @@ -24,13 +24,13 @@ declare(strict_types=1); namespace FireflyIII\Support\Authentication; -use Illuminate\Support\Facades\Log; use FireflyIII\Console\Commands\Correction\CreatesGroupMemberships; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Role; use FireflyIII\User; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\UserProvider; +use Illuminate\Support\Facades\Log; use Illuminate\Support\Str; use Override; use SensitiveParameter; @@ -53,7 +53,7 @@ class RemoteUserProvider implements UserProvider * * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function retrieveByCredentials(array $credentials): ?Authenticatable + public function retrieveByCredentials(array $credentials): null|Authenticatable { Log::debug(sprintf('Now at %s', __METHOD__)); @@ -71,14 +71,7 @@ class RemoteUserProvider implements UserProvider $user = User::where('email', $identifier)->first(); if (null === $user) { Log::debug(sprintf('User with email "%s" not found. Will be created.', $identifier)); - $user = User::create( - [ - 'blocked' => false, - 'blocked_code' => null, - 'email' => $identifier, - 'password' => bcrypt(Str::random(64)), - ] - ); + $user = User::create(['blocked' => false, 'blocked_code' => null, 'email' => $identifier, 'password' => bcrypt(Str::random(64))]); // if this is the first user, give them admin as well. if (1 === User::count()) { $roleObject = Role::where('name', 'owner')->first(); @@ -101,7 +94,7 @@ class RemoteUserProvider implements UserProvider * * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function retrieveByToken($identifier, #[SensitiveParameter] $token): ?Authenticatable + public function retrieveByToken($identifier, #[SensitiveParameter] $token): null|Authenticatable { Log::debug(sprintf('Now at %s', __METHOD__)); diff --git a/app/Support/Balance.php b/app/Support/Balance.php index 96fc7d35e6..fcd47d1d36 100644 --- a/app/Support/Balance.php +++ b/app/Support/Balance.php @@ -50,25 +50,24 @@ class Balance return $cache->get(); } - $query = Transaction::whereIn('transactions.account_id', $accounts->pluck('id')->toArray()) + $query = Transaction::whereIn('transactions.account_id', $accounts->pluck('id')->toArray()) ->leftJoin('transaction_journals', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->orderBy('transaction_journals.date', 'desc') ->orderBy('transaction_journals.order', 'asc') ->orderBy('transaction_journals.description', 'desc') ->orderBy('transactions.amount', 'desc') - ->where('transaction_journals.date', '<=', $date) - ; + ->where('transaction_journals.date', '<=', $date); - $result = $query->get(['transactions.account_id', 'transactions.transaction_currency_id', 'transactions.balance_after']); + $result = $query->get(['transactions.account_id', 'transactions.transaction_currency_id', 'transactions.balance_after']); foreach ($result as $entry) { - $accountId = (int)$entry->account_id; - $currencyId = (int)$entry->transaction_currency_id; + $accountId = (int) $entry->account_id; + $currencyId = (int) $entry->transaction_currency_id; $currencies[$currencyId] ??= Amount::getTransactionCurrencyById($currencyId); - $return[$accountId] ??= []; + $return[$accountId] ??= []; if (array_key_exists($currencyId, $return[$accountId])) { continue; } - $return[$accountId][$currencyId] = ['currency' => $currencies[$currencyId], 'balance' => $entry->balance_after, 'date' => clone $date]; + $return[$accountId][$currencyId] = ['currency' => $currencies[$currencyId], 'balance' => $entry->balance_after, 'date' => clone $date]; } return $return; diff --git a/app/Support/Binder/AccountList.php b/app/Support/Binder/AccountList.php index e2d77aa9c3..ad6daac31e 100644 --- a/app/Support/Binder/AccountList.php +++ b/app/Support/Binder/AccountList.php @@ -23,10 +23,10 @@ declare(strict_types=1); namespace FireflyIII\Support\Binder; -use Illuminate\Support\Facades\Log; use FireflyIII\Enums\AccountTypeEnum; use Illuminate\Routing\Route; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Log; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** @@ -43,24 +43,31 @@ class AccountList implements BinderInterface $collection = new Collection(); if ('allAssetAccounts' === $value) { /** @var Collection $collection */ - $collection = auth()->user()->accounts() + $collection = auth() + ->user() + ->accounts() ->leftJoin('account_types', 'account_types.id', '=', 'accounts.account_type_id') - ->whereIn('account_types.type', [AccountTypeEnum::ASSET->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value]) + ->whereIn('account_types.type', [ + AccountTypeEnum::ASSET->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::MORTGAGE->value + ]) ->orderBy('accounts.name', 'ASC') - ->get(['accounts.*']) - ; + ->get(['accounts.*']); } if ('allAssetAccounts' !== $value) { - $incoming = array_map(\intval(...), explode(',', $value)); - $list = array_merge(array_unique($incoming), [0]); + $incoming = array_map(\intval(...), explode(',', $value)); + $list = array_merge(array_unique($incoming), [0]); /** @var Collection $collection */ - $collection = auth()->user()->accounts() + $collection = auth() + ->user() + ->accounts() ->leftJoin('account_types', 'account_types.id', '=', 'accounts.account_type_id') ->whereIn('accounts.id', $list) ->orderBy('accounts.name', 'ASC') - ->get(['accounts.*']) - ; + ->get(['accounts.*']); } if ($collection->count() > 0) { diff --git a/app/Support/Binder/BudgetList.php b/app/Support/Binder/BudgetList.php index adaef6db1f..14038f699b 100644 --- a/app/Support/Binder/BudgetList.php +++ b/app/Support/Binder/BudgetList.php @@ -23,10 +23,10 @@ declare(strict_types=1); namespace FireflyIII\Support\Binder; -use Illuminate\Support\Facades\Log; use FireflyIII\Models\Budget; use Illuminate\Routing\Route; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Log; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** @@ -41,14 +41,10 @@ class BudgetList implements BinderInterface { if (auth()->check()) { if ('allBudgets' === $value) { - return auth()->user()->budgets()->where('active', true) - ->orderBy('order', 'ASC') - ->orderBy('name', 'ASC') - ->get() - ; + return auth()->user()->budgets()->where('active', true)->orderBy('order', 'ASC')->orderBy('name', 'ASC')->get(); } - $list = array_unique(array_map(\intval(...), explode(',', $value))); + $list = array_unique(array_map(\intval(...), explode(',', $value))); if (0 === count($list)) { // @phpstan-ignore-line Log::warning('Budget list count is zero, return 404.'); @@ -57,11 +53,7 @@ class BudgetList implements BinderInterface } /** @var Collection $collection */ - $collection = auth()->user()->budgets() - ->where('active', true) - ->whereIn('id', $list) - ->get() - ; + $collection = auth()->user()->budgets()->where('active', true)->whereIn('id', $list)->get(); // add empty budget if applicable. if (in_array(0, $list, true)) { diff --git a/app/Support/Binder/CLIToken.php b/app/Support/Binder/CLIToken.php index 14a5ae6172..66486aa356 100644 --- a/app/Support/Binder/CLIToken.php +++ b/app/Support/Binder/CLIToken.php @@ -24,10 +24,10 @@ declare(strict_types=1); namespace FireflyIII\Support\Binder; -use FireflyIII\Support\Facades\Preferences; -use Illuminate\Support\Facades\Log; use FireflyIII\Repositories\User\UserRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; use Illuminate\Routing\Route; +use Illuminate\Support\Facades\Log; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** diff --git a/app/Support/Binder/CategoryList.php b/app/Support/Binder/CategoryList.php index 1cd4eb0e3a..3e7b4c93a2 100644 --- a/app/Support/Binder/CategoryList.php +++ b/app/Support/Binder/CategoryList.php @@ -40,22 +40,16 @@ class CategoryList implements BinderInterface { if (auth()->check()) { if ('allCategories' === $value) { - return auth()->user()->categories() - ->orderBy('name', 'ASC') - ->get() - ; + return auth()->user()->categories()->orderBy('name', 'ASC')->get(); } - $list = array_unique(array_map(\intval(...), explode(',', $value))); + $list = array_unique(array_map(\intval(...), explode(',', $value))); if (0 === count($list)) { // @phpstan-ignore-line throw new NotFoundHttpException(); } /** @var Collection $collection */ - $collection = auth()->user()->categories() - ->whereIn('id', $list) - ->get() - ; + $collection = auth()->user()->categories()->whereIn('id', $list)->get(); // add empty category if applicable. if (in_array(0, $list, true)) { diff --git a/app/Support/Binder/Date.php b/app/Support/Binder/Date.php index 26b955716c..812641c8a2 100644 --- a/app/Support/Binder/Date.php +++ b/app/Support/Binder/Date.php @@ -23,12 +23,12 @@ declare(strict_types=1); namespace FireflyIII\Support\Binder; -use Illuminate\Support\Facades\Log; use Carbon\Carbon; use Carbon\Exceptions\InvalidDateException; use Carbon\Exceptions\InvalidFormatException; use FireflyIII\Helpers\Fiscal\FiscalHelperInterface; use Illuminate\Routing\Route; +use Illuminate\Support\Facades\Log; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** @@ -44,21 +44,21 @@ class Date implements BinderInterface /** @var FiscalHelperInterface $fiscalHelper */ $fiscalHelper = app(FiscalHelperInterface::class); - $magicWords = [ - 'currentMonthStart' => today(config('app.timezone'))->startOfMonth(), - 'currentMonthEnd' => today(config('app.timezone'))->endOfMonth(), - 'currentYearStart' => today(config('app.timezone'))->startOfYear(), - 'currentYearEnd' => today(config('app.timezone'))->endOfYear(), + $magicWords = [ + 'currentMonthStart' => today(config('app.timezone'))->startOfMonth(), + 'currentMonthEnd' => today(config('app.timezone'))->endOfMonth(), + 'currentYearStart' => today(config('app.timezone'))->startOfYear(), + 'currentYearEnd' => today(config('app.timezone'))->endOfYear(), - 'previousMonthStart' => today(config('app.timezone'))->startOfMonth()->subDay()->startOfMonth(), - 'previousMonthEnd' => today(config('app.timezone'))->startOfMonth()->subDay()->endOfMonth(), - 'previousYearStart' => today(config('app.timezone'))->startOfYear()->subDay()->startOfYear(), - 'previousYearEnd' => today(config('app.timezone'))->startOfYear()->subDay()->endOfYear(), + 'previousMonthStart' => today(config('app.timezone'))->startOfMonth()->subDay()->startOfMonth(), + 'previousMonthEnd' => today(config('app.timezone'))->startOfMonth()->subDay()->endOfMonth(), + 'previousYearStart' => today(config('app.timezone'))->startOfYear()->subDay()->startOfYear(), + 'previousYearEnd' => today(config('app.timezone'))->startOfYear()->subDay()->endOfYear(), 'currentFiscalYearStart' => $fiscalHelper->startOfFiscalYear(today(config('app.timezone'))), 'currentFiscalYearEnd' => $fiscalHelper->endOfFiscalYear(today(config('app.timezone'))), 'previousFiscalYearStart' => $fiscalHelper->startOfFiscalYear(today(config('app.timezone')))->subYear(), - 'previousFiscalYearEnd' => $fiscalHelper->endOfFiscalYear(today(config('app.timezone')))->subYear(), + 'previousFiscalYearEnd' => $fiscalHelper->endOfFiscalYear(today(config('app.timezone')))->subYear() ]; if (array_key_exists($value, $magicWords)) { $return = $magicWords[$value]; diff --git a/app/Support/Binder/DynamicConfigKey.php b/app/Support/Binder/DynamicConfigKey.php index 42b4db8c9b..b71474bd08 100644 --- a/app/Support/Binder/DynamicConfigKey.php +++ b/app/Support/Binder/DynamicConfigKey.php @@ -32,19 +32,18 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; */ class DynamicConfigKey { - public static array $accepted - = [ - 'configuration.is_demo_site', // boolean - 'configuration.permission_update_check', // -1, 0 or 1 (never asked, no permission, permission) - 'configuration.single_user_mode', // boolean - 'configuration.last_update_check', // timestamp - 'configuration.enable_exchange_rates', // boolean - 'configuration.use_running_balance', // boolean - 'configuration.enable_external_map', // boolean - 'configuration.enable_external_rates', // boolean - 'configuration.allow_webhooks', // boolean - 'configuration.valid_url_protocols', // string ("http,https") - ]; + public static array $accepted = [ + 'configuration.is_demo_site', // boolean + 'configuration.permission_update_check', // -1, 0 or 1 (never asked, no permission, permission) + 'configuration.single_user_mode', // boolean + 'configuration.last_update_check', // timestamp + 'configuration.enable_exchange_rates', // boolean + 'configuration.use_running_balance', // boolean + 'configuration.enable_external_map', // boolean + 'configuration.enable_external_rates', // boolean + 'configuration.allow_webhooks', // boolean + 'configuration.valid_url_protocols' // string ("http,https") + ]; /** * @throws NotFoundHttpException diff --git a/app/Support/Binder/EitherConfigKey.php b/app/Support/Binder/EitherConfigKey.php index ed41ac53ca..0b34c86642 100644 --- a/app/Support/Binder/EitherConfigKey.php +++ b/app/Support/Binder/EitherConfigKey.php @@ -32,38 +32,37 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; */ class EitherConfigKey { - public static array $static - = [ - // currency conversion - 'cer.enabled', + public static array $static = [ + // currency conversion + 'cer.enabled', - // firefly iii settings - 'firefly.version', - 'firefly.default_location', - 'firefly.account_to_transaction', - 'firefly.allowed_opposing_types', - 'firefly.accountRoles', - 'firefly.valid_liabilities', - 'firefly.interest_periods', - 'firefly.bill_periods', - 'firefly.enable_external_map', - 'firefly.expected_source_types', - 'firefly.credit_card_types', - 'firefly.languages', - 'app.timezone', - 'firefly.valid_view_ranges', - 'firefly.preselected_accounts', + // firefly iii settings + 'firefly.version', + 'firefly.default_location', + 'firefly.account_to_transaction', + 'firefly.allowed_opposing_types', + 'firefly.accountRoles', + 'firefly.valid_liabilities', + 'firefly.interest_periods', + 'firefly.bill_periods', + 'firefly.enable_external_map', + 'firefly.expected_source_types', + 'firefly.credit_card_types', + 'firefly.languages', + 'app.timezone', + 'firefly.valid_view_ranges', + 'firefly.preselected_accounts', - // triggers and actions: - 'firefly.rule-actions', - 'firefly.context-rule-actions', - 'search.operators', + // triggers and actions: + 'firefly.rule-actions', + 'firefly.context-rule-actions', + 'search.operators', - // webhooks - 'webhook.triggers', - 'webhook.responses', - 'webhook.deliveries', - ]; + // webhooks + 'webhook.triggers', + 'webhook.responses', + 'webhook.deliveries' + ]; /** * @throws NotFoundHttpException diff --git a/app/Support/Binder/JournalList.php b/app/Support/Binder/JournalList.php index 0ecdad1fff..f76bfb999f 100644 --- a/app/Support/Binder/JournalList.php +++ b/app/Support/Binder/JournalList.php @@ -39,15 +39,20 @@ class JournalList implements BinderInterface public static function routeBinder(string $value, Route $route): array { if (auth()->check()) { - $list = self::parseList($value); + $list = self::parseList($value); // get the journals by using the collector. /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); - $collector->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value, TransactionTypeEnum::RECONCILIATION->value]); + $collector->setTypes([ + TransactionTypeEnum::WITHDRAWAL->value, + TransactionTypeEnum::DEPOSIT->value, + TransactionTypeEnum::TRANSFER->value, + TransactionTypeEnum::RECONCILIATION->value + ]); $collector->withCategoryInformation()->withBudgetInformation()->withTagInformation()->withAccountInformation(); $collector->setJournalIds($list); - $result = $collector->getExtractedJournals(); + $result = $collector->getExtractedJournals(); if (0 === count($result)) { throw new NotFoundHttpException(); } diff --git a/app/Support/Binder/TagList.php b/app/Support/Binder/TagList.php index 6894fa7c30..3fd514a654 100644 --- a/app/Support/Binder/TagList.php +++ b/app/Support/Binder/TagList.php @@ -42,12 +42,9 @@ class TagList implements BinderInterface { if (auth()->check()) { if ('allTags' === $value) { - return auth()->user()->tags() - ->orderBy('tag', 'ASC') - ->get() - ; + return auth()->user()->tags()->orderBy('tag', 'ASC')->get(); } - $list = array_unique(array_map(\strtolower(...), explode(',', $value))); + $list = array_unique(array_map(\strtolower(...), explode(',', $value))); Log::debug('List of tags is', $list); if (0 === count($list)) { // @phpstan-ignore-line @@ -59,24 +56,22 @@ class TagList implements BinderInterface /** @var TagRepositoryInterface $repository */ $repository = app(TagRepositoryInterface::class); $repository->setUser(auth()->user()); - $allTags = $repository->get(); + $allTags = $repository->get(); - $collection = $allTags->filter( - static function (Tag $tag) use ($list): bool { - if (in_array(strtolower($tag->tag), $list, true)) { - Log::debug(sprintf('TagList: (string) found tag #%d ("%s") in list.', $tag->id, $tag->tag)); + $collection = $allTags->filter(static function (Tag $tag) use ($list): bool { + if (in_array(strtolower($tag->tag), $list, true)) { + Log::debug(sprintf('TagList: (string) found tag #%d ("%s") in list.', $tag->id, $tag->tag)); - return true; - } - if (in_array((string)$tag->id, $list, true)) { - Log::debug(sprintf('TagList: (id) found tag #%d ("%s") in list.', $tag->id, $tag->tag)); - - return true; - } - - return false; + return true; } - ); + if (in_array((string) $tag->id, $list, true)) { + Log::debug(sprintf('TagList: (id) found tag #%d ("%s") in list.', $tag->id, $tag->tag)); + + return true; + } + + return false; + }); if ($collection->count() > 0) { return $collection; diff --git a/app/Support/Binder/TagOrId.php b/app/Support/Binder/TagOrId.php index 685119eff3..48f766a3d5 100644 --- a/app/Support/Binder/TagOrId.php +++ b/app/Support/Binder/TagOrId.php @@ -23,10 +23,10 @@ declare(strict_types=1); namespace FireflyIII\Support\Binder; -use Illuminate\Support\Facades\Log; use FireflyIII\Models\Tag; use FireflyIII\Repositories\Tag\TagRepositoryInterface; use Illuminate\Routing\Route; +use Illuminate\Support\Facades\Log; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** @@ -41,9 +41,9 @@ class TagOrId implements BinderInterface $repository = app(TagRepositoryInterface::class); $repository->setUser(auth()->user()); - $result = $repository->findByTag($value); + $result = $repository->findByTag($value); if (null === $result) { - $result = $repository->find((int)$value); + $result = $repository->find((int) $value); } if (null !== $result) { return $result; diff --git a/app/Support/Binder/UserGroupAccount.php b/app/Support/Binder/UserGroupAccount.php index c395655e87..da10ad580c 100644 --- a/app/Support/Binder/UserGroupAccount.php +++ b/app/Support/Binder/UserGroupAccount.php @@ -41,10 +41,7 @@ class UserGroupAccount implements BinderInterface if (auth()->check()) { /** @var User $user */ $user = auth()->user(); - $account = Account::where('id', (int)$value) - ->where('user_group_id', $user->user_group_id) - ->first() - ; + $account = Account::where('id', (int) $value)->where('user_group_id', $user->user_group_id)->first(); if (null !== $account) { return $account; } diff --git a/app/Support/Binder/UserGroupBill.php b/app/Support/Binder/UserGroupBill.php index bd2489965e..6c7974d7a2 100644 --- a/app/Support/Binder/UserGroupBill.php +++ b/app/Support/Binder/UserGroupBill.php @@ -41,10 +41,7 @@ class UserGroupBill implements BinderInterface if (auth()->check()) { /** @var User $user */ $user = auth()->user(); - $currency = Bill::where('id', (int)$value) - ->where('user_group_id', $user->user_group_id) - ->first() - ; + $currency = Bill::where('id', (int) $value)->where('user_group_id', $user->user_group_id)->first(); if (null !== $currency) { return $currency; } diff --git a/app/Support/Binder/UserGroupExchangeRate.php b/app/Support/Binder/UserGroupExchangeRate.php index 862564fde1..69e0c81211 100644 --- a/app/Support/Binder/UserGroupExchangeRate.php +++ b/app/Support/Binder/UserGroupExchangeRate.php @@ -38,10 +38,7 @@ class UserGroupExchangeRate implements BinderInterface if (auth()->check()) { /** @var User $user */ $user = auth()->user(); - $rate = CurrencyExchangeRate::where('id', (int)$value) - ->where('user_group_id', $user->user_group_id) - ->first() - ; + $rate = CurrencyExchangeRate::where('id', (int) $value)->where('user_group_id', $user->user_group_id)->first(); if (null !== $rate) { return $rate; } diff --git a/app/Support/Binder/UserGroupTransaction.php b/app/Support/Binder/UserGroupTransaction.php index fbbf5c1f43..cdd487a231 100644 --- a/app/Support/Binder/UserGroupTransaction.php +++ b/app/Support/Binder/UserGroupTransaction.php @@ -38,10 +38,7 @@ class UserGroupTransaction implements BinderInterface if (auth()->check()) { /** @var User $user */ $user = auth()->user(); - $group = TransactionGroup::where('id', (int)$value) - ->where('user_group_id', $user->user_group_id) - ->first() - ; + $group = TransactionGroup::where('id', (int) $value)->where('user_group_id', $user->user_group_id)->first(); if (null !== $group) { return $group; } diff --git a/app/Support/CacheProperties.php b/app/Support/CacheProperties.php index 1414e07c91..ebb2381982 100644 --- a/app/Support/CacheProperties.php +++ b/app/Support/CacheProperties.php @@ -23,8 +23,8 @@ declare(strict_types=1); namespace FireflyIII\Support; -use FireflyIII\Support\Facades\Preferences; use Carbon\Carbon; +use FireflyIII\Support\Facades\Preferences; use FireflyIII\Support\Facades\Steam; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Cache; @@ -37,7 +37,7 @@ use function Safe\json_encode; */ class CacheProperties { - protected string $hash = ''; + protected string $hash = ''; protected Collection $properties; public function __construct() @@ -91,13 +91,13 @@ class CacheProperties private function hash(): void { - $content = ''; + $content = ''; foreach ($this->properties as $property) { try { $content = sprintf('%s%s', $content, json_encode($property, JSON_THROW_ON_ERROR)); } catch (JsonException) { // @ignoreException - $content = sprintf('%s%s', $content, hash('sha256', (string)Carbon::now()->getTimestamp())); + $content = sprintf('%s%s', $content, hash('sha256', (string) Carbon::now()->getTimestamp())); } } $this->hash = substr(hash('sha256', $content), 0, 16); diff --git a/app/Support/Calendar/Calculator.php b/app/Support/Calendar/Calculator.php index 5e08fd614d..6fd2361ee4 100644 --- a/app/Support/Calendar/Calculator.php +++ b/app/Support/Calendar/Calculator.php @@ -33,9 +33,10 @@ use SplObjectStorage; */ class Calculator { - public const int DEFAULT_INTERVAL = 1; - private static ?SplObjectStorage $intervalMap = null; // @phpstan-ignore-line - private static array $intervals = []; + public const int DEFAULT_INTERVAL = 1; + + private static null|SplObjectStorage $intervalMap = null; // @phpstan-ignore-line + private static array $intervals = []; private function containsInterval(Periodicity $periodicity): bool { @@ -49,7 +50,7 @@ class Calculator } self::$intervalMap = new SplObjectStorage(); foreach (Periodicity::cases() as $interval) { - $periodicityClass = sprintf('%s\Periodicity\%s', __NAMESPACE__, $interval->name); + $periodicityClass = sprintf('%s\Periodicity\%s', __NAMESPACE__, $interval->name); self::$intervals[] = $interval->name; self::$intervalMap->attach($interval, new $periodicityClass()); } diff --git a/app/Support/Chart/Budget/FrontpageChartGenerator.php b/app/Support/Chart/Budget/FrontpageChartGenerator.php index ed27174151..7c20dc5dc5 100644 --- a/app/Support/Chart/Budget/FrontpageChartGenerator.php +++ b/app/Support/Chart/Budget/FrontpageChartGenerator.php @@ -30,24 +30,24 @@ use FireflyIII\Models\TransactionCurrency; use FireflyIII\Repositories\Budget\BudgetLimitRepositoryInterface; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Repositories\Budget\OperationsRepositoryInterface; +use FireflyIII\Support\Facades\Steam; use FireflyIII\User; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; -use FireflyIII\Support\Facades\Steam; /** * Class FrontpageChartGenerator */ class FrontpageChartGenerator { - public bool $convertToPrimary = false; - public TransactionCurrency $default; - protected OperationsRepositoryInterface $opsRepository; + public bool $convertToPrimary = false; + public TransactionCurrency $default; + protected OperationsRepositoryInterface $opsRepository; private readonly BudgetLimitRepositoryInterface $blRepository; - private readonly BudgetRepositoryInterface $budgetRepository; - private Carbon $end; - private string $monthAndDayFormat = ''; - private Carbon $start; + private readonly BudgetRepositoryInterface $budgetRepository; + private Carbon $end; + private string $monthAndDayFormat = ''; + private Carbon $start; /** * FrontpageChartGenerator constructor. @@ -55,8 +55,8 @@ class FrontpageChartGenerator public function __construct() { $this->budgetRepository = app(BudgetRepositoryInterface::class); - $this->blRepository = app(BudgetLimitRepositoryInterface::class); - $this->opsRepository = app(OperationsRepositoryInterface::class); + $this->blRepository = app(BudgetLimitRepositoryInterface::class); + $this->opsRepository = app(OperationsRepositoryInterface::class); } /** @@ -69,9 +69,9 @@ class FrontpageChartGenerator Log::debug('Now in generate for budget chart.'); $budgets = $this->budgetRepository->getActiveBudgets(); $data = [ - ['label' => (string)trans('firefly.spent_in_budget'), 'entries' => [], 'type' => 'bar'], - ['label' => (string)trans('firefly.left_to_spend'), 'entries' => [], 'type' => 'bar'], - ['label' => (string)trans('firefly.overspent'), 'entries' => [], 'type' => 'bar'], + ['label' => (string) trans('firefly.spent_in_budget'), 'entries' => [], 'type' => 'bar'], + ['label' => (string) trans('firefly.left_to_spend'), 'entries' => [], 'type' => 'bar'], + ['label' => (string) trans('firefly.overspent'), 'entries' => [], 'type' => 'bar'] ]; // loop al budgets: @@ -103,8 +103,8 @@ class FrontpageChartGenerator $this->blRepository->setUser($user); $this->opsRepository->setUser($user); - $locale = Steam::getLocale(); - $this->monthAndDayFormat = (string)trans('config.month_and_day_js', [], $locale); + $locale = Steam::getLocale(); + $this->monthAndDayFormat = (string) trans('config.month_and_day_js', [], $locale); } /** @@ -133,10 +133,10 @@ class FrontpageChartGenerator /** @var array $entry */ foreach ($spent as $entry) { - $title = sprintf('%s (%s)', $budget->name, $entry['currency_name']); - $data[0]['entries'][$title] = bcmul((string)$entry['sum'], '-1'); // spent - $data[1]['entries'][$title] = 0; // left to spend - $data[2]['entries'][$title] = 0; // overspent + $title = sprintf('%s (%s)', $budget->name, $entry['currency_name']); + $data[0]['entries'][$title] = bcmul((string) $entry['sum'], '-1'); // spent + $data[1]['entries'][$title] = 0; // left to spend + $data[2]['entries'][$title] = 0; // overspent } return $data; @@ -181,7 +181,7 @@ class FrontpageChartGenerator Log::debug(sprintf('Processing limit #%d with %s %s', $limit->id, $limit->transactionCurrency->code, $limit->amount)); } - $spent = $this->opsRepository->sumExpenses($limit->start_date, $limit->end_date, null, new Collection()->push($budget), $currency); + $spent = $this->opsRepository->sumExpenses($limit->start_date, $limit->end_date, null, new Collection()->push($budget), $currency); Log::debug(sprintf('Spent array has %d entries.', count($spent))); /** @var array $entry */ @@ -208,7 +208,7 @@ class FrontpageChartGenerator */ private function processRow(array $data, Budget $budget, BudgetLimit $limit, array $entry): array { - $title = sprintf('%s (%s)', $budget->name, $entry['currency_name']); + $title = sprintf('%s (%s)', $budget->name, $entry['currency_name']); Log::debug(sprintf('Title is "%s"', $title)); if ($limit->start_date->startOfDay()->ne($this->start->startOfDay()) || $limit->end_date->startOfDay()->ne($this->end->startOfDay())) { $title = sprintf( @@ -219,22 +219,28 @@ class FrontpageChartGenerator $limit->end_date->isoFormat($this->monthAndDayFormat) ); } - $usePrimary = $this->convertToPrimary && $this->default->id !== $limit->transaction_currency_id; - $amount = $limit->amount; + $usePrimary = $this->convertToPrimary && $this->default->id !== $limit->transaction_currency_id; + $amount = $limit->amount; Log::debug(sprintf('Amount is "%s".', $amount)); if ($usePrimary && $limit->transaction_currency_id !== $this->default->id) { $amount = $limit->native_amount; Log::debug(sprintf('Amount is now "%s".', $amount)); } - $amount ??= '0'; - $sumSpent = bcmul((string)$entry['sum'], '-1'); // spent + $amount ??= '0'; + $sumSpent = bcmul((string) $entry['sum'], '-1'); // spent $data[0]['entries'][$title] ??= '0'; $data[1]['entries'][$title] ??= '0'; $data[2]['entries'][$title] ??= '0'; - $data[0]['entries'][$title] = bcadd((string)$data[0]['entries'][$title], 1 === bccomp($sumSpent, $amount) ? $amount : $sumSpent); // spent - $data[1]['entries'][$title] = bcadd((string)$data[1]['entries'][$title], 1 === bccomp($amount, $sumSpent) ? bcadd((string)$entry['sum'], $amount) : '0'); // left to spent - $data[2]['entries'][$title] = bcadd((string)$data[2]['entries'][$title], 1 === bccomp($amount, $sumSpent) ? '0' : bcmul(bcadd((string)$entry['sum'], $amount), '-1')); // overspent + $data[0]['entries'][$title] = bcadd((string) $data[0]['entries'][$title], 1 === bccomp($sumSpent, $amount) ? $amount : $sumSpent); // spent + $data[1]['entries'][$title] = bcadd( + (string) $data[1]['entries'][$title], + 1 === bccomp($amount, $sumSpent) ? bcadd((string) $entry['sum'], $amount) : '0' + ); // left to spent + $data[2]['entries'][$title] = bcadd( + (string) $data[2]['entries'][$title], + 1 === bccomp($amount, $sumSpent) ? '0' : bcmul(bcadd((string) $entry['sum'], $amount), '-1') + ); // overspent Log::debug(sprintf('Amount [spent] is now %s.', $data[0]['entries'][$title])); Log::debug(sprintf('Amount [left] is now %s.', $data[1]['entries'][$title])); diff --git a/app/Support/Chart/Category/FrontpageChartGenerator.php b/app/Support/Chart/Category/FrontpageChartGenerator.php index 655f44092b..775ac9e7d6 100644 --- a/app/Support/Chart/Category/FrontpageChartGenerator.php +++ b/app/Support/Chart/Category/FrontpageChartGenerator.php @@ -42,38 +42,46 @@ class FrontpageChartGenerator { use AugumentData; - public bool $convertToPrimary = false; - public TransactionCurrency $primaryCurrency; - private AccountRepositoryInterface $accountRepos; - private array $currencies = []; + public bool $convertToPrimary = false; + public TransactionCurrency $primaryCurrency; + private AccountRepositoryInterface $accountRepos; + private array $currencies = []; private NoCategoryRepositoryInterface $noCatRepos; private OperationsRepositoryInterface $opsRepos; - private CategoryRepositoryInterface $repository; + private CategoryRepositoryInterface $repository; /** * FrontpageChartGenerator constructor. */ - public function __construct(private Carbon $start, private Carbon $end) - { - $this->repository = app(CategoryRepositoryInterface::class); + public function __construct( + private Carbon $start, + private Carbon $end + ) { + $this->repository = app(CategoryRepositoryInterface::class); $this->accountRepos = app(AccountRepositoryInterface::class); - $this->opsRepos = app(OperationsRepositoryInterface::class); - $this->noCatRepos = app(NoCategoryRepositoryInterface::class); + $this->opsRepos = app(OperationsRepositoryInterface::class); + $this->noCatRepos = app(NoCategoryRepositoryInterface::class); } public function generate(): array { Log::debug(sprintf('Now in %s', __METHOD__)); - $categories = $this->repository->getCategories(); - $accounts = $this->accountRepos->getAccountsByType([AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::ASSET->value, AccountTypeEnum::DEFAULT->value]); - $collection = $this->collectExpensesAll($categories, $accounts); + $categories = $this->repository->getCategories(); + $accounts = $this->accountRepos->getAccountsByType([ + AccountTypeEnum::DEBT->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::MORTGAGE->value, + AccountTypeEnum::ASSET->value, + AccountTypeEnum::DEFAULT->value + ]); + $collection = $this->collectExpensesAll($categories, $accounts); // collect for no-category: - $noCategory = $this->collectNoCatExpenses($accounts); - $collection = array_merge($collection, $noCategory); + $noCategory = $this->collectNoCatExpenses($accounts); + $collection = array_merge($collection, $noCategory); // sort temp array by amount. - $amounts = array_column($collection, 'sum_float'); + $amounts = array_column($collection, 'sum_float'); array_multisort($amounts, SORT_ASC, $collection); $currencyData = $this->createCurrencyGroups($collection); @@ -83,14 +91,14 @@ class FrontpageChartGenerator private function addCurrency(array $currency): void { - $currencyId = (int)$currency['currency_id']; + $currencyId = (int) $currency['currency_id']; $this->currencies[$currencyId] ??= [ 'currency_id' => $currencyId, 'currency_name' => $currency['currency_name'], 'currency_symbol' => $currency['currency_symbol'], 'currency_code' => $currency['currency_code'], - 'currency_decimal_places' => $currency['currency_decimal_places'], + 'currency_decimal_places' => $currency['currency_decimal_places'] ]; } @@ -109,8 +117,8 @@ class FrontpageChartGenerator $tempData[] = [ 'name' => $category->name, 'sum' => $currency['sum'], - 'sum_float' => round((float)$currency['sum'], $currency['currency_decimal_places']), - 'currency_id' => (int)$currency['currency_id'], + 'sum_float' => round((float) $currency['sum'], $currency['currency_decimal_places']), + 'currency_id' => (int) $currency['currency_id'] ]; } } @@ -125,10 +133,10 @@ class FrontpageChartGenerator foreach ($noCatExp as $currency) { $this->addCurrency($currency); $tempData[] = [ - 'name' => trans('firefly.no_category'), - 'sum' => $currency['sum'], - 'sum_float' => round((float)$currency['sum'], $currency['currency_decimal_places'] ?? 2), // intentional float - 'currency_id' => (int)$currency['currency_id'], + 'name' => trans('firefly.no_category'), + 'sum' => $currency['sum'], + 'sum_float' => round((float) $currency['sum'], $currency['currency_decimal_places'] ?? 2), // intentional float + 'currency_id' => (int) $currency['currency_id'] ]; } @@ -144,12 +152,12 @@ class FrontpageChartGenerator * @var array $currency */ foreach ($this->currencies as $currencyId => $currency) { - $key = sprintf('spent-%d', $currencyId); + $key = sprintf('spent-%d', $currencyId); $return[$key] = [ - 'label' => sprintf('%s (%s)', (string)trans('firefly.spent'), $currency['currency_name']), + 'label' => sprintf('%s (%s)', (string) trans('firefly.spent'), $currency['currency_name']), 'type' => 'bar', 'currency_symbol' => $currency['currency_symbol'], - 'entries' => $names, + 'entries' => $names ]; } @@ -160,10 +168,10 @@ class FrontpageChartGenerator { /** @var array $array */ foreach ($monetaryData as $array) { - $direction = $array['sum_float'] < 0 ? 'spent' : 'earned'; - $key = sprintf('%s-%d', $direction, $array['currency_id']); - $category = $array['name']; - $amount = $array['sum_float'] < 0 ? $array['sum_float'] * -1 : $array['sum_float']; + $direction = $array['sum_float'] < 0 ? 'spent' : 'earned'; + $key = sprintf('%s-%d', $direction, $array['currency_id']); + $category = $array['name']; + $amount = $array['sum_float'] < 0 ? $array['sum_float'] * -1 : $array['sum_float']; $currencyData[$key]['entries'][$category] = $amount; } diff --git a/app/Support/Chart/Category/WholePeriodChartGenerator.php b/app/Support/Chart/Category/WholePeriodChartGenerator.php index ffea514655..8557528b8a 100644 --- a/app/Support/Chart/Category/WholePeriodChartGenerator.php +++ b/app/Support/Chart/Category/WholePeriodChartGenerator.php @@ -24,14 +24,14 @@ declare(strict_types=1); namespace FireflyIII\Support\Chart\Category; -use FireflyIII\Support\Facades\Navigation; use Carbon\Carbon; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Models\Category; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Category\OperationsRepositoryInterface; -use Illuminate\Support\Collection; +use FireflyIII\Support\Facades\Navigation; use FireflyIII\Support\Facades\Steam; +use Illuminate\Support\Collection; /** * Class WholePeriodChartGenerator @@ -42,68 +42,74 @@ class WholePeriodChartGenerator public function generate(Category $category, Carbon $start, Carbon $end): array { - $collection = new Collection()->push($category); + $collection = new Collection()->push($category); /** @var OperationsRepositoryInterface $opsRepository */ - $opsRepository = app(OperationsRepositoryInterface::class); + $opsRepository = app(OperationsRepositoryInterface::class); /** @var AccountRepositoryInterface $accountRepository */ $accountRepository = app(AccountRepositoryInterface::class); - $types = [AccountTypeEnum::DEFAULT->value, AccountTypeEnum::ASSET->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value]; - $accounts = $accountRepository->getAccountsByType($types); - $step = $this->calculateStep($start, $end); - $chartData = []; - $spent = []; - $earned = []; + $types = [ + AccountTypeEnum::DEFAULT->value, + AccountTypeEnum::ASSET->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::MORTGAGE->value + ]; + $accounts = $accountRepository->getAccountsByType($types); + $step = $this->calculateStep($start, $end); + $chartData = []; + $spent = []; + $earned = []; - $current = clone $start; + $current = clone $start; while ($current <= $end) { - $key = $current->format('Y-m-d'); - $currentEnd = Navigation::endOfPeriod($current, $step); - $spent[$key] = $opsRepository->sumExpenses($current, $currentEnd, $accounts, $collection); + $key = $current->format('Y-m-d'); + $currentEnd = Navigation::endOfPeriod($current, $step); + $spent[$key] = $opsRepository->sumExpenses($current, $currentEnd, $accounts, $collection); $earned[$key] = $opsRepository->sumIncome($current, $currentEnd, $accounts, $collection); - $current = Navigation::addPeriod($current, $step); + $current = Navigation::addPeriod($current, $step); } - $currencies = $this->extractCurrencies($spent) + $this->extractCurrencies($earned); + $currencies = $this->extractCurrencies($spent) + $this->extractCurrencies($earned); // generate chart data (for each currency) /** @var array $currency */ foreach ($currencies as $currency) { - $code = $currency['currency_code']; - $name = $currency['currency_name']; - $chartData[sprintf('spent-in-%s', $code)] = [ - 'label' => (string)trans('firefly.box_spent_in_currency', ['currency' => $name]), + $code = $currency['currency_code']; + $name = $currency['currency_name']; + $chartData[sprintf('spent-in-%s', $code)] = [ + 'label' => (string) trans('firefly.box_spent_in_currency', ['currency' => $name]), 'entries' => [], 'type' => 'bar', - 'backgroundColor' => 'rgba(219, 68, 55, 0.5)', // red + 'backgroundColor' => 'rgba(219, 68, 55, 0.5)' // red ]; $chartData[sprintf('earned-in-%s', $code)] = [ - 'label' => (string)trans('firefly.box_earned_in_currency', ['currency' => $name]), + 'label' => (string) trans('firefly.box_earned_in_currency', ['currency' => $name]), 'entries' => [], 'type' => 'bar', - 'backgroundColor' => 'rgba(0, 141, 76, 0.5)', // green + 'backgroundColor' => 'rgba(0, 141, 76, 0.5)' // green ]; } - $current = clone $start; + $current = clone $start; while ($current <= $end) { - $key = $current->format('Y-m-d'); - $label = Navigation::periodShow($current, $step); + $key = $current->format('Y-m-d'); + $label = Navigation::periodShow($current, $step); /** @var array $currency */ foreach ($currencies as $currency) { - $code = $currency['currency_code']; - $currencyId = $currency['currency_id']; - $spentInfoKey = sprintf('spent-in-%s', $code); - $earnedInfoKey = sprintf('earned-in-%s', $code); - $spentAmount = $spent[$key][$currencyId]['sum'] ?? '0'; - $earnedAmount = $earned[$key][$currencyId]['sum'] ?? '0'; - $chartData[$spentInfoKey]['entries'][$label] = Steam::bcround($spentAmount, $currency['currency_decimal_places']); + $code = $currency['currency_code']; + $currencyId = $currency['currency_id']; + $spentInfoKey = sprintf('spent-in-%s', $code); + $earnedInfoKey = sprintf('earned-in-%s', $code); + $spentAmount = $spent[$key][$currencyId]['sum'] ?? '0'; + $earnedAmount = $earned[$key][$currencyId]['sum'] ?? '0'; + $chartData[$spentInfoKey]['entries'][$label] = Steam::bcround($spentAmount, $currency['currency_decimal_places']); $chartData[$earnedInfoKey]['entries'][$label] = Steam::bcround($earnedAmount, $currency['currency_decimal_places']); } $current = Navigation::addPeriod($current, $step); @@ -146,7 +152,7 @@ class WholePeriodChartGenerator 'currency_name' => $currencyRow['currency_name'], 'currency_symbol' => $currencyRow['currency_symbol'], 'currency_code' => $currencyRow['currency_code'], - 'currency_decimal_places' => $currencyRow['currency_decimal_places'], + 'currency_decimal_places' => $currencyRow['currency_decimal_places'] ]; } } diff --git a/app/Support/Chart/ChartData.php b/app/Support/Chart/ChartData.php index e3b086295b..2de1fe0fae 100644 --- a/app/Support/Chart/ChartData.php +++ b/app/Support/Chart/ChartData.php @@ -39,12 +39,12 @@ class ChartData public function add(array $data): void { if (array_key_exists('currency_id', $data)) { - $data['currency_id'] = (string)$data['currency_id']; + $data['currency_id'] = (string) $data['currency_id']; } if (array_key_exists('primary_currency_id', $data)) { - $data['primary_currency_id'] = (string)$data['primary_currency_id']; + $data['primary_currency_id'] = (string) $data['primary_currency_id']; } - $required = ['start', 'date', 'end', 'entries']; + $required = ['start', 'date', 'end', 'entries']; foreach ($required as $field) { if (!array_key_exists($field, $data)) { throw new FireflyException(sprintf('Data-set is missing the "%s"-variable.', $field)); diff --git a/app/Support/ChartColour.php b/app/Support/ChartColour.php index 9e938b9946..464037126d 100644 --- a/app/Support/ChartColour.php +++ b/app/Support/ChartColour.php @@ -31,31 +31,30 @@ class ChartColour /** * @var array */ - public static $colours - = [ - [53, 124, 165], - [0, 141, 76], - [219, 139, 11], - [202, 25, 90], - [85, 82, 153], - [66, 133, 244], - [219, 68, 55], - [244, 180, 0], - [15, 157, 88], - [171, 71, 188], - [0, 172, 193], - [255, 112, 67], - [158, 157, 36], - [92, 107, 192], - [240, 98, 146], - [0, 121, 107], - [194, 24, 91], - ]; + public static $colours = [ + [53, 124, 165], + [0, 141, 76], + [219, 139, 11], + [202, 25, 90], + [85, 82, 153], + [66, 133, 244], + [219, 68, 55], + [244, 180, 0], + [15, 157, 88], + [171, 71, 188], + [0, 172, 193], + [255, 112, 67], + [158, 157, 36], + [92, 107, 192], + [240, 98, 146], + [0, 121, 107], + [194, 24, 91] + ]; public static function getColour(int $index): string { $index %= count(self::$colours); - $row = self::$colours[$index]; + $row = self::$colours[$index]; return sprintf('rgba(%d, %d, %d, 0.7)', $row[0], $row[1], $row[2]); } diff --git a/app/Support/Cronjobs/AbstractCronjob.php b/app/Support/Cronjobs/AbstractCronjob.php index 43f4fa579c..cddaae44c1 100644 --- a/app/Support/Cronjobs/AbstractCronjob.php +++ b/app/Support/Cronjobs/AbstractCronjob.php @@ -31,13 +31,13 @@ use Carbon\Carbon; */ abstract class AbstractCronjob { - public bool $jobErrored = false; - public bool $jobFired = false; - public bool $jobSucceeded = false; - public ?string $message = null; - public int $timeBetweenRuns = 43200; + public bool $jobErrored = false; + public bool $jobFired = false; + public bool $jobSucceeded = false; + public null|string $message = null; + public int $timeBetweenRuns = 43200; protected Carbon $date; - protected bool $force = false; + protected bool $force = false; /** * AbstractCronjob constructor. @@ -51,7 +51,7 @@ abstract class AbstractCronjob final public function setDate(Carbon $date): void { - $newDate = clone $date; + $newDate = clone $date; $this->date = $newDate; } diff --git a/app/Support/Cronjobs/AutoBudgetCronjob.php b/app/Support/Cronjobs/AutoBudgetCronjob.php index c9722c87fd..3112ee29b5 100644 --- a/app/Support/Cronjobs/AutoBudgetCronjob.php +++ b/app/Support/Cronjobs/AutoBudgetCronjob.php @@ -24,11 +24,11 @@ declare(strict_types=1); namespace FireflyIII\Support\Cronjobs; -use FireflyIII\Support\Facades\Preferences; use Carbon\Carbon; use FireflyIII\Jobs\CreateAutoBudgetLimits; use FireflyIII\Models\Configuration; use FireflyIII\Support\Facades\FireflyConfig; +use FireflyIII\Support\Facades\Preferences; use Illuminate\Support\Facades\Log; /** @@ -40,7 +40,7 @@ class AutoBudgetCronjob extends AbstractCronjob { /** @var Configuration $config */ $config = FireflyConfig::get('last_ab_job', 0); - $lastTime = (int)$config->data; + $lastTime = (int) $config->data; $diff = now(config('app.timezone'))->getTimestamp() - $lastTime; $diffForHumans = now(config('app.timezone'))->diffForHumans(Carbon::createFromTimestamp($lastTime), null, true); if (0 === $lastTime) { @@ -71,17 +71,17 @@ class AutoBudgetCronjob extends AbstractCronjob Log::info(sprintf('Will now fire auto budget cron job task for date "%s".', $this->date->format('Y-m-d'))); /** @var CreateAutoBudgetLimits $job */ - $job = app(CreateAutoBudgetLimits::class, [$this->date]); + $job = app(CreateAutoBudgetLimits::class, [$this->date]); $job->setDate($this->date); $job->handle(); // get stuff from job: - $this->jobFired = true; - $this->jobErrored = false; + $this->jobFired = true; + $this->jobErrored = false; $this->jobSucceeded = true; - $this->message = 'Auto-budget cron job fired successfully.'; + $this->message = 'Auto-budget cron job fired successfully.'; - FireflyConfig::set('last_ab_job', (int)$this->date->format('U')); + FireflyConfig::set('last_ab_job', (int) $this->date->format('U')); Log::info('Done with auto budget cron job task.'); } } diff --git a/app/Support/Cronjobs/BillWarningCronjob.php b/app/Support/Cronjobs/BillWarningCronjob.php index be6d9e2f0d..00989aaca8 100644 --- a/app/Support/Cronjobs/BillWarningCronjob.php +++ b/app/Support/Cronjobs/BillWarningCronjob.php @@ -24,12 +24,12 @@ declare(strict_types=1); namespace FireflyIII\Support\Cronjobs; -use FireflyIII\Support\Facades\Preferences; use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Jobs\WarnAboutBills; use FireflyIII\Models\Configuration; use FireflyIII\Support\Facades\FireflyConfig; +use FireflyIII\Support\Facades\Preferences; use Illuminate\Support\Facades\Log; /** @@ -46,7 +46,7 @@ class BillWarningCronjob extends AbstractCronjob /** @var Configuration $config */ $config = FireflyConfig::get('last_bw_job', 0); - $lastTime = (int)$config->data; + $lastTime = (int) $config->data; $diff = now(config('app.timezone'))->getTimestamp() - $lastTime; $diffForHumans = now(config('app.timezone'))->diffForHumans(Carbon::createFromTimestamp($lastTime), null, true); @@ -58,9 +58,9 @@ class BillWarningCronjob extends AbstractCronjob Log::info(sprintf('It has been %s since the bill notification cron-job has fired.', $diffForHumans)); if (false === $this->force) { Log::info('The cron-job will not fire now.'); - $this->message = sprintf('It has been %s since the bill notification cron-job has fired. It will not fire now.', $diffForHumans); - $this->jobFired = false; - $this->jobErrored = false; + $this->message = sprintf('It has been %s since the bill notification cron-job has fired. It will not fire now.', $diffForHumans); + $this->jobFired = false; + $this->jobErrored = false; $this->jobSucceeded = false; return; @@ -83,19 +83,19 @@ class BillWarningCronjob extends AbstractCronjob Log::info(sprintf('Will now fire bill notification job task for date "%s".', $this->date->format('Y-m-d H:i:s'))); /** @var WarnAboutBills $job */ - $job = app(WarnAboutBills::class); + $job = app(WarnAboutBills::class); $job->setDate($this->date); $job->setForce($this->force); $job->handle(); // get stuff from job: - $this->jobFired = true; - $this->jobErrored = false; + $this->jobFired = true; + $this->jobErrored = false; $this->jobSucceeded = true; - $this->message = 'Bill notification cron job fired successfully.'; + $this->message = 'Bill notification cron job fired successfully.'; - FireflyConfig::set('last_bw_job', (int)$this->date->format('U')); - Log::info(sprintf('Marked the last time this job has run as "%s" (%d)', $this->date->format('Y-m-d H:i:s'), (int)$this->date->format('U'))); + FireflyConfig::set('last_bw_job', (int) $this->date->format('U')); + Log::info(sprintf('Marked the last time this job has run as "%s" (%d)', $this->date->format('Y-m-d H:i:s'), (int) $this->date->format('U'))); Log::info('Done with bill notification cron job task.'); } } diff --git a/app/Support/Cronjobs/ExchangeRatesCronjob.php b/app/Support/Cronjobs/ExchangeRatesCronjob.php index 98af3966d5..63e100e5c0 100644 --- a/app/Support/Cronjobs/ExchangeRatesCronjob.php +++ b/app/Support/Cronjobs/ExchangeRatesCronjob.php @@ -24,11 +24,11 @@ declare(strict_types=1); namespace FireflyIII\Support\Cronjobs; -use FireflyIII\Support\Facades\Preferences; use Carbon\Carbon; use FireflyIII\Jobs\DownloadExchangeRates; use FireflyIII\Models\Configuration; use FireflyIII\Support\Facades\FireflyConfig; +use FireflyIII\Support\Facades\Preferences; use Illuminate\Support\Facades\Log; /** @@ -40,7 +40,7 @@ class ExchangeRatesCronjob extends AbstractCronjob { /** @var Configuration $config */ $config = FireflyConfig::get('last_cer_job', 0); - $lastTime = (int)$config->data; + $lastTime = (int) $config->data; $diff = now(config('app.timezone'))->getTimestamp() - $lastTime; $diffForHumans = now(config('app.timezone'))->diffForHumans(Carbon::createFromTimestamp($lastTime), null, true); if (0 === $lastTime) { @@ -72,17 +72,17 @@ class ExchangeRatesCronjob extends AbstractCronjob Log::info(sprintf('Will now fire exchange rates cron job task for date "%s".', $this->date->format('Y-m-d'))); /** @var DownloadExchangeRates $job */ - $job = app(DownloadExchangeRates::class); + $job = app(DownloadExchangeRates::class); $job->setDate($this->date); $job->handle(); // get stuff from job: - $this->jobFired = true; - $this->jobErrored = false; + $this->jobFired = true; + $this->jobErrored = false; $this->jobSucceeded = true; - $this->message = 'Exchange rates cron job fired successfully.'; + $this->message = 'Exchange rates cron job fired successfully.'; - FireflyConfig::set('last_cer_job', (int)$this->date->format('U')); + FireflyConfig::set('last_cer_job', (int) $this->date->format('U')); Log::info('Done with exchange rates job task.'); } } diff --git a/app/Support/Cronjobs/RecurringCronjob.php b/app/Support/Cronjobs/RecurringCronjob.php index 297bfa8d66..fe0de200e7 100644 --- a/app/Support/Cronjobs/RecurringCronjob.php +++ b/app/Support/Cronjobs/RecurringCronjob.php @@ -24,12 +24,12 @@ declare(strict_types=1); namespace FireflyIII\Support\Cronjobs; -use FireflyIII\Support\Facades\Preferences; use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Jobs\CreateRecurringTransactions; use FireflyIII\Models\Configuration; use FireflyIII\Support\Facades\FireflyConfig; +use FireflyIII\Support\Facades\Preferences; use Illuminate\Support\Facades\Log; /** @@ -46,7 +46,7 @@ class RecurringCronjob extends AbstractCronjob /** @var Configuration $config */ $config = FireflyConfig::get('last_rt_job', 0); - $lastTime = (int)$config->data; + $lastTime = (int) $config->data; $diff = now(config('app.timezone'))->getTimestamp() - $lastTime; $diffForHumans = now(config('app.timezone'))->diffForHumans(Carbon::createFromTimestamp($lastTime), null, true); @@ -58,9 +58,9 @@ class RecurringCronjob extends AbstractCronjob Log::info(sprintf('It has been "%s" since the recurring transactions cron-job has fired.', $diffForHumans)); if (false === $this->force) { Log::info('The cron-job will not fire now.'); - $this->message = sprintf('It has been "%s" since the recurring transactions cron-job has fired. It will not fire now.', $diffForHumans); - $this->jobFired = false; - $this->jobErrored = false; + $this->message = sprintf('It has been "%s" since the recurring transactions cron-job has fired. It will not fire now.', $diffForHumans); + $this->jobFired = false; + $this->jobErrored = false; $this->jobSucceeded = false; return; @@ -81,18 +81,18 @@ class RecurringCronjob extends AbstractCronjob { Log::info(sprintf('Will now fire recurring cron job task for date "%s".', $this->date->format('Y-m-d H:i:s'))); - $job = new CreateRecurringTransactions($this->date); + $job = new CreateRecurringTransactions($this->date); $job->setForce($this->force); $job->handle(); // get stuff from job: - $this->jobFired = true; - $this->jobErrored = false; + $this->jobFired = true; + $this->jobErrored = false; $this->jobSucceeded = true; - $this->message = 'Recurring transactions cron job fired successfully.'; + $this->message = 'Recurring transactions cron job fired successfully.'; - FireflyConfig::set('last_rt_job', (int)$this->date->format('U')); - Log::info(sprintf('Marked the last time this job has run as "%s" (%d)', $this->date->format('Y-m-d H:i:s'), (int)$this->date->format('U'))); + FireflyConfig::set('last_rt_job', (int) $this->date->format('U')); + Log::info(sprintf('Marked the last time this job has run as "%s" (%d)', $this->date->format('Y-m-d H:i:s'), (int) $this->date->format('U'))); Log::info('Done with recurring cron job task.'); } } diff --git a/app/Support/Cronjobs/UpdateCheckCronjob.php b/app/Support/Cronjobs/UpdateCheckCronjob.php index d9987a73ad..8d9a4b1cf0 100644 --- a/app/Support/Cronjobs/UpdateCheckCronjob.php +++ b/app/Support/Cronjobs/UpdateCheckCronjob.php @@ -41,50 +41,53 @@ class UpdateCheckCronjob extends AbstractCronjob Log::debug('Now in checkForUpdates()'); // should not check for updates: - $permission = FireflyConfig::get('permission_update_check', -1); - $value = (int)$permission->data; + $permission = FireflyConfig::get('permission_update_check', -1); + $value = (int) $permission->data; if (1 !== $value) { Log::debug('Update check is not enabled.'); // get stuff from job: - $this->jobFired = false; - $this->jobErrored = false; + $this->jobFired = false; + $this->jobErrored = false; $this->jobSucceeded = true; - $this->message = 'The update check is not enabled.'; + $this->message = 'The update check is not enabled.'; return; } // TODO this is duplicate. /** @var Configuration $lastCheckTime */ - $lastCheckTime = FireflyConfig::get('last_update_check', Carbon::now()->getTimestamp()); - $now = Carbon::now()->getTimestamp(); - $diff = $now - $lastCheckTime->data; + $lastCheckTime = FireflyConfig::get('last_update_check', Carbon::now()->getTimestamp()); + $now = Carbon::now()->getTimestamp(); + $diff = $now - $lastCheckTime->data; Log::debug(sprintf('Last check time is %d, current time is %d, difference is %d', $lastCheckTime->data, $now, $diff)); if ($diff < 604800 && false === $this->force) { // get stuff from job: - $this->jobFired = false; - $this->jobErrored = false; + $this->jobFired = false; + $this->jobErrored = false; $this->jobSucceeded = true; - $this->message = sprintf('Checked for updates less than a week ago (on %s).', Carbon::createFromTimestamp($lastCheckTime->data)->format('Y-m-d H:i:s')); + $this->message = sprintf( + 'Checked for updates less than a week ago (on %s).', + Carbon::createFromTimestamp($lastCheckTime->data)->format('Y-m-d H:i:s') + ); return; } // last check time was more than a week ago. Log::debug('Have not checked for a new version in a week!'); - $release = $this->getLatestRelease(); + $release = $this->getLatestRelease(); if ('error' === $release['level']) { // get stuff from job: - $this->jobFired = true; - $this->jobErrored = true; + $this->jobFired = true; + $this->jobErrored = true; $this->jobSucceeded = false; - $this->message = $release['message']; + $this->message = $release['message']; return; } // get stuff from job: - $this->jobFired = true; - $this->jobErrored = false; + $this->jobFired = true; + $this->jobErrored = false; $this->jobSucceeded = false; - $this->message = $release['message']; + $this->message = $release['message']; } } diff --git a/app/Support/Cronjobs/WebhookCronjob.php b/app/Support/Cronjobs/WebhookCronjob.php index d6c57123de..21c82dab8c 100644 --- a/app/Support/Cronjobs/WebhookCronjob.php +++ b/app/Support/Cronjobs/WebhookCronjob.php @@ -24,12 +24,12 @@ declare(strict_types=1); namespace FireflyIII\Support\Cronjobs; -use FireflyIII\Support\Facades\Preferences; use Carbon\Carbon; use FireflyIII\Events\RequestedSendWebhookMessages; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Configuration; use FireflyIII\Support\Facades\FireflyConfig; +use FireflyIII\Support\Facades\Preferences; use Illuminate\Support\Facades\Log; /** @@ -46,7 +46,7 @@ class WebhookCronjob extends AbstractCronjob /** @var Configuration $config */ $config = FireflyConfig::get('last_webhook_job', 0); - $lastTime = (int)$config->data; + $lastTime = (int) $config->data; $diff = now(config('app.timezone'))->getTimestamp() - $lastTime; $diffForHumans = now(config('app.timezone'))->diffForHumans(Carbon::createFromTimestamp($lastTime), null, true); @@ -58,9 +58,9 @@ class WebhookCronjob extends AbstractCronjob Log::info(sprintf('It has been %s since the webhook cron-job has fired.', $diffForHumans)); if (false === $this->force) { Log::info('The cron-job will not fire now.'); - $this->message = sprintf('It has been %s since the webhook cron-job has fired. It will not fire now.', $diffForHumans); - $this->jobFired = false; - $this->jobErrored = false; + $this->message = sprintf('It has been %s since the webhook cron-job has fired. It will not fire now.', $diffForHumans); + $this->jobFired = false; + $this->jobErrored = false; $this->jobSucceeded = false; return; @@ -86,13 +86,13 @@ class WebhookCronjob extends AbstractCronjob event(new RequestedSendWebhookMessages()); // get stuff from job: - $this->jobFired = true; - $this->jobErrored = false; + $this->jobFired = true; + $this->jobErrored = false; $this->jobSucceeded = true; - $this->message = 'Send webhook messages cron job fired successfully.'; + $this->message = 'Send webhook messages cron job fired successfully.'; - FireflyConfig::set('last_webhook_job', (int)$this->date->format('U')); - Log::info(sprintf('Marked the last time this job has run as "%s" (%d)', $this->date->format('Y-m-d H:i:s'), (int)$this->date->format('U'))); + FireflyConfig::set('last_webhook_job', (int) $this->date->format('U')); + Log::info(sprintf('Marked the last time this job has run as "%s" (%d)', $this->date->format('Y-m-d H:i:s'), (int) $this->date->format('U'))); Log::info('Done with webhook cron job task.'); } } diff --git a/app/Support/Debug/Timer.php b/app/Support/Debug/Timer.php index 31119addc4..b2d58f4353 100644 --- a/app/Support/Debug/Timer.php +++ b/app/Support/Debug/Timer.php @@ -28,8 +28,8 @@ use Illuminate\Support\Facades\Log; class Timer { - private static ?Timer $instance = null; - private array $times = []; + private static null|Timer $instance = null; + private array $times = []; private function __construct() { diff --git a/app/Support/ExpandedForm.php b/app/Support/ExpandedForm.php index 92d315ab15..a83a9b6184 100644 --- a/app/Support/ExpandedForm.php +++ b/app/Support/ExpandedForm.php @@ -23,11 +23,11 @@ declare(strict_types=1); namespace FireflyIII\Support; -use Illuminate\Support\Facades\Log; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Support\Form\FormSupport; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Log; use Throwable; /** @@ -42,13 +42,13 @@ class ExpandedForm * * @throws FireflyException */ - public function amountNoCurrency(string $name, $value = null, ?array $options = null): string + public function amountNoCurrency(string $name, $value = null, null|array $options = null): string { $options ??= []; - $label = $this->label($name, $options); - $options = $this->expandOptionArray($name, $label, $options); - $classes = $this->getHolderClasses($name); - $value = $this->fillFieldValue($name, $value); + $label = $this->label($name, $options); + $options = $this->expandOptionArray($name, $label, $options); + $classes = $this->getHolderClasses($name); + $value = $this->fillFieldValue($name, $value); $options['step'] = 'any'; unset($options['currency'], $options['placeholder']); @@ -57,7 +57,13 @@ class ExpandedForm // $value = round((float)$value, 8); // } try { - $html = view('form.amount-no-currency', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render(); + $html = view('form.amount-no-currency', [ + 'classes' => $classes, + 'name' => $name, + 'label' => $label, + 'value' => $value, + 'options' => $options + ])->render(); } catch (Throwable $e) { Log::error(sprintf('Could not render amountNoCurrency(): %s', $e->getMessage())); $html = 'Could not render amountNoCurrency.'; @@ -73,26 +79,32 @@ class ExpandedForm * * @throws FireflyException */ - public function checkbox(string $name, ?int $value = null, $checked = null, ?array $options = null): string + public function checkbox(string $name, null|int $value = null, $checked = null, null|array $options = null): string { $options ??= []; $value ??= 1; $options['checked'] = true === $checked; if (app('session')->has('preFilled')) { - $preFilled = session('preFilled'); + $preFilled = session('preFilled'); $options['checked'] = $preFilled[$name] ?? $options['checked']; } - $label = $this->label($name, $options); - $options = $this->expandOptionArray($name, $label, $options); - $classes = $this->getHolderClasses($name); - $value = $this->fillFieldValue($name, $value); + $label = $this->label($name, $options); + $options = $this->expandOptionArray($name, $label, $options); + $classes = $this->getHolderClasses($name); + $value = $this->fillFieldValue($name, $value); unset($options['placeholder'], $options['autocomplete'], $options['class']); try { - $html = view('form.checkbox', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render(); + $html = view('form.checkbox', [ + 'classes' => $classes, + 'name' => $name, + 'label' => $label, + 'value' => $value, + 'options' => $options + ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render checkbox(): %s', $e->getMessage())); $html = 'Could not render checkbox.'; @@ -108,7 +120,7 @@ class ExpandedForm * * @throws FireflyException */ - public function date(string $name, $value = null, ?array $options = null): string + public function date(string $name, $value = null, null|array $options = null): string { $label = $this->label($name, $options); $options = $this->expandOptionArray($name, $label, $options); @@ -117,7 +129,7 @@ class ExpandedForm unset($options['placeholder']); try { - $html = view('form.date', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render(); + $html = view('form.date', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render date(): %s', $e->getMessage())); $html = 'Could not render date.'; @@ -131,7 +143,7 @@ class ExpandedForm /** * @throws FireflyException */ - public function file(string $name, ?array $options = null): string + public function file(string $name, null|array $options = null): string { $options ??= []; $label = $this->label($name, $options); @@ -139,7 +151,7 @@ class ExpandedForm $classes = $this->getHolderClasses($name); try { - $html = view('form.file', ['classes' => $classes, 'name' => $name, 'label' => $label, 'options' => $options])->render(); + $html = view('form.file', ['classes' => $classes, 'name' => $name, 'label' => $label, 'options' => $options])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render file(): %s', $e->getMessage())); $html = 'Could not render file.'; @@ -155,9 +167,9 @@ class ExpandedForm * * @throws FireflyException */ - public function integer(string $name, $value = null, ?array $options = null): string + public function integer(string $name, $value = null, null|array $options = null): string { - $options ??= []; + $options ??= []; $label = $this->label($name, $options); $options = $this->expandOptionArray($name, $label, $options); $classes = $this->getHolderClasses($name); @@ -165,7 +177,13 @@ class ExpandedForm $options['step'] ??= '1'; try { - $html = view('form.integer', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render(); + $html = view('form.integer', [ + 'classes' => $classes, + 'name' => $name, + 'label' => $label, + 'value' => $value, + 'options' => $options + ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render integer(): %s', $e->getMessage())); $html = 'Could not render integer.'; @@ -181,7 +199,7 @@ class ExpandedForm * * @throws FireflyException */ - public function location(string $name, $value = null, ?array $options = null): string + public function location(string $name, $value = null, null|array $options = null): string { $options ??= []; $label = $this->label($name, $options); @@ -190,7 +208,13 @@ class ExpandedForm $value = $this->fillFieldValue($name, $value); try { - $html = view('form.location', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render(); + $html = view('form.location', [ + 'classes' => $classes, + 'name' => $name, + 'label' => $label, + 'value' => $value, + 'options' => $options + ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render location(): %s', $e->getMessage())); $html = 'Could not render location.'; @@ -203,16 +227,16 @@ class ExpandedForm public function makeSelectListWithEmpty(Collection $set): array { - $selectList = []; + $selectList = []; $selectList[0] = '(none)'; - $fields = ['title', 'name', 'description']; + $fields = ['title', 'name', 'description']; /** @var Model $entry */ foreach ($set as $entry) { // All Eloquent models have an ID - $entryId = $entry->id; - $current = $entry->toArray(); - $title = null; + $entryId = $entry->id; + $current = $entry->toArray(); + $title = null; foreach ($fields as $field) { if (array_key_exists($field, $current) && null === $title) { $title = $current[$field]; @@ -229,13 +253,13 @@ class ExpandedForm * * @throws FireflyException */ - public function objectGroup($value = null, ?array $options = null): string + public function objectGroup($value = null, null|array $options = null): string { - $name = 'object_group'; - $label = $this->label($name, $options); - $options = $this->expandOptionArray($name, $label, $options); - $classes = $this->getHolderClasses($name); - $value = $this->fillFieldValue($name, $value); + $name = 'object_group'; + $label = $this->label($name, $options); + $options = $this->expandOptionArray($name, $label, $options); + $classes = $this->getHolderClasses($name); + $value = $this->fillFieldValue($name, $value); $options['rows'] = 4; if (null === $value) { @@ -243,7 +267,13 @@ class ExpandedForm } try { - $html = view('form.object_group', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render(); + $html = view('form.object_group', [ + 'classes' => $classes, + 'name' => $name, + 'label' => $label, + 'value' => $value, + 'options' => $options + ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render objectGroup(): %s', $e->getMessage())); $html = 'Could not render objectGroup.'; @@ -274,14 +304,14 @@ class ExpandedForm /** * @throws FireflyException */ - public function password(string $name, ?array $options = null): string + public function password(string $name, null|array $options = null): string { $label = $this->label($name, $options); $options = $this->expandOptionArray($name, $label, $options); $classes = $this->getHolderClasses($name); try { - $html = view('form.password', ['classes' => $classes, 'name' => $name, 'label' => $label, 'options' => $options])->render(); + $html = view('form.password', ['classes' => $classes, 'name' => $name, 'label' => $label, 'options' => $options])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render password(): %s', $e->getMessage())); $html = 'Could not render password.'; @@ -295,14 +325,20 @@ class ExpandedForm /** * @throws FireflyException */ - public function passwordWithValue(string $name, string $value, ?array $options = null): string + public function passwordWithValue(string $name, string $value, null|array $options = null): string { $label = $this->label($name, $options); $options = $this->expandOptionArray($name, $label, $options); $classes = $this->getHolderClasses($name); try { - $html = view('form.password', ['classes' => $classes, 'value' => $value, 'name' => $name, 'label' => $label, 'options' => $options])->render(); + $html = view('form.password', [ + 'classes' => $classes, + 'value' => $value, + 'name' => $name, + 'label' => $label, + 'options' => $options + ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render passwordWithValue(): %s', $e->getMessage())); $html = 'Could not render passwordWithValue.'; @@ -320,17 +356,23 @@ class ExpandedForm * * @throws FireflyException */ - public function percentage(string $name, $value = null, ?array $options = null): string + public function percentage(string $name, $value = null, null|array $options = null): string { - $label = $this->label($name, $options); - $options = $this->expandOptionArray($name, $label, $options); - $classes = $this->getHolderClasses($name); - $value = $this->fillFieldValue($name, $value); + $label = $this->label($name, $options); + $options = $this->expandOptionArray($name, $label, $options); + $classes = $this->getHolderClasses($name); + $value = $this->fillFieldValue($name, $value); $options['step'] = 'any'; unset($options['placeholder']); try { - $html = view('form.percentage', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render(); + $html = view('form.percentage', [ + 'classes' => $classes, + 'name' => $name, + 'label' => $label, + 'value' => $value, + 'options' => $options + ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render percentage(): %s', $e->getMessage())); $html = 'Could not render percentage.'; @@ -346,14 +388,14 @@ class ExpandedForm * * @throws FireflyException */ - public function staticText(string $name, $value, ?array $options = null): string + public function staticText(string $name, $value, null|array $options = null): string { $label = $this->label($name, $options); $options = $this->expandOptionArray($name, $label, $options); $classes = $this->getHolderClasses($name); try { - $html = view('form.static', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render(); + $html = view('form.static', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render staticText(): %s', $e->getMessage())); $html = 'Could not render staticText.'; @@ -369,7 +411,7 @@ class ExpandedForm * * @throws FireflyException */ - public function text(string $name, $value = null, ?array $options = null): string + public function text(string $name, $value = null, null|array $options = null): string { $label = $this->label($name, $options); $options = $this->expandOptionArray($name, $label, $options); @@ -377,7 +419,7 @@ class ExpandedForm $value = $this->fillFieldValue($name, $value); try { - $html = view('form.text', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render(); + $html = view('form.text', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render text(): %s', $e->getMessage())); $html = 'Could not render text.'; @@ -393,12 +435,12 @@ class ExpandedForm * * @throws FireflyException */ - public function textarea(string $name, $value = null, ?array $options = null): string + public function textarea(string $name, $value = null, null|array $options = null): string { - $label = $this->label($name, $options); - $options = $this->expandOptionArray($name, $label, $options); - $classes = $this->getHolderClasses($name); - $value = $this->fillFieldValue($name, $value); + $label = $this->label($name, $options); + $options = $this->expandOptionArray($name, $label, $options); + $classes = $this->getHolderClasses($name); + $value = $this->fillFieldValue($name, $value); $options['rows'] = 4; if (null === $value) { @@ -406,7 +448,13 @@ class ExpandedForm } try { - $html = view('form.textarea', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render(); + $html = view('form.textarea', [ + 'classes' => $classes, + 'name' => $name, + 'label' => $label, + 'value' => $value, + 'options' => $options + ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render textarea(): %s', $e->getMessage())); $html = 'Could not render textarea.'; diff --git a/app/Support/Export/ExportDataGenerator.php b/app/Support/Export/ExportDataGenerator.php index f7cf2a8c41..be93d46414 100644 --- a/app/Support/Export/ExportDataGenerator.php +++ b/app/Support/Export/ExportDataGenerator.php @@ -72,29 +72,30 @@ class ExportDataGenerator { use ConvertsDataTypes; - private const string ADD_RECORD_ERR = 'Could not add record to set: %s'; - private const string EXPORT_ERR = 'Could not export to string: %s'; + private const string ADD_RECORD_ERR = 'Could not add record to set: %s'; + private const string EXPORT_ERR = 'Could not export to string: %s'; + private Collection $accounts; - private Carbon $end; - private bool $exportAccounts = false; - private bool $exportBills = false; - private bool $exportBudgets = false; - private bool $exportCategories = false; - private bool $exportPiggies = false; - private bool $exportRecurring = false; - private bool $exportRules = false; - private bool $exportTags = false; - private bool $exportTransactions = false; - private Carbon $start; - private User $user; - private UserGroup $userGroup; // @phpstan-ignore-line + private Carbon $end; + private bool $exportAccounts = false; + private bool $exportBills = false; + private bool $exportBudgets = false; + private bool $exportCategories = false; + private bool $exportPiggies = false; + private bool $exportRecurring = false; + private bool $exportRules = false; + private bool $exportTags = false; + private bool $exportTransactions = false; + private Carbon $start; + private User $user; + private UserGroup $userGroup; // @phpstan-ignore-line public function __construct() { $this->accounts = new Collection(); - $this->start = today(config('app.timezone')); + $this->start = today(config('app.timezone')); $this->start->subYear(); - $this->end = today(config('app.timezone')); + $this->end = today(config('app.timezone')); } /** @@ -231,7 +232,7 @@ class ExportDataGenerator */ private function exportAccounts(): string { - $header = [ + $header = [ 'user_id', 'account_id', 'created_at', @@ -248,18 +249,18 @@ class ExportDataGenerator 'cc_payment_date', 'in_net_worth', 'interest', - 'interest_period', + 'interest_period' ]; /** @var AccountRepositoryInterface $repository */ - $repository = app(AccountRepositoryInterface::class); + $repository = app(AccountRepositoryInterface::class); $repository->setUser($this->user); $allAccounts = $repository->getAccountsByType([]); $records = []; /** @var Account $account */ foreach ($allAccounts as $account) { - $currency = $repository->getAccountCurrency($account); + $currency = $repository->getAccountCurrency($account); $records[] = [ $this->user->id, $account->id, @@ -277,12 +278,12 @@ class ExportDataGenerator $repository->getMetaValue($account, 'cc_monthly_payment_date'), $repository->getMetaValue($account, 'include_net_worth'), $repository->getMetaValue($account, 'interest'), - $repository->getMetaValue($account, 'interest_period'), + $repository->getMetaValue($account, 'interest_period') ]; } // load the CSV document from a string - $csv = Writer::createFromString(); + $csv = Writer::createFromString(); // insert the header try { @@ -315,8 +316,8 @@ class ExportDataGenerator /** @var BillRepositoryInterface $repository */ $repository = app(BillRepositoryInterface::class); $repository->setUser($this->user); - $bills = $repository->getBills(); - $header = [ + $bills = $repository->getBills(); + $header = [ 'user_id', 'bill_id', 'created_at', @@ -328,9 +329,9 @@ class ExportDataGenerator 'date', 'repeat_freq', 'skip', - 'active', + 'active' ]; - $records = []; + $records = []; /** @var Bill $bill */ foreach ($bills as $bill) { @@ -346,12 +347,12 @@ class ExportDataGenerator $bill->date->format('Y-m-d'), $bill->repeat_freq, $bill->skip, - $bill->active, + $bill->active ]; } // load the CSV document from a string - $csv = Writer::createFromString(); + $csv = Writer::createFromString(); // insert the header try { @@ -381,23 +382,13 @@ class ExportDataGenerator */ private function exportBudgets(): string { - $header = [ - 'user_id', - 'budget_id', - 'name', - 'active', - 'order', - 'start_date', - 'end_date', - 'currency_code', - 'amount', - ]; + $header = ['user_id', 'budget_id', 'name', 'active', 'order', 'start_date', 'end_date', 'currency_code', 'amount']; $budgetRepos = app(BudgetRepositoryInterface::class); $budgetRepos->setUser($this->user); - $limitRepos = app(BudgetLimitRepositoryInterface::class); - $budgets = $budgetRepos->getBudgets(); - $records = []; + $limitRepos = app(BudgetLimitRepositoryInterface::class); + $budgets = $budgetRepos->getBudgets(); + $records = []; /** @var Budget $budget */ foreach ($budgets as $budget) { @@ -414,13 +405,13 @@ class ExportDataGenerator $limit->start_date->format('Y-m-d'), $limit->end_date->format('Y-m-d'), $limit->transactionCurrency->code, - $limit->amount, + $limit->amount ]; } } // load the CSV document from a string - $csv = Writer::createFromString(); + $csv = Writer::createFromString(); // insert the header try { @@ -450,10 +441,10 @@ class ExportDataGenerator */ private function exportCategories(): string { - $header = ['user_id', 'category_id', 'created_at', 'updated_at', 'name']; + $header = ['user_id', 'category_id', 'created_at', 'updated_at', 'name']; /** @var CategoryRepositoryInterface $catRepos */ - $catRepos = app(CategoryRepositoryInterface::class); + $catRepos = app(CategoryRepositoryInterface::class); $catRepos->setUser($this->user); $records = []; @@ -461,17 +452,11 @@ class ExportDataGenerator /** @var Category $category */ foreach ($categories as $category) { - $records[] = [ - $this->user->id, - $category->id, - $category->created_at->toAtomString(), - $category->updated_at->toAtomString(), - $category->name, - ]; + $records[] = [$this->user->id, $category->id, $category->created_at->toAtomString(), $category->updated_at->toAtomString(), $category->name]; } // load the CSV document from a string - $csv = Writer::createFromString(); + $csv = Writer::createFromString(); // insert the header try { @@ -502,14 +487,14 @@ class ExportDataGenerator private function exportPiggies(): string { /** @var PiggyBankRepositoryInterface $piggyRepos */ - $piggyRepos = app(PiggyBankRepositoryInterface::class); + $piggyRepos = app(PiggyBankRepositoryInterface::class); $piggyRepos->setUser($this->user); /** @var AccountRepositoryInterface $accountRepos */ $accountRepos = app(AccountRepositoryInterface::class); $accountRepos->setUser($this->user); - $header = [ + $header = [ 'user_id', 'piggy_bank_id', 'created_at', @@ -523,16 +508,16 @@ class ExportDataGenerator 'start_date', 'target_date', 'order', - 'active', + 'active' ]; - $records = []; - $piggies = $piggyRepos->getPiggyBanks(); + $records = []; + $piggies = $piggyRepos->getPiggyBanks(); /** @var PiggyBank $piggy */ foreach ($piggies as $piggy) { $repetition = $piggyRepos->getRepetition($piggy); $currency = $accountRepos->getAccountCurrency($piggy->account); - $records[] = [ + $records[] = [ $this->user->id, $piggy->id, $piggy->created_at->toAtomString(), @@ -546,12 +531,12 @@ class ExportDataGenerator $piggy->start_date?->format('Y-m-d'), $piggy->target_date?->format('Y-m-d'), $piggy->order, - $piggy->active, + $piggy->active ]; } // load the CSV document from a string - $csv = Writer::createFromString(); + $csv = Writer::createFromString(); // insert the header try { @@ -584,25 +569,63 @@ class ExportDataGenerator /** @var RecurringRepositoryInterface $recurringRepos */ $recurringRepos = app(RecurringRepositoryInterface::class); $recurringRepos->setUser($this->user); - $header = [ + $header = [ // recurrence: - 'user_id', 'recurrence_id', 'row_contains', 'created_at', 'updated_at', 'type', 'title', 'description', 'first_date', 'repeat_until', 'latest_date', 'repetitions', 'apply_rules', 'active', + 'user_id', + 'recurrence_id', + 'row_contains', + 'created_at', + 'updated_at', + 'type', + 'title', + 'description', + 'first_date', + 'repeat_until', + 'latest_date', + 'repetitions', + 'apply_rules', + 'active', // repetition info: - 'type', 'moment', 'skip', 'weekend', + 'type', + 'moment', + 'skip', + 'weekend', // transactions + meta: - 'currency_code', 'foreign_currency_code', 'source_name', 'source_type', 'destination_name', 'destination_type', 'amount', 'foreign_amount', 'category', 'budget', 'piggy_bank', 'tags', + 'currency_code', + 'foreign_currency_code', + 'source_name', + 'source_type', + 'destination_name', + 'destination_type', + 'amount', + 'foreign_amount', + 'category', + 'budget', + 'piggy_bank', + 'tags' ]; - $records = []; - $recurrences = $recurringRepos->get(); + $records = []; + $recurrences = $recurringRepos->get(); /** @var Recurrence $recurrence */ foreach ($recurrences as $recurrence) { // add recurrence: $records[] = [ - $this->user->id, $recurrence->id, + $this->user->id, + $recurrence->id, 'recurrence', - $recurrence->created_at->toAtomString(), $recurrence->updated_at->toAtomString(), $recurrence->transactionType->type, $recurrence->title, $recurrence->description, $recurrence->first_date?->format('Y-m-d'), $recurrence->repeat_until?->format('Y-m-d'), $recurrence->latest_date?->format('Y-m-d'), $recurrence->repetitions, $recurrence->apply_rules, $recurrence->active, + $recurrence->created_at->toAtomString(), + $recurrence->updated_at->toAtomString(), + $recurrence->transactionType->type, + $recurrence->title, + $recurrence->description, + $recurrence->first_date?->format('Y-m-d'), + $recurrence->repeat_until?->format('Y-m-d'), + $recurrence->latest_date?->format('Y-m-d'), + $recurrence->repetitions, + $recurrence->apply_rules, + $recurrence->active ]; // add new row for each repetition @@ -613,10 +636,23 @@ class ExportDataGenerator $this->user->id, $recurrence->id, 'repetition', - null, null, null, null, null, null, null, null, null, null, null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, // repetition: - $repetition->repetition_type, $repetition->repetition_moment, $repetition->repetition_skip, $repetition->weekend, + $repetition->repetition_type, + $repetition->repetition_moment, + $repetition->repetition_skip, + $repetition->weekend ]; } @@ -627,23 +663,47 @@ class ExportDataGenerator $piggyBankId = $recurringRepos->getPiggyBank($transaction); $tags = $recurringRepos->getTags($transaction); - $records[] = [ + $records[] = [ // recurrence $this->user->id, $recurrence->id, 'transaction', - null, null, null, null, null, null, null, null, null, null, null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, // repetition: - null, null, null, null, + null, + null, + null, + null, // transaction: - $transaction->transactionCurrency->code, $transaction->foreignCurrency?->code, $transaction->sourceAccount->name, $transaction->sourceAccount->accountType->type, $transaction->destinationAccount->name, $transaction->destinationAccount->accountType->type, $transaction->amount, $transaction->foreign_amount, $categoryName, $budgetId, $piggyBankId, implode(',', $tags), + $transaction->transactionCurrency->code, + $transaction->foreignCurrency?->code, + $transaction->sourceAccount->name, + $transaction->sourceAccount->accountType->type, + $transaction->destinationAccount->name, + $transaction->destinationAccount->accountType->type, + $transaction->amount, + $transaction->foreign_amount, + $categoryName, + $budgetId, + $piggyBankId, + implode(',', $tags) ]; } } // load the CSV document from a string - $csv = Writer::createFromString(); + $csv = Writer::createFromString(); // insert the header try { @@ -674,53 +734,123 @@ class ExportDataGenerator private function exportRules(): string { $header = [ - 'user_id', 'rule_id', 'row_contains', - 'created_at', 'updated_at', 'group_id', 'title', 'description', 'order', 'active', 'stop_processing', 'strict', - 'trigger_type', 'trigger_value', 'trigger_order', 'trigger_active', 'trigger_stop_processing', - 'action_type', 'action_value', 'action_order', 'action_active', 'action_stop_processing']; + 'user_id', + 'rule_id', + 'row_contains', + 'created_at', + 'updated_at', + 'group_id', + 'title', + 'description', + 'order', + 'active', + 'stop_processing', + 'strict', + 'trigger_type', + 'trigger_value', + 'trigger_order', + 'trigger_active', + 'trigger_stop_processing', + 'action_type', + 'action_value', + 'action_order', + 'action_active', + 'action_stop_processing' + ]; $ruleRepos = app(RuleRepositoryInterface::class); $ruleRepos->setUser($this->user); - $rules = $ruleRepos->getAll(); - $records = []; + $rules = $ruleRepos->getAll(); + $records = []; /** @var Rule $rule */ foreach ($rules as $rule) { - $entry = [ - $this->user->id, $rule->id, + $entry = [ + $this->user->id, + $rule->id, 'rule', - $rule->created_at->toAtomString(), $rule->updated_at->toAtomString(), $rule->ruleGroup->id, $rule->ruleGroup->title, $rule->title, $rule->description, $rule->order, $rule->active, $rule->stop_processing, $rule->strict, - null, null, null, null, null, null, null, null, null, + $rule->created_at->toAtomString(), + $rule->updated_at->toAtomString(), + $rule->ruleGroup->id, + $rule->ruleGroup->title, + $rule->title, + $rule->description, + $rule->order, + $rule->active, + $rule->stop_processing, + $rule->strict, + null, + null, + null, + null, + null, + null, + null, + null, + null ]; $records[] = $entry; /** @var RuleTrigger $trigger */ foreach ($rule->ruleTriggers as $trigger) { - $entry = [ + $entry = [ $this->user->id, $rule->id, 'trigger', - null, null, null, null, null, null, null, null, null, - $trigger->trigger_type, $trigger->trigger_value, $trigger->order, $trigger->active, $trigger->stop_processing, - null, null, null, null, null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + $trigger->trigger_type, + $trigger->trigger_value, + $trigger->order, + $trigger->active, + $trigger->stop_processing, + null, + null, + null, + null, + null ]; $records[] = $entry; } /** @var RuleAction $action */ foreach ($rule->ruleActions as $action) { - $entry = [ + $entry = [ $this->user->id, $rule->id, 'action', - null, null, null, null, null, null, null, null, null, null, null, null, null, null, - $action->action_type, $action->action_value, $action->order, $action->active, $action->stop_processing, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + null, + $action->action_type, + $action->action_value, + $action->order, + $action->active, + $action->stop_processing ]; $records[] = $entry; } } // load the CSV document from a string - $csv = Writer::createFromString(); + $csv = Writer::createFromString(); // insert the header try { @@ -752,12 +882,12 @@ class ExportDataGenerator */ private function exportTags(): string { - $header = ['user_id', 'tag_id', 'created_at', 'updated_at', 'tag', 'date', 'description', 'latitude', 'longitude', 'zoom_level']; + $header = ['user_id', 'tag_id', 'created_at', 'updated_at', 'tag', 'date', 'description', 'latitude', 'longitude', 'zoom_level']; $tagRepos = app(TagRepositoryInterface::class); $tagRepos->setUser($this->user); - $tags = $tagRepos->get(); - $records = []; + $tags = $tagRepos->get(); + $records = []; /** @var Tag $tag */ foreach ($tags as $tag) { @@ -771,12 +901,12 @@ class ExportDataGenerator $tag->description, $tag->latitude, $tag->longitude, - $tag->zoomLevel, + $tag->zoomLevel ]; } // load the CSV document from a string - $csv = Writer::createFromString(); + $csv = Writer::createFromString(); // insert the header try { @@ -808,76 +938,170 @@ class ExportDataGenerator { Log::debug('Will now export transactions.'); // TODO better place for keys? - $header = ['user_id', 'group_id', 'journal_id', 'created_at', 'updated_at', 'group_title', 'type', 'currency_code', 'amount', 'foreign_currency_code', 'foreign_amount', 'primary_currency_code', 'pc_amount', 'pc_foreign_amount', 'description', 'date', 'source_name', 'source_iban', 'source_type', 'destination_name', 'destination_iban', 'destination_type', 'reconciled', 'category', 'budget', 'bill', 'tags', 'notes']; + $header = [ + 'user_id', + 'group_id', + 'journal_id', + 'created_at', + 'updated_at', + 'group_title', + 'type', + 'currency_code', + 'amount', + 'foreign_currency_code', + 'foreign_amount', + 'primary_currency_code', + 'pc_amount', + 'pc_foreign_amount', + 'description', + 'date', + 'source_name', + 'source_iban', + 'source_type', + 'destination_name', + 'destination_iban', + 'destination_type', + 'reconciled', + 'category', + 'budget', + 'bill', + 'tags', + 'notes' + ]; $metaFields = config('firefly.journal_meta_fields'); $header = array_merge($header, $metaFields); $primary = Amount::getPrimaryCurrency(); - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $collector->setUser($this->user); - $collector->setRange($this->start, $this->end)->withAccountInformation()->withCategoryInformation()->withBillInformation()->withBudgetInformation()->withTagInformation()->withNotes(); + $collector + ->setRange($this->start, $this->end) + ->withAccountInformation() + ->withCategoryInformation() + ->withBillInformation() + ->withBudgetInformation() + ->withTagInformation() + ->withNotes(); if (0 !== $this->accounts->count()) { $collector->setAccounts($this->accounts); } - $journals = $collector->getExtractedJournals(); + $journals = $collector->getExtractedJournals(); // get repository for meta data: $repository = app(TransactionGroupRepositoryInterface::class); $repository->setUser($this->user); - $records = []; + $records = []; /** @var array $journal */ foreach ($journals as $journal) { $metaData = $repository->getMetaFields($journal['transaction_journal_id'], $metaFields); $amount = Steam::bcround(Steam::negative($journal['amount']), $journal['currency_decimal_places']); - $foreignAmount = null === $journal['foreign_amount'] ? null : Steam::bcround(Steam::negative($journal['foreign_amount']), $journal['foreign_currency_decimal_places']); + $foreignAmount = null === $journal['foreign_amount'] + ? null + : Steam::bcround(Steam::negative($journal['foreign_amount']), $journal['foreign_currency_decimal_places']); $pcAmount = null === $journal['pc_amount'] ? null : Steam::bcround(Steam::negative($journal['pc_amount']), $primary->decimal_places); - $pcForeignAmount = null === $journal['pc_foreign_amount'] ? null : Steam::bcround(Steam::negative($journal['pc_foreign_amount']), $primary->decimal_places); + $pcForeignAmount = null === $journal['pc_foreign_amount'] + ? null + : Steam::bcround(Steam::negative($journal['pc_foreign_amount']), $primary->decimal_places); if (TransactionTypeEnum::WITHDRAWAL->value !== $journal['transaction_type_type']) { $amount = Steam::bcround(Steam::positive($journal['amount']), $journal['currency_decimal_places']); - $foreignAmount = null === $journal['foreign_amount'] ? null : Steam::bcround(Steam::positive($journal['foreign_amount']), $journal['foreign_currency_decimal_places']); + $foreignAmount = null === $journal['foreign_amount'] + ? null + : Steam::bcround(Steam::positive($journal['foreign_amount']), $journal['foreign_currency_decimal_places']); $pcAmount = null === $journal['pc_amount'] ? null : Steam::bcround(Steam::positive($journal['pc_amount']), $primary->decimal_places); - $pcForeignAmount = null === $journal['pc_foreign_amount'] ? null : Steam::bcround(Steam::positive($journal['pc_foreign_amount']), $primary->decimal_places); + $pcForeignAmount = null === $journal['pc_foreign_amount'] + ? null + : Steam::bcround(Steam::positive($journal['pc_foreign_amount']), $primary->decimal_places); } // opening balance depends on source account type. - if (TransactionTypeEnum::OPENING_BALANCE->value === $journal['transaction_type_type'] && AccountTypeEnum::ASSET->value === $journal['source_account_type']) { + if ( + TransactionTypeEnum::OPENING_BALANCE->value === $journal['transaction_type_type'] + && AccountTypeEnum::ASSET->value === $journal['source_account_type'] + ) { $amount = Steam::bcround(Steam::negative($journal['amount']), $journal['currency_decimal_places']); - $foreignAmount = null === $journal['foreign_amount'] ? null : Steam::bcround(Steam::negative($journal['foreign_amount']), $journal['foreign_currency_decimal_places']); + $foreignAmount = null === $journal['foreign_amount'] + ? null + : Steam::bcround(Steam::negative($journal['foreign_amount']), $journal['foreign_currency_decimal_places']); $pcAmount = null === $journal['pc_amount'] ? null : Steam::bcround(Steam::negative($journal['pc_amount']), $primary->decimal_places); - $pcForeignAmount = null === $journal['pc_foreign_amount'] ? null : Steam::bcround(Steam::negative($journal['pc_foreign_amount']), $primary->decimal_places); + $pcForeignAmount = null === $journal['pc_foreign_amount'] + ? null + : Steam::bcround(Steam::negative($journal['pc_foreign_amount']), $primary->decimal_places); } - $records[] = [ - $journal['user_id'], $journal['transaction_group_id'], $journal['transaction_journal_id'], $journal['created_at']->toAtomString(), $journal['updated_at']->toAtomString(), $journal['transaction_group_title'], $journal['transaction_type_type'], + $records[] = [ + $journal['user_id'], + $journal['transaction_group_id'], + $journal['transaction_journal_id'], + $journal['created_at']->toAtomString(), + $journal['updated_at']->toAtomString(), + $journal['transaction_group_title'], + $journal['transaction_type_type'], // amounts and currencies - $journal['currency_code'], $amount, $journal['foreign_currency_code'], $foreignAmount, $primary->code, $pcAmount, $pcForeignAmount, + $journal['currency_code'], + $amount, + $journal['foreign_currency_code'], + $foreignAmount, + $primary->code, + $pcAmount, + $pcForeignAmount, // more fields - $journal['description'], $journal['date']->toAtomString(), $journal['source_account_name'], $journal['source_account_iban'], $journal['source_account_type'], $journal['destination_account_name'], $journal['destination_account_iban'], $journal['destination_account_type'], $journal['reconciled'], $journal['category_name'], $journal['budget_name'], $journal['bill_name'], + $journal['description'], + $journal['date']->toAtomString(), + $journal['source_account_name'], + $journal['source_account_iban'], + $journal['source_account_type'], + $journal['destination_account_name'], + $journal['destination_account_iban'], + $journal['destination_account_type'], + $journal['reconciled'], + $journal['category_name'], + $journal['budget_name'], + $journal['bill_name'], $this->mergeTags($journal['tags']), $this->clearStringKeepNewlines($journal['notes']), // sepa - $metaData['sepa_cc'], $metaData['sepa_ct_op'], $metaData['sepa_ct_id'], $metaData['sepa_db'], $metaData['sepa_country'], $metaData['sepa_ep'], $metaData['sepa_ci'], $metaData['sepa_batch_id'], $metaData['external_url'], + $metaData['sepa_cc'], + $metaData['sepa_ct_op'], + $metaData['sepa_ct_id'], + $metaData['sepa_db'], + $metaData['sepa_country'], + $metaData['sepa_ep'], + $metaData['sepa_ci'], + $metaData['sepa_batch_id'], + $metaData['external_url'], // dates - $metaData['interest_date'], $metaData['book_date'], $metaData['process_date'], $metaData['due_date'], $metaData['payment_date'], $metaData['invoice_date'], + $metaData['interest_date'], + $metaData['book_date'], + $metaData['process_date'], + $metaData['due_date'], + $metaData['payment_date'], + $metaData['invoice_date'], // others - $metaData['recurrence_id'], $metaData['internal_reference'], $metaData['bunq_payment_id'], $metaData['import_hash'], $metaData['import_hash_v2'], $metaData['external_id'], $metaData['original_source'], + $metaData['recurrence_id'], + $metaData['internal_reference'], + $metaData['bunq_payment_id'], + $metaData['import_hash'], + $metaData['import_hash_v2'], + $metaData['external_id'], + $metaData['original_source'], // recurring transactions - $metaData['recurrence_total'], $metaData['recurrence_count'], + $metaData['recurrence_total'], + $metaData['recurrence_count'] ]; } // load the CSV document from a string - $csv = Writer::createFromString(); + $csv = Writer::createFromString(); // insert the header try { diff --git a/app/Support/Facades/Preferences.php b/app/Support/Facades/Preferences.php index 998763b705..d8d7d7af11 100644 --- a/app/Support/Facades/Preferences.php +++ b/app/Support/Facades/Preferences.php @@ -23,8 +23,8 @@ declare(strict_types=1); namespace FireflyIII\Support\Facades; -use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Facade; +use Illuminate\Support\Facades\Log; class Preferences extends Facade { diff --git a/app/Support/FireflyConfig.php b/app/Support/FireflyConfig.php index 94f004ab5c..46fdeda41f 100644 --- a/app/Support/FireflyConfig.php +++ b/app/Support/FireflyConfig.php @@ -39,7 +39,7 @@ class FireflyConfig { public function delete(string $name): void { - $fullName = 'ff3-config-'.$name; + $fullName = 'ff3-config-' . $name; if (Cache::has($fullName)) { Cache::forget($fullName); } @@ -51,9 +51,9 @@ class FireflyConfig * * @throws FireflyException */ - public function get(string $name, mixed $default = null): ?Configuration + public function get(string $name, mixed $default = null): null|Configuration { - $fullName = 'ff3-config-'.$name; + $fullName = 'ff3-config-' . $name; if (Cache::has($fullName)) { return Cache::get($fullName); } @@ -78,7 +78,7 @@ class FireflyConfig return $this->set($name, $default); } - public function getEncrypted(string $name, mixed $default = null): ?Configuration + public function getEncrypted(string $name, mixed $default = null): null|Configuration { $result = $this->get($name, $default); if (!$result instanceof Configuration) { @@ -101,7 +101,7 @@ class FireflyConfig return $result; } - public function getFresh(string $name, mixed $default = null): ?Configuration + public function getFresh(string $name, mixed $default = null): null|Configuration { $config = Configuration::where('name', $name)->first(['id', 'name', 'data']); if (null !== $config) { @@ -134,7 +134,7 @@ class FireflyConfig $config = Configuration::whereName($name)->whereNull('deleted_at')->first(); } catch (QueryException $e) { Log::error($e->getMessage()); - $item = new Configuration(); + $item = new Configuration(); $item->name = $name; $item->data = $value; @@ -142,17 +142,17 @@ class FireflyConfig } if (null === $config) { - $item = new Configuration(); + $item = new Configuration(); $item->name = $name; $item->data = $value; $item->save(); - Cache::forget('ff3-config-'.$name); + Cache::forget('ff3-config-' . $name); return $item; } $config->data = $value; $config->save(); - Cache::forget('ff3-config-'.$name); + Cache::forget('ff3-config-' . $name); return $config; } diff --git a/app/Support/Form/AccountForm.php b/app/Support/Form/AccountForm.php index f512c1aa0c..f5663024c0 100644 --- a/app/Support/Form/AccountForm.php +++ b/app/Support/Form/AccountForm.php @@ -24,11 +24,11 @@ declare(strict_types=1); namespace FireflyIII\Support\Form; -use Illuminate\Support\Facades\Log; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Account; use FireflyIII\Repositories\Account\AccountRepositoryInterface; +use Illuminate\Support\Facades\Log; use Throwable; /** @@ -46,14 +46,20 @@ class AccountForm /** * Grouped dropdown list of all accounts that are valid as the destination of a withdrawal. */ - public function activeDepositDestinations(string $name, mixed $value = null, ?array $options = null): string + public function activeDepositDestinations(string $name, mixed $value = null, null|array $options = null): string { - $types = [AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::CREDITCARD->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::REVENUE->value]; - $repository = $this->getAccountRepository(); - $grouped = $this->getAccountsGrouped($types, $repository); - $cash = $repository->getCashAccount(); - $key = (string)trans('firefly.cash_account_type'); - $grouped[$key][$cash->id] = sprintf('(%s)', (string)trans('firefly.cash')); + $types = [ + AccountTypeEnum::MORTGAGE->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::CREDITCARD->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::REVENUE->value + ]; + $repository = $this->getAccountRepository(); + $grouped = $this->getAccountsGrouped($types, $repository); + $cash = $repository->getCashAccount(); + $key = (string) trans('firefly.cash_account_type'); + $grouped[$key][$cash->id] = sprintf('(%s)', (string) trans('firefly.cash')); return $this->select($name, $grouped, $value, $options); } @@ -61,15 +67,21 @@ class AccountForm /** * Grouped dropdown list of all accounts that are valid as the destination of a withdrawal. */ - public function activeWithdrawalDestinations(string $name, mixed $value = null, ?array $options = null): string + public function activeWithdrawalDestinations(string $name, mixed $value = null, null|array $options = null): string { - $types = [AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::CREDITCARD->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::EXPENSE->value]; - $repository = $this->getAccountRepository(); - $grouped = $this->getAccountsGrouped($types, $repository); + $types = [ + AccountTypeEnum::MORTGAGE->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::CREDITCARD->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::EXPENSE->value + ]; + $repository = $this->getAccountRepository(); + $grouped = $this->getAccountsGrouped($types, $repository); - $cash = $repository->getCashAccount(); - $key = (string)trans('firefly.cash_account_type'); - $grouped[$key][$cash->id] = sprintf('(%s)', (string)trans('firefly.cash')); + $cash = $repository->getCashAccount(); + $key = (string) trans('firefly.cash_account_type'); + $grouped[$key][$cash->id] = sprintf('(%s)', (string) trans('firefly.cash')); return $this->select($name, $grouped, $value, $options); } @@ -79,22 +91,35 @@ class AccountForm * * @throws FireflyException */ - public function assetAccountCheckList(string $name, ?array $options = null): string + public function assetAccountCheckList(string $name, null|array $options = null): string { - $options ??= []; + $options ??= []; $label = $this->label($name, $options); $options = $this->expandOptionArray($name, $label, $options); $classes = $this->getHolderClasses($name); $selected = request()->old($name) ?? []; // get all asset accounts: - $types = [AccountTypeEnum::ASSET->value, AccountTypeEnum::DEFAULT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::DEBT->value]; - $grouped = $this->getAccountsGrouped($types); + $types = [ + AccountTypeEnum::ASSET->value, + AccountTypeEnum::DEFAULT->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::MORTGAGE->value, + AccountTypeEnum::DEBT->value + ]; + $grouped = $this->getAccountsGrouped($types); unset($options['class']); try { - $html = view('form.assetAccountCheckList', ['classes' => $classes, 'selected' => $selected, 'name' => $name, 'label' => $label, 'options' => $options, 'grouped' => $grouped])->render(); + $html = view('form.assetAccountCheckList', [ + 'classes' => $classes, + 'selected' => $selected, + 'name' => $name, + 'label' => $label, + 'options' => $options, + 'grouped' => $grouped + ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render assetAccountCheckList(): %s', $e->getMessage())); $html = 'Could not render assetAccountCheckList.'; @@ -110,7 +135,7 @@ class AccountForm * * @param mixed $value */ - public function assetAccountList(string $name, $value = null, ?array $options = null): string + public function assetAccountList(string $name, $value = null, null|array $options = null): string { $types = [AccountTypeEnum::ASSET->value, AccountTypeEnum::DEFAULT->value]; $grouped = $this->getAccountsGrouped($types); @@ -123,9 +148,15 @@ class AccountForm * * @param mixed $value */ - public function assetLiabilityMultiAccountList(string $name, $value = null, ?array $options = null): string + public function assetLiabilityMultiAccountList(string $name, $value = null, null|array $options = null): string { - $types = [AccountTypeEnum::ASSET->value, AccountTypeEnum::DEFAULT->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value]; + $types = [ + AccountTypeEnum::ASSET->value, + AccountTypeEnum::DEFAULT->value, + AccountTypeEnum::MORTGAGE->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::LOAN->value + ]; $grouped = $this->getAccountsGrouped($types); return $this->multiSelect($name, $grouped, $value, $options); @@ -136,15 +167,21 @@ class AccountForm * * @param mixed $value */ - public function longAccountList(string $name, $value = null, ?array $options = null): string + public function longAccountList(string $name, $value = null, null|array $options = null): string { - $types = [AccountTypeEnum::ASSET->value, AccountTypeEnum::DEFAULT->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value]; + $types = [ + AccountTypeEnum::ASSET->value, + AccountTypeEnum::DEFAULT->value, + AccountTypeEnum::MORTGAGE->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::LOAN->value + ]; $grouped = $this->getAccountsGrouped($types); return $this->select($name, $grouped, $value, $options); } - private function getAccountsGrouped(array $types, ?AccountRepositoryInterface $repository = null): array + private function getAccountsGrouped(array $types, null|AccountRepositoryInterface $repository = null): array { if (!$repository instanceof AccountRepositoryInterface) { $repository = $this->getAccountRepository(); @@ -155,7 +192,7 @@ class AccountForm /** @var Account $account */ foreach ($accountList as $account) { - $role = (string)$repository->getMetaValue($account, 'account_role'); + $role = (string) $repository->getMetaValue($account, 'account_role'); if (in_array($account->accountType->type, $liabilityTypes, true)) { $role = sprintf('l_%s', $account->accountType->type); } @@ -168,7 +205,7 @@ class AccountForm $role = 'revenue_account'; } } - $key = (string)trans(sprintf('firefly.opt_group_%s', $role)); + $key = (string) trans(sprintf('firefly.opt_group_%s', $role)); $grouped[$key][$account->id] = $account->name; } diff --git a/app/Support/Form/CurrencyForm.php b/app/Support/Form/CurrencyForm.php index 9e7188b8d9..cbb198ec58 100644 --- a/app/Support/Form/CurrencyForm.php +++ b/app/Support/Form/CurrencyForm.php @@ -24,14 +24,14 @@ declare(strict_types=1); namespace FireflyIII\Support\Form; -use Illuminate\Support\Facades\Log; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\TransactionCurrency; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; -use Illuminate\Support\Collection; -use Throwable; -use FireflyIII\Support\Facades\Steam; use FireflyIII\Support\Facades\Amount; +use FireflyIII\Support\Facades\Steam; +use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Log; +use Throwable; /** * Class CurrencyForm @@ -47,7 +47,7 @@ class CurrencyForm * * @throws FireflyException */ - public function amount(string $name, $value = null, ?array $options = null): string + public function amount(string $name, $value = null, null|array $options = null): string { return $this->currencyField($name, 'amount', $value, $options); } @@ -59,7 +59,7 @@ class CurrencyForm * * @throws FireflyException */ - public function balanceAll(string $name, $value = null, ?array $options = null): string + public function balanceAll(string $name, $value = null, null|array $options = null): string { return $this->allCurrencyField($name, 'balance', $value, $options); } @@ -69,18 +69,18 @@ class CurrencyForm * * @param mixed $value */ - public function currencyList(string $name, $value = null, ?array $options = null): string + public function currencyList(string $name, $value = null, null|array $options = null): string { /** @var CurrencyRepositoryInterface $currencyRepos */ $currencyRepos = app(CurrencyRepositoryInterface::class); // get all currencies: - $list = $currencyRepos->get(); - $array = []; + $list = $currencyRepos->get(); + $array = []; /** @var TransactionCurrency $currency */ foreach ($list as $currency) { - $array[$currency->id] = $currency->name.' ('.$currency->symbol.')'; + $array[$currency->id] = $currency->name . ' (' . $currency->symbol . ')'; } return $this->select($name, $array, $value, $options); @@ -91,20 +91,18 @@ class CurrencyForm * * @param mixed $value */ - public function currencyListEmpty(string $name, $value = null, ?array $options = null): string + public function currencyListEmpty(string $name, $value = null, null|array $options = null): string { /** @var CurrencyRepositoryInterface $currencyRepos */ $currencyRepos = app(CurrencyRepositoryInterface::class); // get all currencies: - $list = $currencyRepos->get(); - $array = [ - 0 => (string)trans('firefly.no_currency'), - ]; + $list = $currencyRepos->get(); + $array = [0 => (string) trans('firefly.no_currency')]; /** @var TransactionCurrency $currency */ foreach ($list as $currency) { - $array[$currency->id] = $currency->name.' ('.$currency->symbol.')'; + $array[$currency->id] = $currency->name . ' (' . $currency->symbol . ')'; } return $this->select($name, $array, $value, $options); @@ -117,26 +115,26 @@ class CurrencyForm * * @throws FireflyException */ - protected function allCurrencyField(string $name, string $view, $value = null, ?array $options = null): string + protected function allCurrencyField(string $name, string $view, $value = null, null|array $options = null): string { - $label = $this->label($name, $options); - $options = $this->expandOptionArray($name, $label, $options); - $classes = $this->getHolderClasses($name); - $value = $this->fillFieldValue($name, $value); + $label = $this->label($name, $options); + $options = $this->expandOptionArray($name, $label, $options); + $classes = $this->getHolderClasses($name); + $value = $this->fillFieldValue($name, $value); $options['step'] = 'any'; $primaryCurrency = $options['currency'] ?? Amount::getPrimaryCurrency(); /** @var Collection $currencies */ - $currencies = Amount::getAllCurrencies(); + $currencies = Amount::getAllCurrencies(); unset($options['currency'], $options['placeholder']); // perhaps the currency has been sent to us in the field $amount_currency_id_$name (amount_currency_id_amount) - $preFilled = session('preFilled'); + $preFilled = session('preFilled'); if (!is_array($preFilled)) { $preFilled = []; } - $key = 'amount_currency_id_'.$name; - $sentCurrencyId = array_key_exists($key, $preFilled) ? (int)$preFilled[$key] : $primaryCurrency->id; + $key = 'amount_currency_id_' . $name; + $sentCurrencyId = array_key_exists($key, $preFilled) ? (int) $preFilled[$key] : $primaryCurrency->id; Log::debug(sprintf('Sent currency ID is %d', $sentCurrencyId)); @@ -156,7 +154,15 @@ class CurrencyForm } try { - $html = view('form.'.$view, ['primaryCurrency' => $primaryCurrency, 'currencies' => $currencies, 'classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render(); + $html = view('form.' . $view, [ + 'primaryCurrency' => $primaryCurrency, + 'currencies' => $currencies, + 'classes' => $classes, + 'name' => $name, + 'label' => $label, + 'value' => $value, + 'options' => $options + ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render currencyField(): %s', $e->getMessage())); $html = 'Could not render currencyField.'; @@ -170,25 +176,25 @@ class CurrencyForm /** * @throws FireflyException */ - protected function currencyField(string $name, string $view, mixed $value = null, ?array $options = null): string + protected function currencyField(string $name, string $view, mixed $value = null, null|array $options = null): string { - $label = $this->label($name, $options); - $options = $this->expandOptionArray($name, $label, $options); - $classes = $this->getHolderClasses($name); - $value = $this->fillFieldValue($name, $value); + $label = $this->label($name, $options); + $options = $this->expandOptionArray($name, $label, $options); + $classes = $this->getHolderClasses($name); + $value = $this->fillFieldValue($name, $value); $options['step'] = 'any'; $primaryCurrency = $options['currency'] ?? Amount::getPrimaryCurrency(); /** @var Collection $currencies */ - $currencies = Amount::getCurrencies(); + $currencies = Amount::getCurrencies(); unset($options['currency'], $options['placeholder']); // perhaps the currency has been sent to us in the field $amount_currency_id_$name (amount_currency_id_amount) - $preFilled = session('preFilled'); + $preFilled = session('preFilled'); if (!is_array($preFilled)) { $preFilled = []; } - $key = 'amount_currency_id_'.$name; - $sentCurrencyId = array_key_exists($key, $preFilled) ? (int)$preFilled[$key] : $primaryCurrency->id; + $key = 'amount_currency_id_' . $name; + $sentCurrencyId = array_key_exists($key, $preFilled) ? (int) $preFilled[$key] : $primaryCurrency->id; Log::debug(sprintf('Sent currency ID is %d', $sentCurrencyId)); @@ -208,7 +214,15 @@ class CurrencyForm } try { - $html = view('form.'.$view, ['primaryCurrency' => $primaryCurrency, 'currencies' => $currencies, 'classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render(); + $html = view('form.' . $view, [ + 'primaryCurrency' => $primaryCurrency, + 'currencies' => $currencies, + 'classes' => $classes, + 'name' => $name, + 'label' => $label, + 'value' => $value, + 'options' => $options + ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render currencyField(): %s', $e->getMessage())); $html = 'Could not render currencyField.'; diff --git a/app/Support/Form/FormSupport.php b/app/Support/Form/FormSupport.php index ff1a1f0a7b..ba2fa555ff 100644 --- a/app/Support/Form/FormSupport.php +++ b/app/Support/Form/FormSupport.php @@ -24,9 +24,9 @@ declare(strict_types=1); namespace FireflyIII\Support\Form; -use Illuminate\Support\Facades\Log; use Carbon\Carbon; use FireflyIII\Repositories\Account\AccountRepositoryInterface; +use Illuminate\Support\Facades\Log; use Illuminate\Support\MessageBag; use Throwable; @@ -35,9 +35,9 @@ use Throwable; */ trait FormSupport { - public function multiSelect(string $name, ?array $list = null, mixed $selected = null, ?array $options = null): string + public function multiSelect(string $name, null|array $list = null, mixed $selected = null, null|array $options = null): string { - $list ??= []; + $list ??= []; $label = $this->label($name, $options); $options = $this->expandOptionArray($name, $label, $options); $classes = $this->getHolderClasses($name); @@ -46,7 +46,14 @@ trait FormSupport unset($options['autocomplete'], $options['placeholder']); try { - $html = view('form.multi-select', ['classes' => $classes, 'name' => $name, 'label' => $label, 'selected' => $selected, 'options' => $options, 'list' => $list])->render(); + $html = view('form.multi-select', [ + 'classes' => $classes, + 'name' => $name, + 'label' => $label, + 'selected' => $selected, + 'options' => $options, + 'list' => $list + ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render multi-select(): %s', $e->getMessage())); $html = 'Could not render multi-select.'; @@ -58,9 +65,9 @@ trait FormSupport /** * @param mixed $selected */ - public function select(string $name, ?array $list = null, $selected = null, ?array $options = null): string + public function select(string $name, null|array $list = null, $selected = null, null|array $options = null): string { - $list ??= []; + $list ??= []; $label = $this->label($name, $options); $options = $this->expandOptionArray($name, $label, $options); $classes = $this->getHolderClasses($name); @@ -68,7 +75,14 @@ trait FormSupport unset($options['autocomplete'], $options['placeholder']); try { - $html = view('form.select', ['classes' => $classes, 'name' => $name, 'label' => $label, 'selected' => $selected, 'options' => $options, 'list' => $list])->render(); + $html = view('form.select', [ + 'classes' => $classes, + 'name' => $name, + 'label' => $label, + 'selected' => $selected, + 'options' => $options, + 'list' => $list + ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Could not render select(): %s', $e->getMessage())); $html = 'Could not render select.'; @@ -80,14 +94,14 @@ trait FormSupport /** * @param mixed $label */ - protected function expandOptionArray(string $name, $label, ?array $options = null): array + protected function expandOptionArray(string $name, $label, null|array $options = null): array { $options ??= []; - $name = str_replace('[]', '', $name); - $options['class'] = 'form-control'; - $options['id'] = 'ffInput_'.$name; + $name = str_replace('[]', '', $name); + $options['class'] = 'form-control'; + $options['id'] = 'ffInput_' . $name; $options['autocomplete'] = 'off'; - $options['placeholder'] = ucfirst((string)$label); + $options['placeholder'] = ucfirst((string) $label); return $options; } @@ -138,7 +152,7 @@ trait FormSupport return 'form-group'; } - protected function label(string $name, ?array $options = null): string + protected function label(string $name, null|array $options = null): string { $options ??= []; if (array_key_exists('label', $options)) { @@ -146,6 +160,6 @@ trait FormSupport } $name = str_replace('[]', '', $name); - return (string)trans('form.'.$name); + return (string) trans('form.' . $name); } } diff --git a/app/Support/Form/PiggyBankForm.php b/app/Support/Form/PiggyBankForm.php index 0818d96157..27e2324b49 100644 --- a/app/Support/Form/PiggyBankForm.php +++ b/app/Support/Form/PiggyBankForm.php @@ -41,45 +41,31 @@ class PiggyBankForm * * @param mixed $value */ - public function piggyBankList(string $name, $value = null, ?array $options = null): string + public function piggyBankList(string $name, $value = null, null|array $options = null): string { // make repositories /** @var PiggyBankRepositoryInterface $repository */ $repository = app(PiggyBankRepositoryInterface::class); $piggyBanks = $repository->getPiggyBanksWithAmount(); - $title = (string)trans('firefly.default_group_title_name'); + $title = (string) trans('firefly.default_group_title_name'); $array = []; - $subList = [ - 0 => [ - 'group' => [ - 'title' => $title, - ], - 'piggies' => [ - (string)trans('firefly.none_in_select_list'), - ], - ], - ]; + $subList = [0 => ['group' => ['title' => $title], 'piggies' => [(string) trans('firefly.none_in_select_list')]]]; /** @var PiggyBank $piggy */ foreach ($piggyBanks as $piggy) { - $group = $piggy->objectGroups->first(); - $groupTitle = null; - $groupOrder = 0; + $group = $piggy->objectGroups->first(); + $groupTitle = null; + $groupOrder = 0; if (null !== $group) { $groupTitle = $group->title; $groupOrder = $group->order; } - $subList[$groupOrder] ??= [ - 'group' => [ - 'title' => $groupTitle, - ], - 'piggies' => [], - ]; + $subList[$groupOrder] ??= ['group' => ['title' => $groupTitle], 'piggies' => []]; $subList[$groupOrder]['piggies'][$piggy->id] = $piggy->name; } ksort($subList); foreach ($subList as $info) { - $groupTitle = $info['group']['title']; + $groupTitle = $info['group']['title']; $array[$groupTitle] = $info['piggies']; } diff --git a/app/Support/Form/RuleForm.php b/app/Support/Form/RuleForm.php index 066fdbb5f8..b84d4e6ad0 100644 --- a/app/Support/Form/RuleForm.php +++ b/app/Support/Form/RuleForm.php @@ -35,14 +35,14 @@ class RuleForm { use FormSupport; - public function ruleGroupList(string $name, mixed $value = null, ?array $options = null): string + public function ruleGroupList(string $name, mixed $value = null, null|array $options = null): string { /** @var RuleGroupRepositoryInterface $groupRepos */ $groupRepos = app(RuleGroupRepositoryInterface::class); // get all currencies: - $list = $groupRepos->get(); - $array = []; + $list = $groupRepos->get(); + $array = []; /** @var RuleGroup $group */ foreach ($list as $group) { @@ -52,23 +52,21 @@ class RuleForm return $this->select($name, $array, $value, $options); } - public function ruleGroupListWithEmpty(string $name, $value = null, ?array $options = null): string + public function ruleGroupListWithEmpty(string $name, $value = null, null|array $options = null): string { $options ??= []; $options['class'] = 'form-control'; /** @var RuleGroupRepositoryInterface $groupRepos */ - $groupRepos = app(RuleGroupRepositoryInterface::class); + $groupRepos = app(RuleGroupRepositoryInterface::class); // get all currencies: - $list = $groupRepos->get(); - $array = [ - 0 => (string)trans('firefly.none_in_select_list'), - ]; + $list = $groupRepos->get(); + $array = [0 => (string) trans('firefly.none_in_select_list')]; /** @var RuleGroup $group */ foreach ($list as $group) { - if (array_key_exists('hidden', $options) && (int)$options['hidden'] !== $group->id) { + if (array_key_exists('hidden', $options) && (int) $options['hidden'] !== $group->id) { $array[$group->id] = $group->title; } } diff --git a/app/Support/Http/Api/AccountBalanceGrouped.php b/app/Support/Http/Api/AccountBalanceGrouped.php index 060371a4a5..170d314b2c 100644 --- a/app/Support/Http/Api/AccountBalanceGrouped.php +++ b/app/Support/Http/Api/AccountBalanceGrouped.php @@ -39,16 +39,16 @@ use Illuminate\Support\Facades\Log; */ class AccountBalanceGrouped { - private array $accountIds = []; - private string $carbonFormat; + private array $accountIds = []; + private string $carbonFormat; private readonly ExchangeRateConverter $converter; - private array $currencies = []; - private array $data = []; - private Carbon $end; - private array $journals = []; - private string $preferredRange; - private TransactionCurrency $primary; - private Carbon $start; + private array $currencies = []; + private array $data = []; + private Carbon $end; + private array $journals = []; + private string $preferredRange; + private TransactionCurrency $primary; + private Carbon $start; public function __construct() { @@ -66,13 +66,13 @@ 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_id' => (string) $currency['currency_id'], 'currency_symbol' => $currency['currency_symbol'], 'currency_code' => $currency['currency_code'], 'currency_decimal_places' => $currency['currency_decimal_places'], - 'primary_currency_id' => (string)$currency['primary_currency_id'], + 'primary_currency_id' => (string) $currency['primary_currency_id'], 'primary_currency_symbol' => $currency['primary_currency_symbol'], 'primary_currency_code' => $currency['primary_currency_code'], 'primary_currency_decimal_places' => $currency['primary_currency_decimal_places'], @@ -83,15 +83,15 @@ class AccountBalanceGrouped 'type' => 'line', 'period' => $this->preferredRange, 'entries' => [], - 'pc_entries' => [], + 'pc_entries' => [] ]; - $expense = [ + $expense = [ 'label' => 'spent', - 'currency_id' => (string)$currency['currency_id'], + 'currency_id' => (string) $currency['currency_id'], 'currency_symbol' => $currency['currency_symbol'], 'currency_code' => $currency['currency_code'], 'currency_decimal_places' => $currency['currency_decimal_places'], - 'primary_currency_id' => (string)$currency['primary_currency_id'], + 'primary_currency_id' => (string) $currency['primary_currency_id'], 'primary_currency_symbol' => $currency['primary_currency_symbol'], 'primary_currency_code' => $currency['primary_currency_code'], 'primary_currency_decimal_places' => $currency['primary_currency_decimal_places'], @@ -102,27 +102,27 @@ class AccountBalanceGrouped 'yAxisID' => 0, 'period' => $this->preferredRange, 'entries' => [], - 'pc_entries' => [], + 'pc_entries' => [] ]; // 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']); + $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; @@ -163,25 +163,25 @@ class AccountBalanceGrouped public function setPreferredRange(string $preferredRange): void { $this->preferredRange = $preferredRange; - $this->carbonFormat = Navigation::preferredCarbonFormatByPeriod($preferredRange); + $this->carbonFormat = Navigation::preferredCarbonFormatByPeriod($preferredRange); } public function setPrimary(TransactionCurrency $primary): void { - $this->primary = $primary; - $primaryCurrencyId = $primary->id; - $this->currencies = [$primary->id => $primary]; // currency cache + $this->primary = $primary; + $primaryCurrencyId = $primary->id; + $this->currencies = [$primary->id => $primary]; // currency cache $this->data[$primaryCurrencyId] = [ - 'currency_id' => (string)$primaryCurrencyId, + 'currency_id' => (string) $primaryCurrencyId, 'currency_symbol' => $primary->symbol, 'currency_code' => $primary->code, 'currency_name' => $primary->name, 'currency_decimal_places' => $primary->decimal_places, - 'primary_currency_id' => (string)$primaryCurrencyId, + 'primary_currency_id' => (string) $primaryCurrencyId, 'primary_currency_symbol' => $primary->symbol, 'primary_currency_code' => $primary->code, 'primary_currency_name' => $primary->name, - 'primary_currency_decimal_places' => $primary->decimal_places, + 'primary_currency_decimal_places' => $primary->decimal_places ]; } @@ -192,32 +192,26 @@ 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'], - 'currency_code' => $journal['currency_code'], - 'currency_name' => $journal['currency_name'], - 'currency_decimal_places' => $journal['currency_decimal_places'], + 'currency_id' => (string) $currencyId, + 'currency_symbol' => $journal['currency_symbol'], + 'currency_code' => $journal['currency_code'], + 'currency_name' => $journal['currency_name'], + 'currency_decimal_places' => $journal['currency_decimal_places'], // primary currency info (could be the same) - 'primary_currency_id' => (string)$this->primary->id, + 'primary_currency_id' => (string) $this->primary->id, 'primary_currency_code' => $this->primary->code, 'primary_currency_symbol' => $this->primary->symbol, - 'primary_currency_decimal_places' => $this->primary->decimal_places, + 'primary_currency_decimal_places' => $this->primary->decimal_places ]; } private function createDefaultPeriodEntry(array $journal): void { - $currencyId = (int)$journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $period = $journal['date']->format($this->carbonFormat); - $this->data[$currencyId][$period] ??= [ - 'period' => $period, - 'spent' => '0', - 'earned' => '0', - 'pc_spent' => '0', - 'pc_earned' => '0', - ]; + $this->data[$currencyId][$period] ??= ['period' => $period, 'spent' => '0', 'earned' => '0', 'pc_spent' => '0', 'pc_earned' => '0']; } private function findCurrency(int $currencyId): TransactionCurrency @@ -236,15 +230,12 @@ class AccountBalanceGrouped // transfer or reconcile or opening balance, and these accounts are the destination. if ( TransactionTypeEnum::DEPOSIT->value === $journal['transaction_type_type'] - || ( - ( - TransactionTypeEnum::TRANSFER->value === $journal['transaction_type_type'] - || TransactionTypeEnum::RECONCILIATION->value === $journal['transaction_type_type'] - || TransactionTypeEnum::OPENING_BALANCE->value === $journal['transaction_type_type'] - ) - && in_array($journal['destination_account_id'], $this->accountIds, true) + TransactionTypeEnum::TRANSFER->value === $journal['transaction_type_type'] + || TransactionTypeEnum::RECONCILIATION->value === $journal['transaction_type_type'] + || TransactionTypeEnum::OPENING_BALANCE->value === $journal['transaction_type_type'] ) + && in_array($journal['destination_account_id'], $this->accountIds, true) ) { return 'earned'; } @@ -267,9 +258,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); @@ -277,24 +268,24 @@ 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) { + if ((int) $journal['foreign_currency_id'] === $this->primary->id) { $amountConverted = $journal['foreign_amount'] ?? '0'; $amountConverted = 'earned' === $key ? Steam::positive($amountConverted) : Steam::negative($amountConverted); } // 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); - $this->data[$currencyId][$period][$convertedKey] = bcadd((string)$this->data[$currencyId][$period][$convertedKey], $amountConverted); + $convertedKey = sprintf('pc_%s', $key); + $this->data[$currencyId][$period][$convertedKey] = bcadd((string) $this->data[$currencyId][$period][$convertedKey], $amountConverted); } } diff --git a/app/Support/Http/Api/AccountFilter.php b/app/Support/Http/Api/AccountFilter.php index dcc74dcd21..c08ea05aff 100644 --- a/app/Support/Http/Api/AccountFilter.php +++ b/app/Support/Http/Api/AccountFilter.php @@ -31,67 +31,85 @@ use FireflyIII\Enums\AccountTypeEnum; */ trait AccountFilter { - protected array $types - = [ - 'all' => [ - AccountTypeEnum::DEFAULT->value, - AccountTypeEnum::CASH->value, - AccountTypeEnum::ASSET->value, - AccountTypeEnum::EXPENSE->value, - AccountTypeEnum::REVENUE->value, - AccountTypeEnum::INITIAL_BALANCE->value, - AccountTypeEnum::BENEFICIARY->value, - AccountTypeEnum::IMPORT->value, - AccountTypeEnum::RECONCILIATION->value, - AccountTypeEnum::LOAN->value, - AccountTypeEnum::DEBT->value, - AccountTypeEnum::MORTGAGE->value, - ], - 'normal' => [ - AccountTypeEnum::ASSET->value, - AccountTypeEnum::EXPENSE->value, - AccountTypeEnum::REVENUE->value, - AccountTypeEnum::LOAN->value, - AccountTypeEnum::DEBT->value, - AccountTypeEnum::MORTGAGE->value, - ], - 'asset' => [AccountTypeEnum::DEFAULT->value, AccountTypeEnum::ASSET->value], - 'cash' => [AccountTypeEnum::CASH->value], - 'expense' => [AccountTypeEnum::EXPENSE->value, AccountTypeEnum::BENEFICIARY->value], - 'revenue' => [AccountTypeEnum::REVENUE->value], - 'special' => [AccountTypeEnum::CASH->value, AccountTypeEnum::INITIAL_BALANCE->value, AccountTypeEnum::IMPORT->value, AccountTypeEnum::RECONCILIATION->value], - 'hidden' => [AccountTypeEnum::INITIAL_BALANCE->value, AccountTypeEnum::IMPORT->value, AccountTypeEnum::RECONCILIATION->value], - 'liability' => [AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::CREDITCARD->value], - 'liabilities' => [AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::CREDITCARD->value], - AccountTypeEnum::DEFAULT->value => [AccountTypeEnum::DEFAULT->value], - AccountTypeEnum::CASH->value => [AccountTypeEnum::CASH->value], - AccountTypeEnum::ASSET->value => [AccountTypeEnum::ASSET->value], - AccountTypeEnum::EXPENSE->value => [AccountTypeEnum::EXPENSE->value], - AccountTypeEnum::REVENUE->value => [AccountTypeEnum::REVENUE->value], - AccountTypeEnum::INITIAL_BALANCE->value => [AccountTypeEnum::INITIAL_BALANCE->value], - AccountTypeEnum::BENEFICIARY->value => [AccountTypeEnum::BENEFICIARY->value], - AccountTypeEnum::IMPORT->value => [AccountTypeEnum::IMPORT->value], - AccountTypeEnum::RECONCILIATION->value => [AccountTypeEnum::RECONCILIATION->value], - AccountTypeEnum::LOAN->value => [AccountTypeEnum::LOAN->value], - AccountTypeEnum::MORTGAGE->value => [AccountTypeEnum::MORTGAGE->value], - AccountTypeEnum::DEBT->value => [AccountTypeEnum::DEBT->value], - AccountTypeEnum::CREDITCARD->value => [AccountTypeEnum::CREDITCARD->value], - AccountTypeEnum::LIABILITY_CREDIT->value => [AccountTypeEnum::LIABILITY_CREDIT->value], - 'default account' => [AccountTypeEnum::DEFAULT->value], - 'cash account' => [AccountTypeEnum::CASH->value], - 'asset account' => [AccountTypeEnum::ASSET->value], - 'expense account' => [AccountTypeEnum::EXPENSE->value], - 'revenue account' => [AccountTypeEnum::REVENUE->value], - 'initial balance account' => [AccountTypeEnum::INITIAL_BALANCE->value], - 'reconciliation' => [AccountTypeEnum::RECONCILIATION->value], - 'loan' => [AccountTypeEnum::LOAN->value], - 'mortgage' => [AccountTypeEnum::MORTGAGE->value], - 'debt' => [AccountTypeEnum::DEBT->value], - 'credit card' => [AccountTypeEnum::CREDITCARD->value], - 'credit-card' => [AccountTypeEnum::CREDITCARD->value], - 'creditcard' => [AccountTypeEnum::CREDITCARD->value], - 'cc' => [AccountTypeEnum::CREDITCARD->value], - ]; + protected array $types = [ + 'all' => [ + AccountTypeEnum::DEFAULT->value, + AccountTypeEnum::CASH->value, + AccountTypeEnum::ASSET->value, + AccountTypeEnum::EXPENSE->value, + AccountTypeEnum::REVENUE->value, + AccountTypeEnum::INITIAL_BALANCE->value, + AccountTypeEnum::BENEFICIARY->value, + AccountTypeEnum::IMPORT->value, + AccountTypeEnum::RECONCILIATION->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::MORTGAGE->value + ], + 'normal' => [ + AccountTypeEnum::ASSET->value, + AccountTypeEnum::EXPENSE->value, + AccountTypeEnum::REVENUE->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::MORTGAGE->value + ], + 'asset' => [AccountTypeEnum::DEFAULT->value, AccountTypeEnum::ASSET->value], + 'cash' => [AccountTypeEnum::CASH->value], + 'expense' => [AccountTypeEnum::EXPENSE->value, AccountTypeEnum::BENEFICIARY->value], + 'revenue' => [AccountTypeEnum::REVENUE->value], + 'special' => [ + AccountTypeEnum::CASH->value, + AccountTypeEnum::INITIAL_BALANCE->value, + AccountTypeEnum::IMPORT->value, + AccountTypeEnum::RECONCILIATION->value + ], + 'hidden' => [ + AccountTypeEnum::INITIAL_BALANCE->value, + AccountTypeEnum::IMPORT->value, + AccountTypeEnum::RECONCILIATION->value + ], + 'liability' => [ + AccountTypeEnum::DEBT->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::MORTGAGE->value, + AccountTypeEnum::CREDITCARD->value + ], + 'liabilities' => [ + AccountTypeEnum::DEBT->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::MORTGAGE->value, + AccountTypeEnum::CREDITCARD->value + ], + AccountTypeEnum::DEFAULT->value => [AccountTypeEnum::DEFAULT->value], + AccountTypeEnum::CASH->value => [AccountTypeEnum::CASH->value], + AccountTypeEnum::ASSET->value => [AccountTypeEnum::ASSET->value], + AccountTypeEnum::EXPENSE->value => [AccountTypeEnum::EXPENSE->value], + AccountTypeEnum::REVENUE->value => [AccountTypeEnum::REVENUE->value], + AccountTypeEnum::INITIAL_BALANCE->value => [AccountTypeEnum::INITIAL_BALANCE->value], + AccountTypeEnum::BENEFICIARY->value => [AccountTypeEnum::BENEFICIARY->value], + AccountTypeEnum::IMPORT->value => [AccountTypeEnum::IMPORT->value], + AccountTypeEnum::RECONCILIATION->value => [AccountTypeEnum::RECONCILIATION->value], + AccountTypeEnum::LOAN->value => [AccountTypeEnum::LOAN->value], + AccountTypeEnum::MORTGAGE->value => [AccountTypeEnum::MORTGAGE->value], + AccountTypeEnum::DEBT->value => [AccountTypeEnum::DEBT->value], + AccountTypeEnum::CREDITCARD->value => [AccountTypeEnum::CREDITCARD->value], + AccountTypeEnum::LIABILITY_CREDIT->value => [AccountTypeEnum::LIABILITY_CREDIT->value], + 'default account' => [AccountTypeEnum::DEFAULT->value], + 'cash account' => [AccountTypeEnum::CASH->value], + 'asset account' => [AccountTypeEnum::ASSET->value], + 'expense account' => [AccountTypeEnum::EXPENSE->value], + 'revenue account' => [AccountTypeEnum::REVENUE->value], + 'initial balance account' => [AccountTypeEnum::INITIAL_BALANCE->value], + 'reconciliation' => [AccountTypeEnum::RECONCILIATION->value], + 'loan' => [AccountTypeEnum::LOAN->value], + 'mortgage' => [AccountTypeEnum::MORTGAGE->value], + 'debt' => [AccountTypeEnum::DEBT->value], + 'credit card' => [AccountTypeEnum::CREDITCARD->value], + 'credit-card' => [AccountTypeEnum::CREDITCARD->value], + 'creditcard' => [AccountTypeEnum::CREDITCARD->value], + 'cc' => [AccountTypeEnum::CREDITCARD->value] + ]; /** * All the available types. diff --git a/app/Support/Http/Api/CleansChartData.php b/app/Support/Http/Api/CleansChartData.php index aef2ec443f..f5c2f22ae1 100644 --- a/app/Support/Http/Api/CleansChartData.php +++ b/app/Support/Http/Api/CleansChartData.php @@ -47,7 +47,7 @@ trait CleansChartData * @var array $array */ foreach ($data as $index => $array) { - $array = $this->cleanSingleArray($index, $array); + $array = $this->cleanSingleArray($index, $array); $return[] = $array; } @@ -57,15 +57,12 @@ trait CleansChartData private function cleanSingleArray(mixed $index, array $array): array { if (array_key_exists('currency_id', $array)) { - $array['currency_id'] = (string)$array['currency_id']; + $array['currency_id'] = (string) $array['currency_id']; } if (array_key_exists('primary_currency_id', $array)) { - $array['primary_currency_id'] = (string)$array['primary_currency_id']; + $array['primary_currency_id'] = (string) $array['primary_currency_id']; } - $required = [ - 'start_date', 'end_date', 'period', 'yAxisID', 'type', 'entries', 'pc_entries', - 'currency_id', 'primary_currency_id', - ]; + $required = ['start_date', 'end_date', 'period', 'yAxisID', 'type', 'entries', 'pc_entries', 'currency_id', 'primary_currency_id']; foreach ($required as $field) { if (!array_key_exists($field, $array)) { throw new FireflyException(sprintf('Data-set "%s" is missing the "%s"-variable.', $index, $field)); diff --git a/app/Support/Http/Api/CollectsAccountsFromFilter.php b/app/Support/Http/Api/CollectsAccountsFromFilter.php index 3c17a34d80..0b87003b0f 100644 --- a/app/Support/Http/Api/CollectsAccountsFromFilter.php +++ b/app/Support/Http/Api/CollectsAccountsFromFilter.php @@ -24,8 +24,8 @@ declare(strict_types=1); namespace FireflyIII\Support\Http\Api; -use FireflyIII\Support\Facades\Preferences; use FireflyIII\Enums\AccountTypeEnum; +use FireflyIII\Support\Facades\Preferences; use Illuminate\Support\Collection; trait CollectsAccountsFromFilter @@ -40,7 +40,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); } @@ -53,7 +53,10 @@ trait CollectsAccountsFromFilter } // if no preselected, but no accounts: if ('empty' === $queryParameters['preselected'] && 0 === $collection->count()) { - $defaultSet = $this->repository->getAccountsByType([AccountTypeEnum::ASSET->value, AccountTypeEnum::DEFAULT->value])->pluck('id')->toArray(); + $defaultSet = $this->repository + ->getAccountsByType([AccountTypeEnum::ASSET->value, AccountTypeEnum::DEFAULT->value]) + ->pluck('id') + ->toArray(); $frontpage = Preferences::get('frontpageAccounts', $defaultSet); if (!(is_array($frontpage->data) && count($frontpage->data) > 0)) { @@ -66,7 +69,13 @@ trait CollectsAccountsFromFilter // both options are overruled by "preselected" if ('all' === $queryParameters['preselected']) { - return $this->repository->getAccountsByType([AccountTypeEnum::ASSET->value, AccountTypeEnum::DEFAULT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value]); + return $this->repository->getAccountsByType([ + AccountTypeEnum::ASSET->value, + AccountTypeEnum::DEFAULT->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::MORTGAGE->value + ]); } if ('assets' === $queryParameters['preselected'] || 'Asset account' === $queryParameters['preselected']) { return $this->repository->getAccountsByType([AccountTypeEnum::ASSET->value, AccountTypeEnum::DEFAULT->value]); diff --git a/app/Support/Http/Api/ExchangeRateConverter.php b/app/Support/Http/Api/ExchangeRateConverter.php index 752aafd3b0..6d8b5b9400 100644 --- a/app/Support/Http/Api/ExchangeRateConverter.php +++ b/app/Support/Http/Api/ExchangeRateConverter.php @@ -31,10 +31,10 @@ use FireflyIII\Models\TransactionCurrency; use FireflyIII\Models\UserGroup; use FireflyIII\Support\CacheProperties; use FireflyIII\Support\Facades\Amount; +use FireflyIII\Support\Facades\FireflyConfig; use FireflyIII\Support\Facades\Steam; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Log; -use FireflyIII\Support\Facades\FireflyConfig; /** * Class ExchangeRateConverter @@ -127,9 +127,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); @@ -145,22 +145,24 @@ 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) { // \Illuminate\Support\Facades\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); + // \Illuminate\Support\Facades\Log::debug(sprintf('Inverted rate for %s to EUR is %s.', $currency->code, $rate)); // return $rate; } // 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); + // \Illuminate\Support\Facades\Log::debug(sprintf('Backup rate for %s to EUR is %s.', $currency->code, $backup)); // return $backup; } @@ -169,14 +171,14 @@ class ExchangeRateConverter return '0'; } - private function getFromDB(int $from, int $to, string $date): ?string + private function getFromDB(int $from, int $to, string $date): null|string { if ($from === $to) { Log::debug('ExchangeRateConverter: From and to are the same, return "1".'); 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; @@ -186,7 +188,7 @@ class ExchangeRateConverter return $preparedRate; } - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($key); if ($cache->has()) { $rate = $cache->get(); @@ -199,15 +201,15 @@ class ExchangeRateConverter } /** @var null|CurrencyExchangeRate $result */ - $result = $this->userGroup->currencyExchangeRates() + $result = $this->userGroup + ->currencyExchangeRates() ->where('from_currency_id', $from) ->where('to_currency_id', $to) ->where('date', '<=', $date) ->orderBy('date', 'DESC') - ->first() - ; + ->first(); ++$this->queryCount; - $rate = (string)$result?->rate; + $rate = (string) $result?->rate; if ('' === $rate) { Log::debug(sprintf('ExchangeRateConverter: Found no rate for #%d->#%d (%s) in the DB.', $from, $to, $date)); @@ -223,17 +225,9 @@ class ExchangeRateConverter $cache->store($rate); // if the rate has not been cached during this particular run, save it - $this->prepared[$date] ??= [ - $from => [ - $to => $rate, - ], - ]; + $this->prepared[$date] ??= [$from => [$to => $rate]]; // also save the exchange rate the other way around: - $this->prepared[$date] ??= [ - $to => [ - $from => bcdiv('1', $rate), - ], - ]; + $this->prepared[$date] ??= [$to => [$from => bcdiv('1', $rate)]]; return $rate; } @@ -243,8 +237,8 @@ class ExchangeRateConverter */ private function getRate(TransactionCurrency $from, TransactionCurrency $to, Carbon $date): string { - $key = $this->getCacheKey($from, $to, $date); - $res = Cache::get($key); + $key = $this->getCacheKey($from, $to, $date); + $res = Cache::get($key); // find in cache if (null !== $res) { @@ -254,7 +248,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'))); @@ -263,7 +257,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); diff --git a/app/Support/Http/Api/SummaryBalanceGrouped.php b/app/Support/Http/Api/SummaryBalanceGrouped.php index 1bed87a1c6..c69c6f7766 100644 --- a/app/Support/Http/Api/SummaryBalanceGrouped.php +++ b/app/Support/Http/Api/SummaryBalanceGrouped.php @@ -31,12 +31,13 @@ use Illuminate\Support\Facades\Log; class SummaryBalanceGrouped { - private const string SUM = 'sum'; - private array $amounts = []; - private array $currencies = []; + private const string SUM = 'sum'; + + private array $amounts = []; + private array $currencies = []; private readonly CurrencyRepositoryInterface $currencyRepository; - private TransactionCurrency $default; - private array $keys = [self::SUM]; + private TransactionCurrency $default; + private array $keys = [self::SUM]; public function __construct() { @@ -46,22 +47,22 @@ class SummaryBalanceGrouped public function groupData(): array { Log::debug('Now going to group data.'); - $return = []; + $return = []; foreach ($this->keys as $key) { - $title = match ($key) { - 'sum' => 'balance', + $title = match ($key) { + 'sum' => 'balance', 'expense' => 'spent', - 'income' => 'earned', - default => 'something' + 'income' => 'earned', + default => 'something' }; $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, + 'currency_decimal_places' => $this->default->decimal_places ]; } // loop 3: format amounts: @@ -71,24 +72,24 @@ class SummaryBalanceGrouped // skip primary entries. continue; } - $currencyId = (int)$currencyId; - $currency = $this->currencies[$currencyId] ?? $this->currencyRepository->find($currencyId); + $currencyId = (int) $currencyId; + $currency = $this->currencies[$currencyId] ?? $this->currencyRepository->find($currencyId); $this->currencies[$currencyId] = $currency; // create objects for big array. foreach ($this->keys as $key) { - $title = match ($key) { - 'sum' => 'balance', + $title = match ($key) { + 'sum' => 'balance', 'expense' => 'spent', - 'income' => 'earned', - default => 'something' + 'income' => 'earned', + default => 'something' }; $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, + 'currency_decimal_places' => $currency->decimal_places ]; } } @@ -100,34 +101,34 @@ class SummaryBalanceGrouped { Log::debug(sprintf('Created new ExchangeRateConverter in %s', __METHOD__)); Log::debug(sprintf('Now in groupTransactions with key "%s" and %d journal(s)', $key, count($journals))); - $converter = new ExchangeRateConverter(); + $converter = new ExchangeRateConverter(); $this->keys[] = $key; - $multiplier = 'income' === $key ? '-1' : '1'; + $multiplier = 'income' === $key ? '-1' : '1'; /** @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']; } // prep the arrays - $this->amounts[$key] ??= []; - $this->amounts[$key][$currencyId] ??= '0'; - $this->amounts[$key]['primary'] ??= '0'; + $this->amounts[$key] ??= []; + $this->amounts[$key][$currencyId] ??= '0'; + $this->amounts[$key]['primary'] ??= '0'; $this->amounts[self::SUM][$currencyId] ??= '0'; - $this->amounts[self::SUM]['primary'] ??= '0'; + $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/TransactionFilter.php b/app/Support/Http/Api/TransactionFilter.php index 4d75755e29..fb6802347e 100644 --- a/app/Support/Http/Api/TransactionFilter.php +++ b/app/Support/Http/Api/TransactionFilter.php @@ -31,36 +31,39 @@ use FireflyIII\Enums\TransactionTypeEnum; */ trait TransactionFilter { - protected $transactionTypes - = [ - 'all' => [ - TransactionTypeEnum::WITHDRAWAL->value, - TransactionTypeEnum::DEPOSIT->value, - TransactionTypeEnum::TRANSFER->value, - TransactionTypeEnum::OPENING_BALANCE->value, - TransactionTypeEnum::RECONCILIATION->value, - ], - TransactionTypeEnum::WITHDRAWAL->value => [TransactionTypeEnum::WITHDRAWAL->value], - 'withdrawal' => [TransactionTypeEnum::WITHDRAWAL->value], - 'withdrawals' => [TransactionTypeEnum::WITHDRAWAL->value], - 'expense' => [TransactionTypeEnum::WITHDRAWAL->value], - 'expenses' => [TransactionTypeEnum::WITHDRAWAL->value], - TransactionTypeEnum::DEPOSIT->value => [TransactionTypeEnum::DEPOSIT->value], - 'income' => [TransactionTypeEnum::DEPOSIT->value], - 'deposit' => [TransactionTypeEnum::DEPOSIT->value], - 'deposits' => [TransactionTypeEnum::DEPOSIT->value], - TransactionTypeEnum::TRANSFER->value => [TransactionTypeEnum::TRANSFER->value], - 'transfer' => [TransactionTypeEnum::TRANSFER->value], - 'transfers' => [TransactionTypeEnum::TRANSFER->value], - TransactionTypeEnum::OPENING_BALANCE->value => [TransactionTypeEnum::OPENING_BALANCE->value], - 'opening_balance' => [TransactionTypeEnum::OPENING_BALANCE->value], - TransactionTypeEnum::RECONCILIATION->value => [TransactionTypeEnum::RECONCILIATION->value], - 'reconciliation' => [TransactionTypeEnum::RECONCILIATION->value], - 'reconciliations' => [TransactionTypeEnum::RECONCILIATION->value], - 'special' => [TransactionTypeEnum::OPENING_BALANCE->value, TransactionTypeEnum::RECONCILIATION->value], - 'specials' => [TransactionTypeEnum::OPENING_BALANCE->value, TransactionTypeEnum::RECONCILIATION->value], - 'default' => [TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value], - ]; + protected $transactionTypes = [ + 'all' => [ + TransactionTypeEnum::WITHDRAWAL->value, + TransactionTypeEnum::DEPOSIT->value, + TransactionTypeEnum::TRANSFER->value, + TransactionTypeEnum::OPENING_BALANCE->value, + TransactionTypeEnum::RECONCILIATION->value + ], + TransactionTypeEnum::WITHDRAWAL->value => [TransactionTypeEnum::WITHDRAWAL->value], + 'withdrawal' => [TransactionTypeEnum::WITHDRAWAL->value], + 'withdrawals' => [TransactionTypeEnum::WITHDRAWAL->value], + 'expense' => [TransactionTypeEnum::WITHDRAWAL->value], + 'expenses' => [TransactionTypeEnum::WITHDRAWAL->value], + TransactionTypeEnum::DEPOSIT->value => [TransactionTypeEnum::DEPOSIT->value], + 'income' => [TransactionTypeEnum::DEPOSIT->value], + 'deposit' => [TransactionTypeEnum::DEPOSIT->value], + 'deposits' => [TransactionTypeEnum::DEPOSIT->value], + TransactionTypeEnum::TRANSFER->value => [TransactionTypeEnum::TRANSFER->value], + 'transfer' => [TransactionTypeEnum::TRANSFER->value], + 'transfers' => [TransactionTypeEnum::TRANSFER->value], + TransactionTypeEnum::OPENING_BALANCE->value => [TransactionTypeEnum::OPENING_BALANCE->value], + 'opening_balance' => [TransactionTypeEnum::OPENING_BALANCE->value], + TransactionTypeEnum::RECONCILIATION->value => [TransactionTypeEnum::RECONCILIATION->value], + 'reconciliation' => [TransactionTypeEnum::RECONCILIATION->value], + 'reconciliations' => [TransactionTypeEnum::RECONCILIATION->value], + 'special' => [TransactionTypeEnum::OPENING_BALANCE->value, TransactionTypeEnum::RECONCILIATION->value], + 'specials' => [TransactionTypeEnum::OPENING_BALANCE->value, TransactionTypeEnum::RECONCILIATION->value], + 'default' => [ + TransactionTypeEnum::WITHDRAWAL->value, + TransactionTypeEnum::DEPOSIT->value, + TransactionTypeEnum::TRANSFER->value + ] + ]; /** * All the types you can request. diff --git a/app/Support/Http/Api/ValidatesUserGroupTrait.php b/app/Support/Http/Api/ValidatesUserGroupTrait.php index 3d17a7b42c..a0423d7683 100644 --- a/app/Support/Http/Api/ValidatesUserGroupTrait.php +++ b/app/Support/Http/Api/ValidatesUserGroupTrait.php @@ -38,7 +38,7 @@ use Illuminate\Support\Facades\Log; */ trait ValidatesUserGroupTrait { - protected User $user; + protected User $user; protected UserGroup $userGroup; /** @@ -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); @@ -102,7 +102,7 @@ trait ValidatesUserGroupTrait if ($user->hasRoleInGroupOrOwner($group, $role)) { Log::debug(sprintf('validateUserGroup: User has role "%s" in group #%d, return the group.', $role->value, $groupId)); $this->userGroup = $group; - $this->user = $user; + $this->user = $user; return $group; } @@ -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 d7422f34c2..903eddee56 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); } @@ -106,17 +106,25 @@ trait AugumentData { /** @var AccountRepositoryInterface $repository */ $repository = app(AccountRepositoryInterface::class); - $accounts = $repository->getAccountsByType([AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::ASSET->value, AccountTypeEnum::DEFAULT->value, AccountTypeEnum::EXPENSE->value, AccountTypeEnum::CASH->value]); + $accounts = $repository->getAccountsByType([ + AccountTypeEnum::LOAN->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::MORTGAGE->value, + AccountTypeEnum::ASSET->value, + AccountTypeEnum::DEFAULT->value, + AccountTypeEnum::EXPENSE->value, + AccountTypeEnum::CASH->value + ]); $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 +144,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 +160,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; } @@ -166,19 +174,19 @@ trait AugumentData /** * Gets all budget limits for a budget. */ - protected function getLimits(Budget $budget, Carbon $start, Carbon $end): Collection // get data + augment with info - { + protected function getLimits(Budget $budget, Carbon $start, Carbon $end): Collection + { // get data + augment with info 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,39 +197,39 @@ 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; $currentEnd->addMonth(); } // primary currency amount. - $expenses = $opsRepository->sumExpenses($currentStart, $currentEnd, null, $budgetCollection, $entry->transactionCurrency, $this->convertToPrimary); - $spent = $expenses[$currency->id]['sum'] ?? '0'; + $expenses = $opsRepository->sumExpenses($currentStart, $currentEnd, null, $budgetCollection, $entry->transactionCurrency, $this->convertToPrimary); + $spent = $expenses[$currency->id]['sum'] ?? '0'; $entry->pc_spent = $spent; // normal amount: - $expenses = $opsRepository->sumExpenses($currentStart, $currentEnd, null, $budgetCollection, $entry->transactionCurrency); - $spent = $expenses[$entry->transactionCurrency->id]['sum'] ?? '0'; - $entry->spent = $spent; + $expenses = $opsRepository->sumExpenses($currentStart, $currentEnd, null, $budgetCollection, $entry->transactionCurrency); + $spent = $expenses[$entry->transactionCurrency->id]['sum'] ?? '0'; + $entry->spent = $spent; $limits->push($entry); } @@ -240,7 +248,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 +257,7 @@ trait AugumentData } $grouped[$name] ??= '0'; - $grouped[$name] = bcadd((string)$journal['amount'], $grouped[$name]); + $grouped[$name] = bcadd((string) $journal['amount'], $grouped[$name]); } return $grouped; @@ -258,21 +266,18 @@ trait AugumentData /** * Spent in a period. */ - protected function spentInPeriod(Collection $assets, Collection $opposing, Carbon $start, Carbon $end): array // get data + augment with info - { + protected function spentInPeriod(Collection $assets, Collection $opposing, Carbon $start, Carbon $end): array + { // get data + augment with info /** @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 = [ - 'grand_sum' => '0', - 'per_currency' => [], - ]; + $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'])) { @@ -281,14 +286,14 @@ trait AugumentData 'currency' => [ 'name' => $journal['currency_name'], 'symbol' => $journal['currency_symbol'], - 'decimal_places' => $journal['currency_decimal_places'], - ], + 'decimal_places' => $journal['currency_decimal_places'] + ] ]; } // 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/BasicDataSupport.php b/app/Support/Http/Controllers/BasicDataSupport.php index 702b1bbc4c..77b8a17420 100644 --- a/app/Support/Http/Controllers/BasicDataSupport.php +++ b/app/Support/Http/Controllers/BasicDataSupport.php @@ -46,7 +46,7 @@ trait BasicDataSupport /** * Find the ID in a given array. Return null if not there (amount). */ - protected function isInArrayDate(array $array, int $entryId): ?Carbon + protected function isInArrayDate(array $array, int $entryId): null|Carbon { return $array[$entryId] ?? null; } diff --git a/app/Support/Http/Controllers/ChartGeneration.php b/app/Support/Http/Controllers/ChartGeneration.php index 3480b03078..de2be2f248 100644 --- a/app/Support/Http/Controllers/ChartGeneration.php +++ b/app/Support/Http/Controllers/ChartGeneration.php @@ -45,8 +45,8 @@ trait ChartGeneration * * @throws FireflyException */ - protected function accountBalanceChart(Collection $accounts, Carbon $start, Carbon $end): array // chart helper method. - { + protected function accountBalanceChart(Collection $accounts, Carbon $start, Carbon $end): array + { // chart helper method. // chart properties for cache: $convertToPrimary = Amount::convertToPrimary(); $cache = new CacheProperties(); @@ -59,48 +59,44 @@ trait ChartGeneration return $cache->get(); } Log::debug('Regenerate chart.account.account-balance-chart from scratch.'); - $locale = Steam::getLocale(); + $locale = 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 = Amount::getPrimaryCurrency(); - $chartData = []; + $primary = 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 = [ - 'label' => $account->name, - 'currency_symbol' => $currency->symbol, - 'entries' => [], - ]; + $currentSet = ['label' => $account->name, 'currency_symbol' => $currency->symbol, 'entries' => []]; $currentStart = clone $start; $range = Steam::finalAccountBalanceInRange($account, clone $start, clone $end, $this->convertToPrimary); $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 a69c44ac54..e26076f379 100644 --- a/app/Support/Http/Controllers/CreateStuff.php +++ b/app/Support/Http/Controllers/CreateStuff.php @@ -43,8 +43,8 @@ trait CreateStuff /** * Creates an asset account. */ - protected function createAssetAccount(NewUserFormRequest $request, TransactionCurrency $currency): bool // create stuff - { + protected function createAssetAccount(NewUserFormRequest $request, TransactionCurrency $currency): bool + { // create stuff /** @var AccountRepositoryInterface $repository */ $repository = app(AccountRepositoryInterface::class); $assetAccount = [ @@ -57,7 +57,7 @@ trait CreateStuff 'account_role' => 'defaultAsset', 'opening_balance' => $request->input('bank_balance'), 'opening_balance_date' => new Carbon(), - 'currency_id' => $currency->id, + 'currency_id' => $currency->id ]; $repository->store($assetAccount); @@ -68,12 +68,12 @@ trait CreateStuff /** * Creates a cash wallet. */ - protected function createCashWalletAccount(TransactionCurrency $currency, string $language): bool // create stuff - { + protected function createCashWalletAccount(TransactionCurrency $currency, string $language): bool + { // create stuff /** @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, @@ -82,7 +82,7 @@ trait CreateStuff 'account_role' => 'cashWalletAsset', 'opening_balance' => null, 'opening_balance_date' => null, - 'currency_id' => $currency->id, + 'currency_id' => $currency->id ]; $repository->store($assetAccount); @@ -95,32 +95,29 @@ trait CreateStuff */ protected function createOAuthKeys(): void // create stuff { - [$publicKey, $privateKey] = [ - Passport::keyPath('oauth-public.key'), - Passport::keyPath('oauth-private.key'), - ]; + [$publicKey, $privateKey] = [Passport::keyPath('oauth-public.key'), Passport::keyPath('oauth-private.key')]; if (file_exists($publicKey) || file_exists($privateKey)) { 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')); } /** * Create a savings account. */ - protected function createSavingsAccount(NewUserFormRequest $request, TransactionCurrency $currency, string $language): bool // create stuff - { + protected function createSavingsAccount(NewUserFormRequest $request, TransactionCurrency $currency, string $language): bool + { // create stuff /** @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, @@ -129,7 +126,7 @@ trait CreateStuff 'account_role' => 'savingAsset', 'opening_balance' => $request->input('savings_balance'), 'opening_balance_date' => new Carbon(), - 'currency_id' => $currency->id, + 'currency_id' => $currency->id ]; $repository->store($savingsAccount); @@ -141,11 +138,6 @@ trait CreateStuff */ protected function createUser(array $data): User // create object { - return User::create( - [ - 'email' => $data['email'], - 'password' => bcrypt($data['password']), - ] - ); + return User::create(['email' => $data['email'], 'password' => bcrypt($data['password'])]); } } diff --git a/app/Support/Http/Controllers/CronRunner.php b/app/Support/Http/Controllers/CronRunner.php index ed3e950024..a25277c105 100644 --- a/app/Support/Http/Controllers/CronRunner.php +++ b/app/Support/Http/Controllers/CronRunner.php @@ -47,19 +47,14 @@ trait CronRunner try { $billWarning->fire(); } catch (FireflyException $e) { - return [ - 'job_fired' => false, - 'job_succeeded' => false, - 'job_errored' => true, - 'message' => $e->getMessage(), - ]; + return ['job_fired' => false, 'job_succeeded' => false, 'job_errored' => true, 'message' => $e->getMessage()]; } return [ 'job_fired' => $billWarning->jobFired, 'job_succeeded' => $billWarning->jobSucceeded, 'job_errored' => $billWarning->jobErrored, - 'message' => $billWarning->message, + 'message' => $billWarning->message ]; } @@ -73,19 +68,14 @@ trait CronRunner try { $exchangeRates->fire(); } catch (FireflyException $e) { - return [ - 'job_fired' => false, - 'job_succeeded' => false, - 'job_errored' => true, - 'message' => $e->getMessage(), - ]; + return ['job_fired' => false, 'job_succeeded' => false, 'job_errored' => true, 'message' => $e->getMessage()]; } return [ 'job_fired' => $exchangeRates->jobFired, 'job_succeeded' => $exchangeRates->jobSucceeded, 'job_errored' => $exchangeRates->jobErrored, - 'message' => $exchangeRates->message, + 'message' => $exchangeRates->message ]; } @@ -99,19 +89,14 @@ trait CronRunner try { $autoBudget->fire(); } catch (FireflyException $e) { - return [ - 'job_fired' => false, - 'job_succeeded' => false, - 'job_errored' => true, - 'message' => $e->getMessage(), - ]; + return ['job_fired' => false, 'job_succeeded' => false, 'job_errored' => true, 'message' => $e->getMessage()]; } return [ 'job_fired' => $autoBudget->jobFired, 'job_succeeded' => $autoBudget->jobSucceeded, 'job_errored' => $autoBudget->jobErrored, - 'message' => $autoBudget->message, + 'message' => $autoBudget->message ]; } @@ -125,19 +110,14 @@ trait CronRunner try { $recurring->fire(); } catch (FireflyException $e) { - return [ - 'job_fired' => false, - 'job_succeeded' => false, - 'job_errored' => true, - 'message' => $e->getMessage(), - ]; + return ['job_fired' => false, 'job_succeeded' => false, 'job_errored' => true, 'message' => $e->getMessage()]; } return [ 'job_fired' => $recurring->jobFired, 'job_succeeded' => $recurring->jobSucceeded, 'job_errored' => $recurring->jobErrored, - 'message' => $recurring->message, + 'message' => $recurring->message ]; } @@ -151,19 +131,14 @@ trait CronRunner try { $webhook->fire(); } catch (FireflyException $e) { - return [ - 'job_fired' => false, - 'job_succeeded' => false, - 'job_errored' => true, - 'message' => $e->getMessage(), - ]; + 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, + 'message' => $webhook->message ]; } } diff --git a/app/Support/Http/Controllers/DateCalculation.php b/app/Support/Http/Controllers/DateCalculation.php index f8d2204e21..fdf1bceea3 100644 --- a/app/Support/Http/Controllers/DateCalculation.php +++ b/app/Support/Http/Controllers/DateCalculation.php @@ -24,8 +24,8 @@ declare(strict_types=1); namespace FireflyIII\Support\Http\Controllers; -use FireflyIII\Support\Facades\Navigation; use Carbon\Carbon; +use FireflyIII\Support\Facades\Navigation; /** * Trait DateCalculation @@ -41,13 +41,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); } /** @@ -64,7 +64,7 @@ trait DateCalculation $difference = $start->diffInDays($today, true) + 1; } - return (int)$difference; + return (int) $difference; } protected function calculateStep(Carbon $start, Carbon $end): string @@ -91,23 +91,23 @@ trait DateCalculation protected function getNextPeriods(Carbon $date, string $range): array { // select thing for next 12 periods: - $loop = []; + $loop = []; /** @var Carbon $current */ $current = Navigation::startOfPeriod($date, $range); $current = Navigation::endOfPeriod($current, $range); $current->addDay(); - $count = 0; + $count = 0; while ($count < 12) { $current = Navigation::endOfPeriod($current, $range); $currentStart = Navigation::startOfPeriod($current, $range); - $loop[] = [ + $loop[] = [ 'label' => $current->format('Y-m-d'), 'title' => Navigation::periodShow($current, $range), 'start' => clone $currentStart, - 'end' => clone $current, + 'end' => clone $current ]; ++$count; $current->addDay(); @@ -123,7 +123,7 @@ trait DateCalculation protected function getPreviousPeriods(Carbon $date, string $range): array { // select thing for last 12 periods: - $loop = []; + $loop = []; /** @var Carbon $current */ $current = Navigation::startOfPeriod($date, $range); @@ -132,11 +132,11 @@ trait DateCalculation $current->subDay(); $current = Navigation::startOfPeriod($current, $range); $currentEnd = Navigation::endOfPeriod($current, $range); - $loop[] = [ + $loop[] = [ 'label' => $current->format('Y-m-d'), 'title' => Navigation::periodShow($current, $range), 'start' => clone $current, - 'end' => clone $currentEnd, + 'end' => clone $currentEnd ]; ++$count; } diff --git a/app/Support/Http/Controllers/GetConfigurationData.php b/app/Support/Http/Controllers/GetConfigurationData.php index ea6733cf1e..400003f0ca 100644 --- a/app/Support/Http/Controllers/GetConfigurationData.php +++ b/app/Support/Http/Controllers/GetConfigurationData.php @@ -24,10 +24,10 @@ declare(strict_types=1); namespace FireflyIII\Support\Http\Controllers; -use FireflyIII\Support\Facades\Navigation; use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Support\Facades\FireflyConfig; +use FireflyIII\Support\Facades\Navigation; use Illuminate\Support\Facades\Log; /** @@ -46,10 +46,10 @@ trait GetConfigurationData E_ALL => 'E_ALL', E_ALL & ~E_DEPRECATED => 'E_ALL & ~E_DEPRECATED ', E_ALL & ~E_NOTICE => 'E_ALL & ~E_NOTICE', - E_COMPILE_ERROR | E_RECOVERABLE_ERROR | E_ERROR | E_CORE_ERROR => 'E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR', + 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; } /** @@ -62,13 +62,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; } } Log::debug(sprintf('Total basic steps for %s is %d', $routeKey, count($steps))); @@ -83,25 +83,23 @@ trait GetConfigurationData */ protected function getDateRangeConfig(): array // get configuration + get preferences. { - $viewRange = Navigation::getViewRange(false); + $viewRange = 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 range is the current range: - $title => [$start, $end], - ]; + $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]]; Log::debug(sprintf('dateRange: the date range in the session is"%s" - "%s"', $start->format('Y-m-d'), $end->format('Y-m-d'))); // when current range is a custom range, add the current period as the next range. @@ -109,99 +107,99 @@ trait GetConfigurationData $index = Navigation::periodShow($start, $viewRange); $customPeriodStart = Navigation::startOfPeriod($start, $viewRange); $customPeriodEnd = Navigation::endOfPeriod($customPeriodStart, $viewRange); - $ranges[$index] = [$customPeriodStart, $customPeriodEnd]; + $ranges[$index] = [$customPeriodStart, $customPeriodEnd]; } // then add previous range and next range, but skip this for the lastX and YTD stuff. if (!in_array($viewRange, config('firefly.dynamic_date_ranges', []), true)) { - $previousDate = Navigation::subtractPeriod($start, $viewRange); - $index = Navigation::periodShow($previousDate, $viewRange); - $previousStart = Navigation::startOfPeriod($previousDate, $viewRange); - $previousEnd = Navigation::endOfPeriod($previousStart, $viewRange); + $previousDate = Navigation::subtractPeriod($start, $viewRange); + $index = Navigation::periodShow($previousDate, $viewRange); + $previousStart = Navigation::startOfPeriod($previousDate, $viewRange); + $previousEnd = Navigation::endOfPeriod($previousStart, $viewRange); $ranges[$index] = [$previousStart, $previousEnd]; - $nextDate = Navigation::addPeriod($start, $viewRange); - $index = Navigation::periodShow($nextDate, $viewRange); - $nextStart = Navigation::startOfPeriod($nextDate, $viewRange); - $nextEnd = Navigation::endOfPeriod($nextStart, $viewRange); + $nextDate = Navigation::addPeriod($start, $viewRange); + $index = Navigation::periodShow($nextDate, $viewRange); + $nextStart = Navigation::startOfPeriod($nextDate, $viewRange); + $nextEnd = Navigation::endOfPeriod($nextStart, $viewRange); $ranges[$index] = [$nextStart, $nextEnd]; } // today: /** @var Carbon $todayStart */ - $todayStart = Navigation::startOfPeriod($today, $viewRange); + $todayStart = Navigation::startOfPeriod($today, $viewRange); /** @var Carbon $todayEnd */ - $todayEnd = Navigation::endOfPeriod($todayStart, $viewRange); + $todayEnd = 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'); + $seven = today(config('app.timezone'))->subDays(7); + $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'); + $thirty = today(config('app.timezone'))->subDays(30); + $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'); + $monthBegin = today(config('app.timezone'))->startOfMonth(); + $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'); + $yearBegin = today(config('app.timezone'))->startOfYear(); + $index = (string) trans('firefly.year_to_date'); $ranges[$index] = [$yearBegin, new Carbon()]; // previous year: - $yearBegin = today(config('app.timezone'))->subYear()->startOfYear(); - $index = (string)trans('firefly.previous_year', ['year' => $yearBegin->year]); + $yearBegin = today(config('app.timezone'))->subYear()->startOfYear(); + $index = (string) trans('firefly.previous_year', ['year' => $yearBegin->year]); $ranges[$index] = [$yearBegin, $yearBegin->clone()->endOfYear()]; // 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, - ], + 'ranges' => $ranges + ] ]; } /** * Get specific info for special routes. */ - protected function getSpecificSteps(string $route, string $specificPage): array // get config values - { + protected function getSpecificSteps(string $route, string $specificPage): array + { // get config values $steps = []; $routeKey = ''; // 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; } } } @@ -213,7 +211,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(); Log::debug(sprintf('verifyRecurringCronJob: last time is %d ("%s"), now is %d', $lastTime, $config?->data, $now)); if (0 === $lastTime) { @@ -221,7 +219,7 @@ trait GetConfigurationData return; } - if ($now - $lastTime > 129600) { + if (($now - $lastTime) > 129600) { request()->session()->flash('warning', trans('firefly.recurring_cron_long_ago')); } } diff --git a/app/Support/Http/Controllers/ModelInformation.php b/app/Support/Http/Controllers/ModelInformation.php index 523c225d26..5cfb0bbc11 100644 --- a/app/Support/Http/Controllers/ModelInformation.php +++ b/app/Support/Http/Controllers/ModelInformation.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Support\Http\Controllers; -use Illuminate\Support\Facades\Log; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\AccountType; @@ -33,6 +32,7 @@ use FireflyIII\Models\Tag; use FireflyIII\Models\Transaction; use FireflyIII\Models\TransactionJournal; use FireflyIII\Repositories\Account\AccountRepositoryInterface; +use Illuminate\Support\Facades\Log; use Throwable; /** @@ -48,15 +48,12 @@ trait ModelInformation protected function getActionsForBill(Bill $bill): array // get info and argument { try { - $result = view( - 'rules.partials.action', - [ - 'oldAction' => 'link_to_bill', - 'oldValue' => $bill->name, - 'oldChecked' => false, - 'count' => 1, - ] - )->render(); + $result = view('rules.partials.action', [ + 'oldAction' => 'link_to_bill', + 'oldValue' => $bill->name, + 'oldChecked' => false, + 'count' => 1 + ])->render(); } catch (Throwable $e) { Log::error(sprintf('Throwable was thrown in getActionsForBill(): %s', $e->getMessage())); Log::error($e->getTraceAsString()); @@ -76,21 +73,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); @@ -101,7 +98,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; @@ -115,35 +112,27 @@ 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); $result = []; $billTriggers = ['currency_is', 'amount_more', 'amount_less', 'description_contains']; - $values = [ - $bill->transactionCurrency()->first()?->name, - $bill->amount_min, - $bill->amount_max, - $bill->name, - ]; + $values = [$bill->transactionCurrency()->first()?->name, $bill->amount_min, $bill->amount_max, $bill->name]; foreach ($billTriggers as $index => $trigger) { try { - $string = view( - 'rules.partials.trigger', - [ - 'oldTrigger' => $trigger, - 'oldValue' => $values[$index], - 'oldChecked' => false, - 'count' => $index + 1, - 'triggers' => $triggers, - ] - )->render(); + $string = view('rules.partials.trigger', [ + 'oldTrigger' => $trigger, + 'oldValue' => $values[$index], + 'oldChecked' => false, + 'count' => $index + 1, + 'triggers' => $triggers + ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Throwable was thrown in getTriggersForBill(): %s', $e->getMessage())); Log::debug($e->getTraceAsString()); @@ -166,88 +155,88 @@ 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; } // type $journalTriggers[$index] = 'transaction_type'; - $values[$index] = $journal->transactionType->type; + $values[$index] = $journal->transactionType->type; ++$index; // currency $journalTriggers[$index] = 'currency_is'; - $values[$index] = sprintf('%s (%s)', $journal->transactionCurrency?->name, $journal->transactionCurrency?->code); + $values[$index] = sprintf('%s (%s)', $journal->transactionCurrency?->name, $journal->transactionCurrency?->code); ++$index; // amount_exactly: $journalTriggers[$index] = 'amount_is'; - $values[$index] = $destination->amount; + $values[$index] = $destination->amount; ++$index; // description_is: $journalTriggers[$index] = 'description_is'; - $values[$index] = $journal->description; + $values[$index] = $journal->description; ++$index; // from_account_is $journalTriggers[$index] = 'source_account_is'; - $values[$index] = $source->account->name; + $values[$index] = $source->account->name; ++$index; // to_account_is $journalTriggers[$index] = 'destination_account_is'; - $values[$index] = $destination->account->name; + $values[$index] = $destination->account->name; ++$index; // category (if) - $category = $journal->categories()->first(); + $category = $journal->categories()->first(); if (null !== $category) { $journalTriggers[$index] = 'category_is'; - $values[$index] = $category->name; + $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; + $values[$index] = $budget->name; ++$index; } // tags (if) - $tags = $journal->tags()->get(); + $tags = $journal->tags()->get(); /** @var Tag $tag */ foreach ($tags as $tag) { $journalTriggers[$index] = 'tag_is'; - $values[$index] = $tag->tag; + $values[$index] = $tag->tag; ++$index; } // notes (if) - $notes = $journal->notes()->first(); + $notes = $journal->notes()->first(); if (null !== $notes) { $journalTriggers[$index] = 'notes_is'; - $values[$index] = $notes->text; + $values[$index] = $notes->text; } foreach ($journalTriggers as $ii => $trigger) { @@ -257,7 +246,7 @@ trait ModelInformation 'oldValue' => $values[$ii], 'oldChecked' => false, 'count' => $ii + 1, - 'triggers' => $triggers, + 'triggers' => $triggers ]; $string = view('rules.partials.trigger', $renderInfo)->render(); } catch (Throwable $e) { diff --git a/app/Support/Http/Controllers/PeriodOverview.php b/app/Support/Http/Controllers/PeriodOverview.php index 225e4033f0..0d57b4eae1 100644 --- a/app/Support/Http/Controllers/PeriodOverview.php +++ b/app/Support/Http/Controllers/PeriodOverview.php @@ -75,13 +75,13 @@ use Illuminate\Support\Str; */ trait PeriodOverview { - protected AccountRepositoryInterface $accountRepository; - protected CategoryRepositoryInterface $categoryRepository; - protected TagRepositoryInterface $tagRepository; - protected JournalRepositoryInterface $journalRepos; + protected AccountRepositoryInterface $accountRepository; + protected CategoryRepositoryInterface $categoryRepository; + protected TagRepositoryInterface $tagRepository; + protected JournalRepositoryInterface $journalRepos; protected PeriodStatisticRepositoryInterface $periodStatisticRepo; - private Collection $statistics; // temp data holder - private array $transactions; // temp data holder + private Collection $statistics; // temp data holder + private array $transactions; // temp data holder /** * This method returns "period entries", so nov-2015, dec-2015, etc. (this depends on the users session range) @@ -93,18 +93,18 @@ trait PeriodOverview protected function getAccountPeriodOverview(Account $account, Carbon $start, Carbon $end): array { Log::debug(sprintf('Now in getAccountPeriodOverview(#%d, %s %s)', $account->id, $start->format('Y-m-d H:i:s.u'), $end->format('Y-m-d H:i:s.u'))); - $this->accountRepository = app(AccountRepositoryInterface::class); + $this->accountRepository = app(AccountRepositoryInterface::class); $this->accountRepository->setUser($account->user); $this->periodStatisticRepo = app(PeriodStatisticRepositoryInterface::class); - $range = Navigation::getViewRange(true); - [$start, $end] = $end < $start ? [$end, $start] : [$start, $end]; + $range = Navigation::getViewRange(true); + [$start, $end] = $end < $start ? [$end, $start] : [$start, $end]; /** @var array $dates */ - $dates = Navigation::blockPeriods($start, $end, $range); - [$start, $end] = $this->getPeriodFromBlocks($dates, $start, $end); - $this->statistics = $this->periodStatisticRepo->allInRangeForModel($account, $start, $end); + $dates = Navigation::blockPeriods($start, $end, $range); + [$start, $end] = $this->getPeriodFromBlocks($dates, $start, $end); + $this->statistics = $this->periodStatisticRepo->allInRangeForModel($account, $start, $end); - $entries = []; + $entries = []; Log::debug(sprintf('Count of loops: %d', count($dates))); foreach ($dates as $currentDate) { $entries[] = $this->getSingleModelPeriod($account, $currentDate['period'], $currentDate['start'], $currentDate['end']); @@ -140,19 +140,18 @@ trait PeriodOverview */ protected function getCategoryPeriodOverview(Category $category, Carbon $start, Carbon $end): array { - $this->categoryRepository = app(CategoryRepositoryInterface::class); + $this->categoryRepository = app(CategoryRepositoryInterface::class); $this->categoryRepository->setUser($category->user); $this->periodStatisticRepo = app(PeriodStatisticRepositoryInterface::class); - $range = Navigation::getViewRange(true); - [$start, $end] = $end < $start ? [$end, $start] : [$start, $end]; + $range = Navigation::getViewRange(true); + [$start, $end] = $end < $start ? [$end, $start] : [$start, $end]; /** @var array $dates */ - $dates = Navigation::blockPeriods($start, $end, $range); - $entries = []; - [$start, $end] = $this->getPeriodFromBlocks($dates, $start, $end); - $this->statistics = $this->periodStatisticRepo->allInRangeForModel($category, $start, $end); - + $dates = Navigation::blockPeriods($start, $end, $range); + $entries = []; + [$start, $end] = $this->getPeriodFromBlocks($dates, $start, $end); + $this->statistics = $this->periodStatisticRepo->allInRangeForModel($category, $start, $end); Log::debug(sprintf('Count of loops: %d', count($dates))); foreach ($dates as $currentDate) { @@ -173,14 +172,14 @@ trait PeriodOverview { Log::debug(sprintf('Now in getNoModelPeriodOverview(%s, %s %s)', $model, $start->format('Y-m-d'), $end->format('Y-m-d'))); $this->periodStatisticRepo = app(PeriodStatisticRepositoryInterface::class); - $range = Navigation::getViewRange(true); - [$start, $end] = $end < $start ? [$end, $start] : [$start, $end]; + $range = Navigation::getViewRange(true); + [$start, $end] = $end < $start ? [$end, $start] : [$start, $end]; /** @var array $dates */ - $dates = Navigation::blockPeriods($start, $end, $range); - [$start, $end] = $this->getPeriodFromBlocks($dates, $start, $end); - $entries = []; - $this->statistics = $this->periodStatisticRepo->allInRangeForPrefix(sprintf('no_%s', $model), $start, $end); + $dates = Navigation::blockPeriods($start, $end, $range); + [$start, $end] = $this->getPeriodFromBlocks($dates, $start, $end); + $entries = []; + $this->statistics = $this->periodStatisticRepo->allInRangeForPrefix(sprintf('no_%s', $model), $start, $end); Log::debug(sprintf('Collected %d stats', $this->statistics->count())); foreach ($dates as $currentDate) { @@ -206,7 +205,7 @@ trait PeriodOverview case 'budget': // 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]); $spent = $collector->getExtractedJournals(); $earned = []; @@ -217,23 +216,23 @@ trait PeriodOverview case 'category': // 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]); - $earned = $collector->getExtractedJournals(); + $earned = $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]); - $spent = $collector->getExtractedJournals(); + $spent = $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]); @@ -244,15 +243,10 @@ trait PeriodOverview $groupedSpent = $this->groupByCurrency($spent); $groupedEarned = $this->groupByCurrency($earned); $groupedTransferred = $this->groupByCurrency($transferred); - $entry - = [ - 'title' => $title, - 'route' => route(sprintf('%s.no-%s', Str::plural($model), $model), [$start->format('Y-m-d'), $end->format('Y-m-d')]), - 'total_transactions' => count($spent), - 'spent' => $groupedSpent, - 'earned' => $groupedEarned, - 'transferred' => $groupedTransferred, - ]; + $entry = ['title' => $title, 'route' => route(sprintf('%s.no-%s', Str::plural($model), $model), [ + $start->format('Y-m-d'), + $end->format('Y-m-d') + ]), 'total_transactions' => count($spent), 'spent' => $groupedSpent, 'earned' => $groupedEarned, 'transferred' => $groupedTransferred]; $this->saveGroupedForPrefix(sprintf('no_%s', $model), $start, $end, 'spent', $groupedSpent); $this->saveGroupedForPrefix(sprintf('no_%s', $model), $start, $end, 'earned', $groupedEarned); $this->saveGroupedForPrefix(sprintf('no_%s', $model), $start, $end, 'transferred', $groupedTransferred); @@ -261,42 +255,36 @@ trait PeriodOverview } Log::debug(sprintf('Found %d statistics in period %s - %s.', count($statistics), $start->format('Y-m-d'), $end->format('Y-m-d'))); - $entry - = [ - 'title' => $title, - 'route' => route(sprintf('%s.no-%s', Str::plural($model), $model), [$start->format('Y-m-d'), $end->format('Y-m-d')]), - 'total_transactions' => 0, - 'spent' => [], - 'earned' => [], - 'transferred' => [], - ]; - $grouped = []; + $entry = ['title' => $title, 'route' => route(sprintf('%s.no-%s', Str::plural($model), $model), [ + $start->format('Y-m-d'), + $end->format('Y-m-d') + ]), 'total_transactions' => 0, 'spent' => [], 'earned' => [], 'transferred' => []]; + $grouped = []; /** @var PeriodStatistic $statistic */ foreach ($statistics as $statistic) { - $type = str_replace(sprintf('no_%s_', $model), '', $statistic->type); - $id = (int)$statistic->transaction_currency_id; - $currency = Amount::getTransactionCurrencyById($id); + $type = str_replace(sprintf('no_%s_', $model), '', $statistic->type); + $id = (int) $statistic->transaction_currency_id; + $currency = Amount::getTransactionCurrencyById($id); $grouped[$type]['count'] ??= 0; $grouped[$type][$id] = [ - 'amount' => (string)$statistic->amount, - 'count' => (int)$statistic->count, + '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, + 'currency_decimal_places' => $currency->decimal_places ]; - $grouped[$type]['count'] += (int)$statistic->count; + $grouped[$type]['count'] += (int) $statistic->count; } - $types = ['spent', 'earned', 'transferred']; + $types = ['spent', 'earned', 'transferred']; foreach ($types as $type) { if (array_key_exists($type, $grouped)) { $entry['total_transactions'] += $grouped[$type]['count']; unset($grouped[$type]['count']); $entry[$type] = $grouped[$type]; } - } return $entry; @@ -305,15 +293,19 @@ trait PeriodOverview protected function getSingleModelPeriod(Model $model, string $period, Carbon $start, Carbon $end): array { Log::debug(sprintf('Now in getSingleModelPeriod(%s #%d, %s %s)', $model::class, $model->id, $start->format('Y-m-d'), $end->format('Y-m-d'))); - $types = ['spent', 'earned', 'transferred_in', 'transferred_away']; - $return = [ + $types = ['spent', 'earned', 'transferred_in', 'transferred_away']; + $return = [ 'title' => Navigation::periodShow($start, $period), - 'route' => route(sprintf('%s.show', strtolower(Str::plural(class_basename($model)))), [$model->id, $start->format('Y-m-d'), $end->format('Y-m-d')]), - 'total_transactions' => 0, + 'route' => route(sprintf('%s.show', strtolower(Str::plural(class_basename($model)))), [ + $model->id, + $start->format('Y-m-d'), + $end->format('Y-m-d') + ]), + 'total_transactions' => 0 ]; $this->transactions = []; foreach ($types as $type) { - $set = $this->getSingleModelPeriodByType($model, $start, $end, $type); + $set = $this->getSingleModelPeriodByType($model, $start, $end, $type); $return['total_transactions'] += $set['count']; unset($set['count']); $return[$type] = $set; @@ -331,7 +323,7 @@ trait PeriodOverview } return $this->statistics->filter( - static fn (PeriodStatistic $statistic): bool => $statistic->start->eq($start) && $statistic->end->eq($end) && $statistic->type === $type + static fn(PeriodStatistic $statistic): bool => $statistic->start->eq($start) && $statistic->end->eq($end) && $statistic->type === $type ); } @@ -344,13 +336,24 @@ trait PeriodOverview } return $this->statistics->filter( - static fn (PeriodStatistic $statistic): bool => $statistic->start->eq($start) && $statistic->end->eq($end) && str_starts_with($statistic->type, $prefix) + static fn(PeriodStatistic $statistic): bool => ( + $statistic->start->eq($start) + && $statistic->end->eq($end) + && str_starts_with($statistic->type, $prefix) + ) ); } private function getSingleModelPeriodByType(Model $model, Carbon $start, Carbon $end, string $type): array { - Log::debug(sprintf('Now in getSingleModelPeriodByType(%s #%d, %s %s, %s)', $model::class, $model->id, $start->format('Y-m-d'), $end->format('Y-m-d'), $type)); + Log::debug(sprintf( + 'Now in getSingleModelPeriodByType(%s #%d, %s %s, %s)', + $model::class, + $model->id, + $start->format('Y-m-d'), + $end->format('Y-m-d'), + $type + )); $statistics = $this->filterStatistics($start, $end, $type); // nothing found, regenerate them. @@ -383,7 +386,6 @@ trait PeriodOverview throw new FireflyException(sprintf('Cannot deal with category period type %s', $type)); case 'spent': - $result = $this->filterTransactionsByType(TransactionTypeEnum::WITHDRAWAL, $start, $end); break; @@ -411,24 +413,22 @@ trait PeriodOverview return $grouped; } - $grouped = [ - 'count' => 0, - ]; + $grouped = ['count' => 0]; /** @var PeriodStatistic $statistic */ foreach ($statistics as $statistic) { - $id = (int)$statistic->transaction_currency_id; - $currency = Amount::getTransactionCurrencyById($id); + $id = (int) $statistic->transaction_currency_id; + $currency = Amount::getTransactionCurrencyById($id); $grouped[$id] = [ - 'amount' => (string)$statistic->amount, - 'count' => (int)$statistic->count, + '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, + 'currency_decimal_places' => $currency->decimal_places ]; - $grouped['count'] += (int)$statistic->count; + $grouped['count'] += (int) $statistic->count; } return $grouped; @@ -439,21 +439,20 @@ trait PeriodOverview * * @throws FireflyException */ - protected function getTagPeriodOverview(Tag $tag, Carbon $start, Carbon $end): array // period overview for tags. - { - $this->tagRepository = app(TagRepositoryInterface::class); + protected function getTagPeriodOverview(Tag $tag, Carbon $start, Carbon $end): array + { // period overview for tags. + $this->tagRepository = app(TagRepositoryInterface::class); $this->tagRepository->setUser($tag->user); $this->periodStatisticRepo = app(PeriodStatisticRepositoryInterface::class); - $range = Navigation::getViewRange(true); - [$start, $end] = $end < $start ? [$end, $start] : [$start, $end]; + $range = Navigation::getViewRange(true); + [$start, $end] = $end < $start ? [$end, $start] : [$start, $end]; /** @var array $dates */ - $dates = Navigation::blockPeriods($start, $end, $range); - $entries = []; - [$start, $end] = $this->getPeriodFromBlocks($dates, $start, $end); - $this->statistics = $this->periodStatisticRepo->allInRangeForModel($tag, $start, $end); - + $dates = Navigation::blockPeriods($start, $end, $range); + $entries = []; + [$start, $end] = $this->getPeriodFromBlocks($dates, $start, $end); + $this->statistics = $this->periodStatisticRepo->allInRangeForModel($tag, $start, $end); Log::debug(sprintf('Count of loops: %d', count($dates))); foreach ($dates as $currentDate) { @@ -468,12 +467,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'); @@ -483,16 +482,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']); @@ -509,15 +508,18 @@ trait PeriodOverview $transferred = $this->filterJournalsByDate($genericSet, $currentDate['start'], $currentDate['end']); } } - $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), - ]; + $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) + ]; ++$loops; } @@ -527,7 +529,15 @@ trait PeriodOverview private function saveGroupedAsStatistics(Model $model, Carbon $start, Carbon $end, string $type, array $array): void { unset($array['count']); - Log::debug(sprintf('saveGroupedAsStatistics(%s #%d, %s, %s, "%s", array(%d))', $model::class, $model->id, $start->format('Y-m-d'), $end->format('Y-m-d'), $type, count($array))); + Log::debug(sprintf( + 'saveGroupedAsStatistics(%s #%d, %s, %s, "%s", array(%d))', + $model::class, + $model->id, + $start->format('Y-m-d'), + $end->format('Y-m-d'), + $type, + count($array) + )); foreach ($array as $entry) { $this->periodStatisticRepo->saveStatistic($model, $entry['currency_id'], $start, $end, $type, $entry['count'], $entry['amount']); } @@ -540,7 +550,14 @@ trait PeriodOverview private function saveGroupedForPrefix(string $prefix, Carbon $start, Carbon $end, string $type, array $array): void { unset($array['count']); - Log::debug(sprintf('saveGroupedForPrefix("%s", %s, %s, "%s", array(%d))', $prefix, $start->format('Y-m-d'), $end->format('Y-m-d'), $type, count($array))); + Log::debug(sprintf( + 'saveGroupedForPrefix("%s", %s, %s, "%s", array(%d))', + $prefix, + $start->format('Y-m-d'), + $end->format('Y-m-d'), + $type, + count($array) + )); foreach ($array as $entry) { $this->periodStatisticRepo->savePrefixedStatistic($prefix, $entry['currency_id'], $start, $end, $type, $entry['count'], $entry['amount']); } @@ -575,9 +592,8 @@ trait PeriodOverview $date = Carbon::parse($item['date']); $fits = $item['type'] === $type->value && $date >= $start && $date <= $end; if ($fits) { - // if type is withdrawal, negative amount: - if (TransactionTypeEnum::WITHDRAWAL === $type && 1 === bccomp((string)$item['amount'], '0')) { + if (TransactionTypeEnum::WITHDRAWAL === $type && 1 === bccomp((string) $item['amount'], '0')) { $item['amount'] = Steam::negative($item['amount']); } $result[] = $item; @@ -594,12 +610,12 @@ trait PeriodOverview foreach ($this->transactions as $item) { $date = Carbon::parse($item['date']); if ($date >= $start && $date <= $end) { - if ('Transfer' === $item['type'] && 'away' === $direction && -1 === bccomp((string)$item['amount'], '0')) { + if ('Transfer' === $item['type'] && 'away' === $direction && -1 === bccomp((string) $item['amount'], '0')) { $result[] = $item; continue; } - if ('Transfer' === $item['type'] && 'in' === $direction && 1 === bccomp((string)$item['amount'], '0')) { + if ('Transfer' === $item['type'] && 'in' === $direction && 1 === bccomp((string) $item['amount'], '0')) { $result[] = $item; } } @@ -611,25 +627,23 @@ trait PeriodOverview private function groupByCurrency(array $journals): array { Log::debug('groupByCurrency()'); - $return = [ - 'count' => 0, - ]; + $return = ['count' => 0]; if (0 === count($journals)) { return $return; } /** @var array $journal */ foreach ($journals as $journal) { - $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 = (string) ($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 = (string) ($journal['amount'] ?? '0'); if ($this->convertToPrimary && $currencyId !== $this->primaryCurrency->id && $foreignCurrencyId !== $this->primaryCurrency->id) { - $amount = (string) ($journal['pc_amount'] ?? '0'); + $amount = (string) ($journal['pc_amount'] ?? '0'); $currencyId = $this->primaryCurrency->id; $currencyCode = $this->primaryCurrency->code; $currencyName = $this->primaryCurrency->name; @@ -637,7 +651,7 @@ trait PeriodOverview $currencyDecimalPlaces = $this->primaryCurrency->decimal_places; } if ($this->convertToPrimary && $currencyId !== $this->primaryCurrency->id && $foreignCurrencyId === $this->primaryCurrency->id) { - $currencyId = (int)$foreignCurrencyId; + $currencyId = (int) $foreignCurrencyId; $currencyCode = $journal['foreign_currency_code']; $currencyName = $journal['foreign_currency_name']; $currencySymbol = $journal['foreign_currency_symbol']; @@ -651,11 +665,10 @@ trait PeriodOverview 'currency_name' => $currencyName, 'currency_code' => $currencyCode, 'currency_symbol' => $currencySymbol, - 'currency_decimal_places' => $currencyDecimalPlaces, + 'currency_decimal_places' => $currencyDecimalPlaces ]; - - $return[$currencyId]['amount'] = bcadd((string)$return[$currencyId]['amount'], $amount); + $return[$currencyId]['amount'] = bcadd((string) $return[$currencyId]['amount'], $amount); ++$return[$currencyId]['count']; ++$return['count']; } diff --git a/app/Support/Http/Controllers/RenderPartialViews.php b/app/Support/Http/Controllers/RenderPartialViews.php index ff7cb1c416..67ea7d42a7 100644 --- a/app/Support/Http/Controllers/RenderPartialViews.php +++ b/app/Support/Http/Controllers/RenderPartialViews.php @@ -24,8 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Support\Http\Controllers; -use FireflyIII\Models\Tag; -use Illuminate\Support\Facades\Log; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Helpers\Report\PopupReportInterface; @@ -34,11 +32,13 @@ use FireflyIII\Models\Budget; use FireflyIII\Models\Rule; use FireflyIII\Models\RuleAction; use FireflyIII\Models\RuleTrigger; +use FireflyIII\Models\Tag; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Repositories\Category\CategoryRepositoryInterface; use FireflyIII\Repositories\Tag\TagRepositoryInterface; use FireflyIII\Support\Search\OperatorQuerySearch; +use Illuminate\Support\Facades\Log; use Throwable; /** @@ -54,23 +54,23 @@ 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', ['journals' => $journals, 'budget' => $budget, 'account' => $account])->render(); + $view = view('popup.report.balance-amount', ['journals' => $journals, 'budget' => $budget, 'account' => $account])->render(); } catch (Throwable $e) { Log::error(sprintf('Could not render: %s', $e->getMessage())); $view = 'Firefly III could not render the view. Please see the log files.'; @@ -115,17 +115,17 @@ 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', ['journals' => $journals, 'budget' => $budget])->render(); + $view = view('popup.report.budget-spent-amount', ['journals' => $journals, 'budget' => $budget])->render(); } catch (Throwable $e) { Log::error(sprintf('Could not render: %s', $e->getMessage())); $view = 'Firefly III could not render the view. Please see the log files.'; @@ -144,11 +144,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 { @@ -195,8 +195,18 @@ trait RenderPartialViews { /** @var AccountRepositoryInterface $repository */ $repository = app(AccountRepositoryInterface::class); - $expense = $repository->getActiveAccountsByType([AccountTypeEnum::EXPENSE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value]); - $revenue = $repository->getActiveAccountsByType([AccountTypeEnum::REVENUE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value]); + $expense = $repository->getActiveAccountsByType([ + AccountTypeEnum::EXPENSE->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::MORTGAGE->value + ]); + $revenue = $repository->getActiveAccountsByType([ + AccountTypeEnum::REVENUE->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::MORTGAGE->value + ]); $set = []; /** @var Account $account */ @@ -206,8 +216,10 @@ trait RenderPartialViews foreach ($revenue as $otherAccount) { if ( ( - ($otherAccount->name === $account->name) - || (null !== $account->iban && null !== $otherAccount->iban && $otherAccount->iban === $account->iban) + $otherAccount->name === $account->name + || null !== $account->iban + && null !== $otherAccount->iban + && $otherAccount->iban === $account->iban ) && $otherAccount->id !== $account->id ) { @@ -239,17 +251,17 @@ 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', ['journals' => $journals, 'account' => $account])->render(); + $view = view('popup.report.expense-entry', ['journals' => $journals, 'account' => $account])->render(); } catch (Throwable $e) { Log::error(sprintf('Could not render: %s', $e->getMessage())); $view = 'Firefly III could not render the view. Please see the log files.'; @@ -267,25 +279,22 @@ 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(); /** @var RuleAction $entry */ foreach ($currentActions as $entry) { - $count = ($index + 1); + $count = $index + 1; try { - $actions[] = view( - 'rules.partials.action', - [ - 'oldAction' => $entry->action_type, - 'oldValue' => $entry->action_value, - 'oldChecked' => $entry->stop_processing, - 'count' => $count, - ] - )->render(); + $actions[] = view('rules.partials.action', [ + 'oldAction' => $entry->action_type, + 'oldValue' => $entry->action_value, + 'oldChecked' => $entry->stop_processing, + 'count' => $count + ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Throwable was thrown in getCurrentActions(): %s', $e->getMessage())); Log::error($e->getTraceAsString()); @@ -307,11 +316,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); @@ -323,24 +332,21 @@ trait RenderPartialViews /** @var RuleTrigger $entry */ foreach ($currentTriggers as $entry) { if ('user_action' !== $entry->trigger_type) { - $count = ($index + 1); + $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); } - $renderedEntries[] = view( - 'rules.partials.trigger', - [ - 'oldTrigger' => $rootOperator, - 'oldValue' => $entry->trigger_value, - 'oldChecked' => $entry->stop_processing, - 'oldProhibited' => str_starts_with((string)$entry->trigger_type, '-'), - 'count' => $count, - 'triggers' => $triggers, - ] - )->render(); + $renderedEntries[] = view('rules.partials.trigger', [ + 'oldTrigger' => $rootOperator, + 'oldValue' => $entry->trigger_value, + 'oldChecked' => $entry->stop_processing, + 'oldProhibited' => str_starts_with((string) $entry->trigger_type, '-'), + 'count' => $count, + 'triggers' => $triggers + ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Throwable was thrown in getCurrentTriggers(): %s', $e->getMessage())); Log::error($e->getTraceAsString()); @@ -366,17 +372,17 @@ 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', ['journals' => $journals, 'account' => $account])->render(); + $view = view('popup.report.income-entry', ['journals' => $journals, 'account' => $account])->render(); } catch (Throwable $e) { Log::error(sprintf('Could not render: %s', $e->getMessage())); $view = 'Firefly III could not render the view. Please see the log files.'; @@ -417,15 +423,12 @@ trait RenderPartialViews $repository = app(TagRepositoryInterface::class); $tags = $repository->get(); - $grouped = []; + $grouped = []; /** @var Tag $tag */ foreach ($tags as $tag) { - $year = (int) $tag->date?->year; - $grouped[$year] ??= [ - 'tags' => [], - 'year' => 0 === $year ? trans('firefly.no_date') : $year, - ]; + $year = (int) $tag->date?->year; + $grouped[$year] ??= ['tags' => [], 'year' => 0 === $year ? trans('firefly.no_date') : $year]; $grouped[$year]['tags'][] = $tag; } ksort($grouped); diff --git a/app/Support/Http/Controllers/RequestInformation.php b/app/Support/Http/Controllers/RequestInformation.php index 1f4e42b0f7..bdd31f80e5 100644 --- a/app/Support/Http/Controllers/RequestInformation.php +++ b/app/Support/Http/Controllers/RequestInformation.php @@ -24,12 +24,12 @@ declare(strict_types=1); namespace FireflyIII\Support\Http\Controllers; -use FireflyIII\Support\Facades\Preferences; use Carbon\Carbon; use FireflyIII\Exceptions\ValidationException; use FireflyIII\Http\Requests\RuleFormRequest; use FireflyIII\Http\Requests\TestRuleFormRequest; use FireflyIII\Support\Binder\AccountList; +use FireflyIII\Support\Facades\Preferences; use FireflyIII\User; use Illuminate\Contracts\Validation\Validator as ValidatorContract; use Illuminate\Routing\Route; @@ -80,13 +80,13 @@ trait RequestInformation $data = $request->get('triggers'); if (is_array($data)) { foreach ($data as $triggerInfo) { - $current = [ + $current = [ '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); + $current = RuleFormRequest::replaceAmountTrigger($current); $triggers[] = $current; } } @@ -102,13 +102,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 = Preferences::get($key, false)->data; @@ -129,7 +129,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; } @@ -144,20 +144,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; } @@ -167,14 +167,14 @@ trait RequestInformation * * @throws ValidationException */ - final protected function validatePassword(User $user, string $current, string $new): bool // get request info - { + 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; @@ -185,12 +185,9 @@ trait RequestInformation */ final protected function validator(array $data): ValidatorContract { - return Validator::make( - $data, - [ - 'email' => 'required|string|email|max:255|unique:users', - 'password' => 'required|string|min:16|secure_password|confirmed', - ] - ); + return Validator::make($data, [ + 'email' => 'required|string|email|max:255|unique:users', + 'password' => 'required|string|min:16|secure_password|confirmed' + ]); } } diff --git a/app/Support/Http/Controllers/RuleManagement.php b/app/Support/Http/Controllers/RuleManagement.php index e26d27498c..4b3048f044 100644 --- a/app/Support/Http/Controllers/RuleManagement.php +++ b/app/Support/Http/Controllers/RuleManagement.php @@ -24,11 +24,11 @@ declare(strict_types=1); namespace FireflyIII\Support\Http\Controllers; -use Illuminate\Support\Facades\Log; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Repositories\RuleGroup\RuleGroupRepositoryInterface; use FireflyIII\Support\Search\OperatorQuerySearch; use Illuminate\Http\Request; +use Illuminate\Support\Facades\Log; use Throwable; /** @@ -47,15 +47,12 @@ trait RuleManagement if (is_array($oldInput)) { foreach ($oldInput as $oldAction) { try { - $triggers[] = view( - 'rules.partials.action', - [ - 'oldAction' => $oldAction['type'], - 'oldValue' => $oldAction['value'] ?? '', - 'oldChecked' => 1 === (int)($oldAction['stop_processing'] ?? '0'), - 'count' => $index + 1, - ] - )->render(); + $triggers[] = view('rules.partials.action', [ + 'oldAction' => $oldAction['type'], + 'oldValue' => $oldAction['value'] ?? '', + 'oldChecked' => 1 === (int) ($oldAction['stop_processing'] ?? '0'), + 'count' => $index + 1 + ])->render(); } catch (Throwable $e) { Log::error(sprintf('Throwable was thrown in getPreviousActions(): %s', $e->getMessage())); Log::error($e->getTraceAsString()); @@ -75,11 +72,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); @@ -90,17 +87,14 @@ trait RuleManagement if (is_array($oldInput)) { foreach ($oldInput as $oldTrigger) { try { - $renderedEntries[] = view( - 'rules.partials.trigger', - [ - 'oldTrigger' => OperatorQuerySearch::getRootOperator($oldTrigger['type']), - 'oldValue' => $oldTrigger['value'] ?? '', - 'oldChecked' => 1 === (int)($oldTrigger['stop_processing'] ?? '0'), - 'oldProhibited' => 1 === (int)($oldTrigger['prohibited'] ?? '0'), - 'count' => $index + 1, - 'triggers' => $triggers, - ] - )->render(); + $renderedEntries[] = view('rules.partials.trigger', [ + 'oldTrigger' => OperatorQuerySearch::getRootOperator($oldTrigger['type']), + 'oldValue' => $oldTrigger['value'] ?? '', + 'oldChecked' => 1 === (int) ($oldTrigger['stop_processing'] ?? '0'), + 'oldProhibited' => 1 === (int) ($oldTrigger['prohibited'] ?? '0'), + 'count' => $index + 1, + 'triggers' => $triggers + ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Throwable was thrown in getPreviousTriggers(): %s', $e->getMessage())); Log::error($e->getTraceAsString()); @@ -125,28 +119,25 @@ 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( - 'rules.partials.trigger', - [ - 'oldTrigger' => $rootOperator, - 'oldValue' => $needsContext ? $operator['value'] : '', - 'oldChecked' => false, - 'oldProhibited' => $operator['prohibited'] ?? false, - 'count' => $index + 1, - 'triggers' => $triggers, - ] - )->render(); + $renderedEntries[] = view('rules.partials.trigger', [ + 'oldTrigger' => $rootOperator, + 'oldValue' => $needsContext ? $operator['value'] : '', + 'oldChecked' => false, + 'oldProhibited' => $operator['prohibited'] ?? false, + 'count' => $index + 1, + 'triggers' => $triggers + ])->render(); } catch (Throwable $e) { Log::debug(sprintf('Throwable was thrown in getPreviousTriggers(): %s', $e->getMessage())); Log::error($e->getTraceAsString()); @@ -165,9 +156,9 @@ 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'), - 'active' => true, + 'title' => (string) trans('firefly.default_rule_group_name'), + 'description' => (string) trans('firefly.default_rule_group_description'), + 'active' => true ]; $repository->store($data); diff --git a/app/Support/Http/Controllers/TransactionCalculation.php b/app/Support/Http/Controllers/TransactionCalculation.php index 17df264ce8..f341b43d7b 100644 --- a/app/Support/Http/Controllers/TransactionCalculation.php +++ b/app/Support/Http/Controllers/TransactionCalculation.php @@ -39,15 +39,11 @@ 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]) - ; + $collector->setAccounts($total)->setRange($start, $end)->withAccountInformation()->setTypes([TransactionTypeEnum::WITHDRAWAL->value]); return $collector->getExtractedJournals(); } @@ -60,9 +56,12 @@ trait TransactionCalculation /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); - $collector->setAccounts($accounts)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::TRANSFER->value]) - ->setTags($tags)->withAccountInformation() - ; + $collector + ->setAccounts($accounts) + ->setRange($start, $end) + ->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::TRANSFER->value]) + ->setTags($tags) + ->withAccountInformation(); return $collector->getExtractedJournals(); } @@ -74,9 +73,12 @@ 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() - ; + $collector + ->setAccounts($accounts) + ->setRange($start, $end) + ->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::TRANSFER->value]) + ->setBudgets($budgets) + ->withAccountInformation(); return $collector->getExtractedJournals(); } @@ -93,8 +95,7 @@ trait TransactionCalculation ->setRange($start, $end) ->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::TRANSFER->value]) ->setCategories($categories) - ->withAccountInformation() - ; + ->withAccountInformation(); return $collector->getExtractedJournals(); } @@ -106,9 +107,12 @@ 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() - ; + $collector + ->setAccounts($accounts) + ->setRange($start, $end) + ->setTypes([TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value]) + ->setCategories($categories) + ->withAccountInformation(); return $collector->getExtractedJournals(); } @@ -118,7 +122,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); @@ -134,9 +138,12 @@ 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() - ; + $collector + ->setAccounts($accounts) + ->setRange($start, $end) + ->setTypes([TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value]) + ->setTags($tags) + ->withAccountInformation(); return $collector->getExtractedJournals(); } diff --git a/app/Support/Http/Controllers/UserNavigation.php b/app/Support/Http/Controllers/UserNavigation.php index b0f81f163d..4b5fb087f8 100644 --- a/app/Support/Http/Controllers/UserNavigation.php +++ b/app/Support/Http/Controllers/UserNavigation.php @@ -24,16 +24,16 @@ declare(strict_types=1); namespace FireflyIII\Support\Http\Controllers; -use Illuminate\Support\Facades\Log; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Models\Account; use FireflyIII\Models\Transaction; use FireflyIII\Models\TransactionGroup; use FireflyIII\Models\TransactionJournal; +use FireflyIII\Support\Facades\Steam; use Illuminate\Http\RedirectResponse; use Illuminate\Routing\Redirector; -use FireflyIII\Support\Facades\Steam; +use Illuminate\Support\Facades\Log; /** * Trait UserNavigation @@ -51,7 +51,7 @@ trait UserNavigation final protected function getPreviousUrl(string $identifier): string { Log::debug(sprintf('Trying to retrieve URL stored under "%s"', $identifier)); - $url = (string)session($identifier); + $url = (string) session($identifier); Log::debug(sprintf('The URL is %s', $url)); return Steam::getSafeUrl($url, route('index')); @@ -62,7 +62,14 @@ trait UserNavigation */ final protected function isEditableAccount(Account $account): bool { - $editable = [AccountTypeEnum::EXPENSE->value, AccountTypeEnum::REVENUE->value, AccountTypeEnum::ASSET->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value]; + $editable = [ + AccountTypeEnum::EXPENSE->value, + AccountTypeEnum::REVENUE->value, + AccountTypeEnum::ASSET->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::MORTGAGE->value + ]; $type = $account->accountType->type; return in_array($type, $editable, true); @@ -71,12 +78,17 @@ 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; } $type = $journal->transactionType->type; - $editable = [TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::TRANSFER->value, TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::RECONCILIATION->value]; + $editable = [ + TransactionTypeEnum::WITHDRAWAL->value, + TransactionTypeEnum::TRANSFER->value, + TransactionTypeEnum::DEPOSIT->value, + TransactionTypeEnum::RECONCILIATION->value + ]; return in_array($type, $editable, true); } @@ -84,7 +96,11 @@ trait UserNavigation final protected function redirectAccountToAccount(Account $account): Redirector|RedirectResponse { $type = $account->accountType->type; - if (AccountTypeEnum::RECONCILIATION->value === $type || AccountTypeEnum::INITIAL_BALANCE->value === $type || AccountTypeEnum::LIABILITY_CREDIT->value === $type) { + if ( + AccountTypeEnum::RECONCILIATION->value === $type + || AccountTypeEnum::INITIAL_BALANCE->value === $type + || AccountTypeEnum::LIABILITY_CREDIT->value === $type + ) { // reconciliation must be stored somewhere in this account's transactions. /** @var null|Transaction $transaction */ @@ -95,10 +111,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) { 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')); @@ -115,7 +131,7 @@ trait UserNavigation final protected function redirectGroupToAccount(TransactionGroup $group): Redirector|RedirectResponse { /** @var null|TransactionJournal $journal */ - $journal = $group->transactionJournals()->first(); + $journal = $group->transactionJournals()->first(); if (null === $journal) { Log::error(sprintf('No journals in group #%d', $group->id)); @@ -123,7 +139,12 @@ trait UserNavigation } // prefer redirect to everything but expense and revenue: $transactions = $journal->transactions; - $ignore = [AccountTypeEnum::REVENUE->value, AccountTypeEnum::EXPENSE->value, AccountTypeEnum::RECONCILIATION->value, AccountTypeEnum::INITIAL_BALANCE->value]; + $ignore = [ + AccountTypeEnum::REVENUE->value, + AccountTypeEnum::EXPENSE->value, + AccountTypeEnum::RECONCILIATION->value, + AccountTypeEnum::INITIAL_BALANCE->value + ]; /** @var Transaction $transaction */ foreach ($transactions as $transaction) { @@ -136,7 +157,7 @@ trait UserNavigation return redirect(route('index')); } - final protected function rememberPreviousUrl(string $identifier): ?string + final protected function rememberPreviousUrl(string $identifier): null|string { $return = Steam::getSafePreviousUrl(); session()->put($identifier, $return); diff --git a/app/Support/JsonApi/Enrichments/AccountEnrichment.php b/app/Support/JsonApi/Enrichments/AccountEnrichment.php index 7b59442993..437e085133 100644 --- a/app/Support/JsonApi/Enrichments/AccountEnrichment.php +++ b/app/Support/JsonApi/Enrichments/AccountEnrichment.php @@ -53,36 +53,36 @@ use Override; */ class AccountEnrichment implements EnrichmentInterface { - private array $accountTypeIds = []; - private array $accountTypes = []; - private array $balances = []; - private Collection $collection; - private readonly bool $convertToPrimary; - private array $currencies = []; - private ?Carbon $date = null; - private ?Carbon $end = null; - private array $endBalances = []; - private array $ids = []; - private array $lastActivities = []; - private array $locations = []; - private array $mappedObjects = []; - private array $meta = []; - private array $notes = []; - private array $objectGroups = []; - private array $openingBalances = []; + private array $accountTypeIds = []; + private array $accountTypes = []; + private array $balances = []; + private Collection $collection; + private readonly bool $convertToPrimary; + private array $currencies = []; + private null|Carbon $date = null; + private null|Carbon $end = null; + private array $endBalances = []; + private array $ids = []; + private array $lastActivities = []; + private array $locations = []; + private array $mappedObjects = []; + private array $meta = []; + private array $notes = []; + private array $objectGroups = []; + private array $openingBalances = []; private readonly TransactionCurrency $primaryCurrency; - private array $sort = []; - private ?Carbon $start = null; - private array $startBalances = []; - private User $user; - private UserGroup $userGroup; + private array $sort = []; + private null|Carbon $start = null; + private array $startBalances = []; + private User $user; + private UserGroup $userGroup; /** * TODO The account enricher must do conversion from and to the primary currency. */ public function __construct() { - $this->primaryCurrency = Amount::getPrimaryCurrency(); + $this->primaryCurrency = Amount::getPrimaryCurrency(); $this->convertToPrimary = Amount::convertToPrimary(); } @@ -130,7 +130,7 @@ class AccountEnrichment implements EnrichmentInterface return $this->date; } - public function setDate(?Carbon $date): void + public function setDate(null|Carbon $date): void { if ($date instanceof Carbon) { $date->endOfDay(); @@ -139,7 +139,7 @@ class AccountEnrichment implements EnrichmentInterface $this->date = $date; } - public function setEnd(?Carbon $end): void + public function setEnd(null|Carbon $end): void { $this->end = $end; } @@ -149,14 +149,14 @@ class AccountEnrichment implements EnrichmentInterface $this->sort = $sort; } - public function setStart(?Carbon $start): void + public function setStart(null|Carbon $start): void { $this->start = $start; } public function setUser(User $user): void { - $this->user = $user; + $this->user = $user; $this->userGroup = $user->userGroup; } @@ -168,15 +168,11 @@ class AccountEnrichment implements EnrichmentInterface private function appendCollectedData(): void { $this->collection = $this->collection->map(function (Account $item): Account { - $id = (int)$item->id; - $item->full_account_type = $this->accountTypes[(int)$item->account_type_id] ?? null; - $meta = [ + $id = (int) $item->id; + $item->full_account_type = $this->accountTypes[(int) $item->account_type_id] ?? null; + $meta = [ 'currency' => null, - 'location' => [ - 'latitude' => null, - 'longitude' => null, - 'zoom_level' => null, - ], + 'location' => ['latitude' => null, 'longitude' => null, 'zoom_level' => null], 'object_group_id' => null, 'object_group_order' => null, 'object_group_title' => null, @@ -184,13 +180,13 @@ class AccountEnrichment implements EnrichmentInterface 'opening_balance_amount' => null, 'account_number' => null, 'notes' => $this->notes[$id] ?? null, - 'last_activity' => $this->lastActivities[$id] ?? null, + 'last_activity' => $this->lastActivities[$id] ?? null ]; // add object group if available if (array_key_exists($id, $this->mappedObjects)) { - $key = $this->mappedObjects[$id]; - $meta['object_group_id'] = (string)$this->objectGroups[$key]['id']; + $key = $this->mappedObjects[$id]; + $meta['object_group_id'] = (string) $this->objectGroups[$key]['id']; $meta['object_group_title'] = $this->objectGroups[$key]['title']; $meta['object_group_order'] = $this->objectGroups[$key]['order']; } @@ -206,41 +202,44 @@ class AccountEnrichment implements EnrichmentInterface } // also add currency, if present. if (array_key_exists('currency_id', $meta)) { - $currencyId = (int)$meta['currency_id']; + $currencyId = (int) $meta['currency_id']; $meta['currency'] = $this->currencies[$currencyId]; } if (array_key_exists($id, $this->openingBalances)) { - $meta['opening_balance_date'] = $this->openingBalances[$id]['date']; + $meta['opening_balance_date'] = $this->openingBalances[$id]['date']; $meta['opening_balance_amount'] = $this->openingBalances[$id]['amount']; } // add balances // get currencies: - $currency = $this->primaryCurrency; // assume primary currency + $currency = $this->primaryCurrency; // assume primary currency if (null !== $meta['currency']) { $currency = $meta['currency']; } // get the current balance: - $date = $this->getDate(); + $date = $this->getDate(); // $finalBalance = Steam::finalAccountBalance($item, $date, $this->primaryCurrency, $this->convertToPrimary); - $finalBalance = $this->balances[$id]; - $balanceDifference = $this->getBalanceDifference($id, $currency); - Log::debug(sprintf('Call finalAccountBalance(%s) with date/time "%s"', var_export($this->convertToPrimary, true), $date->toIso8601String()), $finalBalance); + $finalBalance = $this->balances[$id]; + $balanceDifference = $this->getBalanceDifference($id, $currency); + Log::debug( + sprintf('Call finalAccountBalance(%s) with date/time "%s"', var_export($this->convertToPrimary, true), $date->toIso8601String()), + $finalBalance + ); // collect current balances: - $currentBalance = Steam::bcround($finalBalance[$currency->code] ?? '0', $currency->decimal_places); - $openingBalance = Steam::bcround($meta['opening_balance_amount'] ?? '0', $currency->decimal_places); - $virtualBalance = Steam::bcround($item->virtual_balance ?? '0', $currency->decimal_places); - $debtAmount = $meta['current_debt'] ?? null; + $currentBalance = Steam::bcround($finalBalance[$currency->code] ?? '0', $currency->decimal_places); + $openingBalance = Steam::bcround($meta['opening_balance_amount'] ?? '0', $currency->decimal_places); + $virtualBalance = Steam::bcround($item->virtual_balance ?? '0', $currency->decimal_places); + $debtAmount = $meta['current_debt'] ?? null; // set some pc_ default values to NULL: - $pcCurrentBalance = null; - $pcOpeningBalance = null; - $pcVirtualBalance = null; - $pcDebtAmount = null; - $pcBalanceDifference = null; + $pcCurrentBalance = null; + $pcOpeningBalance = null; + $pcVirtualBalance = null; + $pcDebtAmount = null; + $pcBalanceDifference = null; // convert to primary currency if needed: if ($this->convertToPrimary && $currency->id !== $this->primaryCurrency->id) { @@ -266,7 +265,7 @@ class AccountEnrichment implements EnrichmentInterface $pcOpeningBalance = null; } $meta['current_balance_date'] = $this->getDate(); - $meta['balances'] = [ + $meta['balances'] = [ 'current_balance' => $currentBalance, 'pc_current_balance' => $pcCurrentBalance, 'opening_balance' => $openingBalance, @@ -276,10 +275,10 @@ class AccountEnrichment implements EnrichmentInterface 'debt_amount' => $debtAmount, 'pc_debt_amount' => $pcDebtAmount, 'balance_difference' => $balanceDifference, - 'pc_balance_difference' => $pcBalanceDifference, + 'pc_balance_difference' => $pcBalanceDifference ]; // end add balances - $item->meta = $meta; + $item->meta = $meta; return $item; }); @@ -289,10 +288,13 @@ class AccountEnrichment implements EnrichmentInterface { $this->balances = Steam::accountsBalancesOptimized($this->collection, $this->getDate(), $this->primaryCurrency, $this->convertToPrimary); if ($this->start instanceof Carbon && $this->end instanceof Carbon) { - [ - $this->startBalances, - $this->endBalances, - ] = Steam::accountsBalancesInRange($this->collection, $this->start, $this->end, $this->primaryCurrency, $this->convertToPrimary); + [$this->startBalances, $this->endBalances] = Steam::accountsBalancesInRange( + $this->collection, + $this->start, + $this->end, + $this->primaryCurrency, + $this->convertToPrimary + ); } } @@ -300,10 +302,10 @@ class AccountEnrichment implements EnrichmentInterface { /** @var Account $account */ foreach ($this->collection as $account) { - $this->ids[] = (int)$account->id; - $this->accountTypeIds[] = (int)$account->account_type_id; + $this->ids[] = (int) $account->id; + $this->accountTypeIds[] = (int) $account->account_type_id; } - $this->ids = array_unique($this->ids); + $this->ids = array_unique($this->ids); $this->accountTypeIds = array_unique($this->accountTypeIds); } @@ -314,38 +316,50 @@ class AccountEnrichment implements EnrichmentInterface private function collectLocations(): void { - $locations = Location::query()->whereIn('locatable_id', $this->ids) - ->where('locatable_type', Account::class)->get(['locations.locatable_id', 'locations.latitude', 'locations.longitude', 'locations.zoom_level'])->toArray() - ; + $locations = Location::query() + ->whereIn('locatable_id', $this->ids) + ->where('locatable_type', Account::class) + ->get(['locations.locatable_id', 'locations.latitude', 'locations.longitude', 'locations.zoom_level']) + ->toArray(); foreach ($locations as $location) { - $this->locations[(int)$location['locatable_id']] - = [ - 'latitude' => (float)$location['latitude'], - 'longitude' => (float)$location['longitude'], - 'zoom_level' => (int)$location['zoom_level'], - ]; + $this->locations[(int) $location['locatable_id']] = [ + 'latitude' => (float) $location['latitude'], + 'longitude' => (float) $location['longitude'], + 'zoom_level' => (int) $location['zoom_level'] + ]; } Log::debug(sprintf('Enrich with %d locations(s)', count($this->locations))); } private function collectMetaData(): void { - $set = AccountMeta::whereIn('name', ['is_multi_currency', 'include_net_worth', 'currency_id', 'account_role', 'account_number', 'BIC', 'liability_direction', 'interest', 'interest_period', 'current_debt']) + $set = AccountMeta::whereIn('name', [ + 'is_multi_currency', + 'include_net_worth', + 'currency_id', + 'account_role', + 'account_number', + 'BIC', + 'liability_direction', + 'interest', + 'interest_period', + 'current_debt' + ]) ->whereIn('account_id', $this->ids) - ->get(['account_meta.id', 'account_meta.account_id', 'account_meta.name', 'account_meta.data'])->toArray() - ; + ->get(['account_meta.id', 'account_meta.account_id', 'account_meta.name', 'account_meta.data']) + ->toArray(); /** @var array $entry */ foreach ($set as $entry) { - $this->meta[(int)$entry['account_id']][$entry['name']] = (string)$entry['data']; + $this->meta[(int) $entry['account_id']][$entry['name']] = (string) $entry['data']; if ('currency_id' === $entry['name']) { - $this->currencies[(int)$entry['data']] = true; + $this->currencies[(int) $entry['data']] = true; } } if (count($this->currencies) > 0) { $currencies = TransactionCurrency::whereIn('id', array_keys($this->currencies))->get(); foreach ($currencies as $currency) { - $this->currencies[(int)$currency->id] = $currency; + $this->currencies[(int) $currency->id] = $currency; } } $this->currencies[0] = $this->primaryCurrency; @@ -358,36 +372,37 @@ class AccountEnrichment implements EnrichmentInterface private function collectNotes(): void { - $notes = Note::query()->whereIn('noteable_id', $this->ids) + $notes = Note::query() + ->whereIn('noteable_id', $this->ids) ->whereNotNull('notes.text') ->where('notes.text', '!=', '') - ->where('noteable_type', Account::class)->get(['notes.noteable_id', 'notes.text'])->toArray() - ; + ->where('noteable_type', Account::class) + ->get(['notes.noteable_id', 'notes.text']) + ->toArray(); foreach ($notes as $note) { - $this->notes[(int)$note['noteable_id']] = (string)$note['text']; + $this->notes[(int) $note['noteable_id']] = (string) $note['text']; } Log::debug(sprintf('Enrich with %d note(s)', count($this->notes))); } private function collectObjectGroups(): void { - $set = DB::table('object_groupables') + $set = DB::table('object_groupables') ->whereIn('object_groupable_id', $this->ids) ->where('object_groupable_type', Account::class) - ->get(['object_groupable_id', 'object_group_id']) - ; + ->get(['object_groupable_id', 'object_group_id']); - $ids = array_unique($set->pluck('object_group_id')->toArray()); + $ids = array_unique($set->pluck('object_group_id')->toArray()); foreach ($set as $entry) { - $this->mappedObjects[(int)$entry->object_groupable_id] = (int)$entry->object_group_id; + $this->mappedObjects[(int) $entry->object_groupable_id] = (int) $entry->object_group_id; } $groups = ObjectGroup::whereIn('id', $ids)->get(['id', 'title', 'order'])->toArray(); foreach ($groups as $group) { - $group['id'] = (int)$group['id']; - $group['order'] = (int)$group['order']; - $this->objectGroups[(int)$group['id']] = $group; + $group['id'] = (int) $group['id']; + $group['order'] = (int) $group['order']; + $this->objectGroups[(int) $group['id']] = $group; } } @@ -401,20 +416,11 @@ class AccountEnrichment implements EnrichmentInterface ->setUserGroup($this->userGroup) ->setAccounts($this->collection) ->withAccountInformation() - ->setTypes([TransactionTypeEnum::OPENING_BALANCE->value]) - ; - $journals = $collector->getExtractedJournals(); + ->setTypes([TransactionTypeEnum::OPENING_BALANCE->value]); + $journals = $collector->getExtractedJournals(); foreach ($journals as $journal) { - $this->openingBalances[(int)$journal['source_account_id']] - = [ - 'amount' => Steam::negative($journal['amount']), - 'date' => $journal['date'], - ]; - $this->openingBalances[(int)$journal['destination_account_id']] - = [ - 'amount' => Steam::positive($journal['amount']), - 'date' => $journal['date'], - ]; + $this->openingBalances[(int) $journal['source_account_id']] = ['amount' => Steam::negative($journal['amount']), 'date' => $journal['date']]; + $this->openingBalances[(int) $journal['destination_account_id']] = ['amount' => Steam::positive($journal['amount']), 'date' => $journal['date']]; } } @@ -424,11 +430,11 @@ class AccountEnrichment implements EnrichmentInterface /** @var AccountType $type */ foreach ($types as $type) { - $this->accountTypes[(int)$type->id] = $type->type; + $this->accountTypes[(int) $type->id] = $type->type; } } - private function getBalanceDifference(int $id, TransactionCurrency $currency): ?string + private function getBalanceDifference(int $id, TransactionCurrency $currency): null|string { if (!$this->start instanceof Carbon || !$this->end instanceof Carbon) { return null; @@ -438,8 +444,8 @@ class AccountEnrichment implements EnrichmentInterface if (0 === count($startBalance) || 0 === count($endBalance)) { return null; } - $start = $startBalance[$currency->code] ?? '0'; - $end = $endBalance[$currency->code] ?? '0'; + $start = $startBalance[$currency->code] ?? '0'; + $end = $endBalance[$currency->code] ?? '0'; return bcsub($end, $start); } @@ -460,7 +466,11 @@ class AccountEnrichment implements EnrichmentInterface case 'current_balance': case 'pc_current_balance': - $this->collection = $this->collection->sortBy(static fn (Account $account) => $account->meta['balances'][$parameter[0]] ?? '0', SORT_NUMERIC, 'desc' === $parameter[1]); + $this->collection = $this->collection->sortBy( + static fn(Account $account) => $account->meta['balances'][$parameter[0]] ?? '0', + SORT_NUMERIC, + 'desc' === $parameter[1] + ); break; } diff --git a/app/Support/JsonApi/Enrichments/AvailableBudgetEnrichment.php b/app/Support/JsonApi/Enrichments/AvailableBudgetEnrichment.php index 8e09d2c5da..5558ce620a 100644 --- a/app/Support/JsonApi/Enrichments/AvailableBudgetEnrichment.php +++ b/app/Support/JsonApi/Enrichments/AvailableBudgetEnrichment.php @@ -40,26 +40,26 @@ use Override; class AvailableBudgetEnrichment implements EnrichmentInterface { - private Collection $collection; // @phpstan-ignore-line - private readonly bool $convertToPrimary; // @phpstan-ignore-line - private array $currencies = []; - private array $currencyIds = []; - private array $ids = []; - private readonly NoBudgetRepositoryInterface $noBudgetRepository; + private Collection $collection; // @phpstan-ignore-line + private readonly bool $convertToPrimary; // @phpstan-ignore-line + private array $currencies = []; + private array $currencyIds = []; + private array $ids = []; + private readonly NoBudgetRepositoryInterface $noBudgetRepository; private readonly OperationsRepositoryInterface $opsRepository; - private array $pcSpentInBudgets = []; - private array $pcSpentOutsideBudgets = []; - private readonly BudgetRepositoryInterface $repository; - private array $spentInBudgets = []; - private array $spentOutsideBudgets = []; + private array $pcSpentInBudgets = []; + private array $pcSpentOutsideBudgets = []; + private readonly BudgetRepositoryInterface $repository; + private array $spentInBudgets = []; + private array $spentOutsideBudgets = []; public function __construct() { // $this->primaryCurrency = Amount::getPrimaryCurrency(); - $this->convertToPrimary = Amount::convertToPrimary(); + $this->convertToPrimary = Amount::convertToPrimary(); $this->noBudgetRepository = app(NoBudgetRepositoryInterface::class); - $this->opsRepository = app(OperationsRepositoryInterface::class); - $this->repository = app(BudgetRepositoryInterface::class); + $this->opsRepository = app(OperationsRepositoryInterface::class); + $this->repository = app(BudgetRepositoryInterface::class); } #[Override] @@ -103,7 +103,7 @@ class AvailableBudgetEnrichment implements EnrichmentInterface private function appendCollectedData(): void { $this->collection = $this->collection->map(function (AvailableBudget $item): AvailableBudget { - $id = (int)$item->id; + $id = (int) $item->id; $currencyId = $this->currencyIds[$id]; $currency = $this->currencies[$currencyId]; $meta = [ @@ -111,7 +111,7 @@ class AvailableBudgetEnrichment implements EnrichmentInterface 'spent_in_budgets' => $this->spentInBudgets[$id] ?? [], 'pc_spent_in_budgets' => $this->pcSpentInBudgets[$id] ?? [], 'spent_outside_budgets' => $this->spentOutsideBudgets[$id] ?? [], - 'pc_spent_outside_budgets' => $this->pcSpentOutsideBudgets[$id] ?? [], + 'pc_spent_outside_budgets' => $this->pcSpentOutsideBudgets[$id] ?? [] ]; $item->meta = $meta; @@ -124,7 +124,7 @@ class AvailableBudgetEnrichment implements EnrichmentInterface $ids = array_unique(array_values($this->currencyIds)); $set = TransactionCurrency::whereIn('id', $ids)->get(); foreach ($set as $currency) { - $this->currencies[(int)$currency->id] = $currency; + $this->currencies[(int) $currency->id] = $currency; } } @@ -132,8 +132,8 @@ class AvailableBudgetEnrichment implements EnrichmentInterface { /** @var AvailableBudget $availableBudget */ foreach ($this->collection as $availableBudget) { - $this->ids[] = (int)$availableBudget->id; - $this->currencyIds[(int)$availableBudget->id] = (int)$availableBudget->transaction_currency_id; + $this->ids[] = (int) $availableBudget->id; + $this->currencyIds[(int) $availableBudget->id] = (int) $availableBudget->transaction_currency_id; } $this->ids = array_unique($this->ids); } @@ -146,18 +146,40 @@ class AvailableBudgetEnrichment implements EnrichmentInterface $spentInBudgets = $this->opsRepository->collectExpenses($start, $end, null, $allActive); $spentOutsideBudgets = $this->noBudgetRepository->collectExpenses($start, $end); foreach ($this->collection as $availableBudget) { - $id = (int)$availableBudget->id; - $currencyId = $this->currencyIds[$id]; - $currency = $this->currencies[$currencyId]; - $filteredSpentInBudgets = $this->opsRepository->sumCollectedExpenses($spentInBudgets, $availableBudget->start_date, $availableBudget->end_date, $currency); - $filteredSpentOutsideBudgets = $this->opsRepository->sumCollectedExpenses($spentOutsideBudgets, $availableBudget->start_date, $availableBudget->end_date, $currency); - $this->spentInBudgets[$id] = array_values($filteredSpentInBudgets); + $id = (int) $availableBudget->id; + $currencyId = $this->currencyIds[$id]; + $currency = $this->currencies[$currencyId]; + $filteredSpentInBudgets = $this->opsRepository->sumCollectedExpenses( + $spentInBudgets, + $availableBudget->start_date, + $availableBudget->end_date, + $currency + ); + $filteredSpentOutsideBudgets = $this->opsRepository->sumCollectedExpenses( + $spentOutsideBudgets, + $availableBudget->start_date, + $availableBudget->end_date, + $currency + ); + $this->spentInBudgets[$id] = array_values($filteredSpentInBudgets); $this->spentOutsideBudgets[$id] = array_values($filteredSpentOutsideBudgets); if ($this->convertToPrimary) { - $pcFilteredSpentInBudgets = $this->opsRepository->sumCollectedExpenses($spentInBudgets, $availableBudget->start_date, $availableBudget->end_date, $currency, true); - $pcFilteredSpentOutsideBudgets = $this->opsRepository->sumCollectedExpenses($spentOutsideBudgets, $availableBudget->start_date, $availableBudget->end_date, $currency, true); - $this->pcSpentInBudgets[$id] = array_values($pcFilteredSpentInBudgets); + $pcFilteredSpentInBudgets = $this->opsRepository->sumCollectedExpenses( + $spentInBudgets, + $availableBudget->start_date, + $availableBudget->end_date, + $currency, + true + ); + $pcFilteredSpentOutsideBudgets = $this->opsRepository->sumCollectedExpenses( + $spentOutsideBudgets, + $availableBudget->start_date, + $availableBudget->end_date, + $currency, + true + ); + $this->pcSpentInBudgets[$id] = array_values($pcFilteredSpentInBudgets); $this->pcSpentOutsideBudgets[$id] = array_values($pcFilteredSpentOutsideBudgets); } } diff --git a/app/Support/JsonApi/Enrichments/BudgetEnrichment.php b/app/Support/JsonApi/Enrichments/BudgetEnrichment.php index 92e953a7be..3053b17bf4 100644 --- a/app/Support/JsonApi/Enrichments/BudgetEnrichment.php +++ b/app/Support/JsonApi/Enrichments/BudgetEnrichment.php @@ -1,6 +1,5 @@ first(); } - public function setEnd(?Carbon $end): void + public function setEnd(null|Carbon $end): void { $this->end = $end; } - public function setStart(?Carbon $start): void + public function setStart(null|Carbon $start): void { $this->start = $start; } @@ -101,8 +100,8 @@ class BudgetEnrichment implements EnrichmentInterface private function appendCollectedData(): void { $this->collection = $this->collection->map(function (Budget $item): Budget { - $id = (int)$item->id; - $meta = [ + $id = (int) $item->id; + $meta = [ 'object_group_id' => null, 'object_group_order' => null, 'object_group_title' => null, @@ -110,18 +109,17 @@ class BudgetEnrichment implements EnrichmentInterface 'currency' => $this->currencies[$id] ?? null, 'auto_budget' => $this->autoBudgets[$id] ?? null, 'spent' => $this->spent[$id] ?? null, - 'pc_spent' => $this->pcSpent[$id] ?? null, + 'pc_spent' => $this->pcSpent[$id] ?? null ]; // add object group if available if (array_key_exists($id, $this->mappedObjects)) { - $key = $this->mappedObjects[$id]; - $meta['object_group_id'] = (string)$this->objectGroups[$key]['id']; + $key = $this->mappedObjects[$id]; + $meta['object_group_id'] = (string) $this->objectGroups[$key]['id']; $meta['object_group_title'] = $this->objectGroups[$key]['title']; $meta['object_group_order'] = $this->objectGroups[$key]['order']; } - $item->meta = $meta; return $item; @@ -134,13 +132,13 @@ class BudgetEnrichment implements EnrichmentInterface /** @var AutoBudget $autoBudget */ foreach ($set as $autoBudget) { - $budgetId = (int)$autoBudget->budget_id; - $this->currencies[$budgetId] = $autoBudget->transactionCurrency; + $budgetId = (int) $autoBudget->budget_id; + $this->currencies[$budgetId] = $autoBudget->transactionCurrency; $this->autoBudgets[$budgetId] = [ - 'type' => (int)$autoBudget->auto_budget_type, + 'type' => (int) $autoBudget->auto_budget_type, 'period' => $autoBudget->period, 'amount' => $autoBudget->amount, - 'pc_amount' => $autoBudget->native_amount, + 'pc_amount' => $autoBudget->native_amount ]; } } @@ -154,10 +152,10 @@ class BudgetEnrichment implements EnrichmentInterface $opsRepository->setUserGroup($this->userGroup); // $spent = $this->beautify(); // $set = $this->opsRepository->sumExpenses($start, $end, null, new Collection()->push($budget)) - $expenses = $opsRepository->collectExpenses($this->start, $this->end, null, $this->collection); + $expenses = $opsRepository->collectExpenses($this->start, $this->end, null, $this->collection); foreach ($this->collection as $item) { - $id = (int)$item->id; - $this->spent[$id] = array_values($opsRepository->sumCollectedExpensesByBudget($expenses, $item)); + $id = (int) $item->id; + $this->spent[$id] = array_values($opsRepository->sumCollectedExpensesByBudget($expenses, $item)); $this->pcSpent[$id] = array_values($opsRepository->sumCollectedExpensesByBudget($expenses, $item, true)); } } @@ -167,43 +165,44 @@ class BudgetEnrichment implements EnrichmentInterface { /** @var Budget $budget */ foreach ($this->collection as $budget) { - $this->ids[] = (int)$budget->id; + $this->ids[] = (int) $budget->id; } $this->ids = array_unique($this->ids); } private function collectNotes(): void { - $notes = Note::query()->whereIn('noteable_id', $this->ids) + $notes = Note::query() + ->whereIn('noteable_id', $this->ids) ->whereNotNull('notes.text') ->where('notes.text', '!=', '') - ->where('noteable_type', Budget::class)->get(['notes.noteable_id', 'notes.text'])->toArray() - ; + ->where('noteable_type', Budget::class) + ->get(['notes.noteable_id', 'notes.text']) + ->toArray(); foreach ($notes as $note) { - $this->notes[(int)$note['noteable_id']] = (string)$note['text']; + $this->notes[(int) $note['noteable_id']] = (string) $note['text']; } Log::debug(sprintf('Enrich with %d note(s)', count($this->notes))); } private function collectObjectGroups(): void { - $set = DB::table('object_groupables') + $set = DB::table('object_groupables') ->whereIn('object_groupable_id', $this->ids) ->where('object_groupable_type', Budget::class) - ->get(['object_groupable_id', 'object_group_id']) - ; + ->get(['object_groupable_id', 'object_group_id']); - $ids = array_unique($set->pluck('object_group_id')->toArray()); + $ids = array_unique($set->pluck('object_group_id')->toArray()); foreach ($set as $entry) { - $this->mappedObjects[(int)$entry->object_groupable_id] = (int)$entry->object_group_id; + $this->mappedObjects[(int) $entry->object_groupable_id] = (int) $entry->object_group_id; } $groups = ObjectGroup::whereIn('id', $ids)->get(['id', 'title', 'order'])->toArray(); foreach ($groups as $group) { - $group['id'] = (int)$group['id']; - $group['order'] = (int)$group['order']; - $this->objectGroups[(int)$group['id']] = $group; + $group['id'] = (int) $group['id']; + $group['order'] = (int) $group['order']; + $this->objectGroups[(int) $group['id']] = $group; } } } diff --git a/app/Support/JsonApi/Enrichments/BudgetLimitEnrichment.php b/app/Support/JsonApi/Enrichments/BudgetLimitEnrichment.php index 5a94106a48..865df49bd3 100644 --- a/app/Support/JsonApi/Enrichments/BudgetLimitEnrichment.php +++ b/app/Support/JsonApi/Enrichments/BudgetLimitEnrichment.php @@ -1,6 +1,5 @@ convertToPrimary = Amount::convertToPrimary(); - $this->primaryCurrency = Amount::getPrimaryCurrency(); + $this->primaryCurrency = Amount::getPrimaryCurrency(); } public function enrich(Collection $collection): Collection @@ -86,21 +85,23 @@ class BudgetLimitEnrichment implements EnrichmentInterface $this->user = $user; } - public function setUserGroup(UserGroup $userGroup): void {} + public function setUserGroup(UserGroup $userGroup): void + { + } private function appendCollectedData(): void { $this->collection = $this->collection->map(function (BudgetLimit $item): BudgetLimit { - $id = (int)$item->id; - $currencyId = (int)$item->transaction_currency_id; + $id = (int) $item->id; + $currencyId = (int) $item->transaction_currency_id; if (0 === $currencyId) { $currencyId = $this->primaryCurrency->id; } - $meta = [ + $meta = [ 'notes' => $this->notes[$id] ?? null, 'spent' => $this->expenses[$id] ?? [], 'pc_spent' => $this->pcExpenses[$id] ?? [], - 'currency' => $this->currencies[$currencyId], + 'currency' => $this->currencies[$currencyId] ]; $item->meta = $meta; @@ -110,23 +111,37 @@ class BudgetLimitEnrichment implements EnrichmentInterface private function collectBudgets(): void { - $budgetIds = $this->collection->pluck('budget_id')->unique()->toArray(); - $budgets = Budget::whereIn('id', $budgetIds)->get(); + $budgetIds = $this->collection + ->pluck('budget_id') + ->unique() + ->toArray(); + $budgets = Budget::whereIn('id', $budgetIds)->get(); $repository = app(OperationsRepository::class); $repository->setUser($this->user); - $expenses = $repository->collectExpenses($this->start, $this->end, null, $budgets); + $expenses = $repository->collectExpenses($this->start, $this->end, null, $budgets); /** @var BudgetLimit $budgetLimit */ foreach ($this->collection as $budgetLimit) { Log::debug(sprintf('Filtering expenses for budget limit #%d (budget #%d)', $budgetLimit->id, $budgetLimit->budget_id)); - $id = (int)$budgetLimit->id; - $filteredExpenses = $this->filterToBudget($expenses, $budgetLimit->budget_id); - $filteredExpenses = $repository->sumCollectedExpenses($filteredExpenses, $budgetLimit->start_date, $budgetLimit->end_date, $budgetLimit->transactionCurrency); + $id = (int) $budgetLimit->id; + $filteredExpenses = $this->filterToBudget($expenses, $budgetLimit->budget_id); + $filteredExpenses = $repository->sumCollectedExpenses( + $filteredExpenses, + $budgetLimit->start_date, + $budgetLimit->end_date, + $budgetLimit->transactionCurrency + ); $this->expenses[$id] = array_values($filteredExpenses); if ($this->convertToPrimary && $budgetLimit->transactionCurrency->id !== $this->primaryCurrency->id) { - $pcFilteredExpenses = $repository->sumCollectedExpenses($expenses, $budgetLimit->start_date, $budgetLimit->end_date, $budgetLimit->transactionCurrency, true); + $pcFilteredExpenses = $repository->sumCollectedExpenses( + $expenses, + $budgetLimit->start_date, + $budgetLimit->end_date, + $budgetLimit->transactionCurrency, + true + ); $this->pcExpenses[$id] = array_values($pcFilteredExpenses); } if ($this->convertToPrimary && $budgetLimit->transactionCurrency->id === $this->primaryCurrency->id) { @@ -138,48 +153,50 @@ class BudgetLimitEnrichment implements EnrichmentInterface private function collectCurrencies(): void { $this->currencies[$this->primaryCurrency->id] = $this->primaryCurrency; - $currencies = TransactionCurrency::whereIn('id', $this->currencyIds)->whereNot('id', $this->primaryCurrency->id)->get(); + $currencies = TransactionCurrency::whereIn('id', $this->currencyIds)->whereNot('id', $this->primaryCurrency->id)->get(); foreach ($currencies as $currency) { - $this->currencies[(int)$currency->id] = $currency; + $this->currencies[(int) $currency->id] = $currency; } } private function collectIds(): void { - $this->start = $this->collection->min('start_date') ?? Carbon::now()->startOfMonth(); - $this->end = $this->collection->max('end_date') ?? Carbon::now()->endOfMonth(); + $this->start = $this->collection->min('start_date') ?? Carbon::now()->startOfMonth(); + $this->end = $this->collection->max('end_date') ?? Carbon::now()->endOfMonth(); // #11096 make sure that the max end date is also at the end of the day, $this->end->endOfDay(); /** @var BudgetLimit $limit */ foreach ($this->collection as $limit) { - $id = (int)$limit->id; + $id = (int) $limit->id; $this->ids[] = $id; - if (0 !== (int)$limit->transaction_currency_id) { - $this->currencyIds[$id] = (int)$limit->transaction_currency_id; + if (0 !== (int) $limit->transaction_currency_id) { + $this->currencyIds[$id] = (int) $limit->transaction_currency_id; } } - $this->ids = array_unique($this->ids); + $this->ids = array_unique($this->ids); $this->currencyIds = array_unique($this->currencyIds); } private function collectNotes(): void { - $notes = Note::query()->whereIn('noteable_id', $this->ids) + $notes = Note::query() + ->whereIn('noteable_id', $this->ids) ->whereNotNull('notes.text') ->where('notes.text', '!=', '') - ->where('noteable_type', BudgetLimit::class)->get(['notes.noteable_id', 'notes.text'])->toArray() - ; + ->where('noteable_type', BudgetLimit::class) + ->get(['notes.noteable_id', 'notes.text']) + ->toArray(); foreach ($notes as $note) { - $this->notes[(int)$note['noteable_id']] = (string)$note['text']; + $this->notes[(int) $note['noteable_id']] = (string) $note['text']; } Log::debug(sprintf('Enrich with %d note(s)', count($this->notes))); } private function filterToBudget(array $expenses, int $budget): array { - $result = array_filter($expenses, static fn (array $item): bool => (int)$item['budget_id'] === $budget); + $result = array_filter($expenses, static fn(array $item): bool => (int) $item['budget_id'] === $budget); Log::debug(sprintf('filterToBudget for budget #%d, from %d to %d items', $budget, count($expenses), count($result))); return $result; @@ -187,13 +204,13 @@ class BudgetLimitEnrichment implements EnrichmentInterface private function stringifyIds(): void { - $this->expenses = array_map(static fn ($first): array => array_map(static function (array $second): array { - $second['currency_id'] = (string)($second['currency_id'] ?? 0); + $this->expenses = array_map(static fn($first): array => array_map(static function (array $second): array { + $second['currency_id'] = (string) ($second['currency_id'] ?? 0); return $second; }, $first), $this->expenses); - $this->pcExpenses = array_map(static fn (array $first): array => array_map(static function (array $second): array { + $this->pcExpenses = array_map(static fn(array $first): array => array_map(static function (array $second): array { $second['currency_id'] ??= 0; return $second; diff --git a/app/Support/JsonApi/Enrichments/CategoryEnrichment.php b/app/Support/JsonApi/Enrichments/CategoryEnrichment.php index 699102912e..c232b6a403 100644 --- a/app/Support/JsonApi/Enrichments/CategoryEnrichment.php +++ b/app/Support/JsonApi/Enrichments/CategoryEnrichment.php @@ -1,6 +1,5 @@ first(); } - public function setEnd(?Carbon $end): void + public function setEnd(null|Carbon $end): void { $this->end = $end; } - public function setStart(?Carbon $start): void + public function setStart(null|Carbon $start): void { $this->start = $start; } @@ -95,15 +94,15 @@ class CategoryEnrichment implements EnrichmentInterface private function appendCollectedData(): void { $this->collection = $this->collection->map(function (Category $item): Category { - $id = (int)$item->id; - $meta = [ + $id = (int) $item->id; + $meta = [ 'notes' => $this->notes[$id] ?? null, 'spent' => $this->spent[$id] ?? null, 'pc_spent' => $this->pcSpent[$id] ?? null, 'earned' => $this->earned[$id] ?? null, 'pc_earned' => $this->pcEarned[$id] ?? null, 'transfers' => $this->transfers[$id] ?? null, - 'pc_transfers' => $this->pcTransfers[$id] ?? null, + 'pc_transfers' => $this->pcTransfers[$id] ?? null ]; $item->meta = $meta; @@ -115,20 +114,22 @@ class CategoryEnrichment implements EnrichmentInterface { /** @var Category $category */ foreach ($this->collection as $category) { - $this->ids[] = (int)$category->id; + $this->ids[] = (int) $category->id; } $this->ids = array_unique($this->ids); } private function collectNotes(): void { - $notes = Note::query()->whereIn('noteable_id', $this->ids) + $notes = Note::query() + ->whereIn('noteable_id', $this->ids) ->whereNotNull('notes.text') ->where('notes.text', '!=', '') - ->where('noteable_type', Category::class)->get(['notes.noteable_id', 'notes.text'])->toArray() - ; + ->where('noteable_type', Category::class) + ->get(['notes.noteable_id', 'notes.text']) + ->toArray(); foreach ($notes as $note) { - $this->notes[(int)$note['noteable_id']] = (string)$note['text']; + $this->notes[(int) $note['noteable_id']] = (string) $note['text']; } Log::debug(sprintf('Enrich with %d note(s)', count($this->notes))); } @@ -140,16 +141,16 @@ class CategoryEnrichment implements EnrichmentInterface $opsRepository = app(OperationsRepositoryInterface::class); $opsRepository->setUser($this->user); $opsRepository->setUserGroup($this->userGroup); - $expenses = $opsRepository->collectExpenses($this->start, $this->end, null, $this->collection); - $income = $opsRepository->collectIncome($this->start, $this->end, null, $this->collection); - $transfers = $opsRepository->collectTransfers($this->start, $this->end, null, $this->collection); + $expenses = $opsRepository->collectExpenses($this->start, $this->end, null, $this->collection); + $income = $opsRepository->collectIncome($this->start, $this->end, null, $this->collection); + $transfers = $opsRepository->collectTransfers($this->start, $this->end, null, $this->collection); foreach ($this->collection as $item) { - $id = (int)$item->id; - $this->spent[$id] = array_values($opsRepository->sumCollectedTransactionsByCategory($expenses, $item, 'negative')); - $this->pcSpent[$id] = array_values($opsRepository->sumCollectedTransactionsByCategory($expenses, $item, 'negative', true)); - $this->earned[$id] = array_values($opsRepository->sumCollectedTransactionsByCategory($income, $item, 'positive')); - $this->pcEarned[$id] = array_values($opsRepository->sumCollectedTransactionsByCategory($income, $item, 'positive', true)); - $this->transfers[$id] = array_values($opsRepository->sumCollectedTransactionsByCategory($transfers, $item, 'positive')); + $id = (int) $item->id; + $this->spent[$id] = array_values($opsRepository->sumCollectedTransactionsByCategory($expenses, $item, 'negative')); + $this->pcSpent[$id] = array_values($opsRepository->sumCollectedTransactionsByCategory($expenses, $item, 'negative', true)); + $this->earned[$id] = array_values($opsRepository->sumCollectedTransactionsByCategory($income, $item, 'positive')); + $this->pcEarned[$id] = array_values($opsRepository->sumCollectedTransactionsByCategory($income, $item, 'positive', true)); + $this->transfers[$id] = array_values($opsRepository->sumCollectedTransactionsByCategory($transfers, $item, 'positive')); $this->pcTransfers[$id] = array_values($opsRepository->sumCollectedTransactionsByCategory($transfers, $item, 'positive', true)); } } diff --git a/app/Support/JsonApi/Enrichments/PiggyBankEnrichment.php b/app/Support/JsonApi/Enrichments/PiggyBankEnrichment.php index 318768d807..b0a02c7039 100644 --- a/app/Support/JsonApi/Enrichments/PiggyBankEnrichment.php +++ b/app/Support/JsonApi/Enrichments/PiggyBankEnrichment.php @@ -1,6 +1,5 @@ primaryCurrency = Amount::getPrimaryCurrency(); - $this->date = now(config('app.timezone')); + $this->date = now(config('app.timezone')); } public function enrich(Collection $collection): Collection @@ -70,7 +69,6 @@ class PiggyBankEnrichment implements EnrichmentInterface $this->collectObjectGroups(); $this->collectNotes(); - $this->appendCollectedData(); return $this->collection; @@ -90,21 +88,23 @@ class PiggyBankEnrichment implements EnrichmentInterface $this->setUserGroup($user->userGroup); } - public function setUserGroup(UserGroup $userGroup): void {} + public function setUserGroup(UserGroup $userGroup): void + { + } private function appendCollectedData(): void { $this->collection = $this->collection->map(function (PiggyBank $item): PiggyBank { - $id = (int)$item->id; - $currencyId = (int)$item->transaction_currency_id; - $currency = $this->currencies[$currencyId] ?? $this->primaryCurrency; - $targetAmount = null; + $id = (int) $item->id; + $currencyId = (int) $item->transaction_currency_id; + $currency = $this->currencies[$currencyId] ?? $this->primaryCurrency; + $targetAmount = null; if (0 !== bccomp($item->target_amount, '0')) { $targetAmount = $item->target_amount; } - $meta = [ - 'notes' => $this->notes[$id] ?? null, - 'currency' => $this->currencies[$currencyId] ?? null, + $meta = [ + 'notes' => $this->notes[$id] ?? null, + 'currency' => $this->currencies[$currencyId] ?? null, // 'auto_budget' => $this->autoBudgets[$id] ?? null, // 'spent' => $this->spent[$id] ?? null, // 'pc_spent' => $this->pcSpent[$id] ?? null, @@ -114,56 +114,70 @@ class PiggyBankEnrichment implements EnrichmentInterface 'current_amount' => '0', 'pc_current_amount' => '0', 'target_amount' => null === $targetAmount ? null : Steam::bcround($targetAmount, $currency->decimal_places), - 'pc_target_amount' => null === $item->native_target_amount ? null : Steam::bcround($item->native_target_amount, $this->primaryCurrency->decimal_places), + 'pc_target_amount' => null === $item->native_target_amount + ? null + : Steam::bcround($item->native_target_amount, $this->primaryCurrency->decimal_places), 'left_to_save' => null, 'pc_left_to_save' => null, 'save_per_month' => null, 'pc_save_per_month' => null, - 'accounts' => [], + 'accounts' => [] ]; // add object group if available if (array_key_exists($id, $this->mappedObjects)) { - $key = $this->mappedObjects[$id]; - $meta['object_group_id'] = (string)$this->objectGroups[$key]['id']; + $key = $this->mappedObjects[$id]; + $meta['object_group_id'] = (string) $this->objectGroups[$key]['id']; $meta['object_group_title'] = $this->objectGroups[$key]['title']; $meta['object_group_order'] = $this->objectGroups[$key]['order']; } // add current amount(s). foreach ($this->amounts[$id] as $accountId => $row) { - $meta['accounts'][] = [ - 'account_id' => (string)$accountId, + $meta['accounts'][] = [ + 'account_id' => (string) $accountId, 'name' => $this->accounts[$accountId]['name'] ?? '', 'current_amount' => Steam::bcround($row['current_amount'], $currency->decimal_places), - 'pc_current_amount' => Steam::bcround($row['pc_current_amount'], $this->primaryCurrency->decimal_places), + 'pc_current_amount' => Steam::bcround($row['pc_current_amount'], $this->primaryCurrency->decimal_places) ]; - $meta['current_amount'] = bcadd($meta['current_amount'], (string) $row['current_amount']); + $meta['current_amount'] = bcadd($meta['current_amount'], (string) $row['current_amount']); // only add pc_current_amount when the pc_current_amount is set - $meta['pc_current_amount'] = null === $row['pc_current_amount'] ? null : bcadd((string) $meta['pc_current_amount'], (string) $row['pc_current_amount']); + $meta['pc_current_amount'] = null === $row['pc_current_amount'] + ? null + : bcadd((string) $meta['pc_current_amount'], (string) $row['pc_current_amount']); } - $meta['current_amount'] = Steam::bcround($meta['current_amount'], $currency->decimal_places); + $meta['current_amount'] = Steam::bcround($meta['current_amount'], $currency->decimal_places); // only round this number when pc_current_amount is set. - $meta['pc_current_amount'] = null === $meta['pc_current_amount'] ? null : Steam::bcround($meta['pc_current_amount'], $this->primaryCurrency->decimal_places); + $meta['pc_current_amount'] = null === $meta['pc_current_amount'] + ? null + : Steam::bcround($meta['pc_current_amount'], $this->primaryCurrency->decimal_places); // calculate left to save, only when there is a target amount. if (null !== $targetAmount) { - $meta['left_to_save'] = bcsub((string) $meta['target_amount'], (string) $meta['current_amount']); - $meta['pc_left_to_save'] = null === $meta['pc_target_amount'] ? null : bcsub((string) $meta['pc_target_amount'], (string) $meta['pc_current_amount']); + $meta['left_to_save'] = bcsub((string) $meta['target_amount'], (string) $meta['current_amount']); + $meta['pc_left_to_save'] = null === $meta['pc_target_amount'] + ? null + : bcsub((string) $meta['pc_target_amount'], (string) $meta['pc_current_amount']); } // get suggested per month. - $meta['save_per_month'] = Steam::bcround($this->getSuggestedMonthlyAmount($this->date, $item->target_date, $meta['target_amount'], $meta['current_amount']), $currency->decimal_places); + $meta['save_per_month'] = Steam::bcround( + $this->getSuggestedMonthlyAmount($this->date, $item->target_date, $meta['target_amount'], $meta['current_amount']), + $currency->decimal_places + ); if (null !== $meta['pc_current_amount']) { - $meta['pc_save_per_month'] = Steam::bcround($this->getSuggestedMonthlyAmount($this->date, $item->target_date, $meta['pc_target_amount'], $meta['pc_current_amount']), $currency->decimal_places); + $meta['pc_save_per_month'] = Steam::bcround( + $this->getSuggestedMonthlyAmount($this->date, $item->target_date, $meta['pc_target_amount'], $meta['pc_current_amount']), + $currency->decimal_places + ); } - $item->meta = $meta; + $item->meta = $meta; return $item; }); } - public function setDate(?Carbon $date): void + public function setDate(null|Carbon $date): void { $this->date = $date; } @@ -172,104 +186,111 @@ class PiggyBankEnrichment implements EnrichmentInterface { /** @var PiggyBank $piggy */ foreach ($this->collection as $piggy) { - $id = (int)$piggy->id; - $this->ids[] = $id; - $this->currencyIds[$id] = (int)$piggy->transaction_currency_id; + $id = (int) $piggy->id; + $this->ids[] = $id; + $this->currencyIds[$id] = (int) $piggy->transaction_currency_id; } - $this->ids = array_unique($this->ids); + $this->ids = array_unique($this->ids); // collect currencies. $currencies = TransactionCurrency::whereIn('id', $this->currencyIds)->get(); foreach ($currencies as $currency) { - $this->currencies[(int)$currency->id] = $currency; + $this->currencies[(int) $currency->id] = $currency; } // collect accounts - $set = DB::table('account_piggy_bank')->whereIn('piggy_bank_id', $this->ids)->get(['piggy_bank_id', 'account_id', 'current_amount', 'native_current_amount']); + $set = DB::table('account_piggy_bank')->whereIn('piggy_bank_id', $this->ids)->get([ + 'piggy_bank_id', + 'account_id', + 'current_amount', + 'native_current_amount' + ]); foreach ($set as $item) { - $id = (int)$item->piggy_bank_id; - $accountId = (int)$item->account_id; + $id = (int) $item->piggy_bank_id; + $accountId = (int) $item->account_id; $this->amounts[$id] ??= []; if (!array_key_exists($id, $this->accountIds)) { - $this->accountIds[$id] = (int)$item->account_id; + $this->accountIds[$id] = (int) $item->account_id; } if (!array_key_exists($accountId, $this->amounts[$id])) { - $this->amounts[$id][$accountId] = [ - 'current_amount' => '0', - 'pc_current_amount' => '0', - ]; + $this->amounts[$id][$accountId] = ['current_amount' => '0', 'pc_current_amount' => '0']; } - $this->amounts[$id][$accountId]['current_amount'] = bcadd((string) $this->amounts[$id][$accountId]['current_amount'], (string)$item->current_amount); + $this->amounts[$id][$accountId]['current_amount'] = bcadd( + (string) $this->amounts[$id][$accountId]['current_amount'], + (string) $item->current_amount + ); if (null !== $this->amounts[$id][$accountId]['pc_current_amount'] && null !== $item->native_current_amount) { - $this->amounts[$id][$accountId]['pc_current_amount'] = bcadd($this->amounts[$id][$accountId]['pc_current_amount'], (string)$item->native_current_amount); + $this->amounts[$id][$accountId]['pc_current_amount'] = bcadd( + $this->amounts[$id][$accountId]['pc_current_amount'], + (string) $item->native_current_amount + ); } } // get account currency preference for ALL. - $set = AccountMeta::whereIn('account_id', array_values($this->accountIds))->where('name', 'currency_id')->get(); + $set = AccountMeta::whereIn('account_id', array_values($this->accountIds))->where('name', 'currency_id')->get(); /** @var AccountMeta $item */ foreach ($set as $item) { - $accountId = (int)$item->account_id; - $currencyId = (int)$item->data; + $accountId = (int) $item->account_id; + $currencyId = (int) $item->data; if (!array_key_exists($currencyId, $this->currencies)) { $this->currencies[$currencyId] = Amount::getTransactionCurrencyById($currencyId); } + // $this->accountCurrencies[$accountId] = $this->currencies[$currencyId]; } // get account info. - $set = Account::whereIn('id', array_values($this->accountIds))->get(); + $set = Account::whereIn('id', array_values($this->accountIds))->get(); /** @var Account $item */ foreach ($set as $item) { - $id = (int)$item->id; - $this->accounts[$id] = [ - 'id' => $id, - 'name' => $item->name, - ]; + $id = (int) $item->id; + $this->accounts[$id] = ['id' => $id, 'name' => $item->name]; } } private function collectNotes(): void { - $notes = Note::query()->whereIn('noteable_id', $this->ids) + $notes = Note::query() + ->whereIn('noteable_id', $this->ids) ->whereNotNull('notes.text') ->where('notes.text', '!=', '') - ->where('noteable_type', PiggyBank::class)->get(['notes.noteable_id', 'notes.text'])->toArray() - ; + ->where('noteable_type', PiggyBank::class) + ->get(['notes.noteable_id', 'notes.text']) + ->toArray(); foreach ($notes as $note) { - $this->notes[(int)$note['noteable_id']] = (string)$note['text']; + $this->notes[(int) $note['noteable_id']] = (string) $note['text']; } Log::debug(sprintf('Enrich with %d note(s)', count($this->notes))); } private function collectObjectGroups(): void { - $set = DB::table('object_groupables') + $set = DB::table('object_groupables') ->whereIn('object_groupable_id', $this->ids) ->where('object_groupable_type', PiggyBank::class) - ->get(['object_groupable_id', 'object_group_id']) - ; + ->get(['object_groupable_id', 'object_group_id']); - $ids = array_unique($set->pluck('object_group_id')->toArray()); + $ids = array_unique($set->pluck('object_group_id')->toArray()); foreach ($set as $entry) { - $this->mappedObjects[(int)$entry->object_groupable_id] = (int)$entry->object_group_id; + $this->mappedObjects[(int) $entry->object_groupable_id] = (int) $entry->object_group_id; } $groups = ObjectGroup::whereIn('id', $ids)->get(['id', 'title', 'order'])->toArray(); foreach ($groups as $group) { - $group['id'] = (int)$group['id']; - $group['order'] = (int)$group['order']; - $this->objectGroups[(int)$group['id']] = $group; + $group['id'] = (int) $group['id']; + $group['order'] = (int) $group['order']; + $this->objectGroups[(int) $group['id']] = $group; } } /** * Returns the suggested amount the user should save per month, or "". */ - private function getSuggestedMonthlyAmount(?Carbon $startDate, ?Carbon $targetDate, ?string $targetAmount, string $currentAmount): string + private function getSuggestedMonthlyAmount(null|Carbon $startDate, null|Carbon $targetDate, null|string $targetAmount, string $currentAmount): string { if (null === $targetAmount || !$targetDate instanceof Carbon || !$startDate instanceof Carbon) { return '0'; @@ -277,12 +298,12 @@ class PiggyBankEnrichment implements EnrichmentInterface $savePerMonth = '0'; if (1 === bccomp($targetAmount, $currentAmount)) { $now = today(config('app.timezone')); - $diffInMonths = (int)$startDate->diffInMonths($targetDate); + $diffInMonths = (int) $startDate->diffInMonths($targetDate); $remainingAmount = bcsub($targetAmount, $currentAmount); // more than 1 month to go and still need money to save: if ($diffInMonths > 0 && 1 === bccomp($remainingAmount, '0')) { - $savePerMonth = bcdiv($remainingAmount, (string)$diffInMonths); + $savePerMonth = bcdiv($remainingAmount, (string) $diffInMonths); } // less than 1 month to go but still need money to save: diff --git a/app/Support/JsonApi/Enrichments/PiggyBankEventEnrichment.php b/app/Support/JsonApi/Enrichments/PiggyBankEventEnrichment.php index 4ada77c069..9c491f40ac 100644 --- a/app/Support/JsonApi/Enrichments/PiggyBankEventEnrichment.php +++ b/app/Support/JsonApi/Enrichments/PiggyBankEventEnrichment.php @@ -1,6 +1,5 @@ setUserGroup($user->userGroup); } - public function setUserGroup(UserGroup $userGroup): void {} + public function setUserGroup(UserGroup $userGroup): void + { + } private function appendCollectedData(): void { $this->collection = $this->collection->map(function (PiggyBankEvent $item): PiggyBankEvent { - $id = (int)$item->id; - $piggyId = (int)$item->piggy_bank_id; - $journalId = (int)$item->transaction_journal_id; - $currency = null; + $id = (int) $item->id; + $piggyId = (int) $item->piggy_bank_id; + $journalId = (int) $item->transaction_journal_id; + $currency = null; if (array_key_exists($piggyId, $this->accountIds)) { $accountId = $this->accountIds[$piggyId]; if (array_key_exists($accountId, $this->accountCurrencies)) { $currency = $this->accountCurrencies[$accountId]; } } - $meta = [ - 'transaction_group_id' => array_key_exists($journalId, $this->groupIds) ? (string)$this->groupIds[$journalId] : null, - 'currency' => $currency, + $meta = [ + 'transaction_group_id' => array_key_exists($journalId, $this->groupIds) ? (string) $this->groupIds[$journalId] : null, + 'currency' => $currency ]; $item->meta = $meta; return $item; }); - } private function collectIds(): void { /** @var PiggyBankEvent $event */ foreach ($this->collection as $event) { - $this->ids[] = (int)$event->id; - $this->journalIds[(int)$event->id] = (int)$event->transaction_journal_id; - $this->piggyBankIds[(int)$event->id] = (int)$event->piggy_bank_id; + $this->ids[] = (int) $event->id; + $this->journalIds[(int) $event->id] = (int) $event->transaction_journal_id; + $this->piggyBankIds[(int) $event->id] = (int) $event->piggy_bank_id; } $this->ids = array_unique($this->ids); // collect groups with journal info. - $set = TransactionJournal::whereIn('id', $this->journalIds)->get(['id', 'transaction_group_id']); + $set = TransactionJournal::whereIn('id', $this->journalIds)->get(['id', 'transaction_group_id']); /** @var TransactionJournal $item */ foreach ($set as $item) { - $this->groupIds[(int)$item->id] = (int)$item->transaction_group_id; + $this->groupIds[(int) $item->id] = (int) $item->transaction_group_id; } // collect account info. - $set = DB::table('account_piggy_bank')->whereIn('piggy_bank_id', $this->piggyBankIds)->get(['piggy_bank_id', 'account_id']); + $set = DB::table('account_piggy_bank')->whereIn('piggy_bank_id', $this->piggyBankIds)->get(['piggy_bank_id', 'account_id']); foreach ($set as $item) { - $id = (int)$item->piggy_bank_id; + $id = (int) $item->piggy_bank_id; if (!array_key_exists($id, $this->accountIds)) { - $this->accountIds[$id] = (int)$item->account_id; + $this->accountIds[$id] = (int) $item->account_id; } } // get account currency preference for ALL. - $set = AccountMeta::whereIn('account_id', array_values($this->accountIds))->where('name', 'currency_id')->get(); + $set = AccountMeta::whereIn('account_id', array_values($this->accountIds))->where('name', 'currency_id')->get(); /** @var AccountMeta $item */ foreach ($set as $item) { - $accountId = (int)$item->account_id; - $currencyId = (int)$item->data; + $accountId = (int) $item->account_id; + $currencyId = (int) $item->data; if (!array_key_exists($currencyId, $this->currencies)) { $this->currencies[$currencyId] = Amount::getTransactionCurrencyById($currencyId); } diff --git a/app/Support/JsonApi/Enrichments/RecurringEnrichment.php b/app/Support/JsonApi/Enrichments/RecurringEnrichment.php index c033225c58..dba219d7a4 100644 --- a/app/Support/JsonApi/Enrichments/RecurringEnrichment.php +++ b/app/Support/JsonApi/Enrichments/RecurringEnrichment.php @@ -1,6 +1,5 @@ primaryCurrency = Amount::getPrimaryCurrency(); + $this->primaryCurrency = Amount::getPrimaryCurrency(); $this->convertToPrimary = Amount::convertToPrimary(); } @@ -115,32 +114,48 @@ class RecurringEnrichment implements EnrichmentInterface public function getRepetitionDescription(RecurrenceRepetition $repetition): string { if ('daily' === $repetition->repetition_type) { - return (string)trans('firefly.recurring_daily', [], $this->language); + return (string) trans('firefly.recurring_daily', [], $this->language); } if ('weekly' === $repetition->repetition_type) { $dayOfWeek = trans(sprintf('config.dow_%s', $repetition->repetition_moment), [], $this->language); if ($repetition->repetition_skip > 0) { - return (string)trans('firefly.recurring_weekly_skip', ['weekday' => $dayOfWeek, 'skip' => $repetition->repetition_skip + 1], $this->language); + return (string) trans( + 'firefly.recurring_weekly_skip', + ['weekday' => $dayOfWeek, 'skip' => $repetition->repetition_skip + 1], + $this->language + ); } - return (string)trans('firefly.recurring_weekly', ['weekday' => $dayOfWeek], $this->language); + return (string) trans('firefly.recurring_weekly', ['weekday' => $dayOfWeek], $this->language); } if ('monthly' === $repetition->repetition_type) { if ($repetition->repetition_skip > 0) { - return (string)trans('firefly.recurring_monthly_skip', ['dayOfMonth' => $repetition->repetition_moment, 'skip' => $repetition->repetition_skip + 1], $this->language); + return (string) trans( + 'firefly.recurring_monthly_skip', + ['dayOfMonth' => $repetition->repetition_moment, 'skip' => $repetition->repetition_skip + 1], + $this->language + ); } - return (string)trans('firefly.recurring_monthly', ['dayOfMonth' => $repetition->repetition_moment, 'skip' => $repetition->repetition_skip - 1], $this->language); + return (string) trans( + 'firefly.recurring_monthly', + ['dayOfMonth' => $repetition->repetition_moment, 'skip' => $repetition->repetition_skip - 1], + $this->language + ); } if ('ndom' === $repetition->repetition_type) { - $parts = explode(',', $repetition->repetition_moment); + $parts = explode(',', $repetition->repetition_moment); // first part is number of week, second is weekday. $dayOfWeek = trans(sprintf('config.dow_%s', $parts[1]), [], $this->language); if ($repetition->repetition_skip > 0) { - return (string)trans('firefly.recurring_ndom_skip', ['skip' => $repetition->repetition_skip, 'weekday' => $dayOfWeek, 'dayOfMonth' => $parts[0]], $this->language); + return (string) trans( + 'firefly.recurring_ndom_skip', + ['skip' => $repetition->repetition_skip, 'weekday' => $dayOfWeek, 'dayOfMonth' => $parts[0]], + $this->language + ); } - return (string)trans('firefly.recurring_ndom', ['weekday' => $dayOfWeek, 'dayOfMonth' => $parts[0]], $this->language); + return (string) trans('firefly.recurring_ndom', ['weekday' => $dayOfWeek, 'dayOfMonth' => $parts[0]], $this->language); } if ('yearly' === $repetition->repetition_type) { $today = today(config('app.timezone'))->endOfYear(); @@ -150,9 +165,9 @@ class RecurringEnrichment implements EnrichmentInterface } // $diffInYears = (int)$today->diffInYears($repDate, true); // $repDate->addYears($diffInYears); // technically not necessary. - $string = $repDate->isoFormat((string)trans('config.month_and_day_no_year_js')); + $string = $repDate->isoFormat((string) trans('config.month_and_day_no_year_js')); - return (string)trans('firefly.recurring_yearly', ['date' => $string], $this->language); + return (string) trans('firefly.recurring_yearly', ['date' => $string], $this->language); } return ''; @@ -173,11 +188,11 @@ class RecurringEnrichment implements EnrichmentInterface private function appendCollectedData(): void { $this->collection = $this->collection->map(function (Recurrence $item): Recurrence { - $id = (int)$item->id; - $meta = [ + $id = (int) $item->id; + $meta = [ 'notes' => $this->notes[$id] ?? null, 'repetitions' => array_values($this->repetitions[$id] ?? []), - 'transactions' => $this->processTransactions(array_values($this->transactions[$id] ?? [])), + 'transactions' => $this->processTransactions(array_values($this->transactions[$id] ?? [])) ]; $item->meta = $meta; @@ -193,7 +208,7 @@ class RecurringEnrichment implements EnrichmentInterface /** @var Account $account */ foreach ($accounts as $account) { - $id = (int)$account->id; + $id = (int) $account->id; $this->accounts[$id] = $account; Log::debug(sprintf('Collected account #%d', $id)); } @@ -208,11 +223,11 @@ class RecurringEnrichment implements EnrichmentInterface $bills = Bill::whereIn('id', $ids)->get(); $mapped = []; foreach ($bills as $bill) { - $mapped[(int)$bill->id] = $bill; + $mapped[(int) $bill->id] = $bill; } foreach ($billIds as $info) { - $recurrenceId = $info['recurrence_id']; - $transactionId = $info['transaction_id']; + $recurrenceId = $info['recurrence_id']; + $transactionId = $info['transaction_id']; $this->transactions[$recurrenceId][$transactionId]['subscription_name'] = $mapped[$info['bill_id']]->name ?? ''; } } @@ -226,11 +241,11 @@ class RecurringEnrichment implements EnrichmentInterface $categories = Budget::whereIn('id', $ids)->get(); $mapped = []; foreach ($categories as $category) { - $mapped[(int)$category->id] = $category; + $mapped[(int) $category->id] = $category; } foreach ($budgetIds as $info) { - $recurrenceId = $info['recurrence_id']; - $transactionId = $info['transaction_id']; + $recurrenceId = $info['recurrence_id']; + $transactionId = $info['transaction_id']; $this->transactions[$recurrenceId][$transactionId]['budget_name'] = $mapped[$info['budget_id']]->name ?? ''; } } @@ -244,11 +259,11 @@ class RecurringEnrichment implements EnrichmentInterface $categories = Category::whereIn('id', $ids)->get(); $mapped = []; foreach ($categories as $category) { - $mapped[(int)$category->id] = $category; + $mapped[(int) $category->id] = $category; } foreach ($categoryIds as $info) { - $recurrenceId = $info['recurrence_id']; - $transactionId = $info['transaction_id']; + $recurrenceId = $info['recurrence_id']; + $transactionId = $info['transaction_id']; $this->transactions[$recurrenceId][$transactionId]['category_name'] = $mapped[$info['category_id']]->name ?? ''; } } @@ -268,7 +283,7 @@ class RecurringEnrichment implements EnrichmentInterface $transactionId = $info['transaction_id']; $category = $factory->findOrCreate(null, $info['category_name']); if (null !== $category) { - $this->transactions[$recurrenceId][$transactionId]['category_id'] = (string)$category->id; + $this->transactions[$recurrenceId][$transactionId]['category_id'] = (string) $category->id; $this->transactions[$recurrenceId][$transactionId]['category_name'] = $category->name; } } @@ -279,7 +294,7 @@ class RecurringEnrichment implements EnrichmentInterface $all = array_merge(array_unique($this->currencyIds), array_unique($this->foreignCurrencyIds)); $currencies = TransactionCurrency::whereIn('id', array_unique($all))->get(); foreach ($currencies as $currency) { - $id = (int)$currency->id; + $id = (int) $currency->id; $this->currencies[$id] = $currency; Log::debug(sprintf('Collected currency #%d', $id)); } @@ -289,7 +304,7 @@ class RecurringEnrichment implements EnrichmentInterface { /** @var Recurrence $recurrence */ foreach ($this->collection as $recurrence) { - $id = (int)$recurrence->id; + $id = (int) $recurrence->id; $this->ids[] = $id; Log::debug(sprintf('Collected recurrence id #%d', $id)); } @@ -299,14 +314,16 @@ class RecurringEnrichment implements EnrichmentInterface private function collectNotes(): void { - $notes = Note::query()->whereIn('noteable_id', $this->ids) + $notes = Note::query() + ->whereIn('noteable_id', $this->ids) ->whereNotNull('notes.text') ->where('notes.text', '!=', '') - ->where('noteable_type', Recurrence::class)->get(['notes.id', 'notes.noteable_id', 'notes.text'])->toArray() - ; + ->where('noteable_type', Recurrence::class) + ->get(['notes.id', 'notes.noteable_id', 'notes.text']) + ->toArray(); foreach ($notes as $note) { - $notableId = (int)$note['noteable_id']; - $this->notes[$notableId] = (string)$note['text']; + $notableId = (int) $note['noteable_id']; + $this->notes[$notableId] = (string) $note['text']; Log::debug(sprintf('Collected note #%d for recurrence #%d', $note['id'], $notableId)); } Log::debug(sprintf('Enrich with %d note(s)', count($this->notes))); @@ -321,11 +338,11 @@ class RecurringEnrichment implements EnrichmentInterface $piggyBanks = PiggyBank::whereIn('id', $ids)->get(); $mapped = []; foreach ($piggyBanks as $piggyBank) { - $mapped[(int)$piggyBank->id] = $piggyBank; + $mapped[(int) $piggyBank->id] = $piggyBank; } foreach ($piggyBankIds as $info) { - $recurrenceId = $info['recurrence_id']; - $transactionId = $info['transaction_id']; + $recurrenceId = $info['recurrence_id']; + $transactionId = $info['transaction_id']; $this->transactions[$recurrenceId][$transactionId]['piggy_bank_name'] = $mapped[$info['piggy_bank_id']]->name ?? ''; } } @@ -335,36 +352,36 @@ class RecurringEnrichment implements EnrichmentInterface Log::debug('Start of enrichment: collectRepetitions()'); $repository = app(RecurringRepositoryInterface::class); $repository->setUserGroup($this->userGroup); - $set = RecurrenceRepetition::whereIn('recurrence_id', $this->ids)->get(); + $set = RecurrenceRepetition::whereIn('recurrence_id', $this->ids)->get(); /** @var RecurrenceRepetition $repetition */ foreach ($set as $repetition) { - $recurrence = $this->collection->filter(static fn (Recurrence $item): bool => (int)$item->id === (int)$repetition->recurrence_id)->first(); - $fromDate = clone ($recurrence->latest_date ?? $recurrence->first_date); - $recurrenceId = (int)$repetition->recurrence_id; - $repId = (int)$repetition->id; + $recurrence = $this->collection->filter(static fn(Recurrence $item): bool => (int) $item->id === (int) $repetition->recurrence_id)->first(); + $fromDate = clone ($recurrence->latest_date ?? $recurrence->first_date); + $recurrenceId = (int) $repetition->recurrence_id; + $repId = (int) $repetition->id; $this->repetitions[$recurrenceId] ??= []; Log::debug(sprintf('Collected repetition #%d of recurrence #%d.', $repId, $recurrenceId)); // get the (future) occurrences for this specific type of repetition: - $amount = 'daily' === $repetition->repetition_type ? 9 : 5; - $set = $repository->getXOccurrencesSince($repetition, $fromDate, now(config('app.timezone')), $amount); - $occurrences = []; + $amount = 'daily' === $repetition->repetition_type ? 9 : 5; + $set = $repository->getXOccurrencesSince($repetition, $fromDate, now(config('app.timezone')), $amount); + $occurrences = []; /** @var Carbon $carbon */ foreach ($set as $carbon) { $occurrences[] = $carbon->toAtomString(); } $this->repetitions[$recurrenceId][$repId] = [ - 'id' => (string)$repId, + 'id' => (string) $repId, 'created_at' => $repetition->created_at->toAtomString(), 'updated_at' => $repetition->updated_at->toAtomString(), 'type' => $repetition->repetition_type, - 'moment' => (string)$repetition->repetition_moment, - 'skip' => (int)$repetition->repetition_skip, - 'weekend' => RecurrenceRepetitionWeekend::from((int)$repetition->weekend)->value, + 'moment' => (string) $repetition->repetition_moment, + 'skip' => (int) $repetition->repetition_skip, + 'weekend' => RecurrenceRepetitionWeekend::from((int) $repetition->weekend)->value, 'description' => $this->getRepetitionDescription($repetition), - 'occurrences' => $occurrences, + 'occurrences' => $occurrences ]; } Log::debug('End of enrichment: collectRepetitions()'); @@ -372,11 +389,11 @@ class RecurringEnrichment implements EnrichmentInterface private function collectTransactionMetaData(): void { - $rtIds = []; + $rtIds = []; foreach ($this->ids as $recurrenceId) { $rtIds = array_merge($rtIds, array_keys($this->transactions[$recurrenceId])); } - $meta = RecurrenceTransactionMeta::whereNull('deleted_at')->whereIn('rt_id', $rtIds)->get(); + $meta = RecurrenceTransactionMeta::whereNull('deleted_at')->whereIn('rt_id', $rtIds)->get(); // other meta-data to be collected: $billIds = []; $piggyBankIds = []; @@ -384,13 +401,13 @@ class RecurringEnrichment implements EnrichmentInterface $categoryNames = []; $budgetIds = []; foreach ($meta as $entry) { - $id = (int)$entry->id; - $transactionId = (int)$entry->rt_id; + $id = (int) $entry->id; + $transactionId = (int) $entry->rt_id; // this should refer to another array, were rtIds can be used to find the recurrence. - $recurrenceId = $this->recurrenceByTransaction[$transactionId] ?? 0; + $recurrenceId = $this->recurrenceByTransaction[$transactionId] ?? 0; Log::debug(sprintf('Collecting meta data entry #%d for recurrence transaction #%d, for recurrence #%d ', $id, $transactionId, $recurrenceId)); - $name = (string)($entry->name ?? ''); + $name = (string) ($entry->name ?? ''); if (0 === $recurrenceId) { Log::error(sprintf('Could not find recurrence ID for recurrence transaction ID #%d', $transactionId)); @@ -402,32 +419,28 @@ class RecurringEnrichment implements EnrichmentInterface throw new FireflyException(sprintf('Recurrence transformer cant handle field "%s"', $name)); case 'bill_id': - if ((int)$entry->value > 0) { + if ((int) $entry->value > 0) { $this->transactions[$recurrenceId][$transactionId]['subscription_id'] = $entry->value; if (!array_key_exists($id, $billIds)) { - $billIds[$id] = [ - 'recurrence_id' => $recurrenceId, - 'transaction_id' => $transactionId, - 'bill_id' => (int)$entry->value, - ]; + $billIds[$id] = ['recurrence_id' => $recurrenceId, 'transaction_id' => $transactionId, 'bill_id' => (int) $entry->value]; } } break; case 'tags': - $this->transactions[$recurrenceId][$transactionId]['tags'] = json_decode((string)$entry->value); + $this->transactions[$recurrenceId][$transactionId]['tags'] = json_decode((string) $entry->value); break; case 'piggy_bank_id': - if ((int)$entry->value > 0) { - $this->transactions[$recurrenceId][$transactionId]['piggy_bank_id'] = (string)$entry->value; + if ((int) $entry->value > 0) { + $this->transactions[$recurrenceId][$transactionId]['piggy_bank_id'] = (string) $entry->value; if (!array_key_exists($id, $piggyBankIds)) { $piggyBankIds[$id] = [ 'recurrence_id' => $recurrenceId, 'transaction_id' => $transactionId, - 'piggy_bank_id' => (int)$entry->value, + 'piggy_bank_id' => (int) $entry->value ]; } } @@ -435,13 +448,13 @@ class RecurringEnrichment implements EnrichmentInterface break; case 'category_id': - if ((int)$entry->value > 0) { - $this->transactions[$recurrenceId][$transactionId]['category_id'] = (string)$entry->value; + if ((int) $entry->value > 0) { + $this->transactions[$recurrenceId][$transactionId]['category_id'] = (string) $entry->value; if (!array_key_exists($id, $categoryIds)) { $categoryIds[$id] = [ 'recurrence_id' => $recurrenceId, 'transaction_id' => $transactionId, - 'category_id' => (int)$entry->value, + 'category_id' => (int) $entry->value ]; } } @@ -449,28 +462,20 @@ class RecurringEnrichment implements EnrichmentInterface break; case 'category_name': - if ('' !== (string)$entry->value) { - $this->transactions[$recurrenceId][$transactionId]['category_name'] = (string)$entry->value; + if ('' !== (string) $entry->value) { + $this->transactions[$recurrenceId][$transactionId]['category_name'] = (string) $entry->value; if (!array_key_exists($id, $categoryIds)) { - $categoryNames[$id] = [ - 'recurrence_id' => $recurrenceId, - 'transaction_id' => $transactionId, - 'category_name' => $entry->value, - ]; + $categoryNames[$id] = ['recurrence_id' => $recurrenceId, 'transaction_id' => $transactionId, 'category_name' => $entry->value]; } } break; case 'budget_id': - if ((int)$entry->value > 0) { - $this->transactions[$recurrenceId][$transactionId]['budget_id'] = (string)$entry->value; + if ((int) $entry->value > 0) { + $this->transactions[$recurrenceId][$transactionId]['budget_id'] = (string) $entry->value; if (!array_key_exists($id, $budgetIds)) { - $budgetIds[$id] = [ - 'recurrence_id' => $recurrenceId, - 'transaction_id' => $transactionId, - 'budget_id' => (int)$entry->value, - ]; + $budgetIds[$id] = ['recurrence_id' => $recurrenceId, 'transaction_id' => $transactionId, 'budget_id' => (int) $entry->value]; } } @@ -490,21 +495,21 @@ class RecurringEnrichment implements EnrichmentInterface /** @var RecurrenceTransaction $transaction */ foreach ($set as $transaction) { - $recurrenceId = (int)$transaction->recurrence_id; - $transactionId = (int)$transaction->id; - $this->recurrenceByTransaction[$transactionId] = $recurrenceId; + $recurrenceId = (int) $transaction->recurrence_id; + $transactionId = (int) $transaction->id; + $this->recurrenceByTransaction[$transactionId] = $recurrenceId; $this->transactions[$recurrenceId] ??= []; - $amount = $transaction->amount; - $foreignAmount = $transaction->foreign_amount; + $amount = $transaction->amount; + $foreignAmount = $transaction->foreign_amount; Log::debug(sprintf('Collected transaction #%d of recurrence #%d', $transactionId, $recurrenceId)); $this->transactions[$recurrenceId][$transactionId] = [ - 'id' => (string)$transactionId, - 'transaction_currency_id' => (int)$transaction->transaction_currency_id, - 'foreign_currency_id' => null === $transaction->foreign_currency_id ? null : (int)$transaction->foreign_currency_id, - 'source_id' => (int)$transaction->source_id, + 'id' => (string) $transactionId, + 'transaction_currency_id' => (int) $transaction->transaction_currency_id, + 'foreign_currency_id' => null === $transaction->foreign_currency_id ? null : (int) $transaction->foreign_currency_id, + 'source_id' => (int) $transaction->source_id, 'object_has_currency_setting' => true, - 'destination_id' => (int)$transaction->destination_id, + 'destination_id' => (int) $transaction->destination_id, 'amount' => $amount, 'foreign_amount' => $foreignAmount, 'pc_amount' => null, @@ -518,15 +523,14 @@ class RecurringEnrichment implements EnrichmentInterface 'piggy_bank_id' => null, 'piggy_bank_name' => null, 'subscription_id' => null, - 'subscription_name' => null, - + 'subscription_name' => null ]; // collect all kinds of meta-data to be collected later. - $this->currencyIds[$transactionId] = (int)$transaction->transaction_currency_id; - $this->sourceAccountIds[$transactionId] = (int)$transaction->source_id; - $this->destinationAccountIds[$transactionId] = (int)$transaction->destination_id; + $this->currencyIds[$transactionId] = (int) $transaction->transaction_currency_id; + $this->sourceAccountIds[$transactionId] = (int) $transaction->source_id; + $this->destinationAccountIds[$transactionId] = (int) $transaction->destination_id; if (null !== $transaction->foreign_currency_id) { - $this->foreignCurrencyIds[$transactionId] = (int)$transaction->foreign_currency_id; + $this->foreignCurrencyIds[$transactionId] = (int) $transaction->foreign_currency_id; } } } @@ -534,12 +538,12 @@ class RecurringEnrichment implements EnrichmentInterface private function getLanguage(): void { /** @var Preference $preference */ - $preference = Preferences::getForUser($this->user, 'language', config('firefly.default_language', 'en_US')); - $language = $preference->data; + $preference = Preferences::getForUser($this->user, 'language', config('firefly.default_language', 'en_US')); + $language = $preference->data; if (is_array($language)) { $language = 'en_US'; } - $language = (string)$language; + $language = (string) $language; $this->language = $language; } @@ -548,66 +552,71 @@ class RecurringEnrichment implements EnrichmentInterface $return = []; $converter = new ExchangeRateConverter(); foreach ($transactions as $transaction) { - $currencyId = $transaction['transaction_currency_id']; - $pcAmount = null; - $pcForeignAmount = null; + $currencyId = $transaction['transaction_currency_id']; + $pcAmount = null; + $pcForeignAmount = null; // set the same amount in the primary currency, if both are the same anyway. - if ($this->convertToPrimary && $currencyId === (int)$this->primaryCurrency->id) { + if ($this->convertToPrimary && $currencyId === (int) $this->primaryCurrency->id) { $pcAmount = $transaction['amount']; } // convert the amount to the primary currency, if it is not the same. - if ($this->convertToPrimary && $currencyId !== (int)$this->primaryCurrency->id) { + if ($this->convertToPrimary && $currencyId !== (int) $this->primaryCurrency->id) { $pcAmount = $converter->convert($this->currencies[$currencyId], $this->primaryCurrency, today(), $transaction['amount']); } if (null !== $transaction['foreign_amount'] && null !== $transaction['foreign_currency_id']) { $foreignCurrencyId = $transaction['foreign_currency_id']; if ($foreignCurrencyId !== $this->primaryCurrency->id) { - $pcForeignAmount = $converter->convert($this->currencies[$foreignCurrencyId], $this->primaryCurrency, today(), $transaction['foreign_amount']); + $pcForeignAmount = $converter->convert( + $this->currencies[$foreignCurrencyId], + $this->primaryCurrency, + today(), + $transaction['foreign_amount'] + ); } } - $transaction['pc_amount'] = $pcAmount; - $transaction['pc_foreign_amount'] = $pcForeignAmount; + $transaction['pc_amount'] = $pcAmount; + $transaction['pc_foreign_amount'] = $pcForeignAmount; - $sourceId = $transaction['source_id']; - $transaction['source_name'] = $this->accounts[$sourceId]->name; - $transaction['source_iban'] = $this->accounts[$sourceId]->iban; - $transaction['source_type'] = $this->accounts[$sourceId]->accountType->type; - $transaction['source_id'] = (string)$transaction['source_id']; + $sourceId = $transaction['source_id']; + $transaction['source_name'] = $this->accounts[$sourceId]->name; + $transaction['source_iban'] = $this->accounts[$sourceId]->iban; + $transaction['source_type'] = $this->accounts[$sourceId]->accountType->type; + $transaction['source_id'] = (string) $transaction['source_id']; - $destId = $transaction['destination_id']; - $transaction['destination_name'] = $this->accounts[$destId]->name; - $transaction['destination_iban'] = $this->accounts[$destId]->iban; - $transaction['destination_type'] = $this->accounts[$destId]->accountType->type; - $transaction['destination_id'] = (string)$transaction['destination_id']; + $destId = $transaction['destination_id']; + $transaction['destination_name'] = $this->accounts[$destId]->name; + $transaction['destination_iban'] = $this->accounts[$destId]->iban; + $transaction['destination_type'] = $this->accounts[$destId]->accountType->type; + $transaction['destination_id'] = (string) $transaction['destination_id']; - $transaction['currency_id'] = (string)$currencyId; - $transaction['currency_name'] = $this->currencies[$currencyId]->name; - $transaction['currency_code'] = $this->currencies[$currencyId]->code; - $transaction['currency_symbol'] = $this->currencies[$currencyId]->symbol; - $transaction['currency_decimal_places'] = $this->currencies[$currencyId]->decimal_places; + $transaction['currency_id'] = (string) $currencyId; + $transaction['currency_name'] = $this->currencies[$currencyId]->name; + $transaction['currency_code'] = $this->currencies[$currencyId]->code; + $transaction['currency_symbol'] = $this->currencies[$currencyId]->symbol; + $transaction['currency_decimal_places'] = $this->currencies[$currencyId]->decimal_places; - $transaction['primary_currency_id'] = (string)$this->primaryCurrency->id; - $transaction['primary_currency_name'] = $this->primaryCurrency->name; - $transaction['primary_currency_code'] = $this->primaryCurrency->code; - $transaction['primary_currency_symbol'] = $this->primaryCurrency->symbol; + $transaction['primary_currency_id'] = (string) $this->primaryCurrency->id; + $transaction['primary_currency_name'] = $this->primaryCurrency->name; + $transaction['primary_currency_code'] = $this->primaryCurrency->code; + $transaction['primary_currency_symbol'] = $this->primaryCurrency->symbol; $transaction['primary_currency_decimal_places'] = $this->primaryCurrency->decimal_places; // $transaction['foreign_currency_id'] = null; - $transaction['foreign_currency_name'] = null; - $transaction['foreign_currency_code'] = null; - $transaction['foreign_currency_symbol'] = null; + $transaction['foreign_currency_name'] = null; + $transaction['foreign_currency_code'] = null; + $transaction['foreign_currency_symbol'] = null; $transaction['foreign_currency_decimal_places'] = null; if (null !== $transaction['foreign_currency_id']) { - $currencyId = $transaction['foreign_currency_id']; - $transaction['foreign_currency_id'] = (string)$currencyId; - $transaction['foreign_currency_name'] = $this->currencies[$currencyId]->name; - $transaction['foreign_currency_code'] = $this->currencies[$currencyId]->code; - $transaction['foreign_currency_symbol'] = $this->currencies[$currencyId]->symbol; + $currencyId = $transaction['foreign_currency_id']; + $transaction['foreign_currency_id'] = (string) $currencyId; + $transaction['foreign_currency_name'] = $this->currencies[$currencyId]->name; + $transaction['foreign_currency_code'] = $this->currencies[$currencyId]->code; + $transaction['foreign_currency_symbol'] = $this->currencies[$currencyId]->symbol; $transaction['foreign_currency_decimal_places'] = $this->currencies[$currencyId]->decimal_places; } unset($transaction['transaction_currency_id']); - $return[] = $transaction; + $return[] = $transaction; } return $return; diff --git a/app/Support/JsonApi/Enrichments/SubscriptionEnrichment.php b/app/Support/JsonApi/Enrichments/SubscriptionEnrichment.php index 76780dec0b..0651e10551 100644 --- a/app/Support/JsonApi/Enrichments/SubscriptionEnrichment.php +++ b/app/Support/JsonApi/Enrichments/SubscriptionEnrichment.php @@ -1,6 +1,5 @@ convertToPrimary = Amount::convertToPrimary(); - $this->primaryCurrency = Amount::getPrimaryCurrency(); + $this->primaryCurrency = Amount::getPrimaryCurrency(); } public function enrich(Collection $collection): Collection @@ -77,18 +76,17 @@ class SubscriptionEnrichment implements EnrichmentInterface $this->collectPaidDates(); $this->collectPayDates(); - // TODO clean me up. - $notes = $this->notes; - $paidDates = $this->paidDates; - $payDates = $this->payDates; + $notes = $this->notes; + $paidDates = $this->paidDates; + $payDates = $this->payDates; $this->collection = $this->collection->map(function (Bill $item) use ($notes, $paidDates, $payDates): Bill { - $id = (int)$item->id; - $currency = $item->transactionCurrency; - $nem = $this->getNextExpectedMatch($payDates[$id] ?? []); + $id = (int) $item->id; + $currency = $item->transactionCurrency; + $nem = $this->getNextExpectedMatch($payDates[$id] ?? []); - $meta = [ + $meta = [ 'notes' => null, 'object_group_id' => null, 'object_group_title' => null, @@ -97,32 +95,35 @@ class SubscriptionEnrichment implements EnrichmentInterface 'paid_dates' => $this->filterPaidDates($paidDates[$id] ?? []), 'pay_dates' => $payDates[$id] ?? [], 'nem' => $nem, - 'nem_diff' => $this->getNextExpectedMatchDiff($nem, $payDates[$id] ?? []), + 'nem_diff' => $this->getNextExpectedMatchDiff($nem, $payDates[$id] ?? []) ]; - $amounts = [ + $amounts = [ 'amount_min' => Steam::bcround($item->amount_min, $currency->decimal_places), 'amount_max' => Steam::bcround($item->amount_max, $currency->decimal_places), 'average' => Steam::bcround(bcdiv(bcadd($item->amount_min, $item->amount_max), '2'), $currency->decimal_places), 'pc_amount_min' => null, 'pc_amount_max' => null, - 'pc_average' => null, + 'pc_average' => null ]; if ($this->convertToPrimary && $currency->id === $this->primaryCurrency->id) { $amounts['pc_amount_min'] = $amounts['amount_min']; $amounts['pc_amount_max'] = $amounts['amount_max']; - $amounts['pc_average'] = $amounts['average']; + $amounts['pc_average'] = $amounts['average']; } if ($this->convertToPrimary && $currency->id !== $this->primaryCurrency->id) { $amounts['pc_amount_min'] = Steam::bcround($item->native_amount_min, $this->primaryCurrency->decimal_places); $amounts['pc_amount_max'] = Steam::bcround($item->native_amount_max, $this->primaryCurrency->decimal_places); - $amounts['pc_average'] = Steam::bcround(bcdiv(bcadd($item->native_amount_min, $item->native_amount_max), '2'), $this->primaryCurrency->decimal_places); + $amounts['pc_average'] = Steam::bcround( + bcdiv(bcadd($item->native_amount_min, $item->native_amount_max), '2'), + $this->primaryCurrency->decimal_places + ); } // add object group if available if (array_key_exists($id, $this->mappedObjects)) { $key = $this->mappedObjects[$id]; if (array_key_exists($key, $this->objectGroups)) { - $meta['object_group_id'] = (string)$this->objectGroups[$key]['id']; + $meta['object_group_id'] = (string) $this->objectGroups[$key]['id']; $meta['object_group_title'] = $this->objectGroups[$key]['title']; $meta['object_group_order'] = $this->objectGroups[$key]['order']; } @@ -134,7 +135,7 @@ class SubscriptionEnrichment implements EnrichmentInterface } $item->amounts = $amounts; - $item->meta = $meta; + $item->meta = $meta; return $item; }); @@ -151,12 +152,12 @@ class SubscriptionEnrichment implements EnrichmentInterface return $collection->first(); } - public function setEnd(?Carbon $end): void + public function setEnd(null|Carbon $end): void { $this->end = $end; } - public function setStart(?Carbon $start): void + public function setStart(null|Carbon $start): void { $this->start = $start; } @@ -166,20 +167,22 @@ class SubscriptionEnrichment implements EnrichmentInterface $this->user = $user; } - public function setUserGroup(UserGroup $userGroup): void {} + public function setUserGroup(UserGroup $userGroup): void + { + } /** * Returns the latest date in the set, or start when set is empty. */ protected function lastPaidDate(Bill $subscription, Collection $dates, Carbon $default): Carbon { - $filtered = $dates->filter(static fn (TransactionJournal $journal): bool => (int)$journal->bill_id === (int)$subscription->id); + $filtered = $dates->filter(static fn(TransactionJournal $journal): bool => (int) $journal->bill_id === (int) $subscription->id); Log::debug(sprintf('Filtered down from %d to %d entries for bill #%d.', $dates->count(), $filtered->count(), $subscription->id)); if (0 === $filtered->count()) { return $default; } - $latest = $filtered->first()->date; + $latest = $filtered->first()->date; /** @var TransactionJournal $journal */ foreach ($filtered as $journal) { @@ -193,36 +196,37 @@ class SubscriptionEnrichment implements EnrichmentInterface private function collectNotes(): void { - $notes = Note::query()->whereIn('noteable_id', $this->subscriptionIds) + $notes = Note::query() + ->whereIn('noteable_id', $this->subscriptionIds) ->whereNotNull('notes.text') ->where('notes.text', '!=', '') - ->where('noteable_type', Bill::class)->get(['notes.noteable_id', 'notes.text'])->toArray() - ; + ->where('noteable_type', Bill::class) + ->get(['notes.noteable_id', 'notes.text']) + ->toArray(); foreach ($notes as $note) { - $this->notes[(int)$note['noteable_id']] = (string)$note['text']; + $this->notes[(int) $note['noteable_id']] = (string) $note['text']; } Log::debug(sprintf('Enrich with %d note(s)', count($this->notes))); } private function collectObjectGroups(): void { - $set = DB::table('object_groupables') + $set = DB::table('object_groupables') ->whereIn('object_groupable_id', $this->subscriptionIds) ->where('object_groupable_type', Bill::class) - ->get(['object_groupable_id', 'object_group_id']) - ; + ->get(['object_groupable_id', 'object_group_id']); - $ids = array_unique($set->pluck('object_group_id')->toArray()); + $ids = array_unique($set->pluck('object_group_id')->toArray()); foreach ($set as $entry) { - $this->mappedObjects[(int)$entry->object_groupable_id] = (int)$entry->object_group_id; + $this->mappedObjects[(int) $entry->object_groupable_id] = (int) $entry->object_group_id; } $groups = ObjectGroup::whereIn('id', $ids)->get(['id', 'title', 'order'])->toArray(); foreach ($groups as $group) { - $group['id'] = (int)$group['id']; - $group['order'] = (int)$group['order']; - $this->objectGroups[(int)$group['id']] = $group; + $group['id'] = (int) $group['id']; + $group['order'] = (int) $group['order']; + $this->objectGroups[(int) $group['id']] = $group; } } @@ -240,13 +244,13 @@ class SubscriptionEnrichment implements EnrichmentInterface // 2023-07-18 this particular date is used to search for the last paid date. // 2023-07-18 the cloned $searchDate is used to grab the correct transactions. /** @var Carbon $start */ - $start = clone $this->start; - $searchStart = clone $start; + $start = clone $this->start; + $searchStart = clone $start; $start->subDay(); /** @var Carbon $end */ - $end = clone $this->end; - $searchEnd = clone $end; + $end = clone $this->end; + $searchEnd = clone $end; // move the search dates to the start of the day. $searchStart->startOfDay(); @@ -255,98 +259,96 @@ class SubscriptionEnrichment implements EnrichmentInterface Log::debug(sprintf('Search parameters are: start: %s, end: %s', $searchStart->format('Y-m-d H:i:s'), $searchEnd->format('Y-m-d H:i:s'))); // Get from database when bills were paid. - $set = $this->user->transactionJournals() + $set = $this->user + ->transactionJournals() ->whereIn('bill_id', $this->subscriptionIds) ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->leftJoin('transaction_currencies AS currency', 'currency.id', '=', 'transactions.transaction_currency_id') ->leftJoin('transaction_currencies AS foreign_currency', 'foreign_currency.id', '=', 'transactions.foreign_currency_id') ->where('transactions.amount', '>', 0) - ->before($searchEnd)->after($searchStart)->get( - [ - 'transaction_journals.id', - 'transaction_journals.date', - 'transaction_journals.bill_id', - 'transaction_journals.transaction_group_id', - 'transactions.transaction_currency_id', - 'currency.code AS transaction_currency_code', - 'currency.symbol AS transaction_currency_symbol', - 'currency.decimal_places AS transaction_currency_decimal_places', - 'transactions.foreign_currency_id', - 'foreign_currency.code AS foreign_currency_code', - 'foreign_currency.symbol AS foreign_currency_symbol', - 'foreign_currency.decimal_places AS foreign_currency_decimal_places', - 'transactions.amount', - 'transactions.foreign_amount', - ] - ) - ; + ->before($searchEnd) + ->after($searchStart) + ->get([ + 'transaction_journals.id', + 'transaction_journals.date', + 'transaction_journals.bill_id', + 'transaction_journals.transaction_group_id', + 'transactions.transaction_currency_id', + 'currency.code AS transaction_currency_code', + 'currency.symbol AS transaction_currency_symbol', + 'currency.decimal_places AS transaction_currency_decimal_places', + 'transactions.foreign_currency_id', + 'foreign_currency.code AS foreign_currency_code', + 'foreign_currency.symbol AS foreign_currency_symbol', + 'foreign_currency.decimal_places AS foreign_currency_decimal_places', + 'transactions.amount', + 'transactions.foreign_amount' + ]); Log::debug(sprintf('Count %d entries in set', $set->count())); // for each bill, do a loop. - $converter = new ExchangeRateConverter(); + $converter = new ExchangeRateConverter(); /** @var Bill $subscription */ foreach ($this->collection as $subscription) { // Grab from array the most recent payment. If none exist, fall back to the start date and pretend *that* was the last paid date. Log::debug(sprintf('Grab last paid date from function, return %s if it comes up with nothing.', $start->format('Y-m-d'))); - $lastPaidDate = $this->lastPaidDate($subscription, $set, $start); + $lastPaidDate = $this->lastPaidDate($subscription, $set, $start); Log::debug(sprintf('Result of lastPaidDate is %s', $lastPaidDate->format('Y-m-d'))); // At this point the "next match" is exactly after the last time the bill was paid. - $result = []; - $filtered = $set->filter(static fn (TransactionJournal $journal): bool => (int)$journal->bill_id === (int)$subscription->id); + $result = []; + $filtered = $set->filter(static fn(TransactionJournal $journal): bool => (int) $journal->bill_id === (int) $subscription->id); foreach ($filtered as $entry) { - $array = [ - 'transaction_group_id' => (string)$entry->transaction_group_id, - 'transaction_journal_id' => (string)$entry->id, + $array = [ + 'transaction_group_id' => (string) $entry->transaction_group_id, + 'transaction_journal_id' => (string) $entry->id, 'date' => $entry->date->toAtomString(), 'date_object' => $entry->date, - 'subscription_id' => (string)$entry->bill_id, - 'currency_id' => (string)$entry->transaction_currency_id, + 'subscription_id' => (string) $entry->bill_id, + 'currency_id' => (string) $entry->transaction_currency_id, 'currency_code' => $entry->transaction_currency_code, 'currency_symbol' => $entry->transaction_currency_symbol, 'currency_decimal_places' => $entry->transaction_currency_decimal_places, - 'primary_currency_id' => (string)$this->primaryCurrency->id, + 'primary_currency_id' => (string) $this->primaryCurrency->id, 'primary_currency_code' => $this->primaryCurrency->code, 'primary_currency_symbol' => $this->primaryCurrency->symbol, 'primary_currency_decimal_places' => $this->primaryCurrency->decimal_places, 'amount' => Steam::bcround($entry->amount, $entry->transaction_currency_decimal_places), 'pc_amount' => null, 'foreign_amount' => null, - 'pc_foreign_amount' => null, - + 'pc_foreign_amount' => null ]; if (null !== $entry->foreign_amount && null !== $entry->foreign_currency_code) { - $array['foreign_currency_id'] = (string)$entry->foreign_currency_id; - $array['foreign_currency_code'] = $entry->foreign_currency_code; - $array['foreign_currency_symbol'] = $entry->foreign_currency_symbol; + $array['foreign_currency_id'] = (string) $entry->foreign_currency_id; + $array['foreign_currency_code'] = $entry->foreign_currency_code; + $array['foreign_currency_symbol'] = $entry->foreign_currency_symbol; $array['foreign_currency_decimal_places'] = $entry->foreign_currency_decimal_places; - $array['foreign_amount'] = Steam::bcround((string) $entry->foreign_amount, $entry->foreign_currency_decimal_places); + $array['foreign_amount'] = Steam::bcround((string) $entry->foreign_amount, $entry->foreign_currency_decimal_places); } // convert to primary, but is already primary. - if ($this->convertToPrimary && (int)$entry->transaction_currency_id === $this->primaryCurrency->id) { + if ($this->convertToPrimary && (int) $entry->transaction_currency_id === $this->primaryCurrency->id) { $array['pc_amount'] = $array['amount']; } // convert to primary, but is NOT already primary. - if ($this->convertToPrimary && (int)$entry->transaction_currency_id !== $this->primaryCurrency->id) { + if ($this->convertToPrimary && (int) $entry->transaction_currency_id !== $this->primaryCurrency->id) { $array['pc_amount'] = $converter->convert($entry->transactionCurrency, $this->primaryCurrency, $entry->date, (string) $entry->amount); } // convert to primary, but foreign is already primary. - if ($this->convertToPrimary && (int)$entry->foreign_currency_id === $this->primaryCurrency->id) { + if ($this->convertToPrimary && (int) $entry->foreign_currency_id === $this->primaryCurrency->id) { $array['pc_foreign_amount'] = $array['foreign_amount']; } // convert to primary, but foreign is NOT already primary. - if ($this->convertToPrimary && null !== $entry->foreign_currency_id && (int)$entry->foreign_currency_id !== $this->primaryCurrency->id) { + if ($this->convertToPrimary && null !== $entry->foreign_currency_id && (int) $entry->foreign_currency_id !== $this->primaryCurrency->id) { // TODO this is very database intensive. /** @var TransactionCurrency $foreignCurrency */ - $foreignCurrency = Amount::getTransactionCurrencyById($entry->foreign_currency_id); + $foreignCurrency = Amount::getTransactionCurrencyById($entry->foreign_currency_id); $array['pc_foreign_amount'] = $converter->convert($foreignCurrency, $this->primaryCurrency, $entry->date, (string) $entry->amount); } $result[] = $array; } - $this->paidDates[(int)$subscription->id] = $result; + $this->paidDates[(int) $subscription->id] = $result; } - } private function collectPayDates(): void @@ -359,12 +361,19 @@ class SubscriptionEnrichment implements EnrichmentInterface /** @var Bill $subscription */ foreach ($this->collection as $subscription) { - $id = (int)$subscription->id; - $lastPaidDate = $this->getLastPaidDate($this->paidDates[$id] ?? []); - $payDates = $this->calculator->getPayDates($this->start, $this->end, $subscription->date, $subscription->repeat_freq, $subscription->skip, $lastPaidDate); - $payDatesFormatted = []; + $id = (int) $subscription->id; + $lastPaidDate = $this->getLastPaidDate($this->paidDates[$id] ?? []); + $payDates = $this->calculator->getPayDates( + $this->start, + $this->end, + $subscription->date, + $subscription->repeat_freq, + $subscription->skip, + $lastPaidDate + ); + $payDatesFormatted = []; foreach ($payDates as $string) { - $date = Carbon::createFromFormat('!Y-m-d', $string, config('app.timezone')); + $date = Carbon::createFromFormat('!Y-m-d', $string, config('app.timezone')); if (!$date instanceof Carbon) { $date = today(config('app.timezone')); } @@ -378,7 +387,7 @@ class SubscriptionEnrichment implements EnrichmentInterface { /** @var Bill $bill */ foreach ($this->collection as $bill) { - $this->subscriptionIds[] = (int)$bill->id; + $this->subscriptionIds[] = (int) $bill->id; } $this->subscriptionIds = array_unique($this->subscriptionIds); } @@ -392,7 +401,7 @@ class SubscriptionEnrichment implements EnrichmentInterface }, $entries); } - private function getLastPaidDate(array $paidData): ?Carbon + private function getLastPaidDate(array $paidData): null|Carbon { // Log::debug('getLastPaidDate()'); $return = null; @@ -416,7 +425,7 @@ class SubscriptionEnrichment implements EnrichmentInterface return $return; } - private function getNextExpectedMatch(array $payDates): ?Carbon + private function getNextExpectedMatch(array $payDates): null|Carbon { // next expected match $nem = null; @@ -431,10 +440,7 @@ class SubscriptionEnrichment implements EnrichmentInterface $nem = $nemDate; // nullify again when it's outside the current view range. - if ( - ($this->start instanceof Carbon && $nemDate->lt($this->start)) - || ($this->end instanceof Carbon && $nemDate->gt($this->end)) - ) { + if ($this->start instanceof Carbon && $nemDate->lt($this->start) || $this->end instanceof Carbon && $nemDate->gt($this->end)) { $nem = null; $nemDate = null; $firstPayDate = null; @@ -444,7 +450,7 @@ class SubscriptionEnrichment implements EnrichmentInterface return $nem; } - private function getNextExpectedMatchDiff(?Carbon $nem, array $payDates): string + private function getNextExpectedMatchDiff(null|Carbon $nem, array $payDates): string { if (!$nem instanceof Carbon) { return trans('firefly.not_expected_period'); @@ -462,7 +468,10 @@ class SubscriptionEnrichment implements EnrichmentInterface } catch (InvalidFormatException) { $temp2 = today(config('app.timezone')); } - $nemDiff = trans('firefly.bill_expected_date', ['date' => $temp2->diffForHumans(today(config('app.timezone')), CarbonInterface::DIFF_RELATIVE_TO_NOW)]); + $nemDiff = trans('firefly.bill_expected_date', ['date' => $temp2->diffForHumans( + today(config('app.timezone')), + CarbonInterface::DIFF_RELATIVE_TO_NOW + )]); } unset($temp2); diff --git a/app/Support/JsonApi/Enrichments/TransactionGroupEnrichment.php b/app/Support/JsonApi/Enrichments/TransactionGroupEnrichment.php index 78f87d5f7b..9f54fd6dfc 100644 --- a/app/Support/JsonApi/Enrichments/TransactionGroupEnrichment.php +++ b/app/Support/JsonApi/Enrichments/TransactionGroupEnrichment.php @@ -45,19 +45,19 @@ use Override; class TransactionGroupEnrichment implements EnrichmentInterface { - private array $attachmentCount = []; - private Collection $collection; - private readonly array $dateFields; - private array $journalIds = []; - private array $locations = []; - private array $metaData = []; - private array $notes = []; + private array $attachmentCount = []; + private Collection $collection; + private readonly array $dateFields; + private array $journalIds = []; + private array $locations = []; + private array $metaData = []; + private array $notes = []; private readonly TransactionCurrency $primaryCurrency; - private array $tags = []; // @phpstan-ignore-line + private array $tags = []; // @phpstan-ignore-line public function __construct() { - $this->dateFields = ['interest_date', 'book_date', 'process_date', 'due_date', 'payment_date', 'invoice_date']; + $this->dateFields = ['interest_date', 'book_date', 'process_date', 'due_date', 'payment_date', 'invoice_date']; $this->primaryCurrency = Amount::getPrimaryCurrency(); } @@ -94,51 +94,58 @@ class TransactionGroupEnrichment implements EnrichmentInterface throw new FireflyException('Cannot enrich single model.'); } - public function setUser(User $user): void {} + public function setUser(User $user): void + { + } - public function setUserGroup(UserGroup $userGroup): void {} + public function setUserGroup(UserGroup $userGroup): void + { + } private function appendCollectedData(): void { - $notes = $this->notes; - $tags = $this->tags; - $metaData = $this->metaData; - $locations = $this->locations; - $attachmentCount = $this->attachmentCount; - $primaryCurrency = $this->primaryCurrency; + $notes = $this->notes; + $tags = $this->tags; + $metaData = $this->metaData; + $locations = $this->locations; + $attachmentCount = $this->attachmentCount; + $primaryCurrency = $this->primaryCurrency; - $this->collection = $this->collection->map(function (array $item) use ($primaryCurrency, $notes, $tags, $metaData, $locations, $attachmentCount): array { + $this->collection = $this->collection->map(function (array $item) use ( + $primaryCurrency, + $notes, + $tags, + $metaData, + $locations, + $attachmentCount + ): array { foreach ($item['transactions'] as $index => $transaction) { - $journalId = (int)$transaction['transaction_journal_id']; + $journalId = (int) $transaction['transaction_journal_id']; // attach notes if they exist: - $item['transactions'][$index]['notes'] = $notes[$journalId] ?? null; + $item['transactions'][$index]['notes'] = $notes[$journalId] ?? null; // attach tags if they exist: - $item['transactions'][$index]['tags'] = array_key_exists($journalId, $tags) ? $tags[$journalId] : []; + $item['transactions'][$index]['tags'] = array_key_exists($journalId, $tags) ? $tags[$journalId] : []; // attachment count $item['transactions'][$index]['attachment_count'] = array_key_exists($journalId, $attachmentCount) ? $attachmentCount[$journalId] : 0; // default location data - $item['transactions'][$index]['location'] = [ - 'latitude' => null, - 'longitude' => null, - 'zoom_level' => null, - ]; + $item['transactions'][$index]['location'] = ['latitude' => null, 'longitude' => null, 'zoom_level' => null]; // primary currency $item['transactions'][$index]['primary_currency'] = [ - 'id' => (string)$primaryCurrency->id, + 'id' => (string) $primaryCurrency->id, 'code' => $primaryCurrency->code, 'name' => $primaryCurrency->name, 'symbol' => $primaryCurrency->symbol, - 'decimal_places' => $primaryCurrency->decimal_places, + 'decimal_places' => $primaryCurrency->decimal_places ]; // append meta data - $item['transactions'][$index]['meta'] = []; - $item['transactions'][$index]['meta_date'] = []; + $item['transactions'][$index]['meta'] = []; + $item['transactions'][$index]['meta_date'] = []; if (array_key_exists($journalId, $metaData)) { // loop al meta data: foreach ($metaData[$journalId] as $name => $value) { @@ -170,10 +177,9 @@ class TransactionGroupEnrichment implements EnrichmentInterface ->where('attachable_type', TransactionJournal::class) ->groupBy('attachable_id') ->get(['attachable_id', DB::raw('COUNT(id) as nr_of_attachments')]) - ->toArray() - ; + ->toArray(); foreach ($attachments as $row) { - $this->attachmentCount[(int)$row['attachable_id']] = (int)$row['nr_of_attachments']; + $this->attachmentCount[(int) $row['attachable_id']] = (int) $row['nr_of_attachments']; } } @@ -190,16 +196,17 @@ class TransactionGroupEnrichment implements EnrichmentInterface private function collectLocations(): void { - $locations = Location::query()->whereIn('locatable_id', $this->journalIds) - ->where('locatable_type', TransactionJournal::class)->get(['locations.locatable_id', 'locations.latitude', 'locations.longitude', 'locations.zoom_level'])->toArray() - ; + $locations = Location::query() + ->whereIn('locatable_id', $this->journalIds) + ->where('locatable_type', TransactionJournal::class) + ->get(['locations.locatable_id', 'locations.latitude', 'locations.longitude', 'locations.zoom_level']) + ->toArray(); foreach ($locations as $location) { - $this->locations[(int)$location['locatable_id']] - = [ - 'latitude' => (float)$location['latitude'], - 'longitude' => (float)$location['longitude'], - 'zoom_level' => (int)$location['zoom_level'], - ]; + $this->locations[(int) $location['locatable_id']] = [ + 'latitude' => (float) $location['latitude'], + 'longitude' => (float) $location['longitude'], + 'zoom_level' => (int) $location['zoom_level'] + ]; } Log::debug(sprintf('Enrich with %d locations(s)', count($this->locations))); } @@ -208,8 +215,8 @@ class TransactionGroupEnrichment implements EnrichmentInterface { $set = TransactionJournalMeta::whereIn('transaction_journal_id', $this->journalIds)->get(['transaction_journal_id', 'name', 'data'])->toArray(); foreach ($set as $entry) { - $name = $entry['name']; - $data = (string)$entry['data']; + $name = $entry['name']; + $data = (string) $entry['data']; if ('' === $data) { continue; } @@ -220,19 +227,21 @@ class TransactionGroupEnrichment implements EnrichmentInterface continue; } - $this->metaData[(int)$entry['transaction_journal_id']][$name] = $data; + $this->metaData[(int) $entry['transaction_journal_id']][$name] = $data; } } private function collectNotes(): void { - $notes = Note::query()->whereIn('noteable_id', $this->journalIds) + $notes = Note::query() + ->whereIn('noteable_id', $this->journalIds) ->whereNotNull('notes.text') ->where('notes.text', '!=', '') - ->where('noteable_type', TransactionJournal::class)->get(['notes.noteable_id', 'notes.text'])->toArray() - ; + ->where('noteable_type', TransactionJournal::class) + ->get(['notes.noteable_id', 'notes.text']) + ->toArray(); foreach ($notes as $note) { - $this->notes[(int)$note['noteable_id']] = (string)$note['text']; + $this->notes[(int) $note['noteable_id']] = (string) $note['text']; } Log::debug(sprintf('Enrich with %d note(s)', count($this->notes))); } @@ -241,10 +250,10 @@ class TransactionGroupEnrichment implements EnrichmentInterface { $set = Tag::leftJoin('tag_transaction_journal', 'tags.id', '=', 'tag_transaction_journal.tag_id') ->whereIn('tag_transaction_journal.transaction_journal_id', $this->journalIds) - ->get(['tag_transaction_journal.transaction_journal_id', 'tags.tag'])->toArray() - ; + ->get(['tag_transaction_journal.transaction_journal_id', 'tags.tag']) + ->toArray(); foreach ($set as $item) { - $journalId = $item['transaction_journal_id']; + $journalId = $item['transaction_journal_id']; $this->tags[$journalId] ??= []; $this->tags[$journalId][] = $item['tag']; } diff --git a/app/Support/JsonApi/Enrichments/WebhookEnrichment.php b/app/Support/JsonApi/Enrichments/WebhookEnrichment.php index 6fdddf2632..0eaa3c61cd 100644 --- a/app/Support/JsonApi/Enrichments/WebhookEnrichment.php +++ b/app/Support/JsonApi/Enrichments/WebhookEnrichment.php @@ -1,6 +1,5 @@ first(); } - public function setUser(User $user): void {} + public function setUser(User $user): void + { + } - public function setUserGroup(UserGroup $userGroup): void {} + public function setUserGroup(UserGroup $userGroup): void + { + } private function appendCollectedInfo(): void { $this->collection = $this->collection->map(function (Webhook $item): Webhook { - $meta = [ + $meta = [ 'deliveries' => $this->webhookDeliveries[$item->id] ?? [], 'responses' => $this->webhookResponses[$item->id] ?? [], - 'triggers' => $this->webhookTriggers[$item->id] ?? [], + 'triggers' => $this->webhookTriggers[$item->id] ?? [] ]; $item->meta = $meta; @@ -120,7 +123,6 @@ class WebhookEnrichment implements EnrichmentInterface foreach ($all as $item) { $this->triggers[$item->id] = $item->key; } - } private function collectWebhookInfo(): void @@ -129,8 +131,8 @@ class WebhookEnrichment implements EnrichmentInterface /** @var stdClass $item */ foreach ($set as $item) { - $id = $item->webhook_id; - $deliveryId = $item->webhook_delivery_id; + $id = $item->webhook_id; + $deliveryId = $item->webhook_delivery_id; $this->webhookDeliveries[$id][] = WebhookDeliveryEnum::from($this->deliveries[$deliveryId])->name; } @@ -138,8 +140,8 @@ class WebhookEnrichment implements EnrichmentInterface /** @var stdClass $item */ foreach ($set as $item) { - $id = $item->webhook_id; - $responseId = $item->webhook_response_id; + $id = $item->webhook_id; + $responseId = $item->webhook_response_id; $this->webhookResponses[$id][] = WebhookResponseEnum::from($this->responses[$responseId])->name; } @@ -147,8 +149,8 @@ class WebhookEnrichment implements EnrichmentInterface /** @var stdClass $item */ foreach ($set as $item) { - $id = $item->webhook_id; - $triggerId = $item->webhook_trigger_id; + $id = $item->webhook_id; + $triggerId = $item->webhook_trigger_id; $this->webhookTriggers[$id][] = WebhookTriggerEnum::from($this->triggers[$triggerId])->name; } } diff --git a/app/Support/Models/AccountBalanceCalculator.php b/app/Support/Models/AccountBalanceCalculator.php index 931abb3d0e..f689e98a8f 100644 --- a/app/Support/Models/AccountBalanceCalculator.php +++ b/app/Support/Models/AccountBalanceCalculator.php @@ -70,35 +70,34 @@ class AccountBalanceCalculator return; } Log::debug(__METHOD__); - $object = new self(); + $object = new self(); - $set = []; + $set = []; foreach ($transactionJournal->transactions as $transaction) { $set[$transaction->account_id] = $transaction->account; } $accounts = new Collection()->push(...$set); // find meta value: - $date = $transactionJournal->date; - $meta = $transactionJournal->transactionJournalMeta()->where('name', '_internal_previous_date')->where('data', '!=', '')->first(); + $date = $transactionJournal->date; + $meta = $transactionJournal->transactionJournalMeta()->where('name', '_internal_previous_date')->where('data', '!=', '')->first(); Log::debug(sprintf('Date used is "%s"', $date->toW3cString())); if (null !== $meta) { $date = Carbon::parse($meta->data); Log::debug(sprintf('Date is overruled with "%s"', $date->toW3cString())); } - $object->optimizedCalculation($accounts, $date); } - private function getLatestBalance(int $accountId, int $currencyId, ?Carbon $notBefore): string + private function getLatestBalance(int $accountId, int $currencyId, null|Carbon $notBefore): string { if (!$notBefore instanceof Carbon) { Log::debug(sprintf('Start balance for account #%d and currency #%d is 0.', $accountId, $currencyId)); return '0'; } - $query = Transaction::leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') + $query = Transaction::leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->whereNull('transactions.deleted_at') ->where('transactions.transaction_currency_id', $currencyId) ->whereNull('transaction_journals.deleted_at') @@ -108,11 +107,18 @@ class AccountBalanceCalculator ->orderBy('transaction_journals.id', 'DESC') ->orderBy('transaction_journals.description', 'DESC') ->orderBy('transactions.amount', 'DESC') - ->where('transactions.account_id', $accountId) - ; + ->where('transactions.account_id', $accountId); $query->where('transaction_journals.date', '<', $notBefore); - $first = $query->first(['transactions.id', 'transactions.balance_dirty', 'transactions.transaction_currency_id', 'transaction_journals.date', 'transactions.account_id', 'transactions.amount', 'transactions.balance_after']); + $first = $query->first([ + 'transactions.id', + 'transactions.balance_dirty', + 'transactions.transaction_currency_id', + 'transaction_journals.date', + 'transactions.account_id', + 'transactions.amount', + 'transactions.balance_after' + ]); if (null === $first) { Log::debug(sprintf('Found no transactions for currency #%d and account #%d, return 0.', $currencyId, $accountId)); @@ -120,14 +126,18 @@ class AccountBalanceCalculator return '0'; } - - $balance = (string)($first->balance_after ?? '0'); - Log::debug(sprintf('getLatestBalance: found balance: %s in transaction #%d on moment %s', Steam::bcround($balance, 2), $first->id ?? 0, $notBefore->format('Y-m-d H:i:s'))); + $balance = (string) ($first->balance_after ?? '0'); + Log::debug(sprintf( + 'getLatestBalance: found balance: %s in transaction #%d on moment %s', + Steam::bcround($balance, 2), + $first->id ?? 0, + $notBefore->format('Y-m-d H:i:s') + )); return $balance; } - private function optimizedCalculation(Collection $accounts, ?Carbon $notBefore = null): void + private function optimizedCalculation(Collection $accounts, null|Carbon $notBefore = null): void { if ($notBefore instanceof Carbon) { $notBefore->startOfDay(); @@ -148,8 +158,7 @@ class AccountBalanceCalculator ->orderBy('transaction_journals.order', 'desc') ->orderBy('transaction_journals.id', 'asc') ->orderBy('transaction_journals.description', 'asc') - ->orderBy('transactions.amount', 'asc') - ; + ->orderBy('transactions.amount', 'asc'); if ($accounts->count() > 0) { $query->whereIn('transactions.account_id', $accounts->pluck('id')->toArray()); } @@ -157,7 +166,14 @@ class AccountBalanceCalculator $query->where('transaction_journals.date', '>=', $notBefore); } - $set = $query->get(['transactions.id', 'transactions.balance_dirty', 'transactions.transaction_currency_id', 'transaction_journals.date', 'transactions.account_id', 'transactions.amount']); + $set = $query->get([ + 'transactions.id', + 'transactions.balance_dirty', + 'transactions.transaction_currency_id', + 'transaction_journals.date', + 'transactions.account_id', + 'transactions.amount' + ]); Log::debug(sprintf('Found %d transaction(s)', $set->count())); // the balance value is an array. @@ -167,20 +183,23 @@ class AccountBalanceCalculator foreach ($set as $entry) { // Log::debug(sprintf('Processing transaction #%d with currency #%d and amount %s', $entry->id, $entry->transaction_currency_id, Steam::bcround($entry->amount, 2))); // start with empty array: - $balances[$entry->account_id] ??= []; - $balances[$entry->account_id][$entry->transaction_currency_id] ??= [$this->getLatestBalance($entry->account_id, $entry->transaction_currency_id, $notBefore), null]; + $balances[$entry->account_id] ??= []; + $balances[$entry->account_id][$entry->transaction_currency_id] ??= [ + $this->getLatestBalance($entry->account_id, $entry->transaction_currency_id, $notBefore), + null + ]; // before and after are easy: - $before = $balances[$entry->account_id][$entry->transaction_currency_id][0]; - $after = bcadd($before, (string)$entry->amount); + $before = $balances[$entry->account_id][$entry->transaction_currency_id][0]; + $after = bcadd($before, (string) $entry->amount); // Log::debug(sprintf('Before:%s, after:%s', Steam::bcround($before, 2), Steam::bcround($after, 2))); if (true === $entry->balance_dirty || $accounts->count() > 0) { // update the transaction: $entry->balance_before = $before; - $entry->balance_after = $after; - $entry->balance_dirty = false; + $entry->balance_after = $after; + $entry->balance_dirty = false; $entry->saveQuietly(); // do not observe this change, or we get stuck in a loop. ++$count; } @@ -189,8 +208,8 @@ class AccountBalanceCalculator $balances[$entry->account_id][$entry->transaction_currency_id] = [$after, $entry->date]; } Log::debug(sprintf('end of optimizedCalculation, corrected %d balance(s)', $count)); - // then update all transactions. + // then update all transactions. // save all collected balances in their respective account objects. // $this->storeAccountBalances($balances); } @@ -224,17 +243,17 @@ class AccountBalanceCalculator } /** @var AccountBalance $object */ - $object = $account->accountBalances()->firstOrCreate( - [ + $object = $account + ->accountBalances() + ->firstOrCreate([ 'title' => 'running_balance', 'balance' => '0', 'transaction_currency_id' => $currencyId, 'date' => $balance[1], - 'date_tz' => $balance[1]?->format('e'), - ] - ); + 'date_tz' => $balance[1]?->format('e') + ]); $object->balance = $balance[0]; - $object->date = $balance[1]; + $object->date = $balance[1]; $object->date_tz = $balance[1]?->format('e'); $object->saveQuietly(); } diff --git a/app/Support/Models/BillDateCalculator.php b/app/Support/Models/BillDateCalculator.php index d29244e726..cd904de57e 100644 --- a/app/Support/Models/BillDateCalculator.php +++ b/app/Support/Models/BillDateCalculator.php @@ -24,8 +24,8 @@ declare(strict_types=1); namespace FireflyIII\Support\Models; -use FireflyIII\Support\Facades\Navigation; use Carbon\Carbon; +use FireflyIII\Support\Facades\Navigation; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; @@ -40,7 +40,7 @@ class BillDateCalculator * * @SuppressWarnings("PHPMD.ExcessiveParameterList") */ - public function getPayDates(Carbon $earliest, Carbon $latest, Carbon $billStart, string $period, int $skip, ?Carbon $lastPaid): array + public function getPayDates(Carbon $earliest, Carbon $latest, Carbon $billStart, string $period, int $skip, null|Carbon $lastPaid): array { $this->diffInMonths = 0; $earliest->startOfDay(); @@ -48,17 +48,23 @@ class BillDateCalculator $billStart->startOfDay(); Log::debug('Now in BillDateCalculator::getPayDates()'); Log::debug(sprintf('Dates must be between %s and %s.', $earliest->format('Y-m-d'), $latest->format('Y-m-d'))); - Log::debug(sprintf('Bill started on %s, period is "%s", skip is %d, last paid = "%s".', $billStart->format('Y-m-d'), $period, $skip, $lastPaid?->format('Y-m-d'))); + Log::debug(sprintf( + 'Bill started on %s, period is "%s", skip is %d, last paid = "%s".', + $billStart->format('Y-m-d'), + $period, + $skip, + $lastPaid?->format('Y-m-d') + )); - $daysUntilEOM = Navigation::daysUntilEndOfMonth($billStart); + $daysUntilEOM = Navigation::daysUntilEndOfMonth($billStart); Log::debug(sprintf('For bill start, days until end of month is %d', $daysUntilEOM)); - $set = new Collection(); - $currentStart = clone $earliest; + $set = new Collection(); + $currentStart = clone $earliest; // 2023-06-23 subDay to fix 7655 $currentStart->subDay(); - $loop = 0; + $loop = 0; Log::debug('Start of loop'); while ($currentStart <= $latest) { @@ -98,7 +104,11 @@ class BillDateCalculator $nextUntilEOM = Navigation::daysUntilEndOfMonth($nextExpectedMatch); $diffEOM = $daysUntilEOM - $nextUntilEOM; if ($diffEOM > 0) { - Log::debug(sprintf('Bill start is %d days from the end of the month. nextExceptedMatch is %d days from the end of the month.', $daysUntilEOM, $nextUntilEOM)); + Log::debug(sprintf( + 'Bill start is %d days from the end of the month. nextExceptedMatch is %d days from the end of the month.', + $daysUntilEOM, + $nextUntilEOM + )); $nextExpectedMatch->subDays(); Log::debug(sprintf('Subtract %d days from next expected match, which is now %s', $diffEOM, $nextExpectedMatch->format('Y-m-d'))); } @@ -108,7 +118,7 @@ class BillDateCalculator // for the next loop, go to end of period, THEN add day. Log::debug('Add one day to nextExpectedMatch/currentStart.'); $nextExpectedMatch->addDay(); - $currentStart = clone $nextExpectedMatch; + $currentStart = clone $nextExpectedMatch; ++$loop; if ($loop > 31) { @@ -118,8 +128,8 @@ class BillDateCalculator } } Log::debug('end of loop'); - $simple = $set->map( // @phpstan-ignore-line - static fn (Carbon $date) => $date->format('Y-m-d') + $simple = $set->map( // @phpstan-ignore-line + static fn(Carbon $date) => $date->format('Y-m-d') ); Log::debug(sprintf('Found %d pay dates', $set->count()), $simple->toArray()); @@ -141,13 +151,13 @@ class BillDateCalculator return $billStartDate; } - $steps = Navigation::diffInPeriods($period, $skip, $earliest, $billStartDate); + $steps = Navigation::diffInPeriods($period, $skip, $earliest, $billStartDate); if ($steps === $this->diffInMonths) { Log::debug(sprintf('Steps is %d, which is the same as diffInMonths (%d), so we add another 1.', $steps, $this->diffInMonths)); ++$steps; } $this->diffInMonths = $steps; - $result = clone $billStartDate; + $result = clone $billStartDate; if ($steps > 0) { --$steps; Log::debug(sprintf('Steps is %d, because addPeriod already adds 1.', $steps)); diff --git a/app/Support/Models/ReturnsIntegerIdTrait.php b/app/Support/Models/ReturnsIntegerIdTrait.php index eb628bf26e..5763f9a6fd 100644 --- a/app/Support/Models/ReturnsIntegerIdTrait.php +++ b/app/Support/Models/ReturnsIntegerIdTrait.php @@ -38,8 +38,6 @@ trait ReturnsIntegerIdTrait */ protected function id(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } } diff --git a/app/Support/Models/ReturnsIntegerUserIdTrait.php b/app/Support/Models/ReturnsIntegerUserIdTrait.php index e9aeed82ba..c831ea2da3 100644 --- a/app/Support/Models/ReturnsIntegerUserIdTrait.php +++ b/app/Support/Models/ReturnsIntegerUserIdTrait.php @@ -36,15 +36,11 @@ trait ReturnsIntegerUserIdTrait */ protected function userGroupId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } protected function userId(): Attribute { - return Attribute::make( - get: static fn ($value): int => (int)$value, - ); + return Attribute::make(get: static fn($value): int => (int) $value); } } diff --git a/app/Support/Navigation.php b/app/Support/Navigation.php index 5bda050c6d..118adaa6a4 100644 --- a/app/Support/Navigation.php +++ b/app/Support/Navigation.php @@ -41,7 +41,7 @@ class Navigation { private readonly Calculator $calculator; - public function __construct(?Calculator $calculator = null) + public function __construct(null|Calculator $calculator = null) { $this->calculator = $calculator instanceof Calculator ? $calculator : new Calculator(); } @@ -68,21 +68,17 @@ class Navigation '1Y' => Periodicity::Yearly, 'custom' => Periodicity::Monthly, // custom? just add one month. // last X periods? Jump the relevant month / quarter / year - 'last7' => Periodicity::Weekly, - 'last30' => Periodicity::Monthly, - 'last90' => Periodicity::Quarterly, - 'last365' => Periodicity::Yearly, - 'MTD' => Periodicity::Monthly, - 'QTD' => Periodicity::Quarterly, - 'YTD' => Periodicity::Yearly, + 'last7' => Periodicity::Weekly, + 'last30' => Periodicity::Monthly, + 'last90' => Periodicity::Quarterly, + 'last365' => Periodicity::Yearly, + 'MTD' => Periodicity::Monthly, + 'QTD' => Periodicity::Quarterly, + 'YTD' => Periodicity::Yearly ]; if (!array_key_exists($repeatFreq, $functionMap)) { - Log::error(sprintf( - 'The periodicity %s is unknown. Choose one of available periodicity: %s', - $repeatFreq, - implode(', ', array_keys($functionMap)) - )); + Log::error(sprintf('The periodicity %s is unknown. Choose one of available periodicity: %s', $repeatFreq, implode(', ', array_keys($functionMap)))); return $theDate; } @@ -95,7 +91,7 @@ class Navigation if ($end < $start) { [$start, $end] = [$end, $start]; } - $periods = []; + $periods = []; // first, 13 periods of [range] $loopCount = 0; $loopDate = clone $end; @@ -108,11 +104,7 @@ class Navigation // make sure we don't go overboard if ($workEnd->gt($start)) { - $periods[] = [ - 'start' => clone $workStart, - 'end' => clone $workEnd, - 'period' => $range, - ]; + $periods[] = ['start' => clone $workStart, 'end' => clone $workEnd, 'period' => $range]; } // skip to the next period: $workStart->subDay()->startOfDay(); @@ -128,11 +120,7 @@ class Navigation // make sure we don't go overboard if ($workEnd->gt($start)) { - $periods[] = [ - 'start' => clone $workStart, - 'end' => clone $workEnd, - 'period' => '1Y', - ]; + $periods[] = ['start' => clone $workStart, 'end' => clone $workEnd, 'period' => '1Y']; } // skip to the next period: $workStart->subDay()->startOfDay(); @@ -147,26 +135,26 @@ class Navigation { $endOfMonth = $date->copy()->endOfMonth(); - return (int)$date->diffInDays($endOfMonth, true); + return (int) $date->diffInDays($endOfMonth, true); } public function diffInPeriods(string $period, int $skip, Carbon $beginning, Carbon $end): int { Log::debug(sprintf('diffInPeriods: %s (skip: %d), between %s and %s.', $period, $skip, $beginning->format('Y-m-d'), $end->format('Y-m-d'))); - $map = [ + $map = [ 'daily' => 'diffInDays', 'weekly' => 'diffInWeeks', 'monthly' => 'diffInMonths', 'quarterly' => 'diffInMonths', 'half-year' => 'diffInMonths', - 'yearly' => 'diffInYears', + 'yearly' => 'diffInYears' ]; if (!array_key_exists($period, $map)) { Log::warning(sprintf('No diffInPeriods for period "%s"', $period)); return 1; } - $func = $map[$period]; + $func = $map[$period]; // first do the diff $floatDiff = $beginning->{$func}($end, true); // @phpstan-ignore-line @@ -181,27 +169,22 @@ class Navigation } // then do ceil() - $diff = ceil($floatDiff); + $diff = ceil($floatDiff); Log::debug(sprintf('Diff is %f periods (%d rounded up)', $floatDiff, $diff)); if ($skip > 0) { $parameter = $skip + 1; $diff = ceil($diff / $parameter) * $parameter; - Log::debug(sprintf( - 'diffInPeriods: skip is %d, so param is %d, and diff becomes %d', - $skip, - $parameter, - $diff - )); + Log::debug(sprintf('diffInPeriods: skip is %d, so param is %d, and diff becomes %d', $skip, $parameter, $diff)); } - return (int)$diff; + return (int) $diff; } public function endOfPeriod(Carbon $end, string $repeatFreq): Carbon { - $currentEnd = clone $end; + $currentEnd = clone $end; // Log::debug(sprintf('Now in endOfPeriod("%s", "%s").', $currentEnd->toIso8601String(), $repeatFreq)); if ('MTD' === $repeatFreq && $end->isFuture()) { // fall back to a monthly schedule if the requested period is MTD. @@ -236,9 +219,9 @@ class Navigation 'half_year' => 'addMonths', 'year' => 'addYear', 'yearly' => 'addYear', - '1Y' => 'addYear', + '1Y' => 'addYear' ]; - $modifierMap = ['half-year' => 6, 'half_year' => 6, '6M' => 6]; + $modifierMap = ['half-year' => 6, 'half_year' => 6, '6M' => 6]; $subDay = ['week', 'weekly', '1W', 'month', 'monthly', '1M', '3M', 'quarter', 'quarterly', '6M', 'half-year', 'half_year', '1Y', 'year', 'yearly']; if ('custom' === $repeatFreq) { @@ -250,18 +233,23 @@ class Navigation Log::debug('Session data available.'); /** @var Carbon $tStart */ - $tStart = session('start', today(config('app.timezone'))->startOfMonth()); + $tStart = session('start', today(config('app.timezone'))->startOfMonth()); /** @var Carbon $tEnd */ $tEnd = session('end', today(config('app.timezone'))->endOfMonth()); - $diffInDays = (int)$tStart->diffInDays($tEnd, true); + $diffInDays = (int) $tStart->diffInDays($tEnd, true); } Log::debug(sprintf('Diff in days is %d', $diffInDays)); $currentEnd->addDays($diffInDays); // add sanity check. if ($currentEnd->lt($end)) { - throw new FireflyException(sprintf('[a] endOfPeriod(%s, %s) failed, because it resulted in %s.', $end->toW3cString(), $repeatFreq, $currentEnd->toW3cString())); + throw new FireflyException(sprintf( + '[a] endOfPeriod(%s, %s) failed, because it resulted in %s.', + $end->toW3cString(), + $repeatFreq, + $currentEnd->toW3cString() + )); } return $currentEnd; @@ -272,7 +260,12 @@ class Navigation $res = $today->endOfDay()->milli(0); // add sanity check. if ($res->lt($end)) { - throw new FireflyException(sprintf('[b] endOfPeriod(%s, %s) failed, because it resulted in %s.', $end->toW3cString(), $repeatFreq, $res->toW3cString())); + throw new FireflyException(sprintf( + '[b] endOfPeriod(%s, %s) failed, because it resulted in %s.', + $end->toW3cString(), + $repeatFreq, + $res->toW3cString() + )); } return $res; @@ -280,21 +273,26 @@ class Navigation // add sanity check. if ($currentEnd->lt($end)) { - throw new FireflyException(sprintf('[c] endOfPeriod(%s, %s) failed, because it resulted in %s.', $end->toW3cString(), $repeatFreq, $currentEnd->toW3cString())); + throw new FireflyException(sprintf( + '[c] endOfPeriod(%s, %s) failed, because it resulted in %s.', + $end->toW3cString(), + $repeatFreq, + $currentEnd->toW3cString() + )); } return $end->endOfMonth(); } - $result = match ($repeatFreq) { - 'last7' => $currentEnd->addDays(7)->startOfDay(), - 'last30' => $currentEnd->addDays(30)->startOfDay(), - 'last90' => $currentEnd->addDays(90)->startOfDay(), + $result = match ($repeatFreq) { + 'last7' => $currentEnd->addDays(7)->startOfDay(), + 'last30' => $currentEnd->addDays(30)->startOfDay(), + 'last90' => $currentEnd->addDays(90)->startOfDay(), 'last365' => $currentEnd->addDays(365)->startOfDay(), - 'MTD' => $currentEnd->startOfMonth()->startOfDay(), - 'QTD' => $currentEnd->firstOfQuarter()->startOfDay(), - 'YTD' => $currentEnd->startOfYear()->startOfDay(), - default => null, + 'MTD' => $currentEnd->startOfMonth()->startOfDay(), + 'QTD' => $currentEnd->firstOfQuarter()->startOfDay(), + 'YTD' => $currentEnd->startOfYear()->startOfDay(), + default => null }; if (null !== $result) { // add sanity check. @@ -316,7 +314,12 @@ class Navigation break; } if ($currentEnd->lt($end)) { - throw new FireflyException(sprintf('[d] endOfPeriod(%s, %s) failed, because it resulted in %s.', $end->toW3cString(), $repeatFreq, $currentEnd->toW3cString())); + throw new FireflyException(sprintf( + '[d] endOfPeriod(%s, %s) failed, because it resulted in %s.', + $end->toW3cString(), + $repeatFreq, + $currentEnd->toW3cString() + )); } } @@ -324,18 +327,22 @@ class Navigation } unset($result); - if (!array_key_exists($repeatFreq, $functionMap)) { Log::error(sprintf('Cannot do endOfPeriod for $repeat_freq "%s"', $repeatFreq)); // add sanity check. if ($currentEnd->lt($end)) { - throw new FireflyException(sprintf('[e] endOfPeriod(%s, %s) failed, because it resulted in %s.', $end->toW3cString(), $repeatFreq, $currentEnd->toW3cString())); + throw new FireflyException(sprintf( + '[e] endOfPeriod(%s, %s) failed, because it resulted in %s.', + $end->toW3cString(), + $repeatFreq, + $currentEnd->toW3cString() + )); } return $end; } - $function = $functionMap[$repeatFreq]; + $function = $functionMap[$repeatFreq]; if (array_key_exists($repeatFreq, $modifierMap)) { $currentEnd->{$function}($modifierMap[$repeatFreq])->milli(0); // @phpstan-ignore-line @@ -346,7 +353,12 @@ class Navigation // add sanity check. if ($currentEnd->lt($end)) { - throw new FireflyException(sprintf('[f] endOfPeriod(%s, %s) failed, because it resulted in %s.', $end->toW3cString(), $repeatFreq, $currentEnd->toW3cString())); + throw new FireflyException(sprintf( + '[f] endOfPeriod(%s, %s) failed, because it resulted in %s.', + $end->toW3cString(), + $repeatFreq, + $currentEnd->toW3cString() + )); } return $currentEnd; @@ -360,13 +372,18 @@ class Navigation // add sanity check. if ($currentEnd->lt($end)) { - throw new FireflyException(sprintf('[g] endOfPeriod(%s, %s) failed, because it resulted in %s.', $end->toW3cString(), $repeatFreq, $currentEnd->toW3cString())); + throw new FireflyException(sprintf( + '[g] endOfPeriod(%s, %s) failed, because it resulted in %s.', + $end->toW3cString(), + $repeatFreq, + $currentEnd->toW3cString() + )); } return $currentEnd; } - public function endOfX(Carbon $theCurrentEnd, string $repeatFreq, ?Carbon $maxDate): Carbon + public function endOfX(Carbon $theCurrentEnd, string $repeatFreq, null|Carbon $maxDate): Carbon { $functionMap = [ '1D' => 'endOfDay', @@ -382,10 +399,10 @@ class Navigation 'quarterly' => 'lastOfQuarter', '1Y' => 'endOfYear', 'year' => 'endOfYear', - 'yearly' => 'endOfYear', + 'yearly' => 'endOfYear' ]; - $currentEnd = clone $theCurrentEnd; + $currentEnd = clone $theCurrentEnd; if (array_key_exists($repeatFreq, $functionMap)) { $function = $functionMap[$repeatFreq]; @@ -409,17 +426,17 @@ class Navigation if (is_array($range)) { $range = '1M'; } - $range = (string)$range; + $range = (string) $range; if (!$correct) { return $range; } return match ($range) { - 'last7' => '1W', - 'last30', 'MTD' => '1M', - 'last90', 'QTD' => '3M', + 'last7' => '1W', + 'last30', 'MTD' => '1M', + 'last90', 'QTD' => '3M', 'last365', 'YTD' => '1Y', - default => $range, + default => $range }; } @@ -428,28 +445,28 @@ class Navigation */ public function listOfPeriods(Carbon $start, Carbon $end): array { - $locale = Steam::getLocale(); + $locale = Steam::getLocale(); // define period to increment $increment = 'addDay'; $format = $this->preferredCarbonFormat($start, $end); - $displayFormat = (string)trans('config.month_and_day_js', [], $locale); + $displayFormat = (string) trans('config.month_and_day_js', [], $locale); $diff = $start->diffInMonths($end, true); // increment by month (for year) if ($diff >= 1.0001 && $diff < 12.001) { $increment = 'addMonth'; - $displayFormat = (string)trans('config.month_js'); + $displayFormat = (string) trans('config.month_js'); } // increment by year (for multi-year) if ($diff >= 12.0001) { $increment = 'addYear'; - $displayFormat = (string)trans('config.year_js'); + $displayFormat = (string) trans('config.year_js'); } - $begin = clone $start; - $entries = []; + $begin = clone $start; + $entries = []; while ($begin < $end) { - $formatted = $begin->format($format); - $displayed = $begin->isoFormat($displayFormat); + $formatted = $begin->format($format); + $displayed = $begin->isoFormat($displayFormat); $entries[$formatted] = $displayed; $begin->{$increment}(); // @phpstan-ignore-line } @@ -467,10 +484,11 @@ class Navigation Log::error($exception->getMessage(), ['exception' => $exception]); } - Log::debug( - 'Any error occurred to calculate the next date.', - ['date' => $epoch, 'periodicity' => $periodicity->name, 'skipInterval' => $skipInterval] - ); + Log::debug('Any error occurred to calculate the next date.', [ + 'date' => $epoch, + 'periodicity' => $periodicity->name, + 'skipInterval' => $skipInterval + ]); return $epoch; } @@ -479,26 +497,26 @@ class Navigation { $date = clone $theDate; $formatMap = [ - '1D' => (string)trans('config.specific_day_js'), - 'daily' => (string)trans('config.specific_day_js'), - 'custom' => (string)trans('config.specific_day_js'), - '1W' => (string)trans('config.week_in_year_js'), - 'week' => (string)trans('config.week_in_year_js'), - 'weekly' => (string)trans('config.week_in_year_js'), - '1M' => (string)trans('config.month_js'), - 'MTD' => (string)trans('config.month_js'), - 'month' => (string)trans('config.month_js'), - 'monthly' => (string)trans('config.month_js'), - '1Y' => (string)trans('config.year_js'), - 'YTD' => (string)trans('config.year_js'), - 'year' => (string)trans('config.year_js'), - 'yearly' => (string)trans('config.year_js'), - '6M' => (string)trans('config.half_year_js'), - 'last7' => (string)trans('config.specific_day_js'), - 'last30' => (string)trans('config.month_js'), - 'last90' => (string)trans('config.month_js'), - 'last365' => (string)trans('config.year_js'), - 'QTD' => (string)trans('config.month_js'), + '1D' => (string) trans('config.specific_day_js'), + 'daily' => (string) trans('config.specific_day_js'), + 'custom' => (string) trans('config.specific_day_js'), + '1W' => (string) trans('config.week_in_year_js'), + 'week' => (string) trans('config.week_in_year_js'), + 'weekly' => (string) trans('config.week_in_year_js'), + '1M' => (string) trans('config.month_js'), + 'MTD' => (string) trans('config.month_js'), + 'month' => (string) trans('config.month_js'), + 'monthly' => (string) trans('config.month_js'), + '1Y' => (string) trans('config.year_js'), + 'YTD' => (string) trans('config.year_js'), + 'year' => (string) trans('config.year_js'), + 'yearly' => (string) trans('config.year_js'), + '6M' => (string) trans('config.half_year_js'), + 'last7' => (string) trans('config.specific_day_js'), + 'last30' => (string) trans('config.month_js'), + 'last90' => (string) trans('config.month_js'), + 'last365' => (string) trans('config.year_js'), + 'QTD' => (string) trans('config.month_js') ]; if (array_key_exists($repeatFrequency, $formatMap)) { @@ -544,12 +562,12 @@ class Navigation public function preferredCarbonFormatByPeriod(string $period): string { return match ($period) { - default => 'Y-m-d', + default => 'Y-m-d', // '1D' => 'Y-m-d', - '1W' => '\WW,Y', - '1M' => 'Y-m', + '1W' => '\WW,Y', + '1M' => 'Y-m', '3M', '6M' => '\QQ,Y', - '1Y' => 'Y', + '1Y' => 'Y' }; } @@ -563,14 +581,14 @@ class Navigation $locale = Steam::getLocale(); $diff = $start->diffInMonths($end, true); if ($diff >= 1.001 && $diff < 12.001) { - return (string)trans('config.month_js', [], $locale); + return (string) trans('config.month_js', [], $locale); } if ($diff >= 12.001) { - return (string)trans('config.year_js', [], $locale); + return (string) trans('config.year_js', [], $locale); } - return (string)trans('config.month_and_day_js', [], $locale); + return (string) trans('config.month_and_day_js', [], $locale); } /** @@ -629,9 +647,9 @@ class Navigation public function startOfPeriod(Carbon $theDate, string $repeatFreq): Carbon { - $date = clone $theDate; + $date = clone $theDate; // Log::debug(sprintf('Now in startOfPeriod("%s", "%s")', $date->toIso8601String(), $repeatFreq)); - $functionMap = [ + $functionMap = [ '1D' => 'startOfDay', 'daily' => 'startOfDay', '1W' => 'startOfWeek', @@ -646,12 +664,10 @@ class Navigation 'year' => 'startOfYear', 'yearly' => 'startOfYear', '1Y' => 'startOfYear', - 'MTD' => 'startOfMonth', + 'MTD' => 'startOfMonth' ]; - $parameterMap = [ - 'startOfWeek' => [Carbon::MONDAY], - ]; + $parameterMap = ['startOfWeek' => [Carbon::MONDAY]]; if (array_key_exists($repeatFreq, $functionMap)) { $function = $functionMap[$repeatFreq]; @@ -678,15 +694,15 @@ class Navigation return $date; } - $result = match ($repeatFreq) { - 'last7' => $date->subDays(7)->startOfDay(), - 'last30' => $date->subDays(30)->startOfDay(), - 'last90' => $date->subDays(90)->startOfDay(), + $result = match ($repeatFreq) { + 'last7' => $date->subDays(7)->startOfDay(), + 'last30' => $date->subDays(30)->startOfDay(), + 'last90' => $date->subDays(90)->startOfDay(), 'last365' => $date->subDays(365)->startOfDay(), - 'MTD' => $date->startOfMonth()->startOfDay(), - 'QTD' => $date->firstOfQuarter()->startOfDay(), - 'YTD' => $date->startOfYear()->startOfDay(), - default => null, + 'MTD' => $date->startOfMonth()->startOfDay(), + 'QTD' => $date->firstOfQuarter()->startOfDay(), + 'YTD' => $date->startOfYear()->startOfDay(), + default => null }; if (null !== $result) { // Log::debug(sprintf('Result is "%s"', $date->toIso8601String())); @@ -707,10 +723,10 @@ class Navigation /** * @throws FireflyException */ - public function subtractPeriod(Carbon $theDate, string $repeatFreq, ?int $subtract = null): Carbon + public function subtractPeriod(Carbon $theDate, string $repeatFreq, null|int $subtract = null): Carbon { $subtract ??= 1; - $date = clone $theDate; + $date = clone $theDate; // 1D 1W 1M 3M 6M 1Y $functionMap = [ '1D' => 'subDays', @@ -723,15 +739,9 @@ class Navigation 'monthly' => 'subMonths', 'year' => 'subYears', '1Y' => 'subYears', - 'yearly' => 'subYears', - ]; - $modifierMap = [ - 'quarter' => 3, - '3M' => 3, - 'quarterly' => 3, - 'half-year' => 6, - '6M' => 6, + 'yearly' => 'subYears' ]; + $modifierMap = ['quarter' => 3, '3M' => 3, 'quarterly' => 3, 'half-year' => 6, '6M' => 6]; if (array_key_exists($repeatFreq, $functionMap)) { $function = $functionMap[$repeatFreq]; $date->{$function}($subtract); // @phpstan-ignore-line @@ -749,11 +759,11 @@ class Navigation // this is then subtracted from $theDate (* $subtract). if ('custom' === $repeatFreq) { /** @var Carbon $tStart */ - $tStart = session('start', today(config('app.timezone'))->startOfMonth()); + $tStart = session('start', today(config('app.timezone'))->startOfMonth()); /** @var Carbon $tEnd */ $tEnd = session('end', today(config('app.timezone'))->endOfMonth()); - $diffInDays = (int)$tStart->diffInDays($tEnd, true); + $diffInDays = (int) $tStart->diffInDays($tEnd, true); $date->subDays($diffInDays * $subtract); return $date; @@ -808,13 +818,7 @@ class Navigation public function updateEndDate(string $range, Carbon $start): Carbon { Log::debug(sprintf('updateEndDate("%s", "%s")', $range, $start->format('Y-m-d'))); - $functionMap = [ - '1D' => 'endOfDay', - '1W' => 'endOfWeek', - '1M' => 'endOfMonth', - '3M' => 'lastOfQuarter', - 'custom' => 'startOfMonth', // this only happens in test situations. - ]; + $functionMap = ['1D' => 'endOfDay', '1W' => 'endOfWeek', '1M' => 'endOfMonth', '3M' => 'lastOfQuarter', 'custom' => 'startOfMonth']; // this only happens in test situations. $end = clone $start; if (array_key_exists($range, $functionMap)) { @@ -843,15 +847,7 @@ class Navigation return $fiscalHelper->endOfFiscalYear($end); } - $list = [ - 'last7', - 'last30', - 'last90', - 'last365', - 'YTD', - 'QTD', - 'MTD', - ]; + $list = ['last7', 'last30', 'last90', 'last365', 'YTD', 'QTD', 'MTD']; if (in_array($range, $list, true)) { $end = today(config('app.timezone')); $end->endOfDay(); @@ -874,7 +870,7 @@ class Navigation '1W' => 'startOfWeek', '1M' => 'startOfMonth', '3M' => 'firstOfQuarter', - 'custom' => 'startOfMonth', // this only happens in test situations. + 'custom' => 'startOfMonth' // this only happens in test situations. ]; if (array_key_exists($range, $functionMap)) { $function = $functionMap[$range]; diff --git a/app/Support/Notifications/UrlValidator.php b/app/Support/Notifications/UrlValidator.php index cd6ffefd87..3daaa434cc 100644 --- a/app/Support/Notifications/UrlValidator.php +++ b/app/Support/Notifications/UrlValidator.php @@ -31,6 +31,10 @@ class UrlValidator { public static function isValidWebhookURL(string $url): bool { - return str_starts_with($url, 'https://hooks.slack.com/services/') || str_starts_with($url, 'https://discord.com/api/webhooks/') || str_ends_with($url, '/slack'); + return ( + str_starts_with($url, 'https://hooks.slack.com/services/') + || str_starts_with($url, 'https://discord.com/api/webhooks/') + || str_ends_with($url, '/slack') + ); } } diff --git a/app/Support/NullArrayObject.php b/app/Support/NullArrayObject.php index a1b6b190de..58287c2edb 100644 --- a/app/Support/NullArrayObject.php +++ b/app/Support/NullArrayObject.php @@ -37,8 +37,10 @@ class NullArrayObject extends ArrayObject * @param null $default */ /** @phpstan-ignore-next-line */ - public function __construct(array $array, public $default = null) - { + public function __construct( + array $array, + public $default = null + ) { parent::__construct($array); } diff --git a/app/Support/Observers/RecalculatesAvailableBudgetsTrait.php b/app/Support/Observers/RecalculatesAvailableBudgetsTrait.php index ff0fb4b53d..e2004d9482 100644 --- a/app/Support/Observers/RecalculatesAvailableBudgetsTrait.php +++ b/app/Support/Observers/RecalculatesAvailableBudgetsTrait.php @@ -1,6 +1,5 @@ setUser($availableBudget->user); - $newAmount = '0'; - $abPeriod = Period::make($availableBudget->start_date, $availableBudget->end_date, Precision::DAY()); - Log::debug( - sprintf( - 'Now at AB #%d, ("%s" to "%s")', - $availableBudget->id, - $availableBudget->start_date->format('Y-m-d'), - $availableBudget->end_date->format('Y-m-d') - ) - ); + $newAmount = '0'; + $abPeriod = Period::make($availableBudget->start_date, $availableBudget->end_date, Precision::DAY()); + Log::debug(sprintf( + 'Now at AB #%d, ("%s" to "%s")', + $availableBudget->id, + $availableBudget->start_date->format('Y-m-d'), + $availableBudget->end_date->format('Y-m-d') + )); // have to recalculate everything just in case. - $set = $repository->getAllBudgetLimitsByCurrency($availableBudget->transactionCurrency, $availableBudget->start_date, $availableBudget->end_date); + $set = $repository->getAllBudgetLimitsByCurrency($availableBudget->transactionCurrency, $availableBudget->start_date, $availableBudget->end_date); Log::debug(sprintf('Found %d interesting budget limit(s).', $set->count())); /** @var BudgetLimit $budgetLimit */ foreach ($set as $budgetLimit) { - Log::debug( - sprintf( - 'Found interesting budget limit #%d ("%s" to "%s")', - $budgetLimit->id, - $budgetLimit->start_date->format('Y-m-d'), - $budgetLimit->end_date->format('Y-m-d') - ) - ); + Log::debug(sprintf( + 'Found interesting budget limit #%d ("%s" to "%s")', + $budgetLimit->id, + $budgetLimit->start_date->format('Y-m-d'), + $budgetLimit->end_date->format('Y-m-d') + )); // overlap in days: - $limitPeriod = Period::make( - $budgetLimit->start_date, - $budgetLimit->end_date, - precision : Precision::DAY(), - boundaries: Boundaries::EXCLUDE_NONE() - ); + $limitPeriod = Period::make($budgetLimit->start_date, $budgetLimit->end_date, precision: Precision::DAY(), boundaries: Boundaries::EXCLUDE_NONE()); // if both equal each other, amount from this BL must be added to the AB if ($limitPeriod->equals($abPeriod)) { Log::debug('This budget limit is equal to the available budget period.'); - $newAmount = bcadd($newAmount, (string)$budgetLimit->amount); + $newAmount = bcadd($newAmount, (string) $budgetLimit->amount); } // if budget limit period is inside AB period, it can be added in full. if (!$limitPeriod->equals($abPeriod) && $abPeriod->contains($limitPeriod)) { Log::debug('This budget limit is smaller than the available budget period.'); - $newAmount = bcadd($newAmount, (string)$budgetLimit->amount); + $newAmount = bcadd($newAmount, (string) $budgetLimit->amount); } if (!$limitPeriod->equals($abPeriod) && !$abPeriod->contains($limitPeriod) && $abPeriod->overlapsWith($limitPeriod)) { Log::debug('This budget limit is something else entirely!'); $overlap = $abPeriod->overlap($limitPeriod); if ($overlap instanceof Period) { $length = $overlap->length(); - $daily = bcmul($this->getDailyAmount($budgetLimit), (string)$length); + $daily = bcmul($this->getDailyAmount($budgetLimit), (string) $length); $newAmount = bcadd($newAmount, $daily); } } @@ -113,17 +103,16 @@ trait RecalculatesAvailableBudgetsTrait if (0 === $budgetLimit->id) { return '0'; } - $limitPeriod = Period::make( - $budgetLimit->start_date, - $budgetLimit->end_date, - precision : Precision::DAY(), - boundaries: Boundaries::EXCLUDE_NONE() - ); + $limitPeriod = Period::make($budgetLimit->start_date, $budgetLimit->end_date, precision: Precision::DAY(), boundaries: Boundaries::EXCLUDE_NONE()); $days = $limitPeriod->length(); - $amount = bcdiv($budgetLimit->amount, (string)$days, 12); - Log::debug( - sprintf('Total amount for budget limit #%d is %s. Nr. of days is %d. Amount per day is %s', $budgetLimit->id, $budgetLimit->amount, $days, $amount) - ); + $amount = bcdiv($budgetLimit->amount, (string) $days, 12); + Log::debug(sprintf( + 'Total amount for budget limit #%d is %s. Nr. of days is %d. Amount per day is %s', + $budgetLimit->id, + $budgetLimit->amount, + $days, + $amount + )); return $amount; } @@ -133,7 +122,7 @@ trait RecalculatesAvailableBudgetsTrait Log::debug(sprintf('Now in updateAvailableBudget(limit #%d)', $budgetLimit->id)); /** @var null|Budget $budget */ - $budget = Budget::find($budgetLimit->budget_id); + $budget = Budget::find($budgetLimit->budget_id); if (null === $budget) { Log::warning('Budget is null, probably deleted, find deleted version.'); @@ -148,7 +137,7 @@ trait RecalculatesAvailableBudgetsTrait } /** @var null|User $user */ - $user = $budget->user; + $user = $budget->user; // sanity check. It happens when the budget has been deleted so the original user is unknown. if (null === $user) { @@ -158,7 +147,6 @@ trait RecalculatesAvailableBudgetsTrait return; } - // based on the view range of the user (month week quarter etc) the budget limit could // either overlap multiple available budget periods or be contained in a single one. // all have to be created or updated. @@ -172,31 +160,35 @@ trait RecalculatesAvailableBudgetsTrait if (null === $viewRange || is_array($viewRange)) { $viewRange = '1M'; } - $viewRange = (string)$viewRange; + $viewRange = (string) $viewRange; - $start = Navigation::startOfPeriod($budgetLimit->start_date, $viewRange); - $end = Navigation::startOfPeriod($budgetLimit->end_date, $viewRange); - $end = Navigation::endOfPeriod($end, $viewRange); + $start = Navigation::startOfPeriod($budgetLimit->start_date, $viewRange); + $end = Navigation::startOfPeriod($budgetLimit->end_date, $viewRange); + $end = Navigation::endOfPeriod($end, $viewRange); if ($end < $start) { - [$start, $end] = [$end, $start]; + [$start, $end] = [$end, $start]; $budgetLimit->start_date = $start; - $budgetLimit->end_date = $end; + $budgetLimit->end_date = $end; $budgetLimit->saveQuietly(); } - // limit period in total is: $limitPeriod = Period::make($start, $end, precision: Precision::DAY(), boundaries: Boundaries::EXCLUDE_NONE()); Log::debug(sprintf('Limit period is from %s to %s', $start->format('Y-m-d'), $end->format('Y-m-d'))); // from the start until the end of the budget limit, need to loop! - $current = clone $start; + $current = clone $start; while ($current <= $end) { - $currentEnd = Navigation::endOfPeriod($current, $viewRange); + $currentEnd = Navigation::endOfPeriod($current, $viewRange); // create or find AB for this particular period, and set the amount accordingly. /** @var null|AvailableBudget $availableBudget */ - $availableBudget = $user->availableBudgets()->where('start_date', $current->format('Y-m-d'))->where('end_date', $currentEnd->format('Y-m-d'))->where('transaction_currency_id', $budgetLimit->transaction_currency_id)->first(); + $availableBudget = $user + ->availableBudgets() + ->where('start_date', $current->format('Y-m-d')) + ->where('end_date', $currentEnd->format('Y-m-d')) + ->where('transaction_currency_id', $budgetLimit->transaction_currency_id) + ->first(); if (null !== $availableBudget) { Log::debug('Found 1 AB, will update.'); @@ -205,7 +197,7 @@ trait RecalculatesAvailableBudgetsTrait if (null === $availableBudget && $currentEnd->gte($current)) { $currentPeriod = Period::make($current, $currentEnd, precision: Precision::DAY(), boundaries: Boundaries::EXCLUDE_NONE()); $daily = $this->getDailyAmount($budgetLimit); - $amount = bcmul((string)$daily, (string)$currentPeriod->length(), 12); + $amount = bcmul((string) $daily, (string) $currentPeriod->length(), 12); // no need to calculate if period is equal. if ($currentPeriod->equals($limitPeriod)) { @@ -216,18 +208,16 @@ trait RecalculatesAvailableBudgetsTrait } if (0 !== bccomp($amount, '0')) { Log::debug(sprintf('Will create AB for period %s to %s', $current->format('Y-m-d'), $currentEnd->format('Y-m-d'))); - $availableBudget = new AvailableBudget( - [ - 'user_id' => $user->id, - 'user_group_id' => $user->user_group_id, - 'transaction_currency_id' => $budgetLimit->transaction_currency_id, - 'start_date' => $current, - 'start_date_tz' => $current->format('e'), - 'end_date' => $currentEnd, - 'end_date_tz' => $currentEnd->format('e'), - 'amount' => $amount, - ] - ); + $availableBudget = new AvailableBudget([ + 'user_id' => $user->id, + 'user_group_id' => $user->user_group_id, + 'transaction_currency_id' => $budgetLimit->transaction_currency_id, + 'start_date' => $current, + 'start_date_tz' => $current->format('e'), + 'end_date' => $currentEnd, + 'end_date_tz' => $currentEnd->format('e'), + 'amount' => $amount + ]); $availableBudget->save(); Log::debug(sprintf('ID of new AB is #%d', $availableBudget->id)); $this->calculateAmount($availableBudget); @@ -235,7 +225,7 @@ trait RecalculatesAvailableBudgetsTrait } // prep for next loop - $current = Navigation::addPeriod($current, $viewRange); + $current = Navigation::addPeriod($current, $viewRange); } } } diff --git a/app/Support/ParseDateString.php b/app/Support/ParseDateString.php index 7e518f9a04..d3a39e2658 100644 --- a/app/Support/ParseDateString.php +++ b/app/Support/ParseDateString.php @@ -38,20 +38,19 @@ use function Safe\preg_match; */ class ParseDateString { - private array $keywords - = [ - 'today', - 'yesterday', - 'tomorrow', - 'start of this week', - 'end of this week', - 'start of this month', - 'end of this month', - 'start of this quarter', - 'end of this quarter', - 'start of this year', - 'end of this year', - ]; + private array $keywords = [ + 'today', + 'yesterday', + 'tomorrow', + 'start of this week', + 'end of this week', + 'start of this month', + 'end of this month', + 'start of this quarter', + 'end of this quarter', + 'start of this year', + 'end of this year' + ]; public function isDateRange(string $date): bool { @@ -78,15 +77,15 @@ class ParseDateString public function parseDate(string $date): Carbon { Log::debug(sprintf('parseDate("%s")', $date)); - $date = strtolower($date); + $date = strtolower($date); // parse keywords: if (in_array($date, $this->keywords, true)) { return $this->parseKeyword($date); } // if regex for YYYY-MM-DD: - $pattern = '/^(19|20)\d\d-(0[1-9]|1[012])-(0[1-9]|[12]\d|3[01])$/'; - $result = preg_match($pattern, $date); + $pattern = '/^(19|20)\d\d-(0[1-9]|1[012])-(0[1-9]|[12]\d|3[01])$/'; + $result = preg_match($pattern, $date); if (0 !== $result) { return $this->parseDefaultDate($date); } @@ -113,7 +112,7 @@ class ParseDateString return new Carbon('1984-09-17'); } // maybe a year, nothing else? - if (4 === strlen($date) && is_numeric($date) && (int)$date > 1000 && (int)$date <= 3000) { + if (4 === strlen($date) && is_numeric($date) && (int) $date > 1000 && (int) $date <= 3000) { return new Carbon(sprintf('%d-01-01', $date)); } @@ -123,9 +122,7 @@ class ParseDateString public function parseRange(string $date): array { // several types of range can be submitted - $result = [ - 'exact' => new Carbon('1984-09-17'), - ]; + $result = ['exact' => new Carbon('1984-09-17')]; switch (true) { default: @@ -264,9 +261,7 @@ class ParseDateString { $parts = explode('-', $date); - return [ - 'day' => $parts[2], - ]; + return ['day' => $parts[2]]; } protected function parseDefaultDate(string $date): Carbon @@ -290,17 +285,17 @@ class ParseDateString $today = today(config('app.timezone'))->startOfDay(); return match ($keyword) { - default => $today, - 'yesterday' => $today->subDay(), - 'tomorrow' => $today->addDay(), - 'start of this week' => $today->startOfWeek(CarbonInterface::MONDAY), - 'end of this week' => $today->endOfWeek(CarbonInterface::SUNDAY), - 'start of this month' => $today->startOfMonth(), - 'end of this month' => $today->endOfMonth(), + default => $today, + 'yesterday' => $today->subDay(), + 'tomorrow' => $today->addDay(), + 'start of this week' => $today->startOfWeek(CarbonInterface::MONDAY), + 'end of this week' => $today->endOfWeek(CarbonInterface::SUNDAY), + 'start of this month' => $today->startOfMonth(), + 'end of this month' => $today->endOfMonth(), 'start of this quarter' => $today->startOfQuarter(), - 'end of this quarter' => $today->endOfQuarter(), - 'start of this year' => $today->startOfYear(), - 'end of this year' => $today->endOfYear(), + 'end of this quarter' => $today->endOfQuarter(), + 'start of this year' => $today->startOfYear(), + 'end of this year' => $today->endOfYear() }; } @@ -312,9 +307,7 @@ class ParseDateString Log::debug(sprintf('parseMonthRange: Parsed "%s".', $date)); $parts = explode('-', $date); - return [ - 'month' => $parts[1], - ]; + return ['month' => $parts[1]]; } /** @@ -325,10 +318,7 @@ class ParseDateString Log::debug(sprintf('parseMonthYearRange: Parsed "%s".', $date)); $parts = explode('-', $date); - return [ - 'year' => $parts[0], - 'month' => $parts[1], - ]; + return ['year' => $parts[0], 'month' => $parts[1]]; } protected function parseRelativeDate(string $date): Carbon @@ -337,29 +327,17 @@ class ParseDateString $parts = explode(' ', $date); $today = today(config('app.timezone'))->startOfDay(); $functions = [ - [ - 'd' => 'subDays', - 'w' => 'subWeeks', - 'm' => 'subMonths', - 'q' => 'subQuarters', - 'y' => 'subYears', - ], - [ - 'd' => 'addDays', - 'w' => 'addWeeks', - 'm' => 'addMonths', - 'q' => 'addQuarters', - 'y' => 'addYears', - ], + ['d' => 'subDays', 'w' => 'subWeeks', 'm' => 'subMonths', 'q' => 'subQuarters', 'y' => 'subYears'], + ['d' => 'addDays', 'w' => 'addWeeks', 'm' => 'addMonths', 'q' => 'addQuarters', 'y' => 'addYears'] ]; foreach ($parts as $part) { Log::debug(sprintf('Now parsing part "%s"', $part)); - $part = trim($part); + $part = trim($part); // verify if correct - $pattern = '/[+-]\d+[wqmdy]/'; - $result = preg_match($pattern, $part); + $pattern = '/[+-]\d+[wqmdy]/'; + $result = preg_match($pattern, $part); if (0 === $result) { Log::error(sprintf('Part "%s" does not match regular expression. Will be skipped.', $part)); @@ -367,13 +345,13 @@ class ParseDateString } $direction = str_starts_with($part, '+') ? 1 : 0; $period = $part[strlen($part) - 1]; - $number = (int)substr($part, 1, -1); + $number = (int) substr($part, 1, -1); if (!array_key_exists($period, $functions[$direction])) { Log::error(sprintf('No method for direction %d and period "%s".', $direction, $period)); continue; } - $func = $functions[$direction][$period]; + $func = $functions[$direction][$period]; Log::debug(sprintf('Will now do %s(%d) on %s', $func, $number, $today->format('Y-m-d'))); $today->{$func}($number); // @phpstan-ignore-line Log::debug(sprintf('Resulting date is %s', $today->format('Y-m-d'))); @@ -390,9 +368,7 @@ class ParseDateString Log::debug(sprintf('parseYearRange: Parsed "%s"', $date)); $parts = explode('-', $date); - return [ - 'year' => $parts[0], - ]; + return ['year' => $parts[0]]; } /** @@ -403,10 +379,7 @@ class ParseDateString Log::debug(sprintf('parseDayYearRange: Parsed "%s".', $date)); $parts = explode('-', $date); - return [ - 'year' => $parts[0], - 'day' => $parts[2], - ]; + return ['year' => $parts[0], 'day' => $parts[2]]; } /** @@ -417,9 +390,6 @@ class ParseDateString Log::debug(sprintf('parseMonthDayRange: Parsed "%s".', $date)); $parts = explode('-', $date); - return [ - 'month' => $parts[1], - 'day' => $parts[2], - ]; + return ['month' => $parts[1], 'day' => $parts[2]]; } } diff --git a/app/Support/Preferences.php b/app/Support/Preferences.php index 2b841aa520..5816d841aa 100644 --- a/app/Support/Preferences.php +++ b/app/Support/Preferences.php @@ -53,8 +53,7 @@ class Preferences $q->whereNull('user_group_id'); $q->orWhere('user_group_id', $user->user_group_id); }) - ->get() - ; + ->get(); } public function beginsWith(User $user, string $search): Collection @@ -90,12 +89,12 @@ class Preferences Cache::put($key, '', 5); } - public function get(string $name, array|bool|int|string|null $default = null): ?Preference + public function get(string $name, array|bool|int|string|null $default = null): null|Preference { /** @var null|User $user */ $user = auth()->user(); if (null === $user) { - $preference = new Preference(); + $preference = new Preference(); $preference->data = $default; return $preference; @@ -113,8 +112,7 @@ class Preferences $q->orWhere('user_group_id', $user->user_group_id); }) ->whereIn('name', $list) - ->get(['id', 'name', 'data']) - ; + ->get(['id', 'name', 'data']); /** @var Preference $preference */ foreach ($preferences as $preference) { @@ -129,7 +127,7 @@ class Preferences return $result; } - public function getEncrypted(string $name, mixed $default = null): ?Preference + public function getEncrypted(string $name, mixed $default = null): null|Preference { $result = $this->get($name, $default); if (!$result instanceof Preference) { @@ -156,7 +154,7 @@ class Preferences return $result; } - public function getEncryptedForUser(User $user, string $name, array|bool|int|string|null $default = null): ?Preference + public function getEncryptedForUser(User $user, string $name, array|bool|int|string|null $default = null): null|Preference { $result = $this->getForUser($user, $name, $default); if ('' === $result->data) { @@ -177,11 +175,10 @@ class Preferences return $result; } - return $result; } - public function getForUser(User $user, string $name, array|bool|int|string|null $default = null): ?Preference + public function getForUser(User $user, string $name, array|bool|int|string|null $default = null): null|Preference { // Log::debug(sprintf('getForUser(#%d, "%s")', $user->id, $name)); // don't care about user group ID, except for some specific preferences. @@ -192,7 +189,7 @@ class Preferences $query->where('user_group_id', $userGroupId); } - $preference = $query->first(['id', 'user_id', 'user_group_id', 'name', 'data', 'updated_at', 'created_at']); + $preference = $query->first(['id', 'user_id', 'user_group_id', 'name', 'data', 'updated_at', 'created_at']); if (null !== $preference && null === $preference->data) { $preference->delete(); @@ -216,12 +213,12 @@ class Preferences return $this->setForUser($user, $name, $default); } - public function getFresh(string $name, array|bool|int|string|null $default = null): ?Preference + public function getFresh(string $name, array|bool|int|string|null $default = null): null|Preference { /** @var null|User $user */ $user = auth()->user(); if (null === $user) { - $preference = new Preference(); + $preference = new Preference(); $preference->data = $default; return $preference; @@ -232,8 +229,8 @@ class Preferences public function lastActivity(): string { - $instance = PreferencesSingleton::getInstance(); - $pref = $instance->getPreference('last_activity'); + $instance = PreferencesSingleton::getInstance(); + $pref = $instance->getPreference('last_activity'); if (null !== $pref) { // Log::debug(sprintf('Found last activity in singleton: %s', $pref)); return $pref; @@ -247,7 +244,7 @@ class Preferences if (is_array($lastActivity)) { $lastActivity = implode(',', $lastActivity); } - $setting = hash('sha256', (string)$lastActivity); + $setting = hash('sha256', (string) $lastActivity); $instance->setPreference('last_activity', $setting); return $setting; @@ -267,7 +264,7 @@ class Preferences $user = auth()->user(); if (null === $user) { // make new preference, return it: - $pref = new Preference(); + $pref = new Preference(); $pref->name = $name; $pref->data = $value; @@ -292,19 +289,19 @@ class Preferences public function setForUser(User $user, string $name, array|bool|int|string|null $value): Preference { - $fullName = sprintf('preference%s%s', $user->id, $name); - $userGroupId = $this->getUserGroupId($user, $name); - $userGroupId = 0 === (int)$userGroupId ? null : (int)$userGroupId; + $fullName = sprintf('preference%s%s', $user->id, $name); + $userGroupId = $this->getUserGroupId($user, $name); + $userGroupId = 0 === (int) $userGroupId ? null : (int) $userGroupId; Cache::forget($fullName); - $query = Preference::where('user_id', $user->id)->where('name', $name); + $query = Preference::where('user_id', $user->id)->where('name', $name); if (null !== $userGroupId) { Log::debug('Include user group ID in query'); $query->where('user_group_id', $userGroupId); } - $preference = $query->first(['id', 'user_id', 'user_group_id', 'name', 'data', 'updated_at', 'created_at']); + $preference = $query->first(['id', 'user_id', 'user_group_id', 'name', 'data', 'updated_at', 'created_at']); if (null !== $preference && null === $value) { $preference->delete(); @@ -315,11 +312,10 @@ class Preferences return new Preference(); } if (null === $preference) { - $preference = new Preference(); - $preference->user_id = (int)$user->id; + $preference = new Preference(); + $preference->user_id = (int) $user->id; $preference->user_group_id = $userGroupId; - $preference->name = $name; - + $preference->name = $name; } $preference->data = $value; $preference->save(); @@ -328,12 +324,12 @@ class Preferences return $preference; } - private function getUserGroupId(User $user, string $preferenceName): ?int + private function getUserGroupId(User $user, string $preferenceName): null|int { $groupId = null; $items = config('firefly.admin_specific_prefs') ?? []; if (in_array($preferenceName, $items, true)) { - return (int)$user->user_group_id; + return (int) $user->user_group_id; } return $groupId; diff --git a/app/Support/Report/Budget/BudgetReportGenerator.php b/app/Support/Report/Budget/BudgetReportGenerator.php index 0950a7c300..d421efa7f1 100644 --- a/app/Support/Report/Budget/BudgetReportGenerator.php +++ b/app/Support/Report/Budget/BudgetReportGenerator.php @@ -32,9 +32,9 @@ use FireflyIII\Repositories\Budget\BudgetLimitRepositoryInterface; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Repositories\Budget\NoBudgetRepositoryInterface; use FireflyIII\Repositories\Budget\OperationsRepositoryInterface; +use FireflyIII\Support\Facades\Amount; use FireflyIII\User; use Illuminate\Support\Collection; -use FireflyIII\Support\Facades\Amount; /** * Class BudgetReportGenerator @@ -43,26 +43,26 @@ use FireflyIII\Support\Facades\Amount; */ class BudgetReportGenerator { - private Collection $accounts; + private Collection $accounts; private readonly BudgetLimitRepositoryInterface $blRepository; - private Collection $budgets; - private TransactionCurrency $currency; - private Carbon $end; - private readonly NoBudgetRepositoryInterface $nbRepository; - private readonly OperationsRepositoryInterface $opsRepository; - private array $report = []; - private readonly BudgetRepositoryInterface $repository; - private Carbon $start; + private Collection $budgets; + private TransactionCurrency $currency; + private Carbon $end; + private readonly NoBudgetRepositoryInterface $nbRepository; + private readonly OperationsRepositoryInterface $opsRepository; + private array $report = []; + private readonly BudgetRepositoryInterface $repository; + private Carbon $start; /** * BudgetReportGenerator constructor. */ public function __construct() { - $this->repository = app(BudgetRepositoryInterface::class); - $this->blRepository = app(BudgetLimitRepositoryInterface::class); + $this->repository = app(BudgetRepositoryInterface::class); + $this->blRepository = app(BudgetLimitRepositoryInterface::class); $this->opsRepository = app(OperationsRepositoryInterface::class); - $this->nbRepository = app(NoBudgetRepositoryInterface::class); + $this->nbRepository = app(NoBudgetRepositoryInterface::class); } /** @@ -70,18 +70,13 @@ class BudgetReportGenerator */ public function accountPerBudget(): void { - $spent = $this->opsRepository->listExpenses($this->start, $this->end, $this->accounts, $this->budgets); + $spent = $this->opsRepository->listExpenses($this->start, $this->end, $this->accounts, $this->budgets); $this->report = []; /** @var Account $account */ foreach ($this->accounts as $account) { $accountId = $account->id; - $this->report[$accountId] ??= [ - 'name' => $account->name, - 'id' => $account->id, - 'iban' => $account->iban, - 'currencies' => [], - ]; + $this->report[$accountId] ??= ['name' => $account->name, 'id' => $account->id, 'iban' => $account->iban, 'currencies' => []]; } // loop expenses. @@ -96,10 +91,7 @@ class BudgetReportGenerator */ public function general(): void { - $this->report = [ - 'budgets' => [], - 'sums' => [], - ]; + $this->report = ['budgets' => [], 'sums' => []]; $this->generalBudgetReport(); $this->noBudgetReport(); @@ -159,23 +151,18 @@ class BudgetReportGenerator private function noBudgetReport(): void { // add no budget info. - $this->report['budgets'][0] = [ - 'budget_id' => null, - 'budget_name' => null, - 'no_budget' => true, - 'budget_limits' => [], - ]; + $this->report['budgets'][0] = ['budget_id' => null, 'budget_name' => null, 'no_budget' => true, 'budget_limits' => []]; - $noBudget = $this->nbRepository->sumExpenses($this->start, $this->end, $this->accounts); + $noBudget = $this->nbRepository->sumExpenses($this->start, $this->end, $this->accounts); foreach ($noBudget as $noBudgetEntry) { // currency information: - $nbCurrencyId = (int)($noBudgetEntry['currency_id'] ?? $this->currency->id); - $nbCurrencyCode = $noBudgetEntry['currency_code'] ?? $this->currency->code; - $nbCurrencyName = $noBudgetEntry['currency_name'] ?? $this->currency->name; - $nbCurrencySymbol = $noBudgetEntry['currency_symbol'] ?? $this->currency->symbol; - $nbCurrencyDp = $noBudgetEntry['currency_decimal_places'] ?? $this->currency->decimal_places; + $nbCurrencyId = (int) ($noBudgetEntry['currency_id'] ?? $this->currency->id); + $nbCurrencyCode = $noBudgetEntry['currency_code'] ?? $this->currency->code; + $nbCurrencyName = $noBudgetEntry['currency_name'] ?? $this->currency->name; + $nbCurrencySymbol = $noBudgetEntry['currency_symbol'] ?? $this->currency->symbol; + $nbCurrencyDp = $noBudgetEntry['currency_decimal_places'] ?? $this->currency->decimal_places; - $this->report['budgets'][0]['budget_limits'][] = [ + $this->report['budgets'][0]['budget_limits'][] = [ 'budget_limit_id' => null, 'start_date' => $this->start, 'end_date' => $this->end, @@ -189,20 +176,20 @@ class BudgetReportGenerator 'currency_code' => $nbCurrencyCode, 'currency_name' => $nbCurrencyName, 'currency_symbol' => $nbCurrencySymbol, - 'currency_decimal_places' => $nbCurrencyDp, + 'currency_decimal_places' => $nbCurrencyDp ]; - $this->report['sums'][$nbCurrencyId]['spent'] = bcadd($this->report['sums'][$nbCurrencyId]['spent'] ?? '0', (string)$noBudgetEntry['sum']); + $this->report['sums'][$nbCurrencyId]['spent'] = bcadd($this->report['sums'][$nbCurrencyId]['spent'] ?? '0', (string) $noBudgetEntry['sum']); // append currency info because it may be missing: - $this->report['sums'][$nbCurrencyId]['currency_id'] = $nbCurrencyId; - $this->report['sums'][$nbCurrencyId]['currency_code'] = $nbCurrencyCode; - $this->report['sums'][$nbCurrencyId]['currency_name'] = $nbCurrencyName; - $this->report['sums'][$nbCurrencyId]['currency_symbol'] = $nbCurrencySymbol; + $this->report['sums'][$nbCurrencyId]['currency_id'] = $nbCurrencyId; + $this->report['sums'][$nbCurrencyId]['currency_code'] = $nbCurrencyCode; + $this->report['sums'][$nbCurrencyId]['currency_name'] = $nbCurrencyName; + $this->report['sums'][$nbCurrencyId]['currency_symbol'] = $nbCurrencySymbol; $this->report['sums'][$nbCurrencyId]['currency_decimal_places'] = $nbCurrencyDp; // append other sums because they might be missing: $this->report['sums'][$nbCurrencyId]['overspent'] ??= '0'; - $this->report['sums'][$nbCurrencyId]['left'] ??= '0'; - $this->report['sums'][$nbCurrencyId]['budgeted'] ??= '0'; + $this->report['sums'][$nbCurrencyId]['left'] ??= '0'; + $this->report['sums'][$nbCurrencyId]['budgeted'] ??= '0'; } } @@ -214,24 +201,24 @@ class BudgetReportGenerator // make percentages based on total amount. foreach ($this->report['budgets'] as $budgetId => $data) { foreach ($data['budget_limits'] as $limitId => $entry) { - $budgetId = (int)$budgetId; - $limitId = (int)$limitId; - $currencyId = (int)$entry['currency_id']; - $spent = $entry['spent']; - $totalSpent = $this->report['sums'][$currencyId]['spent'] ?? '0'; - $spentPct = '0'; - $budgeted = $entry['budgeted']; - $totalBudgeted = $this->report['sums'][$currencyId]['budgeted'] ?? '0'; - $budgetedPct = '0'; + $budgetId = (int) $budgetId; + $limitId = (int) $limitId; + $currencyId = (int) $entry['currency_id']; + $spent = $entry['spent']; + $totalSpent = $this->report['sums'][$currencyId]['spent'] ?? '0'; + $spentPct = '0'; + $budgeted = $entry['budgeted']; + $totalBudgeted = $this->report['sums'][$currencyId]['budgeted'] ?? '0'; + $budgetedPct = '0'; - if (0 !== bccomp((string)$spent, '0') && 0 !== bccomp($totalSpent, '0')) { - $spentPct = round((float)bcmul(bcdiv((string)$spent, $totalSpent), '100')); + if (0 !== bccomp((string) $spent, '0') && 0 !== bccomp($totalSpent, '0')) { + $spentPct = round((float) bcmul(bcdiv((string) $spent, $totalSpent), '100')); } - if (0 !== bccomp((string)$budgeted, '0') && 0 !== bccomp($totalBudgeted, '0')) { - $budgetedPct = round((float)bcmul(bcdiv((string)$budgeted, $totalBudgeted), '100')); + if (0 !== bccomp((string) $budgeted, '0') && 0 !== bccomp($totalBudgeted, '0')) { + $budgetedPct = round((float) bcmul(bcdiv((string) $budgeted, $totalBudgeted), '100')); } $this->report['sums'][$currencyId]['budgeted'] ??= '0'; - $this->report['budgets'][$budgetId]['budget_limits'][$limitId]['spent_pct'] = $spentPct; + $this->report['budgets'][$budgetId]['budget_limits'][$limitId]['spent_pct'] = $spentPct; $this->report['budgets'][$budgetId]['budget_limits'][$limitId]['budgeted_pct'] = $budgetedPct; } } @@ -247,11 +234,11 @@ class BudgetReportGenerator 'budget_id' => $budgetId, 'budget_name' => $budget->name, 'no_budget' => false, - 'budget_limits' => [], + 'budget_limits' => [] ]; // get all budget limits for budget in period: - $limits = $this->blRepository->getBudgetLimits($budget, $this->start, $this->end); + $limits = $this->blRepository->getBudgetLimits($budget, $this->start, $this->end); /** @var BudgetLimit $limit */ foreach ($limits as $limit) { @@ -264,25 +251,25 @@ class BudgetReportGenerator */ private function processBudgetExpenses(array $expenses, array $budget): void { - $budgetId = (int)$budget['id']; - $currencyId = (int)$expenses['currency_id']; + $budgetId = (int) $budget['id']; + $currencyId = (int) $expenses['currency_id']; foreach ($budget['transaction_journals'] as $journal) { $sourceAccountId = $journal['source_account_id']; - $this->report[$sourceAccountId]['currencies'][$currencyId] - ??= [ - 'currency_id' => $expenses['currency_id'], - 'currency_symbol' => $expenses['currency_symbol'], - 'currency_name' => $expenses['currency_name'], - 'currency_decimal_places' => $expenses['currency_decimal_places'], - 'budgets' => [], - ]; + $this->report[$sourceAccountId]['currencies'][$currencyId] ??= [ + 'currency_id' => $expenses['currency_id'], + 'currency_symbol' => $expenses['currency_symbol'], + 'currency_name' => $expenses['currency_name'], + 'currency_decimal_places' => $expenses['currency_decimal_places'], + 'budgets' => [] + ]; - $this->report[$sourceAccountId]['currencies'][$currencyId]['budgets'][$budgetId] - ??= '0'; + $this->report[$sourceAccountId]['currencies'][$currencyId]['budgets'][$budgetId] ??= '0'; - $this->report[$sourceAccountId]['currencies'][$currencyId]['budgets'][$budgetId] - = bcadd($this->report[$sourceAccountId]['currencies'][$currencyId]['budgets'][$budgetId], (string)$journal['amount']); + $this->report[$sourceAccountId]['currencies'][$currencyId]['budgets'][$budgetId] = bcadd( + $this->report[$sourceAccountId]['currencies'][$currencyId]['budgets'][$budgetId], + (string) $journal['amount'] + ); } } @@ -301,14 +288,14 @@ class BudgetReportGenerator */ private function processLimit(Budget $budget, BudgetLimit $limit): void { - $budgetId = $budget->id; - $limitId = $limit->id; - $limitCurrency = $limit->transactionCurrency ?? $this->currency; - $currencyId = $limitCurrency->id; - $expenses = $this->opsRepository->sumExpenses($limit->start_date, $limit->end_date, $this->accounts, new Collection()->push($budget)); - $spent = $expenses[$currencyId]['sum'] ?? '0'; - $left = -1 === bccomp(bcadd($limit->amount, $spent), '0') ? '0' : bcadd($limit->amount, $spent); - $overspent = 1 === bccomp(bcmul($spent, '-1'), $limit->amount) ? bcadd($spent, $limit->amount) : '0'; + $budgetId = $budget->id; + $limitId = $limit->id; + $limitCurrency = $limit->transactionCurrency ?? $this->currency; + $currencyId = $limitCurrency->id; + $expenses = $this->opsRepository->sumExpenses($limit->start_date, $limit->end_date, $this->accounts, new Collection()->push($budget)); + $spent = $expenses[$currencyId]['sum'] ?? '0'; + $left = -1 === bccomp(bcadd($limit->amount, $spent), '0') ? '0' : bcadd($limit->amount, $spent); + $overspent = 1 === bccomp(bcmul($spent, '-1'), $limit->amount) ? bcadd($spent, $limit->amount) : '0'; $this->report['budgets'][$budgetId]['budget_limits'][$limitId] ??= [ 'budget_limit_id' => $limitId, @@ -324,25 +311,24 @@ class BudgetReportGenerator 'currency_code' => $limitCurrency->code, 'currency_name' => $limitCurrency->name, 'currency_symbol' => $limitCurrency->symbol, - 'currency_decimal_places' => $limitCurrency->decimal_places, + 'currency_decimal_places' => $limitCurrency->decimal_places ]; // make sum information: - $this->report['sums'][$currencyId] - ??= [ - 'budgeted' => '0', - 'spent' => '0', - 'left' => '0', - 'overspent' => '0', - 'currency_id' => $currencyId, - 'currency_code' => $limitCurrency->code, - 'currency_name' => $limitCurrency->name, - 'currency_symbol' => $limitCurrency->symbol, - 'currency_decimal_places' => $limitCurrency->decimal_places, - ]; - $this->report['sums'][$currencyId]['budgeted'] = bcadd((string)$this->report['sums'][$currencyId]['budgeted'], $limit->amount); - $this->report['sums'][$currencyId]['spent'] = bcadd((string)$this->report['sums'][$currencyId]['spent'], $spent); - $this->report['sums'][$currencyId]['left'] = bcadd((string)$this->report['sums'][$currencyId]['left'], bcadd($limit->amount, $spent)); - $this->report['sums'][$currencyId]['overspent'] = bcadd((string)$this->report['sums'][$currencyId]['overspent'], $overspent); + $this->report['sums'][$currencyId] ??= [ + 'budgeted' => '0', + 'spent' => '0', + 'left' => '0', + 'overspent' => '0', + 'currency_id' => $currencyId, + 'currency_code' => $limitCurrency->code, + 'currency_name' => $limitCurrency->name, + 'currency_symbol' => $limitCurrency->symbol, + 'currency_decimal_places' => $limitCurrency->decimal_places + ]; + $this->report['sums'][$currencyId]['budgeted'] = bcadd((string) $this->report['sums'][$currencyId]['budgeted'], $limit->amount); + $this->report['sums'][$currencyId]['spent'] = bcadd((string) $this->report['sums'][$currencyId]['spent'], $spent); + $this->report['sums'][$currencyId]['left'] = bcadd((string) $this->report['sums'][$currencyId]['left'], bcadd($limit->amount, $spent)); + $this->report['sums'][$currencyId]['overspent'] = bcadd((string) $this->report['sums'][$currencyId]['overspent'], $overspent); } } diff --git a/app/Support/Report/Category/CategoryReportGenerator.php b/app/Support/Report/Category/CategoryReportGenerator.php index 51570e7696..0373294d88 100644 --- a/app/Support/Report/Category/CategoryReportGenerator.php +++ b/app/Support/Report/Category/CategoryReportGenerator.php @@ -35,19 +35,19 @@ use Illuminate\Support\Collection; */ class CategoryReportGenerator { - private Collection $accounts; - private Carbon $end; + private Collection $accounts; + private Carbon $end; private readonly NoCategoryRepositoryInterface $noCatRepository; private readonly OperationsRepositoryInterface $opsRepository; - private array $report; - private Carbon $start; + private array $report; + private Carbon $start; /** * CategoryReportGenerator constructor. */ public function __construct() { - $this->opsRepository = app(OperationsRepositoryInterface::class); + $this->opsRepository = app(OperationsRepositoryInterface::class); $this->noCatRepository = app(NoCategoryRepositoryInterface::class); } @@ -62,20 +62,17 @@ class CategoryReportGenerator */ public function operations(): void { - $earnedWith = $this->opsRepository->listIncome($this->start, $this->end, $this->accounts); - $spentWith = $this->opsRepository->listExpenses($this->start, $this->end, $this->accounts); + $earnedWith = $this->opsRepository->listIncome($this->start, $this->end, $this->accounts); + $spentWith = $this->opsRepository->listExpenses($this->start, $this->end, $this->accounts); // also transferred out and transferred into these accounts in this category: $transferredIn = $this->opsRepository->listTransferredIn($this->start, $this->end, $this->accounts); $transferredOut = $this->opsRepository->listTransferredOut($this->start, $this->end, $this->accounts); - $earnedWithout = $this->noCatRepository->listIncome($this->start, $this->end, $this->accounts); - $spentWithout = $this->noCatRepository->listExpenses($this->start, $this->end, $this->accounts); + $earnedWithout = $this->noCatRepository->listIncome($this->start, $this->end, $this->accounts); + $spentWithout = $this->noCatRepository->listExpenses($this->start, $this->end, $this->accounts); - $this->report = [ - 'categories' => [], - 'sums' => [], - ]; + $this->report = ['categories' => [], 'sums' => []]; // needs four for-each loops. foreach ([$earnedWith, $spentWith, $earnedWithout, $spentWithout, $transferredIn, $transferredOut] as $data) { @@ -117,35 +114,31 @@ class CategoryReportGenerator 'currency_decimal_places' => $currencyRow['currency_decimal_places'], 'spent' => '0', 'earned' => '0', - 'sum' => '0', + 'sum' => '0' ]; // loop journals: foreach ($categoryRow['transaction_journals'] as $journal) { // sum of sums - $this->report['sums'][$currencyId]['sum'] = bcadd((string)$this->report['sums'][$currencyId]['sum'], (string)$journal['amount']); + $this->report['sums'][$currencyId]['sum'] = bcadd((string) $this->report['sums'][$currencyId]['sum'], (string) $journal['amount']); // sum of spent: - $this->report['sums'][$currencyId]['spent'] = -1 === bccomp((string)$journal['amount'], '0') ? bcadd( - (string)$this->report['sums'][$currencyId]['spent'], - (string)$journal['amount'] - ) : $this->report['sums'][$currencyId]['spent']; + $this->report['sums'][$currencyId]['spent'] = -1 === bccomp((string) $journal['amount'], '0') + ? bcadd((string) $this->report['sums'][$currencyId]['spent'], (string) $journal['amount']) + : $this->report['sums'][$currencyId]['spent']; // sum of earned - $this->report['sums'][$currencyId]['earned'] = 1 === bccomp((string)$journal['amount'], '0') ? bcadd( - (string)$this->report['sums'][$currencyId]['earned'], - (string)$journal['amount'] - ) : $this->report['sums'][$currencyId]['earned']; + $this->report['sums'][$currencyId]['earned'] = 1 === bccomp((string) $journal['amount'], '0') + ? bcadd((string) $this->report['sums'][$currencyId]['earned'], (string) $journal['amount']) + : $this->report['sums'][$currencyId]['earned']; // sum of category - $this->report['categories'][$key]['sum'] = bcadd((string)$this->report['categories'][$key]['sum'], (string)$journal['amount']); + $this->report['categories'][$key]['sum'] = bcadd((string) $this->report['categories'][$key]['sum'], (string) $journal['amount']); // total spent in category - $this->report['categories'][$key]['spent'] = -1 === bccomp((string)$journal['amount'], '0') ? bcadd( - (string)$this->report['categories'][$key]['spent'], - (string)$journal['amount'] - ) : $this->report['categories'][$key]['spent']; + $this->report['categories'][$key]['spent'] = -1 === bccomp((string) $journal['amount'], '0') + ? bcadd((string) $this->report['categories'][$key]['spent'], (string) $journal['amount']) + : $this->report['categories'][$key]['spent']; // total earned in category - $this->report['categories'][$key]['earned'] = 1 === bccomp((string)$journal['amount'], '0') ? bcadd( - (string)$this->report['categories'][$key]['earned'], - (string)$journal['amount'] - ) : $this->report['categories'][$key]['earned']; + $this->report['categories'][$key]['earned'] = 1 === bccomp((string) $journal['amount'], '0') + ? bcadd((string) $this->report['categories'][$key]['earned'], (string) $journal['amount']) + : $this->report['categories'][$key]['earned']; } } @@ -159,7 +152,7 @@ class CategoryReportGenerator 'currency_symbol' => $currencyRow['currency_symbol'], 'currency_name' => $currencyRow['currency_name'], 'currency_code' => $currencyRow['currency_code'], - 'currency_decimal_places' => $currencyRow['currency_decimal_places'], + 'currency_decimal_places' => $currencyRow['currency_decimal_places'] ]; /** diff --git a/app/Support/Report/Summarizer/TransactionSummarizer.php b/app/Support/Report/Summarizer/TransactionSummarizer.php index 921d897857..e117ffdf8b 100644 --- a/app/Support/Report/Summarizer/TransactionSummarizer.php +++ b/app/Support/Report/Summarizer/TransactionSummarizer.php @@ -36,7 +36,7 @@ class TransactionSummarizer private TransactionCurrency $default; private User $user; - public function __construct(?User $user = null) + public function __construct(null|User $user = null) { if ($user instanceof User) { $this->setUser($user); @@ -48,14 +48,14 @@ class TransactionSummarizer Log::debug(sprintf('Now in groupByCurrencyId([%d journals], "%s", %s)', count($journals), $method, var_export($includeForeign, true))); $array = []; foreach ($journals as $journal) { - $field = 'amount'; + $field = 'amount'; // grab default currency information. - $currencyId = (int) $journal['currency_id']; - $currencyName = $journal['currency_name']; - $currencySymbol = $journal['currency_symbol']; - $currencyCode = $journal['currency_code']; - $currencyDecimalPlaces = $journal['currency_decimal_places']; + $currencyId = (int) $journal['currency_id']; + $currencyName = $journal['currency_name']; + $currencySymbol = $journal['currency_symbol']; + $currencyCode = $journal['currency_code']; + $currencyDecimalPlaces = $journal['currency_decimal_places']; // prepare foreign currency info: $foreignCurrencyId = 0; @@ -106,14 +106,14 @@ class TransactionSummarizer } // first process normal amount - $amount = (string) ($journal[$field] ?? '0'); + $amount = (string) ($journal[$field] ?? '0'); $array[$currencyId] ??= [ 'sum' => '0', 'currency_id' => $currencyId, 'currency_name' => $currencyName, 'currency_symbol' => $currencySymbol, 'currency_code' => $currencyCode, - 'currency_decimal_places' => $currencyDecimalPlaces, + 'currency_decimal_places' => $currencyDecimalPlaces ]; if ('positive' === $method) { @@ -132,7 +132,7 @@ class TransactionSummarizer 'currency_name' => $foreignCurrencyName, 'currency_symbol' => $foreignCurrencySymbol, 'currency_code' => $foreignCurrencyCode, - 'currency_decimal_places' => $foreignCurrencyDecimalPlaces, + 'currency_decimal_places' => $foreignCurrencyDecimalPlaces ]; if ('positive' === $method) { @@ -181,7 +181,7 @@ class TransactionSummarizer if ($convertToPrimary && $journal['currency_id'] !== $primary->id && $primary->id === $journal['foreign_currency_id']) { $field = 'foreign_amount'; } - $key = sprintf('%s-%s', $journal[$idKey], $currencyId); + $key = sprintf('%s-%s', $journal[$idKey], $currencyId); // sum it all up or create a new array. $array[$key] ??= [ 'id' => $journal[$idKey], @@ -191,11 +191,11 @@ class TransactionSummarizer 'currency_name' => $currencyName, 'currency_symbol' => $currencySymbol, 'currency_code' => $currencyCode, - 'currency_decimal_places' => $currencyDecimalPlaces, + 'currency_decimal_places' => $currencyDecimalPlaces ]; // add the data from the $field to the array. - $array[$key]['sum'] = bcadd($array[$key]['sum'], (string) Steam::{$method}((string) ($journal[$field] ?? '0'))); // @phpstan-ignore-line + $array[$key]['sum'] = bcadd($array[$key]['sum'], (string) Steam::{$method}((string) ($journal[$field] ?? '0'))); // @phpstan-ignore-line Log::debug(sprintf( 'Field for transaction #%d is "%s" (%s). Sum: %s', $journal['transaction_group_id'], @@ -214,7 +214,7 @@ class TransactionSummarizer $journal['foreign_amount'], $array[$key]['sum'] )); - $key = sprintf('%s-%s', $journal[$idKey], $journal['foreign_currency_id']); + $key = sprintf('%s-%s', $journal[$idKey], $journal['foreign_currency_id']); $array[$key] ??= [ 'id' => $journal[$idKey], 'name' => $journal[$nameKey], @@ -223,7 +223,7 @@ class TransactionSummarizer 'currency_name' => $journal['foreign_currency_name'], 'currency_symbol' => $journal['foreign_currency_symbol'], 'currency_code' => $journal['foreign_currency_code'], - 'currency_decimal_places' => $journal['foreign_currency_decimal_places'], + 'currency_decimal_places' => $journal['foreign_currency_decimal_places'] ]; $array[$key]['sum'] = bcadd($array[$key]['sum'], (string) Steam::{$method}((string) $journal['foreign_amount'])); // @phpstan-ignore-line } @@ -240,8 +240,8 @@ class TransactionSummarizer public function setUser(User $user): void { - $this->user = $user; - $this->default = Amount::getPrimaryCurrencyByUserGroup($user->userGroup); + $this->user = $user; + $this->default = Amount::getPrimaryCurrencyByUserGroup($user->userGroup); $this->convertToPrimary = Amount::convertToPrimary($user); } } diff --git a/app/Support/Repositories/Recurring/CalculateRangeOccurrences.php b/app/Support/Repositories/Recurring/CalculateRangeOccurrences.php index f9fd9994ee..f333bda663 100644 --- a/app/Support/Repositories/Recurring/CalculateRangeOccurrences.php +++ b/app/Support/Repositories/Recurring/CalculateRangeOccurrences.php @@ -24,8 +24,8 @@ declare(strict_types=1); namespace FireflyIII\Support\Repositories\Recurring; -use Illuminate\Support\Facades\Log; use Carbon\Carbon; +use Illuminate\Support\Facades\Log; /** * Trait CalculateRangeOccurrences @@ -41,7 +41,7 @@ trait CalculateRangeOccurrences $return = []; $attempts = 0; while ($start <= $end) { - if (0 === $attempts % $skipMod) { + if (0 === ($attempts % $skipMod)) { $return[] = clone $start; } $start->addDay(); @@ -59,15 +59,15 @@ trait CalculateRangeOccurrences { $return = []; $attempts = 0; - $dayOfMonth = (int)$moment; + $dayOfMonth = (int) $moment; if ($start->day > $dayOfMonth) { // day has passed already, add a month. $start->addMonth(); } while ($start < $end) { $domCorrected = min($dayOfMonth, $start->daysInMonth); - $start->day = $domCorrected; - if (0 === $attempts % $skipMod && $start->lte($start) && $end->gte($start)) { + $start->day = $domCorrected; + if (0 === ($attempts % $skipMod) && $start->lte($start) && $end->gte($start)) { $return[] = clone $start; } ++$attempts; @@ -83,8 +83,8 @@ trait CalculateRangeOccurrences */ protected function getNdomInRange(Carbon $start, Carbon $end, int $skipMod, string $moment): array { - $return = []; - $attempts = 0; + $return = []; + $attempts = 0; $start->startOfMonth(); // this feels a bit like a cop out but why reinvent the wheel? $counters = [1 => 'first', 2 => 'second', 3 => 'third', 4 => 'fourth', 5 => 'fifth']; @@ -93,7 +93,7 @@ trait CalculateRangeOccurrences while ($start <= $end) { $string = sprintf('%s %s of %s %s', $counters[$parts[0]], $daysOfWeek[$parts[1]], $start->format('F'), $start->format('Y')); $newCarbon = new Carbon($string); - if (0 === $attempts % $skipMod) { + if (0 === ($attempts % $skipMod)) { $return[] = clone $newCarbon; } ++$attempts; @@ -109,12 +109,12 @@ trait CalculateRangeOccurrences */ protected function getWeeklyInRange(Carbon $start, Carbon $end, int $skipMod, string $moment): array { - $return = []; - $attempts = 0; + $return = []; + $attempts = 0; Log::debug('Rep is weekly.'); // monday = 1 // sunday = 7 - $dayOfWeek = (int)$moment; + $dayOfWeek = (int) $moment; Log::debug(sprintf('DoW in repetition is %d, in mutator is %d', $dayOfWeek, $start->dayOfWeekIso)); if ($start->dayOfWeekIso > $dayOfWeek) { // day has already passed this week, add one week: @@ -128,7 +128,7 @@ trait CalculateRangeOccurrences $start->addDays($dayDifference); Log::debug(sprintf('Mutator is now: %s', $start->format('Y-m-d'))); while ($start <= $end) { - if (0 === $attempts % $skipMod && $start->lte($start) && $end->gte($start)) { + if (0 === ($attempts % $skipMod) && $start->lte($start) && $end->gte($start)) { Log::debug('Date is in range of start+end, add to set.'); $return[] = clone $start; } @@ -146,19 +146,19 @@ trait CalculateRangeOccurrences */ protected function getYearlyInRange(Carbon $start, Carbon $end, int $skipMod, string $moment): array { - $attempts = 0; - $date = new Carbon($moment); + $attempts = 0; + $date = new Carbon($moment); $date->year = $start->year; - $return = []; + $return = []; if ($start > $date) { $date->addYear(); } // is $date between $start and $end? - $obj = clone $date; - $count = 0; + $obj = clone $date; + $count = 0; while ($obj <= $end && $obj >= $start && $count < 10) { - if (0 === $attempts % $skipMod) { + if (0 === ($attempts % $skipMod)) { $return[] = clone $obj; } $obj->addYears(); diff --git a/app/Support/Repositories/Recurring/CalculateXOccurrences.php b/app/Support/Repositories/Recurring/CalculateXOccurrences.php index f31171810f..fc871155f1 100644 --- a/app/Support/Repositories/Recurring/CalculateXOccurrences.php +++ b/app/Support/Repositories/Recurring/CalculateXOccurrences.php @@ -43,7 +43,7 @@ trait CalculateXOccurrences $attempts = 0; while ($total < $count) { $mutator->addDay(); - if (0 === $attempts % $skipMod) { + if (0 === ($attempts % $skipMod)) { $return[] = clone $mutator; ++$total; } @@ -63,7 +63,7 @@ trait CalculateXOccurrences $mutator = clone $date; $total = 0; $attempts = 0; - $dayOfMonth = (int)$moment; + $dayOfMonth = (int) $moment; if ($mutator->day > $dayOfMonth) { // day has passed already, add a month. $mutator->addMonth(); @@ -72,7 +72,7 @@ trait CalculateXOccurrences while ($total < $count) { $domCorrected = min($dayOfMonth, $mutator->daysInMonth); $mutator->day = $domCorrected; - if (0 === $attempts % $skipMod) { + if (0 === ($attempts % $skipMod)) { $return[] = clone $mutator; ++$total; } @@ -89,10 +89,10 @@ trait CalculateXOccurrences */ protected function getXNDomOccurrences(Carbon $date, int $count, int $skipMod, string $moment): array { - $return = []; - $total = 0; - $attempts = 0; - $mutator = clone $date; + $return = []; + $total = 0; + $attempts = 0; + $mutator = clone $date; $mutator->addDay(); // always assume today has passed. $mutator->startOfMonth(); // this feels a bit like a cop out but why reinvent the wheel? @@ -103,7 +103,7 @@ trait CalculateXOccurrences while ($total < $count) { $string = sprintf('%s %s of %s %s', $counters[$parts[0]], $daysOfWeek[$parts[1]], $mutator->format('F'), $mutator->format('Y')); $newCarbon = new Carbon($string); - if (0 === $attempts % $skipMod) { + if (0 === ($attempts % $skipMod)) { $return[] = clone $newCarbon; ++$total; } @@ -120,14 +120,14 @@ trait CalculateXOccurrences */ protected function getXWeeklyOccurrences(Carbon $date, int $count, int $skipMod, string $moment): array { - $return = []; - $total = 0; - $attempts = 0; - $mutator = clone $date; + $return = []; + $total = 0; + $attempts = 0; + $mutator = clone $date; // monday = 1 // sunday = 7 $mutator->addDay(); // always assume today has passed. - $dayOfWeek = (int)$moment; + $dayOfWeek = (int) $moment; if ($mutator->dayOfWeekIso > $dayOfWeek) { // day has already passed this week, add one week: $mutator->addWeek(); @@ -138,7 +138,7 @@ trait CalculateXOccurrences $mutator->addDays($dayDifference); while ($total < $count) { - if (0 === $attempts % $skipMod) { + if (0 === ($attempts % $skipMod)) { $return[] = clone $mutator; ++$total; } @@ -155,18 +155,18 @@ trait CalculateXOccurrences */ protected function getXYearlyOccurrences(Carbon $date, int $count, int $skipMod, string $moment): array { - $return = []; - $mutator = clone $date; - $total = 0; - $attempts = 0; - $date = new Carbon($moment); + $return = []; + $mutator = clone $date; + $total = 0; + $attempts = 0; + $date = new Carbon($moment); $date->year = $mutator->year; if ($mutator > $date) { $date->addYear(); } - $obj = clone $date; + $obj = clone $date; while ($total < $count) { - if (0 === $attempts % $skipMod) { + if (0 === ($attempts % $skipMod)) { $return[] = clone $obj; ++$total; } diff --git a/app/Support/Repositories/Recurring/CalculateXOccurrencesSince.php b/app/Support/Repositories/Recurring/CalculateXOccurrencesSince.php index ccef5770ca..828e0eb949 100644 --- a/app/Support/Repositories/Recurring/CalculateXOccurrencesSince.php +++ b/app/Support/Repositories/Recurring/CalculateXOccurrencesSince.php @@ -44,7 +44,7 @@ trait CalculateXOccurrencesSince $total = 0; $attempts = 0; while ($total < $count) { - if (0 === $attempts % $skipMod && $mutator->gt($afterDate)) { + if (0 === ($attempts % $skipMod) && $mutator->gt($afterDate)) { $return[] = clone $mutator; ++$total; } @@ -68,7 +68,7 @@ trait CalculateXOccurrencesSince $mutator = clone $date; $total = 0; $attempts = 0; - $dayOfMonth = (int)$moment; + $dayOfMonth = (int) $moment; $dayOfMonth = 0 === $dayOfMonth ? 1 : $dayOfMonth; if ($mutator->day > $dayOfMonth) { Log::debug(sprintf('%d is after %d, add a month. Mutator is now...', $mutator->day, $dayOfMonth)); @@ -81,13 +81,13 @@ trait CalculateXOccurrencesSince $domCorrected = min($dayOfMonth, $mutator->daysInMonth); $mutator->day = $domCorrected; $mutator->setTime(0, 0); - if (0 === $attempts % $skipMod && $mutator->gte($afterDate)) { + if (0 === ($attempts % $skipMod) && $mutator->gte($afterDate)) { Log::debug(sprintf('Mutator is now %s and is added to the list.', $mutator->toAtomString())); $return[] = clone $mutator; ++$total; } ++$attempts; - $mutator = $mutator->endOfMonth()->addDay(); + $mutator = $mutator->endOfMonth()->addDay(); } Log::debug('Collected enough occurrences.'); @@ -103,10 +103,10 @@ trait CalculateXOccurrencesSince protected function getXNDomOccurrencesSince(Carbon $date, Carbon $afterDate, int $count, int $skipMod, string $moment): array { Log::debug(sprintf('Now in %s', __METHOD__)); - $return = []; - $total = 0; - $attempts = 0; - $mutator = clone $date; + $return = []; + $total = 0; + $attempts = 0; + $mutator = clone $date; $mutator->addDay(); // always assume today has passed. $mutator->startOfMonth(); // this feels a bit like a cop out but why reinvent the wheel? @@ -117,7 +117,7 @@ trait CalculateXOccurrencesSince while ($total < $count) { $string = sprintf('%s %s of %s %s', $counters[$parts[0]], $daysOfWeek[$parts[1]], $mutator->format('F'), $mutator->format('Y')); $newCarbon = new Carbon($string); - if (0 === $attempts % $skipMod && $mutator->gte($afterDate)) { + if (0 === ($attempts % $skipMod) && $mutator->gte($afterDate)) { $return[] = clone $newCarbon; ++$total; } @@ -137,15 +137,15 @@ trait CalculateXOccurrencesSince protected function getXWeeklyOccurrencesSince(Carbon $date, Carbon $afterDate, int $count, int $skipMod, string $moment): array { Log::debug(sprintf('Now in %s', __METHOD__)); - $return = []; - $total = 0; - $attempts = 0; - $mutator = clone $date; + $return = []; + $total = 0; + $attempts = 0; + $mutator = clone $date; // monday = 1 // sunday = 7 // Removed assumption today has passed, see issue https://github.com/firefly-iii/firefly-iii/issues/4798 // $mutator->addDay(); // always assume today has passed. - $dayOfWeek = (int)$moment; + $dayOfWeek = (int) $moment; if ($mutator->dayOfWeekIso > $dayOfWeek) { // day has already passed this week, add one week: $mutator->addWeek(); @@ -156,7 +156,7 @@ trait CalculateXOccurrencesSince $mutator->addDays($dayDifference); while ($total < $count) { - if (0 === $attempts % $skipMod && $mutator->gte($afterDate)) { + if (0 === ($attempts % $skipMod) && $mutator->gte($afterDate)) { $return[] = clone $mutator; ++$total; } @@ -176,25 +176,28 @@ trait CalculateXOccurrencesSince protected function getXYearlyOccurrencesSince(Carbon $date, Carbon $afterDate, int $count, int $skipMod, string $moment): array { Log::debug(sprintf('Now in %s(%s, %d, %d, %s)', __METHOD__, $date->format('Y-m-d'), $date->format('Y-m-d'), $count, $skipMod)); - $return = []; - $mutator = clone $date; - $total = 0; - $attempts = 0; - $date = new Carbon($moment); + $return = []; + $mutator = clone $date; + $total = 0; + $attempts = 0; + $date = new Carbon($moment); $date->year = $mutator->year; if ($mutator > $date) { - Log::debug( - sprintf('mutator (%s) > date (%s), so add a year to date (%s)', $mutator->format('Y-m-d'), $date->format('Y-m-d'), $date->format('Y-m-d')) - ); + Log::debug(sprintf( + 'mutator (%s) > date (%s), so add a year to date (%s)', + $mutator->format('Y-m-d'), + $date->format('Y-m-d'), + $date->format('Y-m-d') + )); $date->addYear(); Log::debug(sprintf('Date is now %s', $date->format('Y-m-d'))); } - $obj = clone $date; + $obj = clone $date; while ($total < $count) { Log::debug(sprintf('total (%d) < count (%d) so go.', $total, $count)); Log::debug(sprintf('attempts (%d) %% skipmod (%d) === %d', $attempts, $skipMod, $attempts % $skipMod)); Log::debug(sprintf('Obj (%s) gte afterdate (%s)? %s', $obj->format('Y-m-d'), $afterDate->format('Y-m-d'), var_export($obj->gte($afterDate), true))); - if (0 === $attempts % $skipMod && $obj->gte($afterDate)) { + if (0 === ($attempts % $skipMod) && $obj->gte($afterDate)) { Log::debug('All conditions true, add obj.'); $return[] = clone $obj; ++$total; diff --git a/app/Support/Repositories/Recurring/FiltersWeekends.php b/app/Support/Repositories/Recurring/FiltersWeekends.php index 508e13f638..753befdfb7 100644 --- a/app/Support/Repositories/Recurring/FiltersWeekends.php +++ b/app/Support/Repositories/Recurring/FiltersWeekends.php @@ -46,7 +46,7 @@ trait FiltersWeekends return $dates; } - $return = []; + $return = []; /** @var Carbon $date */ foreach ($dates as $date) { @@ -60,11 +60,13 @@ trait FiltersWeekends // is weekend and must set back to Friday? if (RecurrenceRepetitionWeekend::WEEKEND_TO_FRIDAY->value === $repetition->weekend) { - $clone = clone $date; + $clone = clone $date; $clone->addDays(5 - $date->dayOfWeekIso); - Log::debug( - sprintf('Date is %s, and this is in the weekend, so corrected to %s (Friday).', $date->format('D d M Y'), $clone->format('D d M Y')) - ); + Log::debug(sprintf( + 'Date is %s, and this is in the weekend, so corrected to %s (Friday).', + $date->format('D d M Y'), + $clone->format('D d M Y') + )); $return[] = clone $clone; continue; @@ -72,14 +74,16 @@ trait FiltersWeekends // postpone to Monday? if (RecurrenceRepetitionWeekend::WEEKEND_TO_MONDAY->value === $repetition->weekend) { - $clone = clone $date; + $clone = clone $date; $clone->addDays(8 - $date->dayOfWeekIso); - Log::debug( - sprintf('Date is %s, and this is in the weekend, so corrected to %s (Monday).', $date->format('D d M Y'), $clone->format('D d M Y')) - ); + Log::debug(sprintf( + 'Date is %s, and this is in the weekend, so corrected to %s (Monday).', + $date->format('D d M Y'), + $clone->format('D d M Y') + )); $return[] = $clone; - } + // Log::debug(sprintf('Date is %s, removed from final result', $date->format('D d M Y'))); } diff --git a/app/Support/Repositories/UserGroup/UserGroupInterface.php b/app/Support/Repositories/UserGroup/UserGroupInterface.php index d7a737b919..82e8f6ccd6 100644 --- a/app/Support/Repositories/UserGroup/UserGroupInterface.php +++ b/app/Support/Repositories/UserGroup/UserGroupInterface.php @@ -33,9 +33,9 @@ interface UserGroupInterface { public function checkUserGroupAccess(UserRoleEnum $role): bool; - public function getUser(): ?User; + public function getUser(): null|User; - public function getUserGroup(): ?UserGroup; + public function getUserGroup(): null|UserGroup; public function setUser(Authenticatable|User|null $user): void; diff --git a/app/Support/Repositories/UserGroup/UserGroupTrait.php b/app/Support/Repositories/UserGroup/UserGroupTrait.php index 6a4a958917..6940fe5ac6 100644 --- a/app/Support/Repositories/UserGroup/UserGroupTrait.php +++ b/app/Support/Repositories/UserGroup/UserGroupTrait.php @@ -37,8 +37,8 @@ use Illuminate\Support\Facades\Log; */ trait UserGroupTrait { - protected ?User $user = null; - protected ?UserGroup $userGroup = null; + protected null|User $user = null; + protected null|UserGroup $userGroup = null; public function checkUserGroupAccess(UserRoleEnum $role): bool { @@ -53,7 +53,7 @@ trait UserGroupTrait return false; } - public function getUser(): ?User + public function getUser(): null|User { return $this->user; } @@ -64,7 +64,7 @@ trait UserGroupTrait public function setUser(Authenticatable|User|null $user): void { if ($user instanceof User) { - $this->user = $user; + $this->user = $user; if (null === $user->userGroup) { throw new FireflyException(sprintf('User #%d ("%s") has no user group.', $user->id, $user->email)); } @@ -77,7 +77,7 @@ trait UserGroupTrait throw new FireflyException(sprintf('Object is %s, not User.', $class)); } - public function getUserGroup(): ?UserGroup + public function getUserGroup(): null|UserGroup { return $this->userGroup; } @@ -98,16 +98,13 @@ trait UserGroupTrait */ public function setUserGroupById(int $userGroupId): void { - $memberships = GroupMembership::where('user_id', $this->user->id) - ->where('user_group_id', $userGroupId) - ->count() - ; + $memberships = GroupMembership::where('user_id', $this->user->id)->where('user_group_id', $userGroupId)->count(); if (0 === $memberships) { throw new FireflyException(sprintf('User #%d has no access to administration #%d', $this->user->id, $userGroupId)); } /** @var null|UserGroup $userGroup */ - $userGroup = UserGroup::find($userGroupId); + $userGroup = UserGroup::find($userGroupId); if (null === $userGroup) { throw new FireflyException(sprintf('Cannot find administration for user #%d', $this->user->id)); } diff --git a/app/Support/Request/AppendsLocationData.php b/app/Support/Request/AppendsLocationData.php index bcad45157d..74112ad460 100644 --- a/app/Support/Request/AppendsLocationData.php +++ b/app/Support/Request/AppendsLocationData.php @@ -39,9 +39,9 @@ trait AppendsLocationData $lat = $information['latitude'] ?? null; if (null !== $long && null !== $lat && $this->validLongitude($long) && $this->validLatitude($lat)) { $return['store_location'] = true; - $return['longitude'] = $information['longitude']; - $return['latitude'] = $information['latitude']; - $return['zoom_level'] = $information['zoom_level']; + $return['longitude'] = $information['longitude']; + $return['latitude'] = $information['latitude']; + $return['zoom_level'] = $information['zoom_level']; } } @@ -88,58 +88,56 @@ trait AppendsLocationData /** * Read the submitted Request data and add new or updated Location data to the array. */ - protected function appendLocationData(array $data, ?string $prefix): array + protected function appendLocationData(array $data, null|string $prefix): array { Log::debug(sprintf('Now in appendLocationData("%s")', $prefix), $data); - $data['store_location'] = false; + $data['store_location'] = false; $data['update_location'] = false; $data['remove_location'] = false; - $data['longitude'] = null; - $data['latitude'] = null; - $data['zoom_level'] = null; + $data['longitude'] = null; + $data['latitude'] = null; + $data['zoom_level'] = null; - $longitudeKey = $this->getLocationKey($prefix, 'longitude'); - $latitudeKey = $this->getLocationKey($prefix, 'latitude'); - $zoomLevelKey = $this->getLocationKey($prefix, 'zoom_level'); - $isValidPOST = $this->isValidPost($prefix); - $isValidPUT = $this->isValidPUT($prefix); - $isValidEmptyPUT = $this->isValidEmptyPUT($prefix); + $longitudeKey = $this->getLocationKey($prefix, 'longitude'); + $latitudeKey = $this->getLocationKey($prefix, 'latitude'); + $zoomLevelKey = $this->getLocationKey($prefix, 'zoom_level'); + $isValidPOST = $this->isValidPost($prefix); + $isValidPUT = $this->isValidPUT($prefix); + $isValidEmptyPUT = $this->isValidEmptyPUT($prefix); // for a POST (store), all fields must be present and not NULL. if ($isValidPOST) { Log::debug('Method is POST and all fields present and not NULL.'); $data['store_location'] = true; - $data['longitude'] = $this->convertString($longitudeKey); - $data['latitude'] = $this->convertString($latitudeKey); - $data['zoom_level'] = $this->convertString($zoomLevelKey); + $data['longitude'] = $this->convertString($longitudeKey); + $data['latitude'] = $this->convertString($latitudeKey); + $data['zoom_level'] = $this->convertString($zoomLevelKey); } // for a PUT (api update) or POST update (UI) if ($isValidPUT) { Log::debug('Method is PUT and all fields present and not NULL.'); $data['update_location'] = true; - $data['longitude'] = $this->convertString($longitudeKey); - $data['latitude'] = $this->convertString($latitudeKey); - $data['zoom_level'] = $this->convertString($zoomLevelKey); + $data['longitude'] = $this->convertString($longitudeKey); + $data['latitude'] = $this->convertString($latitudeKey); + $data['zoom_level'] = $this->convertString($zoomLevelKey); } if ($isValidEmptyPUT) { Log::debug('Method is PUT and all fields present and NULL.'); $data['remove_location'] = true; } Log::debug(sprintf('Returning longitude: "%s", latitude: "%s", zoom level: "%s"', $data['longitude'], $data['latitude'], $data['zoom_level'])); - Log::debug( - sprintf( - 'Returning actions: store: %s, update: %s, delete: %s', - var_export($data['store_location'], true), - var_export($data['update_location'], true), - var_export($data['remove_location'], true), - ) - ); + Log::debug(sprintf( + 'Returning actions: store: %s, update: %s, delete: %s', + var_export($data['store_location'], true), + var_export($data['update_location'], true), + var_export($data['remove_location'], true) + )); return $data; } - private function getLocationKey(?string $prefix, string $key): string + private function getLocationKey(null|string $prefix, string $key): string { if (null === $prefix) { return $key; @@ -148,7 +146,7 @@ trait AppendsLocationData return sprintf('%s_%s', $prefix, $key); } - private function isValidEmptyPUT(?string $prefix): bool + private function isValidEmptyPUT(null|string $prefix): bool { $longitudeKey = $this->getLocationKey($prefix, 'longitude'); $latitudeKey = $this->getLocationKey($prefix, 'latitude'); @@ -157,14 +155,12 @@ trait AppendsLocationData return ( null === $this->get($longitudeKey) && null === $this->get($latitudeKey) - && null === $this->get($zoomLevelKey)) - && ( - 'PUT' === $this->method() - || ('POST' === $this->method() && $this->routeIs('*.update')) - ); + && null === $this->get($zoomLevelKey) + && ('PUT' === $this->method() || 'POST' === $this->method() && $this->routeIs('*.update')) + ); } - private function isValidPUT(?string $prefix): bool + private function isValidPUT(null|string $prefix): bool { $longitudeKey = $this->getLocationKey($prefix, 'longitude'); $latitudeKey = $this->getLocationKey($prefix, 'latitude'); @@ -204,7 +200,7 @@ trait AppendsLocationData return false; } - private function isValidPost(?string $prefix): bool + private function isValidPost(null|string $prefix): bool { Log::debug('Now in isValidPost()'); $longitudeKey = $this->getLocationKey($prefix, 'longitude'); @@ -244,14 +240,14 @@ trait AppendsLocationData private function validLatitude(string $latitude): bool { - $number = (float)$latitude; + $number = (float) $latitude; return $number >= -90 && $number <= 90; } private function validLongitude(string $longitude): bool { - $number = (float)$longitude; + $number = (float) $longitude; return $number >= -180 && $number <= 180; } diff --git a/app/Support/Request/ChecksLogin.php b/app/Support/Request/ChecksLogin.php index 2781c131db..905e1a9424 100644 --- a/app/Support/Request/ChecksLogin.php +++ b/app/Support/Request/ChecksLogin.php @@ -24,10 +24,10 @@ declare(strict_types=1); namespace FireflyIII\Support\Request; -use Illuminate\Support\Facades\Log; use FireflyIII\Enums\UserRoleEnum; use FireflyIII\Models\UserGroup; use FireflyIII\User; +use Illuminate\Support\Facades\Log; /** * Trait ChecksLogin @@ -41,7 +41,7 @@ trait ChecksLogin { Log::debug(sprintf('Now in %s', __METHOD__)); // Only allow logged-in users - $check = auth()->check(); + $check = auth()->check(); if (!$check) { return false; } @@ -77,22 +77,22 @@ trait ChecksLogin * Will throw exception if invalid. * TODO duplicated in JSONAPI code. */ - public function getUserGroup(): ?UserGroup + public function getUserGroup(): null|UserGroup { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); Log::debug('Now in getUserGroup()'); /** @var null|UserGroup $userGroup */ $userGroup = $this->route()?->parameter('userGroup'); if (null === $userGroup) { Log::debug('Request class has no userGroup parameter, but perhaps there is a parameter.'); - $userGroupId = (int)$this->get('user_group_id'); + $userGroupId = (int) $this->get('user_group_id'); if (0 === $userGroupId) { Log::debug(sprintf('Request class has no user_group_id parameter, grab default from user (group #%d).', $user->user_group_id)); - $userGroupId = (int)$user->user_group_id; + $userGroupId = (int) $user->user_group_id; } - $userGroup = UserGroup::find($userGroupId); + $userGroup = UserGroup::find($userGroupId); if (null === $userGroup) { Log::error(sprintf('Request class has user_group_id (#%d), but group does not exist.', $userGroupId)); diff --git a/app/Support/Request/ConvertsDataTypes.php b/app/Support/Request/ConvertsDataTypes.php index 8b13aefa74..e325adf055 100644 --- a/app/Support/Request/ConvertsDataTypes.php +++ b/app/Support/Request/ConvertsDataTypes.php @@ -39,67 +39,66 @@ use function Safe\preg_replace; */ trait ConvertsDataTypes { - private array $characters - = [ - "\0", // NUL - "\f", // form feed - "\v", // vertical tab - "\u{0001}", // start of heading - "\u{0002}", // start of text - "\u{0003}", // end of text - "\u{0004}", // end of transmission - "\u{0005}", // enquiry - "\u{0006}", // ACK - "\u{0007}", // BEL - "\u{0008}", // backspace - "\u{000E}", // shift out - "\u{000F}", // shift in - "\u{0010}", // data link escape - "\u{0011}", // DC1 - "\u{0012}", // DC2 - "\u{0013}", // DC3 - "\u{0014}", // DC4 - "\u{0015}", // NAK - "\u{0016}", // SYN - "\u{0017}", // ETB - "\u{0018}", // CAN - "\u{0019}", // EM - "\u{001A}", // SUB - "\u{001B}", // escape - "\u{001C}", // file separator - "\u{001D}", // group separator - "\u{001E}", // record separator - "\u{001F}", // unit separator - "\u{007F}", // DEL - "\u{00A0}", // non-breaking space - "\u{1680}", // ogham space mark - "\u{180E}", // mongolian vowel separator - "\u{2000}", // en quad - "\u{2001}", // em quad - "\u{2002}", // en space - "\u{2003}", // em space - "\u{2004}", // three-per-em space - "\u{2005}", // four-per-em space - "\u{2006}", // six-per-em space - "\u{2007}", // figure space - "\u{2008}", // punctuation space - "\u{2009}", // thin space - "\u{200A}", // hair space - "\u{200B}", // zero width space - "\u{202F}", // narrow no-break space - "\u{3000}", // ideographic space - "\u{FEFF}", // zero width no -break space - "\r", // carriage return - ]; + private array $characters = [ + "\0", // NUL + "\f", // form feed + "\v", // vertical tab + "\u{0001}", // start of heading + "\u{0002}", // start of text + "\u{0003}", // end of text + "\u{0004}", // end of transmission + "\u{0005}", // enquiry + "\u{0006}", // ACK + "\u{0007}", // BEL + "\u{0008}", // backspace + "\u{000E}", // shift out + "\u{000F}", // shift in + "\u{0010}", // data link escape + "\u{0011}", // DC1 + "\u{0012}", // DC2 + "\u{0013}", // DC3 + "\u{0014}", // DC4 + "\u{0015}", // NAK + "\u{0016}", // SYN + "\u{0017}", // ETB + "\u{0018}", // CAN + "\u{0019}", // EM + "\u{001A}", // SUB + "\u{001B}", // escape + "\u{001C}", // file separator + "\u{001D}", // group separator + "\u{001E}", // record separator + "\u{001F}", // unit separator + "\u{007F}", // DEL + "\u{00A0}", // non-breaking space + "\u{1680}", // ogham space mark + "\u{180E}", // mongolian vowel separator + "\u{2000}", // en quad + "\u{2001}", // em quad + "\u{2002}", // en space + "\u{2003}", // em space + "\u{2004}", // three-per-em space + "\u{2005}", // four-per-em space + "\u{2006}", // six-per-em space + "\u{2007}", // figure space + "\u{2008}", // punctuation space + "\u{2009}", // thin space + "\u{200A}", // hair space + "\u{200B}", // zero width space + "\u{202F}", // narrow no-break space + "\u{3000}", // ideographic space + "\u{FEFF}", // zero width no -break space + "\r" // carriage return + ]; - public function clearIban(?string $string): ?string + public function clearIban(null|string $string): null|string { $string = $this->clearString($string); return Steam::filterSpaces($string); } - public function clearString(?string $string): ?string + public function clearString(null|string $string): null|string { $string = $this->clearStringKeepNewlines($string); @@ -116,7 +115,7 @@ trait ConvertsDataTypes return trim($string); } - public function clearStringKeepNewlines(?string $string): ?string + public function clearStringKeepNewlines(null|string $string): null|string { if (null === $string) { return null; @@ -142,21 +141,21 @@ trait ConvertsDataTypes */ public function convertInteger(string $field): int { - return (int)$this->get($field); + return (int) $this->get($field); } public function convertSortParameters(string $field, string $class): array { // assume this all works, because the validator would have caught any errors. - $parameter = (string)request()->query->get($field); + $parameter = (string) request()->query->get($field); if ('' === $parameter) { return []; } $parts = explode(',', $parameter); $sortParameters = []; foreach ($parts as $part) { - $part = trim($part); - $direction = 'asc'; + $part = trim($part); + $direction = 'asc'; if ('-' === $part[0]) { $part = substr($part, 1); $direction = 'desc'; @@ -177,7 +176,7 @@ trait ConvertsDataTypes return $default; } - return (string)$this->clearString((string)$entry); + return (string) $this->clearString((string) $entry); } /** @@ -208,7 +207,7 @@ trait ConvertsDataTypes $collection = new Collection(); if (is_array($set)) { foreach ($set as $accountId) { - $account = $repository->find((int)$accountId); + $account = $repository->find((int) $accountId); if (null !== $account) { $collection->push($account); } @@ -233,13 +232,13 @@ trait ConvertsDataTypes */ public function stringWithNewlines(string $field): string { - return (string)$this->clearStringKeepNewlines((string)($this->get($field) ?? '')); + return (string) $this->clearStringKeepNewlines((string) ($this->get($field) ?? '')); } /** * @param mixed $array */ - protected function arrayFromValue($array): ?array + protected function arrayFromValue($array): null|array { if (is_array($array)) { return $array; @@ -254,7 +253,7 @@ trait ConvertsDataTypes return null; } - protected function convertBoolean(?string $value): bool + protected function convertBoolean(null|string $value): bool { if (null === $value) { return false; @@ -278,16 +277,16 @@ trait ConvertsDataTypes return '1' === $value; } - protected function convertDateTime(?string $string): ?Carbon + protected function convertDateTime(null|string $string): null|Carbon { - $value = $this->get((string)$string); + $value = $this->get((string) $string); if (null === $value) { return null; } if ('' === $value) { return null; } - if (10 === strlen((string)$value)) { + if (10 === strlen((string) $value)) { // probably a date format. try { $carbon = Carbon::createFromFormat('Y-m-d', $value, config('app.timezone')); @@ -329,20 +328,19 @@ trait ConvertsDataTypes /** * Return floating value. */ - protected function convertFloat(string $field): ?float + protected function convertFloat(string $field): null|float { $res = $this->get($field); if (null === $res) { return null; } - return (float)$res; + return (float) $res; } - protected function dateFromValue(?string $string): ?Carbon + protected function dateFromValue(null|string $string): null|Carbon { if (null === $string) { - return null; } if ('' === $string) { @@ -365,7 +363,7 @@ trait ConvertsDataTypes return $carbon; } - protected function floatFromValue(?string $string): ?float + protected function floatFromValue(null|string $string): null|float { if (null === $string) { return null; @@ -374,7 +372,7 @@ trait ConvertsDataTypes return null; } - return (float)$string; + return (float) $string; } /** @@ -386,7 +384,7 @@ trait ConvertsDataTypes $return = []; foreach ($fields as $field => $info) { if (true === $this->has($info[0])) { - $method = $info[1]; + $method = $info[1]; $return[$field] = $this->{$method}($info[0]); // @phpstan-ignore-line } } @@ -397,9 +395,9 @@ trait ConvertsDataTypes /** * Return date or NULL. */ - protected function getCarbonDate(string $field): ?Carbon + protected function getCarbonDate(string $field): null|Carbon { - $data = (string)$this->get($field); + $data = (string) $this->get($field); Log::debug(sprintf('Date string is "%s"', $data)); if ('' === $data) { @@ -419,7 +417,7 @@ trait ConvertsDataTypes /** * Parse to integer */ - protected function integerFromValue(?string $string): ?int + protected function integerFromValue(null|string $string): null|int { if (null === $string) { return null; @@ -428,24 +426,24 @@ trait ConvertsDataTypes return null; } - return (int)$string; + return (int) $string; } /** * Return integer value, or NULL when it's not set. */ - protected function nullableInteger(string $field): ?int + protected function nullableInteger(string $field): null|int { if (false === $this->has($field)) { return null; } - $value = (string)$this->get($field); + $value = (string) $this->get($field); if ('' === $value) { return null; } - return (int)$value; + return (int) $value; } protected function parseAccounts(mixed $array): array @@ -458,9 +456,9 @@ trait ConvertsDataTypes if (!is_array($entry)) { continue; } - $amount = null; + $amount = null; if (array_key_exists('current_amount', $entry)) { - $amount = $this->clearString((string)($entry['current_amount'] ?? '0')); + $amount = $this->clearString((string) ($entry['current_amount'] ?? '0')); if (null === $entry['current_amount']) { $amount = null; } @@ -468,10 +466,7 @@ trait ConvertsDataTypes if (!array_key_exists('current_amount', $entry)) { $amount = null; } - $return[] = [ - 'account_id' => $this->integerFromValue((string)($entry['account_id'] ?? '0')), - 'current_amount' => $amount, - ]; + $return[] = ['account_id' => $this->integerFromValue((string) ($entry['account_id'] ?? '0')), 'current_amount' => $amount]; } return $return; diff --git a/app/Support/Request/GetRecurrenceData.php b/app/Support/Request/GetRecurrenceData.php index 40f23738dd..50dc0cd8f2 100644 --- a/app/Support/Request/GetRecurrenceData.php +++ b/app/Support/Request/GetRecurrenceData.php @@ -38,12 +38,12 @@ trait GetRecurrenceData foreach ($stringKeys as $key) { if (array_key_exists($key, $transaction)) { - $return[$key] = (string)$transaction[$key]; + $return[$key] = (string) $transaction[$key]; } } foreach ($intKeys as $key) { if (array_key_exists($key, $transaction)) { - $return[$key] = (int)$transaction[$key]; + $return[$key] = (int) $transaction[$key]; } } foreach ($keys as $key) { diff --git a/app/Support/Request/ValidatesWebhooks.php b/app/Support/Request/ValidatesWebhooks.php index 38ad9cb9e9..711cbc7f56 100644 --- a/app/Support/Request/ValidatesWebhooks.php +++ b/app/Support/Request/ValidatesWebhooks.php @@ -1,6 +1,5 @@ after( - static function (Validator $validator): void { - Log::debug('Validating webhook'); - if (count($validator->failed()) > 0) { + $validator->after(static function (Validator $validator): void { + Log::debug('Validating webhook'); + if (count($validator->failed()) > 0) { + return; + } + $data = $validator->getData(); + $triggers = $data['triggers'] ?? []; + $responses = $data['responses'] ?? []; + + if (0 === count($triggers) || 0 === count($responses)) { + Log::debug('No trigger or response, return.'); + + return; + } + $validTriggers = array_values(Webhook::getTriggers()); + $validResponses = array_values(Webhook::getResponses()); + $containsAny = false; + $count = 0; + foreach ($triggers as $trigger) { + if (!in_array($trigger, $validTriggers, true)) { return; } - $data = $validator->getData(); - $triggers = $data['triggers'] ?? []; - $responses = $data['responses'] ?? []; - - if (0 === count($triggers) || 0 === count($responses)) { - Log::debug('No trigger or response, return.'); + ++$count; + if ($trigger === WebhookTrigger::ANY->name) { + $containsAny = true; + } + } + if ($containsAny && $count > 1) { + $validator->errors()->add('triggers.0', trans('validation.only_any_trigger')); + return; + } + foreach ($responses as $response) { + if (!in_array($response, $validResponses, true)) { return; } - $validTriggers = array_values(Webhook::getTriggers()); - $validResponses = array_values(Webhook::getResponses()); - $containsAny = false; - $count = 0; - foreach ($triggers as $trigger) { - if (!in_array($trigger, $validTriggers, true)) { + } + // some combinations are illegal. + foreach ($triggers as $i => $trigger) { + $forbidden = config(sprintf('webhooks.forbidden_responses.%s', $trigger)); + if (null === $forbidden) { + $validator->errors()->add(sprintf('triggers.%d', $i), trans('validation.unknown_webhook_trigger', ['trigger' => $trigger])); + + continue; + } + foreach ($responses as $ii => $response) { + if (in_array($response, $forbidden, true)) { + Log::debug(sprintf('Trigger %s and response %s are forbidden.', $trigger, $response)); + $validator->errors()->add( + sprintf('responses.%d', $ii), + trans('validation.bad_webhook_combination', ['trigger' => $trigger, 'response' => $response]) + ); + return; } - ++$count; - if ($trigger === WebhookTrigger::ANY->name) { - $containsAny = true; - } - } - if ($containsAny && $count > 1) { - $validator->errors()->add('triggers.0', trans('validation.only_any_trigger')); - - return; - } - foreach ($responses as $response) { - if (!in_array($response, $validResponses, true)) { - return; - } - } - // some combinations are illegal. - foreach ($triggers as $i => $trigger) { - $forbidden = config(sprintf('webhooks.forbidden_responses.%s', $trigger)); - if (null === $forbidden) { - $validator->errors()->add(sprintf('triggers.%d', $i), trans('validation.unknown_webhook_trigger', ['trigger' => $trigger])); - - continue; - } - foreach ($responses as $ii => $response) { - if (in_array($response, $forbidden, true)) { - Log::debug(sprintf('Trigger %s and response %s are forbidden.', $trigger, $response)); - $validator->errors()->add(sprintf('responses.%d', $ii), trans('validation.bad_webhook_combination', ['trigger' => $trigger, 'response' => $response])); - - return; - } - } } } - ); + }); } } diff --git a/app/Support/Search/AccountSearch.php b/app/Support/Search/AccountSearch.php index 9fbaa27e37..8e556410e2 100644 --- a/app/Support/Search/AccountSearch.php +++ b/app/Support/Search/AccountSearch.php @@ -36,53 +36,50 @@ use function Safe\json_encode; */ class AccountSearch implements GenericSearchInterface { - public const string SEARCH_ALL = 'all'; + public const string SEARCH_ALL = 'all'; - public const string SEARCH_IBAN = 'iban'; + public const string SEARCH_IBAN = 'iban'; - public const string SEARCH_ID = 'id'; + public const string SEARCH_ID = 'id'; - public const string SEARCH_NAME = 'name'; + public const string SEARCH_NAME = 'name'; public const string SEARCH_NUMBER = 'number'; + private string $field; private string $query; - private array $types = []; - private User $user; + private array $types = []; + private User $user; public function search(): Collection { - $searchQuery = $this->user->accounts() + $searchQuery = $this->user + ->accounts() ->leftJoin('account_types', 'accounts.account_type_id', '=', 'account_types.id') ->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id') - ->whereIn('account_types.type', $this->types) - ; + ->whereIn('account_types.type', $this->types); $like = sprintf('%%%s%%', $this->query); $originalQuery = $this->query; switch ($this->field) { default: case self::SEARCH_ALL: - $searchQuery->where( - static function (Builder $q) use ($like): void { - $q->whereLike('accounts.id', $like); - $q->orWhereLike('accounts.name', $like); - $q->orWhereLike('accounts.iban', $like); - } - ); + $searchQuery->where(static function (Builder $q) use ($like): void { + $q->whereLike('accounts.id', $like); + $q->orWhereLike('accounts.name', $like); + $q->orWhereLike('accounts.iban', $like); + }); // meta data: - $searchQuery->orWhere( - static function (Builder $q) use ($originalQuery): void { - $json = json_encode($originalQuery, JSON_THROW_ON_ERROR); - $q->where('account_meta.name', '=', 'account_number'); - $q->whereLike('account_meta.data', $json); - } - ); + $searchQuery->orWhere(static function (Builder $q) use ($originalQuery): void { + $json = json_encode($originalQuery, JSON_THROW_ON_ERROR); + $q->where('account_meta.name', '=', 'account_number'); + $q->whereLike('account_meta.data', $json); + }); break; case self::SEARCH_ID: - $searchQuery->where('accounts.id', '=', (int)$originalQuery); + $searchQuery->where('accounts.id', '=', (int) $originalQuery); break; @@ -98,13 +95,11 @@ class AccountSearch implements GenericSearchInterface case self::SEARCH_NUMBER: // meta data: - $searchQuery->Where( - static function (Builder $q) use ($originalQuery): void { - $json = json_encode($originalQuery, JSON_THROW_ON_ERROR); - $q->where('account_meta.name', 'account_number'); - $q->where('account_meta.data', $json); - } - ); + $searchQuery->Where(static function (Builder $q) use ($originalQuery): void { + $json = json_encode($originalQuery, JSON_THROW_ON_ERROR); + $q->where('account_meta.name', 'account_number'); + $q->where('account_meta.data', $json); + }); break; } diff --git a/app/Support/Search/OperatorQuerySearch.php b/app/Support/Search/OperatorQuerySearch.php index e05be49745..bfb5d22d3e 100644 --- a/app/Support/Search/OperatorQuerySearch.php +++ b/app/Support/Search/OperatorQuerySearch.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Support\Search; -use FireflyIII\Support\Facades\Preferences; use Carbon\Carbon; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Enums\SearchDirection; @@ -40,6 +39,8 @@ use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Repositories\Category\CategoryRepositoryInterface; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\Repositories\Tag\TagRepositoryInterface; +use FireflyIII\Support\Facades\Preferences; +use FireflyIII\Support\Facades\Steam; use FireflyIII\Support\ParseDateString; use FireflyIII\Support\Search\QueryParser\FieldNode; use FireflyIII\Support\Search\QueryParser\Node; @@ -52,7 +53,6 @@ use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; use LogicException; use TypeError; -use FireflyIII\Support\Facades\Steam; /** * Class OperatorQuerySearch @@ -61,26 +61,26 @@ use FireflyIII\Support\Facades\Steam; */ class OperatorQuerySearch implements SearchInterface { - protected Carbon $date; - private readonly AccountRepositoryInterface $accountRepository; - private readonly BillRepositoryInterface $billRepository; - private readonly BudgetRepositoryInterface $budgetRepository; + protected Carbon $date; + private readonly AccountRepositoryInterface $accountRepository; + private readonly BillRepositoryInterface $billRepository; + private readonly BudgetRepositoryInterface $budgetRepository; private readonly CategoryRepositoryInterface $categoryRepository; - private GroupCollectorInterface $collector; + private GroupCollectorInterface $collector; private readonly CurrencyRepositoryInterface $currencyRepository; - private array $excludeTags = []; - private array $includeAnyTags = []; + private array $excludeTags = []; + private array $includeAnyTags = []; // added to fix #8632 - private array $includeTags = []; - private array $invalidOperators = []; - private int $limit = 25; - private readonly Collection $operators; - private int $page = 1; - private array $prohibitedWords = []; - private readonly float $startTime; + private array $includeTags = []; + private array $invalidOperators = []; + private int $limit = 25; + private readonly Collection $operators; + private int $page = 1; + private array $prohibitedWords = []; + private readonly float $startTime; private readonly TagRepositoryInterface $tagRepository; - private readonly array $validOperators; - private array $words = []; + private readonly array $validOperators; + private array $words = []; /** * OperatorQuerySearch constructor. @@ -88,14 +88,14 @@ class OperatorQuerySearch implements SearchInterface public function __construct() { Log::debug('Constructed OperatorQuerySearch'); - $this->operators = new Collection(); - $this->validOperators = array_keys(config('search.operators')); - $this->startTime = microtime(true); - $this->accountRepository = app(AccountRepositoryInterface::class); + $this->operators = new Collection(); + $this->validOperators = array_keys(config('search.operators')); + $this->startTime = microtime(true); + $this->accountRepository = app(AccountRepositoryInterface::class); $this->categoryRepository = app(CategoryRepositoryInterface::class); - $this->budgetRepository = app(BudgetRepositoryInterface::class); - $this->billRepository = app(BillRepositoryInterface::class); - $this->tagRepository = app(TagRepositoryInterface::class); + $this->budgetRepository = app(BudgetRepositoryInterface::class); + $this->billRepository = app(BillRepositoryInterface::class); + $this->tagRepository = app(TagRepositoryInterface::class); $this->currencyRepository = app(CurrencyRepositoryInterface::class); } @@ -111,7 +111,7 @@ class OperatorQuerySearch implements SearchInterface $operator = substr($operator, 1); } - $config = config(sprintf('search.operators.%s', $operator)); + $config = config(sprintf('search.operators.%s', $operator)); if (null === $config) { throw new FireflyException(sprintf('No configuration for search operator "%s"', $operator)); } @@ -238,12 +238,15 @@ class OperatorQuerySearch implements SearchInterface $this->tagRepository->setUser($user); $this->collector = app(GroupCollectorInterface::class); $this->collector->setUser($user); - $this->collector->withAccountInformation()->withCategoryInformation()->withBudgetInformation(); + $this->collector + ->withAccountInformation() + ->withCategoryInformation() + ->withBudgetInformation(); - $this->setLimit((int)Preferences::getForUser($user, 'listPageSize', 50)->data); + $this->setLimit((int) Preferences::getForUser($user, 'listPageSize', 50)->data); } - private function findCurrency(string $value): ?TransactionCurrency + private function findCurrency(string $value): null|TransactionCurrency { if (str_contains($value, '(') && str_contains($value, ')')) { // bad method to split and get the currency code: @@ -272,7 +275,7 @@ class OperatorQuerySearch implements SearchInterface $value = $node->getValue(); $prohibited = $node->isProhibited($flipProhibitedFlag); - $context = config(sprintf('search.operators.%s.needs_context', $operator)); + $context = config(sprintf('search.operators.%s.needs_context', $operator)); // is an operator that needs no context, and value is false, then prohibited = true. if ('false' === $value && in_array($operator, $this->validOperators, true) && false === $context && !$prohibited) { @@ -286,21 +289,14 @@ class OperatorQuerySearch implements SearchInterface } // must be valid operator: - $inArray = in_array($operator, $this->validOperators, true); + $inArray = in_array($operator, $this->validOperators, true); if ($inArray && $this->updateCollector($operator, $value, $prohibited)) { - $this->operators->push([ - 'type' => self::getRootOperator($operator), - 'value' => $value, - 'prohibited' => $prohibited, - ]); + $this->operators->push(['type' => self::getRootOperator($operator), 'value' => $value, 'prohibited' => $prohibited]); Log::debug(sprintf('Added operator type "%s"', $operator)); } if (!$inArray) { Log::debug(sprintf('Added INVALID operator type "%s"', $operator)); - $this->invalidOperators[] = [ - 'type' => $operator, - 'value' => $value, - ]; + $this->invalidOperators[] = ['type' => $operator, 'value' => $value]; } } @@ -347,7 +343,7 @@ class OperatorQuerySearch implements SearchInterface private function handleStringNode(StringNode $node, bool $flipProhibitedFlag): void { - $string = $node->getValue(); + $string = $node->getValue(); $prohibited = $node->isProhibited($flipProhibitedFlag); @@ -372,17 +368,12 @@ class OperatorQuerySearch implements SearchInterface $parsedDate = $parser->parseDate($value); } catch (FireflyException) { Log::debug(sprintf('Could not parse date "%s", will return empty array.', $value)); - $this->invalidOperators[] = [ - 'type' => $type, - 'value' => $value, - ]; + $this->invalidOperators[] = ['type' => $type, 'value' => $value]; return []; } - return [ - 'exact' => $parsedDate, - ]; + return ['exact' => $parsedDate]; } private function parseTagInstructions(): void @@ -442,7 +433,13 @@ class OperatorQuerySearch implements SearchInterface Log::debug(sprintf('searchAccount("%s", %s, %s)', $value, $stringPosition->name, $searchDirection->name)); // search direction (default): for source accounts - $searchTypes = [AccountTypeEnum::ASSET->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::REVENUE->value]; + $searchTypes = [ + AccountTypeEnum::ASSET->value, + AccountTypeEnum::MORTGAGE->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::REVENUE->value + ]; $collectorMethod = 'setSourceAccounts'; if ($prohibited) { $collectorMethod = 'excludeSourceAccounts'; @@ -451,7 +448,13 @@ class OperatorQuerySearch implements SearchInterface // search direction: for destination accounts if (SearchDirection::DESTINATION === $searchDirection) { // destination // destination can be - $searchTypes = [AccountTypeEnum::ASSET->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::EXPENSE->value]; + $searchTypes = [ + AccountTypeEnum::ASSET->value, + AccountTypeEnum::MORTGAGE->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::EXPENSE->value + ]; $collectorMethod = 'setDestinationAccounts'; if ($prohibited) { $collectorMethod = 'excludeDestinationAccounts'; @@ -459,14 +462,21 @@ class OperatorQuerySearch implements SearchInterface } // either account could be: if (SearchDirection::BOTH === $searchDirection) { - $searchTypes = [AccountTypeEnum::ASSET->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::EXPENSE->value, AccountTypeEnum::REVENUE->value]; + $searchTypes = [ + AccountTypeEnum::ASSET->value, + AccountTypeEnum::MORTGAGE->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::EXPENSE->value, + AccountTypeEnum::REVENUE->value + ]; $collectorMethod = 'setAccounts'; if ($prohibited) { $collectorMethod = 'excludeAccounts'; } } // string position (default): starts with: - $stringMethod = 'str_starts_with'; + $stringMethod = 'str_starts_with'; // string position: ends with: if (StringPosition::ENDS === $stringPosition) { @@ -480,7 +490,7 @@ class OperatorQuerySearch implements SearchInterface } // get accounts: - $accounts = $this->accountRepository->searchAccount($value, $searchTypes, 1337); + $accounts = $this->accountRepository->searchAccount($value, $searchTypes, 1337); if (0 === $accounts->count() && false === $prohibited) { Log::warning('Found zero accounts, search for non existing account, NO results will be returned.'); $this->collector->findNothing(); @@ -493,9 +503,7 @@ class OperatorQuerySearch implements SearchInterface return; } Log::debug(sprintf('Found %d accounts, will filter.', $accounts->count())); - $filtered = $accounts->filter( - static fn (Account $account): bool => $stringMethod(strtolower($account->name), strtolower($value)) - ); + $filtered = $accounts->filter(static fn(Account $account): bool => $stringMethod(strtolower($account->name), strtolower($value))); if (0 === $filtered->count()) { Log::warning('Left with zero accounts, so cannot find anything, NO results will be returned.'); @@ -520,7 +528,13 @@ class OperatorQuerySearch implements SearchInterface Log::debug(sprintf('searchAccountNr(%s, %d, %d)', $value, $searchDirection->name, $stringPosition->name)); // search direction (default): for source accounts - $searchTypes = [AccountTypeEnum::ASSET->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::REVENUE->value]; + $searchTypes = [ + AccountTypeEnum::ASSET->value, + AccountTypeEnum::MORTGAGE->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::REVENUE->value + ]; $collectorMethod = 'setSourceAccounts'; if ($prohibited) { $collectorMethod = 'excludeSourceAccounts'; @@ -529,7 +543,13 @@ class OperatorQuerySearch implements SearchInterface // search direction: for destination accounts if (SearchDirection::DESTINATION === $searchDirection) { // destination can be - $searchTypes = [AccountTypeEnum::ASSET->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::EXPENSE->value]; + $searchTypes = [ + AccountTypeEnum::ASSET->value, + AccountTypeEnum::MORTGAGE->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::EXPENSE->value + ]; $collectorMethod = 'setDestinationAccounts'; if ($prohibited) { $collectorMethod = 'excludeDestinationAccounts'; @@ -538,7 +558,14 @@ class OperatorQuerySearch implements SearchInterface // either account could be: if (SearchDirection::BOTH === $searchDirection) { - $searchTypes = [AccountTypeEnum::ASSET->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::EXPENSE->value, AccountTypeEnum::REVENUE->value]; + $searchTypes = [ + AccountTypeEnum::ASSET->value, + AccountTypeEnum::MORTGAGE->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::EXPENSE->value, + AccountTypeEnum::REVENUE->value + ]; $collectorMethod = 'setAccounts'; if ($prohibited) { $collectorMethod = 'excludeAccounts'; @@ -546,7 +573,7 @@ class OperatorQuerySearch implements SearchInterface } // string position (default): starts with: - $stringMethod = 'str_starts_with'; + $stringMethod = 'str_starts_with'; // string position: ends with: if (StringPosition::ENDS === $stringPosition) { @@ -560,7 +587,7 @@ class OperatorQuerySearch implements SearchInterface } // search for accounts: - $accounts = $this->accountRepository->searchAccountNr($value, $searchTypes, 1337); + $accounts = $this->accountRepository->searchAccountNr($value, $searchTypes, 1337); if (0 === $accounts->count()) { Log::debug('Found zero accounts, search for invalid account.'); Log::warning('Call to findNothing() from searchAccountNr().'); @@ -571,22 +598,20 @@ class OperatorQuerySearch implements SearchInterface // if found, do filter Log::debug(sprintf('Found %d accounts, will filter.', $accounts->count())); - $filtered = $accounts->filter( - static function (Account $account) use ($value, $stringMethod): bool { - // either IBAN or account number - $ibanMatch = $stringMethod(strtolower((string)$account->iban), strtolower($value)); - $accountNrMatch = false; + $filtered = $accounts->filter(static function (Account $account) use ($value, $stringMethod): bool { + // either IBAN or account number + $ibanMatch = $stringMethod(strtolower((string) $account->iban), strtolower($value)); + $accountNrMatch = false; - /** @var AccountMeta $meta */ - foreach ($account->accountMeta as $meta) { - if ('account_number' === $meta->name && $stringMethod(strtolower((string)$meta->data), strtolower($value))) { - $accountNrMatch = true; - } + /** @var AccountMeta $meta */ + foreach ($account->accountMeta as $meta) { + if ('account_number' === $meta->name && $stringMethod(strtolower((string) $meta->data), strtolower($value))) { + $accountNrMatch = true; } - - return $ibanMatch || $accountNrMatch; } - ); + + return $ibanMatch || $accountNrMatch; + }); if (0 === $filtered->count()) { Log::debug('Left with zero, search for invalid account'); @@ -620,7 +645,7 @@ class OperatorQuerySearch implements SearchInterface case 'exact': if ($value instanceof Carbon) { $this->collector->setAfter($value); - $this->operators->push(['type' => 'date_after', 'value' => $value->format('Y-m-d')]); + $this->operators->push(['type' => 'date_after', 'value' => $value->format('Y-m-d')]); } break; @@ -629,7 +654,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set date_is_after YEAR value "%s"', $value)); $this->collector->yearAfter($value); - $this->operators->push(['type' => 'date_after_year', 'value' => $value]); + $this->operators->push(['type' => 'date_after_year', 'value' => $value]); } break; @@ -638,7 +663,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set date_is_after MONTH value "%s"', $value)); $this->collector->monthAfter($value); - $this->operators->push(['type' => 'date_after_month', 'value' => $value]); + $this->operators->push(['type' => 'date_after_month', 'value' => $value]); } break; @@ -647,7 +672,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set date_is_after DAY value "%s"', $value)); $this->collector->dayAfter($value); - $this->operators->push(['type' => 'date_after_day', 'value' => $value]); + $this->operators->push(['type' => 'date_after_day', 'value' => $value]); } break; @@ -676,7 +701,7 @@ class OperatorQuerySearch implements SearchInterface case 'exact': if ($value instanceof Carbon) { $this->collector->setBefore($value); - $this->operators->push(['type' => 'date_before', 'value' => $value->format('Y-m-d')]); + $this->operators->push(['type' => 'date_before', 'value' => $value->format('Y-m-d')]); } break; @@ -685,7 +710,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set date_is_before YEAR value "%s"', $value)); $this->collector->yearBefore($value); - $this->operators->push(['type' => 'date_before_year', 'value' => $value]); + $this->operators->push(['type' => 'date_before_year', 'value' => $value]); } break; @@ -694,7 +719,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set date_is_before MONTH value "%s"', $value)); $this->collector->monthBefore($value); - $this->operators->push(['type' => 'date_before_month', 'value' => $value]); + $this->operators->push(['type' => 'date_before_month', 'value' => $value]); } break; @@ -703,7 +728,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set date_is_before DAY value "%s"', $value)); $this->collector->dayBefore($value); - $this->operators->push(['type' => 'date_before_day', 'value' => $value]); + $this->operators->push(['type' => 'date_before_day', 'value' => $value]); } break; @@ -733,7 +758,7 @@ class OperatorQuerySearch implements SearchInterface if ($value instanceof Carbon) { Log::debug(sprintf('Set date_is_exact value "%s"', $value->format('Y-m-d'))); $this->collector->setRange($value, $value); - $this->operators->push(['type' => 'date_on', 'value' => $value->format('Y-m-d')]); + $this->operators->push(['type' => 'date_on', 'value' => $value->format('Y-m-d')]); } break; @@ -741,7 +766,7 @@ class OperatorQuerySearch implements SearchInterface case 'exact_not': if ($value instanceof Carbon) { $this->collector->excludeRange($value, $value); - $this->operators->push(['type' => 'not_date_on', 'value' => $value->format('Y-m-d')]); + $this->operators->push(['type' => 'not_date_on', 'value' => $value->format('Y-m-d')]); } break; @@ -750,7 +775,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set date_is_exact YEAR value "%s"', $value)); $this->collector->yearIs($value); - $this->operators->push(['type' => 'date_on_year', 'value' => $value]); + $this->operators->push(['type' => 'date_on_year', 'value' => $value]); } break; @@ -759,7 +784,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set date_is_exact_not YEAR value "%s"', $value)); $this->collector->yearIsNot($value); - $this->operators->push(['type' => 'not_date_on_year', 'value' => $value]); + $this->operators->push(['type' => 'not_date_on_year', 'value' => $value]); } break; @@ -768,7 +793,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set date_is_exact MONTH value "%s"', $value)); $this->collector->monthIs($value); - $this->operators->push(['type' => 'date_on_month', 'value' => $value]); + $this->operators->push(['type' => 'date_on_month', 'value' => $value]); } break; @@ -777,7 +802,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set date_is_exact not MONTH value "%s"', $value)); $this->collector->monthIsNot($value); - $this->operators->push(['type' => 'not_date_on_month', 'value' => $value]); + $this->operators->push(['type' => 'not_date_on_month', 'value' => $value]); } break; @@ -786,7 +811,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set date_is_exact DAY value "%s"', $value)); $this->collector->dayIs($value); - $this->operators->push(['type' => 'date_on_day', 'value' => $value]); + $this->operators->push(['type' => 'date_on_day', 'value' => $value]); } break; @@ -795,7 +820,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set not date_is_exact DAY value "%s"', $value)); $this->collector->dayIsNot($value); - $this->operators->push(['type' => 'not_date_on_day', 'value' => $value]); + $this->operators->push(['type' => 'not_date_on_day', 'value' => $value]); } break; @@ -827,7 +852,7 @@ class OperatorQuerySearch implements SearchInterface if ($value instanceof Carbon) { Log::debug(sprintf('Set %s_is_exact value "%s"', $field, $value->format('Y-m-d'))); $this->collector->setMetaDateRange($value, $value, $field); - $this->operators->push(['type' => sprintf('%s_on', $field), 'value' => $value->format('Y-m-d')]); + $this->operators->push(['type' => sprintf('%s_on', $field), 'value' => $value->format('Y-m-d')]); } break; @@ -836,7 +861,7 @@ class OperatorQuerySearch implements SearchInterface if ($value instanceof Carbon) { Log::debug(sprintf('Set NOT %s_is_exact value "%s"', $field, $value->format('Y-m-d'))); $this->collector->excludeMetaDateRange($value, $value, $field); - $this->operators->push(['type' => sprintf('not_%s_on', $field), 'value' => $value->format('Y-m-d')]); + $this->operators->push(['type' => sprintf('not_%s_on', $field), 'value' => $value->format('Y-m-d')]); } break; @@ -845,7 +870,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set %s_is_exact YEAR value "%s"', $field, $value)); $this->collector->metaYearIs($value, $field); - $this->operators->push(['type' => sprintf('%s_on_year', $field), 'value' => $value]); + $this->operators->push(['type' => sprintf('%s_on_year', $field), 'value' => $value]); } break; @@ -854,7 +879,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set NOT %s_is_exact YEAR value "%s"', $field, $value)); $this->collector->metaYearIsNot($value, $field); - $this->operators->push(['type' => sprintf('not_%s_on_year', $field), 'value' => $value]); + $this->operators->push(['type' => sprintf('not_%s_on_year', $field), 'value' => $value]); } break; @@ -863,7 +888,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set %s_is_exact MONTH value "%s"', $field, $value)); $this->collector->metaMonthIs($value, $field); - $this->operators->push(['type' => sprintf('%s_on_month', $field), 'value' => $value]); + $this->operators->push(['type' => sprintf('%s_on_month', $field), 'value' => $value]); } break; @@ -872,7 +897,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set NOT %s_is_exact MONTH value "%s"', $field, $value)); $this->collector->metaMonthIsNot($value, $field); - $this->operators->push(['type' => sprintf('not_%s_on_month', $field), 'value' => $value]); + $this->operators->push(['type' => sprintf('not_%s_on_month', $field), 'value' => $value]); } break; @@ -881,7 +906,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set %s_is_exact DAY value "%s"', $field, $value)); $this->collector->metaDayIs($value, $field); - $this->operators->push(['type' => sprintf('%s_on_day', $field), 'value' => $value]); + $this->operators->push(['type' => sprintf('%s_on_day', $field), 'value' => $value]); } break; @@ -890,7 +915,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set NOT %s_is_exact DAY value "%s"', $field, $value)); $this->collector->metaDayIsNot($value, $field); - $this->operators->push(['type' => sprintf('not_%s_on_day', $field), 'value' => $value]); + $this->operators->push(['type' => sprintf('not_%s_on_day', $field), 'value' => $value]); } break; @@ -920,7 +945,7 @@ class OperatorQuerySearch implements SearchInterface if ($value instanceof Carbon) { Log::debug(sprintf('Set %s_is_exact value "%s"', $field, $value->format('Y-m-d'))); $this->collector->setObjectRange($value, clone $value, $field); - $this->operators->push(['type' => sprintf('%s_on', $field), 'value' => $value->format('Y-m-d')]); + $this->operators->push(['type' => sprintf('%s_on', $field), 'value' => $value->format('Y-m-d')]); } break; @@ -929,7 +954,7 @@ class OperatorQuerySearch implements SearchInterface if ($value instanceof Carbon) { Log::debug(sprintf('Set NOT %s_is_exact value "%s"', $field, $value->format('Y-m-d'))); $this->collector->excludeObjectRange($value, clone $value, $field); - $this->operators->push(['type' => sprintf('not_%s_on', $field), 'value' => $value->format('Y-m-d')]); + $this->operators->push(['type' => sprintf('not_%s_on', $field), 'value' => $value->format('Y-m-d')]); } break; @@ -938,7 +963,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set %s_is_exact YEAR value "%s"', $field, $value)); $this->collector->objectYearIs($value, $field); - $this->operators->push(['type' => sprintf('%s_on_year', $field), 'value' => $value]); + $this->operators->push(['type' => sprintf('%s_on_year', $field), 'value' => $value]); } break; @@ -947,7 +972,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set NOT %s_is_exact YEAR value "%s"', $field, $value)); $this->collector->objectYearIsNot($value, $field); - $this->operators->push(['type' => sprintf('not_%s_on_year', $field), 'value' => $value]); + $this->operators->push(['type' => sprintf('not_%s_on_year', $field), 'value' => $value]); } break; @@ -956,7 +981,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set %s_is_exact MONTH value "%s"', $field, $value)); $this->collector->objectMonthIs($value, $field); - $this->operators->push(['type' => sprintf('%s_on_month', $field), 'value' => $value]); + $this->operators->push(['type' => sprintf('%s_on_month', $field), 'value' => $value]); } break; @@ -965,7 +990,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set NOT %s_is_exact MONTH value "%s"', $field, $value)); $this->collector->objectMonthIsNot($value, $field); - $this->operators->push(['type' => sprintf('not_%s_on_month', $field), 'value' => $value]); + $this->operators->push(['type' => sprintf('not_%s_on_month', $field), 'value' => $value]); } break; @@ -974,7 +999,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set %s_is_exact DAY value "%s"', $field, $value)); $this->collector->objectDayIs($value, $field); - $this->operators->push(['type' => sprintf('%s_on_day', $field), 'value' => $value]); + $this->operators->push(['type' => sprintf('%s_on_day', $field), 'value' => $value]); } break; @@ -983,7 +1008,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set NOT %s_is_exact DAY value "%s"', $field, $value)); $this->collector->objectDayIsNot($value, $field); - $this->operators->push(['type' => sprintf('not_%s_on_day', $field), 'value' => $value]); + $this->operators->push(['type' => sprintf('not_%s_on_day', $field), 'value' => $value]); } break; @@ -1012,7 +1037,7 @@ class OperatorQuerySearch implements SearchInterface case 'exact': if ($value instanceof Carbon) { $this->collector->setMetaAfter($value, $field); - $this->operators->push(['type' => sprintf('%s_after', $field), 'value' => $value->format('Y-m-d')]); + $this->operators->push(['type' => sprintf('%s_after', $field), 'value' => $value->format('Y-m-d')]); } break; @@ -1021,7 +1046,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set %s_is_after YEAR value "%s"', $field, $value)); $this->collector->metaYearAfter($value, $field); - $this->operators->push(['type' => sprintf('%s_after_year', $field), 'value' => $value]); + $this->operators->push(['type' => sprintf('%s_after_year', $field), 'value' => $value]); } break; @@ -1030,7 +1055,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set %s_is_after MONTH value "%s"', $field, $value)); $this->collector->metaMonthAfter($value, $field); - $this->operators->push(['type' => sprintf('%s_after_month', $field), 'value' => $value]); + $this->operators->push(['type' => sprintf('%s_after_month', $field), 'value' => $value]); } break; @@ -1039,7 +1064,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set %s_is_after DAY value "%s"', $field, $value)); $this->collector->metaDayAfter($value, $field); - $this->operators->push(['type' => sprintf('%s_after_day', $field), 'value' => $value]); + $this->operators->push(['type' => sprintf('%s_after_day', $field), 'value' => $value]); } break; @@ -1068,7 +1093,7 @@ class OperatorQuerySearch implements SearchInterface case 'exact': if ($value instanceof Carbon) { $this->collector->setMetaBefore($value, $field); - $this->operators->push(['type' => sprintf('%s_before', $field), 'value' => $value->format('Y-m-d')]); + $this->operators->push(['type' => sprintf('%s_before', $field), 'value' => $value->format('Y-m-d')]); } break; @@ -1077,7 +1102,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set %s_is_before YEAR value "%s"', $field, $value)); $this->collector->metaYearBefore($value, $field); - $this->operators->push(['type' => sprintf('%s_before_year', $field), 'value' => $value]); + $this->operators->push(['type' => sprintf('%s_before_year', $field), 'value' => $value]); } break; @@ -1086,7 +1111,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set %s_is_before MONTH value "%s"', $field, $value)); $this->collector->metaMonthBefore($value, $field); - $this->operators->push(['type' => sprintf('%s_before_month', $field), 'value' => $value]); + $this->operators->push(['type' => sprintf('%s_before_month', $field), 'value' => $value]); } break; @@ -1095,7 +1120,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set %s_is_before DAY value "%s"', $field, $value)); $this->collector->metaDayBefore($value, $field); - $this->operators->push(['type' => sprintf('%s_before_day', $field), 'value' => $value]); + $this->operators->push(['type' => sprintf('%s_before_day', $field), 'value' => $value]); } break; @@ -1124,7 +1149,7 @@ class OperatorQuerySearch implements SearchInterface case 'exact': if ($value instanceof Carbon) { $this->collector->setObjectAfter($value, $field); - $this->operators->push(['type' => sprintf('%s_after', $field), 'value' => $value->format('Y-m-d')]); + $this->operators->push(['type' => sprintf('%s_after', $field), 'value' => $value->format('Y-m-d')]); } break; @@ -1133,7 +1158,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set date_is_after YEAR value "%s"', $value)); $this->collector->objectYearAfter($value, $field); - $this->operators->push(['type' => sprintf('%s_after_year', $field), 'value' => $value]); + $this->operators->push(['type' => sprintf('%s_after_year', $field), 'value' => $value]); } break; @@ -1142,7 +1167,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set date_is_after MONTH value "%s"', $value)); $this->collector->objectMonthAfter($value, $field); - $this->operators->push(['type' => sprintf('%s_after_month', $field), 'value' => $value]); + $this->operators->push(['type' => sprintf('%s_after_month', $field), 'value' => $value]); } break; @@ -1151,7 +1176,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set date_is_after DAY value "%s"', $value)); $this->collector->objectDayAfter($value, $field); - $this->operators->push(['type' => sprintf('%s_after_day', $field), 'value' => $value]); + $this->operators->push(['type' => sprintf('%s_after_day', $field), 'value' => $value]); } break; @@ -1180,7 +1205,7 @@ class OperatorQuerySearch implements SearchInterface case 'exact': if ($value instanceof Carbon) { $this->collector->setObjectBefore($value, $field); - $this->operators->push(['type' => sprintf('%s_before', $field), 'value' => $value->format('Y-m-d')]); + $this->operators->push(['type' => sprintf('%s_before', $field), 'value' => $value->format('Y-m-d')]); } break; @@ -1189,7 +1214,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set date_is_before YEAR value "%s"', $value)); $this->collector->objectYearBefore($value, $field); - $this->operators->push(['type' => sprintf('%s_before_year', $field), 'value' => $value]); + $this->operators->push(['type' => sprintf('%s_before_year', $field), 'value' => $value]); } break; @@ -1198,7 +1223,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set date_is_before MONTH value "%s"', $value)); $this->collector->objectMonthBefore($value, $field); - $this->operators->push(['type' => sprintf('%s_before_month', $field), 'value' => $value]); + $this->operators->push(['type' => sprintf('%s_before_month', $field), 'value' => $value]); } break; @@ -1207,7 +1232,7 @@ class OperatorQuerySearch implements SearchInterface if (is_string($value)) { Log::debug(sprintf('Set date_is_before DAY value "%s"', $value)); $this->collector->objectDayBefore($value, $field); - $this->operators->push(['type' => sprintf('%s_before_day', $field), 'value' => $value]); + $this->operators->push(['type' => sprintf('%s_before_day', $field), 'value' => $value]); } break; @@ -1239,14 +1264,13 @@ class OperatorQuerySearch implements SearchInterface throw new FireflyException(sprintf('Unsupported search operator: "%s"', $operator)); - // some search operators are ignored, basically: + // some search operators are ignored, basically: case 'user_action': Log::info(sprintf('Ignore search operator "%s"', $operator)); return false; - - // all account related searches: + // all account related searches: case 'account_is': $this->searchAccount($value, SearchDirection::BOTH, StringPosition::IS); @@ -1409,7 +1433,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'source_account_id': - $account = $this->accountRepository->find((int)$value); + $account = $this->accountRepository->find((int) $value); if (null !== $account) { $this->collector->setSourceAccounts(new Collection()->push($account)); } @@ -1422,7 +1446,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-source_account_id': - $account = $this->accountRepository->find((int)$value); + $account = $this->accountRepository->find((int) $value); if (null !== $account) { $this->collector->excludeSourceAccounts(new Collection()->push($account)); } @@ -1435,25 +1459,25 @@ class OperatorQuerySearch implements SearchInterface break; case 'journal_id': - $parts = explode(',', $value); + $parts = explode(',', $value); $this->collector->setJournalIds($parts); break; case '-journal_id': - $parts = explode(',', $value); + $parts = explode(',', $value); $this->collector->excludeJournalIds($parts); break; case 'id': - $parts = explode(',', $value); + $parts = explode(',', $value); $this->collector->setIds($parts); break; case '-id': - $parts = explode(',', $value); + $parts = explode(',', $value); $this->collector->excludeIds($parts); break; @@ -1539,7 +1563,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'destination_account_id': - $account = $this->accountRepository->find((int)$value); + $account = $this->accountRepository->find((int) $value); if (null !== $account) { $this->collector->setDestinationAccounts(new Collection()->push($account)); } @@ -1551,7 +1575,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-destination_account_id': - $account = $this->accountRepository->find((int)$value); + $account = $this->accountRepository->find((int) $value); if (null !== $account) { $this->collector->excludeDestinationAccounts(new Collection()->push($account)); } @@ -1564,12 +1588,12 @@ class OperatorQuerySearch implements SearchInterface case 'account_id': Log::debug(sprintf('Now in "account_id" with value "%s"', $value)); - $parts = explode(',', $value); - $collection = new Collection(); + $parts = explode(',', $value); + $collection = new Collection(); foreach ($parts as $accountId) { - $accountId = (int)$accountId; + $accountId = (int) $accountId; Log::debug(sprintf('Searching for account with ID #%d', $accountId)); - $account = $this->accountRepository->find($accountId); + $account = $this->accountRepository->find($accountId); if (null !== $account) { Log::debug(sprintf('Found account with ID #%d ("%s")', $accountId, $account->name)); $collection->push($account); @@ -1590,10 +1614,10 @@ class OperatorQuerySearch implements SearchInterface break; case '-account_id': - $parts = explode(',', $value); - $collection = new Collection(); + $parts = explode(',', $value); + $collection = new Collection(); foreach ($parts as $accountId) { - $account = $this->accountRepository->find((int)$accountId); + $account = $this->accountRepository->find((int) $accountId); if (null !== $account) { $collection->push($account); } @@ -1608,47 +1632,45 @@ class OperatorQuerySearch implements SearchInterface break; - - // cash account + // cash account case 'source_is_cash': - $account = $this->getCashAccount(); + $account = $this->getCashAccount(); $this->collector->setSourceAccounts(new Collection()->push($account)); break; case '-source_is_cash': - $account = $this->getCashAccount(); + $account = $this->getCashAccount(); $this->collector->excludeSourceAccounts(new Collection()->push($account)); break; case 'destination_is_cash': - $account = $this->getCashAccount(); + $account = $this->getCashAccount(); $this->collector->setDestinationAccounts(new Collection()->push($account)); break; case '-destination_is_cash': - $account = $this->getCashAccount(); + $account = $this->getCashAccount(); $this->collector->excludeDestinationAccounts(new Collection()->push($account)); break; case 'account_is_cash': - $account = $this->getCashAccount(); + $account = $this->getCashAccount(); $this->collector->setAccounts(new Collection()->push($account)); break; case '-account_is_cash': - $account = $this->getCashAccount(); + $account = $this->getCashAccount(); $this->collector->excludeAccounts(new Collection()->push($account)); break; - - // description + // description case 'description_starts': $this->collector->descriptionStarts([$value]); @@ -1671,7 +1693,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'description_contains': - $this->words[] = $value; + $this->words[] = $value; return false; @@ -1690,11 +1712,10 @@ class OperatorQuerySearch implements SearchInterface break; - - // currency + // currency case 'currency_is': - $currency = $this->findCurrency($value); + $currency = $this->findCurrency($value); if ($currency instanceof TransactionCurrency) { $this->collector->setCurrency($currency); } @@ -1706,7 +1727,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-currency_is': - $currency = $this->findCurrency($value); + $currency = $this->findCurrency($value); if ($currency instanceof TransactionCurrency) { $this->collector->excludeCurrency($currency); } @@ -1718,7 +1739,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'foreign_currency_is': - $currency = $this->findCurrency($value); + $currency = $this->findCurrency($value); if ($currency instanceof TransactionCurrency) { $this->collector->setForeignCurrency($currency); } @@ -1730,7 +1751,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-foreign_currency_is': - $currency = $this->findCurrency($value); + $currency = $this->findCurrency($value); if ($currency instanceof TransactionCurrency) { $this->collector->excludeForeignCurrency($currency); } @@ -1741,8 +1762,7 @@ class OperatorQuerySearch implements SearchInterface break; - - // attachments + // attachments case 'has_attachments': case '-has_no_attachments': @@ -1758,8 +1778,7 @@ class OperatorQuerySearch implements SearchInterface break; - - // categories + // categories case '-has_any_category': case 'has_no_category': $this->collector->withoutCategory(); @@ -1773,7 +1792,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'category_is': - $category = $this->categoryRepository->findByName($value); + $category = $this->categoryRepository->findByName($value); if (null !== $category) { $this->collector->setCategory($category); @@ -1785,7 +1804,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-category_is': - $category = $this->categoryRepository->findByName($value); + $category = $this->categoryRepository->findByName($value); if (null !== $category) { $this->collector->excludeCategory($category); @@ -1795,7 +1814,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'category_ends': - $result = $this->categoryRepository->categoryEndsWith($value, 1337); + $result = $this->categoryRepository->categoryEndsWith($value, 1337); if ($result->count() > 0) { $this->collector->setCategories($result); } @@ -1807,7 +1826,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-category_ends': - $result = $this->categoryRepository->categoryEndsWith($value, 1337); + $result = $this->categoryRepository->categoryEndsWith($value, 1337); if ($result->count() > 0) { $this->collector->excludeCategories($result); } @@ -1819,7 +1838,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'category_starts': - $result = $this->categoryRepository->categoryStartsWith($value, 1337); + $result = $this->categoryRepository->categoryStartsWith($value, 1337); if ($result->count() > 0) { $this->collector->setCategories($result); } @@ -1831,7 +1850,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-category_starts': - $result = $this->categoryRepository->categoryStartsWith($value, 1337); + $result = $this->categoryRepository->categoryStartsWith($value, 1337); if ($result->count() > 0) { $this->collector->excludeCategories($result); } @@ -1843,7 +1862,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'category_contains': - $result = $this->categoryRepository->searchCategory($value, 1337); + $result = $this->categoryRepository->searchCategory($value, 1337); if ($result->count() > 0) { $this->collector->setCategories($result); } @@ -1855,7 +1874,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-category_contains': - $result = $this->categoryRepository->searchCategory($value, 1337); + $result = $this->categoryRepository->searchCategory($value, 1337); if ($result->count() > 0) { $this->collector->excludeCategories($result); } @@ -1866,8 +1885,7 @@ class OperatorQuerySearch implements SearchInterface break; - - // budgets + // budgets case '-has_any_budget': case 'has_no_budget': @@ -1882,7 +1900,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'budget_contains': - $result = $this->budgetRepository->searchBudget($value, 1337); + $result = $this->budgetRepository->searchBudget($value, 1337); if ($result->count() > 0) { $this->collector->setBudgets($result); } @@ -1894,7 +1912,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-budget_contains': - $result = $this->budgetRepository->searchBudget($value, 1337); + $result = $this->budgetRepository->searchBudget($value, 1337); if ($result->count() > 0) { $this->collector->excludeBudgets($result); } @@ -1906,7 +1924,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'budget_is': - $budget = $this->budgetRepository->findByName($value); + $budget = $this->budgetRepository->findByName($value); if (null !== $budget) { $this->collector->setBudget($budget); @@ -1918,7 +1936,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-budget_is': - $budget = $this->budgetRepository->findByName($value); + $budget = $this->budgetRepository->findByName($value); if (null !== $budget) { $this->collector->excludeBudget($budget); @@ -1930,7 +1948,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'budget_ends': - $result = $this->budgetRepository->budgetEndsWith($value, 1337); + $result = $this->budgetRepository->budgetEndsWith($value, 1337); if ($result->count() > 0) { $this->collector->setBudgets($result); } @@ -1942,7 +1960,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-budget_ends': - $result = $this->budgetRepository->budgetEndsWith($value, 1337); + $result = $this->budgetRepository->budgetEndsWith($value, 1337); if ($result->count() > 0) { $this->collector->excludeBudgets($result); } @@ -1954,7 +1972,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'budget_starts': - $result = $this->budgetRepository->budgetStartsWith($value, 1337); + $result = $this->budgetRepository->budgetStartsWith($value, 1337); if ($result->count() > 0) { $this->collector->setBudgets($result); } @@ -1966,7 +1984,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-budget_starts': - $result = $this->budgetRepository->budgetStartsWith($value, 1337); + $result = $this->budgetRepository->budgetStartsWith($value, 1337); if ($result->count() > 0) { $this->collector->excludeBudgets($result); } @@ -1977,8 +1995,7 @@ class OperatorQuerySearch implements SearchInterface break; - - // bill + // bill case '-has_any_bill': case 'has_no_bill': @@ -1993,7 +2010,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'bill_contains': - $result = $this->billRepository->searchBill($value, 1337); + $result = $this->billRepository->searchBill($value, 1337); if ($result->count() > 0) { $this->collector->setBills($result); @@ -2005,7 +2022,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-bill_contains': - $result = $this->billRepository->searchBill($value, 1337); + $result = $this->billRepository->searchBill($value, 1337); if ($result->count() > 0) { $this->collector->excludeBills($result); @@ -2017,7 +2034,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'bill_is': - $bill = $this->billRepository->findByName($value); + $bill = $this->billRepository->findByName($value); if (null !== $bill) { $this->collector->setBill($bill); @@ -2029,7 +2046,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-bill_is': - $bill = $this->billRepository->findByName($value); + $bill = $this->billRepository->findByName($value); if (null !== $bill) { $this->collector->excludeBills(new Collection()->push($bill)); @@ -2041,7 +2058,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'bill_ends': - $result = $this->billRepository->billEndsWith($value, 1337); + $result = $this->billRepository->billEndsWith($value, 1337); if ($result->count() > 0) { $this->collector->setBills($result); } @@ -2053,7 +2070,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-bill_ends': - $result = $this->billRepository->billEndsWith($value, 1337); + $result = $this->billRepository->billEndsWith($value, 1337); if ($result->count() > 0) { $this->collector->excludeBills($result); } @@ -2065,7 +2082,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'bill_starts': - $result = $this->billRepository->billStartsWith($value, 1337); + $result = $this->billRepository->billStartsWith($value, 1337); if ($result->count() > 0) { $this->collector->setBills($result); } @@ -2077,7 +2094,7 @@ class OperatorQuerySearch implements SearchInterface break; case '-bill_starts': - $result = $this->billRepository->billStartsWith($value, 1337); + $result = $this->billRepository->billStartsWith($value, 1337); if ($result->count() > 0) { $this->collector->excludeBills($result); } @@ -2088,8 +2105,7 @@ class OperatorQuerySearch implements SearchInterface break; - - // tags + // tags case '-has_any_tag': case 'has_no_tag': @@ -2105,10 +2121,10 @@ class OperatorQuerySearch implements SearchInterface case '-tag_is_not': case 'tag_is': - $result = $this->tagRepository->findByTag($value); + $result = $this->tagRepository->findByTag($value); if (null !== $result) { $this->includeTags[] = $result->id; - $this->includeTags = array_unique($this->includeTags); + $this->includeTags = array_unique($this->includeTags); } // no tags found means search must result in nothing. if (null === $result) { @@ -2120,7 +2136,7 @@ class OperatorQuerySearch implements SearchInterface break; case 'tag_contains': - $tags = $this->tagRepository->searchTag($value); + $tags = $this->tagRepository->searchTag($value); if (0 === $tags->count()) { Log::info(sprintf('No valid tags in "%s"-operator, so search will not return ANY results.', $operator)); Log::warning(sprintf('Call to findNothing() from %s.', $operator)); @@ -2128,14 +2144,14 @@ class OperatorQuerySearch implements SearchInterface } if ($tags->count() > 0) { // changed from includeTags to includeAnyTags for #8632 - $ids = array_values($tags->pluck('id')->toArray()); + $ids = array_values($tags->pluck('id')->toArray()); $this->includeAnyTags = array_unique(array_merge($this->includeAnyTags, $ids)); } break; case 'tag_starts': - $tags = $this->tagRepository->tagStartsWith($value); + $tags = $this->tagRepository->tagStartsWith($value); if (0 === $tags->count()) { Log::info(sprintf('No valid tags in "%s"-operator, so search will not return ANY results.', $operator)); Log::warning(sprintf('Call to findNothing() from %s.', $operator)); @@ -2143,56 +2159,56 @@ class OperatorQuerySearch implements SearchInterface } if ($tags->count() > 0) { // changed from includeTags to includeAnyTags for #8632 - $ids = array_values($tags->pluck('id')->toArray()); + $ids = array_values($tags->pluck('id')->toArray()); $this->includeAnyTags = array_unique(array_merge($this->includeAnyTags, $ids)); } break; case '-tag_starts': - $tags = $this->tagRepository->tagStartsWith($value); + $tags = $this->tagRepository->tagStartsWith($value); if (0 === $tags->count()) { Log::info(sprintf('No valid tags in "%s"-operator, so search will not return ANY results.', $operator)); Log::warning(sprintf('Call to findNothing() from %s.', $operator)); $this->collector->findNothing(); } if ($tags->count() > 0) { - $ids = array_values($tags->pluck('id')->toArray()); + $ids = array_values($tags->pluck('id')->toArray()); $this->excludeTags = array_unique(array_merge($this->includeTags, $ids)); } break; case 'tag_ends': - $tags = $this->tagRepository->tagEndsWith($value); + $tags = $this->tagRepository->tagEndsWith($value); if (0 === $tags->count()) { Log::info(sprintf('No valid tags in "%s"-operator, so search will not return ANY results.', $operator)); Log::warning(sprintf('Call to findNothing() from %s.', $operator)); $this->collector->findNothing(); } if ($tags->count() > 0) { - $ids = array_values($tags->pluck('id')->toArray()); + $ids = array_values($tags->pluck('id')->toArray()); $this->includeTags = array_unique(array_merge($this->includeTags, $ids)); } break; case '-tag_ends': - $tags = $this->tagRepository->tagEndsWith($value); + $tags = $this->tagRepository->tagEndsWith($value); if (0 === $tags->count()) { Log::info(sprintf('No valid tags in "%s"-operator, so search will not return ANY results.', $operator)); Log::warning(sprintf('Call to findNothing() from %s.', $operator)); $this->collector->findNothing(); } if ($tags->count() > 0) { - $ids = array_values($tags->pluck('id')->toArray()); + $ids = array_values($tags->pluck('id')->toArray()); $this->excludeTags = array_unique(array_merge($this->includeTags, $ids)); } break; case '-tag_contains': - $tags = $this->tagRepository->searchTag($value)->keyBy('id'); + $tags = $this->tagRepository->searchTag($value)->keyBy('id'); if (0 === $tags->count()) { Log::info(sprintf('No valid tags in "%s"-operator, so search will not return ANY results.', $operator)); @@ -2200,7 +2216,7 @@ class OperatorQuerySearch implements SearchInterface $this->collector->findNothing(); } if ($tags->count() > 0) { - $ids = array_values($tags->pluck('id')->toArray()); + $ids = array_values($tags->pluck('id')->toArray()); $this->excludeTags = array_unique(array_merge($this->excludeTags, $ids)); } @@ -2208,16 +2224,15 @@ class OperatorQuerySearch implements SearchInterface case '-tag_is': case 'tag_is_not': - $result = $this->tagRepository->findByTag($value); + $result = $this->tagRepository->findByTag($value); if (null !== $result) { $this->excludeTags[] = $result->id; - $this->excludeTags = array_unique($this->excludeTags); + $this->excludeTags = array_unique($this->excludeTags); } break; - - // notes + // notes case 'notes_contains': $this->collector->notesContain($value); @@ -2281,14 +2296,13 @@ class OperatorQuerySearch implements SearchInterface break; - - // amount + // amount case 'amount_is': // strip comma's, make dots. Log::debug(sprintf('Original value "%s"', $value)); - $value = str_replace(',', '.', $value); - $amount = Steam::positive($value); + $value = str_replace(',', '.', $value); + $amount = Steam::positive($value); Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $amount)); $this->collector->amountIs($amount); @@ -2297,8 +2311,8 @@ class OperatorQuerySearch implements SearchInterface case '-amount_is': // strip comma's, make dots. Log::debug(sprintf('Original value "%s"', $value)); - $value = str_replace(',', '.', $value); - $amount = Steam::positive($value); + $value = str_replace(',', '.', $value); + $amount = Steam::positive($value); Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $amount)); $this->collector->amountIsNot($amount); @@ -2306,9 +2320,9 @@ class OperatorQuerySearch implements SearchInterface case 'foreign_amount_is': // strip comma's, make dots. - $value = str_replace(',', '.', $value); + $value = str_replace(',', '.', $value); - $amount = Steam::positive($value); + $amount = Steam::positive($value); Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $amount)); $this->collector->foreignAmountIs($amount); @@ -2316,9 +2330,9 @@ class OperatorQuerySearch implements SearchInterface case '-foreign_amount_is': // strip comma's, make dots. - $value = str_replace(',', '.', $value); + $value = str_replace(',', '.', $value); - $amount = Steam::positive($value); + $amount = Steam::positive($value); Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $amount)); $this->collector->foreignAmountIsNot($amount); @@ -2327,9 +2341,9 @@ class OperatorQuerySearch implements SearchInterface case '-amount_more': case 'amount_less': // strip comma's, make dots. - $value = str_replace(',', '.', $value); + $value = str_replace(',', '.', $value); - $amount = Steam::positive($value); + $amount = Steam::positive($value); Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $amount)); $this->collector->amountLess($amount); @@ -2338,9 +2352,9 @@ class OperatorQuerySearch implements SearchInterface case '-foreign_amount_more': case 'foreign_amount_less': // strip comma's, make dots. - $value = str_replace(',', '.', $value); + $value = str_replace(',', '.', $value); - $amount = Steam::positive($value); + $amount = Steam::positive($value); Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $amount)); $this->collector->foreignAmountLess($amount); @@ -2350,8 +2364,8 @@ class OperatorQuerySearch implements SearchInterface case 'amount_more': Log::debug(sprintf('Now handling operator "%s"', $operator)); // strip comma's, make dots. - $value = str_replace(',', '.', $value); - $amount = Steam::positive($value); + $value = str_replace(',', '.', $value); + $amount = Steam::positive($value); Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $amount)); $this->collector->amountMore($amount); @@ -2361,15 +2375,14 @@ class OperatorQuerySearch implements SearchInterface case 'foreign_amount_more': Log::debug(sprintf('Now handling operator "%s"', $operator)); // strip comma's, make dots. - $value = str_replace(',', '.', $value); - $amount = Steam::positive($value); + $value = str_replace(',', '.', $value); + $amount = Steam::positive($value); Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $amount)); $this->collector->foreignAmountMore($amount); break; - - // transaction type + // transaction type case 'transaction_type': $this->collector->setTypes([ucfirst($value)]); @@ -2383,152 +2396,151 @@ class OperatorQuerySearch implements SearchInterface break; - - // dates + // dates case '-date_on': case 'date_on': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setExactDateParams($range, $prohibited); return false; case 'date_before': case '-date_after': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setDateBeforeParams($range); return false; case 'date_after': case '-date_before': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setDateAfterParams($range); return false; case 'interest_date_on': case '-interest_date_on': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setExactMetaDateParams('interest_date', $range, $prohibited); return false; case 'interest_date_before': case '-interest_date_after': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setMetaDateBeforeParams('interest_date', $range); return false; case 'interest_date_after': case '-interest_date_before': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setMetaDateAfterParams('interest_date', $range); return false; case 'book_date_on': case '-book_date_on': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setExactMetaDateParams('book_date', $range, $prohibited); return false; case 'book_date_before': case '-book_date_after': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setMetaDateBeforeParams('book_date', $range); return false; case 'book_date_after': case '-book_date_before': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setMetaDateAfterParams('book_date', $range); return false; case 'process_date_on': case '-process_date_on': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setExactMetaDateParams('process_date', $range, $prohibited); return false; case 'process_date_before': case '-process_date_after': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setMetaDateBeforeParams('process_date', $range); return false; case 'process_date_after': case '-process_date_before': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setMetaDateAfterParams('process_date', $range); return false; case 'due_date_on': case '-due_date_on': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setExactMetaDateParams('due_date', $range, $prohibited); return false; case 'due_date_before': case '-due_date_after': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setMetaDateBeforeParams('due_date', $range); return false; case 'due_date_after': case '-due_date_before': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setMetaDateAfterParams('due_date', $range); return false; case 'payment_date_on': case '-payment_date_on': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setExactMetaDateParams('payment_date', $range, $prohibited); return false; case 'payment_date_before': case '-payment_date_after': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setMetaDateBeforeParams('payment_date', $range); return false; case 'payment_date_after': case '-payment_date_before': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setMetaDateAfterParams('payment_date', $range); return false; case 'invoice_date_on': case '-invoice_date_on': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setExactMetaDateParams('invoice_date', $range, $prohibited); return false; case 'invoice_date_before': case '-invoice_date_after': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setMetaDateBeforeParams('invoice_date', $range); return false; case 'invoice_date_after': case '-invoice_date_before': - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setMetaDateAfterParams('invoice_date', $range); return false; @@ -2536,7 +2548,7 @@ class OperatorQuerySearch implements SearchInterface case 'created_at_on': case '-created_at_on': Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $value)); - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setExactObjectDateParams('created_at', $range, $prohibited); return false; @@ -2544,7 +2556,7 @@ class OperatorQuerySearch implements SearchInterface case 'created_at_before': case '-created_at_after': Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $value)); - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setObjectDateBeforeParams('created_at', $range); return false; @@ -2552,7 +2564,7 @@ class OperatorQuerySearch implements SearchInterface case 'created_at_after': case '-created_at_before': Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $value)); - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setObjectDateAfterParams('created_at', $range); return false; @@ -2560,7 +2572,7 @@ class OperatorQuerySearch implements SearchInterface case 'updated_at_on': case '-updated_at_on': Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $value)); - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setExactObjectDateParams('updated_at', $range, $prohibited); return false; @@ -2568,7 +2580,7 @@ class OperatorQuerySearch implements SearchInterface case 'updated_at_before': case '-updated_at_after': Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $value)); - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setObjectDateBeforeParams('updated_at', $range); return false; @@ -2576,13 +2588,12 @@ class OperatorQuerySearch implements SearchInterface case 'updated_at_after': case '-updated_at_before': Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $value)); - $range = $this->parseDateRange($operator, $value); + $range = $this->parseDateRange($operator, $value); $this->setObjectDateAfterParams('updated_at', $range); return false; - - // external URL + // external URL case '-any_external_url': case 'no_external_url': @@ -2648,8 +2659,7 @@ class OperatorQuerySearch implements SearchInterface break; - - // other fields + // other fields case 'external_id_is': $this->collector->setExternalId($value); diff --git a/app/Support/Search/QueryParser/FieldNode.php b/app/Support/Search/QueryParser/FieldNode.php index 6faecc918f..aa2ad611df 100644 --- a/app/Support/Search/QueryParser/FieldNode.php +++ b/app/Support/Search/QueryParser/FieldNode.php @@ -1,6 +1,5 @@ prohibited = $prohibited; } diff --git a/app/Support/Search/QueryParser/GdbotsQueryParser.php b/app/Support/Search/QueryParser/GdbotsQueryParser.php index 95d65556e8..cd7a47a518 100644 --- a/app/Support/Search/QueryParser/GdbotsQueryParser.php +++ b/app/Support/Search/QueryParser/GdbotsQueryParser.php @@ -1,6 +1,5 @@ parser->parse($query); - $nodes = array_map( - $this->convertNode(...), - $result->getNodes() - ); + $nodes = array_map($this->convertNode(...), $result->getNodes()); return new NodeGroup($nodes); } catch (LogicException|TypeError $e) { @@ -70,27 +66,17 @@ class GdbotsQueryParser implements QueryParserInterface private function convertNode(GdbotsNode\Node $node): Node { - switch (true) { case $node instanceof GdbotsNode\Word: return new StringNode($node->getValue(), BoolOperator::PROHIBITED === $node->getBoolOperator()); case $node instanceof GdbotsNode\Field: - return new FieldNode( - $node->getValue(), - (string)$node->getNode()->getValue(), - BoolOperator::PROHIBITED === $node->getBoolOperator() - ); + return new FieldNode($node->getValue(), (string) $node->getNode()->getValue(), BoolOperator::PROHIBITED === $node->getBoolOperator()); case $node instanceof GdbotsNode\Subquery: Log::debug('Subquery'); - return new NodeGroup( - array_map( - $this->convertNode(...), - $node->getNodes() - ) - ); + return new NodeGroup(array_map($this->convertNode(...), $node->getNodes())); case $node instanceof GdbotsNode\Phrase: case $node instanceof GdbotsNode\Numbr: @@ -100,12 +86,10 @@ class GdbotsQueryParser implements QueryParserInterface case $node instanceof GdbotsNode\Mention: case $node instanceof GdbotsNode\Emoticon: case $node instanceof GdbotsNode\Emoji: - return new StringNode((string)$node->getValue(), BoolOperator::PROHIBITED === $node->getBoolOperator()); + return new StringNode((string) $node->getValue(), BoolOperator::PROHIBITED === $node->getBoolOperator()); default: - throw new FireflyException( - sprintf('Unsupported node type: %s', $node::class) - ); + throw new FireflyException(sprintf('Unsupported node type: %s', $node::class)); } } } diff --git a/app/Support/Search/QueryParser/Node.php b/app/Support/Search/QueryParser/Node.php index 31412cfdab..fb2246abdc 100644 --- a/app/Support/Search/QueryParser/Node.php +++ b/app/Support/Search/QueryParser/Node.php @@ -1,6 +1,5 @@ getNodes()) !== count($this->getNodes())) { - Log::debug(sprintf('Return false because node count is different. Original is %d, compare is %d', count($this->getNodes()), count($compare->getNodes()))); + Log::debug(sprintf( + 'Return false because node count is different. Original is %d, compare is %d', + count($this->getNodes()), + count($compare->getNodes()) + )); return false; } @@ -85,6 +88,5 @@ abstract class Node // Log::debug(sprintf('This %s is (not flipped) now prohibited: %s',get_class($this), var_export($this->prohibited, true))); return $this->prohibited; - } } diff --git a/app/Support/Search/QueryParser/NodeGroup.php b/app/Support/Search/QueryParser/NodeGroup.php index 017a5a89c0..c604a5bc84 100644 --- a/app/Support/Search/QueryParser/NodeGroup.php +++ b/app/Support/Search/QueryParser/NodeGroup.php @@ -1,6 +1,5 @@ prohibited = $prohibited; } diff --git a/app/Support/Search/QueryParser/NodeResult.php b/app/Support/Search/QueryParser/NodeResult.php index 15b1565051..6b602b9180 100644 --- a/app/Support/Search/QueryParser/NodeResult.php +++ b/app/Support/Search/QueryParser/NodeResult.php @@ -33,7 +33,7 @@ namespace FireflyIII\Support\Search\QueryParser; class NodeResult { public function __construct( - public readonly ?Node $node, - public readonly bool $isSubqueryEnd + public readonly null|Node $node, + public readonly bool $isSubqueryEnd ) {} } diff --git a/app/Support/Search/QueryParser/QueryParser.php b/app/Support/Search/QueryParser/QueryParser.php index d3aabf49d3..54f9efade5 100644 --- a/app/Support/Search/QueryParser/QueryParser.php +++ b/app/Support/Search/QueryParser/QueryParser.php @@ -1,6 +1,5 @@ query = $query; + $this->query = $query; $this->position = 0; return $this->buildNodeGroup(false); @@ -65,8 +64,8 @@ class QueryParser implements QueryParserInterface if ('\\' === $char && '"' === $nextChar) { // Log::debug('BACKSLASH!'); // escaped quote, pretend it's a normal char and continue two places (skipping the actual character). - $tokenUnderConstruction .= '\\'.$nextChar; - $this->position += 2; + $tokenUnderConstruction .= '\\' . $nextChar; + $this->position += 2; continue; } @@ -114,10 +113,7 @@ class QueryParser implements QueryParserInterface // A left parentheses at the beginning of a token indicates the start of a subquery ++$this->position; - return new NodeResult( - $this->buildNodeGroup(true, $prohibited), - false - ); + return new NodeResult($this->buildNodeGroup(true, $prohibited), false); } // In any other location, it's just a normal character $tokenUnderConstruction .= $char; @@ -131,9 +127,7 @@ class QueryParser implements QueryParserInterface ++$this->position; return new NodeResult( - '' !== $tokenUnderConstruction - ? $this->createNode($tokenUnderConstruction, $fieldName, $prohibited) - : null, + '' !== $tokenUnderConstruction ? $this->createNode($tokenUnderConstruction, $fieldName, $prohibited) : null, true ); } @@ -142,13 +136,12 @@ class QueryParser implements QueryParserInterface break; - case ':': $skipNext = false; if ('' === $tokenUnderConstruction) { // In any other location, it's just a normal character $tokenUnderConstruction .= $char; - $skipNext = true; + $skipNext = true; } if ('' !== $tokenUnderConstruction && !$skipNext) { // @phpstan-ignore-line Log::debug(sprintf('Turns out that "%s" is a field name. Reset the token.', $tokenUnderConstruction)); @@ -157,7 +150,6 @@ class QueryParser implements QueryParserInterface $tokenUnderConstruction = ''; } - break; case ' ': @@ -165,10 +157,7 @@ class QueryParser implements QueryParserInterface if ('' !== $tokenUnderConstruction) { ++$this->position; - return new NodeResult( - $this->createNode($tokenUnderConstruction, $fieldName, $prohibited), - false - ); + return new NodeResult($this->createNode($tokenUnderConstruction, $fieldName, $prohibited), false); } break; @@ -180,9 +169,7 @@ class QueryParser implements QueryParserInterface ++$this->position; } - $finalNode = '' !== $tokenUnderConstruction || '' !== $fieldName - ? $this->createNode($tokenUnderConstruction, $fieldName, $prohibited) - : null; + $finalNode = '' !== $tokenUnderConstruction || '' !== $fieldName ? $this->createNode($tokenUnderConstruction, $fieldName, $prohibited) : null; return new NodeResult($finalNode, true); } @@ -193,7 +180,7 @@ class QueryParser implements QueryParserInterface $nodeResult = $this->buildNextNode($isSubquery); while ($nodeResult->node instanceof Node) { - $nodes[] = $nodeResult->node; + $nodes[] = $nodeResult->node; if ($nodeResult->isSubqueryEnd) { break; } diff --git a/app/Support/Search/QueryParser/QueryParserInterface.php b/app/Support/Search/QueryParser/QueryParserInterface.php index 809f7b02c1..5d16b5b343 100644 --- a/app/Support/Search/QueryParser/QueryParserInterface.php +++ b/app/Support/Search/QueryParser/QueryParserInterface.php @@ -1,6 +1,5 @@ prohibited = $prohibited; } diff --git a/app/Support/Singleton/PreferencesSingleton.php b/app/Support/Singleton/PreferencesSingleton.php index 646e1c60bf..72b36e141e 100644 --- a/app/Support/Singleton/PreferencesSingleton.php +++ b/app/Support/Singleton/PreferencesSingleton.php @@ -1,6 +1,5 @@ count(), $date->toIso8601String(), var_export($inclusive, true))); - $result = []; + public function accountsBalancesOptimized( + Collection $accounts, + Carbon $date, + null|TransactionCurrency $primary = null, + null|bool $convertToPrimary = null, + bool $inclusive = true + ): array { + Log::debug(sprintf( + 'accountsBalancesOptimized: Called for %d account(s) with date/time "%s" (inclusive: %s)', + $accounts->count(), + $date->toIso8601String(), + var_export($inclusive, true) + )); + $result = []; $convertToPrimary ??= Amount::convertToPrimary(); $primary ??= Amount::getPrimaryCurrency(); - $currencies = $this->getCurrencies($accounts); + $currencies = $this->getCurrencies($accounts); // balance(s) in all currencies for ALL accounts. $arrayOfSums = Transaction::whereIn('account_id', $accounts->pluck('id')->toArray()) @@ -66,63 +76,64 @@ class Steam ->leftJoin('transaction_currencies', 'transaction_currencies.id', '=', 'transactions.transaction_currency_id') ->where('transaction_journals.date', $inclusive ? '<=' : '<', $date->format('Y-m-d H:i:s')) ->groupBy(['transactions.account_id', 'transaction_currencies.code']) - ->get(['transactions.account_id', 'transaction_currencies.code', DB::raw('SUM(transactions.amount) as sum_of_amount')])->toArray() - ; + ->get(['transactions.account_id', 'transaction_currencies.code', DB::raw('SUM(transactions.amount) as sum_of_amount')]) + ->toArray(); Log::debug('Array of sums: ', $arrayOfSums); /** @var Account $account */ foreach ($accounts as $account) { - $return = [ - 'pc_balance' => '0', - 'balance' => '0', // this key is overwritten right away, but I must remember it is always created. - ]; - $currency = $currencies[$account->id]; + $return = ['pc_balance' => '0', 'balance' => '0']; // this key is overwritten right away, but I must remember it is always created. + $currency = $currencies[$account->id]; // second array - $accountSums = array_filter($arrayOfSums, static fn (array $entry): bool => $entry['account_id'] === $account->id); + $accountSums = array_filter($arrayOfSums, static fn(array $entry): bool => $entry['account_id'] === $account->id); if (0 === count($accountSums)) { $result[$account->id] = $return; continue; } - $sumsByCode = []; + $sumsByCode = []; foreach ($accountSums as $accountSum) { // $accountSum = array_values($accountSum)[0]; - $sumOfAmount = (string)$accountSum['sum_of_amount']; - $sumOfAmount = $this->floatalize('' === $sumOfAmount ? '0' : $sumOfAmount); + $sumOfAmount = (string) $accountSum['sum_of_amount']; + $sumOfAmount = $this->floatalize('' === $sumOfAmount ? '0' : $sumOfAmount); $sumsByCode[$accountSum['code']] = $sumOfAmount; } // Log::debug('All balances are (joined)', $others); // if there is no request to convert, take this as "balance" and "pc_balance". - $return['balance'] = $sumsByCode[$currency->code] ?? '0'; + $return['balance'] = $sumsByCode[$currency->code] ?? '0'; if (!$convertToPrimary) { unset($return['pc_balance']); + // Log::debug(sprintf('Set balance to %s, unset pc_balance', $return['balance'])); } // if there is a request to convert, convert to "pc_balance" and use "balance" for whichever amount is in the primary currency. if ($convertToPrimary) { $return['pc_balance'] = $this->convertAllBalances($sumsByCode, $primary, $date); + // Log::debug(sprintf('Set pc_balance to %s', $return['pc_balance'])); } // either way, the balance is always combined with the virtual balance: - $virtualBalance = (string)('' === (string)$account->virtual_balance ? '0' : $account->virtual_balance); + $virtualBalance = (string) ('' === (string) $account->virtual_balance ? '0' : $account->virtual_balance); if ($convertToPrimary) { // the primary currency balance is combined with a converted virtual_balance: - $converter = new ExchangeRateConverter(); - $pcVirtualBalance = $converter->convert($currency, $primary, $date, $virtualBalance); + $converter = new ExchangeRateConverter(); + $pcVirtualBalance = $converter->convert($currency, $primary, $date, $virtualBalance); $return['pc_balance'] = bcadd($pcVirtualBalance, $return['pc_balance']); + // Log::debug(sprintf('Primary virtual balance makes the primary total %s', $return['pc_balance'])); } if (!$convertToPrimary) { // if not, also increase the balance + primary balance for consistency. $return['balance'] = bcadd($return['balance'], $virtualBalance); + // Log::debug(sprintf('Virtual balance makes the (primary currency) total %s', $return['balance'])); } - $final = array_merge($return, $sumsByCode); + $final = array_merge($return, $sumsByCode); $result[$account->id] = $final; Log::debug(sprintf('Final balance for account #%d is', $account->id), $final); } @@ -134,18 +145,23 @@ class Steam * Calls accountsBalancesOptimized for the given accounts and makes sure that inclusive is set to false, so it * properly gets the balance of a range. */ - public function accountsBalancesInRange(Collection $accounts, Carbon $start, Carbon $end, ?TransactionCurrency $primary = null, ?bool $convertToPrimary = null): array - { + public function accountsBalancesInRange( + Collection $accounts, + Carbon $start, + Carbon $end, + null|TransactionCurrency $primary = null, + null|bool $convertToPrimary = null + ): array { return [ $this->accountsBalancesOptimized($accounts, $start, $primary, $convertToPrimary, inclusive: false), - $this->accountsBalancesOptimized($accounts, $end, $primary, $convertToPrimary), + $this->accountsBalancesOptimized($accounts, $end, $primary, $convertToPrimary) ]; } /** * https://stackoverflow.com/questions/1642614/how-to-ceil-floor-and-round-bcmath-numbers */ - public function bcround(?string $number, int $precision = 0): string + public function bcround(null|string $number, int $precision = 0): string { if (null === $number) { return '0'; @@ -161,16 +177,16 @@ class Steam // Log::debug(sprintf('Trying bcround("%s",%d)', $number, $precision)); if (str_contains($number, '.')) { if ('-' !== $number[0]) { - return bcadd($number, '0.'.str_repeat('0', $precision).'5', $precision); + return bcadd($number, '0.' . str_repeat('0', $precision) . '5', $precision); } - return bcsub($number, '0.'.str_repeat('0', $precision).'5', $precision); + return bcsub($number, '0.' . str_repeat('0', $precision) . '5', $precision); } return $number; } - public function filterAccountBalance(array $set, Account $account, bool $convertToPrimary, ?TransactionCurrency $currency = null): array + public function filterAccountBalance(array $set, Account $account, bool $convertToPrimary, null|TransactionCurrency $currency = null): array { Log::debug(sprintf('filterAccountBalance(#%d)', $account->id), $set); if (0 === count($set)) { @@ -221,7 +237,7 @@ class Steam return $set; } - public function filterAccountBalances(array $total, Account $account, bool $convertToPrimary, ?TransactionCurrency $currency = null): array + public function filterAccountBalances(array $total, Account $account, bool $convertToPrimary, null|TransactionCurrency $currency = null): array { Log::debug(sprintf('filterAccountBalances(#%d)', $account->id)); $return = []; @@ -282,7 +298,7 @@ class Steam "\u{3000}", // ideographic space "\u{FEFF}", // zero width no -break space "\x20", // plain old normal space, - ' ', + ' ' ]; // clear zalgo text @@ -292,31 +308,34 @@ class Steam return str_replace($search, '', $string); } - #[Deprecated( - message: <<<'TXT' + #[Deprecated(message: <<<'TXT' - By default this method returns "smaller than or equal to", so be careful with END OF DAY. - If you need end of day balance, use "inclusive = false". + By default this method returns "smaller than or equal to", so be careful with END OF DAY. + If you need end of day balance, use "inclusive = false". - Returns the balance of an account at exact moment given. Array with at least one value. - Always returns: - "balance": balance in the account's currency OR user's primary currency if the account has no currency - "EUR": balance in EUR (or whatever currencies the account has balance in) + Returns the balance of an account at exact moment given. Array with at least one value. + Always returns: + "balance": balance in the account's currency OR user's primary currency if the account has no currency + "EUR": balance in EUR (or whatever currencies the account has balance in) - If the user has $convertToPrimary: - "balance": balance in the account's currency OR user's primary currency if the account has no currency - --> "pc_balance": balance in the user's primary currency, with all amounts converted to the primary currency. - "EUR": balance in EUR (or whatever currencies the account has balance in) - TXT - )] - public function finalAccountBalance(Account $account, Carbon $date, ?TransactionCurrency $primary = null, ?bool $convertToPrimary = null, bool $inclusive = true): array - { - - $cache = new CacheProperties(); + If the user has $convertToPrimary: + "balance": balance in the account's currency OR user's primary currency if the account has no currency + --> "pc_balance": balance in the user's primary currency, with all amounts converted to the primary currency. + "EUR": balance in EUR (or whatever currencies the account has balance in) + TXT)] + public function finalAccountBalance( + Account $account, + Carbon $date, + null|TransactionCurrency $primary = null, + null|bool $convertToPrimary = null, + bool $inclusive = true + ): array { + $cache = new CacheProperties(); $cache->addProperty($account->id); $cache->addProperty($date); if ($cache->has()) { Log::debug(sprintf('CACHED finalAccountBalance(#%d, %s, inclusive:%s)', $account->id, $date->format('Y-m-d H:i:s'), var_export($inclusive, true))); + // return $cache->get(); } Log::debug(sprintf('finalAccountBalance(#%d, %s)', $account->id, $date->format('Y-m-d H:i:s'))); @@ -327,56 +346,58 @@ class Steam $primary = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup); } // account balance thing. - $currencyPresent = isset($account->meta) && array_key_exists('currency', $account->meta) && null !== $account->meta['currency']; + $currencyPresent = isset($account->meta) && array_key_exists('currency', $account->meta) && null !== $account->meta['currency']; if ($currencyPresent) { $accountCurrency = $account->meta['currency']; } if (!$currencyPresent) { $accountCurrency = $this->getAccountCurrency($account); } - $hasCurrency = null !== $accountCurrency; - $currency = $hasCurrency ? $accountCurrency : $primary; - $return = [ - 'pc_balance' => '0', - 'balance' => '0', // this key is overwritten right away, but I must remember it is always created. - ]; + $hasCurrency = null !== $accountCurrency; + $currency = $hasCurrency ? $accountCurrency : $primary; + $return = ['pc_balance' => '0', 'balance' => '0']; // this key is overwritten right away, but I must remember it is always created. // balance(s) in all currencies. - $array = $account->transactions() + $array = $account + ->transactions() ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->leftJoin('transaction_currencies', 'transaction_currencies.id', '=', 'transactions.transaction_currency_id') ->where('transaction_journals.date', $inclusive ? '<=' : '<', $date->format('Y-m-d H:i:s')) - ->get(['transaction_currencies.code', 'transactions.amount'])->toArray() - ; - $others = $this->groupAndSumTransactions($array, 'code', 'amount'); + ->get(['transaction_currencies.code', 'transactions.amount']) + ->toArray(); + $others = $this->groupAndSumTransactions($array, 'code', 'amount'); Log::debug('All balances are (joined)', $others); // if there is no request to convert, take this as "balance" and "pc_balance". $return['balance'] = $others[$currency->code] ?? '0'; if (!$convertToPrimary) { unset($return['pc_balance']); + // Log::debug(sprintf('Set balance to %s, unset pc_balance', $return['balance'])); } // if there is a request to convert, convert to "pc_balance" and use "balance" for whichever amount is in the primary currency. if ($convertToPrimary) { $return['pc_balance'] = $this->convertAllBalances($others, $primary, $date); + // Log::debug(sprintf('Set pc_balance to %s', $return['pc_balance'])); } // either way, the balance is always combined with the virtual balance: - $virtualBalance = (string)('' === (string)$account->virtual_balance ? '0' : $account->virtual_balance); + $virtualBalance = (string) ('' === (string) $account->virtual_balance ? '0' : $account->virtual_balance); if ($convertToPrimary) { // the primary currency balance is combined with a converted virtual_balance: - $converter = new ExchangeRateConverter(); - $pcVirtualBalance = $converter->convert($currency, $primary, $date, $virtualBalance); + $converter = new ExchangeRateConverter(); + $pcVirtualBalance = $converter->convert($currency, $primary, $date, $virtualBalance); $return['pc_balance'] = bcadd($pcVirtualBalance, $return['pc_balance']); + // Log::debug(sprintf('Primary virtual balance makes the primary total %s', $return['pc_balance'])); } if (!$convertToPrimary) { // if not, also increase the balance + primary balance for consistency. $return['balance'] = bcadd($return['balance'], $virtualBalance); + // Log::debug(sprintf('Virtual balance makes the (primary currency) total %s', $return['balance'])); } - $final = array_merge($return, $others); + $final = array_merge($return, $others); Log::debug('Final balance is', $final); $cache->store($final); @@ -394,7 +415,7 @@ class Steam Log::debug(sprintf('called finalAccountBalanceInRange(#%d, %s, %s)', $account->id, $start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s'))); // set up cache - $cache = new CacheProperties(); + $cache = new CacheProperties(); $cache->addProperty($account->id); $cache->addProperty('final-balance-in-range'); $cache->addProperty($start); @@ -402,18 +423,19 @@ class Steam $cache->addProperty($end); if ($cache->has()) { Log::debug('Return cached finalAccountBalanceInRange'); + // return $cache->get(); } - $balances = []; - $formatted = $start->format('Y-m-d'); + $balances = []; + $formatted = $start->format('Y-m-d'); Log::debug('Get first balance to start.'); // 2025-10-08 replaced finalAccountBalance with accountsBalancesOptimized: - $primaryCurrency = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup); - $startBalance = $this->accountsBalancesOptimized(new Collection()->push($account), $start, $primaryCurrency, $convertToPrimary, false)[$account->id]; - $accountCurrency = $this->getAccountCurrency($account); - $hasCurrency = $accountCurrency instanceof TransactionCurrency; - $currency = $accountCurrency ?? $primaryCurrency; + $primaryCurrency = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup); + $startBalance = $this->accountsBalancesOptimized(new Collection()->push($account), $start, $primaryCurrency, $convertToPrimary, false)[$account->id]; + $accountCurrency = $this->getAccountCurrency($account); + $hasCurrency = $accountCurrency instanceof TransactionCurrency; + $currency = $accountCurrency ?? $primaryCurrency; Log::debug(sprintf('Currency is %s', $currency->code)); // set start balances: @@ -425,17 +447,15 @@ class Steam Log::debug(sprintf('Also set start balance in %s', $primaryCurrency->code)); $startBalance[$primaryCurrency->code] ??= '0'; } - $currencies = [ - $currency->id => $currency, - $primaryCurrency->id => $primaryCurrency, - ]; + $currencies = [$currency->id => $currency, $primaryCurrency->id => $primaryCurrency]; $balances[$formatted] = $startBalance; Log::debug('Final start balance: ', $startBalance); // sums up the balance changes per day. Log::debug(sprintf('Date >= %s and <= %s', $start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s'))); - $set = $account->transactions() + $set = $account + ->transactions() ->leftJoin('transaction_journals', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->where('transaction_journals.date', '>=', $start->format('Y-m-d H:i:s')) ->where('transaction_journals.date', '<=', $end->format('Y-m-d H:i:s')) @@ -443,58 +463,50 @@ class Steam ->groupBy('transactions.transaction_currency_id') ->orderBy('transaction_journals.date', 'ASC') ->whereNull('transaction_journals.deleted_at') - ->get( - [ // @phpstan-ignore-line - 'transaction_journals.date', - 'transactions.transaction_currency_id', - DB::raw('SUM(transactions.amount) AS sum_of_day'), - ] - ) - ; - - $currentBalance = $startBalance; - $converter = new ExchangeRateConverter(); + ->get(['transaction_journals.date', 'transactions.transaction_currency_id', DB::raw('SUM(transactions.amount) AS sum_of_day')]); // @phpstan-ignore-line + $currentBalance = $startBalance; + $converter = new ExchangeRateConverter(); /** @var Transaction $entry */ foreach ($set as $entry) { // get date object - $carbon = new Carbon($entry->date, $entry->date_tz); - $carbonKey = $carbon->format('Y-m-d'); + $carbon = new Carbon($entry->date, $entry->date_tz); + $carbonKey = $carbon->format('Y-m-d'); // make sure sum is a string: - $sumOfDay = (string)($entry->sum_of_day ?? '0'); + $sumOfDay = (string) ($entry->sum_of_day ?? '0'); // #10426 make sure sum is not in scientific notation. - $sumOfDay = $this->floatalize($sumOfDay); + $sumOfDay = $this->floatalize($sumOfDay); // find currency of this entry, does not have to exist. $currencies[$entry->transaction_currency_id] ??= Amount::getTransactionCurrencyById($entry->transaction_currency_id); // make sure this $entry has its own $entryCurrency /** @var TransactionCurrency $entryCurrency */ - $entryCurrency = $currencies[$entry->transaction_currency_id]; + $entryCurrency = $currencies[$entry->transaction_currency_id]; Log::debug(sprintf('Processing transaction(s) on moment %s', $carbon->format('Y-m-d H:i:s'))); // add amount to current balance in currency code. - $currentBalance[$entryCurrency->code] ??= '0'; - $currentBalance[$entryCurrency->code] = bcadd($sumOfDay, (string)$currentBalance[$entryCurrency->code]); + $currentBalance[$entryCurrency->code] ??= '0'; + $currentBalance[$entryCurrency->code] = bcadd($sumOfDay, (string) $currentBalance[$entryCurrency->code]); // if not requested to convert to primary currency, add the amount to "balance", do nothing else. if (!$convertToPrimary) { - $currentBalance['balance'] = bcadd((string)$currentBalance['balance'], $sumOfDay); + $currentBalance['balance'] = bcadd((string) $currentBalance['balance'], $sumOfDay); } // if convert to primary currency add the converted amount to "pc_balance". // if there is a request to convert, convert to "pc_balance" and use "balance" for whichever amount is in the primary currency. if ($convertToPrimary) { - $pcSumOfDay = $converter->convert($entryCurrency, $primaryCurrency, $carbon, $sumOfDay); - $currentBalance['pc_balance'] = bcadd((string)($currentBalance['pc_balance'] ?? '0'), $pcSumOfDay); + $pcSumOfDay = $converter->convert($entryCurrency, $primaryCurrency, $carbon, $sumOfDay); + $currentBalance['pc_balance'] = bcadd((string) ($currentBalance['pc_balance'] ?? '0'), $pcSumOfDay); // if it's the same currency as the entry, also add to balance (see other code). if ($currency->id === $entryCurrency->id) { - $currentBalance['balance'] = bcadd((string)$currentBalance['balance'], $sumOfDay); + $currentBalance['balance'] = bcadd((string) $currentBalance['balance'], $sumOfDay); } } // add to final array. - $balances[$carbonKey] = $currentBalance; + $balances[$carbonKey] = $currentBalance; Log::debug(sprintf('Updated entry [%s]', $carbonKey), $currentBalance); } $cache->store($balances); @@ -511,32 +523,32 @@ class Steam */ public function floatalize(string $value): string { - $value = strtoupper($value); + $value = strtoupper($value); if (!str_contains($value, 'E')) { return $value; } Log::debug(sprintf('Floatalizing %s', $value)); - $number = substr($value, 0, (int)strpos($value, 'E')); + $number = substr($value, 0, (int) strpos($value, 'E')); if (str_contains($number, '.')) { - $post = strlen(substr($number, (int)strpos($number, '.') + 1)); - $mantis = substr($value, (int)strpos($value, 'E') + 1); + $post = strlen(substr($number, (int) strpos($number, '.') + 1)); + $mantis = substr($value, (int) strpos($value, 'E') + 1); if ($mantis < 0) { - $post += abs((int)$mantis); + $post += abs((int) $mantis); } // TODO careless float could break financial math. - return number_format((float)$value, $post, '.', ''); + return number_format((float) $value, $post, '.', ''); } // TODO careless float could break financial math. - return number_format((float)$value, 0, '.', ''); + return number_format((float) $value, 0, '.', ''); } - public function getAccountCurrency(Account $account): ?TransactionCurrency + public function getAccountCurrency(Account $account): null|TransactionCurrency { - $type = $account->accountType->type; - $list = config('firefly.valid_currency_account_types'); + $type = $account->accountType->type; + $list = config('firefly.valid_currency_account_types'); // return null if not in this list. if (!in_array($type, $list, true)) { @@ -547,7 +559,7 @@ class Steam return null; } - return Amount::getTransactionCurrencyById((int)$result->data); + return Amount::getTransactionCurrencyById((int) $result->data); } public function getHostName(string $ipAddress): string @@ -561,11 +573,11 @@ class Steam $hostName = $ipAddress; } - if ('' !== (string)$hostName && $hostName !== $ipAddress) { + if ('' !== (string) $hostName && $hostName !== $ipAddress) { $host = $hostName; } - return (string)$host; + return (string) $host; } /** @@ -589,17 +601,18 @@ class Steam { $list = []; - $set = auth()->user()->transactions() + $set = auth() + ->user() + ->transactions() ->whereIn('transactions.account_id', $accounts) ->groupBy(['transactions.account_id', 'transaction_journals.user_id']) - ->get(['transactions.account_id', DB::raw('MAX(transaction_journals.date) AS max_date')]) // @phpstan-ignore-line - ; + ->get(['transactions.account_id', DB::raw('MAX(transaction_journals.date) AS max_date')]); // @phpstan-ignore-line /** @var Transaction $entry */ foreach ($set as $entry) { - $date = new Carbon($entry->max_date, config('app.timezone')); + $date = new Carbon($entry->max_date, config('app.timezone')); $date->setTimezone(config('app.timezone')); - $list[(int)$entry->account_id] = $date; + $list[(int) $entry->account_id] = $date; } return $list; @@ -615,14 +628,14 @@ class Steam if (null !== $cached) { return $cached; } - $locale = Preferences::get('locale', config('firefly.default_locale', 'equal'))->data; + $locale = Preferences::get('locale', config('firefly.default_locale', 'equal'))->data; if (is_array($locale)) { $locale = 'equal'; } if ('equal' === $locale) { $locale = $this->getLanguage(); } - $locale = (string)$locale; + $locale = (string) $locale; // Check for Windows to replace the locale correctly. if ('WIN' === strtoupper(substr(PHP_OS, 0, 3))) { @@ -648,10 +661,7 @@ class Steam public function getLocaleArray(string $locale): array { - return [ - sprintf('%s.utf8', $locale), - sprintf('%s.UTF-8', $locale), - ]; + return [sprintf('%s.utf8', $locale), sprintf('%s.UTF-8', $locale)]; } /** @@ -678,7 +688,7 @@ class Steam public function getSafeUrl(string $unknownUrl, string $safeUrl): string { // Log::debug(sprintf('getSafeUrl(%s, %s)', $unknownUrl, $safeUrl)); - $returnUrl = $safeUrl; + $returnUrl = $safeUrl; // die('in get safe url'); try { @@ -724,7 +734,7 @@ class Steam return $amount; } - public function opposite(?string $amount = null): ?string + public function opposite(null|string $amount = null): null|string { if (null === $amount) { return null; @@ -741,24 +751,24 @@ class Steam // has a K in it, remove the K and multiply by 1024. $bytes = bcmul(rtrim($string, 'k'), '1024'); - return (int)$bytes; + return (int) $bytes; } if (false !== stripos($string, 'm')) { // has a M in it, remove the M and multiply by 1048576. $bytes = bcmul(rtrim($string, 'm'), '1048576'); - return (int)$bytes; + return (int) $bytes; } if (false !== stripos($string, 'g')) { // has a G in it, remove the G and multiply by (1024)^3. $bytes = bcmul(rtrim($string, 'g'), '1073741824'); - return (int)$bytes; + return (int) $bytes; } - return (int)$string; + return (int) $string; } public function positive(string $amount): string @@ -797,12 +807,12 @@ class Steam if (null === $preference) { $singleton->setPreference($key, $currency); } - $current = $amount; + $current = $amount; if ($currency->id !== $primary->id) { $current = $converter->convert($currency, $primary, $date, $amount); Log::debug(sprintf('Convert %s %s to %s %s', $currency->code, $amount, $primary->code, $current)); } - $total = bcadd((string)$current, $total); + $total = bcadd((string) $current, $total); } return $total; @@ -810,24 +820,24 @@ class Steam private function getCurrencies(Collection $accounts): array { - $currencies = []; - $accountCurrencies = []; - $accountPreferences = []; - $primary = Amount::getPrimaryCurrency(); + $currencies = []; + $accountCurrencies = []; + $accountPreferences = []; + $primary = Amount::getPrimaryCurrency(); $currencies[$primary->id] = $primary; - $ids = $accounts->pluck('id')->toArray(); - $result = AccountMeta::whereIn('account_id', $ids)->where('name', 'currency_id')->get(); + $ids = $accounts->pluck('id')->toArray(); + $result = AccountMeta::whereIn('account_id', $ids)->where('name', 'currency_id')->get(); /** @var AccountMeta $item */ foreach ($result as $item) { - $integer = (int)$item->data; + $integer = (int) $item->data; if (0 !== $integer) { - $accountPreferences[(int)$item->account_id] = $integer; + $accountPreferences[(int) $item->account_id] = $integer; } } // collect those currencies, skip primary because we already have it. - $set = TransactionCurrency::whereIn('id', $accountPreferences)->where('id', '!=', $primary->id)->get(); + $set = TransactionCurrency::whereIn('id', $accountPreferences)->where('id', '!=', $primary->id)->get(); foreach ($set as $item) { $currencies[$item->id] = $item; } @@ -837,7 +847,7 @@ class Steam $accountId = $account->id; $currencyPresent = isset($account->meta) && array_key_exists('currency', $account->meta) && null !== $account->meta['currency']; if ($currencyPresent) { - $currencyId = $account->meta['currency']->id; + $currencyId = $account->meta['currency']->id; $currencies[$currencyId] ??= $account->meta['currency']; $accountCurrencies[$accountId] = $account->meta['currency']; } @@ -857,8 +867,8 @@ class Steam $return = []; foreach ($array as $item) { - $groupKey = $item[$group] ?? 'unknown'; - $return[$groupKey] = bcadd($return[$groupKey] ?? '0', (string)$item[$field]); + $groupKey = $item[$group] ?? 'unknown'; + $return[$groupKey] = bcadd($return[$groupKey] ?? '0', (string) $item[$field]); } return $return; diff --git a/app/Support/System/GeneratesInstallationId.php b/app/Support/System/GeneratesInstallationId.php index 93cde62b2e..79b972ef22 100644 --- a/app/Support/System/GeneratesInstallationId.php +++ b/app/Support/System/GeneratesInstallationId.php @@ -24,10 +24,10 @@ declare(strict_types=1); namespace FireflyIII\Support\System; -use Illuminate\Support\Facades\Log; use FireflyIII\Exceptions\FireflyException; -use Ramsey\Uuid\Uuid; use FireflyIII\Support\Facades\FireflyConfig; +use Illuminate\Support\Facades\Log; +use Ramsey\Uuid\Uuid; /** * Trait GeneratesInstallationId @@ -51,7 +51,7 @@ trait GeneratesInstallationId if (null === $config) { $uuid4 = Uuid::uuid4(); - $uniqueId = (string)$uuid4; + $uniqueId = (string) $uuid4; Log::info(sprintf('Created Firefly III installation ID %s', $uniqueId)); FireflyConfig::set('installation_id', $uniqueId); } diff --git a/app/Support/System/IsOldVersion.php b/app/Support/System/IsOldVersion.php index 345463abfe..a4c1831f60 100644 --- a/app/Support/System/IsOldVersion.php +++ b/app/Support/System/IsOldVersion.php @@ -1,6 +1,7 @@ lt($latestDate)) { Log::debug(sprintf('This current version is older, current = %s, latest version %s.', $current, $latest)); @@ -67,12 +68,16 @@ trait IsOldVersion protected function isOldVersionInstalled(): bool { // version compare thing. - $configBuildTime = (int)config('firefly.build_time'); - $dbBuildTime = (int)FireflyConfig::getFresh('ff3_build_time', 123)->data; + $configBuildTime = (int) config('firefly.build_time'); + $dbBuildTime = (int) FireflyConfig::getFresh('ff3_build_time', 123)->data; $configTime = Carbon::createFromTimestamp($configBuildTime, config('app.timezone')); $dbTime = Carbon::createFromTimestamp($dbBuildTime, config('app.timezone')); if ($dbBuildTime < $configBuildTime) { - Log::warning(sprintf('Your database was last managed by an older version of Firefly III (I see %s, I expect %s). Redirect to migrate routine.', $dbTime->format('Y-m-d H:i:s'), $configTime->format('Y-m-d H:i:s'))); + Log::warning(sprintf( + 'Your database was last managed by an older version of Firefly III (I see %s, I expect %s). Redirect to migrate routine.', + $dbTime->format('Y-m-d H:i:s'), + $configTime->format('Y-m-d H:i:s') + )); return true; } diff --git a/app/Support/System/OAuthKeys.php b/app/Support/System/OAuthKeys.php index f753722aa9..3930e2941a 100644 --- a/app/Support/System/OAuthKeys.php +++ b/app/Support/System/OAuthKeys.php @@ -65,7 +65,7 @@ class OAuthKeys Log::debug(sprintf('Private key file at "%s" exists? %s', $private, var_export($privateExists, true))); Log::debug(sprintf('Public key file at "%s" exists ? %s', $public, var_export($publicExists, true))); - $result = file_exists($private) && file_exists($public); + $result = file_exists($private) && file_exists($public); Log::debug(sprintf('Method will return %s', var_export($result, true))); return $result; @@ -83,8 +83,8 @@ class OAuthKeys if ($hasPrivate && $hasPublic) { try { - $privateKey = trim((string)FireflyConfig::get(self::PRIVATE_KEY)?->data); - $publicKey = trim((string)FireflyConfig::get(self::PUBLIC_KEY)?->data); + $privateKey = trim((string) FireflyConfig::get(self::PRIVATE_KEY)?->data); + $publicKey = trim((string) FireflyConfig::get(self::PUBLIC_KEY)?->data); } catch (ContainerExceptionInterface|FireflyException|NotFoundExceptionInterface $e) { Log::error(sprintf('Could not validate keysInDatabase(): %s', $e->getMessage())); Log::error($e->getTraceAsString()); @@ -102,7 +102,7 @@ class OAuthKeys if ('' !== $publicKey) { Log::debug(sprintf('SHA2 hash of public key in DB : %s', hash('sha256', $publicKey))); } - $return = '' !== $privateKey && '' !== $publicKey; + $return = '' !== $privateKey && '' !== $publicKey; Log::debug(sprintf('keysInDatabase will return %s', var_export($return, true))); return $return; @@ -117,8 +117,8 @@ class OAuthKeys public static function restoreKeysFromDB(): bool { Log::debug('restoreKeysFromDB()'); - $privateKey = (string)FireflyConfig::get(self::PRIVATE_KEY)?->data; - $publicKey = (string)FireflyConfig::get(self::PUBLIC_KEY)?->data; + $privateKey = (string) FireflyConfig::get(self::PRIVATE_KEY)?->data; + $publicKey = (string) FireflyConfig::get(self::PUBLIC_KEY)?->data; if ('' === $privateKey) { Log::warning('Private key is not in the database.'); @@ -141,8 +141,8 @@ class OAuthKeys return false; } - $private = storage_path('oauth-private.key'); - $public = storage_path('oauth-public.key'); + $private = storage_path('oauth-private.key'); + $public = storage_path('oauth-public.key'); file_put_contents($private, $privateContent); file_put_contents($public, $publicContent); @@ -162,8 +162,18 @@ class OAuthKeys FireflyConfig::set(self::PRIVATE_KEY, Crypt::encrypt($privateContent)); FireflyConfig::set(self::PUBLIC_KEY, Crypt::encrypt($publicContent)); - Log::debug(sprintf('Will store the content of file "%s" as "%s" in the database (hash: %s)', $private, self::PRIVATE_KEY, hash('sha256', $privateContent))); - Log::debug(sprintf('Will store the content of file "%s" as "%s" in the database (hash: %s)', $public, self::PUBLIC_KEY, hash('sha256', $publicContent))); + Log::debug(sprintf( + 'Will store the content of file "%s" as "%s" in the database (hash: %s)', + $private, + self::PRIVATE_KEY, + hash('sha256', $privateContent) + )); + Log::debug(sprintf( + 'Will store the content of file "%s" as "%s" in the database (hash: %s)', + $public, + self::PUBLIC_KEY, + hash('sha256', $publicContent) + )); } public static function verifyKeysRoutine(): void diff --git a/app/Support/Twig/AmountFormat.php b/app/Support/Twig/AmountFormat.php index dbf22254b3..d42d2c9abc 100644 --- a/app/Support/Twig/AmountFormat.php +++ b/app/Support/Twig/AmountFormat.php @@ -42,21 +42,13 @@ class AmountFormat extends AbstractExtension #[Override] public function getFilters(): array { - return [ - $this->formatAmount(), - $this->formatAmountPlain(), - ]; + return [$this->formatAmount(), $this->formatAmountPlain()]; } #[Override] public function getFunctions(): array { - return [ - $this->formatAmountByAccount(), - $this->formatAmountBySymbol(), - $this->formatAmountByCurrency(), - $this->formatAmountByCode(), - ]; + return [$this->formatAmountByAccount(), $this->formatAmountBySymbol(), $this->formatAmountByCurrency(), $this->formatAmountByCode()]; } protected function formatAmount(): TwigFilter @@ -81,7 +73,7 @@ class AmountFormat extends AbstractExtension { return new TwigFunction( 'formatAmountByAccount', - static function (AccountModel $account, string $amount, ?bool $coloured = null): string { + static function (AccountModel $account, string $amount, null|bool $coloured = null): string { $coloured ??= true; /** @var AccountRepositoryInterface $accountRepos */ @@ -102,7 +94,7 @@ class AmountFormat extends AbstractExtension // formatAmountByCode return new TwigFunction( 'formatAmountByCode', - static function (string $amount, string $code, ?bool $coloured = null): string { + static function (string $amount, string $code, null|bool $coloured = null): string { $coloured ??= true; try { @@ -126,7 +118,7 @@ class AmountFormat extends AbstractExtension { return new TwigFunction( 'formatAmountByCurrency', - static function (TransactionCurrency $currency, string $amount, ?bool $coloured = null): string { + static function (TransactionCurrency $currency, string $amount, null|bool $coloured = null): string { $coloured ??= true; return Amount::formatAnything($currency, $amount, $coloured); @@ -142,18 +134,23 @@ class AmountFormat extends AbstractExtension { return new TwigFunction( 'formatAmountBySymbol', - static function (string $amount, ?string $symbol = null, ?int $decimalPlaces = null, ?bool $coloured = null): string { - + static function (string $amount, null|string $symbol = null, null|int $decimalPlaces = null, null|bool $coloured = null): string { if (null === $symbol) { - $message = sprintf('formatAmountBySymbol("%s", %s, %d, %s) was called without a symbol. Please browse to /flush to clear your cache.', $amount, var_export($symbol, true), $decimalPlaces, var_export($coloured, true)); + $message = sprintf( + 'formatAmountBySymbol("%s", %s, %d, %s) was called without a symbol. Please browse to /flush to clear your cache.', + $amount, + var_export($symbol, true), + $decimalPlaces, + var_export($coloured, true) + ); Log::error($message); $currency = Amount::getPrimaryCurrency(); } if (null !== $symbol) { $decimalPlaces ??= 2; $coloured ??= true; - $currency = new TransactionCurrency(); - $currency->symbol = $symbol; + $currency = new TransactionCurrency(); + $currency->symbol = $symbol; $currency->decimal_places = $decimalPlaces; } diff --git a/app/Support/Twig/General.php b/app/Support/Twig/General.php index 12ddcfc696..05576787ca 100644 --- a/app/Support/Twig/General.php +++ b/app/Support/Twig/General.php @@ -50,13 +50,7 @@ class General extends AbstractExtension #[Override] public function getFilters(): array { - return [ - $this->balance(), - $this->formatFilesize(), - $this->mimeIcon(), - $this->markdown(), - $this->phpHostName(), - ]; + return [$this->balance(), $this->formatFilesize(), $this->mimeIcon(), $this->markdown(), $this->phpHostName()]; } #[Override] @@ -73,7 +67,7 @@ class General extends AbstractExtension $this->hasRole(), $this->getRootSearchOperator(), $this->carbonize(), - $this->fireflyIIIConfig(), + $this->fireflyIIIConfig() ]; } @@ -83,19 +77,16 @@ class General extends AbstractExtension */ protected function activeRoutePartial(): TwigFunction { - return new TwigFunction( - 'activeRoutePartial', - static function (): string { - $args = func_get_args(); - $route = $args[0]; // name of the route. - $name = Route::getCurrentRoute()->getName() ?? ''; - if (str_contains($name, $route)) { - return 'active'; - } - - return ''; + return new TwigFunction('activeRoutePartial', static function (): string { + $args = func_get_args(); + $route = $args[0]; // name of the route. + $name = Route::getCurrentRoute()->getName() ?? ''; + if (str_contains($name, $route)) { + return 'active'; } - ); + + return ''; + }); } /** @@ -108,13 +99,9 @@ class General extends AbstractExtension 'activeRoutePartialObjectType', static function (array $context): string { [, $route, $objectType] = func_get_args(); - $activeObjectType = $context['objectType'] ?? false; + $activeObjectType = $context['objectType'] ?? false; - if ($objectType === $activeObjectType - && false !== stripos( - (string)Route::getCurrentRoute()->getName(), - (string)$route - )) { + if ($objectType === $activeObjectType && false !== stripos((string) Route::getCurrentRoute()->getName(), (string) $route)) { return 'active'; } @@ -130,19 +117,16 @@ class General extends AbstractExtension */ protected function activeRouteStrict(): TwigFunction { - return new TwigFunction( - 'activeRouteStrict', - static function (): string { - $args = func_get_args(); - $route = $args[0]; // name of the route. + return new TwigFunction('activeRouteStrict', static function (): string { + $args = func_get_args(); + $route = $args[0]; // name of the route. - if (\Route::getCurrentRoute()->getName() === $route) { - return 'active'; - } - - return ''; + if (\Route::getCurrentRoute()->getName() === $route) { + return 'active'; } - ); + + return ''; + }); } /** @@ -150,69 +134,64 @@ class General extends AbstractExtension */ protected function balance(): TwigFilter { - return new TwigFilter( - 'balance', - static function (?Account $account): string { - if (!$account instanceof Account) { - return '0'; - } - - /** @var Carbon $date */ - $date = now(); - - // get the date from the current session. If it's in the future, keep `now()`. - /** @var Carbon $session */ - $session = clone session('end', today(config('app.timezone'))->endOfMonth()); - if ($session->lt($date)) { - $date = $session->copy(); - $date->endOfDay(); - } - Log::debug(sprintf('twig balance: Call finalAccountBalance with date/time "%s"', $date->toIso8601String())); - - // 2025-10-08 replace finalAccountBalance with accountsBalancesOptimized. - $info = Steam::accountsBalancesOptimized(new Collection()->push($account), $date)[$account->id]; - // $info = Steam::finalAccountBalance($account, $date); - $currency = Steam::getAccountCurrency($account); - $primary = Amount::getPrimaryCurrency(); - $convertToPrimary = Amount::convertToPrimary(); - $usePrimary = $convertToPrimary && $primary->id !== $currency->id; - $currency ??= $primary; - $strings = []; - foreach ($info as $key => $balance) { - if ('balance' === $key) { - // balance in account currency. - if (!$usePrimary) { - $strings[] = Amount::formatAnything($currency, $balance, false); - } - - continue; - } - if ('pc_balance' === $key) { - // balance in primary currency. - if ($usePrimary) { - $strings[] = Amount::formatAnything($primary, $balance, false); - } - - continue; - } - // for multi currency accounts. - if ($usePrimary && $key !== $primary->code) { - $strings[] = Amount::formatAnything(Amount::getTransactionCurrencyByCode($key), $balance, false); - } - } - - return implode(', ', $strings); - // return \FireflyIII\Support\Facades\Steam::balance($account, $date); + return new TwigFilter('balance', static function (null|Account $account): string { + if (!$account instanceof Account) { + return '0'; } - ); + + /** @var Carbon $date */ + $date = now(); + + // get the date from the current session. If it's in the future, keep `now()`. + /** @var Carbon $session */ + $session = clone session('end', today(config('app.timezone'))->endOfMonth()); + if ($session->lt($date)) { + $date = $session->copy(); + $date->endOfDay(); + } + Log::debug(sprintf('twig balance: Call finalAccountBalance with date/time "%s"', $date->toIso8601String())); + + // 2025-10-08 replace finalAccountBalance with accountsBalancesOptimized. + $info = Steam::accountsBalancesOptimized(new Collection()->push($account), $date)[$account->id]; + // $info = Steam::finalAccountBalance($account, $date); + $currency = Steam::getAccountCurrency($account); + $primary = Amount::getPrimaryCurrency(); + $convertToPrimary = Amount::convertToPrimary(); + $usePrimary = $convertToPrimary && $primary->id !== $currency->id; + $currency ??= $primary; + $strings = []; + foreach ($info as $key => $balance) { + if ('balance' === $key) { + // balance in account currency. + if (!$usePrimary) { + $strings[] = Amount::formatAnything($currency, $balance, false); + } + + continue; + } + if ('pc_balance' === $key) { + // balance in primary currency. + if ($usePrimary) { + $strings[] = Amount::formatAnything($primary, $balance, false); + } + + continue; + } + // for multi currency accounts. + if ($usePrimary && $key !== $primary->code) { + $strings[] = Amount::formatAnything(Amount::getTransactionCurrencyByCode($key), $balance, false); + } + } + + return implode(', ', $strings); + + // return \FireflyIII\Support\Facades\Steam::balance($account, $date); + }); } protected function carbonize(): TwigFunction { - return new TwigFunction( - 'carbonize', - static fn (string $date): Carbon => new Carbon($date, config('app.timezone')) - ); + return new TwigFunction('carbonize', static fn(string $date): Carbon => new Carbon($date, config('app.timezone'))); } /** @@ -220,14 +199,11 @@ class General extends AbstractExtension */ protected function formatDate(): TwigFunction { - return new TwigFunction( - 'formatDate', - static function (string $date, string $format): string { - $carbon = new Carbon($date); + return new TwigFunction('formatDate', static function (string $date, string $format): string { + $carbon = new Carbon($date); - return $carbon->isoFormat($format); - } - ); + return $carbon->isoFormat($format); + }); } /** @@ -235,22 +211,19 @@ class General extends AbstractExtension */ protected function formatFilesize(): TwigFilter { - return new TwigFilter( - 'filesize', - static function (int $size): string { - // less than one GB, more than one MB - if ($size < (1024 * 1024 * 2014) && $size >= (1024 * 1024)) { - return round($size / (1024 * 1024), 2).' MB'; - } - - // less than one MB - if ($size < (1024 * 1024)) { - return round($size / 1024, 2).' KB'; - } - - return $size.' bytes'; + return new TwigFilter('filesize', static function (int $size): string { + // less than one GB, more than one MB + if ($size < (1024 * 1024 * 2014) && $size >= (1024 * 1024)) { + return round($size / (1024 * 1024), 2) . ' MB'; } - ); + + // less than one MB + if ($size < (1024 * 1024)) { + return round($size / 1024, 2) . ' KB'; + } + + return $size . ' bytes'; + }); } /** @@ -258,31 +231,25 @@ class General extends AbstractExtension */ protected function getMetaField(): TwigFunction { - return new TwigFunction( - 'accountGetMetaField', - static function (Account $account, string $field): string { - /** @var AccountRepositoryInterface $repository */ - $repository = app(AccountRepositoryInterface::class); - $result = $repository->getMetaValue($account, $field); - if (null === $result) { - return ''; - } - - return $result; + return new TwigFunction('accountGetMetaField', static function (Account $account, string $field): string { + /** @var AccountRepositoryInterface $repository */ + $repository = app(AccountRepositoryInterface::class); + $result = $repository->getMetaValue($account, $field); + if (null === $result) { + return ''; } - ); + + return $result; + }); } protected function getRootSearchOperator(): TwigFunction { - return new TwigFunction( - 'getRootSearchOperator', - static function (string $operator): string { - $result = OperatorQuerySearch::getRootOperator($operator); + return new TwigFunction('getRootSearchOperator', static function (string $operator): string { + $result = OperatorQuerySearch::getRootOperator($operator); - return str_replace('-', 'not_', $result); - } - ); + return str_replace('-', 'not_', $result); + }); } /** @@ -290,14 +257,11 @@ class General extends AbstractExtension */ protected function hasRole(): TwigFunction { - return new TwigFunction( - 'hasRole', - static function (string $role): bool { - $repository = app(UserRepositoryInterface::class); + return new TwigFunction('hasRole', static function (string $role): bool { + $repository = app(UserRepositoryInterface::class); - return $repository->hasRole(auth()->user(), $role); - } - ); + return $repository->hasRole(auth()->user(), $role); + }); } protected function markdown(): TwigFilter @@ -305,15 +269,9 @@ class General extends AbstractExtension return new TwigFilter( 'markdown', static function (string $text): string { - $converter = new GithubFlavoredMarkdownConverter( - [ - 'allow_unsafe_links' => false, - 'max_nesting_level' => 5, - 'html_input' => 'escape', - ] - ); + $converter = new GithubFlavoredMarkdownConverter(['allow_unsafe_links' => false, 'max_nesting_level' => 5, 'html_input' => 'escape']); - return (string)$converter->convert($text); + return (string) $converter->convert($text); }, ['is_safe' => ['html']] ); @@ -325,19 +283,16 @@ class General extends AbstractExtension */ protected function menuOpenRoutePartial(): TwigFunction { - return new TwigFunction( - 'menuOpenRoutePartial', - static function (): string { - $args = func_get_args(); - $route = $args[0]; // name of the route. - $name = Route::getCurrentRoute()->getName() ?? ''; - if (str_contains($name, $route)) { - return 'menu-open'; - } - - return ''; + return new TwigFunction('menuOpenRoutePartial', static function (): string { + $args = func_get_args(); + $route = $args[0]; // name of the route. + $name = Route::getCurrentRoute()->getName() ?? ''; + if (str_contains($name, $route)) { + return 'menu-open'; } - ); + + return ''; + }); } /** @@ -349,15 +304,62 @@ class General extends AbstractExtension { return new TwigFilter( 'mimeIcon', - static fn (string $string): string => match ($string) { - 'application/pdf' => 'fa-file-pdf-o', - 'image/webp', 'image/png', 'image/jpeg', 'image/svg+xml', 'image/heic', 'image/heic-sequence', 'application/vnd.oasis.opendocument.image' => 'fa-file-image-o', - 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'application/x-iwork-pages-sffpages', 'application/vnd.sun.xml.writer', 'application/vnd.sun.xml.writer.template', 'application/vnd.sun.xml.writer.global', 'application/vnd.stardivision.writer', 'application/vnd.stardivision.writer-global', 'application/vnd.oasis.opendocument.text', 'application/vnd.oasis.opendocument.text-template', 'application/vnd.oasis.opendocument.text-web', 'application/vnd.oasis.opendocument.text-master' => 'fa-file-word-o', - 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'application/vnd.sun.xml.calc', 'application/vnd.sun.xml.calc.template', 'application/vnd.stardivision.calc', 'application/vnd.oasis.opendocument.spreadsheet', 'application/vnd.oasis.opendocument.spreadsheet-template' => 'fa-file-excel-o', - 'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'application/vnd.openxmlformats-officedocument.presentationml.template', 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'application/vnd.sun.xml.impress', 'application/vnd.sun.xml.impress.template', 'application/vnd.stardivision.impress', 'application/vnd.oasis.opendocument.presentation', 'application/vnd.oasis.opendocument.presentation-template' => 'fa-file-powerpoint-o', - 'application/vnd.sun.xml.draw', 'application/vnd.sun.xml.draw.template', 'application/vnd.stardivision.draw', 'application/vnd.oasis.opendocument.chart' => 'fa-paint-brush', - 'application/vnd.oasis.opendocument.graphics', 'application/vnd.oasis.opendocument.graphics-template', 'application/vnd.sun.xml.math', 'application/vnd.stardivision.math', 'application/vnd.oasis.opendocument.formula', 'application/vnd.oasis.opendocument.database' => 'fa-calculator', - default => 'fa-file-o', + static fn(string $string): string => match ($string) { + 'application/pdf' => 'fa-file-pdf-o', + 'image/webp', + 'image/png', + 'image/jpeg', + 'image/svg+xml', + 'image/heic', + 'image/heic-sequence', + 'application/vnd.oasis.opendocument.image' + => 'fa-file-image-o', + 'application/msword', + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', + 'application/x-iwork-pages-sffpages', + 'application/vnd.sun.xml.writer', + 'application/vnd.sun.xml.writer.template', + 'application/vnd.sun.xml.writer.global', + 'application/vnd.stardivision.writer', + 'application/vnd.stardivision.writer-global', + 'application/vnd.oasis.opendocument.text', + 'application/vnd.oasis.opendocument.text-template', + 'application/vnd.oasis.opendocument.text-web', + 'application/vnd.oasis.opendocument.text-master' + => 'fa-file-word-o', + 'application/vnd.ms-excel', + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', + 'application/vnd.sun.xml.calc', + 'application/vnd.sun.xml.calc.template', + 'application/vnd.stardivision.calc', + 'application/vnd.oasis.opendocument.spreadsheet', + 'application/vnd.oasis.opendocument.spreadsheet-template' + => 'fa-file-excel-o', + 'application/vnd.ms-powerpoint', + 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + 'application/vnd.openxmlformats-officedocument.presentationml.template', + 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', + 'application/vnd.sun.xml.impress', + 'application/vnd.sun.xml.impress.template', + 'application/vnd.stardivision.impress', + 'application/vnd.oasis.opendocument.presentation', + 'application/vnd.oasis.opendocument.presentation-template' + => 'fa-file-powerpoint-o', + 'application/vnd.sun.xml.draw', + 'application/vnd.sun.xml.draw.template', + 'application/vnd.stardivision.draw', + 'application/vnd.oasis.opendocument.chart' + => 'fa-paint-brush', + 'application/vnd.oasis.opendocument.graphics', + 'application/vnd.oasis.opendocument.graphics-template', + 'application/vnd.sun.xml.math', + 'application/vnd.stardivision.math', + 'application/vnd.oasis.opendocument.formula', + 'application/vnd.oasis.opendocument.database' + => 'fa-calculator', + default => 'fa-file-o' }, ['is_safe' => ['html']] ); @@ -368,21 +370,18 @@ class General extends AbstractExtension */ protected function phpHostName(): TwigFilter { - return new TwigFilter( - 'phphost', - static function (string $string): string { - $proto = parse_url($string, PHP_URL_SCHEME); - $host = parse_url($string, PHP_URL_HOST); - if (is_array($host)) { - $host = implode(' ', $host); - } - if (is_array($proto)) { - $proto = implode(' ', $proto); - } - - return e(sprintf('%s://%s', $proto, $host)); + return new TwigFilter('phphost', static function (string $string): string { + $proto = parse_url($string, PHP_URL_SCHEME); + $host = parse_url($string, PHP_URL_HOST); + if (is_array($host)) { + $host = implode(' ', $host); } - ); + if (is_array($proto)) { + $proto = implode(' ', $proto); + } + + return e(sprintf('%s://%s', $proto, $host)); + }); } /** @@ -390,17 +389,11 @@ class General extends AbstractExtension */ protected function phpdate(): TwigFunction { - return new TwigFunction( - 'phpdate', - date(...) - ); + return new TwigFunction('phpdate', date(...)); } private function fireflyIIIConfig() { - return new TwigFunction( - 'fireflyiiiconfig', - static fn (string $string, mixed $default): mixed => FireflyConfig::get($string, $default)->data - ); + return new TwigFunction('fireflyiiiconfig', static fn(string $string, mixed $default): mixed => FireflyConfig::get($string, $default)->data); } } diff --git a/app/Support/Twig/Rule.php b/app/Support/Twig/Rule.php index afd1d49bb4..5c610264e3 100644 --- a/app/Support/Twig/Rule.php +++ b/app/Support/Twig/Rule.php @@ -35,62 +35,49 @@ class Rule extends AbstractExtension { public function allActionTriggers(): TwigFunction { - return new TwigFunction( - 'allRuleActions', - static function (): array { - // array of valid values for actions - $ruleActions = array_keys(Config::get('firefly.rule-actions')); - $possibleActions = []; - foreach ($ruleActions as $key) { - $possibleActions[$key] = (string)trans('firefly.rule_action_'.$key.'_choice'); - } - unset($ruleActions); - asort($possibleActions); - - return $possibleActions; + return new TwigFunction('allRuleActions', static function (): array { + // array of valid values for actions + $ruleActions = array_keys(Config::get('firefly.rule-actions')); + $possibleActions = []; + foreach ($ruleActions as $key) { + $possibleActions[$key] = (string) trans('firefly.rule_action_' . $key . '_choice'); } - ); + unset($ruleActions); + asort($possibleActions); + + return $possibleActions; + }); } public function allJournalTriggers(): TwigFunction { - return new TwigFunction( - 'allJournalTriggers', - static fn (): array => [ - 'store-journal' => (string)trans('firefly.rule_trigger_store_journal'), - 'update-journal' => (string)trans('firefly.rule_trigger_update_journal'), - 'manual-activation' => (string)trans('firefly.rule_trigger_manual'), - ] - ); + return new TwigFunction('allJournalTriggers', static fn(): array => [ + 'store-journal' => (string) trans('firefly.rule_trigger_store_journal'), + 'update-journal' => (string) trans('firefly.rule_trigger_update_journal'), + 'manual-activation' => (string) trans('firefly.rule_trigger_manual') + ]); } public function allRuleTriggers(): TwigFunction { - return new TwigFunction( - 'allRuleTriggers', - static function (): array { - $ruleTriggers = array_keys(config('search.operators')); - $possibleTriggers = []; - foreach ($ruleTriggers as $key) { - if ('user_action' !== $key) { - $possibleTriggers[$key] = (string)trans('firefly.rule_trigger_'.$key.'_choice'); - } + return new TwigFunction('allRuleTriggers', static function (): array { + $ruleTriggers = array_keys(config('search.operators')); + $possibleTriggers = []; + foreach ($ruleTriggers as $key) { + if ('user_action' !== $key) { + $possibleTriggers[$key] = (string) trans('firefly.rule_trigger_' . $key . '_choice'); } - unset($ruleTriggers); - asort($possibleTriggers); - - return $possibleTriggers; } - ); + unset($ruleTriggers); + asort($possibleTriggers); + + return $possibleTriggers; + }); } #[Override] public function getFunctions(): array { - return [ - $this->allJournalTriggers(), - $this->allRuleTriggers(), - $this->allActionTriggers(), - ]; + return [$this->allJournalTriggers(), $this->allRuleTriggers(), $this->allActionTriggers()]; } } diff --git a/app/Support/Twig/TransactionGroupTwig.php b/app/Support/Twig/TransactionGroupTwig.php index b3b8469a26..877b2ae404 100644 --- a/app/Support/Twig/TransactionGroupTwig.php +++ b/app/Support/Twig/TransactionGroupTwig.php @@ -24,18 +24,18 @@ declare(strict_types=1); namespace FireflyIII\Support\Twig; -use Carbon\CarbonInterface; use Carbon\Carbon; +use Carbon\CarbonInterface; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Models\Transaction; use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionJournalMeta; +use FireflyIII\Support\Facades\Amount; use Illuminate\Support\Facades\DB; use Override; use Twig\Extension\AbstractExtension; use Twig\TwigFunction; -use FireflyIII\Support\Facades\Amount; use function Safe\json_decode; @@ -47,13 +47,7 @@ class TransactionGroupTwig extends AbstractExtension #[Override] public function getFunctions(): array { - return [ - $this->journalArrayAmount(), - $this->journalObjectAmount(), - $this->journalHasMeta(), - $this->journalGetMetaDate(), - $this->journalGetMetaField(), - ]; + return [$this->journalArrayAmount(), $this->journalObjectAmount(), $this->journalHasMeta(), $this->journalGetMetaDate(), $this->journalGetMetaField()]; } /** @@ -80,61 +74,49 @@ class TransactionGroupTwig extends AbstractExtension public function journalGetMetaDate(): TwigFunction { - return new TwigFunction( - 'journalGetMetaDate', - static function (int $journalId, string $metaField): Carbon|CarbonInterface { - /** @var null|TransactionJournalMeta $entry */ - $entry = DB::table('journal_meta') - ->where('name', $metaField) - ->where('transaction_journal_id', $journalId) - ->whereNull('deleted_at') - ->first() - ; - if (null === $entry) { - return today(config('app.timezone')); - } - - return new Carbon(json_decode((string)$entry->data, false)); + return new TwigFunction('journalGetMetaDate', static function (int $journalId, string $metaField): Carbon|CarbonInterface { + /** @var null|TransactionJournalMeta $entry */ + $entry = DB::table('journal_meta') + ->where('name', $metaField) + ->where('transaction_journal_id', $journalId) + ->whereNull('deleted_at') + ->first(); + if (null === $entry) { + return today(config('app.timezone')); } - ); + + return new Carbon(json_decode((string) $entry->data, false)); + }); } public function journalGetMetaField(): TwigFunction { - return new TwigFunction( - 'journalGetMetaField', - static function (int $journalId, string $metaField) { - /** @var null|TransactionJournalMeta $entry */ - $entry = DB::table('journal_meta') - ->where('name', $metaField) - ->where('transaction_journal_id', $journalId) - ->whereNull('deleted_at') - ->first() - ; - if (null === $entry) { - return ''; - } - - return json_decode((string)$entry->data, true); + return new TwigFunction('journalGetMetaField', static function (int $journalId, string $metaField) { + /** @var null|TransactionJournalMeta $entry */ + $entry = DB::table('journal_meta') + ->where('name', $metaField) + ->where('transaction_journal_id', $journalId) + ->whereNull('deleted_at') + ->first(); + if (null === $entry) { + return ''; } - ); + + return json_decode((string) $entry->data, true); + }); } public function journalHasMeta(): TwigFunction { - return new TwigFunction( - 'journalHasMeta', - static function (int $journalId, string $metaField): bool { - $count = DB::table('journal_meta') - ->where('name', $metaField) - ->where('transaction_journal_id', $journalId) - ->whereNull('deleted_at') - ->count() - ; + return new TwigFunction('journalHasMeta', static function (int $journalId, string $metaField): bool { + $count = DB::table('journal_meta') + ->where('name', $metaField) + ->where('transaction_journal_id', $journalId) + ->whereNull('deleted_at') + ->count(); - return 1 === $count; - } - ); + return 1 === $count; + }); } /** @@ -163,9 +145,9 @@ class TransactionGroupTwig extends AbstractExtension */ private function foreignJournalArrayAmount(array $array): string { - $type = $array['transaction_type_type'] ?? TransactionTypeEnum::WITHDRAWAL->value; - $amount = $array['foreign_amount'] ?? '0'; - $colored = true; + $type = $array['transaction_type_type'] ?? TransactionTypeEnum::WITHDRAWAL->value; + $amount = $array['foreign_amount'] ?? '0'; + $colored = true; $sourceType = $array['source_account_type'] ?? 'invalid'; $amount = $this->signAmount($amount, $type, $sourceType); @@ -173,7 +155,7 @@ class TransactionGroupTwig extends AbstractExtension if (TransactionTypeEnum::TRANSFER->value === $type) { $colored = false; } - $result = Amount::formatFlat($array['foreign_currency_symbol'], (int)$array['foreign_currency_decimal_places'], $amount, $colored); + $result = Amount::formatFlat($array['foreign_currency_symbol'], (int) $array['foreign_currency_decimal_places'], $amount, $colored); if (TransactionTypeEnum::TRANSFER->value === $type) { return sprintf('%s', $result); } @@ -186,7 +168,7 @@ class TransactionGroupTwig extends AbstractExtension */ private function foreignJournalObjectAmount(TransactionJournal $journal): string { - $type = $journal->transactionType->type; + $type = $journal->transactionType->type; /** @var Transaction $first */ $first = $journal->transactions()->where('amount', '<', 0)->first(); @@ -195,12 +177,12 @@ class TransactionGroupTwig extends AbstractExtension $colored = true; $sourceType = $first->account->accountType()->first()->type; - $amount = $this->signAmount($amount, $type, $sourceType); + $amount = $this->signAmount($amount, $type, $sourceType); if (TransactionTypeEnum::TRANSFER->value === $type) { $colored = false; } - $result = Amount::formatFlat($currency->symbol, $currency->decimal_places, $amount, $colored); + $result = Amount::formatFlat($currency->symbol, $currency->decimal_places, $amount, $colored); if (TransactionTypeEnum::TRANSFER->value === $type) { return sprintf('%s', $result); } @@ -231,7 +213,7 @@ class TransactionGroupTwig extends AbstractExtension $colored = false; } - $result = Amount::formatFlat($array['currency_symbol'], (int)$array['currency_decimal_places'], $amount, $colored); + $result = Amount::formatFlat($array['currency_symbol'], (int) $array['currency_decimal_places'], $amount, $colored); if (TransactionTypeEnum::TRANSFER->value === $type) { return sprintf('%s', $result); } @@ -244,7 +226,7 @@ class TransactionGroupTwig extends AbstractExtension */ private function normalJournalObjectAmount(TransactionJournal $journal): string { - $type = $journal->transactionType->type; + $type = $journal->transactionType->type; /** @var Transaction $first */ $first = $journal->transactions()->where('amount', '<', 0)->first(); @@ -253,12 +235,12 @@ class TransactionGroupTwig extends AbstractExtension $colored = true; $sourceType = $first->account->accountType()->first()->type; - $amount = $this->signAmount($amount, $type, $sourceType); + $amount = $this->signAmount($amount, $type, $sourceType); if (TransactionTypeEnum::TRANSFER->value === $type) { $colored = false; } - $result = Amount::formatFlat($currency->symbol, $currency->decimal_places, $amount, $colored); + $result = Amount::formatFlat($currency->symbol, $currency->decimal_places, $amount, $colored); if (TransactionTypeEnum::TRANSFER->value === $type) { return sprintf('%s', $result); } diff --git a/app/Support/Twig/Translation.php b/app/Support/Twig/Translation.php index 3acc5509be..de3630a7b5 100644 --- a/app/Support/Twig/Translation.php +++ b/app/Support/Twig/Translation.php @@ -37,22 +37,13 @@ class Translation extends AbstractExtension #[Override] public function getFilters(): array { - return [ - new TwigFilter( - '_', - static fn (string $name) => (string)trans(sprintf('firefly.%s', $name)), - ['is_safe' => ['html']] - ), - ]; + return [new TwigFilter('_', static fn(string $name) => (string) trans(sprintf('firefly.%s', $name)), ['is_safe' => ['html']])]; } #[Override] public function getFunctions(): array { - return [ - $this->journalLinkTranslation(), - $this->laravelTranslation(), - ]; + return [$this->journalLinkTranslation(), $this->laravelTranslation()]; } public function journalLinkTranslation(): TwigFunction @@ -74,16 +65,13 @@ class Translation extends AbstractExtension public function laravelTranslation(): TwigFunction { - return new TwigFunction( - '__', - static function (string $key): array|string|Translator { - $translation = trans($key); - if ($key === $translation) { - return $key; - } - - return $translation; + return new TwigFunction('__', static function (string $key): array|string|Translator { + $translation = trans($key); + if ($key === $translation) { + return $key; } - ); + + return $translation; + }); } } diff --git a/app/TransactionRules/Actions/AddTag.php b/app/TransactionRules/Actions/AddTag.php index ba07470d45..c3e895df59 100644 --- a/app/TransactionRules/Actions/AddTag.php +++ b/app/TransactionRules/Actions/AddTag.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; use FireflyIII\Enums\TransactionTypeEnum; -use Illuminate\Support\Facades\Log; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Factory\TagFactory; @@ -32,6 +31,7 @@ use FireflyIII\Models\RuleAction; use FireflyIII\Models\TransactionJournal; use FireflyIII\User; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Log; /** * Class AddTag. @@ -41,7 +41,9 @@ class AddTag implements ActionInterface /** * TriggerInterface constructor. */ - public function __construct(private readonly RuleAction $action) {} + public function __construct( + private readonly RuleAction $action + ) {} public function actOnArray(array $journal): bool { @@ -50,13 +52,17 @@ class AddTag implements ActionInterface $factory = app(TagFactory::class); /** @var User $user */ - $user = User::find($journal['user_id']); + $user = User::find($journal['user_id']); $factory->setUser($user); $tagName = $this->action->getValue($journal); $tag = $factory->findOrCreate($tagName); - $type = $journal['transaction_type_type']; - if (TransactionTypeEnum::OPENING_BALANCE->value === $type || TransactionTypeEnum::LIABILITY_CREDIT->value === $type || TransactionTypeEnum::INVALID->value === $type) { + $type = $journal['transaction_type_type']; + if ( + TransactionTypeEnum::OPENING_BALANCE->value === $type + || TransactionTypeEnum::LIABILITY_CREDIT->value === $type + || TransactionTypeEnum::INVALID->value === $type + ) { // fail silently on invalid transaction types. return false; @@ -69,10 +75,16 @@ class AddTag implements ActionInterface return false; } - $count = DB::table('tag_transaction_journal')->where('tag_id', $tag->id)->where('transaction_journal_id', $journal['transaction_journal_id'])->count(); + $count = DB::table('tag_transaction_journal') + ->where('tag_id', $tag->id) + ->where('transaction_journal_id', $journal['transaction_journal_id']) + ->count(); if (0 === $count) { // add to journal: - DB::table('tag_transaction_journal')->insert(['tag_id' => $tag->id, 'transaction_journal_id' => $journal['transaction_journal_id']]); + DB::table('tag_transaction_journal')->insert([ + 'tag_id' => $tag->id, + 'transaction_journal_id' => $journal['transaction_journal_id'] + ]); Log::debug(sprintf('RuleAction AddTag. Added tag #%d ("%s") to journal %d.', $tag->id, $tag->tag, $journal['transaction_journal_id'])); /** @var TransactionJournal $object */ @@ -83,9 +95,12 @@ class AddTag implements ActionInterface return true; } - Log::debug( - sprintf('RuleAction AddTag fired but tag %d ("%s") was already added to journal %d.', $tag->id, $tag->tag, $journal['transaction_journal_id']) - ); + Log::debug(sprintf( + 'RuleAction AddTag fired but tag %d ("%s") was already added to journal %d.', + $tag->id, + $tag->tag, + $journal['transaction_journal_id'] + )); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.tag_already_added', ['tag' => $tagName]))); return false; diff --git a/app/TransactionRules/Actions/AppendDescription.php b/app/TransactionRules/Actions/AppendDescription.php index 946c4c5def..ff9b687fc1 100644 --- a/app/TransactionRules/Actions/AppendDescription.php +++ b/app/TransactionRules/Actions/AppendDescription.php @@ -40,18 +40,23 @@ class AppendDescription implements ActionInterface /** * TriggerInterface constructor. */ - public function __construct(private RuleAction $action) {} + public function __construct( + private RuleAction $action + ) {} public function actOnArray(array $journal): bool { $this->refreshNotes($journal); $append = $this->action->getValue($journal); $description = sprintf('%s %s', $journal['description'], $append); - DB::table('transaction_journals')->where('id', $journal['transaction_journal_id'])->limit(1)->update(['description' => $description]); + DB::table('transaction_journals') + ->where('id', $journal['transaction_journal_id']) + ->limit(1) + ->update(['description' => $description]); // event for audit log entry /** @var TransactionJournal $object */ - $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); + $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); event(new TriggeredAuditLog($this->action->rule, $object, 'update_description', $journal['description'], $description)); return true; diff --git a/app/TransactionRules/Actions/AppendDescriptionToNotes.php b/app/TransactionRules/Actions/AppendDescriptionToNotes.php index bff3b7b292..8c5c4ba067 100644 --- a/app/TransactionRules/Actions/AppendDescriptionToNotes.php +++ b/app/TransactionRules/Actions/AppendDescriptionToNotes.php @@ -24,13 +24,13 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; -use Illuminate\Support\Facades\Log; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Models\Note; use FireflyIII\Models\RuleAction; use FireflyIII\Models\TransactionJournal; use FireflyIII\TransactionRules\Traits\RefreshNotesTrait; +use Illuminate\Support\Facades\Log; /** * Class AppendDescriptionToNotes @@ -43,7 +43,9 @@ class AppendDescriptionToNotes implements ActionInterface /** * TriggerInterface constructor. */ - public function __construct(private RuleAction $action) {} + public function __construct( + private RuleAction $action + ) {} public function actOnArray(array $journal): bool { @@ -57,9 +59,9 @@ class AppendDescriptionToNotes implements ActionInterface return false; } - $note = $object->notes()->first(); + $note = $object->notes()->first(); if (null === $note) { - $note = new Note(); + $note = new Note(); $note->noteable()->associate($object); $note->text = ''; } @@ -70,7 +72,7 @@ class AppendDescriptionToNotes implements ActionInterface if ('' === $note->text) { $note->text = (string) $object->description; } - $after = $note->text; + $after = $note->text; // event for audit log entry event(new TriggeredAuditLog($this->action->rule, $object, 'update_notes', $before, $after)); diff --git a/app/TransactionRules/Actions/AppendNotes.php b/app/TransactionRules/Actions/AppendNotes.php index 483accfd44..ab79871136 100644 --- a/app/TransactionRules/Actions/AppendNotes.php +++ b/app/TransactionRules/Actions/AppendNotes.php @@ -23,12 +23,12 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; -use Illuminate\Support\Facades\Log; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Models\Note; use FireflyIII\Models\RuleAction; use FireflyIII\Models\TransactionJournal; use FireflyIII\TransactionRules\Traits\RefreshNotesTrait; +use Illuminate\Support\Facades\Log; /** * Class AppendNotes. @@ -41,29 +41,28 @@ class AppendNotes implements ActionInterface /** * TriggerInterface constructor. */ - public function __construct(private RuleAction $action) {} + public function __construct( + private RuleAction $action + ) {} public function actOnArray(array $journal): bool { $this->refreshNotes($journal); - $dbNote = Note::where('noteable_id', (int) $journal['transaction_journal_id']) - ->where('noteable_type', TransactionJournal::class) - ->first(['notes.*']) - ; + $dbNote = Note::where('noteable_id', (int) $journal['transaction_journal_id'])->where('noteable_type', TransactionJournal::class)->first(['notes.*']); if (null === $dbNote) { - $dbNote = new Note(); - $dbNote->noteable_id = (int) $journal['transaction_journal_id']; + $dbNote = new Note(); + $dbNote->noteable_id = (int) $journal['transaction_journal_id']; $dbNote->noteable_type = TransactionJournal::class; - $dbNote->text = ''; + $dbNote->text = ''; } - $before = $dbNote->text; - $append = $this->action->getValue($journal); - $text = sprintf('%s%s', $dbNote->text, $append); + $before = $dbNote->text; + $append = $this->action->getValue($journal); + $text = sprintf('%s%s', $dbNote->text, $append); $dbNote->text = $text; $dbNote->save(); /** @var TransactionJournal $object */ - $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); + $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); Log::debug(sprintf('RuleAction AppendNotes appended "%s" to "%s".', $append, $before)); event(new TriggeredAuditLog($this->action->rule, $object, 'update_notes', $before, $text)); diff --git a/app/TransactionRules/Actions/AppendNotesToDescription.php b/app/TransactionRules/Actions/AppendNotesToDescription.php index e9543f7f1d..e9ced2573e 100644 --- a/app/TransactionRules/Actions/AppendNotesToDescription.php +++ b/app/TransactionRules/Actions/AppendNotesToDescription.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; -use Illuminate\Support\Facades\Log; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Models\Note; @@ -32,6 +31,7 @@ use FireflyIII\Models\RuleAction; use FireflyIII\Models\TransactionJournal; use FireflyIII\Support\Request\ConvertsDataTypes; use FireflyIII\TransactionRules\Traits\RefreshNotesTrait; +use Illuminate\Support\Facades\Log; /** * Class AppendNotesToDescription @@ -45,7 +45,9 @@ class AppendNotesToDescription implements ActionInterface /** * TriggerInterface constructor. */ - public function __construct(private RuleAction $action) {} + public function __construct( + private RuleAction $action + ) {} public function actOnArray(array $journal): bool { @@ -60,16 +62,16 @@ class AppendNotesToDescription implements ActionInterface return false; } - $note = $object->notes()->first(); + $note = $object->notes()->first(); if (null === $note) { Log::debug('Journal has no notes.'); - $note = new Note(); + $note = new Note(); $note->noteable()->associate($object); $note->text = ''; } // only append if there is something to append if ('' !== $note->text) { - $before = $object->description; + $before = $object->description; $object->description = trim(sprintf('%s %s', $object->description, (string) $this->clearString($note->text))); $object->save(); Log::debug(sprintf('Journal description is updated to "%s".', $object->description)); diff --git a/app/TransactionRules/Actions/ClearBudget.php b/app/TransactionRules/Actions/ClearBudget.php index 3d9ece4d31..6f69e68c52 100644 --- a/app/TransactionRules/Actions/ClearBudget.php +++ b/app/TransactionRules/Actions/ClearBudget.php @@ -23,12 +23,12 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; -use Illuminate\Support\Facades\Log; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Models\RuleAction; use FireflyIII\Models\TransactionJournal; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Log; /** * Class ClearBudget. @@ -38,7 +38,9 @@ class ClearBudget implements ActionInterface /** * TriggerInterface constructor. */ - public function __construct(private readonly RuleAction $action) {} + public function __construct( + private readonly RuleAction $action + ) {} public function actOnArray(array $journal): bool { diff --git a/app/TransactionRules/Actions/ClearCategory.php b/app/TransactionRules/Actions/ClearCategory.php index 05e3857bd5..89801cbca4 100644 --- a/app/TransactionRules/Actions/ClearCategory.php +++ b/app/TransactionRules/Actions/ClearCategory.php @@ -23,12 +23,12 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; -use Illuminate\Support\Facades\Log; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Models\RuleAction; use FireflyIII\Models\TransactionJournal; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Log; /** * Class ClearCategory. @@ -38,7 +38,9 @@ class ClearCategory implements ActionInterface /** * TriggerInterface constructor. */ - public function __construct(private readonly RuleAction $action) {} + public function __construct( + private readonly RuleAction $action + ) {} public function actOnArray(array $journal): bool { diff --git a/app/TransactionRules/Actions/ClearNotes.php b/app/TransactionRules/Actions/ClearNotes.php index 8e03c895c0..c710a60fa0 100644 --- a/app/TransactionRules/Actions/ClearNotes.php +++ b/app/TransactionRules/Actions/ClearNotes.php @@ -23,13 +23,13 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; -use Illuminate\Support\Facades\Log; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Models\Note; use FireflyIII\Models\RuleAction; use FireflyIII\Models\TransactionJournal; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Log; /** * Class ClearNotes. @@ -39,7 +39,9 @@ class ClearNotes implements ActionInterface /** * TriggerInterface constructor. */ - public function __construct(private readonly RuleAction $action) {} + public function __construct( + private readonly RuleAction $action + ) {} public function actOnArray(array $journal): bool { @@ -47,7 +49,7 @@ class ClearNotes implements ActionInterface $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); /** @var null|Note $notes */ - $notes = $object->notes()->first(); + $notes = $object->notes()->first(); if (null === $notes) { Log::debug(sprintf('RuleAction ClearNotes, journal #%d has no notes.', $journal['transaction_journal_id'])); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.journal_already_no_notes'))); @@ -59,8 +61,7 @@ class ClearNotes implements ActionInterface DB::table('notes') ->where('noteable_id', $journal['transaction_journal_id']) ->where('noteable_type', TransactionJournal::class) - ->delete() - ; + ->delete(); Log::debug(sprintf('RuleAction ClearNotes removed all notes from journal #%d.', $journal['transaction_journal_id'])); event(new TriggeredAuditLog($this->action->rule, $object, 'clear_notes', $before, null)); diff --git a/app/TransactionRules/Actions/ConvertToDeposit.php b/app/TransactionRules/Actions/ConvertToDeposit.php index cb95871410..842ccc4744 100644 --- a/app/TransactionRules/Actions/ConvertToDeposit.php +++ b/app/TransactionRules/Actions/ConvertToDeposit.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; -use Illuminate\Support\Facades\Log; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; @@ -38,6 +37,7 @@ use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionType; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Log; /** * Class ConvertToDeposit @@ -47,7 +47,9 @@ class ConvertToDeposit implements ActionInterface /** * TriggerInterface constructor. */ - public function __construct(private readonly RuleAction $action) {} + public function __construct( + private readonly RuleAction $action + ) {} public function actOnArray(array $journal): bool { @@ -55,14 +57,14 @@ class ConvertToDeposit implements ActionInterface // make object from array (so the data is fresh). /** @var null|TransactionJournal $object */ - $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); + $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); if (null === $object) { Log::error(sprintf('Cannot find journal #%d, cannot convert to deposit.', $journal['transaction_journal_id'])); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.journal_not_found'))); return false; } - $groupCount = TransactionJournal::where('transaction_group_id', $journal['transaction_group_id'])->count(); + $groupCount = TransactionJournal::where('transaction_group_id', $journal['transaction_group_id'])->count(); if ($groupCount > 1) { Log::error(sprintf('Group #%d has more than one transaction in it, cannot convert to deposit.', $journal['transaction_group_id'])); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.split_group'))); @@ -71,7 +73,7 @@ class ConvertToDeposit implements ActionInterface } Log::debug(sprintf('Convert journal #%d to deposit.', $journal['transaction_journal_id'])); - $type = $object->transactionType->type; + $type = $object->transactionType->type; if (TransactionTypeEnum::DEPOSIT->value === $type) { Log::error(sprintf('Journal #%d is already a deposit (rule #%d).', $journal['transaction_journal_id'], $this->action->rule_id)); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.is_already_deposit'))); @@ -92,7 +94,15 @@ class ConvertToDeposit implements ActionInterface return false; } - event(new TriggeredAuditLog($this->action->rule, $object, 'update_transaction_type', TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::DEPOSIT->value)); + event( + new TriggeredAuditLog( + $this->action->rule, + $object, + 'update_transaction_type', + TransactionTypeEnum::WITHDRAWAL->value, + TransactionTypeEnum::DEPOSIT->value + ) + ); return $res; } @@ -108,7 +118,15 @@ class ConvertToDeposit implements ActionInterface return false; } - event(new TriggeredAuditLog($this->action->rule, $object, 'update_transaction_type', TransactionTypeEnum::TRANSFER->value, TransactionTypeEnum::DEPOSIT->value)); + event( + new TriggeredAuditLog( + $this->action->rule, + $object, + 'update_transaction_type', + TransactionTypeEnum::TRANSFER->value, + TransactionTypeEnum::DEPOSIT->value + ) + ); return $res; } @@ -125,22 +143,22 @@ class ConvertToDeposit implements ActionInterface */ private function convertWithdrawalArray(TransactionJournal $journal, string $actionValue = ''): bool { - $user = $journal->user; + $user = $journal->user; // find or create revenue account. /** @var AccountFactory $factory */ - $factory = app(AccountFactory::class); + $factory = app(AccountFactory::class); $factory->setUser($user); - $repository = app(AccountRepositoryInterface::class); + $repository = app(AccountRepositoryInterface::class); $repository->setUser($user); - $destAccount = $this->getDestinationAccount($journal); - $sourceAccount = $this->getSourceAccount($journal); + $destAccount = $this->getDestinationAccount($journal); + $sourceAccount = $this->getSourceAccount($journal); // get the action value, or use the original destination name in case the action value is empty: // this becomes a new or existing (revenue) account, which is the source of the new deposit. - $opposingName = '' === $actionValue ? $destAccount->name : $actionValue; + $opposingName = '' === $actionValue ? $destAccount->name : $actionValue; // we check all possible source account types if one exists: $validTypes = config('firefly.expected_source_types.source.Deposit'); $opposingAccount = $repository->findByName($opposingName, $validTypes); @@ -154,23 +172,18 @@ class ConvertToDeposit implements ActionInterface DB::table('transactions') ->where('transaction_journal_id', '=', $journal->id) ->where('amount', '<', 0) - ->update(['account_id' => $opposingAccount->id]) - ; + ->update(['account_id' => $opposingAccount->id]); // update the destination transaction and put in the original source account ID. DB::table('transactions') ->where('transaction_journal_id', '=', $journal->id) ->where('amount', '>', 0) - ->update(['account_id' => $sourceAccount->id]) - ; + ->update(['account_id' => $sourceAccount->id]); // change transaction type of journal: - $newType = TransactionType::whereType(TransactionTypeEnum::DEPOSIT->value)->first(); + $newType = TransactionType::whereType(TransactionTypeEnum::DEPOSIT->value)->first(); - DB::table('transaction_journals') - ->where('id', '=', $journal->id) - ->update(['transaction_type_id' => $newType->id, 'bill_id' => null]) - ; + DB::table('transaction_journals')->where('id', '=', $journal->id)->update(['transaction_type_id' => $newType->id, 'bill_id' => null]); Log::debug('Converted withdrawal to deposit.'); @@ -214,21 +227,21 @@ class ConvertToDeposit implements ActionInterface */ private function convertTransferArray(TransactionJournal $journal, string $actionValue = ''): bool { - $user = $journal->user; + $user = $journal->user; // find or create revenue account. /** @var AccountFactory $factory */ - $factory = app(AccountFactory::class); + $factory = app(AccountFactory::class); $factory->setUser($user); - $repository = app(AccountRepositoryInterface::class); + $repository = app(AccountRepositoryInterface::class); $repository->setUser($user); - $sourceAccount = $this->getSourceAccount($journal); + $sourceAccount = $this->getSourceAccount($journal); // get the action value, or use the original source name in case the action value is empty: // this becomes a new or existing (revenue) account, which is the source of the new deposit. - $opposingName = '' === $actionValue ? $sourceAccount->name : $actionValue; + $opposingName = '' === $actionValue ? $sourceAccount->name : $actionValue; // we check all possible source account types if one exists: $validTypes = config('firefly.expected_source_types.source.Deposit'); $opposingAccount = $repository->findByName($opposingName, $validTypes); @@ -242,16 +255,12 @@ class ConvertToDeposit implements ActionInterface DB::table('transactions') ->where('transaction_journal_id', '=', $journal->id) ->where('amount', '<', 0) - ->update(['account_id' => $opposingAccount->id]) - ; + ->update(['account_id' => $opposingAccount->id]); // change transaction type of journal: - $newType = TransactionType::whereType(TransactionTypeEnum::DEPOSIT->value)->first(); + $newType = TransactionType::whereType(TransactionTypeEnum::DEPOSIT->value)->first(); - DB::table('transaction_journals') - ->where('id', '=', $journal->id) - ->update(['transaction_type_id' => $newType->id, 'bill_id' => null]) - ; + DB::table('transaction_journals')->where('id', '=', $journal->id)->update(['transaction_type_id' => $newType->id, 'bill_id' => null]); Log::debug('Converted transfer to deposit.'); diff --git a/app/TransactionRules/Actions/ConvertToTransfer.php b/app/TransactionRules/Actions/ConvertToTransfer.php index b2e5385b88..eaed32b9a2 100644 --- a/app/TransactionRules/Actions/ConvertToTransfer.php +++ b/app/TransactionRules/Actions/ConvertToTransfer.php @@ -48,7 +48,9 @@ class ConvertToTransfer implements ActionInterface /** * TriggerInterface constructor. */ - public function __construct(private readonly RuleAction $action) {} + public function __construct( + private readonly RuleAction $action + ) {} /** * @SuppressWarnings("PHPMD.ExcessiveMethodLength") @@ -56,18 +58,18 @@ class ConvertToTransfer implements ActionInterface */ public function actOnArray(array $journal): bool { - $accountName = $this->action->getValue($journal); + $accountName = $this->action->getValue($journal); // make object from array (so the data is fresh). /** @var null|TransactionJournal $object */ - $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); + $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); if (null === $object) { Log::error(sprintf('Cannot find journal #%d, cannot convert to transfer.', $journal['transaction_journal_id'])); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.journal_not_found'))); return false; } - $groupCount = TransactionJournal::where('transaction_group_id', $journal['transaction_group_id'])->count(); + $groupCount = TransactionJournal::where('transaction_group_id', $journal['transaction_group_id'])->count(); if ($groupCount > 1) { Log::error(sprintf('Group #%d has more than one transaction in it, cannot convert to transfer.', $journal['transaction_group_id'])); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.split_group'))); @@ -75,9 +77,9 @@ class ConvertToTransfer implements ActionInterface return false; } - $type = $object->transactionType->type; - $user = $object->user; - $journalId = $object->id; + $type = $object->transactionType->type; + $user = $object->user; + $journalId = $object->id; if (TransactionTypeEnum::TRANSFER->value === $type) { Log::error(sprintf('Journal #%d is already a transfer so cannot be converted (rule #%d).', $object->id, $this->action->rule_id)); // event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.is_already_transfer'))); @@ -92,21 +94,29 @@ class ConvertToTransfer implements ActionInterface // find the asset account in the action value. /** @var AccountRepositoryInterface $repository */ - $repository = app(AccountRepositoryInterface::class); + $repository = app(AccountRepositoryInterface::class); $repository->setUser($user); $expectedType = null; if (TransactionTypeEnum::WITHDRAWAL->value === $type) { $expectedType = $this->getSourceType($journalId); + // Withdrawal? Replace destination with account with same type as source. } if (TransactionTypeEnum::DEPOSIT->value === $type) { $expectedType = $this->getDestinationType($journalId); + // Deposit? Replace source with account with same type as destination. } - $opposing = $repository->findByName($accountName, [$expectedType]); + $opposing = $repository->findByName($accountName, [$expectedType]); if (null === $opposing) { - Log::error(sprintf('Journal #%d cannot be converted because no valid %s account with name "%s" exists (rule #%d).', $expectedType, $journalId, $accountName, $this->action->rule_id)); + Log::error(sprintf( + 'Journal #%d cannot be converted because no valid %s account with name "%s" exists (rule #%d).', + $expectedType, + $journalId, + $accountName, + $this->action->rule_id + )); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.no_valid_opposing', ['name' => $accountName]))); return false; @@ -125,7 +135,15 @@ class ConvertToTransfer implements ActionInterface return false; } if ($res) { - event(new TriggeredAuditLog($this->action->rule, $object, 'update_transaction_type', TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::TRANSFER->value)); + event( + new TriggeredAuditLog( + $this->action->rule, + $object, + 'update_transaction_type', + TransactionTypeEnum::WITHDRAWAL->value, + TransactionTypeEnum::TRANSFER->value + ) + ); } return $res; @@ -143,7 +161,15 @@ class ConvertToTransfer implements ActionInterface return false; } if ($res) { - event(new TriggeredAuditLog($this->action->rule, $object, 'update_transaction_type', TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value)); + event( + new TriggeredAuditLog( + $this->action->rule, + $object, + 'update_transaction_type', + TransactionTypeEnum::DEPOSIT->value, + TransactionTypeEnum::TRANSFER->value + ) + ); } return $res; @@ -159,7 +185,7 @@ class ConvertToTransfer implements ActionInterface return ''; } - return (string)$journal->transactions()->where('amount', '<', 0)->first()?->account?->accountType?->type; + return (string) $journal->transactions()->where('amount', '<', 0)->first()?->account?->accountType?->type; } private function getDestinationType(int $journalId): string @@ -172,7 +198,7 @@ class ConvertToTransfer implements ActionInterface return ''; } - return (string)$journal->transactions()->where('amount', '>', 0)->first()?->account?->accountType?->type; + return (string) $journal->transactions()->where('amount', '>', 0)->first()?->account?->accountType?->type; } /** @@ -184,57 +210,73 @@ class ConvertToTransfer implements ActionInterface */ private function convertWithdrawalArray(TransactionJournal $journal, Account $opposing): bool { - $repository = app(AccountRepositoryInterface::class); - $sourceAccount = $this->getSourceAccount($journal); + $repository = app(AccountRepositoryInterface::class); + $sourceAccount = $this->getSourceAccount($journal); $repository->setUser($sourceAccount->user); if ($sourceAccount->id === $opposing->id) { - Log::error(vsprintf('Journal #%d has already has "%s" as a source asset. ConvertToTransfer failed. (rule #%d).', [$journal->id, $opposing->name, $this->action->rule_id])); + Log::error(vsprintf('Journal #%d has already has "%s" as a source asset. ConvertToTransfer failed. (rule #%d).', [ + $journal->id, + $opposing->name, + $this->action->rule_id + ])); event(new RuleActionFailedOnObject($this->action, $journal, trans('rules.already_has_source_asset', ['name' => $opposing->name]))); return false; } /** @var Transaction $sourceTransaction */ - $sourceTransaction = Transaction::where('transaction_journal_id', '=', $journal->id)->where('amount', '<', 0)->first(); + $sourceTransaction = Transaction::where('transaction_journal_id', '=', $journal->id)->where('amount', '<', 0)->first(); /** @var Transaction $destTransaction */ - $destTransaction = Transaction::where('transaction_journal_id', '=', $journal->id)->where('amount', '>', 0)->first(); + $destTransaction = Transaction::where('transaction_journal_id', '=', $journal->id)->where('amount', '>', 0)->first(); // update destination transaction: $destTransaction->account_id = $opposing->id; $destTransaction->save(); // check if the currencies are a match. /** @var TransactionCurrency $sourceCurrency */ - $sourceCurrency = $repository->getAccountCurrency($sourceAccount); + $sourceCurrency = $repository->getAccountCurrency($sourceAccount); /** @var TransactionCurrency $destCurrency */ - $destCurrency = $repository->getAccountCurrency($opposing); + $destCurrency = $repository->getAccountCurrency($opposing); // if the currencies do not match, need to be smart about the involved amounts: if ($sourceCurrency->id !== $destCurrency->id) { Log::debug(sprintf('Accounts have different currencies. Source has %s, dest has %s', $sourceCurrency->code, $destCurrency->code)); - $foreignAmount = '' === (string)$sourceTransaction->foreign_amount ? $sourceTransaction->amount : $sourceTransaction->foreign_amount; + $foreignAmount = '' === (string) $sourceTransaction->foreign_amount ? $sourceTransaction->amount : $sourceTransaction->foreign_amount; Log::debug(sprintf('Foreign amount: %s', $foreignAmount)); // source transaction: set the foreign currency ID and leave as is. - $sourceTransaction->foreign_currency_id = $destCurrency->id; - $sourceTransaction->foreign_amount = Steam::negative($foreignAmount); + $sourceTransaction->foreign_currency_id = $destCurrency->id; + $sourceTransaction->foreign_amount = Steam::negative($foreignAmount); $sourceTransaction->save(); - Log::debug(sprintf('Set source transaction #%d foreign currency ID to #%d (amount: %s)', $sourceTransaction->id, $destCurrency->id, $foreignAmount)); + Log::debug(sprintf( + 'Set source transaction #%d foreign currency ID to #%d (amount: %s)', + $sourceTransaction->id, + $destCurrency->id, + $foreignAmount + )); // dest transaction: set reverse amounts and currency IDs from source transaction. - $destTransaction->foreign_currency_id = $sourceCurrency->transaction_currency_id; + $destTransaction->foreign_currency_id = $sourceCurrency->transaction_currency_id; $destTransaction->transaction_currency_id = $sourceTransaction->foreign_currency_id; - $destTransaction->amount = Steam::positive($foreignAmount); - $destTransaction->foreign_amount = Steam::positive($sourceTransaction->amount); + $destTransaction->amount = Steam::positive($foreignAmount); + $destTransaction->foreign_amount = Steam::positive($sourceTransaction->amount); $destTransaction->save(); - Log::debug(sprintf('Set dest transaction #%d to #%d %s and foreign #%d %s', $destTransaction->id, $destTransaction->transaction_currency_id, $destTransaction->amount, $destTransaction->foreign_currency_id, $destTransaction->foreign_amount)); + Log::debug(sprintf( + 'Set dest transaction #%d to #%d %s and foreign #%d %s', + $destTransaction->id, + $destTransaction->transaction_currency_id, + $destTransaction->amount, + $destTransaction->foreign_currency_id, + $destTransaction->foreign_amount + )); } // change transaction type of journal: - $newType = TransactionType::whereType(TransactionTypeEnum::TRANSFER->value)->first(); + $newType = TransactionType::whereType(TransactionTypeEnum::TRANSFER->value)->first(); - DB::table('transaction_journals')->where('id', '=', $journal->id)->update(['transaction_type_id' => $newType->id, 'bill_id' => null]); + DB::table('transaction_journals')->where('id', '=', $journal->id)->update(['transaction_type_id' => $newType->id, 'bill_id' => null]); Log::debug('Converted withdrawal to transfer.'); @@ -265,12 +307,11 @@ class ConvertToTransfer implements ActionInterface { $destAccount = $this->getDestinationAccount($journal); if ($destAccount->id === $opposing->id) { - Log::error( - vsprintf( - 'Journal #%d has already has "%s" as a destination asset. ConvertToTransfer failed. (rule #%d).', - [$journal->id, $opposing->name, $this->action->rule_id] - ) - ); + Log::error(vsprintf('Journal #%d has already has "%s" as a destination asset. ConvertToTransfer failed. (rule #%d).', [ + $journal->id, + $opposing->name, + $this->action->rule_id + ])); event(new RuleActionFailedOnObject($this->action, $journal, trans('rules.already_has_destination_asset', ['name' => $opposing->name]))); return false; @@ -280,16 +321,12 @@ class ConvertToTransfer implements ActionInterface DB::table('transactions') ->where('transaction_journal_id', '=', $journal->id) ->where('amount', '<', 0) - ->update(['account_id' => $opposing->id]) - ; + ->update(['account_id' => $opposing->id]); // change transaction type of journal: - $newType = TransactionType::whereType(TransactionTypeEnum::TRANSFER->value)->first(); + $newType = TransactionType::whereType(TransactionTypeEnum::TRANSFER->value)->first(); - DB::table('transaction_journals') - ->where('id', '=', $journal->id) - ->update(['transaction_type_id' => $newType->id, 'bill_id' => null]) - ; + DB::table('transaction_journals')->where('id', '=', $journal->id)->update(['transaction_type_id' => $newType->id, 'bill_id' => null]); Log::debug('Converted deposit to transfer.'); diff --git a/app/TransactionRules/Actions/ConvertToWithdrawal.php b/app/TransactionRules/Actions/ConvertToWithdrawal.php index 803163ca83..4b7f9f64fc 100644 --- a/app/TransactionRules/Actions/ConvertToWithdrawal.php +++ b/app/TransactionRules/Actions/ConvertToWithdrawal.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; -use Illuminate\Support\Facades\Log; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; @@ -38,6 +37,7 @@ use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionType; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Log; /** * Class ConvertToWithdrawal @@ -47,7 +47,9 @@ class ConvertToWithdrawal implements ActionInterface /** * TriggerInterface constructor. */ - public function __construct(private readonly RuleAction $action) {} + public function __construct( + private readonly RuleAction $action + ) {} public function actOnArray(array $journal): bool { @@ -55,14 +57,14 @@ class ConvertToWithdrawal implements ActionInterface // make object from array (so the data is fresh). /** @var null|TransactionJournal $object */ - $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); + $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); if (null === $object) { Log::error(sprintf('Cannot find journal #%d, cannot convert to withdrawal.', $journal['transaction_journal_id'])); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.journal_not_found'))); return false; } - $groupCount = TransactionJournal::where('transaction_group_id', $journal['transaction_group_id'])->count(); + $groupCount = TransactionJournal::where('transaction_group_id', $journal['transaction_group_id'])->count(); if ($groupCount > 1) { Log::error(sprintf('Group #%d has more than one transaction in it, cannot convert to withdrawal.', $journal['transaction_group_id'])); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.split_group'))); @@ -70,7 +72,7 @@ class ConvertToWithdrawal implements ActionInterface return false; } - $type = $object->transactionType->type; + $type = $object->transactionType->type; if (TransactionTypeEnum::WITHDRAWAL->value === $type) { Log::error(sprintf('Journal #%d is already a withdrawal (rule #%d).', $journal['transaction_journal_id'], $this->action->rule_id)); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.is_already_withdrawal'))); @@ -94,7 +96,15 @@ class ConvertToWithdrawal implements ActionInterface return false; } - event(new TriggeredAuditLog($this->action->rule, $object, 'update_transaction_type', TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::WITHDRAWAL->value)); + event( + new TriggeredAuditLog( + $this->action->rule, + $object, + 'update_transaction_type', + TransactionTypeEnum::DEPOSIT->value, + TransactionTypeEnum::WITHDRAWAL->value + ) + ); return $res; } @@ -110,7 +120,15 @@ class ConvertToWithdrawal implements ActionInterface return false; } - event(new TriggeredAuditLog($this->action->rule, $object, 'update_transaction_type', TransactionTypeEnum::TRANSFER->value, TransactionTypeEnum::WITHDRAWAL->value)); + event( + new TriggeredAuditLog( + $this->action->rule, + $object, + 'update_transaction_type', + TransactionTypeEnum::TRANSFER->value, + TransactionTypeEnum::WITHDRAWAL->value + ) + ); return $res; } @@ -120,21 +138,21 @@ class ConvertToWithdrawal implements ActionInterface */ private function convertDepositArray(TransactionJournal $journal, string $actionValue = ''): bool { - $user = $journal->user; + $user = $journal->user; /** @var AccountFactory $factory */ - $factory = app(AccountFactory::class); + $factory = app(AccountFactory::class); $factory->setUser($user); - $repository = app(AccountRepositoryInterface::class); + $repository = app(AccountRepositoryInterface::class); $repository->setUser($user); - $sourceAccount = $this->getSourceAccount($journal); - $destAccount = $this->getDestinationAccount($journal); + $sourceAccount = $this->getSourceAccount($journal); + $destAccount = $this->getDestinationAccount($journal); // get the action value, or use the original source name in case the action value is empty: // this becomes a new or existing (expense) account, which is the destination of the new withdrawal. - $opposingName = '' === $actionValue ? $sourceAccount->name : $actionValue; + $opposingName = '' === $actionValue ? $sourceAccount->name : $actionValue; // we check all possible source account types if one exists: $validTypes = config('firefly.expected_source_types.destination.Withdrawal'); $opposingAccount = $repository->findByName($opposingName, $validTypes); @@ -148,22 +166,17 @@ class ConvertToWithdrawal implements ActionInterface DB::table('transactions') ->where('transaction_journal_id', '=', $journal->id) ->where('amount', '<', 0) - ->update(['account_id' => $destAccount->id]) - ; + ->update(['account_id' => $destAccount->id]); // update destination transaction(s) to be new expense account. DB::table('transactions') ->where('transaction_journal_id', '=', $journal->id) ->where('amount', '>', 0) - ->update(['account_id' => $opposingAccount->id]) - ; + ->update(['account_id' => $opposingAccount->id]); // change transaction type of journal: - $newType = TransactionType::whereType(TransactionTypeEnum::WITHDRAWAL->value)->first(); - DB::table('transaction_journals') - ->where('id', '=', $journal->id) - ->update(['transaction_type_id' => $newType->id]) - ; + $newType = TransactionType::whereType(TransactionTypeEnum::WITHDRAWAL->value)->first(); + DB::table('transaction_journals')->where('id', '=', $journal->id)->update(['transaction_type_id' => $newType->id]); Log::debug('Converted deposit to withdrawal.'); @@ -207,20 +220,20 @@ class ConvertToWithdrawal implements ActionInterface private function convertTransferArray(TransactionJournal $journal, string $actionValue = ''): bool { // find or create expense account. - $user = $journal->user; + $user = $journal->user; /** @var AccountFactory $factory */ - $factory = app(AccountFactory::class); + $factory = app(AccountFactory::class); $factory->setUser($user); - $repository = app(AccountRepositoryInterface::class); + $repository = app(AccountRepositoryInterface::class); $repository->setUser($user); - $destAccount = $this->getDestinationAccount($journal); + $destAccount = $this->getDestinationAccount($journal); // get the action value, or use the original source name in case the action value is empty: // this becomes a new or existing (expense) account, which is the destination of the new withdrawal. - $opposingName = '' === $actionValue ? $destAccount->name : $actionValue; + $opposingName = '' === $actionValue ? $destAccount->name : $actionValue; // we check all possible source account types if one exists: $validTypes = config('firefly.expected_source_types.destination.Withdrawal'); $opposingAccount = $repository->findByName($opposingName, $validTypes); @@ -234,15 +247,11 @@ class ConvertToWithdrawal implements ActionInterface DB::table('transactions') ->where('transaction_journal_id', '=', $journal->id) ->where('amount', '>', 0) - ->update(['account_id' => $opposingAccount->id]) - ; + ->update(['account_id' => $opposingAccount->id]); // change transaction type of journal: - $newType = TransactionType::whereType(TransactionTypeEnum::WITHDRAWAL->value)->first(); - DB::table('transaction_journals') - ->where('id', '=', $journal->id) - ->update(['transaction_type_id' => $newType->id]) - ; + $newType = TransactionType::whereType(TransactionTypeEnum::WITHDRAWAL->value)->first(); + DB::table('transaction_journals')->where('id', '=', $journal->id)->update(['transaction_type_id' => $newType->id]); Log::debug('Converted transfer to withdrawal.'); diff --git a/app/TransactionRules/Actions/DeleteTransaction.php b/app/TransactionRules/Actions/DeleteTransaction.php index 530d3967de..5c11333145 100644 --- a/app/TransactionRules/Actions/DeleteTransaction.php +++ b/app/TransactionRules/Actions/DeleteTransaction.php @@ -23,13 +23,13 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; -use Illuminate\Support\Facades\Log; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Models\RuleAction; use FireflyIII\Models\TransactionGroup; use FireflyIII\Models\TransactionJournal; use FireflyIII\Services\Internal\Destroy\JournalDestroyService; use FireflyIII\Services\Internal\Destroy\TransactionGroupDestroyService; +use Illuminate\Support\Facades\Log; /** * Class DeleteTransaction. @@ -39,21 +39,21 @@ class DeleteTransaction implements ActionInterface /** * TriggerInterface constructor. */ - public function __construct(private readonly RuleAction $action) {} + public function __construct( + private readonly RuleAction $action + ) {} public function actOnArray(array $journal): bool { - $count = TransactionJournal::where('transaction_group_id', $journal['transaction_group_id'])->count(); + $count = TransactionJournal::where('transaction_group_id', $journal['transaction_group_id'])->count(); // destroy entire group. if (1 === $count) { - Log::debug( - sprintf( - 'RuleAction DeleteTransaction DELETED the entire transaction group of journal #%d ("%s").', - $journal['transaction_journal_id'], - $journal['description'] - ) - ); + Log::debug(sprintf( + 'RuleAction DeleteTransaction DELETED the entire transaction group of journal #%d ("%s").', + $journal['transaction_journal_id'], + $journal['description'] + )); /** @var TransactionGroup $group */ $group = TransactionGroup::find($journal['transaction_group_id']); @@ -64,9 +64,11 @@ class DeleteTransaction implements ActionInterface return true; } - Log::debug( - sprintf('RuleAction DeleteTransaction DELETED transaction journal #%d ("%s").', $journal['transaction_journal_id'], $journal['description']) - ); + Log::debug(sprintf( + 'RuleAction DeleteTransaction DELETED transaction journal #%d ("%s").', + $journal['transaction_journal_id'], + $journal['description'] + )); // trigger delete factory: /** @var null|TransactionJournal $object */ diff --git a/app/TransactionRules/Actions/LinkToBill.php b/app/TransactionRules/Actions/LinkToBill.php index 636c1c6c49..0f6b1453cd 100644 --- a/app/TransactionRules/Actions/LinkToBill.php +++ b/app/TransactionRules/Actions/LinkToBill.php @@ -41,34 +41,48 @@ class LinkToBill implements ActionInterface /** * TriggerInterface constructor. */ - public function __construct(private readonly RuleAction $action) {} + public function __construct( + private readonly RuleAction $action + ) {} public function actOnArray(array $journal): bool { /** @var User $user */ - $user = User::find($journal['user_id']); + $user = User::find($journal['user_id']); /** @var BillRepositoryInterface $repository */ $repository = app(BillRepositoryInterface::class); $repository->setUser($user); - $billName = $this->action->getValue($journal); - $bill = $repository->findByName($billName); + $billName = $this->action->getValue($journal); + $bill = $repository->findByName($billName); /** @var TransactionJournal $object */ - $object = TransactionJournal::with('transactionType')->find($journal['transaction_journal_id']); - $type = $object->transactionType->type; + $object = TransactionJournal::with('transactionType')->find($journal['transaction_journal_id']); + $type = $object->transactionType->type; if (null !== $bill && TransactionTypeEnum::WITHDRAWAL->value === $type) { - $count = DB::table('transaction_journals')->where('id', '=', $journal['transaction_journal_id'])->where('bill_id', $bill->id)->count(); + $count = DB::table('transaction_journals') + ->where('id', '=', $journal['transaction_journal_id']) + ->where('bill_id', $bill->id) + ->count(); if (0 !== $count) { - Log::error(sprintf('RuleAction LinkToBill could not set the bill of journal #%d to bill "%s": already set.', $journal['transaction_journal_id'], $billName)); + Log::error(sprintf( + 'RuleAction LinkToBill could not set the bill of journal #%d to bill "%s": already set.', + $journal['transaction_journal_id'], + $billName + )); // event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.already_linked_to_subscription', ['name' => $billName]))); return false; } DB::table('transaction_journals')->where('id', '=', $journal['transaction_journal_id'])->update(['bill_id' => $bill->id]); - Log::debug(sprintf('RuleAction LinkToBill set the bill of journal #%d to bill #%d ("%s").', $journal['transaction_journal_id'], $bill->id, $bill->name)); + Log::debug(sprintf( + 'RuleAction LinkToBill set the bill of journal #%d to bill #%d ("%s").', + $journal['transaction_journal_id'], + $bill->id, + $bill->name + )); /** @var TransactionJournal $object */ $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); @@ -77,7 +91,11 @@ class LinkToBill implements ActionInterface return true; } - Log::error(sprintf('RuleAction LinkToBill could not set the bill of journal #%d to bill "%s": no such bill found or not a withdrawal.', $journal['transaction_journal_id'], $billName)); + Log::error(sprintf( + 'RuleAction LinkToBill could not set the bill of journal #%d to bill "%s": no such bill found or not a withdrawal.', + $journal['transaction_journal_id'], + $billName + )); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_find_subscription', ['name' => $billName]))); return false; diff --git a/app/TransactionRules/Actions/MoveDescriptionToNotes.php b/app/TransactionRules/Actions/MoveDescriptionToNotes.php index 9d33d00438..cbbf28409f 100644 --- a/app/TransactionRules/Actions/MoveDescriptionToNotes.php +++ b/app/TransactionRules/Actions/MoveDescriptionToNotes.php @@ -24,12 +24,12 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; -use Illuminate\Support\Facades\Log; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Models\Note; use FireflyIII\Models\RuleAction; use FireflyIII\Models\TransactionJournal; +use Illuminate\Support\Facades\Log; /** * Class MoveDescriptionToNotes @@ -40,12 +40,14 @@ class MoveDescriptionToNotes implements ActionInterface /** * TriggerInterface constructor. */ - public function __construct(private readonly RuleAction $action) {} + public function __construct( + private readonly RuleAction $action + ) {} public function actOnArray(array $journal): bool { /** @var null|TransactionJournal $object */ - $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); + $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); if (null === $object) { Log::error(sprintf('No journal #%d belongs to user #%d.', $journal['transaction_journal_id'], $journal['user_id'])); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.journal_other_user'))); @@ -54,23 +56,23 @@ class MoveDescriptionToNotes implements ActionInterface } /** @var null|Note $note */ - $note = $object->notes()->first(); + $note = $object->notes()->first(); if (null === $note) { - $note = new Note(); + $note = new Note(); $note->noteable()->associate($object); $note->text = ''; } $before = $note->text; $beforeDescription = $object->description; if ('' !== $note->text) { - $note->text = trim(sprintf("%s \n%s", $note->text, $object->description)); + $note->text = trim(sprintf("%s \n%s", $note->text, $object->description)); $object->description = '(no description)'; } if ('' === $note->text) { - $note->text = (string) $object->description; + $note->text = (string) $object->description; $object->description = '(no description)'; } - $after = $note->text; + $after = $note->text; event(new TriggeredAuditLog($this->action->rule, $object, 'update_description', $beforeDescription, $object->description)); event(new TriggeredAuditLog($this->action->rule, $object, 'update_notes', $before, $after)); diff --git a/app/TransactionRules/Actions/MoveNotesToDescription.php b/app/TransactionRules/Actions/MoveNotesToDescription.php index 26ed48c2b6..467af03186 100644 --- a/app/TransactionRules/Actions/MoveNotesToDescription.php +++ b/app/TransactionRules/Actions/MoveNotesToDescription.php @@ -24,12 +24,12 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; -use Illuminate\Support\Facades\Log; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Models\RuleAction; use FireflyIII\Models\TransactionJournal; use FireflyIII\Support\Request\ConvertsDataTypes; +use Illuminate\Support\Facades\Log; /** * Class MoveNotesToDescription @@ -46,19 +46,21 @@ class MoveNotesToDescription implements ActionInterface /** * TriggerInterface constructor. */ - public function __construct(private RuleAction $action) {} + public function __construct( + private RuleAction $action + ) {} public function actOnArray(array $journal): bool { /** @var null|TransactionJournal $object */ - $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); + $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); if (null === $object) { Log::error(sprintf('No journal #%d belongs to user #%d.', $journal['transaction_journal_id'], $journal['user_id'])); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.journal_other_user'))); return false; } - $note = $object->notes()->first(); + $note = $object->notes()->first(); if (null === $note) { event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.no_notes_to_move'))); @@ -72,8 +74,8 @@ class MoveNotesToDescription implements ActionInterface return false; } - $before = $object->description; - $beforeNote = $note->text; + $before = $object->description; + $beforeNote = $note->text; $object->description = (string) $this->clearString($note->text); $object->save(); $note->delete(); diff --git a/app/TransactionRules/Actions/PrependDescription.php b/app/TransactionRules/Actions/PrependDescription.php index 37e888ca34..18657957ef 100644 --- a/app/TransactionRules/Actions/PrependDescription.php +++ b/app/TransactionRules/Actions/PrependDescription.php @@ -37,13 +37,18 @@ class PrependDescription implements ActionInterface /** * TriggerInterface constructor. */ - public function __construct(private readonly RuleAction $action) {} + public function __construct( + private readonly RuleAction $action + ) {} public function actOnArray(array $journal): bool { $before = $journal['description']; $after = sprintf('%s%s', $this->action->getValue($journal), $journal['description']); - DB::table('transaction_journals')->where('id', $journal['transaction_journal_id'])->limit(1)->update(['description' => $after]); + DB::table('transaction_journals') + ->where('id', $journal['transaction_journal_id']) + ->limit(1) + ->update(['description' => $after]); // journal /** @var TransactionJournal $object */ diff --git a/app/TransactionRules/Actions/PrependNotes.php b/app/TransactionRules/Actions/PrependNotes.php index 71bdfb028e..67ce2b4fc7 100644 --- a/app/TransactionRules/Actions/PrependNotes.php +++ b/app/TransactionRules/Actions/PrependNotes.php @@ -23,11 +23,11 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; -use Illuminate\Support\Facades\Log; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Models\Note; use FireflyIII\Models\RuleAction; use FireflyIII\Models\TransactionJournal; +use Illuminate\Support\Facades\Log; /** * Class PrependNotes. @@ -38,30 +38,29 @@ class PrependNotes implements ActionInterface /** * TriggerInterface constructor. */ - public function __construct(private readonly RuleAction $action) {} + public function __construct( + private readonly RuleAction $action + ) {} public function actOnArray(array $journal): bool { - $dbNote = Note::where('noteable_id', (int) $journal['transaction_journal_id']) - ->where('noteable_type', TransactionJournal::class) - ->first(['notes.*']) - ; + $dbNote = Note::where('noteable_id', (int) $journal['transaction_journal_id'])->where('noteable_type', TransactionJournal::class)->first(['notes.*']); if (null === $dbNote) { - $dbNote = new Note(); - $dbNote->noteable_id = (int) $journal['transaction_journal_id']; + $dbNote = new Note(); + $dbNote->noteable_id = (int) $journal['transaction_journal_id']; $dbNote->noteable_type = TransactionJournal::class; - $dbNote->text = ''; + $dbNote->text = ''; } - $before = $dbNote->text; - $after = $this->action->getValue($journal); + $before = $dbNote->text; + $after = $this->action->getValue($journal); Log::debug(sprintf('RuleAction PrependNotes prepended "%s" to "%s".', $after, $dbNote->text)); - $text = sprintf('%s%s', $after, $dbNote->text); + $text = sprintf('%s%s', $after, $dbNote->text); $dbNote->text = $text; $dbNote->save(); // journal /** @var TransactionJournal $object */ - $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); + $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); // audit log event(new TriggeredAuditLog($this->action->rule, $object, 'update_notes', $before, $text)); diff --git a/app/TransactionRules/Actions/RemoveAllTags.php b/app/TransactionRules/Actions/RemoveAllTags.php index f21a6c2254..6b25422593 100644 --- a/app/TransactionRules/Actions/RemoveAllTags.php +++ b/app/TransactionRules/Actions/RemoveAllTags.php @@ -23,12 +23,12 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; -use Illuminate\Support\Facades\Log; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Models\RuleAction; use FireflyIII\Models\TransactionJournal; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Log; /** * Class RemoveAllTags. @@ -38,12 +38,14 @@ class RemoveAllTags implements ActionInterface /** * TriggerInterface constructor. */ - public function __construct(private readonly RuleAction $action) {} + public function __construct( + private readonly RuleAction $action + ) {} public function actOnArray(array $journal): bool { DB::table('tag_transaction_journal')->where('transaction_journal_id', $journal['transaction_journal_id'])->delete(); - $count = DB::table('tag_transaction_journal')->where('transaction_journal_id', $journal['transaction_journal_id'])->count(); + $count = DB::table('tag_transaction_journal')->where('transaction_journal_id', $journal['transaction_journal_id'])->count(); if (0 === $count) { Log::debug(sprintf('RuleAction RemoveAllTags, journal #%d has no tags.', $journal['transaction_journal_id'])); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.no_tags_to_remove'))); diff --git a/app/TransactionRules/Actions/RemoveTag.php b/app/TransactionRules/Actions/RemoveTag.php index 80c8f13066..5fcb9cd13f 100644 --- a/app/TransactionRules/Actions/RemoveTag.php +++ b/app/TransactionRules/Actions/RemoveTag.php @@ -23,13 +23,13 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; -use Illuminate\Support\Facades\Log; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Models\RuleAction; use FireflyIII\Models\TransactionJournal; use FireflyIII\User; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Log; /** * Class RemoveTag. @@ -39,30 +39,39 @@ class RemoveTag implements ActionInterface /** * TriggerInterface constructor. */ - public function __construct(private readonly RuleAction $action) {} + public function __construct( + private readonly RuleAction $action + ) {} public function actOnArray(array $journal): bool { - $name = $this->action->getValue($journal); + $name = $this->action->getValue($journal); /** @var User $user */ - $user = User::find($journal['user_id']); - $tag = $user->tags()->where('tag', $name)->first(); + $user = User::find($journal['user_id']); + $tag = $user->tags()->where('tag', $name)->first(); // if tag does not exist, no need to continue: if (null === $tag) { - Log::debug( - sprintf('RuleAction RemoveTag tried to remove tag "%s" from journal #%d but no such tag exists.', $name, $journal['transaction_journal_id']) - ); + Log::debug(sprintf( + 'RuleAction RemoveTag tried to remove tag "%s" from journal #%d but no such tag exists.', + $name, + $journal['transaction_journal_id'] + )); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_find_tag', ['tag' => $name]))); return false; } - $count = DB::table('tag_transaction_journal')->where('transaction_journal_id', $journal['transaction_journal_id'])->where('tag_id', $tag->id)->count(); + $count = DB::table('tag_transaction_journal') + ->where('transaction_journal_id', $journal['transaction_journal_id']) + ->where('tag_id', $tag->id) + ->count(); if (0 === $count) { - Log::debug( - sprintf('RuleAction RemoveTag tried to remove tag "%s" from journal #%d but no such tag is linked.', $name, $journal['transaction_journal_id']) - ); + Log::debug(sprintf( + 'RuleAction RemoveTag tried to remove tag "%s" from journal #%d but no such tag is linked.', + $name, + $journal['transaction_journal_id'] + )); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_unlink_tag', ['tag' => $name]))); return false; @@ -72,8 +81,7 @@ class RemoveTag implements ActionInterface DB::table('tag_transaction_journal') ->where('transaction_journal_id', $journal['transaction_journal_id']) ->where('tag_id', $tag->id) - ->delete() - ; + ->delete(); /** @var TransactionJournal $object */ $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); diff --git a/app/TransactionRules/Actions/SetAmount.php b/app/TransactionRules/Actions/SetAmount.php index 856e342336..1968c185c3 100644 --- a/app/TransactionRules/Actions/SetAmount.php +++ b/app/TransactionRules/Actions/SetAmount.php @@ -40,7 +40,9 @@ class SetAmount implements ActionInterface /** * TriggerInterface constructor. */ - public function __construct(private RuleAction $action) {} + public function __construct( + private RuleAction $action + ) {} public function actOnArray(array $journal): bool { @@ -55,7 +57,7 @@ class SetAmount implements ActionInterface return false; } - $value = $this->action->getValue($journal); + $value = $this->action->getValue($journal); if (!is_numeric($value) || 0 === bccomp($value, '0')) { Log::debug(sprintf('RuleAction SetAmount, amount "%s" is not a number or is zero, will not continue.', $value)); @@ -65,10 +67,10 @@ class SetAmount implements ActionInterface } /** @var TransactionJournal $object */ - $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); + $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); - $positive = Steam::positive($value); - $negative = Steam::negative($value); + $positive = Steam::positive($value); + $negative = Steam::negative($value); $this->updatePositive($object, $positive); $this->updateNegative($object, $negative); @@ -76,21 +78,23 @@ class SetAmount implements ActionInterface // event for audit log entry if (0 !== bccomp($journal['amount'], $value)) { - event(new TriggeredAuditLog( - $this->action->rule, - $object, - 'update_amount', - [ - 'currency_symbol' => $object->transactionCurrency->symbol, - 'decimal_places' => $object->transactionCurrency->decimal_places, - 'amount' => $journal['amount'], - ], - [ - 'currency_symbol' => $object->transactionCurrency->symbol, - 'decimal_places' => $object->transactionCurrency->decimal_places, - 'amount' => $value, - ] - )); + event( + new TriggeredAuditLog( + $this->action->rule, + $object, + 'update_amount', + [ + 'currency_symbol' => $object->transactionCurrency->symbol, + 'decimal_places' => $object->transactionCurrency->decimal_places, + 'amount' => $journal['amount'] + ], + [ + 'currency_symbol' => $object->transactionCurrency->symbol, + 'decimal_places' => $object->transactionCurrency->decimal_places, + 'amount' => $value + ] + ) + ); } return true; diff --git a/app/TransactionRules/Actions/SetBudget.php b/app/TransactionRules/Actions/SetBudget.php index 4aa0c06243..920e57734e 100644 --- a/app/TransactionRules/Actions/SetBudget.php +++ b/app/TransactionRules/Actions/SetBudget.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; -use Illuminate\Support\Facades\Log; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; @@ -31,6 +30,7 @@ use FireflyIII\Models\RuleAction; use FireflyIII\Models\TransactionJournal; use FireflyIII\User; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Log; /** * Class SetBudget. @@ -40,38 +40,39 @@ class SetBudget implements ActionInterface /** * TriggerInterface constructor. */ - public function __construct(private readonly RuleAction $action) {} + public function __construct( + private readonly RuleAction $action + ) {} public function actOnArray(array $journal): bool { /** @var User $user */ - $user = User::find($journal['user_id']); - $search = $this->action->getValue($journal); + $user = User::find($journal['user_id']); + $search = $this->action->getValue($journal); - $budget = $user->budgets()->where('name', $search)->first(); + $budget = $user->budgets()->where('name', $search)->first(); if (null === $budget) { - Log::debug( - sprintf( - 'RuleAction SetBudget could not set budget of journal #%d to "%s" because no such budget exists.', - $journal['transaction_journal_id'], - $search - ) - ); + Log::debug(sprintf( + 'RuleAction SetBudget could not set budget of journal #%d to "%s" because no such budget exists.', + $journal['transaction_journal_id'], + $search + )); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_find_budget', ['name' => $search]))); return false; } if (TransactionTypeEnum::WITHDRAWAL->value !== $journal['transaction_type_type']) { - Log::debug( - sprintf( - 'RuleAction SetBudget could not set budget of journal #%d to "%s" because journal is a %s.', - $journal['transaction_journal_id'], - $search, - $journal['transaction_type_type'] - ) - ); - event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_set_budget', ['type' => $journal['transaction_type_type'], 'name' => $search]))); + Log::debug(sprintf( + 'RuleAction SetBudget could not set budget of journal #%d to "%s" because journal is a %s.', + $journal['transaction_journal_id'], + $search, + $journal['transaction_type_type'] + )); + event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_set_budget', [ + 'type' => $journal['transaction_type_type'], + 'name' => $search + ]))); return false; } @@ -87,15 +88,21 @@ class SetBudget implements ActionInterface return false; } - Log::debug( - sprintf('RuleAction SetBudget set the budget of journal #%d to budget #%d ("%s").', $journal['transaction_journal_id'], $budget->id, $budget->name) - ); + Log::debug(sprintf( + 'RuleAction SetBudget set the budget of journal #%d to budget #%d ("%s").', + $journal['transaction_journal_id'], + $budget->id, + $budget->name + )); DB::table('budget_transaction_journal')->where('transaction_journal_id', '=', $journal['transaction_journal_id'])->delete(); - DB::table('budget_transaction_journal')->insert(['transaction_journal_id' => $journal['transaction_journal_id'], 'budget_id' => $budget->id]); + DB::table('budget_transaction_journal')->insert([ + 'transaction_journal_id' => $journal['transaction_journal_id'], + 'budget_id' => $budget->id + ]); /** @var TransactionJournal $object */ - $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); + $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); event(new TriggeredAuditLog($this->action->rule, $object, 'set_budget', $oldBudgetName, $budget->name)); return true; diff --git a/app/TransactionRules/Actions/SetCategory.php b/app/TransactionRules/Actions/SetCategory.php index 0ac36cd83e..b709829bde 100644 --- a/app/TransactionRules/Actions/SetCategory.php +++ b/app/TransactionRules/Actions/SetCategory.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; -use Illuminate\Support\Facades\Log; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Factory\CategoryFactory; @@ -31,6 +30,7 @@ use FireflyIII\Models\RuleAction; use FireflyIII\Models\TransactionJournal; use FireflyIII\User; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Log; /** * Class SetCategory. @@ -40,13 +40,15 @@ class SetCategory implements ActionInterface /** * TriggerInterface constructor. */ - public function __construct(private readonly RuleAction $action) {} + public function __construct( + private readonly RuleAction $action + ) {} public function actOnArray(array $journal): bool { /** @var null|User $user */ - $user = User::find($journal['user_id']); - $search = $this->action->getValue($journal); + $user = User::find($journal['user_id']); + $search = $this->action->getValue($journal); if (null === $user) { Log::error(sprintf('Journal has no valid user ID so action SetCategory("%s") cannot be applied', $search), $journal); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.no_such_journal'))); @@ -55,30 +57,26 @@ class SetCategory implements ActionInterface } /** @var CategoryFactory $factory */ - $factory = app(CategoryFactory::class); + $factory = app(CategoryFactory::class); $factory->setUser($user); - $category = $factory->findOrCreate(null, $search); + $category = $factory->findOrCreate(null, $search); if (null === $category) { - Log::debug( - sprintf( - 'RuleAction SetCategory could not set category of journal #%d to "%s" because no such category exists.', - $journal['transaction_journal_id'], - $search - ) - ); + Log::debug(sprintf( + 'RuleAction SetCategory could not set category of journal #%d to "%s" because no such category exists.', + $journal['transaction_journal_id'], + $search + )); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_find_category', ['name' => $search]))); return false; } - Log::debug( - sprintf( - 'RuleAction SetCategory set the category of journal #%d to category #%d ("%s").', - $journal['transaction_journal_id'], - $category->id, - $category->name - ) - ); + Log::debug(sprintf( + 'RuleAction SetCategory set the category of journal #%d to category #%d ("%s").', + $journal['transaction_journal_id'], + $category->id, + $category->name + )); // find previous category /** @var TransactionJournal $object */ @@ -92,10 +90,13 @@ class SetCategory implements ActionInterface } DB::table('category_transaction_journal')->where('transaction_journal_id', '=', $journal['transaction_journal_id'])->delete(); - DB::table('category_transaction_journal')->insert(['transaction_journal_id' => $journal['transaction_journal_id'], 'category_id' => $category->id]); + DB::table('category_transaction_journal')->insert([ + 'transaction_journal_id' => $journal['transaction_journal_id'], + 'category_id' => $category->id + ]); /** @var TransactionJournal $object */ - $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); + $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); event(new TriggeredAuditLog($this->action->rule, $object, 'set_category', $oldCategoryName, $category->name)); return true; diff --git a/app/TransactionRules/Actions/SetDescription.php b/app/TransactionRules/Actions/SetDescription.php index 66c0023450..c8b852bdda 100644 --- a/app/TransactionRules/Actions/SetDescription.php +++ b/app/TransactionRules/Actions/SetDescription.php @@ -40,7 +40,9 @@ class SetDescription implements ActionInterface /** * TriggerInterface constructor. */ - public function __construct(private RuleAction $action) {} + public function __construct( + private RuleAction $action + ) {} public function actOnArray(array $journal): bool { @@ -52,26 +54,21 @@ class SetDescription implements ActionInterface $after = $this->action->getValue($journal); // replace newlines. - $after = trim(str_replace(["\r", "\n", "\t", "\036", "\025"], '', $after)); + $after = trim(str_replace(["\r", "\n", "\t", "\036", "\025"], '', $after)); if ('' === $after) { Log::warning('Action resulted in an empty description, reset to default value.'); $after = '(no description)'; } - DB::table('transaction_journals') - ->where('id', '=', $journal['transaction_journal_id']) - ->update(['description' => $after]) - ; + DB::table('transaction_journals')->where('id', '=', $journal['transaction_journal_id'])->update(['description' => $after]); - Log::debug( - sprintf( - 'RuleAction SetDescription changed the description of journal #%d from "%s" to "%s".', - $journal['transaction_journal_id'], - $journal['description'], - $after - ) - ); + Log::debug(sprintf( + 'RuleAction SetDescription changed the description of journal #%d from "%s" to "%s".', + $journal['transaction_journal_id'], + $journal['description'], + $after + )); $object->refresh(); event(new TriggeredAuditLog($this->action->rule, $object, 'update_description', $before, $after)); diff --git a/app/TransactionRules/Actions/SetDestinationAccount.php b/app/TransactionRules/Actions/SetDestinationAccount.php index c2e71b0f24..7c060935c9 100644 --- a/app/TransactionRules/Actions/SetDestinationAccount.php +++ b/app/TransactionRules/Actions/SetDestinationAccount.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; -use Illuminate\Support\Facades\Log; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; @@ -34,6 +33,7 @@ use FireflyIII\Models\TransactionJournal; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\User; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Log; /** * Class SetDestinationAccount. @@ -45,17 +45,19 @@ class SetDestinationAccount implements ActionInterface /** * TriggerInterface constructor. */ - public function __construct(private readonly RuleAction $action) {} + public function __construct( + private readonly RuleAction $action + ) {} public function actOnArray(array $journal): bool { - $accountName = $this->action->getValue($journal); + $accountName = $this->action->getValue($journal); /** @var User $user */ - $user = User::find($journal['user_id']); + $user = User::find($journal['user_id']); /** @var null|TransactionJournal $object */ - $object = $user->transactionJournals()->find((int) $journal['transaction_journal_id']); + $object = $user->transactionJournals()->find((int) $journal['transaction_journal_id']); $this->repository = app(AccountRepositoryInterface::class); if (null === $object) { @@ -64,19 +66,13 @@ class SetDestinationAccount implements ActionInterface return false; } - $type = $object->transactionType->type; + $type = $object->transactionType->type; $this->repository->setUser($user); // if this is a transfer or a deposit, the new destination account must be an asset account or a default account, and it MUST exist: - $newAccount = $this->findAssetAccount($type, $accountName); + $newAccount = $this->findAssetAccount($type, $accountName); if ((TransactionTypeEnum::DEPOSIT->value === $type || TransactionTypeEnum::TRANSFER->value === $type) && !$newAccount instanceof Account) { - Log::error( - sprintf( - 'Cant change destination account of journal #%d because no asset account with name "%s" exists.', - $object->id, - $accountName - ) - ); + Log::error(sprintf('Cant change destination account of journal #%d because no asset account with name "%s" exists.', $object->id, $accountName)); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_find_asset', ['name' => $accountName]))); return false; @@ -84,7 +80,7 @@ class SetDestinationAccount implements ActionInterface // new destination account must be different from the current source account: /** @var null|Transaction $source */ - $source = $object->transactions()->where('amount', '<', 0)->first(); + $source = $object->transactions()->where('amount', '<', 0)->first(); if (null === $source) { Log::error('Could not find source transaction.'); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_find_source_transaction'))); @@ -99,13 +95,11 @@ class SetDestinationAccount implements ActionInterface return false; } if ($newAccount instanceof Account && $newAccount->id === $source->account_id) { - Log::error( - sprintf( - 'New destination account ID #%d and current source account ID #%d are the same. Do nothing.', - $newAccount->id, - $source->account_id - ) - ); + Log::error(sprintf( + 'New destination account ID #%d and current source account ID #%d are the same. Do nothing.', + $newAccount->id, + $source->account_id + )); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.already_has_destination', ['name' => $newAccount->name]))); @@ -118,12 +112,7 @@ class SetDestinationAccount implements ActionInterface $newAccount = $this->findWithdrawalDestinationAccount($accountName); } if (!$newAccount instanceof Account) { - Log::error( - sprintf( - 'No destination account found for name "%s".', - $accountName - ) - ); + Log::error(sprintf('No destination account found for name "%s".', $accountName)); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.no_destination', ['name' => $accountName]))); @@ -138,15 +127,14 @@ class SetDestinationAccount implements ActionInterface DB::table('transactions') ->where('transaction_journal_id', '=', $object->id) ->where('amount', '>', 0) - ->update(['account_id' => $newAccount->id]) - ; + ->update(['account_id' => $newAccount->id]); Log::debug(sprintf('Updated journal #%d (group #%d) and gave it new destination account ID.', $object->id, $object->transaction_group_id)); return true; } - private function findAssetAccount(string $type, string $accountName): ?Account + private function findAssetAccount(string $type, string $accountName): null|Account { // switch on type: $allowed = config(sprintf('firefly.expected_source_types.destination.%s', $type)); @@ -167,7 +155,7 @@ class SetDestinationAccount implements ActionInterface 'account_type_id' => null, 'virtual_balance' => 0, 'active' => true, - 'iban' => null, + 'iban' => null ]; $account = $this->repository->store($data); } diff --git a/app/TransactionRules/Actions/SetDestinationToCashAccount.php b/app/TransactionRules/Actions/SetDestinationToCashAccount.php index 34aa5392c3..e15bd884b7 100644 --- a/app/TransactionRules/Actions/SetDestinationToCashAccount.php +++ b/app/TransactionRules/Actions/SetDestinationToCashAccount.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; -use Illuminate\Support\Facades\Log; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; @@ -34,6 +33,7 @@ use FireflyIII\Models\TransactionJournal; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\User; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Log; /** * Class SetDestinationToCashAccount @@ -43,16 +43,18 @@ class SetDestinationToCashAccount implements ActionInterface /** * TriggerInterface constructor. */ - public function __construct(private readonly RuleAction $action) {} + public function __construct( + private readonly RuleAction $action + ) {} public function actOnArray(array $journal): bool { /** @var User $user */ - $user = User::find($journal['user_id']); + $user = User::find($journal['user_id']); /** @var null|TransactionJournal $object */ - $object = $user->transactionJournals()->find((int) $journal['transaction_journal_id']); - $repository = app(AccountRepositoryInterface::class); + $object = $user->transactionJournals()->find((int) $journal['transaction_journal_id']); + $repository = app(AccountRepositoryInterface::class); if (null === $object) { Log::error('Could not find journal.'); @@ -60,7 +62,7 @@ class SetDestinationToCashAccount implements ActionInterface return false; } - $type = $object->transactionType->type; + $type = $object->transactionType->type; if (TransactionTypeEnum::WITHDRAWAL->value !== $type) { Log::error('Transaction must be withdrawal.'); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.not_withdrawal'))); @@ -74,7 +76,7 @@ class SetDestinationToCashAccount implements ActionInterface // new destination account must be different from the current source account: /** @var null|Transaction $source */ - $source = $object->transactions()->where('amount', '<', 0)->first(); + $source = $object->transactions()->where('amount', '<', 0)->first(); if (null === $source) { Log::error('Could not find source transaction.'); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_find_source_transaction'))); @@ -89,13 +91,11 @@ class SetDestinationToCashAccount implements ActionInterface return false; } if ($cashAccount->id === $source->account_id) { - Log::error( - sprintf( - 'New destination account ID #%d and current source account ID #%d are the same. Do nothing.', - $cashAccount->id, - $source->account_id - ) - ); + Log::error(sprintf( + 'New destination account ID #%d and current source account ID #%d are the same. Do nothing.', + $cashAccount->id, + $source->account_id + )); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.already_has_destination', ['name' => $cashAccount->name]))); @@ -108,8 +108,7 @@ class SetDestinationToCashAccount implements ActionInterface DB::table('transactions') ->where('transaction_journal_id', '=', $object->id) ->where('amount', '>', 0) - ->update(['account_id' => $cashAccount->id]) - ; + ->update(['account_id' => $cashAccount->id]); Log::debug(sprintf('Updated journal #%d (group #%d) and gave it new destination account ID.', $object->id, $object->transaction_group_id)); diff --git a/app/TransactionRules/Actions/SetNotes.php b/app/TransactionRules/Actions/SetNotes.php index 26e48501bb..0b0b5855bf 100644 --- a/app/TransactionRules/Actions/SetNotes.php +++ b/app/TransactionRules/Actions/SetNotes.php @@ -23,11 +23,11 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; -use Illuminate\Support\Facades\Log; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Models\Note; use FireflyIII\Models\RuleAction; use FireflyIII\Models\TransactionJournal; +use Illuminate\Support\Facades\Log; /** * Class SetNotes. @@ -37,35 +37,33 @@ class SetNotes implements ActionInterface /** * TriggerInterface constructor. */ - public function __construct(private readonly RuleAction $action) {} + public function __construct( + private readonly RuleAction $action + ) {} public function actOnArray(array $journal): bool { - $dbNote = Note::where('noteable_id', $journal['transaction_journal_id']) - ->where('noteable_type', TransactionJournal::class)->first() - ; + $dbNote = Note::where('noteable_id', $journal['transaction_journal_id'])->where('noteable_type', TransactionJournal::class)->first(); if (null === $dbNote) { - $dbNote = new Note(); - $dbNote->noteable_id = $journal['transaction_journal_id']; + $dbNote = new Note(); + $dbNote->noteable_id = $journal['transaction_journal_id']; $dbNote->noteable_type = TransactionJournal::class; - $dbNote->text = ''; + $dbNote->text = ''; } - $oldNotes = $dbNote->text; - $newNotes = $this->action->getValue($journal); + $oldNotes = $dbNote->text; + $newNotes = $this->action->getValue($journal); $dbNote->text = $newNotes; $dbNote->save(); - Log::debug( - sprintf( - 'RuleAction SetNotes changed the notes of journal #%d from "%s" to "%s".', - $journal['transaction_journal_id'], - $oldNotes, - $newNotes - ) - ); + Log::debug(sprintf( + 'RuleAction SetNotes changed the notes of journal #%d from "%s" to "%s".', + $journal['transaction_journal_id'], + $oldNotes, + $newNotes + )); /** @var TransactionJournal $object */ - $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); + $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); event(new TriggeredAuditLog($this->action->rule, $object, 'update_notes', $oldNotes, $newNotes)); diff --git a/app/TransactionRules/Actions/SetSourceAccount.php b/app/TransactionRules/Actions/SetSourceAccount.php index ba6ae75d8e..148772d0d6 100644 --- a/app/TransactionRules/Actions/SetSourceAccount.php +++ b/app/TransactionRules/Actions/SetSourceAccount.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; -use Illuminate\Support\Facades\Log; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; @@ -34,6 +33,7 @@ use FireflyIII\Models\TransactionJournal; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\User; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Log; /** * Class SetSourceAccount. @@ -45,17 +45,19 @@ class SetSourceAccount implements ActionInterface /** * TriggerInterface constructor. */ - public function __construct(private readonly RuleAction $action) {} + public function __construct( + private readonly RuleAction $action + ) {} public function actOnArray(array $journal): bool { - $accountName = $this->action->getValue($journal); + $accountName = $this->action->getValue($journal); /** @var User $user */ - $user = User::find($journal['user_id']); + $user = User::find($journal['user_id']); /** @var null|TransactionJournal $object */ - $object = $user->transactionJournals()->find((int) $journal['transaction_journal_id']); + $object = $user->transactionJournals()->find((int) $journal['transaction_journal_id']); $this->repository = app(AccountRepositoryInterface::class); if (null === $object) { Log::error('Could not find journal.'); @@ -63,15 +65,13 @@ class SetSourceAccount implements ActionInterface return false; } - $type = $object->transactionType->type; + $type = $object->transactionType->type; $this->repository->setUser($user); // if this is a transfer or a withdrawal, the new source account must be an asset account or a default account, and it MUST exist: - $newAccount = $this->findAssetAccount($type, $accountName); + $newAccount = $this->findAssetAccount($type, $accountName); if ((TransactionTypeEnum::WITHDRAWAL->value === $type || TransactionTypeEnum::TRANSFER->value === $type) && !$newAccount instanceof Account) { - Log::error( - sprintf('Cant change source account of journal #%d because no asset account with name "%s" exists.', $object->id, $accountName) - ); + Log::error(sprintf('Cant change source account of journal #%d because no asset account with name "%s" exists.', $object->id, $accountName)); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_find_asset', ['name' => $accountName]))); return false; @@ -79,7 +79,7 @@ class SetSourceAccount implements ActionInterface // new source account must be different from the current destination account: /** @var null|Transaction $destination */ - $destination = $object->transactions()->where('amount', '>', 0)->first(); + $destination = $object->transactions()->where('amount', '>', 0)->first(); if (null === $destination) { Log::error('Could not find destination transaction.'); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_find_destination_transaction'))); @@ -94,13 +94,11 @@ class SetSourceAccount implements ActionInterface return false; } if ($newAccount instanceof Account && $newAccount->id === $destination->account_id) { - Log::error( - sprintf( - 'New source account ID #%d and current destination account ID #%d are the same. Do nothing.', - $newAccount->id, - $destination->account_id - ) - ); + Log::error(sprintf( + 'New source account ID #%d and current destination account ID #%d are the same. Do nothing.', + $newAccount->id, + $destination->account_id + )); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.already_has_source', ['name' => $newAccount->name]))); return false; @@ -118,8 +116,7 @@ class SetSourceAccount implements ActionInterface DB::table('transactions') ->where('transaction_journal_id', '=', $object->id) ->where('amount', '<', 0) - ->update(['account_id' => $newAccount->id]) - ; + ->update(['account_id' => $newAccount->id]); event(new TriggeredAuditLog($this->action->rule, $object, 'set_source', null, $newAccount->name)); @@ -128,7 +125,7 @@ class SetSourceAccount implements ActionInterface return true; } - private function findAssetAccount(string $type, string $accountName): ?Account + private function findAssetAccount(string $type, string $accountName): null|Account { // switch on type: $allowed = config(sprintf('firefly.expected_source_types.source.%s', $type)); @@ -150,7 +147,7 @@ class SetSourceAccount implements ActionInterface 'account_type_id' => null, 'virtual_balance' => 0, 'active' => true, - 'iban' => null, + 'iban' => null ]; $account = $this->repository->store($data); } diff --git a/app/TransactionRules/Actions/SetSourceToCashAccount.php b/app/TransactionRules/Actions/SetSourceToCashAccount.php index 9cea693e82..e66d9771b4 100644 --- a/app/TransactionRules/Actions/SetSourceToCashAccount.php +++ b/app/TransactionRules/Actions/SetSourceToCashAccount.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; -use Illuminate\Support\Facades\Log; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; @@ -34,6 +33,7 @@ use FireflyIII\Models\TransactionJournal; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\User; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Log; /** * Class SetSourceToCashAccount @@ -43,16 +43,18 @@ class SetSourceToCashAccount implements ActionInterface /** * TriggerInterface constructor. */ - public function __construct(private readonly RuleAction $action) {} + public function __construct( + private readonly RuleAction $action + ) {} public function actOnArray(array $journal): bool { /** @var User $user */ - $user = User::find($journal['user_id']); + $user = User::find($journal['user_id']); /** @var null|TransactionJournal $object */ - $object = $user->transactionJournals()->find((int) $journal['transaction_journal_id']); - $repository = app(AccountRepositoryInterface::class); + $object = $user->transactionJournals()->find((int) $journal['transaction_journal_id']); + $repository = app(AccountRepositoryInterface::class); if (null === $object) { Log::error('Could not find journal.'); @@ -60,7 +62,7 @@ class SetSourceToCashAccount implements ActionInterface return false; } - $type = $object->transactionType->type; + $type = $object->transactionType->type; if (TransactionTypeEnum::DEPOSIT->value !== $type) { Log::error('Transaction must be deposit.'); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.not_deposit'))); @@ -89,13 +91,11 @@ class SetSourceToCashAccount implements ActionInterface return false; } if ($cashAccount->id === $destination->account_id) { - Log::error( - sprintf( - 'New source account ID #%d and current destination account ID #%d are the same. Do nothing.', - $cashAccount->id, - $destination->account_id - ) - ); + Log::error(sprintf( + 'New source account ID #%d and current destination account ID #%d are the same. Do nothing.', + $cashAccount->id, + $destination->account_id + )); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.already_has_source', ['name' => $cashAccount->name]))); @@ -108,8 +108,7 @@ class SetSourceToCashAccount implements ActionInterface DB::table('transactions') ->where('transaction_journal_id', '=', $object->id) ->where('amount', '<', 0) - ->update(['account_id' => $cashAccount->id]) - ; + ->update(['account_id' => $cashAccount->id]); Log::debug(sprintf('Updated journal #%d (group #%d) and gave it new source account ID.', $object->id, $object->transaction_group_id)); diff --git a/app/TransactionRules/Actions/SwitchAccounts.php b/app/TransactionRules/Actions/SwitchAccounts.php index 5ee4219b0d..4c75771352 100644 --- a/app/TransactionRules/Actions/SwitchAccounts.php +++ b/app/TransactionRules/Actions/SwitchAccounts.php @@ -24,13 +24,13 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Actions; -use Illuminate\Support\Facades\Log; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Events\Model\Rule\RuleActionFailedOnArray; use FireflyIII\Events\TriggeredAuditLog; use FireflyIII\Models\RuleAction; use FireflyIII\Models\Transaction; use FireflyIII\Models\TransactionJournal; +use Illuminate\Support\Facades\Log; /** * Class SwitchAccounts @@ -40,20 +40,22 @@ class SwitchAccounts implements ActionInterface /** * TriggerInterface constructor. */ - public function __construct(private readonly RuleAction $action) {} + public function __construct( + private readonly RuleAction $action + ) {} public function actOnArray(array $journal): bool { // make object from array (so the data is fresh). /** @var null|TransactionJournal $object */ - $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); + $object = TransactionJournal::where('user_id', $journal['user_id'])->find($journal['transaction_journal_id']); if (null === $object) { Log::error(sprintf('Cannot find journal #%d, cannot switch accounts.', $journal['transaction_journal_id'])); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.no_such_journal'))); return false; } - $groupCount = TransactionJournal::where('transaction_group_id', $journal['transaction_group_id'])->count(); + $groupCount = TransactionJournal::where('transaction_group_id', $journal['transaction_group_id'])->count(); if ($groupCount > 1) { Log::error(sprintf('Group #%d has more than one transaction in it, cannot switch accounts.', $journal['transaction_group_id'])); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.split_group'))); @@ -61,29 +63,37 @@ class SwitchAccounts implements ActionInterface return false; } - $type = $object->transactionType->type; + $type = $object->transactionType->type; if (TransactionTypeEnum::TRANSFER->value !== $type) { - Log::error(sprintf('Journal #%d is NOT a transfer (rule #%d), cannot switch accounts.', $journal['transaction_journal_id'], $this->action->rule_id)); + Log::error(sprintf( + 'Journal #%d is NOT a transfer (rule #%d), cannot switch accounts.', + $journal['transaction_journal_id'], + $this->action->rule_id + )); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.is_not_transfer'))); return false; } /** @var null|Transaction $sourceTransaction */ - $sourceTransaction = $object->transactions()->where('amount', '<', 0)->first(); + $sourceTransaction = $object->transactions()->where('amount', '<', 0)->first(); /** @var null|Transaction $destTransaction */ - $destTransaction = $object->transactions()->where('amount', '>', 0)->first(); + $destTransaction = $object->transactions()->where('amount', '>', 0)->first(); if (null === $sourceTransaction || null === $destTransaction) { - Log::error(sprintf('Journal #%d has no source or destination transaction (rule #%d), cannot switch accounts.', $journal['transaction_journal_id'], $this->action->rule_id)); + Log::error(sprintf( + 'Journal #%d has no source or destination transaction (rule #%d), cannot switch accounts.', + $journal['transaction_journal_id'], + $this->action->rule_id + )); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_find_accounts'))); return false; } - $sourceAccountId = $sourceTransaction->account_id; - $destinationAccountId = $destTransaction->account_id; + $sourceAccountId = $sourceTransaction->account_id; + $destinationAccountId = $destTransaction->account_id; $sourceTransaction->account_id = $destinationAccountId; - $destTransaction->account_id = $sourceAccountId; + $destTransaction->account_id = $sourceAccountId; $sourceTransaction->save(); $destTransaction->save(); diff --git a/app/TransactionRules/Actions/UpdatePiggyBank.php b/app/TransactionRules/Actions/UpdatePiggyBank.php index 628200c599..4a4585db66 100644 --- a/app/TransactionRules/Actions/UpdatePiggyBank.php +++ b/app/TransactionRules/Actions/UpdatePiggyBank.php @@ -42,7 +42,9 @@ class UpdatePiggyBank implements ActionInterface /** * TriggerInterface constructor. */ - public function __construct(private readonly RuleAction $action) {} + public function __construct( + private readonly RuleAction $action + ) {} public function actOnArray(array $journal): bool { @@ -52,12 +54,12 @@ class UpdatePiggyBank implements ActionInterface // refresh the transaction type. /** @var User $user */ - $user = User::find($journal['user_id']); + $user = User::find($journal['user_id']); /** @var TransactionJournal $journalObj */ - $journalObj = $user->transactionJournals()->find($journal['transaction_journal_id']); + $journalObj = $user->transactionJournals()->find($journal['transaction_journal_id']); - $piggyBank = $this->findPiggyBank($user, $actionValue); + $piggyBank = $this->findPiggyBank($user, $actionValue); if (!$piggyBank instanceof PiggyBank) { Log::info(sprintf('No piggy bank named "%s", cant execute action #%d of rule #%d', $actionValue, $this->action->id, $this->action->rule_id)); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_find_piggy', ['name' => $actionValue]))); @@ -69,18 +71,22 @@ class UpdatePiggyBank implements ActionInterface // piggy bank already has an event for this transaction journal? if ($this->alreadyEventPresent($piggyBank, $journal)) { - Log::info(sprintf('Piggy bank #%d ("%s") already has an event for transaction journal #%d, so no action will be taken.', $piggyBank->id, $piggyBank->name, $journalObj->id)); + Log::info(sprintf( + 'Piggy bank #%d ("%s") already has an event for transaction journal #%d, so no action will be taken.', + $piggyBank->id, + $piggyBank->name, + $journalObj->id + )); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.cannot_find_piggy', ['name' => $actionValue]))); return false; } - /** @var Transaction $destination */ $destination = $journalObj->transactions()->where('amount', '>', 0)->first(); - $accounts = $this->getAccounts($journalObj); + $accounts = $this->getAccounts($journalObj); Log::debug(sprintf('Source account is #%d: "%s"', $accounts['source']->id, $accounts['source']->name)); Log::debug(sprintf('Destination account is #%d: "%s"', $accounts['destination']->id, $accounts['source']->name)); @@ -88,20 +94,12 @@ class UpdatePiggyBank implements ActionInterface if ($this->isConnected($piggyBank, $accounts['source']) && !$this->isConnected($piggyBank, $accounts['destination'])) { Log::debug('Piggy bank account is linked to source, so remove amount from piggy bank.'); $this->removeAmount($piggyBank, $journal, $journalObj, $accounts['source'], $destination->amount); - event( - new TriggeredAuditLog( - $this->action->rule, - $journalObj, - 'remove_from_piggy', - null, - [ - 'currency_symbol' => $journalObj->transactionCurrency->symbol, - 'decimal_places' => $journalObj->transactionCurrency->decimal_places, - 'amount' => $destination->amount, - 'piggy' => $piggyBank->name, - ] - ) - ); + event(new TriggeredAuditLog($this->action->rule, $journalObj, 'remove_from_piggy', null, [ + 'currency_symbol' => $journalObj->transactionCurrency->symbol, + 'decimal_places' => $journalObj->transactionCurrency->decimal_places, + 'amount' => $destination->amount, + 'piggy' => $piggyBank->name + ])); return true; } @@ -111,37 +109,37 @@ class UpdatePiggyBank implements ActionInterface Log::debug('Piggy bank account is linked to source, so add amount to piggy bank.'); $this->addAmount($piggyBank, $journal, $journalObj, $accounts['destination'], $destination->amount); - event( - new TriggeredAuditLog( - $this->action->rule, - $journalObj, - 'add_to_piggy', - null, - [ - 'currency_symbol' => $journalObj->transactionCurrency->symbol, - 'decimal_places' => $journalObj->transactionCurrency->decimal_places, - 'amount' => $destination->amount, - 'piggy' => $piggyBank->name, - 'piggy_id' => $piggyBank->id, - ] - ) - ); + event(new TriggeredAuditLog($this->action->rule, $journalObj, 'add_to_piggy', null, [ + 'currency_symbol' => $journalObj->transactionCurrency->symbol, + 'decimal_places' => $journalObj->transactionCurrency->decimal_places, + 'amount' => $destination->amount, + 'piggy' => $piggyBank->name, + 'piggy_id' => $piggyBank->id + ])); return true; } if ($this->isConnected($piggyBank, $accounts['source']) && $this->isConnected($piggyBank, $accounts['destination'])) { - Log::info(sprintf('Piggy bank is linked to BOTH source ("#%d") and destination ("#%d"), so no action will be taken.', $accounts['source']->id, $accounts['destination']->id)); + Log::info(sprintf( + 'Piggy bank is linked to BOTH source ("#%d") and destination ("#%d"), so no action will be taken.', + $accounts['source']->id, + $accounts['destination']->id + )); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.no_link_piggy', ['name' => $actionValue]))); return false; } - Log::info(sprintf('Piggy bank is not linked to source ("#%d") or destination ("#%d"), so no action will be taken.', $accounts['source']->id, $accounts['destination']->id)); + Log::info(sprintf( + 'Piggy bank is not linked to source ("#%d") or destination ("#%d"), so no action will be taken.', + $accounts['source']->id, + $accounts['destination']->id + )); event(new RuleActionFailedOnArray($this->action, $journal, trans('rules.no_link_piggy', ['name' => $actionValue]))); return false; } - private function findPiggyBank(User $user, string $name): ?PiggyBank + private function findPiggyBank(User $user, string $name): null|PiggyBank { /** @var PiggyBankRepositoryInterface $repository */ $repository = app(PiggyBankRepositoryInterface::class); @@ -154,11 +152,11 @@ class UpdatePiggyBank implements ActionInterface { return [ 'source' => $journal->transactions()->where('amount', '<', '0')->first()?->account, - 'destination' => $journal->transactions()->where('amount', '>', '0')->first()?->account, + 'destination' => $journal->transactions()->where('amount', '>', '0')->first()?->account ]; } - private function isConnected(PiggyBank $piggyBank, ?Account $link): bool + private function isConnected(PiggyBank $piggyBank, null|Account $link): bool { if (!$link instanceof Account) { return false; @@ -181,11 +179,11 @@ class UpdatePiggyBank implements ActionInterface $accountRepository->setUser($account->user); // how much can we remove from this piggy bank? - $toRemove = $repository->getCurrentAmount($piggyBank, $account); + $toRemove = $repository->getCurrentAmount($piggyBank, $account); Log::debug(sprintf('Amount is %s, max to remove is %s', $amount, $toRemove)); // if $amount is bigger than $toRemove, shrink it. - $amount = -1 === bccomp($amount, $toRemove) ? $amount : $toRemove; + $amount = -1 === bccomp($amount, $toRemove) ? $amount : $toRemove; Log::debug(sprintf('Amount is now %s', $amount)); // if amount is zero, stop. @@ -199,7 +197,10 @@ class UpdatePiggyBank implements ActionInterface if (false === $repository->canRemoveAmount($piggyBank, $account, $amount)) { Log::warning(sprintf('Cannot remove %s from piggy bank.', $amount)); $currency = $accountRepository->getAccountCurrency($account) ?? Amount::getPrimaryCurrency(); - event(new RuleActionFailedOnArray($this->action, $array, trans('rules.cannot_remove_from_piggy', ['amount' => Amount::formatAnything($amount, $currency, false), 'name' => $piggyBank->name]))); + event(new RuleActionFailedOnArray($this->action, $array, trans('rules.cannot_remove_from_piggy', [ + 'amount' => Amount::formatAnything($amount, $currency, false), + 'name' => $piggyBank->name + ]))); return; } @@ -217,7 +218,7 @@ class UpdatePiggyBank implements ActionInterface // how much can we add to the piggy bank? if (0 !== bccomp($piggyBank->target_amount, '0')) { - $toAdd = bcsub($piggyBank->target_amount, $repository->getCurrentAmount($piggyBank, $account)); + $toAdd = bcsub($piggyBank->target_amount, $repository->getCurrentAmount($piggyBank, $account)); Log::debug(sprintf('Max amount to add to piggy bank is %s, amount is %s', $toAdd, $amount)); // update amount to fit: @@ -239,7 +240,10 @@ class UpdatePiggyBank implements ActionInterface if (false === $repository->canAddAmount($piggyBank, $account, $amount)) { Log::warning(sprintf('Cannot add %s to piggy bank.', $amount)); $currency = $accountRepository->getAccountCurrency($account) ?? Amount::getPrimaryCurrency(); - event(new RuleActionFailedOnArray($this->action, $array, trans('rules.cannot_add_to_piggy', ['amount' => Amount::formatAnything($currency, $amount, false), 'name' => $piggyBank->name]))); + event(new RuleActionFailedOnArray($this->action, $array, trans('rules.cannot_add_to_piggy', [ + 'amount' => Amount::formatAnything($currency, $amount, false), + 'name' => $piggyBank->name + ]))); return; } diff --git a/app/TransactionRules/Engine/SearchRuleEngine.php b/app/TransactionRules/Engine/SearchRuleEngine.php index 80ce408749..a9731cc1ce 100644 --- a/app/TransactionRules/Engine/SearchRuleEngine.php +++ b/app/TransactionRules/Engine/SearchRuleEngine.php @@ -45,16 +45,16 @@ use Illuminate\Support\Facades\Log; class SearchRuleEngine implements RuleEngineInterface { private readonly Collection $groups; - private array $operators = []; + private array $operators = []; // always collect the triggers from the database, unless indicated otherwise. - private bool $refreshTriggers = true; - private array $resultCount = []; + private bool $refreshTriggers = true; + private array $resultCount = []; private readonly Collection $rules; - private User $user; + private User $user; public function __construct() { - $this->rules = new Collection(); + $this->rules = new Collection(); $this->groups = new Collection(); } @@ -69,7 +69,7 @@ class SearchRuleEngine implements RuleEngineInterface Log::debug('SearchRuleEngine::find()'); $collection = new Collection(); foreach ($this->rules as $rule) { - $found = new Collection(); + $found = new Collection(); if (true === $rule->strict) { $found = $this->findStrictRule($rule); } @@ -78,7 +78,7 @@ class SearchRuleEngine implements RuleEngineInterface } $collection = $collection->merge($found); } - $result = $collection->unique(); + $result = $collection->unique(); Log::debug(sprintf('SearchRuleEngine::find() returns %d unique transactions.', $result->count())); return $result; @@ -90,8 +90,8 @@ class SearchRuleEngine implements RuleEngineInterface private function findStrictRule(Rule $rule): Collection { Log::debug(sprintf('Now in findStrictRule(#%d)', $rule->id ?? 0)); - $searchArray = []; - $triggers = []; + $searchArray = []; + $triggers = []; if ($this->refreshTriggers) { $triggers = $rule->ruleTriggers()->orderBy('order', 'ASC')->get(); } @@ -110,7 +110,7 @@ class SearchRuleEngine implements RuleEngineInterface } // if the trigger needs no context, value is different: - $needsContext = (bool) (config(sprintf('search.operators.%s.needs_context', $contextSearch)) ?? true); + $needsContext = (bool) (config(sprintf('search.operators.%s.needs_context', $contextSearch)) ?? true); if (false === $needsContext) { Log::debug(sprintf('SearchRuleEngine:: add a rule trigger (no context): %s:true', $ruleTrigger->trigger_type)); $searchArray[$ruleTrigger->trigger_type][] = 'true'; @@ -126,7 +126,7 @@ class SearchRuleEngine implements RuleEngineInterface Log::debug(sprintf('SearchRuleEngine:: add local added operator: %s:"%s"', $operator['type'], $operator['value'])); $searchArray[$operator['type']][] = sprintf('"%s"', $operator['value']); } - $date = today(config('app.timezone')); + $date = today(config('app.timezone')); if ($this->hasSpecificJournalTrigger($searchArray)) { $date = $this->setDateFromJournalTrigger($searchArray); } @@ -146,7 +146,7 @@ class SearchRuleEngine implements RuleEngineInterface } } - $result = $searchEngine->searchTransactions(); + $result = $searchEngine->searchTransactions(); return $result->getCollection(); } @@ -171,7 +171,7 @@ class SearchRuleEngine implements RuleEngineInterface $dateTrigger = true; } } - $result = $journalTrigger && $dateTrigger; + $result = $journalTrigger && $dateTrigger; Log::debug(sprintf('Result of hasSpecificJournalTrigger is %s.', var_export($result, true))); return $result; @@ -190,7 +190,7 @@ class SearchRuleEngine implements RuleEngineInterface if (0 !== $journalId) { $repository = app(JournalRepositoryInterface::class); $repository->setUser($this->user); - $journal = $repository->find($journalId); + $journal = $repository->find($journalId); if (null !== $journal) { $date = $journal->date; Log::debug(sprintf('Found journal #%d with date %s.', $journal->id, $journal->date->format('Y-m-d'))); @@ -205,7 +205,7 @@ class SearchRuleEngine implements RuleEngineInterface public function setUser(User $user): void { - $this->user = $user; + $this->user = $user; $this->operators = []; } @@ -228,7 +228,13 @@ class SearchRuleEngine implements RuleEngineInterface /** @var RuleTrigger $ruleTrigger */ foreach ($triggers as $ruleTrigger) { - Log::debug(sprintf('Now at rule trigger #%d: %s:"%s" (%s).', $ruleTrigger->id, $ruleTrigger->trigger_type, $ruleTrigger->trigger_value, var_export($ruleTrigger->stop_processing, true))); + Log::debug(sprintf( + 'Now at rule trigger #%d: %s:"%s" (%s).', + $ruleTrigger->id, + $ruleTrigger->trigger_type, + $ruleTrigger->trigger_value, + var_export($ruleTrigger->stop_processing, true) + )); if (false === $ruleTrigger->active) { Log::debug('Trigger is not active, continue.'); @@ -266,10 +272,10 @@ class SearchRuleEngine implements RuleEngineInterface $searchEngine->parseQuery(sprintf('%s:%s', $type, $value)); } - $result = $searchEngine->searchTransactions(); - $collection = $result->getCollection(); + $result = $searchEngine->searchTransactions(); + $collection = $result->getCollection(); Log::debug(sprintf('Found in this run, %d transactions', $collection->count())); - $total = $total->merge($collection); + $total = $total->merge($collection); Log::debug(sprintf('Total collection is now %d transactions', $total->count())); ++$count; // if trigger says stop processing, do so. @@ -283,17 +289,16 @@ class SearchRuleEngine implements RuleEngineInterface Log::debug(sprintf('Done running %d trigger(s)', $count)); // make collection unique - $unique = $total->unique( - static function (array $group): string { - $str = ''; - foreach ($group['transactions'] as $transaction) { - $str = sprintf('%s%d', $str, $transaction['transaction_journal_id']); - } - - return sprintf('%d%s', $group['id'], $str); - // Log::debug(sprintf('Return key: %s ', $key)); + $unique = $total->unique(static function (array $group): string { + $str = ''; + foreach ($group['transactions'] as $transaction) { + $str = sprintf('%s%d', $str, $transaction['transaction_journal_id']); } - ); + + return sprintf('%d%s', $group['id'], $str); + + // Log::debug(sprintf('Return key: %s ', $key)); + }); Log::debug(sprintf('SearchRuleEngine:: Found %d transactions using search engine.', $unique->count())); @@ -316,7 +321,10 @@ class SearchRuleEngine implements RuleEngineInterface foreach ($this->rules as $rule) { // @phpstan-ignore-line $result = $this->fireRule($rule); if ($result && true === $rule->stop_processing) { - Log::debug(sprintf('Rule #%d has triggered and executed, but calls to stop processing. Since not in the context of a group, do not stop.', $rule->id)); + Log::debug(sprintf( + 'Rule #%d has triggered and executed, but calls to stop processing. Since not in the context of a group, do not stop.', + $rule->id + )); } if (false === $result && true === $rule->stop_processing) { Log::debug(sprintf('Rule #%d has triggered and changed nothing, but calls to stop processing. Do not stop.', $rule->id)); @@ -373,7 +381,7 @@ class SearchRuleEngine implements RuleEngineInterface $this->processResults($rule, $collection); - $result = $collection->count() > 0; + $result = $collection->count() > 0; if ($result) { Log::debug(sprintf('SearchRuleEngine:: Done. Rule #%d was triggered (on %d transaction(s)).', $rule->id, $collection->count())); @@ -442,14 +450,12 @@ class SearchRuleEngine implements RuleEngineInterface $journalId = $transaction['transaction_journal_id'] ?? 0; if ($result) { $this->resultCount[$journalId] = array_key_exists($journalId, $this->resultCount) ? $this->resultCount[$journalId]++ : 1; - Log::debug( - sprintf( - 'Action "%s" on journal #%d was executed, so count a result. Updated transaction journal count is now %d.', - $ruleAction->action_type, - $transaction['transaction_journal_id'] ?? 0, - count($this->resultCount), - ) - ); + Log::debug(sprintf( + 'Action "%s" on journal #%d was executed, so count a result. Updated transaction journal count is now %d.', + $ruleAction->action_type, + $transaction['transaction_journal_id'] ?? 0, + count($this->resultCount) + )); } if (false === $result) { Log::debug(sprintf('Action "%s" reports NO changes were made.', $ruleAction->action_type)); @@ -471,7 +477,9 @@ class SearchRuleEngine implements RuleEngineInterface private function addNotes(array $transaction): array { $transaction['notes'] = ''; - $dbNote = Note::where('noteable_id', (int) $transaction['transaction_journal_id'])->where('noteable_type', TransactionJournal::class)->first(['notes.*']); + $dbNote = Note::where('noteable_id', (int) $transaction['transaction_journal_id']) + ->where('noteable_type', TransactionJournal::class) + ->first(['notes.*']); if (null !== $dbNote) { $transaction['notes'] = $dbNote->text; } @@ -508,14 +516,14 @@ class SearchRuleEngine implements RuleEngineInterface } if (!$group->relationLoaded('rules')) { Log::debug('Group rules have NOT been pre-loaded, load them NOW.'); - $rules = $group->rules() + $rules = $group + ->rules() ->orderBy('rules.order', 'ASC') -// ->leftJoin('rule_triggers', 'rules.id', '=', 'rule_triggers.rule_id') -// ->where('rule_triggers.trigger_type', 'user_action') -// ->where('rule_triggers.trigger_value', 'store-journal') + // ->leftJoin('rule_triggers', 'rules.id', '=', 'rule_triggers.rule_id') + // ->where('rule_triggers.trigger_type', 'user_action') + // ->where('rule_triggers.trigger_value', 'store-journal') ->where('rules.active', true) - ->get(['rules.*']) - ; + ->get(['rules.*']); } Log::debug(sprintf('Going to fire group #%d with %d rule(s)', $group->id, $rules->count())); diff --git a/app/TransactionRules/Expressions/ActionExpression.php b/app/TransactionRules/Expressions/ActionExpression.php index 429d4f1495..52ba5242c6 100644 --- a/app/TransactionRules/Expressions/ActionExpression.php +++ b/app/TransactionRules/Expressions/ActionExpression.php @@ -31,69 +31,69 @@ use Symfony\Component\ExpressionLanguage\SyntaxError; class ActionExpression { - private static array $NAMES - = [ - // 'transaction_group_id', - // 'user_id', - // 'user_group_id', - 'created_at', - 'updated_at', - 'transaction_group_title', - 'group_created_at', - 'group_updated_at', - // 'transaction_journal_id', - // 'transaction_type_id', - 'description', - 'date', - // 'order', - 'transaction_type_type', - // 'source_transaction_id', - 'source_account_id', - // 'reconciled', - 'amount', - // 'currency_id', - 'currency_code', - 'currency_name', - 'currency_symbol', - 'currency_decimal_places', - 'foreign_amount', - // 'foreign_currency_id', - 'foreign_currency_code', - 'foreign_currency_name', - 'foreign_currency_symbol', - 'foreign_currency_decimal_places', - 'destination_account_id', - 'source_account_name', - 'source_account_iban', - 'source_account_type', - 'destination_account_name', - 'destination_account_iban', - 'destination_account_type', - 'category_id', - 'category_name', - 'budget_id', - 'budget_name', - 'tags', - // 'attachments', - 'interest_date', - 'payment_date', - 'invoice_date', - 'book_date', - 'due_date', - 'process_date', - // 'destination_transaction_id', - 'notes', - ]; + private static array $NAMES = [ + // 'transaction_group_id', + // 'user_id', + // 'user_group_id', + 'created_at', + 'updated_at', + 'transaction_group_title', + 'group_created_at', + 'group_updated_at', + // 'transaction_journal_id', + // 'transaction_type_id', + 'description', + 'date', + // 'order', + 'transaction_type_type', + // 'source_transaction_id', + 'source_account_id', + // 'reconciled', + 'amount', + // 'currency_id', + 'currency_code', + 'currency_name', + 'currency_symbol', + 'currency_decimal_places', + 'foreign_amount', + // 'foreign_currency_id', + 'foreign_currency_code', + 'foreign_currency_name', + 'foreign_currency_symbol', + 'foreign_currency_decimal_places', + 'destination_account_id', + 'source_account_name', + 'source_account_iban', + 'source_account_type', + 'destination_account_name', + 'destination_account_iban', + 'destination_account_type', + 'category_id', + 'category_name', + 'budget_id', + 'budget_name', + 'tags', + // 'attachments', + 'interest_date', + 'payment_date', + 'invoice_date', + 'book_date', + 'due_date', + 'process_date', + // 'destination_transaction_id', + 'notes' + ]; private readonly ExpressionLanguage $expressionLanguage; - private readonly bool $isExpression; - private readonly ?SyntaxError $validationError; + private readonly bool $isExpression; + private readonly null|SyntaxError $validationError; - public function __construct(private readonly string $expr) - { + public function __construct( + private readonly string $expr + ) { $this->expressionLanguage = app(ExpressionLanguage::class); - $this->isExpression = $this->isExpression($this->expr); - $this->validationError = $this->validate(); + $this->isExpression = $this->isExpression($this->expr); + $this->validationError = $this->validate(); } private function isExpression(string $expr): bool @@ -101,7 +101,7 @@ class ActionExpression return str_starts_with($expr, '=') && strlen($expr) > 1; } - private function validate(): ?SyntaxError + private function validate(): null|SyntaxError { if (!$this->isExpression) { return null; @@ -130,7 +130,7 @@ class ActionExpression $this->expressionLanguage->lint($expr, self::$NAMES); } - public function getValidationError(): ?SyntaxError + public function getValidationError(): null|SyntaxError { return $this->validationError; } diff --git a/app/TransactionRules/Expressions/ActionExpressionLanguageProvider.php b/app/TransactionRules/Expressions/ActionExpressionLanguageProvider.php index 0daaafb332..0974c1faa5 100644 --- a/app/TransactionRules/Expressions/ActionExpressionLanguageProvider.php +++ b/app/TransactionRules/Expressions/ActionExpressionLanguageProvider.php @@ -39,24 +39,16 @@ class ActionExpressionLanguageProvider implements ExpressionFunctionProviderInte return (string) $str; } - return strtolower($str.'!'); + return strtolower($str . '!'); }; return [ - new ExpressionFunction( - 'constant2', - static fn ($str): string => sprintf('(is_string(%1$s) ? strtolower(%1$s) : %1$s)', $str.'!'), - $function - ), - new ExpressionFunction( - 'constant', - static fn ($str): string => sprintf('(is_string(%1$s) ? strtolower(%1$s) : %1$s)', $str.'!'), - $function - ), + new ExpressionFunction('constant2', static fn($str): string => sprintf('(is_string(%1$s) ? strtolower(%1$s) : %1$s)', $str . '!'), $function), + new ExpressionFunction('constant', static fn($str): string => sprintf('(is_string(%1$s) ? strtolower(%1$s) : %1$s)', $str . '!'), $function), ExpressionFunction::fromPhp('substr'), ExpressionFunction::fromPhp('strlen'), - ExpressionFunction::fromPhp('strpos'), + ExpressionFunction::fromPhp('strpos') ]; } } diff --git a/app/TransactionRules/Factory/ActionFactory.php b/app/TransactionRules/Factory/ActionFactory.php index c05dca063a..9a8d21656f 100644 --- a/app/TransactionRules/Factory/ActionFactory.php +++ b/app/TransactionRules/Factory/ActionFactory.php @@ -23,11 +23,11 @@ declare(strict_types=1); namespace FireflyIII\TransactionRules\Factory; -use Illuminate\Support\Facades\Log; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\RuleAction; use FireflyIII\Support\Domain; use FireflyIII\TransactionRules\Actions\ActionInterface; +use Illuminate\Support\Facades\Log; /** * Class ActionFactory can create actions. @@ -65,12 +65,12 @@ class ActionFactory $actionTypes = self::getActionTypes(); if (!array_key_exists($actionType, $actionTypes)) { - throw new FireflyException('No such action exists ("'.e($actionType).'").'); + throw new FireflyException('No such action exists ("' . e($actionType) . '").'); } - $class = $actionTypes[$actionType]; + $class = $actionTypes[$actionType]; if (!class_exists($class)) { - throw new FireflyException('Could not instantiate class for rule action type "'.e($actionType).'" ('.e($class).').'); + throw new FireflyException('Could not instantiate class for rule action type "' . e($actionType) . '" (' . e($class) . ').'); } return $class; diff --git a/app/TransactionRules/Traits/RefreshNotesTrait.php b/app/TransactionRules/Traits/RefreshNotesTrait.php index a9ab866a8c..ca1fe44ca0 100644 --- a/app/TransactionRules/Traits/RefreshNotesTrait.php +++ b/app/TransactionRules/Traits/RefreshNotesTrait.php @@ -33,7 +33,9 @@ trait RefreshNotesTrait final protected function refreshNotes(array $transaction): array { $transaction['notes'] = ''; - $dbNote = Note::where('noteable_id', (int) $transaction['transaction_journal_id'])->where('noteable_type', TransactionJournal::class)->first(['notes.*']); + $dbNote = Note::where('noteable_id', (int) $transaction['transaction_journal_id']) + ->where('noteable_type', TransactionJournal::class) + ->first(['notes.*']); if (null !== $dbNote) { $transaction['notes'] = $dbNote->text; } diff --git a/app/Transformers/AccountTransformer.php b/app/Transformers/AccountTransformer.php index 5538e745e7..2f568098cb 100644 --- a/app/Transformers/AccountTransformer.php +++ b/app/Transformers/AccountTransformer.php @@ -36,8 +36,8 @@ use FireflyIII\Support\Facades\Amount; */ class AccountTransformer extends AbstractTransformer { - protected bool $convertToPrimary; - protected TransactionCurrency $primary; + protected bool $convertToPrimary; + protected TransactionCurrency $primary; protected AccountRepositoryInterface $repository; /** @@ -45,9 +45,9 @@ class AccountTransformer extends AbstractTransformer */ public function __construct() { - $this->repository = app(AccountRepositoryInterface::class); + $this->repository = app(AccountRepositoryInterface::class); $this->convertToPrimary = Amount::convertToPrimary(); - $this->primary = Amount::getPrimaryCurrency(); + $this->primary = Amount::getPrimaryCurrency(); } /** @@ -58,26 +58,24 @@ class AccountTransformer extends AbstractTransformer public function transform(Account $account): array { if (null === $account->meta) { - $account->meta = [ - 'currency' => null, - ]; + $account->meta = ['currency' => null]; } // get account type: - $accountType = (string)config(sprintf('firefly.shortNamesByFullName.%s', $account->full_account_type)); - $liabilityType = (string)config(sprintf('firefly.shortLiabilityNameByFullName.%s', $account->full_account_type)); - $liabilityType = '' === $liabilityType ? null : strtolower($liabilityType); - $liabilityDirection = $account->meta['liability_direction'] ?? null; - $accountRole = $this->getAccountRole($account, $accountType); - $hasCurrencySettings = null !== $account->meta['currency']; - $includeNetWorth = 1 === (int)($account->meta['include_net_worth'] ?? 0); - $longitude = $account->meta['location']['longitude'] ?? null; - $latitude = $account->meta['location']['latitude'] ?? null; - $zoomLevel = $account->meta['location']['zoom_level'] ?? null; - $order = $account->order; + $accountType = (string) config(sprintf('firefly.shortNamesByFullName.%s', $account->full_account_type)); + $liabilityType = (string) config(sprintf('firefly.shortLiabilityNameByFullName.%s', $account->full_account_type)); + $liabilityType = '' === $liabilityType ? null : strtolower($liabilityType); + $liabilityDirection = $account->meta['liability_direction'] ?? null; + $accountRole = $this->getAccountRole($account, $accountType); + $hasCurrencySettings = null !== $account->meta['currency']; + $includeNetWorth = 1 === (int) ($account->meta['include_net_worth'] ?? 0); + $longitude = $account->meta['location']['longitude'] ?? null; + $latitude = $account->meta['location']['latitude'] ?? null; + $zoomLevel = $account->meta['location']['zoom_level'] ?? null; + $order = $account->order; // get primary currency as fallback: - $currency = $this->primary; // assume primary currency + $currency = $this->primary; // assume primary currency if ($hasCurrencySettings) { $currency = $account->meta['currency']; } @@ -89,92 +87,87 @@ class AccountTransformer extends AbstractTransformer // get some listed information from the account meta-data: [$creditCardType, $monthlyPaymentDate] = $this->getCCInfo($account, $accountRole, $accountType); - $openingBalanceDate = $this->getOpeningBalance($account, $accountType); - [$interest, $interestPeriod] = $this->getInterest($account, $accountType); + $openingBalanceDate = $this->getOpeningBalance($account, $accountType); + [$interest, $interestPeriod] = $this->getInterest($account, $accountType); return [ - 'id' => (string)$account->id, - 'created_at' => $account->created_at->toAtomString(), - 'updated_at' => $account->updated_at->toAtomString(), - 'active' => $account->active, - 'order' => $order, - 'name' => $account->name, - 'type' => strtolower($accountType), - 'account_role' => $accountRole, + 'id' => (string) $account->id, + 'created_at' => $account->created_at->toAtomString(), + 'updated_at' => $account->updated_at->toAtomString(), + 'active' => $account->active, + 'order' => $order, + 'name' => $account->name, + 'type' => strtolower($accountType), + 'account_role' => $accountRole, - 'object_group_id' => $account->meta['object_group_id'], - 'object_group_order' => $account->meta['object_group_order'], - 'object_group_title' => $account->meta['object_group_title'], + 'object_group_id' => $account->meta['object_group_id'], + 'object_group_order' => $account->meta['object_group_order'], + 'object_group_title' => $account->meta['object_group_title'], // currency information, structured for 6.3.0. - 'object_has_currency_setting' => $hasCurrencySettings, + 'object_has_currency_setting' => $hasCurrencySettings, // currency is object specific or primary, already determined above. - 'currency_id' => (string)$currency['id'], - 'currency_name' => $currency['name'], - 'currency_code' => $currency['code'], - 'currency_symbol' => $currency['symbol'], - 'currency_decimal_places' => $currency['decimal_places'], + 'currency_id' => (string) $currency['id'], + 'currency_name' => $currency['name'], + 'currency_code' => $currency['code'], + 'currency_symbol' => $currency['symbol'], + 'currency_decimal_places' => $currency['decimal_places'], - 'primary_currency_id' => (string)$this->primary->id, + 'primary_currency_id' => (string) $this->primary->id, 'primary_currency_name' => $this->primary->name, 'primary_currency_code' => $this->primary->code, 'primary_currency_symbol' => $this->primary->symbol, 'primary_currency_decimal_places' => $this->primary->decimal_places, // balances, structured for 6.3.0. - 'current_balance' => $account->meta['balances']['current_balance'], - 'pc_current_balance' => $account->meta['balances']['pc_current_balance'], + 'current_balance' => $account->meta['balances']['current_balance'], + 'pc_current_balance' => $account->meta['balances']['pc_current_balance'], - 'opening_balance' => $account->meta['balances']['opening_balance'], - 'pc_opening_balance' => $account->meta['balances']['pc_opening_balance'], + 'opening_balance' => $account->meta['balances']['opening_balance'], + 'pc_opening_balance' => $account->meta['balances']['pc_opening_balance'], - 'virtual_balance' => $account->meta['balances']['virtual_balance'], - 'pc_virtual_balance' => $account->meta['balances']['pc_virtual_balance'], + 'virtual_balance' => $account->meta['balances']['virtual_balance'], + 'pc_virtual_balance' => $account->meta['balances']['pc_virtual_balance'], - 'debt_amount' => $account->meta['balances']['debt_amount'], - 'pc_debt_amount' => $account->meta['balances']['pc_debt_amount'], + 'debt_amount' => $account->meta['balances']['debt_amount'], + 'pc_debt_amount' => $account->meta['balances']['pc_debt_amount'], - 'balance_difference' => $account->meta['balances']['balance_difference'], - 'pc_balance_difference' => $account->meta['balances']['pc_balance_difference'], + 'balance_difference' => $account->meta['balances']['balance_difference'], + 'pc_balance_difference' => $account->meta['balances']['pc_balance_difference'], - 'current_balance_date' => $account->meta['current_balance_date']->toAtomString(), - 'notes' => $account->meta['notes'] ?? null, - 'monthly_payment_date' => $monthlyPaymentDate, - 'credit_card_type' => $creditCardType, - 'account_number' => $account->meta['account_number'], - 'iban' => '' === $account->iban ? null : $account->iban, - 'bic' => $account->meta['BIC'] ?? null, - 'opening_balance_date' => $openingBalanceDate, - 'liability_type' => $liabilityType, - 'liability_direction' => $liabilityDirection, - 'interest' => $interest, - 'interest_period' => $interestPeriod, - 'include_net_worth' => $includeNetWorth, - 'longitude' => $longitude, - 'latitude' => $latitude, - 'zoom_level' => $zoomLevel, - 'last_activity' => $account->meta['last_activity']?->toAtomString(), - 'links' => [ - [ - 'rel' => 'self', - 'uri' => sprintf('/accounts/%d', $account->id), - ], - ], + 'current_balance_date' => $account->meta['current_balance_date']->toAtomString(), + 'notes' => $account->meta['notes'] ?? null, + 'monthly_payment_date' => $monthlyPaymentDate, + 'credit_card_type' => $creditCardType, + 'account_number' => $account->meta['account_number'], + 'iban' => '' === $account->iban ? null : $account->iban, + 'bic' => $account->meta['BIC'] ?? null, + 'opening_balance_date' => $openingBalanceDate, + 'liability_type' => $liabilityType, + 'liability_direction' => $liabilityDirection, + 'interest' => $interest, + 'interest_period' => $interestPeriod, + 'include_net_worth' => $includeNetWorth, + 'longitude' => $longitude, + 'latitude' => $latitude, + 'zoom_level' => $zoomLevel, + 'last_activity' => $account->meta['last_activity']?->toAtomString(), + 'links' => [['rel' => 'self', 'uri' => sprintf('/accounts/%d', $account->id)]] ]; } - private function getAccountRole(Account $account, string $accountType): ?string + private function getAccountRole(Account $account, string $accountType): null|string { $accountRole = $account->meta['account_role'] ?? null; - if ('asset' !== $accountType || '' === (string)$accountRole) { + if ('asset' !== $accountType || '' === (string) $accountRole) { return null; } return $accountRole; } - private function getCCInfo(Account $account, ?string $accountRole, string $accountType): array + private function getCCInfo(Account $account, null|string $accountRole, string $accountType): array { $monthlyPaymentDate = null; $creditCardType = null; @@ -185,13 +178,13 @@ class AccountTransformer extends AbstractTransformer if (null !== $monthlyPaymentDate) { // try classic date: if (10 === strlen($monthlyPaymentDate)) { - $object = Carbon::createFromFormat('!Y-m-d', $monthlyPaymentDate, config('app.timezone')); + $object = Carbon::createFromFormat('!Y-m-d', $monthlyPaymentDate, config('app.timezone')); if (!$object instanceof Carbon) { $object = today(config('app.timezone')); } $monthlyPaymentDate = $object->toAtomString(); } - if (10 !== strlen((string)$monthlyPaymentDate)) { + if (10 !== strlen((string) $monthlyPaymentDate)) { $monthlyPaymentDate = Carbon::parse($monthlyPaymentDate, config('app.timezone'))->toAtomString(); } } @@ -199,19 +192,18 @@ class AccountTransformer extends AbstractTransformer return [$creditCardType, $monthlyPaymentDate]; } - private function getOpeningBalance(Account $account, string $accountType): ?string + private function getOpeningBalance(Account $account, string $accountType): null|string { $openingBalanceDate = null; if (in_array($accountType, ['asset', 'liabilities'], true)) { $openingBalanceDate = $account->meta['opening_balance_date'] ?? null; } if (null !== $openingBalanceDate) { - $object = Carbon::createFromFormat('Y-m-d H:i:s', $openingBalanceDate, config('app.timezone')); + $object = Carbon::createFromFormat('Y-m-d H:i:s', $openingBalanceDate, config('app.timezone')); if (!$object instanceof Carbon) { $object = today(config('app.timezone')); } $openingBalanceDate = $object->toAtomString(); - } return $openingBalanceDate; diff --git a/app/Transformers/AttachmentTransformer.php b/app/Transformers/AttachmentTransformer.php index 5611a00d96..05c7292035 100644 --- a/app/Transformers/AttachmentTransformer.php +++ b/app/Transformers/AttachmentTransformer.php @@ -63,12 +63,7 @@ class AttachmentTransformer extends AbstractTransformer 'notes' => $this->repository->getNoteText($attachment), 'mime' => $attachment->mime, 'size' => (int) $attachment->size, - 'links' => [ - [ - 'rel' => 'self', - 'uri' => '/attachment/'.$attachment->id, - ], - ], + 'links' => [['rel' => 'self', 'uri' => '/attachment/' . $attachment->id]] ]; } } diff --git a/app/Transformers/AvailableBudgetTransformer.php b/app/Transformers/AvailableBudgetTransformer.php index a019bb9985..5f7ce0d594 100644 --- a/app/Transformers/AvailableBudgetTransformer.php +++ b/app/Transformers/AvailableBudgetTransformer.php @@ -34,7 +34,7 @@ use FireflyIII\Support\Facades\Steam; */ class AvailableBudgetTransformer extends AbstractTransformer { - private readonly bool $convertToPrimary; + private readonly bool $convertToPrimary; private readonly TransactionCurrency $primary; /** @@ -42,7 +42,7 @@ class AvailableBudgetTransformer extends AbstractTransformer */ public function __construct() { - $this->primary = Amount::getPrimaryCurrency(); + $this->primary = Amount::getPrimaryCurrency(); $this->convertToPrimary = Amount::convertToPrimary(); } @@ -60,17 +60,17 @@ class AvailableBudgetTransformer extends AbstractTransformer } return [ - 'id' => (string) $availableBudget->id, - 'created_at' => $availableBudget->created_at->toAtomString(), - 'updated_at' => $availableBudget->updated_at->toAtomString(), + 'id' => (string) $availableBudget->id, + 'created_at' => $availableBudget->created_at->toAtomString(), + 'updated_at' => $availableBudget->updated_at->toAtomString(), // currencies according to 6.3.0 - 'object_has_currency_setting' => true, - 'currency_id' => (string) $currency->id, - 'currency_name' => $currency->name, - 'currency_code' => $currency->code, - 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => $currency->decimal_places, + 'object_has_currency_setting' => true, + 'currency_id' => (string) $currency->id, + 'currency_name' => $currency->name, + 'currency_code' => $currency->code, + 'currency_symbol' => $currency->symbol, + 'currency_decimal_places' => $currency->decimal_places, 'primary_currency_id' => (string) $this->primary->id, 'primary_currency_name' => $this->primary->name, @@ -78,20 +78,15 @@ class AvailableBudgetTransformer extends AbstractTransformer 'primary_currency_symbol' => $this->primary->symbol, 'primary_currency_decimal_places' => $this->primary->decimal_places, - 'amount' => $amount, - 'pc_amount' => $pcAmount, - 'start' => $availableBudget->start_date->toAtomString(), - 'end' => $availableBudget->end_date->endOfDay()->toAtomString(), - 'spent_in_budgets' => $availableBudget->meta['spent_in_budgets'], - 'pc_spent_in_budgets' => $availableBudget->meta['pc_spent_in_budgets'], - 'spent_outside_budgets' => $availableBudget->meta['spent_outside_budgets'], - 'pc_spent_outside_budgets' => $availableBudget->meta['pc_spent_outside_budgets'], - 'links' => [ - [ - 'rel' => 'self', - 'uri' => '/available_budgets/'.$availableBudget->id, - ], - ], + 'amount' => $amount, + 'pc_amount' => $pcAmount, + 'start' => $availableBudget->start_date->toAtomString(), + 'end' => $availableBudget->end_date->endOfDay()->toAtomString(), + 'spent_in_budgets' => $availableBudget->meta['spent_in_budgets'], + 'pc_spent_in_budgets' => $availableBudget->meta['pc_spent_in_budgets'], + 'spent_outside_budgets' => $availableBudget->meta['spent_outside_budgets'], + 'pc_spent_outside_budgets' => $availableBudget->meta['pc_spent_outside_budgets'], + 'links' => [['rel' => 'self', 'uri' => '/available_budgets/' . $availableBudget->id]] ]; } } diff --git a/app/Transformers/BillTransformer.php b/app/Transformers/BillTransformer.php index 96d4732307..a7fc401cf8 100644 --- a/app/Transformers/BillTransformer.php +++ b/app/Transformers/BillTransformer.php @@ -50,20 +50,19 @@ class BillTransformer extends AbstractTransformer { $currency = $bill->transactionCurrency; - return [ - 'id' => $bill->id, - 'created_at' => $bill->created_at->toAtomString(), - 'updated_at' => $bill->updated_at->toAtomString(), - 'name' => $bill->name, + 'id' => $bill->id, + 'created_at' => $bill->created_at->toAtomString(), + 'updated_at' => $bill->updated_at->toAtomString(), + 'name' => $bill->name, // currencies according to 6.3.0 - 'object_has_currency_setting' => true, - 'currency_id' => (string) $bill->transaction_currency_id, - 'currency_name' => $currency->name, - 'currency_code' => $currency->code, - 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => $currency->decimal_places, + 'object_has_currency_setting' => true, + 'currency_id' => (string) $bill->transaction_currency_id, + 'currency_name' => $currency->name, + 'currency_code' => $currency->code, + 'currency_symbol' => $currency->symbol, + 'currency_decimal_places' => $currency->decimal_places, 'primary_currency_id' => (string) $this->primary->id, 'primary_currency_name' => $this->primary->name, @@ -72,38 +71,33 @@ class BillTransformer extends AbstractTransformer 'primary_currency_decimal_places' => $this->primary->decimal_places, // amounts according to 6.3.0 - 'amount_min' => $bill->amounts['amount_min'], - 'pc_amount_min' => $bill->amounts['pc_amount_min'], + 'amount_min' => $bill->amounts['amount_min'], + 'pc_amount_min' => $bill->amounts['pc_amount_min'], - 'amount_max' => $bill->amounts['amount_max'], - 'pc_amount_max' => $bill->amounts['pc_amount_max'], + 'amount_max' => $bill->amounts['amount_max'], + 'pc_amount_max' => $bill->amounts['pc_amount_max'], - 'amount_avg' => $bill->amounts['average'], - 'pc_amount_avg' => $bill->amounts['pc_average'], + 'amount_avg' => $bill->amounts['average'], + 'pc_amount_avg' => $bill->amounts['pc_average'], - 'date' => $bill->date->toAtomString(), - 'end_date' => $bill->end_date?->toAtomString(), - 'extension_date' => $bill->extension_date?->toAtomString(), - 'repeat_freq' => $bill->repeat_freq, - 'skip' => $bill->skip, - 'active' => $bill->active, - 'order' => $bill->order, - 'notes' => $bill->meta['notes'], - 'object_group_id' => $bill->meta['object_group_id'], - 'object_group_order' => $bill->meta['object_group_order'], - 'object_group_title' => $bill->meta['object_group_title'], + 'date' => $bill->date->toAtomString(), + 'end_date' => $bill->end_date?->toAtomString(), + 'extension_date' => $bill->extension_date?->toAtomString(), + 'repeat_freq' => $bill->repeat_freq, + 'skip' => $bill->skip, + 'active' => $bill->active, + 'order' => $bill->order, + 'notes' => $bill->meta['notes'], + 'object_group_id' => $bill->meta['object_group_id'], + 'object_group_order' => $bill->meta['object_group_order'], + 'object_group_title' => $bill->meta['object_group_title'], - 'paid_dates' => $bill->meta['paid_dates'], - 'pay_dates' => $bill->meta['pay_dates'], - 'next_expected_match' => $bill->meta['nem']?->toAtomString(), - 'next_expected_match_diff' => $bill->meta['nem_diff'], + 'paid_dates' => $bill->meta['paid_dates'], + 'pay_dates' => $bill->meta['pay_dates'], + 'next_expected_match' => $bill->meta['nem']?->toAtomString(), + 'next_expected_match_diff' => $bill->meta['nem_diff'], - 'links' => [ - [ - 'rel' => 'self', - 'uri' => '/bills/'.$bill->id, - ], - ], + 'links' => [['rel' => 'self', 'uri' => '/bills/' . $bill->id]] ]; } } diff --git a/app/Transformers/BudgetLimitTransformer.php b/app/Transformers/BudgetLimitTransformer.php index edd1287ee3..bc642c5a6c 100644 --- a/app/Transformers/BudgetLimitTransformer.php +++ b/app/Transformers/BudgetLimitTransformer.php @@ -36,16 +36,13 @@ use League\Fractal\Resource\Item; */ class BudgetLimitTransformer extends AbstractTransformer { - protected array $availableIncludes - = [ - 'budget', - ]; - protected bool $convertToPrimary; + protected array $availableIncludes = ['budget']; + protected bool $convertToPrimary; protected TransactionCurrency $primaryCurrency; public function __construct() { - $this->primaryCurrency = Amount::getPrimaryCurrency(); + $this->primaryCurrency = Amount::getPrimaryCurrency(); $this->convertToPrimary = Amount::convertToPrimary(); } @@ -60,7 +57,7 @@ class BudgetLimitTransformer extends AbstractTransformer $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); $enrichment->setUser($budget->user); - $budget = $enrichment->enrichSingle($budget); + $budget = $enrichment->enrichSingle($budget); return $this->item($budget, new BudgetTransformer(), 'budgets'); } @@ -70,7 +67,6 @@ class BudgetLimitTransformer extends AbstractTransformer */ public function transform(BudgetLimit $budgetLimit): array { - $currency = $budgetLimit->meta['currency']; $amount = Steam::bcround($budgetLimit->amount, $currency->decimal_places); $pcAmount = null; @@ -82,21 +78,21 @@ class BudgetLimitTransformer extends AbstractTransformer } return [ - 'id' => (string)$budgetLimit->id, - 'created_at' => $budgetLimit->created_at->toAtomString(), - 'updated_at' => $budgetLimit->updated_at->toAtomString(), - 'start' => $budgetLimit->start_date->toAtomString(), - 'end' => $budgetLimit->end_date->endOfDay()->toAtomString(), - 'budget_id' => (string)$budgetLimit->budget_id, + 'id' => (string) $budgetLimit->id, + 'created_at' => $budgetLimit->created_at->toAtomString(), + 'updated_at' => $budgetLimit->updated_at->toAtomString(), + 'start' => $budgetLimit->start_date->toAtomString(), + 'end' => $budgetLimit->end_date->endOfDay()->toAtomString(), + 'budget_id' => (string) $budgetLimit->budget_id, // currency settings according to 6.3.0 - 'object_has_currency_setting' => true, + 'object_has_currency_setting' => true, - 'currency_id' => (string)$currency->id, - 'currency_name' => $currency->name, - 'currency_code' => $currency->code, - 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => $currency->decimal_places, + 'currency_id' => (string) $currency->id, + 'currency_name' => $currency->name, + 'currency_code' => $currency->code, + 'currency_symbol' => $currency->symbol, + 'currency_decimal_places' => $currency->decimal_places, 'primary_currency_id' => (string) $this->primaryCurrency->id, 'primary_currency_name' => $this->primaryCurrency->name, @@ -104,18 +100,13 @@ class BudgetLimitTransformer extends AbstractTransformer 'primary_currency_symbol' => $this->primaryCurrency->symbol, 'primary_currency_decimal_places' => $this->primaryCurrency->decimal_places, - 'amount' => $amount, - 'pc_amount' => $pcAmount, - 'period' => $budgetLimit->period, - 'spent' => $budgetLimit->meta['spent'], - 'pc_spent' => $budgetLimit->meta['pc_spent'], - 'notes' => $budgetLimit->meta['notes'], - 'links' => [ - [ - 'rel' => 'self', - 'uri' => '/budgets/limits/'.$budgetLimit->id, - ], - ], + 'amount' => $amount, + 'pc_amount' => $pcAmount, + 'period' => $budgetLimit->period, + 'spent' => $budgetLimit->meta['spent'], + 'pc_spent' => $budgetLimit->meta['pc_spent'], + 'notes' => $budgetLimit->meta['notes'], + 'links' => [['rel' => 'self', 'uri' => '/budgets/limits/' . $budgetLimit->id]] ]; } } diff --git a/app/Transformers/BudgetTransformer.php b/app/Transformers/BudgetTransformer.php index 41bfbd1394..9b97f6802c 100644 --- a/app/Transformers/BudgetTransformer.php +++ b/app/Transformers/BudgetTransformer.php @@ -36,22 +36,22 @@ use Symfony\Component\HttpFoundation\ParameterBag; */ class BudgetTransformer extends AbstractTransformer { - private readonly bool $convertToPrimary; + private readonly bool $convertToPrimary; private readonly TransactionCurrency $primaryCurrency; - private array $types; + private array $types; /** * BudgetTransformer constructor. */ public function __construct() { - $this->parameters = new ParameterBag(); - $this->primaryCurrency = Amount::getPrimaryCurrency(); + $this->parameters = new ParameterBag(); + $this->primaryCurrency = Amount::getPrimaryCurrency(); $this->convertToPrimary = Amount::convertToPrimary(); - $this->types = [ + $this->types = [ AutoBudgetType::AUTO_BUDGET_RESET->value => 'reset', AutoBudgetType::AUTO_BUDGET_ROLLOVER->value => 'rollover', - AutoBudgetType::AUTO_BUDGET_ADJUSTED->value => 'adjusted', + AutoBudgetType::AUTO_BUDGET_ADJUSTED->value => 'adjusted' ]; } @@ -60,14 +60,13 @@ class BudgetTransformer extends AbstractTransformer */ public function transform(Budget $budget): array { - // info for auto budget. $abType = null; $abAmount = null; $abPrimary = null; $abPeriod = null; - $currency = $budget->meta['currency'] ?? null; + $currency = $budget->meta['currency'] ?? null; if (null !== $budget->meta['auto_budget']) { $abType = $this->types[$budget->meta['auto_budget']['type']]; @@ -77,43 +76,38 @@ class BudgetTransformer extends AbstractTransformer } return [ - 'id' => (string)$budget->id, - 'created_at' => $budget->created_at->toAtomString(), - 'updated_at' => $budget->updated_at->toAtomString(), - 'active' => $budget->active, - 'name' => $budget->name, - 'order' => $budget->order, - 'notes' => $budget->meta['notes'], - 'auto_budget_type' => $abType, - 'auto_budget_period' => $abPeriod, - 'object_group_id' => $budget->meta['object_group_id'], - 'object_group_order' => $budget->meta['object_group_order'], - 'object_group_title' => $budget->meta['object_group_title'], + 'id' => (string) $budget->id, + 'created_at' => $budget->created_at->toAtomString(), + 'updated_at' => $budget->updated_at->toAtomString(), + 'active' => $budget->active, + 'name' => $budget->name, + 'order' => $budget->order, + 'notes' => $budget->meta['notes'], + 'auto_budget_type' => $abType, + 'auto_budget_period' => $abPeriod, + 'object_group_id' => $budget->meta['object_group_id'], + 'object_group_order' => $budget->meta['object_group_order'], + 'object_group_title' => $budget->meta['object_group_title'], // new currency settings. - 'object_has_currency_setting' => null !== $budget->meta['currency'], - 'currency_id' => null === $currency ? null : (string)$currency->id, - 'currency_code' => $currency?->code, - 'currency_name' => $currency?->name, - 'currency_symbol' => $currency?->symbol, - 'currency_decimal_places' => $currency?->decimal_places, + 'object_has_currency_setting' => null !== $budget->meta['currency'], + 'currency_id' => null === $currency ? null : (string) $currency->id, + 'currency_code' => $currency?->code, + 'currency_name' => $currency?->name, + 'currency_symbol' => $currency?->symbol, + 'currency_decimal_places' => $currency?->decimal_places, - 'primary_currency_id' => (string)$this->primaryCurrency->id, + 'primary_currency_id' => (string) $this->primaryCurrency->id, 'primary_currency_name' => $this->primaryCurrency->name, 'primary_currency_code' => $this->primaryCurrency->code, 'primary_currency_symbol' => $this->primaryCurrency->symbol, 'primary_currency_decimal_places' => $this->primaryCurrency->decimal_places, - 'auto_budget_amount' => $abAmount, - 'pc_auto_budget_amount' => $abPrimary, - 'spent' => null === $budget->meta['spent'] ? null : $this->beautify($budget->meta['spent']), - 'pc_spent' => null === $budget->meta['pc_spent'] ? null : $this->beautify($budget->meta['pc_spent']), - 'links' => [ - [ - 'rel' => 'self', - 'uri' => '/budgets/'.$budget->id, - ], - ], + 'auto_budget_amount' => $abAmount, + 'pc_auto_budget_amount' => $abPrimary, + 'spent' => null === $budget->meta['spent'] ? null : $this->beautify($budget->meta['spent']), + 'pc_spent' => null === $budget->meta['pc_spent'] ? null : $this->beautify($budget->meta['pc_spent']), + 'links' => [['rel' => 'self', 'uri' => '/budgets/' . $budget->id]] ]; } @@ -121,8 +115,8 @@ class BudgetTransformer extends AbstractTransformer { $return = []; foreach ($array as $data) { - $data['sum'] = Steam::bcround($data['sum'], (int)$data['currency_decimal_places']); - $return[] = $data; + $data['sum'] = Steam::bcround($data['sum'], (int) $data['currency_decimal_places']); + $return[] = $data; } return $return; diff --git a/app/Transformers/CategoryTransformer.php b/app/Transformers/CategoryTransformer.php index 36d25b2921..1bb2a013ec 100644 --- a/app/Transformers/CategoryTransformer.php +++ b/app/Transformers/CategoryTransformer.php @@ -49,45 +49,39 @@ class CategoryTransformer extends AbstractTransformer */ public function transform(Category $category): array { - return [ - 'id' => $category->id, - 'created_at' => $category->created_at->toAtomString(), - 'updated_at' => $category->updated_at->toAtomString(), - 'name' => $category->name, - 'notes' => $category->meta['notes'], + 'id' => $category->id, + 'created_at' => $category->created_at->toAtomString(), + 'updated_at' => $category->updated_at->toAtomString(), + 'name' => $category->name, + 'notes' => $category->meta['notes'], // category never has currency settings. 'object_has_currency_setting' => false, - 'primary_currency_id' => (string)$this->primaryCurrency->id, + 'primary_currency_id' => (string) $this->primaryCurrency->id, 'primary_currency_name' => $this->primaryCurrency->name, 'primary_currency_code' => $this->primaryCurrency->code, 'primary_currency_symbol' => $this->primaryCurrency->symbol, - 'primary_currency_decimal_places' => (int)$this->primaryCurrency->decimal_places, + 'primary_currency_decimal_places' => (int) $this->primaryCurrency->decimal_places, 'spent' => $this->beautify($category->meta['spent']), 'pc_spent' => $this->beautify($category->meta['pc_spent']), 'earned' => $this->beautify($category->meta['earned']), 'pc_earned' => $this->beautify($category->meta['pc_earned']), 'transferred' => $this->beautify($category->meta['transfers']), 'pc_transferred' => $this->beautify($category->meta['pc_transfers']), - 'links' => [ - [ - 'rel' => 'self', - 'uri' => '/categories/'.$category->id, - ], - ], + 'links' => [['rel' => 'self', 'uri' => '/categories/' . $category->id]] ]; } - private function beautify(?array $array): ?array + private function beautify(null|array $array): null|array { if (null === $array) { return null; } $return = []; foreach ($array as $data) { - $data['sum'] = Steam::bcround($data['sum'], (int)$data['currency_decimal_places']); - $return[] = $data; + $data['sum'] = Steam::bcround($data['sum'], (int) $data['currency_decimal_places']); + $return[] = $data; } return $return; diff --git a/app/Transformers/CurrencyTransformer.php b/app/Transformers/CurrencyTransformer.php index 649bbe6fb9..17bc259da3 100644 --- a/app/Transformers/CurrencyTransformer.php +++ b/app/Transformers/CurrencyTransformer.php @@ -48,12 +48,7 @@ class CurrencyTransformer extends AbstractTransformer 'code' => $currency->code, 'symbol' => $currency->symbol, 'decimal_places' => $currency->decimal_places, - 'links' => [ - [ - 'rel' => 'self', - 'uri' => '/currencies/'.$currency->id, - ], - ], + 'links' => [['rel' => 'self', 'uri' => '/currencies/' . $currency->id]] ]; } } diff --git a/app/Transformers/ExchangeRateTransformer.php b/app/Transformers/ExchangeRateTransformer.php index 18566cc69a..f9317d3bc3 100644 --- a/app/Transformers/ExchangeRateTransformer.php +++ b/app/Transformers/ExchangeRateTransformer.php @@ -42,31 +42,9 @@ class ExchangeRateTransformer extends AbstractTransformer */ public function transform(CurrencyExchangeRate $rate): array { - return [ - 'id' => (string) $rate->id, - 'created_at' => $rate->created_at->toAtomString(), - 'updated_at' => $rate->updated_at->toAtomString(), - - 'from_currency_id' => (string) $rate->fromCurrency->id, - 'from_currency_name' => $rate->fromCurrency->name, - 'from_currency_code' => $rate->fromCurrency->code, - 'from_currency_symbol' => $rate->fromCurrency->symbol, - 'from_currency_decimal_places' => $rate->fromCurrency->decimal_places, - - 'to_currency_id' => (string) $rate->toCurrency->id, - 'to_currency_name' => $rate->toCurrency->name, - 'to_currency_code' => $rate->toCurrency->code, - 'to_currency_symbol' => $rate->toCurrency->symbol, - 'to_currency_decimal_places' => $rate->toCurrency->decimal_places, - - 'rate' => $rate->rate, - 'date' => $rate->date->toAtomString(), - 'links' => [ - [ - 'rel' => 'self', - 'uri' => sprintf('/exchange-rates/%s', $rate->id), - ], - ], - ]; + return ['id' => (string) $rate->id, 'created_at' => $rate->created_at->toAtomString(), 'updated_at' => $rate->updated_at->toAtomString(), + 'from_currency_id' => (string) $rate->fromCurrency->id, 'from_currency_name' => $rate->fromCurrency->name, 'from_currency_code' => $rate->fromCurrency->code, 'from_currency_symbol' => $rate->fromCurrency->symbol, 'from_currency_decimal_places' => $rate->fromCurrency->decimal_places, + 'to_currency_id' => (string) $rate->toCurrency->id, 'to_currency_name' => $rate->toCurrency->name, 'to_currency_code' => $rate->toCurrency->code, 'to_currency_symbol' => $rate->toCurrency->symbol, 'to_currency_decimal_places' => $rate->toCurrency->decimal_places, + 'rate' => $rate->rate, 'date' => $rate->date->toAtomString(), 'links' => [['rel' => 'self', 'uri' => sprintf('/exchange-rates/%s', $rate->id)]]]; } } diff --git a/app/Transformers/LinkTypeTransformer.php b/app/Transformers/LinkTypeTransformer.php index f01db6355c..b325426a5f 100644 --- a/app/Transformers/LinkTypeTransformer.php +++ b/app/Transformers/LinkTypeTransformer.php @@ -44,12 +44,7 @@ class LinkTypeTransformer extends AbstractTransformer 'inward' => $linkType->inward, 'outward' => $linkType->outward, 'editable' => $linkType->editable, - 'links' => [ - [ - 'rel' => 'self', - 'uri' => '/link_types/'.$linkType->id, - ], - ], + 'links' => [['rel' => 'self', 'uri' => '/link_types/' . $linkType->id]] ]; } } diff --git a/app/Transformers/ObjectGroupTransformer.php b/app/Transformers/ObjectGroupTransformer.php index fa38e1d819..86ae348c61 100644 --- a/app/Transformers/ObjectGroupTransformer.php +++ b/app/Transformers/ObjectGroupTransformer.php @@ -55,12 +55,7 @@ class ObjectGroupTransformer extends AbstractTransformer 'updated_at' => $objectGroup->updated_at?->toAtomString(), 'title' => $objectGroup->title, 'order' => $objectGroup->order, - 'links' => [ - [ - 'rel' => 'self', - 'uri' => '/object_groups/'.$objectGroup->id, - ], - ], + 'links' => [['rel' => 'self', 'uri' => '/object_groups/' . $objectGroup->id]] ]; } } diff --git a/app/Transformers/PiggyBankEventTransformer.php b/app/Transformers/PiggyBankEventTransformer.php index a4fc3ea440..95c6a4b807 100644 --- a/app/Transformers/PiggyBankEventTransformer.php +++ b/app/Transformers/PiggyBankEventTransformer.php @@ -36,14 +36,14 @@ use FireflyIII\Support\Facades\Steam; class PiggyBankEventTransformer extends AbstractTransformer { private readonly TransactionCurrency $primaryCurrency; - private readonly bool $convertToPrimary; + private readonly bool $convertToPrimary; /** * PiggyBankEventTransformer constructor. */ public function __construct() { - $this->primaryCurrency = Amount::getPrimaryCurrency(); + $this->primaryCurrency = Amount::getPrimaryCurrency(); $this->convertToPrimary = Amount::convertToPrimary(); } @@ -65,34 +65,29 @@ class PiggyBankEventTransformer extends AbstractTransformer } return [ - 'id' => (string)$event->id, - 'created_at' => $event->created_at?->toAtomString(), - 'updated_at' => $event->updated_at?->toAtomString(), - 'amount' => $amount, - 'pc_amount' => $primaryAmount, + 'id' => (string) $event->id, + 'created_at' => $event->created_at?->toAtomString(), + 'updated_at' => $event->updated_at?->toAtomString(), + 'amount' => $amount, + 'pc_amount' => $primaryAmount, // currencies according to 6.3.0 - 'has_currency_setting' => true, - 'currency_id' => (string)$currency->id, - 'currency_name' => $currency->name, - 'currency_code' => $currency->code, - 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => $currency->decimal_places, + 'has_currency_setting' => true, + 'currency_id' => (string) $currency->id, + 'currency_name' => $currency->name, + 'currency_code' => $currency->code, + 'currency_symbol' => $currency->symbol, + 'currency_decimal_places' => $currency->decimal_places, - 'primary_currency_id' => (string)$this->primaryCurrency->id, + 'primary_currency_id' => (string) $this->primaryCurrency->id, 'primary_currency_name' => $this->primaryCurrency->name, 'primary_currency_code' => $this->primaryCurrency->code, 'primary_currency_symbol' => $this->primaryCurrency->symbol, 'primary_currency_decimal_places' => $this->primaryCurrency->decimal_places, - 'transaction_journal_id' => null !== $event->transaction_journal_id ? (string)$event->transaction_journal_id : null, - 'transaction_group_id' => $event->meta['transaction_group_id'], - 'links' => [ - [ - 'rel' => 'self', - 'uri' => sprintf('/piggy-banks/%d/events/%s', $event->piggy_bank_id, $event->id), - ], - ], + 'transaction_journal_id' => null !== $event->transaction_journal_id ? (string) $event->transaction_journal_id : null, + 'transaction_group_id' => $event->meta['transaction_group_id'], + 'links' => [['rel' => 'self', 'uri' => sprintf('/piggy-banks/%d/events/%s', $event->piggy_bank_id, $event->id)]] ]; } } diff --git a/app/Transformers/PiggyBankTransformer.php b/app/Transformers/PiggyBankTransformer.php index 9088044890..cb3ab73d67 100644 --- a/app/Transformers/PiggyBankTransformer.php +++ b/app/Transformers/PiggyBankTransformer.php @@ -33,7 +33,7 @@ use FireflyIII\Support\Facades\Amount; */ class PiggyBankTransformer extends AbstractTransformer { - private readonly TransactionCurrency $primaryCurrency; + private readonly TransactionCurrency $primaryCurrency; /** * PiggyBankTransformer constructor. @@ -51,57 +51,51 @@ class PiggyBankTransformer extends AbstractTransformer // Amounts, depending on 0.0 state of target amount $percentage = null; if (null !== $piggyBank->meta['target_amount'] && 0 !== bccomp((string) $piggyBank->meta['current_amount'], '0')) { // target amount is not 0.00 - $percentage = (int)bcmul(bcdiv((string) $piggyBank->meta['current_amount'], $piggyBank->meta['target_amount']), '100'); + $percentage = (int) bcmul(bcdiv((string) $piggyBank->meta['current_amount'], $piggyBank->meta['target_amount']), '100'); } $startDate = $piggyBank->start_date?->toAtomString(); $targetDate = $piggyBank->target_date?->toAtomString(); return [ - 'id' => (string)$piggyBank->id, - 'created_at' => $piggyBank->created_at->toAtomString(), - 'updated_at' => $piggyBank->updated_at->toAtomString(), - 'name' => $piggyBank->name, - 'percentage' => $percentage, - 'start_date' => $startDate, - 'target_date' => $targetDate, - 'order' => $piggyBank->order, - 'active' => true, - 'notes' => $piggyBank->meta['notes'], - 'object_group_id' => $piggyBank->meta['object_group_id'], - 'object_group_order' => $piggyBank->meta['object_group_order'], - 'object_group_title' => $piggyBank->meta['object_group_title'], - 'accounts' => $piggyBank->meta['accounts'], + 'id' => (string) $piggyBank->id, + 'created_at' => $piggyBank->created_at->toAtomString(), + 'updated_at' => $piggyBank->updated_at->toAtomString(), + 'name' => $piggyBank->name, + 'percentage' => $percentage, + 'start_date' => $startDate, + 'target_date' => $targetDate, + 'order' => $piggyBank->order, + 'active' => true, + 'notes' => $piggyBank->meta['notes'], + 'object_group_id' => $piggyBank->meta['object_group_id'], + 'object_group_order' => $piggyBank->meta['object_group_order'], + 'object_group_title' => $piggyBank->meta['object_group_title'], + 'accounts' => $piggyBank->meta['accounts'], // currency settings, 6.3.0. - 'object_has_currency_setting' => true, - 'currency_id' => (string)$piggyBank->meta['currency']->id, - 'currency_name' => $piggyBank->meta['currency']->name, - 'currency_code' => $piggyBank->meta['currency']->code, - 'currency_symbol' => $piggyBank->meta['currency']->symbol, - 'currency_decimal_places' => $piggyBank->meta['currency']->decimal_places, + 'object_has_currency_setting' => true, + 'currency_id' => (string) $piggyBank->meta['currency']->id, + 'currency_name' => $piggyBank->meta['currency']->name, + 'currency_code' => $piggyBank->meta['currency']->code, + 'currency_symbol' => $piggyBank->meta['currency']->symbol, + 'currency_decimal_places' => $piggyBank->meta['currency']->decimal_places, - 'primary_currency_id' => (string)$this->primaryCurrency->id, + 'primary_currency_id' => (string) $this->primaryCurrency->id, 'primary_currency_name' => $this->primaryCurrency->name, 'primary_currency_code' => $this->primaryCurrency->code, 'primary_currency_symbol' => $this->primaryCurrency->symbol, - 'primary_currency_decimal_places' => (int)$this->primaryCurrency->decimal_places, + 'primary_currency_decimal_places' => (int) $this->primaryCurrency->decimal_places, + 'target_amount' => $piggyBank->meta['target_amount'], + 'pc_target_amount' => $piggyBank->meta['pc_target_amount'], + 'current_amount' => $piggyBank->meta['current_amount'], + 'pc_current_amount' => $piggyBank->meta['pc_current_amount'], + 'left_to_save' => $piggyBank->meta['left_to_save'], + 'pc_left_to_save' => $piggyBank->meta['pc_left_to_save'], + 'save_per_month' => $piggyBank->meta['save_per_month'], + 'pc_save_per_month' => $piggyBank->meta['pc_save_per_month'], - 'target_amount' => $piggyBank->meta['target_amount'], - 'pc_target_amount' => $piggyBank->meta['pc_target_amount'], - 'current_amount' => $piggyBank->meta['current_amount'], - 'pc_current_amount' => $piggyBank->meta['pc_current_amount'], - 'left_to_save' => $piggyBank->meta['left_to_save'], - 'pc_left_to_save' => $piggyBank->meta['pc_left_to_save'], - 'save_per_month' => $piggyBank->meta['save_per_month'], - 'pc_save_per_month' => $piggyBank->meta['pc_save_per_month'], - - 'links' => [ - [ - 'rel' => 'self', - 'uri' => sprintf('/piggy-banks/%d', $piggyBank->id), - ], - ], + 'links' => [['rel' => 'self', 'uri' => sprintf('/piggy-banks/%d', $piggyBank->id)]] ]; } } diff --git a/app/Transformers/PreferenceTransformer.php b/app/Transformers/PreferenceTransformer.php index 78dead2380..2e9823c423 100644 --- a/app/Transformers/PreferenceTransformer.php +++ b/app/Transformers/PreferenceTransformer.php @@ -44,7 +44,7 @@ class PreferenceTransformer extends AbstractTransformer 'updated_at' => $preference->updated_at->toAtomString(), 'user_group_id' => $userGroupId, 'name' => $preference->name, - 'data' => $preference->data, + 'data' => $preference->data ]; } } diff --git a/app/Transformers/RecurrenceTransformer.php b/app/Transformers/RecurrenceTransformer.php index 03d7058184..98ed926b02 100644 --- a/app/Transformers/RecurrenceTransformer.php +++ b/app/Transformers/RecurrenceTransformer.php @@ -39,13 +39,13 @@ class RecurrenceTransformer extends AbstractTransformer { Log::debug('Now in Recurrence::transform()'); - $shortType = (string)config(sprintf('firefly.transactionTypesToShort.%s', $recurrence->transactionType->type)); - $reps = 0 === (int)$recurrence->repetitions ? null : (int)$recurrence->repetitions; + $shortType = (string) config(sprintf('firefly.transactionTypesToShort.%s', $recurrence->transactionType->type)); + $reps = 0 === (int) $recurrence->repetitions ? null : (int) $recurrence->repetitions; Log::debug('Get basic data.'); // basic data. return [ - 'id' => (string)$recurrence->id, + 'id' => (string) $recurrence->id, 'created_at' => $recurrence->created_at->toAtomString(), 'updated_at' => $recurrence->updated_at->toAtomString(), 'type' => $shortType, @@ -60,12 +60,7 @@ class RecurrenceTransformer extends AbstractTransformer 'notes' => $recurrence->meta['notes'], 'repetitions' => $recurrence->meta['repetitions'], 'transactions' => $recurrence->meta['transactions'], - 'links' => [ - [ - 'rel' => 'self', - 'uri' => '/recurring/'.$recurrence->id, - ], - ], + 'links' => [['rel' => 'self', 'uri' => '/recurring/' . $recurrence->id]] ]; } } diff --git a/app/Transformers/RuleGroupTransformer.php b/app/Transformers/RuleGroupTransformer.php index 696eda4fbb..b3cb484a62 100644 --- a/app/Transformers/RuleGroupTransformer.php +++ b/app/Transformers/RuleGroupTransformer.php @@ -44,12 +44,7 @@ class RuleGroupTransformer extends AbstractTransformer 'description' => $ruleGroup->description, 'order' => $ruleGroup->order, 'active' => $ruleGroup->active, - 'links' => [ - [ - 'rel' => 'self', - 'uri' => '/rule_groups/'.$ruleGroup->id, - ], - ], + 'links' => [['rel' => 'self', 'uri' => '/rule_groups/' . $ruleGroup->id]] ]; } } diff --git a/app/Transformers/RuleTransformer.php b/app/Transformers/RuleTransformer.php index 8e58a519cb..8a69e1ba39 100644 --- a/app/Transformers/RuleTransformer.php +++ b/app/Transformers/RuleTransformer.php @@ -69,12 +69,7 @@ class RuleTransformer extends AbstractTransformer 'trigger' => $this->getRuleTrigger($rule), 'triggers' => $this->triggers($rule), 'actions' => $this->actions($rule), - 'links' => [ - [ - 'rel' => 'self', - 'uri' => '/rules/'.$rule->id, - ], - ], + 'links' => [['rel' => 'self', 'uri' => '/rules/' . $rule->id]] ]; } @@ -123,7 +118,7 @@ class RuleTransformer extends AbstractTransformer $triggerValue = 'true'; } - $result[] = [ + $result[] = [ 'id' => (string) $ruleTrigger->id, 'created_at' => $ruleTrigger->created_at->toAtomString(), 'updated_at' => $ruleTrigger->updated_at->toAtomString(), @@ -132,7 +127,7 @@ class RuleTransformer extends AbstractTransformer 'prohibited' => $prohibited, 'order' => $ruleTrigger->order, 'active' => $ruleTrigger->active, - 'stop_processing' => $ruleTrigger->stop_processing, + 'stop_processing' => $ruleTrigger->stop_processing ]; } @@ -154,7 +149,7 @@ class RuleTransformer extends AbstractTransformer 'value' => $ruleAction->action_value, 'order' => $ruleAction->order, 'active' => $ruleAction->active, - 'stop_processing' => $ruleAction->stop_processing, + 'stop_processing' => $ruleAction->stop_processing ]; } diff --git a/app/Transformers/TagTransformer.php b/app/Transformers/TagTransformer.php index d9222069e9..5778023fd4 100644 --- a/app/Transformers/TagTransformer.php +++ b/app/Transformers/TagTransformer.php @@ -39,7 +39,7 @@ class TagTransformer extends AbstractTransformer */ public function transform(Tag $tag): array { - $date = $tag->date?->format('Y-m-d'); + $date = $tag->date?->format('Y-m-d'); /** @var null|Location $location */ $location = $tag->locations()->first(); @@ -62,12 +62,7 @@ class TagTransformer extends AbstractTransformer 'longitude' => $longitude, 'latitude' => $latitude, 'zoom_level' => $zoomLevel, - 'links' => [ - [ - 'rel' => 'self', - 'uri' => '/tags/'.$tag->id, - ], - ], + 'links' => [['rel' => 'self', 'uri' => '/tags/' . $tag->id]] ]; } } diff --git a/app/Transformers/TransactionGroupTransformer.php b/app/Transformers/TransactionGroupTransformer.php index c7a59c1520..55897b2ffb 100644 --- a/app/Transformers/TransactionGroupTransformer.php +++ b/app/Transformers/TransactionGroupTransformer.php @@ -46,8 +46,8 @@ use Illuminate\Support\Facades\Log; class TransactionGroupTransformer extends AbstractTransformer { private readonly TransactionGroupRepositoryInterface $groupRepos; - private readonly array $metaDateFields; - private readonly array $metaFields; + private readonly array $metaDateFields; + private readonly array $metaFields; /** * Constructor. @@ -55,8 +55,8 @@ class TransactionGroupTransformer extends AbstractTransformer public function __construct() { Log::debug('TransactionGroupTransformer constructor.'); - $this->groupRepos = app(TransactionGroupRepositoryInterface::class); - $this->metaFields = [ + $this->groupRepos = app(TransactionGroupRepositoryInterface::class); + $this->metaFields = [ 'sepa_cc', 'sepa_ct_op', 'sepa_ct_id', @@ -73,7 +73,7 @@ class TransactionGroupTransformer extends AbstractTransformer 'original_source', 'external_url', 'recurrence_count', - 'recurrence_total', + 'recurrence_total' ]; $this->metaDateFields = ['interest_date', 'book_date', 'process_date', 'due_date', 'payment_date', 'invoice_date', '_internal_previous_date']; } @@ -91,12 +91,7 @@ class TransactionGroupTransformer extends AbstractTransformer 'user_group' => (string) $data['user_group_id'], 'group_title' => $data['title'], 'transactions' => $this->transformTransactions($data), - 'links' => [ - [ - 'rel' => 'self', - 'uri' => '/transactions/'.$first['transaction_group_id'], - ], - ], + 'links' => [['rel' => 'self', 'uri' => '/transactions/' . $first['transaction_group_id']]] ]; } @@ -117,8 +112,8 @@ class TransactionGroupTransformer extends AbstractTransformer private function transformTransaction(array $transaction): array { // amount: - $amount = Steam::positive((string) ($transaction['amount'] ?? '0')); - $foreignAmount = null; + $amount = Steam::positive((string) ($transaction['amount'] ?? '0')); + $foreignAmount = null; if (null !== $transaction['foreign_amount'] && '' !== $transaction['foreign_amount'] && 0 !== bccomp('0', (string) $transaction['foreign_amount'])) { $foreignAmount = Steam::positive($transaction['foreign_amount']); } @@ -131,7 +126,7 @@ class TransactionGroupTransformer extends AbstractTransformer if (array_key_exists('pc_amount', $transaction) && null !== $transaction['pc_amount']) { $transaction['pc_amount'] = Steam::positive($transaction['pc_amount']); } - $type = $this->stringFromArray($transaction, 'transaction_type_type', TransactionTypeEnum::WITHDRAWAL->value); + $type = $this->stringFromArray($transaction, 'transaction_type_type', TransactionTypeEnum::WITHDRAWAL->value); // must be 0 (int) or NULL $recurrenceTotal = $transaction['meta']['recurrence_total'] ?? null; @@ -140,20 +135,20 @@ class TransactionGroupTransformer extends AbstractTransformer $recurrenceCount = null !== $recurrenceCount ? (int) $recurrenceCount : null; return [ - 'user' => (string) $transaction['user_id'], - 'transaction_journal_id' => (string) $transaction['transaction_journal_id'], - 'type' => strtolower((string) $type), - 'date' => $transaction['date']->toAtomString(), - 'order' => $transaction['order'], + 'user' => (string) $transaction['user_id'], + 'transaction_journal_id' => (string) $transaction['transaction_journal_id'], + 'type' => strtolower((string) $type), + 'date' => $transaction['date']->toAtomString(), + 'order' => $transaction['order'], // currency information, structured for 6.3.0. - 'object_has_currency_setting' => true, + 'object_has_currency_setting' => true, - 'currency_id' => (string) $transaction['currency_id'], - 'currency_code' => $transaction['currency_code'], - 'currency_name' => $transaction['currency_name'], - 'currency_symbol' => $transaction['currency_symbol'], - 'currency_decimal_places' => (int) $transaction['currency_decimal_places'], + 'currency_id' => (string) $transaction['currency_id'], + 'currency_code' => $transaction['currency_code'], + 'currency_name' => $transaction['currency_name'], + 'currency_symbol' => $transaction['currency_symbol'], + 'currency_decimal_places' => (int) $transaction['currency_decimal_places'], 'foreign_currency_id' => $this->stringFromArray($transaction, 'foreign_currency_id', null), 'foreign_currency_code' => $transaction['foreign_currency_code'], @@ -168,83 +163,83 @@ class TransactionGroupTransformer extends AbstractTransformer 'primary_currency_decimal_places' => $transaction['primary_currency']['decimal_places'] ?? null, // amounts, structured for 6.3.0. - 'amount' => $amount, - 'pc_amount' => $transaction['pc_amount'] ?? null, + 'amount' => $amount, + 'pc_amount' => $transaction['pc_amount'] ?? null, - 'foreign_amount' => $foreignAmount, - 'pc_foreign_amount' => null, + 'foreign_amount' => $foreignAmount, + 'pc_foreign_amount' => null, - 'source_balance_after' => $transaction['source_balance_after'] ?? null, - 'pc_source_balance_after' => null, + 'source_balance_after' => $transaction['source_balance_after'] ?? null, + 'pc_source_balance_after' => null, // destination balance after - 'destination_balance_after' => $transaction['destination_balance_after'] ?? null, - 'pc_destination_balance_after' => null, + 'destination_balance_after' => $transaction['destination_balance_after'] ?? null, + 'pc_destination_balance_after' => null, - 'source_balance_dirty' => $transaction['source_balance_dirty'], - 'destination_balance_dirty' => $transaction['destination_balance_dirty'], + 'source_balance_dirty' => $transaction['source_balance_dirty'], + 'destination_balance_dirty' => $transaction['destination_balance_dirty'], - 'description' => $transaction['description'], + 'description' => $transaction['description'], - 'source_id' => (string) $transaction['source_account_id'], - 'source_name' => $transaction['source_account_name'], - 'source_iban' => $transaction['source_account_iban'], - 'source_type' => $transaction['source_account_type'], + 'source_id' => (string) $transaction['source_account_id'], + 'source_name' => $transaction['source_account_name'], + 'source_iban' => $transaction['source_account_iban'], + 'source_type' => $transaction['source_account_type'], - 'destination_id' => (string) $transaction['destination_account_id'], - 'destination_name' => $transaction['destination_account_name'], - 'destination_iban' => $transaction['destination_account_iban'], - 'destination_type' => $transaction['destination_account_type'], + 'destination_id' => (string) $transaction['destination_account_id'], + 'destination_name' => $transaction['destination_account_name'], + 'destination_iban' => $transaction['destination_account_iban'], + 'destination_type' => $transaction['destination_account_type'], - 'budget_id' => $this->stringFromArray($transaction, 'budget_id', null), - 'budget_name' => $transaction['budget_name'], + 'budget_id' => $this->stringFromArray($transaction, 'budget_id', null), + 'budget_name' => $transaction['budget_name'], - 'category_id' => $this->stringFromArray($transaction, 'category_id', null), - 'category_name' => $transaction['category_name'], + 'category_id' => $this->stringFromArray($transaction, 'category_id', null), + 'category_name' => $transaction['category_name'], - 'bill_id' => $this->stringFromArray($transaction, 'bill_id', null), - 'bill_name' => $transaction['bill_name'], - 'subscription_id' => $this->stringFromArray($transaction, 'bill_id', null), - 'subscription_name' => $transaction['bill_name'], + 'bill_id' => $this->stringFromArray($transaction, 'bill_id', null), + 'bill_name' => $transaction['bill_name'], + 'subscription_id' => $this->stringFromArray($transaction, 'bill_id', null), + 'subscription_name' => $transaction['bill_name'], - 'reconciled' => $transaction['reconciled'], - 'notes' => $transaction['notes'], - 'tags' => $transaction['tags'], + 'reconciled' => $transaction['reconciled'], + 'notes' => $transaction['notes'], + 'tags' => $transaction['tags'], - 'internal_reference' => $transaction['meta']['internal_reference'] ?? null, - 'external_id' => $transaction['meta']['external_id'] ?? null, - 'original_source' => $transaction['meta']['original_source'] ?? null, - 'recurrence_id' => $transaction['meta']['recurrence_id'] ?? null, - 'recurrence_total' => $recurrenceTotal, - 'recurrence_count' => $recurrenceCount, - 'external_url' => $transaction['meta']['external_url'] ?? null, - 'import_hash_v2' => $transaction['meta']['import_hash_v2'] ?? null, + 'internal_reference' => $transaction['meta']['internal_reference'] ?? null, + 'external_id' => $transaction['meta']['external_id'] ?? null, + 'original_source' => $transaction['meta']['original_source'] ?? null, + 'recurrence_id' => $transaction['meta']['recurrence_id'] ?? null, + 'recurrence_total' => $recurrenceTotal, + 'recurrence_count' => $recurrenceCount, + 'external_url' => $transaction['meta']['external_url'] ?? null, + 'import_hash_v2' => $transaction['meta']['import_hash_v2'] ?? null, - 'sepa_cc' => $transaction['meta']['sepa_cc'] ?? null, - 'sepa_ct_op' => $transaction['meta']['sepa_ct_op'] ?? null, - 'sepa_ct_id' => $transaction['meta']['sepa_ct_id'] ?? null, - 'sepa_db' => $transaction['meta']['sepa_db'] ?? null, - 'sepa_country' => $transaction['meta']['sepa_country'] ?? null, - 'sepa_ep' => $transaction['meta']['sepa_ep'] ?? null, - 'sepa_ci' => $transaction['meta']['sepa_ci'] ?? null, - 'sepa_batch_id' => $transaction['meta']['sepa_batch_id'] ?? null, + 'sepa_cc' => $transaction['meta']['sepa_cc'] ?? null, + 'sepa_ct_op' => $transaction['meta']['sepa_ct_op'] ?? null, + 'sepa_ct_id' => $transaction['meta']['sepa_ct_id'] ?? null, + 'sepa_db' => $transaction['meta']['sepa_db'] ?? null, + 'sepa_country' => $transaction['meta']['sepa_country'] ?? null, + 'sepa_ep' => $transaction['meta']['sepa_ep'] ?? null, + 'sepa_ci' => $transaction['meta']['sepa_ci'] ?? null, + 'sepa_batch_id' => $transaction['meta']['sepa_batch_id'] ?? null, - 'interest_date' => array_key_exists('interest_date', $transaction['meta_date']) ? $transaction['meta_date']['interest_date']->toW3CString() : null, - 'book_date' => array_key_exists('book_date', $transaction['meta_date']) ? $transaction['meta_date']['book_date']->toW3CString() : null, - 'process_date' => array_key_exists('process_date', $transaction['meta_date']) ? $transaction['meta_date']['process_date']->toW3CString() : null, - 'due_date' => array_key_exists('due_date', $transaction['meta_date']) ? $transaction['meta_date']['due_date']->toW3CString() : null, - 'payment_date' => array_key_exists('payment_date', $transaction['meta_date']) ? $transaction['meta_date']['payment_date']->toW3CString() : null, - 'invoice_date' => array_key_exists('invoice_date', $transaction['meta_date']) ? $transaction['meta_date']['invoice_date']->toW3CString() : null, + 'interest_date' => array_key_exists('interest_date', $transaction['meta_date']) ? $transaction['meta_date']['interest_date']->toW3CString() : null, + 'book_date' => array_key_exists('book_date', $transaction['meta_date']) ? $transaction['meta_date']['book_date']->toW3CString() : null, + 'process_date' => array_key_exists('process_date', $transaction['meta_date']) ? $transaction['meta_date']['process_date']->toW3CString() : null, + 'due_date' => array_key_exists('due_date', $transaction['meta_date']) ? $transaction['meta_date']['due_date']->toW3CString() : null, + 'payment_date' => array_key_exists('payment_date', $transaction['meta_date']) ? $transaction['meta_date']['payment_date']->toW3CString() : null, + 'invoice_date' => array_key_exists('invoice_date', $transaction['meta_date']) ? $transaction['meta_date']['invoice_date']->toW3CString() : null, // location data - 'longitude' => $transaction['location']['longitude'], - 'latitude' => $transaction['location']['latitude'], - 'zoom_level' => $transaction['location']['zoom_level'], - 'has_attachments' => $transaction['attachment_count'] > 0, + 'longitude' => $transaction['location']['longitude'], + 'latitude' => $transaction['location']['latitude'], + 'zoom_level' => $transaction['location']['zoom_level'], + 'has_attachments' => $transaction['attachment_count'] > 0 ]; } - private function stringFromArray(array $array, string $key, ?string $default): ?string + private function stringFromArray(array $array, string $key, null|string $default): null|string { if (array_key_exists($key, $array) && null === $array[$key]) { return null; @@ -276,12 +271,7 @@ class TransactionGroupTransformer extends AbstractTransformer 'user' => $group->user_id, 'group_title' => $group->title, 'transactions' => $this->transformJournals($group->transactionJournals), - 'links' => [ - [ - 'rel' => 'self', - 'uri' => '/transactions/'.$group->id, - ], - ], + 'links' => [['rel' => 'self', 'uri' => '/transactions/' . $group->id]] ]; } catch (FireflyException $e) { Log::error($e->getMessage()); @@ -334,10 +324,10 @@ class TransactionGroupTransformer extends AbstractTransformer $foreignAmount = Steam::bcround($foreignAmount, $foreignCurrency['decimal_places'] ?? 0); } - $longitude = null; - $latitude = null; - $zoomLevel = null; - $location = $this->getLocation($journal); + $longitude = null; + $latitude = null; + $zoomLevel = null; + $location = $this->getLocation($journal); if ($location instanceof Location) { $longitude = $location->longitude; $latitude = $location->latitude; @@ -345,77 +335,77 @@ class TransactionGroupTransformer extends AbstractTransformer } return [ - 'user' => $journal->user_id, - 'transaction_journal_id' => (string) $journal->id, - 'type' => strtolower((string) $type), - 'date' => $journal->date->toAtomString(), - 'order' => $journal->order, + 'user' => $journal->user_id, + 'transaction_journal_id' => (string) $journal->id, + 'type' => strtolower((string) $type), + 'date' => $journal->date->toAtomString(), + 'order' => $journal->order, - 'currency_id' => (string) $currency->id, - 'currency_code' => $currency->code, - 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => $currency->decimal_places, + 'currency_id' => (string) $currency->id, + 'currency_code' => $currency->code, + 'currency_symbol' => $currency->symbol, + 'currency_decimal_places' => $currency->decimal_places, 'foreign_currency_id' => (string) $foreignCurrency['id'], 'foreign_currency_code' => $foreignCurrency['code'], 'foreign_currency_symbol' => $foreignCurrency['symbol'], 'foreign_currency_decimal_places' => $foreignCurrency['decimal_places'], - 'amount' => Steam::bcround($amount, $currency->decimal_places), - 'foreign_amount' => $foreignAmount, + 'amount' => Steam::bcround($amount, $currency->decimal_places), + 'foreign_amount' => $foreignAmount, - 'description' => $journal->description, + 'description' => $journal->description, - 'source_id' => (string) $source->account_id, - 'source_name' => $source->account->name, - 'source_iban' => $source->account->iban, - 'source_type' => $source->account->accountType->type, + 'source_id' => (string) $source->account_id, + 'source_name' => $source->account->name, + 'source_iban' => $source->account->iban, + 'source_type' => $source->account->accountType->type, - 'destination_id' => (string) $destination->account_id, - 'destination_name' => $destination->account->name, - 'destination_iban' => $destination->account->iban, - 'destination_type' => $destination->account->accountType->type, + 'destination_id' => (string) $destination->account_id, + 'destination_name' => $destination->account->name, + 'destination_iban' => $destination->account->iban, + 'destination_type' => $destination->account->accountType->type, - 'budget_id' => (string) $budget['id'], - 'budget_name' => $budget['name'], + 'budget_id' => (string) $budget['id'], + 'budget_name' => $budget['name'], - 'category_id' => (string) $category['id'], - 'category_name' => $category['name'], + 'category_id' => (string) $category['id'], + 'category_name' => $category['name'], - 'bill_id' => (string) $bill['id'], - 'bill_name' => $bill['name'], + 'bill_id' => (string) $bill['id'], + 'bill_name' => $bill['name'], - 'reconciled' => $source->reconciled, - 'notes' => $this->groupRepos->getNoteText($journal->id), - 'tags' => $this->groupRepos->getTags($journal->id), + 'reconciled' => $source->reconciled, + 'notes' => $this->groupRepos->getNoteText($journal->id), + 'tags' => $this->groupRepos->getTags($journal->id), - 'internal_reference' => $metaFieldData['internal_reference'], - 'external_id' => $metaFieldData['external_id'], - 'original_source' => $metaFieldData['original_source'], - 'recurrence_id' => $metaFieldData['recurrence_id'], - 'bunq_payment_id' => $metaFieldData['bunq_payment_id'], - 'import_hash_v2' => $metaFieldData['import_hash_v2'], + 'internal_reference' => $metaFieldData['internal_reference'], + 'external_id' => $metaFieldData['external_id'], + 'original_source' => $metaFieldData['original_source'], + 'recurrence_id' => $metaFieldData['recurrence_id'], + 'bunq_payment_id' => $metaFieldData['bunq_payment_id'], + 'import_hash_v2' => $metaFieldData['import_hash_v2'], - 'sepa_cc' => $metaFieldData['sepa_cc'], - 'sepa_ct_op' => $metaFieldData['sepa_ct_op'], - 'sepa_ct_id' => $metaFieldData['sepa_ct_id'], - 'sepa_db' => $metaFieldData['sepa_db'], - 'sepa_country' => $metaFieldData['sepa_country'], - 'sepa_ep' => $metaFieldData['sepa_ep'], - 'sepa_ci' => $metaFieldData['sepa_ci'], - 'sepa_batch_id' => $metaFieldData['sepa_batch_id'], + 'sepa_cc' => $metaFieldData['sepa_cc'], + 'sepa_ct_op' => $metaFieldData['sepa_ct_op'], + 'sepa_ct_id' => $metaFieldData['sepa_ct_id'], + 'sepa_db' => $metaFieldData['sepa_db'], + 'sepa_country' => $metaFieldData['sepa_country'], + 'sepa_ep' => $metaFieldData['sepa_ep'], + 'sepa_ci' => $metaFieldData['sepa_ci'], + 'sepa_batch_id' => $metaFieldData['sepa_batch_id'], - 'interest_date' => $metaDates['interest_date'], - 'book_date' => $metaDates['book_date'], - 'process_date' => $metaDates['process_date'], - 'due_date' => $metaDates['due_date'], - 'payment_date' => $metaDates['payment_date'], - 'invoice_date' => $metaDates['invoice_date'], + 'interest_date' => $metaDates['interest_date'], + 'book_date' => $metaDates['book_date'], + 'process_date' => $metaDates['process_date'], + 'due_date' => $metaDates['due_date'], + 'payment_date' => $metaDates['payment_date'], + 'invoice_date' => $metaDates['invoice_date'], // location data - 'longitude' => $longitude, - 'latitude' => $latitude, - 'zoom_level' => $zoomLevel, + 'longitude' => $longitude, + 'latitude' => $latitude, + 'zoom_level' => $zoomLevel ]; } @@ -424,9 +414,7 @@ class TransactionGroupTransformer extends AbstractTransformer */ private function getSourceTransaction(TransactionJournal $journal): Transaction { - $result = $journal->transactions->first( - static fn (Transaction $transaction): bool => (float) $transaction->amount < 0 - ); + $result = $journal->transactions->first(static fn(Transaction $transaction): bool => (float) $transaction->amount < 0); if (null === $result) { throw new FireflyException(sprintf('Journal #%d unexpectedly has no source transaction.', $journal->id)); } @@ -439,9 +427,7 @@ class TransactionGroupTransformer extends AbstractTransformer */ private function getDestinationTransaction(TransactionJournal $journal): Transaction { - $result = $journal->transactions->first( - static fn (Transaction $transaction): bool => (float) $transaction->amount > 0 - ); + $result = $journal->transactions->first(static fn(Transaction $transaction): bool => (float) $transaction->amount > 0); if (null === $result) { throw new FireflyException(sprintf('Journal #%d unexpectedly has no destination transaction.', $journal->id)); } @@ -454,7 +440,7 @@ class TransactionGroupTransformer extends AbstractTransformer return Steam::positive($amount); } - private function getForeignAmount(?string $foreignAmount): ?string + private function getForeignAmount(null|string $foreignAmount): null|string { if (null !== $foreignAmount && '' !== $foreignAmount && 0 !== bccomp('0', $foreignAmount)) { return Steam::positive($foreignAmount); @@ -465,14 +451,7 @@ class TransactionGroupTransformer extends AbstractTransformer private function getDates(NullArrayObject $dates): array { - $fields = [ - 'interest_date', - 'book_date', - 'process_date', - 'due_date', - 'payment_date', - 'invoice_date', - ]; + $fields = ['interest_date', 'book_date', 'process_date', 'due_date', 'payment_date', 'invoice_date']; $return = []; foreach ($fields as $field) { $return[$field] = null; @@ -484,71 +463,57 @@ class TransactionGroupTransformer extends AbstractTransformer return $return; } - private function getForeignCurrency(?TransactionCurrency $currency): array + private function getForeignCurrency(null|TransactionCurrency $currency): array { - $array = [ - 'id' => null, - 'code' => null, - 'symbol' => null, - 'decimal_places' => null, - ]; + $array = ['id' => null, 'code' => null, 'symbol' => null, 'decimal_places' => null]; if (!$currency instanceof TransactionCurrency) { return $array; } - $array['id'] = $currency->id; - $array['code'] = $currency->code; - $array['symbol'] = $currency->symbol; + $array['id'] = $currency->id; + $array['code'] = $currency->code; + $array['symbol'] = $currency->symbol; $array['decimal_places'] = $currency->decimal_places; return $array; } - private function getBudget(?Budget $budget): array + private function getBudget(null|Budget $budget): array { - $array = [ - 'id' => null, - 'name' => null, - ]; + $array = ['id' => null, 'name' => null]; if (!$budget instanceof Budget) { return $array; } - $array['id'] = $budget->id; + $array['id'] = $budget->id; $array['name'] = $budget->name; return $array; } - private function getCategory(?Category $category): array + private function getCategory(null|Category $category): array { - $array = [ - 'id' => null, - 'name' => null, - ]; + $array = ['id' => null, 'name' => null]; if (!$category instanceof Category) { return $array; } - $array['id'] = $category->id; + $array['id'] = $category->id; $array['name'] = $category->name; return $array; } - private function getBill(?Bill $bill): array + private function getBill(null|Bill $bill): array { - $array = [ - 'id' => null, - 'name' => null, - ]; + $array = ['id' => null, 'name' => null]; if (!$bill instanceof Bill) { return $array; } - $array['id'] = (string) $bill->id; + $array['id'] = (string) $bill->id; $array['name'] = $bill->name; return $array; } - private function getLocation(TransactionJournal $journal): ?Location + private function getLocation(TransactionJournal $journal): null|Location { /** @var null|Location */ return $journal->locations()->first(); diff --git a/app/Transformers/TransactionLinkTransformer.php b/app/Transformers/TransactionLinkTransformer.php index 25b83f8597..c3f8a62b5b 100644 --- a/app/Transformers/TransactionLinkTransformer.php +++ b/app/Transformers/TransactionLinkTransformer.php @@ -55,12 +55,7 @@ class TransactionLinkTransformer extends AbstractTransformer 'outward_id' => (string) $link->destination_id, 'link_type_id' => (string) $link->link_type_id, 'notes' => '' === $notes ? null : $notes, - 'links' => [ - [ - 'rel' => 'self', - 'uri' => '/transaction_links/'.$link->id, - ], - ], + 'links' => [['rel' => 'self', 'uri' => '/transaction_links/' . $link->id]] ]; } } diff --git a/app/Transformers/UserGroupTransformer.php b/app/Transformers/UserGroupTransformer.php index 2eb115fe4a..091ee9a565 100644 --- a/app/Transformers/UserGroupTransformer.php +++ b/app/Transformers/UserGroupTransformer.php @@ -49,9 +49,9 @@ class UserGroupTransformer extends AbstractTransformer /** @var UserGroup $userGroup */ foreach ($objects as $userGroup) { - $userGroupId = $userGroup->id; - $this->inUse[$userGroupId] = $user->user_group_id === $userGroupId; - $access = $user->hasRoleInGroupOrOwner($userGroup, UserRoleEnum::VIEW_MEMBERSHIPS) || $user->hasRole('owner'); + $userGroupId = $userGroup->id; + $this->inUse[$userGroupId] = $user->user_group_id === $userGroupId; + $access = $user->hasRoleInGroupOrOwner($userGroup, UserRoleEnum::VIEW_MEMBERSHIPS) || $user->hasRole('owner'); $this->membershipsVisible[$userGroupId] = $access; if ($access) { $groupMemberships = $userGroup->groupMemberships()->get(); @@ -62,7 +62,7 @@ class UserGroupTransformer extends AbstractTransformer 'user_id' => (string) $groupMembership->user_id, 'user_email' => $groupMembership->user->email, 'role' => $groupMembership->userRole->title, - 'you' => $groupMembership->user_id === $user->id, + 'you' => $groupMembership->user_id === $user->id ]; } } @@ -75,17 +75,17 @@ class UserGroupTransformer extends AbstractTransformer private function mergeMemberships(): void { - $new = []; + $new = []; foreach ($this->memberships as $groupId => $members) { $new[$groupId] ??= []; foreach ($members as $member) { - $mail = $member['user_email']; + $mail = $member['user_email']; $new[$groupId][$mail] ??= [ 'user_id' => (string) $member['user_id'], 'user_email' => $member['user_email'], 'you' => $member['you'], - 'roles' => [], + 'roles' => [] ]; $new[$groupId][$mail]['roles'][] = $member['role']; } @@ -112,8 +112,9 @@ class UserGroupTransformer extends AbstractTransformer 'primary_currency_code' => $currency->code, 'primary_currency_symbol' => $currency->symbol, 'primary_currency_decimal_places' => $currency->decimal_places, - 'members' => array_values($this->memberships[$userGroup->id] ?? []), + 'members' => array_values($this->memberships[$userGroup->id] ?? []) ]; + // if the user has a specific role in this group, then collect the memberships. } } diff --git a/app/Transformers/UserTransformer.php b/app/Transformers/UserTransformer.php index d4a06aefb0..a896b2657d 100644 --- a/app/Transformers/UserTransformer.php +++ b/app/Transformers/UserTransformer.php @@ -49,12 +49,7 @@ class UserTransformer extends AbstractTransformer 'blocked' => 1 === (int) $user->blocked, 'blocked_code' => '' === $user->blocked_code ? null : $user->blocked_code, 'role' => $this->repository->getRoleByUser($user), - 'links' => [ - [ - 'rel' => 'self', - 'uri' => '/users/'.$user->id, - ], - ], + 'links' => [['rel' => 'self', 'uri' => '/users/' . $user->id]] ]; } } diff --git a/app/Transformers/WebhookAttemptTransformer.php b/app/Transformers/WebhookAttemptTransformer.php index 2ab04f184a..5309d6ab94 100644 --- a/app/Transformers/WebhookAttemptTransformer.php +++ b/app/Transformers/WebhookAttemptTransformer.php @@ -43,7 +43,7 @@ class WebhookAttemptTransformer extends AbstractTransformer 'webhook_message_id' => (string) $attempt->webhook_message_id, 'status_code' => (int) $attempt->status_code, 'logs' => $attempt->logs, - 'response' => $attempt->response, + 'response' => $attempt->response ]; } } diff --git a/app/Transformers/WebhookMessageTransformer.php b/app/Transformers/WebhookMessageTransformer.php index 24bc25d4c2..a17c403042 100644 --- a/app/Transformers/WebhookMessageTransformer.php +++ b/app/Transformers/WebhookMessageTransformer.php @@ -56,7 +56,7 @@ class WebhookMessageTransformer extends AbstractTransformer 'errored' => $message->errored, 'webhook_id' => (string) $message->webhook_id, 'uuid' => $message->uuid, - 'message' => $json, + 'message' => $json ]; } } diff --git a/app/Transformers/WebhookTransformer.php b/app/Transformers/WebhookTransformer.php index 9eace066e5..f9f6b62a4c 100644 --- a/app/Transformers/WebhookTransformer.php +++ b/app/Transformers/WebhookTransformer.php @@ -47,12 +47,7 @@ class WebhookTransformer extends AbstractTransformer 'deliveries' => $webhook->meta['deliveries'], 'responses' => $webhook->meta['responses'], 'url' => $webhook->url, - 'links' => [ - [ - 'rel' => 'self', - 'uri' => sprintf('/webhooks/%d', $webhook->id), - ], - ], + 'links' => [['rel' => 'self', 'uri' => sprintf('/webhooks/%d', $webhook->id)]] ]; } } diff --git a/app/User.php b/app/User.php index 0e8ebbb748..286ae83ca4 100644 --- a/app/User.php +++ b/app/User.php @@ -251,21 +251,20 @@ class User extends Authenticatable Log::debug(sprintf('in hasAnyRoleInGroup(%s)', implode(', ', $roles))); /** @var Collection $dbRoles */ - $dbRoles = UserRole::whereIn('title', $roles)->get(); + $dbRoles = UserRole::whereIn('title', $roles)->get(); if (0 === $dbRoles->count()) { Log::error(sprintf('Could not find role(s): %s. Probably migration mishap.', implode(', ', $roles))); return false; } - $dbRolesIds = $dbRoles->pluck('id')->toArray(); - $dbRolesTitles = $dbRoles->pluck('title')->toArray(); + $dbRolesIds = $dbRoles->pluck('id')->toArray(); + $dbRolesTitles = $dbRoles->pluck('title')->toArray(); $groupMemberships = $this ->groupMemberships() ->whereIn('user_role_id', $dbRolesIds) ->where('user_group_id', $userGroup->id) - ->get() - ; + ->get(); if (0 === $groupMemberships->count()) { Log::error(sprintf( 'User #%d "%s" does not have roles %s in user group #%d "%s"', @@ -360,13 +359,13 @@ class User extends Authenticatable */ public function routeNotificationFor($driver, $notification = null) { - $method = 'routeNotificationFor'.Str::studly($driver); + $method = 'routeNotificationFor' . Str::studly($driver); if (method_exists($this, $method)) { return $this->{$method}($notification); // @phpstan-ignore-line } - $email = $this->email; + $email = $this->email; // see if user has alternative email address: - $pref = Preferences::getForUser($this, 'remote_guard_alt_email'); + $pref = Preferences::getForUser($this, 'remote_guard_alt_email'); if (null !== $pref) { $email = $pref->data; } @@ -376,7 +375,7 @@ class User extends Authenticatable } return match ($driver) { - 'mail' => $email, + 'mail' => $email, default => null }; } @@ -408,14 +407,14 @@ class User extends Authenticatable /** * Route notifications for the Slack channel. */ - public function routeNotificationForSlack(Notification $notification): ?string + public function routeNotificationForSlack(Notification $notification): null|string { // this check does not validate if the user is owner, Should be done by notification itself. - $res = FireflyConfig::getEncrypted('slack_webhook_url', '')->data; + $res = FireflyConfig::getEncrypted('slack_webhook_url', '')->data; if (is_array($res)) { $res = ''; } - $res = (string) $res; + $res = (string) $res; if (property_exists($notification, 'type') && 'owner' === $notification->type) { return $res; diff --git a/app/Validation/Account/DepositValidation.php b/app/Validation/Account/DepositValidation.php index 574f00cb9b..f419db53f2 100644 --- a/app/Validation/Account/DepositValidation.php +++ b/app/Validation/Account/DepositValidation.php @@ -44,13 +44,13 @@ trait DepositValidation Log::debug('Now in validateDepositDestination', $array); // source can be any of the following types. - $validTypes = $this->combinations[$this->transactionType][$this->source->accountType->type] ?? []; + $validTypes = $this->combinations[$this->transactionType][$this->source->accountType->type] ?? []; if (null === $accountId && null === $accountName && null === $accountIban && false === $this->canCreateTypes($validTypes)) { // if both values are NULL we return false, // because the destination of a deposit can't be created. $this->destError = (string) trans('validation.deposit_dest_need_data'); Log::error('Both values are NULL, cant create deposit destination.'); - $result = false; + $result = false; } // if the account can be created anyway we don't need to search. if (null === $result && true === $this->canCreateTypes($validTypes)) { @@ -63,8 +63,8 @@ trait DepositValidation $search = $this->findExistingAccount($validTypes, $array); if (null === $search) { Log::debug('findExistingAccount() returned NULL, so the result is false.'); - $this->destError = (string) trans('validation.deposit_dest_bad_data', ['id' => $accountId, 'name' => $accountName]); - $result = false; + $this->destError = (string) trans('validation.deposit_dest_bad_data', ['id' => $accountId, 'name' => $accountName]); + $result = false; } if (null !== $search) { Log::debug(sprintf('findExistingAccount() returned #%d ("%s"), so the result is true.', $search->id, $search->name)); @@ -79,7 +79,7 @@ trait DepositValidation abstract protected function canCreateTypes(array $accountTypes): bool; - abstract protected function findExistingAccount(array $validTypes, array $data): ?Account; + abstract protected function findExistingAccount(array $validTypes, array $data): null|Account; /** * Pretty complex unfortunately. @@ -97,20 +97,16 @@ trait DepositValidation // null = we found nothing at all or didn't even search // false = invalid results - $result = null; + $result = null; // source can be any of the following types. - $validTypes = array_keys($this->combinations[$this->transactionType]); - if (null === $accountId - && null === $accountName - && null === $accountIban - && null === $accountNumber - && false === $this->canCreateTypes($validTypes)) { + $validTypes = array_keys($this->combinations[$this->transactionType]); + if (null === $accountId && null === $accountName && null === $accountIban && null === $accountNumber && false === $this->canCreateTypes($validTypes)) { // if both values are NULL return false, // because the source of a deposit can't be created. // (this never happens). $this->sourceError = (string) trans('validation.deposit_source_need_data'); - $result = false; + $result = false; } // if there is an iban, it can only be in use by a valid source type, or we will fail. @@ -132,8 +128,8 @@ trait DepositValidation Log::debug(sprintf('User submitted an ID (#%d), which is a "%s", so this is not a valid source.', $accountId, $search->accountType->type)); Log::debug(sprintf('Firefly III does not accept ID #%d as valid account data.', $accountId)); // #10921 Set result false - $this->sourceError = (string) trans('validation.withdrawal_source_bad_data', ['id' => $accountId, 'name' => $accountName]); - $result = false; + $this->sourceError = (string) trans('validation.withdrawal_source_bad_data', ['id' => $accountId, 'name' => $accountName]); + $result = false; } if (null !== $search && in_array($search->accountType->type, $validTypes, true)) { Log::debug('ID result is not null and seems valid, save as source account.'); @@ -160,9 +156,11 @@ trait DepositValidation if (null !== $accountNumber && '' !== $accountNumber) { $search = $this->accountRepository->findByAccountNumber($accountNumber, $validTypes); if (null !== $search && !in_array($search->accountType->type, $validTypes, true)) { - Log::debug( - sprintf('User submitted number ("%s"), which is a "%s", so this is not a valid source.', $accountNumber, $search->accountType->type) - ); + Log::debug(sprintf( + 'User submitted number ("%s"), which is a "%s", so this is not a valid source.', + $accountNumber, + $search->accountType->type + )); $result = false; } if (null !== $search && in_array($search->accountType->type, $validTypes, true)) { @@ -174,11 +172,11 @@ trait DepositValidation // if the account can be created anyway we don't need to search. if (null === $result && true === $this->canCreateTypes($validTypes)) { - $result = true; + $result = true; // set the source to be a (dummy) revenue account. - $account = new Account(); - $accountType = AccountType::whereType(AccountTypeEnum::REVENUE->value)->first(); + $account = new Account(); + $accountType = AccountType::whereType(AccountTypeEnum::REVENUE->value)->first(); $account->accountType = $accountType; $this->setSource($account); } diff --git a/app/Validation/Account/LiabilityValidation.php b/app/Validation/Account/LiabilityValidation.php index b66c84651b..228b9694ea 100644 --- a/app/Validation/Account/LiabilityValidation.php +++ b/app/Validation/Account/LiabilityValidation.php @@ -24,10 +24,10 @@ declare(strict_types=1); namespace FireflyIII\Validation\Account; -use Illuminate\Support\Facades\Log; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Models\Account; use FireflyIII\Models\AccountType; +use Illuminate\Support\Facades\Log; /** * Trait LiabilityValidation @@ -78,7 +78,7 @@ trait LiabilityValidation Log::debug('Now in validateLCSource', $array); // if the array has an ID and ID is not null, try to find it and check type. // this account must be a liability - $accountId = $array['id'] ?? null; + $accountId = $array['id'] ?? null; if (null !== $accountId) { Log::debug('Source ID is not null, assume were looking for a liability.'); // find liability credit: @@ -97,7 +97,7 @@ trait LiabilityValidation // if array has name and is not null, return true. $accountName = $array['name'] ?? null; - $result = true; + $result = true; if ('' === $accountName || null === $accountName) { Log::error('Array must have a name, is not the case, return false.'); $result = false; @@ -105,8 +105,8 @@ trait LiabilityValidation if ($result) { Log::error('Array has a name, return true.'); // set the source to be a (dummy) revenue account. - $account = new Account(); - $accountType = AccountType::whereType(AccountTypeEnum::LIABILITY_CREDIT->value)->first(); + $account = new Account(); + $accountType = AccountType::whereType(AccountTypeEnum::LIABILITY_CREDIT->value)->first(); $account->accountType = $accountType; $this->setSource($account); } diff --git a/app/Validation/Account/OBValidation.php b/app/Validation/Account/OBValidation.php index 39d2b5fc22..b404c9bf1a 100644 --- a/app/Validation/Account/OBValidation.php +++ b/app/Validation/Account/OBValidation.php @@ -42,13 +42,13 @@ trait OBValidation Log::debug('Now in validateOBDestination', $array); // source can be any of the following types. - $validTypes = $this->combinations[$this->transactionType][$this->source?->accountType->type] ?? []; + $validTypes = $this->combinations[$this->transactionType][$this->source?->accountType->type] ?? []; if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) { // if both values are NULL we return false, // because the destination of a deposit can't be created. $this->destError = (string) trans('validation.ob_dest_need_data'); Log::error('Both values are NULL, cant create OB destination.'); - $result = false; + $result = false; } // if the account can be created anyway we don't need to search. if (null === $result && true === $this->canCreateTypes($validTypes)) { @@ -61,8 +61,8 @@ trait OBValidation $search = $this->findExistingAccount($validTypes, $array); if (null === $search) { Log::debug('findExistingAccount() returned NULL, so the result is false.', $validTypes); - $this->destError = (string) trans('validation.ob_dest_bad_data', ['id' => $accountId, 'name' => $accountName]); - $result = false; + $this->destError = (string) trans('validation.ob_dest_bad_data', ['id' => $accountId, 'name' => $accountName]); + $result = false; } if (null !== $search) { Log::debug(sprintf('findExistingAccount() returned #%d ("%s"), so the result is true.', $search->id, $search->name)); @@ -86,16 +86,16 @@ trait OBValidation $accountId = $array['id'] ?? null; $accountName = $array['name'] ?? null; Log::debug('Now in validateOBSource', $array); - $result = null; + $result = null; // source can be any of the following types. - $validTypes = array_keys($this->combinations[$this->transactionType]); + $validTypes = array_keys($this->combinations[$this->transactionType]); if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) { // if both values are NULL return false, // because the source of a deposit can't be created. // (this never happens). $this->sourceError = (string) trans('validation.ob_source_need_data'); - $result = false; + $result = false; } // if the user submits an ID only but that ID is not of the correct type, @@ -106,10 +106,10 @@ trait OBValidation // the source resulted in an account, but it's not of a valid type. if (null !== $search && !in_array($search->accountType->type, $validTypes, true)) { - $message = sprintf('User submitted only an ID (#%d), which is a "%s", so this is not a valid source.', $accountId, $search->accountType->type); + $message = sprintf('User submitted only an ID (#%d), which is a "%s", so this is not a valid source.', $accountId, $search->accountType->type); Log::debug($message); $this->sourceError = $message; - $result = false; + $result = false; } // the source resulted in an account, AND it's of a valid type. if (null !== $search && in_array($search->accountType->type, $validTypes, true)) { @@ -122,13 +122,13 @@ trait OBValidation // if the account can be created anyway we don't need to search. if (null === $result && true === $this->canCreateTypes($validTypes)) { Log::debug('Result is still null.'); - $result = true; + $result = true; // set the source to be a (dummy) initial balance account. - $account = new Account(); + $account = new Account(); /** @var AccountType $accountType */ - $accountType = AccountType::whereType(AccountTypeEnum::INITIAL_BALANCE->value)->first(); + $accountType = AccountType::whereType(AccountTypeEnum::INITIAL_BALANCE->value)->first(); $account->accountType = $accountType; $this->setSource($account); } diff --git a/app/Validation/Account/ReconciliationValidation.php b/app/Validation/Account/ReconciliationValidation.php index fd307a05a3..08913680aa 100644 --- a/app/Validation/Account/ReconciliationValidation.php +++ b/app/Validation/Account/ReconciliationValidation.php @@ -24,16 +24,16 @@ declare(strict_types=1); namespace FireflyIII\Validation\Account; -use Illuminate\Support\Facades\Log; use FireflyIII\Models\Account; +use Illuminate\Support\Facades\Log; /** * Trait ReconciliationValidation */ trait ReconciliationValidation { - public ?Account $destination = null; - public ?Account $source = null; + public null|Account $destination = null; + public null|Account $source = null; protected function validateReconciliationDestination(array $array): bool { @@ -51,10 +51,10 @@ trait ReconciliationValidation Log::debug('Now in validateReconciliationDestination', $array); // source can be any of the following types. - $validTypes = array_keys($this->combinations[$this->transactionType]); - $search = $this->findExistingAccount($validTypes, $array); + $validTypes = array_keys($this->combinations[$this->transactionType]); + $search = $this->findExistingAccount($validTypes, $array); if (null === $search) { - $this->sourceError = (string) trans('validation.reconciliation_source_bad_data', ['id' => $accountId, 'name' => $accountName]); + $this->sourceError = (string) trans('validation.reconciliation_source_bad_data', ['id' => $accountId, 'name' => $accountName]); Log::warning('Not a valid source. Cant find it.', $validTypes); return false; @@ -86,10 +86,10 @@ trait ReconciliationValidation Log::debug('Now in validateReconciliationSource', $array); // source can be any of the following types. - $validTypes = array_keys($this->combinations[$this->transactionType]); - $search = $this->findExistingAccount($validTypes, $array); + $validTypes = array_keys($this->combinations[$this->transactionType]); + $search = $this->findExistingAccount($validTypes, $array); if (null === $search) { - $this->sourceError = (string) trans('validation.reconciliation_source_bad_data', ['id' => $accountId, 'name' => $accountName]); + $this->sourceError = (string) trans('validation.reconciliation_source_bad_data', ['id' => $accountId, 'name' => $accountName]); Log::warning('Not a valid source. Cant find it.', $validTypes); return false; diff --git a/app/Validation/Account/TransferValidation.php b/app/Validation/Account/TransferValidation.php index 6efcff3fe6..d174133eaa 100644 --- a/app/Validation/Account/TransferValidation.php +++ b/app/Validation/Account/TransferValidation.php @@ -24,8 +24,8 @@ declare(strict_types=1); namespace FireflyIII\Validation\Account; -use Illuminate\Support\Facades\Log; use FireflyIII\Models\Account; +use Illuminate\Support\Facades\Log; /** * Trait TransferValidation @@ -39,7 +39,7 @@ trait TransferValidation $accountIban = $array['iban'] ?? null; Log::debug('Now in validateTransferDestination', $array); // source can be any of the following types. - $validTypes = $this->combinations[$this->transactionType][$this->source->accountType->type] ?? []; + $validTypes = $this->combinations[$this->transactionType][$this->source->accountType->type] ?? []; if (null === $accountId && null === $accountName && null === $accountIban && false === $this->canCreateTypes($validTypes)) { // if both values are NULL we return false, // because the destination of a transfer can't be created. @@ -50,9 +50,9 @@ trait TransferValidation } // or try to find the account: - $search = $this->findExistingAccount($validTypes, $array); + $search = $this->findExistingAccount($validTypes, $array); if (null === $search) { - $this->destError = (string) trans('validation.transfer_dest_bad_data', ['id' => $accountId, 'name' => $accountName]); + $this->destError = (string) trans('validation.transfer_dest_bad_data', ['id' => $accountId, 'name' => $accountName]); return false; } @@ -61,7 +61,7 @@ trait TransferValidation // must not be the same as the source account if (null !== $this->source && $this->source->id === $this->destination->id) { $this->sourceError = 'Source and destination are the same.'; - $this->destError = 'Source and destination are the same.'; + $this->destError = 'Source and destination are the same.'; return false; } @@ -71,7 +71,7 @@ trait TransferValidation abstract protected function canCreateTypes(array $accountTypes): bool; - abstract protected function findExistingAccount(array $validTypes, array $data): ?Account; + abstract protected function findExistingAccount(array $validTypes, array $data): null|Account; protected function validateTransferSource(array $array): bool { @@ -81,10 +81,8 @@ trait TransferValidation $accountNumber = $array['number'] ?? null; Log::debug('Now in validateTransferSource', $array); // source can be any of the following types. - $validTypes = array_keys($this->combinations[$this->transactionType]); - if (null === $accountId && null === $accountName - && null === $accountIban && null === $accountNumber - && false === $this->canCreateTypes($validTypes)) { + $validTypes = array_keys($this->combinations[$this->transactionType]); + if (null === $accountId && null === $accountName && null === $accountIban && null === $accountNumber && false === $this->canCreateTypes($validTypes)) { // if both values are NULL we return false, // because the source of a withdrawal can't be created. $this->sourceError = (string) trans('validation.transfer_source_need_data'); @@ -94,9 +92,9 @@ trait TransferValidation } // otherwise try to find the account: - $search = $this->findExistingAccount($validTypes, $array); + $search = $this->findExistingAccount($validTypes, $array); if (null === $search) { - $this->sourceError = (string) trans('validation.transfer_source_bad_data', ['id' => $accountId, 'name' => $accountName]); + $this->sourceError = (string) trans('validation.transfer_source_bad_data', ['id' => $accountId, 'name' => $accountName]); Log::warning('Not a valid source, cant find it.', $validTypes); return false; diff --git a/app/Validation/Account/WithdrawalValidation.php b/app/Validation/Account/WithdrawalValidation.php index 3abd29b17b..0a9f624334 100644 --- a/app/Validation/Account/WithdrawalValidation.php +++ b/app/Validation/Account/WithdrawalValidation.php @@ -40,7 +40,13 @@ trait WithdrawalValidation $accountIban = $array['iban'] ?? null; Log::debug('Now in validateGenericSource', $array); // source can be any of the following types. - $validTypes = [AccountTypeEnum::ASSET->value, AccountTypeEnum::REVENUE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value]; + $validTypes = [ + AccountTypeEnum::ASSET->value, + AccountTypeEnum::REVENUE->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::MORTGAGE->value + ]; if (null === $accountId && null === $accountName && null === $accountIban && false === $this->canCreateTypes($validTypes)) { // if both values are NULL we return TRUE // because we assume the user doesn't want to submit / change anything. @@ -51,9 +57,9 @@ trait WithdrawalValidation } // otherwise try to find the account: - $search = $this->findExistingAccount($validTypes, $array); + $search = $this->findExistingAccount($validTypes, $array); if (null === $search) { - $this->sourceError = (string) trans('validation.withdrawal_source_bad_data', ['id' => $accountId, 'name' => $accountName]); + $this->sourceError = (string) trans('validation.withdrawal_source_bad_data', ['id' => $accountId, 'name' => $accountName]); Log::warning('Not a valid source. Cant find it.', $validTypes); return false; @@ -66,7 +72,7 @@ trait WithdrawalValidation abstract protected function canCreateTypes(array $accountTypes): bool; - abstract protected function findExistingAccount(array $validTypes, array $data): ?Account; + abstract protected function findExistingAccount(array $validTypes, array $data): null|Account; protected function validateWithdrawalDestination(array $array): bool { @@ -76,7 +82,7 @@ trait WithdrawalValidation $accountNumber = $array['number'] ?? null; Log::debug('Now in validateWithdrawalDestination()', $array); // source can be any of the following types. - $validTypes = $this->combinations[$this->transactionType][$this->source->accountType->type] ?? []; + $validTypes = $this->combinations[$this->transactionType][$this->source->accountType->type] ?? []; Log::debug('Source type can be: ', $validTypes); if (null === $accountId && null === $accountName && null === $accountIban && null === $accountNumber && false === $this->canCreateTypes($validTypes)) { // if both values are NULL return false, @@ -90,14 +96,14 @@ trait WithdrawalValidation if (null !== $accountId && 0 !== $accountId && $accountId !== $this->source->id) { $found = $this->accountRepository->find($accountId); if (null !== $found) { - $type = $found->accountType->type; + $type = $found->accountType->type; if (in_array($type, $validTypes, true)) { $this->setDestination($found); return true; } // todo explain error in log message. - $this->destError = (string) trans('validation.withdrawal_dest_bad_data', ['id' => $accountId, 'name' => $accountName]); + $this->destError = (string) trans('validation.withdrawal_dest_bad_data', ['id' => $accountId, 'name' => $accountName]); return false; } @@ -128,7 +134,7 @@ trait WithdrawalValidation Log::debug('Now in validateWithdrawalSource', $array); // source can be any of the following types. - $validTypes = array_keys($this->combinations[$this->transactionType]); + $validTypes = array_keys($this->combinations[$this->transactionType]); if (null === $accountId && null === $accountName && null === $accountNumber && null === $accountIban && false === $this->canCreateTypes($validTypes)) { // if both values are NULL we return false, // because the source of a withdrawal can't be created. @@ -139,9 +145,9 @@ trait WithdrawalValidation } // otherwise try to find the account: - $search = $this->findExistingAccount($validTypes, $array); + $search = $this->findExistingAccount($validTypes, $array); if (null === $search) { - $this->sourceError = (string) trans('validation.withdrawal_source_bad_data', ['id' => $accountId, 'name' => $accountName]); + $this->sourceError = (string) trans('validation.withdrawal_source_bad_data', ['id' => $accountId, 'name' => $accountName]); Log::warning('Not a valid source. Cant find it.', $validTypes); return false; diff --git a/app/Validation/AccountValidator.php b/app/Validation/AccountValidator.php index f79768aba0..403db6612b 100644 --- a/app/Validation/AccountValidator.php +++ b/app/Validation/AccountValidator.php @@ -50,30 +50,30 @@ class AccountValidator use TransferValidation; use WithdrawalValidation; - public bool $createMode = false; - public string $destError = 'No error yet.'; - public ?Account $destination = null; - public ?Account $source = null; - public string $sourceError = 'No error yet.'; + public bool $createMode = false; + public string $destError = 'No error yet.'; + public null|Account $destination = null; + public null|Account $source = null; + public string $sourceError = 'No error yet.'; private AccountRepositoryInterface $accountRepository; - private array $combinations; - private string $transactionType; + private array $combinations; + private string $transactionType; /** * AccountValidator constructor. */ public function __construct() { - $this->combinations = config('firefly.source_dests'); + $this->combinations = config('firefly.source_dests'); $this->accountRepository = app(AccountRepositoryInterface::class); } - public function getSource(): ?Account + public function getSource(): null|Account { return $this->source; } - public function setSource(?Account $account): void + public function setSource(null|Account $account): void { if (!$account instanceof Account) { Log::debug('AccountValidator source is set to NULL'); @@ -84,7 +84,7 @@ class AccountValidator $this->source = $account; } - public function setDestination(?Account $account): void + public function setDestination(null|Account $account): void { if (!$account instanceof Account) { Log::debug('AccountValidator destination is set to NULL'); @@ -126,37 +126,37 @@ class AccountValidator $this->destError = sprintf('AccountValidator::validateDestination cannot handle "%s", so it will always return false.', $this->transactionType); Log::error(sprintf('AccountValidator::validateDestination cannot handle "%s", so it will always return false.', $this->transactionType)); - $result = false; + $result = false; break; case TransactionTypeEnum::WITHDRAWAL->value: - $result = $this->validateWithdrawalDestination($array); + $result = $this->validateWithdrawalDestination($array); break; case TransactionTypeEnum::DEPOSIT->value: - $result = $this->validateDepositDestination($array); + $result = $this->validateDepositDestination($array); break; case TransactionTypeEnum::TRANSFER->value: - $result = $this->validateTransferDestination($array); + $result = $this->validateTransferDestination($array); break; case TransactionTypeEnum::OPENING_BALANCE->value: - $result = $this->validateOBDestination($array); + $result = $this->validateOBDestination($array); break; case TransactionTypeEnum::LIABILITY_CREDIT->value: - $result = $this->validateLCDestination($array); + $result = $this->validateLCDestination($array); break; case TransactionTypeEnum::RECONCILIATION->value: - $result = $this->validateReconciliationDestination($array); + $result = $this->validateReconciliationDestination($array); break; } @@ -229,7 +229,12 @@ class AccountValidator protected function canCreateType(string $accountType): bool { - $canCreate = [AccountTypeEnum::EXPENSE->value, AccountTypeEnum::REVENUE->value, AccountTypeEnum::INITIAL_BALANCE->value, AccountTypeEnum::LIABILITY_CREDIT->value]; + $canCreate = [ + AccountTypeEnum::EXPENSE->value, + AccountTypeEnum::REVENUE->value, + AccountTypeEnum::INITIAL_BALANCE->value, + AccountTypeEnum::LIABILITY_CREDIT->value + ]; return in_array($accountType, $canCreate, true); } @@ -241,7 +246,7 @@ class AccountValidator * @SuppressWarnings("PHPMD.BooleanArgumentFlag") * @SuppressWarnings("PHPMD.NPathComplexity") */ - protected function findExistingAccount(array $validTypes, array $data, bool $inverse = false): ?Account + protected function findExistingAccount(array $validTypes, array $data, bool $inverse = false): null|Account { Log::debug('Now in findExistingAccount', [$validTypes, $data]); Log::debug('The search will be reversed!'); @@ -256,8 +261,14 @@ class AccountValidator $accountType = $first instanceof Account ? $first->accountType->type : 'invalid'; $check = in_array($accountType, $validTypes, true); $check = $inverse ? !$check : $check; // reverse the validation check if necessary. - if (($first instanceof Account) && $check) { - Log::debug(sprintf('ID: Found %s account #%d ("%s", IBAN "%s")', $first->accountType->type, $first->id, $first->name, $first->iban ?? 'no iban')); + if ($first instanceof Account && $check) { + Log::debug(sprintf( + 'ID: Found %s account #%d ("%s", IBAN "%s")', + $first->accountType->type, + $first->id, + $first->name, + $first->iban ?? 'no iban' + )); return $first; } @@ -269,8 +280,14 @@ class AccountValidator $accountType = $first instanceof Account ? $first->accountType->type : 'invalid'; $check = in_array($accountType, $validTypes, true); $check = $inverse ? !$check : $check; // reverse the validation check if necessary. - if (($first instanceof Account) && $check) { - Log::debug(sprintf('Iban: Found %s account #%d ("%s", IBAN "%s")', $first->accountType->type, $first->id, $first->name, $first->iban ?? 'no iban')); + if ($first instanceof Account && $check) { + Log::debug(sprintf( + 'Iban: Found %s account #%d ("%s", IBAN "%s")', + $first->accountType->type, + $first->id, + $first->name, + $first->iban ?? 'no iban' + )); return $first; } @@ -282,8 +299,14 @@ class AccountValidator $accountType = $first instanceof Account ? $first->accountType->type : 'invalid'; $check = in_array($accountType, $validTypes, true); $check = $inverse ? !$check : $check; // reverse the validation check if necessary. - if (($first instanceof Account) && $check) { - Log::debug(sprintf('Number: Found %s account #%d ("%s", IBAN "%s")', $first->accountType->type, $first->id, $first->name, $first->iban ?? 'no iban')); + if ($first instanceof Account && $check) { + Log::debug(sprintf( + 'Number: Found %s account #%d ("%s", IBAN "%s")', + $first->accountType->type, + $first->id, + $first->name, + $first->iban ?? 'no iban' + )); return $first; } @@ -293,7 +316,13 @@ class AccountValidator if ('' !== (string) $accountName) { $first = $this->accountRepository->findByName($accountName, $validTypes); if ($first instanceof Account) { - Log::debug(sprintf('Name: Found %s account #%d ("%s", IBAN "%s")', $first->accountType->type, $first->id, $first->name, $first->iban ?? 'no iban')); + Log::debug(sprintf( + 'Name: Found %s account #%d ("%s", IBAN "%s")', + $first->accountType->type, + $first->id, + $first->name, + $first->iban ?? 'no iban' + )); return $first; } diff --git a/app/Validation/Api/Data/Bulk/ValidatesBulkTransactionQuery.php b/app/Validation/Api/Data/Bulk/ValidatesBulkTransactionQuery.php index 89ea275b39..52812f9b1f 100644 --- a/app/Validation/Api/Data/Bulk/ValidatesBulkTransactionQuery.php +++ b/app/Validation/Api/Data/Bulk/ValidatesBulkTransactionQuery.php @@ -24,8 +24,8 @@ declare(strict_types=1); namespace FireflyIII\Validation\Api\Data\Bulk; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Repositories\Account\AccountRepositoryInterface; +use Illuminate\Contracts\Validation\Validator; use function Safe\json_decode; @@ -33,7 +33,7 @@ trait ValidatesBulkTransactionQuery { protected function validateTransactionQuery(Validator $validator): void { - $data = $validator->getData(); + $data = $validator->getData(); // assumption is all validation has already taken place and the query key exists. $query = $data['query'] ?? '[]'; $json = json_decode($query, true, 8, JSON_THROW_ON_ERROR); @@ -41,13 +41,14 @@ trait ValidatesBulkTransactionQuery if ( array_key_exists('where', $json) && array_key_exists('update', $json) - && array_key_exists('account_id', $json['where']) && array_key_exists('account_id', $json['update']) + && array_key_exists('account_id', $json['where']) + && array_key_exists('account_id', $json['update']) ) { // find both accounts, must be same type. // already validated: belongs to this user. - $repository = app(AccountRepositoryInterface::class); - $source = $repository->find((int) $json['where']['account_id']); - $dest = $repository->find((int) $json['update']['account_id']); + $repository = app(AccountRepositoryInterface::class); + $source = $repository->find((int) $json['where']['account_id']); + $dest = $repository->find((int) $json['update']['account_id']); if (null === $source) { $validator->errors()->add('query', sprintf((string) trans('validation.invalid_query_data'), 'where', 'account_id')); @@ -68,11 +69,7 @@ trait ValidatesBulkTransactionQuery // some account types (like expenses) do not have currency, so they have to be omitted $sourceCurrency = $repository->getAccountCurrency($source); $destCurrency = $repository->getAccountCurrency($dest); - if ( - null !== $sourceCurrency - && null !== $destCurrency - && $sourceCurrency->id !== $destCurrency->id - ) { + if (null !== $sourceCurrency && null !== $destCurrency && $sourceCurrency->id !== $destCurrency->id) { $validator->errors()->add('query', (string) trans('validation.invalid_query_currency')); } } diff --git a/app/Validation/AutoBudget/ValidatesAutoBudgetRequest.php b/app/Validation/AutoBudget/ValidatesAutoBudgetRequest.php index 28bad253e3..dcbffa2545 100644 --- a/app/Validation/AutoBudget/ValidatesAutoBudgetRequest.php +++ b/app/Validation/AutoBudget/ValidatesAutoBudgetRequest.php @@ -36,8 +36,8 @@ trait ValidatesAutoBudgetRequest */ protected function validateAutoBudgetAmount(Validator $validator): void { - $data = $validator->getData(); - $type = $data['auto_budget_type'] ?? ''; + $data = $validator->getData(); + $type = $data['auto_budget_type'] ?? ''; /** @var null|float|int|string $amount */ $amount = $data['auto_budget_amount'] ?? null; diff --git a/app/Validation/CurrencyValidation.php b/app/Validation/CurrencyValidation.php index 3409114cb6..4e312f4bf2 100644 --- a/app/Validation/CurrencyValidation.php +++ b/app/Validation/CurrencyValidation.php @@ -52,7 +52,11 @@ trait CurrencyValidation continue; } - if (!array_key_exists('foreign_amount', $transaction) && !array_key_exists('foreign_currency_id', $transaction) && !array_key_exists('foreign_currency_code', $transaction)) { + if ( + !array_key_exists('foreign_amount', $transaction) + && !array_key_exists('foreign_currency_id', $transaction) + && !array_key_exists('foreign_currency_code', $transaction) + ) { Log::debug('validateForeignCurrencyInformation: no foreign currency information present at all.'); continue; @@ -66,27 +70,27 @@ trait CurrencyValidation (array_key_exists('foreign_currency_id', $transaction) || array_key_exists('foreign_currency_code', $transaction)) && (null !== $foreignId || null !== $foreignCode) ) { - $validator->errors()->add('transactions.'.$index.'.foreign_amount', (string) trans('validation.require_currency_amount')); - $validator->errors()->add('transactions.'.$index.'.foreign_currency_id', (string) trans('validation.require_currency_amount')); - $validator->errors()->add('transactions.'.$index.'.foreign_currency_code', (string) trans('validation.require_currency_amount')); + $validator->errors()->add('transactions.' . $index . '.foreign_amount', (string) trans('validation.require_currency_amount')); + $validator->errors()->add('transactions.' . $index . '.foreign_currency_id', (string) trans('validation.require_currency_amount')); + $validator->errors()->add('transactions.' . $index . '.foreign_currency_code', (string) trans('validation.require_currency_amount')); } continue; } - $compare = bccomp('0', $foreignAmount); + $compare = bccomp('0', $foreignAmount); if (-1 === $compare) { Log::debug('validateForeignCurrencyInformation: array contains foreign amount info.'); if (!array_key_exists('foreign_currency_id', $transaction) && !array_key_exists('foreign_currency_code', $transaction)) { Log::debug('validateForeignCurrencyInformation: array contains NO foreign currency info.'); - $validator->errors()->add('transactions.'.$index.'.foreign_amount', (string) trans('validation.require_currency_info')); + $validator->errors()->add('transactions.' . $index . '.foreign_amount', (string) trans('validation.require_currency_info')); } } if (0 === $compare && ('' !== (string) $foreignId || '' !== (string) $foreignCode)) { Log::debug('validateForeignCurrencyInformation: array contains foreign currency info, but zero amount.'); - $validator->errors()->add('transactions.'.$index.'.foreign_currency_id', (string) trans('validation.require_currency_amount')); - $validator->errors()->add('transactions.'.$index.'.foreign_currency_code', (string) trans('validation.require_currency_amount')); - $validator->errors()->add('transactions.'.$index.'.foreign_amount', (string) trans('validation.require_currency_amount')); + $validator->errors()->add('transactions.' . $index . '.foreign_currency_id', (string) trans('validation.require_currency_amount')); + $validator->errors()->add('transactions.' . $index . '.foreign_currency_code', (string) trans('validation.require_currency_amount')); + $validator->errors()->add('transactions.' . $index . '.foreign_amount', (string) trans('validation.require_currency_amount')); } } } diff --git a/app/Validation/FireflyValidator.php b/app/Validation/FireflyValidator.php index 804b6f0fdd..5bdbe629b9 100644 --- a/app/Validation/FireflyValidator.php +++ b/app/Validation/FireflyValidator.php @@ -23,9 +23,8 @@ declare(strict_types=1); namespace FireflyIII\Validation; -use ErrorException; -use FireflyIII\Support\Facades\Preferences; use Config; +use ErrorException; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Account; @@ -39,6 +38,7 @@ use FireflyIII\Repositories\Bill\BillRepositoryInterface; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface; use FireflyIII\Services\Password\Verifier; +use FireflyIII\Support\Facades\Preferences; use FireflyIII\Support\ParseDateString; use FireflyIII\User; use Illuminate\Support\Facades\DB; @@ -80,7 +80,7 @@ class FireflyValidator extends Validator if (!is_string($value) || 6 !== strlen($value)) { return false; } - $user = auth()->user(); + $user = auth()->user(); if (null === $user) { Log::error('No user during validate2faCode'); @@ -91,7 +91,7 @@ class FireflyValidator extends Validator if (is_array($secret)) { $secret = ''; } - $secret = (string) $secret; + $secret = (string) $secret; return (bool) Facade::verifyKey($secret, $value); } @@ -110,7 +110,10 @@ class FireflyValidator extends Validator if (0 === (int) $value) { return true; } - $count = DB::table($parameters[0])->where('user_id', auth()->user()->id)->where($field, $value)->count(); + $count = DB::table($parameters[0]) + ->where('user_id', auth()->user()->id) + ->where($field, $value) + ->count(); return 1 === $count; } @@ -134,7 +137,7 @@ class FireflyValidator extends Validator if (!is_string($value) || 6 !== strlen($value)) { return false; } - $user = auth()->user(); + $user = auth()->user(); if (null === $user) { Log::error('No user during validate2faCode'); @@ -204,7 +207,7 @@ class FireflyValidator extends Validator "\u{FEFF}", // zero width no -break space ' ', '-', - '?', + '?' ]; $replace = ''; $value = str_replace($search, $replace, $value); @@ -218,13 +221,41 @@ class FireflyValidator extends Validator Log::error($e->getMessage()); } $search = [' ', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']; - $replace = ['', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35']; + $replace = [ + '', + '10', + '11', + '12', + '13', + '14', + '15', + '16', + '17', + '18', + '19', + '20', + '21', + '22', + '23', + '24', + '25', + '26', + '27', + '28', + '29', + '30', + '31', + '32', + '33', + '34', + '35' + ]; // take - $first = substr($value, 0, 4); - $last = substr($value, 4); - $iban = $last.$first; - $iban = trim(str_replace($search, $replace, $iban)); + $first = substr($value, 0, 4); + $last = substr($value, 4); + $iban = $last . $first; + $iban = trim(str_replace($search, $replace, $iban)); if ('' === $iban) { return false; } @@ -291,12 +322,12 @@ class FireflyValidator extends Validator return 1 === $count; } - public function validateRuleActionValue(string $attribute, ?string $value = null): bool + public function validateRuleActionValue(string $attribute, null|string $value = null): bool { // first, get the index from this string: $value ??= ''; - $parts = explode('.', $attribute); - $index = (int) ($parts[1] ?? '0'); + $parts = explode('.', $attribute); + $index = (int) ($parts[1] ?? '0'); // get the name of the trigger from the data array: $actionType = $this->data['actions'][$index]['type'] ?? 'invalid'; @@ -332,17 +363,14 @@ class FireflyValidator extends Validator if ('convert_transfer' === $actionType) { /** @var AccountRepositoryInterface $repository */ $repository = app(AccountRepositoryInterface::class); - $account = $repository->findByName( - $value, - [ - AccountTypeEnum::DEFAULT->value, - AccountTypeEnum::ASSET->value, - AccountTypeEnum::LOAN->value, - AccountTypeEnum::DEBT->value, - AccountTypeEnum::MORTGAGE->value, - AccountTypeEnum::CREDITCARD->value, - ] - ); + $account = $repository->findByName($value, [ + AccountTypeEnum::DEFAULT->value, + AccountTypeEnum::ASSET->value, + AccountTypeEnum::LOAN->value, + AccountTypeEnum::DEBT->value, + AccountTypeEnum::MORTGAGE->value, + AccountTypeEnum::CREDITCARD->value + ]); return null !== $account; } @@ -362,11 +390,11 @@ class FireflyValidator extends Validator /** * $attribute has the format triggers.%d.value. */ - public function validateRuleTriggerValue(string $attribute, ?string $value = null): bool + public function validateRuleTriggerValue(string $attribute, null|string $value = null): bool { // first, get the index from this string: - $parts = explode('.', $attribute); - $index = (int) ($parts[1] ?? '0'); + $parts = explode('.', $attribute); + $index = (int) ($parts[1] ?? '0'); // get the name of the trigger from the data array: $triggerType = $this->data['triggers'][$index]['type'] ?? 'invalid'; @@ -377,21 +405,35 @@ class FireflyValidator extends Validator } // these trigger types need a numerical check: - $numerical = ['amount_less', 'amount_more', 'amount_exactly']; + $numerical = ['amount_less', 'amount_more', 'amount_exactly']; if (in_array($triggerType, $numerical, true)) { return is_numeric($value); } // these triggers need just the word "true": // TODO create a helper to automatically return these. - $needTrue = [ - 'reconciled', 'has_attachments', 'has_any_category', 'has_any_budget', 'has_any_bill', 'has_any_tag', 'any_notes', 'any_external_url', 'has_no_attachments', 'has_no_category', 'has_no_budget', 'has_no_bill', 'has_no_tag', 'no_notes', 'no_external_url', + $needTrue = [ + 'reconciled', + 'has_attachments', + 'has_any_category', + 'has_any_budget', + 'has_any_bill', + 'has_any_tag', + 'any_notes', + 'any_external_url', + 'has_no_attachments', + 'has_no_category', + 'has_no_budget', + 'has_no_bill', + 'has_no_tag', + 'no_notes', + 'no_external_url', 'source_is_cash', 'destination_is_cash', 'account_is_cash', 'exists', 'no_external_id', - 'any_external_id', + 'any_external_id' ]; if (in_array($triggerType, $needTrue, true)) { return 'true' === $value; @@ -399,7 +441,7 @@ class FireflyValidator extends Validator // these trigger types need a simple strlen check: // TODO create a helper to automatically return these. - $length = [ + $length = [ 'source_account_starts', 'source_account_ends', 'source_account_is', @@ -419,7 +461,7 @@ class FireflyValidator extends Validator 'notes_contain', 'notes_start', 'notes_end', - 'notes_are', + 'notes_are' ]; if (in_array($triggerType, $length, true)) { return '' !== $value; @@ -463,9 +505,9 @@ class FireflyValidator extends Validator * * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function validateSecurePassword($attribute, ?string $value): bool + public function validateSecurePassword($attribute, null|string $value): bool { - $value = (string)$value; + $value = (string) $value; $verify = false; if (array_key_exists('verify_password', $this->data)) { $verify = 1 === (int) $this->data['verify_password']; @@ -540,9 +582,9 @@ class FireflyValidator extends Validator } /** @var User $user */ - $user = User::find($this->data['user_id']); - $type = AccountType::find($this->data['account_type_id'])->first(); - $value = $this->data['name']; + $user = User::find($this->data['user_id']); + $type = AccountType::find($this->data['account_type_id'])->first(); + $value = $this->data['name']; /** @var null|Account $result */ $result = $user->accounts()->where('account_type_id', $type->id)->where('name', $value)->first(); @@ -553,7 +595,7 @@ class FireflyValidator extends Validator private function validateByAccountTypeString(string $value, array $parameters, string $type): bool { /** @var null|array $search */ - $search = Config::get('firefly.accountTypeByIdentifier.'.$type); + $search = Config::get('firefly.accountTypeByIdentifier.' . $type); if (null === $search) { return false; @@ -564,10 +606,7 @@ class FireflyValidator extends Validator $accountTypeIds = $accountTypes->pluck('id')->toArray(); /** @var null|Account $result */ - $result = auth()->user()->accounts()->whereIn('account_type_id', $accountTypeIds)->where('id', '!=', $ignore) - ->where('name', $value) - ->first() - ; + $result = auth()->user()->accounts()->whereIn('account_type_id', $accountTypeIds)->where('id', '!=', $ignore)->where('name', $value)->first(); return null === $result; } @@ -582,10 +621,7 @@ class FireflyValidator extends Validator $ignore = (int) ($parameters[0] ?? 0.0); /** @var null|Account $result */ - $result = auth()->user()->accounts()->where('account_type_id', $type->id)->where('id', '!=', $ignore) - ->where('name', $value) - ->first() - ; + $result = auth()->user()->accounts()->where('account_type_id', $type->id)->where('id', '!=', $ignore)->where('name', $value)->first(); return null === $result; } @@ -598,13 +634,10 @@ class FireflyValidator extends Validator /** @var Account $existingAccount */ $existingAccount = Account::find($accountId); - $type = $existingAccount->accountType; - $ignore = $existingAccount->id; + $type = $existingAccount->accountType; + $ignore = $existingAccount->id; - $entry = auth()->user()->accounts()->where('account_type_id', $type->id)->where('id', '!=', $ignore) - ->where('name', $value) - ->first() - ; + $entry = auth()->user()->accounts()->where('account_type_id', $type->id)->where('id', '!=', $ignore)->where('name', $value)->first(); return null === $entry; } @@ -617,13 +650,10 @@ class FireflyValidator extends Validator /** @var Account $existingAccount */ $existingAccount = Account::find($this->data['id']); - $type = $existingAccount->accountType; - $ignore = $existingAccount->id; + $type = $existingAccount->accountType; + $ignore = $existingAccount->id; - $entry = auth()->user()->accounts()->where('account_type_id', $type->id)->where('id', '!=', $ignore) - ->where('name', $value) - ->first() - ; + $entry = auth()->user()->accounts()->where('account_type_id', $type->id)->where('id', '!=', $ignore)->where('name', $value)->first(); return null === $entry; } @@ -649,19 +679,18 @@ class FireflyValidator extends Validator $accountId = (int) ($parameters[0] ?? 0.0); } - $query = AccountMeta::leftJoin('accounts', 'accounts.id', '=', 'account_meta.account_id') + $query = AccountMeta::leftJoin('accounts', 'accounts.id', '=', 'account_meta.account_id') ->whereNull('accounts.deleted_at') ->where('accounts.user_id', auth()->user()->id) ->where('account_meta.name', 'account_number') - ->where('account_meta.data', json_encode($value)) - ; + ->where('account_meta.data', json_encode($value)); if ($accountId > 0) { // exclude current account from check. $query->where('account_meta.account_id', '!=', $accountId); } - $set = $query->get(['account_meta.*']); - $count = $set->count(); + $set = $query->get(['account_meta.*']); + $count = $set->count(); if (0 === $count) { return true; } @@ -669,7 +698,7 @@ class FireflyValidator extends Validator // pretty much impossible but still. return false; } - $type = $this->data['objectType'] ?? 'unknown'; + $type = $this->data['objectType'] ?? 'unknown'; if ('expense' !== $type && 'revenue' !== $type) { Log::warning(sprintf('Account number "%s" is not unique and account type "%s" cannot share its account number.', $value, $type)); @@ -696,7 +725,7 @@ class FireflyValidator extends Validator /** * @SuppressWarnings("PHPMD.UnusedFormalParameter") */ - public function validateUniqueCurrencyCode(?string $attribute, ?string $value): bool + public function validateUniqueCurrencyCode(null|string $attribute, null|string $value): bool { return $this->validateUniqueCurrency('code', (string) $attribute, (string) $value); } @@ -706,15 +735,18 @@ class FireflyValidator extends Validator */ public function validateUniqueCurrency(string $field, string $attribute, string $value): bool { - return 0 === DB::table('transaction_currencies')->where($field, $value)->whereNull('deleted_at')->count(); + return 0 === DB::table('transaction_currencies') + ->where($field, $value) + ->whereNull('deleted_at') + ->count(); } - public function validateUniqueCurrencyName(?string $attribute, ?string $value): bool + public function validateUniqueCurrencyName(null|string $attribute, null|string $value): bool { return $this->validateUniqueCurrency('name', (string) $attribute, (string) $value); } - public function validateUniqueCurrencySymbol(?string $attribute, ?string $value): bool + public function validateUniqueCurrencySymbol(null|string $attribute, null|string $value): bool { return $this->validateUniqueCurrency('symbol', (string) $attribute, (string) $value); } @@ -739,7 +771,7 @@ class FireflyValidator extends Validator // get existing webhook value: if (0 !== $existingId) { /** @var null|Webhook $webhook */ - $webhook = auth()->user()->webhooks()->find($existingId); + $webhook = auth()->user()->webhooks()->find($existingId); if (null === $webhook) { return false; } @@ -761,8 +793,8 @@ class FireflyValidator extends Validator ->where('response', $response) ->where('delivery', $delivery) ->where('id', '!=', $existingId) - ->where('url', $url)->count() - ; + ->where('url', $url) + ->count(); } return false; @@ -784,22 +816,23 @@ class FireflyValidator extends Validator public function validateUniqueObjectForUser($attribute, $value, $parameters): bool { [$table, $field] = $parameters; - $exclude = (int) ($parameters[2] ?? 0.0); + $exclude = (int) ($parameters[2] ?? 0.0); /* * If other data (in $this->getData()) contains * ID field, set that field to be the $exclude. */ - $data = $this->getData(); + $data = $this->getData(); if (!array_key_exists(2, $parameters) && array_key_exists('id', $data) && (int) $data['id'] > 0) { $exclude = (int) $data['id']; } // get entries from table - $result = DB::table($table)->where('user_id', auth()->user()->id)->whereNull('deleted_at') + $result = DB::table($table) + ->where('user_id', auth()->user()->id) + ->whereNull('deleted_at') ->where('id', '!=', $exclude) ->where($field, $value) - ->first([$field]) - ; + ->first([$field]); if (null === $result) { return true; // not found, so true. } @@ -821,8 +854,7 @@ class FireflyValidator extends Validator $query = DB::table('object_groups') ->whereNull('object_groups.deleted_at') ->where('object_groups.user_id', auth()->user()->id) - ->where('object_groups.title', $value) - ; + ->where('object_groups.title', $value); if (null !== $exclude) { $query->where('object_groups.id', '!=', (int) $exclude); } @@ -842,8 +874,7 @@ class FireflyValidator extends Validator $exclude = $parameters[0] ?? null; $query = PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id') ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id') - ->where('accounts.user_id', auth()->user()->id) - ; + ->where('accounts.user_id', auth()->user()->id); if (null !== $exclude) { $query->where('piggy_banks.id', '!=', (int) $exclude); } @@ -866,18 +897,18 @@ class FireflyValidator extends Validator $deliveries = Webhook::getDeliveriesForValidation(); // integers - $trigger = $triggers[$this->data['trigger']] ?? 0; - $response = $responses[$this->data['response']] ?? 0; - $delivery = $deliveries[$this->data['delivery']] ?? 0; - $url = $this->data['url']; - $userId = auth()->user()->id; + $trigger = $triggers[$this->data['trigger']] ?? 0; + $response = $responses[$this->data['response']] ?? 0; + $delivery = $deliveries[$this->data['delivery']] ?? 0; + $url = $this->data['url']; + $userId = auth()->user()->id; return 0 === Webhook::whereUserId($userId) ->where('trigger', $trigger) ->where('response', $response) ->where('delivery', $delivery) - ->where('url', $url)->count() - ; + ->where('url', $url) + ->count(); } return false; diff --git a/app/Validation/GroupValidation.php b/app/Validation/GroupValidation.php index 61acde4f07..11dfba4b42 100644 --- a/app/Validation/GroupValidation.php +++ b/app/Validation/GroupValidation.php @@ -24,11 +24,11 @@ declare(strict_types=1); namespace FireflyIII\Validation; -use Illuminate\Support\Facades\Log; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Transaction; use FireflyIII\Models\TransactionGroup; +use Illuminate\Contracts\Validation\Validator; +use Illuminate\Support\Facades\Log; /** * Trait GroupValidation. @@ -56,7 +56,7 @@ trait GroupValidation 'source_iban', 'destination_iban', 'source_number', - 'destination_number', + 'destination_number' ]; /** @var null|array $transaction */ @@ -73,16 +73,11 @@ trait GroupValidation } // set errors: if (false === $hasAccountInfo && !$hasJournalId) { - $validator->errors()->add( - sprintf('transactions.%d.source_id', $index), - (string) trans('validation.generic_no_source') - ); - $validator->errors()->add( - sprintf('transactions.%d.destination_id', $index), - (string) trans('validation.generic_no_destination') - ); + $validator->errors()->add(sprintf('transactions.%d.source_id', $index), (string) trans('validation.generic_no_source')); + $validator->errors()->add(sprintf('transactions.%d.destination_id', $index), (string) trans('validation.generic_no_destination')); } } + // only an issue if there is no transaction_journal_id } @@ -92,20 +87,33 @@ trait GroupValidation { Log::debug(sprintf('Now in %s', __METHOD__)); - $count = Transaction::leftJoin('transaction_journals', 'transaction_journals.id', 'transactions.transaction_journal_id') + $count = Transaction::leftJoin('transaction_journals', 'transaction_journals.id', 'transactions.transaction_journal_id') ->leftJoin('transaction_groups', 'transaction_groups.id', 'transaction_journals.transaction_group_id') ->where('transaction_journals.transaction_group_id', $transactionGroup->id) - ->where('transactions.reconciled', 1)->where('transactions.amount', '<', 0)->count('transactions.id') - ; + ->where('transactions.reconciled', 1) + ->where('transactions.amount', '<', 0) + ->count('transactions.id'); if (0 === $count) { Log::debug(sprintf('Transaction is not reconciled, done with %s', __METHOD__)); return; } $data = $validator->getData(); - $forbidden = ['amount', 'foreign_amount', 'currency_code', 'currency_id', 'foreign_currency_code', 'foreign_currency_id', - 'source_id', 'source_name', 'source_number', 'source_iban', - 'destination_id', 'destination_name', 'destination_number', 'destination_iban', + $forbidden = [ + 'amount', + 'foreign_amount', + 'currency_code', + 'currency_id', + 'foreign_currency_code', + 'foreign_currency_id', + 'source_id', + 'source_name', + 'source_number', + 'source_iban', + 'destination_id', + 'destination_name', + 'destination_number', + 'destination_iban' ]; // stop protesting when reconciliation is set to FALSE. @@ -163,7 +171,7 @@ trait GroupValidation $data = $validator->getData(); $transactions = $this->getTransactionsArray($validator); - $groupTitle = $data['group_title'] ?? ''; + $groupTitle = $data['group_title'] ?? ''; if ('' === $groupTitle && count($transactions) > 1) { $validator->errors()->add('group_title', (string) trans('validation.group_title_mandatory')); } diff --git a/app/Validation/RecurrenceValidation.php b/app/Validation/RecurrenceValidation.php index a76bd8b19a..90d430b476 100644 --- a/app/Validation/RecurrenceValidation.php +++ b/app/Validation/RecurrenceValidation.php @@ -24,11 +24,11 @@ declare(strict_types=1); namespace FireflyIII\Validation; -use Illuminate\Support\Facades\Log; -use Illuminate\Contracts\Validation\Validator; use Carbon\Carbon; use FireflyIII\Models\Recurrence; use FireflyIII\Models\RecurrenceTransaction; +use Illuminate\Contracts\Validation\Validator; +use Illuminate\Support\Facades\Log; use InvalidArgumentException; /** @@ -45,9 +45,9 @@ trait RecurrenceValidation */ public function valUpdateAccountInfo(Validator $validator): void { - $data = $validator->getData(); + $data = $validator->getData(); - $transactionType = $data['type'] ?? 'invalid'; + $transactionType = $data['type'] ?? 'invalid'; // grab model from parameter and try to set the transaction type from it if ('invalid' === $transactionType) { @@ -72,14 +72,14 @@ trait RecurrenceValidation } } - $transactions = $data['transactions'] ?? []; + $transactions = $data['transactions'] ?? []; /** @var AccountValidator $accountValidator */ $accountValidator = app(AccountValidator::class); Log::debug(sprintf('Going to loop %d transaction(s)', count($transactions))); foreach ($transactions as $index => $transaction) { - $transactionType = $transaction['type'] ?? $transactionType; + $transactionType = $transaction['type'] ?? $transactionType; $accountValidator->setTransactionType($transactionType); if ( @@ -91,9 +91,9 @@ trait RecurrenceValidation continue; } // validate source account. - $sourceId = array_key_exists('source_id', $transaction) ? (int) $transaction['source_id'] : null; - $sourceName = $transaction['source_name'] ?? null; - $validSource = $accountValidator->validateSource(['id' => $sourceId, 'name' => $sourceName]); + $sourceId = array_key_exists('source_id', $transaction) ? (int) $transaction['source_id'] : null; + $sourceName = $transaction['source_name'] ?? null; + $validSource = $accountValidator->validateSource(['id' => $sourceId, 'name' => $sourceName]); // do something with result: if (false === $validSource) { @@ -105,7 +105,7 @@ trait RecurrenceValidation // validate destination account $destinationId = array_key_exists('destination_id', $transaction) ? (int) $transaction['destination_id'] : null; $destinationName = $transaction['destination_name'] ?? null; - $validDestination = $accountValidator->validateDestination(['id' => $destinationId, 'name' => $destinationName]); + $validDestination = $accountValidator->validateDestination(['id' => $destinationId, 'name' => $destinationName]); // do something with result: if (false === $validDestination) { $validator->errors()->add(sprintf('transactions.%d.destination_id', $index), $accountValidator->destError); @@ -267,8 +267,8 @@ trait RecurrenceValidation return; } - $nthDay = (int) $parameters[0]; - $dayOfWeek = (int) $parameters[1]; + $nthDay = (int) $parameters[0]; + $dayOfWeek = (int) $parameters[1]; if ($nthDay < 1 || $nthDay > 5) { $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string) trans('validation.valid_recurrence_rep_moment')); @@ -317,15 +317,15 @@ trait RecurrenceValidation return; } - $originalTrCount = $recurrence->recurrenceTransactions()->count(); + $originalTrCount = $recurrence->recurrenceTransactions()->count(); if (1 === $submittedTrCount && 1 === $originalTrCount) { - $first = $transactions[0]; // can safely assume index 0. + $first = $transactions[0]; // can safely assume index 0. if (!array_key_exists('id', $first)) { Log::debug('Single count and no ID, done.'); return; // home safe! } - $id = $first['id']; + $id = $first['id']; if ('' === (string) $id) { Log::debug('Single count and empty ID, done.'); @@ -343,7 +343,7 @@ trait RecurrenceValidation } Log::debug('Multi ID validation.'); - $idsMandatory = false; + $idsMandatory = false; if ($submittedTrCount < $originalTrCount) { Log::debug(sprintf('User submits %d transaction, recurrence has %d transactions. All entries must have ID.', $submittedTrCount, $originalTrCount)); $idsMandatory = true; @@ -360,7 +360,7 @@ trait RecurrenceValidation * 2. If the user submits more transactions than already present, count the number of existing transactions. At least those must be matched. After that, submit as many as you like. * 3. If the user submits the same number of transactions as already present, all but one must have an ID. */ - $unmatchedIds = 0; + $unmatchedIds = 0; foreach ($transactions as $index => $transaction) { Log::debug(sprintf('Now at %d/%d', $index + 1, $submittedTrCount)); @@ -390,7 +390,7 @@ trait RecurrenceValidation } } // if too many don't match, but you haven't submitted more than already present: - $maxUnmatched = max(1, $submittedTrCount - $originalTrCount); + $maxUnmatched = max(1, $submittedTrCount - $originalTrCount); Log::debug(sprintf('Submitted: %d. Original: %d. User can submit %d unmatched transactions.', $submittedTrCount, $originalTrCount, $maxUnmatched)); if ($unmatchedIds > $maxUnmatched) { Log::warning(sprintf('Too many unmatched transactions (%d).', $unmatchedIds)); diff --git a/app/Validation/TransactionValidation.php b/app/Validation/TransactionValidation.php index 04f76ecf87..fe82eb95f1 100644 --- a/app/Validation/TransactionValidation.php +++ b/app/Validation/TransactionValidation.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Validation; -use Illuminate\Contracts\Validation\Validator; use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Exceptions\FireflyException; @@ -35,9 +34,10 @@ use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\UserGroup; use FireflyIII\Repositories\Account\AccountRepository; use FireflyIII\Repositories\Account\AccountRepositoryInterface; -use FireflyIII\User; -use Illuminate\Support\Facades\Log; use FireflyIII\Support\Facades\Amount; +use FireflyIII\User; +use Illuminate\Contracts\Validation\Validator; +use Illuminate\Support\Facades\Log; /** * Trait TransactionValidation @@ -49,7 +49,7 @@ trait TransactionValidation * * Inclusion of user and/or group is optional. */ - public function validateAccountInformation(Validator $validator, ?User $user = null, ?UserGroup $userGroup = null): void + public function validateAccountInformation(Validator $validator, null|User $user = null, null|UserGroup $userGroup = null): void { if ($validator->errors()->count() > 0) { return; @@ -66,7 +66,7 @@ trait TransactionValidation * @var array $transaction */ foreach ($transactions as $index => $transaction) { - $transaction['user'] = $user; + $transaction['user'] = $user; $transaction['user_group'] = $userGroup; if (!is_int($index)) { continue; @@ -99,7 +99,7 @@ trait TransactionValidation Log::debug(sprintf('Now in validateSingleAccount(%d)', $index)); /** @var AccountValidator $accountValidator */ - $accountValidator = app(AccountValidator::class); + $accountValidator = app(AccountValidator::class); if (array_key_exists('user', $transaction) && null !== $transaction['user']) { $accountValidator->setUser($transaction['user']); @@ -108,21 +108,16 @@ trait TransactionValidation $accountValidator->setUserGroup($transaction['user_group']); } - $transactionType = $transaction['type'] ?? $transactionType; + $transactionType = $transaction['type'] ?? $transactionType; $accountValidator->setTransactionType($transactionType); // validate source account. - $sourceId = array_key_exists('source_id', $transaction) ? (int) $transaction['source_id'] : null; - $sourceName = array_key_exists('source_name', $transaction) ? (string) $transaction['source_name'] : null; - $sourceIban = array_key_exists('source_iban', $transaction) ? (string) $transaction['source_iban'] : null; - $sourceNumber = array_key_exists('source_number', $transaction) ? (string) $transaction['source_number'] : null; - $source = [ - 'id' => $sourceId, - 'name' => $sourceName, - 'iban' => $sourceIban, - 'number' => $sourceNumber, - ]; - $validSource = $accountValidator->validateSource($source); + $sourceId = array_key_exists('source_id', $transaction) ? (int) $transaction['source_id'] : null; + $sourceName = array_key_exists('source_name', $transaction) ? (string) $transaction['source_name'] : null; + $sourceIban = array_key_exists('source_iban', $transaction) ? (string) $transaction['source_iban'] : null; + $sourceNumber = array_key_exists('source_number', $transaction) ? (string) $transaction['source_number'] : null; + $source = ['id' => $sourceId, 'name' => $sourceName, 'iban' => $sourceIban, 'number' => $sourceNumber]; + $validSource = $accountValidator->validateSource($source); // do something with result: if (false === $validSource) { @@ -136,12 +131,7 @@ trait TransactionValidation $destinationName = array_key_exists('destination_name', $transaction) ? (string) $transaction['destination_name'] : null; $destinationIban = array_key_exists('destination_iban', $transaction) ? (string) $transaction['destination_iban'] : null; $destinationNumber = array_key_exists('destination_number', $transaction) ? (string) $transaction['destination_number'] : null; - $destination = [ - 'id' => $destinationId, - 'name' => $destinationName, - 'iban' => $destinationIban, - 'number' => $destinationNumber, - ]; + $destination = ['id' => $destinationId, 'name' => $destinationName, 'iban' => $destinationIban, 'number' => $destinationNumber]; $validDestination = $accountValidator->validateDestination($destination); // do something with result: if (false === $validDestination) { @@ -161,8 +151,12 @@ trait TransactionValidation protected function sanityCheckReconciliation(Validator $validator, string $transactionType, int $index, array $source, array $destination): void { Log::debug('Now in sanityCheckReconciliation'); - if (TransactionTypeEnum::RECONCILIATION->value === ucfirst($transactionType) - && null === $source['id'] && null === $source['name'] && null === $destination['id'] && null === $destination['name'] + if ( + TransactionTypeEnum::RECONCILIATION->value === ucfirst($transactionType) + && null === $source['id'] + && null === $source['name'] + && null === $destination['id'] + && null === $destination['name'] ) { Log::debug('Both are NULL, error!'); $validator->errors()->add(sprintf('transactions.%d.source_id', $index), trans('validation.reconciliation_either_account')); @@ -171,9 +165,11 @@ trait TransactionValidation $validator->errors()->add(sprintf('transactions.%d.destination_name', $index), trans('validation.reconciliation_either_account')); } - if (TransactionTypeEnum::RECONCILIATION->value === $transactionType + if ( + TransactionTypeEnum::RECONCILIATION->value === $transactionType && (null !== $source['id'] || null !== $source['name']) - && (null !== $destination['id'] || null !== $destination['name'])) { + && (null !== $destination['id'] || null !== $destination['name']) + ) { Log::debug('Both are not NULL, error!'); $validator->errors()->add(sprintf('transactions.%d.source_id', $index), trans('validation.reconciliation_either_account')); $validator->errors()->add(sprintf('transactions.%d.source_name', $index), trans('validation.reconciliation_either_account')); @@ -189,11 +185,11 @@ trait TransactionValidation * @SuppressWarnings("PHPMD.NPathComplexity") */ private function sanityCheckForeignCurrency( - Validator $validator, + Validator $validator, AccountValidator $accountValidator, - array $transaction, - string $transactionType, - int $index + array $transaction, + string $transactionType, + int $index ): void { Log::debug('Now in sanityCheckForeignCurrency()'); if (0 !== $validator->errors()->count()) { @@ -211,8 +207,8 @@ trait TransactionValidation return; } - $source = $accountValidator->source; - $destination = $accountValidator->destination; + $source = $accountValidator->source; + $destination = $accountValidator->destination; Log::debug(sprintf('Source: #%d "%s (%s)"', $source->id, $source->name, $source->accountType->type)); Log::debug(sprintf('Destination: #%d "%s" (%s)', $destination->id, $destination->name, $destination->accountType->type)); @@ -366,7 +362,8 @@ trait TransactionValidation !array_key_exists('source_id', $transaction) && !array_key_exists('source_name', $transaction) && !array_key_exists('destination_id', $transaction) - && !array_key_exists('destination_name', $transaction)) { + && !array_key_exists('destination_name', $transaction) + ) { Log::debug('No account data has been submitted so will not validating account info.'); return; @@ -377,8 +374,8 @@ trait TransactionValidation $accountValidator = app(AccountValidator::class); // 2025-01-29 grab the transaction type from the update array. - $originalType = $this->getTransactionType($transactionGroup, []); - $transactionType = $transaction['type'] ?? $originalType; + $originalType = $this->getTransactionType($transactionGroup, []); + $transactionType = $transaction['type'] ?? $originalType; Log::debug(sprintf('Determined transaction type to be "%s"', $transactionType)); // get the transaction type using the original transaction group: @@ -396,9 +393,12 @@ trait TransactionValidation $sourceName = $transaction['source_name'] ?? null; $sourceIban = $transaction['source_iban'] ?? null; $sourceNumber = $transaction['source_number'] ?? null; - $validSource = $accountValidator->validateSource( - ['id' => $sourceId, 'name' => $sourceName, 'iban' => $sourceIban, 'number' => $sourceNumber] - ); + $validSource = $accountValidator->validateSource([ + 'id' => $sourceId, + 'name' => $sourceName, + 'iban' => $sourceIban, + 'number' => $sourceNumber + ]); // do something with result: if (false === $validSource) { @@ -440,7 +440,7 @@ trait TransactionValidation $destinationName = $transaction['destination_name'] ?? null; $destinationIban = $transaction['destination_iban'] ?? null; $destinationNumber = $transaction['destination_number'] ?? null; - $array = ['id' => $destinationId, 'name' => $destinationName, 'iban' => $destinationIban, 'number' => $destinationNumber]; + $array = ['id' => $destinationId, 'name' => $destinationName, 'iban' => $destinationIban, 'number' => $destinationNumber]; $validDestination = $accountValidator->validateDestination($array); // do something with result: if (false === $validDestination) { @@ -462,7 +462,7 @@ trait TransactionValidation return $transactions[0]['type'] ?? strtolower((string) $group->transactionJournals()->first()?->transactionType->type); } - private function getOriginalSource(array $transaction, TransactionGroup $transactionGroup): ?Account + private function getOriginalSource(array $transaction, TransactionGroup $transactionGroup): null|Account { if (1 === $transactionGroup->transactionJournals->count()) { $journal = $transactionGroup->transactionJournals->first(); @@ -544,17 +544,17 @@ trait TransactionValidation Log::debug('Now in validateTransactionTypes()'); $transactions = $this->getTransactionsArray($validator); - $types = []; + $types = []; foreach ($transactions as $transaction) { $types[] = $transaction['type'] ?? 'invalid'; } - $unique = array_unique($types); + $unique = array_unique($types); if (count($unique) > 1) { $validator->errors()->add('transactions.0.type', (string) trans('validation.transaction_types_equal')); return; } - $first = $unique[0] ?? 'invalid'; + $first = $unique[0] ?? 'invalid'; if ('invalid' === $first) { $validator->errors()->add('transactions.0.type', (string) trans('validation.invalid_transaction_type')); } @@ -571,9 +571,9 @@ trait TransactionValidation foreach ($transactions as $transaction) { $originalType = $this->getOriginalType((int) ($transaction['transaction_journal_id'] ?? 0)); // if type is not set, fall back to the type of the journal, if one is given. - $types[] = $transaction['type'] ?? $originalType; + $types[] = $transaction['type'] ?? $originalType; } - $unique = array_unique($types); + $unique = array_unique($types); if (count($unique) > 1) { Log::warning('Add error for mismatch transaction types.'); $validator->errors()->add('transactions.0.type', (string) trans('validation.transaction_types_equal')); @@ -610,15 +610,15 @@ trait TransactionValidation if (count($transactions) < 2) { return; } - $type = $transactions[0]['type'] ?? 'withdrawal'; - $sources = []; - $dests = []; + $type = $transactions[0]['type'] ?? 'withdrawal'; + $sources = []; + $dests = []; foreach ($transactions as $transaction) { $sources[] = sprintf('%d-%s', $transaction['source_id'] ?? 0, $transaction['source_name'] ?? ''); - $dests[] = sprintf('%d-%s', $transaction['destination_id'] ?? 0, $transaction['destination_name'] ?? ''); + $dests[] = sprintf('%d-%s', $transaction['destination_id'] ?? 0, $transaction['destination_name'] ?? ''); } - $sources = array_unique($sources); - $dests = array_unique($dests); + $sources = array_unique($sources); + $dests = array_unique($dests); switch ($type) { default: @@ -662,15 +662,15 @@ trait TransactionValidation return; } - $type = $this->getTransactionType($transactionGroup, $transactions); + $type = $this->getTransactionType($transactionGroup, $transactions); // compare source IDs, destination IDs, source names and destination names. // I think I can get away with one combination being equal, as long as the rest // of the code picks up on this as well. // either way all fields must be blank or all equal // but if IDs are equal don't bother with the names. - $comparison = $this->collectComparisonData($transactions); - $result = $this->compareAccountData($type, $comparison); + $comparison = $this->collectComparisonData($transactions); + $result = $this->compareAccountData($type, $comparison); if (false === $result) { if ('withdrawal' === $type) { $validator->errors()->add('transactions.0.source_id', (string) trans('validation.all_accounts_equal')); @@ -699,7 +699,7 @@ trait TransactionValidation /** @var array $transaction */ foreach ($transactions as $transaction) { // source or destination may be omitted. If this is the case, use the original source / destination name + ID. - $originalData = $this->getOriginalData((int) ($transaction['transaction_journal_id'] ?? 0)); + $originalData = $this->getOriginalData((int) ($transaction['transaction_journal_id'] ?? 0)); // get field. $comparison[$field][] = $transaction[$field] ?? $originalData[$field]; @@ -711,27 +711,28 @@ trait TransactionValidation private function getOriginalData(int $journalId): array { - $return = [ - 'source_id' => 0, - 'source_name' => '', - 'destination_id' => 0, - 'destination_name' => '', - ]; + $return = ['source_id' => 0, 'source_name' => '', 'destination_id' => 0, 'destination_name' => '']; if (0 === $journalId) { return $return; } /** @var null|Transaction $source */ - $source = Transaction::where('transaction_journal_id', $journalId)->where('amount', '<', 0)->with(['account'])->first(); + $source = Transaction::where('transaction_journal_id', $journalId) + ->where('amount', '<', 0) + ->with(['account']) + ->first(); if (null !== $source) { - $return['source_id'] = $source->account_id; + $return['source_id'] = $source->account_id; $return['source_name'] = $source->account->name; } /** @var null|Transaction $destination */ - $destination = Transaction::where('transaction_journal_id', $journalId)->where('amount', '>', 0)->with(['account'])->first(); + $destination = Transaction::where('transaction_journal_id', $journalId) + ->where('amount', '>', 0) + ->with(['account']) + ->first(); if (null !== $destination) { - $return['destination_id'] = $destination->account_id; + $return['destination_id'] = $destination->account_id; $return['destination_name'] = $destination->account->name; } @@ -741,9 +742,9 @@ trait TransactionValidation private function compareAccountData(string $type, array $comparison): bool { return match ($type) { - default => $this->compareAccountDataWithdrawal($comparison), - 'deposit' => $this->compareAccountDataDeposit($comparison), - 'transfer' => $this->compareAccountDataTransfer($comparison), + default => $this->compareAccountDataWithdrawal($comparison), + 'deposit' => $this->compareAccountDataDeposit($comparison), + 'transfer' => $this->compareAccountDataTransfer($comparison) }; } diff --git a/database/factories/AccountFactory.php b/database/factories/AccountFactory.php index dd2eb4ac04..dbcf8e18be 100644 --- a/database/factories/AccountFactory.php +++ b/database/factories/AccountFactory.php @@ -1,4 +1,5 @@ $this->faker->name(), - 'active' => true, - ]; + return ['name' => $this->faker->name(), 'active' => true]; } public function withType(AccountTypeEnum $type): static diff --git a/database/seeders/AccountTypeSeeder.php b/database/seeders/AccountTypeSeeder.php index ab34b8b772..41aef49e1a 100644 --- a/database/seeders/AccountTypeSeeder.php +++ b/database/seeders/AccountTypeSeeder.php @@ -35,7 +35,7 @@ class AccountTypeSeeder extends Seeder { public function run(): void { - foreach(AccountTypeEnum::cases() as $type) { + foreach (AccountTypeEnum::cases() as $type) { if (null === AccountType::where('type', $type->value)->first()) { try { AccountType::create(['type' => $type->value]); diff --git a/database/seeders/ConfigSeeder.php b/database/seeders/ConfigSeeder.php index 082b3406f1..d155b2487a 100644 --- a/database/seeders/ConfigSeeder.php +++ b/database/seeders/ConfigSeeder.php @@ -37,18 +37,13 @@ class ConfigSeeder extends Seeder */ public function run(): void { - $entry = Configuration::where('name', 'db_version')->first(); + $entry = Configuration::where('name', 'db_version')->first(); if (null === $entry) { - Configuration::create( - [ - 'name' => 'db_version', - 'data' => 1, - ] - ); + Configuration::create(['name' => 'db_version', 'data' => 1]); return; } - $version = (int) config('firefly.db_version'); + $version = (int) config('firefly.db_version'); $entry->data = $version; $entry->save(); } diff --git a/database/seeders/ExchangeRateSeeder.php b/database/seeders/ExchangeRateSeeder.php index d61a5f6101..c5229d0413 100644 --- a/database/seeders/ExchangeRateSeeder.php +++ b/database/seeders/ExchangeRateSeeder.php @@ -36,7 +36,7 @@ class ExchangeRateSeeder extends Seeder { public function run(): void { - $count = User::count(); + $count = User::count(); if (0 === $count) { app('log')->debug('Will not seed exchange rates yet.'); @@ -71,19 +71,14 @@ class ExchangeRateSeeder extends Seeder } } - private function getCurrency(string $code): ?TransactionCurrency + private function getCurrency(string $code): null|TransactionCurrency { return TransactionCurrency::whereNull('deleted_at')->where('code', $code)->first(); } private function hasRate(User $user, TransactionCurrency $from, TransactionCurrency $to, string $date): bool { - return $user->currencyExchangeRates() - ->where('from_currency_id', $from->id) - ->where('to_currency_id', $to->id) - ->where('date', $date) - ->count() > 0 - ; + return $user->currencyExchangeRates()->where('from_currency_id', $from->id)->where('to_currency_id', $to->id)->where('date', $date)->count() > 0; } /** @@ -91,15 +86,13 @@ class ExchangeRateSeeder extends Seeder */ private function addRate(User $user, TransactionCurrency $from, TransactionCurrency $to, string $date, float $rate): void { - CurrencyExchangeRate::create( - [ - 'user_id' => $user->id, - 'user_group_id' => $user->user_group_id ?? null, - 'from_currency_id' => $from->id, - 'to_currency_id' => $to->id, - 'date' => $date, - 'rate' => $rate, - ] - ); + CurrencyExchangeRate::create([ + 'user_id' => $user->id, + 'user_group_id' => $user->user_group_id ?? null, + 'from_currency_id' => $from->id, + 'to_currency_id' => $to->id, + 'date' => $date, + 'rate' => $rate + ]); } } diff --git a/database/seeders/LinkTypeSeeder.php b/database/seeders/LinkTypeSeeder.php index 7f2aa36bbd..84eca0a7c6 100644 --- a/database/seeders/LinkTypeSeeder.php +++ b/database/seeders/LinkTypeSeeder.php @@ -35,30 +35,10 @@ class LinkTypeSeeder extends Seeder public function run(): void { $types = [ - [ - 'name' => 'Related', - 'inward' => 'relates to', - 'outward' => 'relates to', - 'editable' => false, - ], - [ - 'name' => 'Refund', - 'inward' => 'is (partially) refunded by', - 'outward' => '(partially) refunds', - 'editable' => false, - ], - [ - 'name' => 'Paid', - 'inward' => 'is (partially) paid for by', - 'outward' => '(partially) pays for', - 'editable' => false, - ], - [ - 'name' => 'Reimbursement', - 'inward' => 'is (partially) reimbursed by', - 'outward' => '(partially) reimburses', - 'editable' => false, - ], + ['name' => 'Related', 'inward' => 'relates to', 'outward' => 'relates to', 'editable' => false], + ['name' => 'Refund', 'inward' => 'is (partially) refunded by', 'outward' => '(partially) refunds', 'editable' => false], + ['name' => 'Paid', 'inward' => 'is (partially) paid for by', 'outward' => '(partially) pays for', 'editable' => false], + ['name' => 'Reimbursement', 'inward' => 'is (partially) reimbursed by', 'outward' => '(partially) reimburses', 'editable' => false] ]; foreach ($types as $type) { if (null === LinkType::where('name', $type['name'])->first()) { diff --git a/database/seeders/PermissionSeeder.php b/database/seeders/PermissionSeeder.php index 5c66b3af29..0e39017ed4 100644 --- a/database/seeders/PermissionSeeder.php +++ b/database/seeders/PermissionSeeder.php @@ -35,16 +35,8 @@ class PermissionSeeder extends Seeder public function run(): void { $roles = [ - [ - 'name' => 'owner', - 'display_name' => 'Site Owner', - 'description' => 'User runs this instance of FF3', - ], - [ - 'name' => 'demo', - 'display_name' => 'Demo User', - 'description' => 'User is a demo user', - ], + ['name' => 'owner', 'display_name' => 'Site Owner', 'description' => 'User runs this instance of FF3'], + ['name' => 'demo', 'display_name' => 'Demo User', 'description' => 'User is a demo user'] ]; foreach ($roles as $role) { if (null === Role::where('name', $role['name'])->first()) { diff --git a/database/seeders/TransactionCurrencySeeder.php b/database/seeders/TransactionCurrencySeeder.php index 56df126edd..d97811f956 100644 --- a/database/seeders/TransactionCurrencySeeder.php +++ b/database/seeders/TransactionCurrencySeeder.php @@ -34,58 +34,58 @@ class TransactionCurrencySeeder extends Seeder { public function run(): void { - $currencies = []; + $currencies = []; // european currencies - $currencies[] = ['code' => 'EUR', 'name' => 'Euro', 'symbol' => '€', 'decimal_places' => 2, 'enabled' => 1]; - $currencies[] = ['code' => 'HUF', 'name' => 'Hungarian forint', 'symbol' => 'Ft', 'decimal_places' => 2]; - $currencies[] = ['code' => 'GBP', 'name' => 'British Pound', 'symbol' => '£', 'decimal_places' => 2]; - $currencies[] = ['code' => 'UAH', 'name' => 'Ukrainian hryvnia', 'symbol' => '₴', 'decimal_places' => 2]; - $currencies[] = ['code' => 'PLN', 'name' => 'Polish złoty', 'symbol' => 'zł', 'decimal_places' => 2]; - $currencies[] = ['code' => 'TRY', 'name' => 'Turkish lira', 'symbol' => '₺', 'decimal_places' => 2]; - $currencies[] = ['code' => 'DKK', 'name' => 'Dansk krone', 'symbol' => 'kr.', 'decimal_places' => 2]; - $currencies[] = ['code' => 'ISK', 'name' => 'Íslensk króna', 'symbol' => 'kr.', 'decimal_places' => 2]; - $currencies[] = ['code' => 'NOK', 'name' => 'Norsk krone', 'symbol' => 'kr.', 'decimal_places' => 2]; - $currencies[] = ['code' => 'SEK', 'name' => 'Svensk krona', 'symbol' => 'kr.', 'decimal_places' => 2]; - $currencies[] = ['code' => 'RON', 'name' => 'Romanian leu', 'symbol' => 'lei', 'decimal_places' => 2]; + $currencies[] = ['code' => 'EUR', 'name' => 'Euro', 'symbol' => '€', 'decimal_places' => 2, 'enabled' => 1]; + $currencies[] = ['code' => 'HUF', 'name' => 'Hungarian forint', 'symbol' => 'Ft', 'decimal_places' => 2]; + $currencies[] = ['code' => 'GBP', 'name' => 'British Pound', 'symbol' => '£', 'decimal_places' => 2]; + $currencies[] = ['code' => 'UAH', 'name' => 'Ukrainian hryvnia', 'symbol' => '₴', 'decimal_places' => 2]; + $currencies[] = ['code' => 'PLN', 'name' => 'Polish złoty', 'symbol' => 'zł', 'decimal_places' => 2]; + $currencies[] = ['code' => 'TRY', 'name' => 'Turkish lira', 'symbol' => '₺', 'decimal_places' => 2]; + $currencies[] = ['code' => 'DKK', 'name' => 'Dansk krone', 'symbol' => 'kr.', 'decimal_places' => 2]; + $currencies[] = ['code' => 'ISK', 'name' => 'Íslensk króna', 'symbol' => 'kr.', 'decimal_places' => 2]; + $currencies[] = ['code' => 'NOK', 'name' => 'Norsk krone', 'symbol' => 'kr.', 'decimal_places' => 2]; + $currencies[] = ['code' => 'SEK', 'name' => 'Svensk krona', 'symbol' => 'kr.', 'decimal_places' => 2]; + $currencies[] = ['code' => 'RON', 'name' => 'Romanian leu', 'symbol' => 'lei', 'decimal_places' => 2]; // american currencies - $currencies[] = ['code' => 'USD', 'name' => 'US Dollar', 'symbol' => '$', 'decimal_places' => 2]; - $currencies[] = ['code' => 'BRL', 'name' => 'Brazilian real', 'symbol' => 'R$', 'decimal_places' => 2]; - $currencies[] = ['code' => 'CAD', 'name' => 'Canadian dollar', 'symbol' => 'C$', 'decimal_places' => 2]; - $currencies[] = ['code' => 'MXN', 'name' => 'Mexican peso', 'symbol' => 'MX$', 'decimal_places' => 2]; - $currencies[] = ['code' => 'PEN', 'name' => 'Peruvian Sol', 'symbol' => 'S/', 'decimal_places' => 2]; - $currencies[] = ['code' => 'ARS', 'name' => 'Argentinian Peso', 'symbol' => '$', 'decimal_places' => 2]; - $currencies[] = ['code' => 'COP', 'name' => 'Colombian Peso', 'symbol' => '$', 'decimal_places' => 2]; - $currencies[] = ['code' => 'CLP', 'name' => 'Chilean Peso', 'symbol' => '$', 'decimal_places' => 2]; - $currencies[] = ['code' => 'UYU', 'name' => 'Uruguayan Peso', 'symbol' => '$', 'decimal_places' => 2]; + $currencies[] = ['code' => 'USD', 'name' => 'US Dollar', 'symbol' => '$', 'decimal_places' => 2]; + $currencies[] = ['code' => 'BRL', 'name' => 'Brazilian real', 'symbol' => 'R$', 'decimal_places' => 2]; + $currencies[] = ['code' => 'CAD', 'name' => 'Canadian dollar', 'symbol' => 'C$', 'decimal_places' => 2]; + $currencies[] = ['code' => 'MXN', 'name' => 'Mexican peso', 'symbol' => 'MX$', 'decimal_places' => 2]; + $currencies[] = ['code' => 'PEN', 'name' => 'Peruvian Sol', 'symbol' => 'S/', 'decimal_places' => 2]; + $currencies[] = ['code' => 'ARS', 'name' => 'Argentinian Peso', 'symbol' => '$', 'decimal_places' => 2]; + $currencies[] = ['code' => 'COP', 'name' => 'Colombian Peso', 'symbol' => '$', 'decimal_places' => 2]; + $currencies[] = ['code' => 'CLP', 'name' => 'Chilean Peso', 'symbol' => '$', 'decimal_places' => 2]; + $currencies[] = ['code' => 'UYU', 'name' => 'Uruguayan Peso', 'symbol' => '$', 'decimal_places' => 2]; // oceanian currencies - $currencies[] = ['code' => 'IDR', 'name' => 'Indonesian rupiah', 'symbol' => 'Rp', 'decimal_places' => 2]; - $currencies[] = ['code' => 'AUD', 'name' => 'Australian dollar', 'symbol' => 'A$', 'decimal_places' => 2]; - $currencies[] = ['code' => 'NZD', 'name' => 'New Zealand dollar', 'symbol' => 'NZ$', 'decimal_places' => 2]; + $currencies[] = ['code' => 'IDR', 'name' => 'Indonesian rupiah', 'symbol' => 'Rp', 'decimal_places' => 2]; + $currencies[] = ['code' => 'AUD', 'name' => 'Australian dollar', 'symbol' => 'A$', 'decimal_places' => 2]; + $currencies[] = ['code' => 'NZD', 'name' => 'New Zealand dollar', 'symbol' => 'NZ$', 'decimal_places' => 2]; // african currencies - $currencies[] = ['code' => 'EGP', 'name' => 'Egyptian pound', 'symbol' => 'E£', 'decimal_places' => 2]; - $currencies[] = ['code' => 'MAD', 'name' => 'Moroccan dirham', 'symbol' => 'DH', 'decimal_places' => 2]; - $currencies[] = ['code' => 'ZAR', 'name' => 'South African rand', 'symbol' => 'R', 'decimal_places' => 2]; + $currencies[] = ['code' => 'EGP', 'name' => 'Egyptian pound', 'symbol' => 'E£', 'decimal_places' => 2]; + $currencies[] = ['code' => 'MAD', 'name' => 'Moroccan dirham', 'symbol' => 'DH', 'decimal_places' => 2]; + $currencies[] = ['code' => 'ZAR', 'name' => 'South African rand', 'symbol' => 'R', 'decimal_places' => 2]; // asian currencies - $currencies[] = ['code' => 'JPY', 'name' => 'Japanese yen', 'symbol' => '¥', 'decimal_places' => 0]; - $currencies[] = ['code' => 'CNY', 'name' => 'Chinese yuan', 'symbol' => '¥', 'decimal_places' => 2]; - $currencies[] = ['code' => 'KRW', 'name' => 'South Korean won','symbol' => '₩', 'decimal_places' => 2,]; + $currencies[] = ['code' => 'JPY', 'name' => 'Japanese yen', 'symbol' => '¥', 'decimal_places' => 0]; + $currencies[] = ['code' => 'CNY', 'name' => 'Chinese yuan', 'symbol' => '¥', 'decimal_places' => 2]; + $currencies[] = ['code' => 'KRW', 'name' => 'South Korean won', 'symbol' => '₩', 'decimal_places' => 2]; // $currencies[] = ['code' => 'RMB', 'name' => 'Chinese yuan', 'symbol' => '¥', 'decimal_places' => 2]; - $currencies[] = ['code' => 'RUB', 'name' => 'Russian ruble', 'symbol' => '₽', 'decimal_places' => 2]; - $currencies[] = ['code' => 'INR', 'name' => 'Indian rupee', 'symbol' => '₹', 'decimal_places' => 2]; + $currencies[] = ['code' => 'RUB', 'name' => 'Russian ruble', 'symbol' => '₽', 'decimal_places' => 2]; + $currencies[] = ['code' => 'INR', 'name' => 'Indian rupee', 'symbol' => '₹', 'decimal_places' => 2]; // ALL NEW CURRENCIES BELOW THIS LINE - $currencies[] = ['code' => 'ILS', 'name' => 'Israeli new shekel', 'symbol' => '₪', 'decimal_places' => 2]; - $currencies[] = ['code' => 'CHF', 'name' => 'Swiss franc', 'symbol' => 'CHF', 'decimal_places' => 2]; - $currencies[] = ['code' => 'HRK', 'name' => 'Croatian kuna', 'symbol' => 'kn', 'decimal_places' => 2]; - $currencies[] = ['code' => 'HKD', 'name' => 'Hong Kong dollar', 'symbol' => 'HK$', 'decimal_places' => 2]; - $currencies[] = ['code' => 'CZK', 'name' => 'Czech koruna', 'symbol' => 'Kč', 'decimal_places' => 2]; - $currencies[] = ['code' => 'KZT', 'name' => 'Kazakhstani tenge', 'symbol' => '₸', 'decimal_places' => 2]; - $currencies[] = ['code' => 'SAR', 'name' => 'Saudi Riyal', 'symbol' => 'SAR', 'decimal_places' => 2]; - $currencies[] = ['code' => 'RSD', 'name' => 'Serbian Dinar', 'symbol' => 'RSD', 'decimal_places' => 2]; + $currencies[] = ['code' => 'ILS', 'name' => 'Israeli new shekel', 'symbol' => '₪', 'decimal_places' => 2]; + $currencies[] = ['code' => 'CHF', 'name' => 'Swiss franc', 'symbol' => 'CHF', 'decimal_places' => 2]; + $currencies[] = ['code' => 'HRK', 'name' => 'Croatian kuna', 'symbol' => 'kn', 'decimal_places' => 2]; + $currencies[] = ['code' => 'HKD', 'name' => 'Hong Kong dollar', 'symbol' => 'HK$', 'decimal_places' => 2]; + $currencies[] = ['code' => 'CZK', 'name' => 'Czech koruna', 'symbol' => 'Kč', 'decimal_places' => 2]; + $currencies[] = ['code' => 'KZT', 'name' => 'Kazakhstani tenge', 'symbol' => '₸', 'decimal_places' => 2]; + $currencies[] = ['code' => 'SAR', 'name' => 'Saudi Riyal', 'symbol' => 'SAR', 'decimal_places' => 2]; + $currencies[] = ['code' => 'RSD', 'name' => 'Serbian Dinar', 'symbol' => 'RSD', 'decimal_places' => 2]; foreach ($currencies as $currency) { if (null === TransactionCurrency::where('code', $currency['code'])->first()) { diff --git a/database/seeders/TransactionTypeSeeder.php b/database/seeders/TransactionTypeSeeder.php index 71d247a799..3b38d101ae 100644 --- a/database/seeders/TransactionTypeSeeder.php +++ b/database/seeders/TransactionTypeSeeder.php @@ -45,7 +45,5 @@ class TransactionTypeSeeder extends Seeder } } } - - } } diff --git a/database/seeders/WebhookDataSeeder.php b/database/seeders/WebhookDataSeeder.php index 236831e62a..6ad02a03a3 100644 --- a/database/seeders/WebhookDataSeeder.php +++ b/database/seeders/WebhookDataSeeder.php @@ -2,8 +2,6 @@ declare(strict_types=1); - - /* * WebhookDataSeeder.php * Copyright (c) 2025 james@firefly-iii.org @@ -26,12 +24,12 @@ declare(strict_types=1); namespace Database\Seeders; -use FireflyIII\Enums\WebhookTrigger; -use FireflyIII\Enums\WebhookResponse; use FireflyIII\Enums\WebhookDelivery; -use FireflyIII\Models\WebhookTrigger as WebhookTriggerModel; -use FireflyIII\Models\WebhookResponse as WebhookResponseModel; +use FireflyIII\Enums\WebhookResponse; +use FireflyIII\Enums\WebhookTrigger; use FireflyIII\Models\WebhookDelivery as WebhookDeliveryModel; +use FireflyIII\Models\WebhookResponse as WebhookResponseModel; +use FireflyIII\Models\WebhookTrigger as WebhookTriggerModel; use Illuminate\Database\Seeder; class WebhookDataSeeder extends Seeder @@ -44,7 +42,7 @@ class WebhookDataSeeder extends Seeder foreach (WebhookTrigger::cases() as $trigger) { if (null === WebhookTriggerModel::where('key', $trigger->value)->where('title', $trigger->name)->first()) { try { - WebhookTriggerModel::create(['key' => $trigger->value, 'title' => $trigger->name]); + WebhookTriggerModel::create(['key' => $trigger->value, 'title' => $trigger->name]); } catch (\PDOException $e) { // @ignoreException } @@ -53,7 +51,7 @@ class WebhookDataSeeder extends Seeder foreach (WebhookResponse::cases() as $response) { if (null === WebhookResponseModel::where('key', $response->value)->where('title', $response->name)->first()) { try { - WebhookResponseModel::create(['key' => $response->value, 'title' => $response->name]); + WebhookResponseModel::create(['key' => $response->value, 'title' => $response->name]); } catch (\PDOException $e) { // @ignoreException } @@ -62,7 +60,7 @@ class WebhookDataSeeder extends Seeder foreach (WebhookDelivery::cases() as $delivery) { if (null === WebhookDeliveryModel::where('key', $delivery->value)->where('title', $delivery->name)->first()) { try { - WebhookDeliveryModel::create(['key' => $delivery->value, 'title' => $delivery->name]); + WebhookDeliveryModel::create(['key' => $delivery->value, 'title' => $delivery->name]); } catch (\PDOException $e) { // @ignoreException } diff --git a/tests/feature/TestCase.php b/tests/feature/TestCase.php index 5b7d128abb..6569e9baea 100644 --- a/tests/feature/TestCase.php +++ b/tests/feature/TestCase.php @@ -33,12 +33,6 @@ abstract class TestCase extends BaseTestCase protected function createUser(): User { - return User::create( - [ - 'email' => 'james@firefly', - 'password' => 'secret', - ] - ); - + return User::create(['email' => 'james@firefly', 'password' => 'secret']); } } diff --git a/tests/integration/Api/Autocomplete/BillControllerTest.php b/tests/integration/Api/Autocomplete/BillControllerTest.php index a0ae364922..07b4418ff1 100644 --- a/tests/integration/Api/Autocomplete/BillControllerTest.php +++ b/tests/integration/Api/Autocomplete/BillControllerTest.php @@ -25,9 +25,9 @@ declare(strict_types=1); namespace Tests\integration\Api\Autocomplete; use FireflyIII\Models\Bill; +use FireflyIII\User; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\integration\TestCase; -use FireflyIII\User; /** * Class BillControllerTest @@ -48,15 +48,14 @@ final class BillControllerTest extends TestCase for ($i = 1; $i <= $count; ++$i) { $bill = Bill::create([ 'user_id' => $user->id, - 'name' => 'Bill '.$i, + 'name' => 'Bill ' . $i, 'user_group_id' => $user->user_group_id, 'amount_min' => random_int(1, 100), // random amount - 'amount_max' => random_int(101, 200), // random amount - 'match' => 'MIGRATED_TO_RULES', - 'date' => '2024-01-01', - 'repeat_freq' => 'monthly', - 'automatch' => 1, - + 'amount_max' => random_int(101, 200), // random amount + 'match' => 'MIGRATED_TO_RULES', + 'date' => '2024-01-01', + 'repeat_freq' => 'monthly', + 'automatch' => 1 ]); } } @@ -73,7 +72,7 @@ final class BillControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheBillsEndpointThenReturns200HttpCode(): void { // act as a user - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $response = $this->get(route('api.v1.autocomplete.bills'), ['Accept' => 'application/json']); @@ -83,7 +82,7 @@ final class BillControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheBillsEndpointThenReturnsBills(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestBills(5, $user); @@ -92,51 +91,31 @@ final class BillControllerTest extends TestCase $response->assertHeader('Content-Type', 'application/json'); $response->assertJsonCount(5); $response->assertJsonFragment(['name' => 'Bill 1']); - $response->assertJsonStructure([ - '*' => [ - 'id', - 'name', - 'active', - ], - ]); - + $response->assertJsonStructure(['*' => ['id', 'name', 'active']]); } public function testGivenAuthenticatedRequestWhenCallingTheBillsEndpointWithQueryThenReturnsBillsWithLimit(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestBills(5, $user); - $response = $this->get(route('api.v1.autocomplete.bills', [ - 'query' => 'Bill', - 'limit' => 3, - ]), ['Accept' => 'application/json']); + $response = $this->get(route('api.v1.autocomplete.bills', ['query' => 'Bill', 'limit' => 3]), ['Accept' => 'application/json']); $response->assertStatus(200); $response->assertHeader('Content-Type', 'application/json'); $response->assertJsonCount(3); $response->assertJsonFragment(['name' => 'Bill 1']); - $response->assertJsonStructure([ - '*' => [ - 'id', - 'name', - 'active', - ], - ]); - + $response->assertJsonStructure(['*' => ['id', 'name', 'active']]); } public function testGivenAuthenticatedRequestWhenCallingTheBillsEndpointWithQueryThenReturnsBillsThatMatchQuery(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestBills(20, $user); - $response = $this->get(route('api.v1.autocomplete.bills', [ - 'query' => 'Bill 1', - 'limit' => 20, - ]), ['Accept' => 'application/json']); + $response = $this->get(route('api.v1.autocomplete.bills', ['query' => 'Bill 1', 'limit' => 20]), ['Accept' => 'application/json']); $response->assertStatus(200); $response->assertHeader('Content-Type', 'application/json'); diff --git a/tests/integration/Api/Autocomplete/BudgetControllerTest.php b/tests/integration/Api/Autocomplete/BudgetControllerTest.php index 23bc8ba048..7730412c56 100644 --- a/tests/integration/Api/Autocomplete/BudgetControllerTest.php +++ b/tests/integration/Api/Autocomplete/BudgetControllerTest.php @@ -25,9 +25,9 @@ declare(strict_types=1); namespace Tests\integration\Api\Autocomplete; use FireflyIII\Models\Budget; +use FireflyIII\User; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\integration\TestCase; -use FireflyIII\User; /** * Class BudgetControllerTest @@ -48,9 +48,9 @@ final class BudgetControllerTest extends TestCase for ($i = 1; $i <= $count; ++$i) { $budget = Budget::create([ 'user_id' => $user->id, - 'name' => 'Budget '.$i, + 'name' => 'Budget ' . $i, 'user_group_id' => $user->user_group_id, - 'active' => 1, + 'active' => 1 ]); } } @@ -67,18 +67,17 @@ final class BudgetControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheBudgetsEndpointThenReturns200HttpCode(): void { // act as a user - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $response = $this->get(route('api.v1.autocomplete.budgets'), ['Accept' => 'application/json']); $response->assertStatus(200); $response->assertHeader('Content-Type', 'application/json'); - } public function testGivenAuthenticatedRequestWhenCallingTheBudgetsEndpointThenReturnsBudgets(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestBudgets(5, $user); @@ -87,24 +86,16 @@ final class BudgetControllerTest extends TestCase $response->assertHeader('Content-Type', 'application/json'); $response->assertJsonCount(5); $response->assertJsonFragment(['name' => 'Budget 1']); - $response->assertJsonStructure([ - '*' => [ - 'id', - 'name', - ], - ]); + $response->assertJsonStructure(['*' => ['id', 'name']]); } public function testGivenAuthenticatedRequestWhenCallingTheBudgetsEndpointWithQueryThenReturnsBudgetsWithLimit(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestBudgets(5, $user); - $response = $this->get(route('api.v1.autocomplete.budgets', [ - 'query' => 'Budget', - 'limit' => 3, - ]), ['Accept' => 'application/json']); + $response = $this->get(route('api.v1.autocomplete.budgets', ['query' => 'Budget', 'limit' => 3]), ['Accept' => 'application/json']); $response->assertStatus(200); $response->assertHeader('Content-Type', 'application/json'); @@ -113,14 +104,11 @@ final class BudgetControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheBudgetsEndpointWithQueryThenReturnsBudgetsThatMatchQuery(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestBudgets(20, $user); - $response = $this->get(route('api.v1.autocomplete.budgets', [ - 'query' => 'Budget 1', - 'limit' => 20, - ]), ['Accept' => 'application/json']); + $response = $this->get(route('api.v1.autocomplete.budgets', ['query' => 'Budget 1', 'limit' => 20]), ['Accept' => 'application/json']); $response->assertStatus(200); $response->assertHeader('Content-Type', 'application/json'); diff --git a/tests/integration/Api/Autocomplete/CategoryControllerTest.php b/tests/integration/Api/Autocomplete/CategoryControllerTest.php index b678f24bef..e2899b9adb 100644 --- a/tests/integration/Api/Autocomplete/CategoryControllerTest.php +++ b/tests/integration/Api/Autocomplete/CategoryControllerTest.php @@ -25,9 +25,9 @@ declare(strict_types=1); namespace Tests\integration\Api\Autocomplete; use FireflyIII\Models\Category; +use FireflyIII\User; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\integration\TestCase; -use FireflyIII\User; /** * Class CategoryControllerTest @@ -46,11 +46,7 @@ final class CategoryControllerTest extends TestCase private function createTestCategories(int $count, User $user): void { for ($i = 1; $i <= $count; ++$i) { - $category = Category::create([ - 'user_id' => $user->id, - 'name' => 'Category '.$i, - 'user_group_id' => $user->user_group_id, - ]); + $category = Category::create(['user_id' => $user->id, 'name' => 'Category ' . $i, 'user_group_id' => $user->user_group_id]); } } @@ -66,18 +62,17 @@ final class CategoryControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheCategoriesEndpointThenReturns200HttpCode(): void { // act as a user - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $response = $this->get(route('api.v1.autocomplete.categories'), ['Accept' => 'application/json']); $response->assertStatus(200); $response->assertHeader('Content-Type', 'application/json'); - } public function testGivenAuthenticatedRequestWhenCallingTheCategoriesEndpointThenReturnsCategories(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestCategories(5, $user); @@ -86,24 +81,16 @@ final class CategoryControllerTest extends TestCase $response->assertHeader('Content-Type', 'application/json'); $response->assertJsonCount(5); $response->assertJsonFragment(['name' => 'Category 1']); - $response->assertJsonStructure([ - '*' => [ - 'id', - 'name', - ], - ]); + $response->assertJsonStructure(['*' => ['id', 'name']]); } public function testGivenAuthenticatedRequestWhenCallingTheCategoriesEndpointWithQueryThenReturnsCategoriesWithLimit(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestCategories(5, $user); - $response = $this->get(route('api.v1.autocomplete.categories', [ - 'query' => 'Category', - 'limit' => 3, - ]), ['Accept' => 'application/json']); + $response = $this->get(route('api.v1.autocomplete.categories', ['query' => 'Category', 'limit' => 3]), ['Accept' => 'application/json']); $response->assertStatus(200); $response->assertHeader('Content-Type', 'application/json'); @@ -112,14 +99,11 @@ final class CategoryControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheCategoriesEndpointWithQueryThenReturnsCategoriesThatMatchQuery(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestCategories(20, $user); - $response = $this->get(route('api.v1.autocomplete.categories', [ - 'query' => 'Category 1', - 'limit' => 20, - ]), ['Accept' => 'application/json']); + $response = $this->get(route('api.v1.autocomplete.categories', ['query' => 'Category 1', 'limit' => 20]), ['Accept' => 'application/json']); $response->assertStatus(200); $response->assertHeader('Content-Type', 'application/json'); diff --git a/tests/integration/Api/Autocomplete/CurrencyControllerTest.php b/tests/integration/Api/Autocomplete/CurrencyControllerTest.php index a034b6c728..85ad1a4c9e 100644 --- a/tests/integration/Api/Autocomplete/CurrencyControllerTest.php +++ b/tests/integration/Api/Autocomplete/CurrencyControllerTest.php @@ -46,11 +46,11 @@ final class CurrencyControllerTest extends TestCase { for ($i = 1; $i <= $count; ++$i) { $currency = TransactionCurrency::create([ - 'name' => 'Currency '.$i, - 'code' => 'CUR'.$i, - 'symbol' => 'C'.$i, + 'name' => 'Currency ' . $i, + 'code' => 'CUR' . $i, + 'symbol' => 'C' . $i, 'decimal_places' => $i, - 'enabled' => $enabled, + 'enabled' => $enabled ]); } } @@ -67,7 +67,7 @@ final class CurrencyControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheCurrenciesEndpointThenReturns200HttpCode(): void { // act as a user - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); // test API @@ -79,7 +79,7 @@ final class CurrencyControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheCurrenciesEndpointThenReturnsACollectionOfEnabledCurrencies(): void { // act as a user - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); // create test data @@ -91,15 +91,7 @@ final class CurrencyControllerTest extends TestCase $response->assertHeader('Content-Type', 'application/json'); $response->assertJsonFragment(['name' => 'Currency 1']); $response->assertJsonFragment(['code' => 'CUR1']); - $response->assertJsonStructure([ - '*' => [ - 'id', - 'name', - 'code', - 'symbol', - 'decimal_places', - ], - ]); + $response->assertJsonStructure(['*' => ['id', 'name', 'code', 'symbol', 'decimal_places']]); $response->assertJsonCount(10); } @@ -107,7 +99,7 @@ final class CurrencyControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheCurrenciesEndpointDoesNotReturnDisabledCurrencies(): void { // act as a user - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); // create test data @@ -123,7 +115,7 @@ final class CurrencyControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheCurrenciesEndpointWithQueryThenReturnsCurrenciesWithLimit(): void { // act as a user - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); // create test data @@ -134,30 +126,18 @@ final class CurrencyControllerTest extends TestCase $response->assertStatus(200); $response->assertHeader('Content-Type', 'application/json'); $response->assertJsonFragment(['name' => 'Currency 1']); - $response->assertJsonStructure([ - '*' => [ - 'id', - 'name', - 'code', - 'symbol', - 'decimal_places', - ], - ]); + $response->assertJsonStructure(['*' => ['id', 'name', 'code', 'symbol', 'decimal_places']]); $response->assertJsonCount(1); - } public function testGivenAuthenticatedRequestWhenCallingTheCurrenciesEndpointWithQueryThenReturnsCurrenciesThatMatchQuery(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestCurrencies(20, true); - $response = $this->get(route('api.v1.autocomplete.currencies', [ - 'query' => 'Currency 1', - 'limit' => 20, - ]), ['Accept' => 'application/json']); + $response = $this->get(route('api.v1.autocomplete.currencies', ['query' => 'Currency 1', 'limit' => 20]), ['Accept' => 'application/json']); $response->assertStatus(200); $response->assertHeader('Content-Type', 'application/json'); // Currency 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 (11) diff --git a/tests/integration/Api/Autocomplete/ObjectGroupControllerTest.php b/tests/integration/Api/Autocomplete/ObjectGroupControllerTest.php index e714115793..809e0e3e6f 100644 --- a/tests/integration/Api/Autocomplete/ObjectGroupControllerTest.php +++ b/tests/integration/Api/Autocomplete/ObjectGroupControllerTest.php @@ -25,9 +25,9 @@ declare(strict_types=1); namespace Tests\integration\Api\Autocomplete; use FireflyIII\Models\ObjectGroup; +use FireflyIII\User; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\integration\TestCase; -use FireflyIII\User; /** * Class ObjectGroupControllerTest @@ -47,10 +47,10 @@ final class ObjectGroupControllerTest extends TestCase { for ($i = 1; $i <= $count; ++$i) { $objectGroup = ObjectGroup::create([ - 'title' => 'Object Group '.$i, + 'title' => 'Object Group ' . $i, 'order' => $i, 'user_group_id' => $user->user_group_id, - 'user_id' => $user->id, + 'user_id' => $user->id ]); } } @@ -66,7 +66,7 @@ final class ObjectGroupControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheObjectGroupsEndpointThenReturns200HttpCode(): void { // act as a user - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); // test API @@ -77,7 +77,7 @@ final class ObjectGroupControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheObjectGroupsEndpointThenReturnsObjectGroups(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestObjectGroups(5, $user); @@ -86,50 +86,31 @@ final class ObjectGroupControllerTest extends TestCase $response->assertHeader('Content-Type', 'application/json'); $response->assertJsonCount(5); $response->assertJsonFragment(['title' => 'Object Group 1']); - $response->assertJsonStructure([ - '*' => [ - 'id', - 'name', - 'title', - ], - ]); + $response->assertJsonStructure(['*' => ['id', 'name', 'title']]); } public function testGivenAuthenticatedRequestWhenCallingTheObjectGroupsEndpointWithQueryThenReturnsObjectGroupsWithLimit(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestObjectGroups(5, $user); - $response = $this->get(route('api.v1.autocomplete.object-groups', [ - 'query' => 'Object Group', - 'limit' => 3, - ]), ['Accept' => 'application/json']); + $response = $this->get(route('api.v1.autocomplete.object-groups', ['query' => 'Object Group', 'limit' => 3]), ['Accept' => 'application/json']); $response->assertStatus(200); $response->assertHeader('Content-Type', 'application/json'); $response->assertJsonCount(3); $response->assertJsonFragment(['name' => 'Object Group 1']); - $response->assertJsonStructure([ - '*' => [ - 'id', - 'name', - 'title', - ], - ]); - + $response->assertJsonStructure(['*' => ['id', 'name', 'title']]); } public function testGivenAuthenticatedRequestWhenCallingTheObjectGroupsEndpointWithQueryThenReturnsObjectGroupsThatMatchQuery(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestObjectGroups(20, $user); - $response = $this->get(route('api.v1.autocomplete.object-groups', [ - 'query' => 'Object Group 1', - 'limit' => 20, - ]), ['Accept' => 'application/json']); + $response = $this->get(route('api.v1.autocomplete.object-groups', ['query' => 'Object Group 1', 'limit' => 20]), ['Accept' => 'application/json']); $response->assertStatus(200); $response->assertHeader('Content-Type', 'application/json'); diff --git a/tests/integration/Api/Autocomplete/PiggyBankControllerTest.php b/tests/integration/Api/Autocomplete/PiggyBankControllerTest.php index ce62738b74..74ee91f5a8 100644 --- a/tests/integration/Api/Autocomplete/PiggyBankControllerTest.php +++ b/tests/integration/Api/Autocomplete/PiggyBankControllerTest.php @@ -49,41 +49,31 @@ final class PiggyBankControllerTest extends TestCase private function createTestPiggyBanks(int $count, User $user): void { - $type = AccountType::whereType(AccountTypeEnum::DEFAULT->value)->first(); + $type = AccountType::whereType(AccountTypeEnum::DEFAULT->value)->first(); if (null === $type) { $type = AccountType::create(['type' => AccountTypeEnum::DEFAULT->value]); } $currency = TransactionCurrency::whereCode('EUR')->first(); if (null === $currency) { - $currency = TransactionCurrency::create( - [ - 'code' => 'EUR', - 'name' => 'Euro', - 'symbol' => '€', - ] - ); + $currency = TransactionCurrency::create(['code' => 'EUR', 'name' => 'Euro', 'symbol' => '€']); } for ($i = 1; $i <= $count; ++$i) { - $piggyBank = PiggyBank::create( - [ - 'user_id' => $user->id, - 'name' => 'Piggy bank '.$i, - 'target_amount' => 1000, - 'transaction_currency_id' => $currency->id, - 'target_date' => now()->addDays(30), - 'user_group_id' => $user->user_group_id, - 'active' => 1, - ] - ); - $account = Account::create( - [ - 'user_id' => $user->id, - 'name' => 'Account '.$i, - 'user_group_id' => $user->user_group_id, - 'account_type_id' => $type->id, - 'active' => 1, - ] - ); + $piggyBank = PiggyBank::create([ + 'user_id' => $user->id, + 'name' => 'Piggy bank ' . $i, + 'target_amount' => 1000, + 'transaction_currency_id' => $currency->id, + 'target_date' => now()->addDays(30), + 'user_group_id' => $user->user_group_id, + 'active' => 1 + ]); + $account = Account::create([ + 'user_id' => $user->id, + 'name' => 'Account ' . $i, + 'user_group_id' => $user->user_group_id, + 'account_type_id' => $type->id, + 'active' => 1 + ]); $piggyBank->accounts()->save($account); } } @@ -100,18 +90,17 @@ final class PiggyBankControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheBudgetsEndpointThenReturns200HttpCode(): void { // act as a user - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $response = $this->get(route('api.v1.autocomplete.piggy-banks'), ['Accept' => 'application/json']); $response->assertStatus(200); $response->assertHeader('Content-Type', 'application/json'); - } public function testGivenAuthenticatedRequestWhenCallingTheBudgetsEndpointThenReturnsBudgets(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestPiggyBanks(5, $user); @@ -120,24 +109,16 @@ final class PiggyBankControllerTest extends TestCase $response->assertHeader('Content-Type', 'application/json'); $response->assertJsonCount(5); $response->assertJsonFragment(['name' => 'Piggy bank 1']); - $response->assertJsonStructure([ - '*' => [ - 'id', - 'name', - ], - ]); + $response->assertJsonStructure(['*' => ['id', 'name']]); } public function testGivenAuthenticatedRequestWhenCallingTheBudgetsEndpointWithQueryThenReturnsBudgetsWithLimit(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestPiggyBanks(5, $user); - $response = $this->get(route('api.v1.autocomplete.piggy-banks', [ - 'query' => 'Piggy', - 'limit' => 3, - ]), ['Accept' => 'application/json']); + $response = $this->get(route('api.v1.autocomplete.piggy-banks', ['query' => 'Piggy', 'limit' => 3]), ['Accept' => 'application/json']); $response->assertStatus(200); $response->assertHeader('Content-Type', 'application/json'); @@ -146,14 +127,11 @@ final class PiggyBankControllerTest extends TestCase public function testGivenAuthenticatedRequestWhenCallingTheBudgetsEndpointWithQueryThenReturnsBudgetsThatMatchQuery(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestPiggyBanks(20, $user); - $response = $this->get(route('api.v1.autocomplete.piggy-banks', [ - 'query' => 'Piggy bank 1', - 'limit' => 20, - ]), ['Accept' => 'application/json']); + $response = $this->get(route('api.v1.autocomplete.piggy-banks', ['query' => 'Piggy bank 1', 'limit' => 20]), ['Accept' => 'application/json']); $response->assertStatus(200); $response->assertHeader('Content-Type', 'application/json'); diff --git a/tests/integration/Api/Autocomplete/RecurrenceControllerTest.php b/tests/integration/Api/Autocomplete/RecurrenceControllerTest.php index 4eee2178ac..6bb2f36d41 100644 --- a/tests/integration/Api/Autocomplete/RecurrenceControllerTest.php +++ b/tests/integration/Api/Autocomplete/RecurrenceControllerTest.php @@ -50,13 +50,12 @@ final class RecurrenceControllerTest extends TestCase 'user_id' => $user->id, 'user_group_id' => $user->user_group_id, 'transaction_type_id' => 1, - 'title' => 'Recurrence '.$i, - 'description' => 'Recurrence '.$i, + 'title' => 'Recurrence ' . $i, + 'description' => 'Recurrence ' . $i, 'first_date' => today(), 'apply_rules' => 1, 'active' => 1, - 'repetitions' => 5, - + 'repetitions' => 5 ]); } } @@ -73,7 +72,7 @@ final class RecurrenceControllerTest extends TestCase public function testAuthenticatedCall(): void { // act as a user - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $response = $this->get(route('api.v1.autocomplete.recurring'), ['Accept' => 'application/json']); @@ -83,7 +82,7 @@ final class RecurrenceControllerTest extends TestCase public function testGivenAuthenticatedRequestWithItems(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestRecurrences(5, $user); @@ -92,51 +91,31 @@ final class RecurrenceControllerTest extends TestCase $response->assertHeader('Content-Type', 'application/json'); $response->assertJsonCount(5); $response->assertJsonFragment(['name' => 'Recurrence 1']); - $response->assertJsonStructure([ - '*' => [ - 'id', - 'name', - 'active', - ], - ]); - + $response->assertJsonStructure(['*' => ['id', 'name', 'active']]); } public function testGivenAuthenticatedRequestWithItemsLimited(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestRecurrences(5, $user); - $response = $this->get(route('api.v1.autocomplete.recurring', [ - 'query' => 'Recurrence', - 'limit' => 3, - ]), ['Accept' => 'application/json']); + $response = $this->get(route('api.v1.autocomplete.recurring', ['query' => 'Recurrence', 'limit' => 3]), ['Accept' => 'application/json']); $response->assertStatus(200); $response->assertHeader('Content-Type', 'application/json'); $response->assertJsonCount(3); $response->assertJsonFragment(['name' => 'Recurrence 1']); - $response->assertJsonStructure([ - '*' => [ - 'id', - 'name', - 'active', - ], - ]); - + $response->assertJsonStructure(['*' => ['id', 'name', 'active']]); } public function testGivenAuthenticatedRequestWithItemsLots(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestRecurrences(20, $user); - $response = $this->get(route('api.v1.autocomplete.recurring', [ - 'query' => 'Recurrence 1', - 'limit' => 20, - ]), ['Accept' => 'application/json']); + $response = $this->get(route('api.v1.autocomplete.recurring', ['query' => 'Recurrence 1', 'limit' => 20]), ['Accept' => 'application/json']); $response->assertStatus(200); $response->assertHeader('Content-Type', 'application/json'); diff --git a/tests/integration/Api/Autocomplete/RuleControllerTest.php b/tests/integration/Api/Autocomplete/RuleControllerTest.php index 7edba01b43..c999e9a8cf 100644 --- a/tests/integration/Api/Autocomplete/RuleControllerTest.php +++ b/tests/integration/Api/Autocomplete/RuleControllerTest.php @@ -44,28 +44,26 @@ final class RuleControllerTest extends TestCase private function createTestRules(int $count, User $user): void { - $ruleGroup = RuleGroup::create( - [ - 'user_id' => $user->id, - 'user_group_id' => $user->user_group_id, - 'title' => 'RuleGroup 1', - 'description' => 'RuleGroup 1', - 'order' => 1, - 'active' => 1, - 'stop_processing' => 0, - ] - ); + $ruleGroup = RuleGroup::create([ + 'user_id' => $user->id, + 'user_group_id' => $user->user_group_id, + 'title' => 'RuleGroup 1', + 'description' => 'RuleGroup 1', + 'order' => 1, + 'active' => 1, + 'stop_processing' => 0 + ]); for ($i = 1; $i <= $count; ++$i) { $rule = Rule::create([ - 'user_id' => $user->id, - 'user_group_id' => $user->user_group_id, - 'rule_group_id' => $ruleGroup->id, - 'title' => 'Rule '.$i, - 'description' => 'Rule '.$i, - 'order' => 1, - 'active' => 1, - 'stop_processing' => 0, - 'strict' => 0, + 'user_id' => $user->id, + 'user_group_id' => $user->user_group_id, + 'rule_group_id' => $ruleGroup->id, + 'title' => 'Rule ' . $i, + 'description' => 'Rule ' . $i, + 'order' => 1, + 'active' => 1, + 'stop_processing' => 0, + 'strict' => 0 ]); } } @@ -82,7 +80,7 @@ final class RuleControllerTest extends TestCase public function testAuthenticatedCall(): void { // act as a user - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $response = $this->get(route('api.v1.autocomplete.rules'), ['Accept' => 'application/json']); @@ -92,7 +90,7 @@ final class RuleControllerTest extends TestCase public function testGivenAuthenticatedRequestWithItems(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestRules(5, $user); @@ -101,51 +99,31 @@ final class RuleControllerTest extends TestCase $response->assertHeader('Content-Type', 'application/json'); $response->assertJsonCount(5); $response->assertJsonFragment(['name' => 'Rule 1']); - $response->assertJsonStructure([ - '*' => [ - 'id', - 'name', - 'active', - ], - ]); - + $response->assertJsonStructure(['*' => ['id', 'name', 'active']]); } public function testGivenAuthenticatedRequestWithItemsLimited(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestRules(5, $user); - $response = $this->get(route('api.v1.autocomplete.rules', [ - 'query' => 'Rule', - 'limit' => 3, - ]), ['Accept' => 'application/json']); + $response = $this->get(route('api.v1.autocomplete.rules', ['query' => 'Rule', 'limit' => 3]), ['Accept' => 'application/json']); $response->assertStatus(200); $response->assertHeader('Content-Type', 'application/json'); $response->assertJsonCount(3); $response->assertJsonFragment(['name' => 'Rule 1']); - $response->assertJsonStructure([ - '*' => [ - 'id', - 'name', - 'active', - ], - ]); - + $response->assertJsonStructure(['*' => ['id', 'name', 'active']]); } public function testGivenAuthenticatedRequestWithItemsLots(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestRules(20, $user); - $response = $this->get(route('api.v1.autocomplete.rules', [ - 'query' => 'Rule 1', - 'limit' => 20, - ]), ['Accept' => 'application/json']); + $response = $this->get(route('api.v1.autocomplete.rules', ['query' => 'Rule 1', 'limit' => 20]), ['Accept' => 'application/json']); $response->assertStatus(200); $response->assertHeader('Content-Type', 'application/json'); diff --git a/tests/integration/Api/Autocomplete/RuleGroupControllerTest.php b/tests/integration/Api/Autocomplete/RuleGroupControllerTest.php index 3e4aa26e5d..fcb3b88f6e 100644 --- a/tests/integration/Api/Autocomplete/RuleGroupControllerTest.php +++ b/tests/integration/Api/Autocomplete/RuleGroupControllerTest.php @@ -43,19 +43,16 @@ final class RuleGroupControllerTest extends TestCase private function createTestRuleGroups(int $count, User $user): void { - for ($i = 1; $i <= $count; ++$i) { - $ruleGroup = RuleGroup::create( - [ - 'user_id' => $user->id, - 'user_group_id' => $user->user_group_id, - 'title' => 'RuleGroup '.$i, - 'description' => 'RuleGroup '.$i, - 'order' => 1, - 'active' => 1, - 'stop_processing' => 0, - ] - ); + $ruleGroup = RuleGroup::create([ + 'user_id' => $user->id, + 'user_group_id' => $user->user_group_id, + 'title' => 'RuleGroup ' . $i, + 'description' => 'RuleGroup ' . $i, + 'order' => 1, + 'active' => 1, + 'stop_processing' => 0 + ]); } } @@ -71,7 +68,7 @@ final class RuleGroupControllerTest extends TestCase public function testAuthenticatedCall(): void { // act as a user - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $response = $this->get(route('api.v1.autocomplete.rule-groups'), ['Accept' => 'application/json']); @@ -81,7 +78,7 @@ final class RuleGroupControllerTest extends TestCase public function testGivenAuthenticatedRequestWithItems(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestRuleGroups(5, $user); @@ -90,51 +87,31 @@ final class RuleGroupControllerTest extends TestCase $response->assertHeader('Content-Type', 'application/json'); $response->assertJsonCount(5); $response->assertJsonFragment(['name' => 'RuleGroup 1']); - $response->assertJsonStructure([ - '*' => [ - 'id', - 'name', - 'active', - ], - ]); - + $response->assertJsonStructure(['*' => ['id', 'name', 'active']]); } public function testGivenAuthenticatedRequestWithItemsLimited(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestRuleGroups(5, $user); - $response = $this->get(route('api.v1.autocomplete.rule-groups', [ - 'query' => 'RuleGroup', - 'limit' => 3, - ]), ['Accept' => 'application/json']); + $response = $this->get(route('api.v1.autocomplete.rule-groups', ['query' => 'RuleGroup', 'limit' => 3]), ['Accept' => 'application/json']); $response->assertStatus(200); $response->assertHeader('Content-Type', 'application/json'); $response->assertJsonCount(3); $response->assertJsonFragment(['name' => 'RuleGroup 1']); - $response->assertJsonStructure([ - '*' => [ - 'id', - 'name', - 'active', - ], - ]); - + $response->assertJsonStructure(['*' => ['id', 'name', 'active']]); } public function testGivenAuthenticatedRequestWithItemsLots(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestRuleGroups(20, $user); - $response = $this->get(route('api.v1.autocomplete.rule-groups', [ - 'query' => 'RuleGroup 1', - 'limit' => 20, - ]), ['Accept' => 'application/json']); + $response = $this->get(route('api.v1.autocomplete.rule-groups', ['query' => 'RuleGroup 1', 'limit' => 20]), ['Accept' => 'application/json']); $response->assertStatus(200); $response->assertHeader('Content-Type', 'application/json'); diff --git a/tests/integration/Api/Autocomplete/TagControllerTest.php b/tests/integration/Api/Autocomplete/TagControllerTest.php index 2f947b491a..aaf04388c0 100644 --- a/tests/integration/Api/Autocomplete/TagControllerTest.php +++ b/tests/integration/Api/Autocomplete/TagControllerTest.php @@ -43,16 +43,13 @@ final class TagControllerTest extends TestCase private function createTestTags(int $count, User $user): void { - for ($i = 1; $i <= $count; ++$i) { - $tag = Tag::create( - [ - 'user_id' => $user->id, - 'user_group_id' => $user->user_group_id, - 'tag' => 'Tag '.$i, - 'tag_mode' => 'nothing', - ] - ); + $tag = Tag::create([ + 'user_id' => $user->id, + 'user_group_id' => $user->user_group_id, + 'tag' => 'Tag ' . $i, + 'tag_mode' => 'nothing' + ]); } } @@ -68,7 +65,7 @@ final class TagControllerTest extends TestCase public function testAuthenticatedCall(): void { // act as a user - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $response = $this->get(route('api.v1.autocomplete.tags'), ['Accept' => 'application/json']); @@ -78,7 +75,7 @@ final class TagControllerTest extends TestCase public function testGivenAuthenticatedRequestWithItems(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestTags(5, $user); @@ -87,51 +84,31 @@ final class TagControllerTest extends TestCase $response->assertHeader('Content-Type', 'application/json'); $response->assertJsonCount(5); $response->assertJsonFragment(['name' => 'Tag 1']); - $response->assertJsonStructure([ - '*' => [ - 'id', - 'name', - 'tag', - ], - ]); - + $response->assertJsonStructure(['*' => ['id', 'name', 'tag']]); } public function testGivenAuthenticatedRequestWithItemsLimited(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestTags(5, $user); - $response = $this->get(route('api.v1.autocomplete.tags', [ - 'query' => 'Tag', - 'limit' => 3, - ]), ['Accept' => 'application/json']); + $response = $this->get(route('api.v1.autocomplete.tags', ['query' => 'Tag', 'limit' => 3]), ['Accept' => 'application/json']); $response->assertStatus(200); $response->assertHeader('Content-Type', 'application/json'); $response->assertJsonCount(3); $response->assertJsonFragment(['name' => 'Tag 1']); - $response->assertJsonStructure([ - '*' => [ - 'id', - 'name', - 'tag', - ], - ]); - + $response->assertJsonStructure(['*' => ['id', 'name', 'tag']]); } public function testGivenAuthenticatedRequestWithItemsLots(): void { - $user = $this->createAuthenticatedUser(); + $user = $this->createAuthenticatedUser(); $this->actingAs($user); $this->createTestTags(20, $user); - $response = $this->get(route('api.v1.autocomplete.tags', [ - 'query' => 'Tag 1', - 'limit' => 20, - ]), ['Accept' => 'application/json']); + $response = $this->get(route('api.v1.autocomplete.tags', ['query' => 'Tag 1', 'limit' => 20]), ['Accept' => 'application/json']); $response->assertStatus(200); $response->assertHeader('Content-Type', 'application/json'); diff --git a/tests/integration/Api/Chart/AccountControllerTest.php b/tests/integration/Api/Chart/AccountControllerTest.php index fbb60429c0..0389401578 100644 --- a/tests/integration/Api/Chart/AccountControllerTest.php +++ b/tests/integration/Api/Chart/AccountControllerTest.php @@ -1,6 +1,5 @@ actingAs($this->user); $response = $this->getJson(route('api.v1.chart.account.overview')); $response->assertStatus(422); - } public function testGetOverviewChart(): void { $this->actingAs($this->user); - $params = [ - 'start' => '2024-01-01', - 'end' => '2024-01-31', - ]; - $response = $this->getJson(route('api.v1.chart.account.overview').'?'.http_build_query($params)); + $params = ['start' => '2024-01-01', 'end' => '2024-01-31']; + $response = $this->getJson(route('api.v1.chart.account.overview') . '?' . http_build_query($params)); $response->assertStatus(200); - } } diff --git a/tests/integration/Api/Chart/BalanceControllerTest.php b/tests/integration/Api/Chart/BalanceControllerTest.php index bcfc308467..ffcba4996a 100644 --- a/tests/integration/Api/Chart/BalanceControllerTest.php +++ b/tests/integration/Api/Chart/BalanceControllerTest.php @@ -1,6 +1,5 @@ actingAs($this->user); $response = $this->getJson(route('api.v1.chart.balance.balance')); $response->assertStatus(422); - } public function testGetOverviewChart(): void { $this->actingAs($this->user); - $params = [ - 'start' => '2024-01-01', - 'end' => '2024-01-31', - ]; - $response = $this->getJson(route('api.v1.chart.balance.balance').'?'.http_build_query($params)); + $params = ['start' => '2024-01-01', 'end' => '2024-01-31']; + $response = $this->getJson(route('api.v1.chart.balance.balance') . '?' . http_build_query($params)); $response->assertStatus(200); - } } diff --git a/tests/integration/Api/Chart/BudgetControllerTest.php b/tests/integration/Api/Chart/BudgetControllerTest.php index f565dcda28..639b540931 100644 --- a/tests/integration/Api/Chart/BudgetControllerTest.php +++ b/tests/integration/Api/Chart/BudgetControllerTest.php @@ -1,6 +1,5 @@ actingAs($this->user); $response = $this->getJson(route('api.v1.chart.budget.overview')); $response->assertStatus(422); - } public function testGetOverviewChart(): void { $this->actingAs($this->user); - $params = [ - 'start' => '2024-01-01', - 'end' => '2024-01-31', - ]; - $response = $this->getJson(route('api.v1.chart.budget.overview').'?'.http_build_query($params)); + $params = ['start' => '2024-01-01', 'end' => '2024-01-31']; + $response = $this->getJson(route('api.v1.chart.budget.overview') . '?' . http_build_query($params)); $response->assertStatus(200); - } } diff --git a/tests/integration/Api/Chart/CategoryControllerTest.php b/tests/integration/Api/Chart/CategoryControllerTest.php index ed77df6a98..25e917ad3e 100644 --- a/tests/integration/Api/Chart/CategoryControllerTest.php +++ b/tests/integration/Api/Chart/CategoryControllerTest.php @@ -1,6 +1,5 @@ actingAs($this->user); $response = $this->getJson(route('api.v1.chart.category.overview')); $response->assertStatus(422); - } public function testGetOverviewChart(): void { $this->actingAs($this->user); - $params = [ - 'start' => '2024-01-01', - 'end' => '2024-01-31', - ]; - $response = $this->getJson(route('api.v1.chart.category.overview').'?'.http_build_query($params)); + $params = ['start' => '2024-01-01', 'end' => '2024-01-31']; + $response = $this->getJson(route('api.v1.chart.category.overview') . '?' . http_build_query($params)); $response->assertStatus(200); - } } diff --git a/tests/integration/Api/Models/Account/ListControllerTest.php b/tests/integration/Api/Models/Account/ListControllerTest.php index 2d508a7796..d04f0c183c 100644 --- a/tests/integration/Api/Models/Account/ListControllerTest.php +++ b/tests/integration/Api/Models/Account/ListControllerTest.php @@ -1,6 +1,5 @@ user = $this->createAuthenticatedUser(); + $this->user = $this->createAuthenticatedUser(); $this->actingAs($this->user); - $this->account = Account::factory()->for($this->user)->withType(AccountTypeEnum::ASSET)->create(); - app(AttachmentFactory::class)->setUser($this->user)->create([ - 'filename' => 'test 1', - 'title' => 'test 1', - 'attachable_type' => Account::class, - 'attachable_id' => $this->account->id, - ]); - app(AttachmentFactory::class)->setUser($this->user)->create([ - 'filename' => 'test 2', - 'title' => 'test 2', - 'attachable_type' => Account::class, - 'attachable_id' => $this->account->id, - ]); + $this->account = Account::factory() + ->for($this->user) + ->withType(AccountTypeEnum::ASSET) + ->create(); + app(AttachmentFactory::class) + ->setUser($this->user) + ->create([ + 'filename' => 'test 1', + 'title' => 'test 1', + 'attachable_type' => Account::class, + 'attachable_id' => $this->account->id + ]); + app(AttachmentFactory::class) + ->setUser($this->user) + ->create([ + 'filename' => 'test 2', + 'title' => 'test 2', + 'attachable_type' => Account::class, + 'attachable_id' => $this->account->id + ]); } public function testIndex(): void @@ -72,18 +79,14 @@ final class ListControllerTest extends TestCase $this->actingAs($this->user); $response = $this->getJson(route('api.v1.accounts.attachments', ['account' => $this->account->id])); $response->assertStatus(200); - $response->assertJson([ - 'meta' => ['pagination' => ['total' => 2, 'total_pages' => 1]], - ]); + $response->assertJson(['meta' => ['pagination' => ['total' => 2, 'total_pages' => 1]]]); } public function testIndexCanChangePageSize(): void { $this->actingAs($this->user); - $response = $this->getJson(route('api.v1.accounts.attachments', ['account' => $this->account->id, 'limit' => 1])); + $response = $this->getJson(route('api.v1.accounts.attachments', ['account' => $this->account->id, 'limit' => 1])); $response->assertStatus(200); - $response->assertJson([ - 'meta' => ['pagination' => ['total' => 2, 'total_pages' => 2]], - ]); + $response->assertJson(['meta' => ['pagination' => ['total' => 2, 'total_pages' => 2]]]); } } diff --git a/tests/integration/Api/Models/Account/ShowControllerTest.php b/tests/integration/Api/Models/Account/ShowControllerTest.php index c80943f01d..97a2397797 100644 --- a/tests/integration/Api/Models/Account/ShowControllerTest.php +++ b/tests/integration/Api/Models/Account/ShowControllerTest.php @@ -1,6 +1,5 @@ user = $this->createAuthenticatedUser(); $this->actingAs($this->user); - Account::factory()->for($this->user)->withType(AccountTypeEnum::ASSET)->create(); - Account::factory()->for($this->user)->withType(AccountTypeEnum::REVENUE)->create(); - Account::factory()->for($this->user)->withType(AccountTypeEnum::EXPENSE)->create(); - Account::factory()->for($this->user)->withType(AccountTypeEnum::DEBT)->create(); - Account::factory()->for($this->user)->withType(AccountTypeEnum::ASSET)->create(); + Account::factory() + ->for($this->user) + ->withType(AccountTypeEnum::ASSET) + ->create(); + Account::factory() + ->for($this->user) + ->withType(AccountTypeEnum::REVENUE) + ->create(); + Account::factory() + ->for($this->user) + ->withType(AccountTypeEnum::EXPENSE) + ->create(); + Account::factory() + ->for($this->user) + ->withType(AccountTypeEnum::DEBT) + ->create(); + Account::factory() + ->for($this->user) + ->withType(AccountTypeEnum::ASSET) + ->create(); } public function testIndex(): void @@ -62,15 +77,13 @@ final class ShowControllerTest extends TestCase $this->actingAs($this->user); $response = $this->getJson(route('api.v1.accounts.index')); $response->assertStatus(200); - $response->assertJson([ - 'meta' => ['pagination' => ['total' => 5]], - ]); + $response->assertJson(['meta' => ['pagination' => ['total' => 5]]]); } public function testIndexFailsOnUnknownAccountType(): void { $this->actingAs($this->user); - $response = $this->getJson(route('api.v1.accounts.index').'?type=foobar'); + $response = $this->getJson(route('api.v1.accounts.index') . '?type=foobar'); $response->assertStatus(422); $response->assertJson(['errors' => ['type' => ['The selected type is invalid.']]]); } @@ -78,14 +91,11 @@ final class ShowControllerTest extends TestCase public function testIndexCanFilterOnAccountType(): void { $this->actingAs($this->user); - $response = $this->getJson(route('api.v1.accounts.index').'?type=asset'); + $response = $this->getJson(route('api.v1.accounts.index') . '?type=asset'); $response->assertStatus(200); $response->assertJson([ - 'data' => [ - ['attributes' => ['type' => 'asset']], - ['attributes' => ['type' => 'asset']], - ], - 'meta' => ['pagination' => ['total' => 2]], + 'data' => [['attributes' => ['type' => 'asset']], ['attributes' => ['type' => 'asset']]], + 'meta' => ['pagination' => ['total' => 2]] ]); } } diff --git a/tests/integration/Api/System/AboutControllerTest.php b/tests/integration/Api/System/AboutControllerTest.php index 71db85f1ea..3a41fee2ba 100644 --- a/tests/integration/Api/System/AboutControllerTest.php +++ b/tests/integration/Api/System/AboutControllerTest.php @@ -27,8 +27,8 @@ namespace Tests\integration\Api\System; use FireflyIII\User; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Testing\Fluent\AssertableJson; -use Tests\integration\TestCase; use Override; +use Tests\integration\TestCase; /** * Class AboutControllerTest @@ -40,7 +40,8 @@ use Override; final class AboutControllerTest extends TestCase { use RefreshDatabase; - private ?User $user = null; + + private null|User $user = null; #[Override] protected function setUp(): void @@ -58,15 +59,7 @@ final class AboutControllerTest extends TestCase $response = $this->getJson(route('api.v1.about.index')); $response->assertOk(); - $response->assertJsonStructure([ - 'data' => [ - 'version', - 'api_version', - 'php_version', - 'os', - 'driver', - ], - ]); + $response->assertJsonStructure(['data' => ['version', 'api_version', 'php_version', 'os', 'driver']]); } public function testGivenAuthenticatedRequestReturnsUserInformation(): void @@ -74,10 +67,9 @@ final class AboutControllerTest extends TestCase $response = $this->getJson(route('api.v1.about.user')); $response->assertOk(); - $response->assertJson( - fn (AssertableJson $json): AssertableJson => $json - ->where('data.attributes.email', $this->user->email) - ->where('data.attributes.role', $this->user->role) - ); + $response->assertJson(fn(AssertableJson $json): AssertableJson => $json->where('data.attributes.email', $this->user->email)->where( + 'data.attributes.role', + $this->user->role + )); } } diff --git a/tests/integration/CreatesApplication.php b/tests/integration/CreatesApplication.php index 7c0e8f8d93..307527ac68 100644 --- a/tests/integration/CreatesApplication.php +++ b/tests/integration/CreatesApplication.php @@ -38,7 +38,7 @@ trait CreatesApplication */ public function createApplication() { - $app = require __DIR__.'/../../bootstrap/app.php'; + $app = require __DIR__ . '/../../bootstrap/app.php'; $app->make(Kernel::class)->bootstrap(); diff --git a/tests/integration/Support/Models/BillDateCalculatorTest.php b/tests/integration/Support/Models/BillDateCalculatorTest.php index 6402bf4328..99fcdfd521 100644 --- a/tests/integration/Support/Models/BillDateCalculatorTest.php +++ b/tests/integration/Support/Models/BillDateCalculatorTest.php @@ -24,9 +24,9 @@ declare(strict_types=1); namespace Tests\integration\Support\Models; -use Override; use Carbon\Carbon; use FireflyIII\Support\Models\BillDateCalculator; +use Override; use PHPUnit\Framework\Attributes\DataProvider; use Tests\integration\TestCase; @@ -52,8 +52,15 @@ final class BillDateCalculatorTest extends TestCase * Stupid long method names I'm not going to do that. */ #[DataProvider('provideDates')] - public function testGivenSomeDataItWorks(Carbon $earliest, Carbon $latest, Carbon $billStart, string $period, int $skip, ?Carbon $lastPaid, array $expected): void - { + public function testGivenSomeDataItWorks( + Carbon $earliest, + Carbon $latest, + Carbon $billStart, + string $period, + int $skip, + null|Carbon $lastPaid, + array $expected + ): void { $result = $this->calculator->getPayDates($earliest, $latest, $billStart, $period, $skip, $lastPaid); $this->assertSame($expected, $result); } @@ -65,18 +72,58 @@ final class BillDateCalculatorTest extends TestCase yield '1Ma' => [Carbon::parse('2023-11-01'), Carbon::parse('2023-11-30'), Carbon::parse('2023-01-01'), 'monthly', 0, null, ['2023-11-01']]; // already paid on the first, expect it next month. - yield '1Mb' => [Carbon::parse('2023-11-01'), Carbon::parse('2023-11-30'), Carbon::parse('2023-01-01'), 'monthly', 0, Carbon::parse('2023-11-01'), ['2023-12-01']]; + yield '1Mb' => [ + Carbon::parse('2023-11-01'), + Carbon::parse('2023-11-30'), + Carbon::parse('2023-01-01'), + 'monthly', + 0, + Carbon::parse('2023-11-01'), + ['2023-12-01'] + ]; // already paid on the 12th, expect it next month. - yield '1Mc' => [Carbon::parse('2023-11-01'), Carbon::parse('2023-11-30'), Carbon::parse('2023-01-01'), 'monthly', 0, Carbon::parse('2023-11-12'), ['2023-12-01']]; + yield '1Mc' => [ + Carbon::parse('2023-11-01'), + Carbon::parse('2023-11-30'), + Carbon::parse('2023-01-01'), + 'monthly', + 0, + Carbon::parse('2023-11-12'), + ['2023-12-01'] + ]; // every month, start on 2024-01-30, view is quarterly - yield '1Md' => [Carbon::parse('2023-01-01'), Carbon::parse('2023-03-31'), Carbon::parse('2023-01-29'), 'monthly', 0, null, ['2023-01-29', '2023-02-28', '2023-03-29']]; + yield '1Md' => [ + Carbon::parse('2023-01-01'), + Carbon::parse('2023-03-31'), + Carbon::parse('2023-01-29'), + 'monthly', + 0, + null, + ['2023-01-29', '2023-02-28', '2023-03-29'] + ]; // every month, start on 2024-01-30, view is quarterly - yield '1Me' => [Carbon::parse('2024-01-01'), Carbon::parse('2024-03-31'), Carbon::parse('2023-01-30'), 'monthly', 0, null, ['2024-01-30', '2024-02-29', '2024-03-30']]; + yield '1Me' => [ + Carbon::parse('2024-01-01'), + Carbon::parse('2024-03-31'), + Carbon::parse('2023-01-30'), + 'monthly', + 0, + null, + ['2024-01-30', '2024-02-29', '2024-03-30'] + ]; // yearly not due this month. Should jump to next year. - yield '1Ya' => [Carbon::parse('2023-11-01'), Carbon::parse('2023-11-30'), Carbon::parse('2021-05-01'), 'yearly', 0, Carbon::parse('2023-05-02'), ['2024-05-01']]; + yield '1Ya' => [ + Carbon::parse('2023-11-01'), + Carbon::parse('2023-11-30'), + Carbon::parse('2021-05-01'), + 'yearly', + 0, + Carbon::parse('2023-05-02'), + ['2024-05-01'] + ]; } } diff --git a/tests/integration/Support/NavigationCustomEndOfPeriodTest.php b/tests/integration/Support/NavigationCustomEndOfPeriodTest.php index 16102bc7fc..2eb368022a 100644 --- a/tests/integration/Support/NavigationCustomEndOfPeriodTest.php +++ b/tests/integration/Support/NavigationCustomEndOfPeriodTest.php @@ -44,7 +44,7 @@ final class NavigationCustomEndOfPeriodTest extends TestCase $expected = Carbon::parse('2023-09-04'); $navigation = new Navigation(); - $period = $navigation->endOfPeriod($from, 'custom'); + $period = $navigation->endOfPeriod($from, 'custom'); $this->assertSame($expected->toDateString(), $period->toDateString()); } } diff --git a/tests/integration/TestCase.php b/tests/integration/TestCase.php index e1b42991b2..95a31adcb8 100644 --- a/tests/integration/TestCase.php +++ b/tests/integration/TestCase.php @@ -41,7 +41,8 @@ abstract class TestCase extends BaseTestCase use RefreshDatabase; protected const MAX_ITERATIONS = 2; - protected $seed = true; + + protected $seed = true; public function dateRangeProvider(): array { @@ -52,7 +53,7 @@ abstract class TestCase extends BaseTestCase 'three months' => ['3M'], 'six months' => ['6M'], 'one year' => ['1Y'], - 'custom range' => ['custom'], + 'custom range' => ['custom'] ]; } @@ -65,20 +66,9 @@ abstract class TestCase extends BaseTestCase { $group = UserGroup::create(['title' => 'test@email.com']); $role = UserRole::where('title', 'owner')->first(); - $user = User::create([ - 'email' => 'test@email.com', - 'password' => 'password', - 'user_group_id' => $group->id, - ]); - - GroupMembership::create( - [ - 'user_id' => $user->id, - 'user_group_id' => $group->id, - 'user_role_id' => $role->id, - ] - ); + $user = User::create(['email' => 'test@email.com', 'password' => 'password', 'user_group_id' => $group->id]); + GroupMembership::create(['user_id' => $user->id, 'user_group_id' => $group->id, 'user_role_id' => $role->id]); return $user; } diff --git a/tests/unit/Support/Calendar/CalculatorProvider.php b/tests/unit/Support/Calendar/CalculatorProvider.php index 4133f435ed..72cd29cb39 100644 --- a/tests/unit/Support/Calendar/CalculatorProvider.php +++ b/tests/unit/Support/Calendar/CalculatorProvider.php @@ -26,15 +26,18 @@ namespace Tests\unit\Support\Calendar; use Carbon\Carbon; use FireflyIII\Support\Calendar\Periodicity; -use Tests\unit\Support\Calendar\Periodicity\IntervalProvider; use Generator; +use Tests\unit\Support\Calendar\Periodicity\IntervalProvider; readonly class CalculatorProvider { - public string $label; + public string $label; - private function __construct(public IntervalProvider $intervalProvider, public Periodicity $periodicity, public int $skip = 0) - { + private function __construct( + public IntervalProvider $intervalProvider, + public Periodicity $periodicity, + public int $skip = 0 + ) { $this->label = "{$this->periodicity->name} {$this->intervalProvider->label}"; } @@ -103,7 +106,7 @@ readonly class CalculatorProvider self::from(Periodicity::Yearly, new IntervalProvider(Carbon::now(), Carbon::now()->addYearsNoOverflow(3)), 2), self::from(Periodicity::Yearly, new IntervalProvider(Carbon::parse('2019-01-29'), Carbon::parse('2025-01-29')), 5), - self::from(Periodicity::Yearly, new IntervalProvider(Carbon::parse('2020-02-29'), Carbon::parse('2031-02-28')), 10), + self::from(Periodicity::Yearly, new IntervalProvider(Carbon::parse('2020-02-29'), Carbon::parse('2031-02-28')), 10) ]; /** @var IntervalProvider $interval */ diff --git a/tests/unit/Support/Calendar/CalculatorTest.php b/tests/unit/Support/Calendar/CalculatorTest.php index d6d9677361..78378ece04 100644 --- a/tests/unit/Support/Calendar/CalculatorTest.php +++ b/tests/unit/Support/Calendar/CalculatorTest.php @@ -57,7 +57,7 @@ final class CalculatorTest extends TestCase /** @var IntervalProvider $interval */ foreach ($intervals as $index => $interval) { - $calculator = CalculatorProvider::from($periodicity, $interval); + $calculator = CalculatorProvider::from($periodicity, $interval); $periodicityIntervals["#{$index} {$calculator->label}"] = [$calculator]; } diff --git a/tests/unit/Support/Calendar/Periodicity/BimonthlyTest.php b/tests/unit/Support/Calendar/Periodicity/BimonthlyTest.php index 71bed2a545..df9a8d4378 100644 --- a/tests/unit/Support/Calendar/Periodicity/BimonthlyTest.php +++ b/tests/unit/Support/Calendar/Periodicity/BimonthlyTest.php @@ -24,9 +24,9 @@ declare(strict_types=1); namespace Tests\unit\Support\Calendar\Periodicity; -use FireflyIII\Support\Calendar\Periodicity\Bimonthly; use Carbon\Carbon; use FireflyIII\Support\Calendar\Periodicity; +use FireflyIII\Support\Calendar\Periodicity\Bimonthly; /** * @group unit-test @@ -57,7 +57,7 @@ final class BimonthlyTest extends IntervalTestCase new IntervalProvider(Carbon::parse('2019-11-30'), Carbon::parse('2020-01-30')), new IntervalProvider(Carbon::parse('2020-12-29'), Carbon::parse('2021-02-28')), new IntervalProvider(Carbon::parse('2020-12-30'), Carbon::parse('2021-02-28')), - new IntervalProvider(Carbon::parse('2020-12-31'), Carbon::parse('2021-02-28')), + new IntervalProvider(Carbon::parse('2020-12-31'), Carbon::parse('2021-02-28')) ]; } } diff --git a/tests/unit/Support/Calendar/Periodicity/DailyTest.php b/tests/unit/Support/Calendar/Periodicity/DailyTest.php index 0921b3f0a1..760c963f62 100644 --- a/tests/unit/Support/Calendar/Periodicity/DailyTest.php +++ b/tests/unit/Support/Calendar/Periodicity/DailyTest.php @@ -24,9 +24,9 @@ declare(strict_types=1); namespace Tests\unit\Support\Calendar\Periodicity; -use FireflyIII\Support\Calendar\Periodicity\Daily; use Carbon\Carbon; use FireflyIII\Support\Calendar\Periodicity; +use FireflyIII\Support\Calendar\Periodicity\Daily; /** * @group unit-test @@ -47,9 +47,6 @@ final class DailyTest extends IntervalTestCase public static function provideIntervals(): array { - return [ - new IntervalProvider(Carbon::now(), Carbon::tomorrow()), - new IntervalProvider(Carbon::parse('2023-01-31'), Carbon::parse('2023-02-01')), - ]; + return [new IntervalProvider(Carbon::now(), Carbon::tomorrow()), new IntervalProvider(Carbon::parse('2023-01-31'), Carbon::parse('2023-02-01'))]; } } diff --git a/tests/unit/Support/Calendar/Periodicity/FortnightlyTest.php b/tests/unit/Support/Calendar/Periodicity/FortnightlyTest.php index 095b11b1ac..38c87def6c 100644 --- a/tests/unit/Support/Calendar/Periodicity/FortnightlyTest.php +++ b/tests/unit/Support/Calendar/Periodicity/FortnightlyTest.php @@ -24,9 +24,9 @@ declare(strict_types=1); namespace Tests\unit\Support\Calendar\Periodicity; -use FireflyIII\Support\Calendar\Periodicity\Fortnightly; use Carbon\Carbon; use FireflyIII\Support\Calendar\Periodicity; +use FireflyIII\Support\Calendar\Periodicity\Fortnightly; /** * @group unit-test @@ -49,7 +49,7 @@ final class FortnightlyTest extends IntervalTestCase { return [ new IntervalProvider(Carbon::now(), Carbon::now()->addWeeks(2)), - new IntervalProvider(Carbon::parse('2023-01-31'), Carbon::parse('2023-02-14')), + new IntervalProvider(Carbon::parse('2023-01-31'), Carbon::parse('2023-02-14')) ]; } } diff --git a/tests/unit/Support/Calendar/Periodicity/HalfYearlyTest.php b/tests/unit/Support/Calendar/Periodicity/HalfYearlyTest.php index a30094e41f..8f9727bcd6 100644 --- a/tests/unit/Support/Calendar/Periodicity/HalfYearlyTest.php +++ b/tests/unit/Support/Calendar/Periodicity/HalfYearlyTest.php @@ -24,9 +24,9 @@ declare(strict_types=1); namespace Tests\unit\Support\Calendar\Periodicity; -use FireflyIII\Support\Calendar\Periodicity\HalfYearly; use Carbon\Carbon; use FireflyIII\Support\Calendar\Periodicity; +use FireflyIII\Support\Calendar\Periodicity\HalfYearly; /** * @group unit-test @@ -57,7 +57,7 @@ final class HalfYearlyTest extends IntervalTestCase new IntervalProvider(Carbon::parse('2019-08-30'), Carbon::parse('2020-02-29')), new IntervalProvider(Carbon::parse('2019-08-31'), Carbon::parse('2020-02-29')), new IntervalProvider(Carbon::parse('2020-08-29'), Carbon::parse('2021-02-28')), - new IntervalProvider(Carbon::parse('2020-08-30'), Carbon::parse('2021-02-28')), + new IntervalProvider(Carbon::parse('2020-08-30'), Carbon::parse('2021-02-28')) ]; } } diff --git a/tests/unit/Support/Calendar/Periodicity/IntervalProvider.php b/tests/unit/Support/Calendar/Periodicity/IntervalProvider.php index ec3ed1d784..f469d3b446 100644 --- a/tests/unit/Support/Calendar/Periodicity/IntervalProvider.php +++ b/tests/unit/Support/Calendar/Periodicity/IntervalProvider.php @@ -30,8 +30,10 @@ readonly class IntervalProvider { public string $label; - public function __construct(public Carbon $epoch, public Carbon $expected) - { + public function __construct( + public Carbon $epoch, + public Carbon $expected + ) { $this->label = "given {$this->epoch->toDateString()} expects {$this->expected->toDateString()}"; } } diff --git a/tests/unit/Support/Calendar/Periodicity/MonthlyTest.php b/tests/unit/Support/Calendar/Periodicity/MonthlyTest.php index 1e224da5b6..85a5578ebd 100644 --- a/tests/unit/Support/Calendar/Periodicity/MonthlyTest.php +++ b/tests/unit/Support/Calendar/Periodicity/MonthlyTest.php @@ -24,9 +24,9 @@ declare(strict_types=1); namespace Tests\unit\Support\Calendar\Periodicity; -use FireflyIII\Support\Calendar\Periodicity\Monthly; use Carbon\Carbon; use FireflyIII\Support\Calendar\Periodicity; +use FireflyIII\Support\Calendar\Periodicity\Monthly; /** * @group unit-test @@ -59,7 +59,7 @@ final class MonthlyTest extends IntervalTestCase new IntervalProvider(Carbon::parse('2023-03-31'), Carbon::parse('2023-04-30')), new IntervalProvider(Carbon::parse('2023-05-31'), Carbon::parse('2023-06-30')), // new IntervalProvider(Carbon::parse('2023-08-31'), Carbon::parse('2023-09-30')), - new IntervalProvider(Carbon::parse('2023-10-31'), Carbon::parse('2023-11-30')), + new IntervalProvider(Carbon::parse('2023-10-31'), Carbon::parse('2023-11-30')) ]; } } diff --git a/tests/unit/Support/Calendar/Periodicity/QuarterlyTest.php b/tests/unit/Support/Calendar/Periodicity/QuarterlyTest.php index 4c27daea39..cee10ce3db 100644 --- a/tests/unit/Support/Calendar/Periodicity/QuarterlyTest.php +++ b/tests/unit/Support/Calendar/Periodicity/QuarterlyTest.php @@ -24,9 +24,9 @@ declare(strict_types=1); namespace Tests\unit\Support\Calendar\Periodicity; -use FireflyIII\Support\Calendar\Periodicity\Quarterly; use Carbon\Carbon; use FireflyIII\Support\Calendar\Periodicity; +use FireflyIII\Support\Calendar\Periodicity\Quarterly; /** * @group unit-test @@ -56,7 +56,7 @@ final class QuarterlyTest extends IntervalTestCase new IntervalProvider(Carbon::parse('2019-11-29'), Carbon::parse('2020-02-29')), new IntervalProvider(Carbon::parse('2019-11-30'), Carbon::parse('2020-02-29')), new IntervalProvider(Carbon::parse('2020-11-29'), Carbon::parse('2021-02-28')), - new IntervalProvider(Carbon::parse('2020-11-30'), Carbon::parse('2021-02-28')), + new IntervalProvider(Carbon::parse('2020-11-30'), Carbon::parse('2021-02-28')) ]; } } diff --git a/tests/unit/Support/Calendar/Periodicity/WeeklyTest.php b/tests/unit/Support/Calendar/Periodicity/WeeklyTest.php index 23020042ce..38e9d76871 100644 --- a/tests/unit/Support/Calendar/Periodicity/WeeklyTest.php +++ b/tests/unit/Support/Calendar/Periodicity/WeeklyTest.php @@ -24,9 +24,9 @@ declare(strict_types=1); namespace Tests\unit\Support\Calendar\Periodicity; -use FireflyIII\Support\Calendar\Periodicity\Weekly; use Carbon\Carbon; use FireflyIII\Support\Calendar\Periodicity; +use FireflyIII\Support\Calendar\Periodicity\Weekly; /** * @group unit-test @@ -47,9 +47,6 @@ final class WeeklyTest extends IntervalTestCase public static function provideIntervals(): array { - return [ - new IntervalProvider(Carbon::now(), Carbon::now()->addWeek()), - new IntervalProvider(Carbon::parse('2023-01-31'), Carbon::parse('2023-02-07')), - ]; + return [new IntervalProvider(Carbon::now(), Carbon::now()->addWeek()), new IntervalProvider(Carbon::parse('2023-01-31'), Carbon::parse('2023-02-07'))]; } } diff --git a/tests/unit/Support/Calendar/Periodicity/YearlyTest.php b/tests/unit/Support/Calendar/Periodicity/YearlyTest.php index 36464498a8..a8e369b654 100644 --- a/tests/unit/Support/Calendar/Periodicity/YearlyTest.php +++ b/tests/unit/Support/Calendar/Periodicity/YearlyTest.php @@ -24,9 +24,9 @@ declare(strict_types=1); namespace Tests\unit\Support\Calendar\Periodicity; -use FireflyIII\Support\Calendar\Periodicity\Yearly; use Carbon\Carbon; use FireflyIII\Support\Calendar\Periodicity; +use FireflyIII\Support\Calendar\Periodicity\Yearly; /** * @group unit-test @@ -50,7 +50,7 @@ final class YearlyTest extends IntervalTestCase return [ new IntervalProvider(Carbon::now(), Carbon::now()->addYears(1)), new IntervalProvider(Carbon::parse('2019-01-29'), Carbon::parse('2020-01-29')), - new IntervalProvider(Carbon::parse('2020-02-29'), Carbon::parse('2021-02-28')), + new IntervalProvider(Carbon::parse('2020-02-29'), Carbon::parse('2021-02-28')) ]; } } diff --git a/tests/unit/Support/NavigationAddPeriodTest.php b/tests/unit/Support/NavigationAddPeriodTest.php index 5b5903de67..e637145b6f 100644 --- a/tests/unit/Support/NavigationAddPeriodTest.php +++ b/tests/unit/Support/NavigationAddPeriodTest.php @@ -24,10 +24,10 @@ declare(strict_types=1); namespace Tests\unit\Support; -use Override; use Carbon\Carbon; use FireflyIII\Support\Calendar\Periodicity; use FireflyIII\Support\Navigation; +use Override; use PHPUnit\Framework\Attributes\DataProvider; use Tests\integration\TestCase; @@ -52,8 +52,12 @@ final class NavigationAddPeriodTest extends TestCase } #[DataProvider('providePeriodsWithSkippingParam')] - public function testGivenAFrequencyAndSkipIntervalWhenCalculateTheDateThenReturnsTheSkippedDateSuccessful(int $skip, string $frequency, Carbon $from, Carbon $expected): void - { + public function testGivenAFrequencyAndSkipIntervalWhenCalculateTheDateThenReturnsTheSkippedDateSuccessful( + int $skip, + string $frequency, + Carbon $from, + Carbon $expected + ): void { $period = $this->navigation->addPeriod($from, $frequency, $skip); $this->assertSame($expected->toDateString(), $period->toDateString()); } @@ -61,42 +65,167 @@ final class NavigationAddPeriodTest extends TestCase public static function providePeriodsWithSkippingParam(): iterable { $intervals = [ - '2019-01-31 to 2019-02-11' => ['skip' => 10, 'frequency' => 'daily', 'from' => Carbon::parse('2019-01-31'), 'expected' => Carbon::parse('2019-02-11')], - '1D' => ['skip' => 1, 'frequency' => '1D', 'from' => Carbon::now(), 'expected' => Carbon::now()->addDays(2)], - 'daily' => ['skip' => 1, 'frequency' => 'daily', 'from' => Carbon::now(), 'expected' => Carbon::now()->addDays(2)], - '1W' => ['skip' => 1, 'frequency' => '1W', 'from' => Carbon::now(), 'expected' => Carbon::now()->addWeeks(2)], - 'weekly' => ['skip' => 1, 'frequency' => 'weekly', 'from' => Carbon::now(), 'expected' => Carbon::now()->addWeeks(2)], - 'week' => ['skip' => 1, 'frequency' => 'week', 'from' => Carbon::now(), 'expected' => Carbon::now()->addWeeks(2)], - '1M' => ['skip' => 1, 'frequency' => '1M', 'from' => Carbon::parse('2023-06-25'), 'expected' => Carbon::parse('2023-06-25')->addMonthsNoOverflow(2)], - 'month' => ['skip' => 1, 'frequency' => 'month', 'from' => Carbon::parse('2023-06-25'), 'expected' => Carbon::parse('2023-06-25')->addMonthsNoOverflow(2)], - 'monthly' => ['skip' => 1, 'frequency' => 'monthly', 'from' => Carbon::parse('2023-06-25'), 'expected' => Carbon::parse('2023-06-25')->addMonthsNoOverflow(2)], - '2019-01-29 to 2019-03-29' => ['skip' => 1, 'frequency' => 'monthly', 'from' => Carbon::parse('2019-01-29'), 'expected' => Carbon::parse('2019-03-29')], - '2019-01-30 to 2019-03-30' => ['skip' => 1, 'frequency' => 'monthly', 'from' => Carbon::parse('2019-01-30'), 'expected' => Carbon::parse('2019-03-30')], - '2019-01-31 to 2019-03-31' => ['skip' => 1, 'frequency' => 'monthly', 'from' => Carbon::parse('2019-01-31'), 'expected' => Carbon::parse('2019-03-31')], - '2023-03-31 to 2023-05-31' => ['skip' => 1, 'frequency' => 'monthly', 'from' => Carbon::parse('2023-03-31'), 'expected' => Carbon::parse('2023-05-31')], - '2023-05-31 to 2023-07-31' => ['skip' => 1, 'frequency' => 'monthly', 'from' => Carbon::parse('2023-05-31'), 'expected' => Carbon::parse('2023-07-31')], - '2023-08-31 to 2023-10-31' => ['skip' => 1, 'frequency' => 'monthly', 'from' => Carbon::parse('2023-08-31'), 'expected' => Carbon::parse('2023-10-31')], - '2023-10-31 to 2023-12-31' => ['skip' => 1, 'frequency' => 'monthly', 'from' => Carbon::parse('2023-10-31'), 'expected' => Carbon::parse('2023-12-31')], - '2023-01-31 to 2023-03-30' => ['skip' => 2, 'frequency' => 'monthly', 'from' => Carbon::parse('2023-01-31'), 'expected' => Carbon::parse('2023-04-30')], - '3M' => ['skip' => 1, 'frequency' => '3M', 'from' => Carbon::now(), 'expected' => Carbon::now()->addMonthsNoOverflow(6)], - 'quarter' => ['skip' => 1, 'frequency' => 'quarter', 'from' => Carbon::now(), 'expected' => Carbon::now()->addMonthsNoOverflow(6)], - 'quarterly' => ['skip' => 1, 'frequency' => 'quarterly', 'from' => Carbon::now(), 'expected' => Carbon::now()->addMonthsNoOverflow(6)], - 'quarter_2' => ['skip' => 2, 'frequency' => 'quarter', 'from' => Carbon::now(), 'expected' => Carbon::now()->addMonthsNoOverflow(9)], - 'quarterly_2' => ['skip' => 2, 'frequency' => 'quarterly', 'from' => Carbon::now(), 'expected' => Carbon::now()->addMonthsNoOverflow(9)], - 'quarter_3' => ['skip' => 2, 'frequency' => 'quarter', 'from' => Carbon::parse('2023-01-01'), 'expected' => Carbon::parse('2023-10-01')], - '6M' => ['skip' => 1, 'frequency' => '6M', 'from' => Carbon::now(), 'expected' => Carbon::now()->addMonthsNoOverflow(12)], - 'half-year' => ['skip' => 1, 'frequency' => 'half-year', 'from' => Carbon::now(), 'expected' => Carbon::now()->addMonthsNoOverflow(12)], - 'year' => ['skip' => 1, 'frequency' => 'year', 'from' => Carbon::now(), 'expected' => Carbon::now()->addYears(2)], - 'yearly' => ['skip' => 1, 'frequency' => 'yearly', 'from' => Carbon::now(), 'expected' => Carbon::now()->addYears(2)], - '1Y' => ['skip' => 1, 'frequency' => '1Y', 'from' => Carbon::now(), 'expected' => Carbon::now()->addYears(2)], - '2023-02-01 to 2023-02-15' => ['skip' => 1, 'frequency' => 'last7', 'from' => Carbon::parse('2023-02-01'), 'expected' => Carbon::parse('2023-02-15')], - 'last7' => ['skip' => 1, 'frequency' => 'last7', 'from' => Carbon::now(), 'expected' => Carbon::now()->addDays(14)], - 'last30' => ['skip' => 1, 'frequency' => 'last30', 'from' => Carbon::now(), 'expected' => Carbon::now()->addMonthsNoOverflow(2)], - 'last90' => ['skip' => 1, 'frequency' => 'last90', 'from' => Carbon::now(), 'expected' => Carbon::now()->addMonthsNoOverflow(6)], - 'last365' => ['skip' => 1, 'frequency' => 'last365', 'from' => Carbon::now(), 'expected' => Carbon::now()->addYears(2)], - 'MTD' => ['skip' => 1, 'frequency' => 'MTD', 'from' => Carbon::now(), 'expected' => Carbon::now()->addMonthsNoOverflow(2)], - 'QTD' => ['skip' => 1, 'frequency' => 'QTD', 'from' => Carbon::now(), 'expected' => Carbon::now()->addMonthsNoOverflow(6)], - 'YTD' => ['skip' => 1, 'frequency' => 'YTD', 'from' => Carbon::now(), 'expected' => Carbon::now()->addYears(2)], + '2019-01-31 to 2019-02-11' => [ + 'skip' => 10, + 'frequency' => 'daily', + 'from' => Carbon::parse('2019-01-31'), + 'expected' => Carbon::parse('2019-02-11') + ], + '1D' => ['skip' => 1, 'frequency' => '1D', 'from' => Carbon::now(), 'expected' => Carbon::now()->addDays(2)], + 'daily' => ['skip' => 1, 'frequency' => 'daily', 'from' => Carbon::now(), 'expected' => Carbon::now()->addDays(2)], + '1W' => ['skip' => 1, 'frequency' => '1W', 'from' => Carbon::now(), 'expected' => Carbon::now()->addWeeks(2)], + 'weekly' => ['skip' => 1, 'frequency' => 'weekly', 'from' => Carbon::now(), 'expected' => Carbon::now()->addWeeks(2)], + 'week' => ['skip' => 1, 'frequency' => 'week', 'from' => Carbon::now(), 'expected' => Carbon::now()->addWeeks(2)], + '1M' => [ + 'skip' => 1, + 'frequency' => '1M', + 'from' => Carbon::parse('2023-06-25'), + 'expected' => Carbon::parse('2023-06-25')->addMonthsNoOverflow(2) + ], + 'month' => [ + 'skip' => 1, + 'frequency' => 'month', + 'from' => Carbon::parse('2023-06-25'), + 'expected' => Carbon::parse('2023-06-25')->addMonthsNoOverflow(2) + ], + 'monthly' => [ + 'skip' => 1, + 'frequency' => 'monthly', + 'from' => Carbon::parse('2023-06-25'), + 'expected' => Carbon::parse('2023-06-25')->addMonthsNoOverflow(2) + ], + '2019-01-29 to 2019-03-29' => [ + 'skip' => 1, + 'frequency' => 'monthly', + 'from' => Carbon::parse('2019-01-29'), + 'expected' => Carbon::parse('2019-03-29') + ], + '2019-01-30 to 2019-03-30' => [ + 'skip' => 1, + 'frequency' => 'monthly', + 'from' => Carbon::parse('2019-01-30'), + 'expected' => Carbon::parse('2019-03-30') + ], + '2019-01-31 to 2019-03-31' => [ + 'skip' => 1, + 'frequency' => 'monthly', + 'from' => Carbon::parse('2019-01-31'), + 'expected' => Carbon::parse('2019-03-31') + ], + '2023-03-31 to 2023-05-31' => [ + 'skip' => 1, + 'frequency' => 'monthly', + 'from' => Carbon::parse('2023-03-31'), + 'expected' => Carbon::parse('2023-05-31') + ], + '2023-05-31 to 2023-07-31' => [ + 'skip' => 1, + 'frequency' => 'monthly', + 'from' => Carbon::parse('2023-05-31'), + 'expected' => Carbon::parse('2023-07-31') + ], + '2023-08-31 to 2023-10-31' => [ + 'skip' => 1, + 'frequency' => 'monthly', + 'from' => Carbon::parse('2023-08-31'), + 'expected' => Carbon::parse('2023-10-31') + ], + '2023-10-31 to 2023-12-31' => [ + 'skip' => 1, + 'frequency' => 'monthly', + 'from' => Carbon::parse('2023-10-31'), + 'expected' => Carbon::parse('2023-12-31') + ], + '2023-01-31 to 2023-03-30' => [ + 'skip' => 2, + 'frequency' => 'monthly', + 'from' => Carbon::parse('2023-01-31'), + 'expected' => Carbon::parse('2023-04-30') + ], + '3M' => [ + 'skip' => 1, + 'frequency' => '3M', + 'from' => Carbon::now(), + 'expected' => Carbon::now()->addMonthsNoOverflow(6) + ], + 'quarter' => [ + 'skip' => 1, + 'frequency' => 'quarter', + 'from' => Carbon::now(), + 'expected' => Carbon::now()->addMonthsNoOverflow(6) + ], + 'quarterly' => [ + 'skip' => 1, + 'frequency' => 'quarterly', + 'from' => Carbon::now(), + 'expected' => Carbon::now()->addMonthsNoOverflow(6) + ], + 'quarter_2' => [ + 'skip' => 2, + 'frequency' => 'quarter', + 'from' => Carbon::now(), + 'expected' => Carbon::now()->addMonthsNoOverflow(9) + ], + 'quarterly_2' => [ + 'skip' => 2, + 'frequency' => 'quarterly', + 'from' => Carbon::now(), + 'expected' => Carbon::now()->addMonthsNoOverflow(9) + ], + 'quarter_3' => [ + 'skip' => 2, + 'frequency' => 'quarter', + 'from' => Carbon::parse('2023-01-01'), + 'expected' => Carbon::parse('2023-10-01') + ], + '6M' => [ + 'skip' => 1, + 'frequency' => '6M', + 'from' => Carbon::now(), + 'expected' => Carbon::now()->addMonthsNoOverflow(12) + ], + 'half-year' => [ + 'skip' => 1, + 'frequency' => 'half-year', + 'from' => Carbon::now(), + 'expected' => Carbon::now()->addMonthsNoOverflow(12) + ], + 'year' => ['skip' => 1, 'frequency' => 'year', 'from' => Carbon::now(), 'expected' => Carbon::now()->addYears(2)], + 'yearly' => ['skip' => 1, 'frequency' => 'yearly', 'from' => Carbon::now(), 'expected' => Carbon::now()->addYears(2)], + '1Y' => ['skip' => 1, 'frequency' => '1Y', 'from' => Carbon::now(), 'expected' => Carbon::now()->addYears(2)], + '2023-02-01 to 2023-02-15' => [ + 'skip' => 1, + 'frequency' => 'last7', + 'from' => Carbon::parse('2023-02-01'), + 'expected' => Carbon::parse('2023-02-15') + ], + 'last7' => ['skip' => 1, 'frequency' => 'last7', 'from' => Carbon::now(), 'expected' => Carbon::now()->addDays(14)], + 'last30' => [ + 'skip' => 1, + 'frequency' => 'last30', + 'from' => Carbon::now(), + 'expected' => Carbon::now()->addMonthsNoOverflow(2) + ], + 'last90' => [ + 'skip' => 1, + 'frequency' => 'last90', + 'from' => Carbon::now(), + 'expected' => Carbon::now()->addMonthsNoOverflow(6) + ], + 'last365' => ['skip' => 1, 'frequency' => 'last365', 'from' => Carbon::now(), 'expected' => Carbon::now()->addYears(2)], + 'MTD' => [ + 'skip' => 1, + 'frequency' => 'MTD', + 'from' => Carbon::now(), + 'expected' => Carbon::now()->addMonthsNoOverflow(2) + ], + 'QTD' => [ + 'skip' => 1, + 'frequency' => 'QTD', + 'from' => Carbon::now(), + 'expected' => Carbon::now()->addMonthsNoOverflow(6) + ], + 'YTD' => ['skip' => 1, 'frequency' => 'YTD', 'from' => Carbon::now(), 'expected' => Carbon::now()->addYears(2)] ]; foreach ($intervals as $interval) { yield "{$interval['frequency']} {$interval['from']->toDateString()} to {$interval['expected']->toDateString()}" => $interval; @@ -154,8 +283,11 @@ final class NavigationAddPeriodTest extends TestCase } #[DataProvider('provideFrequencies')] - public function testGivenAIntervalWhenCallTheNextDateByIntervalMethodThenReturnsTheExpectedDateSuccessful(Periodicity $periodicity, Carbon $from, Carbon $expected): void - { + public function testGivenAIntervalWhenCallTheNextDateByIntervalMethodThenReturnsTheExpectedDateSuccessful( + Periodicity $periodicity, + Carbon $from, + Carbon $expected + ): void { $period = $this->navigation->nextDateByInterval($from, $periodicity); $this->assertSame($expected->toDateString(), $period->toDateString()); } diff --git a/tests/unit/Support/NavigationEndOfPeriodTest.php b/tests/unit/Support/NavigationEndOfPeriodTest.php index ca52600d22..74ecf8d0ba 100644 --- a/tests/unit/Support/NavigationEndOfPeriodTest.php +++ b/tests/unit/Support/NavigationEndOfPeriodTest.php @@ -23,10 +23,10 @@ declare(strict_types=1); namespace Tests\unit\Support; -use Override; use Carbon\Carbon; use FireflyIII\Support\Navigation; use Illuminate\Support\Facades\Log; +use Override; use PHPUnit\Framework\Attributes\DataProvider; use Tests\integration\TestCase; @@ -63,29 +63,113 @@ final class NavigationEndOfPeriodTest extends TestCase yield 'daily' => ['daily', Carbon::now(), Carbon::now()->endOfDay()]; - yield '1W' => ['1W', Carbon::now(), Carbon::now()->addWeek()->subDay()->endOfDay()]; + yield '1W' => [ + '1W', + Carbon::now(), + Carbon::now() + ->addWeek() + ->subDay() + ->endOfDay() + ]; - yield 'week' => ['week', Carbon::now(), Carbon::now()->addWeek()->subDay()->endOfDay()]; + yield 'week' => [ + 'week', + Carbon::now(), + Carbon::now() + ->addWeek() + ->subDay() + ->endOfDay() + ]; - yield 'weekly' => ['weekly', Carbon::now(), Carbon::now()->addWeek()->subDay()->endOfDay()]; + yield 'weekly' => [ + 'weekly', + Carbon::now(), + Carbon::now() + ->addWeek() + ->subDay() + ->endOfDay() + ]; - yield 'month' => ['month', Carbon::now(), Carbon::now()->addMonth()->subDay()->endOfDay()]; + yield 'month' => [ + 'month', + Carbon::now(), + Carbon::now() + ->addMonth() + ->subDay() + ->endOfDay() + ]; - yield '1M' => ['1M', Carbon::now(), Carbon::now()->addMonth()->subDay()->endOfDay()]; + yield '1M' => [ + '1M', + Carbon::now(), + Carbon::now() + ->addMonth() + ->subDay() + ->endOfDay() + ]; - yield 'monthly' => ['monthly', Carbon::now(), Carbon::now()->addMonth()->subDay()->endOfDay()]; + yield 'monthly' => [ + 'monthly', + Carbon::now(), + Carbon::now() + ->addMonth() + ->subDay() + ->endOfDay() + ]; - yield '3M' => ['3M', Carbon::now(), Carbon::now()->addQuarter()->subDay()->endOfDay()]; + yield '3M' => [ + '3M', + Carbon::now(), + Carbon::now() + ->addQuarter() + ->subDay() + ->endOfDay() + ]; - yield 'quarter' => ['quarter', Carbon::now(), Carbon::now()->addQuarter()->subDay()->endOfDay()]; + yield 'quarter' => [ + 'quarter', + Carbon::now(), + Carbon::now() + ->addQuarter() + ->subDay() + ->endOfDay() + ]; - yield 'quarterly' => ['quarterly', Carbon::now(), Carbon::now()->addQuarter()->subDay()->endOfDay()]; + yield 'quarterly' => [ + 'quarterly', + Carbon::now(), + Carbon::now() + ->addQuarter() + ->subDay() + ->endOfDay() + ]; - yield 'year' => ['year', Carbon::now(), Carbon::now()->addYearNoOverflow()->subDay()->endOfDay()]; + yield 'year' => [ + 'year', + Carbon::now(), + Carbon::now() + ->addYearNoOverflow() + ->subDay() + ->endOfDay() + ]; - yield 'yearly' => ['yearly', Carbon::now(), Carbon::now()->addYearNoOverflow()->subDay()->endOfDay()]; + yield 'yearly' => [ + 'yearly', + Carbon::now(), + Carbon::now() + ->addYearNoOverflow() + ->subDay() + ->endOfDay() + ]; - yield '1Y' => ['1Y', Carbon::now(), Carbon::now()->addYearNoOverflow()->subDay()->endOfDay()]; + yield '1Y' => [ + '1Y', + Carbon::now(), + Carbon::now() + ->addYearNoOverflow() + ->subDay() + ->endOfDay() + ]; yield 'half-year' => ['half-year', Carbon::parse('2023-05-20'), Carbon::parse('2023-11-19')->endOfDay()]; @@ -99,8 +183,7 @@ final class NavigationEndOfPeriodTest extends TestCase yield 'last365' => ['last365', Carbon::now(), Carbon::now()->addDays(365)->endOfDay()]; - yield 'MTD' => ['MTD', Carbon::now(), - Carbon::now()->isSameMonth(Carbon::now()) ? Carbon::now()->endOfDay() : Carbon::now()->endOfMonth()]; + yield 'MTD' => ['MTD', Carbon::now(), Carbon::now()->isSameMonth(Carbon::now()) ? Carbon::now()->endOfDay() : Carbon::now()->endOfMonth()]; yield 'QTD' => ['QTD', Carbon::now(), Carbon::now()->firstOfQuarter()->startOfDay()]; @@ -110,11 +193,14 @@ final class NavigationEndOfPeriodTest extends TestCase } #[DataProvider('provideUnknownFrequencies')] - public function testGivenADateAndUnknownFrequencyWhenCalculateTheDateThenReturnsTheSameDateSuccessful(string $frequency, Carbon $from, Carbon $expected): void - { + public function testGivenADateAndUnknownFrequencyWhenCalculateTheDateThenReturnsTheSameDateSuccessful( + string $frequency, + Carbon $from, + Carbon $expected + ): void { Log::spy(); - $period = $this->navigation->endOfPeriod($from, $frequency); + $period = $this->navigation->endOfPeriod($from, $frequency); $this->assertSame($expected->toDateString(), $period->toDateString()); $expectedMessage = sprintf('Cannot do endOfPeriod for $repeat_freq "%s"', $frequency); diff --git a/tests/unit/Support/NavigationPreferredCarbonFormatByPeriodTest.php b/tests/unit/Support/NavigationPreferredCarbonFormatByPeriodTest.php index 9045679517..3ec82efb3d 100644 --- a/tests/unit/Support/NavigationPreferredCarbonFormatByPeriodTest.php +++ b/tests/unit/Support/NavigationPreferredCarbonFormatByPeriodTest.php @@ -24,8 +24,8 @@ declare(strict_types=1); namespace Tests\unit\Support; -use Override; use FireflyIII\Support\Navigation; +use Override; use PHPUnit\Framework\Attributes\DataProvider; use Tests\integration\TestCase; diff --git a/tests/unit/Support/NavigationPreferredCarbonFormatTest.php b/tests/unit/Support/NavigationPreferredCarbonFormatTest.php index f45d1d5293..8c85182e57 100644 --- a/tests/unit/Support/NavigationPreferredCarbonFormatTest.php +++ b/tests/unit/Support/NavigationPreferredCarbonFormatTest.php @@ -24,9 +24,9 @@ declare(strict_types=1); namespace Tests\unit\Support; -use Override; use Carbon\Carbon; use FireflyIII\Support\Navigation; +use Override; use PHPUnit\Framework\Attributes\DataProvider; use Tests\integration\TestCase; @@ -51,8 +51,11 @@ final class NavigationPreferredCarbonFormatTest extends TestCase } #[DataProvider('providePeriods')] - public function testGivenStartAndEndDatesWhenCallPreferredCarbonFormatThenReturnsTheExpectedFormatSuccessful(Carbon $start, Carbon $end, string $expected): void - { + public function testGivenStartAndEndDatesWhenCallPreferredCarbonFormatThenReturnsTheExpectedFormatSuccessful( + Carbon $start, + Carbon $end, + string $expected + ): void { $carbonFormat = $this->navigation->preferredCarbonFormat($start, $end); $this->assertSame($expected, $carbonFormat); } diff --git a/tests/unit/Support/NavigationPreferredEndOfPeriodTest.php b/tests/unit/Support/NavigationPreferredEndOfPeriodTest.php index 6687e639d7..01fd9d35c1 100644 --- a/tests/unit/Support/NavigationPreferredEndOfPeriodTest.php +++ b/tests/unit/Support/NavigationPreferredEndOfPeriodTest.php @@ -24,9 +24,9 @@ declare(strict_types=1); namespace Tests\unit\Support; -use Override; use Carbon\Carbon; use FireflyIII\Support\Navigation; +use Override; use PHPUnit\Framework\Attributes\DataProvider; use Tests\integration\TestCase; @@ -51,8 +51,11 @@ final class NavigationPreferredEndOfPeriodTest extends TestCase } #[DataProvider('providePeriods')] - public function testGivenStartAndEndDatesWhenCallPreferredEndOfPeriodThenReturnsTheExpectedFormatSuccessful(Carbon $start, Carbon $end, string $expected): void - { + public function testGivenStartAndEndDatesWhenCallPreferredEndOfPeriodThenReturnsTheExpectedFormatSuccessful( + Carbon $start, + Carbon $end, + string $expected + ): void { $formatPeriod = $this->navigation->preferredEndOfPeriod($start, $end); $this->assertSame($expected, $formatPeriod); } diff --git a/tests/unit/Support/NavigationPreferredRangeFormatTest.php b/tests/unit/Support/NavigationPreferredRangeFormatTest.php index 032b3ba28e..5e9fe0e6e8 100644 --- a/tests/unit/Support/NavigationPreferredRangeFormatTest.php +++ b/tests/unit/Support/NavigationPreferredRangeFormatTest.php @@ -24,9 +24,9 @@ declare(strict_types=1); namespace Tests\unit\Support; -use Override; use Carbon\Carbon; use FireflyIII\Support\Navigation; +use Override; use PHPUnit\Framework\Attributes\DataProvider; use Tests\integration\TestCase; @@ -51,8 +51,11 @@ final class NavigationPreferredRangeFormatTest extends TestCase } #[DataProvider('providePeriods')] - public function testGivenStartAndEndDatesWhenCallPreferredRangeFormatThenReturnsTheExpectedFormatSuccessful(Carbon $start, Carbon $end, string $expected): void - { + public function testGivenStartAndEndDatesWhenCallPreferredRangeFormatThenReturnsTheExpectedFormatSuccessful( + Carbon $start, + Carbon $end, + string $expected + ): void { $formatPeriod = $this->navigation->preferredRangeFormat($start, $end); $this->assertSame($expected, $formatPeriod); } diff --git a/tests/unit/Support/NavigationPreferredSqlFormatTest.php b/tests/unit/Support/NavigationPreferredSqlFormatTest.php index 37c26d8935..ff92f1f724 100644 --- a/tests/unit/Support/NavigationPreferredSqlFormatTest.php +++ b/tests/unit/Support/NavigationPreferredSqlFormatTest.php @@ -24,9 +24,9 @@ declare(strict_types=1); namespace Tests\unit\Support; -use Override; use Carbon\Carbon; use FireflyIII\Support\Navigation; +use Override; use PHPUnit\Framework\Attributes\DataProvider; use Tests\integration\TestCase; @@ -51,8 +51,11 @@ final class NavigationPreferredSqlFormatTest extends TestCase } #[DataProvider('provideDates')] - public function testGivenStartAndEndDatesWhenCallPreferredSqlFormatThenReturnsTheExpectedFormatSuccessful(Carbon $start, Carbon $end, string $expected): void - { + public function testGivenStartAndEndDatesWhenCallPreferredSqlFormatThenReturnsTheExpectedFormatSuccessful( + Carbon $start, + Carbon $end, + string $expected + ): void { $formatPeriod = $this->navigation->preferredSqlFormat($start, $end); $this->assertSame($expected, $formatPeriod); } diff --git a/tests/unit/Support/NavigationStartOfPeriodTest.php b/tests/unit/Support/NavigationStartOfPeriodTest.php index 1fbc177ea6..4fec705705 100644 --- a/tests/unit/Support/NavigationStartOfPeriodTest.php +++ b/tests/unit/Support/NavigationStartOfPeriodTest.php @@ -24,10 +24,10 @@ declare(strict_types=1); namespace Tests\unit\Support; -use Override; use Carbon\Carbon; use FireflyIII\Support\Navigation; use Illuminate\Support\Facades\Log; +use Override; use PHPUnit\Framework\Attributes\DataProvider; use Tests\integration\TestCase; @@ -110,14 +110,14 @@ final class NavigationStartOfPeriodTest extends TestCase } #[DataProvider('provideUnknownFrequencies')] - public function testGivenADateAndUnknownFrequencyWhenCalculateTheDateThenReturnsTheSameDateSuccessful(string $frequency, Carbon $from, Carbon $expected): void - { + public function testGivenADateAndUnknownFrequencyWhenCalculateTheDateThenReturnsTheSameDateSuccessful( + string $frequency, + Carbon $from, + Carbon $expected + ): void { Log::spy(); - Log::shouldReceive('error') - ->with(sprintf('Cannot do startOfPeriod for $repeat_freq "%s"', $frequency)) - ->andReturnNull() - ; + Log::shouldReceive('error')->with(sprintf('Cannot do startOfPeriod for $repeat_freq "%s"', $frequency))->andReturnNull(); $period = $this->navigation->startOfPeriod($from, $frequency); $this->assertSame($expected->toDateString(), $period->toDateString()); diff --git a/tests/unit/Support/Search/QueryParser/AbstractQueryParserInterfaceParseQueryTester.php b/tests/unit/Support/Search/QueryParser/AbstractQueryParserInterfaceParseQueryTester.php index 50f72fe69b..923cba3ee8 100644 --- a/tests/unit/Support/Search/QueryParser/AbstractQueryParserInterfaceParseQueryTester.php +++ b/tests/unit/Support/Search/QueryParser/AbstractQueryParserInterfaceParseQueryTester.php @@ -1,6 +1,5 @@ createParser()->parse($query); $this->assertObjectEquals($expected, $actual); - } public static function queryDataProvider(): iterable { - yield 'empty query' => [ - '', - new NodeGroup([]), - ]; + yield 'empty query' => ['', new NodeGroup([])]; - yield 'simple word' => [ - 'groceries', - new NodeGroup([new StringNode('groceries')]), - ]; + yield 'simple word' => ['groceries', new NodeGroup([new StringNode('groceries')])]; - yield 'prohibited word' => [ - '-groceries', - new NodeGroup([new StringNode('groceries', true)]), - ]; + yield 'prohibited word' => ['-groceries', new NodeGroup([new StringNode('groceries', true)])]; - yield 'prohibited field' => [ - '-amount:100', - new NodeGroup([new FieldNode('amount', '100', true)]), - ]; + yield 'prohibited field' => ['-amount:100', new NodeGroup([new FieldNode('amount', '100', true)])]; - yield 'quoted word' => [ - '"test phrase"', - new NodeGroup([new StringNode('test phrase')]), - ]; + yield 'quoted word' => ['"test phrase"', new NodeGroup([new StringNode('test phrase')])]; - yield 'prohibited quoted word' => [ - '-"test phrase"', - new NodeGroup([new StringNode('test phrase', true)]), - ]; + yield 'prohibited quoted word' => ['-"test phrase"', new NodeGroup([new StringNode('test phrase', true)])]; yield 'multiple words' => [ 'groceries shopping market', - new NodeGroup([ - new StringNode('groceries'), - new StringNode('shopping'), - new StringNode('market'), - ]), + new NodeGroup([new StringNode('groceries'), new StringNode('shopping'), new StringNode('market')]) ]; - yield 'field operator' => [ - 'amount:100', - new NodeGroup([new FieldNode('amount', '100')]), - ]; + yield 'field operator' => ['amount:100', new NodeGroup([new FieldNode('amount', '100')])]; - yield 'quoted field value with single space' => [ - 'description:"test phrase"', - new NodeGroup([new FieldNode('description', 'test phrase')]), - ]; + yield 'quoted field value with single space' => ['description:"test phrase"', new NodeGroup([new FieldNode('description', 'test phrase')])]; - yield 'multiple fields' => [ - 'amount:100 category:food', - new NodeGroup([ - new FieldNode('amount', '100'), - new FieldNode('category', 'food'), - ]), - ]; + yield 'multiple fields' => ['amount:100 category:food', new NodeGroup([new FieldNode('amount', '100'), new FieldNode('category', 'food')])]; yield 'simple subquery' => [ '(amount:100 category:food)', - new NodeGroup([ - new NodeGroup([ - new FieldNode('amount', '100'), - new FieldNode('category', 'food'), - ]), - ]), + new NodeGroup([new NodeGroup([new FieldNode('amount', '100'), new FieldNode('category', 'food')])]) ]; yield 'prohibited subquery' => [ '-(amount:100 category:food)', - new NodeGroup([ - new NodeGroup([ - new FieldNode('amount', '100'), - new FieldNode('category', 'food'), - ], true), - ]), + new NodeGroup([new NodeGroup([new FieldNode('amount', '100'), new FieldNode('category', 'food')], true)]) ]; yield 'nested subquery' => [ '(amount:100 (description:"test" category:food))', - new NodeGroup([ - new NodeGroup([ - new FieldNode('amount', '100'), - new NodeGroup([ - new FieldNode('description', 'test'), - new FieldNode('category', 'food'), - ]), - ]), - ]), + new NodeGroup([new NodeGroup([ + new FieldNode('amount', '100'), + new NodeGroup([new FieldNode('description', 'test'), new FieldNode('category', 'food')]) + ])]) ]; yield 'mixed words and operators' => [ 'groceries amount:50 shopping', - new NodeGroup([ - new StringNode('groceries'), - new FieldNode('amount', '50'), - new StringNode('shopping'), - ]), + new NodeGroup([new StringNode('groceries'), new FieldNode('amount', '50'), new StringNode('shopping')]) ]; yield 'subquery after field value' => [ 'amount:100 (description:"market" category:food)', - new NodeGroup([ - new FieldNode('amount', '100'), - new NodeGroup([ - new FieldNode('description', 'market'), - new FieldNode('category', 'food'), - ]), - ]), + new NodeGroup([new FieldNode('amount', '100'), new NodeGroup([new FieldNode('description', 'market'), new FieldNode('category', 'food')])]) ]; yield 'word followed by subquery' => [ 'groceries (amount:100 description_contains:"test")', - new NodeGroup([ - new StringNode('groceries'), - new NodeGroup([ - new FieldNode('amount', '100'), - new FieldNode('description_contains', 'test'), - ]), - ]), + new NodeGroup([new StringNode('groceries'), new NodeGroup([new FieldNode('amount', '100'), new FieldNode('description_contains', 'test')])]) ]; yield 'nested subquery with prohibited field' => [ '(amount:100 (description_contains:"test payment" -has_attachments:true))', - new NodeGroup([ - new NodeGroup([ - new FieldNode('amount', '100'), - new NodeGroup([ - new FieldNode('description_contains', 'test payment'), - new FieldNode('has_attachments', 'true', true), - ]), - ]), - ]), + new NodeGroup([new NodeGroup([ + new FieldNode('amount', '100'), + new NodeGroup([new FieldNode('description_contains', 'test payment'), new FieldNode('has_attachments', 'true', true)]) + ])]) ]; yield 'complex nested subqueries' => [ @@ -197,43 +125,26 @@ abstract class AbstractQueryParserInterfaceParseQueryTester extends TestCase new FieldNode('category', 'food', true), new StringNode('word'), new FieldNode('description', 'test phrase'), - new NodeGroup([ - new FieldNode('has_notes', 'true'), - ]), - ]), - ]), - ]), + new NodeGroup([new FieldNode('has_notes', 'true')]) + ]) + ]) + ]) ]; - yield 'word with multiple spaces' => [ - '"multiple spaces"', - new NodeGroup([new StringNode('multiple spaces')]), - ]; + yield 'word with multiple spaces' => ['"multiple spaces"', new NodeGroup([new StringNode('multiple spaces')])]; yield 'field with multiple spaces in value' => [ 'description:"multiple spaces here"', - new NodeGroup([new FieldNode('description', 'multiple spaces here')]), + new NodeGroup([new FieldNode('description', 'multiple spaces here')]) ]; - yield 'unmatched right parenthesis in word' => [ - 'test)word', - new NodeGroup([new StringNode('test)word')]), - ]; + yield 'unmatched right parenthesis in word' => ['test)word', new NodeGroup([new StringNode('test)word')])]; - yield 'unmatched right parenthesis in field' => [ - 'description:test)phrase', - new NodeGroup([new FieldNode('description', 'test)phrase')]), - ]; + yield 'unmatched right parenthesis in field' => ['description:test)phrase', new NodeGroup([new FieldNode('description', 'test)phrase')])]; yield 'subquery followed by word' => [ '(amount:100 category:food) shopping', - new NodeGroup([ - new NodeGroup([ - new FieldNode('amount', '100'), - new FieldNode('category', 'food'), - ]), - new StringNode('shopping'), - ]), + new NodeGroup([new NodeGroup([new FieldNode('amount', '100'), new FieldNode('category', 'food')]), new StringNode('shopping')]) ]; } } diff --git a/tests/unit/Support/Search/QueryParser/QueryParserParseQueryTest.php b/tests/unit/Support/Search/QueryParser/QueryParserParseQueryTest.php index 085f11b1f5..b81a7ac4d6 100644 --- a/tests/unit/Support/Search/QueryParser/QueryParserParseQueryTest.php +++ b/tests/unit/Support/Search/QueryParser/QueryParserParseQueryTest.php @@ -1,6 +1,5 @@