diff --git a/.deploy/heroku/.locales b/.deploy/heroku/.locales index 03941c7d18..f628fb64b5 100644 --- a/.deploy/heroku/.locales +++ b/.deploy/heroku/.locales @@ -16,3 +16,4 @@ sv_SE zh-hans_CN zh-hant_CN fi_FI +vi_VN diff --git a/app/Api/V1/Controllers/AccountController.php b/app/Api/V1/Controllers/AccountController.php index 9fa6170065..dae6bec18b 100644 --- a/app/Api/V1/Controllers/AccountController.php +++ b/app/Api/V1/Controllers/AccountController.php @@ -104,7 +104,7 @@ class AccountController extends Controller // types to get, page size: $types = $this->mapAccountTypes($this->parameters->get('type')); - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; // get list of accounts. Count it and split it. $collection = $this->repository->getAccountsByType($types); @@ -142,7 +142,7 @@ class AccountController extends Controller $manager = $this->getManager(); // types to get, page size: - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; // get list of budgets. Count it and split it. $collection = $this->repository->getPiggyBanks($account); @@ -218,7 +218,7 @@ class AccountController extends Controller */ public function transactions(Request $request, Account $account): JsonResponse { - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; $type = $request->get('type') ?? 'default'; $this->parameters->set('type', $type); @@ -227,10 +227,8 @@ class AccountController extends Controller if (null !== $limit && $limit > 0) { $pageSize = $limit; } - $types = $this->mapTransactionTypes($this->parameters->get('type')); $manager = $this->getManager(); - /** @var User $admin */ $admin = auth()->user(); @@ -240,7 +238,6 @@ class AccountController extends Controller $collector->setUser($admin)->setAccounts(new Collection([$account])) ->withAPIInformation()->setLimit($pageSize)->setPage($this->parameters->get('page'))->setTypes($types); - // set range if necessary: if (null !== $this->parameters->get('start') && null !== $this->parameters->get('end')) { $collector->setRange($this->parameters->get('start'), $this->parameters->get('end')); } diff --git a/app/Api/V1/Controllers/AttachmentController.php b/app/Api/V1/Controllers/AttachmentController.php index 737f5fa1fa..a2895d4847 100644 --- a/app/Api/V1/Controllers/AttachmentController.php +++ b/app/Api/V1/Controllers/AttachmentController.php @@ -92,8 +92,8 @@ class AttachmentController extends Controller * @param Attachment $attachment * * @codeCoverageIgnore - * @return LaravelResponse * @throws FireflyException + * @return LaravelResponse */ public function download(Attachment $attachment): LaravelResponse { @@ -108,7 +108,7 @@ class AttachmentController extends Controller 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); @@ -139,7 +139,7 @@ class AttachmentController extends Controller $manager = $this->getManager(); // types to get, page size: - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; // get list of accounts. Count it and split it. $collection = $this->repository->get(); @@ -184,8 +184,8 @@ class AttachmentController extends Controller * * @param AttachmentStoreRequest $request * - * @return JsonResponse * @throws FireflyException + * @return JsonResponse */ public function store(AttachmentStoreRequest $request): JsonResponse { diff --git a/app/Api/V1/Controllers/AvailableBudgetController.php b/app/Api/V1/Controllers/AvailableBudgetController.php index 29b5a761d1..d937bc1043 100644 --- a/app/Api/V1/Controllers/AvailableBudgetController.php +++ b/app/Api/V1/Controllers/AvailableBudgetController.php @@ -92,7 +92,7 @@ class AvailableBudgetController extends Controller $manager = $this->getManager(); // types to get, page size: - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; $start = $this->parameters->get('start'); $end = $this->parameters->get('end'); diff --git a/app/Api/V1/Controllers/BillController.php b/app/Api/V1/Controllers/BillController.php index 6c0b3e28a3..009685d3ec 100644 --- a/app/Api/V1/Controllers/BillController.php +++ b/app/Api/V1/Controllers/BillController.php @@ -85,7 +85,7 @@ class BillController extends Controller public function attachments(Bill $bill): JsonResponse { $manager = $this->getManager(); - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; $collection = $this->repository->getAttachments($bill); $count = $collection->count(); @@ -130,7 +130,7 @@ class BillController extends Controller { $bills = $this->repository->getBills(); $manager = $this->getManager(); - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; $count = $bills->count(); $bills = $bills->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); $paginator = new LengthAwarePaginator($bills, $count, $pageSize, $this->parameters->get('page')); @@ -158,7 +158,7 @@ class BillController extends Controller $manager = $this->getManager(); // types to get, page size: - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; // get list of budgets. Count it and split it. $collection = $this->repository->getRulesForBill($bill); @@ -206,8 +206,8 @@ class BillController extends Controller * * @param BillRequest $request * - * @return JsonResponse * @throws FireflyException + * @return JsonResponse */ public function store(BillRequest $request): JsonResponse { @@ -235,7 +235,7 @@ class BillController extends Controller */ public function transactions(Request $request, Bill $bill): JsonResponse { - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; $type = $request->get('type') ?? 'default'; $this->parameters->set('type', $type); diff --git a/app/Api/V1/Controllers/BudgetController.php b/app/Api/V1/Controllers/BudgetController.php index ee41e4efda..ee94b68f31 100644 --- a/app/Api/V1/Controllers/BudgetController.php +++ b/app/Api/V1/Controllers/BudgetController.php @@ -25,7 +25,8 @@ namespace FireflyIII\Api\V1\Controllers; use Exception; use FireflyIII\Api\V1\Requests\BudgetLimitRequest; -use FireflyIII\Api\V1\Requests\BudgetRequest; +use FireflyIII\Api\V1\Requests\BudgetStoreRequest; +use FireflyIII\Api\V1\Requests\BudgetUpdateRequest; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Helpers\Collector\GroupCollectorInterface; use FireflyIII\Models\Budget; @@ -89,7 +90,7 @@ class BudgetController extends Controller public function budgetLimits(Budget $budget): JsonResponse { $manager = $this->getManager(); - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; $this->parameters->set('budget_id', $budget->id); $collection = $this->blRepository->getBudgetLimits($budget, $this->parameters->get('start'), $this->parameters->get('end')); $count = $collection->count(); @@ -134,7 +135,7 @@ class BudgetController extends Controller $manager = $this->getManager(); // types to get, page size: - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; // get list of budgets. Count it and split it. $collection = $this->repository->getBudgets(); @@ -179,13 +180,13 @@ class BudgetController extends Controller /** * Store a budget. * - * @param BudgetRequest $request + * @param BudgetStoreRequest $request * - * @return JsonResponse * @throws FireflyException * + * @return JsonResponse */ - public function store(BudgetRequest $request): JsonResponse + public function store(BudgetStoreRequest $request): JsonResponse { $budget = $this->repository->store($request->getAll()); $manager = $this->getManager(); @@ -205,8 +206,8 @@ class BudgetController extends Controller * @param BudgetLimitRequest $request * @param Budget $budget * - * @return JsonResponse * @throws Exception + * @return JsonResponse */ public function storeBudgetLimit(BudgetLimitRequest $request, Budget $budget): JsonResponse { @@ -236,7 +237,7 @@ class BudgetController extends Controller */ public function transactions(Request $request, Budget $budget): JsonResponse { - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; // user can overrule page size with limit parameter. $limit = $this->parameters->get('limit'); @@ -291,12 +292,12 @@ class BudgetController extends Controller /** * Update a budget. * - * @param BudgetRequest $request - * @param Budget $budget + * @param BudgetUpdateRequest $request + * @param Budget $budget * * @return JsonResponse */ - public function update(BudgetRequest $request, Budget $budget): JsonResponse + public function update(BudgetUpdateRequest $request, Budget $budget): JsonResponse { $data = $request->getAll(); $budget = $this->repository->update($budget, $data); diff --git a/app/Api/V1/Controllers/BudgetLimitController.php b/app/Api/V1/Controllers/BudgetLimitController.php index 0a2830253f..6fd81263ca 100644 --- a/app/Api/V1/Controllers/BudgetLimitController.php +++ b/app/Api/V1/Controllers/BudgetLimitController.php @@ -102,9 +102,9 @@ class BudgetLimitController extends Controller public function index(Request $request): JsonResponse { $manager = $this->getManager(); - $budgetId = (int)($request->get('budget_id') ?? 0); + $budgetId = (int) ($request->get('budget_id') ?? 0); $budget = $this->repository->findNull($budgetId); - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; $this->parameters->set('budget_id', $budgetId); $collection = new Collection; @@ -156,16 +156,16 @@ class BudgetLimitController extends Controller * * @param BudgetLimitRequest $request * - * @return JsonResponse * @throws FireflyException * + * @return JsonResponse */ public function store(BudgetLimitRequest $request): JsonResponse { $data = $request->getAll(); $budget = $this->repository->findNull($data['budget_id']); if (null === $budget) { - throw new FireflyException('200004: Budget does not exist.'); + throw new FireflyException('200004: Budget does not exist.'); // @codeCoverageIgnore } $data['budget'] = $budget; $budgetLimit = $this->blRepository->storeBudgetLimit($data); @@ -191,7 +191,7 @@ class BudgetLimitController extends Controller */ public function transactions(Request $request, BudgetLimit $budgetLimit): JsonResponse { - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; $type = $request->get('type') ?? 'default'; $this->parameters->set('type', $type); diff --git a/app/Api/V1/Controllers/CategoryController.php b/app/Api/V1/Controllers/CategoryController.php index 984f1c0826..a228b6f49a 100644 --- a/app/Api/V1/Controllers/CategoryController.php +++ b/app/Api/V1/Controllers/CategoryController.php @@ -97,7 +97,7 @@ class CategoryController extends Controller $manager = $this->getManager(); // types to get, page size: - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; // get list of budgets. Count it and split it. $collection = $this->repository->getCategories(); @@ -146,13 +146,13 @@ class CategoryController extends Controller * * @param CategoryRequest $request * - * @return JsonResponse * @throws FireflyException + * @return JsonResponse */ public function store(CategoryRequest $request): JsonResponse { $category = $this->repository->store($request->getAll()); - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var CategoryTransformer $transformer */ $transformer = app(CategoryTransformer::class); @@ -175,7 +175,7 @@ class CategoryController extends Controller */ public function transactions(Request $request, Category $category): JsonResponse { - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; $type = $request->get('type') ?? 'default'; $this->parameters->set('type', $type); diff --git a/app/Api/V1/Controllers/Chart/AccountController.php b/app/Api/V1/Controllers/Chart/AccountController.php index 840efd31f3..c01606a6b0 100644 --- a/app/Api/V1/Controllers/Chart/AccountController.php +++ b/app/Api/V1/Controllers/Chart/AccountController.php @@ -99,10 +99,10 @@ class AccountController extends Controller // loop the end balances. This is an array for each account ($expenses) foreach ($endBalances as $accountId => $expenses) { - $accountId = (int)$accountId; + $accountId = (int) $accountId; // loop each expense entry (each entry can be a different currency). foreach ($expenses as $currencyId => $endAmount) { - $currencyId = (int)$currencyId; + $currencyId = (int) $currencyId; // see if there is an accompanying start amount. // grab the difference and find the currency. @@ -114,7 +114,7 @@ class AccountController extends Controller $tempData[] = [ 'name' => $accountNames[$accountId], 'difference' => $diff, - 'diff_float' => (float)$diff, + 'diff_float' => (float) $diff, 'currency_id' => $currencyId, ]; } @@ -247,10 +247,10 @@ class AccountController extends Controller // loop the end balances. This is an array for each account ($expenses) foreach ($endBalances as $accountId => $expenses) { - $accountId = (int)$accountId; + $accountId = (int) $accountId; // loop each expense entry (each entry can be a different currency). foreach ($expenses as $currencyId => $endAmount) { - $currencyId = (int)$currencyId; + $currencyId = (int) $currencyId; // see if there is an accompanying start amount. // grab the difference and find the currency. @@ -263,7 +263,7 @@ class AccountController extends Controller 'name' => $accountNames[$accountId], 'difference' => bcmul($diff, '-1'), // For some reason this line is never covered in code coverage: - 'diff_float' => ((float)$diff) * -1, // @codeCoverageIgnore + 'diff_float' => ((float) $diff) * -1, // @codeCoverageIgnore 'currency_id' => $currencyId, ]; } diff --git a/app/Api/V1/Controllers/Chart/AvailableBudgetController.php b/app/Api/V1/Controllers/Chart/AvailableBudgetController.php index 5181dcc707..aa83e7bf4c 100644 --- a/app/Api/V1/Controllers/Chart/AvailableBudgetController.php +++ b/app/Api/V1/Controllers/Chart/AvailableBudgetController.php @@ -83,9 +83,9 @@ class AvailableBudgetController extends Controller $spent = $spentInfo['amount']; } } - $left = bcadd($availableBudget->amount, (string)$spent); + $left = bcadd($availableBudget->amount, (string) $spent); // left less than zero? Set to zero. - if (bccomp($left, '0') === -1) { + if (-1 === bccomp($left, '0')) { $left = '0'; } diff --git a/app/Api/V1/Controllers/Chart/CategoryController.php b/app/Api/V1/Controllers/Chart/CategoryController.php index ce26a0b469..9975a0b044 100644 --- a/app/Api/V1/Controllers/Chart/CategoryController.php +++ b/app/Api/V1/Controllers/Chart/CategoryController.php @@ -90,8 +90,8 @@ class CategoryController extends Controller $tempData = []; $spentWith = $this->opsRepository->listExpenses($start, $end); $earnedWith = $this->opsRepository->listIncome($start, $end); - $spentWithout = $this->noCatRepository->listExpenses($start, $end); // refactored - $earnedWithout = $this->noCatRepository->listIncome($start, $end); // refactored + $spentWithout = $this->noCatRepository->listExpenses($start, $end); + $earnedWithout = $this->noCatRepository->listIncome($start, $end); $categories = []; @@ -104,7 +104,7 @@ class CategoryController extends Controller // make data arrays if not yet present. $tempData[$inKey] = $tempData[$inKey] ?? [ 'currency_id' => $currency['currency_id'], - 'label' => (string)trans('firefly.box_earned_in_currency', ['currency' => $currency['currency_name']]), + 'label' => (string) trans('firefly.box_earned_in_currency', ['currency' => $currency['currency_name']]), 'currency_code' => $currency['currency_code'], 'currency_symbol' => $currency['currency_symbol'], 'currency_decimal_places' => $currency['currency_decimal_places'], @@ -117,7 +117,7 @@ class CategoryController extends Controller ]; $tempData[$outKey] = $tempData[$outKey] ?? [ 'currency_id' => $currency['currency_id'], - 'label' => (string)trans('firefly.box_spent_in_currency', ['currency' => $currency['currency_name']]), + 'label' => (string) trans('firefly.box_spent_in_currency', ['currency' => $currency['currency_name']]), 'currency_code' => $currency['currency_code'], 'currency_symbol' => $currency['currency_symbol'], 'currency_decimal_places' => $currency['currency_decimal_places'], @@ -141,48 +141,48 @@ class CategoryController extends Controller } } -// foreach ([] as $set) { -// foreach ($set as $currency) { -// $inKey = sprintf('%d-i', $currency['currency_id']); -// $outKey = sprintf('%d-e', $currency['currency_id']); -// $categories[] = (string)trans('firefly.no_category'); -// // make data arrays if not yet present. -// $tempData[$inKey] = $tempData[$inKey] ?? [ -// 'currency_id' => $currency['currency_id'], -// 'label' => (string)trans('firefly.box_earned_in_currency', ['currency' => $currency['currency_name']]), -// 'currency_code' => $currency['currency_code'], -// 'currency_symbol' => $currency['currency_symbol'], -// 'currency_decimal_places' => $currency['currency_decimal_places'], -// 'type' => 'bar', // line, area or bar -// 'yAxisID' => 0, // 0, 1, 2 -// 'entries' => [ -// // per category: -// // "category" => 5, -// ], -// ]; -// $tempData[$outKey] = $tempData[$outKey] ?? [ -// 'currency_id' => $currency['currency_id'], -// 'label' => (string)trans('firefly.box_spent_in_currency', ['currency' => $currency['currency_name']]), -// 'currency_code' => $currency['currency_code'], -// 'currency_symbol' => $currency['currency_symbol'], -// 'currency_decimal_places' => $currency['currency_decimal_places'], -// 'type' => 'bar', // line, area or bar -// 'yAxisID' => 0, // 0, 1, 2 -// 'entries' => [ -// // per category: -// // "category" => 5, -// ], -// ]; -// foreach ($currency['transaction_journals'] as $journal) { -// // is it expense or income? -// $letter = -1 === bccomp($journal['amount'], '0') ? 'e' : 'i'; -// $currentKey = sprintf('%d-%s', $currency['currency_id'], $letter); -// $name = (string)trans('firefly.no_category'); -// $tempData[$currentKey]['entries'][$name] = $tempData[$currentKey]['entries'][$name] ?? '0'; -// $tempData[$currentKey]['entries'][$name] = bcadd($tempData[$currentKey]['entries'][$name], $journal['amount']); -// } -// } -// } + // foreach ([] as $set) { + // foreach ($set as $currency) { + // $inKey = sprintf('%d-i', $currency['currency_id']); + // $outKey = sprintf('%d-e', $currency['currency_id']); + // $categories[] = (string)trans('firefly.no_category'); + // // make data arrays if not yet present. + // $tempData[$inKey] = $tempData[$inKey] ?? [ + // 'currency_id' => $currency['currency_id'], + // 'label' => (string)trans('firefly.box_earned_in_currency', ['currency' => $currency['currency_name']]), + // 'currency_code' => $currency['currency_code'], + // 'currency_symbol' => $currency['currency_symbol'], + // 'currency_decimal_places' => $currency['currency_decimal_places'], + // 'type' => 'bar', // line, area or bar + // 'yAxisID' => 0, // 0, 1, 2 + // 'entries' => [ + // // per category: + // // "category" => 5, + // ], + // ]; + // $tempData[$outKey] = $tempData[$outKey] ?? [ + // 'currency_id' => $currency['currency_id'], + // 'label' => (string)trans('firefly.box_spent_in_currency', ['currency' => $currency['currency_name']]), + // 'currency_code' => $currency['currency_code'], + // 'currency_symbol' => $currency['currency_symbol'], + // 'currency_decimal_places' => $currency['currency_decimal_places'], + // 'type' => 'bar', // line, area or bar + // 'yAxisID' => 0, // 0, 1, 2 + // 'entries' => [ + // // per category: + // // "category" => 5, + // ], + // ]; + // foreach ($currency['transaction_journals'] as $journal) { + // // is it expense or income? + // $letter = -1 === bccomp($journal['amount'], '0') ? 'e' : 'i'; + // $currentKey = sprintf('%d-%s', $currency['currency_id'], $letter); + // $name = (string)trans('firefly.no_category'); + // $tempData[$currentKey]['entries'][$name] = $tempData[$currentKey]['entries'][$name] ?? '0'; + // $tempData[$currentKey]['entries'][$name] = bcadd($tempData[$currentKey]['entries'][$name], $journal['amount']); + // } + // } + // } // re-sort every spent array and add 0 for missing entries. foreach ($tempData as $index => $set) { diff --git a/app/Api/V1/Controllers/ConfigurationController.php b/app/Api/V1/Controllers/ConfigurationController.php index 23b78898a3..bd81857431 100644 --- a/app/Api/V1/Controllers/ConfigurationController.php +++ b/app/Api/V1/Controllers/ConfigurationController.php @@ -51,7 +51,6 @@ class ConfigurationController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - /** @noinspection UnusedConstructorDependenciesInspection */ $this->repository = app(UserRepositoryInterface::class); /** @var User $admin */ $admin = auth()->user(); @@ -109,13 +108,12 @@ class ConfigurationController extends Controller $lastCheck = app('fireflyconfig')->get('last_update_check'); /** @var Configuration $singleUser */ $singleUser = app('fireflyconfig')->get('single_user_mode'); - $data = [ + + return [ 'is_demo_site' => null === $isDemoSite ? null : $isDemoSite->data, - 'permission_update_check' => null === $updateCheck ? null : (int)$updateCheck->data, - 'last_update_check' => null === $lastCheck ? null : (int)$lastCheck->data, + 'permission_update_check' => null === $updateCheck ? null : (int) $updateCheck->data, + 'last_update_check' => null === $lastCheck ? null : (int) $lastCheck->data, 'single_user_mode' => null === $singleUser ? null : $singleUser->data, ]; - - return $data; } } diff --git a/app/Api/V1/Controllers/Controller.php b/app/Api/V1/Controllers/Controller.php index 806b3f0743..018afbd46e 100644 --- a/app/Api/V1/Controllers/Controller.php +++ b/app/Api/V1/Controllers/Controller.php @@ -104,7 +104,7 @@ class Controller extends BaseController private function getParameters(): ParameterBag { $bag = new ParameterBag; - $page = (int)request()->get('page'); + $page = (int) request()->get('page'); if (0 === $page) { $page = 1; } @@ -131,7 +131,7 @@ class Controller extends BaseController foreach ($integers as $integer) { $value = request()->query->get($integer); if (null !== $value) { - $bag->set($integer, (int)$value); + $bag->set($integer, (int) $value); } } diff --git a/app/Api/V1/Controllers/CurrencyController.php b/app/Api/V1/Controllers/CurrencyController.php index 3a41ac79a4..835092e466 100644 --- a/app/Api/V1/Controllers/CurrencyController.php +++ b/app/Api/V1/Controllers/CurrencyController.php @@ -116,7 +116,7 @@ class CurrencyController extends Controller // types to get, page size: $types = $this->mapAccountTypes($this->parameters->get('type')); - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; // get list of accounts. Count it and split it. /** @var AccountRepositoryInterface $accountRepository */ @@ -126,7 +126,7 @@ class CurrencyController extends Controller // filter list on currency preference: $collection = $unfiltered->filter( static function (Account $account) use ($currency, $accountRepository) { - $currencyId = (int)$accountRepository->getMetaValue($account, 'currency_id'); + $currencyId = (int) $accountRepository->getMetaValue($account, 'currency_id'); return $currencyId === $currency->id; } @@ -165,7 +165,7 @@ class CurrencyController extends Controller $manager = $this->getManager(); // types to get, page size: - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; // get list of available budgets. Count it and split it. @@ -209,7 +209,7 @@ class CurrencyController extends Controller /** @var BillRepositoryInterface $repository */ $repository = app(BillRepositoryInterface::class); - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; $unfiltered = $repository->getBills(); // filter and paginate list: @@ -249,7 +249,7 @@ class CurrencyController extends Controller $blRepository = app(BudgetLimitRepositoryInterface::class); $manager = $this->getManager(); - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; $collection = $blRepository->getAllBudgetLimitsByCurrency($currency, $this->parameters->get('start'), $this->parameters->get('end')); $count = $collection->count(); $budgetLimits = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); @@ -278,7 +278,7 @@ class CurrencyController extends Controller { // create some objects: $manager = $this->getManager(); - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; $collection = $this->repository->getExchangeRates($currency); @@ -302,9 +302,9 @@ class CurrencyController extends Controller * * @param TransactionCurrency $currency * - * @return JsonResponse * @throws FireflyException * @codeCoverageIgnore + * @return JsonResponse */ public function delete(TransactionCurrency $currency): JsonResponse { @@ -391,7 +391,7 @@ class CurrencyController extends Controller */ public function index(): JsonResponse { - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; $collection = $this->repository->getAll(); $count = $collection->count(); // slice them: @@ -455,7 +455,7 @@ class CurrencyController extends Controller { $manager = $this->getManager(); // types to get, page size: - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; // get list of budgets. Count it and split it. /** @var RecurringRepositoryInterface $repository */ @@ -506,7 +506,7 @@ class CurrencyController extends Controller public function rules(TransactionCurrency $currency): JsonResponse { $manager = $this->getManager(); - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; // get list of budgets. Count it and split it. /** @var RuleRepositoryInterface $repository */ @@ -572,8 +572,8 @@ class CurrencyController extends Controller * * @param CurrencyRequest $request * - * @return JsonResponse * @throws FireflyException + * @return JsonResponse */ public function store(CurrencyRequest $request): JsonResponse { @@ -607,7 +607,7 @@ class CurrencyController extends Controller */ public function transactions(Request $request, TransactionCurrency $currency): JsonResponse { - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; $type = $request->get('type') ?? 'default'; $this->parameters->set('type', $type); diff --git a/app/Api/V1/Controllers/CurrencyExchangeRateController.php b/app/Api/V1/Controllers/CurrencyExchangeRateController.php index fa7b69417f..2cdb40ae6a 100644 --- a/app/Api/V1/Controllers/CurrencyExchangeRateController.php +++ b/app/Api/V1/Controllers/CurrencyExchangeRateController.php @@ -69,8 +69,8 @@ class CurrencyExchangeRateController extends Controller * * @param Request $request * - * @return JsonResponse * @throws FireflyException + * @return JsonResponse */ public function index(Request $request): JsonResponse { diff --git a/app/Api/V1/Controllers/ImportController.php b/app/Api/V1/Controllers/ImportController.php index 1c55fd6e4a..52065ac4db 100644 --- a/app/Api/V1/Controllers/ImportController.php +++ b/app/Api/V1/Controllers/ImportController.php @@ -40,6 +40,9 @@ use League\Fractal\Resource\Item; /** * Class ImportController + * + * @deprecated + * @codeCoverageIgnore */ class ImportController extends Controller { @@ -75,7 +78,7 @@ class ImportController extends Controller { // create some objects: $manager = $this->getManager(); - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; // get list of accounts. Count it and split it. $collection = $this->repository->get(); @@ -125,7 +128,7 @@ class ImportController extends Controller */ public function transactions(Request $request, ImportJob $importJob): JsonResponse { - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; $type = $request->get('type') ?? 'default'; $this->parameters->set('type', $type); diff --git a/app/Api/V1/Controllers/LinkTypeController.php b/app/Api/V1/Controllers/LinkTypeController.php index 3436ab701e..ff23e1b463 100644 --- a/app/Api/V1/Controllers/LinkTypeController.php +++ b/app/Api/V1/Controllers/LinkTypeController.php @@ -79,9 +79,9 @@ class LinkTypeController extends Controller * * @param LinkType $linkType * - * @return JsonResponse * @throws FireflyException * @codeCoverageIgnore + * @return JsonResponse */ public function delete(LinkType $linkType): JsonResponse { @@ -103,7 +103,7 @@ class LinkTypeController extends Controller { // create some objects: $manager = $this->getManager(); - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; // get list of accounts. Count it and split it. $collection = $this->repository->get(); @@ -151,8 +151,8 @@ class LinkTypeController extends Controller * * @param LinkTypeRequest $request * - * @return JsonResponse * @throws FireflyException + * @return JsonResponse */ public function store(LinkTypeRequest $request): JsonResponse { @@ -187,7 +187,7 @@ class LinkTypeController extends Controller */ public function transactions(Request $request, LinkType $linkType): JsonResponse { - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; $type = $request->get('type') ?? 'default'; $this->parameters->set('type', $type); @@ -241,8 +241,8 @@ class LinkTypeController extends Controller * @param LinkTypeRequest $request * @param LinkType $linkType * - * @return JsonResponse * @throws FireflyException + * @return JsonResponse */ public function update(LinkTypeRequest $request, LinkType $linkType): JsonResponse { diff --git a/app/Api/V1/Controllers/PiggyBankController.php b/app/Api/V1/Controllers/PiggyBankController.php index 82997c3e3d..a9a153315e 100644 --- a/app/Api/V1/Controllers/PiggyBankController.php +++ b/app/Api/V1/Controllers/PiggyBankController.php @@ -93,7 +93,7 @@ class PiggyBankController extends Controller { $manager = $this->getManager(); // types to get, page size: - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; // get list of budgets. Count it and split it. $collection = $this->repository->getPiggyBanks(); @@ -126,7 +126,7 @@ class PiggyBankController extends Controller public function piggyBankEvents(PiggyBank $piggyBank): JsonResponse { // types to get, page size: - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; $manager = $this->getManager(); $collection = $this->repository->getEvents($piggyBank); @@ -175,13 +175,13 @@ class PiggyBankController extends Controller * * @param PiggyBankRequest $request * - * @return JsonResponse * @throws FireflyException + * @return JsonResponse */ public function store(PiggyBankRequest $request): JsonResponse { $piggyBank = $this->repository->store($request->getAll()); - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var PiggyBankTransformer $transformer */ $transformer = app(PiggyBankTransformer::class); diff --git a/app/Api/V1/Controllers/PreferenceController.php b/app/Api/V1/Controllers/PreferenceController.php index 9f3a77b717..2210e5810f 100644 --- a/app/Api/V1/Controllers/PreferenceController.php +++ b/app/Api/V1/Controllers/PreferenceController.php @@ -147,10 +147,10 @@ class PreferenceController extends Controller $newValue = explode(',', $data['data']); break; case 'listPageSize': - $newValue = (int)$data['data']; + $newValue = (int) $data['data']; break; case 'customFiscalYear': - $newValue = 1 === (int)$data['data']; + $newValue = 1 === (int) $data['data']; break; } $result = app('preferences')->set($preference->name, $newValue); diff --git a/app/Api/V1/Controllers/RecurrenceController.php b/app/Api/V1/Controllers/RecurrenceController.php index fe117ec662..f2a0f1fbf9 100644 --- a/app/Api/V1/Controllers/RecurrenceController.php +++ b/app/Api/V1/Controllers/RecurrenceController.php @@ -99,7 +99,7 @@ class RecurrenceController extends Controller $manager = $this->getManager(); // types to get, page size: - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; // get list of budgets. Count it and split it. $collection = $this->repository->getAll(); @@ -149,8 +149,8 @@ class RecurrenceController extends Controller * * @param RecurrenceStoreRequest $request * - * @return JsonResponse * @throws FireflyException + * @return JsonResponse */ public function store(RecurrenceStoreRequest $request): JsonResponse { @@ -178,7 +178,7 @@ class RecurrenceController extends Controller */ public function transactions(Request $request, Recurrence $recurrence): JsonResponse { - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; $type = $request->get('type') ?? 'default'; $this->parameters->set('type', $type); @@ -224,9 +224,9 @@ class RecurrenceController extends Controller } /** - * @return JsonResponse * @throws FireflyException * @codeCoverageIgnore + * @return JsonResponse */ public function trigger(): JsonResponse { diff --git a/app/Api/V1/Controllers/RuleController.php b/app/Api/V1/Controllers/RuleController.php index 5dce97e5e4..e1ef261a33 100644 --- a/app/Api/V1/Controllers/RuleController.php +++ b/app/Api/V1/Controllers/RuleController.php @@ -105,7 +105,7 @@ class RuleController extends Controller $manager = $this->getManager(); // types to get, page size: - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; // get list of budgets. Count it and split it. $collection = $this->ruleRepository->getAll(); @@ -214,12 +214,12 @@ class RuleController extends Controller * @param RuleTestRequest $request * @param Rule $rule * - * @return JsonResponse * @throws FireflyException + * @return JsonResponse */ public function testRule(RuleTestRequest $request, Rule $rule): JsonResponse { - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; $parameters = $request->getTestParameters(); /** @var Rule $rule */ Log::debug(sprintf('Now testing rule #%d, "%s"', $rule->id, $rule->title)); diff --git a/app/Api/V1/Controllers/RuleGroupController.php b/app/Api/V1/Controllers/RuleGroupController.php index a8801f1814..8e8212fde5 100644 --- a/app/Api/V1/Controllers/RuleGroupController.php +++ b/app/Api/V1/Controllers/RuleGroupController.php @@ -106,7 +106,7 @@ class RuleGroupController extends Controller { $manager = $this->getManager(); // types to get, page size: - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; // get list of rule groups. Count it and split it. $collection = $this->ruleGroupRepository->get(); @@ -177,7 +177,7 @@ class RuleGroupController extends Controller { $manager = $this->getManager(); // types to get, page size: - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; // get list of budgets. Count it and split it. $collection = $this->ruleGroupRepository->getRules($group); @@ -246,13 +246,13 @@ class RuleGroupController extends Controller * @param RuleGroupTestRequest $request * @param RuleGroup $group * - * @return JsonResponse * @throws FireflyException * + * @return JsonResponse */ public function testGroup(RuleGroupTestRequest $request, RuleGroup $group): JsonResponse { - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; Log::debug('Now in testGroup()'); /** @var Collection $rules */ $rules = $this->ruleGroupRepository->getActiveRules($group); @@ -305,8 +305,8 @@ class RuleGroupController extends Controller * @param RuleGroupTriggerRequest $request * @param RuleGroup $group * - * @return JsonResponse * @throws Exception + * @return JsonResponse */ public function triggerGroup(RuleGroupTriggerRequest $request, RuleGroup $group): JsonResponse { diff --git a/app/Api/V1/Controllers/Search/AccountController.php b/app/Api/V1/Controllers/Search/AccountController.php index 6fcea80239..43ff8ffa5f 100644 --- a/app/Api/V1/Controllers/Search/AccountController.php +++ b/app/Api/V1/Controllers/Search/AccountController.php @@ -1,4 +1,5 @@ json($manager->createData($resource)->toArray())->header('Content-Type', 'application/vnd.api+json'); } - -} \ No newline at end of file +} diff --git a/app/Api/V1/Controllers/Search/TransactionController.php b/app/Api/V1/Controllers/Search/TransactionController.php index 3d844f2f04..7febe475e8 100644 --- a/app/Api/V1/Controllers/Search/TransactionController.php +++ b/app/Api/V1/Controllers/Search/TransactionController.php @@ -1,4 +1,5 @@ getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; $manager = $this->getManager(); /** @var User $admin */ $admin = auth()->user(); @@ -113,4 +110,4 @@ class TransferController extends Controller return response()->json($manager->createData($resource)->toArray())->header('Content-Type', 'application/vnd.api+json'); } -} \ No newline at end of file +} diff --git a/app/Api/V1/Controllers/SummaryController.php b/app/Api/V1/Controllers/SummaryController.php index 73df4eff4c..a401ef1fe1 100644 --- a/app/Api/V1/Controllers/SummaryController.php +++ b/app/Api/V1/Controllers/SummaryController.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Api\V1\Controllers; - use Carbon\Carbon; use Exception; use FireflyIII\Api\V1\Requests\DateRequest; @@ -42,7 +41,6 @@ use FireflyIII\Repositories\Budget\OperationsRepositoryInterface; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\User; use Illuminate\Http\JsonResponse; -use Illuminate\Support\Collection; /** * Class SummaryController @@ -98,8 +96,8 @@ class SummaryController extends Controller /** * @param DateRequest $request * - * @return JsonResponse * @throws Exception + * @return JsonResponse */ public function basic(DateRequest $request): JsonResponse { @@ -125,7 +123,6 @@ class SummaryController extends Controller } return response()->json($return); - } /** @@ -152,25 +149,6 @@ class SummaryController extends Controller return $result; } - /** - * This method will scroll through the results of the spentInPeriodMc() array and return the correct info. - * - * @param array $spentInfo - * @param TransactionCurrency $currency - * - * @return string - */ - private function findInSpentArray(array $spentInfo, TransactionCurrency $currency): string - { - foreach ($spentInfo as $array) { - if ($array['currency_id'] === $currency->id) { - return (string)$array['amount']; - } - } - - return '0'; // @codeCoverageIgnore - } - /** * @param Carbon $start * @param Carbon $end @@ -198,8 +176,7 @@ class SummaryController extends Controller $set = $collector->getExtractedJournals(); /** @var array $transactionJournal */ foreach ($set as $transactionJournal) { - - $currencyId = (int)$transactionJournal['currency_id']; + $currencyId = (int) $transactionJournal['currency_id']; $incomes[$currencyId] = $incomes[$currencyId] ?? '0'; $incomes[$currencyId] = bcadd($incomes[$currencyId], bcmul($transactionJournal['amount'], '-1')); $sums[$currencyId] = $sums[$currencyId] ?? '0'; @@ -221,7 +198,7 @@ class SummaryController extends Controller /** @var array $transactionJournal */ foreach ($set as $transactionJournal) { - $currencyId = (int)$transactionJournal['currency_id']; + $currencyId = (int) $transactionJournal['currency_id']; $expenses[$currencyId] = $expenses[$currencyId] ?? '0'; $expenses[$currencyId] = bcadd($expenses[$currencyId], $transactionJournal['amount']); $sums[$currencyId] = $sums[$currencyId] ?? '0'; @@ -295,7 +272,7 @@ class SummaryController extends Controller $return = []; foreach ($paidAmount as $currencyId => $amount) { $amount = bcmul($amount, '-1'); - $currency = $this->currencyRepos->findNull((int)$currencyId); + $currency = $this->currencyRepos->findNull((int) $currencyId); if (null === $currency) { continue; } @@ -315,7 +292,7 @@ class SummaryController extends Controller foreach ($unpaidAmount as $currencyId => $amount) { $amount = bcmul($amount, '-1'); - $currency = $this->currencyRepos->findNull((int)$currencyId); + $currency = $this->currencyRepos->findNull((int) $currencyId); if (null === $currency) { continue; } @@ -340,8 +317,8 @@ class SummaryController extends Controller * @param Carbon $start * @param Carbon $end * - * @return array * @throws Exception + * @return array */ private function getLeftToSpendInfo(Carbon $start, Carbon $end): array { @@ -360,7 +337,7 @@ class SummaryController extends Controller $days = $today->diffInDays($end) + 1; $perDay = '0'; if (0 !== $days && bccomp($leftToSpend, '0') > -1) { - $perDay = bcdiv($leftToSpend, (string)$days); + $perDay = bcdiv($leftToSpend, (string) $days); } $return[] = [ @@ -373,14 +350,18 @@ class SummaryController extends Controller 'currency_decimal_places' => $row['currency_decimal_places'], 'value_parsed' => app('amount')->formatFlat($row['currency_symbol'], $row['currency_decimal_places'], $leftToSpend, false), 'local_icon' => 'money', - 'sub_title' => (string)trans( - 'firefly.box_spend_per_day', ['amount' => app('amount')->formatFlat( - $row['currency_symbol'], $row['currency_decimal_places'], $perDay, false - )] + 'sub_title' => (string) trans( + 'firefly.box_spend_per_day', + ['amount' => app('amount')->formatFlat( + $row['currency_symbol'], + $row['currency_decimal_places'], + $perDay, + false + )] ), ]; - } + return $return; } @@ -443,5 +424,4 @@ class SummaryController extends Controller return $return; } - } diff --git a/app/Api/V1/Controllers/TagController.php b/app/Api/V1/Controllers/TagController.php index 339c3ea9f9..eb60351a51 100644 --- a/app/Api/V1/Controllers/TagController.php +++ b/app/Api/V1/Controllers/TagController.php @@ -25,8 +25,8 @@ namespace FireflyIII\Api\V1\Controllers; use Carbon\Carbon; use FireflyIII\Api\V1\Requests\DateRequest; -use FireflyIII\Api\V1\Requests\TagUpdateRequest; use FireflyIII\Api\V1\Requests\TagStoreRequest; +use FireflyIII\Api\V1\Requests\TagUpdateRequest; use FireflyIII\Helpers\Collector\GroupCollectorInterface; use FireflyIII\Models\Tag; use FireflyIII\Repositories\Tag\TagRepositoryInterface; @@ -117,7 +117,7 @@ class TagController extends Controller { $manager = $this->getManager(); // types to get, page size: - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; // get list of budgets. Count it and split it. $collection = $this->repository->get(); @@ -190,7 +190,7 @@ class TagController extends Controller */ public function transactions(Request $request, Tag $tag): JsonResponse { - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; $type = $request->get('type') ?? 'default'; $this->parameters->set('type', $type); @@ -236,7 +236,7 @@ class TagController extends Controller * Update a rule. * * @param TagUpdateRequest $request - * @param Tag $tag + * @param Tag $tag * * @return JsonResponse */ @@ -288,8 +288,8 @@ class TagController extends Controller ]; /** @var Tag $tag */ foreach ($tags as $tag) { - $earned = (float)$this->repository->earnedInPeriod($tag, $start, $end); - $spent = (float)$this->repository->spentInPeriod($tag, $start, $end); + $earned = (float) $this->repository->earnedInPeriod($tag, $start, $end); + $spent = (float) $this->repository->spentInPeriod($tag, $start, $end); $size = ($spent * -1) + $earned; $min = $min ?? $size; if ($size > 0) { diff --git a/app/Api/V1/Controllers/TransactionController.php b/app/Api/V1/Controllers/TransactionController.php index 9e25876dcb..717598f32f 100644 --- a/app/Api/V1/Controllers/TransactionController.php +++ b/app/Api/V1/Controllers/TransactionController.php @@ -110,7 +110,6 @@ class TransactionController extends Controller $resource = new FractalCollection($attachments, $transformer, 'attachments'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', 'application/vnd.api+json'); - } /** @@ -153,7 +152,7 @@ class TransactionController extends Controller */ public function index(Request $request): JsonResponse { - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; $type = $request->get('type') ?? 'default'; $this->parameters->set('type', $type); @@ -215,7 +214,6 @@ class TransactionController extends Controller $resource = new FractalCollection($events, $transformer, 'piggy_bank_events'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', 'application/vnd.api+json'); - } /** @@ -296,7 +294,7 @@ class TransactionController extends Controller ]; return response()->json($response, 422); - } catch(FireflyException $e) { + } catch (FireflyException $e) { Log::warning('Caught an exception. Return error message.'); Log::error($e->getMessage()); // return bad validation message. @@ -304,7 +302,7 @@ class TransactionController extends Controller $response = [ 'message' => 'The given data was invalid.', 'errors' => [ - 'transactions.0.description' => [sprintf('Internal exception: %s',$e->getMessage())], + 'transactions.0.description' => [sprintf('Internal exception: %s', $e->getMessage())], ], ]; @@ -379,6 +377,5 @@ class TransactionController extends Controller $resource = new Item($selectedGroup, $transformer, 'transactions'); return response()->json($manager->createData($resource)->toArray())->header('Content-Type', 'application/vnd.api+json'); - } } diff --git a/app/Api/V1/Controllers/TransactionLinkController.php b/app/Api/V1/Controllers/TransactionLinkController.php index 347e518172..d5079548b1 100644 --- a/app/Api/V1/Controllers/TransactionLinkController.php +++ b/app/Api/V1/Controllers/TransactionLinkController.php @@ -105,7 +105,7 @@ class TransactionLinkController extends Controller $name = $request->get('name'); // types to get, page size: - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; $linkType = $this->repository->findByName($name); // get list of transaction links. Count it and split it. @@ -155,8 +155,8 @@ class TransactionLinkController extends Controller * * @param TransactionLinkRequest $request * - * @return JsonResponse * @throws FireflyException + * @return JsonResponse */ public function store(TransactionLinkRequest $request): JsonResponse { @@ -186,8 +186,8 @@ class TransactionLinkController extends Controller * @param TransactionLinkRequest $request * @param TransactionJournalLink $journalLink * - * @return JsonResponse * @throws FireflyException + * @return JsonResponse */ public function update(TransactionLinkRequest $request, TransactionJournalLink $journalLink): JsonResponse { diff --git a/app/Api/V1/Controllers/UserController.php b/app/Api/V1/Controllers/UserController.php index b9908cba11..5fc610c7f3 100644 --- a/app/Api/V1/Controllers/UserController.php +++ b/app/Api/V1/Controllers/UserController.php @@ -70,9 +70,9 @@ class UserController extends Controller * * @param User $user * - * @return JsonResponse * @throws FireflyException * @codeCoverageIgnore + * @return JsonResponse */ public function delete(User $user): JsonResponse { @@ -95,7 +95,7 @@ class UserController extends Controller public function index(): JsonResponse { // user preferences - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; $manager = $this->getManager(); // build collection diff --git a/app/Api/V1/Requests/AccountStoreRequest.php b/app/Api/V1/Requests/AccountStoreRequest.php index a2f1c843fd..e8fb256056 100644 --- a/app/Api/V1/Requests/AccountStoreRequest.php +++ b/app/Api/V1/Requests/AccountStoreRequest.php @@ -126,7 +126,7 @@ class AccountStoreRequest extends Request 'interest_period' => 'required_if:type,liability|in:daily,monthly,yearly', 'notes' => 'min:0|max:65536', ]; - $rules = Location::requestRules($rules); + $rules = Location::requestRules($rules); return $rules; } diff --git a/app/Api/V1/Requests/AccountUpdateRequest.php b/app/Api/V1/Requests/AccountUpdateRequest.php index bb4b453da3..182ddf9753 100644 --- a/app/Api/V1/Requests/AccountUpdateRequest.php +++ b/app/Api/V1/Requests/AccountUpdateRequest.php @@ -105,7 +105,7 @@ class AccountUpdateRequest extends Request $types = implode(',', array_keys(config('firefly.subTitlesByIdentifier'))); $ccPaymentTypes = implode(',', array_keys(config('firefly.ccTypes'))); - $rules = [ + $rules = [ 'name' => sprintf('min:1|uniqueAccountForUser:%d', $account->id), 'type' => sprintf('in:%s', $types), 'iban' => 'iban|nullable', diff --git a/app/Api/V1/Requests/AvailableBudgetRequest.php b/app/Api/V1/Requests/AvailableBudgetRequest.php index 8f66dcdcd4..077d077a44 100644 --- a/app/Api/V1/Requests/AvailableBudgetRequest.php +++ b/app/Api/V1/Requests/AvailableBudgetRequest.php @@ -64,15 +64,13 @@ class AvailableBudgetRequest extends Request */ public function rules(): array { - $rules = [ + return [ 'currency_id' => 'numeric|exists:transaction_currencies,id', 'currency_code' => 'min:3|max:3|exists:transaction_currencies,code', 'amount' => 'required|numeric|more:0', 'start' => 'required|date|before:end', 'end' => 'required|date|after:start', ]; - - return $rules; } diff --git a/app/Api/V1/Requests/BillRequest.php b/app/Api/V1/Requests/BillRequest.php index 31f5967d30..ca0ee49a2a 100644 --- a/app/Api/V1/Requests/BillRequest.php +++ b/app/Api/V1/Requests/BillRequest.php @@ -60,7 +60,7 @@ class BillRequest extends Request $active = $this->boolean('active'); } - $data = [ + return [ 'name' => $this->string('name'), 'amount_min' => $this->string('amount_min'), 'amount_max' => $this->string('amount_max'), @@ -72,8 +72,6 @@ class BillRequest extends Request 'active' => $active, 'notes' => $this->nlString('notes'), ]; - - return $data; } /** @@ -121,10 +119,10 @@ class BillRequest extends Request $validator->after( static function (Validator $validator) { $data = $validator->getData(); - $min = (float)($data['amount_min'] ?? 0); - $max = (float)($data['amount_max'] ?? 0); + $min = (float) ($data['amount_min'] ?? 0); + $max = (float) ($data['amount_max'] ?? 0); if ($min > $max) { - $validator->errors()->add('amount_min', (string)trans('validation.amount_min_over_max')); + $validator->errors()->add('amount_min', (string) trans('validation.amount_min_over_max')); } } ); diff --git a/app/Api/V1/Requests/BudgetRequest.php b/app/Api/V1/Requests/BudgetRequest.php deleted file mode 100644 index b33244d599..0000000000 --- a/app/Api/V1/Requests/BudgetRequest.php +++ /dev/null @@ -1,91 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V1\Requests; - -use FireflyIII\Models\Budget; -use FireflyIII\Rules\IsBoolean; - -/** - * Class BudgetRequest - * - * @codeCoverageIgnore - * TODO AFTER 4.8,0: split this into two request classes. - */ -class BudgetRequest extends Request -{ - /** - * Authorize logged in users. - * - * @return bool - */ - public function authorize(): bool - { - // Only allow authenticated users - return auth()->check(); - } - - /** - * Get all data from the request. - * - * @return array - */ - public function getAll(): array - { - $active = true; - if (null !== $this->get('active')) { - $active = $this->boolean('active'); - } - - return [ - 'name' => $this->string('name'), - 'active' => $active, - 'order' => 0, - ]; - } - - /** - * The rules that the incoming request must be matched against. - * - * @return array - */ - public function rules(): array - { - $rules = [ - 'name' => 'required|between:1,100|uniqueObjectForUser:budgets,name', - 'active' => [new IsBoolean], - ]; - switch ($this->method()) { - default: - break; - case 'PUT': - case 'PATCH': - /** @var Budget $budget */ - $budget = $this->route()->parameter('budget'); - $rules['name'] = sprintf('required|between:1,100|uniqueObjectForUser:budgets,name,%d', $budget->id); - break; - } - - return $rules; - } -} diff --git a/app/Api/V1/Requests/BudgetStoreRequest.php b/app/Api/V1/Requests/BudgetStoreRequest.php new file mode 100644 index 0000000000..21799684ac --- /dev/null +++ b/app/Api/V1/Requests/BudgetStoreRequest.php @@ -0,0 +1,106 @@ +. + */ + +declare(strict_types=1); + +namespace FireflyIII\Api\V1\Requests; + +use FireflyIII\Rules\IsBoolean; +use Illuminate\Validation\Validator; + +/** + * Class BudgetStoreRequest + * + * @codeCoverageIgnore + */ +class BudgetStoreRequest extends Request +{ + /** + * Authorize logged in users. + * + * @return bool + */ + public function authorize(): bool + { + // Only allow authenticated users + return auth()->check(); + } + + /** + * Get all data from the request. + * + * @return array + */ + public function getAll(): array + { + $active = true; + if (null !== $this->get('active')) { + $active = $this->boolean('active'); + } + + return [ + 'name' => $this->string('name'), + 'active' => $active, + 'order' => 0, + 'auto_budget_type' => $this->string('auto_budget_type'), + 'transaction_currency_id' => $this->integer('auto_budget_currency_id'), + 'transaction_currency_code' => $this->string('auto_budget_currency_code'), + 'auto_budget_amount' => $this->string('auto_budget_amount'), + 'auto_budget_period' => $this->string('auto_budget_period'), + ]; + } + + /** + * The rules that the incoming request must be matched against. + * + * @return array + */ + public function rules(): array + { + return [ + 'name' => 'required|between:1,100|uniqueObjectForUser:budgets,name', + 'active' => [new IsBoolean], + 'auto_budget_type' => 'in:reset,rollover,none', + 'auto_budget_currency_id' => 'exists:transaction_currencies,id', + 'auto_budget_currency_code' => 'exists:transaction_currencies,code', + 'auto_budget_amount' => 'min:0|max:1000000000', + 'auto_budget_period' => 'in:daily,weekly,monthly,quarterly,half_year,yearly', + ]; + } + + + /** + * Configure the validator instance with special rules for after the basic validation rules. + * + * @param Validator $validator + * + * @return void + */ + public function withValidator(Validator $validator): void + { + $validator->after( + function (Validator $validator) { + // validate all account info + $this->validateAutoBudgetAmount($validator); + } + ); + } +} diff --git a/app/Api/V1/Requests/BudgetUpdateRequest.php b/app/Api/V1/Requests/BudgetUpdateRequest.php new file mode 100644 index 0000000000..0861c5be25 --- /dev/null +++ b/app/Api/V1/Requests/BudgetUpdateRequest.php @@ -0,0 +1,107 @@ +. + */ + +declare(strict_types=1); + +namespace FireflyIII\Api\V1\Requests; + +use FireflyIII\Rules\IsBoolean; +use Illuminate\Validation\Validator; + +/** + * Class BudgetUpdateRequest + * + * @codeCoverageIgnore + */ +class BudgetUpdateRequest extends Request +{ + /** + * Authorize logged in users. + * + * @return bool + */ + public function authorize(): bool + { + // Only allow authenticated users + return auth()->check(); + } + + /** + * Get all data from the request. + * + * @return array + */ + public function getAll(): array + { + $active = true; + if (null !== $this->get('active')) { + $active = $this->boolean('active'); + } + + return [ + 'name' => $this->string('name'), + 'active' => $active, + 'order' => 0, + 'auto_budget_type' => $this->string('auto_budget_type'), + 'transaction_currency_id' => $this->integer('auto_budget_currency_id'), + 'transaction_currency_code' => $this->string('auto_budget_currency_code'), + 'auto_budget_amount' => $this->string('auto_budget_amount'), + 'auto_budget_period' => $this->string('auto_budget_period'), + ]; + } + + /** + * The rules that the incoming request must be matched against. + * + * @return array + */ + public function rules(): array + { + $budget = $this->route()->parameter('budget'); + + return [ + 'name' => sprintf('required|between:1,100|uniqueObjectForUser:budgets,name,%d', $budget->id), + 'active' => [new IsBoolean], + 'auto_budget_type' => 'in:reset,rollover,none', + 'auto_budget_currency_id' => 'exists:transaction_currencies,id', + 'auto_budget_currency_code' => 'exists:transaction_currencies,code', + 'auto_budget_amount' => 'min:0|max:1000000000', + 'auto_budget_period' => 'in:daily,weekly,monthly,quarterly,half_year,yearly', + ]; + } + + /** + * Configure the validator instance with special rules for after the basic validation rules. + * + * @param Validator $validator + * + * @return void + */ + public function withValidator(Validator $validator): void + { + $validator->after( + function (Validator $validator) { + // validate all account info + $this->validateAutoBudgetAmount($validator); + } + ); + } +} diff --git a/app/Api/V1/Requests/RecurrenceStoreRequest.php b/app/Api/V1/Requests/RecurrenceStoreRequest.php index be57cb06c0..8b946fbb61 100644 --- a/app/Api/V1/Requests/RecurrenceStoreRequest.php +++ b/app/Api/V1/Requests/RecurrenceStoreRequest.php @@ -63,7 +63,8 @@ class RecurrenceStoreRequest extends Request if (null !== $this->get('apply_rules')) { $applyRules = $this->boolean('apply_rules'); } - $return = [ + + return [ 'recurrence' => [ 'type' => $this->string('type'), 'title' => $this->string('title'), @@ -77,8 +78,6 @@ class RecurrenceStoreRequest extends Request 'transactions' => $this->getTransactionData(), 'repetitions' => $this->getRepetitionData(), ]; - - return $return; } /** @@ -168,8 +167,8 @@ class RecurrenceStoreRequest extends Request $return[] = [ 'type' => $repetition['type'], 'moment' => $repetition['moment'], - 'skip' => (int)$repetition['skip'], - 'weekend' => (int)$repetition['weekend'], + 'skip' => (int) $repetition['skip'], + 'weekend' => (int) $repetition['weekend'], ]; } @@ -195,25 +194,25 @@ class RecurrenceStoreRequest extends Request foreach ($transactions as $transaction) { $return[] = [ 'amount' => $transaction['amount'], - 'currency_id' => isset($transaction['currency_id']) ? (int)$transaction['currency_id'] : null, + 'currency_id' => isset($transaction['currency_id']) ? (int) $transaction['currency_id'] : null, 'currency_code' => $transaction['currency_code'] ?? null, 'foreign_amount' => $transaction['foreign_amount'] ?? null, - 'foreign_currency_id' => isset($transaction['foreign_currency_id']) ? (int)$transaction['foreign_currency_id'] : null, + 'foreign_currency_id' => isset($transaction['foreign_currency_id']) ? (int) $transaction['foreign_currency_id'] : null, 'foreign_currency_code' => $transaction['foreign_currency_code'] ?? null, - 'source_id' => isset($transaction['source_id']) ? (int)$transaction['source_id'] : null, - 'source_name' => isset($transaction['source_name']) ? (string)$transaction['source_name'] : null, - 'destination_id' => isset($transaction['destination_id']) ? (int)$transaction['destination_id'] : null, - 'destination_name' => isset($transaction['destination_name']) ? (string)$transaction['destination_name'] : null, + 'source_id' => isset($transaction['source_id']) ? (int) $transaction['source_id'] : null, + 'source_name' => isset($transaction['source_name']) ? (string) $transaction['source_name'] : null, + 'destination_id' => isset($transaction['destination_id']) ? (int) $transaction['destination_id'] : null, + 'destination_name' => isset($transaction['destination_name']) ? (string) $transaction['destination_name'] : null, 'description' => $transaction['description'], 'type' => $this->string('type'), // new and updated fields: - 'piggy_bank_id' => isset($transaction['piggy_bank_id']) ? (int)$transaction['piggy_bank_id'] : null, + 'piggy_bank_id' => isset($transaction['piggy_bank_id']) ? (int) $transaction['piggy_bank_id'] : null, 'piggy_bank_name' => $transaction['piggy_bank_name'] ?? null, 'tags' => $transaction['tags'] ?? [], - 'budget_id' => isset($transaction['budget_id']) ? (int)$transaction['budget_id'] : null, + 'budget_id' => isset($transaction['budget_id']) ? (int) $transaction['budget_id'] : null, 'budget_name' => $transaction['budget_name'] ?? null, - 'category_id' => isset($transaction['category_id']) ? (int)$transaction['category_id'] : null, + 'category_id' => isset($transaction['category_id']) ? (int) $transaction['category_id'] : null, 'category_name' => $transaction['category_name'] ?? null, ]; } diff --git a/app/Api/V1/Requests/RecurrenceUpdateRequest.php b/app/Api/V1/Requests/RecurrenceUpdateRequest.php index 7397db39ef..72b169f18b 100644 --- a/app/Api/V1/Requests/RecurrenceUpdateRequest.php +++ b/app/Api/V1/Requests/RecurrenceUpdateRequest.php @@ -63,7 +63,8 @@ class RecurrenceUpdateRequest extends Request if (null !== $this->get('apply_rules')) { $applyRules = $this->boolean('apply_rules'); } - $return = [ + + return [ 'recurrence' => [ 'type' => $this->nullableString('type'), 'title' => $this->nullableString('title'), @@ -78,8 +79,6 @@ class RecurrenceUpdateRequest extends Request 'transactions' => $this->getTransactionData(), 'repetitions' => $this->getRepetitionData(), ]; - - return $return; } /** @@ -170,14 +169,46 @@ class RecurrenceUpdateRequest extends Request $return[] = [ 'type' => $repetition['type'], 'moment' => $repetition['moment'], - 'skip' => (int)$repetition['skip'], - 'weekend' => (int)$repetition['weekend'], + 'skip' => (int) $repetition['skip'], + 'weekend' => (int) $repetition['weekend'], ]; } return $return; } + /** + * @param array $transaction + * + * @return array + */ + private function getSingleData(array $transaction): array + { + return [ + 'amount' => $transaction['amount'], + 'currency_id' => isset($transaction['currency_id']) ? (int) $transaction['currency_id'] : null, + 'currency_code' => $transaction['currency_code'] ?? null, + 'foreign_amount' => $transaction['foreign_amount'] ?? null, + 'foreign_currency_id' => isset($transaction['foreign_currency_id']) ? (int) $transaction['foreign_currency_id'] : null, + 'foreign_currency_code' => $transaction['foreign_currency_code'] ?? null, + 'source_id' => isset($transaction['source_id']) ? (int) $transaction['source_id'] : null, + 'source_name' => isset($transaction['source_name']) ? (string) $transaction['source_name'] : null, + 'destination_id' => isset($transaction['destination_id']) ? (int) $transaction['destination_id'] : null, + 'destination_name' => isset($transaction['destination_name']) ? (string) $transaction['destination_name'] : null, + 'description' => $transaction['description'], + 'type' => $this->string('type'), + + // new and updated fields: + 'piggy_bank_id' => isset($transaction['piggy_bank_id']) ? (int) $transaction['piggy_bank_id'] : null, + 'piggy_bank_name' => $transaction['piggy_bank_name'] ?? null, + 'tags' => $transaction['tags'] ?? [], + 'budget_id' => isset($transaction['budget_id']) ? (int) $transaction['budget_id'] : null, + 'budget_name' => $transaction['budget_name'] ?? null, + 'category_id' => isset($transaction['category_id']) ? (int) $transaction['category_id'] : null, + 'category_name' => $transaction['category_name'] ?? null, + ]; + } + /** * Returns the transaction data as it is found in the submitted data. It's a complex method according to code * standards but it just has a lot of ??-statements because of the fields that may or may not exist. @@ -195,29 +226,7 @@ class RecurrenceUpdateRequest extends Request } /** @var array $transaction */ foreach ($transactions as $transaction) { - $return[] = [ - 'amount' => $transaction['amount'], - 'currency_id' => isset($transaction['currency_id']) ? (int)$transaction['currency_id'] : null, - 'currency_code' => $transaction['currency_code'] ?? null, - 'foreign_amount' => $transaction['foreign_amount'] ?? null, - 'foreign_currency_id' => isset($transaction['foreign_currency_id']) ? (int)$transaction['foreign_currency_id'] : null, - 'foreign_currency_code' => $transaction['foreign_currency_code'] ?? null, - 'source_id' => isset($transaction['source_id']) ? (int)$transaction['source_id'] : null, - 'source_name' => isset($transaction['source_name']) ? (string)$transaction['source_name'] : null, - 'destination_id' => isset($transaction['destination_id']) ? (int)$transaction['destination_id'] : null, - 'destination_name' => isset($transaction['destination_name']) ? (string)$transaction['destination_name'] : null, - 'description' => $transaction['description'], - 'type' => $this->string('type'), - - // new and updated fields: - 'piggy_bank_id' => isset($transaction['piggy_bank_id']) ? (int)$transaction['piggy_bank_id'] : null, - 'piggy_bank_name' => $transaction['piggy_bank_name'] ?? null, - 'tags' => $transaction['tags'] ?? [], - 'budget_id' => isset($transaction['budget_id']) ? (int)$transaction['budget_id'] : null, - 'budget_name' => $transaction['budget_name'] ?? null, - 'category_id' => isset($transaction['category_id']) ? (int)$transaction['category_id'] : null, - 'category_name' => $transaction['category_name'] ?? null, - ]; + $return[] = $this->getSingleData($transaction); } return $return; diff --git a/app/Api/V1/Requests/Request.php b/app/Api/V1/Requests/Request.php index 05495c314d..5c3989c7b1 100644 --- a/app/Api/V1/Requests/Request.php +++ b/app/Api/V1/Requests/Request.php @@ -34,4 +34,5 @@ use FireflyIII\Http\Requests\Request as FireflyIIIRequest; */ class Request extends FireflyIIIRequest { + } diff --git a/app/Api/V1/Requests/RuleGroupTestRequest.php b/app/Api/V1/Requests/RuleGroupTestRequest.php index 4f990d8b00..bdd01747c4 100644 --- a/app/Api/V1/Requests/RuleGroupTestRequest.php +++ b/app/Api/V1/Requests/RuleGroupTestRequest.php @@ -54,7 +54,7 @@ class RuleGroupTestRequest extends Request */ public function getTestParameters(): array { - $return = [ + return [ 'page' => $this->getPage(), 'start_date' => $this->getDate('start_date'), 'end_date' => $this->getDate('end_date'), @@ -62,9 +62,6 @@ class RuleGroupTestRequest extends Request 'trigger_limit' => $this->getTriggerLimit(), 'accounts' => $this->getAccounts(), ]; - - - return $return; } /** @@ -80,7 +77,7 @@ class RuleGroupTestRequest extends Request */ private function getAccounts(): Collection { - $accountList = '' === (string)$this->query('accounts') ? [] : explode(',', $this->query('accounts')); + $accountList = '' === (string) $this->query('accounts') ? [] : explode(',', $this->query('accounts')); $accounts = new Collection; /** @var AccountRepositoryInterface $accountRepository */ @@ -88,7 +85,7 @@ class RuleGroupTestRequest extends Request foreach ($accountList as $accountId) { Log::debug(sprintf('Searching for asset account with id "%s"', $accountId)); - $account = $accountRepository->findNull((int)$accountId); + $account = $accountRepository->findNull((int) $accountId); if ($this->validAccount($account)) { /** @noinspection NullPointerExceptionInspection */ Log::debug(sprintf('Found account #%d ("%s") and its an asset account', $account->id, $account->name)); @@ -117,7 +114,7 @@ class RuleGroupTestRequest extends Request */ private function getPage(): int { - return 0 === (int)$this->query('page') ? 1 : (int)$this->query('page'); + return 0 === (int) $this->query('page') ? 1 : (int) $this->query('page'); } @@ -126,7 +123,7 @@ class RuleGroupTestRequest extends Request */ private function getSearchLimit(): int { - return 0 === (int)$this->query('search_limit') ? (int)config('firefly.test-triggers.limit') : (int)$this->query('search_limit'); + return 0 === (int) $this->query('search_limit') ? (int) config('firefly.test-triggers.limit') : (int) $this->query('search_limit'); } /** @@ -134,7 +131,7 @@ class RuleGroupTestRequest extends Request */ private function getTriggerLimit(): int { - return 0 === (int)$this->query('triggered_limit') ? (int)config('firefly.test-triggers.range') : (int)$this->query('triggered_limit'); + return 0 === (int) $this->query('triggered_limit') ? (int) config('firefly.test-triggers.range') : (int) $this->query('triggered_limit'); } /** diff --git a/app/Api/V1/Requests/RuleGroupTriggerRequest.php b/app/Api/V1/Requests/RuleGroupTriggerRequest.php index 476009b79c..6672fcc35e 100644 --- a/app/Api/V1/Requests/RuleGroupTriggerRequest.php +++ b/app/Api/V1/Requests/RuleGroupTriggerRequest.php @@ -54,14 +54,11 @@ class RuleGroupTriggerRequest extends Request */ public function getTriggerParameters(): array { - $return = [ + return [ 'start_date' => $this->getDate('start_date'), 'end_date' => $this->getDate('end_date'), 'accounts' => $this->getAccounts(), ]; - - - return $return; } /** @@ -80,7 +77,7 @@ class RuleGroupTriggerRequest extends Request */ private function getAccounts(): Collection { - $accountList = '' === (string)$this->query('accounts') ? [] : explode(',', $this->query('accounts')); + $accountList = '' === (string) $this->query('accounts') ? [] : explode(',', $this->query('accounts')); $accounts = new Collection; /** @var AccountRepositoryInterface $accountRepository */ @@ -88,7 +85,7 @@ class RuleGroupTriggerRequest extends Request foreach ($accountList as $accountId) { Log::debug(sprintf('Searching for asset account with id "%s"', $accountId)); - $account = $accountRepository->findNull((int)$accountId); + $account = $accountRepository->findNull((int) $accountId); if ($this->validAccount($account)) { /** @noinspection NullPointerExceptionInspection */ Log::debug(sprintf('Found account #%d ("%s") and its an asset account', $account->id, $account->name)); diff --git a/app/Api/V1/Requests/RuleStoreRequest.php b/app/Api/V1/Requests/RuleStoreRequest.php index dc7fb256f9..bdbac61824 100644 --- a/app/Api/V1/Requests/RuleStoreRequest.php +++ b/app/Api/V1/Requests/RuleStoreRequest.php @@ -65,7 +65,7 @@ class RuleStoreRequest extends Request $stopProcessing = $this->boolean('stop_processing'); } - $data = [ + return [ 'title' => $this->string('title'), 'description' => $this->string('description'), 'rule_group_id' => $this->integer('rule_group_id'), @@ -77,8 +77,6 @@ class RuleStoreRequest extends Request 'triggers' => $this->getRuleTriggers(), 'actions' => $this->getRuleActions(), ]; - - return $data; } /** @@ -94,7 +92,8 @@ class RuleStoreRequest extends Request // some triggers and actions require text: $contextTriggers = implode(',', config('firefly.context-rule-triggers')); $contextActions = implode(',', config('firefly.context-rule-actions')); - $rules = [ + + return [ 'title' => 'required|between:1,100|uniqueObjectForUser:rules,title', 'description' => 'between:1,5000|nullable', 'rule_group_id' => 'required|belongsToUser:rule_groups|required_without:rule_group_title', @@ -112,8 +111,6 @@ class RuleStoreRequest extends Request 'stop_processing' => [new IsBoolean], 'active' => [new IsBoolean], ]; - - return $rules; } /** @@ -144,7 +141,7 @@ class RuleStoreRequest extends Request $actions = $data['actions'] ?? []; // need at least one trigger if (0 === count($actions)) { - $validator->errors()->add('title', (string)trans('validation.at_least_one_action')); + $validator->errors()->add('title', (string) trans('validation.at_least_one_action')); } } @@ -159,7 +156,7 @@ class RuleStoreRequest extends Request $triggers = $data['triggers'] ?? []; // need at least one trigger if (0 === count($triggers)) { - $validator->errors()->add('title', (string)trans('validation.at_least_one_trigger')); + $validator->errors()->add('title', (string) trans('validation.at_least_one_trigger')); } } @@ -175,8 +172,8 @@ class RuleStoreRequest extends Request $return[] = [ 'type' => $action['type'], 'value' => $action['value'], - 'active' => $this->convertBoolean((string)($action['active'] ?? 'false')), - 'stop_processing' => $this->convertBoolean((string)($action['stop_processing'] ?? 'false')), + 'active' => $this->convertBoolean((string) ($action['active'] ?? 'false')), + 'stop_processing' => $this->convertBoolean((string) ($action['stop_processing'] ?? 'false')), ]; } } @@ -196,8 +193,8 @@ class RuleStoreRequest extends Request $return[] = [ 'type' => $trigger['type'], 'value' => $trigger['value'], - 'active' => $this->convertBoolean((string)($trigger['active'] ?? 'false')), - 'stop_processing' => $this->convertBoolean((string)($trigger['stop_processing'] ?? 'false')), + 'active' => $this->convertBoolean((string) ($trigger['active'] ?? 'false')), + 'stop_processing' => $this->convertBoolean((string) ($trigger['stop_processing'] ?? 'false')), ]; } } diff --git a/app/Api/V1/Requests/RuleTestRequest.php b/app/Api/V1/Requests/RuleTestRequest.php index 3aa41ac848..e506ce9d81 100644 --- a/app/Api/V1/Requests/RuleTestRequest.php +++ b/app/Api/V1/Requests/RuleTestRequest.php @@ -54,7 +54,7 @@ class RuleTestRequest extends Request */ public function getTestParameters(): array { - $return = [ + return [ 'page' => $this->getPage(), 'start_date' => $this->getDate('start_date'), 'end_date' => $this->getDate('end_date'), @@ -62,9 +62,6 @@ class RuleTestRequest extends Request 'trigger_limit' => $this->getTriggerLimit(), 'accounts' => $this->getAccounts(), ]; - - - return $return; } /** @@ -80,7 +77,7 @@ class RuleTestRequest extends Request */ private function getAccounts(): Collection { - $accountList = '' === (string)$this->query('accounts') ? [] : explode(',', $this->query('accounts')); + $accountList = '' === (string) $this->query('accounts') ? [] : explode(',', $this->query('accounts')); $accounts = new Collection; /** @var AccountRepositoryInterface $accountRepository */ @@ -88,7 +85,7 @@ class RuleTestRequest extends Request foreach ($accountList as $accountId) { Log::debug(sprintf('Searching for asset account with id "%s"', $accountId)); - $account = $accountRepository->findNull((int)$accountId); + $account = $accountRepository->findNull((int) $accountId); if ($this->validAccount($account)) { /** @noinspection NullPointerExceptionInspection */ Log::debug(sprintf('Found account #%d ("%s") and its an asset account', $account->id, $account->name)); @@ -117,7 +114,7 @@ class RuleTestRequest extends Request */ private function getPage(): int { - return 0 === (int)$this->query('page') ? 1 : (int)$this->query('page'); + return 0 === (int) $this->query('page') ? 1 : (int) $this->query('page'); } @@ -126,7 +123,7 @@ class RuleTestRequest extends Request */ private function getSearchLimit(): int { - return 0 === (int)$this->query('search_limit') ? (int)config('firefly.test-triggers.limit') : (int)$this->query('search_limit'); + return 0 === (int) $this->query('search_limit') ? (int) config('firefly.test-triggers.limit') : (int) $this->query('search_limit'); } /** @@ -134,7 +131,7 @@ class RuleTestRequest extends Request */ private function getTriggerLimit(): int { - return 0 === (int)$this->query('triggered_limit') ? (int)config('firefly.test-triggers.range') : (int)$this->query('triggered_limit'); + return 0 === (int) $this->query('triggered_limit') ? (int) config('firefly.test-triggers.range') : (int) $this->query('triggered_limit'); } /** diff --git a/app/Api/V1/Requests/RuleTriggerRequest.php b/app/Api/V1/Requests/RuleTriggerRequest.php index 8d4042b0b8..d05f4f7dfe 100644 --- a/app/Api/V1/Requests/RuleTriggerRequest.php +++ b/app/Api/V1/Requests/RuleTriggerRequest.php @@ -53,14 +53,11 @@ class RuleTriggerRequest extends Request */ public function getTriggerParameters(): array { - $return = [ + return [ 'start_date' => $this->getDate('start_date'), 'end_date' => $this->getDate('end_date'), 'accounts' => $this->getAccounts(), ]; - - - return $return; } /** @@ -79,7 +76,7 @@ class RuleTriggerRequest extends Request */ private function getAccounts(): Collection { - $accountList = '' === (string)$this->query('accounts') ? [] : explode(',', $this->query('accounts')); + $accountList = '' === (string) $this->query('accounts') ? [] : explode(',', $this->query('accounts')); $accounts = new Collection; /** @var AccountRepositoryInterface $accountRepository */ @@ -87,7 +84,7 @@ class RuleTriggerRequest extends Request foreach ($accountList as $accountId) { Log::debug(sprintf('Searching for asset account with id "%s"', $accountId)); - $account = $accountRepository->findNull((int)$accountId); + $account = $accountRepository->findNull((int) $accountId); if ($this->validAccount($account)) { /** @noinspection NullPointerExceptionInspection */ Log::debug(sprintf('Found account #%d ("%s") and its an asset account', $account->id, $account->name)); diff --git a/app/Api/V1/Requests/RuleUpdateRequest.php b/app/Api/V1/Requests/RuleUpdateRequest.php index 15d05c0032..e1f8186883 100644 --- a/app/Api/V1/Requests/RuleUpdateRequest.php +++ b/app/Api/V1/Requests/RuleUpdateRequest.php @@ -65,7 +65,7 @@ class RuleUpdateRequest extends Request $stopProcessing = $this->boolean('stop_processing'); } - $data = [ + return [ 'title' => $this->nullableString('title'), 'description' => $this->nullableString('description'), 'rule_group_id' => $this->nullableInteger('rule_group_id'), @@ -77,8 +77,6 @@ class RuleUpdateRequest extends Request 'triggers' => $this->getRuleTriggers(), 'actions' => $this->getRuleActions(), ]; - - return $data; } /** @@ -95,7 +93,8 @@ class RuleUpdateRequest extends Request // some triggers and actions require text: $contextTriggers = implode(',', config('firefly.context-rule-triggers')); $contextActions = implode(',', config('firefly.context-rule-actions')); - $rules = [ + + return [ 'title' => sprintf('between:1,100|uniqueObjectForUser:rules,title,%d', $rule->id), 'description' => 'between:1,5000|nullable', 'rule_group_id' => 'belongsToUser:rule_groups', @@ -113,8 +112,6 @@ class RuleUpdateRequest extends Request 'stop_processing' => [new IsBoolean], 'active' => [new IsBoolean], ]; - - return $rules; } /** @@ -145,7 +142,7 @@ class RuleUpdateRequest extends Request $actions = $data['actions'] ?? null; // need at least one action if (is_array($actions) && 0 === count($actions)) { - $validator->errors()->add('title', (string)trans('validation.at_least_one_action')); + $validator->errors()->add('title', (string) trans('validation.at_least_one_action')); } } @@ -160,7 +157,7 @@ class RuleUpdateRequest extends Request $triggers = $data['triggers'] ?? null; // need at least one trigger if (is_array($triggers) && 0 === count($triggers)) { - $validator->errors()->add('title', (string)trans('validation.at_least_one_trigger')); + $validator->errors()->add('title', (string) trans('validation.at_least_one_trigger')); } } @@ -179,8 +176,8 @@ class RuleUpdateRequest extends Request $return[] = [ 'type' => $action['type'], 'value' => $action['value'], - 'active' => $this->convertBoolean((string)($action['active'] ?? 'false')), - 'stop_processing' => $this->convertBoolean((string)($action['stop_processing'] ?? 'false')), + 'active' => $this->convertBoolean((string) ($action['active'] ?? 'false')), + 'stop_processing' => $this->convertBoolean((string) ($action['stop_processing'] ?? 'false')), ]; } } @@ -203,8 +200,8 @@ class RuleUpdateRequest extends Request $return[] = [ 'type' => $trigger['type'], 'value' => $trigger['value'], - 'active' => $this->convertBoolean((string)($trigger['active'] ?? 'false')), - 'stop_processing' => $this->convertBoolean((string)($trigger['stop_processing'] ?? 'false')), + 'active' => $this->convertBoolean((string) ($trigger['active'] ?? 'false')), + 'stop_processing' => $this->convertBoolean((string) ($trigger['stop_processing'] ?? 'false')), ]; } } diff --git a/app/Api/V1/Requests/Search/TransferRequest.php b/app/Api/V1/Requests/Search/TransferRequest.php index 6ee29592f8..5cfb4d3ead 100644 --- a/app/Api/V1/Requests/Search/TransferRequest.php +++ b/app/Api/V1/Requests/Search/TransferRequest.php @@ -1,4 +1,5 @@ 'required|date', ]; } - -} \ No newline at end of file +} diff --git a/app/Api/V1/Requests/TransactionLinkRequest.php b/app/Api/V1/Requests/TransactionLinkRequest.php index 8cf4094318..9086c2cdd5 100644 --- a/app/Api/V1/Requests/TransactionLinkRequest.php +++ b/app/Api/V1/Requests/TransactionLinkRequest.php @@ -110,8 +110,8 @@ class TransactionLinkRequest extends Request $journalRepos->setUser($user); $data = $validator->getData(); - $inwardId = (int)($data['inward_id'] ?? 0); - $outwardId = (int)($data['outward_id'] ?? 0); + $inwardId = (int) ($data['inward_id'] ?? 0); + $outwardId = (int) ($data['outward_id'] ?? 0); $inward = $journalRepos->findNull($inwardId); $outward = $journalRepos->findNull($outwardId); diff --git a/app/Api/V1/Requests/TransactionStoreRequest.php b/app/Api/V1/Requests/TransactionStoreRequest.php index 3b9319dd51..5315c3c22a 100644 --- a/app/Api/V1/Requests/TransactionStoreRequest.php +++ b/app/Api/V1/Requests/TransactionStoreRequest.php @@ -60,14 +60,13 @@ class TransactionStoreRequest extends Request public function getAll(): array { Log::debug('get all data in TransactionStoreRequest'); - $data = [ + + return [ 'group_title' => $this->string('group_title'), 'error_if_duplicate_hash' => $this->boolean('error_if_duplicate_hash'), 'apply_rules' => $this->boolean('apply_rules', true), 'transactions' => $this->getTransactionData(), ]; - - return $data; } /** @@ -78,7 +77,8 @@ class TransactionStoreRequest extends Request public function rules(): array { Log::debug('Collect rules of TransactionStoreRequest'); - $rules = [ + + return [ // basic fields for group: 'group_title' => 'between:1,1000|nullable', 'error_if_duplicate_hash' => [new IsBoolean], @@ -156,8 +156,6 @@ class TransactionStoreRequest extends Request 'transactions.*.invoice_date' => 'date|nullable', ]; - return $rules; - } @@ -214,63 +212,63 @@ class TransactionStoreRequest extends Request $return[] = [ 'type' => $this->stringFromValue($object['type']), 'date' => $this->dateFromValue($object['date']), - 'order' => $this->integerFromValue((string)$object['order']), + 'order' => $this->integerFromValue((string) $object['order']), - 'currency_id' => $this->integerFromValue((string)$object['currency_id']), + 'currency_id' => $this->integerFromValue((string) $object['currency_id']), 'currency_code' => $this->stringFromValue($object['currency_code']), // foreign currency info: - 'foreign_currency_id' => $this->integerFromValue((string)$object['foreign_currency_id']), + 'foreign_currency_id' => $this->integerFromValue((string) $object['foreign_currency_id']), 'foreign_currency_code' => $this->stringFromValue($object['foreign_currency_code']), // amount and foreign amount. Cannot be 0. - 'amount' => $this->stringFromValue((string)$object['amount']), - 'foreign_amount' => $this->stringFromValue((string)$object['foreign_amount']), + 'amount' => $this->stringFromValue((string) $object['amount']), + 'foreign_amount' => $this->stringFromValue((string) $object['foreign_amount']), // description. 'description' => $this->stringFromValue($object['description']), // source of transaction. If everything is null, assume cash account. - 'source_id' => $this->integerFromValue((string)$object['source_id']), + 'source_id' => $this->integerFromValue((string) $object['source_id']), 'source_name' => $this->stringFromValue($object['source_name']), 'source_iban' => $this->stringFromValue($object['source_iban']), 'source_number' => $this->stringFromValue($object['source_number']), 'source_bic' => $this->stringFromValue($object['source_bic']), // destination of transaction. If everything is null, assume cash account. - 'destination_id' => $this->integerFromValue((string)$object['destination_id']), + 'destination_id' => $this->integerFromValue((string) $object['destination_id']), 'destination_name' => $this->stringFromValue($object['destination_name']), 'destination_iban' => $this->stringFromValue($object['destination_iban']), 'destination_number' => $this->stringFromValue($object['destination_number']), 'destination_bic' => $this->stringFromValue($object['destination_bic']), // budget info - 'budget_id' => $this->integerFromValue((string)$object['budget_id']), + 'budget_id' => $this->integerFromValue((string) $object['budget_id']), 'budget_name' => $this->stringFromValue($object['budget_name']), // category info - 'category_id' => $this->integerFromValue((string)$object['category_id']), + 'category_id' => $this->integerFromValue((string) $object['category_id']), 'category_name' => $this->stringFromValue($object['category_name']), // journal bill reference. Optional. Will only work for withdrawals - 'bill_id' => $this->integerFromValue((string)$object['bill_id']), + 'bill_id' => $this->integerFromValue((string) $object['bill_id']), 'bill_name' => $this->stringFromValue($object['bill_name']), // piggy bank reference. Optional. Will only work for transfers - 'piggy_bank_id' => $this->integerFromValue((string)$object['piggy_bank_id']), + 'piggy_bank_id' => $this->integerFromValue((string) $object['piggy_bank_id']), 'piggy_bank_name' => $this->stringFromValue($object['piggy_bank_name']), // some other interesting properties - 'reconciled' => $this->convertBoolean((string)$object['reconciled']), + 'reconciled' => $this->convertBoolean((string) $object['reconciled']), 'notes' => $this->nlStringFromValue($object['notes']), 'tags' => $this->arrayFromValue($object['tags']), // all custom fields: - 'internal_reference' => $this->stringFromValue((string)$object['internal_reference']), - 'external_id' => $this->stringFromValue((string)$object['external_id']), + 'internal_reference' => $this->stringFromValue((string) $object['internal_reference']), + 'external_id' => $this->stringFromValue((string) $object['external_id']), 'original_source' => sprintf('ff3-v%s|api-v%s', config('firefly.version'), config('firefly.api_version')), 'recurrence_id' => $this->integerFromValue($object['recurrence_id']), - 'bunq_payment_id' => $this->stringFromValue((string)$object['bunq_payment_id']), + 'bunq_payment_id' => $this->stringFromValue((string) $object['bunq_payment_id']), 'sepa_cc' => $this->stringFromValue($object['sepa_cc']), 'sepa_ct_op' => $this->stringFromValue($object['sepa_ct_op']), diff --git a/app/Api/V1/Requests/TransactionUpdateRequest.php b/app/Api/V1/Requests/TransactionUpdateRequest.php index 422032ba3e..7ea795c3b7 100644 --- a/app/Api/V1/Requests/TransactionUpdateRequest.php +++ b/app/Api/V1/Requests/TransactionUpdateRequest.php @@ -154,7 +154,7 @@ class TransactionUpdateRequest extends Request */ public function rules(): array { - $rules = [ + return [ // basic fields for group: 'group_title' => 'between:1,1000', 'apply_rules' => [new IsBoolean], @@ -222,8 +222,6 @@ class TransactionUpdateRequest extends Request 'transactions.*.payment_date' => 'date|nullable', 'transactions.*.invoice_date' => 'date|nullable', ]; - - return $rules; } /** @@ -279,6 +277,111 @@ class TransactionUpdateRequest extends Request ); } + /** + * @param array $current + * @param array $transaction + * + * @return array + */ + private function getArrayData(array $current, array $transaction): array + { + foreach ($this->arrayFields as $fieldName) { + if (array_key_exists($fieldName, $transaction)) { + $current[$fieldName] = $this->arrayFromValue($transaction[$fieldName]); + } + } + + return $current; + } + + /** + * @param array $current + * @param array $transaction + * + * @return array + */ + private function getBooleanData(array $current, array $transaction): array + { + foreach ($this->booleanFields as $fieldName) { + if (array_key_exists($fieldName, $transaction)) { + $current[$fieldName] = $this->convertBoolean((string) $transaction[$fieldName]); + } + } + + return $current; + } + + /** + * @param array $current + * @param array $transaction + * + * @return array + */ + private function getDateData(array $current, array $transaction): array + { + foreach ($this->dateFields as $fieldName) { + Log::debug(sprintf('Now at date field %s', $fieldName)); + if (array_key_exists($fieldName, $transaction)) { + $current[$fieldName] = $this->dateFromValue((string) $transaction[$fieldName]); + Log::debug(sprintf('New value: "%s"', (string) $transaction[$fieldName])); + } + } + + return $current; + } + + /** + * For each field, add it to the array if a reference is present in the request: + * + * @param array $current + * + * @return array + */ + private function getIntegerData(array $current, array $transaction): array + { + foreach ($this->integerFields as $fieldName) { + if (array_key_exists($fieldName, $transaction)) { + $current[$fieldName] = $this->integerFromValue((string) $transaction[$fieldName]); + } + } + + return $current; + } + + /** + * @param array $current + * @param array $transaction + * + * @return array + */ + private function getNlStringData(array $current, array $transaction): array + { + foreach ($this->textareaFields as $fieldName) { + if (array_key_exists($fieldName, $transaction)) { + $current[$fieldName] = $this->nlStringFromValue((string) $transaction[$fieldName]); + } + } + + return $current; + } + + /** + * @param array $current + * @param array $transaction + * + * @return array + */ + private function getStringData(array $current, array $transaction): array + { + foreach ($this->stringFields as $fieldName) { + if (array_key_exists($fieldName, $transaction)) { + $current[$fieldName] = $this->stringFromValue((string) $transaction[$fieldName]); + } + } + + return $current; + } + /** * Get transaction data. * @@ -292,48 +395,15 @@ class TransactionUpdateRequest extends Request * @var int $index * @var array $transaction */ - foreach ($this->get('transactions') as $index => $transaction) { + foreach ($this->get('transactions') as $transaction) { // default response is to update nothing in the transaction: - $current = []; - - // for each field, add it to the array if a reference is present in the request: - foreach ($this->integerFields as $fieldName) { - if (array_key_exists($fieldName, $transaction)) { - $current[$fieldName] = $this->integerFromValue((string)$transaction[$fieldName]); - } - } - - foreach ($this->stringFields as $fieldName) { - if (array_key_exists($fieldName, $transaction)) { - $current[$fieldName] = $this->stringFromValue((string)$transaction[$fieldName]); - } - } - - foreach ($this->textareaFields as $fieldName) { - if (array_key_exists($fieldName, $transaction)) { - $current[$fieldName] = $this->nlStringFromValue((string)$transaction[$fieldName]); - } - } - - foreach ($this->dateFields as $fieldName) { - Log::debug(sprintf('Now at date field %s', $fieldName)); - if (array_key_exists($fieldName, $transaction)) { - $current[$fieldName] = $this->dateFromValue((string)$transaction[$fieldName]); - Log::debug(sprintf('New value: "%s"', (string)$transaction[$fieldName])); - } - } - - foreach ($this->booleanFields as $fieldName) { - if (array_key_exists($fieldName, $transaction)) { - $current[$fieldName] = $this->convertBoolean((string)$transaction[$fieldName]); - } - } - - foreach ($this->arrayFields as $fieldName) { - if (array_key_exists($fieldName, $transaction)) { - $current[$fieldName] = $this->arrayFromValue($transaction[$fieldName]); - } - } + $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); $return[] = $current; } diff --git a/app/Api/V1/Requests/UserStoreRequest.php b/app/Api/V1/Requests/UserStoreRequest.php index 89680806d0..e9b55980fe 100644 --- a/app/Api/V1/Requests/UserStoreRequest.php +++ b/app/Api/V1/Requests/UserStoreRequest.php @@ -69,14 +69,13 @@ class UserStoreRequest extends Request if (null !== $this->get('blocked')) { $blocked = $this->boolean('blocked'); } - $data = [ + + return [ 'email' => $this->string('email'), 'blocked' => $blocked, 'blocked_code' => $this->string('blocked_code'), 'role' => $this->string('role'), ]; - - return $data; } /** diff --git a/app/Api/V1/Requests/UserUpdateRequest.php b/app/Api/V1/Requests/UserUpdateRequest.php index bc3fe9d3bb..7dc41b7806 100644 --- a/app/Api/V1/Requests/UserUpdateRequest.php +++ b/app/Api/V1/Requests/UserUpdateRequest.php @@ -69,14 +69,13 @@ class UserUpdateRequest extends Request if (null !== $this->get('blocked')) { $blocked = $this->boolean('blocked'); } - $data = [ + + return [ 'email' => $this->string('email'), 'blocked' => $blocked, 'blocked_code' => $this->string('blocked_code'), 'role' => $this->string('role'), ]; - - return $data; } /** @@ -86,15 +85,14 @@ class UserUpdateRequest extends Request */ public function rules(): array { - $user = $this->route()->parameter('user'); - $rules = [ + $user = $this->route()->parameter('user'); + + return [ 'email' => sprintf('email|unique:users,email,%d', $user->id), 'blocked' => [new IsBoolean], 'blocked_code' => 'in:email_changed', 'role' => 'in:owner,demo,', ]; - - return $rules; } } diff --git a/app/Console/Commands/Correction/CorrectDatabase.php b/app/Console/Commands/Correction/CorrectDatabase.php index 01b6a9c3f6..d2e88f4725 100644 --- a/app/Console/Commands/Correction/CorrectDatabase.php +++ b/app/Console/Commands/Correction/CorrectDatabase.php @@ -30,6 +30,7 @@ use Schema; /** * Class CorrectDatabase + * * @codeCoverageIgnore */ class CorrectDatabase extends Command @@ -73,7 +74,7 @@ class CorrectDatabase extends Command 'firefly-iii:fix-ob-currencies', 'firefly-iii:fix-long-descriptions', 'firefly-iii:fix-recurring-transactions', - 'firefly-iii:restore-oauth-keys' + 'firefly-iii:restore-oauth-keys', ]; foreach ($commands as $command) { $this->line(sprintf('Now executing %s', $command)); diff --git a/app/Console/Commands/Correction/CorrectOpeningBalanceCurrencies.php b/app/Console/Commands/Correction/CorrectOpeningBalanceCurrencies.php index fda42940a7..6b1fc6a04f 100644 --- a/app/Console/Commands/Correction/CorrectOpeningBalanceCurrencies.php +++ b/app/Console/Commands/Correction/CorrectOpeningBalanceCurrencies.php @@ -111,15 +111,12 @@ class CorrectOpeningBalanceCurrencies extends Command */ private function getAccount(TransactionJournal $journal): ?Account { - $excluded = []; $transactions = $journal->transactions()->with(['account', 'account.accountType'])->get(); /** @var Transaction $transaction */ foreach ($transactions as $transaction) { $account = $transaction->account; - if (null !== $account) { - if (AccountType::INITIAL_BALANCE !== $account->accountType->type) { - return $account; - } + if ((null !== $account) && AccountType::INITIAL_BALANCE !== $account->accountType->type) { + return $account; } } diff --git a/app/Console/Commands/Correction/CreateAccessTokens.php b/app/Console/Commands/Correction/CreateAccessTokens.php index 6286c3398c..9dd515c17a 100644 --- a/app/Console/Commands/Correction/CreateAccessTokens.php +++ b/app/Console/Commands/Correction/CreateAccessTokens.php @@ -50,8 +50,8 @@ class CreateAccessTokens extends Command /** * Execute the console command. * - * @return int * @throws Exception + * @return int */ public function handle(): int { diff --git a/app/Console/Commands/Correction/DeleteEmptyGroups.php b/app/Console/Commands/Correction/DeleteEmptyGroups.php index a9a640de36..abf75ac2a7 100644 --- a/app/Console/Commands/Correction/DeleteEmptyGroups.php +++ b/app/Console/Commands/Correction/DeleteEmptyGroups.php @@ -25,7 +25,6 @@ namespace FireflyIII\Console\Commands\Correction; use Exception; use FireflyIII\Models\TransactionGroup; -use FireflyIII\Models\TransactionJournal; use Illuminate\Console\Command; use Log; @@ -50,16 +49,16 @@ class DeleteEmptyGroups extends Command /** * Execute the console command. * - * @return mixed * @throws Exception; + * @return mixed */ public function handle(): int { Log::debug(sprintf('Now in %s', __METHOD__)); - $start = microtime(true); - $groupIds = - TransactionGroup - ::leftJoin('transaction_journals','transaction_groups.id','=','transaction_journals.transaction_group_id') + $start = microtime(true); + $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); diff --git a/app/Console/Commands/Correction/DeleteEmptyJournals.php b/app/Console/Commands/Correction/DeleteEmptyJournals.php index 5704b3fdc3..034aeb89d3 100644 --- a/app/Console/Commands/Correction/DeleteEmptyJournals.php +++ b/app/Console/Commands/Correction/DeleteEmptyJournals.php @@ -101,18 +101,18 @@ class DeleteEmptyJournals extends Command ->get([DB::raw('COUNT(transactions.transaction_journal_id) as the_count'), 'transaction_journal_id']); $total = 0; foreach ($set as $row) { - $count = (int)$row->the_count; + $count = (int) $row->the_count; if (1 === $count % 2) { // uneven number, delete journal and transactions: try { - TransactionJournal::find((int)$row->transaction_journal_id)->delete(); + TransactionJournal::find((int) $row->transaction_journal_id)->delete(); // @codeCoverageIgnoreStart } catch (Exception $e) { Log::info(sprintf('Could not delete journal: %s', $e->getMessage())); } // @codeCoverageIgnoreEnd - Transaction::where('transaction_journal_id', (int)$row->transaction_journal_id)->delete(); + Transaction::where('transaction_journal_id', (int) $row->transaction_journal_id)->delete(); $this->info(sprintf('Deleted transaction journal #%d because it had an uneven number of transactions.', $row->transaction_journal_id)); $total++; } diff --git a/app/Console/Commands/Correction/DeleteOrphanedTransactions.php b/app/Console/Commands/Correction/DeleteOrphanedTransactions.php index b9611e599c..c95007b60f 100644 --- a/app/Console/Commands/Correction/DeleteOrphanedTransactions.php +++ b/app/Console/Commands/Correction/DeleteOrphanedTransactions.php @@ -51,8 +51,8 @@ class DeleteOrphanedTransactions extends Command /** * Execute the console command. * - * @return int * @throws Exception + * @return int */ public function handle(): int { @@ -79,7 +79,7 @@ class DeleteOrphanedTransactions extends Command /** @var Transaction $transaction */ foreach ($set as $transaction) { // delete journals - $journal = TransactionJournal::find((int)$transaction->transaction_journal_id); + $journal = TransactionJournal::find((int) $transaction->transaction_journal_id); if ($journal) { try { $journal->delete(); @@ -89,10 +89,13 @@ class DeleteOrphanedTransactions extends Command } // @codeCoverageIgnoreEnd } - Transaction::where('transaction_journal_id', (int)$transaction->transaction_journal_id)->delete(); + Transaction::where('transaction_journal_id', (int) $transaction->transaction_journal_id)->delete(); $this->line( - sprintf('Deleted transaction journal #%d because account #%d was already deleted.', - $transaction->transaction_journal_id, $transaction->account_id) + sprintf( + 'Deleted transaction journal #%d because account #%d was already deleted.', + $transaction->transaction_journal_id, + $transaction->account_id + ) ); $count++; } @@ -120,7 +123,7 @@ class DeleteOrphanedTransactions extends Command ); /** @var stdClass $entry */ foreach ($set as $entry) { - $transaction = Transaction::find((int)$entry->transaction_id); + $transaction = Transaction::find((int) $entry->transaction_id); $transaction->delete(); $this->info( sprintf( @@ -134,6 +137,5 @@ class DeleteOrphanedTransactions extends Command if (0 === $count) { $this->info('No orphaned transactions.'); } - } } diff --git a/app/Console/Commands/Correction/DeleteZeroAmount.php b/app/Console/Commands/Correction/DeleteZeroAmount.php index afae462e17..f96b426eee 100644 --- a/app/Console/Commands/Correction/DeleteZeroAmount.php +++ b/app/Console/Commands/Correction/DeleteZeroAmount.php @@ -49,6 +49,7 @@ class DeleteZeroAmount extends Command /** * Execute the console command. + * * @return int */ public function handle(): int diff --git a/app/Console/Commands/Correction/EnableCurrencies.php b/app/Console/Commands/Correction/EnableCurrencies.php index 87f5fe4ef7..f31d8d102a 100644 --- a/app/Console/Commands/Correction/EnableCurrencies.php +++ b/app/Console/Commands/Correction/EnableCurrencies.php @@ -62,28 +62,28 @@ class EnableCurrencies extends Command /** @var Collection $meta */ $meta = AccountMeta::where('name', 'currency_id')->groupBy('data')->get(['data']); foreach ($meta as $entry) { - $found[] = (int)$entry->data; + $found[] = (int) $entry->data; } // get all from journals: /** @var Collection $journals */ $journals = TransactionJournal::groupBy('transaction_currency_id')->get(['transaction_currency_id']); foreach ($journals as $entry) { - $found[] = (int)$entry->transaction_currency_id; + $found[] = (int) $entry->transaction_currency_id; } // get all from transactions /** @var Collection $transactions */ $transactions = Transaction::groupBy('transaction_currency_id')->get(['transaction_currency_id']); foreach ($transactions as $entry) { - $found[] = (int)$entry->transaction_currency_id; + $found[] = (int) $entry->transaction_currency_id; } // get all from budget limits /** @var Collection $limits */ $limits = BudgetLimit::groupBy('transaction_currency_id')->get(['transaction_currency_id']); foreach ($limits as $entry) { - $found[] = (int)$entry->transaction_currency_id; + $found[] = (int) $entry->transaction_currency_id; } $found = array_unique($found); diff --git a/app/Console/Commands/Correction/FixAccountTypes.php b/app/Console/Commands/Correction/FixAccountTypes.php index 277d72a0df..8b6bd26d8e 100644 --- a/app/Console/Commands/Correction/FixAccountTypes.php +++ b/app/Console/Commands/Correction/FixAccountTypes.php @@ -49,20 +49,20 @@ class FixAccountTypes extends Command * @var string */ protected $signature = 'firefly-iii:fix-account-types'; + /** @var int */ + private $count; /** @var array */ private $expected; /** @var AccountFactory */ private $factory; /** @var array */ private $fixable; - /** @var int */ - private $count; /** * Execute the console command. * - * @return int * @throws FireflyException + * @return int */ public function handle(): int { @@ -109,23 +109,12 @@ class FixAccountTypes extends Command return 0; } - /** - * Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is - * executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should - * be called from the handle method instead of using the constructor to initialize the command. - * - * @codeCoverageIgnore - */ - private function stupidLaravel(): void - { - $this->count = 0; - } - /** * @param TransactionJournal $journal - * @param string $type - * @param Transaction $source - * @param Transaction $dest + * @param string $type + * @param Transaction $source + * @param Transaction $dest + * * @throws FireflyException */ private function fixJournal(TransactionJournal $journal, string $type, Transaction $source, Transaction $dest): void @@ -167,9 +156,12 @@ class FixAccountTypes extends Command $dest->save(); $this->info( sprintf( - 'Transaction journal #%d, destination account changed from #%d ("%s") to #%d ("%s").', $journal->id, - $oldDest->id, $oldDest->name, - $result->id, $result->name + 'Transaction journal #%d, destination account changed from #%d ("%s") to #%d ("%s").', + $journal->id, + $oldDest->id, + $oldDest->name, + $result->id, + $result->name ) ); $this->inspectJournal($journal); @@ -184,9 +176,12 @@ class FixAccountTypes extends Command $source->save(); $this->info( sprintf( - 'Transaction journal #%d, source account changed from #%d ("%s") to #%d ("%s").', $journal->id, - $oldSource->id, $oldSource->name, - $result->id, $result->name + 'Transaction journal #%d, source account changed from #%d ("%s") to #%d ("%s").', + $journal->id, + $oldSource->id, + $oldSource->name, + $result->id, + $result->name ) ); $this->inspectJournal($journal); @@ -198,7 +193,6 @@ class FixAccountTypes extends Command break; } - } /** @@ -274,4 +268,15 @@ class FixAccountTypes extends Command } } + /** + * Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is + * executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should + * be called from the handle method instead of using the constructor to initialize the command. + * + * @codeCoverageIgnore + */ + private function stupidLaravel(): void + { + $this->count = 0; + } } diff --git a/app/Console/Commands/Correction/FixLongDescriptions.php b/app/Console/Commands/Correction/FixLongDescriptions.php index f43b3dd6ab..264c728d58 100644 --- a/app/Console/Commands/Correction/FixLongDescriptions.php +++ b/app/Console/Commands/Correction/FixLongDescriptions.php @@ -51,7 +51,7 @@ class FixLongDescriptions extends Command */ public function handle(): int { - $start = microtime(true); + $start = microtime(true); $journals = TransactionJournal::get(['id', 'description']); /** @var TransactionJournal $journal */ foreach ($journals as $journal) { @@ -73,6 +73,7 @@ class FixLongDescriptions extends Command } $end = round(microtime(true) - $start, 2); $this->info(sprintf('Verified all transaction group and journal title lengths in %s seconds.', $end)); + return 0; } } diff --git a/app/Console/Commands/Correction/FixRecurringTransactions.php b/app/Console/Commands/Correction/FixRecurringTransactions.php index f9e99f6de1..c64039a6f8 100644 --- a/app/Console/Commands/Correction/FixRecurringTransactions.php +++ b/app/Console/Commands/Correction/FixRecurringTransactions.php @@ -51,16 +51,6 @@ class FixRecurringTransactions extends Command /** @var UserRepositoryInterface */ private $userRepos; - /** - * Create a new command instance. - * - * @return void - */ - public function __construct() - { - parent::__construct(); - } - /** * Execute the console command. * diff --git a/app/Console/Commands/Correction/FixUnevenAmount.php b/app/Console/Commands/Correction/FixUnevenAmount.php index 2001cf0848..d545d2f11e 100644 --- a/app/Console/Commands/Correction/FixUnevenAmount.php +++ b/app/Console/Commands/Correction/FixUnevenAmount.php @@ -63,8 +63,8 @@ class FixUnevenAmount extends Command ->get(['transaction_journal_id', DB::raw('SUM(amount) AS the_sum')]); /** @var stdClass $entry */ foreach ($journals as $entry) { - if (0 !== bccomp((string)$entry->the_sum, '0')) { - $this->fixJournal((int)$entry->transaction_journal_id); + if (0 !== bccomp((string) $entry->the_sum, '0')) { + $this->fixJournal((int) $entry->transaction_journal_id); $count++; } } @@ -94,7 +94,8 @@ class FixUnevenAmount extends Command if (null === $source) { $this->error( sprintf( - 'Journal #%d ("%s") has no source transaction. It will be deleted to maintain database consistency.', $journal->id ?? 0, + 'Journal #%d ("%s") has no source transaction. It will be deleted to maintain database consistency.', + $journal->id ?? 0, $journal->description ?? '' ) ); @@ -104,7 +105,7 @@ class FixUnevenAmount extends Command return; } - $amount = bcmul('-1', (string)$source->amount); + $amount = bcmul('-1', (string) $source->amount); // fix amount of destination: /** @var Transaction $destination */ @@ -113,7 +114,8 @@ class FixUnevenAmount extends Command if (null === $destination) { $this->error( sprintf( - 'Journal #%d ("%s") has no destination transaction. It will be deleted to maintain database consistency.', $journal->id ?? 0, + 'Journal #%d ("%s") has no destination transaction. It will be deleted to maintain database consistency.', + $journal->id ?? 0, $journal->description ?? '' ) ); diff --git a/app/Console/Commands/DecryptDatabase.php b/app/Console/Commands/DecryptDatabase.php index 24885712c2..8d90e1134b 100644 --- a/app/Console/Commands/DecryptDatabase.php +++ b/app/Console/Commands/DecryptDatabase.php @@ -54,8 +54,8 @@ class DecryptDatabase extends Command /** * Execute the console command. * - * @return int * @throws FireflyException + * @return int */ public function handle(): int { @@ -92,11 +92,11 @@ class DecryptDatabase extends Command // A separate routine for preferences: if ('preferences' === $table) { // try to json_decrypt the value. - $value = json_decode($value, true) ?? $value; + $value = json_decode($value, true, 512, JSON_THROW_ON_ERROR) ?? $value; Log::debug(sprintf('Decrypted field "%s" "%s" to "%s" in table "%s" (row #%d)', $field, $original, print_r($value, true), $table, $id)); /** @var Preference $object */ - $object = Preference::find((int)$id); + $object = Preference::find((int) $id); if (null !== $object) { $object->data = $value; $object->save(); @@ -131,7 +131,7 @@ class DecryptDatabase extends Command $configName = sprintf('is_decrypted_%s', $table); $configVar = app('fireflyconfig')->get($configName, false); if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; @@ -142,8 +142,9 @@ class DecryptDatabase extends Command * Tries to decrypt data. Will only throw an exception when the MAC is invalid. * * @param $value - * @return string + * * @throws FireflyException + * @return string */ private function tryDecrypt($value) { diff --git a/app/Console/Commands/Export/ExportData.php b/app/Console/Commands/Export/ExportData.php index b2df8e08b4..6b38974478 100644 --- a/app/Console/Commands/Export/ExportData.php +++ b/app/Console/Commands/Export/ExportData.php @@ -22,6 +22,7 @@ namespace FireflyIII\Console\Commands\Export; use Carbon\Carbon; +use Exception; use FireflyIII\Console\Commands\VerifiesAccessToken; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\AccountType; @@ -32,6 +33,7 @@ use FireflyIII\User; use Illuminate\Console\Command; use Illuminate\Support\Collection; use InvalidArgumentException; +use League\Csv\CannotInsertRecord; use Log; /** @@ -76,21 +78,12 @@ class ExportData extends Command /** @var User */ private $user; - /** - * Create a new command instance. - * - * @return void - */ - public function __construct() - { - parent::__construct(); - } - /** * Execute the console command. * - * @return int * @throws FireflyException + * @throws CannotInsertRecord + * @return int */ public function handle(): int { @@ -171,8 +164,8 @@ class ExportData extends Command } /** - * @return Collection * @throws FireflyException + * @return Collection */ private function getAccountsParameter(): Collection { @@ -180,7 +173,7 @@ class ExportData extends Command $accounts = new Collection; $accountList = $this->option('accounts'); $types = [AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]; - if (null !== $accountList && '' !== (string)$accountList) { + if (null !== $accountList && '' !== (string) $accountList) { $accountIds = explode(',', $accountList); $accounts = $this->accountRepository->getAccountsById($accountIds); } @@ -204,8 +197,9 @@ class ExportData extends Command /** * @param string $field * - * @return Carbon * @throws FireflyException + * @throws Exception + * @return Carbon */ private function getDateParameter(string $field): Carbon { @@ -239,8 +233,8 @@ class ExportData extends Command } /** - * @return string * @throws FireflyException + * @return string */ private function getExportDirectory(): string { @@ -256,8 +250,8 @@ class ExportData extends Command } /** - * @return array * @throws FireflyException + * @return array */ private function parseOptions(): array { diff --git a/app/Console/Commands/Import/CreateCSVImport.php b/app/Console/Commands/Import/CreateCSVImport.php index 5583a71c77..c6390e440d 100644 --- a/app/Console/Commands/Import/CreateCSVImport.php +++ b/app/Console/Commands/Import/CreateCSVImport.php @@ -39,6 +39,9 @@ use Log; /** * Class CreateCSVImport. + * + * @deprecated + * @codeCoverageIgnore */ class CreateCSVImport extends Command { @@ -60,12 +63,12 @@ class CreateCSVImport extends Command {configuration? : The configuration file to use for the import.} {--user=1 : The user ID that the import should import for.} {--token= : The user\'s access token.}'; - /** @var UserRepositoryInterface */ - private $userRepository; - /** @var ImportJobRepositoryInterface */ - private $importRepository; /** @var ImportJob */ private $importJob; + /** @var ImportJobRepositoryInterface */ + private $importRepository; + /** @var UserRepositoryInterface */ + private $userRepository; /** * Run the command. @@ -87,13 +90,13 @@ class CreateCSVImport extends Command } // @codeCoverageIgnoreEnd /** @var User $user */ - $user = $this->userRepository->findNull((int)$this->option('user')); - $file = (string)$this->argument('file'); - $configuration = (string)$this->argument('configuration'); + $user = $this->userRepository->findNull((int) $this->option('user')); + $file = (string) $this->argument('file'); + $configuration = (string) $this->argument('configuration'); $this->importRepository->setUser($user); - $configurationData = json_decode(file_get_contents($configuration), true); + $configurationData = json_decode(file_get_contents($configuration), true, 512, JSON_THROW_ON_ERROR); $this->importJob = $this->importRepository->create('file'); @@ -147,21 +150,9 @@ class CreateCSVImport extends Command } /** - * Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is - * executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should - * be called from the handle method instead of using the constructor to initialize the command. - * - * @codeCoverageIgnore - */ - private function stupidLaravel(): void - { - $this->userRepository = app(UserRepositoryInterface::class); - $this->importRepository = app(ImportJobRepositoryInterface::class); - } - - /** - * @param string $message + * @param string $message * @param array|null $data + * * @codeCoverageIgnore */ private function errorLine(string $message, array $data = null): void @@ -171,9 +162,34 @@ class CreateCSVImport extends Command } + /** + * + */ + private function giveFeedback(): void + { + $this->infoLine('Job has finished.'); + + + if (null !== $this->importJob->tag) { + $this->infoLine(sprintf('%d transaction(s) have been imported.', $this->importJob->tag->transactionJournals->count())); + $this->infoLine(sprintf('You can find your transactions under tag "%s"', $this->importJob->tag->tag)); + } + + if (null === $this->importJob->tag) { + $this->errorLine('No transactions have been imported :(.'); + } + if (count($this->importJob->errors) > 0) { + $this->infoLine(sprintf('%d error(s) occurred:', count($this->importJob->errors))); + foreach ($this->importJob->errors as $err) { + $this->errorLine('- ' . $err); + } + } + } + /** * @param string $message - * @param array $data + * @param array $data + * * @codeCoverageIgnore */ private function infoLine(string $message, array $data = null): void @@ -182,65 +198,6 @@ class CreateCSVImport extends Command $this->line($message); } - /** - * Verify user inserts correct arguments. - * - * @noinspection MultipleReturnStatementsInspection - * @return bool - * @codeCoverageIgnore - */ - private function validArguments(): bool - { - $file = (string)$this->argument('file'); - $configuration = (string)$this->argument('configuration'); - $cwd = getcwd(); - $enabled = (bool)config('import.enabled.file'); - - if (false === $enabled) { - $this->errorLine('CSV Provider is not enabled.'); - - return false; - } - - if (!file_exists($file)) { - $this->errorLine(sprintf('Firefly III cannot find file "%s" (working directory: "%s").', $file, $cwd)); - - return false; - } - - if (!file_exists($configuration)) { - $this->errorLine(sprintf('Firefly III cannot find configuration file "%s" (working directory: "%s").', $configuration, $cwd)); - - return false; - } - - $configurationData = json_decode(file_get_contents($configuration), true); - if (null === $configurationData) { - $this->errorLine(sprintf('Firefly III cannot read the contents of configuration file "%s" (working directory: "%s").', $configuration, $cwd)); - - return false; - } - - return true; - } - - /** - * Store the supplied file as an attachment to this job. - * - * @param string $file - * @throws FireflyException - */ - private function storeFile(string $file): void - { - // store file as attachment. - if ('' !== $file) { - $messages = $this->importRepository->storeCLIUpload($this->importJob, 'import_file', $file); - if ($messages->count() > 0) { - throw new FireflyException($messages->first()); - } - } - } - /** * Keep repeating import call until job lands on "provider_finished". * @@ -307,26 +264,75 @@ class CreateCSVImport extends Command } /** + * Store the supplied file as an attachment to this job. * + * @param string $file + * + * @throws FireflyException */ - private function giveFeedback(): void + private function storeFile(string $file): void { - $this->infoLine('Job has finished.'); - - - if (null !== $this->importJob->tag) { - $this->infoLine(sprintf('%d transaction(s) have been imported.', $this->importJob->tag->transactionJournals->count())); - $this->infoLine(sprintf('You can find your transactions under tag "%s"', $this->importJob->tag->tag)); - } - - if (null === $this->importJob->tag) { - $this->errorLine('No transactions have been imported :(.'); - } - if (count($this->importJob->errors) > 0) { - $this->infoLine(sprintf('%d error(s) occurred:', count($this->importJob->errors))); - foreach ($this->importJob->errors as $err) { - $this->errorLine('- ' . $err); + // store file as attachment. + if ('' !== $file) { + $messages = $this->importRepository->storeCLIUpload($this->importJob, 'import_file', $file); + if ($messages->count() > 0) { + throw new FireflyException($messages->first()); } } } + + /** + * Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is + * executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should + * be called from the handle method instead of using the constructor to initialize the command. + * + * @codeCoverageIgnore + */ + private function stupidLaravel(): void + { + $this->userRepository = app(UserRepositoryInterface::class); + $this->importRepository = app(ImportJobRepositoryInterface::class); + } + + /** + * Verify user inserts correct arguments. + * + * @noinspection MultipleReturnStatementsInspection + * @return bool + * @codeCoverageIgnore + */ + private function validArguments(): bool + { + $file = (string) $this->argument('file'); + $configuration = (string) $this->argument('configuration'); + $cwd = getcwd(); + $enabled = (bool) config('import.enabled.file'); + + if (false === $enabled) { + $this->errorLine('CSV Provider is not enabled.'); + + return false; + } + + if (!file_exists($file)) { + $this->errorLine(sprintf('Firefly III cannot find file "%s" (working directory: "%s").', $file, $cwd)); + + return false; + } + + if (!file_exists($configuration)) { + $this->errorLine(sprintf('Firefly III cannot find configuration file "%s" (working directory: "%s").', $configuration, $cwd)); + + return false; + } + + $configurationData = json_decode(file_get_contents($configuration), true, 512, JSON_THROW_ON_ERROR); + if (null === $configurationData) { + $this->errorLine(sprintf('Firefly III cannot read the contents of configuration file "%s" (working directory: "%s").', $configuration, $cwd)); + + return false; + } + + return true; + } } diff --git a/app/Console/Commands/Integrity/ReportIntegrity.php b/app/Console/Commands/Integrity/ReportIntegrity.php index a30e0c5e1f..62e45ed110 100644 --- a/app/Console/Commands/Integrity/ReportIntegrity.php +++ b/app/Console/Commands/Integrity/ReportIntegrity.php @@ -30,6 +30,7 @@ use Schema; /** * Class ReportIntegrity + * * @codeCoverageIgnore */ class ReportIntegrity extends Command diff --git a/app/Console/Commands/Integrity/ReportSum.php b/app/Console/Commands/Integrity/ReportSum.php index 45934f0fb8..2f24e1f00a 100644 --- a/app/Console/Commands/Integrity/ReportSum.php +++ b/app/Console/Commands/Integrity/ReportSum.php @@ -69,7 +69,7 @@ class ReportSum extends Command /** @var User $user */ foreach ($userRepository->all() as $user) { - $sum = (string)$user->transactions()->sum('amount'); + $sum = (string) $user->transactions()->sum('amount'); if (0 !== bccomp($sum, '0')) { $message = sprintf('Error: Transactions for user #%d (%s) are off by %s!', $user->id, $user->email, $sum); $this->error($message); diff --git a/app/Console/Commands/Integrity/RestoreOAuthKeys.php b/app/Console/Commands/Integrity/RestoreOAuthKeys.php index 67950d8798..ec5f0d9d67 100644 --- a/app/Console/Commands/Integrity/RestoreOAuthKeys.php +++ b/app/Console/Commands/Integrity/RestoreOAuthKeys.php @@ -21,8 +21,6 @@ namespace FireflyIII\Console\Commands\Integrity; -use Artisan; -use Crypt; use FireflyIII\Support\System\OAuthKeys; use Illuminate\Console\Command; @@ -122,4 +120,4 @@ class RestoreOAuthKeys extends Command { OAuthKeys::storeKeysInDB(); } -} \ No newline at end of file +} diff --git a/app/Console/Commands/ScanAttachments.php b/app/Console/Commands/ScanAttachments.php index 4546c8c646..8ba285ff00 100644 --- a/app/Console/Commands/ScanAttachments.php +++ b/app/Console/Commands/ScanAttachments.php @@ -63,8 +63,7 @@ class ScanAttachments extends Command $disk = Storage::disk('upload'); /** @var Attachment $attachment */ foreach ($attachments as $attachment) { - $fileName = $attachment->fileName(); - $decryptedContent = ''; + $fileName = $attachment->fileName(); try { $encryptedContent = $disk->get($fileName); } catch (FileNotFoundException $e) { diff --git a/app/Console/Commands/SetLatestVersion.php b/app/Console/Commands/SetLatestVersion.php index 4eb0ce6285..f18441793a 100644 --- a/app/Console/Commands/SetLatestVersion.php +++ b/app/Console/Commands/SetLatestVersion.php @@ -43,16 +43,6 @@ class SetLatestVersion extends Command */ protected $signature = 'firefly-iii:set-latest-version {--james-is-cool}'; - /** - * Create a new command instance. - * - * @return void - */ - public function __construct() - { - parent::__construct(); - } - /** * Execute the console command. * diff --git a/app/Console/Commands/Tools/ApplyRules.php b/app/Console/Commands/Tools/ApplyRules.php index e61398da3a..419b1ec3d2 100644 --- a/app/Console/Commands/Tools/ApplyRules.php +++ b/app/Console/Commands/Tools/ApplyRules.php @@ -68,35 +68,32 @@ 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}'; - - /** @var Collection */ - private $accounts; /** @var array */ private $acceptedAccounts; + /** @var Collection */ + private $accounts; + /** @var bool */ + private $allRules; /** @var Carbon */ private $endDate; + /** @var Collection */ + private $groups; + /** @var RuleGroupRepositoryInterface */ + private $ruleGroupRepository; /** @var array */ private $ruleGroupSelection; + /** @var RuleRepositoryInterface */ + private $ruleRepository; /** @var array */ private $ruleSelection; /** @var Carbon */ private $startDate; - /** @var Collection */ - private $groups; - /** @var bool */ - private $allRules; - - /** @var RuleRepositoryInterface */ - private $ruleRepository; - - /** @var RuleGroupRepositoryInterface */ - private $ruleGroupRepository; /** * Execute the console command. * - * @return int * @throws FireflyException + * @return int */ public function handle(): int { @@ -169,6 +166,49 @@ class ApplyRules extends Command return 0; } + /** + * @return array + */ + private function getRulesToApply(): array + { + $rulesToApply = []; + /** @var RuleGroup $group */ + foreach ($this->groups as $group) { + $rules = $this->ruleGroupRepository->getActiveStoreRules($group); + /** @var Rule $rule */ + foreach ($rules as $rule) { + // if in rule selection, or group in selection or all rules, it's included. + $test = $this->includeRule($rule, $group); + if (true === $test) { + Log::debug(sprintf('Will include rule #%d "%s"', $rule->id, $rule->title)); + $rulesToApply[] = $rule->id; + } + } + } + + return $rulesToApply; + } + + /** + */ + private function grabAllRules(): void + { + $this->groups = $this->ruleGroupRepository->getActiveGroups(); + } + + /** + * @param Rule $rule + * @param RuleGroup $group + * + * @return bool + */ + private function includeRule(Rule $rule, RuleGroup $group): bool + { + return in_array($group->id, $this->ruleGroupSelection, true) + || in_array($rule->id, $this->ruleSelection, true) + || $this->allRules; + } + /** * Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is * executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should @@ -189,8 +229,8 @@ class ApplyRules extends Command } /** - * @return bool * @throws FireflyException + * @return bool */ private function verifyInput(): bool { @@ -212,8 +252,8 @@ class ApplyRules extends Command } /** - * @return bool * @throws FireflyException + * @return bool */ private function verifyInputAccounts(): bool { @@ -240,7 +280,7 @@ class ApplyRules extends Command foreach ($accountList as $accountId) { - $accountId = (int)$accountId; + $accountId = (int) $accountId; $account = $accountRepository->findNull($accountId); if (null !== $account && in_array($account->accountType->type, $this->acceptedAccounts, true)) { $finalList->push($account); @@ -258,66 +298,6 @@ class ApplyRules extends Command } - /** - * @return bool - */ - private function verifyInputRuleGroups(): bool - { - $ruleGroupString = $this->option('rule_groups'); - if (null === $ruleGroupString || '' === $ruleGroupString) { - // can be empty. - return true; - } - $ruleGroupList = explode(',', $ruleGroupString); - // @codeCoverageIgnoreStart - if (0 === count($ruleGroupList)) { - // can be empty. - return true; - } - // @codeCoverageIgnoreEnd - foreach ($ruleGroupList as $ruleGroupId) { - $ruleGroup = $this->ruleGroupRepository->find((int)$ruleGroupId); - if ($ruleGroup->active) { - $this->ruleGroupSelection[] = $ruleGroup->id; - } - if (false === $ruleGroup->active) { - $this->warn(sprintf('Will ignore inactive rule group #%d ("%s")', $ruleGroup->id, $ruleGroup->title)); - } - } - - return true; - } - - /** - * @return bool - */ - private function verifyInputRules(): bool - { - $ruleString = $this->option('rules'); - if (null === $ruleString || '' === $ruleString) { - // can be empty. - return true; - } - $ruleList = explode(',', $ruleString); - - // @codeCoverageIgnoreStart - if (0 === count($ruleList)) { - // can be empty. - - return true; - } - // @codeCoverageIgnoreEnd - - foreach ($ruleList as $ruleId) { - $rule = $this->ruleRepository->find((int)$ruleId); - if (null !== $rule && $rule->active) { - $this->ruleSelection[] = $rule->id; - } - } - - return true; - } - /** * @throws FireflyException */ @@ -355,44 +335,62 @@ class ApplyRules extends Command } /** - */ - private function grabAllRules(): void - { - $this->groups = $this->ruleGroupRepository->getActiveGroups(); - } - - /** - * @param Rule $rule - * @param RuleGroup $group * @return bool */ - private function includeRule(Rule $rule, RuleGroup $group): bool + private function verifyInputRuleGroups(): bool { - return in_array($group->id, $this->ruleGroupSelection, true) || - in_array($rule->id, $this->ruleSelection, true) || - $this->allRules; - } - - /** - * @return array - */ - private function getRulesToApply(): array - { - $rulesToApply = []; - /** @var RuleGroup $group */ - foreach ($this->groups as $group) { - $rules = $this->ruleGroupRepository->getActiveStoreRules($group); - /** @var Rule $rule */ - foreach ($rules as $rule) { - // if in rule selection, or group in selection or all rules, it's included. - $test = $this->includeRule($rule, $group); - if (true === $test) { - Log::debug(sprintf('Will include rule #%d "%s"', $rule->id, $rule->title)); - $rulesToApply[] = $rule->id; - } + $ruleGroupString = $this->option('rule_groups'); + if (null === $ruleGroupString || '' === $ruleGroupString) { + // can be empty. + return true; + } + $ruleGroupList = explode(',', $ruleGroupString); + // @codeCoverageIgnoreStart + if (0 === count($ruleGroupList)) { + // can be empty. + return true; + } + // @codeCoverageIgnoreEnd + foreach ($ruleGroupList as $ruleGroupId) { + $ruleGroup = $this->ruleGroupRepository->find((int) $ruleGroupId); + if ($ruleGroup->active) { + $this->ruleGroupSelection[] = $ruleGroup->id; + } + if (false === $ruleGroup->active) { + $this->warn(sprintf('Will ignore inactive rule group #%d ("%s")', $ruleGroup->id, $ruleGroup->title)); } } - return $rulesToApply; + return true; + } + + /** + * @return bool + */ + private function verifyInputRules(): bool + { + $ruleString = $this->option('rules'); + if (null === $ruleString || '' === $ruleString) { + // can be empty. + return true; + } + $ruleList = explode(',', $ruleString); + + // @codeCoverageIgnoreStart + if (0 === count($ruleList)) { + // can be empty. + + return true; + } + // @codeCoverageIgnoreEnd + + foreach ($ruleList as $ruleId) { + $rule = $this->ruleRepository->find((int) $ruleId); + if (null !== $rule && $rule->active) { + $this->ruleSelection[] = $rule->id; + } + } + + return true; } } diff --git a/app/Console/Commands/Tools/Cron.php b/app/Console/Commands/Tools/Cron.php index 0c1fb62af0..31fc056f76 100644 --- a/app/Console/Commands/Tools/Cron.php +++ b/app/Console/Commands/Tools/Cron.php @@ -27,9 +27,11 @@ namespace FireflyIII\Console\Commands\Tools; use Carbon\Carbon; use Exception; use FireflyIII\Exceptions\FireflyException; +use FireflyIII\Support\Cronjobs\AutoBudgetCronjob; use FireflyIII\Support\Cronjobs\RecurringCronjob; use Illuminate\Console\Command; use InvalidArgumentException; +use Log; /** * Class Cron @@ -56,39 +58,38 @@ class Cron extends Command /** * @return int - * @throws Exception */ public function handle(): int { $date = null; try { $date = new Carbon($this->option('date')); - } catch (InvalidArgumentException $e) { + } catch (InvalidArgumentException|Exception $e) { $this->error(sprintf('"%s" is not a valid date', $this->option('date'))); $e->getMessage(); } + $force = (bool) $this->option('force'); - - $recurring = new RecurringCronjob; - $recurring->setForce($this->option('force')); - - // set date in cron job: - if (null !== $date) { - $recurring->setDate($date); - } - + /* + * Fire recurring transaction cron job. + */ try { - $result = $recurring->fire(); + $this->recurringCronJob($force, $date); } catch (FireflyException $e) { + Log::error($e->getMessage()); + Log::error($e->getTraceAsString()); $this->error($e->getMessage()); + } - return 0; - } - if (false === $result) { - $this->line('The recurring transaction cron job did not fire.'); - } - if (true === $result) { - $this->line('The recurring transaction cron job fired successfully.'); + /* + * Fire auto-budget cron job: + */ + try { + $this->autoBudgetCronJob($force, $date); + } catch (FireflyException $e) { + Log::error($e->getMessage()); + Log::error($e->getTraceAsString()); + $this->error($e->getMessage()); } $this->info('More feedback on the cron jobs can be found in the log files.'); @@ -96,5 +97,56 @@ class Cron extends Command return 0; } + /** + * @param bool $force + * @param Carbon|null $date + * + * @throws FireflyException + * @throws Exception + */ + private function autoBudgetCronJob(bool $force, ?Carbon $date): void + { + $autoBudget = new AutoBudgetCronjob; + $autoBudget->setForce($force); + // set date in cron job: + if (null !== $date) { + $autoBudget->setDate($date); + } + $result = $autoBudget->fire(); + + if (false === $result) { + $this->line('The auto budget cron job did not fire.'); + } + if (true === $result) { + $this->line('The auto budget cron job fired successfully.'); + } + + } + + /** + * @param bool $force + * @param Carbon|null $date + * + * @throws FireflyException + */ + private function recurringCronJob(bool $force, ?Carbon $date): void + { + $recurring = new RecurringCronjob; + $recurring->setForce($force); + + // set date in cron job: + if (null !== $date) { + $recurring->setDate($date); + } + + $result = $recurring->fire(); + + if (false === $result) { + $this->line('The recurring transaction cron job did not fire.'); + } + if (true === $result) { + $this->line('The recurring transaction cron job fired successfully.'); + } + } } diff --git a/app/Console/Commands/Upgrade/AccountCurrencies.php b/app/Console/Commands/Upgrade/AccountCurrencies.php index 4ac42aaaa6..113e1d829a 100644 --- a/app/Console/Commands/Upgrade/AccountCurrencies.php +++ b/app/Console/Commands/Upgrade/AccountCurrencies.php @@ -54,10 +54,10 @@ class AccountCurrencies extends Command protected $signature = 'firefly-iii:account-currencies {--F|force : Force the execution of this command.}'; /** @var AccountRepositoryInterface */ private $accountRepos; - /** @var UserRepositoryInterface */ - private $userRepos; /** @var int */ private $count; + /** @var UserRepositoryInterface */ + private $userRepos; /** * Each (asset) account must have a reference to a preferred currency. If the account does not have one, it's forced upon the account. @@ -90,6 +90,27 @@ class AccountCurrencies extends Command return 0; } + /** + * @return bool + */ + private function isExecuted(): bool + { + $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); + if (null !== $configVar) { + return (bool) $configVar->data; + } + + return false; // @codeCoverageIgnore + } + + /** + * + */ + private function markAsExecuted(): void + { + app('fireflyconfig')->set(self::CONFIG_NAME, true); + } + /** * Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is * executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should @@ -105,29 +126,7 @@ class AccountCurrencies extends Command } /** - * @return bool - */ - private function isExecuted(): bool - { - $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); - if (null !== $configVar) { - return (bool)$configVar->data; - } - - return false; // @codeCoverageIgnore - } - - - /** - * - */ - private function markAsExecuted(): void - { - app('fireflyconfig')->set(self::CONFIG_NAME, true); - } - - /** - * @param Account $account + * @param Account $account * @param TransactionCurrency $currency */ private function updateAccount(Account $account, TransactionCurrency $currency): void @@ -135,13 +134,13 @@ class AccountCurrencies extends Command Log::debug(sprintf('Now in updateAccount(%d, %s)', $account->id, $currency->code)); $this->accountRepos->setUser($account->user); - $accountCurrency = (int)$this->accountRepos->getMetaValue($account, 'currency_id'); + $accountCurrency = (int) $this->accountRepos->getMetaValue($account, 'currency_id'); Log::debug(sprintf('Account currency is #%d', $accountCurrency)); - $openingBalance = $this->accountRepos->getOpeningBalance($account); - $obCurrency = 0; + $openingBalance = $this->accountRepos->getOpeningBalance($account); + $obCurrency = 0; if (null !== $openingBalance) { - $obCurrency = (int)$openingBalance->transaction_currency_id; + $obCurrency = (int) $openingBalance->transaction_currency_id; Log::debug('Account has opening balance.'); } Log::debug(sprintf('Account OB currency is #%d.', $obCurrency)); @@ -178,7 +177,8 @@ class AccountCurrencies extends Command static function (Transaction $transaction) use ($accountCurrency) { $transaction->transaction_currency_id = $accountCurrency; $transaction->save(); - }); + } + ); $this->line(sprintf('Account #%d ("%s") now has a correct currency for opening balance.', $account->id, $account->name)); $this->count++; @@ -194,7 +194,7 @@ class AccountCurrencies extends Command { Log::debug('Now in updateAccountCurrencies()'); $users = $this->userRepos->all(); - $defaultCurrencyCode = (string)config('firefly.default_currency', 'EUR'); + $defaultCurrencyCode = (string) config('firefly.default_currency', 'EUR'); Log::debug(sprintf('Default currency is %s', $defaultCurrencyCode)); foreach ($users as $user) { $this->updateCurrenciesForUser($user, $defaultCurrencyCode); @@ -202,7 +202,7 @@ class AccountCurrencies extends Command } /** - * @param User $user + * @param User $user * @param string $systemCurrencyCode */ private function updateCurrenciesForUser(User $user, string $systemCurrencyCode): void diff --git a/app/Console/Commands/Upgrade/BackToJournals.php b/app/Console/Commands/Upgrade/BackToJournals.php index 198e7d4968..bc6a2aead2 100644 --- a/app/Console/Commands/Upgrade/BackToJournals.php +++ b/app/Console/Commands/Upgrade/BackToJournals.php @@ -111,9 +111,9 @@ class BackToJournals extends Command $chunks = array_chunk($transactions, 500); foreach ($chunks as $chunk) { - $set = DB::table('transactions') - ->whereIn('transactions.id', $chunk) - ->get(['transaction_journal_id'])->pluck('transaction_journal_id')->toArray(); + $set = DB::table('transactions') + ->whereIn('transactions.id', $chunk) + ->get(['transaction_journal_id'])->pluck('transaction_journal_id')->toArray(); /** @noinspection SlowArrayOperationsInLoopInspection */ $array = array_merge($array, $set); } @@ -128,7 +128,7 @@ class BackToJournals extends Command { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; // @codeCoverageIgnore @@ -141,7 +141,7 @@ class BackToJournals extends Command { $configVar = app('fireflyconfig')->get(MigrateToGroups::CONFIG_NAME, false); if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; // @codeCoverageIgnore @@ -212,7 +212,7 @@ class BackToJournals extends Command // both have a budget, but they don't match. if (null !== $budget && null !== $journalBudget && $budget->id !== $journalBudget->id) { // sync to journal: - $journal->budgets()->sync([(int)$budget->id]); + $journal->budgets()->sync([(int) $budget->id]); return; } @@ -220,7 +220,7 @@ class BackToJournals extends Command // transaction has a budget, but the journal doesn't. if (null !== $budget && null === $journalBudget) { // sync to journal: - $journal->budgets()->sync([(int)$budget->id]); + $journal->budgets()->sync([(int) $budget->id]); } } @@ -271,12 +271,12 @@ class BackToJournals extends Command // both have a category, but they don't match. if (null !== $category && null !== $journalCategory && $category->id !== $journalCategory->id) { // sync to journal: - $journal->categories()->sync([(int)$category->id]); + $journal->categories()->sync([(int) $category->id]); } // transaction has a category, but the journal doesn't. if (null !== $category && null === $journalCategory) { - $journal->categories()->sync([(int)$category->id]); + $journal->categories()->sync([(int) $category->id]); } } } diff --git a/app/Console/Commands/Upgrade/BudgetLimitCurrency.php b/app/Console/Commands/Upgrade/BudgetLimitCurrency.php index e25f36356c..990b02bbf8 100644 --- a/app/Console/Commands/Upgrade/BudgetLimitCurrency.php +++ b/app/Console/Commands/Upgrade/BudgetLimitCurrency.php @@ -102,7 +102,7 @@ class BudgetLimitCurrency extends Command { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; // @codeCoverageIgnore diff --git a/app/Console/Commands/Upgrade/CCLiabilities.php b/app/Console/Commands/Upgrade/CCLiabilities.php index 489bf934fa..e5904a7198 100644 --- a/app/Console/Commands/Upgrade/CCLiabilities.php +++ b/app/Console/Commands/Upgrade/CCLiabilities.php @@ -101,7 +101,7 @@ class CCLiabilities extends Command { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; // @codeCoverageIgnore diff --git a/app/Console/Commands/Upgrade/MigrateAttachments.php b/app/Console/Commands/Upgrade/MigrateAttachments.php index eab27f6941..9e2270d7d2 100644 --- a/app/Console/Commands/Upgrade/MigrateAttachments.php +++ b/app/Console/Commands/Upgrade/MigrateAttachments.php @@ -71,7 +71,7 @@ class MigrateAttachments extends Command foreach ($attachments as $att) { // move description: - $description = (string)$att->description; + $description = (string) $att->description; if ('' !== $description) { // find or create note: @@ -111,7 +111,7 @@ class MigrateAttachments extends Command { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; // @codeCoverageIgnore diff --git a/app/Console/Commands/Upgrade/MigrateJournalNotes.php b/app/Console/Commands/Upgrade/MigrateJournalNotes.php index 46f3128fcc..a234c2948f 100644 --- a/app/Console/Commands/Upgrade/MigrateJournalNotes.php +++ b/app/Console/Commands/Upgrade/MigrateJournalNotes.php @@ -110,7 +110,7 @@ class MigrateJournalNotes extends Command { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; // @codeCoverageIgnore diff --git a/app/Console/Commands/Upgrade/MigrateRecurrenceMeta.php b/app/Console/Commands/Upgrade/MigrateRecurrenceMeta.php index 317a9dd157..8ec5d2b47e 100644 --- a/app/Console/Commands/Upgrade/MigrateRecurrenceMeta.php +++ b/app/Console/Commands/Upgrade/MigrateRecurrenceMeta.php @@ -81,7 +81,7 @@ class MigrateRecurrenceMeta extends Command { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; // @codeCoverageIgnore @@ -103,7 +103,7 @@ class MigrateRecurrenceMeta extends Command */ private function migrateEntry(RecurrenceMeta $meta): int { - $recurrence = $meta->recurrence; + $recurrence = $meta->recurrence; if (null === $recurrence) { return 0; } @@ -115,7 +115,7 @@ class MigrateRecurrenceMeta extends Command if ('tags' === $meta->name) { $array = explode(',', $meta->value); - $value = json_encode($array); + $value = json_encode($array, JSON_THROW_ON_ERROR, 512); } RecurrenceTransactionMeta::create( diff --git a/app/Console/Commands/Upgrade/MigrateTagLocations.php b/app/Console/Commands/Upgrade/MigrateTagLocations.php index eec8699002..9989e10b4e 100644 --- a/app/Console/Commands/Upgrade/MigrateTagLocations.php +++ b/app/Console/Commands/Upgrade/MigrateTagLocations.php @@ -84,7 +84,7 @@ class MigrateTagLocations extends Command { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; // @codeCoverageIgnore diff --git a/app/Console/Commands/Upgrade/MigrateToGroups.php b/app/Console/Commands/Upgrade/MigrateToGroups.php index 4645a4e404..f953b784ed 100644 --- a/app/Console/Commands/Upgrade/MigrateToGroups.php +++ b/app/Console/Commands/Upgrade/MigrateToGroups.php @@ -59,21 +59,21 @@ class MigrateToGroups extends Command * @var string */ protected $signature = 'firefly-iii:migrate-to-groups {--F|force : Force the migration, even if it fired before.}'; + /** @var JournalCLIRepositoryInterface */ + private $cliRepository; + private $count; /** @var TransactionGroupFactory */ private $groupFactory; /** @var JournalRepositoryInterface */ private $journalRepository; - /** @var JournalCLIRepositoryInterface */ - private $cliRepository; /** @var JournalDestroyService */ private $service; - private $count; /** * Execute the console command. * - * @return int * @throws Exception + * @return int */ public function handle(): int { @@ -116,25 +116,9 @@ class MigrateToGroups extends Command return 0; } - /** - * Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is - * executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should - * be called from the handle method instead of using the constructor to initialize the command. - * - * @codeCoverageIgnore - */ - private function stupidLaravel(): void - { - $this->count = 0; - $this->journalRepository = app(JournalRepositoryInterface::class); - $this->service = app(JournalDestroyService::class); - $this->groupFactory = app(TransactionGroupFactory::class); - $this->cliRepository = app(JournalCLIRepositoryInterface::class); - } - /** * @param TransactionJournal $journal - * @param Transaction $transaction + * @param Transaction $transaction * * @return Transaction|null */ @@ -142,7 +126,7 @@ class MigrateToGroups extends Command { $set = $journal->transactions->filter( static function (Transaction $subject) use ($transaction) { - $amount = (float)$transaction->amount * -1 === (float)$subject->amount; + $amount = (float) $transaction->amount * -1 === (float) $subject->amount; $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))); @@ -168,6 +152,72 @@ class MigrateToGroups extends Command ); } + /** + * @param Transaction $left + * @param Transaction $right + * + * @return int|null + */ + private function getTransactionBudget(Transaction $left, Transaction $right): ?int + { + Log::debug('Now in getTransactionBudget()'); + + // try to get a budget ID from the left transaction: + /** @var Budget $budget */ + $budget = $left->budgets()->first(); + if (null !== $budget) { + Log::debug(sprintf('Return budget #%d, from transaction #%d', $budget->id, $left->id)); + + return (int) $budget->id; + } + + // try to get a budget ID from the right transaction: + /** @var Budget $budget */ + $budget = $right->budgets()->first(); + if (null !== $budget) { + Log::debug(sprintf('Return budget #%d, from transaction #%d', $budget->id, $right->id)); + + return (int) $budget->id; + } + Log::debug('Neither left or right have a budget, return NULL'); + + // if all fails, return NULL. + return null; + } + + /** + * @param Transaction $left + * @param Transaction $right + * + * @return int|null + */ + private function getTransactionCategory(Transaction $left, Transaction $right): ?int + { + Log::debug('Now in getTransactionCategory()'); + + // try to get a category ID from the left transaction: + /** @var Category $category */ + $category = $left->categories()->first(); + if (null !== $category) { + Log::debug(sprintf('Return category #%d, from transaction #%d', $category->id, $left->id)); + + return (int) $category->id; + } + + // try to get a category ID from the left transaction: + /** @var Category $category */ + $category = $right->categories()->first(); + if (null !== $category) { + Log::debug(sprintf('Return category #%d, from transaction #%d', $category->id, $category->id)); + + return (int) $category->id; + } + Log::debug('Neither left or right have a category, return NULL'); + + // if all fails, return NULL. + return null; + } + /** * @param array $array */ @@ -192,7 +242,7 @@ class MigrateToGroups extends Command { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; // @codeCoverageIgnore @@ -302,7 +352,8 @@ class MigrateToGroups extends Command $this->error( sprintf( 'Journal #%d has no opposing transaction for transaction #%d. Cannot upgrade this entry.', - $journal->id, $transaction->id + $journal->id, + $transaction->id ) ); continue; @@ -365,81 +416,23 @@ class MigrateToGroups extends Command // 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())) + sprintf( + 'Migrated journal #%d into group #%d with these journals: #%s', + $journal->id, + $group->id, + implode(', #', $group->transactionJournals->pluck('id')->toArray()) + ) ); $this->line( - sprintf('Migrated journal #%d into group #%d with these journals: #%s', - $journal->id, $group->id, implode(', #', $group->transactionJournals->pluck('id')->toArray())) + sprintf( + 'Migrated journal #%d into group #%d with these journals: #%s', + $journal->id, + $group->id, + implode(', #', $group->transactionJournals->pluck('id')->toArray()) + ) ); } - /** - * @param Transaction $left - * @param Transaction $right - * - * @return int|null - */ - private function getTransactionBudget(Transaction $left, Transaction $right): ?int - { - Log::debug('Now in getTransactionBudget()'); - - // try to get a budget ID from the left transaction: - /** @var Budget $budget */ - $budget = $left->budgets()->first(); - if (null !== $budget) { - Log::debug(sprintf('Return budget #%d, from transaction #%d', $budget->id, $left->id)); - - return (int)$budget->id; - } - - // try to get a budget ID from the right transaction: - /** @var Budget $budget */ - $budget = $right->budgets()->first(); - if (null !== $budget) { - Log::debug(sprintf('Return budget #%d, from transaction #%d', $budget->id, $right->id)); - - return (int)$budget->id; - } - Log::debug('Neither left or right have a budget, return NULL'); - - // if all fails, return NULL. - return null; - } - - /** - * @param Transaction $left - * @param Transaction $right - * - * @return int|null - */ - private function getTransactionCategory(Transaction $left, Transaction $right): ?int - { - Log::debug('Now in getTransactionCategory()'); - - // try to get a category ID from the left transaction: - /** @var Category $category */ - $category = $left->categories()->first(); - if (null !== $category) { - Log::debug(sprintf('Return category #%d, from transaction #%d', $category->id, $left->id)); - - return (int)$category->id; - } - - // try to get a category ID from the left transaction: - /** @var Category $category */ - $category = $right->categories()->first(); - if (null !== $category) { - Log::debug(sprintf('Return category #%d, from transaction #%d', $category->id, $category->id)); - - return (int)$category->id; - } - Log::debug('Neither left or right have a category, return NULL'); - - // if all fails, return NULL. - return null; - } - /** * */ @@ -448,4 +441,19 @@ class MigrateToGroups extends Command app('fireflyconfig')->set(self::CONFIG_NAME, true); } + /** + * Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is + * executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should + * be called from the handle method instead of using the constructor to initialize the command. + * + * @codeCoverageIgnore + */ + private function stupidLaravel(): void + { + $this->count = 0; + $this->journalRepository = app(JournalRepositoryInterface::class); + $this->service = app(JournalDestroyService::class); + $this->groupFactory = app(TransactionGroupFactory::class); + $this->cliRepository = app(JournalCLIRepositoryInterface::class); + } } diff --git a/app/Console/Commands/Upgrade/MigrateToRules.php b/app/Console/Commands/Upgrade/MigrateToRules.php index 0286d4b70f..d751ffa7cd 100644 --- a/app/Console/Commands/Upgrade/MigrateToRules.php +++ b/app/Console/Commands/Upgrade/MigrateToRules.php @@ -53,22 +53,21 @@ class MigrateToRules extends Command * @var string */ protected $signature = 'firefly-iii:bills-to-rules {--F|force : Force the execution of this command.}'; - - /** @var UserRepositoryInterface */ - private $userRepository; - /** @var RuleGroupRepositoryInterface */ - private $ruleGroupRepository; /** @var BillRepositoryInterface */ private $billRepository; + private $count; + /** @var RuleGroupRepositoryInterface */ + private $ruleGroupRepository; /** @var RuleRepositoryInterface */ private $ruleRepository; - private $count; + /** @var UserRepositoryInterface */ + private $userRepository; /** * Execute the console command. * - * @return int * @throws FireflyException + * @return int */ public function handle(): int { @@ -103,22 +102,6 @@ class MigrateToRules extends Command return 0; } - /** - * Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is - * executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should - * be called from the handle method instead of using the constructor to initialize the command. - * - * @codeCoverageIgnore - */ - private function stupidLaravel(): void - { - $this->count = 0; - $this->userRepository = app(UserRepositoryInterface::class); - $this->ruleGroupRepository = app(RuleGroupRepositoryInterface::class); - $this->billRepository = app(BillRepositoryInterface::class); - $this->ruleRepository = app(RuleRepositoryInterface::class); - } - /** * @return bool */ @@ -126,7 +109,7 @@ class MigrateToRules extends Command { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; // @codeCoverageIgnore @@ -141,45 +124,9 @@ class MigrateToRules extends Command } /** - * Migrate bills to new rule structure for a specific user. - * - * @param User $user - * @throws FireflyException - */ - private function migrateUser(User $user): void - { - $this->ruleGroupRepository->setUser($user); - $this->billRepository->setUser($user); - $this->ruleRepository->setUser($user); - - /** @var Preference $lang */ - $lang = app('preferences')->getForUser($user, 'language', 'en_US'); - $groupTitle = (string)trans('firefly.rulegroup_for_bills_title', [], $lang->data); - $ruleGroup = $this->ruleGroupRepository->findByTitle($groupTitle); - //$currency = $this->getCurrency($user); - - if (null === $ruleGroup) { - $ruleGroup = $this->ruleGroupRepository->store( - [ - 'title' => (string)trans('firefly.rulegroup_for_bills_title', [], $lang->data), - 'description' => (string)trans('firefly.rulegroup_for_bills_description', [], $lang->data), - 'active' => true, - ] - ); - } - $bills = $this->billRepository->getBills(); - - /** @var Bill $bill */ - foreach ($bills as $bill) { - $this->migrateBill($ruleGroup, $bill, $lang); - } - - } - - /** - * @param RuleGroup $ruleGroup - * @param Bill $bill - * @throws FireflyException + * @param RuleGroup $ruleGroup + * @param Bill $bill + * @param Preference $language */ private function migrateBill(RuleGroup $ruleGroup, Bill $bill, Preference $language): void { @@ -194,8 +141,8 @@ class MigrateToRules extends Command 'active' => true, 'strict' => false, 'stop_processing' => false, // field is no longer used. - 'title' => (string)trans('firefly.rule_for_bill_title', ['name' => $bill->name], $language->data), - 'description' => (string)trans('firefly.rule_for_bill_description', ['name' => $bill->name], $language->data), + 'title' => (string) trans('firefly.rule_for_bill_title', ['name' => $bill->name], $language->data), + 'description' => (string) trans('firefly.rule_for_bill_description', ['name' => $bill->name], $language->data), 'trigger' => 'store-journal', 'triggers' => [ [ @@ -246,4 +193,57 @@ class MigrateToRules extends Command $this->billRepository->update($bill, $newBillData); $this->count++; } + + /** + * Migrate bills to new rule structure for a specific user. + * + * @param User $user + * + * @throws FireflyException + */ + private function migrateUser(User $user): void + { + $this->ruleGroupRepository->setUser($user); + $this->billRepository->setUser($user); + $this->ruleRepository->setUser($user); + + /** @var Preference $lang */ + $lang = app('preferences')->getForUser($user, 'language', 'en_US'); + $groupTitle = (string) trans('firefly.rulegroup_for_bills_title', [], $lang->data); + $ruleGroup = $this->ruleGroupRepository->findByTitle($groupTitle); + //$currency = $this->getCurrency($user); + + if (null === $ruleGroup) { + $ruleGroup = $this->ruleGroupRepository->store( + [ + 'title' => (string) trans('firefly.rulegroup_for_bills_title', [], $lang->data), + 'description' => (string) trans('firefly.rulegroup_for_bills_description', [], $lang->data), + 'active' => true, + ] + ); + } + $bills = $this->billRepository->getBills(); + + /** @var Bill $bill */ + foreach ($bills as $bill) { + $this->migrateBill($ruleGroup, $bill, $lang); + } + + } + + /** + * Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is + * executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should + * be called from the handle method instead of using the constructor to initialize the command. + * + * @codeCoverageIgnore + */ + private function stupidLaravel(): void + { + $this->count = 0; + $this->userRepository = app(UserRepositoryInterface::class); + $this->ruleGroupRepository = app(RuleGroupRepositoryInterface::class); + $this->billRepository = app(BillRepositoryInterface::class); + $this->ruleRepository = app(RuleRepositoryInterface::class); + } } diff --git a/app/Console/Commands/Upgrade/OtherCurrenciesCorrections.php b/app/Console/Commands/Upgrade/OtherCurrenciesCorrections.php index daa00621bd..2c40887fc9 100644 --- a/app/Console/Commands/Upgrade/OtherCurrenciesCorrections.php +++ b/app/Console/Commands/Upgrade/OtherCurrenciesCorrections.php @@ -40,7 +40,6 @@ use Illuminate\Console\Command; */ class OtherCurrenciesCorrections extends Command { - public const CONFIG_NAME = '480_other_currencies'; /** * The console command description. @@ -58,14 +57,14 @@ class OtherCurrenciesCorrections extends Command private $accountCurrencies; /** @var AccountRepositoryInterface */ private $accountRepos; - /** @var CurrencyRepositoryInterface */ - private $currencyRepos; - /** @var JournalRepositoryInterface */ - private $journalRepos; /** @var JournalCLIRepositoryInterface */ private $cliRepos; /** @var int */ private $count; + /** @var CurrencyRepositoryInterface */ + private $currencyRepos; + /** @var JournalRepositoryInterface */ + private $journalRepos; /** * Execute the console command. @@ -94,23 +93,6 @@ class OtherCurrenciesCorrections extends Command return 0; } - /** - * Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is - * executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should - * be called from the handle method instead of using the constructor to initialize the command. - * - * @codeCoverageIgnore - */ - private function stupidLaravel(): void - { - $this->count = 0; - $this->accountCurrencies = []; - $this->accountRepos = app(AccountRepositoryInterface::class); - $this->currencyRepos = app(CurrencyRepositoryInterface::class); - $this->journalRepos = app(JournalRepositoryInterface::class); - $this->cliRepos = app(JournalCLIRepositoryInterface::class); - } - /** * @param Account $account * @@ -136,110 +118,6 @@ class OtherCurrenciesCorrections extends Command $this->accountCurrencies[$accountId] = $currency; return $currency; - - - } - - /** - * @return bool - */ - private function isExecuted(): bool - { - $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); - if (null !== $configVar) { - return (bool)$configVar->data; - } - - return false; // @codeCoverageIgnore - } - - /** - * - */ - private function markAsExecuted(): void - { - app('fireflyconfig')->set(self::CONFIG_NAME, true); - } - - /** - * @param TransactionJournal $journal - */ - private function updateJournalCurrency(TransactionJournal $journal): void - { - $this->accountRepos->setUser($journal->user); - $this->journalRepos->setUser($journal->user); - $this->currencyRepos->setUser($journal->user); - $this->cliRepos->setUser($journal->user); - - $leadTransaction = $this->getLeadTransaction($journal); - - if (null === $leadTransaction) { - // @codeCoverageIgnoreStart - $this->error(sprintf('Could not reliably determine which transaction is in the lead for transaction journal #%d.', $journal->id)); - - return; - // @codeCoverageIgnoreEnd - } - - /** @var Account $account */ - $account = $leadTransaction->account; - $currency = $this->getCurrency($account); - if (null === $currency) { - // @codeCoverageIgnoreStart - $this->error(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; - // @codeCoverageIgnoreEnd - } - // fix each transaction: - $journal->transactions->each( - static function (Transaction $transaction) use ($currency) { - if (null === $transaction->transaction_currency_id) { - $transaction->transaction_currency_id = $currency->id; - $transaction->save(); - } - - // when mismatch in transaction: - if (!((int)$transaction->transaction_currency_id === (int)$currency->id)) { - $transaction->foreign_currency_id = (int)$transaction->transaction_currency_id; - $transaction->foreign_amount = $transaction->amount; - $transaction->transaction_currency_id = $currency->id; - $transaction->save(); - } - } - ); - // also update the journal, of course: - $journal->transaction_currency_id = $currency->id; - $this->count++; - $journal->save(); - } - - /** - * This routine verifies that withdrawals, deposits and opening balances have the correct currency settings for - * the accounts they are linked to. - * - * Both source and destination must match the respective currency preference of the related asset account. - * So FF3 must verify all transactions. - * - */ - private function updateOtherJournalsCurrencies(): void - { - $set = - $this->cliRepos->getAllJournals( - [ - TransactionType::WITHDRAWAL, - TransactionType::DEPOSIT, - TransactionType::OPENING_BALANCE, - TransactionType::RECONCILIATION, - ] - ); - - /** @var TransactionJournal $journal */ - foreach ($set as $journal) { - $this->updateJournalCurrency($journal); - } } /** @@ -281,4 +159,129 @@ class OtherCurrenciesCorrections extends Command return $lead; } + + /** + * @return bool + */ + private function isExecuted(): bool + { + $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); + if (null !== $configVar) { + return (bool) $configVar->data; + } + + return false; // @codeCoverageIgnore + } + + /** + * + */ + private function markAsExecuted(): void + { + app('fireflyconfig')->set(self::CONFIG_NAME, true); + } + + /** + * Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is + * executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should + * be called from the handle method instead of using the constructor to initialize the command. + * + * @codeCoverageIgnore + */ + private function stupidLaravel(): void + { + $this->count = 0; + $this->accountCurrencies = []; + $this->accountRepos = app(AccountRepositoryInterface::class); + $this->currencyRepos = app(CurrencyRepositoryInterface::class); + $this->journalRepos = app(JournalRepositoryInterface::class); + $this->cliRepos = app(JournalCLIRepositoryInterface::class); + } + + /** + * @param TransactionJournal $journal + */ + private function updateJournalCurrency(TransactionJournal $journal): void + { + $this->accountRepos->setUser($journal->user); + $this->journalRepos->setUser($journal->user); + $this->currencyRepos->setUser($journal->user); + $this->cliRepos->setUser($journal->user); + + $leadTransaction = $this->getLeadTransaction($journal); + + if (null === $leadTransaction) { + // @codeCoverageIgnoreStart + $this->error(sprintf('Could not reliably determine which transaction is in the lead for transaction journal #%d.', $journal->id)); + + return; + // @codeCoverageIgnoreEnd + } + + /** @var Account $account */ + $account = $leadTransaction->account; + $currency = $this->getCurrency($account); + if (null === $currency) { + // @codeCoverageIgnoreStart + $this->error( + 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; + // @codeCoverageIgnoreEnd + } + // fix each transaction: + $journal->transactions->each( + static function (Transaction $transaction) use ($currency) { + if (null === $transaction->transaction_currency_id) { + $transaction->transaction_currency_id = $currency->id; + $transaction->save(); + } + + // when mismatch in transaction: + if (!((int) $transaction->transaction_currency_id === (int) $currency->id)) { + $transaction->foreign_currency_id = (int) $transaction->transaction_currency_id; + $transaction->foreign_amount = $transaction->amount; + $transaction->transaction_currency_id = $currency->id; + $transaction->save(); + } + } + ); + // also update the journal, of course: + $journal->transaction_currency_id = $currency->id; + $this->count++; + $journal->save(); + } + + /** + * This routine verifies that withdrawals, deposits and opening balances have the correct currency settings for + * the accounts they are linked to. + * + * Both source and destination must match the respective currency preference of the related asset account. + * So FF3 must verify all transactions. + * + */ + private function updateOtherJournalsCurrencies(): void + { + $set + = $this->cliRepos->getAllJournals( + [ + TransactionType::WITHDRAWAL, + TransactionType::DEPOSIT, + TransactionType::OPENING_BALANCE, + TransactionType::RECONCILIATION, + ] + ); + + /** @var TransactionJournal $journal */ + foreach ($set as $journal) { + $this->updateJournalCurrency($journal); + } + } } diff --git a/app/Console/Commands/Upgrade/RenameAccountMeta.php b/app/Console/Commands/Upgrade/RenameAccountMeta.php index 493fbd2f97..6a6e369a8d 100644 --- a/app/Console/Commands/Upgrade/RenameAccountMeta.php +++ b/app/Console/Commands/Upgrade/RenameAccountMeta.php @@ -76,7 +76,7 @@ class RenameAccountMeta extends Command $count += AccountMeta::where('name', $old)->update(['name' => $new]); // delete empty entries while we're at it. - AccountMeta::where('name', $new)->where('data','""')->delete(); + AccountMeta::where('name', $new)->where('data', '""')->delete(); } $this->markAsExecuted(); @@ -101,7 +101,7 @@ class RenameAccountMeta extends Command { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; // @codeCoverageIgnore diff --git a/app/Console/Commands/Upgrade/TransactionIdentifier.php b/app/Console/Commands/Upgrade/TransactionIdentifier.php index 72861c099b..a60db0b924 100644 --- a/app/Console/Commands/Upgrade/TransactionIdentifier.php +++ b/app/Console/Commands/Upgrade/TransactionIdentifier.php @@ -50,15 +50,12 @@ class TransactionIdentifier extends Command * @var string */ protected $signature = 'firefly-iii:transaction-identifiers {--F|force : Force the execution of this command.}'; - - /** @var JournalRepositoryInterface */ - private $journalRepository; - /** @var JournalCLIRepositoryInterface */ private $cliRepository; - /** @var int */ private $count; + /** @var JournalRepositoryInterface */ + private $journalRepository; /** * This method gives all transactions which are part of a split journal (so more than 2) a sort of "order" so they are easier @@ -108,17 +105,36 @@ class TransactionIdentifier extends Command } /** - * Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is - * executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should - * be called from the handle method instead of using the constructor to initialize the command. + * @param Transaction $transaction + * @param array $exclude * - * @codeCoverageIgnore + * @return Transaction|null */ - private function stupidLaravel(): void + private function findOpposing(Transaction $transaction, array $exclude): ?Transaction { - $this->journalRepository = app(JournalRepositoryInterface::class); - $this->cliRepository = app(JournalCLIRepositoryInterface::class); - $this->count = 0; + // find opposing: + $amount = bcmul((string) $transaction->amount, '-1'); + + try { + /** @var Transaction $opposing */ + $opposing = Transaction::where('transaction_journal_id', $transaction->transaction_journal_id) + ->where('amount', $amount)->where('identifier', '=', 0) + ->whereNotIn('id', $exclude) + ->first(); + // @codeCoverageIgnoreStart + } catch (QueryException $e) { + Log::error($e->getMessage()); + $this->error('Firefly III could not find the "identifier" field in the "transactions" table.'); + $this->error(sprintf('This field is required for Firefly III version %s to run.', config('firefly.version'))); + $this->error('Please run "php artisan migrate" to add this field to the table.'); + $this->info('Then, run "php artisan firefly:upgrade-database" to try again.'); + + return null; + } + + // @codeCoverageIgnoreEnd + + return $opposing; } /** @@ -128,7 +144,7 @@ class TransactionIdentifier extends Command { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; // @codeCoverageIgnore @@ -142,6 +158,20 @@ class TransactionIdentifier extends Command app('fireflyconfig')->set(self::CONFIG_NAME, true); } + /** + * Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is + * executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should + * be called from the handle method instead of using the constructor to initialize the command. + * + * @codeCoverageIgnore + */ + private function stupidLaravel(): void + { + $this->journalRepository = app(JournalRepositoryInterface::class); + $this->cliRepository = app(JournalCLIRepositoryInterface::class); + $this->count = 0; + } + /** * Grab all positive transactions from this journal that are not deleted. for each one, grab the negative opposing one * which has 0 as an identifier and give it the same identifier. @@ -171,36 +201,4 @@ class TransactionIdentifier extends Command } } - - /** - * @param Transaction $transaction - * @param array $exclude - * @return Transaction|null - */ - private function findOpposing(Transaction $transaction, array $exclude): ?Transaction - { - // find opposing: - $amount = bcmul((string)$transaction->amount, '-1'); - - try { - /** @var Transaction $opposing */ - $opposing = Transaction::where('transaction_journal_id', $transaction->transaction_journal_id) - ->where('amount', $amount)->where('identifier', '=', 0) - ->whereNotIn('id', $exclude) - ->first(); - // @codeCoverageIgnoreStart - } catch (QueryException $e) { - Log::error($e->getMessage()); - $this->error('Firefly III could not find the "identifier" field in the "transactions" table.'); - $this->error(sprintf('This field is required for Firefly III version %s to run.', config('firefly.version'))); - $this->error('Please run "php artisan migrate" to add this field to the table.'); - $this->info('Then, run "php artisan firefly:upgrade-database" to try again.'); - - return null; - } - - // @codeCoverageIgnoreEnd - - return $opposing; - } } diff --git a/app/Console/Commands/Upgrade/TransferCurrenciesCorrections.php b/app/Console/Commands/Upgrade/TransferCurrenciesCorrections.php index af19d78ad2..90023cbb92 100644 --- a/app/Console/Commands/Upgrade/TransferCurrenciesCorrections.php +++ b/app/Console/Commands/Upgrade/TransferCurrenciesCorrections.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace FireflyIII\Console\Commands\Upgrade; - use FireflyIII\Models\Account; use FireflyIII\Models\Transaction; use FireflyIII\Models\TransactionCurrency; @@ -41,7 +40,6 @@ use Log; */ class TransferCurrenciesCorrections extends Command { - public const CONFIG_NAME = '480_transfer_currencies'; /** * The console command description. @@ -59,27 +57,26 @@ class TransferCurrenciesCorrections extends Command private $accountCurrencies; /** @var AccountRepositoryInterface */ private $accountRepos; - /** @var CurrencyRepositoryInterface */ - private $currencyRepos; - /** @var JournalRepositoryInterface */ - private $journalRepos; /** @var JournalCLIRepositoryInterface */ private $cliRepos; /** @var int */ private $count; - - /** @var Transaction The source transaction of the current journal. */ - private $sourceTransaction; - /** @var Account The source account of the current journal. */ - private $sourceAccount; - /** @var TransactionCurrency The currency preference of the source account of the current journal. */ - private $sourceCurrency; - /** @var Transaction The destination transaction of the current journal. */ - private $destinationTransaction; + /** @var CurrencyRepositoryInterface */ + private $currencyRepos; /** @var Account The destination account of the current journal. */ private $destinationAccount; /** @var TransactionCurrency The currency preference of the destination account of the current journal. */ private $destinationCurrency; + /** @var Transaction The destination transaction of the current journal. */ + private $destinationTransaction; + /** @var JournalRepositoryInterface */ + private $journalRepos; + /** @var Account The source account of the current journal. */ + private $sourceAccount; + /** @var TransactionCurrency The currency preference of the source account of the current journal. */ + private $sourceCurrency; + /** @var Transaction The source transaction of the current journal. */ + private $sourceTransaction; /** * Execute the console command. @@ -118,21 +115,216 @@ class TransferCurrenciesCorrections extends Command } /** - * Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is - * executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should - * be called from the handle method instead of using the constructor to initialize the command. - * - * @codeCoverageIgnore + * The destination transaction must have a currency. If not, it will be added by + * taking it from the destination account's preference. */ - private function stupidLaravel(): void + private function fixDestNoCurrency(): void { - $this->count = 0; - $this->accountRepos = app(AccountRepositoryInterface::class); - $this->currencyRepos = app(CurrencyRepositoryInterface::class); - $this->journalRepos = app(JournalRepositoryInterface::class); - $this->cliRepos = app(JournalCLIRepositoryInterface::class); - $this->accountCurrencies = []; - $this->resetInformation(); + if (null === $this->destinationTransaction->transaction_currency_id && null !== $this->destinationCurrency) { + $this->destinationTransaction + ->transaction_currency_id + = (int) $this->destinationCurrency->id; + $message = sprintf( + 'Transaction #%d has no currency setting, now set to %s.', + $this->destinationTransaction->id, + $this->destinationCurrency->code + ); + Log::debug($message); + $this->line($message); + $this->count++; + $this->destinationTransaction->save(); + } + } + + /** + * If the foreign amount of the destination transaction is null, but that of the other isn't, use this piece of code + * to restore it. + */ + private function fixDestNullForeignAmount(): void + { + if (null === $this->destinationTransaction->foreign_amount && null !== $this->sourceTransaction->foreign_amount) { + $this->destinationTransaction->foreign_amount = bcmul((string) $this->sourceTransaction->foreign_amount, '-1'); + $this->destinationTransaction->save(); + $this->count++; + Log::debug( + sprintf( + 'Restored foreign amount of destination transaction #%d to %s', + $this->destinationTransaction->id, + $this->destinationTransaction->foreign_amount + ) + ); + } + } + + /** + * The destination transaction must have the correct currency. If not, it will be set by + * taking it from the destination account's preference. + */ + private function fixDestinationUnmatchedCurrency(): void + { + if (null !== $this->destinationCurrency + && null === $this->destinationTransaction->foreign_amount + && (int) $this->destinationTransaction->transaction_currency_id !== (int) $this->destinationCurrency->id + ) { + $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, + $this->destinationAccount->id, + $this->destinationTransaction->amount + ); + Log::debug($message); + $this->line($message); + $this->count++; + $this->destinationTransaction->transaction_currency_id = (int) $this->destinationCurrency->id; + $this->destinationTransaction->save(); + } + } + + /** + * If the destination account currency is the same as the source currency, + * both foreign_amount and foreign_currency_id fields must be NULL + * for both transactions (because foreign currency info would not make sense) + * + */ + private function fixInvalidForeignCurrency(): void + { + if ((int) $this->destinationCurrency->id === (int) $this->sourceCurrency->id) { + // update both transactions to match: + $this->sourceTransaction->foreign_amount = null; + $this->sourceTransaction->foreign_currency_id = null; + + $this->destinationTransaction->foreign_amount = null; + $this->destinationTransaction->foreign_currency_id = null; + + $this->sourceTransaction->save(); + $this->destinationTransaction->save(); + + Log::debug( + sprintf( + 'Currency for account "%s" is %s, and currency for account "%s" is also + %s, so transactions #%d and #%d has been verified to be to %s exclusively.', + $this->destinationAccount->name, + $this->destinationCurrency->code, + $this->sourceAccount->name, + $this->sourceCurrency->code, + $this->sourceTransaction->id, + $this->destinationTransaction->id, + $this->sourceCurrency->code + ) + ); + } + } + + /** + * If destination account currency is different from source account currency, + * then both transactions must get the source account's currency as normal currency + * and the opposing account's currency as foreign currency. + */ + private function fixMismatchedForeignCurrency(): void + { + if ((int) $this->sourceCurrency->id !== (int) $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->sourceTransaction->save(); + $this->destinationTransaction->save(); + $this->count++; + Log::debug(sprintf('Verified foreign currency ID of transaction #%d and #%d', $this->sourceTransaction->id, $this->destinationTransaction->id)); + } + } + + /** + * The source transaction must have a currency. If not, it will be added by + * taking it from the source account's preference. + */ + private function fixSourceNoCurrency(): void + { + if (null === $this->sourceTransaction->transaction_currency_id && null !== $this->sourceCurrency) { + $this->sourceTransaction + ->transaction_currency_id + = (int) $this->sourceCurrency->id; + $message = sprintf( + 'Transaction #%d has no currency setting, now set to %s.', + $this->sourceTransaction->id, + $this->sourceCurrency->code + ); + Log::debug($message); + $this->line($message); + $this->count++; + $this->sourceTransaction->save(); + } + } + + /** + * If the foreign amount of the source transaction is null, but that of the other isn't, use this piece of code + * to restore it. + */ + private function fixSourceNullForeignAmount(): void + { + if (null === $this->sourceTransaction->foreign_amount && null !== $this->destinationTransaction->foreign_amount) { + $this->sourceTransaction->foreign_amount = bcmul((string) $this->destinationTransaction->foreign_amount, '-1'); + $this->sourceTransaction->save(); + $this->count++; + Log::debug( + sprintf( + 'Restored foreign amount of source transaction #%d to %s', + $this->sourceTransaction->id, + $this->sourceTransaction->foreign_amount + ) + ); + } + } + + /** + * The source transaction must have the correct currency. If not, it will be set by + * taking it from the source account's preference. + */ + private function fixSourceUnmatchedCurrency(): void + { + if (null !== $this->sourceCurrency + && null === $this->sourceTransaction->foreign_amount + && (int) $this->sourceTransaction->transaction_currency_id !== (int) $this->sourceCurrency->id + ) { + $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, + $this->sourceAccount->id, + $this->sourceTransaction->amount + ); + Log::debug($message); + $this->line($message); + $this->count++; + $this->sourceTransaction->transaction_currency_id = (int) $this->sourceCurrency->id; + $this->sourceTransaction->save(); + } + } + + /** + * This method makes sure that the transaction journal uses the currency given in the source transaction. + * + * @param TransactionJournal $journal + */ + private function fixTransactionJournalCurrency(TransactionJournal $journal): void + { + if ((int) $journal->transaction_currency_id !== (int) $this->sourceCurrency->id) { + $oldCurrencyCode = $journal->transactionCurrency->code ?? '(nothing)'; + $journal->transaction_currency_id = $this->sourceCurrency->id; + $message = sprintf( + 'Transfer #%d ("%s") has been updated to use %s instead of %s.', + $journal->id, + $journal->description, + $this->sourceCurrency->code, + $oldCurrencyCode + ); + $this->count++; + $this->line($message); + Log::debug($message); + $journal->save(); + } } /** @@ -150,7 +342,7 @@ class TransferCurrenciesCorrections extends Command return $this->accountCurrencies[$accountId]; // @codeCoverageIgnore } // TODO we can use getAccountCurrency() instead - $currencyId = (int)$this->accountRepos->getMetaValue($account, 'currency_id'); + $currencyId = (int) $this->accountRepos->getMetaValue($account, 'currency_id'); $result = $this->currencyRepos->findNull($currencyId); if (null === $result) { // @codeCoverageIgnoreStart @@ -162,8 +354,20 @@ class TransferCurrenciesCorrections extends Command $this->accountCurrencies[$accountId] = $result; return $result; + } - + /** + * Extract destination transaction, destination account + destination account currency from the journal. + * + * @param TransactionJournal $journal + * + * @codeCoverageIgnore + */ + private function getDestinationInformation(TransactionJournal $journal): void + { + $this->destinationTransaction = $this->getDestinationTransaction($journal); + $this->destinationAccount = null === $this->destinationTransaction ? null : $this->destinationTransaction->account; + $this->destinationCurrency = null === $this->destinationAccount ? null : $this->getCurrency($this->destinationAccount); } /** @@ -177,6 +381,20 @@ class TransferCurrenciesCorrections extends Command return $transfer->transactions()->where('amount', '>', 0)->first(); } + /** + * Extract source transaction, source account + source account currency from the journal. + * + * @param TransactionJournal $journal + * + * @codeCoverageIgnore + */ + private function getSourceInformation(TransactionJournal $journal): void + { + $this->sourceTransaction = $this->getSourceTransaction($journal); + $this->sourceAccount = null === $this->sourceTransaction ? null : $this->sourceTransaction->account; + $this->sourceCurrency = null === $this->sourceAccount ? null : $this->getCurrency($this->sourceAccount); + } + /** * @param TransactionJournal $transfer * @@ -188,6 +406,19 @@ class TransferCurrenciesCorrections extends Command return $transfer->transactions()->where('amount', '<', 0)->first(); } + /** + * Is either the source or destination transaction NULL? + * + * @return bool + * @codeCoverageIgnore + */ + private function isEmptyTransactions(): bool + { + return null === $this->sourceTransaction || null === $this->destinationTransaction + || null === $this->sourceAccount + || null === $this->destinationAccount; + } + /** * @return bool */ @@ -195,12 +426,56 @@ class TransferCurrenciesCorrections extends Command { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; // @codeCoverageIgnore } + /** + * @return bool + * @codeCoverageIgnore + */ + private function isNoCurrencyPresent(): bool + { + // source account must have a currency preference. + if (null === $this->sourceCurrency) { + $message = sprintf('Account #%d ("%s") must have currency preference but has none.', $this->sourceAccount->id, $this->sourceAccount->name); + Log::error($message); + $this->error($message); + + return true; + } + + // destination account must have a currency preference. + if (null === $this->destinationCurrency) { + $message = sprintf( + 'Account #%d ("%s") must have currency preference but has none.', + $this->destinationAccount->id, + $this->destinationAccount->name + ); + Log::error($message); + $this->error($message); + + return true; + } + + return false; + } + + /** + * Is this a split transaction journal? + * + * @param TransactionJournal $transfer + * + * @return bool + * @codeCoverageIgnore + */ + private function isSplitJournal(TransactionJournal $transfer): bool + { + return $transfer->transactions->count() > 2; + } + /** * */ @@ -210,27 +485,18 @@ class TransferCurrenciesCorrections extends Command } /** - * This method makes sure that the transaction journal uses the currency given in the source transaction. + * Reset all the class fields for the current transfer. * - * @param TransactionJournal $journal + * @codeCoverageIgnore */ - private function fixTransactionJournalCurrency(TransactionJournal $journal): void + private function resetInformation(): void { - if ((int)$journal->transaction_currency_id !== (int)$this->sourceCurrency->id) { - $oldCurrencyCode = $journal->transactionCurrency->code ?? '(nothing)'; - $journal->transaction_currency_id = $this->sourceCurrency->id; - $message = sprintf( - 'Transfer #%d ("%s") has been updated to use %s instead of %s.', - $journal->id, - $journal->description, - $this->sourceCurrency->code, - $oldCurrencyCode - ); - $this->count++; - $this->line($message); - Log::debug($message); - $journal->save(); - } + $this->sourceTransaction = null; + $this->sourceAccount = null; + $this->sourceCurrency = null; + $this->destinationTransaction = null; + $this->destinationAccount = null; + $this->destinationCurrency = null; } /** @@ -253,43 +519,21 @@ class TransferCurrenciesCorrections extends Command } /** - * Reset all the class fields for the current transfer. - * @codeCoverageIgnore - */ - private function resetInformation(): void - { - $this->sourceTransaction = null; - $this->sourceAccount = null; - $this->sourceCurrency = null; - $this->destinationTransaction = null; - $this->destinationAccount = null; - $this->destinationCurrency = null; - } - - /** - * Extract source transaction, source account + source account currency from the journal. + * Laravel will execute ALL __construct() methods for ALL commands whenever a SINGLE command is + * executed. This leads to noticeable slow-downs and class calls. To prevent this, this method should + * be called from the handle method instead of using the constructor to initialize the command. * - * @param TransactionJournal $journal * @codeCoverageIgnore */ - private function getSourceInformation(TransactionJournal $journal): void + private function stupidLaravel(): void { - $this->sourceTransaction = $this->getSourceTransaction($journal); - $this->sourceAccount = null === $this->sourceTransaction ? null : $this->sourceTransaction->account; - $this->sourceCurrency = null === $this->sourceAccount ? null : $this->getCurrency($this->sourceAccount); - } - - /** - * Extract destination transaction, destination account + destination account currency from the journal. - * - * @param TransactionJournal $journal - * @codeCoverageIgnore - */ - private function getDestinationInformation(TransactionJournal $journal): void - { - $this->destinationTransaction = $this->getDestinationTransaction($journal); - $this->destinationAccount = null === $this->destinationTransaction ? null : $this->destinationTransaction->account; - $this->destinationCurrency = null === $this->destinationAccount ? null : $this->getCurrency($this->destinationAccount); + $this->count = 0; + $this->accountRepos = app(AccountRepositoryInterface::class); + $this->currencyRepos = app(CurrencyRepositoryInterface::class); + $this->journalRepos = app(JournalRepositoryInterface::class); + $this->cliRepos = app(JournalCLIRepositoryInterface::class); + $this->accountCurrencies = []; + $this->resetInformation(); } /** @@ -297,7 +541,6 @@ class TransferCurrenciesCorrections extends Command */ private function updateTransferCurrency(TransactionJournal $transfer): void { - $this->resetInformation(); // @codeCoverageIgnoreStart @@ -325,7 +568,8 @@ class TransferCurrenciesCorrections extends Command // @codeCoverageIgnoreStart if ($this->isNoCurrencyPresent()) { $this->error( - sprintf('Source or destination accounts for transaction journal #%d have no currency information. Cannot fix this one.', $transfer->id)); + sprintf('Source or destination accounts for transaction journal #%d have no currency information. Cannot fix this one.', $transfer->id) + ); return; } @@ -355,225 +599,5 @@ class TransferCurrenciesCorrections extends Command // fix journal itself: $this->fixTransactionJournalCurrency($transfer); - } - - /** - * The source transaction must have a currency. If not, it will be added by - * taking it from the source account's preference. - */ - private function fixSourceNoCurrency(): void - { - if (null === $this->sourceTransaction->transaction_currency_id && null !== $this->sourceCurrency) { - $this->sourceTransaction - ->transaction_currency_id = (int)$this->sourceCurrency->id; - $message = sprintf('Transaction #%d has no currency setting, now set to %s.', - $this->sourceTransaction->id, $this->sourceCurrency->code); - Log::debug($message); - $this->line($message); - $this->count++; - $this->sourceTransaction->save(); - } - } - - /** - * The destination transaction must have a currency. If not, it will be added by - * taking it from the destination account's preference. - */ - private function fixDestNoCurrency(): void - { - if (null === $this->destinationTransaction->transaction_currency_id && null !== $this->destinationCurrency) { - $this->destinationTransaction - ->transaction_currency_id = (int)$this->destinationCurrency->id; - $message = sprintf('Transaction #%d has no currency setting, now set to %s.', - $this->destinationTransaction->id, $this->destinationCurrency->code); - Log::debug($message); - $this->line($message); - $this->count++; - $this->destinationTransaction->save(); - } - } - - /** - * The source transaction must have the correct currency. If not, it will be set by - * taking it from the source account's preference. - */ - private function fixSourceUnmatchedCurrency(): void - { - if (null !== $this->sourceCurrency && - null === $this->sourceTransaction->foreign_amount && - (int)$this->sourceTransaction->transaction_currency_id !== (int)$this->sourceCurrency->id - ) { - $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, - $this->sourceAccount->id, - $this->sourceTransaction->amount - ); - Log::debug($message); - $this->line($message); - $this->count++; - $this->sourceTransaction->transaction_currency_id = (int)$this->sourceCurrency->id; - $this->sourceTransaction->save(); - } - } - - /** - * The destination transaction must have the correct currency. If not, it will be set by - * taking it from the destination account's preference. - */ - private function fixDestinationUnmatchedCurrency(): void - { - if (null !== $this->destinationCurrency && - null === $this->destinationTransaction->foreign_amount && - (int)$this->destinationTransaction->transaction_currency_id !== (int)$this->destinationCurrency->id - ) { - $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, - $this->destinationAccount->id, - $this->destinationTransaction->amount - ); - Log::debug($message); - $this->line($message); - $this->count++; - $this->destinationTransaction->transaction_currency_id = (int)$this->destinationCurrency->id; - $this->destinationTransaction->save(); - } - } - - /** - * Is this a split transaction journal? - * - * @param TransactionJournal $transfer - * @return bool - * @codeCoverageIgnore - */ - private function isSplitJournal(TransactionJournal $transfer): bool - { - return $transfer->transactions->count() > 2; - } - - /** - * Is either the source or destination transaction NULL? - * @return bool - * @codeCoverageIgnore - */ - private function isEmptyTransactions(): bool - { - return null === $this->sourceTransaction || null === $this->destinationTransaction || - null === $this->sourceAccount || null === $this->destinationAccount; - } - - /** - * If the destination account currency is the same as the source currency, - * both foreign_amount and foreign_currency_id fields must be NULL - * for both transactions (because foreign currency info would not make sense) - * - */ - private function fixInvalidForeignCurrency(): void - { - if ((int)$this->destinationCurrency->id === (int)$this->sourceCurrency->id) { - // update both transactions to match: - $this->sourceTransaction->foreign_amount = null; - $this->sourceTransaction->foreign_currency_id = null; - - $this->destinationTransaction->foreign_amount = null; - $this->destinationTransaction->foreign_currency_id = null; - - $this->sourceTransaction->save(); - $this->destinationTransaction->save(); - - Log::debug( - sprintf( - 'Currency for account "%s" is %s, and currency for account "%s" is also - %s, so transactions #%d and #%d has been verified to be to %s exclusively.', - $this->destinationAccount->name, $this->destinationCurrency->code, - $this->sourceAccount->name, $this->sourceCurrency->code, - $this->sourceTransaction->id, $this->destinationTransaction->id, $this->sourceCurrency->code - ) - ); - } - } - - /** - * If destination account currency is different from source account currency, - * then both transactions must get the source account's currency as normal currency - * and the opposing account's currency as foreign currency. - */ - private function fixMismatchedForeignCurrency(): void - { - if ((int)$this->sourceCurrency->id !== (int)$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->sourceTransaction->save(); - $this->destinationTransaction->save(); - $this->count++; - Log::debug(sprintf('Verified foreign currency ID of transaction #%d and #%d', $this->sourceTransaction->id, $this->destinationTransaction->id)); - } - } - - /** - * If the foreign amount of the source transaction is null, but that of the other isn't, use this piece of code - * to restore it. - */ - private function fixSourceNullForeignAmount(): void - { - if (null === $this->sourceTransaction->foreign_amount && null !== $this->destinationTransaction->foreign_amount) { - $this->sourceTransaction->foreign_amount = bcmul((string)$this->destinationTransaction->foreign_amount, '-1'); - $this->sourceTransaction->save(); - $this->count++; - Log::debug(sprintf('Restored foreign amount of source transaction #%d to %s', - $this->sourceTransaction->id, $this->sourceTransaction->foreign_amount)); - } - } - - /** - * If the foreign amount of the destination transaction is null, but that of the other isn't, use this piece of code - * to restore it. - */ - private function fixDestNullForeignAmount(): void - { - if (null === $this->destinationTransaction->foreign_amount && null !== $this->sourceTransaction->foreign_amount) { - $this->destinationTransaction->foreign_amount = bcmul((string)$this->sourceTransaction->foreign_amount, '-1'); - $this->destinationTransaction->save(); - $this->count++; - Log::debug(sprintf('Restored foreign amount of destination transaction #%d to %s', - $this->destinationTransaction->id, $this->destinationTransaction->foreign_amount)); - } - } - - /** - * @return bool - * @codeCoverageIgnore - */ - private function isNoCurrencyPresent(): bool - { - // source account must have a currency preference. - if (null === $this->sourceCurrency) { - $message = sprintf('Account #%d ("%s") must have currency preference but has none.', $this->sourceAccount->id, $this->sourceAccount->name); - Log::error($message); - $this->error($message); - - return true; - } - - // destination account must have a currency preference. - if (null === $this->destinationCurrency) { - $message = sprintf('Account #%d ("%s") must have currency preference but has none.', - $this->destinationAccount->id, $this->destinationAccount->name); - Log::error($message); - $this->error($message); - - return true; - } - - return false; - } - } diff --git a/app/Console/Commands/Upgrade/UpgradeDatabase.php b/app/Console/Commands/Upgrade/UpgradeDatabase.php index 13b72703b5..9c330c9554 100644 --- a/app/Console/Commands/Upgrade/UpgradeDatabase.php +++ b/app/Console/Commands/Upgrade/UpgradeDatabase.php @@ -30,6 +30,7 @@ use Illuminate\Console\Command; /** * Class UpgradeDatabase + * * @codeCoverageIgnore */ class UpgradeDatabase extends Command @@ -112,9 +113,9 @@ class UpgradeDatabase extends Command echo $result; } // set new DB version. - app('fireflyconfig')->set('db_version', (int)config('firefly.db_version')); + app('fireflyconfig')->set('db_version', (int) config('firefly.db_version')); // index will set FF3 version. - app('fireflyconfig')->set('ff3_version', (string)config('firefly.version')); + app('fireflyconfig')->set('ff3_version', (string) config('firefly.version')); return 0; } diff --git a/app/Console/Commands/UpgradeFireflyInstructions.php b/app/Console/Commands/UpgradeFireflyInstructions.php index ae9f1e5d35..83c7f1ee6d 100644 --- a/app/Console/Commands/UpgradeFireflyInstructions.php +++ b/app/Console/Commands/UpgradeFireflyInstructions.php @@ -50,10 +50,10 @@ class UpgradeFireflyInstructions extends Command */ public function handle(): int { - if ('update' === (string)$this->argument('task')) { + if ('update' === (string) $this->argument('task')) { $this->updateInstructions(); } - if ('install' === (string)$this->argument('task')) { + if ('install' === (string) $this->argument('task')) { $this->installInstructions(); } diff --git a/app/Console/Commands/VerifiesAccessToken.php b/app/Console/Commands/VerifiesAccessToken.php index bbab0837bc..9c7afe03e6 100644 --- a/app/Console/Commands/VerifiesAccessToken.php +++ b/app/Console/Commands/VerifiesAccessToken.php @@ -38,12 +38,12 @@ use Log; trait VerifiesAccessToken { /** - * @return User * @throws FireflyException + * @return User */ public function getUser(): User { - $userId = (int)$this->option('user'); + $userId = (int) $this->option('user'); /** @var UserRepositoryInterface $repository */ $repository = app(UserRepositoryInterface::class); $user = $repository->findNull($userId); @@ -70,8 +70,8 @@ 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->findNull($userId); diff --git a/app/Events/RequestedReportOnJournals.php b/app/Events/RequestedReportOnJournals.php index b02b29d3ff..0e29b88ea7 100644 --- a/app/Events/RequestedReportOnJournals.php +++ b/app/Events/RequestedReportOnJournals.php @@ -55,7 +55,7 @@ class RequestedReportOnJournals public function __construct(int $userId, Collection $groups) { Log::debug('In event RequestedReportOnJournals.'); - $this->userId = $userId; + $this->userId = $userId; $this->groups = $groups; } diff --git a/app/Exceptions/DuplicateTransactionException.php b/app/Exceptions/DuplicateTransactionException.php index 322916860f..2b607ec9a9 100644 --- a/app/Exceptions/DuplicateTransactionException.php +++ b/app/Exceptions/DuplicateTransactionException.php @@ -20,6 +20,7 @@ */ namespace FireflyIII\Exceptions; + use Exception; /** @@ -27,5 +28,4 @@ use Exception; */ class DuplicateTransactionException extends Exception { - -} \ No newline at end of file +} diff --git a/app/Exceptions/FireflyException.php b/app/Exceptions/FireflyException.php index 5ef1449452..33aa8cad85 100644 --- a/app/Exceptions/FireflyException.php +++ b/app/Exceptions/FireflyException.php @@ -28,6 +28,7 @@ use Exception; /** * Class FireflyException. + * * @codeCoverageIgnore */ class FireflyException extends Exception diff --git a/app/Exceptions/GracefulNotFoundHandler.php b/app/Exceptions/GracefulNotFoundHandler.php index a59de42168..6c4ed1d45a 100644 --- a/app/Exceptions/GracefulNotFoundHandler.php +++ b/app/Exceptions/GracefulNotFoundHandler.php @@ -33,8 +33,11 @@ use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionType; use FireflyIII\User; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; +use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; +use Illuminate\Routing\Redirector; use Log; +use Symfony\Component\HttpFoundation\Response; /** * Class GracefulNotFoundHandler @@ -134,7 +137,7 @@ class GracefulNotFoundHandler extends ExceptionHandler * @param Request $request * @param Exception $exception * - * @return \Illuminate\Http\Response|\Symfony\Component\HttpFoundation\Response + * @return \Illuminate\Http\Response|Response */ private function handleAccount($request, Exception $exception) { @@ -142,7 +145,7 @@ class GracefulNotFoundHandler extends ExceptionHandler /** @var User $user */ $user = auth()->user(); $route = $request->route(); - $accountId = (int)$route->parameter('account'); + $accountId = (int) $route->parameter('account'); /** @var Account $account */ $account = $user->accounts()->with(['accountType'])->withTrashed()->find($accountId); if (null === $account) { @@ -163,7 +166,7 @@ class GracefulNotFoundHandler extends ExceptionHandler /** @var User $user */ $user = auth()->user(); $route = $request->route(); - $attachmentId = (int)$route->parameter('attachment'); + $attachmentId = (int) $route->parameter('attachment'); /** @var Attachment $attachment */ $attachment = $user->attachments()->withTrashed()->find($attachmentId); if (null === $attachment) { @@ -199,7 +202,7 @@ class GracefulNotFoundHandler extends ExceptionHandler * @param $request * @param Exception $exception * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Routing\Redirector|\Symfony\Component\HttpFoundation\Response + * @return RedirectResponse|\Illuminate\Http\Response|Redirector|Response */ private function handleGroup($request, Exception $exception) { @@ -207,7 +210,7 @@ class GracefulNotFoundHandler extends ExceptionHandler /** @var User $user */ $user = auth()->user(); $route = $request->route(); - $groupId = (int)$route->parameter('transactionGroup'); + $groupId = (int) $route->parameter('transactionGroup'); /** @var TransactionGroup $group */ $group = $user->transactionGroups()->withTrashed()->find($groupId); diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index 384b5b4999..e079322857 100644 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -82,15 +82,17 @@ class Handler extends ExceptionHandler 'line' => $exception->getLine(), 'file' => $exception->getFile(), 'trace' => $exception->getTrace(), - ], 500 + ], + 500 ); } return response()->json(['message' => 'Internal Firefly III Exception. See log files.', 'exception' => get_class($exception)], 500); } - if($exception instanceof NotFoundHttpException) { + if ($exception instanceof NotFoundHttpException) { $handler = app(GracefulNotFoundHandler::class); + return $handler->render($request, $exception); } @@ -113,13 +115,12 @@ class Handler extends ExceptionHandler * * @param Exception $exception * + * @throws Exception * @return mixed|void * - * @throws Exception */ public function report(Exception $exception) { - $doMailError = config('firefly.send_error_message'); // if the user wants us to mail: if (true === $doMailError @@ -149,7 +150,7 @@ class Handler extends ExceptionHandler // create job that will mail. $ipAddress = Request::ip() ?? '0.0.0.0'; - $job = new MailError($userData, (string)config('firefly.site_owner'), $ipAddress, $data); + $job = new MailError($userData, (string) config('firefly.site_owner'), $ipAddress, $data); dispatch($job); } diff --git a/app/Exceptions/NotImplementedException.php b/app/Exceptions/NotImplementedException.php index 2e95fce8fd..3bcf0c42d0 100644 --- a/app/Exceptions/NotImplementedException.php +++ b/app/Exceptions/NotImplementedException.php @@ -28,6 +28,7 @@ use Exception; /** * Class NotImplementedException. + * * @codeCoverageIgnore */ class NotImplementedException extends Exception diff --git a/app/Exceptions/ValidationException.php b/app/Exceptions/ValidationException.php index 9a010098ae..cc3b45fb21 100644 --- a/app/Exceptions/ValidationException.php +++ b/app/Exceptions/ValidationException.php @@ -28,6 +28,7 @@ use Exception; /** * Class ValidationExceptions. + * * @codeCoverageIgnore */ class ValidationException extends Exception diff --git a/app/Factory/AccountFactory.php b/app/Factory/AccountFactory.php index e572e3a1ec..86c324f8ed 100644 --- a/app/Factory/AccountFactory.php +++ b/app/Factory/AccountFactory.php @@ -27,7 +27,6 @@ namespace FireflyIII\Factory; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Account; use FireflyIII\Models\AccountType; -use FireflyIII\Models\Location; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Services\Internal\Support\AccountServiceTrait; use FireflyIII\Services\Internal\Support\LocationServiceTrait; @@ -45,18 +44,16 @@ class AccountFactory /** @var AccountRepositoryInterface */ protected $accountRepository; - /** @var User */ - private $user; - - /** @var array */ - private $canHaveVirtual; - /** @var array */ protected $validAssetFields = ['account_role', 'account_number', 'currency_id', 'BIC', 'include_net_worth']; /** @var array */ protected $validCCFields = ['account_role', 'cc_monthly_payment_date', 'cc_type', 'account_number', 'currency_id', 'BIC', 'include_net_worth']; /** @var array */ protected $validFields = ['account_number', 'currency_id', 'BIC', 'interest', 'interest_period', 'include_net_worth']; + /** @var array */ + private $canHaveVirtual; + /** @var User */ + private $user; /** * AccountFactory constructor. @@ -75,8 +72,8 @@ class AccountFactory /** * @param array $data * - * @return Account * @throws FireflyException + * @return Account */ public function create(array $data): Account { @@ -106,7 +103,7 @@ class AccountFactory 'iban' => $data['iban'], ]; - $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'] = $currency->id; @@ -159,8 +156,8 @@ class AccountFactory * @param string $accountName * @param string $accountType * - * @return Account * @throws FireflyException + * @return Account */ public function findOrCreate(string $accountName, string $accountType): Account { @@ -197,7 +194,7 @@ class AccountFactory } /** - * @param int|null $accountTypeId + * @param int|null $accountTypeId * @param null|string $accountType * * @return AccountType|null @@ -205,7 +202,7 @@ class AccountFactory */ protected function getAccountType(?int $accountTypeId, ?string $accountType): ?AccountType { - $accountTypeId = (int)$accountTypeId; + $accountTypeId = (int) $accountTypeId; $result = null; if ($accountTypeId > 0) { $result = AccountType::find($accountTypeId); diff --git a/app/Factory/AccountMetaFactory.php b/app/Factory/AccountMetaFactory.php index c88239511c..de6c2fe317 100644 --- a/app/Factory/AccountMetaFactory.php +++ b/app/Factory/AccountMetaFactory.php @@ -36,6 +36,7 @@ class AccountMetaFactory { /** * Constructor. + * * @codeCoverageIgnore */ public function __construct() diff --git a/app/Factory/AttachmentFactory.php b/app/Factory/AttachmentFactory.php index bf4c225768..22c1d66e15 100644 --- a/app/Factory/AttachmentFactory.php +++ b/app/Factory/AttachmentFactory.php @@ -41,6 +41,7 @@ class AttachmentFactory /** * Constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -53,8 +54,8 @@ class AttachmentFactory /** * @param array $data * - * @return Attachment|null * @throws FireflyException + * @return Attachment|null */ public function create(array $data): ?Attachment { @@ -64,7 +65,7 @@ class AttachmentFactory // get journal instead of transaction. if (Transaction::class === $model) { /** @var Transaction $transaction */ - $transaction = $this->user->transactions()->find((int)$data['model_id']); + $transaction = $this->user->transactions()->find((int) $data['model_id']); if (null === $transaction) { throw new FireflyException('Unexpectedly could not find transaction'); // @codeCoverageIgnore } @@ -87,7 +88,7 @@ class AttachmentFactory 'uploaded' => 0, ] ); - $notes = (string)($data['notes'] ?? ''); + $notes = (string) ($data['notes'] ?? ''); if ('' !== $notes) { $note = new Note; $note->noteable()->associate($attachment); diff --git a/app/Factory/BillFactory.php b/app/Factory/BillFactory.php index f347dbafce..79647a75e3 100644 --- a/app/Factory/BillFactory.php +++ b/app/Factory/BillFactory.php @@ -44,6 +44,7 @@ class BillFactory /** * Constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -56,15 +57,15 @@ class BillFactory /** * @param array $data * - * @return Bill|null * @throws FireflyException + * @return Bill|null */ public function create(array $data): ?Bill { /** @var TransactionCurrencyFactory $factory */ $factory = app(TransactionCurrencyFactory::class); /** @var TransactionCurrency $currency */ - $currency = $factory->find((int)($data['currency_id'] ?? null), (string)($data['currency_code'] ?? null)); + $currency = $factory->find((int) ($data['currency_id'] ?? null), (string) ($data['currency_code'] ?? null)); if (null === $currency) { $currency = app('amount')->getDefaultCurrencyByUser($this->user); @@ -86,7 +87,7 @@ class BillFactory 'active' => $data['active'] ?? true, ] ); - } catch(QueryException $e) { + } catch (QueryException $e) { Log::error($e->getMessage()); Log::error($e->getTraceAsString()); throw new FireflyException('400000: Could not store bill.'); @@ -100,15 +101,15 @@ class BillFactory } /** - * @param int|null $billId + * @param int|null $billId * @param null|string $billName * * @return Bill|null */ public function find(?int $billId, ?string $billName): ?Bill { - $billId = (int)$billId; - $billName = (string)$billName; + $billId = (int) $billId; + $billName = (string) $billName; $bill = null; // first find by ID: if ($billId > 0) { diff --git a/app/Factory/BudgetFactory.php b/app/Factory/BudgetFactory.php index f91da72d5a..ce6f9923d1 100644 --- a/app/Factory/BudgetFactory.php +++ b/app/Factory/BudgetFactory.php @@ -38,6 +38,7 @@ class BudgetFactory /** * Constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -56,8 +57,8 @@ class BudgetFactory */ public function find(?int $budgetId, ?string $budgetName): ?Budget { - $budgetId = (int)$budgetId; - $budgetName = (string)$budgetName; + $budgetId = (int) $budgetId; + $budgetName = (string) $budgetName; if (0 === $budgetId && '' === $budgetName) { return null; diff --git a/app/Factory/CategoryFactory.php b/app/Factory/CategoryFactory.php index 90c6d65213..da55ff6cde 100644 --- a/app/Factory/CategoryFactory.php +++ b/app/Factory/CategoryFactory.php @@ -40,6 +40,7 @@ class CategoryFactory /** * Constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -63,13 +64,13 @@ class CategoryFactory * @param int|null $categoryId * @param null|string $categoryName * - * @return Category|null * @throws FireflyException + * @return Category|null */ public function findOrCreate(?int $categoryId, ?string $categoryName): ?Category { - $categoryId = (int)$categoryId; - $categoryName = (string)$categoryName; + $categoryId = (int) $categoryId; + $categoryName = (string) $categoryName; Log::debug(sprintf('Going to find category with ID %d and name "%s"', $categoryId, $categoryName)); diff --git a/app/Factory/PiggyBankEventFactory.php b/app/Factory/PiggyBankEventFactory.php index ffe8bd35c3..3eee4e3019 100644 --- a/app/Factory/PiggyBankEventFactory.php +++ b/app/Factory/PiggyBankEventFactory.php @@ -39,6 +39,7 @@ class PiggyBankEventFactory { /** * Constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -60,6 +61,7 @@ class PiggyBankEventFactory Log::debug(sprintf('Now in PiggyBankEventCreate for a %s', $journal->transactionType->type)); if (null === $piggyBank) { Log::debug('Piggy bank is null'); + return null; } diff --git a/app/Factory/PiggyBankFactory.php b/app/Factory/PiggyBankFactory.php index b53412c11d..0a67e45240 100644 --- a/app/Factory/PiggyBankFactory.php +++ b/app/Factory/PiggyBankFactory.php @@ -38,6 +38,7 @@ class PiggyBankFactory /** * Constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -56,8 +57,8 @@ class PiggyBankFactory */ public function find(?int $piggyBankId, ?string $piggyBankName): ?PiggyBank { - $piggyBankId = (int)$piggyBankId; - $piggyBankName = (string)$piggyBankName; + $piggyBankId = (int) $piggyBankId; + $piggyBankName = (string) $piggyBankName; if ('' === $piggyBankName && 0 === $piggyBankId) { return null; } diff --git a/app/Factory/RecurrenceFactory.php b/app/Factory/RecurrenceFactory.php index 9ce038bd52..c406845313 100644 --- a/app/Factory/RecurrenceFactory.php +++ b/app/Factory/RecurrenceFactory.php @@ -39,16 +39,16 @@ use Log; */ class RecurrenceFactory { - /** @var User */ - private $user; - /** @var MessageBag */ private $errors; + /** @var User */ + private $user; use TransactionTypeTrait, RecurringTransactionTrait; /** * Constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -62,8 +62,8 @@ class RecurrenceFactory /** * @param array $data * - * @return Recurrence * @throws FireflyException + * @return Recurrence */ public function create(array $data): Recurrence { @@ -79,7 +79,7 @@ class RecurrenceFactory /** @var Carbon $firstDate */ $firstDate = $data['recurrence']['first_date']; - $repetitions = (int)$data['recurrence']['repetitions']; + $repetitions = (int) $data['recurrence']['repetitions']; $recurrence = new Recurrence( [ 'user_id' => $this->user->id, diff --git a/app/Factory/TagFactory.php b/app/Factory/TagFactory.php index 70e277fe60..8e8cdaf409 100644 --- a/app/Factory/TagFactory.php +++ b/app/Factory/TagFactory.php @@ -42,6 +42,7 @@ class TagFactory /** * Constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -58,9 +59,9 @@ class TagFactory */ public function create(array $data): ?Tag { - $zoomLevel = 0 === (int)$data['zoom_level'] ? null : (int)$data['zoom_level']; - $latitude = 0.0 === (float)$data['latitude'] ? null : (float)$data['latitude']; - $longitude = 0.0 === (float)$data['longitude'] ? null : (float)$data['longitude']; + $zoomLevel = 0 === (int) $data['zoom_level'] ? null : (int) $data['zoom_level']; + $latitude = 0.0 === (float) $data['latitude'] ? null : (float) $data['latitude']; + $longitude = 0.0 === (float) $data['longitude'] ? null : (float) $data['longitude']; $array = [ 'user_id' => $this->user->id, 'tag' => trim($data['tag']), diff --git a/app/Factory/TransactionCurrencyFactory.php b/app/Factory/TransactionCurrencyFactory.php index 8ae56ef91b..bd6a74ef73 100644 --- a/app/Factory/TransactionCurrencyFactory.php +++ b/app/Factory/TransactionCurrencyFactory.php @@ -52,8 +52,8 @@ class TransactionCurrencyFactory /** * @param array $data * - * @return TransactionCurrency * @throws FireflyException + * @return TransactionCurrency */ public function create(array $data): TransactionCurrency { @@ -86,8 +86,8 @@ class TransactionCurrencyFactory */ public function find(?int $currencyId, ?string $currencyCode): ?TransactionCurrency { - $currencyCode = (string)$currencyCode; - $currencyId = (int)$currencyId; + $currencyCode = (string) $currencyCode; + $currencyId = (int) $currencyId; if ('' === $currencyCode && 0 === $currencyId) { Log::debug('Cannot find anything on empty currency code and empty currency ID!'); diff --git a/app/Factory/TransactionFactory.php b/app/Factory/TransactionFactory.php index a601499a54..4ede4f858d 100644 --- a/app/Factory/TransactionFactory.php +++ b/app/Factory/TransactionFactory.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Factory; - use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Account; use FireflyIII\Models\Transaction; @@ -39,21 +38,22 @@ use Log; */ class TransactionFactory { - /** @var TransactionJournal */ - private $journal; /** @var Account */ private $account; /** @var TransactionCurrency */ private $currency; /** @var TransactionCurrency */ private $foreignCurrency; - /** @var User */ - private $user; + /** @var TransactionJournal */ + private $journal; /** @var bool */ private $reconciled; + /** @var User */ + private $user; /** * Constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -64,50 +64,14 @@ class TransactionFactory $this->reconciled = false; } - /** - * @param bool $reconciled - * @codeCoverageIgnore - */ - public function setReconciled(bool $reconciled): void - { - $this->reconciled = $reconciled; - } - - /** - * @param Account $account - * @codeCoverageIgnore - */ - public function setAccount(Account $account): void - { - $this->account = $account; - } - - /** - * @param TransactionCurrency $currency - * @codeCoverageIgnore - */ - public function setCurrency(TransactionCurrency $currency): void - { - $this->currency = $currency; - } - - /** - * @param TransactionCurrency $foreignCurrency |null - * @codeCoverageIgnore - */ - public function setForeignCurrency(?TransactionCurrency $foreignCurrency): void - { - $this->foreignCurrency = $foreignCurrency; - } - /** * Create transaction with negative amount (for source accounts). * * @param string $amount * @param string|null $foreignAmount * - * @return Transaction * @throws FireflyException + * @return Transaction */ public function createNegative(string $amount, ?string $foreignAmount): Transaction { @@ -127,8 +91,8 @@ class TransactionFactory * @param string $amount * @param string|null $foreignAmount * - * @return Transaction * @throws FireflyException + * @return Transaction */ public function createPositive(string $amount, ?string $foreignAmount): Transaction { @@ -138,12 +102,43 @@ class TransactionFactory if (null !== $foreignAmount) { $foreignAmount = app('steam')->positive($foreignAmount); } + return $this->create(app('steam')->positive($amount), $foreignAmount); } + /** + * @param Account $account + * + * @codeCoverageIgnore + */ + public function setAccount(Account $account): void + { + $this->account = $account; + } + + /** + * @param TransactionCurrency $currency + * + * @codeCoverageIgnore + */ + public function setCurrency(TransactionCurrency $currency): void + { + $this->currency = $currency; + } + + /** + * @param TransactionCurrency $foreignCurrency |null + * + * @codeCoverageIgnore + */ + public function setForeignCurrency(?TransactionCurrency $foreignCurrency): void + { + $this->foreignCurrency = $foreignCurrency; + } /** * @param TransactionJournal $journal + * * @codeCoverageIgnore */ public function setJournal(TransactionJournal $journal): void @@ -151,8 +146,19 @@ class TransactionFactory $this->journal = $journal; } + /** + * @param bool $reconciled + * + * @codeCoverageIgnore + */ + public function setReconciled(bool $reconciled): void + { + $this->reconciled = $reconciled; + } + /** * @param User $user + * * @codeCoverageIgnore */ public function setUser(User $user): void @@ -164,8 +170,8 @@ class TransactionFactory * @param string $amount * @param string|null $foreignAmount * - * @return Transaction * @throws FireflyException + * @return Transaction */ private function create(string $amount, ?string $foreignAmount): Transaction { @@ -200,7 +206,11 @@ class TransactionFactory if (null !== $result) { Log::debug( sprintf( - 'Created transaction #%d (%s %s, account %s), part of journal #%d', $result->id, $this->currency->code, $amount, $this->account->name, + 'Created transaction #%d (%s %s, account %s), part of journal #%d', + $result->id, + $this->currency->code, + $amount, + $this->account->name, $this->journal->id ) ); @@ -209,7 +219,6 @@ class TransactionFactory if (null !== $this->foreignCurrency && null !== $foreignAmount && $this->foreignCurrency->id !== $this->currency->id && '' !== $foreignAmount) { $result->foreign_currency_id = $this->foreignCurrency->id; $result->foreign_amount = $foreignAmount; - } $result->save(); } diff --git a/app/Factory/TransactionGroupFactory.php b/app/Factory/TransactionGroupFactory.php index 045cdec5e4..34d5a2db8d 100644 --- a/app/Factory/TransactionGroupFactory.php +++ b/app/Factory/TransactionGroupFactory.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Factory; use FireflyIII\Exceptions\DuplicateTransactionException; -use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\TransactionGroup; use FireflyIII\User; use Log; @@ -54,8 +53,8 @@ class TransactionGroupFactory * * @param array $data * - * @return TransactionGroup * @throws DuplicateTransactionException + * @return TransactionGroup */ public function create(array $data): TransactionGroup { @@ -63,12 +62,12 @@ class TransactionGroupFactory $this->journalFactory->setErrorOnHash($data['error_if_duplicate_hash'] ?? false); try { $collection = $this->journalFactory->create($data); - } catch(DuplicateTransactionException $e) { + } catch (DuplicateTransactionException $e) { Log::warning('GroupFactory::create() caught journalFactory::create() with a duplicate!'); throw new DuplicateTransactionException($e->getMessage()); } - $title = $data['group_title'] ?? null; - $title = '' === $title ? null : $title; + $title = $data['group_title'] ?? null; + $title = '' === $title ? null : $title; if (null !== $title) { $title = substr($title, 0, 1000); diff --git a/app/Factory/TransactionJournalFactory.php b/app/Factory/TransactionJournalFactory.php index b0a855b190..6c8aca89f5 100644 --- a/app/Factory/TransactionJournalFactory.php +++ b/app/Factory/TransactionJournalFactory.php @@ -64,6 +64,8 @@ class TransactionJournalFactory private $billRepository; /** @var CurrencyRepositoryInterface */ private $currencyRepository; + /** @var bool */ + private $errorOnHash; /** @var array */ private $fields; /** @var PiggyBankEventFactory */ @@ -76,8 +78,6 @@ class TransactionJournalFactory private $typeRepository; /** @var User The user */ private $user; - /** @var bool */ - private $errorOnHash; /** * Constructor. @@ -125,9 +125,9 @@ class TransactionJournalFactory * * @param array $data * - * @return Collection * @throws DuplicateTransactionException * @throws FireflyException + * @return Collection */ public function create(array $data): Collection { @@ -171,6 +171,17 @@ class TransactionJournalFactory return $collection; } + /** + * @param bool $errorOnHash + */ + public function setErrorOnHash(bool $errorOnHash): void + { + $this->errorOnHash = $errorOnHash; + if (true === $errorOnHash) { + Log::info('Will trigger duplication alert for this journal.'); + } + } + /** * Set the user. * @@ -199,7 +210,7 @@ class TransactionJournalFactory $set = [ 'journal' => $journal, 'name' => $field, - 'data' => (string)($data[$field] ?? ''), + 'data' => (string) ($data[$field] ?? ''), ]; Log::debug(sprintf('Going to store meta-field "%s", with value "%s".', $set['name'], $set['data'])); @@ -209,12 +220,32 @@ class TransactionJournalFactory $factory->updateOrCreate($set); } + /** + * Set foreign currency to NULL if it's the same as the normal currency: + * + * @param TransactionCurrency $currency + * @param TransactionCurrency|null $foreignCurrency + * + * @return TransactionCurrency|null + */ + private function compareCurrencies(?TransactionCurrency $currency, ?TransactionCurrency $foreignCurrency): ?TransactionCurrency + { + if (null === $currency) { + return null; + } + if (null !== $foreignCurrency && $foreignCurrency->id === $currency->id) { + return null; + } + + return $foreignCurrency; + } + /** * @param NullArrayObject $row * - * @return TransactionJournal|null * @throws FireflyException * @throws DuplicateTransactionException + * @return TransactionJournal|null */ private function createJournal(NullArrayObject $row): ?TransactionJournal { @@ -226,18 +257,15 @@ class TransactionJournalFactory $type = $this->typeRepository->findTransactionType(null, $row['type']); $carbon = $row['date'] ?? new Carbon; $order = $row['order'] ?? 0; - $currency = $this->currencyRepository->findCurrency((int)$row['currency_id'], $row['currency_code']); + $currency = $this->currencyRepository->findCurrency((int) $row['currency_id'], $row['currency_code']); $foreignCurrency = $this->currencyRepository->findCurrencyNull($row['foreign_currency_id'], $row['foreign_currency_code']); - $bill = $this->billRepository->findBill((int)$row['bill_id'], $row['bill_name']); + $bill = $this->billRepository->findBill((int) $row['bill_id'], $row['bill_name']); $billId = TransactionType::WITHDRAWAL === $type->type && null !== $bill ? $bill->id : null; - $description = app('steam')->cleanString((string)$row['description']); + $description = app('steam')->cleanString((string) $row['description']); /** Manipulate basic fields */ $carbon->setTimezone(config('app.timezone')); - /** Get source + destination account */ - Log::debug(sprintf('Currency is #%d (%s)', $currency->id, $currency->code)); - try { // validate source and destination using a new Validator. $this->validateAccounts($row); @@ -249,7 +277,7 @@ class TransactionJournalFactory } /** create or get source and destination accounts */ $sourceInfo = [ - 'id' => (int)$row['source_id'], + 'id' => (int) $row['source_id'], 'name' => $row['source_name'], 'iban' => $row['source_iban'], 'number' => $row['source_number'], @@ -257,7 +285,7 @@ class TransactionJournalFactory ]; $destInfo = [ - 'id' => (int)$row['destination_id'], + 'id' => (int) $row['destination_id'], 'name' => $row['destination_name'], 'iban' => $row['destination_iban'], 'number' => $row['destination_number'], @@ -268,55 +296,10 @@ class TransactionJournalFactory $sourceAccount = $this->getAccount($type->type, 'source', $sourceInfo); $destinationAccount = $this->getAccount($type->type, 'destination', $destInfo); - - // TODO AFTER 4.8,0 better handling below: - - /** double check currencies. */ - $sourceCurrency = $currency; - $destCurrency = $currency; - $sourceForeignCurrency = $foreignCurrency; - $destForeignCurrency = $foreignCurrency; - - if (TransactionType::WITHDRAWAL === $type->type) { - // make sure currency is correct. - $currency = $this->getCurrency($currency, $sourceAccount); - // make sure foreign currency != currency. - if (null !== $foreignCurrency && $foreignCurrency->id === $currency->id) { - $foreignCurrency = null; - } - $sourceCurrency = $currency; - $destCurrency = $currency; - $sourceForeignCurrency = $foreignCurrency; - $destForeignCurrency = $foreignCurrency; - } - if (TransactionType::DEPOSIT === $type->type) { - // make sure currency is correct. - $currency = $this->getCurrency($currency, $destinationAccount); - // make sure foreign currency != currency. - if (null !== $foreignCurrency && $foreignCurrency->id === $currency->id) { - $foreignCurrency = null; - } - - $sourceCurrency = $currency; - $destCurrency = $currency; - $sourceForeignCurrency = $foreignCurrency; - $destForeignCurrency = $foreignCurrency; - } - - if (TransactionType::TRANSFER === $type->type) { - // get currencies - $currency = $this->getCurrency($currency, $sourceAccount); - $foreignCurrency = $this->getCurrency($foreignCurrency, $destinationAccount); - - $sourceCurrency = $currency; - $destCurrency = $currency; - $sourceForeignCurrency = $foreignCurrency; - $destForeignCurrency = $foreignCurrency; - } - - $description = '' === $description ? '(empty description)' : $description; - $description = substr($description, 0, 255); - + $currency = $this->getCurrencyByAccount($type->type, $currency, $sourceAccount, $destinationAccount); + $foreignCurrency = $this->compareCurrencies($currency, $foreignCurrency); + $foreignCurrency = $this->getForeignByAccount($type->type, $foreignCurrency, $destinationAccount); + $description = $this->getDescription($description); /** Create a basic journal. */ $journal = TransactionJournal::create( @@ -325,7 +308,7 @@ class TransactionJournalFactory 'transaction_type_id' => $type->id, 'bill_id' => $billId, 'transaction_currency_id' => $currency->id, - 'description' => substr($description,0,1000), + 'description' => substr($description, 0, 1000), 'date' => $carbon->format('Y-m-d H:i:s'), 'order' => $order, 'tag_count' => 0, @@ -340,11 +323,11 @@ class TransactionJournalFactory $transactionFactory->setUser($this->user); $transactionFactory->setJournal($journal); $transactionFactory->setAccount($sourceAccount); - $transactionFactory->setCurrency($sourceCurrency); - $transactionFactory->setForeignCurrency($sourceForeignCurrency); + $transactionFactory->setCurrency($currency); + $transactionFactory->setForeignCurrency($foreignCurrency); $transactionFactory->setReconciled($row['reconciled'] ?? false); try { - $negative = $transactionFactory->createNegative((string)$row['amount'], (string)$row['foreign_amount']); + $negative = $transactionFactory->createNegative((string) $row['amount'], (string) $row['foreign_amount']); } catch (FireflyException $e) { Log::error('Exception creating negative transaction.'); Log::error($e->getMessage()); @@ -359,11 +342,11 @@ class TransactionJournalFactory $transactionFactory->setUser($this->user); $transactionFactory->setJournal($journal); $transactionFactory->setAccount($destinationAccount); - $transactionFactory->setCurrency($destCurrency); - $transactionFactory->setForeignCurrency($destForeignCurrency); + $transactionFactory->setCurrency($currency); + $transactionFactory->setForeignCurrency($foreignCurrency); $transactionFactory->setReconciled($row['reconciled'] ?? false); try { - $transactionFactory->createPositive((string)$row['amount'], (string)$row['foreign_amount']); + $transactionFactory->createPositive((string) $row['amount'], (string) $row['foreign_amount']); } catch (FireflyException $e) { Log::error('Exception creating positive transaction.'); Log::error($e->getMessage()); @@ -493,6 +476,55 @@ class TransactionJournalFactory return $result; } + /** + * @param string $type + * @param TransactionCurrency|null $currency + * @param Account $source + * @param Account $destination + * + * @return TransactionCurrency + */ + private function getCurrencyByAccount(string $type, ?TransactionCurrency $currency, Account $source, Account $destination): TransactionCurrency + { + switch ($type) { + default: + case TransactionType::WITHDRAWAL: + case TransactionType::TRANSFER: + return $this->getCurrency($currency, $source); + case TransactionType::DEPOSIT: + return $this->getCurrency($currency, $destination); + + } + } + + /** + * @param string $description + * + * @return string + */ + private function getDescription(string $description): string + { + $description = '' === $description ? '(empty description)' : $description; + + return substr($description, 0, 255); + } + + /** + * @param string $type + * @param TransactionCurrency|null $foreignCurrency + * @param Account $destination + * + * @return TransactionCurrency|null + */ + private function getForeignByAccount(string $type, ?TransactionCurrency $foreignCurrency, Account $destination): ?TransactionCurrency + { + if (TransactionType::TRANSFER === $type) { + return $this->getCurrency($foreignCurrency, $destination); + } + + return $foreignCurrency; + } + /** * @param NullArrayObject $row * @@ -506,7 +538,7 @@ class TransactionJournalFactory $json = json_encode($dataRow); if (false === $json) { // @codeCoverageIgnoreStart - $json = json_encode((string)microtime()); + $json = json_encode((string) microtime()); Log::error(sprintf('Could not hash the original row! %s', json_last_error_msg()), $dataRow); // @codeCoverageIgnoreEnd } @@ -542,7 +574,7 @@ class TransactionJournalFactory return; } - $piggyBank = $this->piggyRepository->findPiggyBank((int)$data['piggy_bank_id'], $data['piggy_bank_name']); + $piggyBank = $this->piggyRepository->findPiggyBank((int) $data['piggy_bank_id'], $data['piggy_bank_name']); if (null !== $piggyBank) { $this->piggyEventFactory->create($journal, $piggyBank); @@ -565,7 +597,7 @@ class TransactionJournalFactory $this->accountValidator->setTransactionType($transactionType); // validate source account. - $sourceId = isset($data['source_id']) ? (int)$data['source_id'] : null; + $sourceId = isset($data['source_id']) ? (int) $data['source_id'] : null; $sourceName = $data['source_name'] ?? null; $validSource = $this->accountValidator->validateSource($sourceId, $sourceName); @@ -575,7 +607,7 @@ class TransactionJournalFactory } Log::debug('Source seems valid.'); // validate destination account - $destinationId = isset($data['destination_id']) ? (int)$data['destination_id'] : null; + $destinationId = isset($data['destination_id']) ? (int) $data['destination_id'] : null; $destinationName = $data['destination_name'] ?? null; $validDestination = $this->accountValidator->validateDestination($destinationId, $destinationName); // do something with result: @@ -584,16 +616,5 @@ class TransactionJournalFactory } } - /** - * @param bool $errorOnHash - */ - public function setErrorOnHash(bool $errorOnHash): void - { - $this->errorOnHash = $errorOnHash; - if (true === $errorOnHash) { - Log::info('Will trigger duplication alert for this journal.'); - } - } - } diff --git a/app/Factory/TransactionJournalMetaFactory.php b/app/Factory/TransactionJournalMetaFactory.php index 6e696196e4..88b0059749 100644 --- a/app/Factory/TransactionJournalMetaFactory.php +++ b/app/Factory/TransactionJournalMetaFactory.php @@ -36,6 +36,7 @@ class TransactionJournalMetaFactory { /** * Constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -71,7 +72,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) { diff --git a/app/Factory/TransactionTypeFactory.php b/app/Factory/TransactionTypeFactory.php index eb509e1dda..45b0414c94 100644 --- a/app/Factory/TransactionTypeFactory.php +++ b/app/Factory/TransactionTypeFactory.php @@ -35,6 +35,7 @@ class TransactionTypeFactory { /** * Constructor. + * * @codeCoverageIgnore */ public function __construct() diff --git a/app/Generator/Chart/Basic/ChartJsGenerator.php b/app/Generator/Chart/Basic/ChartJsGenerator.php index 6a8e160dcd..943ef66e5f 100644 --- a/app/Generator/Chart/Basic/ChartJsGenerator.php +++ b/app/Generator/Chart/Basic/ChartJsGenerator.php @@ -63,7 +63,7 @@ class ChartJsGenerator implements GeneratorInterface $amounts = array_column($data, 'amount'); $next = next($amounts); $sortFlag = SORT_ASC; - if (!is_bool($next) && 1 === bccomp((string)$next, '0')) { + if (!is_bool($next) && 1 === bccomp((string) $next, '0')) { $sortFlag = SORT_DESC; } array_multisort($amounts, $sortFlag, $data); @@ -72,7 +72,7 @@ class ChartJsGenerator implements GeneratorInterface $index = 0; foreach ($data as $key => $valueArray) { // make larger than 0 - $chartData['datasets'][0]['data'][] = (float)app('steam')->positive((string)$valueArray['amount']); + $chartData['datasets'][0]['data'][] = (float) app('steam')->positive((string) $valueArray['amount']); $chartData['datasets'][0]['backgroundColor'][] = ChartColour::getColour($index); $chartData['datasets'][0]['currency_symbol'][] = $valueArray['currency_symbol']; $chartData['labels'][] = $key; @@ -178,7 +178,7 @@ class ChartJsGenerator implements GeneratorInterface // different sort when values are positive and when they're negative. asort($data); $next = next($data); - if (!is_bool($next) && 1 === bccomp((string)$next, '0')) { + if (!is_bool($next) && 1 === bccomp((string) $next, '0')) { // next is positive, sort other way around. arsort($data); } @@ -187,7 +187,7 @@ class ChartJsGenerator implements GeneratorInterface $index = 0; foreach ($data as $key => $value) { // make larger than 0 - $chartData['datasets'][0]['data'][] = (float)app('steam')->positive((string)$value); + $chartData['datasets'][0]['data'][] = (float) app('steam')->positive((string) $value); $chartData['datasets'][0]['backgroundColor'][] = ChartColour::getColour($index); $chartData['labels'][] = $key; diff --git a/app/Generator/Chart/Basic/GeneratorInterface.php b/app/Generator/Chart/Basic/GeneratorInterface.php index 3bf8331f19..b92994f858 100644 --- a/app/Generator/Chart/Basic/GeneratorInterface.php +++ b/app/Generator/Chart/Basic/GeneratorInterface.php @@ -46,7 +46,7 @@ interface GeneratorInterface * 'fill' => if to fill a line? optional, will not be included when unused. * 'entries' => * [ - * 'label-of-entry' => 'value' + * key => [value => x, 'currency_symbol' => 'x'] * ] * ] * 1: [ @@ -56,7 +56,7 @@ interface GeneratorInterface * 'fill' => if to fill a line? optional, will not be included when unused. * 'entries' => * [ - * 'label-of-entry' => 'value' + * key => [value => x, 'currency_symbol' => 'x'] * ] * ] * diff --git a/app/Generator/Report/Account/MonthReportGenerator.php b/app/Generator/Report/Account/MonthReportGenerator.php index d4538afee6..34c7c63b74 100644 --- a/app/Generator/Report/Account/MonthReportGenerator.php +++ b/app/Generator/Report/Account/MonthReportGenerator.php @@ -52,14 +52,14 @@ class MonthReportGenerator implements ReportGeneratorInterface public function generate(): string { $accountIds = implode(',', $this->accounts->pluck('id')->toArray()); - $doubleIds = implode(',', $this->expense->pluck('id')->toArray()); + $doubleIds = implode(',', $this->expense->pluck('id')->toArray()); $reportType = 'account'; $preferredPeriod = $this->preferredPeriod(); try { $result = view('reports.double.report', compact('accountIds', 'reportType', 'doubleIds', 'preferredPeriod')) ->with('start', $this->start)->with('end', $this->end) - ->with('doubles', $this->expense) - ->render(); + ->with('doubles', $this->expense) + ->render(); } catch (Throwable $e) { Log::error(sprintf('Cannot render reports.double.report: %s', $e->getMessage())); $result = sprintf('Could not render report view: %s', $e->getMessage()); diff --git a/app/Generator/Report/Audit/MonthReportGenerator.php b/app/Generator/Report/Audit/MonthReportGenerator.php index e35e46b570..55757386c3 100644 --- a/app/Generator/Report/Audit/MonthReportGenerator.php +++ b/app/Generator/Report/Audit/MonthReportGenerator.php @@ -51,9 +51,9 @@ class MonthReportGenerator implements ReportGeneratorInterface /** * Generates the report. * - * @return string * @throws FireflyException * @codeCoverageIgnore + * @return string */ public function generate(): string { @@ -100,9 +100,9 @@ class MonthReportGenerator implements ReportGeneratorInterface * @param Account $account * @param Carbon $date * + * @throws FireflyException * @return array * - * @throws FireflyException */ public function getAuditReport(Account $account, Carbon $date): array { @@ -117,7 +117,7 @@ class MonthReportGenerator implements ReportGeneratorInterface /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); $collector->setAccounts(new Collection([$account]))->setRange($this->start, $this->end)->withAccountInformation() - ->withBudgetInformation()->withCategoryInformation()->withBillInformation(); + ->withBudgetInformation()->withCategoryInformation()->withBillInformation(); $journals = $collector->getExtractedJournals(); $journals = array_reverse($journals, true); $dayBeforeBalance = app('steam')->balance($account, $date); @@ -159,9 +159,9 @@ class MonthReportGenerator implements ReportGeneratorInterface 'journals' => $journals, 'currency' => $currency, 'exists' => count($journals) > 0, - 'end' => $this->end->formatLocalized((string)trans('config.month_and_day')), + 'end' => $this->end->formatLocalized((string) trans('config.month_and_day')), 'endBalance' => app('steam')->balance($account, $this->end), - 'dayBefore' => $date->formatLocalized((string)trans('config.month_and_day')), + 'dayBefore' => $date->formatLocalized((string) trans('config.month_and_day')), 'dayBeforeBalance' => $dayBeforeBalance, ]; diff --git a/app/Generator/Report/Category/MonthReportGenerator.php b/app/Generator/Report/Category/MonthReportGenerator.php index 4836354b38..1bc8be9b89 100644 --- a/app/Generator/Report/Category/MonthReportGenerator.php +++ b/app/Generator/Report/Category/MonthReportGenerator.php @@ -76,7 +76,7 @@ class MonthReportGenerator implements ReportGeneratorInterface // render! try { - return view('reports.category.month', compact('accountIds', 'categoryIds', 'reportType',)) + return view('reports.category.month', compact('accountIds', 'categoryIds', 'reportType', )) ->with('start', $this->start)->with('end', $this->end) ->with('categories', $this->categories) ->with('accounts', $this->accounts) diff --git a/app/Generator/Report/ReportGeneratorFactory.php b/app/Generator/Report/ReportGeneratorFactory.php index ceeb641a0f..011cf97fc1 100644 --- a/app/Generator/Report/ReportGeneratorFactory.php +++ b/app/Generator/Report/ReportGeneratorFactory.php @@ -39,9 +39,9 @@ class ReportGeneratorFactory * @param Carbon $start * @param Carbon $end * + * @throws FireflyException * @return ReportGeneratorInterface * - * @throws FireflyException */ public static function reportGenerator(string $type, Carbon $start, Carbon $end): ReportGeneratorInterface { diff --git a/app/Generator/Report/Tag/MonthReportGenerator.php b/app/Generator/Report/Tag/MonthReportGenerator.php index 54784d10e7..c7b6b32a60 100644 --- a/app/Generator/Report/Tag/MonthReportGenerator.php +++ b/app/Generator/Report/Tag/MonthReportGenerator.php @@ -76,7 +76,8 @@ class MonthReportGenerator implements ReportGeneratorInterface // render! try { $result = view( - 'reports.tag.month', compact('accountIds', 'reportType', 'tagIds') + 'reports.tag.month', + compact('accountIds', 'reportType', '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())); @@ -177,6 +178,4 @@ class MonthReportGenerator implements ReportGeneratorInterface return $this; } - - } diff --git a/app/Handlers/Events/APIEventHandler.php b/app/Handlers/Events/APIEventHandler.php index 31daf32fde..649dc9804c 100644 --- a/app/Handlers/Events/APIEventHandler.php +++ b/app/Handlers/Events/APIEventHandler.php @@ -49,7 +49,7 @@ class APIEventHandler { /** @var UserRepositoryInterface $repository */ $repository = app(UserRepositoryInterface::class); - $user = $repository->findNull((int)$event->userId); + $user = $repository->findNull((int) $event->userId); if (null !== $user) { $email = $user->email; $ipAddress = Request::ip(); diff --git a/app/Handlers/Events/UpdatedGroupEventHandler.php b/app/Handlers/Events/UpdatedGroupEventHandler.php index f478f9983e..f9b0fac623 100644 --- a/app/Handlers/Events/UpdatedGroupEventHandler.php +++ b/app/Handlers/Events/UpdatedGroupEventHandler.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace FireflyIII\Handlers\Events; use FireflyIII\Events\UpdatedTransactionGroup; -use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\TransactionJournal; use FireflyIII\TransactionRules\Engine\RuleEngine; diff --git a/app/Handlers/Events/VersionCheckEventHandler.php b/app/Handlers/Events/VersionCheckEventHandler.php index a1c57662a8..2af01ca01f 100644 --- a/app/Handlers/Events/VersionCheckEventHandler.php +++ b/app/Handlers/Events/VersionCheckEventHandler.php @@ -25,9 +25,7 @@ declare(strict_types=1); namespace FireflyIII\Handlers\Events; -use Carbon\Carbon; use FireflyIII\Events\RequestedVersionCheckStatus; -use FireflyIII\Exceptions\FireflyException; use FireflyIII\Helpers\Update\UpdateTrait; use FireflyIII\Models\Configuration; use FireflyIII\Repositories\User\UserRepositoryInterface; @@ -53,9 +51,10 @@ class VersionCheckEventHandler // should not check for updates: $permission = app('fireflyconfig')->get('permission_update_check', -1); - $value = (int)$permission->data; + $value = (int) $permission->data; if (1 !== $value) { Log::info('Update check is not enabled.'); + return; } @@ -65,6 +64,7 @@ class VersionCheckEventHandler $user = $event->user; if (!$repository->hasRole($user, 'owner')) { Log::debug('User is not admin, done.'); + return; } @@ -75,11 +75,12 @@ class VersionCheckEventHandler Log::debug(sprintf('Last check time is %d, current time is %d, difference is %d', $lastCheckTime->data, $now, $diff)); if ($diff < 604800) { Log::debug(sprintf('Checked for updates less than a week ago (on %s).', date('Y-m-d H:i:s', $lastCheckTime->data))); + 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(); session()->flash($release['level'], $release['message']); app('fireflyconfig')->set('last_update_check', time()); diff --git a/app/Helpers/Attachments/AttachmentHelper.php b/app/Helpers/Attachments/AttachmentHelper.php index 9512d2d91d..261363410c 100644 --- a/app/Helpers/Attachments/AttachmentHelper.php +++ b/app/Helpers/Attachments/AttachmentHelper.php @@ -26,7 +26,9 @@ use Crypt; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Attachment; use Illuminate\Contracts\Encryption\DecryptException; +use Illuminate\Contracts\Encryption\EncryptException; use Illuminate\Contracts\Filesystem\FileNotFoundException; +use Illuminate\Contracts\Filesystem\Filesystem; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Storage; @@ -50,18 +52,19 @@ class AttachmentHelper implements AttachmentHelperInterface /** @var int Max upload size. */ protected $maxUploadSize = 0; - /** @var \Illuminate\Contracts\Filesystem\Filesystem The disk where attachments are stored. */ + /** @var Filesystem The disk where attachments are stored. */ protected $uploadDisk; /** * AttachmentHelper constructor. + * * @codeCoverageIgnore */ public function __construct() { - $this->maxUploadSize = (int)config('firefly.maxUploadSize'); - $this->allowedMimes = (array)config('firefly.allowedMimes'); + $this->maxUploadSize = (int) config('firefly.maxUploadSize'); + $this->allowedMimes = (array) config('firefly.allowedMimes'); $this->errors = new MessageBag; $this->messages = new MessageBag; $this->attachments = new Collection; @@ -104,16 +107,18 @@ class AttachmentHelper implements AttachmentHelperInterface * Returns the file path relative to upload disk for an attachment, * * @param Attachment $attachment + * * @codeCoverageIgnore * @return string */ public function getAttachmentLocation(Attachment $attachment): string { - return sprintf('%sat-%d.data', DIRECTORY_SEPARATOR, (int)$attachment->id); + return sprintf('%sat-%d.data', DIRECTORY_SEPARATOR, (int) $attachment->id); } /** * Get all attachments. + * * @codeCoverageIgnore * @return Collection */ @@ -198,8 +203,8 @@ class AttachmentHelper implements AttachmentHelperInterface * @param object $model * @param array|null $files * - * @return bool * @throws FireflyException + * @return bool */ public function saveAttachmentsForModel(object $model, ?array $files): bool { @@ -242,7 +247,7 @@ class AttachmentHelper implements AttachmentHelperInterface $count = $model->user->attachments()->where('md5', $md5)->where('attachable_id', $model->id)->where('attachable_type', $class)->count(); $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; @@ -257,9 +262,9 @@ class AttachmentHelper implements AttachmentHelperInterface * @param UploadedFile $file * @param Model $model * - * @return Attachment|null - * @throws \Illuminate\Contracts\Encryption\EncryptException + * @throws EncryptException * @throws FireflyException + * @return Attachment|null */ protected function processFile(UploadedFile $file, Model $model): ?Attachment { @@ -286,7 +291,7 @@ class AttachmentHelper implements AttachmentHelperInterface throw new FireflyException('Cannot upload empty or non-existent file.'); // @codeCoverageIgnore } - $content = $fileObject->fread($file->getSize()); + $content = $fileObject->fread($file->getSize()); Log::debug(sprintf('Full file length is %d and upload size is %d.', strlen($content), $file->getSize())); // store it: @@ -296,7 +301,7 @@ class AttachmentHelper implements AttachmentHelperInterface $this->attachments->push($attachment); $name = e($file->getClientOriginalName()); // add message: - $msg = (string)trans('validation.file_attached', ['name' => $name]); + $msg = (string) trans('validation.file_attached', ['name' => $name]); $this->messages->add('attachments', $msg); } @@ -320,7 +325,7 @@ class AttachmentHelper implements AttachmentHelperInterface $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); @@ -345,7 +350,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); diff --git a/app/Helpers/Collector/GroupCollector.php b/app/Helpers/Collector/GroupCollector.php index 410f0a7519..ce4149c5a0 100644 --- a/app/Helpers/Collector/GroupCollector.php +++ b/app/Helpers/Collector/GroupCollector.php @@ -58,10 +58,12 @@ class GroupCollector implements GroupCollectorInterface private $hasBudgetInformation; /** @var bool Will be true if query result contains category info. */ private $hasCatInformation; - /** @var bool Will be true of the query has the tag info tables joined. */ - private $hasJoinedTagTables; /** @var bool Will be true for attachments */ private $hasJoinedAttTables; + /** @var bool Will be true of the query has the tag info tables joined. */ + private $hasJoinedTagTables; + /** @var array */ + private $integerFields; /** @var int The maximum number of results. */ private $limit; /** @var int The page to return. */ @@ -72,8 +74,6 @@ class GroupCollector implements GroupCollectorInterface private $total; /** @var User The user object. */ private $user; - /** @var array */ - private $integerFields; /** * Group collector constructor. @@ -210,7 +210,6 @@ class GroupCollector implements GroupCollectorInterface */ public function dumpQuery(): void { - echo $this->query->toSql(); echo '
';
         print_r($this->query->getBindings());
@@ -304,7 +303,6 @@ class GroupCollector implements GroupCollectorInterface
         }
 
         return $collection;
-
     }
 
     /**
@@ -331,7 +329,7 @@ class GroupCollector implements GroupCollectorInterface
         $sum      = '0';
         /** @var array $journal */
         foreach ($journals as $journal) {
-            $amount = (string)$journal['amount'];
+            $amount = (string) $journal['amount'];
             $sum    = bcadd($sum, $amount);
         }
 
@@ -510,6 +508,24 @@ class GroupCollector implements GroupCollectorInterface
         return $this;
     }
 
+    /**
+     * Collect transactions created on a specific date.
+     *
+     * @param Carbon $date
+     *
+     * @return GroupCollectorInterface
+     */
+    public function setCreatedAt(Carbon $date): GroupCollectorInterface
+    {
+        $after  = $date->format('Y-m-d 00:00:00');
+        $before = $date->format('Y-m-d 23:59:59');
+        $this->query->where('transaction_journals.created_at', '>=', $after);
+        $this->query->where('transaction_journals.created_at', '<=', $before);
+        Log::debug(sprintf('GroupCollector created_at is now after %s (inclusive)', $after));
+
+        return $this;
+    }
+
     /**
      * Limit results to a specific currency, either foreign or normal one.
      *
@@ -742,6 +758,24 @@ class GroupCollector implements GroupCollectorInterface
         return $this;
     }
 
+    /**
+     * Collect transactions updated on a specific date.
+     *
+     * @param Carbon $date
+     *
+     * @return GroupCollectorInterface
+     */
+    public function setUpdatedAt(Carbon $date): GroupCollectorInterface
+    {
+        $after  = $date->format('Y-m-d 00:00:00');
+        $before = $date->format('Y-m-d 23:59:59');
+        $this->query->where('transaction_journals.updated_at', '>=', $after);
+        $this->query->where('transaction_journals.updated_at', '<=', $before);
+        Log::debug(sprintf('GroupCollector created_at is now after %s (inclusive)', $after));
+
+        return $this;
+    }
+
     /**
      * Set the user object and start the query.
      *
@@ -757,6 +791,43 @@ class GroupCollector implements GroupCollectorInterface
         return $this;
     }
 
+    /**
+     * Either account can be set, but NOT both. This effectively excludes internal transfers.
+     *
+     * @param Collection $accounts
+     *
+     * @return GroupCollectorInterface
+     */
+    public function setXorAccounts(Collection $accounts): GroupCollectorInterface
+    {
+        if ($accounts->count() > 0) {
+            $accountIds = $accounts->pluck('id')->toArray();
+            $this->query->where(
+                static function (EloquentBuilder $q1) use ($accountIds) {
+                    // sourceAccount is in the set, and destination is NOT.
+
+                    $q1->where(
+                        static function (EloquentBuilder $q2) use ($accountIds) {
+                            $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) {
+                            $q3->whereNotIn('source.account_id', $accountIds);
+                            $q3->whereIn('destination.account_id', $accountIds);
+                        }
+                    );
+                }
+            );
+
+            app('log')->debug(sprintf('GroupCollector: setXorAccounts: %s', implode(', ', $accountIds)));
+        }
+
+        return $this;
+    }
+
     /**
      * Automatically include all stuff required to make API calls work.
      *
@@ -810,6 +881,17 @@ class GroupCollector implements GroupCollectorInterface
         return $this;
     }
 
+    /**
+     * @inheritDoc
+     */
+    public function withAttachmentInformation(): GroupCollectorInterface
+    {
+        $this->fields[] = 'attachments.id as attachment_id';
+        $this->joinAttachmentTables();
+
+        return $this;
+    }
+
     /**
      * Will include bill name + ID, if any.
      *
@@ -933,25 +1015,12 @@ class GroupCollector implements GroupCollectorInterface
     private function convertToInteger(array $array): array
     {
         foreach ($this->integerFields as $field) {
-            $array[$field] = isset($array[$field]) ? (int)$array[$field] : null;
+            $array[$field] = isset($array[$field]) ? (int) $array[$field] : null;
         }
 
         return $array;
     }
 
-    /**
-     * Join table to get tag information.
-     */
-    private function joinTagTables(): void
-    {
-        if (false === $this->hasJoinedTagTables) {
-            // join some extra tables:
-            $this->hasJoinedTagTables = true;
-            $this->query->leftJoin('tag_transaction_journal', 'tag_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id');
-            $this->query->leftJoin('tags', 'tag_transaction_journal.tag_id', '=', 'tags.id');
-        }
-    }
-
     /**
      * Join table to get attachment information.
      */
@@ -971,33 +1040,16 @@ class GroupCollector implements GroupCollectorInterface
     }
 
     /**
-     * @param array              $existingJournal
-     * @param TransactionJournal $newJournal
-     *
-     * @return array
+     * Join table to get tag information.
      */
-    private function mergeTags(array $existingJournal, TransactionJournal $newJournal): array
+    private function joinTagTables(): void
     {
-        $newArray = $newJournal->toArray();
-        if (isset($newArray['tag_id'])) { // assume the other fields are present as well.
-            $tagId = (int)$newJournal['tag_id'];
-
-            $tagDate = null;
-            try {
-                $tagDate = Carbon::parse($newArray['tag_date']);
-            } catch (InvalidDateException $e) {
-                Log::debug(sprintf('Could not parse date: %s', $e->getMessage()));
-            }
-
-            $existingJournal['tags'][$tagId] = [
-                'id'          => (int)$newArray['tag_id'],
-                'name'        => $newArray['tag_name'],
-                'date'        => $tagDate,
-                'description' => $newArray['tag_description'],
-            ];
+        if (false === $this->hasJoinedTagTables) {
+            // join some extra tables:
+            $this->hasJoinedTagTables = true;
+            $this->query->leftJoin('tag_transaction_journal', 'tag_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id');
+            $this->query->leftJoin('tags', 'tag_transaction_journal.tag_id', '=', 'tags.id');
         }
-
-        return $existingJournal;
     }
 
     /**
@@ -1010,7 +1062,7 @@ class GroupCollector implements GroupCollectorInterface
     {
         $newArray = $newJournal->toArray();
         if (isset($newArray['attachment_id'])) {
-            $attachmentId                                  = (int)$newJournal['tag_id'];
+            $attachmentId                                  = (int) $newJournal['tag_id'];
             $existingJournal['attachments'][$attachmentId] = [
                 'id' => $attachmentId,
             ];
@@ -1019,6 +1071,35 @@ class GroupCollector implements GroupCollectorInterface
         return $existingJournal;
     }
 
+    /**
+     * @param array              $existingJournal
+     * @param TransactionJournal $newJournal
+     *
+     * @return array
+     */
+    private function mergeTags(array $existingJournal, TransactionJournal $newJournal): array
+    {
+        $newArray = $newJournal->toArray();
+        if (isset($newArray['tag_id'])) { // assume the other fields are present as well.
+            $tagId = (int) $newJournal['tag_id'];
+
+            $tagDate = null;
+            try {
+                $tagDate = Carbon::parse($newArray['tag_date']);
+            } catch (InvalidDateException $e) {
+                Log::debug(sprintf('Could not parse date: %s', $e->getMessage()));
+            }
+
+            $existingJournal['tags'][$tagId] = [
+                'id'          => (int) $newArray['tag_id'],
+                'name'        => $newArray['tag_name'],
+                'date'        => $tagDate,
+                'description' => $newArray['tag_description'],
+            ];
+        }
+
+        return $existingJournal;
+    }
 
     /**
      * @param Collection $collection
@@ -1036,21 +1117,21 @@ class GroupCollector implements GroupCollectorInterface
                 // make new array
                 $parsedGroup                            = $this->parseAugmentedJournal($augumentedJournal);
                 $groupArray                             = [
-                    'id'               => (int)$augumentedJournal->transaction_group_id,
-                    'user_id'          => (int)$augumentedJournal->user_id,
+                    'id'               => (int) $augumentedJournal->transaction_group_id,
+                    'user_id'          => (int) $augumentedJournal->user_id,
                     'title'            => $augumentedJournal->transaction_group_title,
                     'transaction_type' => $parsedGroup['transaction_type_type'],
                     'count'            => 1,
                     'sums'             => [],
                     'transactions'     => [],
                 ];
-                $journalId                              = (int)$augumentedJournal->transaction_journal_id;
+                $journalId                              = (int) $augumentedJournal->transaction_journal_id;
                 $groupArray['transactions'][$journalId] = $parsedGroup;
                 $groups[$groupId]                       = $groupArray;
                 continue;
             }
             // or parse the rest.
-            $journalId = (int)$augumentedJournal->transaction_journal_id;
+            $journalId = (int) $augumentedJournal->transaction_journal_id;
             $groups[$groupId]['count']++;
 
             if (isset($groups[$groupId]['transactions'][$journalId])) {
@@ -1063,8 +1144,6 @@ class GroupCollector implements GroupCollectorInterface
                 // create second, third, fourth split:
                 $groups[$groupId]['transactions'][$journalId] = $this->parseAugmentedJournal($augumentedJournal);
             }
-
-
         }
 
         $groups = $this->parseSums($groups);
@@ -1093,9 +1172,9 @@ class GroupCollector implements GroupCollectorInterface
         // convert values to integers:
         $result = $this->convertToInteger($result);
 
-        $result['reconciled'] = 1 === (int)$result['reconciled'];
+        $result['reconciled'] = 1 === (int) $result['reconciled'];
         if (isset($augumentedJournal['tag_id'])) { // assume the other fields are present as well.
-            $tagId   = (int)$augumentedJournal['tag_id'];
+            $tagId   = (int) $augumentedJournal['tag_id'];
             $tagDate = null;
             try {
                 $tagDate = Carbon::parse($augumentedJournal['tag_date']);
@@ -1104,7 +1183,7 @@ 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'],
@@ -1113,7 +1192,7 @@ class GroupCollector implements GroupCollectorInterface
 
         // also merge attachments:
         if (isset($augumentedJournal['attachment_id'])) {
-            $attachmentId                         = (int)$augumentedJournal['attachment_id'];
+            $attachmentId                         = (int) $augumentedJournal['attachment_id'];
             $result['attachments'][$attachmentId] = [
                 'id' => $attachmentId,
             ];
@@ -1136,7 +1215,7 @@ 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'];
 
                 // set default:
                 if (!isset($groups[$groudId]['sums'][$currencyId])) {
@@ -1149,7 +1228,7 @@ class GroupCollector implements GroupCollectorInterface
                 $groups[$groudId]['sums'][$currencyId]['amount'] = bcadd($groups[$groudId]['sums'][$currencyId]['amount'], $transaction['amount'] ?? '0');
 
                 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 (!isset($groups[$groudId]['sums'][$currencyId])) {
@@ -1160,7 +1239,8 @@ class GroupCollector implements GroupCollectorInterface
                         $groups[$groudId]['sums'][$currencyId]['amount']                  = '0';
                     }
                     $groups[$groudId]['sums'][$currencyId]['amount'] = bcadd(
-                        $groups[$groudId]['sums'][$currencyId]['amount'], $transaction['foreign_amount'] ?? '0'
+                        $groups[$groudId]['sums'][$currencyId]['amount'],
+                        $transaction['foreign_amount'] ?? '0'
                     );
                 }
             }
@@ -1183,17 +1263,19 @@ class GroupCollector implements GroupCollectorInterface
 
             // join source transaction.
             ->leftJoin(
-                'transactions as source', function (JoinClause $join) {
-                $join->on('source.transaction_journal_id', '=', 'transaction_journals.id')
+                'transactions as source',
+                function (JoinClause $join) {
+                    $join->on('source.transaction_journal_id', '=', 'transaction_journals.id')
                      ->where('source.amount', '<', 0);
-            }
+                }
             )
             // join destination transaction
             ->leftJoin(
-                'transactions as destination', function (JoinClause $join) {
-                $join->on('destination.transaction_journal_id', '=', 'transaction_journals.id')
+                'transactions as destination',
+                function (JoinClause $join) {
+                    $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')
@@ -1209,88 +1291,4 @@ class GroupCollector implements GroupCollectorInterface
             ->orderBy('transaction_journals.description', 'DESC')
             ->orderBy('source.amount', 'DESC');
     }
-
-    /**
-     * Either account can be set, but NOT both. This effectively excludes internal transfers.
-     *
-     * @param Collection $accounts
-     *
-     * @return GroupCollectorInterface
-     */
-    public function setXorAccounts(Collection $accounts): GroupCollectorInterface
-    {
-        if ($accounts->count() > 0) {
-            $accountIds = $accounts->pluck('id')->toArray();
-            $this->query->where(
-                static function (EloquentBuilder $q1) use ($accountIds) {
-                    // sourceAccount is in the set, and destination is NOT.
-
-                    $q1->where(
-                        static function (EloquentBuilder $q2) use ($accountIds) {
-                            $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) {
-                            $q3->whereNotIn('source.account_id', $accountIds);
-                            $q3->whereIn('destination.account_id', $accountIds);
-                        }
-                    );
-                }
-            );
-
-            app('log')->debug(sprintf('GroupCollector: setXorAccounts: %s', implode(', ', $accountIds)));
-        }
-
-        return $this;
-    }
-
-    /**
-     * Collect transactions created on a specific date.
-     *
-     * @param Carbon $date
-     *
-     * @return GroupCollectorInterface
-     */
-    public function setCreatedAt(Carbon $date): GroupCollectorInterface
-    {
-        $after  = $date->format('Y-m-d 00:00:00');
-        $before = $date->format('Y-m-d 23:59:59');
-        $this->query->where('transaction_journals.created_at', '>=', $after);
-        $this->query->where('transaction_journals.created_at', '<=', $before);
-        Log::debug(sprintf('GroupCollector created_at is now after %s (inclusive)', $after));
-
-        return $this;
-    }
-
-    /**
-     * Collect transactions updated on a specific date.
-     *
-     * @param Carbon $date
-     *
-     * @return GroupCollectorInterface
-     */
-    public function setUpdatedAt(Carbon $date): GroupCollectorInterface
-    {
-        $after  = $date->format('Y-m-d 00:00:00');
-        $before = $date->format('Y-m-d 23:59:59');
-        $this->query->where('transaction_journals.updated_at', '>=', $after);
-        $this->query->where('transaction_journals.updated_at', '<=', $before);
-        Log::debug(sprintf('GroupCollector created_at is now after %s (inclusive)', $after));
-
-        return $this;
-    }
-
-    /**
-     * @inheritDoc
-     */
-    public function withAttachmentInformation(): GroupCollectorInterface
-    {
-        $this->fields[] = 'attachments.id as attachment_id';
-        $this->joinAttachmentTables();
-
-        return $this;
-    }
 }
diff --git a/app/Helpers/Collector/GroupCollectorInterface.php b/app/Helpers/Collector/GroupCollectorInterface.php
index df69fc4439..6975ca7b44 100644
--- a/app/Helpers/Collector/GroupCollectorInterface.php
+++ b/app/Helpers/Collector/GroupCollectorInterface.php
@@ -57,13 +57,6 @@ interface GroupCollectorInterface
      */
     public function amountLess(string $amount): GroupCollectorInterface;
 
-    /**
-     * Add basic info on attachments of transactions.
-     *
-     * @return GroupCollectorInterface
-     */
-    public function withAttachmentInformation(): GroupCollectorInterface;
-
     /**
      * Get transactions where the amount is more than.
      *
@@ -128,15 +121,6 @@ interface GroupCollectorInterface
      */
     public function setAccounts(Collection $accounts): GroupCollectorInterface;
 
-    /**
-     * Either account can be set, but NOT both. This effectively excludes internal transfers.
-     *
-     * @param Collection $accounts
-     *
-     * @return GroupCollectorInterface
-     */
-    public function setXorAccounts(Collection $accounts): GroupCollectorInterface;
-
     /**
      * Collect transactions after a specific date.
      *
@@ -146,24 +130,6 @@ interface GroupCollectorInterface
      */
     public function setAfter(Carbon $date): GroupCollectorInterface;
 
-    /**
-     * Collect transactions created on a specific date.
-     *
-     * @param Carbon $date
-     *
-     * @return GroupCollectorInterface
-     */
-    public function setCreatedAt(Carbon $date): GroupCollectorInterface;
-
-    /**
-     * Collect transactions updated on a specific date.
-     *
-     * @param Carbon $date
-     *
-     * @return GroupCollectorInterface
-     */
-    public function setUpdatedAt(Carbon $date): GroupCollectorInterface;
-
     /**
      * Collect transactions before a specific date.
      *
@@ -236,6 +202,14 @@ interface GroupCollectorInterface
      */
     public function setCategory(Category $category): GroupCollectorInterface;
 
+    /**
+     * Collect transactions created on a specific date.
+     *
+     * @param Carbon $date
+     *
+     * @return GroupCollectorInterface
+     */
+    public function setCreatedAt(Carbon $date): GroupCollectorInterface;
 
     /**
      * Limit results to a specific currency, either foreign or normal one.
@@ -355,6 +329,15 @@ interface GroupCollectorInterface
      */
     public function setTypes(array $types): GroupCollectorInterface;
 
+    /**
+     * Collect transactions updated on a specific date.
+     *
+     * @param Carbon $date
+     *
+     * @return GroupCollectorInterface
+     */
+    public function setUpdatedAt(Carbon $date): GroupCollectorInterface;
+
     /**
      * Set the user object and start the query.
      *
@@ -364,6 +347,15 @@ interface GroupCollectorInterface
      */
     public function setUser(User $user): GroupCollectorInterface;
 
+    /**
+     * Either account can be set, but NOT both. This effectively excludes internal transfers.
+     *
+     * @param Collection $accounts
+     *
+     * @return GroupCollectorInterface
+     */
+    public function setXorAccounts(Collection $accounts): GroupCollectorInterface;
+
     /**
      * Automatically include all stuff required to make API calls work.
      *
@@ -378,6 +370,13 @@ interface GroupCollectorInterface
      */
     public function withAccountInformation(): GroupCollectorInterface;
 
+    /**
+     * Add basic info on attachments of transactions.
+     *
+     * @return GroupCollectorInterface
+     */
+    public function withAttachmentInformation(): GroupCollectorInterface;
+
     /**
      * Include bill name + ID.
      *
diff --git a/app/Helpers/Fiscal/FiscalHelper.php b/app/Helpers/Fiscal/FiscalHelper.php
index 1bdf1c1852..10959f29c3 100644
--- a/app/Helpers/Fiscal/FiscalHelper.php
+++ b/app/Helpers/Fiscal/FiscalHelper.php
@@ -79,7 +79,7 @@ class FiscalHelper implements FiscalHelperInterface
         if (true === $this->useCustomFiscalYear) {
             $prefStartStr = app('preferences')->get('fiscalYearStart', '01-01')->data;
             [$mth, $day] = explode('-', $prefStartStr);
-            $startDate->day((int)$day)->month((int)$mth);
+            $startDate->day((int) $day)->month((int) $mth);
 
             // if start date is after passed date, sub 1 year.
             if ($startDate > $date) {
diff --git a/app/Helpers/Report/NetWorth.php b/app/Helpers/Report/NetWorth.php
index 347f7ec68b..a906e08619 100644
--- a/app/Helpers/Report/NetWorth.php
+++ b/app/Helpers/Report/NetWorth.php
@@ -99,7 +99,7 @@ class NetWorth implements NetWorthInterface
         /** @var Account $account */
         foreach ($accounts as $account) {
             Log::debug(sprintf('Now at account #%d: "%s"', $account->id, $account->name));
-            $currencyId = (int)$this->accountRepository->getMetaValue($account, 'currency_id');
+            $currencyId = (int) $this->accountRepository->getMetaValue($account, 'currency_id');
             $currencyId = 0 === $currencyId ? $default->id : $currencyId;
 
             Log::debug(sprintf('Currency ID is #%d', $currencyId));
@@ -111,9 +111,9 @@ class NetWorth implements NetWorthInterface
 
             // if the account is a credit card, subtract the virtual balance from the balance,
             // to better reflect that this is not money that is actually "yours".
-            $role           = (string)$this->accountRepository->getMetaValue($account, 'account_role');
-            $virtualBalance = (string)$account->virtual_balance;
-            if ('ccAsset' === $role && '' !== $virtualBalance && (float)$virtualBalance > 0) {
+            $role           = (string) $this->accountRepository->getMetaValue($account, 'account_role');
+            $virtualBalance = (string) $account->virtual_balance;
+            if ('ccAsset' === $role && '' !== $virtualBalance && (float) $virtualBalance > 0) {
                 $balance = bcsub($balance, $virtualBalance);
             }
 
diff --git a/app/Helpers/Report/PopupReport.php b/app/Helpers/Report/PopupReport.php
index 46900e008b..7b586b8866 100644
--- a/app/Helpers/Report/PopupReport.php
+++ b/app/Helpers/Report/PopupReport.php
@@ -87,7 +87,7 @@ class PopupReport implements PopupReportInterface
         if (null !== $currencyId) {
             /** @var CurrencyRepositoryInterface $repos */
             $repos    = app(CurrencyRepositoryInterface::class);
-            $currency = $repos->find((int)$currencyId);
+            $currency = $repos->find((int) $currencyId);
         }
 
 
@@ -124,7 +124,7 @@ class PopupReport implements PopupReportInterface
         if (null !== $currencyId) {
             /** @var CurrencyRepositoryInterface $repos */
             $repos    = app(CurrencyRepositoryInterface::class);
-            $currency = $repos->find((int)$currencyId);
+            $currency = $repos->find((int) $currencyId);
         }
 
 
@@ -154,7 +154,7 @@ class PopupReport implements PopupReportInterface
      * Collect journals by a category.
      *
      * @param Category|null $category
-     * @param array    $attributes
+     * @param array         $attributes
      *
      * @return array
      */
@@ -166,7 +166,7 @@ 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 */
@@ -179,10 +179,10 @@ class PopupReport implements PopupReportInterface
                   ->withCategoryInformation()
                   ->setRange($attributes['startDate'], $attributes['endDate'])->withAccountInformation();
 
-        if(null!== $category) {
+        if (null !== $category) {
             $collector->setCategory($category);
         }
-        if(null === $category) {
+        if (null === $category) {
             $collector->withoutCategory();
         }
 
@@ -209,7 +209,7 @@ 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 JournalRepositoryInterface $repository */
diff --git a/app/Helpers/Report/PopupReportInterface.php b/app/Helpers/Report/PopupReportInterface.php
index 6c987b6030..4e46ee3805 100644
--- a/app/Helpers/Report/PopupReportInterface.php
+++ b/app/Helpers/Report/PopupReportInterface.php
@@ -25,7 +25,6 @@ namespace FireflyIII\Helpers\Report;
 use FireflyIII\Models\Account;
 use FireflyIII\Models\Budget;
 use FireflyIII\Models\Category;
-use Illuminate\Support\Collection;
 
 /**
  * Interface PopupReportInterface.
@@ -68,7 +67,7 @@ interface PopupReportInterface
      * Group by category.
      *
      * @param Category|null $category
-     * @param array    $attributes
+     * @param array         $attributes
      *
      * @return array
      */
diff --git a/app/Helpers/Report/ReportHelper.php b/app/Helpers/Report/ReportHelper.php
index 72c495315a..3d532a132a 100644
--- a/app/Helpers/Report/ReportHelper.php
+++ b/app/Helpers/Report/ReportHelper.php
@@ -43,6 +43,7 @@ class ReportHelper implements ReportHelperInterface
 
     /**
      * ReportHelper constructor.
+     *
      * @param BudgetRepositoryInterface $budgetRepository
      */
     public function __construct(BudgetRepositoryInterface $budgetRepository)
@@ -62,8 +63,8 @@ class ReportHelper implements ReportHelperInterface
      *
      * Excludes bills which have not had a payment on the mentioned accounts.
      *
-     * @param Carbon $start
-     * @param Carbon $end
+     * @param Carbon     $start
+     * @param Carbon     $end
      * @param Collection $accounts
      *
      * @return array
diff --git a/app/Helpers/Report/ReportHelperInterface.php b/app/Helpers/Report/ReportHelperInterface.php
index 0c7d668ad1..e246ee946f 100644
--- a/app/Helpers/Report/ReportHelperInterface.php
+++ b/app/Helpers/Report/ReportHelperInterface.php
@@ -23,7 +23,6 @@ declare(strict_types=1);
 namespace FireflyIII\Helpers\Report;
 
 use Carbon\Carbon;
-use FireflyIII\Helpers\Collection\Bill as BillCollection;
 use Illuminate\Support\Collection;
 
 /**
diff --git a/app/Http/Controllers/Account/CreateController.php b/app/Http/Controllers/Account/CreateController.php
index ed01a7b06d..0aa93172d6 100644
--- a/app/Http/Controllers/Account/CreateController.php
+++ b/app/Http/Controllers/Account/CreateController.php
@@ -23,13 +23,16 @@ declare(strict_types=1);
 
 namespace FireflyIII\Http\Controllers\Account;
 
-
 use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\Http\Requests\AccountFormRequest;
 use FireflyIII\Models\AccountType;
 use FireflyIII\Repositories\Account\AccountRepositoryInterface;
 use FireflyIII\Support\Http\Controllers\ModelInformation;
+use Illuminate\Contracts\View\Factory;
+use Illuminate\Http\RedirectResponse;
 use Illuminate\Http\Request;
+use Illuminate\Routing\Redirector;
+use Illuminate\View\View;
 use Log;
 
 /**
@@ -44,6 +47,7 @@ class CreateController extends Controller
 
     /**
      * CreateController constructor.
+     *
      * @codeCoverageIgnore
      */
     public function __construct()
@@ -54,7 +58,7 @@ class CreateController extends Controller
         $this->middleware(
             function ($request, $next) {
                 app('view')->share('mainTitleIcon', 'fa-credit-card');
-                app('view')->share('title', (string)trans('firefly.accounts'));
+                app('view')->share('title', (string) trans('firefly.accounts'));
 
                 $this->repository = app(AccountRepositoryInterface::class);
 
@@ -66,17 +70,17 @@ class CreateController extends Controller
     /**
      * Create a new account.
      *
-     * @param Request $request
+     * @param Request     $request
      * @param string|null $objectType
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function create(Request $request, string $objectType = null)
     {
         $objectType      = $objectType ?? 'asset';
         $defaultCurrency = app('amount')->getDefaultCurrency();
         $subTitleIcon    = config(sprintf('firefly.subIconsByIdentifier.%s', $objectType));
-        $subTitle        = (string)trans(sprintf('firefly.make_new_%s_account', $objectType));
+        $subTitle        = (string) trans(sprintf('firefly.make_new_%s_account', $objectType));
         $roles           = $this->getRoles();
         $liabilityTypes  = $this->getLiabilityTypes();
         $hasOldInput     = null !== $request->old('_token');
@@ -91,17 +95,18 @@ class CreateController extends Controller
 
         // interest calculation periods:
         $interestPeriods = [
-            'daily'   => (string)trans('firefly.interest_calc_daily'),
-            'monthly' => (string)trans('firefly.interest_calc_monthly'),
-            'yearly'  => (string)trans('firefly.interest_calc_yearly'),
+            'daily'   => (string) trans('firefly.interest_calc_daily'),
+            'monthly' => (string) trans('firefly.interest_calc_monthly'),
+            'yearly'  => (string) trans('firefly.interest_calc_yearly'),
         ];
 
         // pre fill some data
         $request->session()->flash(
-            'preFilled', [
-                           'currency_id'       => $defaultCurrency->id,
-                           'include_net_worth' => $hasOldInput ? (bool)$request->old('include_net_worth') : true,
-                       ]
+            'preFilled',
+            [
+                'currency_id'       => $defaultCurrency->id,
+                'include_net_worth' => $hasOldInput ? (bool) $request->old('include_net_worth') : true,
+            ]
         );
 
         // put previous url in session if not redirect from store (not "create another").
@@ -119,13 +124,13 @@ class CreateController extends Controller
      *
      * @param AccountFormRequest $request
      *
-     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
+     * @return RedirectResponse|Redirector
      */
     public function store(AccountFormRequest $request)
     {
         $data    = $request->getAccountData();
         $account = $this->repository->store($data);
-        $request->session()->flash('success', (string)trans('firefly.stored_new_account', ['name' => $account->name]));
+        $request->session()->flash('success', (string) trans('firefly.stored_new_account', ['name' => $account->name]));
         app('preferences')->mark();
 
         Log::channel('audit')->info('Stored new account.', $data);
@@ -138,7 +143,7 @@ class CreateController extends Controller
         }
         // redirect to previous URL.
         $redirect = redirect($this->getPreviousUri('accounts.create.uri'));
-        if (1 === (int)$request->get('create_another')) {
+        if (1 === (int) $request->get('create_another')) {
             // set value so create routine will not overwrite URL:
             $request->session()->put('accounts.create.fromStore', true);
 
@@ -147,7 +152,4 @@ class CreateController extends Controller
 
         return $redirect;
     }
-
-
-
 }
diff --git a/app/Http/Controllers/Account/DeleteController.php b/app/Http/Controllers/Account/DeleteController.php
index d04ca94a94..2823266223 100644
--- a/app/Http/Controllers/Account/DeleteController.php
+++ b/app/Http/Controllers/Account/DeleteController.php
@@ -28,7 +28,11 @@ use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\Models\Account;
 use FireflyIII\Repositories\Account\AccountRepositoryInterface;
 use FireflyIII\Support\Http\Controllers\UserNavigation;
+use Illuminate\Contracts\View\Factory;
+use Illuminate\Http\RedirectResponse;
 use Illuminate\Http\Request;
+use Illuminate\Routing\Redirector;
+use Illuminate\View\View;
 
 /**
  * Class DeleteController
@@ -42,6 +46,7 @@ class DeleteController extends Controller
 
     /**
      * DeleteController constructor.
+     *
      * @codeCoverageIgnore
      */
     public function __construct()
@@ -52,7 +57,7 @@ class DeleteController extends Controller
         $this->middleware(
             function ($request, $next) {
                 app('view')->share('mainTitleIcon', 'fa-credit-card');
-                app('view')->share('title', (string)trans('firefly.accounts'));
+                app('view')->share('title', (string) trans('firefly.accounts'));
 
                 $this->repository = app(AccountRepositoryInterface::class);
 
@@ -66,7 +71,7 @@ class DeleteController extends Controller
      *
      * @param Account $account
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function delete(Account $account)
     {
@@ -75,7 +80,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]);
@@ -92,7 +97,7 @@ class DeleteController extends Controller
      * @param Request $request
      * @param Account $account
      *
-     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
+     * @return RedirectResponse|Redirector
      */
     public function destroy(Request $request, Account $account)
     {
@@ -103,11 +108,11 @@ class DeleteController extends Controller
         $type     = $account->accountType->type;
         $typeName = config(sprintf('firefly.shortNamesByFullName.%s', $type));
         $name     = $account->name;
-        $moveTo   = $this->repository->findNull((int)$request->get('move_account_before_delete'));
+        $moveTo   = $this->repository->findNull((int) $request->get('move_account_before_delete'));
 
         $this->repository->destroy($account, $moveTo);
 
-        $request->session()->flash('success', (string)trans(sprintf('firefly.%s_deleted', $typeName), ['name' => $name]));
+        $request->session()->flash('success', (string) trans(sprintf('firefly.%s_deleted', $typeName), ['name' => $name]));
         app('preferences')->mark();
 
         return redirect($this->getPreviousUri('accounts.delete.uri'));
diff --git a/app/Http/Controllers/Account/EditController.php b/app/Http/Controllers/Account/EditController.php
index 06e59e435d..cce2a91275 100644
--- a/app/Http/Controllers/Account/EditController.php
+++ b/app/Http/Controllers/Account/EditController.php
@@ -23,7 +23,6 @@ declare(strict_types=1);
 
 namespace FireflyIII\Http\Controllers\Account;
 
-
 use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\Http\Requests\AccountFormRequest;
 use FireflyIII\Models\Account;
@@ -31,7 +30,11 @@ use FireflyIII\Repositories\Account\AccountRepositoryInterface;
 use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
 use FireflyIII\Support\Http\Controllers\ModelInformation;
 use FireflyIII\Support\Http\Controllers\UserNavigation;
+use Illuminate\Contracts\View\Factory;
+use Illuminate\Http\RedirectResponse;
 use Illuminate\Http\Request;
+use Illuminate\Routing\Redirector;
+use Illuminate\View\View;
 
 /**
  *
@@ -56,7 +59,7 @@ class EditController extends Controller
         $this->middleware(
             function ($request, $next) {
                 app('view')->share('mainTitleIcon', 'fa-credit-card');
-                app('view')->share('title', (string)trans('firefly.accounts'));
+                app('view')->share('title', (string) trans('firefly.accounts'));
 
                 $this->repository    = app(AccountRepositoryInterface::class);
                 $this->currencyRepos = app(CurrencyRepositoryInterface::class);
@@ -69,11 +72,11 @@ class EditController extends Controller
     /**
      * Edit account overview.
      *
-     * @param Request $request
-     * @param Account $account
+     * @param Request                    $request
+     * @param Account                    $account
      * @param AccountRepositoryInterface $repository
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      *
      */
     public function edit(Request $request, Account $account, AccountRepositoryInterface $repository)
@@ -83,7 +86,7 @@ class EditController extends Controller
         }
 
         $objectType     = config('firefly.shortNamesByFullName')[$account->accountType->type];
-        $subTitle       = (string)trans(sprintf('firefly.edit_%s_account', $objectType), ['name' => $account->name]);
+        $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();
@@ -103,9 +106,9 @@ class EditController extends Controller
 
         // interest calculation periods:
         $interestPeriods = [
-            'daily'   => (string)trans('firefly.interest_calc_daily'),
-            'monthly' => (string)trans('firefly.interest_calc_monthly'),
-            'yearly'  => (string)trans('firefly.interest_calc_yearly'),
+            'daily'   => (string) trans('firefly.interest_calc_daily'),
+            'monthly' => (string) trans('firefly.interest_calc_monthly'),
+            'yearly'  => (string) trans('firefly.interest_calc_yearly'),
         ];
 
         // put previous url in session if not redirect from store (not "return_to_edit").
@@ -114,7 +117,7 @@ class EditController extends Controller
         }
         $request->session()->forget('accounts.edit.fromUpdate');
 
-        $openingBalanceAmount = (string)$repository->getOpeningBalanceAmount($account);
+        $openingBalanceAmount = (string) $repository->getOpeningBalanceAmount($account);
         $openingBalanceDate   = $repository->getOpeningBalanceDate($account);
         $currency             = $this->repository->getAccountCurrency($account) ?? app('amount')->getDefaultCurrency();
 
@@ -139,15 +142,25 @@ 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,
         ];
 
         $request->session()->flash('preFilled', $preFilled);
 
         return view(
-            'accounts.edit', compact(
-            'account', 'currency', 'subTitle', 'subTitleIcon', 'locations', 'objectType', 'roles', 'preFilled', 'liabilityTypes', 'interestPeriods'
-        )
+            'accounts.edit',
+            compact(
+                'account',
+                'currency',
+                'subTitle',
+                'subTitleIcon',
+                'locations',
+                'objectType',
+                'roles',
+                'preFilled',
+                'liabilityTypes',
+                'interestPeriods'
+            )
         );
     }
 
@@ -156,9 +169,9 @@ class EditController extends Controller
      * Update the account.
      *
      * @param AccountFormRequest $request
-     * @param Account $account
+     * @param Account            $account
      *
-     * @return $this|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
+     * @return $this|RedirectResponse|Redirector
      */
     public function update(AccountFormRequest $request, Account $account)
     {
@@ -169,11 +182,11 @@ class EditController extends Controller
         $data = $request->getAccountData();
         $this->repository->update($account, $data);
 
-        $request->session()->flash('success', (string)trans('firefly.updated_account', ['name' => $account->name]));
+        $request->session()->flash('success', (string) trans('firefly.updated_account', ['name' => $account->name]));
         app('preferences')->mark();
 
         $redirect = redirect($this->getPreviousUri('accounts.edit.uri'));
-        if (1 === (int)$request->get('return_to_edit')) {
+        if (1 === (int) $request->get('return_to_edit')) {
             // set value so edit routine will not overwrite URL:
             $request->session()->put('accounts.edit.fromUpdate', true);
 
@@ -182,5 +195,4 @@ class EditController extends Controller
 
         return $redirect;
     }
-
 }
diff --git a/app/Http/Controllers/Account/IndexController.php b/app/Http/Controllers/Account/IndexController.php
index b1af86bcdd..8d09a2d818 100644
--- a/app/Http/Controllers/Account/IndexController.php
+++ b/app/Http/Controllers/Account/IndexController.php
@@ -28,8 +28,10 @@ use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\Models\Account;
 use FireflyIII\Repositories\Account\AccountRepositoryInterface;
 use FireflyIII\Support\Http\Controllers\BasicDataSupport;
+use Illuminate\Contracts\View\Factory;
 use Illuminate\Http\Request;
 use Illuminate\Pagination\LengthAwarePaginator;
+use Illuminate\View\View;
 
 /**
  *
@@ -43,6 +45,7 @@ class IndexController extends Controller
 
     /**
      * IndexController constructor.
+     *
      * @codeCoverageIgnore
      */
     public function __construct()
@@ -53,7 +56,7 @@ class IndexController extends Controller
         $this->middleware(
             function ($request, $next) {
                 app('view')->share('mainTitleIcon', 'fa-credit-card');
-                app('view')->share('title', (string)trans('firefly.accounts'));
+                app('view')->share('title', (string) trans('firefly.accounts'));
 
                 $this->repository = app(AccountRepositoryInterface::class);
 
@@ -66,19 +69,19 @@ class IndexController extends Controller
      * @param Request $request
      * @param string  $objectType
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function inactive(Request $request, string $objectType)
     {
         $objectType   = $objectType ?? 'asset';
         $inactivePage = true;
-        $subTitle     = (string)trans(sprintf('firefly.%s_accounts_inactive', $objectType));
+        $subTitle     = (string) trans(sprintf('firefly.%s_accounts_inactive', $objectType));
         $subTitleIcon = config(sprintf('firefly.subIconsByIdentifier.%s', $objectType));
         $types        = config(sprintf('firefly.accountTypesByIdentifier.%s', $objectType));
         $collection   = $this->repository->getInactiveAccountsByType($types);
         $total        = $collection->count();
-        $page         = 0 === (int)$request->get('page') ? 1 : (int)$request->get('page');
-        $pageSize     = (int)app('preferences')->get('listPageSize', 50)->data;
+        $page         = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page');
+        $pageSize     = (int) app('preferences')->get('listPageSize', 50)->data;
         $accounts     = $collection->slice(($page - 1) * $pageSize, $pageSize);
         unset($collection);
         /** @var Carbon $start */
@@ -99,8 +102,8 @@ class IndexController extends Controller
                 $account->endBalance        = $this->isInArray($endBalances, $account->id);
                 $account->difference        = bcsub($account->endBalance, $account->startBalance);
                 $account->interest          = round($this->repository->getMetaValue($account, 'interest'), 6);
-                $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->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));
             }
         );
 
@@ -108,7 +111,7 @@ class IndexController extends Controller
         $accounts = new LengthAwarePaginator($accounts, $total, $pageSize, $page);
         $accounts->setPath(route('accounts.inactive.index', [$objectType]));
 
-        return view('accounts.index', compact('objectType','inactivePage', 'subTitleIcon', 'subTitle', 'page', 'accounts'));
+        return view('accounts.index', compact('objectType', 'inactivePage', 'subTitleIcon', 'subTitle', 'page', 'accounts'));
 
     }
 
@@ -116,20 +119,20 @@ class IndexController extends Controller
      * Show list of accounts.
      *
      * @param Request $request
-     * @param string $objectType
+     * @param string  $objectType
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function index(Request $request, string $objectType)
     {
         $objectType    = $objectType ?? 'asset';
-        $subTitle      = (string)trans(sprintf('firefly.%s_accounts', $objectType));
+        $subTitle      = (string) trans(sprintf('firefly.%s_accounts', $objectType));
         $subTitleIcon  = config(sprintf('firefly.subIconsByIdentifier.%s', $objectType));
         $types         = config(sprintf('firefly.accountTypesByIdentifier.%s', $objectType));
         $collection    = $this->repository->getActiveAccountsByType($types);
         $total         = $collection->count();
-        $page          = 0 === (int)$request->get('page') ? 1 : (int)$request->get('page');
-        $pageSize      = (int)app('preferences')->get('listPageSize', 50)->data;
+        $page          = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page');
+        $pageSize      = (int) app('preferences')->get('listPageSize', 50)->data;
         $accounts      = $collection->slice(($page - 1) * $pageSize, $pageSize);
         $inactiveCount = $this->repository->getInactiveAccountsByType($types)->count();
 
@@ -153,9 +156,9 @@ class IndexController extends Controller
                 $account->endBalance        = $this->isInArray($endBalances, $account->id);
                 $account->difference        = bcsub($account->endBalance, $account->startBalance);
                 $account->interest          = round($this->repository->getMetaValue($account, 'interest'), 6);
-                $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->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);
             }
         );
 
diff --git a/app/Http/Controllers/Account/ReconcileController.php b/app/Http/Controllers/Account/ReconcileController.php
index cbc6185ecf..6e5106194f 100644
--- a/app/Http/Controllers/Account/ReconcileController.php
+++ b/app/Http/Controllers/Account/ReconcileController.php
@@ -25,6 +25,7 @@ namespace FireflyIII\Http\Controllers\Account;
 
 use Carbon\Carbon;
 use Exception;
+use FireflyIII\Exceptions\DuplicateTransactionException;
 use FireflyIII\Exceptions\FireflyException;
 use FireflyIII\Factory\TransactionGroupFactory;
 use FireflyIII\Http\Controllers\Controller;
@@ -37,6 +38,10 @@ use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
 use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
 use FireflyIII\Support\Http\Controllers\UserNavigation;
 use FireflyIII\User;
+use Illuminate\Contracts\View\Factory;
+use Illuminate\Http\RedirectResponse;
+use Illuminate\Routing\Redirector;
+use Illuminate\View\View;
 use Log;
 
 /**
@@ -54,6 +59,7 @@ class ReconcileController extends Controller
 
     /**
      * ReconcileController constructor.
+     *
      * @codeCoverageIgnore
      */
     public function __construct()
@@ -64,7 +70,7 @@ class ReconcileController extends Controller
         $this->middleware(
             function ($request, $next) {
                 app('view')->share('mainTitleIcon', 'fa-credit-card');
-                app('view')->share('title', (string)trans('firefly.accounts'));
+                app('view')->share('title', (string) trans('firefly.accounts'));
                 $this->repository    = app(JournalRepositoryInterface::class);
                 $this->accountRepos  = app(AccountRepositoryInterface::class);
                 $this->currencyRepos = app(CurrencyRepositoryInterface::class);
@@ -77,12 +83,12 @@ class ReconcileController extends Controller
     /**
      * Reconciliation overview.
      *
-     * @param Account $account
+     * @param Account     $account
      * @param Carbon|null $start
      * @param Carbon|null $end
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
      * @throws Exception
+     * @return Factory|RedirectResponse|Redirector|View
      */
     public function reconcile(Account $account, Carbon $start = null, Carbon $end = null)
     {
@@ -93,7 +99,7 @@ class ReconcileController extends Controller
 
         if (AccountType::ASSET !== $account->accountType->type) {
             // @codeCoverageIgnoreStart
-            session()->flash('error', (string)trans('firefly.must_be_asset_account'));
+            session()->flash('error', (string) trans('firefly.must_be_asset_account'));
 
             return redirect(route('accounts.index', [config(sprintf('firefly.shortNamesByFullName.%s', $account->accountType->type))]));
             // @codeCoverageIgnoreEnd
@@ -111,7 +117,6 @@ class ReconcileController extends Controller
             $start = clone session('start', app('navigation')->startOfPeriod(new Carbon, $range));
             /** @var Carbon $end */
             $end = clone session('end', app('navigation')->endOfPeriod(new Carbon, $range));
-
         }
         if (null === $end) {
             /** @var Carbon $end */
@@ -128,7 +133,7 @@ class ReconcileController extends Controller
 
         $endBalance   = round(app('steam')->balance($account, $end), $currency->decimal_places);
         $subTitleIcon = config(sprintf('firefly.subIconsByIdentifier.%s', $account->accountType->type));
-        $subTitle     = (string)trans('firefly.reconcile_account', ['account' => $account->name]);
+        $subTitle     = (string) trans('firefly.reconcile_account', ['account' => $account->name]);
 
         // various links
         $transactionsUri = route('accounts.reconcile.transactions', [$account->id, '%start%', '%end%']);
@@ -136,21 +141,34 @@ class ReconcileController extends Controller
         $indexUri        = route('accounts.reconcile', [$account->id, '%start%', '%end%']);
         $objectType      = 'asset';
 
-        return view('accounts.reconcile.index',
-                    compact('account', 'currency', 'objectType',
-                            'subTitleIcon', 'start', 'end', 'subTitle', 'startBalance', 'endBalance',
-                            'transactionsUri', 'overviewUri', 'indexUri'));
+        return view(
+            'accounts.reconcile.index',
+            compact(
+                'account',
+                'currency',
+                'objectType',
+                'subTitleIcon',
+                'start',
+                'end',
+                'subTitle',
+                'startBalance',
+                'endBalance',
+                'transactionsUri',
+                'overviewUri',
+                'indexUri'
+            )
+        );
     }
 
     /**
      * Submit a new reconciliation.
      *
      * @param ReconciliationStoreRequest $request
-     * @param Account $account
-     * @param Carbon $start
-     * @param Carbon $end
+     * @param Account                    $account
+     * @param Carbon                     $start
+     * @param Carbon                     $end
      *
-     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
+     * @return RedirectResponse|Redirector
      */
     public function submit(ReconciliationStoreRequest $request, Account $account, Carbon $start, Carbon $end)
     {
@@ -163,7 +181,7 @@ class ReconcileController extends Controller
 
         /** @var string $journalId */
         foreach ($data['journals'] as $journalId) {
-            $this->repository->reconcileById((int)$journalId);
+            $this->repository->reconcileById((int) $journalId);
         }
         Log::debug('Reconciled all transactions.');
 
@@ -180,10 +198,10 @@ class ReconcileController extends Controller
         Log::debug('End of routine.');
         app('preferences')->mark();
         if ('' === $result) {
-            session()->flash('success', (string)trans('firefly.reconciliation_stored'));
+            session()->flash('success', (string) trans('firefly.reconciliation_stored'));
         }
         if ('' !== $result) {
-            session()->flash('error', (string)trans('firefly.reconciliation_error', ['error' => $result]));
+            session()->flash('error', (string) trans('firefly.reconciliation_error', ['error' => $result]));
         }
 
         return redirect(route('accounts.show', [$account->id]));
@@ -197,8 +215,8 @@ class ReconcileController extends Controller
      * @param Carbon  $end
      * @param string  $difference
      *
+     * @throws DuplicateTransactionException
      * @return string
-     * @throws \FireflyIII\Exceptions\DuplicateTransactionException
      */
     private function createReconciliation(Account $account, Carbon $start, Carbon $end, string $difference)
     {
@@ -220,9 +238,11 @@ class ReconcileController extends Controller
         }
 
         // title:
-        $description = trans('firefly.reconciliation_transaction_title',
-                             ['from' => $start->formatLocalized($this->monthAndDayFormat), 'to'   => $end->formatLocalized($this->monthAndDayFormat)]);
-        $submission = [
+        $description = trans(
+            'firefly.reconciliation_transaction_title',
+            ['from' => $start->formatLocalized($this->monthAndDayFormat), 'to' => $end->formatLocalized($this->monthAndDayFormat)]
+        );
+        $submission  = [
             'user'         => auth()->user()->id,
             'group_title'  => null,
             'transactions' => [
diff --git a/app/Http/Controllers/Account/ShowController.php b/app/Http/Controllers/Account/ShowController.php
index f422374399..ea8d7bc57f 100644
--- a/app/Http/Controllers/Account/ShowController.php
+++ b/app/Http/Controllers/Account/ShowController.php
@@ -32,7 +32,9 @@ use FireflyIII\Repositories\Account\AccountRepositoryInterface;
 use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
 use FireflyIII\Support\Http\Controllers\PeriodOverview;
 use FireflyIII\Support\Http\Controllers\UserNavigation;
+use Illuminate\Http\RedirectResponse;
 use Illuminate\Http\Request;
+use Illuminate\Routing\Redirector;
 use Illuminate\Support\Collection;
 use View;
 
@@ -51,6 +53,7 @@ class ShowController extends Controller
 
     /**
      * ShowController constructor.
+     *
      * @codeCoverageIgnore
      */
     public function __construct()
@@ -63,7 +66,7 @@ class ShowController extends Controller
         $this->middleware(
             function ($request, $next) {
                 app('view')->share('mainTitleIcon', 'fa-credit-card');
-                app('view')->share('title', (string)trans('firefly.accounts'));
+                app('view')->share('title', (string) trans('firefly.accounts'));
 
                 $this->repository    = app(AccountRepositoryInterface::class);
                 $this->currencyRepos = app(CurrencyRepositoryInterface::class);
@@ -77,13 +80,13 @@ class ShowController extends Controller
     /**
      * Show an account.
      *
-     * @param Request $request
-     * @param Account $account
+     * @param Request     $request
+     * @param Account     $account
      * @param Carbon|null $start
      * @param Carbon|null $end
      *
-     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|View
      * @throws Exception
+     * @return RedirectResponse|Redirector|View
      */
     public function show(Request $request, Account $account, Carbon $start = null, Carbon $end = null)
     {
@@ -103,12 +106,12 @@ class ShowController extends Controller
         $objectType       = config(sprintf('firefly.shortNamesByFullName.%s', $account->accountType->type));
         $today            = new Carbon;
         $subTitleIcon     = config(sprintf('firefly.subIconsByIdentifier.%s', $account->accountType->type));
-        $page             = (int)$request->get('page');
-        $pageSize         = (int)app('preferences')->get('listPageSize', 50)->data;
+        $page             = (int) $request->get('page');
+        $pageSize         = (int) app('preferences')->get('listPageSize', 50)->data;
         $currency         = $this->repository->getAccountCurrency($account) ?? app('amount')->getDefaultCurrency();
         $fStart           = $start->formatLocalized($this->monthAndDayFormat);
         $fEnd             = $end->formatLocalized($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]);
         $chartUri         = route('chart.account.period', [$account->id, $start->format('Y-m-d'), $end->format('Y-m-d')]);
         $firstTransaction = $this->repository->oldestJournalDate($account) ?? $start;
         $periods          = $this->getAccountPeriodOverview($account, $firstTransaction, $end);
@@ -123,13 +126,25 @@ class ShowController extends Controller
         $groups = $collector->getPaginatedGroups();
         $groups->setPath(route('accounts.show', [$account->id, $start->format('Y-m-d'), $end->format('Y-m-d')]));
         $showAll = false;
-        $balance  = app('steam')->balance($account, $end);
+        $balance = app('steam')->balance($account, $end);
 
         return view(
             'accounts.show',
             compact(
-                'account', 'showAll', 'objectType', 'currency', 'today', 'periods', 'subTitleIcon', 'groups', 'subTitle', 'start', 'end',
-                'chartUri', 'location','balance'
+                'account',
+                'showAll',
+                'objectType',
+                'currency',
+                'today',
+                'periods',
+                'subTitleIcon',
+                'groups',
+                'subTitle',
+                'start',
+                'end',
+                'chartUri',
+                'location',
+                'balance'
             )
         );
     }
@@ -139,8 +154,9 @@ class ShowController extends Controller
      *
      * @param Request $request
      * @param Account $account
-     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|View
+     *
      * @throws Exception
+     * @return RedirectResponse|Redirector|View
      */
     public function showAll(Request $request, Account $account)
     {
@@ -156,10 +172,10 @@ class ShowController extends Controller
         $today        = new Carbon;
         $start        = $this->repository->oldestJournalDate($account) ?? Carbon::now()->startOfMonth();
         $subTitleIcon = config('firefly.subIconsByIdentifier.' . $account->accountType->type);
-        $page         = (int)$request->get('page');
-        $pageSize     = (int)app('preferences')->get('listPageSize', 50)->data;
+        $page         = (int) $request->get('page');
+        $pageSize     = (int) app('preferences')->get('listPageSize', 50)->data;
         $currency     = $this->repository->getAccountCurrency($account) ?? app('amount')->getDefaultCurrency();
-        $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;
         /** @var GroupCollectorInterface $collector */
         $collector = app(GroupCollectorInterface::class);
@@ -173,10 +189,22 @@ class ShowController extends Controller
         return view(
             'accounts.show',
             compact(
-                'account', 'showAll', 'location', 'objectType', 'isLiability', 'currency', 'today',
-                'chartUri', 'periods', 'subTitleIcon', 'groups', 'subTitle', 'start', 'end', 'balance'
+                'account',
+                'showAll',
+                'location',
+                'objectType',
+                'isLiability',
+                'currency',
+                'today',
+                'chartUri',
+                'periods',
+                'subTitleIcon',
+                'groups',
+                'subTitle',
+                'start',
+                'end',
+                'balance'
             )
         );
     }
-
 }
diff --git a/app/Http/Controllers/Admin/ConfigurationController.php b/app/Http/Controllers/Admin/ConfigurationController.php
index c83a0ab33d..6a026d938d 100644
--- a/app/Http/Controllers/Admin/ConfigurationController.php
+++ b/app/Http/Controllers/Admin/ConfigurationController.php
@@ -27,7 +27,9 @@ use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\Http\Middleware\IsDemoUser;
 use FireflyIII\Http\Middleware\IsSandStormUser;
 use FireflyIII\Http\Requests\ConfigurationRequest;
+use Illuminate\Contracts\View\Factory;
 use Illuminate\Http\RedirectResponse;
+use Illuminate\View\View;
 use Log;
 
 /**
@@ -37,6 +39,7 @@ class ConfigurationController extends Controller
 {
     /**
      * ConfigurationController constructor.
+     *
      * @codeCoverageIgnore
      */
     public function __construct()
@@ -45,7 +48,7 @@ class ConfigurationController extends Controller
 
         $this->middleware(
             static function ($request, $next) {
-                app('view')->share('title', (string)trans('firefly.administration'));
+                app('view')->share('title', (string) trans('firefly.administration'));
                 app('view')->share('mainTitleIcon', 'fa-hand-spock-o');
 
                 return $next($request);
@@ -58,11 +61,11 @@ class ConfigurationController extends Controller
     /**
      * Show configuration index.
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function index()
     {
-        $subTitle     = (string)trans('firefly.instance_configuration');
+        $subTitle     = (string) trans('firefly.instance_configuration');
         $subTitleIcon = 'fa-wrench';
 
         Log::channel('audit')->info('User visits admin config index.');
@@ -98,7 +101,7 @@ class ConfigurationController extends Controller
         app('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'));
         app('preferences')->mark();
 
         return redirect()->route('admin.configuration.index');
diff --git a/app/Http/Controllers/Admin/HomeController.php b/app/Http/Controllers/Admin/HomeController.php
index efb892300f..5c3366037f 100644
--- a/app/Http/Controllers/Admin/HomeController.php
+++ b/app/Http/Controllers/Admin/HomeController.php
@@ -27,7 +27,11 @@ use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\Http\Middleware\IsDemoUser;
 use FireflyIII\Http\Middleware\IsSandStormUser;
 use FireflyIII\User;
+use Illuminate\Contracts\View\Factory;
+use Illuminate\Http\RedirectResponse;
 use Illuminate\Http\Request;
+use Illuminate\Routing\Redirector;
+use Illuminate\View\View;
 use Log;
 
 /**
@@ -37,6 +41,7 @@ class HomeController extends Controller
 {
     /**
      * ConfigurationController constructor.
+     *
      * @codeCoverageIgnore
      */
     public function __construct()
@@ -49,14 +54,14 @@ class HomeController extends Controller
     /**
      * Index of the admin.
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function index()
     {
         Log::channel('audit')->info('User visits admin index.');
-        $title         = (string)trans('firefly.administration');
+        $title         = (string) trans('firefly.administration');
         $mainTitleIcon = 'fa-hand-spock-o';
-        $sandstorm     = 1 === (int)getenv('SANDSTORM');
+        $sandstorm     = 1 === (int) getenv('SANDSTORM');
 
         return view('admin.index', compact('title', 'mainTitleIcon', 'sandstorm'));
     }
@@ -66,7 +71,7 @@ class HomeController extends Controller
      *
      * @param Request $request
      *
-     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
+     * @return RedirectResponse|Redirector
      */
     public function testMessage(Request $request)
     {
@@ -76,7 +81,7 @@ class HomeController extends Controller
         $ipAddress = $request->ip();
         Log::debug(sprintf('Now in testMessage() controller. IP is %s', $ipAddress));
         event(new AdminRequestedTestMessage($user, $ipAddress));
-        session()->flash('info', (string)trans('firefly.send_test_triggered'));
+        session()->flash('info', (string) trans('firefly.send_test_triggered'));
 
         return redirect(route('admin.index'));
     }
diff --git a/app/Http/Controllers/Admin/LinkController.php b/app/Http/Controllers/Admin/LinkController.php
index 370aa8c564..134943c4e1 100644
--- a/app/Http/Controllers/Admin/LinkController.php
+++ b/app/Http/Controllers/Admin/LinkController.php
@@ -27,7 +27,10 @@ use FireflyIII\Http\Middleware\IsDemoUser;
 use FireflyIII\Http\Requests\LinkTypeFormRequest;
 use FireflyIII\Models\LinkType;
 use FireflyIII\Repositories\LinkType\LinkTypeRepositoryInterface;
+use Illuminate\Contracts\View\Factory;
+use Illuminate\Http\RedirectResponse;
 use Illuminate\Http\Request;
+use Illuminate\Routing\Redirector;
 use Log;
 use View;
 
@@ -42,6 +45,7 @@ class LinkController extends Controller
 
     /**
      * LinkController constructor.
+     *
      * @codeCoverageIgnore
      */
     public function __construct()
@@ -50,7 +54,7 @@ class LinkController extends Controller
 
         $this->middleware(
             function ($request, $next) {
-                app('view')->share('title', (string)trans('firefly.administration'));
+                app('view')->share('title', (string) trans('firefly.administration'));
                 app('view')->share('mainTitleIcon', 'fa-hand-spock-o');
                 $this->repository = app(LinkTypeRepositoryInterface::class);
 
@@ -63,13 +67,13 @@ class LinkController extends Controller
     /**
      * Make a new link form.
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|\Illuminate\View\View
      */
     public function create()
     {
         Log::channel('audit')->info('User visits link index.');
 
-        $subTitle     = (string)trans('firefly.create_new_link_type');
+        $subTitle     = (string) trans('firefly.create_new_link_type');
         $subTitleIcon = 'fa-link';
 
         // put previous url in session if not redirect from store (not "create another").
@@ -83,25 +87,25 @@ class LinkController extends Controller
     /**
      * Delete a link form.
      *
-     * @param Request $request
+     * @param Request  $request
      * @param LinkType $linkType
      *
-     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|View
+     * @return RedirectResponse|Redirector|View
      */
     public function delete(Request $request, LinkType $linkType)
     {
         if (!$linkType->editable) {
-            $request->session()->flash('error', (string)trans('firefly.cannot_edit_link_type', ['name' => e($linkType->name)]));
+            $request->session()->flash('error', (string) trans('firefly.cannot_edit_link_type', ['name' => e($linkType->name)]));
 
             return redirect(route('admin.links.index'));
         }
 
         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) {
@@ -119,19 +123,19 @@ class LinkController extends Controller
     /**
      * Actually destroy the link.
      *
-     * @param Request $request
+     * @param Request  $request
      * @param LinkType $linkType
      *
-     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
+     * @return RedirectResponse|Redirector
      */
     public function destroy(Request $request, LinkType $linkType)
     {
         Log::channel('audit')->info(sprintf('User destroyed link type #%d', $linkType->id));
         $name   = $linkType->name;
-        $moveTo = $this->repository->findNull((int)$request->get('move_link_type_before_delete'));
+        $moveTo = $this->repository->findNull((int) $request->get('move_link_type_before_delete'));
         $this->repository->destroy($linkType, $moveTo);
 
-        $request->session()->flash('success', (string)trans('firefly.deleted_link_type', ['name' => $name]));
+        $request->session()->flash('success', (string) trans('firefly.deleted_link_type', ['name' => $name]));
         app('preferences')->mark();
 
         return redirect($this->getPreviousUri('link-types.delete.uri'));
@@ -140,19 +144,19 @@ class LinkController extends Controller
     /**
      * Edit a link form.
      *
-     * @param Request $request
+     * @param Request  $request
      * @param LinkType $linkType
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
+     * @return Factory|RedirectResponse|Redirector|\Illuminate\View\View
      */
     public function edit(Request $request, LinkType $linkType)
     {
         if (!$linkType->editable) {
-            $request->session()->flash('error', (string)trans('firefly.cannot_edit_link_type', ['name' => e($linkType->name)]));
+            $request->session()->flash('error', (string) trans('firefly.cannot_edit_link_type', ['name' => e($linkType->name)]));
 
             return redirect(route('admin.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));
@@ -169,11 +173,11 @@ class LinkController extends Controller
     /**
      * Show index of all links.
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|\Illuminate\View\View
      */
     public function index()
     {
-        $subTitle     = (string)trans('firefly.journal_link_configuration');
+        $subTitle     = (string) trans('firefly.journal_link_configuration');
         $subTitleIcon = 'fa-link';
         $linkTypes    = $this->repository->get();
 
@@ -192,11 +196,11 @@ class LinkController extends Controller
      *
      * @param LinkType $linkType
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|\Illuminate\View\View
      */
     public function show(LinkType $linkType)
     {
-        $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);
 
@@ -210,7 +214,7 @@ class LinkController extends Controller
      *
      * @param LinkTypeFormRequest $request
      *
-     * @return $this|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
+     * @return $this|RedirectResponse|Redirector
      */
     public function store(LinkTypeFormRequest $request)
     {
@@ -223,9 +227,9 @@ class LinkController extends Controller
 
         Log::channel('audit')->info('User stored new link type.', $linkType->toArray());
 
-        $request->session()->flash('success', (string)trans('firefly.stored_new_link_type', ['name' => $linkType->name]));
+        $request->session()->flash('success', (string) trans('firefly.stored_new_link_type', ['name' => $linkType->name]));
         $redirect = redirect($this->getPreviousUri('link-types.create.uri'));
-        if (1 === (int)$request->get('create_another')) {
+        if (1 === (int) $request->get('create_another')) {
             // set value so create routine will not overwrite URL:
             $request->session()->put('link-types.create.fromStore', true);
 
@@ -240,14 +244,14 @@ class LinkController extends Controller
      * Update an existing link.
      *
      * @param LinkTypeFormRequest $request
-     * @param LinkType $linkType
+     * @param LinkType            $linkType
      *
-     * @return $this|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
+     * @return $this|RedirectResponse|Redirector
      */
     public function update(LinkTypeFormRequest $request, LinkType $linkType)
     {
         if (!$linkType->editable) {
-            $request->session()->flash('error', (string)trans('firefly.cannot_edit_link_type', ['name' => e($linkType->name)]));
+            $request->session()->flash('error', (string) trans('firefly.cannot_edit_link_type', ['name' => e($linkType->name)]));
 
             return redirect(route('admin.links.index'));
         }
@@ -261,10 +265,10 @@ class LinkController extends Controller
 
         Log::channel('audit')->info(sprintf('User update link type #%d.', $linkType->id), $data);
 
-        $request->session()->flash('success', (string)trans('firefly.updated_link_type', ['name' => $linkType->name]));
+        $request->session()->flash('success', (string) trans('firefly.updated_link_type', ['name' => $linkType->name]));
         app('preferences')->mark();
         $redirect = redirect($this->getPreviousUri('link-types.edit.uri'));
-        if (1 === (int)$request->get('return_to_edit')) {
+        if (1 === (int) $request->get('return_to_edit')) {
             // set value so edit routine will not overwrite URL:
             $request->session()->put('link-types.edit.fromUpdate', true);
 
diff --git a/app/Http/Controllers/Admin/TelemetryController.php b/app/Http/Controllers/Admin/TelemetryController.php
index 0456883e67..b0ac841193 100644
--- a/app/Http/Controllers/Admin/TelemetryController.php
+++ b/app/Http/Controllers/Admin/TelemetryController.php
@@ -21,8 +21,9 @@
 
 namespace FireflyIII\Http\Controllers\Admin;
 
-
 use FireflyIII\Http\Controllers\Controller;
+use Illuminate\Contracts\View\Factory;
+use Illuminate\View\View;
 
 /**
  * Class TelemetryController
@@ -35,7 +36,7 @@ class TelemetryController extends Controller
 
         $this->middleware(
             static function ($request, $next) {
-                app('view')->share('title', (string)trans('firefly.administration'));
+                app('view')->share('title', (string) trans('firefly.administration'));
                 app('view')->share('mainTitleIcon', 'fa-hand-spock-o');
 
                 return $next($request);
@@ -59,7 +60,7 @@ class TelemetryController extends Controller
     public function index()
     {
         app('view')->share('subTitleIcon', 'fa-eye');
-        app('view')->share('subTitle', (string)trans('firefly.telemetry_admin_index'));
+        app('view')->share('subTitle', (string) trans('firefly.telemetry_admin_index'));
         $version = config('firefly.version');
         $enabled = config('firefly.telemetry', false);
         $count   = 1;
@@ -68,11 +69,10 @@ class TelemetryController extends Controller
     }
 
     /**
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function view()
     {
         return view('admin.telemetry.view');
     }
-
-}
\ No newline at end of file
+}
diff --git a/app/Http/Controllers/Admin/UpdateController.php b/app/Http/Controllers/Admin/UpdateController.php
index 620ccb7565..f21d016fda 100644
--- a/app/Http/Controllers/Admin/UpdateController.php
+++ b/app/Http/Controllers/Admin/UpdateController.php
@@ -27,8 +27,13 @@ use FireflyIII\Helpers\Update\UpdateTrait;
 use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\Http\Middleware\IsDemoUser;
 use FireflyIII\Http\Middleware\IsSandStormUser;
+use Illuminate\Contracts\View\Factory;
 use Illuminate\Http\RedirectResponse;
 use Illuminate\Http\Request;
+use Illuminate\Routing\Redirector;
+use Illuminate\View\View;
+use Psr\Container\ContainerExceptionInterface;
+use Psr\Container\NotFoundExceptionInterface;
 
 /**
  * Class HomeController.
@@ -45,7 +50,7 @@ class UpdateController extends Controller
         parent::__construct();
         $this->middleware(
             static function ($request, $next) {
-                app('view')->share('title', (string)trans('firefly.administration'));
+                app('view')->share('title', (string) trans('firefly.administration'));
                 app('view')->share('mainTitleIcon', 'fa-hand-spock-o');
 
                 return $next($request);
@@ -58,28 +63,28 @@ class UpdateController extends Controller
     /**
      * Show page with update options.
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
-     * @throws \Psr\Container\NotFoundExceptionInterface
-     * @throws \Psr\Container\ContainerExceptionInterface
+     * @throws NotFoundExceptionInterface
+     * @throws ContainerExceptionInterface
+     * @return Factory|View
      */
     public function index()
     {
-        $subTitle        = (string)trans('firefly.update_check_title');
+        $subTitle        = (string) trans('firefly.update_check_title');
         $subTitleIcon    = 'fa-star';
         $permission      = app('fireflyconfig')->get('permission_update_check', -1);
         $channel         = app('fireflyconfig')->get('update_channel', 'stable');
         $selected        = $permission->data;
         $channelSelected = $channel->data;
         $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_ask_me_later'),
+            0  => (string) trans('firefly.updates_do_not_check'),
+            1  => (string) trans('firefly.updates_enable_check'),
         ];
 
         $channelOptions = [
-            'stable' => (string)trans('firefly.update_channel_stable'),
-            'beta'   => (string)trans('firefly.update_channel_beta'),
-            'alpha'  => (string)trans('firefly.update_channel_alpha'),
+            'stable' => (string) trans('firefly.update_channel_stable'),
+            'beta'   => (string) trans('firefly.update_channel_beta'),
+            'alpha'  => (string) trans('firefly.update_channel_alpha'),
         ];
 
         return view('admin.update.index', compact('subTitle', 'subTitleIcon', 'selected', 'options', 'channelSelected', 'channelOptions'));
@@ -90,17 +95,17 @@ class UpdateController extends Controller
      *
      * @param Request $request
      *
-     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
+     * @return RedirectResponse|Redirector
      */
     public function post(Request $request)
     {
-        $checkForUpdates = (int)$request->get('check_for_updates');
+        $checkForUpdates = (int) $request->get('check_for_updates');
         $channel         = $request->get('update_channel');
         $channel         = in_array($channel, ['stable', 'beta', 'alpha'], true) ? $channel : 'stable';
         app('fireflyconfig')->set('permission_update_check', $checkForUpdates);
         app('fireflyconfig')->set('last_update_check', time());
         app('fireflyconfig')->set('update_channel', $channel);
-        session()->flash('success', (string)trans('firefly.configuration_updated'));
+        session()->flash('success', (string) trans('firefly.configuration_updated'));
 
         return redirect(route('admin.update-check'));
     }
@@ -110,7 +115,7 @@ class UpdateController extends Controller
      */
     public function updateCheck(): RedirectResponse
     {
-        $release      = $this->getLatestRelease();
+        $release = $this->getLatestRelease();
 
         session()->flash($release['level'], $release['message']);
 
diff --git a/app/Http/Controllers/Admin/UserController.php b/app/Http/Controllers/Admin/UserController.php
index 605ce72cb0..0236199d6c 100644
--- a/app/Http/Controllers/Admin/UserController.php
+++ b/app/Http/Controllers/Admin/UserController.php
@@ -28,6 +28,8 @@ use FireflyIII\Http\Middleware\IsSandStormUser;
 use FireflyIII\Http\Requests\UserFormRequest;
 use FireflyIII\Repositories\User\UserRepositoryInterface;
 use FireflyIII\User;
+use Illuminate\Http\RedirectResponse;
+use Illuminate\Routing\Redirector;
 use Log;
 
 /**
@@ -47,9 +49,10 @@ class UserController extends Controller
 
         $this->middleware(
             function ($request, $next) {
-                app('view')->share('title', (string)trans('firefly.administration'));
+                app('view')->share('title', (string) trans('firefly.administration'));
                 app('view')->share('mainTitleIcon', 'fa-hand-spock-o');
                 $this->repository = app(UserRepositoryInterface::class);
+
                 return $next($request);
             }
         );
@@ -66,7 +69,7 @@ class UserController extends Controller
      */
     public function delete(User $user)
     {
-        $subTitle = (string)trans('firefly.delete_user', ['email' => $user->email]);
+        $subTitle = (string) trans('firefly.delete_user', ['email' => $user->email]);
 
         return view('admin.users.delete', compact('user', 'subTitle'));
     }
@@ -74,14 +77,14 @@ class UserController extends Controller
     /**
      * Destroy a user.
      *
-     * @param User                    $user
+     * @param User $user
      *
-     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
+     * @return RedirectResponse|Redirector
      */
     public function destroy(User $user)
     {
         $this->repository->destroy($user);
-        session()->flash('success', (string)trans('firefly.user_deleted'));
+        session()->flash('success', (string) trans('firefly.user_deleted'));
 
         return redirect(route('admin.users'));
     }
@@ -101,13 +104,13 @@ class UserController extends Controller
         }
         session()->forget('users.edit.fromUpdate');
 
-        $subTitle     = (string)trans('firefly.edit_user', ['email' => $user->email]);
+        $subTitle     = (string) trans('firefly.edit_user', ['email' => $user->email]);
         $subTitleIcon = 'fa-user-o';
         $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'),
+            ''              => (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'),
         ];
 
         return view('admin.users.edit', compact('user', 'subTitle', 'subTitleIcon', 'codes'));
@@ -120,7 +123,7 @@ class UserController extends Controller
      */
     public function index()
     {
-        $subTitle     = (string)trans('firefly.user_administration');
+        $subTitle     = (string) trans('firefly.user_administration');
         $subTitleIcon = 'fa-users';
         $users        = $this->repository->all();
 
@@ -138,32 +141,38 @@ class UserController extends Controller
     /**
      * Show single user.
      *
-     * @param User                    $user
+     * @param User $user
      *
      * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
      */
     public function show(User $user)
     {
-        $title         = (string)trans('firefly.administration');
+        $title         = (string) trans('firefly.administration');
         $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(
-            'admin.users.show', compact(
-                                  'title', 'mainTitleIcon', 'subTitle', 'subTitleIcon', 'information', 'user'
-                              )
+            'admin.users.show',
+            compact(
+                'title',
+                'mainTitleIcon',
+                'subTitle',
+                'subTitleIcon',
+                'information',
+                'user'
+            )
         );
     }
 
     /**
      * Update single user.
      *
-     * @param UserFormRequest         $request
-     * @param User                    $user
+     * @param UserFormRequest $request
+     * @param User            $user
      *
-     * @return $this|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
+     * @return $this|RedirectResponse|Redirector
      */
     public function update(UserFormRequest $request, User $user)
     {
@@ -178,10 +187,10 @@ class UserController extends Controller
         $this->repository->changeStatus($user, $data['blocked'], $data['blocked_code']);
         $this->repository->updateEmail($user, $data['email']);
 
-        session()->flash('success', (string)trans('firefly.updated_user', ['email' => $user->email]));
+        session()->flash('success', (string) trans('firefly.updated_user', ['email' => $user->email]));
         app('preferences')->mark();
         $redirect = redirect($this->getPreviousUri('users.edit.uri'));
-        if (1 === (int)$request->get('return_to_edit')) {
+        if (1 === (int) $request->get('return_to_edit')) {
             // @codeCoverageIgnoreStart
             session()->put('users.edit.fromUpdate', true);
 
diff --git a/app/Http/Controllers/AttachmentController.php b/app/Http/Controllers/AttachmentController.php
index 2b52e55758..211be6430d 100644
--- a/app/Http/Controllers/AttachmentController.php
+++ b/app/Http/Controllers/AttachmentController.php
@@ -41,6 +41,7 @@ class AttachmentController extends Controller
 
     /**
      * AttachmentController constructor.
+     *
      * @codeCoverageIgnore
      */
     public function __construct()
@@ -51,7 +52,7 @@ class AttachmentController extends Controller
         $this->middleware(
             function ($request, $next) {
                 app('view')->share('mainTitleIcon', 'fa-paperclip');
-                app('view')->share('title', (string)trans('firefly.attachments'));
+                app('view')->share('title', (string) trans('firefly.attachments'));
                 $this->repository = app(AttachmentRepositoryInterface::class);
 
                 return $next($request);
@@ -68,7 +69,7 @@ class AttachmentController extends Controller
      */
     public function delete(Attachment $attachment)
     {
-        $subTitle = (string)trans('firefly.delete_attachment', ['name' => $attachment->filename]);
+        $subTitle = (string) trans('firefly.delete_attachment', ['name' => $attachment->filename]);
 
         // put previous url in session
         $this->rememberPreviousUri('attachments.delete.uri');
@@ -79,7 +80,7 @@ class AttachmentController extends Controller
     /**
      * Destroy attachment.
      *
-     * @param Request $request
+     * @param Request    $request
      * @param Attachment $attachment
      *
      * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
@@ -90,7 +91,7 @@ class AttachmentController extends Controller
 
         $this->repository->destroy($attachment);
 
-        $request->session()->flash('success', (string)trans('firefly.attachment_deleted', ['name' => $name]));
+        $request->session()->flash('success', (string) trans('firefly.attachment_deleted', ['name' => $name]));
         app('preferences')->mark();
 
         return redirect($this->getPreviousUri('attachments.delete.uri'));
@@ -101,9 +102,9 @@ class AttachmentController extends Controller
      *
      * @param Attachment $attachment
      *
+     * @throws FireflyException
      * @return mixed
      *
-     * @throws FireflyException
      */
     public function download(Attachment $attachment)
     {
@@ -132,7 +133,7 @@ class AttachmentController extends Controller
     /**
      * Edit an attachment.
      *
-     * @param Request $request
+     * @param Request    $request
      * @param Attachment $attachment
      *
      * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
@@ -140,7 +141,7 @@ class AttachmentController extends Controller
     public function edit(Request $request, Attachment $attachment)
     {
         $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')) {
@@ -179,7 +180,7 @@ class AttachmentController extends Controller
      * Update attachment.
      *
      * @param AttachmentFormRequest $request
-     * @param Attachment $attachment
+     * @param Attachment            $attachment
      *
      * @return RedirectResponse
      */
@@ -188,11 +189,11 @@ class AttachmentController extends Controller
         $data = $request->getAttachmentData();
         $this->repository->update($attachment, $data);
 
-        $request->session()->flash('success', (string)trans('firefly.attachment_updated', ['name' => $attachment->filename]));
+        $request->session()->flash('success', (string) trans('firefly.attachment_updated', ['name' => $attachment->filename]));
         app('preferences')->mark();
 
         $redirect = redirect($this->getPreviousUri('attachments.edit.uri'));
-        if (1 === (int)$request->get('return_to_edit')) {
+        if (1 === (int) $request->get('return_to_edit')) {
             // @codeCoverageIgnoreStart
             $request->session()->put('attachments.edit.fromUpdate', true);
 
@@ -209,8 +210,8 @@ class AttachmentController extends Controller
      *
      * @param Attachment $attachment
      *
-     * @return LaravelResponse
      * @throws FireflyException
+     * @return LaravelResponse
      */
     public function view(Request $request, Attachment $attachment): LaravelResponse
     {
@@ -231,11 +232,13 @@ class AttachmentController extends Controller
             ];
 
             return response()->make(
-                $content, 200, [
-                            'Content-Security-Policy' => implode('; ', $csp),
-                            'Content-Type'        => $attachment->mime,
-                            'Content-Disposition' => 'inline; filename="' . $attachment->filename . '"',
-                        ]
+                $content,
+                200,
+                [
+                    'Content-Security-Policy' => implode('; ', $csp),
+                    'Content-Type'            => $attachment->mime,
+                    'Content-Disposition'     => 'inline; filename="' . $attachment->filename . '"',
+                ]
             );
         }
         throw new FireflyException('Could not find the indicated attachment. The file is no longer there.');
diff --git a/app/Http/Controllers/Auth/ForgotPasswordController.php b/app/Http/Controllers/Auth/ForgotPasswordController.php
index a26156997b..d45cb00d97 100644
--- a/app/Http/Controllers/Auth/ForgotPasswordController.php
+++ b/app/Http/Controllers/Auth/ForgotPasswordController.php
@@ -26,13 +26,18 @@ namespace FireflyIII\Http\Controllers\Auth;
 use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\Repositories\User\UserRepositoryInterface;
 use FireflyIII\User;
+use Illuminate\Contracts\View\Factory;
 use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
+use Illuminate\Http\JsonResponse;
+use Illuminate\Http\RedirectResponse;
 use Illuminate\Http\Request;
 use Illuminate\Support\Facades\Password;
+use Illuminate\View\View;
 use Log;
 
 /**
  * Class ForgotPasswordController
+ *
  * @codeCoverageIgnore
  */
 class ForgotPasswordController extends Controller
@@ -51,11 +56,11 @@ class ForgotPasswordController extends Controller
     /**
      * Send a reset link to the given user.
      *
-     * @param  \Illuminate\Http\Request $request
+     * @param Request                 $request
      *
-     * @param UserRepositoryInterface   $repository
+     * @param UserRepositoryInterface $repository
      *
-     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
+     * @return RedirectResponse|JsonResponse
      */
     public function sendResetLinkEmail(Request $request, UserRepositoryInterface $repository)
     {
@@ -77,7 +82,7 @@ class ForgotPasswordController extends Controller
         $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')]);
+            return back()->withErrors(['email' => (string) trans('firefly.cannot_reset_demo_user')]);
         }
 
         // We will send the password reset link to this user. Once we have attempted
@@ -99,7 +104,7 @@ class ForgotPasswordController extends Controller
      *
      * @codeCoverageIgnore
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function showLinkRequestForm()
     {
@@ -114,7 +119,7 @@ class ForgotPasswordController extends Controller
         $singleUserMode    = app('fireflyconfig')->get('single_user_mode', config('firefly.configuration.single_user_mode'))->data;
         $userCount         = User::count();
         $allowRegistration = true;
-        $pageTitle         = (string)trans('firefly.forgot_pw_page_title');
+        $pageTitle         = (string) trans('firefly.forgot_pw_page_title');
         if (true === $singleUserMode && $userCount > 0) {
             $allowRegistration = false;
         }
diff --git a/app/Http/Controllers/Auth/LoginController.php b/app/Http/Controllers/Auth/LoginController.php
index b35328dc67..1b6ee69d60 100644
--- a/app/Http/Controllers/Auth/LoginController.php
+++ b/app/Http/Controllers/Auth/LoginController.php
@@ -26,10 +26,15 @@ use Adldap;
 use DB;
 use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\Providers\RouteServiceProvider;
+use Illuminate\Contracts\View\Factory;
 use Illuminate\Foundation\Auth\AuthenticatesUsers;
+use Illuminate\Http\JsonResponse;
+use Illuminate\Http\RedirectResponse;
 use Illuminate\Http\Request;
 use Illuminate\Validation\ValidationException;
+use Illuminate\View\View;
 use Log;
+use Symfony\Component\HttpFoundation\Response;
 
 /**
  * Class LoginController
@@ -66,11 +71,11 @@ class LoginController extends Controller
     /**
      * Handle a login request to the application.
      *
-     * @param \Illuminate\Http\Request $request
+     * @param Request $request
      *
-     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
+     * @throws ValidationException
+     * @return RedirectResponse|\Illuminate\Http\Response|JsonResponse
      *
-     * @throws \Illuminate\Validation\ValidationException
      */
     public function login(Request $request)
     {
@@ -121,13 +126,13 @@ class LoginController extends Controller
     /**
      * Show the application's login form.
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\Response|\Illuminate\View\View
+     * @return Factory|\Illuminate\Http\Response|View
      */
     public function showLoginForm(Request $request)
     {
         $count         = DB::table('users')->count();
         $loginProvider = config('firefly.login_provider');
-        $title         = (string)trans('firefly.login_page_title');
+        $title         = (string) trans('firefly.login_page_title');
         if (0 === $count && 'eloquent' === $loginProvider) {
             return redirect(route('register')); // @codeCoverageIgnore
         }
@@ -155,11 +160,11 @@ class LoginController extends Controller
     /**
      * Get the failed login response instance.
      *
-     * @param \Illuminate\Http\Request $request
-     *
-     * @return \Symfony\Component\HttpFoundation\Response
+     * @param Request $request
      *
      * @throws ValidationException
+     * @return Response
+     *
      */
     protected function sendFailedLoginResponse(Request $request)
     {
diff --git a/app/Http/Controllers/Auth/RegisterController.php b/app/Http/Controllers/Auth/RegisterController.php
index 88c32c106b..f6671ee5a2 100644
--- a/app/Http/Controllers/Auth/RegisterController.php
+++ b/app/Http/Controllers/Auth/RegisterController.php
@@ -28,9 +28,12 @@ use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\Support\Http\Controllers\CreateStuff;
 use FireflyIII\Support\Http\Controllers\RequestInformation;
 use FireflyIII\User;
-use Illuminate\Auth\Events\Registered;
+use Illuminate\Contracts\View\Factory;
 use Illuminate\Foundation\Auth\RegistersUsers;
+use Illuminate\Http\RedirectResponse;
 use Illuminate\Http\Request;
+use Illuminate\Routing\Redirector;
+use Illuminate\View\View;
 use Log;
 
 /**
@@ -67,7 +70,7 @@ class RegisterController extends Controller
      *
      * @param Request $request
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
+     * @return Factory|RedirectResponse|Redirector|View
      */
     public function register(Request $request)
     {
@@ -97,7 +100,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);
 
@@ -109,7 +112,7 @@ class RegisterController extends Controller
      *
      * @param Request $request
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function showRegistrationForm(Request $request)
     {
@@ -118,7 +121,7 @@ class RegisterController extends Controller
         $isDemoSite        = app('fireflyconfig')->get('is_demo_site', config('firefly.configuration.is_demo_site'))->data;
         $singleUserMode    = app('fireflyconfig')->get('single_user_mode', config('firefly.configuration.single_user_mode'))->data;
         $userCount         = User::count();
-        $pageTitle         = (string)trans('firefly.register_page_title');
+        $pageTitle         = (string) trans('firefly.register_page_title');
 
         if (true === $isDemoSite) {
             $allowRegistration = false;
diff --git a/app/Http/Controllers/Auth/ResetPasswordController.php b/app/Http/Controllers/Auth/ResetPasswordController.php
index 4b9372e896..da141ca67b 100644
--- a/app/Http/Controllers/Auth/ResetPasswordController.php
+++ b/app/Http/Controllers/Auth/ResetPasswordController.php
@@ -25,9 +25,13 @@ namespace FireflyIII\Http\Controllers\Auth;
 
 use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\User;
+use Illuminate\Contracts\View\Factory;
 use Illuminate\Foundation\Auth\ResetsPasswords;
+use Illuminate\Http\JsonResponse;
+use Illuminate\Http\RedirectResponse;
 use Illuminate\Http\Request;
 use Illuminate\Support\Facades\Password;
+use Illuminate\View\View;
 
 /**
  * Class ResetPasswordController
@@ -61,10 +65,10 @@ class ResetPasswordController extends Controller
     /**
      * Reset the given user's password.
      *
-     * @param  \Illuminate\Http\Request $request
+     * @param Request $request
      *
-     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
      * @throws \Illuminate\Validation\ValidationException
+     * @return RedirectResponse|JsonResponse
      */
     public function reset(Request $request)
     {
@@ -87,9 +91,10 @@ class ResetPasswordController extends Controller
         // 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, $password) {
-            $this->resetPassword($user, $password);
-        }
+            $this->credentials($request),
+            function ($user, $password) {
+                $this->resetPassword($user, $password);
+            }
         );
 
         // If the password was successfully reset, we will redirect the user back to
@@ -105,10 +110,10 @@ class ResetPasswordController extends Controller
      *
      * If no token is present, display the link request form.
      *
-     * @param  Request     $request
-     * @param  string|null $token
+     * @param Request     $request
+     * @param string|null $token
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function showResetForm(Request $request, $token = null)
     {
@@ -123,7 +128,7 @@ class ResetPasswordController extends Controller
         $singleUserMode    = app('fireflyconfig')->get('single_user_mode', config('firefly.configuration.single_user_mode'))->data;
         $userCount         = User::count();
         $allowRegistration = true;
-        $pageTitle         = (string)trans('firefly.reset_pw_page_title');
+        $pageTitle         = (string) trans('firefly.reset_pw_page_title');
         if (true === $singleUserMode && $userCount > 0) {
             $allowRegistration = false;
         }
diff --git a/app/Http/Controllers/Auth/TwoFactorController.php b/app/Http/Controllers/Auth/TwoFactorController.php
index 3f0ea68425..a0ed675119 100644
--- a/app/Http/Controllers/Auth/TwoFactorController.php
+++ b/app/Http/Controllers/Auth/TwoFactorController.php
@@ -24,8 +24,9 @@ namespace FireflyIII\Http\Controllers\Auth;
 
 use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\User;
+use Illuminate\Http\RedirectResponse;
 use Illuminate\Http\Request;
-use Log;
+use Illuminate\Routing\Redirector;
 use PragmaRX\Google2FALaravel\Support\Authenticator;
 use Preferences;
 
@@ -44,14 +45,15 @@ 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', compact('user', 'siteOwner', 'title'));
     }
 
     /**
      * @param Request $request
      *
-     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
+     * @return RedirectResponse|Redirector
      */
     public function submitMFA(Request $request)
     {
diff --git a/app/Http/Controllers/BillController.php b/app/Http/Controllers/BillController.php
index c41b5cbc4d..dd20530567 100644
--- a/app/Http/Controllers/BillController.php
+++ b/app/Http/Controllers/BillController.php
@@ -34,14 +34,17 @@ use FireflyIII\Repositories\Bill\BillRepositoryInterface;
 use FireflyIII\TransactionRules\TransactionMatcher;
 use FireflyIII\Transformers\AttachmentTransformer;
 use FireflyIII\Transformers\BillTransformer;
+use Illuminate\Contracts\View\Factory;
 use Illuminate\Http\RedirectResponse;
 use Illuminate\Http\Request;
+use Illuminate\Routing\Redirector;
 use Illuminate\Support\Collection;
+use Illuminate\View\View;
 use League\Fractal\Manager;
 use League\Fractal\Resource\Item;
 use League\Fractal\Serializer\DataArraySerializer;
-use Symfony\Component\HttpFoundation\ParameterBag;
 use Log;
+use Symfony\Component\HttpFoundation\ParameterBag;
 
 /**
  * Class BillController.
@@ -71,7 +74,7 @@ class BillController extends Controller
 
         $this->middleware(
             function ($request, $next) {
-                app('view')->share('title', (string)trans('firefly.bills'));
+                app('view')->share('title', (string) trans('firefly.bills'));
                 app('view')->share('mainTitleIcon', 'fa-calendar-o');
                 $this->attachments    = app(AttachmentHelperInterface::class);
                 $this->billRepository = app(BillRepositoryInterface::class);
@@ -86,7 +89,7 @@ class BillController extends Controller
      *
      * @param Request $request
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function create(Request $request)
     {
@@ -94,9 +97,9 @@ class BillController extends Controller
         /** @var array $billPeriods */
         $billPeriods = config('firefly.bill_periods');
         foreach ($billPeriods as $current) {
-            $periods[$current] = strtolower((string)trans('firefly.repeat_freq_' . $current));
+            $periods[$current] = strtolower((string) trans('firefly.repeat_freq_' . $current));
         }
-        $subTitle        = (string)trans('firefly.create_new_bill');
+        $subTitle        = (string) trans('firefly.create_new_bill');
         $defaultCurrency = app('amount')->getDefaultCurrency();
 
         // put previous url in session if not redirect from store (not "create another").
@@ -113,13 +116,13 @@ class BillController extends Controller
      *
      * @param Bill $bill
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function delete(Bill $bill)
     {
         // put previous url in session
         $this->rememberPreviousUri('bills.delete.uri');
-        $subTitle = (string)trans('firefly.delete_bill', ['name' => $bill->name]);
+        $subTitle = (string) trans('firefly.delete_bill', ['name' => $bill->name]);
 
         return view('bills.delete', compact('bill', 'subTitle'));
     }
@@ -130,14 +133,14 @@ class BillController extends Controller
      * @param Request $request
      * @param Bill    $bill
      *
-     * @return RedirectResponse|\Illuminate\Routing\Redirector
+     * @return RedirectResponse|Redirector
      */
     public function destroy(Request $request, Bill $bill)
     {
         $name = $bill->name;
         $this->billRepository->destroy($bill);
 
-        $request->session()->flash('success', (string)trans('firefly.deleted_bill', ['name' => $name]));
+        $request->session()->flash('success', (string) trans('firefly.deleted_bill', ['name' => $name]));
         app('preferences')->mark();
 
         return redirect($this->getPreviousUri('bills.delete.uri'));
@@ -149,7 +152,7 @@ class BillController extends Controller
      * @param Request $request
      * @param Bill    $bill
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function edit(Request $request, Bill $bill)
     {
@@ -158,10 +161,10 @@ class BillController extends Controller
         $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')) {
@@ -169,8 +172,8 @@ class BillController extends Controller
         }
 
         $currency         = app('amount')->getDefaultCurrency();
-        $bill->amount_min = round((float)$bill->amount_min, $currency->decimal_places);
-        $bill->amount_max = round((float)$bill->amount_max, $currency->decimal_places);
+        $bill->amount_min = round((float) $bill->amount_min, $currency->decimal_places);
+        $bill->amount_max = round((float) $bill->amount_max, $currency->decimal_places);
         $defaultCurrency  = app('amount')->getDefaultCurrency();
 
         // code to handle active-checkboxes
@@ -179,7 +182,7 @@ class BillController extends Controller
         $preFilled = [
             'notes'                   => $this->billRepository->getNoteText($bill),
             'transaction_currency_id' => $bill->transaction_currency_id,
-            'active'                  => $hasOldInput ? (bool)$request->old('active') : $bill->active,
+            'active'                  => $hasOldInput ? (bool) $request->old('active') : $bill->active,
         ];
 
         $request->session()->flash('preFilled', $preFilled);
@@ -191,7 +194,7 @@ class BillController extends Controller
     /**
      * Show all bills.
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function index()
     {
@@ -244,14 +247,14 @@ class BillController extends Controller
      * @param Request $request
      * @param Bill    $bill
      *
-     * @return RedirectResponse|\Illuminate\Routing\Redirector
-     * @throws \FireflyIII\Exceptions\FireflyException
+     * @throws FireflyException
+     * @return RedirectResponse|Redirector
      */
     public function rescan(Request $request, Bill $bill)
     {
         $total = 0;
         if (false === $bill->active) {
-            $request->session()->flash('warning', (string)trans('firefly.cannot_scan_inactive_bill'));
+            $request->session()->flash('warning', (string) trans('firefly.cannot_scan_inactive_bill'));
 
             return redirect(route('bills.show', [$bill->id]));
         }
@@ -261,7 +264,7 @@ class BillController extends Controller
             $total = 0;
         }
         if (0 === $set->count()) {
-            $request->session()->flash('error', (string)trans('firefly.no_rules_for_bill'));
+            $request->session()->flash('error', (string) trans('firefly.no_rules_for_bill'));
 
             return redirect(route('bills.show', [$bill->id]));
         }
@@ -282,7 +285,7 @@ class BillController extends Controller
         }
 
 
-        $request->session()->flash('success', (string)trans('firefly.rescanned_bill', ['total' => $total]));
+        $request->session()->flash('success', (string) trans('firefly.rescanned_bill', ['total' => $total]));
         app('preferences')->mark();
 
         return redirect(route('bills.show', [$bill->id]));
@@ -294,7 +297,7 @@ class BillController extends Controller
      * @param Request $request
      * @param Bill    $bill
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function show(Request $request, Bill $bill)
     {
@@ -306,8 +309,8 @@ class BillController extends Controller
         /** @var Carbon $end */
         $end            = session('end');
         $year           = $start->year;
-        $page           = (int)$request->get('page');
-        $pageSize       = (int)app('preferences')->get('listPageSize', 50)->data;
+        $page           = (int) $request->get('page');
+        $pageSize       = (int) app('preferences')->get('listPageSize', 50)->data;
         $yearAverage    = $this->billRepository->getYearAverage($bill, $start);
         $overallAverage = $this->billRepository->getOverallAverage($bill);
         $manager        = new Manager();
@@ -372,11 +375,11 @@ class BillController extends Controller
             $bill = $this->billRepository->store($billData);
         } catch (FireflyException $e) {
             Log::error($e->getMessage());
-            $request->session()->flash('error', (string)trans('firefly.bill_store_error'));
+            $request->session()->flash('error', (string) trans('firefly.bill_store_error'));
 
             return redirect(route('bills.create'))->withInput();
         }
-        $request->session()->flash('success', (string)trans('firefly.stored_new_bill', ['name' => $bill->name]));
+        $request->session()->flash('success', (string) trans('firefly.stored_new_bill', ['name' => $bill->name]));
         app('preferences')->mark();
 
         /** @var array $files */
@@ -403,7 +406,7 @@ class BillController extends Controller
         $billData = $request->getBillData();
         $bill     = $this->billRepository->update($bill, $billData);
 
-        $request->session()->flash('success', (string)trans('firefly.updated_bill', ['name' => $bill->name]));
+        $request->session()->flash('success', (string) trans('firefly.updated_bill', ['name' => $bill->name]));
         app('preferences')->mark();
 
         /** @var array $files */
@@ -416,7 +419,7 @@ class BillController extends Controller
         }
         $redirect = redirect($this->getPreviousUri('bills.edit.uri'));
 
-        if (1 === (int)$request->get('return_to_edit')) {
+        if (1 === (int) $request->get('return_to_edit')) {
             // @codeCoverageIgnoreStart
             $request->session()->put('bills.edit.fromUpdate', true);
 
@@ -455,8 +458,8 @@ class BillController extends Controller
                     'avg'                     => '0',
                 ];
 
-            $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[$currencyId]['avg'] = bcadd($sums[$currencyId]['avg'], $avg);
         }
 
diff --git a/app/Http/Controllers/Budget/AvailableBudgetController.php b/app/Http/Controllers/Budget/AvailableBudgetController.php
index 57e5b1c4ab..9458546129 100644
--- a/app/Http/Controllers/Budget/AvailableBudgetController.php
+++ b/app/Http/Controllers/Budget/AvailableBudgetController.php
@@ -23,7 +23,6 @@ declare(strict_types=1);
 
 namespace FireflyIII\Http\Controllers\Budget;
 
-
 use Carbon\Carbon;
 use Carbon\Exceptions\InvalidDateException;
 use FireflyIII\Http\Controllers\Controller;
@@ -31,7 +30,11 @@ use FireflyIII\Models\AvailableBudget;
 use FireflyIII\Models\TransactionCurrency;
 use FireflyIII\Repositories\Budget\AvailableBudgetRepositoryInterface;
 use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
+use Illuminate\Contracts\View\Factory;
+use Illuminate\Http\RedirectResponse;
 use Illuminate\Http\Request;
+use Illuminate\Routing\Redirector;
+use Illuminate\View\View;
 use Log;
 
 /**
@@ -55,7 +58,7 @@ class AvailableBudgetController extends Controller
 
         $this->middleware(
             function ($request, $next) {
-                app('view')->share('title', (string)trans('firefly.budgets'));
+                app('view')->share('title', (string) trans('firefly.budgets'));
                 app('view')->share('mainTitleIcon', 'fa-tasks');
                 $this->abRepository  = app(AvailableBudgetRepositoryInterface::class);
                 $this->currencyRepos = app(CurrencyRepositoryInterface::class);
@@ -75,7 +78,7 @@ class AvailableBudgetController extends Controller
      * @param Carbon                   $end
      * @param TransactionCurrency|null $currency
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
+     * @return Factory|RedirectResponse|Redirector|View
      */
     public function create(Request $request, Carbon $start, Carbon $end, ?TransactionCurrency $currency = null)
     {
@@ -92,7 +95,7 @@ class AvailableBudgetController extends Controller
 
             return redirect(route('available-budgets.edit', [$first->id]));
         }
-        $page = (int)($request->get('page') ?? 1);
+        $page = (int) ($request->get('page') ?? 1);
 
         return view('budgets.available-budgets.create', compact('start', 'end', 'page', 'currency'));
     }
@@ -104,7 +107,7 @@ class AvailableBudgetController extends Controller
      * @param Carbon  $start
      * @param Carbon  $end
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function createAlternative(Request $request, Carbon $start, Carbon $end)
     {
@@ -126,7 +129,7 @@ class AvailableBudgetController extends Controller
         );
 
 
-        $page = (int)($request->get('page') ?? 1);
+        $page = (int) ($request->get('page') ?? 1);
 
         return view('budgets.available-budgets.create-alternative', compact('start', 'end', 'page', 'currencies'));
     }
@@ -134,7 +137,7 @@ class AvailableBudgetController extends Controller
     /**
      * @param AvailableBudget $availableBudget
      *
-     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
+     * @return RedirectResponse|Redirector
      */
     public function delete(AvailableBudget $availableBudget)
     {
@@ -150,17 +153,17 @@ class AvailableBudgetController extends Controller
      * @param Carbon          $start
      * @param Carbon          $end
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function edit(AvailableBudget $availableBudget, Carbon $start, Carbon $end)
     {
-        return view('budgets.available-budgets.edit', compact('availableBudget','start','end'));
+        return view('budgets.available-budgets.edit', compact('availableBudget', 'start', 'end'));
     }
 
     /**
      * @param Request $request
      *
-     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
+     * @return RedirectResponse|Redirector
      */
     public function store(Request $request)
     {
@@ -174,7 +177,7 @@ class AvailableBudgetController extends Controller
             Log::info($e->getMessage());
         }
         // find currency
-        $currency = $this->currencyRepos->find((int)$request->get('currency_id'));
+        $currency = $this->currencyRepos->find((int) $request->get('currency_id'));
         if (null === $currency) {
             session()->flash('error', trans('firefly.invalid_currency'));
 
@@ -209,7 +212,7 @@ class AvailableBudgetController extends Controller
      * @param Carbon          $start
      * @param Carbon          $end
      *
-     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
+     * @return RedirectResponse|Redirector
      */
     public function update(Request $request, AvailableBudget $availableBudget, Carbon $start, Carbon $end)
     {
@@ -218,5 +221,4 @@ class AvailableBudgetController extends Controller
 
         return redirect(route('budgets.index', [$start->format('Y-m-d'), $end->format('Y-m-d')]));
     }
-
-}
\ No newline at end of file
+}
diff --git a/app/Http/Controllers/Budget/BudgetLimitController.php b/app/Http/Controllers/Budget/BudgetLimitController.php
index 800c5ed0b4..5e528faf61 100644
--- a/app/Http/Controllers/Budget/BudgetLimitController.php
+++ b/app/Http/Controllers/Budget/BudgetLimitController.php
@@ -23,7 +23,6 @@ declare(strict_types=1);
 
 namespace FireflyIII\Http\Controllers\Budget;
 
-
 use Carbon\Carbon;
 use FireflyIII\Exceptions\FireflyException;
 use FireflyIII\Http\Controllers\Controller;
@@ -36,9 +35,13 @@ use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
 use FireflyIII\Repositories\Budget\OperationsRepositoryInterface;
 use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
 use FireflyIII\Support\Http\Controllers\DateCalculation;
+use Illuminate\Contracts\View\Factory;
 use Illuminate\Http\JsonResponse;
+use Illuminate\Http\RedirectResponse;
 use Illuminate\Http\Request;
+use Illuminate\Routing\Redirector;
 use Illuminate\Support\Collection;
+use Illuminate\View\View;
 use Log;
 
 /**
@@ -66,7 +69,7 @@ class BudgetLimitController extends Controller
         parent::__construct();
         $this->middleware(
             function ($request, $next) {
-                app('view')->share('title', (string)trans('firefly.budgets'));
+                app('view')->share('title', (string) trans('firefly.budgets'));
                 app('view')->share('mainTitleIcon', 'fa-tasks');
                 $this->repository    = app(BudgetRepositoryInterface::class);
                 $this->opsRepository = app(OperationsRepositoryInterface::class);
@@ -83,7 +86,7 @@ class BudgetLimitController extends Controller
      * @param Carbon $start
      * @param Carbon $end
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function create(Budget $budget, Carbon $start, Carbon $end)
     {
@@ -111,7 +114,7 @@ class BudgetLimitController extends Controller
      * @param Request     $request
      * @param BudgetLimit $budgetLimit
      *
-     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
+     * @return RedirectResponse|Redirector
      */
     public function delete(Request $request, BudgetLimit $budgetLimit)
     {
@@ -124,14 +127,14 @@ class BudgetLimitController extends Controller
     /**
      * @param Request $request
      *
-     * @return JsonResponse|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
      * @throws FireflyException
+     * @return JsonResponse|RedirectResponse|Redirector
      */
     public function store(Request $request)
     {
         // first search for existing one and update it if necessary.
-        $currency = $this->currencyRepos->find((int)$request->get('transaction_currency_id'));
-        $budget   = $this->repository->findNull((int)$request->get('budget_id'));
+        $currency = $this->currencyRepos->find((int) $request->get('transaction_currency_id'));
+        $budget   = $this->repository->findNull((int) $request->get('budget_id'));
         if (null === $currency || null === $budget) {
             throw new FireflyException('No valid currency or budget.');
         }
@@ -169,7 +172,7 @@ class BudgetLimitController extends Controller
             $array['spent']            = $spentArr[$currency->id]['sum'] ?? '0';
             $array['left_formatted']   = app('amount')->formatAnything($limit->transactionCurrency, bcadd($array['spent'], $array['amount']));
             $array['amount_formatted'] = app('amount')->formatAnything($limit->transactionCurrency, $limit['amount']);
-            $array['days_left']        = (string)$this->activeDaysLeft($start, $end);
+            $array['days_left']        = (string) $this->activeDaysLeft($start, $end);
             // left per day:
             $array['left_per_day'] = bcdiv(bcadd($array['spent'], $array['amount']), $array['days_left']);
 
@@ -196,12 +199,16 @@ class BudgetLimitController extends Controller
         $array = $limit->toArray();
 
         $spentArr                  = $this->opsRepository->sumExpenses(
-            $limit->start_date, $limit->end_date, null, new Collection([$budgetLimit->budget]), $budgetLimit->transactionCurrency
+            $limit->start_date,
+            $limit->end_date,
+            null,
+            new Collection([$budgetLimit->budget]),
+            $budgetLimit->transactionCurrency
         );
         $array['spent']            = $spentArr[$budgetLimit->transactionCurrency->id]['sum'] ?? '0';
         $array['left_formatted']   = app('amount')->formatAnything($limit->transactionCurrency, bcadd($array['spent'], $array['amount']));
         $array['amount_formatted'] = app('amount')->formatAnything($limit->transactionCurrency, $limit['amount']);
-        $array['days_left']        = (string)$this->activeDaysLeft($limit->start_date, $limit->end_date);
+        $array['days_left']        = (string) $this->activeDaysLeft($limit->start_date, $limit->end_date);
         // left per day:
         $array['left_per_day'] = bcdiv(bcadd($array['spent'], $array['amount']), $array['days_left']);
 
@@ -210,7 +217,5 @@ class BudgetLimitController extends Controller
         $array['left_per_day_formatted'] = app('amount')->formatAnything($limit->transactionCurrency, $array['left_per_day']);
 
         return response()->json($array);
-
     }
-
-}
\ No newline at end of file
+}
diff --git a/app/Http/Controllers/Budget/CreateController.php b/app/Http/Controllers/Budget/CreateController.php
index 6418b8251f..607e3ea84e 100644
--- a/app/Http/Controllers/Budget/CreateController.php
+++ b/app/Http/Controllers/Budget/CreateController.php
@@ -25,10 +25,13 @@ namespace FireflyIII\Http\Controllers\Budget;
 
 
 use FireflyIII\Http\Controllers\Controller;
-use FireflyIII\Http\Requests\BudgetFormRequest;
+use FireflyIII\Http\Requests\BudgetFormStoreRequest;
+use FireflyIII\Models\AutoBudget;
 use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
+use Illuminate\Contracts\View\Factory;
 use Illuminate\Http\RedirectResponse;
 use Illuminate\Http\Request;
+use Illuminate\View\View;
 
 /**
  * Class CreateController
@@ -40,6 +43,7 @@ class CreateController extends Controller
 
     /**
      * CreateController constructor.
+     *
      * @codeCoverageIgnore
      */
     public function __construct()
@@ -49,7 +53,7 @@ class CreateController extends Controller
 
         $this->middleware(
             function ($request, $next) {
-                app('view')->share('title', (string)trans('firefly.budgets'));
+                app('view')->share('title', (string) trans('firefly.budgets'));
                 app('view')->share('mainTitleIcon', 'fa-tasks');
                 $this->repository = app(BudgetRepositoryInterface::class);
 
@@ -64,39 +68,65 @@ class CreateController extends Controller
      *
      * @param Request $request
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function create(Request $request)
     {
+        $hasOldInput = null !== $request->old('_token');
+
+        // auto budget types
+        $autoBudgetTypes   = [
+            0                                => (string) trans('firefly.auto_budget_none'),
+            AutoBudget::AUTO_BUDGET_RESET    => (string) trans('firefly.auto_budget_reset'),
+            AutoBudget::AUTO_BUDGET_ROLLOVER => (string) trans('firefly.auto_budget_rollover'),
+        ];
+        $autoBudgetPeriods = [
+            'daily'     => (string) trans('firefly.auto_budget_period_daily'),
+            'weekly'    => (string) trans('firefly.auto_budget_period_weekly'),
+            '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'),
+        ];
+        $currency          = app('amount')->getDefaultCurrency();
+
+        $preFilled = [
+            'auto_budget_period'      => $hasOldInput ? (bool) $request->old('auto_budget_period') : 'monthly',
+            'auto_budget_currency_id' => $hasOldInput ? (int) $request->old('auto_budget_currency_id') : $currency->id,
+        ];
+
+        $request->session()->flash('preFilled', $preFilled);
+
         // put previous url in session if not redirect from store (not "create another").
         if (true !== session('budgets.create.fromStore')) {
             $this->rememberPreviousUri('budgets.create.uri');
         }
         $request->session()->forget('budgets.create.fromStore');
-        $subTitle = (string)trans('firefly.create_new_budget');
+        $subTitle = (string) trans('firefly.create_new_budget');
 
-        return view('budgets.create', compact('subTitle'));
+        return view('budgets.create', compact('subTitle', 'autoBudgetTypes', 'autoBudgetPeriods'));
     }
 
 
     /**
      * Stores a budget.
      *
-     * @param BudgetFormRequest $request
+     * @param BudgetFormStoreRequest $request
      *
-     * @return \Illuminate\Http\RedirectResponse
+     * @return RedirectResponse
      */
-    public function store(BudgetFormRequest $request): RedirectResponse
+    public function store(BudgetFormStoreRequest $request): RedirectResponse
     {
-        $data   = $request->getBudgetData();
+        $data = $request->getBudgetData();
+
         $budget = $this->repository->store($data);
         $this->repository->cleanupBudgets();
-        $request->session()->flash('success', (string)trans('firefly.stored_new_budget', ['name' => $budget->name]));
+        $request->session()->flash('success', (string) trans('firefly.stored_new_budget', ['name' => $budget->name]));
         app('preferences')->mark();
 
         $redirect = redirect($this->getPreviousUri('budgets.create.uri'));
 
-        if (1 === (int)$request->get('create_another')) {
+        if (1 === (int) $request->get('create_another')) {
             // @codeCoverageIgnoreStart
             $request->session()->put('budgets.create.fromStore', true);
 
diff --git a/app/Http/Controllers/Budget/DeleteController.php b/app/Http/Controllers/Budget/DeleteController.php
index d6090143d4..442b856fa8 100644
--- a/app/Http/Controllers/Budget/DeleteController.php
+++ b/app/Http/Controllers/Budget/DeleteController.php
@@ -27,7 +27,11 @@ namespace FireflyIII\Http\Controllers\Budget;
 use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\Models\Budget;
 use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
+use Illuminate\Contracts\View\Factory;
+use Illuminate\Http\RedirectResponse;
 use Illuminate\Http\Request;
+use Illuminate\Routing\Redirector;
+use Illuminate\View\View;
 
 /**
  *
@@ -40,6 +44,7 @@ class DeleteController extends Controller
 
     /**
      * DeleteController constructor.
+     *
      * @codeCoverageIgnore
      */
     public function __construct()
@@ -48,7 +53,7 @@ class DeleteController extends Controller
 
         $this->middleware(
             function ($request, $next) {
-                app('view')->share('title', (string)trans('firefly.budgets'));
+                app('view')->share('title', (string) trans('firefly.budgets'));
                 app('view')->share('mainTitleIcon', 'fa-tasks');
                 $this->repository = app(BudgetRepositoryInterface::class);
 
@@ -63,11 +68,11 @@ class DeleteController extends Controller
      *
      * @param Budget $budget
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function delete(Budget $budget)
     {
-        $subTitle = (string)trans('firefly.delete_budget', ['name' => $budget->name]);
+        $subTitle = (string) trans('firefly.delete_budget', ['name' => $budget->name]);
 
         // put previous url in session
         $this->rememberPreviousUri('budgets.delete.uri');
@@ -81,13 +86,13 @@ class DeleteController extends Controller
      * @param Request $request
      * @param Budget  $budget
      *
-     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
+     * @return RedirectResponse|Redirector
      */
     public function destroy(Request $request, Budget $budget)
     {
         $name = $budget->name;
         $this->repository->destroy($budget);
-        $request->session()->flash('success', (string)trans('firefly.deleted_budget', ['name' => $name]));
+        $request->session()->flash('success', (string) trans('firefly.deleted_budget', ['name' => $name]));
         app('preferences')->mark();
 
         return redirect($this->getPreviousUri('budgets.delete.uri'));
diff --git a/app/Http/Controllers/Budget/EditController.php b/app/Http/Controllers/Budget/EditController.php
index f7af796cd7..ad79b1cced 100644
--- a/app/Http/Controllers/Budget/EditController.php
+++ b/app/Http/Controllers/Budget/EditController.php
@@ -25,11 +25,14 @@ namespace FireflyIII\Http\Controllers\Budget;
 
 
 use FireflyIII\Http\Controllers\Controller;
-use FireflyIII\Http\Requests\BudgetFormRequest;
+use FireflyIII\Http\Requests\BudgetFormUpdateRequest;
+use FireflyIII\Models\AutoBudget;
 use FireflyIII\Models\Budget;
 use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
+use Illuminate\Contracts\View\Factory;
 use Illuminate\Http\RedirectResponse;
 use Illuminate\Http\Request;
+use Illuminate\View\View;
 
 /**
  *
@@ -42,6 +45,7 @@ class EditController extends Controller
 
     /**
      * EditController constructor.
+     *
      * @codeCoverageIgnore
      */
     public function __construct()
@@ -50,7 +54,7 @@ class EditController extends Controller
 
         $this->middleware(
             function ($request, $next) {
-                app('view')->share('title', (string)trans('firefly.budgets'));
+                app('view')->share('title', (string) trans('firefly.budgets'));
                 app('view')->share('mainTitleIcon', 'fa-tasks');
                 $this->repository = app(BudgetRepositoryInterface::class);
 
@@ -65,17 +69,38 @@ class EditController extends Controller
      * @param Request $request
      * @param Budget  $budget
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function edit(Request $request, Budget $budget)
     {
-        $subTitle = (string)trans('firefly.edit_budget', ['name' => $budget->name]);
+        $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'),
+            AutoBudget::AUTO_BUDGET_RESET    => (string) trans('firefly.auto_budget_reset'),
+            AutoBudget::AUTO_BUDGET_ROLLOVER => (string) trans('firefly.auto_budget_rollover'),
+        ];
+        $autoBudgetPeriods = [
+            'daily'     => (string) trans('firefly.auto_budget_period_daily'),
+            'weekly'    => (string) trans('firefly.auto_budget_period_weekly'),
+            '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'),
+        ];
 
         // code to handle active-checkboxes
         $hasOldInput = null !== $request->old('_token');
+        $currency    = app('amount')->getDefaultCurrency();
         $preFilled   = [
-            'active' => $hasOldInput ? (bool)$request->old('active') : $budget->active,
+            'active'                  => $hasOldInput ? (bool) $request->old('active') : $budget->active,
+            'auto_budget_currency_id' => $hasOldInput ? (int) $request->old('auto_budget_currency_id') : $currency->id,
         ];
+        if ($autoBudget) {
+            $preFilled['auto_budget_amount'] = $hasOldInput ? $request->old('auto_budget_amount') : $autoBudget->amount;
+        }
 
         // put previous url in session if not redirect from store (not "return_to_edit").
         if (true !== session('budgets.edit.fromUpdate')) {
@@ -84,29 +109,29 @@ class EditController extends Controller
         $request->session()->forget('budgets.edit.fromUpdate');
         $request->session()->flash('preFilled', $preFilled);
 
-        return view('budgets.edit', compact('budget', 'subTitle'));
+        return view('budgets.edit', compact('budget', 'subTitle', 'autoBudgetTypes', 'autoBudgetPeriods', 'autoBudget'));
     }
 
     /**
      * Budget update routine.
      *
-     * @param BudgetFormRequest $request
-     * @param Budget            $budget
+     * @param BudgetFormUpdateRequest $request
+     * @param Budget                  $budget
      *
-     * @return \Illuminate\Http\RedirectResponse
+     * @return RedirectResponse
      */
-    public function update(BudgetFormRequest $request, Budget $budget): RedirectResponse
+    public function update(BudgetFormUpdateRequest $request, Budget $budget): RedirectResponse
     {
         $data = $request->getBudgetData();
         $this->repository->update($budget, $data);
 
-        $request->session()->flash('success', (string)trans('firefly.updated_budget', ['name' => $budget->name]));
+        $request->session()->flash('success', (string) trans('firefly.updated_budget', ['name' => $budget->name]));
         $this->repository->cleanupBudgets();
         app('preferences')->mark();
 
         $redirect = redirect($this->getPreviousUri('budgets.edit.uri'));
 
-        if (1 === (int)$request->get('return_to_edit')) {
+        if (1 === (int) $request->get('return_to_edit')) {
             // @codeCoverageIgnoreStart
             $request->session()->put('budgets.edit.fromUpdate', true);
 
diff --git a/app/Http/Controllers/Budget/IndexController.php b/app/Http/Controllers/Budget/IndexController.php
index f783877877..4690f03887 100644
--- a/app/Http/Controllers/Budget/IndexController.php
+++ b/app/Http/Controllers/Budget/IndexController.php
@@ -23,7 +23,6 @@ declare(strict_types=1);
 
 namespace FireflyIII\Http\Controllers\Budget;
 
-
 use Carbon\Carbon;
 use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\Models\AvailableBudget;
@@ -36,9 +35,11 @@ use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
 use FireflyIII\Repositories\Budget\OperationsRepositoryInterface;
 use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
 use FireflyIII\Support\Http\Controllers\DateCalculation;
+use Illuminate\Contracts\View\Factory;
 use Illuminate\Http\JsonResponse;
 use Illuminate\Http\Request;
 use Illuminate\Support\Collection;
+use Illuminate\View\View;
 use Log;
 
 /**
@@ -47,7 +48,6 @@ use Log;
  */
 class IndexController extends Controller
 {
-
     use DateCalculation;
     /** @var AvailableBudgetRepositoryInterface */
     private $abRepository;
@@ -71,7 +71,7 @@ class IndexController extends Controller
 
         $this->middleware(
             function ($request, $next) {
-                app('view')->share('title', (string)trans('firefly.budgets'));
+                app('view')->share('title', (string) trans('firefly.budgets'));
                 app('view')->share('mainTitleIcon', 'fa-tasks');
                 $this->repository         = app(BudgetRepositoryInterface::class);
                 $this->opsRepository      = app(OperationsRepositoryInterface::class);
@@ -94,7 +94,7 @@ class IndexController extends Controller
      * @param Carbon|null $start
      * @param Carbon|null $end
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function index(Request $request, Carbon $start = null, Carbon $end = null)
     {
@@ -157,14 +157,15 @@ class IndexController extends Controller
         // complement budget with budget limits in range, and expenses in currency X in range.
         /** @var Budget $current */
         foreach ($collection as $current) {
-            $array             = $current->toArray();
-            $array['spent']    = [];
-            $array['budgeted'] = [];
-            $budgetLimits      = $this->blRepository->getBudgetLimits($current, $start, $end);
+            $array                = $current->toArray();
+            $array['spent']       = [];
+            $array['budgeted']    = [];
+            $array['auto_budget'] = $this->repository->getAutoBudget($current);
+            $budgetLimits         = $this->blRepository->getBudgetLimits($current, $start, $end);
 
             /** @var BudgetLimit $limit */
             foreach ($budgetLimits as $limit) {
-                $currency = $limit->transactionCurrency ?? $defaultCurrency;
+                $currency            = $limit->transactionCurrency ?? $defaultCurrency;
                 $array['budgeted'][] = [
                     'id'                      => $limit->id,
                     'amount'                  => round($limit->amount, $currency->decimal_places),
@@ -183,7 +184,6 @@ class IndexController extends Controller
                     $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;
@@ -194,18 +194,25 @@ class IndexController extends Controller
 
 
         return view(
-            'budgets.index', compact(
-                               'availableBudgets',
-                               'budgeted', 'spent',
-                               'prevLoop', 'nextLoop',
-                               'budgets',
-                               'currencies',
-                               'enableAddButton',
-                               'periodTitle',
-                               'defaultCurrency',
-                               'activeDaysPassed', 'activeDaysLeft',
-                               'inactive', 'budgets', 'start', 'end'
-                           )
+            'budgets.index',
+            compact(
+                'availableBudgets',
+                'budgeted',
+                'spent',
+                'prevLoop',
+                'nextLoop',
+                'budgets',
+                'currencies',
+                'enableAddButton',
+                'periodTitle',
+                'defaultCurrency',
+                'activeDaysPassed',
+                'activeDaysLeft',
+                'inactive',
+                'budgets',
+                'start',
+                'end'
+            )
         );
     }
 
@@ -221,7 +228,7 @@ class IndexController extends Controller
         $budgetIds = $request->get('budgetIds');
 
         foreach ($budgetIds as $index => $budgetId) {
-            $budgetId = (int)$budgetId;
+            $budgetId = (int) $budgetId;
             $budget   = $repository->findNull($budgetId);
             if (null !== $budget) {
                 Log::debug(sprintf('Set budget #%d ("%s") to position %d', $budget->id, $budget->name, $index + 1));
@@ -231,6 +238,4 @@ class IndexController extends Controller
 
         return response()->json(['OK']);
     }
-
-
 }
diff --git a/app/Http/Controllers/Budget/ShowController.php b/app/Http/Controllers/Budget/ShowController.php
index 5577640a39..5676e77660 100644
--- a/app/Http/Controllers/Budget/ShowController.php
+++ b/app/Http/Controllers/Budget/ShowController.php
@@ -34,7 +34,9 @@ use FireflyIII\Models\TransactionType;
 use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
 use FireflyIII\Support\Http\Controllers\AugumentData;
 use FireflyIII\Support\Http\Controllers\PeriodOverview;
+use Illuminate\Contracts\View\Factory;
 use Illuminate\Http\Request;
+use Illuminate\View\View;
 
 /**
  *
@@ -57,7 +59,7 @@ class ShowController extends Controller
         parent::__construct();
         $this->middleware(
             function ($request, $next) {
-                app('view')->share('title', (string)trans('firefly.budgets'));
+                app('view')->share('title', (string) trans('firefly.budgets'));
                 app('view')->share('mainTitleIcon', 'fa-tasks');
                 $this->journalRepos = app(JournalRepositoryInterface::class);
 
@@ -69,11 +71,11 @@ class ShowController extends Controller
     /**
      * Show transactions without a budget.
      *
-     * @param Request $request
+     * @param Request     $request
      * @param Carbon|null $start
      * @param Carbon|null $end
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function noBudget(Request $request, Carbon $start = null, Carbon $end = null)
     {
@@ -92,8 +94,8 @@ class ShowController extends Controller
         $first     = $this->journalRepos->firstNull();
         $firstDate = null !== $first ? $first->date : $start;
         $periods   = $this->getNoBudgetPeriodOverview($firstDate, $end);
-        $page      = (int)$request->get('page');
-        $pageSize  = (int)app('preferences')->get('listPageSize', 50)->data;
+        $page      = (int) $request->get('page');
+        $pageSize  = (int) app('preferences')->get('listPageSize', 50)->data;
 
         /** @var GroupCollectorInterface $collector */
         $collector = app(GroupCollectorInterface::class);
@@ -110,17 +112,17 @@ class ShowController extends Controller
      *
      * @param Request $request
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function noBudgetAll(Request $request)
     {
 
-        $subTitle = (string)trans('firefly.all_journals_without_budget');
+        $subTitle = (string) trans('firefly.all_journals_without_budget');
         $first    = $this->journalRepos->firstNull();
         $start    = null === $first ? new Carbon : $first->date;
         $end      = new Carbon;
-        $page     = (int)$request->get('page');
-        $pageSize = (int)app('preferences')->get('listPageSize', 50)->data;
+        $page     = (int) $request->get('page');
+        $pageSize = (int) app('preferences')->get('listPageSize', 50)->data;
 
         /** @var GroupCollectorInterface $collector */
         $collector = app(GroupCollectorInterface::class);
@@ -137,23 +139,23 @@ class ShowController extends Controller
      * Show a single budget.
      *
      * @param Request $request
-     * @param Budget $budget
+     * @param Budget  $budget
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function show(Request $request, Budget $budget)
     {
         /** @var Carbon $start */
-        $allStart      = session('first', Carbon::now()->startOfYear());
-        $allEnd        = new Carbon;
+        $allStart = session('first', Carbon::now()->startOfYear());
+        $allEnd   = new Carbon;
 
         // use session range:
         $start = session('start');
-        $end = session('end');
+        $end   = session('end');
 
 
-        $page       = (int)$request->get('page');
-        $pageSize   = (int)app('preferences')->get('listPageSize', 50)->data;
+        $page       = (int) $request->get('page');
+        $pageSize   = (int) app('preferences')->get('listPageSize', 50)->data;
         $limits     = $this->getLimits($budget, $allStart, $allEnd);
         $repetition = null;
 
@@ -161,12 +163,12 @@ class ShowController extends Controller
         /** @var GroupCollectorInterface $collector */
         $collector = app(GroupCollectorInterface::class);
         $collector->setRange($start, $end)->setBudget($budget)
-                                          ->withAccountInformation()
-                                          ->setLimit($pageSize)->setPage($page)->withBudgetInformation()->withCategoryInformation();
+                  ->withAccountInformation()
+                  ->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', compact('limits', 'budget', 'repetition', 'groups', 'subTitle'));
     }
@@ -174,12 +176,12 @@ class ShowController extends Controller
     /**
      * Show a single budget by a budget limit.
      *
-     * @param Request $request
-     * @param Budget $budget
+     * @param Request     $request
+     * @param Budget      $budget
      * @param BudgetLimit $budgetLimit
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
      * @throws FireflyException
+     * @return Factory|View
      */
     public function showByBudgetLimit(Request $request, Budget $budget, BudgetLimit $budgetLimit)
     {
@@ -187,14 +189,14 @@ class ShowController extends Controller
             throw new FireflyException('This budget limit is not part of this budget.'); // @codeCoverageIgnore
         }
 
-        $page     = (int)$request->get('page');
-        $pageSize = (int)app('preferences')->get('listPageSize', 50)->data;
+        $page     = (int) $request->get('page');
+        $pageSize = (int) app('preferences')->get('listPageSize', 50)->data;
         $subTitle = trans(
             'firefly.budget_in_period',
             [
-                'name'  => $budget->name,
-                'start' => $budgetLimit->start_date->formatLocalized($this->monthAndDayFormat),
-                'end'   => $budgetLimit->end_date->formatLocalized($this->monthAndDayFormat),
+                'name'     => $budget->name,
+                'start'    => $budgetLimit->start_date->formatLocalized($this->monthAndDayFormat),
+                'end'      => $budgetLimit->end_date->formatLocalized($this->monthAndDayFormat),
                 'currency' => $budgetLimit->transactionCurrency->name,
             ]
         );
diff --git a/app/Http/Controllers/Category/CreateController.php b/app/Http/Controllers/Category/CreateController.php
index fccb666e29..b9990df11c 100644
--- a/app/Http/Controllers/Category/CreateController.php
+++ b/app/Http/Controllers/Category/CreateController.php
@@ -27,7 +27,11 @@ namespace FireflyIII\Http\Controllers\Category;
 use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\Http\Requests\CategoryFormRequest;
 use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
+use Illuminate\Contracts\View\Factory;
+use Illuminate\Http\RedirectResponse;
 use Illuminate\Http\Request;
+use Illuminate\Routing\Redirector;
+use Illuminate\View\View;
 
 /**
  * Class CreateController
@@ -39,6 +43,7 @@ class CreateController extends Controller
 
     /**
      * CategoryController constructor.
+     *
      * @codeCoverageIgnore
      */
     public function __construct()
@@ -47,7 +52,7 @@ class CreateController extends Controller
 
         $this->middleware(
             function ($request, $next) {
-                app('view')->share('title', (string)trans('firefly.categories'));
+                app('view')->share('title', (string) trans('firefly.categories'));
                 app('view')->share('mainTitleIcon', 'fa-bar-chart');
                 $this->repository = app(CategoryRepositoryInterface::class);
 
@@ -62,7 +67,7 @@ class CreateController extends Controller
      *
      * @param Request $request
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function create(Request $request)
     {
@@ -70,7 +75,7 @@ class CreateController extends Controller
             $this->rememberPreviousUri('categories.create.uri');
         }
         $request->session()->forget('categories.create.fromStore');
-        $subTitle = (string)trans('firefly.create_new_category');
+        $subTitle = (string) trans('firefly.create_new_category');
 
         return view('categories.create', compact('subTitle'));
     }
@@ -81,18 +86,18 @@ class CreateController extends Controller
      *
      * @param CategoryFormRequest $request
      *
-     * @return $this|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
+     * @return $this|RedirectResponse|Redirector
      */
     public function store(CategoryFormRequest $request)
     {
         $data     = $request->getCategoryData();
         $category = $this->repository->store($data);
 
-        $request->session()->flash('success', (string)trans('firefly.stored_category', ['name' => $category->name]));
+        $request->session()->flash('success', (string) trans('firefly.stored_category', ['name' => $category->name]));
         app('preferences')->mark();
 
         $redirect = redirect(route('categories.index'));
-        if (1 === (int)$request->get('create_another')) {
+        if (1 === (int) $request->get('create_another')) {
             // @codeCoverageIgnoreStart
             $request->session()->put('categories.create.fromStore', true);
 
diff --git a/app/Http/Controllers/Category/DeleteController.php b/app/Http/Controllers/Category/DeleteController.php
index d79a0b2d99..6856243e14 100644
--- a/app/Http/Controllers/Category/DeleteController.php
+++ b/app/Http/Controllers/Category/DeleteController.php
@@ -27,7 +27,11 @@ namespace FireflyIII\Http\Controllers\Category;
 use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\Models\Category;
 use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
+use Illuminate\Contracts\View\Factory;
+use Illuminate\Http\RedirectResponse;
 use Illuminate\Http\Request;
+use Illuminate\Routing\Redirector;
+use Illuminate\View\View;
 
 /**
  * Class DeleteController
@@ -39,6 +43,7 @@ class DeleteController extends Controller
 
     /**
      * CategoryController constructor.
+     *
      * @codeCoverageIgnore
      */
     public function __construct()
@@ -47,7 +52,7 @@ class DeleteController extends Controller
 
         $this->middleware(
             function ($request, $next) {
-                app('view')->share('title', (string)trans('firefly.categories'));
+                app('view')->share('title', (string) trans('firefly.categories'));
                 app('view')->share('mainTitleIcon', 'fa-bar-chart');
                 $this->repository = app(CategoryRepositoryInterface::class);
 
@@ -61,11 +66,11 @@ class DeleteController extends Controller
      *
      * @param Category $category
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function delete(Category $category)
     {
-        $subTitle = (string)trans('firefly.delete_category', ['name' => $category->name]);
+        $subTitle = (string) trans('firefly.delete_category', ['name' => $category->name]);
 
         // put previous url in session
         $this->rememberPreviousUri('categories.delete.uri');
@@ -79,14 +84,14 @@ class DeleteController extends Controller
      * @param Request  $request
      * @param Category $category
      *
-     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
+     * @return RedirectResponse|Redirector
      */
     public function destroy(Request $request, Category $category)
     {
         $name = $category->name;
         $this->repository->destroy($category);
 
-        $request->session()->flash('success', (string)trans('firefly.deleted_category', ['name' => $name]));
+        $request->session()->flash('success', (string) trans('firefly.deleted_category', ['name' => $name]));
         app('preferences')->mark();
 
         return redirect($this->getPreviousUri('categories.delete.uri'));
diff --git a/app/Http/Controllers/Category/EditController.php b/app/Http/Controllers/Category/EditController.php
index 6d422c7f74..3a37863f4b 100644
--- a/app/Http/Controllers/Category/EditController.php
+++ b/app/Http/Controllers/Category/EditController.php
@@ -28,7 +28,11 @@ use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\Http\Requests\CategoryFormRequest;
 use FireflyIII\Models\Category;
 use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
+use Illuminate\Contracts\View\Factory;
+use Illuminate\Http\RedirectResponse;
 use Illuminate\Http\Request;
+use Illuminate\Routing\Redirector;
+use Illuminate\View\View;
 
 /**
  * Class EditController
@@ -41,6 +45,7 @@ class EditController extends Controller
 
     /**
      * CategoryController constructor.
+     *
      * @codeCoverageIgnore
      */
     public function __construct()
@@ -49,7 +54,7 @@ class EditController extends Controller
 
         $this->middleware(
             function ($request, $next) {
-                app('view')->share('title', (string)trans('firefly.categories'));
+                app('view')->share('title', (string) trans('firefly.categories'));
                 app('view')->share('mainTitleIcon', 'fa-bar-chart');
                 $this->repository = app(CategoryRepositoryInterface::class);
 
@@ -65,11 +70,11 @@ class EditController extends Controller
      * @param Request  $request
      * @param Category $category
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function edit(Request $request, Category $category)
     {
-        $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')) {
@@ -83,22 +88,22 @@ class EditController extends Controller
     /**
      * Update category.
      *
-     * @param CategoryFormRequest         $request
-     * @param Category                    $category
+     * @param CategoryFormRequest $request
+     * @param Category            $category
      *
-     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
+     * @return RedirectResponse|Redirector
      */
     public function update(CategoryFormRequest $request, Category $category)
     {
         $data = $request->getCategoryData();
         $this->repository->update($category, $data);
 
-        $request->session()->flash('success', (string)trans('firefly.updated_category', ['name' => $category->name]));
+        $request->session()->flash('success', (string) trans('firefly.updated_category', ['name' => $category->name]));
         app('preferences')->mark();
 
         $redirect = redirect($this->getPreviousUri('categories.edit.uri'));
 
-        if (1 === (int)$request->get('return_to_edit')) {
+        if (1 === (int) $request->get('return_to_edit')) {
             // @codeCoverageIgnoreStart
             $request->session()->put('categories.edit.fromUpdate', true);
 
diff --git a/app/Http/Controllers/Category/IndexController.php b/app/Http/Controllers/Category/IndexController.php
index 7cbdf2244a..063d9e6cec 100644
--- a/app/Http/Controllers/Category/IndexController.php
+++ b/app/Http/Controllers/Category/IndexController.php
@@ -27,9 +27,11 @@ namespace FireflyIII\Http\Controllers\Category;
 use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\Models\Category;
 use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
+use Illuminate\Contracts\View\Factory;
 use Illuminate\Http\Request;
 use Illuminate\Pagination\LengthAwarePaginator;
 use Illuminate\Support\Collection;
+use Illuminate\View\View;
 
 /**
  * Class IndexController
@@ -41,6 +43,7 @@ class IndexController extends Controller
 
     /**
      * CategoryController constructor.
+     *
      * @codeCoverageIgnore
      */
     public function __construct()
@@ -49,7 +52,7 @@ class IndexController extends Controller
 
         $this->middleware(
             function ($request, $next) {
-                app('view')->share('title', (string)trans('firefly.categories'));
+                app('view')->share('title', (string) trans('firefly.categories'));
                 app('view')->share('mainTitleIcon', 'fa-bar-chart');
                 $this->repository = app(CategoryRepositoryInterface::class);
 
@@ -59,18 +62,17 @@ class IndexController extends Controller
     }
 
 
-
     /**
      * Show all categories.
      *
      * @param Request $request
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function index(Request $request)
     {
-        $page       = 0 === (int)$request->get('page') ? 1 : (int)$request->get('page');
-        $pageSize   = (int)app('preferences')->get('listPageSize', 50)->data;
+        $page       = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page');
+        $pageSize   = (int) app('preferences')->get('listPageSize', 50)->data;
         $collection = $this->repository->getCategories();
         $total      = $collection->count();
         $collection = $collection->slice(($page - 1) * $pageSize, $pageSize);
diff --git a/app/Http/Controllers/Category/NoCategoryController.php b/app/Http/Controllers/Category/NoCategoryController.php
index 53dbeb0698..e4ff1bef55 100644
--- a/app/Http/Controllers/Category/NoCategoryController.php
+++ b/app/Http/Controllers/Category/NoCategoryController.php
@@ -30,8 +30,10 @@ use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\Models\TransactionType;
 use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
 use FireflyIII\Support\Http\Controllers\PeriodOverview;
+use Illuminate\Contracts\View\Factory;
 use Illuminate\Http\Request;
 use Illuminate\Support\Collection;
+use Illuminate\View\View;
 use Log;
 
 /**
@@ -46,6 +48,7 @@ class NoCategoryController extends Controller
 
     /**
      * CategoryController constructor.
+     *
      * @codeCoverageIgnore
      */
     public function __construct()
@@ -55,7 +58,7 @@ class NoCategoryController extends Controller
 
         $this->middleware(
             function ($request, $next) {
-                app('view')->share('title', (string)trans('firefly.categories'));
+                app('view')->share('title', (string) trans('firefly.categories'));
                 app('view')->share('mainTitleIcon', 'fa-bar-chart');
                 $this->journalRepos = app(JournalRepositoryInterface::class);
 
@@ -67,11 +70,11 @@ class NoCategoryController extends Controller
     /**
      * Show transactions without a category.
      *
-     * @param Request $request
+     * @param Request     $request
      * @param Carbon|null $start
      * @param Carbon|null $end
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function show(Request $request, Carbon $start = null, Carbon $end = null)
     {
@@ -80,8 +83,8 @@ class NoCategoryController extends Controller
         $start = $start ?? session('start');
         /** @var Carbon $end */
         $end      = $end ?? session('end');
-        $page     = (int)$request->get('page');
-        $pageSize = (int)app('preferences')->get('listPageSize', 50)->data;
+        $page     = (int) $request->get('page');
+        $pageSize = (int) app('preferences')->get('listPageSize', 50)->data;
         $subTitle = trans(
             'firefly.without_category_between',
             ['start' => $start->formatLocalized($this->monthAndDayFormat), 'end' => $end->formatLocalized($this->monthAndDayFormat)]
@@ -95,7 +98,7 @@ class NoCategoryController extends Controller
         $collector = app(GroupCollectorInterface::class);
         $collector->setRange($start, $end)
                   ->setLimit($pageSize)->setPage($page)->withoutCategory()
-            ->withAccountInformation()->withBudgetInformation()
+                  ->withAccountInformation()->withBudgetInformation()
                   ->setTypes([TransactionType::WITHDRAWAL, TransactionType::DEPOSIT, TransactionType::TRANSFER]);
         $groups = $collector->getPaginatedGroups();
         $groups->setPath(route('categories.no-category'));
@@ -109,7 +112,7 @@ class NoCategoryController extends Controller
      *
      * @param Request $request
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function showAll(Request $request)
     {
@@ -117,10 +120,10 @@ class NoCategoryController extends Controller
         $start    = null;
         $end      = null;
         $periods  = new Collection;
-        $page     = (int)$request->get('page');
-        $pageSize = (int)app('preferences')->get('listPageSize', 50)->data;
+        $page     = (int) $request->get('page');
+        $pageSize = (int) app('preferences')->get('listPageSize', 50)->data;
         Log::debug('Start of noCategory()');
-        $subTitle = (string)trans('firefly.all_journals_without_category');
+        $subTitle = (string) trans('firefly.all_journals_without_category');
         $first    = $this->journalRepos->firstNull();
         $start    = null === $first ? new Carbon : $first->date;
         $end      = new Carbon;
@@ -130,7 +133,7 @@ class NoCategoryController extends Controller
         /** @var GroupCollectorInterface $collector */
         $collector = app(GroupCollectorInterface::class);
         $collector->setRange($start, $end)->setLimit($pageSize)->setPage($page)->withoutCategory()
-            ->withAccountInformation()->withBudgetInformation()
+                  ->withAccountInformation()->withBudgetInformation()
                   ->setTypes([TransactionType::WITHDRAWAL, TransactionType::DEPOSIT, TransactionType::TRANSFER]);
         $groups = $collector->getPaginatedGroups();
         $groups->setPath(route('categories.no-category.all'));
diff --git a/app/Http/Controllers/Category/ShowController.php b/app/Http/Controllers/Category/ShowController.php
index cf2d608d4e..633f5496fe 100644
--- a/app/Http/Controllers/Category/ShowController.php
+++ b/app/Http/Controllers/Category/ShowController.php
@@ -29,8 +29,10 @@ use FireflyIII\Http\Controllers\Controller;
 use FireflyIII\Models\Category;
 use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
 use FireflyIII\Support\Http\Controllers\PeriodOverview;
+use Illuminate\Contracts\View\Factory;
 use Illuminate\Http\Request;
 use Illuminate\Support\Collection;
+use Illuminate\View\View;
 
 /**
  *
@@ -45,6 +47,7 @@ class ShowController extends Controller
 
     /**
      * CategoryController constructor.
+     *
      * @codeCoverageIgnore
      */
     public function __construct()
@@ -54,7 +57,7 @@ class ShowController extends Controller
 
         $this->middleware(
             function ($request, $next) {
-                app('view')->share('title', (string)trans('firefly.categories'));
+                app('view')->share('title', (string) trans('firefly.categories'));
                 app('view')->share('mainTitleIcon', 'fa-bar-chart');
                 $this->repository = app(CategoryRepositoryInterface::class);
 
@@ -64,16 +67,15 @@ class ShowController extends Controller
     }
 
 
-
     /**
      * Show a single category.
      *
-     * @param Request $request
-     * @param Category $category
+     * @param Request     $request
+     * @param Category    $category
      * @param Carbon|null $start
      * @param Carbon|null $end
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function show(Request $request, Category $category, Carbon $start = null, Carbon $end = null)
     {
@@ -83,8 +85,8 @@ class ShowController extends Controller
         /** @var Carbon $end */
         $end          = $end ?? session('end', Carbon::now()->endOfMonth());
         $subTitleIcon = 'fa-bar-chart';
-        $page         = (int)$request->get('page');
-        $pageSize     = (int)app('preferences')->get('listPageSize', 50)->data;
+        $page         = (int) $request->get('page');
+        $pageSize     = (int) app('preferences')->get('listPageSize', 50)->data;
         $oldest       = $this->repository->firstUseDate($category) ?? Carbon::now()->startOfYear();
         $periods      = $this->getCategoryPeriodOverview($category, $oldest, $end);
         $path         = route('categories.show', [$category->id, $start->format('Y-m-d'), $end->format('Y-m-d')]);
@@ -111,22 +113,22 @@ class ShowController extends Controller
     /**
      * Show all transactions within a category.
      *
-     * @param Request $request
+     * @param Request  $request
      * @param Category $category
      *
-     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
+     * @return Factory|View
      */
     public function showAll(Request $request, Category $category)
     {
         // default values:
         $subTitleIcon = 'fa-bar-chart';
-        $page         = (int)$request->get('page');
-        $pageSize     = (int)app('preferences')->get('listPageSize', 50)->data;
+        $page         = (int) $request->get('page');
+        $pageSize     = (int) app('preferences')->get('listPageSize', 50)->data;
         $start        = null;
         $end          = null;
         $periods      = new Collection;
 
-        $subTitle = (string)trans('firefly.all_journals_for_category', ['name' => $category->name]);
+        $subTitle = (string) trans('firefly.all_journals_for_category', ['name' => $category->name]);
         $first    = $this->repository->firstUseDate($category);
         /** @var Carbon $start */
         $start = $first ?? new Carbon;
diff --git a/app/Http/Controllers/Chart/AccountController.php b/app/Http/Controllers/Chart/AccountController.php
index 475ce39d7a..825d017c00 100644
--- a/app/Http/Controllers/Chart/AccountController.php
+++ b/app/Http/Controllers/Chart/AccountController.php
@@ -59,6 +59,7 @@ class AccountController extends Controller
 
     /**
      * AccountController constructor.
+     *
      * @codeCoverageIgnore
      */
     public function __construct()
@@ -116,10 +117,10 @@ class AccountController extends Controller
 
         // loop the end balances. This is an array for each account ($expenses)
         foreach ($endBalances as $accountId => $expenses) {
-            $accountId = (int)$accountId;
+            $accountId = (int) $accountId;
             // loop each expense entry (each entry can be a different currency).
             foreach ($expenses as $currencyId => $endAmount) {
-                $currencyId = (int)$currencyId;
+                $currencyId = (int) $currencyId;
 
                 // see if there is an accompanying start amount.
                 // grab the difference and find the currency.
@@ -131,7 +132,7 @@ class AccountController extends Controller
                     $tempData[] = [
                         'name'        => $accountNames[$accountId],
                         'difference'  => $diff,
-                        'diff_float'  => (float)$diff,
+                        'diff_float'  => (float) $diff,
                         'currency_id' => $currencyId,
                     ];
                 }
@@ -144,13 +145,13 @@ class AccountController extends Controller
 
         // loop all found currencies and build the data array for the chart.
         /**
-         * @var int $currencyId
+         * @var int                 $currencyId
          * @var TransactionCurrency $currency
          */
         foreach ($currencies as $currencyId => $currency) {
             $dataSet
                                     = [
-                'label'           => (string)trans('firefly.spent'),
+                'label'           => (string) trans('firefly.spent'),
                 'type'            => 'bar',
                 'currency_symbol' => $currency->symbol,
                 'entries'         => $this->expandNames($tempData),
@@ -171,28 +172,12 @@ class AccountController extends Controller
         return response()->json($data);
     }
 
-    /**
-     * Expenses per budget for all time, as shown on account overview.
-     *
-     * @param AccountRepositoryInterface $repository
-     * @param Account $account
-     *
-     * @return JsonResponse
-     */
-    public function expenseBudgetAll(AccountRepositoryInterface $repository, Account $account): JsonResponse
-    {
-        $start = $repository->oldestJournalDate($account) ?? Carbon::now()->startOfMonth();
-        $end   = Carbon::now();
-
-        return $this->expenseBudget($account, $start, $end);
-    }
-
     /**
      * Expenses per budget, as shown on account overview.
      *
      * @param Account $account
-     * @param Carbon $start
-     * @param Carbon $end
+     * @param Carbon  $start
+     * @param Carbon  $end
      *
      * @return JsonResponse
      */
@@ -215,7 +200,7 @@ class AccountController extends Controller
         $budgetIds = [];
         /** @var array $journal */
         foreach ($journals as $journal) {
-            $budgetId    = (int)$journal['budget_id'];
+            $budgetId    = (int) $journal['budget_id'];
             $key         = sprintf('%d-%d', $budgetId, $journal['currency_id']);
             $budgetIds[] = $budgetId;
             if (!isset($result[$key])) {
@@ -234,7 +219,7 @@ class AccountController extends Controller
         foreach ($result as $row) {
             $budgetId          = $row['budget_id'];
             $name              = $names[$budgetId];
-            $label             = (string)trans('firefly.name_in_currency', ['name' => $name, 'currency' => $row['currency_name']]);
+            $label             = (string) trans('firefly.name_in_currency', ['name' => $name, 'currency' => $row['currency_name']]);
             $chartData[$label] = ['amount' => $row['total'], 'currency_symbol' => $row['currency_symbol']];
         }
 
@@ -245,27 +230,27 @@ class AccountController extends Controller
     }
 
     /**
-     * Expenses grouped by category for account.
+     * Expenses per budget for all time, as shown on account overview.
      *
      * @param AccountRepositoryInterface $repository
-     * @param Account $account
+     * @param Account                    $account
      *
      * @return JsonResponse
      */
-    public function expenseCategoryAll(AccountRepositoryInterface $repository, Account $account): JsonResponse
+    public function expenseBudgetAll(AccountRepositoryInterface $repository, Account $account): JsonResponse
     {
         $start = $repository->oldestJournalDate($account) ?? Carbon::now()->startOfMonth();
         $end   = Carbon::now();
 
-        return $this->expenseCategory($account, $start, $end);
+        return $this->expenseBudget($account, $start, $end);
     }
 
     /**
      * Expenses per category for one single account.
      *
      * @param Account $account
-     * @param Carbon $start
-     * @param Carbon $end
+     * @param Carbon  $start
+     * @param Carbon  $end
      *
      * @return JsonResponse
      */
@@ -283,9 +268,9 @@ class AccountController extends Controller
         /** @var GroupCollectorInterface $collector */
         $collector = app(GroupCollectorInterface::class);
         $collector->setAccounts(new Collection([$account]))->setRange($start, $end)->withCategoryInformation()->setTypes([TransactionType::WITHDRAWAL]);
-        $journals    = $collector->getExtractedJournals();
-        $result      = [];
-        $chartData   = [];
+        $journals  = $collector->getExtractedJournals();
+        $result    = [];
+        $chartData = [];
 
         /** @var array $journal */
         foreach ($journals as $journal) {
@@ -293,7 +278,7 @@ class AccountController extends Controller
             if (!isset($result[$key])) {
                 $result[$key] = [
                     'total'           => '0',
-                    'category_id'     => (int)$journal['category_id'],
+                    'category_id'     => (int) $journal['category_id'],
                     'currency_name'   => $journal['currency_name'],
                     'currency_symbol' => $journal['currency_symbol'],
                 ];
@@ -305,7 +290,7 @@ class AccountController extends Controller
         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']]);
+            $label             = (string) trans('firefly.name_in_currency', ['name' => $name, 'currency' => $row['currency_name']]);
             $chartData[$label] = ['amount' => $row['total'], 'currency_symbol' => $row['currency_symbol']];
         }
 
@@ -315,6 +300,22 @@ class AccountController extends Controller
         return response()->json($data);
     }
 
+    /**
+     * Expenses grouped by category for account.
+     *
+     * @param AccountRepositoryInterface $repository
+     * @param Account                    $account
+     *
+     * @return JsonResponse
+     */
+    public function expenseCategoryAll(AccountRepositoryInterface $repository, Account $account): JsonResponse
+    {
+        $start = $repository->oldestJournalDate($account) ?? Carbon::now()->startOfMonth();
+        $end   = Carbon::now();
+
+        return $this->expenseCategory($account, $start, $end);
+    }
+
     /**
      * Shows the balances for all the user's frontpage accounts.
      *
@@ -341,28 +342,12 @@ class AccountController extends Controller
         return response()->json($this->accountBalanceChart($accounts, $start, $end));
     }
 
-    /**
-     * Shows the income grouped by category for an account, in all time.
-     *
-     * @param AccountRepositoryInterface $repository
-     * @param Account $account
-     *
-     * @return JsonResponse
-     */
-    public function incomeCategoryAll(AccountRepositoryInterface $repository, Account $account): JsonResponse
-    {
-        $start = $repository->oldestJournalDate($account) ?? Carbon::now()->startOfMonth();
-        $end   = Carbon::now();
-
-        return $this->incomeCategory($account, $start, $end);
-    }
-
     /**
      * Shows all income per account for each category.
      *
      * @param Account $account
-     * @param Carbon $start
-     * @param Carbon $end
+     * @param Carbon  $start
+     * @param Carbon  $end
      *
      * @return JsonResponse
      */
@@ -382,9 +367,9 @@ class AccountController extends Controller
         $collector = app(GroupCollectorInterface::class);
 
         $collector->setAccounts(new Collection([$account]))->setRange($start, $end)->withCategoryInformation()->setTypes([TransactionType::DEPOSIT]);
-        $journals    = $collector->getExtractedJournals();
-        $result      = [];
-        $chartData   = [];
+        $journals  = $collector->getExtractedJournals();
+        $result    = [];
+        $chartData = [];
         /** @var array $journal */
         foreach ($journals as $journal) {
             $key = sprintf('%d-%d', $journal['category_id'], $journal['currency_id']);
@@ -403,7 +388,7 @@ class AccountController extends Controller
         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']]);
+            $label             = (string) trans('firefly.name_in_currency', ['name' => $name, 'currency' => $row['currency_name']]);
             $chartData[$label] = ['amount' => $row['total'], 'currency_symbol' => $row['currency_symbol']];
         }
         $data = $this->generator->multiCurrencyPieChart($chartData);
@@ -412,15 +397,31 @@ class AccountController extends Controller
         return response()->json($data);
     }
 
+    /**
+     * Shows the income grouped by category for an account, in all time.
+     *
+     * @param AccountRepositoryInterface $repository
+     * @param Account                    $account
+     *
+     * @return JsonResponse
+     */
+    public function incomeCategoryAll(AccountRepositoryInterface $repository, Account $account): JsonResponse
+    {
+        $start = $repository->oldestJournalDate($account) ?? Carbon::now()->startOfMonth();
+        $end   = Carbon::now();
+
+        return $this->incomeCategory($account, $start, $end);
+    }
+
     /**
      * Shows overview of account during a single period.
      *
      * TODO this chart is not multi-currency aware.
      *
      * @param Account $account
-     * @param Carbon $start
+     * @param Carbon  $start
      *
-     * @param Carbon $end
+     * @param Carbon  $end
      *
      * @return JsonResponse
      */
@@ -440,14 +441,14 @@ class AccountController extends Controller
         $current   = clone $start;
         switch ($step) {
             case '1D':
-                $format   = (string)trans('config.month_and_day');
+                $format   = (string) trans('config.month_and_day');
                 $range    = app('steam')->balanceInRange($account, $start, $end);
                 $previous = array_values($range)[0];
                 while ($end >= $current) {
                     $theDate           = $current->format('Y-m-d');
                     $balance           = $range[$theDate] ?? $previous;
                     $label             = $current->formatLocalized($format);
-                    $chartData[$label] = (float)$balance;
+                    $chartData[$label] = (float) $balance;
                     $previous          = $balance;
                     $current->addDay();
                 }
@@ -457,7 +458,7 @@ class AccountController extends Controller
             case '1M':
             case '1Y':
                 while ($end >= $current) {
-                    $balance           = (float)app('steam')->balance($account, $current);
+                    $balance           = (float) app('steam')->balance($account, $current);
                     $label             = app('navigation')->periodShow($current, $step);
                     $chartData[$label] = $balance;
                     $current           = app('navigation')->addPeriod($current, $step, 0);
@@ -476,8 +477,8 @@ class AccountController extends Controller
      *
      * TODO this chart is not multi-currency aware.
      *
-     * @param Carbon $start
-     * @param Carbon $end
+     * @param Carbon     $start
+     * @param Carbon     $end
      * @param Collection $accounts
      *
      * @return JsonResponse
@@ -525,10 +526,10 @@ class AccountController extends Controller
 
         // loop the end balances. This is an array for each account ($expenses)
         foreach ($endBalances as $accountId => $expenses) {
-            $accountId = (int)$accountId;
+            $accountId = (int) $accountId;
             // loop each expense entry (each entry can be a different currency).
             foreach ($expenses as $currencyId => $endAmount) {
-                $currencyId = (int)$currencyId;
+                $currencyId = (int) $currencyId;
 
                 // see if there is an accompanying start amount.
                 // grab the difference and find the currency.
@@ -540,7 +541,7 @@ class AccountController extends Controller
                     $tempData[] = [
                         'name'        => $accountNames[$accountId],
                         'difference'  => $diff,
-                        'diff_float'  => (float)$diff,
+                        'diff_float'  => (float) $diff,
                         'currency_id' => $currencyId,
                     ];
                 }
@@ -553,13 +554,13 @@ class AccountController extends Controller
 
         // loop all found currencies and build the data array for the chart.
         /**
-         * @var int $currencyId
+         * @var int                 $currencyId
          * @var TransactionCurrency $currency
          */
         foreach ($currencies as $currencyId => $currency) {
             $dataSet
                                     = [
-                'label'           => (string)trans('firefly.earned'),
+                'label'           => (string) trans('firefly.earned'),
                 'type'            => 'bar',
                 'currency_symbol' => $currency->symbol,
                 'entries'         => $this->expandNames($tempData),
diff --git a/app/Http/Controllers/Chart/BillController.php b/app/Http/Controllers/Chart/BillController.php
index 9909ef07f7..b817da0147 100644
--- a/app/Http/Controllers/Chart/BillController.php
+++ b/app/Http/Controllers/Chart/BillController.php
@@ -42,6 +42,7 @@ class BillController extends Controller
 
     /**
      * BillController constructor.
+     *
      * @codeCoverageIgnore
      */
     public function __construct()
@@ -79,12 +80,12 @@ class BillController extends Controller
 
         foreach ($paid as $currencyId => $amount) {
             $currencies[$currencyId] = $currencies[$currencyId] ?? $currencyRepository->findNull($currencyId);
-            $label                   = (string)trans('firefly.paid_in_currency', ['currency' => $currencies[$currencyId]->name]);
+            $label                   = (string) trans('firefly.paid_in_currency', ['currency' => $currencies[$currencyId]->name]);
             $chartData[$label]       = ['amount' => $amount, 'currency_symbol' => $currencies[$currencyId]->symbol];
         }
         foreach ($unpaid as $currencyId => $amount) {
             $currencies[$currencyId] = $currencies[$currencyId] ?? $currencyRepository->findNull($currencyId);
-            $label                   = (string)trans('firefly.unpaid_in_currency', ['currency' => $currencies[$currencyId]->name]);
+            $label                   = (string) trans('firefly.unpaid_in_currency', ['currency' => $currencies[$currencyId]->name]);
             $chartData[$label]       = ['amount' => $amount, 'currency_symbol' => $currencies[$currencyId]->symbol];
         }
 
@@ -116,18 +117,21 @@ class BillController extends Controller
         $journals  = $collector->setBill($bill)->getExtractedJournals();
 
         // sort the other way around:
-        usort($journals, static function (array $left, array $right) {
-            return $left['date']->gte($right['date'])? 1 : 0;
-        });
+        usort(
+            $journals,
+            static function (array $left, array $right) {
+                return $left['date']->gte($right['date']) ? 1 : 0;
+            }
+        );
 
         $chartData = [
-            ['type' => 'line', 'label' => (string)trans('firefly.max-amount'), 'currency_symbol' => $bill->transactionCurrency->symbol, 'entries' => []],
-            ['type' => 'line', 'label' => (string)trans('firefly.min-amount'), 'currency_symbol' => $bill->transactionCurrency->symbol, 'entries' => []],
-            ['type' => 'bar', 'label' => (string)trans('firefly.journal-amount'), 'currency_symbol' => $bill->transactionCurrency->symbol, 'entries' => []],
+            ['type' => 'line', 'label' => (string) trans('firefly.max-amount'), 'currency_symbol' => $bill->transactionCurrency->symbol, 'entries' => []],
+            ['type' => 'line', 'label' => (string) trans('firefly.min-amount'), 'currency_symbol' => $bill->transactionCurrency->symbol, 'entries' => []],
+            ['type' => 'bar', 'label' => (string) trans('firefly.journal-amount'), 'currency_symbol' => $bill->transactionCurrency->symbol, 'entries' => []],
         ];
 
         foreach ($journals as $journal) {
-            $date                           = $journal['date']->formatLocalized((string)trans('config.month_and_day'));
+            $date                           = $journal['date']->formatLocalized((string) trans('config.month_and_day'));
             $chartData[0]['entries'][$date] = $bill->amount_min; // minimum amount of bill
             $chartData[1]['entries'][$date] = $bill->amount_max; // maximum amount of bill
 
diff --git a/app/Http/Controllers/Chart/BudgetController.php b/app/Http/Controllers/Chart/BudgetController.php
index 295aa232a7..b83692f914 100644
--- a/app/Http/Controllers/Chart/BudgetController.php
+++ b/app/Http/Controllers/Chart/BudgetController.php
@@ -27,9 +27,9 @@ use FireflyIII\Exceptions\FireflyException;
 use FireflyIII\Generator\Chart\Basic\GeneratorInterface;
 use FireflyIII\Helpers\Collector\GroupCollectorInterface;
 use FireflyIII\Http\Controllers\Controller;
-use FireflyIII\Models\TransactionCurrency;
 use FireflyIII\Models\Budget;
 use FireflyIII\Models\BudgetLimit;
+use FireflyIII\Models\TransactionCurrency;
 use FireflyIII\Models\TransactionType;
 use FireflyIII\Repositories\Budget\BudgetLimitRepositoryInterface;
 use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
@@ -104,11 +104,11 @@ class BudgetController extends Controller
         if ($cache->has()) {
             return response()->json($cache->get()); // @codeCoverageIgnore
         }
-        $step       = $this->calculateStep($start, $end); // depending on diff, do something with range of chart.
-        $collection = new Collection([$budget]);
-        $chartData  = [];
-        $loopStart  = clone $start;
-        $loopStart  = app('navigation')->startOfPeriod($loopStart, $step);
+        $step           = $this->calculateStep($start, $end); // depending on diff, do something with range of chart.
+        $collection     = new Collection([$budget]);
+        $chartData      = [];
+        $loopStart      = clone $start;
+        $loopStart      = app('navigation')->startOfPeriod($loopStart, $step);
         $currencies     = [];
         $defaultEntries = [];
         //        echo '
'; @@ -135,10 +135,10 @@ class BudgetController extends Controller // loop all currencies: foreach ($currencies as $currencyId => $currency) { $chartData[$currencyId] = [ - 'label' => count($currencies) > 1 ? sprintf('%s (%s)', $budget->name, $currency['currency_name']) : $budget->name, - 'type' => 'bar', + 'label' => count($currencies) > 1 ? sprintf('%s (%s)', $budget->name, $currency['currency_name']) : $budget->name, + 'type' => 'bar', 'currency_symbol' => $currency['currency_symbol'], - 'entries' => $defaultEntries, + 'entries' => $defaultEntries, ]; foreach ($currency['spent'] as $label => $spent) { $chartData[$currencyId]['entries'][$label] = round(bcmul($spent, '-1'), $currency['currency_decimal_places']); @@ -157,9 +157,9 @@ class BudgetController extends Controller * @param Budget $budget * @param BudgetLimit $budgetLimit * + * @throws FireflyException * @return JsonResponse * - * @throws FireflyException */ public function budgetLimit(Budget $budget, BudgetLimit $budgetLimit): JsonResponse { @@ -186,12 +186,12 @@ class BudgetController extends Controller while ($start <= $end) { $spent = $this->opsRepository->spentInPeriod($budgetCollection, new Collection, $start, $start); $amount = bcadd($amount, $spent); - $format = $start->formatLocalized((string)trans('config.month_and_day')); + $format = $start->formatLocalized((string) trans('config.month_and_day')); $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'] = $budgetLimit->transactionCurrency->symbol; $cache->store($data); @@ -211,7 +211,7 @@ class BudgetController extends Controller public function expenseAsset(Budget $budget, ?BudgetLimit $budgetLimit = null): JsonResponse { /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $budgetLimitId = null === $budgetLimit ? 0 : $budgetLimit->id; $cache = new CacheProperties; $cache->addProperty($budget->id); @@ -238,7 +238,7 @@ class BudgetController extends Controller // group by asset account ID: foreach ($journals as $journal) { - $key = sprintf('%d-%d', (int)$journal['source_account_id'], $journal['currency_id']); + $key = sprintf('%d-%d', (int) $journal['source_account_id'], $journal['currency_id']); $result[$key] = $result[$key] ?? [ 'amount' => '0', 'currency_symbol' => $journal['currency_symbol'], @@ -250,7 +250,7 @@ class BudgetController extends Controller $names = $this->getAccountNames(array_keys($result)); foreach ($result as $combinedId => $info) { $parts = explode('-', $combinedId); - $assetId = (int)$parts[0]; + $assetId = (int) $parts[0]; $title = sprintf('%s (%s)', $names[$assetId] ?? '(empty)', $info['currency_name']); $chartData[$title] = [ @@ -277,7 +277,7 @@ class BudgetController extends Controller public function expenseCategory(Budget $budget, ?BudgetLimit $budgetLimit = null): JsonResponse { /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $budgetLimitId = null === $budgetLimit ? 0 : $budgetLimit->id; $cache = new CacheProperties; $cache->addProperty($budget->id); @@ -314,7 +314,7 @@ class BudgetController extends Controller $names = $this->getCategoryNames(array_keys($result)); foreach ($result as $combinedId => $info) { $parts = explode('-', $combinedId); - $categoryId = (int)$parts[0]; + $categoryId = (int) $parts[0]; $title = sprintf('%s (%s)', $names[$categoryId] ?? '(empty)', $info['currency_name']); $chartData[$title] = [ 'amount' => $info['amount'], @@ -340,7 +340,7 @@ class BudgetController extends Controller public function expenseExpense(Budget $budget, ?BudgetLimit $budgetLimit = null): JsonResponse { /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); + $collector = app(GroupCollectorInterface::class); $budgetLimitId = null === $budgetLimit ? 0 : $budgetLimit->id; $cache = new CacheProperties; $cache->addProperty($budget->id); @@ -379,7 +379,7 @@ class BudgetController extends Controller $names = $this->getAccountNames(array_keys($result)); foreach ($result as $combinedId => $info) { $parts = explode('-', $combinedId); - $opposingId = (int)$parts[0]; + $opposingId = (int) $parts[0]; $name = $names[$opposingId] ?? 'no name'; $title = sprintf('%s (%s)', $name, $info['currency_name']); $chartData[$title] = [ @@ -418,9 +418,9 @@ class BudgetController extends Controller } $budgets = $this->repository->getActiveBudgets(); $chartData = [ - ['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'], ]; /** @var Budget $budget */ @@ -440,14 +440,20 @@ class BudgetController extends Controller /** @var BudgetLimit $limit */ foreach ($limits as $limit) { $spent = $this->opsRepository->sumExpenses( - $limit->start_date, $limit->end_date, null, new Collection([$budget]), $limit->transactionCurrency + $limit->start_date, + $limit->end_date, + null, + new Collection([$budget]), + $limit->transactionCurrency ); /** @var array $entry */ foreach ($spent as $entry) { $title = sprintf('%s (%s)', $budget->name, $entry['currency_name']); if ($limit->start_date->startOfDay()->ne($start->startOfDay()) || $limit->end_date->startOfDay()->ne($end->startOfDay())) { $title = sprintf( - '%s (%s) (%s - %s)', $budget->name, $entry['currency_name'], + '%s (%s) (%s - %s)', + $budget->name, + $entry['currency_name'], $limit->start_date->formatLocalized($this->monthAndDayFormat), $limit->end_date->formatLocalized($this->monthAndDayFormat) ); @@ -498,13 +504,13 @@ class BudgetController extends Controller $preferredRange = app('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, ], [ - '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, 'entries' => [], @@ -513,9 +519,9 @@ class BudgetController extends Controller $currentStart = clone $start; while ($currentStart <= $end) { - $currentStart= app('navigation')->startOfPeriod($currentStart, $preferredRange); - $title = $currentStart->formatLocalized($titleFormat); - $currentEnd = app('navigation')->endOfPeriod($currentStart, $preferredRange); + $currentStart = app('navigation')->startOfPeriod($currentStart, $preferredRange); + $title = $currentStart->formatLocalized($titleFormat); + $currentEnd = app('navigation')->endOfPeriod($currentStart, $preferredRange); // default limit is no limit: $chartData[0]['entries'][$title] = 0; @@ -582,11 +588,9 @@ class BudgetController extends Controller $currentStart = app('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 aaca008c5f..5d16a52981 100644 --- a/app/Http/Controllers/Chart/BudgetReportController.php +++ b/app/Http/Controllers/Chart/BudgetReportController.php @@ -18,7 +18,7 @@ * along with this program. If not, see . */ - /** @noinspection MoreThanThreeArgumentsInspection */ +/** @noinspection MoreThanThreeArgumentsInspection */ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Chart; @@ -118,8 +118,6 @@ class BudgetReportController extends Controller // loop expenses. 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']); @@ -157,8 +155,6 @@ class BudgetReportController extends Controller // loop expenses. 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']); $result[$title] = $result[$title] ?? [ @@ -199,7 +195,9 @@ class BudgetReportController extends Controller $spentKey = sprintf('%d-spent', $currency['currency_id']); $chartData[$spentKey] = $chartData[$spentKey] ?? [ 'label' => sprintf( - '%s (%s)', (string)trans('firefly.spent_in_specific_budget', ['budget' => $budget->name]), $currency['currency_name'] + '%s (%s)', + (string) trans('firefly.spent_in_specific_budget', ['budget' => $budget->name]), + $currency['currency_name'] ), 'type' => 'bar', 'currency_symbol' => $currency['currency_symbol'], @@ -240,8 +238,6 @@ class BudgetReportController extends Controller // loop expenses. 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']); $result[$title] = $result[$title] ?? [ @@ -282,5 +278,4 @@ class BudgetReportController extends Controller return $return; } - } diff --git a/app/Http/Controllers/Chart/CategoryController.php b/app/Http/Controllers/Chart/CategoryController.php index ddc6062980..657a982c54 100644 --- a/app/Http/Controllers/Chart/CategoryController.php +++ b/app/Http/Controllers/Chart/CategoryController.php @@ -191,7 +191,7 @@ class CategoryController extends Controller /** @var array $currency */ foreach ($currencies as $currency) { $dataSet = [ - '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' => $this->expandNames($tempData), @@ -353,7 +353,7 @@ class CategoryController extends Controller if (null !== $category) { /** @var OperationsRepositoryInterface $opsRepository */ $opsRepository = app(OperationsRepositoryInterface::class); - $categoryId = (int)$category->id; + $categoryId = (int) $category->id; // this gives us all currencies $collection = new Collection([$category]); $expenses = $opsRepository->listExpenses($start, $end, null, $collection); @@ -372,7 +372,7 @@ class CategoryController extends Controller $inKey = sprintf('%d-in', $currencyId); $chartData[$outKey] = [ - 'label' => sprintf('%s (%s)', (string)trans('firefly.spent'), $currencyInfo['currency_name']), + 'label' => sprintf('%s (%s)', (string) trans('firefly.spent'), $currencyInfo['currency_name']), 'entries' => [], 'type' => 'bar', 'backgroundColor' => 'rgba(219, 68, 55, 0.5)', // red @@ -380,7 +380,7 @@ class CategoryController extends Controller $chartData[$inKey] = [ - 'label' => sprintf('%s (%s)', (string)trans('firefly.earned'), $currencyInfo['currency_name']), + 'label' => sprintf('%s (%s)', (string) trans('firefly.earned'), $currencyInfo['currency_name']), 'entries' => [], 'type' => 'bar', 'backgroundColor' => 'rgba(0, 141, 76, 0.5)', // green diff --git a/app/Http/Controllers/Chart/CategoryReportController.php b/app/Http/Controllers/Chart/CategoryReportController.php index 11847457d3..4ee924d082 100644 --- a/app/Http/Controllers/Chart/CategoryReportController.php +++ b/app/Http/Controllers/Chart/CategoryReportController.php @@ -316,7 +316,9 @@ class CategoryReportController extends Controller $spentKey = sprintf('%d-spent', $currency['currency_id']); $chartData[$spentKey] = $chartData[$spentKey] ?? [ 'label' => sprintf( - '%s (%s)', (string)trans('firefly.spent_in_specific_category', ['category' => $category->name]), $currency['currency_name'] + '%s (%s)', + (string) trans('firefly.spent_in_specific_category', ['category' => $category->name]), + $currency['currency_name'] ), 'type' => 'bar', 'currency_symbol' => $currency['currency_symbol'], @@ -340,7 +342,9 @@ class CategoryReportController extends Controller $spentKey = sprintf('%d-earned', $currency['currency_id']); $chartData[$spentKey] = $chartData[$spentKey] ?? [ 'label' => sprintf( - '%s (%s)', (string)trans('firefly.earned_in_specific_category', ['category' => $category->name]), $currency['currency_name'] + '%s (%s)', + (string) trans('firefly.earned_in_specific_category', ['category' => $category->name]), + $currency['currency_name'] ), 'type' => 'bar', 'currency_symbol' => $currency['currency_symbol'], @@ -457,5 +461,4 @@ class CategoryReportController extends Controller return $return; } - } diff --git a/app/Http/Controllers/Chart/DoubleReportController.php b/app/Http/Controllers/Chart/DoubleReportController.php index 309397e997..287a2ff551 100644 --- a/app/Http/Controllers/Chart/DoubleReportController.php +++ b/app/Http/Controllers/Chart/DoubleReportController.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Chart; - use Carbon\Carbon; use FireflyIII\Generator\Chart\Basic\GeneratorInterface; use FireflyIII\Http\Controllers\Controller; @@ -196,7 +195,9 @@ class DoubleReportController extends Controller $chartData[$spentKey] = $chartData[$spentKey] ?? [ 'label' => sprintf( - '%s (%s)', (string)trans('firefly.spent_in_specific_double', ['account' => $name]), $currency['currency_name'] + '%s (%s)', + (string) trans('firefly.spent_in_specific_double', ['account' => $name]), + $currency['currency_name'] ), 'type' => 'bar', 'currency_symbol' => $currency['currency_symbol'], @@ -210,7 +211,6 @@ class DoubleReportController extends Controller $chartData[$spentKey]['entries'][$key] = $chartData[$spentKey]['entries'][$key] ?? '0'; $chartData[$spentKey]['entries'][$key] = bcadd($chartData[$spentKey]['entries'][$key], $amount); } - } // loop income. foreach ($earned as $currency) { @@ -220,7 +220,9 @@ class DoubleReportController extends Controller $chartData[$earnedKey] = $chartData[$earnedKey] ?? [ 'label' => sprintf( - '%s (%s)', (string)trans('firefly.earned_in_specific_double', ['account' => $name]), $currency['currency_name'] + '%s (%s)', + (string) trans('firefly.earned_in_specific_double', ['account' => $name]), + $currency['currency_name'] ), 'type' => 'bar', 'currency_symbol' => $currency['currency_symbol'], @@ -242,7 +244,6 @@ class DoubleReportController extends Controller } - /** * @param Collection $accounts * @param Collection $others @@ -275,7 +276,6 @@ class DoubleReportController extends Controller ]; $amount = app('steam')->positive($journal['amount']); $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount); - } // loop each tag: /** @var array $tag */ @@ -334,7 +334,6 @@ class DoubleReportController extends Controller ]; $amount = app('steam')->positive($journal['amount']); $result[$title]['amount'] = bcadd($result[$title]['amount'], $amount); - } // loop each tag: /** @var array $tag */ @@ -364,10 +363,10 @@ class DoubleReportController extends Controller /** * TODO this method is double. * - * @param Collection $accounts - * @param int $id - * @param string $name - * @param null|string $iban + * @param Collection $accounts + * @param int $id + * @param string $name + * @param null|string $iban * * @return string */ @@ -410,6 +409,4 @@ class DoubleReportController extends Controller return $return; } - - -} \ No newline at end of file +} diff --git a/app/Http/Controllers/Chart/ExpenseReportController.php b/app/Http/Controllers/Chart/ExpenseReportController.php index 61fc1eedc9..59d24800ca 100644 --- a/app/Http/Controllers/Chart/ExpenseReportController.php +++ b/app/Http/Controllers/Chart/ExpenseReportController.php @@ -49,6 +49,7 @@ class ExpenseReportController extends Controller /** * ExpenseReportController constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -72,8 +73,8 @@ class ExpenseReportController extends Controller * * @param Collection $accounts * @param Collection $expense - * @param Carbon $start - * @param Carbon $end + * @param Carbon $start + * @param Carbon $end * * @return JsonResponse * @@ -87,7 +88,7 @@ class ExpenseReportController extends Controller $cache->addProperty($start); $cache->addProperty($end); if ($cache->has()) { - return response()->json($cache->get()); // @codeCoverageIgnore + return response()->json($cache->get()); // @codeCoverageIgnore } $format = app('navigation')->preferredCarbonLocalizedFormat($start, $end); @@ -103,7 +104,7 @@ class ExpenseReportController extends Controller // prep chart data: /** - * @var string $name + * @var string $name * @var Collection $combination */ foreach ($combined as $name => $combination) { @@ -111,27 +112,27 @@ class ExpenseReportController extends Controller /** @var Account $exp */ $exp = $combination->first(); $chartData[$exp->id . '-in'] = [ - 'label' => sprintf('%s (%s)', $name, strtolower((string)trans('firefly.income'))), + 'label' => sprintf('%s (%s)', $name, strtolower((string) trans('firefly.income'))), 'type' => 'bar', 'yAxisID' => 'y-axis-0', 'entries' => [], ]; $chartData[$exp->id . '-out'] = [ - 'label' => sprintf('%s (%s)', $name, strtolower((string)trans('firefly.expenses'))), + 'label' => sprintf('%s (%s)', $name, strtolower((string) trans('firefly.expenses'))), 'type' => 'bar', 'yAxisID' => 'y-axis-0', 'entries' => [], ]; // total in, total out: $chartData[$exp->id . '-total-in'] = [ - 'label' => sprintf('%s (%s)', $name, strtolower((string)trans('firefly.sum_of_income'))), + 'label' => sprintf('%s (%s)', $name, strtolower((string) trans('firefly.sum_of_income'))), 'type' => 'line', 'fill' => false, 'yAxisID' => 'y-axis-1', 'entries' => [], ]; $chartData[$exp->id . '-total-out'] = [ - 'label' => sprintf('%s (%s)', $name, strtolower((string)trans('firefly.sum_of_expenses'))), + 'label' => sprintf('%s (%s)', $name, strtolower((string) trans('firefly.sum_of_expenses'))), 'type' => 'line', 'fill' => false, 'yAxisID' => 'y-axis-1', diff --git a/app/Http/Controllers/Chart/PiggyBankController.php b/app/Http/Controllers/Chart/PiggyBankController.php index b99e272b52..72a96d43b7 100644 --- a/app/Http/Controllers/Chart/PiggyBankController.php +++ b/app/Http/Controllers/Chart/PiggyBankController.php @@ -44,6 +44,7 @@ class PiggyBankController extends Controller /** * PiggyBankController constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -98,7 +99,7 @@ class PiggyBankController extends Controller } ); $currentSum = $filtered->sum('amount'); - $label = $oldest->formatLocalized((string)trans('config.month_and_day')); + $label = $oldest->formatLocalized((string) trans('config.month_and_day')); $chartData[$label] = $currentSum; $oldest = app('navigation')->addPeriod($oldest, $step, 0); } @@ -109,7 +110,7 @@ class PiggyBankController extends Controller } ); $finalSum = $finalFiltered->sum('amount'); - $finalLabel = $today->formatLocalized((string)trans('config.month_and_day')); + $finalLabel = $today->formatLocalized((string) trans('config.month_and_day')); $chartData[$finalLabel] = $finalSum; $data = $this->generator->singleSet($piggyBank->name, $chartData); diff --git a/app/Http/Controllers/Chart/ReportController.php b/app/Http/Controllers/Chart/ReportController.php index 107116ab0a..79e3d65a7c 100644 --- a/app/Http/Controllers/Chart/ReportController.php +++ b/app/Http/Controllers/Chart/ReportController.php @@ -110,7 +110,7 @@ class ReportController extends Controller /** @var array $netWorthItem */ foreach ($result as $netWorthItem) { $currencyId = $netWorthItem['currency']->id; - $label = $current->formatLocalized((string)trans('config.month_and_day')); + $label = $current->formatLocalized((string) trans('config.month_and_day')); if (!isset($chartData[$currencyId])) { $chartData[$currencyId] = [ 'label' => 'Net worth in ' . $netWorthItem['currency']->name, @@ -138,7 +138,7 @@ class ReportController extends Controller * @param Carbon $start * @param Carbon $end * - * @return \Illuminate\Http\JsonResponse + * @return JsonResponse */ public function operations(Collection $accounts, Carbon $start, Carbon $end): JsonResponse { @@ -152,10 +152,10 @@ class ReportController extends Controller return response()->json($cache->get()); // @codeCoverageIgnore } Log::debug('Going to do operations for accounts ', $accounts->pluck('id')->toArray()); - $format = app('navigation')->preferredCarbonFormat($start, $end); - $titleFormat = app('navigation')->preferredCarbonLocalizedFormat($start, $end); + $format = app('navigation')->preferredCarbonFormat($start, $end); + $titleFormat = app('navigation')->preferredCarbonLocalizedFormat($start, $end); $preferredRange = app('navigation')->preferredRangeFormat($start, $end); - $ids = $accounts->pluck('id')->toArray(); + $ids = $accounts->pluck('id')->toArray(); // get journals for entire period: $data = []; @@ -173,13 +173,13 @@ class ReportController extends Controller /** @var array $journal */ foreach ($journals as $journal) { $period = $journal['date']->format($format); - $currencyId = (int)$journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $data[$currencyId] = $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'], + 'currency_decimal_places' => (int) $journal['currency_decimal_places'], ]; $data[$currencyId][$period] = $data[$currencyId][$period] ?? [ 'period' => $period, @@ -211,7 +211,7 @@ class ReportController extends Controller /** @var array $currency */ foreach ($data as $currency) { $income = [ - 'label' => (string)trans('firefly.box_earned_in_currency', ['currency' => $currency['currency_name']]), + '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'], @@ -219,7 +219,7 @@ class ReportController extends Controller 'entries' => [], ]; $expense = [ - 'label' => (string)trans('firefly.box_spent_in_currency', ['currency' => $currency['currency_name']]), + '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'], @@ -234,7 +234,7 @@ class ReportController extends Controller $title = $currentStart->formatLocalized($titleFormat); $income['entries'][$title] = round($currency[$key]['earned'] ?? '0', $currency['currency_decimal_places']); $expense['entries'][$title] = round($currency[$key]['spent'] ?? '0', $currency['currency_decimal_places']); - $currentStart = app('navigation')->addPeriod($currentStart, $preferredRange, 0); + $currentStart = app('navigation')->addPeriod($currentStart, $preferredRange, 0); } $chartData[] = $income; diff --git a/app/Http/Controllers/Chart/TagReportController.php b/app/Http/Controllers/Chart/TagReportController.php index 8603d93afa..9b6f8505fd 100644 --- a/app/Http/Controllers/Chart/TagReportController.php +++ b/app/Http/Controllers/Chart/TagReportController.php @@ -264,7 +264,9 @@ class TagReportController extends Controller $spentKey = sprintf('%d-spent', $currency['currency_id']); $chartData[$spentKey] = $chartData[$spentKey] ?? [ 'label' => sprintf( - '%s (%s)', (string)trans('firefly.spent_in_specific_tag', ['tag' => $tag->tag]), $currency['currency_name'] + '%s (%s)', + (string) trans('firefly.spent_in_specific_tag', ['tag' => $tag->tag]), + $currency['currency_name'] ), 'type' => 'bar', 'currency_symbol' => $currency['currency_symbol'], @@ -288,7 +290,9 @@ class TagReportController extends Controller $spentKey = sprintf('%d-earned', $currency['currency_id']); $chartData[$spentKey] = $chartData[$spentKey] ?? [ 'label' => sprintf( - '%s (%s)', (string)trans('firefly.earned_in_specific_tag', ['tag' => $tag->tag]), $currency['currency_name'] + '%s (%s)', + (string) trans('firefly.earned_in_specific_tag', ['tag' => $tag->tag]), + $currency['currency_name'] ), 'type' => 'bar', 'currency_symbol' => $currency['currency_symbol'], @@ -475,5 +479,4 @@ class TagReportController extends Controller return $return; } - } diff --git a/app/Http/Controllers/Chart/TransactionController.php b/app/Http/Controllers/Chart/TransactionController.php new file mode 100644 index 0000000000..1792a002ed --- /dev/null +++ b/app/Http/Controllers/Chart/TransactionController.php @@ -0,0 +1,304 @@ +. + */ + +namespace FireflyIII\Http\Controllers\Chart; + +use Carbon\Carbon; +use FireflyIII\Exceptions\FireflyException; +use FireflyIII\Generator\Chart\Basic\GeneratorInterface; +use FireflyIII\Helpers\Collector\GroupCollectorInterface; +use FireflyIII\Http\Controllers\Controller; +use FireflyIII\Models\TransactionType; +use FireflyIII\Support\CacheProperties; +use Illuminate\Http\JsonResponse; + +/** + * Class TransactionController + */ +class TransactionController extends Controller +{ + + /** @var GeneratorInterface Chart generation methods. */ + protected $generator; + + /** + * TransactionController constructor. + */ + public function __construct() + { + parent::__construct(); + $this->generator = app(GeneratorInterface::class); + } + + /** + * @param string $objectType + * @param Carbon $start + * @param Carbon $end + * + * @throws FireflyException + * @return JsonResponse + */ + public function budgets(Carbon $start, Carbon $end) + { + $cache = new CacheProperties; + $cache->addProperty($start); + $cache->addProperty($end); + $cache->addProperty('chart.transactions.budgets'); + if ($cache->has()) { + return response()->json($cache->get()); // @codeCoverageIgnore + } + + + /** @var GroupCollectorInterface $collector */ + $collector = app(GroupCollectorInterface::class); + $collector->setRange($start, $end); + $collector->withBudgetInformation(); + $collector->setTypes([TransactionType::WITHDRAWAL]); + + $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']); + // key => [value => x, 'currency_symbol' => 'x'] + $data[$title] = $data[$title] ?? [ + 'amount' => '0', + 'currency_symbol' => $journal['currency_symbol'], + ]; + $data[$title]['amount'] = bcadd($data[$title]['amount'], $journal['amount']); + + if (null !== $journal['foreign_amount']) { + $title = sprintf('%s (%s)', $budget, $journal['foreign_currency_symbol']); + $data[$title] = $data[$title] ?? [ + 'amount' => $journal['foreign_amount'], + 'currency_symbol' => $journal['currency_symbol'], + ]; + $data[$title]['amount'] = bcadd($data[$title]['amount'], $journal['foreign_amount']); + } + } + $chart = $this->generator->multiCurrencyPieChart($data); + $cache->store($chart); + + return response()->json($chart); + } + + /** + * @param string $objectType + * @param Carbon $start + * @param Carbon $end + * + * @throws FireflyException + * @return JsonResponse + */ + public function categories(string $objectType, Carbon $start, Carbon $end) + { + $cache = new CacheProperties; + $cache->addProperty($start); + $cache->addProperty($end); + $cache->addProperty($objectType); + $cache->addProperty('chart.transactions.categories'); + if ($cache->has()) { + return response()->json($cache->get()); // @codeCoverageIgnore + } + + + /** @var GroupCollectorInterface $collector */ + $collector = app(GroupCollectorInterface::class); + $collector->setRange($start, $end); + $collector->withCategoryInformation(); + switch ($objectType) { + default: + throw new FireflyException(sprintf('Cant handle "%s"', $objectType)); + case 'withdrawal': + $collector->setTypes([TransactionType::WITHDRAWAL]); + break; + case 'deposit': + $collector->setTypes([TransactionType::DEPOSIT]); + break; + case 'transfers': + $collector->setTypes([TransactionType::TRANSFER]); + break; + } + $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']); + // key => [value => x, 'currency_symbol' => 'x'] + $data[$title] = $data[$title] ?? [ + 'amount' => '0', + 'currency_symbol' => $journal['currency_symbol'], + ]; + $data[$title]['amount'] = bcadd($data[$title]['amount'], $journal['amount']); + + if (null !== $journal['foreign_amount']) { + $title = sprintf('%s (%s)', $category, $journal['foreign_currency_symbol']); + $data[$title] = $data[$title] ?? [ + 'amount' => $journal['foreign_amount'], + 'currency_symbol' => $journal['currency_symbol'], + ]; + $data[$title]['amount'] = bcadd($data[$title]['amount'], $journal['foreign_amount']); + } + } + $chart = $this->generator->multiCurrencyPieChart($data); + $cache->store($chart); + + return response()->json($chart); + } + + /** + * @param string $objectType + * @param Carbon $start + * @param Carbon $end + * + * @throws FireflyException + * @return JsonResponse + */ + public function destinationAccounts(string $objectType, Carbon $start, Carbon $end) + { + $cache = new CacheProperties; + $cache->addProperty($start); + $cache->addProperty($end); + $cache->addProperty($objectType); + $cache->addProperty('chart.transactions.destinations'); + if ($cache->has()) { + //return response()->json($cache->get()); // @codeCoverageIgnore + } + + + /** @var GroupCollectorInterface $collector */ + $collector = app(GroupCollectorInterface::class); + $collector->setRange($start, $end); + $collector->withAccountInformation(); + switch ($objectType) { + default: + throw new FireflyException(sprintf('Cant handle "%s"', $objectType)); + case 'withdrawal': + $collector->setTypes([TransactionType::WITHDRAWAL]); + break; + case 'deposit': + $collector->setTypes([TransactionType::DEPOSIT]); + break; + case 'transfers': + $collector->setTypes([TransactionType::TRANSFER]); + break; + } + $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] = $data[$title] ?? [ + 'amount' => '0', + 'currency_symbol' => $journal['currency_symbol'], + ]; + $data[$title]['amount'] = bcadd($data[$title]['amount'], $journal['amount']); + + if (null !== $journal['foreign_amount']) { + $title = sprintf('%s (%s)', $name, $journal['foreign_currency_symbol']); + $data[$title] = $data[$title] ?? [ + 'amount' => $journal['foreign_amount'], + 'currency_symbol' => $journal['currency_symbol'], + ]; + $data[$title]['amount'] = bcadd($data[$title]['amount'], $journal['foreign_amount']); + } + } + $chart = $this->generator->multiCurrencyPieChart($data); + $cache->store($chart); + + return response()->json($chart); + } + + /** + * @param string $objectType + * @param Carbon $start + * @param Carbon $end + * + * @throws FireflyException + * @return JsonResponse + */ + public function sourceAccounts(string $objectType, Carbon $start, Carbon $end) + { + $cache = new CacheProperties; + $cache->addProperty($start); + $cache->addProperty($end); + $cache->addProperty($objectType); + $cache->addProperty('chart.transactions.sources'); + if ($cache->has()) { + //return response()->json($cache->get()); // @codeCoverageIgnore + } + + + /** @var GroupCollectorInterface $collector */ + $collector = app(GroupCollectorInterface::class); + $collector->setRange($start, $end); + $collector->withAccountInformation(); + switch ($objectType) { + default: + throw new FireflyException(sprintf('Cant handle "%s"', $objectType)); + case 'withdrawal': + $collector->setTypes([TransactionType::WITHDRAWAL]); + break; + case 'deposit': + $collector->setTypes([TransactionType::DEPOSIT]); + break; + case 'transfers': + $collector->setTypes([TransactionType::TRANSFER]); + break; + } + $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] = $data[$title] ?? [ + 'amount' => '0', + 'currency_symbol' => $journal['currency_symbol'], + ]; + $data[$title]['amount'] = bcadd($data[$title]['amount'], $journal['amount']); + + if (null !== $journal['foreign_amount']) { + $title = sprintf('%s (%s)', $name, $journal['foreign_currency_symbol']); + $data[$title] = $data[$title] ?? [ + 'amount' => $journal['foreign_amount'], + 'currency_symbol' => $journal['currency_symbol'], + ]; + $data[$title]['amount'] = bcadd($data[$title]['amount'], $journal['foreign_amount']); + } + } + $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 990eb50182..cdbe66a9cd 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -78,9 +78,9 @@ class Controller extends BaseController $this->middleware( function ($request, $next) { // translations for specific strings: - $this->monthFormat = (string)trans('config.month'); - $this->monthAndDayFormat = (string)trans('config.month_and_day'); - $this->dateTimeFormat = (string)trans('config.date_time'); + $this->monthFormat = (string) trans('config.month'); + $this->monthAndDayFormat = (string) trans('config.month_and_day'); + $this->dateTimeFormat = (string) trans('config.date_time'); // get shown-intro-preference: if (auth()->check()) { @@ -97,5 +97,4 @@ class Controller extends BaseController } ); } - } diff --git a/app/Http/Controllers/CurrencyController.php b/app/Http/Controllers/CurrencyController.php index 5f909449a0..eea45f4b80 100644 --- a/app/Http/Controllers/CurrencyController.php +++ b/app/Http/Controllers/CurrencyController.php @@ -29,8 +29,11 @@ use FireflyIII\Models\TransactionCurrency; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\Repositories\User\UserRepositoryInterface; use FireflyIII\User; +use Illuminate\Contracts\View\Factory; +use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Pagination\LengthAwarePaginator; +use Illuminate\Routing\Redirector; use Log; use View; @@ -47,6 +50,7 @@ class CurrencyController extends Controller /** * CurrencyController constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -55,7 +59,7 @@ class CurrencyController extends Controller $this->middleware( function ($request, $next) { - app('view')->share('title', (string)trans('firefly.currencies')); + app('view')->share('title', (string) trans('firefly.currencies')); app('view')->share('mainTitleIcon', 'fa-usd'); $this->repository = app(CurrencyRepositoryInterface::class); $this->userRepository = app(UserRepositoryInterface::class); @@ -71,20 +75,20 @@ class CurrencyController extends Controller * * @param Request $request * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|View + * @return RedirectResponse|Redirector|View */ public function create(Request $request) { /** @var User $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'))])); + $request->session()->flash('error', (string) trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))])); return redirect(route('currencies.index')); } $subTitleIcon = 'fa-plus'; - $subTitle = (string)trans('firefly.create_currency'); + $subTitle = (string) trans('firefly.create_currency'); // put previous url in session if not redirect from store (not "create another"). if (true !== session('currencies.create.fromStore')) { @@ -103,7 +107,7 @@ class CurrencyController extends Controller * @param Request $request * @param TransactionCurrency $currency * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector */ public function defaultCurrency(Request $request, TransactionCurrency $currency) { @@ -113,7 +117,7 @@ class CurrencyController extends Controller Log::channel('audit')->info(sprintf('Make %s the default currency.', $currency->code)); $this->repository->enable($currency); - $request->session()->flash('success', (string)trans('firefly.new_default_currency', ['name' => $currency->name])); + $request->session()->flash('success', (string) trans('firefly.new_default_currency', ['name' => $currency->name])); return redirect(route('currencies.index')); } @@ -124,7 +128,7 @@ class CurrencyController extends Controller * @param Request $request * @param TransactionCurrency $currency * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|View + * @return RedirectResponse|Redirector|View */ public function delete(Request $request, TransactionCurrency $currency) { @@ -132,7 +136,7 @@ class CurrencyController extends Controller $user = auth()->user(); if (!$this->userRepository->hasRole($user, 'owner')) { // @codeCoverageIgnoreStart - $request->session()->flash('error', (string)trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))])); + $request->session()->flash('error', (string) trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))])); Log::channel('audit')->info(sprintf('Tried to visit page to delete currency %s but is not site owner.', $currency->code)); return redirect(route('currencies.index')); @@ -141,7 +145,7 @@ class CurrencyController 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')->info(sprintf('Tried to visit page to delete currency %s but currency is in use.', $currency->code)); @@ -150,7 +154,7 @@ class CurrencyController extends Controller // put previous url in session $this->rememberPreviousUri('currencies.delete.uri'); - $subTitle = (string)trans('form.delete_currency', ['name' => $currency->name]); + $subTitle = (string) trans('form.delete_currency', ['name' => $currency->name]); Log::channel('audit')->info(sprintf('Visit page to delete currency %s.', $currency->code)); return view('currencies.delete', compact('currency', 'subTitle')); @@ -162,7 +166,7 @@ class CurrencyController extends Controller * @param Request $request * @param TransactionCurrency $currency * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector */ public function destroy(Request $request, TransactionCurrency $currency) { @@ -170,7 +174,7 @@ class CurrencyController extends Controller $user = auth()->user(); if (!$this->userRepository->hasRole($user, 'owner')) { // @codeCoverageIgnoreStart - $request->session()->flash('error', (string)trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))])); + $request->session()->flash('error', (string) trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))])); Log::channel('audit')->info(sprintf('Tried to delete currency %s but is not site owner.', $currency->code)); return redirect(route('currencies.index')); @@ -178,14 +182,14 @@ class CurrencyController extends Controller } if ($this->repository->currencyInUse($currency)) { - $request->session()->flash('error', (string)trans('firefly.cannot_delete_currency', ['name' => e($currency->name)])); + $request->session()->flash('error', (string) trans('firefly.cannot_delete_currency', ['name' => e($currency->name)])); Log::channel('audit')->info(sprintf('Tried to delete currency %s but is in use.', $currency->code)); return redirect(route('currencies.index')); } if ($this->repository->isFallbackCurrency($currency)) { - $request->session()->flash('error', (string)trans('firefly.cannot_delete_fallback_currency', ['name' => e($currency->name)])); + $request->session()->flash('error', (string) trans('firefly.cannot_delete_fallback_currency', ['name' => e($currency->name)])); Log::channel('audit')->info(sprintf('Tried to delete currency %s but is FALLBACK.', $currency->code)); return redirect(route('currencies.index')); @@ -194,7 +198,7 @@ class CurrencyController extends Controller Log::channel('audit')->info(sprintf('Deleted currency %s.', $currency->code)); $this->repository->destroy($currency); - $request->session()->flash('success', (string)trans('firefly.deleted_currency', ['name' => $currency->name])); + $request->session()->flash('success', (string) trans('firefly.deleted_currency', ['name' => $currency->name])); return redirect($this->getPreviousUri('currencies.delete.uri')); } @@ -203,8 +207,8 @@ class CurrencyController extends Controller * @param Request $request * @param TransactionCurrency $currency * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector * @throws FireflyException + * @return RedirectResponse|Redirector */ public function disableCurrency(Request $request, TransactionCurrency $currency) { @@ -214,7 +218,7 @@ class CurrencyController extends Controller $user = auth()->user(); if (!$this->userRepository->hasRole($user, 'owner')) { // @codeCoverageIgnoreStart - $request->session()->flash('error', (string)trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))])); + $request->session()->flash('error', (string) trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))])); Log::channel('audit')->info(sprintf('Tried to disable currency %s but is not site owner.', $currency->code)); return redirect(route('currencies.index')); @@ -224,7 +228,7 @@ class CurrencyController 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')->info(sprintf('Tried to disable currency %s but is in use.', $currency->code)); @@ -248,10 +252,10 @@ class CurrencyController extends Controller } if ('EUR' === $currency->code) { - session()->flash('warning', (string)trans('firefly.disable_EUR_side_effects')); + session()->flash('warning', (string) trans('firefly.disable_EUR_side_effects')); } - 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])); return redirect(route('currencies.index')); } @@ -262,7 +266,7 @@ class CurrencyController extends Controller * @param Request $request * @param TransactionCurrency $currency * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|View + * @return RedirectResponse|Redirector|View */ public function edit(Request $request, TransactionCurrency $currency) { @@ -270,7 +274,7 @@ class CurrencyController extends Controller $user = auth()->user(); if (!$this->userRepository->hasRole($user, 'owner')) { // @codeCoverageIgnoreStart - $request->session()->flash('error', (string)trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))])); + $request->session()->flash('error', (string) trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))])); Log::channel('audit')->info(sprintf('Tried to edit currency %s but is not owner.', $currency->code)); return redirect(route('currencies.index')); @@ -278,13 +282,13 @@ class CurrencyController extends Controller } $subTitleIcon = 'fa-pencil'; - $subTitle = (string)trans('breadcrumbs.edit_currency', ['name' => $currency->name]); + $subTitle = (string) trans('breadcrumbs.edit_currency', ['name' => $currency->name]); $currency->symbol = htmlentities($currency->symbol); // code to handle active-checkboxes $hasOldInput = null !== $request->old('_token'); $preFilled = [ - 'enabled' => $hasOldInput ? (bool)$request->old('enabled') : $currency->enabled, + 'enabled' => $hasOldInput ? (bool) $request->old('enabled') : $currency->enabled, ]; $request->session()->flash('preFilled', $preFilled); @@ -302,14 +306,14 @@ class CurrencyController extends Controller /** * @param TransactionCurrency $currency * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector */ public function enableCurrency(TransactionCurrency $currency) { app('preferences')->mark(); $this->repository->enable($currency); - 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])); Log::channel('audit')->info(sprintf('Enabled currency %s.', $currency->code)); return redirect(route('currencies.index')); @@ -320,14 +324,14 @@ class CurrencyController extends Controller * * @param Request $request * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|\Illuminate\View\View */ public function index(Request $request) { /** @var User $user */ $user = auth()->user(); - $page = 0 === (int)$request->get('page') ? 1 : (int)$request->get('page'); - $pageSize = (int)app('preferences')->get('listPageSize', 50)->data; + $page = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page'); + $pageSize = (int) app('preferences')->get('listPageSize', 50)->data; $collection = $this->repository->getAll(); $total = $collection->count(); $collection = $collection->slice(($page - 1) * $pageSize, $pageSize); @@ -337,7 +341,7 @@ class CurrencyController extends Controller $defaultCurrency = $this->repository->getCurrencyByPreference(app('preferences')->get('currencyPreference', config('firefly.default_currency', 'EUR'))); $isOwner = true; if (!$this->userRepository->hasRole($user, 'owner')) { - $request->session()->flash('info', (string)trans('firefly.ask_site_owner', ['owner' => config('firefly.site_owner')])); + $request->session()->flash('info', (string) trans('firefly.ask_site_owner', ['owner' => config('firefly.site_owner')])); $isOwner = false; } @@ -350,7 +354,7 @@ class CurrencyController extends Controller * * @param CurrencyFormRequest $request * - * @return $this|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return $this|RedirectResponse|Redirector */ public function store(CurrencyFormRequest $request) { @@ -372,15 +376,15 @@ class CurrencyController extends Controller } catch (FireflyException $e) { Log::error($e->getMessage()); Log::channel('audit')->info('Could not store (POST) currency without admin rights.', $data); - $request->session()->flash('error', (string)trans('firefly.could_not_store_currency')); + $request->session()->flash('error', (string) trans('firefly.could_not_store_currency')); $currency = null; } - $redirect = redirect($this->getPreviousUri('currencies.create.uri')); + $redirect = redirect($this->getPreviousUri('currencies.create.uri')); if (null !== $currency) { - $request->session()->flash('success', (string)trans('firefly.created_currency', ['name' => $currency->name])); + $request->session()->flash('success', (string) trans('firefly.created_currency', ['name' => $currency->name])); Log::channel('audit')->info('Created (POST) currency.', $data); - if (1 === (int)$request->get('create_another')) { + if (1 === (int) $request->get('create_another')) { // @codeCoverageIgnoreStart $request->session()->put('currencies.create.fromStore', true); @@ -399,7 +403,7 @@ class CurrencyController extends Controller * @param CurrencyFormRequest $request * @param TransactionCurrency $currency * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector */ public function update(CurrencyFormRequest $request, TransactionCurrency $currency) { @@ -412,7 +416,7 @@ class CurrencyController extends Controller } if (!$this->userRepository->hasRole($user, 'owner')) { // @codeCoverageIgnoreStart - $request->session()->flash('error', (string)trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))])); + $request->session()->flash('error', (string) trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))])); Log::channel('audit')->info('Tried to update (POST) currency without admin rights.', $data); return redirect(route('currencies.index')); @@ -422,10 +426,10 @@ class CurrencyController extends Controller $currency = $this->repository->update($currency, $data); Log::channel('audit')->info('Updated (POST) currency.', $data); - $request->session()->flash('success', (string)trans('firefly.updated_currency', ['name' => $currency->name])); + $request->session()->flash('success', (string) trans('firefly.updated_currency', ['name' => $currency->name])); app('preferences')->mark(); - if (1 === (int)$request->get('return_to_edit')) { + if (1 === (int) $request->get('return_to_edit')) { // @codeCoverageIgnoreStart $request->session()->put('currencies.edit.fromUpdate', true); diff --git a/app/Http/Controllers/DebugController.php b/app/Http/Controllers/DebugController.php index d0e2dd61e3..30e158829f 100644 --- a/app/Http/Controllers/DebugController.php +++ b/app/Http/Controllers/DebugController.php @@ -30,7 +30,9 @@ use Exception; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Middleware\IsDemoUser; use FireflyIII\Support\Http\Controllers\GetConfigurationData; +use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; +use Illuminate\Routing\Redirector; use Illuminate\Routing\Route; use Log; use Monolog\Handler\RotatingFileHandler; @@ -46,6 +48,7 @@ class DebugController extends Controller /** * DebugController constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -77,7 +80,7 @@ class DebugController extends Controller * * @param Request $request * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector */ public function flush(Request $request) { @@ -129,7 +132,7 @@ class DebugController extends Controller $userAgent = $request->header('user-agent'); $trustedProxies = config('firefly.trusted_proxies'); $displayErrors = ini_get('display_errors'); - $errorReporting = $this->errorReporting((int)ini_get('error_reporting')); + $errorReporting = $this->errorReporting((int) ini_get('error_reporting')); $appEnv = config('app.env'); $appDebug = var_export(config('app.debug'), true); $logChannel = config('logging.default'); @@ -140,7 +143,7 @@ class DebugController extends Controller // set languages, see what happens: $original = setlocale(LC_ALL, 0); $localeAttempts = []; - $parts = explode(',', (string)trans('config.locale')); + $parts = explode(',', (string) trans('config.locale')); foreach ($parts as $code) { $code = trim($code); $localeAttempts[$code] = var_export(setlocale(LC_ALL, $code), true); @@ -172,11 +175,29 @@ class DebugController extends Controller } return view( - 'debug', compact( - 'phpVersion', 'extensions', 'localeAttempts', 'appEnv', 'appDebug', 'logChannel', 'appLogLevel', 'now', 'drivers', 'currentDriver', - 'loginProvider', - 'userAgent', 'displayErrors', 'installationId', 'errorReporting', 'phpOs', 'interface', 'logContent', 'cacheDriver', 'trustedProxies' - ) + 'debug', + compact( + 'phpVersion', + 'extensions', + 'localeAttempts', + 'appEnv', + 'appDebug', + 'logChannel', + 'appLogLevel', + 'now', + 'drivers', + 'currentDriver', + 'loginProvider', + 'userAgent', + 'displayErrors', + 'installationId', + 'errorReporting', + 'phpOs', + 'interface', + 'logContent', + 'cacheDriver', + 'trustedProxies' + ) ); } @@ -203,7 +224,7 @@ class DebugController extends Controller $return = ' '; /** @var Route $route */ foreach ($set as $route) { - $name = (string)$route->getName(); + $name = (string) $route->getName(); if (in_array('GET', $route->methods(), true)) { $found = false; foreach ($ignore as $string) { @@ -226,7 +247,7 @@ class DebugController extends Controller * * @param Request $request * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector */ public function testFlash(Request $request) { @@ -237,6 +258,4 @@ class DebugController extends Controller return redirect(route('home')); } - - } diff --git a/app/Http/Controllers/Export/IndexController.php b/app/Http/Controllers/Export/IndexController.php index afeeab5912..04464901cc 100644 --- a/app/Http/Controllers/Export/IndexController.php +++ b/app/Http/Controllers/Export/IndexController.php @@ -27,7 +27,10 @@ use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Middleware\IsDemoUser; use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Support\Export\ExportDataGenerator; +use Illuminate\Contracts\View\Factory; use Illuminate\Http\Response as LaravelResponse; +use Illuminate\View\View; +use League\Csv\CannotInsertRecord; /** * Class IndexController @@ -51,7 +54,7 @@ class IndexController extends Controller $this->middleware( function ($request, $next) { app('view')->share('mainTitleIcon', 'fa-life-bouy'); - app('view')->share('title', (string)trans('firefly.export_data_title')); + app('view')->share('title', (string) trans('firefly.export_data_title')); $this->journalRepository = app(JournalRepositoryInterface::class); $this->middleware(IsDemoUser::class)->except(['index']); @@ -61,8 +64,8 @@ class IndexController extends Controller } /** + * @throws CannotInsertRecord * @return LaravelResponse - * @throws \League\Csv\CannotInsertRecord */ public function export(): LaravelResponse { @@ -97,12 +100,13 @@ class IndexController extends Controller ->header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0') ->header('Pragma', 'public') ->header('Content-Length', strlen($result['transactions'])); + // return CSV file made from 'transactions' array. return $response; } /** - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function index() { diff --git a/app/Http/Controllers/HomeController.php b/app/Http/Controllers/HomeController.php index 7ad7d90e99..270afd955f 100644 --- a/app/Http/Controllers/HomeController.php +++ b/app/Http/Controllers/HomeController.php @@ -31,9 +31,13 @@ use FireflyIII\Models\AccountType; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Bill\BillRepositoryInterface; use FireflyIII\User; +use Illuminate\Contracts\View\Factory; use Illuminate\Http\JsonResponse; +use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; +use Illuminate\Routing\Redirector; use Illuminate\Support\Collection; +use Illuminate\View\View; use Log; /** @@ -59,8 +63,8 @@ class HomeController extends Controller * * @param Request $request * - * @return JsonResponse * @throws Exception + * @return JsonResponse */ public function dateRange(Request $request): JsonResponse { @@ -74,7 +78,7 @@ class HomeController extends Controller // 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')) { + if ($label === (string) trans('firefly.everything') || $label === (string) trans('firefly.customRange')) { $isCustomRange = true; Log::debug('Range is now marked as "custom".'); } @@ -82,7 +86,7 @@ class HomeController extends Controller $diff = $start->diffInDays($end); if ($diff > 50) { - $request->session()->flash('warning', (string)trans('firefly.warning_much_data', ['days' => $diff])); + $request->session()->flash('warning', (string) trans('firefly.warning_much_data', ['days' => $diff])); } $request->session()->put('is_custom_range', $isCustomRange); @@ -101,8 +105,8 @@ class HomeController extends Controller * * @param AccountRepositoryInterface $repository * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View * @throws Exception + * @return Factory|RedirectResponse|Redirector|View */ public function index(AccountRepositoryInterface $repository) { @@ -113,10 +117,11 @@ class HomeController extends Controller if (0 === $count) { return redirect(route('new-user.index')); } - $subTitle = (string)trans('firefly.welcomeBack'); + $subTitle = (string) trans('firefly.welcomeBack'); $transactions = []; $frontPage = app('preferences')->get( - 'frontPageAccounts', $repository->getAccountsByType([AccountType::DEFAULT, AccountType::ASSET])->pluck('id')->toArray() + 'frontPageAccounts', + $repository->getAccountsByType([AccountType::DEFAULT, AccountType::ASSET])->pluck('id')->toArray() ); /** @var Carbon $start */ $start = session('start', Carbon::now()->startOfMonth()); @@ -145,5 +150,4 @@ class HomeController extends Controller return view('index', compact('count', 'subTitle', 'transactions', 'billCount', 'start', 'end', 'today')); } - } diff --git a/app/Http/Controllers/Import/CallbackController.php b/app/Http/Controllers/Import/CallbackController.php index 1c202f7320..9e9c8ad65a 100644 --- a/app/Http/Controllers/Import/CallbackController.php +++ b/app/Http/Controllers/Import/CallbackController.php @@ -26,11 +26,18 @@ namespace FireflyIII\Http\Controllers\Import; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; +use Illuminate\Contracts\View\Factory; +use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; +use Illuminate\Routing\Redirector; +use Illuminate\View\View; use Log; /** * Class CallbackController + * + * @deprecated + * @codeCoverageIgnore */ class CallbackController extends Controller { @@ -42,12 +49,12 @@ class CallbackController extends Controller * * @param ImportJobRepositoryInterface $repository * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View + * @return Factory|RedirectResponse|Redirector|View */ public function ynab(Request $request, ImportJobRepositoryInterface $repository) { - $code = (string)$request->get('code'); - $jobKey = (string)$request->get('state'); + $code = (string) $request->get('code'); + $jobKey = (string) $request->get('state'); if ('' === $code) { return view('error')->with('message', 'You Need A Budget did not reply with a valid authorization code. Firefly III cannot continue.'); diff --git a/app/Http/Controllers/Import/IndexController.php b/app/Http/Controllers/Import/IndexController.php index 67d3f54d63..d06579bded 100644 --- a/app/Http/Controllers/Import/IndexController.php +++ b/app/Http/Controllers/Import/IndexController.php @@ -28,12 +28,19 @@ use FireflyIII\Models\ImportJob; use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; use FireflyIII\Repositories\User\UserRepositoryInterface; use FireflyIII\Support\Binder\ImportProvider; +use Illuminate\Contracts\View\Factory; +use Illuminate\Http\RedirectResponse; use Illuminate\Http\Response as LaravelResponse; +use Illuminate\Routing\Redirector; +use Illuminate\View\View; use Log; /** * * Class IndexController + * + * @deprecated + * @codeCoverageIgnore */ class IndexController extends Controller { @@ -54,7 +61,7 @@ class IndexController extends Controller $this->middleware( function ($request, $next) { app('view')->share('mainTitleIcon', 'fa-archive'); - app('view')->share('title', (string)trans('firefly.import_index_title')); + app('view')->share('title', (string) trans('firefly.import_index_title')); $this->repository = app(ImportJobRepositoryInterface::class); $this->userRepository = app(UserRepositoryInterface::class); $this->providers = ImportProvider::getProviders(); @@ -69,14 +76,14 @@ class IndexController extends Controller * * @param string $importProvider * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector * */ public function create(string $importProvider) { - $hasPreReq = (bool)config(sprintf('import.has_prereq.%s', $importProvider)); - $hasConfig = (bool)config(sprintf('import.has_job_config.%s', $importProvider)); - $allowedForDemo = (bool)config(sprintf('import.allowed_for_demo.%s', $importProvider)); + $hasPreReq = (bool) config(sprintf('import.has_prereq.%s', $importProvider)); + $hasConfig = (bool) config(sprintf('import.has_job_config.%s', $importProvider)); + $allowedForDemo = (bool) config(sprintf('import.allowed_for_demo.%s', $importProvider)); $isDemoUser = $this->userRepository->hasRole(auth()->user(), 'demo'); Log::debug(sprintf('Will create job for provider "%s"', $importProvider)); @@ -109,7 +116,7 @@ class IndexController extends Controller // job has prerequisites: Log::debug('Job provider has prerequisites.'); /** @var PrerequisitesInterface $providerPre */ - $providerPre = app((string)config(sprintf('import.prerequisites.%s', $importProvider))); + $providerPre = app((string) config(sprintf('import.prerequisites.%s', $importProvider))); $providerPre->setUser($importJob->user); // and are not filled in: @@ -177,12 +184,12 @@ class IndexController extends Controller /** * General import index. * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function index() { $providers = $this->providers; - $subTitle = (string)trans('import.index_breadcrumb'); + $subTitle = (string) trans('import.index_breadcrumb'); $subTitleIcon = 'fa-home'; $isDemoUser = $this->userRepository->hasRole(auth()->user(), 'demo'); diff --git a/app/Http/Controllers/Import/JobConfigurationController.php b/app/Http/Controllers/Import/JobConfigurationController.php index 931f3dce9b..50c4ba1aa5 100644 --- a/app/Http/Controllers/Import/JobConfigurationController.php +++ b/app/Http/Controllers/Import/JobConfigurationController.php @@ -27,13 +27,20 @@ use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\ImportJob; use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; use FireflyIII\Support\Http\Controllers\CreateStuff; +use Illuminate\Contracts\View\Factory; +use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Http\UploadedFile; +use Illuminate\Routing\Redirector; use Illuminate\Support\MessageBag; +use Illuminate\View\View; use Log; /** * Class JobConfigurationController + * + * @deprecated + * @codeCoverageIgnore */ class JobConfigurationController extends Controller { @@ -51,7 +58,7 @@ class JobConfigurationController extends Controller $this->middleware( function ($request, $next) { app('view')->share('mainTitleIcon', 'fa-archive'); - app('view')->share('title', (string)trans('firefly.import_index_title')); + app('view')->share('title', (string) trans('firefly.import_index_title')); $this->repository = app(ImportJobRepositoryInterface::class); return $next($request); @@ -64,10 +71,10 @@ class JobConfigurationController extends Controller * * @param ImportJob $importJob * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View - * * @throws FireflyException * + * @return Factory|RedirectResponse|Redirector|View + * */ public function index(ImportJob $importJob) { @@ -75,7 +82,7 @@ class JobConfigurationController extends Controller $allowed = ['has_prereq', 'need_job_config']; if (null !== $importJob && !in_array($importJob->status, $allowed, true)) { Log::error(sprintf('Job has state "%s", but we only accept %s', $importJob->status, json_encode($allowed))); - session()->flash('error', (string)trans('import.bad_job_status', ['status' => e($importJob->status)])); + session()->flash('error', (string) trans('import.bad_job_status', ['status' => e($importJob->status)])); return redirect(route('import.index')); } @@ -83,7 +90,7 @@ class JobConfigurationController extends Controller // if provider has no config, just push it through: $importProvider = $importJob->provider; - if (!(bool)config(sprintf('import.has_job_config.%s', $importProvider))) { + if (!(bool) config(sprintf('import.has_job_config.%s', $importProvider))) { // @codeCoverageIgnoreStart Log::debug('Job needs no config, is ready to run!'); $this->repository->setStatus($importJob, 'ready_to_run'); @@ -102,7 +109,7 @@ class JobConfigurationController extends Controller $view = $configurator->getNextView(); $data = $configurator->getNextData(); - $subTitle = (string)trans('import.job_configuration_breadcrumb', ['key' => $importJob->key]); + $subTitle = (string) trans('import.job_configuration_breadcrumb', ['key' => $importJob->key]); $subTitleIcon = 'fa-wrench'; return view($view, compact('data', 'importJob', 'subTitle', 'subTitleIcon')); @@ -114,16 +121,16 @@ class JobConfigurationController extends Controller * @param Request $request * @param ImportJob $importJob * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector - * * @throws FireflyException + * @return RedirectResponse|Redirector + * */ public function post(Request $request, ImportJob $importJob) { // catch impossible status: $allowed = ['has_prereq', 'need_job_config']; if (null !== $importJob && !in_array($importJob->status, $allowed, true)) { - session()->flash('error', (string)trans('import.bad_job_status', ['status' => e($importJob->status)])); + session()->flash('error', (string) trans('import.bad_job_status', ['status' => e($importJob->status)])); return redirect(route('import.index')); } diff --git a/app/Http/Controllers/Import/JobStatusController.php b/app/Http/Controllers/Import/JobStatusController.php index c311c0ceac..f90dc9f383 100644 --- a/app/Http/Controllers/Import/JobStatusController.php +++ b/app/Http/Controllers/Import/JobStatusController.php @@ -34,6 +34,9 @@ use Log; /** * Class JobStatusController + * + * @deprecated + * @codeCoverageIgnore */ class JobStatusController extends Controller { @@ -53,7 +56,7 @@ class JobStatusController extends Controller $this->middleware( function ($request, $next) { app('view')->share('mainTitleIcon', 'fa-archive'); - app('view')->share('title', (string)trans('firefly.import_index_title')); + app('view')->share('title', (string) trans('firefly.import_index_title')); $this->repository = app(ImportJobRepositoryInterface::class); return $next($request); @@ -71,7 +74,7 @@ class JobStatusController extends Controller public function index(ImportJob $importJob) { $subTitleIcon = 'fa-gear'; - $subTitle = (string)trans('import.job_status_breadcrumb', ['key' => $importJob->key]); + $subTitle = (string) trans('import.job_status_breadcrumb', ['key' => $importJob->key]); return view('import.status', compact('importJob', 'subTitle', 'subTitleIcon')); } @@ -92,7 +95,7 @@ class JobStatusController extends Controller 'count' => $count, 'tag_id' => $importJob->tag_id, 'tag_name' => null === $importJob->tag_id ? null : $importJob->tag->tag, - 'report_txt' => (string)trans('import.unknown_import_result'), + 'report_txt' => (string) trans('import.unknown_import_result'), 'download_config' => false, 'download_config_text' => '', ]; @@ -109,11 +112,12 @@ class JobStatusController extends Controller $count = $this->repository->countByTag($importJob); } if (0 === $count) { - $json['report_txt'] = (string)trans('import.result_no_transactions'); + $json['report_txt'] = (string) trans('import.result_no_transactions'); } if (1 === $count && null !== $importJob->tag_id) { $json['report_txt'] = trans( - 'import.result_one_transaction', ['route' => route('tags.show', [$importJob->tag_id, 'all']), 'tag' => $importJob->tag->tag] + 'import.result_one_transaction', + ['route' => route('tags.show', [$importJob->tag_id, 'all']), 'tag' => $importJob->tag->tag] ); } if ($count > 1 && null !== $importJob->tag_id) { @@ -233,6 +237,4 @@ class JobStatusController extends Controller // expect nothing from routine, just return OK to user. return response()->json(['status' => 'OK', 'message' => 'storage_finished']); } - - } diff --git a/app/Http/Controllers/Import/PrerequisitesController.php b/app/Http/Controllers/Import/PrerequisitesController.php index 062f49d67a..e0c1fea936 100644 --- a/app/Http/Controllers/Import/PrerequisitesController.php +++ b/app/Http/Controllers/Import/PrerequisitesController.php @@ -27,11 +27,18 @@ use FireflyIII\Import\Prerequisites\PrerequisitesInterface; use FireflyIII\Models\ImportJob; use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; use FireflyIII\User; +use Illuminate\Contracts\View\Factory; +use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; +use Illuminate\Routing\Redirector; +use Illuminate\View\View; use Log; /** * Class PrerequisitesController + * + * @deprecated + * @codeCoverageIgnore */ class PrerequisitesController extends Controller { @@ -49,7 +56,7 @@ class PrerequisitesController extends Controller $this->middleware( function ($request, $next) { app('view')->share('mainTitleIcon', 'fa-archive'); - app('view')->share('title', (string)trans('firefly.import_index_title')); + app('view')->share('title', (string) trans('firefly.import_index_title')); app('view')->share('subTitleIcon', 'fa-check'); $this->repository = app(ImportJobRepositoryInterface::class); @@ -66,7 +73,7 @@ class PrerequisitesController extends Controller * @param string $importProvider * @param ImportJob $importJob * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function index(string $importProvider, ImportJob $importJob = null) { @@ -74,13 +81,13 @@ class PrerequisitesController extends Controller $allowed = ['new']; if (null !== $importJob && !in_array($importJob->status, $allowed, true)) { Log::error(sprintf('Job has state "%s" but this Prerequisites::index() only accepts %s', $importJob->status, json_encode($allowed))); - session()->flash('error', (string)trans('import.bad_job_status', ['status' => e($importJob->status)])); + session()->flash('error', (string) trans('import.bad_job_status', ['status' => e($importJob->status)])); return redirect(route('import.index')); } - app('view')->share('subTitle', (string)trans('import.prerequisites_breadcrumb_' . $importProvider)); - $class = (string)config(sprintf('import.prerequisites.%s', $importProvider)); + app('view')->share('subTitle', (string) trans('import.prerequisites_breadcrumb_' . $importProvider)); + $class = (string) config(sprintf('import.prerequisites.%s', $importProvider)); /** @var User $user */ $user = auth()->user(); /** @var PrerequisitesInterface $object */ @@ -97,7 +104,7 @@ class PrerequisitesController extends Controller $view = $object->getView(); - $parameters = ['title' => (string)trans('firefly.import_index_title'), 'mainTitleIcon' => 'fa-archive', 'importJob' => $importJob]; + $parameters = ['title' => (string) trans('firefly.import_index_title'), 'mainTitleIcon' => 'fa-archive', 'importJob' => $importJob]; $parameters = array_merge($object->getViewParameters(), $parameters); return view($view, $parameters); @@ -113,7 +120,7 @@ class PrerequisitesController extends Controller * @param string $importProvider * @param ImportJob $importJob * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector * @see PrerequisitesInterface::storePrerequisites * */ @@ -125,13 +132,13 @@ class PrerequisitesController extends Controller $allowed = ['new']; if (null !== $importJob && !in_array($importJob->status, $allowed, true)) { Log::error(sprintf('Job has state "%s" but this Prerequisites::post() only accepts %s', $importJob->status, json_encode($allowed))); - session()->flash('error', (string)trans('import.bad_job_status', ['status' => e($importJob->status)])); + session()->flash('error', (string) trans('import.bad_job_status', ['status' => e($importJob->status)])); return redirect(route('import.index')); } - $class = (string)config(sprintf('import.prerequisites.%s', $importProvider)); + $class = (string) config(sprintf('import.prerequisites.%s', $importProvider)); /** @var User $user */ $user = auth()->user(); /** @var PrerequisitesInterface $object */ @@ -151,7 +158,7 @@ class PrerequisitesController extends Controller } // session flash! - $request->session()->flash('success', (string)trans('import.prerequisites_saved_for_' . $importProvider)); + $request->session()->flash('success', (string) trans('import.prerequisites_saved_for_' . $importProvider)); // if has job, redirect to global config for provider // if no job, back to index! diff --git a/app/Http/Controllers/JavascriptController.php b/app/Http/Controllers/JavascriptController.php index f2b901bbd6..240c78a98d 100644 --- a/app/Http/Controllers/JavascriptController.php +++ b/app/Http/Controllers/JavascriptController.php @@ -44,7 +44,7 @@ class JavascriptController extends Controller * @param AccountRepositoryInterface $repository * @param CurrencyRepositoryInterface $currencyRepository * - * @return \Illuminate\Http\Response + * @return Response */ public function accounts(AccountRepositoryInterface $repository, CurrencyRepositoryInterface $currencyRepository): Response { @@ -60,7 +60,7 @@ class JavascriptController extends Controller /** @var Account $account */ foreach ($accounts as $account) { $accountId = $account->id; - $currency = (int)$repository->getMetaValue($account, 'currency_id'); + $currency = (int) $repository->getMetaValue($account, 'currency_id'); /** @noinspection NullPointerExceptionInspection */ $currency = 0 === $currency ? $default->id : $currency; $entry = ['preferredCurrency' => $currency, 'name' => $account->name]; @@ -102,15 +102,15 @@ class JavascriptController extends Controller * @param AccountRepositoryInterface $repository * @param CurrencyRepositoryInterface $currencyRepository * - * @return \Illuminate\Http\Response + * @return Response */ public function variables(Request $request, AccountRepositoryInterface $repository, CurrencyRepositoryInterface $currencyRepository): Response { - $account = $repository->findNull((int)$request->get('account')); + $account = $repository->findNull((int) $request->get('account')); $currencyId = 0; if (null !== $account) { // TODO we can use getAccountCurrency() instead - $currencyId = (int)$repository->getMetaValue($account, 'currency_id'); + $currencyId = (int) $repository->getMetaValue($account, 'currency_id'); } /** @var TransactionCurrency $currency */ $currency = $currencyRepository->findNull($currencyId); diff --git a/app/Http/Controllers/Json/AutoCompleteController.php b/app/Http/Controllers/Json/AutoCompleteController.php index 8212f5d21f..820d4ed711 100644 --- a/app/Http/Controllers/Json/AutoCompleteController.php +++ b/app/Http/Controllers/Json/AutoCompleteController.php @@ -22,6 +22,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Json; +use Amount; use Carbon\Carbon; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\Account; @@ -78,7 +79,7 @@ class AutoCompleteController extends Controller Log::debug(sprintf('Now in accounts("%s"). Filtering results.', $search), $filteredAccountTypes); $return = []; - $result = $repository->searchAccount((string)$search, $filteredAccountTypes); + $result = $repository->searchAccount((string) $search, $filteredAccountTypes); $defaultCurrency = app('amount')->getDefaultCurrency(); /** @var Account $account */ @@ -117,7 +118,7 @@ class AutoCompleteController extends Controller */ public function allJournals(Request $request): JsonResponse { - $search = (string)$request->get('search'); + $search = (string) $request->get('search'); /** @var JournalRepositoryInterface $repository */ $repository = app(JournalRepositoryInterface::class); $result = $repository->searchJournalDescriptions($search); @@ -132,7 +133,8 @@ class AutoCompleteController extends Controller $journal['name'] = $journal['description']; return $journal; - }, $array + }, + $array ); return response()->json(array_values($array)); @@ -150,7 +152,7 @@ class AutoCompleteController extends Controller */ public function allJournalsWithID(Request $request): JsonResponse { - $search = (string)$request->get('search'); + $search = (string) $request->get('search'); /** @var JournalRepositoryInterface $repository */ $repository = app(JournalRepositoryInterface::class); @@ -161,7 +163,7 @@ class AutoCompleteController extends Controller $array = []; if (is_numeric($search)) { // search for group, not journal. - $firstResult = $groupRepos->find((int)$search); + $firstResult = $groupRepos->find((int) $search); if (null !== $firstResult) { // group may contain multiple journals, each a result: foreach ($firstResult->transactionJournals as $journal) { @@ -201,7 +203,7 @@ class AutoCompleteController extends Controller Log::debug(sprintf('Now in expenseAccounts(%s). Filtering results.', $search), $allowedAccountTypes); $return = []; - $result = $repository->searchAccount((string)$search, $allowedAccountTypes); + $result = $repository->searchAccount((string) $search, $allowedAccountTypes); /** @var Account $account */ foreach ($result as $account) { @@ -223,7 +225,7 @@ class AutoCompleteController extends Controller */ public function bills(Request $request): JsonResponse { - $query = (string)$request->get('search'); + $query = (string) $request->get('search'); /** @var BillRepositoryInterface $repository */ $repository = app(BillRepositoryInterface::class); $result = $repository->searchBill($query); @@ -239,7 +241,7 @@ class AutoCompleteController extends Controller */ public function budgets(Request $request): JsonResponse { - $search = (string)$request->get('search'); + $search = (string) $request->get('search'); /** @var BudgetRepositoryInterface $repository */ $repository = app(BudgetRepositoryInterface::class); $result = $repository->searchBudget($search); @@ -255,7 +257,7 @@ class AutoCompleteController extends Controller */ public function categories(Request $request): JsonResponse { - $query = (string)$request->get('search'); + $query = (string) $request->get('search'); /** @var CategoryRepositoryInterface $repository */ $repository = app(CategoryRepositoryInterface::class); $result = $repository->searchCategory($query); @@ -297,7 +299,7 @@ class AutoCompleteController extends Controller */ public function currencyNames(Request $request): JsonResponse { - $query = (string)$request->get('search'); + $query = (string) $request->get('search'); /** @var CurrencyRepositoryInterface $repository */ $repository = app(CurrencyRepositoryInterface::class); $result = $repository->searchCurrency($query)->toArray(); @@ -326,7 +328,7 @@ class AutoCompleteController extends Controller Log::debug(sprintf('Now in expenseAccounts(%s). Filtering results.', $search), $allowedAccountTypes); $return = []; - $result = $repository->searchAccount((string)$search, $allowedAccountTypes); + $result = $repository->searchAccount((string) $search, $allowedAccountTypes); /** @var Account $account */ foreach ($result as $account) { @@ -353,7 +355,7 @@ class AutoCompleteController extends Controller $accountRepos = app(AccountRepositoryInterface::class); $piggies = $repository->getPiggyBanks(); - $defaultCurrency = \Amount::getDefaultCurrency(); + $defaultCurrency = Amount::getDefaultCurrency(); $response = []; /** @var PiggyBank $piggy */ foreach ($piggies as $piggy) { @@ -389,7 +391,7 @@ class AutoCompleteController extends Controller Log::debug('Now in revenueAccounts(). Filtering results.', $allowedAccountTypes); $return = []; - $result = $repository->searchAccount((string)$search, $allowedAccountTypes); + $result = $repository->searchAccount((string) $search, $allowedAccountTypes); /** @var Account $account */ foreach ($result as $account) { @@ -411,7 +413,7 @@ class AutoCompleteController extends Controller */ public function tags(Request $request): JsonResponse { - $search = (string)$request->get('search'); + $search = (string) $request->get('search'); /** @var TagRepositoryInterface $repository */ $repository = app(TagRepositoryInterface::class); $result = $repository->searchTags($search); @@ -432,7 +434,7 @@ class AutoCompleteController extends Controller */ public function transactionTypes(Request $request): JsonResponse { - $query = (string)$request->get('search'); + $query = (string) $request->get('search'); /** @var TransactionTypeRepositoryInterface $repository */ $repository = app(TransactionTypeRepositoryInterface::class); $array = $repository->searchTypes($query)->toArray(); @@ -444,5 +446,4 @@ class AutoCompleteController extends Controller return response()->json($array); } - } diff --git a/app/Http/Controllers/Json/BoxController.php b/app/Http/Controllers/Json/BoxController.php index 7ec0f37d45..82ffa2086c 100644 --- a/app/Http/Controllers/Json/BoxController.php +++ b/app/Http/Controllers/Json/BoxController.php @@ -34,7 +34,6 @@ use FireflyIII\Models\TransactionType; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Bill\BillRepositoryInterface; use FireflyIII\Repositories\Budget\AvailableBudgetRepositoryInterface; -use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Repositories\Budget\OperationsRepositoryInterface; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\Support\CacheProperties; @@ -71,7 +70,7 @@ class BoxController extends Controller $end = session('end', Carbon::now()->endOfMonth()); $today = new Carbon; $display = 2; // see method docs. - $boxTitle = (string)trans('firefly.spent'); + $boxTitle = (string) trans('firefly.spent'); $cache = new CacheProperties; $cache->addProperty($start); @@ -98,19 +97,19 @@ class BoxController extends Controller // spent in this period, in budgets, for default currency. // also calculate spent per day. $spent = $opsRepository->sumExpenses($start, $end, null, null, $currency); - $spentAmount = $spent[(int)$currency->id]['sum'] ?? '0'; + $spentAmount = $spent[(int) $currency->id]['sum'] ?? '0'; $spentPerDay = '-1'; if ($availableBudgets->count() > 0) { - $display = 0; // assume user overspent - $boxTitle = (string)trans('firefly.overspent'); - $totalAvailableSum = (string)$availableBudgets->sum('amount'); + $display = 0; // assume user overspent + $boxTitle = (string) trans('firefly.overspent'); + $totalAvailableSum = (string) $availableBudgets->sum('amount'); // calculate with available budget. $leftToSpendAmount = bcadd($totalAvailableSum, $spentAmount); if (1 === bccomp($leftToSpendAmount, '0')) { - $boxTitle = (string)trans('firefly.left_to_spend'); + $boxTitle = (string) trans('firefly.left_to_spend'); $days = $today->diffInDays($end) + 1; $display = 1; // not overspent - $leftPerDayAmount = bcdiv($leftToSpendAmount, (string)$days); + $leftPerDayAmount = bcdiv($leftToSpendAmount, (string) $days); } } @@ -164,7 +163,7 @@ class BoxController extends Controller $set = $collector->getExtractedJournals(); /** @var array $journal */ foreach ($set as $journal) { - $currencyId = (int)$journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $amount = $journal['amount'] ?? '0'; $incomes[$currencyId] = $incomes[$currencyId] ?? '0'; $incomes[$currencyId] = bcadd($incomes[$currencyId], app('steam')->positive($amount)); @@ -180,7 +179,7 @@ class BoxController extends Controller $set = $collector->getExtractedJournals(); /** @var array $journal */ foreach ($set as $journal) { - $currencyId = (int)$journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $expenses[$currencyId] = $expenses[$currencyId] ?? '0'; $expenses[$currencyId] = bcadd($expenses[$currencyId], $journal['amount'] ?? '0'); $sums[$currencyId] = $sums[$currencyId] ?? '0'; diff --git a/app/Http/Controllers/Json/ExchangeController.php b/app/Http/Controllers/Json/ExchangeController.php index 7266179755..41e85d2391 100644 --- a/app/Http/Controllers/Json/ExchangeController.php +++ b/app/Http/Controllers/Json/ExchangeController.php @@ -73,7 +73,7 @@ class ExchangeController extends Controller $return['amount'] = null; if (null !== $request->get('amount')) { // assume amount is in "from" currency: - $return['amount'] = bcmul($request->get('amount'), (string)$rate->rate, 12); + $return['amount'] = bcmul($request->get('amount'), (string) $rate->rate, 12); // round to toCurrency decimal places: $return['amount'] = round($return['amount'], $toCurrency->decimal_places); } diff --git a/app/Http/Controllers/Json/IntroController.php b/app/Http/Controllers/Json/IntroController.php index 1f28f3a82a..f0c92f55bd 100644 --- a/app/Http/Controllers/Json/IntroController.php +++ b/app/Http/Controllers/Json/IntroController.php @@ -115,7 +115,7 @@ class IntroController app('preferences')->set($key, false); app('preferences')->mark(); - return response()->json(['message' => (string)trans('firefly.intro_boxes_after_refresh')]); + return response()->json(['message' => (string) trans('firefly.intro_boxes_after_refresh')]); } /** diff --git a/app/Http/Controllers/Json/ReconcileController.php b/app/Http/Controllers/Json/ReconcileController.php index 4b9a4decb0..f4da7395fe 100644 --- a/app/Http/Controllers/Json/ReconcileController.php +++ b/app/Http/Controllers/Json/ReconcileController.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Json; - use Carbon\Carbon; use FireflyIII\Helpers\Collector\GroupCollectorInterface; use FireflyIII\Http\Controllers\Controller; @@ -56,6 +55,7 @@ class ReconcileController extends Controller /** * ReconcileController constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -66,7 +66,7 @@ class ReconcileController extends Controller $this->middleware( function ($request, $next) { app('view')->share('mainTitleIcon', 'fa-credit-card'); - app('view')->share('title', (string)trans('firefly.accounts')); + app('view')->share('title', (string) trans('firefly.accounts')); $this->repository = app(JournalRepositoryInterface::class); $this->accountRepos = app(AccountRepositoryInterface::class); $this->currencyRepos = app(CurrencyRepositoryInterface::class); @@ -81,8 +81,8 @@ class ReconcileController extends Controller * * @param Request $request * @param Account $account - * @param Carbon $start - * @param Carbon $end + * @param Carbon $start + * @param Carbon $end * * @return JsonResponse */ @@ -141,11 +141,22 @@ class ReconcileController extends Controller try { $view = view( - 'accounts.reconcile.overview', compact( - 'account', 'start', 'diffCompare', 'difference', 'end', 'clearedAmount', - 'startBalance', 'endBalance', 'amount', - 'route', 'countCleared', 'reconSum', 'selectedIds' - ) + 'accounts.reconcile.overview', + compact( + 'account', + 'start', + 'diffCompare', + 'difference', + 'end', + 'clearedAmount', + 'startBalance', + 'endBalance', + 'amount', + 'route', + 'countCleared', + 'reconSum', + 'selectedIds' + ) )->render(); // @codeCoverageIgnoreStart } catch (Throwable $e) { @@ -168,8 +179,8 @@ class ReconcileController extends Controller * Returns a list of transactions in a modal. * * @param Account $account - * @param Carbon $start - * @param Carbon $end + * @param Carbon $start + * @param Carbon $end * * @return mixed * @@ -231,8 +242,10 @@ class ReconcileController extends Controller } try { - $html = view('accounts.reconcile.transactions', - compact('account', 'journals', 'currency', 'start', 'end', 'selectionStart', 'selectionEnd'))->render(); + $html = view( + 'accounts.reconcile.transactions', + compact('account', 'journals', 'currency', 'start', 'end', 'selectionStart', 'selectionEnd') + )->render(); // @codeCoverageIgnoreStart } catch (Throwable $e) { Log::debug(sprintf('Could not render: %s', $e->getMessage())); @@ -245,10 +258,11 @@ class ReconcileController extends Controller } /** - * @param Account $account + * @param Account $account * @param TransactionCurrency $currency - * @param array $journal - * @param string $amount + * @param array $journal + * @param string $amount + * * @return string */ private function processJournal(Account $account, TransactionCurrency $currency, array $journal, string $amount): string diff --git a/app/Http/Controllers/Json/RecurrenceController.php b/app/Http/Controllers/Json/RecurrenceController.php index 6e68511e84..e8ffc0e795 100644 --- a/app/Http/Controllers/Json/RecurrenceController.php +++ b/app/Http/Controllers/Json/RecurrenceController.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Json; - use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; @@ -65,9 +64,9 @@ class RecurrenceController extends Controller * * @param Request $request * + * @throws FireflyException * @return JsonResponse * - * @throws FireflyException */ public function events(Request $request): JsonResponse { @@ -75,10 +74,10 @@ class RecurrenceController extends Controller $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'); + $endDate = '' !== (string) $request->get('end_date') ? Carbon::createFromFormat('Y-m-d', $request->get('end_date')) : null; + $endsAt = (string) $request->get('ends'); $repetitionType = explode(',', $request->get('type'))[0]; - $repetitions = (int)$request->get('reps'); + $repetitions = (int) $request->get('reps'); $repetitionMoment = ''; $start->startOfDay(); @@ -101,8 +100,8 @@ class RecurrenceController extends Controller $repetition = new RecurrenceRepetition; $repetition->repetition_type = $repetitionType; $repetition->repetition_moment = $repetitionMoment; - $repetition->repetition_skip = (int)$request->get('skip'); - $repetition->weekend = (int)$request->get('weekend'); + $repetition->repetition_skip = (int) $request->get('skip'); + $repetition->weekend = (int) $request->get('weekend'); $actualEnd = clone $end; $occurrences = []; switch ($endsAt) { @@ -150,30 +149,31 @@ class RecurrenceController extends Controller { $string = $request->get('date') ?? date('Y-m-d'); $today = Carbon::now()->startOfDay(); - $date = Carbon::createFromFormat('Y-m-d', $string)->startOfDay();; - $preSelected = (string)$request->get('pre_select'); + $date = Carbon::createFromFormat('Y-m-d', $string)->startOfDay(); + $preSelected = (string) $request->get('pre_select'); - 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))); + 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 = []; - if ($date > $today || 'true' === (string)$request->get('past')) { + $result = []; + if ($date > $today || 'true' === (string) $request->get('past')) { Log::debug('Will fill dropdown.'); $weekly = sprintf('weekly,%s', $date->dayOfWeekIso); $monthly = sprintf('monthly,%s', $date->day); - $dayOfWeek = (string)trans(sprintf('config.dow_%s', $date->dayOfWeekIso)); + $dayOfWeek = (string) trans(sprintf('config.dow_%s', $date->dayOfWeekIso)); $ndom = sprintf('ndom,%s,%s', $date->weekOfMonth, $date->dayOfWeekIso); $yearly = sprintf('yearly,%s', $date->format('Y-m-d')); - $yearlyDate = $date->formatLocalized((string)trans('config.month_and_day_no_year')); + $yearlyDate = $date->formatLocalized((string) trans('config.month_and_day_no_year')); $result = [ - 'daily' => ['label' => (string)trans('firefly.recurring_daily'), 'selected' => 0 === strpos($preSelected, 'daily')], - $weekly => ['label' => (string)trans('firefly.recurring_weekly', ['weekday' => $dayOfWeek]), + 'daily' => ['label' => (string) trans('firefly.recurring_daily'), 'selected' => 0 === strpos($preSelected, 'daily')], + $weekly => ['label' => (string) trans('firefly.recurring_weekly', ['weekday' => $dayOfWeek]), 'selected' => 0 === strpos($preSelected, 'weekly')], - $monthly => ['label' => (string)trans('firefly.recurring_monthly', ['dayOfMonth' => $date->day]), + $monthly => ['label' => (string) trans('firefly.recurring_monthly', ['dayOfMonth' => $date->day]), 'selected' => 0 === strpos($preSelected, 'monthly')], - $ndom => ['label' => (string)trans('firefly.recurring_ndom', ['weekday' => $dayOfWeek, 'dayOfMonth' => $date->weekOfMonth]), + $ndom => ['label' => (string) trans('firefly.recurring_ndom', ['weekday' => $dayOfWeek, 'dayOfMonth' => $date->weekOfMonth]), 'selected' => 0 === strpos($preSelected, 'ndom')], - $yearly => ['label' => (string)trans('firefly.recurring_yearly', ['date' => $yearlyDate]), 'selected' => 0 === strpos($preSelected, 'yearly')], + $yearly => ['label' => (string) trans('firefly.recurring_yearly', ['date' => $yearlyDate]), + 'selected' => 0 === strpos($preSelected, 'yearly')], ]; } Log::debug('Dropdown is', $result); @@ -181,5 +181,4 @@ class RecurrenceController extends Controller return response()->json($result); } - } diff --git a/app/Http/Controllers/Json/RuleController.php b/app/Http/Controllers/Json/RuleController.php index f69add2944..28fc13736d 100644 --- a/app/Http/Controllers/Json/RuleController.php +++ b/app/Http/Controllers/Json/RuleController.php @@ -44,11 +44,11 @@ class RuleController extends Controller */ public function action(Request $request): JsonResponse { - $count = (int)$request->get('count') > 0 ? (int)$request->get('count') : 1; + $count = (int) $request->get('count') > 0 ? (int) $request->get('count') : 1; $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', compact('actions', 'count'))->render(); @@ -72,12 +72,12 @@ class RuleController extends Controller */ public function trigger(Request $request): JsonResponse { - $count = (int)$request->get('count') > 0 ? (int)$request->get('count') : 1; + $count = (int) $request->get('count') > 0 ? (int) $request->get('count') : 1; $keys = array_keys(config('firefly.rule-triggers')); $triggers = []; foreach ($keys as $key) { if ('user_action' !== $key) { - $triggers[$key] = (string)trans('firefly.rule_trigger_' . $key . '_choice'); + $triggers[$key] = (string) trans('firefly.rule_trigger_' . $key . '_choice'); } } asort($triggers); diff --git a/app/Http/Controllers/NewUserController.php b/app/Http/Controllers/NewUserController.php index 186e28c4d8..6735072772 100644 --- a/app/Http/Controllers/NewUserController.php +++ b/app/Http/Controllers/NewUserController.php @@ -26,6 +26,8 @@ use FireflyIII\Http\Requests\NewUserFormRequest; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\Support\Http\Controllers\CreateStuff; +use Illuminate\Http\RedirectResponse; +use Illuminate\Routing\Redirector; use View; /** @@ -56,11 +58,11 @@ class NewUserController extends Controller /** * Form the user gets when he has no data in the system. * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|View + * @return RedirectResponse|Redirector|View */ public function index() { - app('view')->share('title', (string)trans('firefly.welcome')); + app('view')->share('title', (string) trans('firefly.welcome')); app('view')->share('mainTitleIcon', 'fa-fire'); $types = config('firefly.accountTypesByIdentifier.asset'); @@ -81,7 +83,7 @@ class NewUserController extends Controller * @param NewUserFormRequest $request * @param CurrencyRepositoryInterface $currencyRepository * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector */ public function submit(NewUserFormRequest $request, CurrencyRepositoryInterface $currencyRepository) { @@ -94,7 +96,7 @@ class NewUserController extends Controller // set language preference: app('preferences')->set('language', $language); // Store currency preference from input: - $currency = $currencyRepository->findNull((int)$request->input('amount_currency_id_bank_balance')); + $currency = $currencyRepository->findNull((int) $request->input('amount_currency_id_bank_balance')); // if is null, set to EUR: if (null === $currency) { @@ -115,7 +117,7 @@ class NewUserController extends Controller 'invoice_date' => false, 'internal_reference' => false, 'notes' => true, 'attachments' => true,]; app('preferences')->set('transaction_journal_optional_fields', $visibleFields); - session()->flash('success', (string)trans('firefly.stored_new_accounts_new_user')); + session()->flash('success', (string) trans('firefly.stored_new_accounts_new_user')); app('preferences')->mark(); return redirect(route('index')); diff --git a/app/Http/Controllers/PiggyBankController.php b/app/Http/Controllers/PiggyBankController.php index cc02d9b6b8..c2a14d6e04 100644 --- a/app/Http/Controllers/PiggyBankController.php +++ b/app/Http/Controllers/PiggyBankController.php @@ -30,11 +30,14 @@ use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface; use FireflyIII\Transformers\AccountTransformer; use FireflyIII\Transformers\PiggyBankTransformer; +use Illuminate\Contracts\View\Factory; use Illuminate\Http\JsonResponse; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Pagination\LengthAwarePaginator; +use Illuminate\Routing\Redirector; use Illuminate\Support\Collection; +use Illuminate\View\View; use Log; use Symfony\Component\HttpFoundation\ParameterBag; @@ -54,6 +57,7 @@ class PiggyBankController extends Controller /** * PiggyBankController constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -62,7 +66,7 @@ class PiggyBankController extends Controller $this->middleware( function ($request, $next) { - app('view')->share('title', (string)trans('firefly.piggyBanks')); + app('view')->share('title', (string) trans('firefly.piggyBanks')); app('view')->share('mainTitleIcon', 'fa-sort-amount-asc'); $this->piggyRepos = app(PiggyBankRepositoryInterface::class); @@ -79,7 +83,7 @@ class PiggyBankController extends Controller * * @param PiggyBank $piggyBank * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function add(PiggyBank $piggyBank) { @@ -99,7 +103,7 @@ class PiggyBankController extends Controller * * @param PiggyBank $piggyBank * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function addMobile(PiggyBank $piggyBank) { @@ -117,11 +121,11 @@ class PiggyBankController extends Controller /** * Create a piggy bank. * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function create() { - $subTitle = (string)trans('firefly.new_piggy_bank'); + $subTitle = (string) trans('firefly.new_piggy_bank'); $subTitleIcon = 'fa-plus'; // put previous url in session if not redirect from store (not "create another"). @@ -138,11 +142,11 @@ class PiggyBankController extends Controller * * @param PiggyBank $piggyBank * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function delete(PiggyBank $piggyBank) { - $subTitle = (string)trans('firefly.delete_piggy_bank', ['name' => $piggyBank->name]); + $subTitle = (string) trans('firefly.delete_piggy_bank', ['name' => $piggyBank->name]); // put previous url in session $this->rememberPreviousUri('piggy-banks.delete.uri'); @@ -159,7 +163,7 @@ class PiggyBankController extends Controller */ public function destroy(PiggyBank $piggyBank): RedirectResponse { - session()->flash('success', (string)trans('firefly.deleted_piggy_bank', ['name' => $piggyBank->name])); + session()->flash('success', (string) trans('firefly.deleted_piggy_bank', ['name' => $piggyBank->name])); app('preferences')->mark(); $this->piggyRepos->destroy($piggyBank); @@ -171,11 +175,11 @@ class PiggyBankController extends Controller * * @param PiggyBank $piggyBank * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function edit(PiggyBank $piggyBank) { - $subTitle = (string)trans('firefly.update_piggy_title', ['name' => $piggyBank->name]); + $subTitle = (string) trans('firefly.update_piggy_title', ['name' => $piggyBank->name]); $subTitleIcon = 'fa-pencil'; $targetDate = null; $startDate = null; @@ -211,15 +215,15 @@ class PiggyBankController extends Controller * * @param Request $request * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function index(Request $request) { $this->piggyRepos->correctOrder(); $collection = $this->piggyRepos->getPiggyBanks(); $total = $collection->count(); - $page = 0 === (int)$request->get('page') ? 1 : (int)$request->get('page'); - $pageSize = (int)app('preferences')->get('listPageSize', 50)->data; + $page = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page'); + $pageSize = (int) app('preferences')->get('listPageSize', 50)->data; $accounts = []; /** @var Carbon $end */ $end = session('end', Carbon::now()->endOfMonth()); @@ -240,7 +244,7 @@ class PiggyBankController extends Controller foreach ($collection as $piggy) { $array = $transformer->transform($piggy); $account = $accountTransformer->transform($piggy->account); - $accountId = (int)$account['id']; + $accountId = (int) $account['id']; if (!isset($accounts[$accountId])) { // create new: $accounts[$accountId] = $account; @@ -288,7 +292,7 @@ class PiggyBankController extends Controller $this->piggyRepos->addAmount($piggyBank, $amount); session()->flash( 'success', - (string)trans( + (string) trans( 'firefly.added_amount_to_piggy', ['amount' => app('amount')->formatAnything($currency, $amount, false), 'name' => $piggyBank->name] ) @@ -301,7 +305,7 @@ class PiggyBankController extends Controller Log::error('Cannot add ' . $amount . ' because canAddAmount returned false.'); session()->flash( 'error', - (string)trans( + (string) trans( 'firefly.cannot_add_amount_piggy', ['amount' => app('amount')->formatAnything($currency, $amount, false), 'name' => e($piggyBank->name)] ) @@ -330,7 +334,7 @@ class PiggyBankController extends Controller $this->piggyRepos->removeAmount($piggyBank, $amount); session()->flash( 'success', - (string)trans( + (string) trans( 'firefly.removed_amount_from_piggy', ['amount' => app('amount')->formatAnything($currency, $amount, false), 'name' => $piggyBank->name] ) @@ -340,11 +344,11 @@ class PiggyBankController extends Controller return redirect(route('piggy-banks.index')); } - $amount = (string)round($request->get('amount'), 12); + $amount = (string) round($request->get('amount'), 12); session()->flash( 'error', - (string)trans( + (string) trans( 'firefly.cannot_remove_from_piggy', ['amount' => app('amount')->formatAnything($currency, $amount, false), 'name' => e($piggyBank->name)] ) @@ -358,12 +362,12 @@ class PiggyBankController extends Controller * * @param PiggyBank $piggyBank * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function remove(PiggyBank $piggyBank) { $repetition = $this->piggyRepos->getRepetition($piggyBank); - $currency = $this->accountRepos->getAccountCurrency($piggyBank->account) ?? app('amount')->getDefaultCurrency(); + $currency = $this->accountRepos->getAccountCurrency($piggyBank->account) ?? app('amount')->getDefaultCurrency(); return view('piggy-banks.remove', compact('piggyBank', 'repetition', 'currency')); } @@ -373,12 +377,12 @@ class PiggyBankController extends Controller * * @param PiggyBank $piggyBank * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function removeMobile(PiggyBank $piggyBank) { $repetition = $this->piggyRepos->getRepetition($piggyBank); - $currency = $this->accountRepos->getAccountCurrency($piggyBank->account) ?? app('amount')->getDefaultCurrency(); + $currency = $this->accountRepos->getAccountCurrency($piggyBank->account) ?? app('amount')->getDefaultCurrency(); return view('piggy-banks.remove-mobile', compact('piggyBank', 'repetition', 'currency')); } @@ -393,7 +397,7 @@ class PiggyBankController extends Controller */ public function setOrder(Request $request, PiggyBank $piggyBank): JsonResponse { - $newOrder = (int)$request->get('order'); + $newOrder = (int) $request->get('order'); $this->piggyRepos->setOrder($piggyBank, $newOrder); return response()->json(['data' => 'OK']); @@ -404,7 +408,7 @@ class PiggyBankController extends Controller * * @param PiggyBank $piggyBank * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function show(PiggyBank $piggyBank) { @@ -429,7 +433,7 @@ class PiggyBankController extends Controller * * @param PiggyBankFormRequest $request * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector */ public function store(PiggyBankFormRequest $request) { @@ -439,12 +443,12 @@ class PiggyBankController extends Controller } $piggyBank = $this->piggyRepos->store($data); - session()->flash('success', (string)trans('firefly.stored_piggy_bank', ['name' => $piggyBank->name])); + session()->flash('success', (string) trans('firefly.stored_piggy_bank', ['name' => $piggyBank->name])); app('preferences')->mark(); $redirect = redirect($this->getPreviousUri('piggy-banks.create.uri')); - if (1 === (int)$request->get('create_another')) { + if (1 === (int) $request->get('create_another')) { // @codeCoverageIgnoreStart session()->put('piggy-banks.create.fromStore', true); @@ -461,19 +465,19 @@ class PiggyBankController extends Controller * @param PiggyBankFormRequest $request * @param PiggyBank $piggyBank * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector */ public function update(PiggyBankFormRequest $request, PiggyBank $piggyBank) { $data = $request->getPiggyBankData(); $piggyBank = $this->piggyRepos->update($piggyBank, $data); - session()->flash('success', (string)trans('firefly.updated_piggy_bank', ['name' => $piggyBank->name])); + session()->flash('success', (string) trans('firefly.updated_piggy_bank', ['name' => $piggyBank->name])); app('preferences')->mark(); $redirect = redirect($this->getPreviousUri('piggy-banks.edit.uri')); - if (1 === (int)$request->get('return_to_edit')) { + if (1 === (int) $request->get('return_to_edit')) { // @codeCoverageIgnoreStart session()->put('piggy-banks.edit.fromUpdate', true); diff --git a/app/Http/Controllers/PreferencesController.php b/app/Http/Controllers/PreferencesController.php index 9af0e535a7..bd5d8f9a58 100644 --- a/app/Http/Controllers/PreferencesController.php +++ b/app/Http/Controllers/PreferencesController.php @@ -26,7 +26,11 @@ use FireflyIII\Models\Account; use FireflyIII\Models\AccountType; use FireflyIII\Models\Preference; use FireflyIII\Repositories\Account\AccountRepositoryInterface; +use Illuminate\Contracts\View\Factory; +use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; +use Illuminate\Routing\Redirector; +use Illuminate\View\View; /** * Class PreferencesController. @@ -35,6 +39,7 @@ class PreferencesController extends Controller { /** * PreferencesController constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -43,7 +48,7 @@ class PreferencesController extends Controller $this->middleware( function ($request, $next) { - app('view')->share('title', (string)trans('firefly.preferences')); + app('view')->share('title', (string) trans('firefly.preferences')); app('view')->share('mainTitleIcon', 'fa-gear'); return $next($request); @@ -56,7 +61,7 @@ class PreferencesController extends Controller * * @param AccountRepositoryInterface $repository * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function index(AccountRepositoryInterface $repository) { @@ -70,13 +75,13 @@ class PreferencesController extends Controller $role = sprintf('opt_group_%s', $repository->getMetaValue($account, 'account_role')); if (in_array($type, [AccountType::MORTGAGE, AccountType::DEBT, AccountType::LOAN], true)) { - $role = sprintf('opt_group_l_%s',$type); + $role = sprintf('opt_group_l_%s', $type); } if ('' === $role || 'opt_group_' === $role) { $role = 'opt_group_defaultAsset'; } - $groupedAccounts[trans(sprintf('firefly.%s',$role))][$account->id] = $account->name; + $groupedAccounts[trans(sprintf('firefly.%s', $role))][$account->id] = $account->name; } ksort($groupedAccounts); @@ -86,12 +91,15 @@ class PreferencesController extends Controller $viewRange = $viewRangePref->data; $frontPageAccounts = app('preferences')->get('frontPageAccounts', $accountIds); $language = app('preferences')->get('language', config('firefly.default_language', 'en_US'))->data; + $languages = config('firefly.languages'); $listPageSize = app('preferences')->get('listPageSize', 50)->data; $customFiscalYear = app('preferences')->get('customFiscalYear', 0)->data; $fiscalYearStartStr = app('preferences')->get('fiscalYearStart', '01-01')->data; $fiscalYearStart = date('Y') . '-' . $fiscalYearStartStr; $tjOptionalFields = app('preferences')->get('transaction_journal_optional_fields', [])->data; + ksort($languages); + // an important fallback is that the frontPageAccount array gets refilled automatically // when it turns up empty. if (0 === count($frontPageAccounts->data)) { @@ -104,6 +112,7 @@ class PreferencesController extends Controller 'language', 'groupedAccounts', 'frontPageAccounts', + 'languages', 'tjOptionalFields', 'viewRange', 'customFiscalYear', @@ -118,7 +127,7 @@ class PreferencesController extends Controller * * @param Request $request * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector * */ public function postIndex(Request $request) @@ -127,7 +136,7 @@ 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; } app('preferences')->set('frontPageAccounts', $frontPageAccounts); } @@ -140,14 +149,14 @@ class PreferencesController extends Controller session()->forget('range'); // custom fiscal year - $customFiscalYear = 1 === (int)$request->get('customFiscalYear'); - $fiscalYearStart = date('m-d', strtotime((string)$request->get('fiscalYearStart'))); + $customFiscalYear = 1 === (int) $request->get('customFiscalYear'); + $fiscalYearStart = date('m-d', strtotime((string) $request->get('fiscalYearStart'))); app('preferences')->set('customFiscalYear', $customFiscalYear); app('preferences')->set('fiscalYearStart', $fiscalYearStart); // save page size: app('preferences')->set('listPageSize', 50); - $listPageSize = (int)$request->get('listPageSize'); + $listPageSize = (int) $request->get('listPageSize'); if ($listPageSize > 0 && $listPageSize < 1337) { app('preferences')->set('listPageSize', $listPageSize); } @@ -178,7 +187,7 @@ class PreferencesController extends Controller ]; app('preferences')->set('transaction_journal_optional_fields', $optionalTj); - session()->flash('success', (string)trans('firefly.saved_preferences')); + session()->flash('success', (string) trans('firefly.saved_preferences')); app('preferences')->mark(); return redirect(route('preferences.index')); diff --git a/app/Http/Controllers/Profile/DataController.php b/app/Http/Controllers/Profile/DataController.php index 35250c2080..12121b4251 100644 --- a/app/Http/Controllers/Profile/DataController.php +++ b/app/Http/Controllers/Profile/DataController.php @@ -21,7 +21,6 @@ namespace FireflyIII\Http\Controllers\Profile; - use FireflyIII\Http\Controllers\Controller; use FireflyIII\Repositories\Budget\AvailableBudgetRepositoryInterface; use FireflyIII\Repositories\Budget\BudgetLimitRepositoryInterface; @@ -86,4 +85,4 @@ class DataController extends Controller return redirect(route('profile.index')); } -} \ No newline at end of file +} diff --git a/app/Http/Controllers/ProfileController.php b/app/Http/Controllers/ProfileController.php index f95586cb6c..ac640b2115 100644 --- a/app/Http/Controllers/ProfileController.php +++ b/app/Http/Controllers/ProfileController.php @@ -41,8 +41,12 @@ use FireflyIII\User; use Google2FA; use Hash; use Illuminate\Contracts\Auth\Guard; +use Illuminate\Contracts\View\Factory; +use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; +use Illuminate\Routing\Redirector; use Illuminate\Support\Collection; +use Illuminate\View\View; use Laravel\Passport\ClientRepository; use Log; use PragmaRX\Recovery\Recovery; @@ -59,6 +63,7 @@ class ProfileController extends Controller /** * ProfileController constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -67,7 +72,7 @@ class ProfileController extends Controller $this->middleware( static function ($request, $next) { - app('view')->share('title', (string)trans('firefly.profile')); + app('view')->share('title', (string) trans('firefly.profile')); app('view')->share('mainTitleIcon', 'fa-user'); return $next($request); @@ -83,7 +88,7 @@ class ProfileController extends Controller * * @param Request $request * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function changeEmail(Request $request) { @@ -98,7 +103,7 @@ class ProfileController extends Controller $title = auth()->user()->email; $email = auth()->user()->email; - $subTitle = (string)trans('firefly.change_your_email'); + $subTitle = (string) trans('firefly.change_your_email'); $subTitleIcon = 'fa-envelope'; return view('profile.change-email', compact('title', 'subTitle', 'subTitleIcon', 'email')); @@ -109,7 +114,7 @@ class ProfileController extends Controller * * @param Request $request * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function changePassword(Request $request) { @@ -123,7 +128,7 @@ class ProfileController extends Controller } $title = auth()->user()->email; - $subTitle = (string)trans('firefly.change_your_password'); + $subTitle = (string) trans('firefly.change_your_password'); $subTitleIcon = 'fa-key'; return view('profile.change-password', compact('title', 'subTitle', 'subTitleIcon')); @@ -132,7 +137,7 @@ class ProfileController extends Controller /** * View that generates a 2FA code for the user. * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function code() { @@ -172,7 +177,7 @@ class ProfileController extends Controller $image = Google2FA::getQRCodeInline($domain, auth()->user()->email, $secret); - return view('profile.code', compact('image', 'secret','codes')); + return view('profile.code', compact('image', 'secret', 'codes')); } /** @@ -181,9 +186,9 @@ class ProfileController extends Controller * @param UserRepositoryInterface $repository * @param string $token * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector - * * @throws FireflyException + * @return RedirectResponse|Redirector + * */ public function confirmEmailChange(UserRepositoryInterface $repository, string $token) { @@ -214,7 +219,7 @@ class ProfileController extends Controller $repository->unblockUser($user); // return to login. - session()->flash('success', (string)trans('firefly.login_with_new_email')); + session()->flash('success', (string) trans('firefly.login_with_new_email')); return redirect(route('login')); } @@ -224,7 +229,7 @@ class ProfileController extends Controller * * @param Request $request * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function deleteAccount(Request $request) { @@ -235,7 +240,7 @@ class ProfileController extends Controller // @codeCoverageIgnoreEnd } $title = auth()->user()->email; - $subTitle = (string)trans('firefly.delete_account'); + $subTitle = (string) trans('firefly.delete_account'); $subTitleIcon = 'fa-trash'; return view('profile.delete-account', compact('title', 'subTitle', 'subTitleIcon')); @@ -244,7 +249,7 @@ class ProfileController extends Controller /** * Delete 2FA routine. * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector */ public function deleteCode() { @@ -255,8 +260,8 @@ class ProfileController extends Controller $user = auth()->user(); $repository->setMFACode($user, null); - 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')); return redirect(route('profile.index')); } @@ -264,7 +269,7 @@ class ProfileController extends Controller /** * Enable 2FA screen. * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector */ public function enable2FA() { @@ -279,7 +284,7 @@ class ProfileController 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. - session()->flash('info', (string)trans('firefly.2fa_already_enabled')); + session()->flash('info', (string) trans('firefly.2fa_already_enabled')); return redirect(route('profile.index')); } @@ -287,7 +292,7 @@ class ProfileController extends Controller /** * Index for profile. * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function index() { @@ -320,7 +325,7 @@ class ProfileController extends Controller } /** - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function newBackupCodes() { @@ -335,6 +340,7 @@ class ProfileController extends Controller app('preferences')->set('mfa_recovery', $recoveryCodes); app('preferences')->mark(); + return view('profile.new-backup-codes', compact('codes')); } @@ -344,7 +350,7 @@ class ProfileController extends Controller * @param EmailFormRequest $request * @param UserRepositoryInterface $repository * - * @return $this|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return $this|RedirectResponse|Redirector */ public function postChangeEmail(EmailFormRequest $request, UserRepositoryInterface $repository) { @@ -362,7 +368,7 @@ class ProfileController extends Controller $newEmail = $request->string('email'); $oldEmail = $user->email; if ($newEmail === $user->email) { - session()->flash('error', (string)trans('firefly.email_not_changed')); + session()->flash('error', (string) trans('firefly.email_not_changed')); return redirect(route('profile.change-email'))->withInput(); } @@ -372,7 +378,7 @@ class ProfileController extends Controller Auth::guard()->logout(); $request->session()->invalidate(); - session()->flash('success', (string)trans('firefly.email_changed')); + session()->flash('success', (string) trans('firefly.email_changed')); return redirect(route('index')); } @@ -387,7 +393,7 @@ class ProfileController extends Controller // force user logout. Auth::guard()->logout(); $request->session()->invalidate(); - session()->flash('success', (string)trans('firefly.email_changed')); + session()->flash('success', (string) trans('firefly.email_changed')); return redirect(route('index')); } @@ -398,7 +404,7 @@ class ProfileController extends Controller * @param ProfileFormRequest $request * @param UserRepositoryInterface $repository * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector */ public function postChangePassword(ProfileFormRequest $request, UserRepositoryInterface $repository) { @@ -425,7 +431,7 @@ class ProfileController extends Controller } $repository->changePassword($user, $request->get('new_password')); - session()->flash('success', (string)trans('firefly.password_changed')); + session()->flash('success', (string) trans('firefly.password_changed')); return redirect(route('profile.index')); } @@ -436,7 +442,7 @@ class ProfileController extends Controller * * @param TokenFormRequest $request * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector */ public function postCode(TokenFormRequest $request) { @@ -448,7 +454,7 @@ class ProfileController extends Controller $secret = session()->get('two-factor-secret'); $repository->setMFACode($user, $secret); - session()->flash('success', (string)trans('firefly.saved_preferences')); + session()->flash('success', (string) trans('firefly.saved_preferences')); app('preferences')->mark(); // also save the code so replay attack is prevented. @@ -475,12 +481,12 @@ class ProfileController extends Controller * @param UserRepositoryInterface $repository * @param DeleteAccountFormRequest $request * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector */ public function postDeleteAccount(UserRepositoryInterface $repository, DeleteAccountFormRequest $request) { if (!Hash::check($request->get('password'), auth()->user()->password)) { - session()->flash('error', (string)trans('firefly.invalid_password')); + session()->flash('error', (string) trans('firefly.invalid_password')); return redirect(route('profile.delete-account')); } @@ -498,7 +504,7 @@ class ProfileController extends Controller /** * Regenerate access token. * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector */ public function regenerate() { @@ -506,7 +512,7 @@ class ProfileController extends Controller $user = auth()->user(); $token = $user->generateAccessToken(); app('preferences')->set('access_token', $token); - session()->flash('success', (string)trans('firefly.token_regenerated')); + session()->flash('success', (string) trans('firefly.token_regenerated')); return redirect(route('profile.index')); } @@ -518,9 +524,9 @@ class ProfileController extends Controller * @param string $token * @param string $hash * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector - * * @throws FireflyException + * @return RedirectResponse|Redirector + * */ public function undoEmailChange(UserRepositoryInterface $repository, string $token, string $hash) { @@ -564,7 +570,7 @@ class ProfileController extends Controller $repository->unblockUser($user); // return to login. - session()->flash('success', (string)trans('firefly.login_with_old_email')); + session()->flash('success', (string) trans('firefly.login_with_old_email')); return redirect(route('login')); } diff --git a/app/Http/Controllers/Recurring/CreateController.php b/app/Http/Controllers/Recurring/CreateController.php index 2db99b6225..f2c45d1ac3 100644 --- a/app/Http/Controllers/Recurring/CreateController.php +++ b/app/Http/Controllers/Recurring/CreateController.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Recurring; - use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; @@ -31,7 +30,11 @@ use FireflyIII\Http\Requests\RecurrenceFormRequest; use FireflyIII\Models\RecurrenceRepetition; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Repositories\Recurring\RecurringRepositoryInterface; +use Illuminate\Contracts\View\Factory; +use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; +use Illuminate\Routing\Redirector; +use Illuminate\View\View; /** * @@ -46,6 +49,7 @@ class CreateController extends Controller /** * CreateController constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -56,8 +60,8 @@ class CreateController extends Controller $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')); + app('view')->share('title', (string) trans('firefly.recurrences')); + app('view')->share('subTitle', (string) trans('firefly.create_new_recurrence')); $this->recurring = app(RecurringRepositoryInterface::class); $this->budgets = app(BudgetRepositoryInterface::class); @@ -72,7 +76,7 @@ class CreateController extends Controller * * @param Request $request * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function create(Request $request) { @@ -88,15 +92,15 @@ class CreateController extends Controller } $request->session()->forget('recurring.create.fromStore'); $repetitionEnds = [ - 'forever' => (string)trans('firefly.repeat_forever'), - 'until_date' => (string)trans('firefly.repeat_until_date'), - 'times' => (string)trans('firefly.repeat_times'), + 'forever' => (string) trans('firefly.repeat_forever'), + 'until_date' => (string) trans('firefly.repeat_until_date'), + 'times' => (string) trans('firefly.repeat_times'), ]; $weekendResponses = [ - RecurrenceRepetition::WEEKEND_DO_NOTHING => (string)trans('firefly.do_nothing'), - RecurrenceRepetition::WEEKEND_SKIP_CREATION => (string)trans('firefly.skip_transaction'), - RecurrenceRepetition::WEEKEND_TO_FRIDAY => (string)trans('firefly.jump_to_friday'), - RecurrenceRepetition::WEEKEND_TO_MONDAY => (string)trans('firefly.jump_to_monday'), + RecurrenceRepetition::WEEKEND_DO_NOTHING => (string) trans('firefly.do_nothing'), + RecurrenceRepetition::WEEKEND_SKIP_CREATION => (string) trans('firefly.skip_transaction'), + RecurrenceRepetition::WEEKEND_TO_FRIDAY => (string) trans('firefly.jump_to_friday'), + RecurrenceRepetition::WEEKEND_TO_MONDAY => (string) trans('firefly.jump_to_monday'), ]; @@ -104,13 +108,14 @@ class CreateController extends Controller $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, + 'active' => $hasOldInput ? (bool) $request->old('active') : true, + 'apply_rules' => $hasOldInput ? (bool) $request->old('apply_rules') : true, ]; $request->session()->flash('preFilled', $preFilled); return view( - 'recurring.create', compact('tomorrow', 'oldRepetitionType', 'weekendResponses', 'preFilled', 'repetitionEnds', 'defaultCurrency', 'budgets') + 'recurring.create', + compact('tomorrow', 'oldRepetitionType', 'weekendResponses', 'preFilled', 'repetitionEnds', 'defaultCurrency', 'budgets') ); } @@ -120,7 +125,7 @@ class CreateController extends Controller * * @param RecurrenceFormRequest $request * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector */ public function store(RecurrenceFormRequest $request) { @@ -129,13 +134,14 @@ class CreateController extends Controller $recurrence = $this->recurring->store($data); } catch (FireflyException $e) { session()->flash('error', $e->getMessage()); + return redirect(route('recurring.create'))->withInput(); } - $request->session()->flash('success', (string)trans('firefly.stored_new_recurrence', ['title' => $recurrence->title])); + $request->session()->flash('success', (string) trans('firefly.stored_new_recurrence', ['title' => $recurrence->title])); app('preferences')->mark(); $redirect = redirect($this->getPreviousUri('recurring.create.uri')); - if (1 === (int)$request->get('create_another')) { + if (1 === (int) $request->get('create_another')) { // set value so create routine will not overwrite URL: $request->session()->put('recurring.create.fromStore', true); @@ -144,7 +150,5 @@ class CreateController extends Controller // redirect to previous URL. return $redirect; - } - } diff --git a/app/Http/Controllers/Recurring/DeleteController.php b/app/Http/Controllers/Recurring/DeleteController.php index e0c7e1e50f..1fa3304f5e 100644 --- a/app/Http/Controllers/Recurring/DeleteController.php +++ b/app/Http/Controllers/Recurring/DeleteController.php @@ -27,7 +27,11 @@ namespace FireflyIII\Http\Controllers\Recurring; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\Recurrence; use FireflyIII\Repositories\Recurring\RecurringRepositoryInterface; +use Illuminate\Contracts\View\Factory; +use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; +use Illuminate\Routing\Redirector; +use Illuminate\View\View; /** * Class DeleteController @@ -39,6 +43,7 @@ class DeleteController extends Controller /** * DeleteController constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -49,7 +54,7 @@ class DeleteController extends Controller $this->middleware( function ($request, $next) { app('view')->share('mainTitleIcon', 'fa-paint-brush'); - app('view')->share('title', (string)trans('firefly.recurrences')); + app('view')->share('title', (string) trans('firefly.recurrences')); $this->recurring = app(RecurringRepositoryInterface::class); @@ -63,11 +68,11 @@ class DeleteController extends Controller * * @param Recurrence $recurrence * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function delete(Recurrence $recurrence) { - $subTitle = (string)trans('firefly.delete_recurring', ['title' => $recurrence->title]); + $subTitle = (string) trans('firefly.delete_recurring', ['title' => $recurrence->title]); // put previous url in session $this->rememberPreviousUri('recurrences.delete.uri'); @@ -80,15 +85,15 @@ class DeleteController extends Controller * Destroy the recurring transaction. * * @param RecurringRepositoryInterface $repository - * @param Request $request - * @param Recurrence $recurrence + * @param Request $request + * @param Recurrence $recurrence * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector */ public function destroy(RecurringRepositoryInterface $repository, Request $request, Recurrence $recurrence) { $repository->destroy($recurrence); - $request->session()->flash('success', (string)trans('firefly.' . 'recurrence_deleted', ['title' => $recurrence->title])); + $request->session()->flash('success', (string) trans('firefly.' . 'recurrence_deleted', ['title' => $recurrence->title])); app('preferences')->mark(); return redirect($this->getPreviousUri('recurrences.delete.uri')); diff --git a/app/Http/Controllers/Recurring/EditController.php b/app/Http/Controllers/Recurring/EditController.php index 807eded1bc..fad9ef560c 100644 --- a/app/Http/Controllers/Recurring/EditController.php +++ b/app/Http/Controllers/Recurring/EditController.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Recurring; +use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Requests\RecurrenceFormRequest; use FireflyIII\Models\Recurrence; @@ -31,7 +32,11 @@ use FireflyIII\Models\RecurrenceRepetition; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Repositories\Recurring\RecurringRepositoryInterface; use FireflyIII\Transformers\RecurrenceTransformer; +use Illuminate\Contracts\View\Factory; +use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; +use Illuminate\Routing\Redirector; +use Illuminate\View\View; use Symfony\Component\HttpFoundation\ParameterBag; /** @@ -47,6 +52,7 @@ class EditController extends Controller /** * EditController constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -57,8 +63,8 @@ class EditController extends Controller $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')); + app('view')->share('title', (string) trans('firefly.recurrences')); + app('view')->share('subTitle', (string) trans('firefly.recurrences')); $this->recurring = app(RecurringRepositoryInterface::class); $this->budgets = app(BudgetRepositoryInterface::class); @@ -71,12 +77,12 @@ class EditController extends Controller /** * Edit a recurring transaction. * - * @param Request $request + * @param Request $request * @param Recurrence $recurrence * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View - * @throws \FireflyIII\Exceptions\FireflyException + * @throws FireflyException * + * @return Factory|View */ public function edit(Request $request, Recurrence $recurrence) { @@ -100,11 +106,11 @@ class EditController extends Controller } $request->session()->forget('recurrences.edit.fromUpdate'); - $repetitionEnd = 'forever'; + $repetitionEnd = 'forever'; $repetitionEnds = [ - 'forever' => (string)trans('firefly.repeat_forever'), - 'until_date' => (string)trans('firefly.repeat_until_date'), - 'times' => (string)trans('firefly.repeat_times'), + 'forever' => (string) trans('firefly.repeat_forever'), + 'until_date' => (string) trans('firefly.repeat_until_date'), + 'times' => (string) trans('firefly.repeat_times'), ]; if (null !== $recurrence->repeat_until) { $repetitionEnd = 'until_date'; // @codeCoverageIgnore @@ -114,17 +120,17 @@ class EditController extends Controller } $weekendResponses = [ - RecurrenceRepetition::WEEKEND_DO_NOTHING => (string)trans('firefly.do_nothing'), - RecurrenceRepetition::WEEKEND_SKIP_CREATION => (string)trans('firefly.skip_transaction'), - RecurrenceRepetition::WEEKEND_TO_FRIDAY => (string)trans('firefly.jump_to_friday'), - RecurrenceRepetition::WEEKEND_TO_MONDAY => (string)trans('firefly.jump_to_monday'), + RecurrenceRepetition::WEEKEND_DO_NOTHING => (string) trans('firefly.do_nothing'), + RecurrenceRepetition::WEEKEND_SKIP_CREATION => (string) trans('firefly.skip_transaction'), + RecurrenceRepetition::WEEKEND_TO_FRIDAY => (string) trans('firefly.jump_to_friday'), + RecurrenceRepetition::WEEKEND_TO_MONDAY => (string) trans('firefly.jump_to_monday'), ]; $hasOldInput = null !== $request->old('_token'); - $preFilled = [ + $preFilled = [ 'transaction_type' => strtolower($recurrence->transactionType->type), - 'active' => $hasOldInput ? (bool)$request->old('active') : $recurrence->active, - 'apply_rules' => $hasOldInput ? (bool)$request->old('apply_rules') : $recurrence->apply_rules, + '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'], ]; @@ -141,10 +147,10 @@ class EditController extends Controller * Update the recurring transaction. * * @param RecurrenceFormRequest $request - * @param Recurrence $recurrence + * @param Recurrence $recurrence * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector - * @throws \FireflyIII\Exceptions\FireflyException + * @throws FireflyException + * @return RedirectResponse|Redirector */ public function update(RecurrenceFormRequest $request, Recurrence $recurrence) { @@ -152,10 +158,10 @@ class EditController extends Controller $this->recurring->update($recurrence, $data); - $request->session()->flash('success', (string)trans('firefly.updated_recurrence', ['title' => $recurrence->title])); + $request->session()->flash('success', (string) trans('firefly.updated_recurrence', ['title' => $recurrence->title])); app('preferences')->mark(); $redirect = redirect($this->getPreviousUri('recurrences.edit.uri')); - if (1 === (int)$request->get('return_to_edit')) { + 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 5f21c4c812..8311f20d94 100644 --- a/app/Http/Controllers/Recurring/IndexController.php +++ b/app/Http/Controllers/Recurring/IndexController.php @@ -25,14 +25,17 @@ namespace FireflyIII\Http\Controllers\Recurring; use Carbon\Carbon; +use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\Recurrence; use FireflyIII\Repositories\Recurring\RecurringRepositoryInterface; use FireflyIII\Support\Http\Controllers\GetConfigurationData; use FireflyIII\Transformers\RecurrenceTransformer; +use Illuminate\Contracts\View\Factory; use Illuminate\Http\Request; use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Support\Collection; +use Illuminate\View\View; use Symfony\Component\HttpFoundation\ParameterBag; /** @@ -58,7 +61,7 @@ class IndexController extends Controller $this->middleware( function ($request, $next) { app('view')->share('mainTitleIcon', 'fa-paint-brush'); - app('view')->share('title', (string)trans('firefly.recurrences')); + app('view')->share('title', (string) trans('firefly.recurrences')); $this->recurring = app(RecurringRepositoryInterface::class); @@ -73,14 +76,14 @@ class IndexController extends Controller * * @param Request $request * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View - * @throws \FireflyIII\Exceptions\FireflyException + * @throws FireflyException * + * @return Factory|View */ public function index(Request $request) { - $page = 0 === (int)$request->get('page') ? 1 : (int)$request->get('page'); - $pageSize = (int)app('preferences')->get('listPageSize', 50)->data; + $page = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page'); + $pageSize = (int) app('preferences')->get('listPageSize', 50)->data; $collection = $this->recurring->get(); // split collection @@ -95,19 +98,19 @@ class IndexController extends Controller $recurring = []; /** @var Recurrence $recurrence */ foreach ($recurrences as $recurrence) { - $today = new Carbon; - $year = new Carbon; + $today = new Carbon; + $year = new Carbon; $year->addYear(); - if($recurrence->first_date > $today) { - $today =clone $recurrence->first_date; - $year = clone $today; + if ($recurrence->first_date > $today) { + $today = clone $recurrence->first_date; + $year = clone $today; $year->addYear(); } $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['occurrences'] = array_slice($this->recurring->getOccurrencesInRange($recurrence->recurrenceRepetitions->first(), $today, $year),0,1); + $array['occurrences'] = array_slice($this->recurring->getOccurrencesInRange($recurrence->recurrenceRepetitions->first(), $today, $year), 0, 1); $recurring[] = $array; } $paginator = new LengthAwarePaginator($recurring, $total, $pageSize, $page); diff --git a/app/Http/Controllers/Recurring/ShowController.php b/app/Http/Controllers/Recurring/ShowController.php index b4da5e4436..23ddd02444 100644 --- a/app/Http/Controllers/Recurring/ShowController.php +++ b/app/Http/Controllers/Recurring/ShowController.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Recurring; - use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; @@ -31,6 +30,8 @@ use FireflyIII\Models\Recurrence; use FireflyIII\Repositories\Recurring\RecurringRepositoryInterface; use FireflyIII\Support\Http\Controllers\GetConfigurationData; use FireflyIII\Transformers\RecurrenceTransformer; +use Illuminate\Contracts\View\Factory; +use Illuminate\View\View; use Symfony\Component\HttpFoundation\ParameterBag; /** @@ -45,6 +46,7 @@ class ShowController extends Controller /** * IndexController constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -56,7 +58,7 @@ class ShowController extends Controller $this->middleware( function ($request, $next) { app('view')->share('mainTitleIcon', 'fa-paint-brush'); - app('view')->share('title', (string)trans('firefly.recurrences')); + app('view')->share('title', (string) trans('firefly.recurrences')); $this->recurring = app(RecurringRepositoryInterface::class); @@ -71,8 +73,8 @@ class ShowController extends Controller * * @param Recurrence $recurrence * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @throws FireflyException + * @return Factory|View */ public function show(Recurrence $recurrence) { @@ -90,8 +92,8 @@ 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', compact('recurrence', 'subTitle', 'array', 'groups')); } -} \ No newline at end of file +} diff --git a/app/Http/Controllers/Report/BudgetController.php b/app/Http/Controllers/Report/BudgetController.php index 7ed503d63a..76f0c283fe 100644 --- a/app/Http/Controllers/Report/BudgetController.php +++ b/app/Http/Controllers/Report/BudgetController.php @@ -118,7 +118,8 @@ class BudgetController extends Controller = $report[$sourceAccountId]['currencies'][$currencyId]['budgets'][$budget['id']] ?? '0'; $report[$sourceAccountId]['currencies'][$currencyId]['budgets'][$budget['id']] = bcadd( - $report[$sourceAccountId]['currencies'][$currencyId]['budgets'][$budget['id']], $journal['amount'] + $report[$sourceAccountId]['currencies'][$currencyId]['budgets'][$budget['id']], + $journal['amount'] ); } } @@ -172,7 +173,8 @@ class BudgetController extends Controller 'sum' => '0', ]; $report[$sourceAccountId]['currencies'][$currencyId]['sum'] = bcadd( - $report[$sourceAccountId]['currencies'][$currencyId]['sum'], $journal['amount'] + $report[$sourceAccountId]['currencies'][$currencyId]['sum'], + $journal['amount'] ); $sums[$currencyId]['sum'] = bcadd($sums[$currencyId]['sum'], $journal['amount']); } @@ -214,8 +216,8 @@ class BudgetController extends Controller ]; $result[$key]['transactions']++; $result[$key]['sum'] = bcadd($journal['amount'], $result[$key]['sum']); - $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string)$result[$key]['transactions']); - $result[$key]['avg_float'] = (float)$result[$key]['avg']; + $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); + $result[$key]['avg_float'] = (float) $result[$key]['avg']; } } } @@ -295,11 +297,11 @@ class BudgetController extends Controller $pct = '0'; if (0 !== bccomp($sum, '0') && 0 !== bccomp($total, '9')) { $pct = round(bcmul(bcdiv($sum, $total), '100')); - } $report[$budgetId]['currencies'][$currencyId]['sum_pct'] = $pct; } } + return view('reports.budget.partials.budgets', compact('sums', 'report')); } @@ -323,7 +325,7 @@ class BudgetController extends Controller $defaultCurrency = app('amount')->getDefaultCurrency(); /** @var Budget $budget */ foreach ($budgets as $budget) { - $budgetId = (int)$budget->id; + $budgetId = (int) $budget->id; $report['budgets'][$budgetId] = $report['budgets'][$budgetId] ?? [ 'budget_id' => $budgetId, 'budget_name' => $budget->name, @@ -335,9 +337,9 @@ class BudgetController extends Controller $limits = $this->blRepository->getBudgetLimits($budget, $start, $end); /** @var BudgetLimit $limit */ foreach ($limits as $limit) { - $limitId = (int)$limit->id; + $limitId = (int) $limit->id; $currency = $limit->transactionCurrency ?? $defaultCurrency; - $currencyId = (int)$currency->id; + $currencyId = (int) $currency->id; $expenses = $this->opsRepository->sumExpenses($limit->start_date, $limit->end_date, $accounts, new Collection([$budget])); $spent = $expenses[$currencyId]['sum'] ?? '0'; $left = -1 === bccomp(bcadd($limit->amount, $spent), '0') ? '0' : bcadd($limit->amount, $spent); @@ -390,6 +392,14 @@ class BudgetController extends Controller ]; $noBudget = $this->nbRepository->sumExpenses($start, $end); foreach ($noBudget as $noBudgetEntry) { + + // currency information: + $nbCurrencyId = (int) ($noBudgetEntry['currency_id'] ?? $defaultCurrency->id); + $nbCurrencyCode = $noBudgetEntry['currency_code'] ?? $defaultCurrency->code; + $nbCurrencyName = $noBudgetEntry['currency_name'] ?? $defaultCurrency->name; + $nbCurrencySymbol = $noBudgetEntry['currency_symbol'] ?? $defaultCurrency->symbol; + $nbCurrencyDp = $noBudgetEntry['currency_decimal_places'] ?? $defaultCurrency->decimal_places; + $report['budgets'][0]['budget_limits'][] = [ 'budget_limit_id' => null, 'start_date' => $start, @@ -400,33 +410,31 @@ class BudgetController extends Controller 'spent_pct' => '0', 'left' => '0', 'overspent' => '0', - 'currency_id' => (int)($noBudgetEntry['currency_id'] ?? $defaultCurrency->id), - 'currency_code' => $noBudgetEntry['currency_code'] ?? $defaultCurrency->code, - 'currency_name' => $noBudgetEntry['currency_name'] ?? $defaultCurrency->name, - 'currency_symbol' => $noBudgetEntry['currency_symbol'] ?? $defaultCurrency->symbol, - 'currency_decimal_places' => $noBudgetEntry['currency_decimal_places'] ?? $defaultCurrency->decimal_places, + 'currency_id' => $nbCurrencyId, + 'currency_code' => $nbCurrencyCode, + 'currency_name' => $nbCurrencyName, + 'currency_symbol' => $nbCurrencySymbol, + 'currency_decimal_places' => $nbCurrencyDp, ]; - $report['sums'][$noBudgetEntry['currency_id']]['spent'] - = bcadd($report['sums'][$noBudgetEntry['currency_id']]['spent'] ?? '0', $noBudgetEntry['sum']); + $report['sums'][$nbCurrencyId]['spent'] = bcadd($report['sums'][$nbCurrencyId]['spent'] ?? '0', $noBudgetEntry['sum']); // append currency info because it may be missing: - $report['sums'][$noBudgetEntry['currency_id']]['currency_id'] = (int)($noBudgetEntry['currency_id'] ?? $defaultCurrency->id); - $report['sums'][$noBudgetEntry['currency_id']]['currency_code'] = $noBudgetEntry['currency_code'] ?? $defaultCurrency->code; - $report['sums'][$noBudgetEntry['currency_id']]['currency_name'] = $noBudgetEntry['currency_name'] ?? $defaultCurrency->name; - $report['sums'][$noBudgetEntry['currency_id']]['currency_symbol'] = $noBudgetEntry['currency_symbol'] ?? $defaultCurrency->symbol; - $report['sums'][$noBudgetEntry['currency_id']]['currency_decimal_places'] = $noBudgetEntry['currency_decimal_places'] ?? $defaultCurrency->decimal_places; + $report['sums'][$nbCurrencyId]['currency_id'] = $nbCurrencyId; + $report['sums'][$nbCurrencyId]['currency_code'] = $nbCurrencyCode; + $report['sums'][$nbCurrencyId]['currency_name'] = $nbCurrencyName; + $report['sums'][$nbCurrencyId]['currency_symbol'] = $nbCurrencySymbol; + $report['sums'][$nbCurrencyId]['currency_decimal_places'] = $nbCurrencyDp; // append other sums because they might be missing: - $report['sums'][$noBudgetEntry['currency_id']]['overspent'] = $report['sums'][$noBudgetEntry['currency_id']]['overspent'] ?? '0'; - $report['sums'][$noBudgetEntry['currency_id']]['left'] = $report['sums'][$noBudgetEntry['currency_id']]['left'] ?? '0'; - $report['sums'][$noBudgetEntry['currency_id']]['budgeted'] = $report['sums'][$noBudgetEntry['currency_id']]['budgeted'] ?? '0'; - + $report['sums'][$nbCurrencyId]['overspent'] = $report['sums'][$nbCurrencyId]['overspent'] ?? '0'; + $report['sums'][$nbCurrencyId]['left'] = $report['sums'][$nbCurrencyId]['left'] ?? '0'; + $report['sums'][$nbCurrencyId]['budgeted'] = $report['sums'][$nbCurrencyId]['budgeted'] ?? '0'; } // make percentages based on total amount. foreach ($report['budgets'] as $budgetId => $data) { foreach ($data['budget_limits'] as $limitId => $entry) { - $budgetId = (int)$budgetId; - $limitId = (int)$limitId; - $currencyId = (int)$entry['currency_id']; + $budgetId = (int) $budgetId; + $limitId = (int) $limitId; + $currencyId = (int) $entry['currency_id']; $spent = $entry['spent']; $totalSpent = $report['sums'][$currencyId]['spent'] ?? '0'; $spentPct = '0'; @@ -445,7 +453,6 @@ class BudgetController extends Controller $report['budgets'][$budgetId]['budget_limits'][$limitId]['budgeted_pct'] = $budgetedPct; } } - //var_dump($report);exit; return view('reports.partials.budgets', compact('report'))->render(); } @@ -498,8 +505,8 @@ class BudgetController extends Controller ]; $report[$key]['entries'][$dateKey] = $report[$key] ['entries'][$dateKey] ?? '0'; $report[$key]['entries'][$dateKey] = bcadd($journal['amount'], $report[$key] ['entries'][$dateKey]); - $report[$key]['sum'] = bcadd($report[$key] ['sum'], $journal['amount']); - $report[$key]['avg'] = bcdiv($report[$key]['sum'], (string)$count); + $report[$key]['sum'] = bcadd($report[$key] ['sum'], $journal['amount']); + $report[$key]['avg'] = bcdiv($report[$key]['sum'], (string) $count); } } } @@ -535,7 +542,7 @@ class BudgetController extends Controller $result[] = [ 'description' => $journal['description'], 'transaction_group_id' => $journal['transaction_group_id'], - 'amount_float' => (float)$journal['amount'], + 'amount_float' => (float) $journal['amount'], 'amount' => $journal['amount'], 'date' => $journal['date']->formatLocalized($this->monthAndDayFormat), 'destination_account_name' => $journal['destination_account_name'], @@ -565,5 +572,4 @@ class BudgetController extends Controller return $result; } - } diff --git a/app/Http/Controllers/Report/CategoryController.php b/app/Http/Controllers/Report/CategoryController.php index 96b7feb93a..8219a43d44 100644 --- a/app/Http/Controllers/Report/CategoryController.php +++ b/app/Http/Controllers/Report/CategoryController.php @@ -114,10 +114,12 @@ class CategoryController extends Controller 'sum' => '0', ]; $report[$sourceAccountId]['currencies'][$currencyId]['categories'][$category['id']]['spent'] = bcadd( - $report[$sourceAccountId]['currencies'][$currencyId]['categories'][$category['id']]['spent'], $journal['amount'] + $report[$sourceAccountId]['currencies'][$currencyId]['categories'][$category['id']]['spent'], + $journal['amount'] ); $report[$sourceAccountId]['currencies'][$currencyId]['categories'][$category['id']]['sum'] = bcadd( - $report[$sourceAccountId]['currencies'][$currencyId]['categories'][$category['id']]['sum'], $journal['amount'] + $report[$sourceAccountId]['currencies'][$currencyId]['categories'][$category['id']]['sum'], + $journal['amount'] ); } } @@ -152,10 +154,12 @@ class CategoryController extends Controller 'sum' => '0', ]; $report[$destinationId]['currencies'][$currencyId]['categories'][$category['id']]['earned'] = bcadd( - $report[$destinationId]['currencies'][$currencyId]['categories'][$category['id']]['earned'], $journal['amount'] + $report[$destinationId]['currencies'][$currencyId]['categories'][$category['id']]['earned'], + $journal['amount'] ); $report[$destinationId]['currencies'][$currencyId]['categories'][$category['id']]['sum'] = bcadd( - $report[$destinationId]['currencies'][$currencyId]['categories'][$category['id']]['sum'], $journal['amount'] + $report[$destinationId]['currencies'][$currencyId]['categories'][$category['id']]['sum'], + $journal['amount'] ); } } @@ -214,10 +218,12 @@ class CategoryController extends Controller 'sum' => '0', ]; $report[$sourceAccountId]['currencies'][$currencyId]['spent'] = bcadd( - $report[$sourceAccountId]['currencies'][$currencyId]['spent'], $journal['amount'] + $report[$sourceAccountId]['currencies'][$currencyId]['spent'], + $journal['amount'] ); $report[$sourceAccountId]['currencies'][$currencyId]['sum'] = bcadd( - $report[$sourceAccountId]['currencies'][$currencyId]['sum'], $journal['amount'] + $report[$sourceAccountId]['currencies'][$currencyId]['sum'], + $journal['amount'] ); $sums[$currencyId]['spent_sum'] = bcadd($sums[$currencyId]['spent_sum'], $journal['amount']); $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], $journal['amount']); @@ -250,10 +256,12 @@ class CategoryController extends Controller 'sum' => '0', ]; $report[$destinationAccountId]['currencies'][$currencyId]['earned'] = bcadd( - $report[$destinationAccountId]['currencies'][$currencyId]['earned'], $journal['amount'] + $report[$destinationAccountId]['currencies'][$currencyId]['earned'], + $journal['amount'] ); $report[$destinationAccountId]['currencies'][$currencyId]['sum'] = bcadd( - $report[$destinationAccountId]['currencies'][$currencyId]['sum'], $journal['amount'] + $report[$destinationAccountId]['currencies'][$currencyId]['sum'], + $journal['amount'] ); $sums[$currencyId]['earned_sum'] = bcadd($sums[$currencyId]['earned_sum'], $journal['amount']); $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], $journal['amount']); @@ -296,8 +304,8 @@ class CategoryController extends Controller ]; $result[$key]['transactions']++; $result[$key]['sum'] = bcadd($journal['amount'], $result[$key]['sum']); - $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string)$result[$key]['transactions']); - $result[$key]['avg_float'] = (float)$result[$key]['avg']; + $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); + $result[$key]['avg_float'] = (float) $result[$key]['avg']; } } } @@ -349,8 +357,8 @@ class CategoryController extends Controller ]; $result[$key]['transactions']++; $result[$key]['sum'] = bcadd($journal['amount'], $result[$key]['sum']); - $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string)$result[$key]['transactions']); - $result[$key]['avg_float'] = (float)$result[$key]['avg']; + $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); + $result[$key]['avg_float'] = (float) $result[$key]['avg']; } } } @@ -420,10 +428,12 @@ class CategoryController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], ]; $report[$categoryId]['currencies'][$currencyId]['spent'] = bcadd( - $report[$categoryId]['currencies'][$currencyId]['spent'], $journal['amount'] + $report[$categoryId]['currencies'][$currencyId]['spent'], + $journal['amount'] ); $report[$categoryId]['currencies'][$currencyId]['sum'] = bcadd( - $report[$categoryId]['currencies'][$currencyId]['sum'], $journal['amount'] + $report[$categoryId]['currencies'][$currencyId]['sum'], + $journal['amount'] ); $sums[$currencyId]['spent_sum'] = bcadd($sums[$currencyId]['spent_sum'], $journal['amount']); @@ -459,10 +469,12 @@ class CategoryController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], ]; $report[$categoryId]['currencies'][$currencyId]['earned'] = bcadd( - $report[$categoryId]['currencies'][$currencyId]['earned'], $journal['amount'] + $report[$categoryId]['currencies'][$currencyId]['earned'], + $journal['amount'] ); $report[$categoryId]['currencies'][$currencyId]['sum'] = bcadd( - $report[$categoryId]['currencies'][$currencyId]['sum'], $journal['amount'] + $report[$categoryId]['currencies'][$currencyId]['sum'], + $journal['amount'] ); $sums[$currencyId]['earned_sum'] = bcadd($sums[$currencyId]['earned_sum'], $journal['amount']); @@ -517,31 +529,31 @@ class CategoryController extends Controller $data = []; $with = $opsRepository->listExpenses($start, $end, $accounts); $without = $noCatRepos->listExpenses($start, $end, $accounts); - foreach([$with, $without] as $set) { - foreach ($set as $currencyId => $currencyRow) { - foreach ($currencyRow['categories'] as $categoryId => $categoryRow) { - $key = sprintf('%d-%d', $currencyId, $categoryId); - $data[$key] = $data[$key] ?? [ - 'id' => $categoryRow['id'], - 'title' => sprintf('%s (%s)', $categoryRow['name'], $currencyRow['currency_name']), - 'currency_id' => $currencyRow['currency_id'], - 'currency_symbol' => $currencyRow['currency_symbol'], - 'currency_name' => $currencyRow['currency_name'], - 'currency_code' => $currencyRow['currency_code'], - 'currency_decimal_places' => $currencyRow['currency_decimal_places'], - 'sum' => '0', - 'entries' => [], + foreach ([$with, $without] as $set) { + foreach ($set as $currencyId => $currencyRow) { + foreach ($currencyRow['categories'] as $categoryId => $categoryRow) { + $key = sprintf('%d-%d', $currencyId, $categoryId); + $data[$key] = $data[$key] ?? [ + 'id' => $categoryRow['id'], + 'title' => sprintf('%s (%s)', $categoryRow['name'], $currencyRow['currency_name']), + 'currency_id' => $currencyRow['currency_id'], + 'currency_symbol' => $currencyRow['currency_symbol'], + 'currency_name' => $currencyRow['currency_name'], + 'currency_code' => $currencyRow['currency_code'], + 'currency_decimal_places' => $currencyRow['currency_decimal_places'], + 'sum' => '0', + 'entries' => [], - ]; - foreach ($categoryRow['transaction_journals'] as $journalId => $journal) { - $date = $journal['date']->format($format); - $data[$key]['entries'][$date] = $data[$key]['entries'][$date] ?? '0'; - $data[$key]['entries'][$date] = bcadd($data[$key]['entries'][$date], $journal['amount']); - $data[$key]['sum'] = bcadd($data[$key]['sum'], $journal['amount']); + ]; + foreach ($categoryRow['transaction_journals'] as $journalId => $journal) { + $date = $journal['date']->format($format); + $data[$key]['entries'][$date] = $data[$key]['entries'][$date] ?? '0'; + $data[$key]['entries'][$date] = bcadd($data[$key]['entries'][$date], $journal['amount']); + $data[$key]['sum'] = bcadd($data[$key]['sum'], $journal['amount']); + } } } } - } $cache->store($data); @@ -603,7 +615,7 @@ class CategoryController extends Controller $data = []; $with = $opsRepository->listIncome($start, $end, $accounts); $without = $noCatRepos->listIncome($start, $end, $accounts); - foreach([$with, $without] as $set) { + foreach ([$with, $without] as $set) { foreach ($set as $currencyId => $currencyRow) { foreach ($currencyRow['categories'] as $categoryId => $categoryRow) { $key = sprintf('%d-%d', $currencyId, $categoryId); @@ -722,22 +734,26 @@ class CategoryController extends Controller $report['sums'][$currencyId]['sum'] = bcadd($report['sums'][$currencyId]['sum'], $journal['amount']); // sum of spent: $report['sums'][$currencyId]['spent'] = -1 === bccomp($journal['amount'], '0') ? bcadd( - $report['sums'][$currencyId]['spent'], $journal['amount'] + $report['sums'][$currencyId]['spent'], + $journal['amount'] ) : $report['sums'][$currencyId]['spent']; // sum of earned $report['sums'][$currencyId]['earned'] = 1 === bccomp($journal['amount'], '0') ? bcadd( - $report['sums'][$currencyId]['earned'], $journal['amount'] + $report['sums'][$currencyId]['earned'], + $journal['amount'] ) : $report['sums'][$currencyId]['earned']; // sum of category $report['categories'][$key]['sum'] = bcadd($report['categories'][$key]['sum'], $journal['amount']); // total spent in category $report['categories'][$key]['spent'] = -1 === bccomp($journal['amount'], '0') ? bcadd( - $report['categories'][$key]['spent'], $journal['amount'] + $report['categories'][$key]['spent'], + $journal['amount'] ) : $report['categories'][$key]['spent']; // total earned in category $report['categories'][$key]['earned'] = 1 === bccomp($journal['amount'], '0') ? bcadd( - $report['categories'][$key]['earned'], $journal['amount'] + $report['categories'][$key]['earned'], + $journal['amount'] ) : $report['categories'][$key]['earned']; } } @@ -777,7 +793,7 @@ class CategoryController extends Controller $result[] = [ 'description' => $journal['description'], 'transaction_group_id' => $journal['transaction_group_id'], - 'amount_float' => (float)$journal['amount'], + 'amount_float' => (float) $journal['amount'], 'amount' => $journal['amount'], 'date' => $journal['date']->formatLocalized($this->monthAndDayFormat), 'destination_account_name' => $journal['destination_account_name'], @@ -827,7 +843,7 @@ class CategoryController extends Controller $result[] = [ 'description' => $journal['description'], 'transaction_group_id' => $journal['transaction_group_id'], - 'amount_float' => (float)$journal['amount'], + 'amount_float' => (float) $journal['amount'], 'amount' => $journal['amount'], 'date' => $journal['date']->formatLocalized($this->monthAndDayFormat), 'source_account_name' => $journal['source_account_name'], @@ -871,6 +887,4 @@ class CategoryController extends Controller return false; } - - } diff --git a/app/Http/Controllers/Report/DoubleController.php b/app/Http/Controllers/Report/DoubleController.php index c08b6f800f..f1d399cb8a 100644 --- a/app/Http/Controllers/Report/DoubleController.php +++ b/app/Http/Controllers/Report/DoubleController.php @@ -100,8 +100,8 @@ class DoubleController extends Controller ]; $result[$key]['transactions']++; $result[$key]['sum'] = bcadd($journal['amount'], $result[$key]['sum']); - $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string)$result[$key]['transactions']); - $result[$key]['avg_float'] = (float)$result[$key]['avg']; + $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); + $result[$key]['avg_float'] = (float) $result[$key]['avg']; } } // sort by amount_float @@ -152,8 +152,8 @@ class DoubleController extends Controller ]; $result[$key]['transactions']++; $result[$key]['sum'] = bcadd($journal['amount'], $result[$key]['sum']); - $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string)$result[$key]['transactions']); - $result[$key]['avg_float'] = (float)$result[$key]['avg']; + $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); + $result[$key]['avg_float'] = (float) $result[$key]['avg']; } } // sort by amount_float @@ -410,7 +410,7 @@ class DoubleController extends Controller $result[] = [ 'description' => $journal['description'], 'transaction_group_id' => $journal['transaction_group_id'], - 'amount_float' => (float)$journal['amount'], + 'amount_float' => (float) $journal['amount'], 'amount' => $journal['amount'], 'date' => $journal['date']->formatLocalized($this->monthAndDayFormat), 'destination_account_name' => $journal['destination_account_name'], @@ -459,7 +459,7 @@ class DoubleController extends Controller $result[] = [ 'description' => $journal['description'], 'transaction_group_id' => $journal['transaction_group_id'], - 'amount_float' => (float)$journal['amount'], + 'amount_float' => (float) $journal['amount'], 'amount' => $journal['amount'], 'date' => $journal['date']->formatLocalized($this->monthAndDayFormat), 'destination_account_name' => $journal['destination_account_name'], @@ -773,10 +773,10 @@ class DoubleController extends Controller /** * TODO this method is double. * - * @param Collection $accounts - * @param int $id - * @param string $name - * @param string|null $iban + * @param Collection $accounts + * @param int $id + * @param string $name + * @param string|null $iban * * @return string */ diff --git a/app/Http/Controllers/Report/TagController.php b/app/Http/Controllers/Report/TagController.php index a2b8ca286c..ccba00cc66 100644 --- a/app/Http/Controllers/Report/TagController.php +++ b/app/Http/Controllers/Report/TagController.php @@ -23,7 +23,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Report; - use Carbon\Carbon; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\Account; @@ -112,10 +111,12 @@ class TagController extends Controller 'sum' => '0', ]; $report[$sourceAccountId]['currencies'][$currencyId]['tags'][$tag['id']]['spent'] = bcadd( - $report[$sourceAccountId]['currencies'][$currencyId]['tags'][$tag['id']]['spent'], $journal['amount'] + $report[$sourceAccountId]['currencies'][$currencyId]['tags'][$tag['id']]['spent'], + $journal['amount'] ); $report[$sourceAccountId]['currencies'][$currencyId]['tags'][$tag['id']]['sum'] = bcadd( - $report[$sourceAccountId]['currencies'][$currencyId]['tags'][$tag['id']]['sum'], $journal['amount'] + $report[$sourceAccountId]['currencies'][$currencyId]['tags'][$tag['id']]['sum'], + $journal['amount'] ); } } @@ -150,10 +151,12 @@ class TagController extends Controller 'sum' => '0', ]; $report[$destinationId]['currencies'][$currencyId]['tags'][$tag['id']]['earned'] = bcadd( - $report[$destinationId]['currencies'][$currencyId]['tags'][$tag['id']]['earned'], $journal['amount'] + $report[$destinationId]['currencies'][$currencyId]['tags'][$tag['id']]['earned'], + $journal['amount'] ); $report[$destinationId]['currencies'][$currencyId]['tags'][$tag['id']]['sum'] = bcadd( - $report[$destinationId]['currencies'][$currencyId]['tags'][$tag['id']]['sum'], $journal['amount'] + $report[$destinationId]['currencies'][$currencyId]['tags'][$tag['id']]['sum'], + $journal['amount'] ); } } @@ -212,10 +215,12 @@ class TagController extends Controller 'sum' => '0', ]; $report[$sourceAccountId]['currencies'][$currencyId]['spent'] = bcadd( - $report[$sourceAccountId]['currencies'][$currencyId]['spent'], $journal['amount'] + $report[$sourceAccountId]['currencies'][$currencyId]['spent'], + $journal['amount'] ); $report[$sourceAccountId]['currencies'][$currencyId]['sum'] = bcadd( - $report[$sourceAccountId]['currencies'][$currencyId]['sum'], $journal['amount'] + $report[$sourceAccountId]['currencies'][$currencyId]['sum'], + $journal['amount'] ); $sums[$currencyId]['spent_sum'] = bcadd($sums[$currencyId]['spent_sum'], $journal['amount']); $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], $journal['amount']); @@ -248,10 +253,12 @@ class TagController extends Controller 'sum' => '0', ]; $report[$destinationAccountId]['currencies'][$currencyId]['earned'] = bcadd( - $report[$destinationAccountId]['currencies'][$currencyId]['earned'], $journal['amount'] + $report[$destinationAccountId]['currencies'][$currencyId]['earned'], + $journal['amount'] ); $report[$destinationAccountId]['currencies'][$currencyId]['sum'] = bcadd( - $report[$destinationAccountId]['currencies'][$currencyId]['sum'], $journal['amount'] + $report[$destinationAccountId]['currencies'][$currencyId]['sum'], + $journal['amount'] ); $sums[$currencyId]['earned_sum'] = bcadd($sums[$currencyId]['earned_sum'], $journal['amount']); $sums[$currencyId]['total_sum'] = bcadd($sums[$currencyId]['total_sum'], $journal['amount']); @@ -294,8 +301,8 @@ class TagController extends Controller ]; $result[$key]['transactions']++; $result[$key]['sum'] = bcadd($journal['amount'], $result[$key]['sum']); - $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string)$result[$key]['transactions']); - $result[$key]['avg_float'] = (float)$result[$key]['avg']; + $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); + $result[$key]['avg_float'] = (float) $result[$key]['avg']; } } } @@ -347,8 +354,8 @@ class TagController extends Controller ]; $result[$key]['transactions']++; $result[$key]['sum'] = bcadd($journal['amount'], $result[$key]['sum']); - $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string)$result[$key]['transactions']); - $result[$key]['avg_float'] = (float)$result[$key]['avg']; + $result[$key]['avg'] = bcdiv($result[$key]['sum'], (string) $result[$key]['transactions']); + $result[$key]['avg_float'] = (float) $result[$key]['avg']; } } } @@ -418,10 +425,12 @@ class TagController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], ]; $report[$tagId]['currencies'][$currencyId]['spent'] = bcadd( - $report[$tagId]['currencies'][$currencyId]['spent'], $journal['amount'] + $report[$tagId]['currencies'][$currencyId]['spent'], + $journal['amount'] ); $report[$tagId]['currencies'][$currencyId]['sum'] = bcadd( - $report[$tagId]['currencies'][$currencyId]['sum'], $journal['amount'] + $report[$tagId]['currencies'][$currencyId]['sum'], + $journal['amount'] ); $sums[$currencyId]['spent_sum'] = bcadd($sums[$currencyId]['spent_sum'], $journal['amount']); @@ -457,10 +466,12 @@ class TagController extends Controller 'currency_decimal_places' => $currency['currency_decimal_places'], ]; $report[$tagId]['currencies'][$currencyId]['earned'] = bcadd( - $report[$tagId]['currencies'][$currencyId]['earned'], $journal['amount'] + $report[$tagId]['currencies'][$currencyId]['earned'], + $journal['amount'] ); $report[$tagId]['currencies'][$currencyId]['sum'] = bcadd( - $report[$tagId]['currencies'][$currencyId]['sum'], $journal['amount'] + $report[$tagId]['currencies'][$currencyId]['sum'], + $journal['amount'] ); $sums[$currencyId]['earned_sum'] = bcadd($sums[$currencyId]['earned_sum'], $journal['amount']); @@ -491,7 +502,7 @@ class TagController extends Controller $result[] = [ 'description' => $journal['description'], 'transaction_group_id' => $journal['transaction_group_id'], - 'amount_float' => (float)$journal['amount'], + 'amount_float' => (float) $journal['amount'], 'amount' => $journal['amount'], 'date' => $journal['date']->formatLocalized($this->monthAndDayFormat), 'destination_account_name' => $journal['destination_account_name'], @@ -541,7 +552,7 @@ class TagController extends Controller $result[] = [ 'description' => $journal['description'], 'transaction_group_id' => $journal['transaction_group_id'], - 'amount_float' => (float)$journal['amount'], + 'amount_float' => (float) $journal['amount'], 'amount' => $journal['amount'], 'date' => $journal['date']->formatLocalized($this->monthAndDayFormat), 'source_account_name' => $journal['source_account_name'], @@ -571,5 +582,4 @@ class TagController extends Controller return $result; } - -} \ No newline at end of file +} diff --git a/app/Http/Controllers/ReportController.php b/app/Http/Controllers/ReportController.php index 249c60a001..a089138782 100644 --- a/app/Http/Controllers/ReportController.php +++ b/app/Http/Controllers/ReportController.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers; use Carbon\Carbon; +use FireflyIII\Exceptions\FireflyException; use FireflyIII\Generator\Report\ReportGeneratorFactory; use FireflyIII\Helpers\Report\ReportHelperInterface; use FireflyIII\Http\Requests\ReportFormRequest; @@ -32,8 +33,11 @@ use FireflyIII\Models\AccountType; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Support\Http\Controllers\RenderPartialViews; +use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; +use Illuminate\Routing\Redirector; use Illuminate\Support\Collection; +use Illuminate\View\View; use Log; /** @@ -59,7 +63,7 @@ class ReportController extends Controller $this->middleware( function ($request, $next) { - app('view')->share('title', (string)trans('firefly.reports')); + app('view')->share('title', (string) trans('firefly.reports')); app('view')->share('mainTitleIcon', 'fa-line-chart'); app('view')->share('subTitleIcon', 'fa-calendar'); $this->helper = app(ReportHelperInterface::class); @@ -70,39 +74,6 @@ class ReportController extends Controller ); } - /** - * Show account report. - * - * @param Collection $accounts - * @param Collection $expense - * @param Carbon $start - * @param Carbon $end - * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|string - * @throws \FireflyIII\Exceptions\FireflyException - */ - public function doubleReport(Collection $accounts, Collection $expense, Carbon $start, Carbon $end) - { - if ($end < $start) { - [$start, $end] = [$end, $start]; - } - - $this->repository->cleanupBudgets(); - - app('view')->share( - 'subTitle', trans( - 'firefly.report_double', - ['start' => $start->formatLocalized($this->monthAndDayFormat), 'end' => $end->formatLocalized($this->monthAndDayFormat)] - ) - ); - - $generator = ReportGeneratorFactory::reportGenerator('Account', $start, $end); - $generator->setAccounts($accounts); - $generator->setExpense($expense); - - return $generator->generate(); - } - /** * Show audit report. * @@ -110,14 +81,14 @@ class ReportController extends Controller * @param Carbon $start * @param Carbon $end * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|string + * @throws FireflyException + * @return Factory|View|string * - * @throws \FireflyIII\Exceptions\FireflyException */ public function auditReport(Collection $accounts, Carbon $start, Carbon $end) { if ($end < $start) { - return view('error')->with('message', (string)trans('firefly.end_after_start_date')); // @codeCoverageIgnore + return view('error')->with('message', (string) trans('firefly.end_after_start_date')); // @codeCoverageIgnore } $this->repository->cleanupBudgets(); @@ -138,7 +109,6 @@ class ReportController extends Controller return $generator->generate(); } - /** * Show budget report. * @@ -147,14 +117,14 @@ class ReportController extends Controller * @param Carbon $start * @param Carbon $end * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|string + * @throws FireflyException + * @return Factory|View|string * - * @throws \FireflyIII\Exceptions\FireflyException */ public function budgetReport(Collection $accounts, Collection $budgets, Carbon $start, Carbon $end) { if ($end < $start) { - return view('error')->with('message', (string)trans('firefly.end_after_start_date')); // @codeCoverageIgnore + return view('error')->with('message', (string) trans('firefly.end_after_start_date')); // @codeCoverageIgnore } $this->repository->cleanupBudgets(); @@ -176,7 +146,6 @@ class ReportController extends Controller return $generator->generate(); } - /** * Show category report. * @@ -185,14 +154,14 @@ class ReportController extends Controller * @param Carbon $start * @param Carbon $end * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|string + * @throws FireflyException + * @return Factory|View|string * - * @throws \FireflyIII\Exceptions\FireflyException */ public function categoryReport(Collection $accounts, Collection $categories, Carbon $start, Carbon $end) { if ($end < $start) { - return view('error')->with('message', (string)trans('firefly.end_after_start_date')); // @codeCoverageIgnore + return view('error')->with('message', (string) trans('firefly.end_after_start_date')); // @codeCoverageIgnore } $this->repository->cleanupBudgets(); @@ -221,14 +190,14 @@ class ReportController extends Controller * @param Carbon $start * @param Carbon $end * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|string + * @throws FireflyException + * @return Factory|View|string * - * @throws \FireflyIII\Exceptions\FireflyException */ public function defaultReport(Collection $accounts, Carbon $start, Carbon $end) { if ($end < $start) { - return view('error')->with('message', (string)trans('firefly.end_after_start_date')); + return view('error')->with('message', (string) trans('firefly.end_after_start_date')); } $this->repository->cleanupBudgets(); @@ -250,12 +219,46 @@ class ReportController extends Controller return $generator->generate(); } + /** + * Show account report. + * + * @param Collection $accounts + * @param Collection $expense + * @param Carbon $start + * @param Carbon $end + * + * @throws FireflyException + * @return Factory|View|string + */ + public function doubleReport(Collection $accounts, Collection $expense, Carbon $start, Carbon $end) + { + if ($end < $start) { + [$start, $end] = [$end, $start]; + } + + $this->repository->cleanupBudgets(); + + app('view')->share( + 'subTitle', + trans( + 'firefly.report_double', + ['start' => $start->formatLocalized($this->monthAndDayFormat), 'end' => $end->formatLocalized($this->monthAndDayFormat)] + ) + ); + + $generator = ReportGeneratorFactory::reportGenerator('Account', $start, $end); + $generator->setAccounts($accounts); + $generator->setExpense($expense); + + return $generator->generate(); + } + /** * Show index. * * @param AccountRepositoryInterface $repository * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function index(AccountRepositoryInterface $repository) { @@ -275,20 +278,20 @@ class ReportController extends Controller $role = sprintf('opt_group_%s', $repository->getMetaValue($account, 'account_role')); if (in_array($type, [AccountType::MORTGAGE, AccountType::DEBT, AccountType::LOAN], true)) { - $role = sprintf('opt_group_l_%s',$type); + $role = sprintf('opt_group_l_%s', $type); } if ('' === $role || 'opt_group_' === $role) { $role = 'opt_group_defaultAsset'; } - $groupedAccounts[trans(sprintf('firefly.%s',$role))][$account->id] = $account; + $groupedAccounts[trans(sprintf('firefly.%s', $role))][$account->id] = $account; } ksort($groupedAccounts); - $accountList = implode(',', $accounts->pluck('id')->toArray()); + $accountList = implode(',', $accounts->pluck('id')->toArray()); $this->repository->cleanupBudgets(); - return view('reports.index', compact('months', 'accounts', 'start', 'accountList','groupedAccounts', 'customFiscalYear')); + return view('reports.index', compact('months', 'accounts', 'start', 'accountList', 'groupedAccounts', 'customFiscalYear')); } /** @@ -327,9 +330,9 @@ class ReportController extends Controller * * @param ReportFormRequest $request * - * @return RedirectResponse|\Illuminate\Routing\Redirector + * @throws FireflyException * - * @throws \FireflyIII\Exceptions\FireflyException + * @return RedirectResponse|Redirector * */ public function postIndex(ReportFormRequest $request) @@ -342,42 +345,42 @@ class ReportController extends Controller $categories = implode(',', $request->getCategoryList()->pluck('id')->toArray()); $budgets = implode(',', $request->getBudgetList()->pluck('id')->toArray()); $tags = implode(',', $request->getTagList()->pluck('id')->toArray()); - $double = implode(',', $request->getDoubleList()->pluck('id')->toArray()); + $double = implode(',', $request->getDoubleList()->pluck('id')->toArray()); $uri = route('reports.index'); if (0 === $request->getAccountList()->count()) { Log::debug('Account count is zero'); - session()->flash('error', (string)trans('firefly.select_at_least_one_account')); + session()->flash('error', (string) trans('firefly.select_at_least_one_account')); return redirect(route('reports.index')); } if ('category' === $reportType && 0 === $request->getCategoryList()->count()) { - session()->flash('error', (string)trans('firefly.select_at_least_one_category')); + session()->flash('error', (string) trans('firefly.select_at_least_one_category')); return redirect(route('reports.index')); } if ('budget' === $reportType && 0 === $request->getBudgetList()->count()) { - session()->flash('error', (string)trans('firefly.select_at_least_one_budget')); + session()->flash('error', (string) trans('firefly.select_at_least_one_budget')); return redirect(route('reports.index')); } if ('tag' === $reportType && 0 === $request->getTagList()->count()) { - session()->flash('error', (string)trans('firefly.select_at_least_one_tag')); + session()->flash('error', (string) trans('firefly.select_at_least_one_tag')); return redirect(route('reports.index')); } if ('double' === $reportType && 0 === $request->getDoubleList()->count()) { - session()->flash('error', (string)trans('firefly.select_at_least_one_expense')); + session()->flash('error', (string) trans('firefly.select_at_least_one_expense')); return redirect(route('reports.index')); } if ($request->getEndDate() < $request->getStartDate()) { - return view('error')->with('message', (string)trans('firefly.end_after_start_date')); + return view('error')->with('message', (string) trans('firefly.end_after_start_date')); } switch ($reportType) { @@ -413,13 +416,13 @@ class ReportController extends Controller * @param Carbon $start * @param Carbon $end * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View|string - * @throws \FireflyIII\Exceptions\FireflyException + * @throws FireflyException + * @return Factory|View|string */ public function tagReport(Collection $accounts, Collection $tags, Carbon $start, Carbon $end) { if ($end < $start) { - return view('error')->with('message', (string)trans('firefly.end_after_start_date')); // @codeCoverageIgnore + return view('error')->with('message', (string) trans('firefly.end_after_start_date')); // @codeCoverageIgnore } $this->repository->cleanupBudgets(); @@ -440,6 +443,4 @@ class ReportController extends Controller return $generator->generate(); } - - } diff --git a/app/Http/Controllers/Rule/CreateController.php b/app/Http/Controllers/Rule/CreateController.php index b80af3a389..e7a50340fd 100644 --- a/app/Http/Controllers/Rule/CreateController.php +++ b/app/Http/Controllers/Rule/CreateController.php @@ -23,17 +23,20 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Rule; - use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Requests\RuleFormRequest; use FireflyIII\Models\Bill; +use FireflyIII\Models\Rule; use FireflyIII\Models\RuleGroup; use FireflyIII\Models\TransactionJournal; use FireflyIII\Repositories\Rule\RuleRepositoryInterface; use FireflyIII\Support\Http\Controllers\ModelInformation; use FireflyIII\Support\Http\Controllers\RuleManagement; +use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; +use Illuminate\Routing\Redirector; +use Illuminate\View\View; /** * Class CreateController @@ -55,7 +58,7 @@ class CreateController extends Controller $this->middleware( function ($request, $next) { - app('view')->share('title', (string)trans('firefly.rules')); + app('view')->share('title', (string) trans('firefly.rules')); app('view')->share('mainTitleIcon', 'fa-random'); $this->ruleRepos = app(RuleRepositoryInterface::class); @@ -71,7 +74,7 @@ class CreateController extends Controller * @param Request $request * @param RuleGroup $ruleGroup * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function create(Request $request, RuleGroup $ruleGroup = null) { @@ -94,9 +97,9 @@ 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 (null !== $ruleGroup) { - $subTitle = (string)trans('firefly.make_new_rule', ['title' => $ruleGroup->title]); + $subTitle = (string) trans('firefly.make_new_rule', ['title' => $ruleGroup->title]); } // flash old data @@ -109,7 +112,8 @@ class CreateController extends Controller session()->forget('rules.create.fromStore'); return view( - 'rules.rule.create', compact('subTitleIcon', 'oldTriggers', 'preFilled', 'oldActions', 'triggerCount', 'actionCount', 'ruleGroup', 'subTitle') + 'rules.rule.create', + compact('subTitleIcon', 'oldTriggers', 'preFilled', 'oldActions', 'triggerCount', 'actionCount', 'ruleGroup', 'subTitle') ); } @@ -119,18 +123,18 @@ class CreateController extends Controller * @param Request $request * @param Bill $bill * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function createFromBill(Request $request, Bill $bill) { - $request->session()->flash('info', (string)trans('firefly.instructions_rule_from_bill', ['name' => e($bill->name)])); + $request->session()->flash('info', (string) trans('firefly.instructions_rule_from_bill', ['name' => e($bill->name)])); $this->createDefaultRuleGroup(); $this->createDefaultRule(); $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. @@ -144,7 +148,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'); // flash old data $request->session()->flash('preFilled', $preFilled); @@ -156,7 +160,8 @@ class CreateController extends Controller session()->forget('rules.create.fromStore'); return view( - 'rules.rule.create', compact('subTitleIcon', 'oldTriggers', 'preFilled', 'oldActions', 'triggerCount', 'actionCount', 'subTitle') + 'rules.rule.create', + compact('subTitleIcon', 'oldTriggers', 'preFilled', 'oldActions', 'triggerCount', 'actionCount', 'subTitle') ); } @@ -166,14 +171,14 @@ class CreateController extends Controller */ public function createFromJournal(Request $request, TransactionJournal $journal) { - $request->session()->flash('info', (string)trans('firefly.instructions_rule_from_journal', ['name' => e($journal->name)])); + $request->session()->flash('info', (string) trans('firefly.instructions_rule_from_journal', ['name' => e($journal->name)])); $subTitleIcon = 'fa-clone'; - $subTitle = (string)trans('firefly.make_new_rule_no_group'); + $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 = []; $triggerCount = count($oldTriggers); $actionCount = count($oldActions); @@ -183,8 +188,8 @@ class CreateController extends Controller // collect pre-filled information: $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]), ]; // flash old data @@ -197,9 +202,24 @@ class CreateController extends Controller session()->forget('rules.create.fromStore'); return view( - 'rules.rule.create', compact('subTitleIcon', 'oldTriggers', 'preFilled', 'oldActions', 'triggerCount', 'actionCount', 'subTitle') + 'rules.rule.create', + compact('subTitleIcon', 'oldTriggers', 'preFilled', 'oldActions', 'triggerCount', 'actionCount', 'subTitle') ); + } + /** + * @param Rule $rule + * + * @return RedirectResponse + */ + public function duplicate(Rule $rule): RedirectResponse + { + /** @var Rule $newRule */ + $newRule = $this->ruleRepos->duplicate($rule); + + session()->flash('success', trans('firefly.duplicated_rule', ['title' => $rule->title, 'newTitle' => $newRule->title])); + + return redirect(route('rules.index')); } /** @@ -207,29 +227,29 @@ class CreateController extends Controller * * @param RuleFormRequest $request * - * @return RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector * */ public function store(RuleFormRequest $request) { $data = $request->getRuleData(); $rule = $this->ruleRepos->store($data); - session()->flash('success', (string)trans('firefly.stored_new_rule', ['title' => $rule->title])); + session()->flash('success', (string) trans('firefly.stored_new_rule', ['title' => $rule->title])); app('preferences')->mark(); // redirect to show bill. - if ('true' === $request->get('return_to_bill') && (int)$request->get('bill_id') > 0) { - return redirect(route('bills.show', [(int)$request->get('bill_id')])); // @codeCoverageIgnore + if ('true' === $request->get('return_to_bill') && (int) $request->get('bill_id') > 0) { + return redirect(route('bills.show', [(int) $request->get('bill_id')])); // @codeCoverageIgnore } // redirect to new bill creation. - if ((int)$request->get('bill_id') > 0) { + if ((int) $request->get('bill_id') > 0) { return redirect($this->getPreviousUri('bills.create.uri')); // @codeCoverageIgnore } $redirect = redirect($this->getPreviousUri('rules.create.uri')); - if (1 === (int)$request->get('create_another')) { + if (1 === (int) $request->get('create_another')) { // @codeCoverageIgnoreStart session()->put('rules.create.fromStore', true); $redirect = redirect(route('rules.create', [$data['rule_group_id']]))->withInput(); @@ -238,5 +258,4 @@ class CreateController extends Controller return $redirect; } - } diff --git a/app/Http/Controllers/Rule/DeleteController.php b/app/Http/Controllers/Rule/DeleteController.php index 15ccb723c1..212631438d 100644 --- a/app/Http/Controllers/Rule/DeleteController.php +++ b/app/Http/Controllers/Rule/DeleteController.php @@ -27,7 +27,9 @@ namespace FireflyIII\Http\Controllers\Rule; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\Rule; use FireflyIII\Repositories\Rule\RuleRepositoryInterface; +use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; +use Illuminate\View\View; /** * Class DeleteController @@ -39,6 +41,7 @@ class DeleteController extends Controller /** * RuleController constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -47,7 +50,7 @@ class DeleteController extends Controller $this->middleware( function ($request, $next) { - app('view')->share('title', (string)trans('firefly.rules')); + app('view')->share('title', (string) trans('firefly.rules')); app('view')->share('mainTitleIcon', 'fa-random'); $this->ruleRepos = app(RuleRepositoryInterface::class); @@ -62,11 +65,11 @@ class DeleteController extends Controller * * @param Rule $rule * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function delete(Rule $rule) { - $subTitle = (string)trans('firefly.delete_rule', ['title' => $rule->title]); + $subTitle = (string) trans('firefly.delete_rule', ['title' => $rule->title]); // put previous url in session $this->rememberPreviousUri('rules.delete.uri'); @@ -86,7 +89,7 @@ class DeleteController extends Controller $title = $rule->title; $this->ruleRepos->destroy($rule); - session()->flash('success', (string)trans('firefly.deleted_rule', ['title' => $title])); + session()->flash('success', (string) trans('firefly.deleted_rule', ['title' => $title])); app('preferences')->mark(); return redirect($this->getPreviousUri('rules.delete.uri')); diff --git a/app/Http/Controllers/Rule/EditController.php b/app/Http/Controllers/Rule/EditController.php index 017bc3236f..bdeea2771b 100644 --- a/app/Http/Controllers/Rule/EditController.php +++ b/app/Http/Controllers/Rule/EditController.php @@ -30,8 +30,11 @@ use FireflyIII\Models\Rule; use FireflyIII\Repositories\Rule\RuleRepositoryInterface; use FireflyIII\Support\Http\Controllers\RenderPartialViews; use FireflyIII\Support\Http\Controllers\RuleManagement; +use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; +use Illuminate\Routing\Redirector; +use Illuminate\View\View; /** * Class EditController @@ -45,6 +48,7 @@ class EditController extends Controller /** * RuleController constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -53,7 +57,7 @@ class EditController extends Controller $this->middleware( function ($request, $next) { - app('view')->share('title', (string)trans('firefly.rules')); + app('view')->share('title', (string) trans('firefly.rules')); app('view')->share('mainTitleIcon', 'fa-random'); $this->ruleRepos = app(RuleRepositoryInterface::class); @@ -69,7 +73,7 @@ class EditController extends Controller * @param Request $request * @param Rule $rule * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function edit(Request $request, Rule $rule) { @@ -95,15 +99,15 @@ class EditController extends Controller $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, + '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, ]; // get rule trigger for update / store-journal: $primaryTrigger = $this->ruleRepos->getPrimaryTrigger($rule); - $subTitle = (string)trans('firefly.edit_rule', ['title' => $rule->title]); + $subTitle = (string) trans('firefly.edit_rule', ['title' => $rule->title]); // put previous url in session if not redirect from store (not "return_to_edit"). if (true !== session('rules.edit.fromUpdate')) { @@ -122,17 +126,17 @@ class EditController extends Controller * @param RuleFormRequest $request * @param Rule $rule * - * @return RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector */ public function update(RuleFormRequest $request, Rule $rule) { $data = $request->getRuleData(); $this->ruleRepos->update($rule, $data); - session()->flash('success', (string)trans('firefly.updated_rule', ['title' => $rule->title])); + session()->flash('success', (string) trans('firefly.updated_rule', ['title' => $rule->title])); app('preferences')->mark(); $redirect = redirect($this->getPreviousUri('rules.edit.uri')); - if (1 === (int)$request->get('return_to_edit')) { + if (1 === (int) $request->get('return_to_edit')) { // @codeCoverageIgnoreStart session()->put('rules.edit.fromUpdate', true); diff --git a/app/Http/Controllers/Rule/IndexController.php b/app/Http/Controllers/Rule/IndexController.php index b5da7dbed2..0233337bc4 100644 --- a/app/Http/Controllers/Rule/IndexController.php +++ b/app/Http/Controllers/Rule/IndexController.php @@ -28,9 +28,12 @@ use FireflyIII\Repositories\Rule\RuleRepositoryInterface; use FireflyIII\Repositories\RuleGroup\RuleGroupRepositoryInterface; use FireflyIII\Support\Http\Controllers\RuleManagement; use FireflyIII\User; +use Illuminate\Contracts\View\Factory; use Illuminate\Http\JsonResponse; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; +use Illuminate\Routing\Redirector; +use Illuminate\View\View; /** * Class IndexController @@ -45,6 +48,7 @@ class IndexController extends Controller /** * RuleController constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -52,7 +56,7 @@ class IndexController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - app('view')->share('title', (string)trans('firefly.rules')); + app('view')->share('title', (string) trans('firefly.rules')); app('view')->share('mainTitleIcon', 'fa-random'); $this->ruleGroupRepos = app(RuleGroupRepositoryInterface::class); $this->ruleRepos = app(RuleRepositoryInterface::class); @@ -67,7 +71,7 @@ class IndexController extends Controller * * @param Rule $rule * - * @return RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector */ public function down(Rule $rule) { @@ -79,7 +83,7 @@ class IndexController extends Controller /** * Index of all rules and groups. * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function index() { @@ -134,7 +138,7 @@ class IndexController extends Controller * * @param Rule $rule * - * @return RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector */ public function up(Rule $rule) { diff --git a/app/Http/Controllers/Rule/SelectController.php b/app/Http/Controllers/Rule/SelectController.php index 90df0060e0..807b6588fb 100644 --- a/app/Http/Controllers/Rule/SelectController.php +++ b/app/Http/Controllers/Rule/SelectController.php @@ -38,9 +38,11 @@ use FireflyIII\Support\Http\Controllers\RuleManagement; use FireflyIII\TransactionRules\Engine\RuleEngine; use FireflyIII\TransactionRules\TransactionMatcher; use FireflyIII\User; +use Illuminate\Contracts\View\Factory; use Illuminate\Http\JsonResponse; use Illuminate\Http\RedirectResponse; use Illuminate\Support\Collection; +use Illuminate\View\View; use Log; use Throwable; @@ -63,7 +65,7 @@ class SelectController extends Controller $this->middleware( function ($request, $next) { - app('view')->share('title', (string)trans('firefly.rules')); + app('view')->share('title', (string) trans('firefly.rules')); app('view')->share('mainTitleIcon', 'fa-random'); $this->accountRepos = app(AccountRepositoryInterface::class); @@ -77,7 +79,7 @@ class SelectController extends Controller * Execute the given rule on a set of existing transactions. * * @param SelectTransactionsRequest $request - * @param Rule $rule + * @param Rule $rule * * @return RedirectResponse */ @@ -89,7 +91,7 @@ class SelectController extends Controller $accounts = $this->accountRepos->getAccountsById($request->get('accounts')); $startDate = new Carbon($request->get('start_date')); $endDate = new Carbon($request->get('end_date')); - $rules = [$rule->id]; + $rules = [$rule->id]; /** @var RuleEngine $ruleEngine */ $ruleEngine = app(RuleEngine::class); @@ -111,7 +113,7 @@ class SelectController extends Controller } // Tell the user that the job is queued - session()->flash('success', (string)trans('firefly.applied_rule_selection', ['title' => $rule->title])); + session()->flash('success', (string) trans('firefly.applied_rule_selection', ['title' => $rule->title])); return redirect()->route('rules.index'); } @@ -122,14 +124,14 @@ class SelectController extends Controller * * @param Rule $rule * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function selectTransactions(Rule $rule) { // does the user have shared accounts? $first = session('first', Carbon::now()->subYear())->format('Y-m-d'); $today = Carbon::now()->format('Y-m-d'); - $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', compact('first', 'today', 'rule', 'subTitle')); } @@ -153,11 +155,11 @@ class SelectController extends Controller $triggers = $this->getValidTriggerList($request); if (0 === count($triggers)) { - return response()->json(['html' => '', 'warning' => (string)trans('firefly.warning_no_valid_triggers')]); // @codeCoverageIgnore + return response()->json(['html' => '', 'warning' => (string) trans('firefly.warning_no_valid_triggers')]); // @codeCoverageIgnore } - $limit = (int)config('firefly.test-triggers.limit'); - $range = (int)config('firefly.test-triggers.range'); + $limit = (int) config('firefly.test-triggers.limit'); + $range = (int) config('firefly.test-triggers.range'); $matchingTransactions = new Collection; $strict = '1' === $request->get('strict'); /** @var TransactionMatcher $matcher */ @@ -179,10 +181,10 @@ class SelectController extends Controller // Warn the user if only a subset of transactions is returned $warning = ''; if (count($matchingTransactions) === $limit) { - $warning = (string)trans('firefly.warning_transaction_subset', ['max_num_transactions' => $limit]); // @codeCoverageIgnore + $warning = (string) trans('firefly.warning_transaction_subset', ['max_num_transactions' => $limit]); // @codeCoverageIgnore } if (0 === count($matchingTransactions)) { - $warning = (string)trans('firefly.warning_no_matching_transactions', ['num_transactions' => $range]); // @codeCoverageIgnore + $warning = (string) trans('firefly.warning_no_matching_transactions', ['num_transactions' => $range]); // @codeCoverageIgnore } // Return json response @@ -219,11 +221,11 @@ class SelectController extends Controller $triggers = $rule->ruleTriggers; if (0 === count($triggers)) { - return response()->json(['html' => '', 'warning' => (string)trans('firefly.warning_no_valid_triggers')]); // @codeCoverageIgnore + return response()->json(['html' => '', 'warning' => (string) trans('firefly.warning_no_valid_triggers')]); // @codeCoverageIgnore } - $limit = (int)config('firefly.test-triggers.limit'); - $range = (int)config('firefly.test-triggers.range'); + $limit = (int) config('firefly.test-triggers.limit'); + $range = (int) config('firefly.test-triggers.range'); $matchingTransactions = new Collection; /** @var TransactionMatcher $matcher */ @@ -243,10 +245,10 @@ class SelectController extends Controller // Warn the user if only a subset of transactions is returned $warning = ''; if (count($matchingTransactions) === $limit) { - $warning = (string)trans('firefly.warning_transaction_subset', ['max_num_transactions' => $limit]); // @codeCoverageIgnore + $warning = (string) trans('firefly.warning_transaction_subset', ['max_num_transactions' => $limit]); // @codeCoverageIgnore } if (0 === count($matchingTransactions)) { - $warning = (string)trans('firefly.warning_no_matching_transactions', ['num_transactions' => $range]); // @codeCoverageIgnore + $warning = (string) trans('firefly.warning_no_matching_transactions', ['num_transactions' => $range]); // @codeCoverageIgnore } // Return json response diff --git a/app/Http/Controllers/RuleGroup/CreateController.php b/app/Http/Controllers/RuleGroup/CreateController.php index 5c6cbed640..d2edd4df2c 100644 --- a/app/Http/Controllers/RuleGroup/CreateController.php +++ b/app/Http/Controllers/RuleGroup/CreateController.php @@ -27,6 +27,10 @@ namespace FireflyIII\Http\Controllers\RuleGroup; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Requests\RuleGroupFormRequest; use FireflyIII\Repositories\RuleGroup\RuleGroupRepositoryInterface; +use Illuminate\Contracts\View\Factory; +use Illuminate\Http\RedirectResponse; +use Illuminate\Routing\Redirector; +use Illuminate\View\View; /** * Class CreateController @@ -38,6 +42,7 @@ class CreateController extends Controller /** * CreateController constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -46,7 +51,7 @@ class CreateController extends Controller $this->middleware( function ($request, $next) { - app('view')->share('title', (string)trans('firefly.rules')); + app('view')->share('title', (string) trans('firefly.rules')); app('view')->share('mainTitleIcon', 'fa-random'); $this->repository = app(RuleGroupRepositoryInterface::class); @@ -59,12 +64,12 @@ class CreateController extends Controller /** * Create a new rule group. * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function create() { $subTitleIcon = 'fa-clone'; - $subTitle = (string)trans('firefly.make_new_rule_group'); + $subTitle = (string) trans('firefly.make_new_rule_group'); // put previous url in session if not redirect from store (not "create another"). if (true !== session('rule-groups.create.fromStore')) { @@ -80,18 +85,18 @@ class CreateController extends Controller * * @param RuleGroupFormRequest $request * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector */ public function store(RuleGroupFormRequest $request) { $data = $request->getRuleGroupData(); $ruleGroup = $this->repository->store($data); - session()->flash('success', (string)trans('firefly.created_new_rule_group', ['title' => $ruleGroup->title])); + session()->flash('success', (string) trans('firefly.created_new_rule_group', ['title' => $ruleGroup->title])); app('preferences')->mark(); $redirect = redirect($this->getPreviousUri('rule-groups.create.uri')); - if (1 === (int)$request->get('create_another')) { + if (1 === (int) $request->get('create_another')) { // @codeCoverageIgnoreStart session()->put('rule-groups.create.fromStore', true); diff --git a/app/Http/Controllers/RuleGroup/DeleteController.php b/app/Http/Controllers/RuleGroup/DeleteController.php index 0f35f290c5..a06fadf159 100644 --- a/app/Http/Controllers/RuleGroup/DeleteController.php +++ b/app/Http/Controllers/RuleGroup/DeleteController.php @@ -27,7 +27,11 @@ namespace FireflyIII\Http\Controllers\RuleGroup; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\RuleGroup; use FireflyIII\Repositories\RuleGroup\RuleGroupRepositoryInterface; +use Illuminate\Contracts\View\Factory; +use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; +use Illuminate\Routing\Redirector; +use Illuminate\View\View; /** * Class DeleteController @@ -39,6 +43,7 @@ class DeleteController extends Controller /** * DeleteController constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -47,7 +52,7 @@ class DeleteController extends Controller $this->middleware( function ($request, $next) { - app('view')->share('title', (string)trans('firefly.rules')); + app('view')->share('title', (string) trans('firefly.rules')); app('view')->share('mainTitleIcon', 'fa-random'); $this->repository = app(RuleGroupRepositoryInterface::class); @@ -63,11 +68,11 @@ class DeleteController extends Controller * * @param RuleGroup $ruleGroup * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function delete(RuleGroup $ruleGroup) { - $subTitle = (string)trans('firefly.delete_rule_group', ['title' => $ruleGroup->title]); + $subTitle = (string) trans('firefly.delete_rule_group', ['title' => $ruleGroup->title]); // put previous url in session $this->rememberPreviousUri('rule-groups.delete.uri'); @@ -78,20 +83,20 @@ class DeleteController extends Controller /** * Actually destroy the rule group. * - * @param Request $request + * @param Request $request * @param RuleGroup $ruleGroup * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector */ public function destroy(Request $request, RuleGroup $ruleGroup) { $title = $ruleGroup->title; /** @var RuleGroup $moveTo */ - $moveTo = $this->repository->find((int)$request->get('move_rules_before_delete')); + $moveTo = $this->repository->find((int) $request->get('move_rules_before_delete')); $this->repository->destroy($ruleGroup, $moveTo); - session()->flash('success', (string)trans('firefly.deleted_rule_group', ['title' => $title])); + session()->flash('success', (string) trans('firefly.deleted_rule_group', ['title' => $title])); app('preferences')->mark(); return redirect($this->getPreviousUri('rule-groups.delete.uri')); diff --git a/app/Http/Controllers/RuleGroup/EditController.php b/app/Http/Controllers/RuleGroup/EditController.php index 4e7963b768..7ace86699b 100644 --- a/app/Http/Controllers/RuleGroup/EditController.php +++ b/app/Http/Controllers/RuleGroup/EditController.php @@ -27,7 +27,11 @@ use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Requests\RuleGroupFormRequest; use FireflyIII\Models\RuleGroup; use FireflyIII\Repositories\RuleGroup\RuleGroupRepositoryInterface; +use Illuminate\Contracts\View\Factory; +use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; +use Illuminate\Routing\Redirector; +use Illuminate\View\View; /** * Class EditController @@ -39,6 +43,7 @@ class EditController extends Controller /** * EditController constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -47,7 +52,7 @@ class EditController extends Controller $this->middleware( function ($request, $next) { - app('view')->share('title', (string)trans('firefly.rules')); + app('view')->share('title', (string) trans('firefly.rules')); app('view')->share('mainTitleIcon', 'fa-random'); $this->repository = app(RuleGroupRepositoryInterface::class); @@ -62,7 +67,7 @@ class EditController extends Controller * * @param RuleGroup $ruleGroup * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector */ public function down(RuleGroup $ruleGroup) { @@ -75,18 +80,18 @@ class EditController extends Controller /** * Edit a rule group. * - * @param Request $request + * @param Request $request * @param RuleGroup $ruleGroup * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function edit(Request $request, RuleGroup $ruleGroup) { - $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, ]; @@ -105,7 +110,7 @@ class EditController extends Controller * * @param RuleGroup $ruleGroup * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector * */ public function up(RuleGroup $ruleGroup) @@ -119,24 +124,24 @@ class EditController extends Controller * Update the rule group. * * @param RuleGroupFormRequest $request - * @param RuleGroup $ruleGroup + * @param RuleGroup $ruleGroup * - * @return $this|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return $this|RedirectResponse|Redirector */ public function update(RuleGroupFormRequest $request, RuleGroup $ruleGroup) { $data = [ 'title' => $request->string('title'), 'description' => $request->nlString('description'), - 'active' => 1 === (int)$request->input('active'), + 'active' => 1 === (int) $request->input('active'), ]; $this->repository->update($ruleGroup, $data); - session()->flash('success', (string)trans('firefly.updated_rule_group', ['title' => $ruleGroup->title])); + session()->flash('success', (string) trans('firefly.updated_rule_group', ['title' => $ruleGroup->title])); app('preferences')->mark(); $redirect = redirect($this->getPreviousUri('rule-groups.edit.uri')); - if (1 === (int)$request->get('return_to_edit')) { + if (1 === (int) $request->get('return_to_edit')) { // @codeCoverageIgnoreStart session()->put('rule-groups.edit.fromUpdate', true); diff --git a/app/Http/Controllers/RuleGroup/ExecutionController.php b/app/Http/Controllers/RuleGroup/ExecutionController.php index 1deac6a443..fdece519f2 100644 --- a/app/Http/Controllers/RuleGroup/ExecutionController.php +++ b/app/Http/Controllers/RuleGroup/ExecutionController.php @@ -25,6 +25,7 @@ namespace FireflyIII\Http\Controllers\RuleGroup; use Carbon\Carbon; +use Exception; use FireflyIII\Helpers\Collector\GroupCollectorInterface; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Requests\SelectTransactionsRequest; @@ -33,7 +34,9 @@ use FireflyIII\Models\RuleGroup; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\RuleGroup\RuleGroupRepositoryInterface; use FireflyIII\TransactionRules\Engine\RuleEngine; +use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; +use Illuminate\View\View; use Log; /** @@ -49,6 +52,7 @@ class ExecutionController extends Controller /** * ExecutionController constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -57,7 +61,7 @@ class ExecutionController extends Controller $this->middleware( function ($request, $next) { - app('view')->share('title', (string)trans('firefly.rules')); + app('view')->share('title', (string) trans('firefly.rules')); app('view')->share('mainTitleIcon', 'fa-random'); $this->repository = app(AccountRepositoryInterface::class); @@ -73,10 +77,10 @@ class ExecutionController extends Controller * Execute the given rulegroup on a set of existing transactions. * * @param SelectTransactionsRequest $request - * @param RuleGroup $ruleGroup + * @param RuleGroup $ruleGroup * + * @throws Exception * @return RedirectResponse - * @throws \Exception */ public function execute(SelectTransactionsRequest $request, RuleGroup $ruleGroup): RedirectResponse { @@ -113,7 +117,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'); } @@ -123,13 +127,13 @@ class ExecutionController extends Controller * * @param RuleGroup $ruleGroup * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function selectTransactions(RuleGroup $ruleGroup) { $first = session('first')->format('Y-m-d'); $today = Carbon::now()->format('Y-m-d'); - $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', compact('first', 'today', 'ruleGroup', 'subTitle')); } diff --git a/app/Http/Controllers/SearchController.php b/app/Http/Controllers/SearchController.php index faafb73e10..992579db8a 100644 --- a/app/Http/Controllers/SearchController.php +++ b/app/Http/Controllers/SearchController.php @@ -23,8 +23,10 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers; use FireflyIII\Support\Search\SearchInterface; +use Illuminate\Contracts\View\Factory; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; +use Illuminate\View\View; use Log; use Throwable; @@ -43,7 +45,7 @@ class SearchController extends Controller $this->middleware( static function ($request, $next) { app('view')->share('mainTitleIcon', 'fa-search'); - app('view')->share('title', (string)trans('firefly.search')); + app('view')->share('title', (string) trans('firefly.search')); return $next($request); } @@ -56,19 +58,19 @@ class SearchController extends Controller * @param Request $request * @param SearchInterface $searcher * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function index(Request $request, SearchInterface $searcher) { - $fullQuery = (string)$request->get('search'); - $page = 0 === (int)$request->get('page') ? 1 : (int)$request->get('page'); + $fullQuery = (string) $request->get('search'); + $page = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page'); // parse search terms: $searcher->parseQuery($fullQuery); $query = $searcher->getWordsAsString(); $modifiers = $searcher->getModifiers(); - $subTitle = (string)trans('breadcrumbs.search_result', ['query' => $query]); + $subTitle = (string) trans('breadcrumbs.search_result', ['query' => $query]); - return view('search.index', compact('query', 'modifiers', 'page','fullQuery', 'subTitle')); + return view('search.index', compact('query', 'modifiers', 'page', 'fullQuery', 'subTitle')); } /** @@ -77,16 +79,16 @@ class SearchController extends Controller * @param Request $request * @param SearchInterface $searcher * - * @return \Illuminate\Http\JsonResponse + * @return JsonResponse */ public function search(Request $request, SearchInterface $searcher): JsonResponse { - $fullQuery = (string)$request->get('query'); - $page = 0 === (int)$request->get('page') ? 1 : (int)$request->get('page'); + $fullQuery = (string) $request->get('query'); + $page = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page'); $searcher->parseQuery($fullQuery); $searcher->setPage($page); - $searcher->setLimit((int)config('firefly.search_result_limit')); + $searcher->setLimit((int) config('firefly.search_result_limit')); $groups = $searcher->searchTransactions(); $hasPages = $groups->hasPages(); $searchTime = round($searcher->searchTime(), 3); // in seconds diff --git a/app/Http/Controllers/System/InstallController.php b/app/Http/Controllers/System/InstallController.php index 57970c23e9..725fa72a80 100644 --- a/app/Http/Controllers/System/InstallController.php +++ b/app/Http/Controllers/System/InstallController.php @@ -31,7 +31,9 @@ use FireflyIII\Http\Controllers\Controller; use FireflyIII\Support\Facades\Preferences; use FireflyIII\Support\Http\Controllers\GetConfigurationData; use Illuminate\Http\JsonResponse; +use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; +use Illuminate\Routing\Redirector; use Illuminate\Support\Arr; use Laravel\Passport\Passport; use Log; @@ -113,15 +115,15 @@ class InstallController extends Controller /** * Show index. * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector */ public function index() { // index will set FF3 version. - app('fireflyconfig')->set('ff3_version', (string)config('firefly.version')); + app('fireflyconfig')->set('ff3_version', (string) config('firefly.version')); // set new DB version. - app('fireflyconfig')->set('db_version', (int)config('firefly.db_version')); + app('fireflyconfig')->set('db_version', (int) config('firefly.db_version')); return view('install.index'); } @@ -154,7 +156,7 @@ class InstallController extends Controller */ public function runCommand(Request $request): JsonResponse { - $requestIndex = (int)$request->get('index'); + $requestIndex = (int) $request->get('index'); $response = [ 'hasNextCommand' => false, 'done' => true, diff --git a/app/Http/Controllers/TagController.php b/app/Http/Controllers/TagController.php index 4567d48ba8..36a4f4f4a5 100644 --- a/app/Http/Controllers/TagController.php +++ b/app/Http/Controllers/TagController.php @@ -29,8 +29,10 @@ use FireflyIII\Http\Requests\TagFormRequest; use FireflyIII\Models\Tag; use FireflyIII\Repositories\Tag\TagRepositoryInterface; use FireflyIII\Support\Http\Controllers\PeriodOverview; +use Illuminate\Contracts\View\Factory; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; +use Illuminate\View\View; use Log; /** @@ -54,7 +56,7 @@ class TagController extends Controller $this->middleware( function ($request, $next) { $this->repository = app(TagRepositoryInterface::class); - app('view')->share('title', (string)trans('firefly.tags')); + app('view')->share('title', (string) trans('firefly.tags')); app('view')->share('mainTitleIcon', 'fa-tags'); return $next($request); @@ -62,39 +64,14 @@ class TagController extends Controller ); } - /** - * - */ - public function massDestroy(Request $request) - { - $tags = $request->get('tags'); - if (null === $tags || !is_array($tags)) { - session()->flash('info', (string)trans('firefly.select_tags_to_delete')); - - return redirect(route('tags.index')); - } - $count = 0; - foreach ($tags as $tagId) { - $tagId = (int)$tagId; - $tag = $this->repository->findNull($tagId); - if (null !== $tag) { - $this->repository->destroy($tag); - $count++; - } - } - session()->flash('success', (string)trans('firefly.deleted_x_tags', ['count' => $count])); - - return redirect(route('tags.index')); - } - /** * Create a new tag. * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function create(Request $request) { - $subTitle = (string)trans('firefly.new_tag'); + $subTitle = (string) trans('firefly.new_tag'); $subTitleIcon = 'fa-tag'; // location info: @@ -122,11 +99,11 @@ class TagController extends Controller * * @param Tag $tag * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function delete(Tag $tag) { - $subTitle = (string)trans('breadcrumbs.delete_tag', ['tag' => $tag->tag]); + $subTitle = (string) trans('breadcrumbs.delete_tag', ['tag' => $tag->tag]); // put previous url in session $this->rememberPreviousUri('tags.delete.uri'); @@ -146,7 +123,7 @@ class TagController extends Controller $tagName = $tag->tag; $this->repository->destroy($tag); - session()->flash('success', (string)trans('firefly.deleted_tag', ['tag' => $tagName])); + session()->flash('success', (string) trans('firefly.deleted_tag', ['tag' => $tagName])); app('preferences')->mark(); return redirect($this->getPreviousUri('tags.delete.uri')); @@ -157,19 +134,19 @@ class TagController extends Controller * * @param Tag $tag * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function edit(Tag $tag) { - $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 ? $location->latitude : config('firefly.default_location.latitude'); - $longitude = $location ? $location->longitude : config('firefly.default_location.longitude'); - $zoomLevel = $location ? $location->zoom_level : config('firefly.default_location.zoom_level'); - $hasLocation = null !== $location; - $locations = [ + $location = $this->repository->getLocation($tag); + $latitude = $location ? $location->latitude : config('firefly.default_location.latitude'); + $longitude = $location ? $location->longitude : config('firefly.default_location.longitude'); + $zoomLevel = $location ? $location->zoom_level : config('firefly.default_location.zoom_level'); + $hasLocation = null !== $location; + $locations = [ 'location' => [ 'latitude' => old('location_latitude') ?? $latitude, 'longitude' => old('location_longitude') ?? $longitude, @@ -184,7 +161,7 @@ class TagController extends Controller } session()->forget('tags.edit.fromUpdate'); - return view('tags.edit', compact('tag', 'subTitle', 'subTitleIcon','locations')); + return view('tags.edit', compact('tag', 'subTitle', 'subTitleIcon', 'locations')); } /** @@ -192,7 +169,7 @@ class TagController extends Controller * * @param TagRepositoryInterface $repository * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function index(TagRepositoryInterface $repository) { @@ -205,7 +182,7 @@ class TagController extends Controller $tags['no-date'] = $repository->getTagsInYear(null); while ($newestTagDate > $oldestTagDate) { - $year = $newestTagDate->year; + $year = $newestTagDate->year; $tags[$year] = $repository->getTagsInYear($year); $newestTagDate->subYear(); } @@ -214,36 +191,62 @@ class TagController extends Controller return view('tags.index', compact('tags', 'count')); } + /** + * + */ + public function massDestroy(Request $request) + { + $tags = $request->get('tags'); + if (null === $tags || !is_array($tags)) { + session()->flash('info', (string) trans('firefly.select_tags_to_delete')); + + return redirect(route('tags.index')); + } + $count = 0; + foreach ($tags as $tagId) { + $tagId = (int) $tagId; + $tag = $this->repository->findNull($tagId); + if (null !== $tag) { + $this->repository->destroy($tag); + $count++; + } + } + session()->flash('success', (string) trans('firefly.deleted_x_tags', ['count' => $count])); + + return redirect(route('tags.index')); + } + /** * Show a single tag. * - * @param Request $request - * @param Tag $tag + * @param Request $request + * @param Tag $tag * @param Carbon|null $start * @param Carbon|null $end * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View * */ public function show(Request $request, Tag $tag, Carbon $start = null, Carbon $end = null) { // default values: $subTitleIcon = 'fa-tag'; - $page = (int)$request->get('page'); - $pageSize = (int)app('preferences')->get('listPageSize', 50)->data; + $page = (int) $request->get('page'); + $pageSize = (int) app('preferences')->get('listPageSize', 50)->data; $start = $start ?? session('start'); $end = $end ?? session('end'); $location = $this->repository->getLocation($tag); $subTitle = trans( - 'firefly.journals_in_period_for_tag', ['tag' => $tag->tag, 'start' => $start->formatLocalized($this->monthAndDayFormat), - 'end' => $end->formatLocalized($this->monthAndDayFormat),] + 'firefly.journals_in_period_for_tag', + ['tag' => $tag->tag, 'start' => $start->formatLocalized($this->monthAndDayFormat), + 'end' => $end->formatLocalized($this->monthAndDayFormat),] ); $startPeriod = $this->repository->firstUseDate($tag); - $startPeriod = $startPeriod ?? new Carbon; - $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')]); + $startPeriod = $startPeriod ?? new Carbon; + $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); @@ -261,19 +264,19 @@ class TagController extends Controller * Show a single tag over all time. * * @param Request $request - * @param Tag $tag + * @param Tag $tag * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View * */ public function showAll(Request $request, Tag $tag) { // default values: $subTitleIcon = 'fa-tag'; - $page = (int)$request->get('page'); - $pageSize = (int)app('preferences')->get('listPageSize', 50)->data; + $page = (int) $request->get('page'); + $pageSize = (int) app('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) ?? new Carbon; $end = new Carbon; $path = route('tags.show', [$tag->id, 'all']); @@ -304,11 +307,11 @@ class TagController extends Controller $result = $this->repository->store($data); Log::debug('Data after storage', $result->toArray()); - session()->flash('success', (string)trans('firefly.created_tag', ['tag' => $data['tag']])); + session()->flash('success', (string) trans('firefly.created_tag', ['tag' => $data['tag']])); app('preferences')->mark(); $redirect = redirect($this->getPreviousUri('tags.create.uri')); - if (1 === (int)$request->get('create_another')) { + if (1 === (int) $request->get('create_another')) { // @codeCoverageIgnoreStart session()->put('tags.create.fromStore', true); @@ -317,14 +320,13 @@ class TagController extends Controller } return $redirect; - } /** * Update a tag. * * @param TagFormRequest $request - * @param Tag $tag + * @param Tag $tag * * @return RedirectResponse */ @@ -333,11 +335,11 @@ class TagController extends Controller $data = $request->collectTagData(); $this->repository->update($tag, $data); - session()->flash('success', (string)trans('firefly.updated_tag', ['tag' => $data['tag']])); + session()->flash('success', (string) trans('firefly.updated_tag', ['tag' => $data['tag']])); app('preferences')->mark(); $redirect = redirect($this->getPreviousUri('tags.edit.uri')); - if (1 === (int)$request->get('return_to_edit')) { + if (1 === (int) $request->get('return_to_edit')) { // @codeCoverageIgnoreStart session()->put('tags.edit.fromUpdate', true); @@ -348,6 +350,4 @@ class TagController extends Controller // redirect to previous URL. return $redirect; } - - } diff --git a/app/Http/Controllers/Transaction/BulkController.php b/app/Http/Controllers/Transaction/BulkController.php index 822e124fac..9a526b44fa 100644 --- a/app/Http/Controllers/Transaction/BulkController.php +++ b/app/Http/Controllers/Transaction/BulkController.php @@ -29,7 +29,9 @@ use FireflyIII\Http\Requests\BulkEditJournalRequest; use FireflyIII\Models\TransactionJournal; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Repositories\Journal\JournalRepositoryInterface; +use Illuminate\Contracts\View\Factory; use Illuminate\Support\Collection; +use Illuminate\View\View; use Log; /** @@ -43,6 +45,7 @@ class BulkController extends Controller /** * BulkController constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -52,7 +55,7 @@ class BulkController extends Controller $this->middleware( function ($request, $next) { $this->repository = app(JournalRepositoryInterface::class); - app('view')->share('title', (string)trans('firefly.transactions')); + app('view')->share('title', (string) trans('firefly.transactions')); app('view')->share('mainTitleIcon', 'fa-repeat'); return $next($request); @@ -67,11 +70,11 @@ class BulkController extends Controller * * @param Collection $journals * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function edit(array $journals) { - $subTitle = (string)trans('firefly.mass_bulk_journals'); + $subTitle = (string) trans('firefly.mass_bulk_journals'); $this->rememberPreviousUri('transactions.bulk-edit.uri'); @@ -97,13 +100,13 @@ class BulkController extends Controller { $journalIds = $request->get('journals'); $journalIds = is_array($journalIds) ? $journalIds : []; - $ignoreCategory = 1 === (int)$request->get('ignore_category'); - $ignoreBudget = 1 === (int)$request->get('ignore_budget'); - $ignoreTags = 1 === (int)$request->get('ignore_tags'); + $ignoreCategory = 1 === (int) $request->get('ignore_category'); + $ignoreBudget = 1 === (int) $request->get('ignore_budget'); + $ignoreTags = 1 === (int) $request->get('ignore_tags'); $count = 0; foreach ($journalIds as $journalId) { - $journalId = (int)$journalId; + $journalId = (int) $journalId; $journal = $this->repository->findNull($journalId); if (null !== $journal) { $resultA = $this->updateJournalBudget($journal, $ignoreBudget, $request->integer('budget_id')); @@ -115,7 +118,7 @@ class BulkController extends Controller } } app('preferences')->mark(); - $request->session()->flash('success', (string)trans('firefly.mass_edited_transactions_success', ['amount' => $count])); + $request->session()->flash('success', (string) trans('firefly.mass_edited_transactions_success', ['amount' => $count])); // redirect to previous URL: return redirect($this->getPreviousUri('transactions.bulk-edit.uri')); @@ -123,26 +126,27 @@ class BulkController extends Controller /** * @param TransactionJournal $journal - * @param bool $ignoreUpdate - * @param array $tags + * @param bool $ignoreUpdate + * @param int $budgetId + * * @return bool */ - private function updateJournalTags(TransactionJournal $journal, bool $ignoreUpdate, array $tags): bool + private function updateJournalBudget(TransactionJournal $journal, bool $ignoreUpdate, int $budgetId): bool { - if (true === $ignoreUpdate) { return false; } - Log::debug(sprintf('Set tags to %s', implode(',', $tags))); - $this->repository->updateTags($journal, $tags); + Log::debug(sprintf('Set budget to %d', $budgetId)); + $this->repository->updateBudget($journal, $budgetId); return true; } /** * @param TransactionJournal $journal - * @param bool $ignoreUpdate - * @param string $category + * @param bool $ignoreUpdate + * @param string $category + * * @return bool */ private function updateJournalCategory(TransactionJournal $journal, bool $ignoreUpdate, string $category): bool @@ -158,17 +162,19 @@ class BulkController extends Controller /** * @param TransactionJournal $journal - * @param bool $ignoreUpdate - * @param int $budgetId + * @param bool $ignoreUpdate + * @param array $tags + * * @return bool */ - private function updateJournalBudget(TransactionJournal $journal, bool $ignoreUpdate, int $budgetId): bool + private function updateJournalTags(TransactionJournal $journal, bool $ignoreUpdate, array $tags): bool { + if (true === $ignoreUpdate) { return false; } - Log::debug(sprintf('Set budget to %d', $budgetId)); - $this->repository->updateBudget($journal, $budgetId); + Log::debug(sprintf('Set tags to %s', implode(',', $tags))); + $this->repository->updateTags($journal, $tags); return true; } diff --git a/app/Http/Controllers/Transaction/ConvertController.php b/app/Http/Controllers/Transaction/ConvertController.php index 3598b1359b..ea21ca6376 100644 --- a/app/Http/Controllers/Transaction/ConvertController.php +++ b/app/Http/Controllers/Transaction/ConvertController.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Transaction; use Carbon\Carbon; +use Exception; use FireflyIII\Events\UpdatedTransactionGroup; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; @@ -38,11 +39,12 @@ use FireflyIII\Support\Http\Controllers\ModelInformation; use FireflyIII\Support\Http\Controllers\UserNavigation; use FireflyIII\Transformers\TransactionGroupTransformer; use FireflyIII\Validation\AccountValidator; +use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; +use Illuminate\Routing\Redirector; use Log; use View; - /** * Class ConvertController. * @@ -57,6 +59,7 @@ class ConvertController extends Controller /** * ConvertController constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -68,7 +71,7 @@ class ConvertController extends Controller function ($request, $next) { $this->repository = app(JournalRepositoryInterface::class); - app('view')->share('title', (string)trans('firefly.transactions')); + app('view')->share('title', (string) trans('firefly.transactions')); app('view')->share('mainTitleIcon', 'fa-exchange'); return $next($request); @@ -80,11 +83,11 @@ class ConvertController extends Controller /** * Show overview of a to be converted transaction. * - * @param TransactionType $destinationType + * @param TransactionType $destinationType * @param TransactionGroup $group * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|View - * @throws \Exception + * @throws Exception + * @return RedirectResponse|Redirector|View */ public function index(TransactionType $destinationType, TransactionGroup $group) { @@ -101,7 +104,7 @@ class ConvertController extends Controller $groupTitle = $group->title ?? $first->description; $groupArray = $transformer->transformObject($group); - $subTitle = (string)trans('firefly.convert_to_' . $destinationType->type, ['description' => $groupTitle]); + $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: @@ -117,31 +120,40 @@ class ConvertController extends Controller 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', compact( - 'sourceType', 'destinationType', - 'group', 'groupTitle', 'groupArray', 'assets', 'validDepositSources', 'liabilities', - 'validWithdrawalDests', 'preFilled', - 'subTitle', 'subTitleIcon' - ) + 'transactions.convert', + compact( + 'sourceType', + 'destinationType', + 'group', + 'groupTitle', + 'groupArray', + 'assets', + 'validDepositSources', + 'liabilities', + 'validWithdrawalDests', + 'preFilled', + 'subTitle', + 'subTitleIcon' + ) ); } /** * Do the conversion. * - * @param Request $request - * @param TransactionType $destinationType + * @param Request $request + * @param TransactionType $destinationType * @param TransactionGroup $group * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector - * * @throws FireflyException + * @return RedirectResponse|Redirector + * */ public function postIndex(Request $request, TransactionType $destinationType, TransactionGroup $group) { @@ -165,156 +177,19 @@ class ConvertController extends Controller $group->refresh(); $this->correctTransfer($group); - session()->flash('success', (string)trans('firefly.converted_to_' . $destinationType->type)); + session()->flash('success', (string) trans('firefly.converted_to_' . $destinationType->type)); event(new UpdatedTransactionGroup($group)); return redirect(route('transactions.show', [$group->id])); } - /** - * @return array - * @throws \Exception - */ - private function getAssetAccounts(): array - { - // make repositories - /** @var AccountRepositoryInterface $repository */ - $repository = app(AccountRepositoryInterface::class); - $accountList = $repository->getActiveAccountsByType([AccountType::ASSET]); - $defaultCurrency = app('amount')->getDefaultCurrency(); - $grouped = []; - // group accounts: - /** @var Account $account */ - foreach ($accountList as $account) { - $balance = app('steam')->balance($account, new Carbon); - $currency = $repository->getAccountCurrency($account) ?? $defaultCurrency; - $role = (string)$repository->getMetaValue($account, 'account_role'); - if ('' === $role) { - $role = 'no_account_type'; // @codeCoverageIgnore - } - - $key = (string)trans('firefly.opt_group_' . $role); - $grouped[$key][$account->id] = $account->name . ' (' . app('amount')->formatAnything($currency, $balance, false) . ')'; - } - - return $grouped; - } - - /** - * @return array - * @throws \Exception - */ - private function getLiabilities(): array - { - // make repositories - /** @var AccountRepositoryInterface $repository */ - $repository = app(AccountRepositoryInterface::class); - $accountList = $repository->getActiveAccountsByType([AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]); - $defaultCurrency = app('amount')->getDefaultCurrency(); - $grouped = []; - // group accounts: - /** @var Account $account */ - foreach ($accountList as $account) { - $balance = app('steam')->balance($account, new Carbon); - $currency = $repository->getAccountCurrency($account) ?? $defaultCurrency; - $role = 'l_' . $account->accountType->type; - $key = (string)trans('firefly.opt_group_' . $role); - $grouped[$key][$account->id] = $account->name . ' (' . app('amount')->formatAnything($currency, $balance, false) . ')'; - } - - return $grouped; - } - - /** - * @return array - */ - private function getValidDepositSources(): array - { - // make repositories - /** @var AccountRepositoryInterface $repository */ - $repository = app(AccountRepositoryInterface::class); - $liabilityTypes = [AccountType::MORTGAGE, AccountType::DEBT, AccountType::CREDITCARD, AccountType::LOAN]; - $accountList = $repository - ->getActiveAccountsByType([AccountType::REVENUE, AccountType::CASH, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]); - $grouped = []; - // group accounts: - /** @var Account $account */ - foreach ($accountList as $account) { - $role = (string)$repository->getMetaValue($account, 'account_role'); - $name = $account->name; - if ('' === $role) { - $role = 'no_account_type'; // @codeCoverageIgnore - } - - // maybe it's a liability thing: - if (in_array($account->accountType->type, $liabilityTypes, true)) { - $role = 'l_' . $account->accountType->type; // @codeCoverageIgnore - } - if (AccountType::CASH === $account->accountType->type) { - // @codeCoverageIgnoreStart - $role = 'cash_account'; - $name = sprintf('(%s)', trans('firefly.cash')); - // @codeCoverageIgnoreEnd - } - if (AccountType::REVENUE === $account->accountType->type) { - $role = 'revenue_account'; // @codeCoverageIgnore - } - - $key = (string)trans('firefly.opt_group_' . $role); - $grouped[$key][$account->id] = $name; - } - - return $grouped; - } - - /** - * @return array - */ - private function getValidWithdrawalDests(): array - { - // make repositories - /** @var AccountRepositoryInterface $repository */ - $repository = app(AccountRepositoryInterface::class); - $liabilityTypes = [AccountType::MORTGAGE, AccountType::DEBT, AccountType::CREDITCARD, AccountType::LOAN]; - $accountList = $repository - ->getActiveAccountsByType([AccountType::EXPENSE, AccountType::CASH, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]); - $grouped = []; - // group accounts: - /** @var Account $account */ - foreach ($accountList as $account) { - $role = (string)$repository->getMetaValue($account, 'account_role'); - $name = $account->name; - if ('' === $role) { - $role = 'no_account_type'; // @codeCoverageIgnore - } - - // maybe it's a liability thing: - if (in_array($account->accountType->type, $liabilityTypes, true)) { - $role = 'l_' . $account->accountType->type; // @codeCoverageIgnore - } - if (AccountType::CASH === $account->accountType->type) { - // @codeCoverageIgnoreStart - $role = 'cash_account'; - $name = sprintf('(%s)', trans('firefly.cash')); - // @codeCoverageIgnoreEnd - } - if (AccountType::EXPENSE === $account->accountType->type) { - $role = 'expense_account'; // @codeCoverageIgnore - } - - $key = (string)trans('firefly.opt_group_' . $role); - $grouped[$key][$account->id] = $name; - } - - return $grouped; - } - /** * @param TransactionJournal $journal - * @param TransactionType $transactionType - * @param array $data - * @return TransactionJournal + * @param TransactionType $transactionType + * @param array $data + * * @throws FireflyException + * @return TransactionJournal */ private function convertJournal(TransactionJournal $journal, TransactionType $transactionType, array $data): TransactionJournal { @@ -329,9 +204,9 @@ class ConvertController extends Controller $destinationName = $data['destination_name'][$journal->id] ?? null; // double check its not an empty string. - $sourceId = '' === $sourceId || null === $sourceId ? null : (int)$sourceId; + $sourceId = '' === $sourceId || null === $sourceId ? null : (int) $sourceId; $sourceName = '' === $sourceName ? null : $sourceName; - $destinationId = '' === $destinationId || null === $destinationId ? null : (int)$destinationId; + $destinationId = '' === $destinationId || null === $destinationId ? null : (int) $destinationId; $destinationName = '' === $destinationName ? null : $destinationName; $validSource = $validator->validateSource($sourceId, $sourceName); $validDestination = $validator->validateDestination($destinationId, $destinationName); @@ -366,4 +241,142 @@ class ConvertController extends Controller private function correctTransfer(TransactionGroup $group): void { } + + /** + * @throws Exception + * @return array + */ + private function getAssetAccounts(): array + { + // make repositories + /** @var AccountRepositoryInterface $repository */ + $repository = app(AccountRepositoryInterface::class); + $accountList = $repository->getActiveAccountsByType([AccountType::ASSET]); + $defaultCurrency = app('amount')->getDefaultCurrency(); + $grouped = []; + // group accounts: + /** @var Account $account */ + foreach ($accountList as $account) { + $balance = app('steam')->balance($account, new Carbon); + $currency = $repository->getAccountCurrency($account) ?? $defaultCurrency; + $role = (string) $repository->getMetaValue($account, 'account_role'); + if ('' === $role) { + $role = 'no_account_type'; // @codeCoverageIgnore + } + + $key = (string) trans('firefly.opt_group_' . $role); + $grouped[$key][$account->id] = $account->name . ' (' . app('amount')->formatAnything($currency, $balance, false) . ')'; + } + + return $grouped; + } + + /** + * @throws Exception + * @return array + */ + private function getLiabilities(): array + { + // make repositories + /** @var AccountRepositoryInterface $repository */ + $repository = app(AccountRepositoryInterface::class); + $accountList = $repository->getActiveAccountsByType([AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]); + $defaultCurrency = app('amount')->getDefaultCurrency(); + $grouped = []; + // group accounts: + /** @var Account $account */ + foreach ($accountList as $account) { + $balance = app('steam')->balance($account, new Carbon); + $currency = $repository->getAccountCurrency($account) ?? $defaultCurrency; + $role = 'l_' . $account->accountType->type; + $key = (string) trans('firefly.opt_group_' . $role); + $grouped[$key][$account->id] = $account->name . ' (' . app('amount')->formatAnything($currency, $balance, false) . ')'; + } + + return $grouped; + } + + /** + * @return array + */ + private function getValidDepositSources(): array + { + // make repositories + /** @var AccountRepositoryInterface $repository */ + $repository = app(AccountRepositoryInterface::class); + $liabilityTypes = [AccountType::MORTGAGE, AccountType::DEBT, AccountType::CREDITCARD, AccountType::LOAN]; + $accountList = $repository + ->getActiveAccountsByType([AccountType::REVENUE, AccountType::CASH, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]); + $grouped = []; + // group accounts: + /** @var Account $account */ + foreach ($accountList as $account) { + $role = (string) $repository->getMetaValue($account, 'account_role'); + $name = $account->name; + if ('' === $role) { + $role = 'no_account_type'; // @codeCoverageIgnore + } + + // maybe it's a liability thing: + if (in_array($account->accountType->type, $liabilityTypes, true)) { + $role = 'l_' . $account->accountType->type; // @codeCoverageIgnore + } + if (AccountType::CASH === $account->accountType->type) { + // @codeCoverageIgnoreStart + $role = 'cash_account'; + $name = sprintf('(%s)', trans('firefly.cash')); + // @codeCoverageIgnoreEnd + } + if (AccountType::REVENUE === $account->accountType->type) { + $role = 'revenue_account'; // @codeCoverageIgnore + } + + $key = (string) trans('firefly.opt_group_' . $role); + $grouped[$key][$account->id] = $name; + } + + return $grouped; + } + + /** + * @return array + */ + private function getValidWithdrawalDests(): array + { + // make repositories + /** @var AccountRepositoryInterface $repository */ + $repository = app(AccountRepositoryInterface::class); + $liabilityTypes = [AccountType::MORTGAGE, AccountType::DEBT, AccountType::CREDITCARD, AccountType::LOAN]; + $accountList = $repository + ->getActiveAccountsByType([AccountType::EXPENSE, AccountType::CASH, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]); + $grouped = []; + // group accounts: + /** @var Account $account */ + foreach ($accountList as $account) { + $role = (string) $repository->getMetaValue($account, 'account_role'); + $name = $account->name; + if ('' === $role) { + $role = 'no_account_type'; // @codeCoverageIgnore + } + + // maybe it's a liability thing: + if (in_array($account->accountType->type, $liabilityTypes, true)) { + $role = 'l_' . $account->accountType->type; // @codeCoverageIgnore + } + if (AccountType::CASH === $account->accountType->type) { + // @codeCoverageIgnoreStart + $role = 'cash_account'; + $name = sprintf('(%s)', trans('firefly.cash')); + // @codeCoverageIgnoreEnd + } + if (AccountType::EXPENSE === $account->accountType->type) { + $role = 'expense_account'; // @codeCoverageIgnore + } + + $key = (string) trans('firefly.opt_group_' . $role); + $grouped[$key][$account->id] = $name; + } + + return $grouped; + } } diff --git a/app/Http/Controllers/Transaction/CreateController.php b/app/Http/Controllers/Transaction/CreateController.php index 6fa54509d9..5617a4a6ae 100644 --- a/app/Http/Controllers/Transaction/CreateController.php +++ b/app/Http/Controllers/Transaction/CreateController.php @@ -23,11 +23,14 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Transaction; - use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\TransactionGroup; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Services\Internal\Update\GroupCloneService; +use Illuminate\Contracts\View\Factory; +use Illuminate\Http\RedirectResponse; +use Illuminate\Routing\Redirector; +use Illuminate\View\View; /** * Class CreateController @@ -49,8 +52,7 @@ class CreateController extends Controller app('view')->share('uploadSize', $uploadSize); $this->middleware( static function ($request, $next) { - - app('view')->share('title', (string)trans('firefly.transactions')); + app('view')->share('title', (string) trans('firefly.transactions')); app('view')->share('mainTitleIcon', 'fa-repeat'); return $next($request); @@ -61,7 +63,7 @@ class CreateController extends Controller /** * @param TransactionGroup $group * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector */ public function cloneGroup(TransactionGroup $group) { @@ -84,20 +86,20 @@ class CreateController extends Controller * * @param string|null objectType * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * @return Factory|View */ public function create(?string $objectType) { app('preferences')->mark(); - $sourceId = (int)request()->get('source'); - $destinationId = (int)request()->get('destination'); + $sourceId = (int) request()->get('source'); + $destinationId = (int) request()->get('destination'); /** @var AccountRepositoryInterface $repository */ $repository = app(AccountRepositoryInterface::class); $cash = $repository->getCashAccount(); $preFilled = session()->has('preFilled') ? session('preFilled') : []; - $subTitle = (string)trans('breadcrumbs.create_new_transaction'); + $subTitle = (string) trans('breadcrumbs.create_new_transaction'); $subTitleIcon = 'fa-plus'; $optionalFields = app('preferences')->get('transaction_journal_optional_fields', [])->data; $allowedOpposingTypes = config('firefly.allowed_opposing_types'); @@ -112,11 +114,21 @@ class CreateController extends Controller return view( - 'transactions.create', compact( - 'subTitleIcon', 'cash', 'objectType', 'subTitle', 'defaultCurrency', 'previousUri', 'optionalFields', 'preFilled', - 'allowedOpposingTypes', - 'accountToTypes','sourceId','destinationId' - ) + 'transactions.create', + compact( + 'subTitleIcon', + 'cash', + 'objectType', + 'subTitle', + 'defaultCurrency', + 'previousUri', + 'optionalFields', + 'preFilled', + 'allowedOpposingTypes', + 'accountToTypes', + 'sourceId', + 'destinationId' + ) ); } } diff --git a/app/Http/Controllers/Transaction/DeleteController.php b/app/Http/Controllers/Transaction/DeleteController.php index 163431dc1b..585bc0a198 100644 --- a/app/Http/Controllers/Transaction/DeleteController.php +++ b/app/Http/Controllers/Transaction/DeleteController.php @@ -26,10 +26,10 @@ namespace FireflyIII\Http\Controllers\Transaction; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\TransactionGroup; -use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Repositories\TransactionGroup\TransactionGroupRepositoryInterface; use FireflyIII\Support\Http\Controllers\UserNavigation; use Illuminate\Http\RedirectResponse; +use Illuminate\Routing\Redirector; use Log; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use URL; @@ -45,6 +45,7 @@ class DeleteController extends Controller /** * IndexController constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -54,7 +55,7 @@ class DeleteController extends Controller // translations: $this->middleware( function ($request, $next) { - app('view')->share('title', (string)trans('firefly.transactions')); + app('view')->share('title', (string) trans('firefly.transactions')); app('view')->share('mainTitleIcon', 'fa-repeat'); $this->repository = app(TransactionGroupRepositoryInterface::class); @@ -69,7 +70,7 @@ class DeleteController extends Controller * * @param TransactionGroup $group * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|View + * @return RedirectResponse|Redirector|View */ public function delete(TransactionGroup $group) { @@ -84,7 +85,7 @@ class DeleteController extends Controller 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 = URL::previous(route('index')); // put previous url in session Log::debug('Will try to remember previous URI'); @@ -111,7 +112,7 @@ class DeleteController extends Controller 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])); $this->repository->destroy($group); diff --git a/app/Http/Controllers/Transaction/EditController.php b/app/Http/Controllers/Transaction/EditController.php index 1e99818055..eb749b8cd3 100644 --- a/app/Http/Controllers/Transaction/EditController.php +++ b/app/Http/Controllers/Transaction/EditController.php @@ -28,6 +28,8 @@ use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\TransactionGroup; use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Support\Http\Controllers\UserNavigation; +use Illuminate\Contracts\View\Factory; +use Illuminate\View\View; /** * Class EditController @@ -35,8 +37,10 @@ use FireflyIII\Support\Http\Controllers\UserNavigation; class EditController extends Controller { use UserNavigation; + /** * EditController constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -54,7 +58,7 @@ class EditController extends Controller $this->middleware( static function ($request, $next) { - app('view')->share('title', (string)trans('firefly.transactions')); + app('view')->share('title', (string) trans('firefly.transactions')); app('view')->share('mainTitleIcon', 'fa-repeat'); return $next($request); @@ -65,7 +69,8 @@ class EditController extends Controller /** * @param TransactionGroup $transactionGroup - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View + * + * @return Factory|View */ public function edit(TransactionGroup $transactionGroup) { diff --git a/app/Http/Controllers/Transaction/IndexController.php b/app/Http/Controllers/Transaction/IndexController.php index 3f2ffa3704..46b42ad72d 100644 --- a/app/Http/Controllers/Transaction/IndexController.php +++ b/app/Http/Controllers/Transaction/IndexController.php @@ -25,11 +25,14 @@ namespace FireflyIII\Http\Controllers\Transaction; use Carbon\Carbon; +use Exception; use FireflyIII\Helpers\Collector\GroupCollectorInterface; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Support\Http\Controllers\PeriodOverview; +use Illuminate\Contracts\View\Factory; use Illuminate\Http\Request; +use Illuminate\View\View; /** * Class IndexController @@ -43,6 +46,7 @@ class IndexController extends Controller /** * IndexController constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -53,7 +57,7 @@ class IndexController extends Controller $this->middleware( function ($request, $next) { app('view')->share('mainTitleIcon', 'fa-credit-card'); - app('view')->share('title', (string)trans('firefly.accounts')); + app('view')->share('title', (string) trans('firefly.accounts')); $this->repository = app(JournalRepositoryInterface::class); @@ -65,20 +69,20 @@ class IndexController extends Controller /** * Index for a range of transactions. * - * @param Request $request - * @param string $objectType + * @param Request $request + * @param string $objectType * @param Carbon|null $start * @param Carbon|null $end * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View - * @throws \Exception + * @throws Exception + * @return Factory|View */ public function index(Request $request, string $objectType, Carbon $start = null, Carbon $end = null) { $subTitleIcon = config('firefly.transactionIconsByType.' . $objectType); $types = config('firefly.transactionTypesByType.' . $objectType); - $page = (int)$request->get('page'); - $pageSize = (int)app('preferences')->get('listPageSize', 50)->data; + $page = (int) $request->get('page'); + $pageSize = (int) app('preferences')->get('listPageSize', 50)->data; if (null === $start) { $start = session('start'); $end = session('end'); @@ -91,7 +95,7 @@ class IndexController extends Controller $path = route('transactions.index', [$objectType, $start->format('Y-m-d'), $end->format('Y-m-d')]); $startStr = $start->formatLocalized($this->monthAndDayFormat); $endStr = $end->formatLocalized($this->monthAndDayFormat); - $subTitle = (string)trans(sprintf('firefly.title_%s_between', $objectType), ['start' => $startStr, 'end' => $endStr]); + $subTitle = (string) trans(sprintf('firefly.title_%s_between', $objectType), ['start' => $startStr, 'end' => $endStr]); $firstJournal = $this->repository->firstNull(); $startPeriod = null === $firstJournal ? new Carbon : $firstJournal->date; @@ -119,9 +123,10 @@ class IndexController extends Controller * Index for ALL transactions. * * @param Request $request - * @param string $objectType - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View - * @throws \Exception + * @param string $objectType + * + * @throws Exception + * @return Factory|View */ public function indexAll(Request $request, string $objectType) { @@ -131,13 +136,13 @@ class IndexController extends Controller $subTitleIcon = config('firefly.transactionIconsByWhat.' . $objectType); $types = config('firefly.transactionTypesByWhat.' . $objectType); - $page = (int)$request->get('page'); - $pageSize = (int)app('preferences')->get('listPageSize', 50)->data; + $page = (int) $request->get('page'); + $pageSize = (int) app('preferences')->get('listPageSize', 50)->data; $path = route('transactions.index.all', [$objectType]); $first = $repository->firstNull(); $start = null === $first ? new Carbon : $first->date; $end = new Carbon; - $subTitle = (string)trans('firefly.all_' . $objectType); + $subTitle = (string) trans('firefly.all_' . $objectType); /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); diff --git a/app/Http/Controllers/Transaction/LinkController.php b/app/Http/Controllers/Transaction/LinkController.php index f1ff8362a2..c9df232c4b 100644 --- a/app/Http/Controllers/Transaction/LinkController.php +++ b/app/Http/Controllers/Transaction/LinkController.php @@ -29,6 +29,8 @@ use FireflyIII\Models\TransactionJournalLink; use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Repositories\LinkType\LinkTypeRepositoryInterface; use Illuminate\Contracts\View\Factory; +use Illuminate\Http\RedirectResponse; +use Illuminate\Routing\Redirector; use Illuminate\View\View; use Log; use URL; @@ -45,6 +47,7 @@ class LinkController extends Controller /** * LinkController constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -53,7 +56,7 @@ class LinkController extends Controller // some useful repositories: $this->middleware( function ($request, $next) { - app('view')->share('title', (string)trans('firefly.transactions')); + app('view')->share('title', (string) trans('firefly.transactions')); app('view')->share('mainTitleIcon', 'fa-repeat'); $this->journalRepository = app(JournalRepositoryInterface::class); @@ -64,17 +67,6 @@ class LinkController extends Controller ); } - /** - * @param TransactionJournal $journal - * @return Factory|View - */ - public function modal(TransactionJournal $journal) - { - $linkTypes = $this->repository->get(); - - return view('transactions.links.modal', compact('journal', 'linkTypes')); - } - /** * Delete a link. * @@ -85,7 +77,7 @@ class LinkController extends Controller public function delete(TransactionJournalLink $link) { $subTitleIcon = 'fa-link'; - $subTitle = (string)trans('breadcrumbs.delete_journal_link'); + $subTitle = (string) trans('breadcrumbs.delete_journal_link'); $this->rememberPreviousUri('journal_links.delete.uri'); return view('transactions.links.delete', compact('link', 'subTitle', 'subTitleIcon')); @@ -96,16 +88,28 @@ class LinkController extends Controller * * @param TransactionJournalLink $link * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector */ public function destroy(TransactionJournalLink $link) { $this->repository->destroyLink($link); - session()->flash('success', (string)trans('firefly.deleted_link')); + session()->flash('success', (string) trans('firefly.deleted_link')); app('preferences')->mark(); - return redirect((string)session('journal_links.delete.uri')); + return redirect((string) session('journal_links.delete.uri')); + } + + /** + * @param TransactionJournal $journal + * + * @return Factory|View + */ + public function modal(TransactionJournal $journal) + { + $linkTypes = $this->repository->get(); + + return view('transactions.links.modal', compact('journal', 'linkTypes')); } /** @@ -114,16 +118,16 @@ class LinkController extends Controller * @param JournalLinkRequest $request * @param TransactionJournal $journal * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector */ public function store(JournalLinkRequest $request, TransactionJournal $journal) { $linkInfo = $request->getLinkInfo(); Log::debug('We are here (store)'); - $other = $this->journalRepository->findNull($linkInfo['transaction_journal_id']); + $other = $this->journalRepository->findNull($linkInfo['transaction_journal_id']); if (null === $other) { - session()->flash('error', (string)trans('firefly.invalid_link_selection')); + session()->flash('error', (string) trans('firefly.invalid_link_selection')); return redirect(route('transactions.show', [$journal->transaction_group_id])); } @@ -131,19 +135,19 @@ class LinkController extends Controller $alreadyLinked = $this->repository->findLink($journal, $other); if ($other->id === $journal->id) { - session()->flash('error', (string)trans('firefly.journals_link_to_self')); + session()->flash('error', (string) trans('firefly.journals_link_to_self')); return redirect(route('transactions.show', [$journal->transaction_group_id])); } if ($alreadyLinked) { - session()->flash('error', (string)trans('firefly.journals_error_linked')); + session()->flash('error', (string) trans('firefly.journals_error_linked')); return redirect(route('transactions.show', [$journal->transaction_group_id])); } Log::debug(sprintf('Journal is %d, opposing is %d', $journal->id, $other->id)); $this->repository->storeLink($linkInfo, $other, $journal); - session()->flash('success', (string)trans('firefly.journals_linked')); + session()->flash('success', (string) trans('firefly.journals_linked')); return redirect(route('transactions.show', [$journal->transaction_group_id])); } @@ -153,7 +157,7 @@ class LinkController extends Controller * * @param TransactionJournalLink $link * - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * @return RedirectResponse|Redirector */ public function switchLink(TransactionJournalLink $link) { diff --git a/app/Http/Controllers/Transaction/MassController.php b/app/Http/Controllers/Transaction/MassController.php index bfa0f2194e..977028bdb3 100644 --- a/app/Http/Controllers/Transaction/MassController.php +++ b/app/Http/Controllers/Transaction/MassController.php @@ -35,6 +35,8 @@ use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Services\Internal\Update\JournalUpdateService; +use Illuminate\Http\RedirectResponse; +use Illuminate\Routing\Redirector; use Illuminate\View\View as IlluminateView; use InvalidArgumentException; use Log; @@ -50,6 +52,7 @@ class MassController extends Controller /** * MassController constructor. + * * @codeCoverageIgnore */ public function __construct() @@ -58,9 +61,10 @@ class MassController extends Controller $this->middleware( function ($request, $next) { - app('view')->share('title', (string)trans('firefly.transactions')); + app('view')->share('title', (string) trans('firefly.transactions')); app('view')->share('mainTitleIcon', 'fa-repeat'); $this->repository = app(JournalRepositoryInterface::class); + return $next($request); } ); @@ -75,7 +79,7 @@ class MassController extends Controller */ public function delete(array $journals): IlluminateView { - $subTitle = (string)trans('firefly.mass_delete_journals'); + $subTitle = (string) trans('firefly.mass_delete_journals'); // put previous url in session $this->rememberPreviousUri('transactions.mass-delete.uri'); @@ -100,8 +104,8 @@ class MassController extends Controller foreach ($ids as $journalId) { /** @var TransactionJournal $journal */ - $journal = $this->repository->findNull((int)$journalId); - if (null !== $journal && (int)$journalId === $journal->id) { + $journal = $this->repository->findNull((int) $journalId); + if (null !== $journal && (int) $journalId === $journal->id) { $this->repository->destroyJournal($journal); ++$count; } @@ -110,7 +114,7 @@ class MassController extends Controller app('preferences')->mark(); - session()->flash('success', (string)trans('firefly.mass_deleted_transactions_success', ['amount' => $count])); + session()->flash('success', (string) trans('firefly.mass_deleted_transactions_success', ['amount' => $count])); // redirect to previous URL: return redirect($this->getPreviousUri('transactions.mass-delete.uri')); @@ -125,7 +129,7 @@ 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 $repository */ $repository = app(AccountRepositoryInterface::class); @@ -158,8 +162,9 @@ class MassController extends Controller * Mass update of journals. * * @param MassEditJournalRequest $request - * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector + * * @throws FireflyException + * @return RedirectResponse|Redirector */ public function update(MassEditJournalRequest $request) { @@ -171,7 +176,7 @@ class MassController extends Controller $count = 0; /** @var string $journalId */ foreach ($journalIds as $journalId) { - $integer = (int)$journalId; + $integer = (int) $journalId; try { $this->updateJournal($integer, $request); $count++; @@ -183,15 +188,86 @@ class MassController extends Controller } app('preferences')->mark(); - session()->flash('success', (string)trans('firefly.mass_edited_transactions_success', ['amount' => $count])); + session()->flash('success', (string) trans('firefly.mass_edited_transactions_success', ['amount' => $count])); // redirect to previous URL: return redirect($this->getPreviousUri('transactions.mass-edit.uri')); } /** - * @param int $journalId * @param MassEditJournalRequest $request + * @param int $journalId + * @param string $string + * + * @return Carbon|null + * @codeCoverageIgnore + */ + private function getDateFromRequest(MassEditJournalRequest $request, int $journalId, string $string): ?Carbon + { + $value = $request->get($string); + if (!is_array($value)) { + return null; + } + if (!isset($value[$journalId])) { + return null; + } + try { + $carbon = Carbon::parse($value[$journalId]); + } catch (InvalidArgumentException $e) { + $e->getMessage(); + + return null; + } + + return $carbon; + } + + /** + * @param MassEditJournalRequest $request + * @param int $journalId + * @param string $string + * + * @return int|null + * @codeCoverageIgnore + */ + private function getIntFromRequest(MassEditJournalRequest $request, int $journalId, string $string): ?int + { + $value = $request->get($string); + if (!is_array($value)) { + return null; + } + if (!isset($value[$journalId])) { + return null; + } + + return (int) $value[$journalId]; + } + + /** + * @param MassEditJournalRequest $request + * @param int $journalId + * @param string $string + * + * @return string|null + * @codeCoverageIgnore + */ + private function getStringFromRequest(MassEditJournalRequest $request, int $journalId, string $string): ?string + { + $value = $request->get($string); + if (!is_array($value)) { + return null; + } + if (!isset($value[$journalId])) { + return null; + } + + return (string) $value[$journalId]; + } + + /** + * @param int $journalId + * @param MassEditJournalRequest $request + * * @throws FireflyException */ private function updateJournal(int $journalId, MassEditJournalRequest $request): void @@ -224,71 +300,4 @@ class MassController extends Controller // trigger rules event(new UpdatedTransactionGroup($journal->transactionGroup)); } - - /** - * @param MassEditJournalRequest $request - * @param int $journalId - * @param string $string - * @return int|null - * @codeCoverageIgnore - */ - private function getIntFromRequest(MassEditJournalRequest $request, int $journalId, string $string): ?int - { - $value = $request->get($string); - if (!is_array($value)) { - return null; - } - if (!isset($value[$journalId])) { - return null; - } - - return (int)$value[$journalId]; - } - - /** - * @param MassEditJournalRequest $request - * @param int $journalId - * @param string $string - * @return string|null - * @codeCoverageIgnore - */ - private function getStringFromRequest(MassEditJournalRequest $request, int $journalId, string $string): ?string - { - $value = $request->get($string); - if (!is_array($value)) { - return null; - } - if (!isset($value[$journalId])) { - return null; - } - - return (string)$value[$journalId]; - } - - /** - * @param MassEditJournalRequest $request - * @param int $journalId - * @param string $string - * @return Carbon|null - * @codeCoverageIgnore - */ - private function getDateFromRequest(MassEditJournalRequest $request, int $journalId, string $string): ?Carbon - { - $value = $request->get($string); - if (!is_array($value)) { - return null; - } - if (!isset($value[$journalId])) { - return null; - } - try { - $carbon = Carbon::parse($value[$journalId]); - } catch (InvalidArgumentException $e) { - $e->getMessage(); - - return null; - } - - return $carbon; - } } diff --git a/app/Http/Controllers/Transaction/ShowController.php b/app/Http/Controllers/Transaction/ShowController.php index acef814d9f..82d5710481 100644 --- a/app/Http/Controllers/Transaction/ShowController.php +++ b/app/Http/Controllers/Transaction/ShowController.php @@ -23,15 +23,17 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Transaction; - use FireflyIII\Exceptions\FireflyException; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Models\TransactionGroup; use FireflyIII\Models\TransactionJournal; use FireflyIII\Repositories\TransactionGroup\TransactionGroupRepositoryInterface; use FireflyIII\Transformers\TransactionGroupTransformer; +use Illuminate\Contracts\View\Factory; +use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Support\Str; +use Illuminate\View\View; use Symfony\Component\HttpFoundation\ParameterBag; /** @@ -54,7 +56,7 @@ class ShowController extends Controller function ($request, $next) { $this->repository = app(TransactionGroupRepositoryInterface::class); - app('view')->share('title', (string)trans('firefly.transactions')); + app('view')->share('title', (string) trans('firefly.transactions')); app('view')->share('mainTitleIcon', 'fa-exchange'); return $next($request); @@ -65,7 +67,7 @@ class ShowController extends Controller /** * @param TransactionGroup $transactionGroup * - * @return \Illuminate\Http\JsonResponse + * @return JsonResponse */ public function debugShow(TransactionGroup $transactionGroup) { @@ -75,20 +77,20 @@ class ShowController extends Controller /** * @param TransactionGroup $transactionGroup * - * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @throws FireflyException + * @return Factory|View */ public function show(Request $request, TransactionGroup $transactionGroup) { /** @var TransactionJournal $first */ - $first = $transactionGroup->transactionJournals()->first(['transaction_journals.*']); - $splits = $transactionGroup->transactionJournals()->count(); + $first = $transactionGroup->transactionJournals()->first(['transaction_journals.*']); + $splits = $transactionGroup->transactionJournals()->count(); - if(null === $first) { + if (null === $first) { throw new FireflyException('This transaction is broken :(.'); } - $type = (string)trans(sprintf('firefly.%s',$first->transactionType->type)); + $type = (string) trans(sprintf('firefly.%s', $first->transactionType->type)); $title = 1 === $splits ? $first->description : $transactionGroup->title; $subTitle = sprintf('%s: "%s"', $type, $title); @@ -113,10 +115,19 @@ class ShowController extends Controller $links = $this->repository->getLinks($transactionGroup); return view( - 'transactions.show', compact( - 'transactionGroup', 'amounts', 'first', 'type', 'subTitle', 'splits', 'groupArray', - 'events', 'attachments', 'links' - ) + 'transactions.show', + compact( + 'transactionGroup', + 'amounts', + 'first', + 'type', + 'subTitle', + 'splits', + 'groupArray', + 'events', + 'attachments', + 'links' + ) ); } diff --git a/app/Http/Kernel.php b/app/Http/Kernel.php index f56b7ec0f2..2c538f94d0 100644 --- a/app/Http/Kernel.php +++ b/app/Http/Kernel.php @@ -71,7 +71,7 @@ class Kernel extends HttpKernel TrimStrings::class, ConvertEmptyStringsToNull::class, TrustProxies::class, - InstallationId::class + InstallationId::class, ]; /** diff --git a/app/Http/Middleware/Authenticate.php b/app/Http/Middleware/Authenticate.php index f961a7f8d9..87e9e2cc0c 100644 --- a/app/Http/Middleware/Authenticate.php +++ b/app/Http/Middleware/Authenticate.php @@ -29,6 +29,7 @@ use FireflyIII\Exceptions\FireflyException; use Illuminate\Auth\AuthenticationException; use Illuminate\Contracts\Auth\Factory as Auth; use Illuminate\Database\QueryException; +use Illuminate\Http\Request; /** * Class Authenticate @@ -38,14 +39,14 @@ class Authenticate /** * The authentication factory instance. * - * @var \Illuminate\Contracts\Auth\Factory + * @var Auth */ protected $auth; /** * Create a new middleware instance. * - * @param \Illuminate\Contracts\Auth\Factory $auth + * @param Auth $auth * * @return void */ @@ -57,14 +58,14 @@ class Authenticate /** * Handle an incoming request. * - * @param \Illuminate\Http\Request $request - * @param \Closure $next - * @param string[] ...$guards - * - * @return mixed + * @param Request $request + * @param Closure $next + * @param string[] ...$guards * * @throws AuthenticationException * @throws FireflyException + * @return mixed + * */ public function handle($request, Closure $next, ...$guards) { @@ -78,11 +79,11 @@ class Authenticate * Determine if the user is logged in to any of the given guards. * * @param $request - * @param array $guards + * @param array $guards * - * @return mixed * @throws AuthenticationException * @throws FireflyException + * @return mixed */ protected function authenticate($request, array $guards) { @@ -96,10 +97,10 @@ class Authenticate // do an extra check on user object. /** @noinspection PhpUndefinedMethodInspection */ $user = $this->auth->authenticate(); - if (1 === (int)$user->blocked) { - $message = (string)trans('firefly.block_account_logout'); + if (1 === (int) $user->blocked) { + $message = (string) trans('firefly.block_account_logout'); if ('email_changed' === $user->blocked_code) { - $message = (string)trans('firefly.email_changed_logout'); + $message = (string) trans('firefly.email_changed_logout'); } app('session')->flash('logoutMessage', $message); /** @noinspection PhpUndefinedMethodInspection */ diff --git a/app/Http/Middleware/Binder.php b/app/Http/Middleware/Binder.php index 399cc4b416..3785604353 100644 --- a/app/Http/Middleware/Binder.php +++ b/app/Http/Middleware/Binder.php @@ -25,6 +25,7 @@ namespace FireflyIII\Http\Middleware; use Closure; use FireflyIII\Support\Domain; use Illuminate\Contracts\Auth\Factory as Auth; +use Illuminate\Http\Request; use Illuminate\Routing\Route; /** @@ -35,7 +36,7 @@ class Binder /** * The authentication factory instance. * - * @var \Illuminate\Contracts\Auth\Factory + * @var Auth */ protected $auth; /** @@ -48,7 +49,7 @@ class Binder /** * Binder constructor. * - * @param \Illuminate\Contracts\Auth\Factory $auth + * @param Auth $auth */ public function __construct(Auth $auth) { @@ -60,8 +61,8 @@ class Binder /** * Handle an incoming request. * - * @param \Illuminate\Http\Request $request - * @param \Closure $next + * @param Request $request + * @param Closure $next * * @return mixed * diff --git a/app/Http/Middleware/InstallationId.php b/app/Http/Middleware/InstallationId.php index 5e7848de6b..8e326da273 100644 --- a/app/Http/Middleware/InstallationId.php +++ b/app/Http/Middleware/InstallationId.php @@ -41,21 +41,21 @@ class InstallationId * @param \Illuminate\Http\Request $request * @param Closure $next * - * @return mixed - * * @throws FireflyException * + * @return mixed + * */ public function handle($request, Closure $next) { $config = app('fireflyconfig')->get('installation_id', null); if (null === $config) { $uuid5 = Uuid::uuid5(Uuid::NAMESPACE_URL, 'firefly-iii.org'); - $uniqueId = (string)$uuid5; + $uniqueId = (string) $uuid5; Log::info(sprintf('Created Firefly III installation ID %s', $uniqueId)); app('fireflyconfig')->set('installation_id', $uniqueId); } return $next($request); } -} \ No newline at end of file +} diff --git a/app/Http/Middleware/Installer.php b/app/Http/Middleware/Installer.php index 7b28bbce1f..01bf1100c9 100644 --- a/app/Http/Middleware/Installer.php +++ b/app/Http/Middleware/Installer.php @@ -29,6 +29,7 @@ use DB; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Support\System\OAuthKeys; use Illuminate\Database\QueryException; +use Illuminate\Http\Request; use Log; /** @@ -42,13 +43,13 @@ class Installer /** * Handle an incoming request. * - * @param \Illuminate\Http\Request $request - * @param \Closure $next - * - * @return mixed + * @param Request $request + * @param Closure $next * * @throws FireflyException * + * @return mixed + * */ public function handle($request, Closure $next) { @@ -107,8 +108,8 @@ class Installer /** * Check if the tables are created and accounted for. * - * @return bool * @throws FireflyException + * @return bool */ private function hasNoTables(): bool { @@ -127,14 +128,12 @@ class Installer Log::warning('There are no Firefly III tables present. Redirect to migrate routine.'); return true; - } throw new FireflyException(sprintf('Could not access the database: %s', $message)); } Log::debug('Everything seems OK with the tables.'); return false; - } /** @@ -145,12 +144,14 @@ class Installer private function oldDBVersion(): bool { // older version in config than database? - $configVersion = (int)config('firefly.db_version'); - $dbVersion = (int)app('fireflyconfig')->getFresh('db_version', 1)->data; + $configVersion = (int) config('firefly.db_version'); + $dbVersion = (int) app('fireflyconfig')->getFresh('db_version', 1)->data; if ($configVersion > $dbVersion) { Log::warning( sprintf( - 'The current configured version (%d) is older than the required version (%d). Redirect to migrate routine.', $dbVersion, $configVersion + 'The current configured version (%d) is older than the required version (%d). Redirect to migrate routine.', + $dbVersion, + $configVersion ) ); @@ -169,12 +170,14 @@ class Installer private function oldVersion(): bool { // version compare thing. - $configVersion = (string)config('firefly.version'); - $dbVersion = (string)app('fireflyconfig')->getFresh('ff3_version', '1.0')->data; + $configVersion = (string) config('firefly.version'); + $dbVersion = (string) app('fireflyconfig')->getFresh('ff3_version', '1.0')->data; if (1 === version_compare($configVersion, $dbVersion)) { Log::warning( sprintf( - 'The current configured Firefly III version (%s) is older than the required version (%s). Redirect to migrate routine.', $dbVersion, $configVersion + 'The current configured Firefly III version (%s) is older than the required version (%s). Redirect to migrate routine.', + $dbVersion, + $configVersion ) ); @@ -184,5 +187,4 @@ class Installer return false; } - } diff --git a/app/Http/Middleware/InterestingMessage.php b/app/Http/Middleware/InterestingMessage.php index f84db776b6..e0fb80cf63 100644 --- a/app/Http/Middleware/InterestingMessage.php +++ b/app/Http/Middleware/InterestingMessage.php @@ -38,8 +38,8 @@ class InterestingMessage /** * Flashes the user an interesting message if the URL parameters warrant it. * - * @param Request $request - * @param \Closure $next + * @param Request $request + * @param Closure $next * * @return mixed * @@ -85,7 +85,7 @@ class InterestingMessage // send message about newly created transaction group. /** @var 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; @@ -101,12 +101,12 @@ class InterestingMessage $title = $count > 1 ? $group->title : $journal->description; if ('created' === $message) { session()->flash('success_uri', 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($journal->transactionType->type); session()->flash('success_uri', 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])); } } diff --git a/app/Http/Middleware/IsAdmin.php b/app/Http/Middleware/IsAdmin.php index df87ecd1e6..8386c3fe93 100644 --- a/app/Http/Middleware/IsAdmin.php +++ b/app/Http/Middleware/IsAdmin.php @@ -36,9 +36,9 @@ class IsAdmin /** * Handle an incoming request. Must be admin. * - * @param \Illuminate\Http\Request $request - * @param \Closure $next - * @param string|null $guard + * @param Request $request + * @param Closure $next + * @param string|null $guard * * @return mixed */ diff --git a/app/Http/Middleware/IsDemoUser.php b/app/Http/Middleware/IsDemoUser.php index 62b773fb06..8d419b4bc0 100644 --- a/app/Http/Middleware/IsDemoUser.php +++ b/app/Http/Middleware/IsDemoUser.php @@ -36,8 +36,8 @@ class IsDemoUser /** * Handle an incoming request. * - * @param \Illuminate\Http\Request $request - * @param \Closure $next + * @param Request $request + * @param Closure $next * * @return mixed */ @@ -53,7 +53,7 @@ class IsDemoUser $repository = app(UserRepositoryInterface::class); if ($repository->hasRole($user, 'demo')) { Log::info('User is a demo user.'); - $request->session()->flash('info', (string)trans('firefly.not_available_demo_user')); + $request->session()->flash('info', (string) trans('firefly.not_available_demo_user')); $current = $request->url(); $previous = $request->session()->previousUrl(); if ($current !== $previous) { diff --git a/app/Http/Middleware/IsSandStormUser.php b/app/Http/Middleware/IsSandStormUser.php index 9ad68c59cb..dc5065d8e8 100644 --- a/app/Http/Middleware/IsSandStormUser.php +++ b/app/Http/Middleware/IsSandStormUser.php @@ -35,9 +35,9 @@ class IsSandStormUser /** * Handle an incoming request. May not be a limited user (ie. Sandstorm env. or demo user). * - * @param \Illuminate\Http\Request $request - * @param \Closure $next - * @param string|null $guard + * @param Request $request + * @param Closure $next + * @param string|null $guard * * @return mixed */ @@ -48,8 +48,8 @@ class IsSandStormUser return $next($request); } - if (1 === (int)getenv('SANDSTORM')) { - app('session')->flash('warning', (string)trans('firefly.sandstorm_not_available')); + if (1 === (int) getenv('SANDSTORM')) { + app('session')->flash('warning', (string) trans('firefly.sandstorm_not_available')); return response()->redirectTo(route('index')); } diff --git a/app/Http/Middleware/Range.php b/app/Http/Middleware/Range.php index 915b275c0b..b73748412b 100644 --- a/app/Http/Middleware/Range.php +++ b/app/Http/Middleware/Range.php @@ -36,8 +36,8 @@ class Range /** * Handle an incoming request. * - * @param \Illuminate\Http\Request $request - * @param Closure $next + * @param Request $request + * @param Closure $next * * @return mixed */ @@ -77,7 +77,7 @@ class Range $lang = $pref->data; App::setLocale($lang); Carbon::setLocale(substr($lang, 0, 2)); - $locale = explode(',', (string)trans('config.locale')); + $locale = explode(',', (string) trans('config.locale')); $locale = array_map('trim', $locale); setlocale(LC_TIME, $locale); @@ -89,12 +89,12 @@ class Range } // save some formats: - $monthAndDayFormat = (string)trans('config.month_and_day'); - $dateTimeFormat = (string)trans('config.date_time'); + $monthAndDayFormat = (string) trans('config.month_and_day'); + $dateTimeFormat = (string) trans('config.date_time'); $defaultCurrency = app('amount')->getDefaultCurrency(); // also format for moment JS: - $madMomentJS = (string)trans('config.month_and_day_moment_js'); + $madMomentJS = (string) trans('config.month_and_day_moment_js'); app('view')->share('madMomentJS', $madMomentJS); app('view')->share('monthAndDayFormat', $monthAndDayFormat); diff --git a/app/Http/Middleware/RedirectIfAuthenticated.php b/app/Http/Middleware/RedirectIfAuthenticated.php index 07db56c63e..9b17c7f49a 100644 --- a/app/Http/Middleware/RedirectIfAuthenticated.php +++ b/app/Http/Middleware/RedirectIfAuthenticated.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Middleware; use Closure; +use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; /** @@ -35,9 +36,9 @@ class RedirectIfAuthenticated /** * Handle an incoming request. * - * @param \Illuminate\Http\Request $request - * @param \Closure $next - * @param string|null $guard + * @param Request $request + * @param Closure $next + * @param string|null $guard * * @return mixed */ diff --git a/app/Http/Middleware/Sandstorm.php b/app/Http/Middleware/Sandstorm.php index 96ce85bfa1..3a2dae74f8 100644 --- a/app/Http/Middleware/Sandstorm.php +++ b/app/Http/Middleware/Sandstorm.php @@ -39,16 +39,16 @@ class Sandstorm * Detects if is using Sandstorm, and responds by logging the user * in and/or creating an account. * - * @param \Illuminate\Http\Request $request - * @param \Closure $next - * @param string|null $guard + * @param Request $request + * @param Closure $next + * @param string|null $guard * * @return mixed */ public function handle(Request $request, Closure $next, $guard = null) { // is in Sandstorm environment? - $sandstorm = 1 === (int)getenv('SANDSTORM'); + $sandstorm = 1 === (int) getenv('SANDSTORM'); app('view')->share('SANDSTORM', $sandstorm); if (!$sandstorm) { return $next($request); @@ -58,7 +58,7 @@ class Sandstorm if (Auth::guard($guard)->guest()) { /** @var UserRepositoryInterface $repository */ $repository = app(UserRepositoryInterface::class); - $userId = (string)$request->header('X-Sandstorm-User-Id'); + $userId = (string) $request->header('X-Sandstorm-User-Id'); // catch anonymous: $userId = '' === $userId ? 'anonymous' : $userId; diff --git a/app/Http/Middleware/SecureHeaders.php b/app/Http/Middleware/SecureHeaders.php index 2274174070..820e01b994 100644 --- a/app/Http/Middleware/SecureHeaders.php +++ b/app/Http/Middleware/SecureHeaders.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Middleware; use Closure; +use Exception; use Illuminate\Http\Request; /** @@ -35,11 +36,11 @@ class SecureHeaders /** * Handle an incoming request. * - * @param \Illuminate\Http\Request $request - * @param \Closure $next + * @param Request $request + * @param Closure $next * + * @throws Exception * @return mixed - * @throws \Exception */ public function handle(Request $request, Closure $next) { @@ -105,8 +106,8 @@ class SecureHeaders */ private function getTrackingScriptSource(): string { - if ('' !== (string)config('firefly.tracker_site_id') && '' !== (string)config('firefly.tracker_url')) { - return (string)config('firefly.tracker_url'); + if ('' !== (string) config('firefly.tracker_site_id') && '' !== (string) config('firefly.tracker_url')) { + return (string) config('firefly.tracker_url'); } return ''; diff --git a/app/Http/Middleware/StartFireflySession.php b/app/Http/Middleware/StartFireflySession.php index 09813c752a..b8102a32b4 100644 --- a/app/Http/Middleware/StartFireflySession.php +++ b/app/Http/Middleware/StartFireflySession.php @@ -22,6 +22,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Middleware; +use Illuminate\Contracts\Session\Session; use Illuminate\Http\Request; use Illuminate\Session\Middleware\StartSession; use Log; @@ -36,8 +37,8 @@ class StartFireflySession extends StartSession /** * Store the current URL for the request if necessary. * - * @param \Illuminate\Http\Request $request - * @param \Illuminate\Contracts\Session\Session $session + * @param Request $request + * @param Session $session */ protected function storeCurrentUrl(Request $request, $session): void { @@ -45,18 +46,20 @@ class StartFireflySession extends StartSession $isScriptPage = strpos($uri, 'jscript'); $isDeletePage = strpos($uri, 'delete'); $isLoginPage = strpos($uri, '/login'); + $isJsonPage = strpos($uri, '/json'); // also stop remembering "delete" URL's. if (false === $isScriptPage && false === $isDeletePage && false === $isLoginPage + && false === $isJsonPage && 'GET' === $request->method() && !$request->ajax()) { $session->setPreviousUrl($uri); - //Log::debug(sprintf('Will set previous URL to %s', $uri)); + Log::debug(sprintf('Will set previous URL to %s', $uri)); return; } - //Log::debug(sprintf('Will NOT set previous URL to %s', $uri)); + Log::debug(sprintf('Will NOT set previous URL to %s', $uri)); } } diff --git a/app/Http/Middleware/TrustProxies.php b/app/Http/Middleware/TrustProxies.php index 67336284f9..4be207df25 100644 --- a/app/Http/Middleware/TrustProxies.php +++ b/app/Http/Middleware/TrustProxies.php @@ -43,7 +43,7 @@ class TrustProxies extends Middleware */ public function __construct(Repository $config) { - $trustedProxies = (string)config('firefly.trusted_proxies'); + $trustedProxies = (string) config('firefly.trusted_proxies'); $this->proxies = explode(',', $trustedProxies); if ('**' === $trustedProxies) { $this->proxies = '**'; diff --git a/app/Http/Requests/AccountFormRequest.php b/app/Http/Requests/AccountFormRequest.php index 1a40b91c22..0ad9dd03e2 100644 --- a/app/Http/Requests/AccountFormRequest.php +++ b/app/Http/Requests/AccountFormRequest.php @@ -112,10 +112,10 @@ class AccountFormRequest extends Request 'what' => 'in:' . $types, 'interest_period' => 'in:daily,monthly,yearly', ]; - $rules = Location::requestRules($rules); + $rules = Location::requestRules($rules); if ('liabilities' === $this->get('objectType')) { - $rules['opening_balance'] = ['numeric', 'required','max:1000000000']; + $rules['opening_balance'] = ['numeric', 'required', 'max:1000000000']; $rules['opening_balance_date'] = 'date|required'; } diff --git a/app/Http/Requests/BudgetFormStoreRequest.php b/app/Http/Requests/BudgetFormStoreRequest.php new file mode 100644 index 0000000000..330c000632 --- /dev/null +++ b/app/Http/Requests/BudgetFormStoreRequest.php @@ -0,0 +1,94 @@ +. + */ +declare(strict_types=1); + +namespace FireflyIII\Http\Requests; + +use Illuminate\Validation\Validator; + +/** + * @codeCoverageIgnore + * Class BudgetFormStoreRequest + */ +class BudgetFormStoreRequest extends Request +{ + /** + * Verify the request. + * + * @return bool + */ + public function authorize(): bool + { + return auth()->check(); + } + + /** + * Returns the data required by the controller. + * + * @return array + */ + public function getBudgetData(): array + { + return [ + 'name' => $this->string('name'), + 'active' => $this->boolean('active'), + 'auto_budget_type' => $this->integer('auto_budget_type'), + 'transaction_currency_id' => $this->integer('transaction_currency_id'), + 'auto_budget_amount' => $this->string('auto_budget_amount'), + 'auto_budget_period' => $this->string('auto_budget_period'), + ]; + } + + /** + * Rules for this request. + * + * @return array + */ + public function rules(): array + { + return [ + 'name' => 'required|between:1,100|uniqueObjectForUser:budgets,name', + 'active' => 'numeric|between:0,1', + 'auto_budget_type' => 'numeric|between:0,2', + 'auto_budget_currency_id' => 'required|exists:transaction_currencies,id', + 'auto_budget_amount' => 'min:0|max:1000000000', + 'auto_budget_period' => 'in:daily,weekly,monthly,quarterly,half_year,yearly', + ]; + } + + /** + * Configure the validator instance with special rules for after the basic validation rules. + * + * @param Validator $validator + * + * @return void + */ + public function withValidator(Validator $validator): void + { + $validator->after( + function (Validator $validator) { + // validate all account info + $this->validateAutoBudgetAmount($validator); + } + ); + } + +} diff --git a/app/Http/Requests/BudgetFormRequest.php b/app/Http/Requests/BudgetFormUpdateRequest.php similarity index 54% rename from app/Http/Requests/BudgetFormRequest.php rename to app/Http/Requests/BudgetFormUpdateRequest.php index 4d0924e7c1..02ce9bebd4 100644 --- a/app/Http/Requests/BudgetFormRequest.php +++ b/app/Http/Requests/BudgetFormUpdateRequest.php @@ -23,14 +23,13 @@ declare(strict_types=1); namespace FireflyIII\Http\Requests; use FireflyIII\Models\Budget; +use Illuminate\Validation\Validator; /** - * Class BudgetFormRequest. - * * @codeCoverageIgnore - * TODO AFTER 4.8,0, split for update/store + * Class BudgetFormUpdateRequest */ -class BudgetFormRequest extends Request +class BudgetFormUpdateRequest extends Request { /** * Verify the request. @@ -50,8 +49,12 @@ class BudgetFormRequest extends Request public function getBudgetData(): array { return [ - 'name' => $this->string('name'), - 'active' => $this->boolean('active'), + 'name' => $this->string('name'), + 'active' => $this->boolean('active'), + 'auto_budget_type' => $this->integer('auto_budget_type'), + 'transaction_currency_id' => $this->integer('auto_budget_currency_id'), + 'auto_budget_amount' => $this->string('auto_budget_amount'), + 'auto_budget_period' => $this->string('auto_budget_period'), ]; } @@ -72,8 +75,29 @@ class BudgetFormRequest extends Request } return [ - 'name' => $nameRule, - 'active' => 'numeric|between:0,1', + 'name' => $nameRule, + 'active' => 'numeric|between:0,1', + 'auto_budget_option' => 'numeric|between:0,2', + 'auto_budget_currency_id' => 'required|exists:transaction_currencies,id', + 'auto_budget_amount' => 'min:0|max:1000000000', + 'auto_budget_period' => 'in:daily,weekly,monthly,quarterly,half_year,yearly', ]; } + + /** + * Configure the validator instance with special rules for after the basic validation rules. + * + * @param Validator $validator + * + * @return void + */ + public function withValidator(Validator $validator): void + { + $validator->after( + function (Validator $validator) { + // validate all account info + $this->validateAutoBudgetAmount($validator); + } + ); + } } diff --git a/app/Http/Requests/JournalLinkRequest.php b/app/Http/Requests/JournalLinkRequest.php index 4c0a65279c..7d5de5438a 100644 --- a/app/Http/Requests/JournalLinkRequest.php +++ b/app/Http/Requests/JournalLinkRequest.php @@ -51,7 +51,7 @@ class JournalLinkRequest extends Request $return = []; $linkType = $this->get('link_type'); $parts = explode('_', $linkType); - $return['link_type_id'] = (int)$parts[0]; + $return['link_type_id'] = (int) $parts[0]; $return['transaction_journal_id'] = $this->integer('opposing'); $return['notes'] = $this->string('notes'); $return['direction'] = $parts[1]; diff --git a/app/Http/Requests/RecurrenceFormRequest.php b/app/Http/Requests/RecurrenceFormRequest.php index 86ccc64d93..b3345ddefb 100644 --- a/app/Http/Requests/RecurrenceFormRequest.php +++ b/app/Http/Requests/RecurrenceFormRequest.php @@ -53,9 +53,9 @@ class RecurrenceFormRequest extends Request /** * Get the data required by the controller. * - * @return array * @throws FireflyException * + * @return array */ public function getAll(): array { @@ -136,9 +136,9 @@ class RecurrenceFormRequest extends Request /** * The rules for this request. * - * @return array * @throws FireflyException * + * @return array */ public function rules(): array { @@ -250,16 +250,16 @@ class RecurrenceFormRequest extends Request default: throw new FireflyException(sprintf('Cannot handle transaction type "%s"', $this->string('transaction_type'))); // @codeCoverageIgnore case 'withdrawal': - $sourceId = (int)$data['source_id']; - $destinationId = (int)$data['withdrawal_destination_id']; + $sourceId = (int) $data['source_id']; + $destinationId = (int) $data['withdrawal_destination_id']; break; case 'deposit': - $sourceId = (int)$data['deposit_source_id']; - $destinationId = (int)$data['destination_id']; + $sourceId = (int) $data['deposit_source_id']; + $destinationId = (int) $data['destination_id']; break; case 'transfer': - $sourceId = (int)$data['source_id']; - $destinationId = (int)$data['destination_id']; + $sourceId = (int) $data['source_id']; + $destinationId = (int) $data['destination_id']; break; } @@ -269,7 +269,7 @@ class RecurrenceFormRequest extends Request // do something with result: if (false === $validSource) { - $message = (string)trans('validation.generic_invalid_source'); + $message = (string) trans('validation.generic_invalid_source'); $validator->errors()->add('source_id', $message); $validator->errors()->add('deposit_source_id', $message); @@ -280,7 +280,7 @@ class RecurrenceFormRequest extends Request $validDestination = $accountValidator->validateDestination($destinationId, null); // do something with result: if (false === $validDestination) { - $message = (string)trans('validation.generic_invalid_destination'); + $message = (string) trans('validation.generic_invalid_destination'); $validator->errors()->add('destination_id', $message); $validator->errors()->add('withdrawal_destination_id', $message); diff --git a/app/Http/Requests/ReportFormRequest.php b/app/Http/Requests/ReportFormRequest.php index 2b6d62059f..150698d1e2 100644 --- a/app/Http/Requests/ReportFormRequest.php +++ b/app/Http/Requests/ReportFormRequest.php @@ -62,7 +62,7 @@ class ReportFormRequest extends Request $collection = new Collection; if (is_array($set)) { foreach ($set as $accountId) { - $account = $repository->findNull((int)$accountId); + $account = $repository->findNull((int) $accountId); if (null !== $account) { $collection->push($account); } @@ -85,7 +85,7 @@ class ReportFormRequest extends Request $collection = new Collection; if (is_array($set)) { foreach ($set as $budgetId) { - $budget = $repository->findNull((int)$budgetId); + $budget = $repository->findNull((int) $budgetId); if (null !== $budget) { $collection->push($budget); } @@ -108,7 +108,7 @@ class ReportFormRequest extends Request $collection = new Collection; if (is_array($set)) { foreach ($set as $categoryId) { - $category = $repository->findNull((int)$categoryId); + $category = $repository->findNull((int) $categoryId); if (null !== $category) { $collection->push($category); } @@ -118,18 +118,41 @@ class ReportFormRequest extends Request return $collection; } + /** + * Validate list of accounts which exist twice in system. + * + * @return Collection + */ + public function getDoubleList(): Collection + { + /** @var AccountRepositoryInterface $repository */ + $repository = app(AccountRepositoryInterface::class); + $set = $this->get('double'); + $collection = new Collection; + if (is_array($set)) { + foreach ($set as $accountId) { + $account = $repository->findNull((int) $accountId); + if (null !== $account) { + $collection->push($account); + } + } + } + + return $collection; + } + /** * Validate end date. * + * @throws FireflyException * @return Carbon * - * @throws FireflyException */ public function getEndDate(): Carbon { $date = new Carbon; $range = $this->get('daterange'); - $parts = explode(' - ', (string)$range); + $parts = explode(' - ', (string) $range); if (2 === count($parts)) { try { $date = new Carbon($parts[1]); @@ -146,41 +169,18 @@ class ReportFormRequest extends Request return $date; } - /** - * Validate list of accounts which exist twice in system. - * - * @return Collection - */ - public function getDoubleList(): Collection - { - /** @var AccountRepositoryInterface $repository */ - $repository = app(AccountRepositoryInterface::class); - $set = $this->get('double'); - $collection = new Collection; - if (is_array($set)) { - foreach ($set as $accountId) { - $account = $repository->findNull((int)$accountId); - if (null !== $account) { - $collection->push($account); - } - } - } - - return $collection; - } - /** * Validate start date. * + * @throws FireflyException * @return Carbon * - * @throws FireflyException */ public function getStartDate(): Carbon { $date = new Carbon; $range = $this->get('daterange'); - $parts = explode(' - ', (string)$range); + $parts = explode(' - ', (string) $range); if (2 === count($parts)) { try { $date = new Carbon($parts[0]); @@ -216,7 +216,7 @@ class ReportFormRequest extends Request $collection->push($tag); continue; } - $tag = $repository->findNull((int)$tagTag); + $tag = $repository->findNull((int) $tagTag); if (null !== $tag) { $collection->push($tag); continue; diff --git a/app/Http/Requests/Request.php b/app/Http/Requests/Request.php index d85310ff38..670e48ab05 100644 --- a/app/Http/Requests/Request.php +++ b/app/Http/Requests/Request.php @@ -26,6 +26,7 @@ use Carbon\Carbon; use Carbon\Exceptions\InvalidDateException; use Exception; use Illuminate\Foundation\Http\FormRequest; +use Illuminate\Validation\Validator; use Log; /** @@ -123,7 +124,7 @@ class Request extends FormRequest return null; } - return (float)$res; + return (float) $res; } /** @@ -135,7 +136,7 @@ class Request extends FormRequest */ public function integer(string $field): int { - return (int)$this->get($field); + return (int) $this->get($field); } /** @@ -154,7 +155,37 @@ class Request extends FormRequest return null; } - return (int)$string; + return (int) $string; + } + + /** + * Return string value, but keep newlines. + * + * @param string $field + * + * @return string + */ + public function nlString(string $field): string + { + return app('steam')->nlCleanString((string) ($this->get($field) ?? '')); + } + + /** + * Parse and clean a string, but keep the newlines. + * + * @param string|null $string + * + * @return string|null + */ + public function nlStringFromValue(?string $string): ?string + { + if (null === $string) { + return null; + } + $result = app('steam')->nlCleanString($string); + + return '' === $result ? null : $result; + } /** @@ -170,12 +201,28 @@ class Request extends FormRequest return null; } - $value = (string)$this->get($field); + $value = (string) $this->get($field); if ('' === $value) { return null; } - return (int)$value; + return (int) $value; + } + + /** + * Return string value, but keep newlines, or NULL if empty. + * + * @param string $field + * + * @return string + */ + public function nullableNlString(string $field): ?string + { + if (!$this->has($field)) { + return null; + } + + return app('steam')->nlCleanString((string) ($this->get($field) ?? '')); } /** @@ -190,7 +237,12 @@ class Request extends FormRequest if (!$this->has($field)) { return null; } - return app('steam')->cleanString((string)($this->get($field) ?? '')); + $res = trim(app('steam')->cleanString((string) ($this->get($field) ?? ''))); + if ('' === $res) { + return null; + } + + return $res; } /** @@ -202,35 +254,7 @@ class Request extends FormRequest */ public function string(string $field): string { - return app('steam')->cleanString((string)($this->get($field) ?? '')); - } - - /** - * Return string value, but keep newlines. - * - * @param string $field - * - * @return string - */ - public function nlString(string $field): string - { - return app('steam')->nlCleanString((string)($this->get($field) ?? '')); - } - - - /** - * Return string value, but keep newlines, or NULL if empty. - * - * @param string $field - * - * @return string - */ - public function nullableNlString(string $field): ?string - { - if (!$this->has($field)) { - return null; - } - return app('steam')->nlCleanString((string)($this->get($field) ?? '')); + return app('steam')->cleanString((string) ($this->get($field) ?? '')); } /** @@ -252,21 +276,61 @@ class Request extends FormRequest } /** - * Parse and clean a string, but keep the newlines. + * Read the submitted Request data and add new or updated Location data to the array. * - * @param string|null $string + * @param array $data * - * @return string|null + * @param string|null $prefix + * + * @return array */ - public function nlStringFromValue(?string $string): ?string + protected function appendLocationData(array $data, ?string $prefix): array { - if (null === $string) { - return null; + Log::debug(sprintf('Now in appendLocationData("%s")', $prefix), $data); + $data['store_location'] = false; + $data['update_location'] = false; + $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'); + $hasLocationKey = $this->getLocationKey($prefix, 'has_location'); + + // for a POST (store, all fields must be present and accounted for: + if ( + ('POST' === $this->method() && $this->routeIs('*.store')) + && ($this->has($longitudeKey) && $this->has($latitudeKey) && $this->has($zoomLevelKey)) + ) { + Log::debug('Method is POST and all fields present.'); + $data['store_location'] = $this->boolean($hasLocationKey); + $data['longitude'] = $this->nullableString($longitudeKey); + $data['latitude'] = $this->nullableString($latitudeKey); + $data['zoom_level'] = $this->nullableString($zoomLevelKey); + } + if ( + ($this->has($longitudeKey) && $this->has($latitudeKey) && $this->has($zoomLevelKey)) + && ( + ('PUT' === $this->method() && $this->routeIs('*.update')) + || ('POST' === $this->method() && $this->routeIs('*.update')) + ) + ) { + Log::debug('Method is PUT and all fields present.'); + $data['update_location'] = true; + $data['longitude'] = $this->nullableString($longitudeKey); + $data['latitude'] = $this->nullableString($latitudeKey); + $data['zoom_level'] = $this->nullableString($zoomLevelKey); + } + if (null === $data['longitude'] || null === $data['latitude'] || null === $data['zoom_level']) { + Log::debug('One of the fields is NULL, wont save.'); + $data['store_location'] = false; + $data['update_location'] = false; } - $result = app('steam')->nlCleanString($string); - return '' === $result ? null : $result; + Log::debug(sprintf('Returning longitude: "%s", latitude: "%s", zoom level: "%s"', $data['longitude'], $data['latitude'], $data['zoom_level'])); + return $data; } /** @@ -300,7 +364,7 @@ class Request extends FormRequest if (null === $this->get($field)) { return null; } - $value = (string)$this->get($field); + $value = (string) $this->get($field); if (10 === strlen($value)) { // probably a date format. try { @@ -326,63 +390,51 @@ class Request extends FormRequest } /** - * Read the submitted Request data and add new or updated Location data to the array. - * - * @param array $data - * - * @param string|null $prefix - * - * @return array + * @param Validator $validator */ - protected function appendLocationData(array $data, ?string $prefix): array + protected function validateAutoBudgetAmount(Validator $validator): void { - Log::debug(sprintf('Now in appendLocationData("%s")', $prefix), $data); - $data['store_location'] = false; - $data['update_location'] = false; - $data['longitude'] = null; - $data['latitude'] = null; - $data['zoom_level'] = null; - - - $longitudeKey = null === $prefix ? 'longitude' : sprintf('%s_longitude', $prefix); - $latitudeKey = null === $prefix ? 'latitude' : sprintf('%s_latitude', $prefix); - $zoomLevelKey = null === $prefix ? 'zoom_level' : sprintf('%s_zoom_level', $prefix); - $hasLocationKey = null === $prefix ? 'has_location' : sprintf('%s_has_location', $prefix); - - // for a POST (store, all fields must be present and accounted for: - if ( - ('POST' === $this->method() && $this->routeIs('*.store')) - && ($this->has($longitudeKey) && $this->has($latitudeKey) && $this->has($zoomLevelKey)) - ) { - Log::debug('Method is POST and all fields present.'); - - $data['store_location'] = $this->boolean($hasLocationKey); - $data['longitude'] = '' === $this->string($longitudeKey) ? null : $this->string($longitudeKey); - $data['latitude'] = '' === $this->string($latitudeKey) ? null : $this->string($latitudeKey); - $data['zoom_level'] = '' === $this->string($zoomLevelKey) ? null : $this->integer($zoomLevelKey); + $data = $validator->getData(); + $type = $data['auto_budget_type'] ?? ''; + $amount = $data['auto_budget_amount'] ?? ''; + $period = (string) ($data['auto_budget_period'] ?? ''); + $currencyId = $data['auto_budget_currency_id'] ?? ''; + $currencyCode = $data['auto_budget_currency_code'] ?? ''; + if (is_numeric($type)) { + $type = (int) $type; } - if ( - ($this->has($longitudeKey) && $this->has($latitudeKey) && $this->has($zoomLevelKey)) - && ( - ('PUT' === $this->method() && $this->routeIs('*.update')) - || ('POST' === $this->method() && $this->routeIs('*.update')) - ) - ) { - Log::debug('Method is PUT and all fields present.'); - $data['update_location'] = true; - $data['longitude'] = '' === $this->string($longitudeKey) ? null : $this->string($longitudeKey); - $data['latitude'] = '' === $this->string($latitudeKey) ? null : $this->string($latitudeKey); - $data['zoom_level'] = '' === $this->string($zoomLevelKey) ? null : $this->integer($zoomLevelKey); + if (0 === $type || 'none' === $type || '' === $type) { + return; } - if (null === $data['longitude'] || null === $data['latitude'] || null === $data['zoom_level']) { - Log::debug('One of the fields is NULL, wont save.'); - $data['store_location'] = false; - $data['update_location'] = false; + // basic float check: + if ('' === $amount) { + $validator->errors()->add('auto_budget_amount', (string) trans('validation.amount_required_for_auto_budget')); + } + if (1 !== bccomp((string) $amount, '0')) { + $validator->errors()->add('auto_budget_amount', (string) trans('validation.auto_budget_amount_positive')); + } + if ('' === $period) { + $validator->errors()->add('auto_budget_period', (string) trans('validation.auto_budget_period_mandatory')); + } + if ('' === $currencyCode && '' === $currencyId) { + $validator->errors()->add('auto_budget_amount', (string) trans('validation.require_currency_info')); } - - Log::debug(sprintf('Returning longitude: "%s", latitude: "%s", zoom level: "%s"', $data['longitude'], $data['latitude'], $data['zoom_level'])); - - return $data; } + /** + * @param string|null $prefix + * @param string $key + * + * @return string + */ + private function getLocationKey(?string $prefix, string $key): string + { + if (null === $prefix) { + return $key; + } + + return sprintf('%s_%s', $prefix, $key); + } + + } diff --git a/app/Http/Requests/RuleFormRequest.php b/app/Http/Requests/RuleFormRequest.php index 43162aecb4..ad0ee86e06 100644 --- a/app/Http/Requests/RuleFormRequest.php +++ b/app/Http/Requests/RuleFormRequest.php @@ -116,7 +116,7 @@ class RuleFormRequest extends Request $return[] = [ 'type' => $action['type'] ?? 'invalid', 'value' => $action['value'] ?? '', - 'stop_processing' => 1 === (int)$stopProcessing, + 'stop_processing' => 1 === (int) $stopProcessing, ]; } } @@ -137,7 +137,7 @@ class RuleFormRequest extends Request $return[] = [ 'type' => $trigger['type'] ?? 'invalid', 'value' => $trigger['value'] ?? '', - 'stop_processing' => 1 === (int)$stopProcessing, + 'stop_processing' => 1 === (int) $stopProcessing, ]; } } diff --git a/app/Http/Requests/TagFormRequest.php b/app/Http/Requests/TagFormRequest.php index 5d7ed76a7a..e6d1180b97 100644 --- a/app/Http/Requests/TagFormRequest.php +++ b/app/Http/Requests/TagFormRequest.php @@ -53,6 +53,7 @@ class TagFormRequest extends Request 'date' => $this->date('date'), 'description' => $this->string('description'), ]; + return $this->appendLocationData($data, 'location'); } @@ -74,12 +75,13 @@ class TagFormRequest extends Request $tagRule = 'required|min:1|uniqueObjectForUser:tags,tag,' . $tag->id; } - $rules= [ + $rules = [ 'tag' => $tagRule, 'id' => $idRule, 'description' => 'min:1|nullable', 'date' => 'date|nullable', ]; + return Location::requestRules($rules); } } diff --git a/app/Import/Converter/Amount.php b/app/Import/Converter/Amount.php index 00c7fdbfe4..ee7630764d 100644 --- a/app/Import/Converter/Amount.php +++ b/app/Import/Converter/Amount.php @@ -26,6 +26,9 @@ use Log; /** * Class Amount. + * + * @deprecated + * @codeCoverageIgnore */ class Amount implements ConverterInterface { @@ -44,7 +47,7 @@ class Amount implements ConverterInterface } Log::debug(sprintf('Start with amount "%s"', $value)); $original = $value; - $value = $this->stripAmount((string)$value); + $value = $this->stripAmount((string) $value); $decimal = null; if ($this->decimalIsDot($value)) { @@ -217,7 +220,7 @@ class Amount implements ConverterInterface $value = substr($value, 2); } // have to strip the € because apparantly the Postbank (DE) thinks "1.000,00 €" is a normal way to format a number. - $value = trim((string)str_replace(['€'], '', $value)); + $value = trim((string) str_replace(['€'], '', $value)); $str = preg_replace('/[^\-\(\)\.\,0-9 ]/', '', $value); $len = strlen($str); if ('(' === $str[0] && ')' === $str[$len - 1]) { diff --git a/app/Import/Converter/AmountCredit.php b/app/Import/Converter/AmountCredit.php index b24747b6dd..3bfb2e6021 100644 --- a/app/Import/Converter/AmountCredit.php +++ b/app/Import/Converter/AmountCredit.php @@ -24,6 +24,9 @@ namespace FireflyIII\Import\Converter; /** * Class AmountCredit + * + * @deprecated + * @codeCoverageIgnore */ class AmountCredit implements ConverterInterface { diff --git a/app/Import/Converter/AmountDebit.php b/app/Import/Converter/AmountDebit.php index 6748802df9..4b96a34662 100644 --- a/app/Import/Converter/AmountDebit.php +++ b/app/Import/Converter/AmountDebit.php @@ -24,6 +24,9 @@ namespace FireflyIII\Import\Converter; /** * Class AmountDebit + * + * @deprecated + * @codeCoverageIgnore */ class AmountDebit implements ConverterInterface { diff --git a/app/Import/Converter/AmountNegated.php b/app/Import/Converter/AmountNegated.php index bd51b71fa7..3bb2483e19 100644 --- a/app/Import/Converter/AmountNegated.php +++ b/app/Import/Converter/AmountNegated.php @@ -24,6 +24,9 @@ namespace FireflyIII\Import\Converter; /** * Class AmountNegated + * + * @deprecated + * @codeCoverageIgnore */ class AmountNegated implements ConverterInterface { diff --git a/app/Import/Converter/BankDebitCredit.php b/app/Import/Converter/BankDebitCredit.php index 600392ba2c..4c5278ab5f 100644 --- a/app/Import/Converter/BankDebitCredit.php +++ b/app/Import/Converter/BankDebitCredit.php @@ -29,6 +29,9 @@ use Log; /** * * Class BankDebitCredit + * + * @deprecated + * @codeCoverageIgnore */ class BankDebitCredit implements ConverterInterface { @@ -36,9 +39,10 @@ class BankDebitCredit implements ConverterInterface /** * Convert a value. * + * @param $value + * * @return mixed * - * @param $value */ public function convert($value): int { diff --git a/app/Import/Converter/ConverterInterface.php b/app/Import/Converter/ConverterInterface.php index 3009f56292..bdf5176eb1 100644 --- a/app/Import/Converter/ConverterInterface.php +++ b/app/Import/Converter/ConverterInterface.php @@ -24,15 +24,19 @@ namespace FireflyIII\Import\Converter; /** * Interface ConverterInterface. + * + * @deprecated + * @codeCoverageIgnore */ interface ConverterInterface { /** * Convert a value. * + * @param $value + * * @return mixed * - * @param $value */ public function convert($value); } diff --git a/app/Import/JobConfiguration/BunqJobConfiguration.php b/app/Import/JobConfiguration/BunqJobConfiguration.php index 195594849b..c4c5f3644b 100644 --- a/app/Import/JobConfiguration/BunqJobConfiguration.php +++ b/app/Import/JobConfiguration/BunqJobConfiguration.php @@ -34,6 +34,9 @@ use Log; /** * Class BunqJobConfiguration + * + * @deprecated + * @codeCoverageIgnore */ class BunqJobConfiguration implements JobConfigurationInterface { @@ -105,8 +108,8 @@ class BunqJobConfiguration implements JobConfigurationInterface /** * Get correct handler. * - * @return BunqJobConfigurationInterface * @throws FireflyException + * @return BunqJobConfigurationInterface */ private function getHandler(): BunqJobConfigurationInterface { diff --git a/app/Import/JobConfiguration/FakeJobConfiguration.php b/app/Import/JobConfiguration/FakeJobConfiguration.php index b1a6ca01f0..132de1ef00 100644 --- a/app/Import/JobConfiguration/FakeJobConfiguration.php +++ b/app/Import/JobConfiguration/FakeJobConfiguration.php @@ -29,6 +29,9 @@ use Illuminate\Support\MessageBag; /** * Class FakeJobConfiguration + * + * @deprecated + * @codeCoverageIgnore */ class FakeJobConfiguration implements JobConfigurationInterface { @@ -76,7 +79,7 @@ class FakeJobConfiguration implements JobConfigurationInterface $artist = strtolower($data['artist'] ?? ''); $song = strtolower($data['song'] ?? ''); $album = strtolower($data['album'] ?? ''); - $applyRules = isset($data['apply_rules']) ? 1 === (int)$data['apply_rules'] : null; + $applyRules = isset($data['apply_rules']) ? 1 === (int) $data['apply_rules'] : null; $configuration = $this->importJob->configuration; if ('david bowie' === $artist) { // store artist @@ -116,8 +119,8 @@ class FakeJobConfiguration implements JobConfigurationInterface { return [ 'rulesOptions' => [ - 1 => (string)trans('firefly.yes'), - 0 => (string)trans('firefly.no'), + 1 => (string) trans('firefly.yes'), + 0 => (string) trans('firefly.no'), ], ]; } diff --git a/app/Import/JobConfiguration/FileJobConfiguration.php b/app/Import/JobConfiguration/FileJobConfiguration.php index df829b1055..76cf4e2ec6 100644 --- a/app/Import/JobConfiguration/FileJobConfiguration.php +++ b/app/Import/JobConfiguration/FileJobConfiguration.php @@ -37,6 +37,9 @@ use Illuminate\Support\MessageBag; /** * Class FileJobConfiguration + * + * @deprecated + * @codeCoverageIgnore */ class FileJobConfiguration implements JobConfigurationInterface { @@ -61,8 +64,8 @@ class FileJobConfiguration implements JobConfigurationInterface * * @param array $data * - * @return MessageBag * @throws FireflyException + * @return MessageBag */ public function configureJob(array $data): MessageBag { @@ -89,9 +92,9 @@ class FileJobConfiguration implements JobConfigurationInterface /** * Returns the view of the next step in the job configuration. * + * @throws FireflyException * @return string * - *@throws FireflyException */ public function getNextView(): string { @@ -128,9 +131,9 @@ class FileJobConfiguration implements JobConfigurationInterface /** * Get the configuration handler for this specific stage. * - * @return FileConfigurationInterface * @throws FireflyException * + * @return FileConfigurationInterface */ private function getConfigurationObject(): FileConfigurationInterface { diff --git a/app/Import/JobConfiguration/FinTSConfigurationSteps.php b/app/Import/JobConfiguration/FinTSConfigurationSteps.php index 5144a4fe00..4a55c548b3 100644 --- a/app/Import/JobConfiguration/FinTSConfigurationSteps.php +++ b/app/Import/JobConfiguration/FinTSConfigurationSteps.php @@ -26,6 +26,9 @@ namespace FireflyIII\Import\JobConfiguration; /** * * Class FinTSConfigurationSteps + * + * @deprecated + * @codeCoverageIgnore */ abstract class FinTSConfigurationSteps { diff --git a/app/Import/JobConfiguration/FinTSJobConfiguration.php b/app/Import/JobConfiguration/FinTSJobConfiguration.php index 61f100b0f1..f7eb84bd95 100644 --- a/app/Import/JobConfiguration/FinTSJobConfiguration.php +++ b/app/Import/JobConfiguration/FinTSJobConfiguration.php @@ -32,6 +32,9 @@ use Illuminate\Support\MessageBag; /** * * Class FinTSJobConfiguration + * + * @deprecated + * @codeCoverageIgnore */ class FinTSJobConfiguration implements JobConfigurationInterface { @@ -54,8 +57,8 @@ class FinTSJobConfiguration implements JobConfigurationInterface * * @param array $data * - * @return MessageBag * @throws FireflyException + * @return MessageBag */ public function configureJob(array $data): MessageBag { @@ -65,8 +68,8 @@ class FinTSJobConfiguration implements JobConfigurationInterface /** * Return the data required for the next step in the job configuration. * - * @return array * @throws FireflyException + * @return array */ public function getNextData(): array { @@ -76,8 +79,8 @@ class FinTSJobConfiguration implements JobConfigurationInterface /** * Returns the view of the next step in the job configuration. * - * @return string * @throws FireflyException + * @return string */ public function getNextView(): string { @@ -106,8 +109,8 @@ class FinTSJobConfiguration implements JobConfigurationInterface /** * Get the configuration handler for this specific stage. * - * @return FinTSConfigurationInterface * @throws FireflyException + * @return FinTSConfigurationInterface */ private function getConfigurationObject(): FinTSConfigurationInterface { diff --git a/app/Import/JobConfiguration/JobConfigurationInterface.php b/app/Import/JobConfiguration/JobConfigurationInterface.php index b4223e0b45..8d3343bb89 100644 --- a/app/Import/JobConfiguration/JobConfigurationInterface.php +++ b/app/Import/JobConfiguration/JobConfigurationInterface.php @@ -27,6 +27,9 @@ use Illuminate\Support\MessageBag; /** * Interface JobConfigurationInterface. + * + * @deprecated + * @codeCoverageIgnore */ interface JobConfigurationInterface { diff --git a/app/Import/JobConfiguration/SpectreJobConfiguration.php b/app/Import/JobConfiguration/SpectreJobConfiguration.php index 92b1688634..1bf3f12bdc 100644 --- a/app/Import/JobConfiguration/SpectreJobConfiguration.php +++ b/app/Import/JobConfiguration/SpectreJobConfiguration.php @@ -37,6 +37,9 @@ use Log; /** * Class SpectreJobConfiguration + * + * @deprecated + * @codeCoverageIgnore */ class SpectreJobConfiguration implements JobConfigurationInterface { @@ -108,9 +111,9 @@ class SpectreJobConfiguration implements JobConfigurationInterface /** * Get correct handler. * - * @return SpectreJobConfigurationInterface * @throws FireflyException * + * @return SpectreJobConfigurationInterface */ private function getHandler(): SpectreJobConfigurationInterface { diff --git a/app/Import/JobConfiguration/YnabJobConfiguration.php b/app/Import/JobConfiguration/YnabJobConfiguration.php index 4c886748a5..60ad0a52a9 100644 --- a/app/Import/JobConfiguration/YnabJobConfiguration.php +++ b/app/Import/JobConfiguration/YnabJobConfiguration.php @@ -35,6 +35,9 @@ use Log; /** * Class YnabJobConfiguration + * + * @deprecated + * @codeCoverageIgnore */ class YnabJobConfiguration implements JobConfigurationInterface { @@ -106,9 +109,9 @@ class YnabJobConfiguration implements JobConfigurationInterface /** * Get correct handler. * - * @return YnabJobConfigurationInterface * @throws FireflyException * + * @return YnabJobConfigurationInterface */ private function getHandler(): YnabJobConfigurationInterface { diff --git a/app/Import/Mapper/AssetAccountIbans.php b/app/Import/Mapper/AssetAccountIbans.php index 2463b7ee1a..b754f7d75a 100644 --- a/app/Import/Mapper/AssetAccountIbans.php +++ b/app/Import/Mapper/AssetAccountIbans.php @@ -28,6 +28,9 @@ use FireflyIII\Repositories\Account\AccountRepositoryInterface; /** * Class AssetAccounts. + * + * @deprecated + * @codeCoverageIgnore */ class AssetAccountIbans implements MapperInterface { @@ -52,7 +55,7 @@ class AssetAccountIbans implements MapperInterface /** @var Account $account */ foreach ($set as $account) { $iban = $account->iban ?? ''; - $accountId = (int)$account->id; + $accountId = (int) $account->id; if ('' !== $iban) { $name = $account->iban . ' (' . $account->name . ')'; @@ -75,7 +78,7 @@ class AssetAccountIbans implements MapperInterface /** @noinspection AdditionOperationOnArraysInspection */ $list = $topList + $list; asort($list); - $list = [0 => (string)trans('import.map_do_not_map')] + $list; + $list = [0 => (string) trans('import.map_do_not_map')] + $list; return $list; } diff --git a/app/Import/Mapper/AssetAccounts.php b/app/Import/Mapper/AssetAccounts.php index 69b6eac96c..0d303977c2 100644 --- a/app/Import/Mapper/AssetAccounts.php +++ b/app/Import/Mapper/AssetAccounts.php @@ -28,6 +28,9 @@ use FireflyIII\Repositories\Account\AccountRepositoryInterface; /** * Class AssetAccounts. + * + * @deprecated + * @codeCoverageIgnore */ class AssetAccounts implements MapperInterface { @@ -47,7 +50,7 @@ class AssetAccounts implements MapperInterface /** @var Account $account */ foreach ($set as $account) { - $accountId = (int)$account->id; + $accountId = (int) $account->id; $name = $account->name; $iban = $account->iban ?? ''; if ('' !== $iban) { @@ -62,7 +65,7 @@ class AssetAccounts implements MapperInterface $list[$accountId] = $name; } asort($list); - $list = [0 => (string)trans('import.map_do_not_map')] + $list; + $list = [0 => (string) trans('import.map_do_not_map')] + $list; return $list; } diff --git a/app/Import/Mapper/Bills.php b/app/Import/Mapper/Bills.php index d24e54a83d..5ba45bd3da 100644 --- a/app/Import/Mapper/Bills.php +++ b/app/Import/Mapper/Bills.php @@ -27,6 +27,9 @@ use FireflyIII\Repositories\Bill\BillRepositoryInterface; /** * Class Bills. + * + * @deprecated + * @codeCoverageIgnore */ class Bills implements MapperInterface { @@ -44,11 +47,11 @@ class Bills implements MapperInterface /** @var Bill $bill */ foreach ($result as $bill) { - $billId = (int)$bill->id; + $billId = (int) $bill->id; $list[$billId] = $bill->name; } asort($list); - $list = [0 => (string)trans('import.map_do_not_map')] + $list; + $list = [0 => (string) trans('import.map_do_not_map')] + $list; return $list; } diff --git a/app/Import/Mapper/Budgets.php b/app/Import/Mapper/Budgets.php index 917d599463..afe68219d6 100644 --- a/app/Import/Mapper/Budgets.php +++ b/app/Import/Mapper/Budgets.php @@ -27,6 +27,9 @@ use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; /** * Class Budgets. + * + * @deprecated + * @codeCoverageIgnore */ class Budgets implements MapperInterface { @@ -44,11 +47,11 @@ class Budgets implements MapperInterface /** @var Budget $budget */ foreach ($result as $budget) { - $budgetId = (int)$budget->id; + $budgetId = (int) $budget->id; $list[$budgetId] = $budget->name; } asort($list); - $list = [0 => (string)trans('import.map_do_not_map')] + $list; + $list = [0 => (string) trans('import.map_do_not_map')] + $list; return $list; } diff --git a/app/Import/Mapper/Categories.php b/app/Import/Mapper/Categories.php index b4a361b01f..2f398d6513 100644 --- a/app/Import/Mapper/Categories.php +++ b/app/Import/Mapper/Categories.php @@ -27,6 +27,9 @@ use FireflyIII\Repositories\Category\CategoryRepositoryInterface; /** * Class Categories. + * + * @deprecated + * @codeCoverageIgnore */ class Categories implements MapperInterface { @@ -44,11 +47,11 @@ class Categories implements MapperInterface /** @var Category $category */ foreach ($result as $category) { - $categoryId = (int)$category->id; + $categoryId = (int) $category->id; $list[$categoryId] = $category->name; } asort($list); - $list = [0 => (string)trans('import.map_do_not_map')] + $list; + $list = [0 => (string) trans('import.map_do_not_map')] + $list; return $list; } diff --git a/app/Import/Mapper/MapperInterface.php b/app/Import/Mapper/MapperInterface.php index cbc289ba35..be211d418b 100644 --- a/app/Import/Mapper/MapperInterface.php +++ b/app/Import/Mapper/MapperInterface.php @@ -24,6 +24,9 @@ namespace FireflyIII\Import\Mapper; /** * Interface MapperInterface. + * + * @deprecated + * @codeCoverageIgnore */ interface MapperInterface { diff --git a/app/Import/Mapper/OpposingAccountIbans.php b/app/Import/Mapper/OpposingAccountIbans.php index 4e63d268a5..117e5db0fd 100644 --- a/app/Import/Mapper/OpposingAccountIbans.php +++ b/app/Import/Mapper/OpposingAccountIbans.php @@ -28,6 +28,9 @@ use FireflyIII\Repositories\Account\AccountRepositoryInterface; /** * Class OpposingAccounts. + * + * @deprecated + * @codeCoverageIgnore */ class OpposingAccountIbans implements MapperInterface { @@ -54,7 +57,7 @@ class OpposingAccountIbans implements MapperInterface /** @var Account $account */ foreach ($set as $account) { $iban = $account->iban ?? ''; - $accountId = (int)$account->id; + $accountId = (int) $account->id; if ('' !== $iban) { $name = $account->iban . ' (' . $account->name . ')'; @@ -78,7 +81,7 @@ class OpposingAccountIbans implements MapperInterface /** @noinspection AdditionOperationOnArraysInspection */ $list = $topList + $list; asort($list); - $list = [0 => (string)trans('import.map_do_not_map')] + $list; + $list = [0 => (string) trans('import.map_do_not_map')] + $list; return $list; } diff --git a/app/Import/Mapper/OpposingAccounts.php b/app/Import/Mapper/OpposingAccounts.php index efdcd00b7d..99453cadeb 100644 --- a/app/Import/Mapper/OpposingAccounts.php +++ b/app/Import/Mapper/OpposingAccounts.php @@ -28,6 +28,10 @@ use FireflyIII\Repositories\Account\AccountRepositoryInterface; /** * Class OpposingAccounts. + * + * @deprecated + * @codeCoverageIgnore + * */ class OpposingAccounts implements MapperInterface { @@ -52,7 +56,7 @@ class OpposingAccounts implements MapperInterface /** @var Account $account */ foreach ($set as $account) { - $accountId = (int)$account->id; + $accountId = (int) $account->id; $name = $account->name; $iban = $account->iban ?? ''; if ('' !== $iban) { @@ -65,7 +69,7 @@ class OpposingAccounts implements MapperInterface $list[$accountId] = $name; } asort($list); - $list = [0 => (string)trans('import.map_do_not_map')] + $list; + $list = [0 => (string) trans('import.map_do_not_map')] + $list; return $list; } diff --git a/app/Import/Mapper/Tags.php b/app/Import/Mapper/Tags.php index b97e03a63c..ea02687994 100644 --- a/app/Import/Mapper/Tags.php +++ b/app/Import/Mapper/Tags.php @@ -27,6 +27,9 @@ use FireflyIII\Repositories\Tag\TagRepositoryInterface; /** * Class Tags. + * + * @deprecated + * @codeCoverageIgnore */ class Tags implements MapperInterface { @@ -44,11 +47,11 @@ class Tags implements MapperInterface /** @var Tag $tag */ foreach ($result as $tag) { - $tagId = (int)$tag->id; + $tagId = (int) $tag->id; $list[$tagId] = $tag->tag; } asort($list); - $list = [0 => (string)trans('import.map_do_not_map')] + $list; + $list = [0 => (string) trans('import.map_do_not_map')] + $list; return $list; } diff --git a/app/Import/Mapper/TransactionCurrencies.php b/app/Import/Mapper/TransactionCurrencies.php index e36c6d00f4..613afcc54d 100644 --- a/app/Import/Mapper/TransactionCurrencies.php +++ b/app/Import/Mapper/TransactionCurrencies.php @@ -26,6 +26,9 @@ use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; /** * Class TransactionCurrencies. + * + * @deprecated + * @codeCoverageIgnore */ class TransactionCurrencies implements MapperInterface { @@ -41,12 +44,12 @@ class TransactionCurrencies implements MapperInterface $currencies = $repository->get(); $list = []; foreach ($currencies as $currency) { - $currencyId = (int)$currency->id; + $currencyId = (int) $currency->id; $list[$currencyId] = $currency->name . ' (' . $currency->code . ')'; } asort($list); - $list = [0 => (string)trans('import.map_do_not_map')] + $list; + $list = [0 => (string) trans('import.map_do_not_map')] + $list; return $list; } diff --git a/app/Import/MapperPreProcess/PreProcessorInterface.php b/app/Import/MapperPreProcess/PreProcessorInterface.php index 1368d5d600..9436db4078 100644 --- a/app/Import/MapperPreProcess/PreProcessorInterface.php +++ b/app/Import/MapperPreProcess/PreProcessorInterface.php @@ -24,6 +24,9 @@ namespace FireflyIII\Import\MapperPreProcess; /** * Interface PreProcessorInterface. + * + * @deprecated + * @codeCoverageIgnore */ interface PreProcessorInterface { diff --git a/app/Import/MapperPreProcess/TagsComma.php b/app/Import/MapperPreProcess/TagsComma.php index 7c2489663c..23427f02cc 100644 --- a/app/Import/MapperPreProcess/TagsComma.php +++ b/app/Import/MapperPreProcess/TagsComma.php @@ -24,6 +24,9 @@ namespace FireflyIII\Import\MapperPreProcess; /** * Class TagsComma. + * + * @deprecated + * @codeCoverageIgnore */ class TagsComma implements PreProcessorInterface { diff --git a/app/Import/MapperPreProcess/TagsSpace.php b/app/Import/MapperPreProcess/TagsSpace.php index 4675c90f86..bab216c2a1 100644 --- a/app/Import/MapperPreProcess/TagsSpace.php +++ b/app/Import/MapperPreProcess/TagsSpace.php @@ -24,6 +24,9 @@ namespace FireflyIII\Import\MapperPreProcess; /** * Class TagsSpace. + * + * @deprecated + * @codeCoverageIgnore */ class TagsSpace implements PreProcessorInterface { diff --git a/app/Import/Prerequisites/BunqPrerequisites.php b/app/Import/Prerequisites/BunqPrerequisites.php index 4feea138ff..664f3aba84 100644 --- a/app/Import/Prerequisites/BunqPrerequisites.php +++ b/app/Import/Prerequisites/BunqPrerequisites.php @@ -33,6 +33,9 @@ use Log; /** * This class contains all the routines necessary to connect to Bunq. + * + * @deprecated + * @codeCoverageIgnore */ class BunqPrerequisites implements PrerequisitesInterface { @@ -80,7 +83,7 @@ class BunqPrerequisites implements PrerequisitesInterface if (!$this->hasExternalIP()) { /** @var IPRetrievalInterface $service */ $service = app(IPRetrievalInterface::class); - $externalIP = (string)$service->getIP(); + $externalIP = (string) $service->getIP(); } return ['api_key' => $key, 'external_ip' => $externalIP]; @@ -188,7 +191,7 @@ class BunqPrerequisites implements PrerequisitesInterface if (null === $apiContext) { return false; } - if ('' === (string)$apiContext->data) { + if ('' === (string) $apiContext->data) { return false; } @@ -206,7 +209,7 @@ class BunqPrerequisites implements PrerequisitesInterface if (null === $apiKey) { return false; } - if ('' === (string)$apiKey->data) { + if ('' === (string) $apiKey->data) { return false; } @@ -224,7 +227,7 @@ class BunqPrerequisites implements PrerequisitesInterface if (null === $externalIP) { return false; } - if ('' === (string)$externalIP->data) { + if ('' === (string) $externalIP->data) { return false; } diff --git a/app/Import/Prerequisites/FakePrerequisites.php b/app/Import/Prerequisites/FakePrerequisites.php index ba9dca7518..8f7ef94cb2 100644 --- a/app/Import/Prerequisites/FakePrerequisites.php +++ b/app/Import/Prerequisites/FakePrerequisites.php @@ -25,11 +25,15 @@ namespace FireflyIII\Import\Prerequisites; use FireflyIII\User; use Illuminate\Support\MessageBag; use Log; +use function request; /** * This class contains all the routines necessary for the fake import provider. * * Class FakePrerequisites + * + * @deprecated + * @codeCoverageIgnore */ class FakePrerequisites implements PrerequisitesInterface { @@ -68,9 +72,9 @@ class FakePrerequisites implements PrerequisitesInterface if ($this->hasApiKey()) { $apiKey = app('preferences')->getForUser($this->user, 'fake_api_key', null)->data; } - $oldKey = (string)\request()->old('api_key'); + $oldKey = (string) request()->old('api_key'); if ('' !== $oldKey) { - $apiKey = \request()->old('api_key'); // @codeCoverageIgnore + $apiKey = request()->old('api_key'); // @codeCoverageIgnore } return ['api_key' => $apiKey]; @@ -133,7 +137,7 @@ class FakePrerequisites implements PrerequisitesInterface if (null === $apiKey->data) { return false; } - if (32 === strlen((string)$apiKey->data)) { + if (32 === strlen((string) $apiKey->data)) { return true; } diff --git a/app/Import/Prerequisites/FilePrerequisites.php b/app/Import/Prerequisites/FilePrerequisites.php index 469d82611d..8cfc105182 100644 --- a/app/Import/Prerequisites/FilePrerequisites.php +++ b/app/Import/Prerequisites/FilePrerequisites.php @@ -30,6 +30,7 @@ use Log; * * This class contains all the routines necessary to import from a file. Hint: there are none. * + * @deprecated * @codeCoverageIgnore */ class FilePrerequisites implements PrerequisitesInterface @@ -44,6 +45,7 @@ class FilePrerequisites implements PrerequisitesInterface Log::warning(sprintf('%s should not be instantiated in the TEST environment!', get_class($this))); } } + /** * Returns view name that allows user to fill in prerequisites. * diff --git a/app/Import/Prerequisites/PrerequisitesInterface.php b/app/Import/Prerequisites/PrerequisitesInterface.php index d6dc89edb6..4ac3992b6e 100644 --- a/app/Import/Prerequisites/PrerequisitesInterface.php +++ b/app/Import/Prerequisites/PrerequisitesInterface.php @@ -27,6 +27,9 @@ use Illuminate\Support\MessageBag; /** * Interface PrerequisitesInterface + * + * @deprecated + * @codeCoverageIgnore */ interface PrerequisitesInterface { diff --git a/app/Import/Prerequisites/SpectrePrerequisites.php b/app/Import/Prerequisites/SpectrePrerequisites.php index 9f77c7db4a..2746c870bf 100644 --- a/app/Import/Prerequisites/SpectrePrerequisites.php +++ b/app/Import/Prerequisites/SpectrePrerequisites.php @@ -29,6 +29,9 @@ use Log; /** * This class contains all the routines necessary to connect to Spectre. + * + * @deprecated + * @codeCoverageIgnore */ class SpectrePrerequisites implements PrerequisitesInterface { @@ -176,7 +179,7 @@ class SpectrePrerequisites implements PrerequisitesInterface if (null === $appId) { return false; } - if ('' === (string)$appId->data) { + if ('' === (string) $appId->data) { return false; } @@ -194,7 +197,7 @@ class SpectrePrerequisites implements PrerequisitesInterface if (null === $secret) { return false; } - if ('' === (string)$secret->data) { + if ('' === (string) $secret->data) { return false; } diff --git a/app/Import/Prerequisites/YnabPrerequisites.php b/app/Import/Prerequisites/YnabPrerequisites.php index 87d22b72cb..234ea3201f 100644 --- a/app/Import/Prerequisites/YnabPrerequisites.php +++ b/app/Import/Prerequisites/YnabPrerequisites.php @@ -29,6 +29,9 @@ use Log; /** * Class YnabPrerequisites + * + * @deprecated + * @codeCoverageIgnore */ class YnabPrerequisites implements PrerequisitesInterface { @@ -129,7 +132,7 @@ class YnabPrerequisites implements PrerequisitesInterface if (null === $clientId) { return false; } - if ('' === (string)$clientId->data) { + if ('' === (string) $clientId->data) { return false; } @@ -147,7 +150,7 @@ class YnabPrerequisites implements PrerequisitesInterface if (null === $clientSecret) { return false; } - if ('' === (string)$clientSecret->data) { + if ('' === (string) $clientSecret->data) { return false; } diff --git a/app/Import/Routine/BunqRoutine.php b/app/Import/Routine/BunqRoutine.php index 9c1c1462ee..c70e425936 100644 --- a/app/Import/Routine/BunqRoutine.php +++ b/app/Import/Routine/BunqRoutine.php @@ -32,6 +32,9 @@ use Log; /** * Class BunqRoutine + * + * @deprecated + * @codeCoverageIgnore */ class BunqRoutine implements RoutineInterface { diff --git a/app/Import/Routine/FakeRoutine.php b/app/Import/Routine/FakeRoutine.php index babb494695..8e81b8fe4a 100644 --- a/app/Import/Routine/FakeRoutine.php +++ b/app/Import/Routine/FakeRoutine.php @@ -33,6 +33,9 @@ use Log; /** * Class FakeRoutine + * + * @deprecated + * @codeCoverageIgnore */ class FakeRoutine implements RoutineInterface { @@ -49,9 +52,9 @@ class FakeRoutine implements RoutineInterface * "ahoy": will log some nonsense and then drop job into status:"need_job_config" to force it back to the job config routine. * "final": will do some logging, sleep for 10 seconds and then finish. Generates 5 random transactions. * - * @return void * @throws FireflyException * + * @return void */ public function run(): void { diff --git a/app/Import/Routine/FileRoutine.php b/app/Import/Routine/FileRoutine.php index 589530bec2..c54d71b911 100644 --- a/app/Import/Routine/FileRoutine.php +++ b/app/Import/Routine/FileRoutine.php @@ -30,6 +30,9 @@ use Log; /** * Class FileRoutine + * + * @deprecated + * @codeCoverageIgnore */ class FileRoutine implements RoutineInterface { diff --git a/app/Import/Routine/FinTSRoutine.php b/app/Import/Routine/FinTSRoutine.php index f43156b6e1..6cb2f72f11 100644 --- a/app/Import/Routine/FinTSRoutine.php +++ b/app/Import/Routine/FinTSRoutine.php @@ -33,6 +33,9 @@ use Illuminate\Support\Facades\Log; /** * * Class FinTSRoutine + * + * @deprecated + * @codeCoverageIgnore */ class FinTSRoutine implements RoutineInterface { diff --git a/app/Import/Routine/RoutineInterface.php b/app/Import/Routine/RoutineInterface.php index edd2455ac3..8d02979e06 100644 --- a/app/Import/Routine/RoutineInterface.php +++ b/app/Import/Routine/RoutineInterface.php @@ -27,6 +27,9 @@ use FireflyIII\Models\ImportJob; /** * Interface RoutineInterface + * + * @deprecated + * @codeCoverageIgnore */ interface RoutineInterface { diff --git a/app/Import/Routine/SpectreRoutine.php b/app/Import/Routine/SpectreRoutine.php index 2fd536a92b..984ef19c68 100644 --- a/app/Import/Routine/SpectreRoutine.php +++ b/app/Import/Routine/SpectreRoutine.php @@ -32,6 +32,9 @@ use Log; /** * Class SpectreRoutine + * + * @deprecated + * @codeCoverageIgnore */ class SpectreRoutine implements RoutineInterface { diff --git a/app/Import/Routine/YnabRoutine.php b/app/Import/Routine/YnabRoutine.php index 9e687ed9a0..5b2cd57197 100644 --- a/app/Import/Routine/YnabRoutine.php +++ b/app/Import/Routine/YnabRoutine.php @@ -34,6 +34,9 @@ use Log; /** * Class YnabRoutine + * + * @deprecated + * @codeCoverageIgnore */ class YnabRoutine implements RoutineInterface { diff --git a/app/Import/Specifics/AbnAmroDescription.php b/app/Import/Specifics/AbnAmroDescription.php index 88b9b8bdf3..d15d42e35d 100644 --- a/app/Import/Specifics/AbnAmroDescription.php +++ b/app/Import/Specifics/AbnAmroDescription.php @@ -25,6 +25,9 @@ namespace FireflyIII\Import\Specifics; /** * Class AbnAmroDescription. * + * @deprecated + * @codeCoverageIgnore + * * Parses the description from txt files for ABN AMRO bank accounts. * * Based on the logic as described in the following Gist: @@ -79,7 +82,7 @@ class AbnAmroDescription implements SpecificInterface // If the description could not be parsed, specify an unknown opposing // account, as an opposing account is required if (!$parsed) { - $this->row[8] = (string)trans('firefly.unknown'); // opposing-account-name + $this->row[8] = (string) trans('firefly.unknown'); // opposing-account-name } return $this->row; diff --git a/app/Import/Specifics/Belfius.php b/app/Import/Specifics/Belfius.php index 626bf34a7f..cc208eab31 100644 --- a/app/Import/Specifics/Belfius.php +++ b/app/Import/Specifics/Belfius.php @@ -25,6 +25,9 @@ namespace FireflyIII\Import\Specifics; /** * Class Belfius. * + * @deprecated + * @codeCoverageIgnore + * * Fixes Belfius CSV files to: * - Correct descriptions for recurring transactions so doubles can be detected when the equivalent incoming * transaction is imported. @@ -54,19 +57,6 @@ class Belfius implements SpecificInterface return 'import.specific_belfius_name'; } - /** - * Run the fix. - * - * @param array $row - * - * @return array - * - */ - public function run(array $row): array - { - return Belfius::processRecurringTransactionDescription($row); - } - /** * Fixes the description for outgoing recurring transactions so doubles can be detected when the equivalent incoming * transaction is imported for another bank account. @@ -80,7 +70,7 @@ class Belfius implements SpecificInterface } $opposingAccountName = $row[5]; - $description = $row[14]; + $description = $row[14]; preg_match('/DOORLOPENDE OPDRACHT.*\s+' . preg_quote($opposingAccountName, '/') . '\s+(.+)\s+REF.\s*:/', $description, $matches); @@ -90,4 +80,17 @@ class Belfius implements SpecificInterface return $row; } + + /** + * Run the fix. + * + * @param array $row + * + * @return array + * + */ + public function run(array $row): array + { + return Belfius::processRecurringTransactionDescription($row); + } } diff --git a/app/Import/Specifics/IngBelgium.php b/app/Import/Specifics/IngBelgium.php index eb7ffdaf14..f31ce7b6c6 100644 --- a/app/Import/Specifics/IngBelgium.php +++ b/app/Import/Specifics/IngBelgium.php @@ -25,6 +25,9 @@ namespace FireflyIII\Import\Specifics; /** * Class IngBelgium. * + * @deprecated + * @codeCoverageIgnore + * * Parses the description and opposing account information (IBAN and name) from CSV files for ING Belgium bank accounts. * */ @@ -53,33 +56,26 @@ class IngBelgium implements SpecificInterface } /** - * Run the specific code. - * - * @param array $row - * - * @return array + * Gets the description from the transaction details and makes sure structured descriptions are in the + * "+++090/9337/55493+++" format. * + * @return string the description */ - public function run(array $row): array + protected static function description(string $transactionDetails): string { - return IngBelgium::processTransactionDetails($row); + $description = IngBelgium::parseInformationFromTransactionDetails($transactionDetails, '/Mededeling:\s*(.+)$/'); + + return IngBelgium::convertStructuredDescriptionToProperFormat($description); } /** - * Gets the description and opposing account information (IBAN and name) from the transaction details and adds - * them to the row of data. + * Gets the opposing account's IBAN from the transaction details. * - * @return array the row containing the description and opposing account's IBAN + * @return string the opposing account's IBAN */ - protected static function processTransactionDetails(array $row): array + protected static function opposingAccountIban(string $transactionDetails): string { - if(isset($row[9])) { - $transactionDetails = $row[9]; - $row[11] = IngBelgium::opposingAccountName($transactionDetails); - $row[12] = IngBelgium::opposingAccountIban($transactionDetails); - $row[13] = IngBelgium::description($transactionDetails); - } - return $row; + return IngBelgium::parseInformationFromTransactionDetails($transactionDetails, '/IBAN:\s*(.+?)(?=\s+)/'); } /** @@ -94,39 +90,36 @@ class IngBelgium implements SpecificInterface } /** - * Gets the opposing account's IBAN from the transaction details. + * Gets the description and opposing account information (IBAN and name) from the transaction details and adds + * them to the row of data. * - * @return string the opposing account's IBAN + * @return array the row containing the description and opposing account's IBAN */ - protected static function opposingAccountIban(string $transactionDetails): string + protected static function processTransactionDetails(array $row): array { - return IngBelgium::parseInformationFromTransactionDetails($transactionDetails, '/IBAN:\s*(.+?)(?=\s+)/'); - } + if (isset($row[9])) { + $transactionDetails = $row[9]; + $row[11] = IngBelgium::opposingAccountName($transactionDetails); + $row[12] = IngBelgium::opposingAccountIban($transactionDetails); + $row[13] = IngBelgium::description($transactionDetails); + } - /** - * Gets the description from the transaction details and makes sure structured descriptions are in the - * "+++090/9337/55493+++" format. - * - * @return string the description - */ - protected static function description(string $transactionDetails): string - { - $description = IngBelgium::parseInformationFromTransactionDetails($transactionDetails, '/Mededeling:\s*(.+)$/'); - return IngBelgium::convertStructuredDescriptionToProperFormat($description); + return $row; } private static function convertStructuredDescriptionToProperFormat(string $description): string { preg_match('/^\*\*\*(\d{3}\/\d{4}\/\d{5})\*\*\*$/', $description, $matches); - if(isset($matches[1])) { + if (isset($matches[1])) { return '+++' . $matches[1] . '+++'; } + return $description; } private static function parseInformationFromTransactionDetails(string $transactionDetails, string $regex): string { - if(isset($transactionDetails)) { + if (isset($transactionDetails)) { preg_match($regex, $transactionDetails, $matches); if (isset($matches[1])) { return trim($matches[1]); @@ -135,4 +128,17 @@ class IngBelgium implements SpecificInterface return ''; } + + /** + * Run the specific code. + * + * @param array $row + * + * @return array + * + */ + public function run(array $row): array + { + return IngBelgium::processTransactionDetails($row); + } } diff --git a/app/Import/Specifics/IngDescription.php b/app/Import/Specifics/IngDescription.php index 382c9bb8a4..684daade09 100644 --- a/app/Import/Specifics/IngDescription.php +++ b/app/Import/Specifics/IngDescription.php @@ -25,6 +25,9 @@ namespace FireflyIII\Import\Specifics; /** * Class IngDescription. * + * @deprecated + * @codeCoverageIgnore + * * Parses the description from CSV files for Ing bank accounts. * * With Mutation 'InternetBankieren', 'Overschrijving', 'Verzamelbetaling' and @@ -104,11 +107,14 @@ class IngDescription implements SpecificInterface } /** - * Remove "Omschrijving" (and NOT its value) from the description. + * Move "Valutadatum" from the description to new column. */ - protected function removeIngDescription(): void + protected function moveValutadatumDescription(): void { - $this->row[8] = preg_replace('/Omschrijving: /', '', $this->row[8]); + $matches = []; + preg_match('/Valutadatum: ([0-9-]+)/', $this->row[8], $matches); + $this->row[9] = date("Ymd", strtotime($matches[1])); + $this->row[8] = preg_replace('/Valutadatum: [0-9-]+/', '', $this->row[8]); } /** @@ -122,17 +128,17 @@ class IngDescription implements SpecificInterface } /** - * Remove "Naam" (and its value) from the description. + * Remove "Omschrijving" (and NOT its value) from the description. */ - protected function removeNameIngDescription(): void + protected function removeIngDescription(): void { - $this->row[8] = preg_replace('/Naam:.*?([a-zA-Z\/]+:)/', '$1', $this->row[8]); + $this->row[8] = preg_replace('/Omschrijving: /', '', $this->row[8]); } /** - * Move "Valutadatum" from the description to new column. + * Remove "Naam" (and its value) from the description. */ - protected function moveValutadatumDescription(): void + protected function removeNameIngDescription(): void { $matches = array(); if (preg_match('/Valutadatum: ([0-9-]+)/', $this->row[8], $matches)) { @@ -146,15 +152,15 @@ class IngDescription implements SpecificInterface */ private function MoveSavingsAccount(): void { - $matches = array(); - if ('' === (string)$this->row[3]) { + $matches = []; + if ('' === (string) $this->row[3]) { if (preg_match('/(Naar|Van) (.*rekening) ([0-9]+)/', $this->row[8], $matches)) { - $matches[3] = sprintf("%010d", $matches[3]); + $matches[3] = sprintf("%010d", $matches[3]); $this->row[1] = $matches[2]; // Savings account name $this->row[3] = $matches[3]; // Savings account number $this->row[8] = preg_replace('/(Naar|Van) (.*rekening) ([0-9]+)/', '', $this->row[8]); // Remove the savings account content from description } elseif (preg_match('/(Naar|Van) (.*rekening) ([0-9]+)/', $this->row[1], $matches)) { - $matches[3] = sprintf("%010d", $matches[3]); + $matches[3] = sprintf("%010d", $matches[3]); $this->row[1] = $matches[2]; // Savings account name $this->row[3] = $matches[3]; // Savings account number } diff --git a/app/Import/Specifics/PresidentsChoice.php b/app/Import/Specifics/PresidentsChoice.php index 737bec0f15..36abe52657 100644 --- a/app/Import/Specifics/PresidentsChoice.php +++ b/app/Import/Specifics/PresidentsChoice.php @@ -24,6 +24,9 @@ namespace FireflyIII\Import\Specifics; /** * Class PresidentsChoice. + * + * @deprecated + * @codeCoverageIgnore */ class PresidentsChoice implements SpecificInterface { diff --git a/app/Import/Specifics/SnsDescription.php b/app/Import/Specifics/SnsDescription.php index 7eeb9bbcf6..f36a683ee5 100644 --- a/app/Import/Specifics/SnsDescription.php +++ b/app/Import/Specifics/SnsDescription.php @@ -24,6 +24,9 @@ namespace FireflyIII\Import\Specifics; /** * Class SnsDescription. + * + * @codeCoverageIgnore + * @deprecated */ class SnsDescription implements SpecificInterface { diff --git a/app/Import/Specifics/SpecificInterface.php b/app/Import/Specifics/SpecificInterface.php index 9eaceb695b..b2a9a6e5fa 100644 --- a/app/Import/Specifics/SpecificInterface.php +++ b/app/Import/Specifics/SpecificInterface.php @@ -24,6 +24,9 @@ namespace FireflyIII\Import\Specifics; /** * Interface SpecificInterface. + * + * @codeCoverageIgnore + * @deprecated */ interface SpecificInterface { diff --git a/app/Import/Storage/ImportArrayStorage.php b/app/Import/Storage/ImportArrayStorage.php index 2ee636c9db..c73ec54186 100644 --- a/app/Import/Storage/ImportArrayStorage.php +++ b/app/Import/Storage/ImportArrayStorage.php @@ -32,17 +32,14 @@ use FireflyIII\Exceptions\FireflyException; use FireflyIII\Helpers\Collector\GroupCollectorInterface; use FireflyIII\Models\ImportJob; use FireflyIII\Models\Preference; -use FireflyIII\Models\Rule; use FireflyIII\Models\TransactionGroup; use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionType; use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; use FireflyIII\Repositories\Journal\JournalRepositoryInterface; -use FireflyIII\Repositories\Rule\RuleRepositoryInterface; use FireflyIII\Repositories\Tag\TagRepositoryInterface; use FireflyIII\Repositories\TransactionGroup\TransactionGroupRepositoryInterface; use FireflyIII\TransactionRules\Engine\RuleEngine; -use FireflyIII\TransactionRules\Processor; use Illuminate\Database\QueryException; use Illuminate\Support\Collection; use Log; @@ -52,6 +49,9 @@ use Log; * * Class ImportArrayStorage * + * @codeCoverageIgnore + * @deprecated + * */ class ImportArrayStorage { @@ -105,8 +105,8 @@ class ImportArrayStorage * - Link to tag * - Run rules (if set to) * - * @return Collection * @throws FireflyException + * @return Collection */ public function store(): Collection { @@ -131,7 +131,7 @@ class ImportArrayStorage app('preferences')->mark(); // email about this: - event(new RequestedReportOnJournals((int)$this->importJob->user_id, $collection)); + event(new RequestedReportOnJournals((int) $this->importJob->user_id, $collection)); return $collection; } @@ -216,7 +216,7 @@ class ImportArrayStorage $hash = $this->getHash($transaction); $existingId = $this->hashExists($hash); if (null !== $existingId) { - $message = (string)trans('import.duplicate_row', ['row' => $index, 'description' => $transaction['description']]); + $message = (string) trans('import.duplicate_row', ['row' => $index, 'description' => $transaction['description']]); $this->logDuplicateObject($transaction, $existingId); $this->repository->addErrorMessage($this->importJob, $message); @@ -225,7 +225,7 @@ class ImportArrayStorage // do transfer detection: if ($this->checkForTransfers && $this->transferExists($transaction)) { - $message = (string)trans('import.duplicate_row', ['row' => $index, 'description' => $transaction['description']]); + $message = (string) trans('import.duplicate_row', ['row' => $index, 'description' => $transaction['description']]); $this->logDuplicateTransfer($transaction); $this->repository->addErrorMessage($this->importJob, $message); @@ -319,7 +319,7 @@ class ImportArrayStorage } Log::info(sprintf('Found a transaction journal with an existing hash: %s', $hash)); - return (int)$entry->transaction_journal_id; + return (int) $entry->transaction_journal_id; } /** @@ -336,7 +336,7 @@ class ImportArrayStorage $repository = app(TagRepositoryInterface::class); $repository->setUser($this->importJob->user); $data = [ - 'tag' => (string)trans('import.import_with_key', ['key' => $this->importJob->key]), + 'tag' => (string) trans('import.import_with_key', ['key' => $this->importJob->key]), 'date' => new Carbon, 'description' => null, 'latitude' => null, @@ -473,9 +473,9 @@ class ImportArrayStorage /** * Store array as journals. * - * @return Collection * @throws FireflyException * + * @return Collection */ private function storeGroupArray(): Collection { @@ -529,21 +529,21 @@ class ImportArrayStorage // get the amount: /** @noinspection UnnecessaryCastingInspection */ - $amount = (string)($transaction['amount'] ?? '0'); + $amount = (string) ($transaction['amount'] ?? '0'); if (bccomp($amount, '0') === -1) { $amount = bcmul($amount, '-1'); // @codeCoverageIgnore } // get the description: //$description = '' === (string)$transaction['description'] ? $transaction['description'] : $transaction['description']; - $description = (string)$transaction['description']; + $description = (string) $transaction['description']; // get the source and destination ID's: - $transactionSourceIDs = [(int)$transaction['source_id'], (int)$transaction['destination_id']]; + $transactionSourceIDs = [(int) $transaction['source_id'], (int) $transaction['destination_id']]; sort($transactionSourceIDs); // get the source and destination names: - $transactionSourceNames = [(string)$transaction['source_name'], (string)$transaction['destination_name']]; + $transactionSourceNames = [(string) $transaction['source_name'], (string) $transaction['destination_name']]; sort($transactionSourceNames); // then loop all transfers: @@ -585,7 +585,7 @@ class ImportArrayStorage Log::debug(sprintf('Comparison is a hit! (%s)', $hits)); // compare source and destination id's - $transferSourceIDs = [(int)$transfer['source_account_id'], (int)$transfer['destination_account_id']]; + $transferSourceIDs = [(int) $transfer['source_account_id'], (int) $transfer['destination_account_id']]; sort($transferSourceIDs); /** @noinspection DisconnectedForeachInstructionInspection */ Log::debug('Comparing current transaction source+dest IDs', $transactionSourceIDs); @@ -600,7 +600,7 @@ class ImportArrayStorage unset($transferSourceIDs); // compare source and destination names - $transferSource = [(string)($transfer['source_account_name'] ?? ''), (string)($transfer['destination_account_name'] ?? '')]; + $transferSource = [(string) ($transfer['source_account_name'] ?? ''), (string) ($transfer['destination_account_name'] ?? '')]; sort($transferSource); /** @noinspection DisconnectedForeachInstructionInspection */ Log::debug('Comparing current transaction source+dest names', $transactionSourceNames); diff --git a/app/Jobs/CreateAutoBudgetLimits.php b/app/Jobs/CreateAutoBudgetLimits.php new file mode 100644 index 0000000000..2bf4be56ce --- /dev/null +++ b/app/Jobs/CreateAutoBudgetLimits.php @@ -0,0 +1,290 @@ +. + */ + +namespace FireflyIII\Jobs; + +use Carbon\Carbon; +use FireflyIII\Exceptions\FireflyException; +use FireflyIII\Models\AutoBudget; +use FireflyIII\Models\Budget; +use FireflyIII\Models\BudgetLimit; +use FireflyIII\Repositories\Budget\OperationsRepositoryInterface; +use Illuminate\Bus\Queueable; +use Illuminate\Contracts\Queue\ShouldQueue; +use Illuminate\Foundation\Bus\Dispatchable; +use Illuminate\Queue\InteractsWithQueue; +use Illuminate\Queue\SerializesModels; +use Illuminate\Support\Collection; +use Log; + +/** + * Class CreateAutoBudgetLimits + */ +class CreateAutoBudgetLimits implements ShouldQueue +{ + use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; + + /** @var Carbon The current date */ + private $date; + + /** + * Create a new job instance. + * + * @codeCoverageIgnore + * + * @param Carbon $date + */ + public function __construct(?Carbon $date) + { + if (null !== $date) { + $date->startOfDay(); + $this->date = $date; + } + Log::debug(sprintf('Created new CreateAutoBudgetLimits("%s")', $this->date->format('Y-m-d'))); + } + + /** + * Execute the job. + * + * @throws FireflyException + */ + public function handle(): void + { + Log::debug(sprintf('Now at start of CreateAutoBudgetLimits() job for %s.', $this->date->format('D d M Y'))); + $autoBudgets = AutoBudget::get(); + Log::debug(sprintf('Found %d auto budgets.', $autoBudgets->count())); + foreach ($autoBudgets as $autoBudget) { + $this->handleAutoBudget($autoBudget); + } + } + + /** + * @param Carbon $date + */ + public function setDate(Carbon $date): void + { + $date->startOfDay(); + $this->date = $date; + } + + /** + * @param AutoBudget $autoBudget + * @param Carbon $start + * @param Carbon $end + * @param string|null $amount + */ + private function createBudgetLimit(AutoBudget $autoBudget, Carbon $start, Carbon $end, ?string $amount = null) + { + 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->budget()->associate($autoBudget->budget); + $budgetLimit->transactionCurrency()->associate($autoBudget->transactionCurrency); + $budgetLimit->start_date = $start; + $budgetLimit->end_date = $end; + $budgetLimit->amount = $amount ?? $autoBudget->amount; + $budgetLimit->save(); + + Log::debug(sprintf('Created budget limit #%d.', $budgetLimit->id)); + } + + /** + * @param AutoBudget $autoBudget + */ + private function createRollover(AutoBudget $autoBudget): void + { + Log::debug(sprintf('Will now manage rollover for auto budget #%d', $autoBudget->id)); + // current period: + $start = app('navigation')->startOfPeriod($this->date, $autoBudget->period); + $end = app('navigation')->endOfPeriod($start, $autoBudget->period); + + // which means previous period: + $previousStart = app('navigation')->subtractPeriod($start, $autoBudget->period); + $previousEnd = app('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') + ) + ); + + // has budget limit in previous period? + $budgetLimit = $this->findBudgetLimit($autoBudget->budget, $previousStart, $previousEnd); + + if (null === $budgetLimit) { + Log::debug('No budget limit exists in previous period, so create one.'); + // if not, create it and we're done. + $this->createBudgetLimit($autoBudget, $start, $end); + Log::debug(sprintf('Done with auto budget #%d', $autoBudget->id)); + + return; + } + Log::debug('Budget limit exists for previous period.'); + // if has one, calculate expenses and use that as a base. + $repository = app(OperationsRepositoryInterface::class); + $repository->setUser($autoBudget->budget->user); + $spent = $repository->sumExpenses($previousStart, $previousEnd, null, new Collection([$autoBudget->budget]), $autoBudget->transactionCurrency); + $currencyId = (int) $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)); + + // previous budget limit + this period + spent + $totalAmount = bcadd(bcadd($budgetLimit->amount, $autoBudget->amount), $spentAmount); + Log::debug(sprintf('Total amount for current budget period will be %s', $totalAmount)); + + if (1 !== bccomp($totalAmount, '0')) { + Log::info(sprintf('The total amount is negative, so it will be reset to %s.', $totalAmount)); + $totalAmount = $autoBudget->amount; + } + + // create budget limit: + $this->createBudgetLimit($autoBudget, $start, $end, $totalAmount); + Log::debug(sprintf('Done with auto budget #%d', $autoBudget->id)); + } + + /** + * @param Budget $budget + * @param Carbon $start + * @param Carbon $end + * + * @return BudgetLimit|null + */ + private function findBudgetLimit(Budget $budget, Carbon $start, Carbon $end): ?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') + ) + ); + + return $budget->budgetlimits() + ->where('start_date', $start->format('Y-m-d')) + ->where('end_date', $end->format('Y-m-d'))->first(); + } + + /** + * @param AutoBudget $autoBudget + * + * @throws FireflyException + */ + private function handleAutoBudget(AutoBudget $autoBudget): void + { + 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")', + $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 = app('navigation')->startOfPeriod($this->date, $autoBudget->period); + $end = app('navigation')->endOfPeriod($start, $autoBudget->period); + + // find budget limit: + $budgetLimit = $this->findBudgetLimit($autoBudget->budget, $start, $end); + + if (null === $budgetLimit && AutoBudget::AUTO_BUDGET_RESET === $autoBudget->auto_budget_type) { + // that's easy: create one. + // do nothing else. + $this->createBudgetLimit($autoBudget, $start, $end); + Log::debug(sprintf('Done with auto budget #%d', $autoBudget->id)); + + return; + } + + if (null === $budgetLimit && AutoBudget::AUTO_BUDGET_ROLLOVER === $autoBudget->auto_budget_type) { + // budget limit exists already, + $this->createRollover($autoBudget); + Log::debug(sprintf('Done with auto budget #%d', $autoBudget->id)); + + return; + } + Log::debug(sprintf('Done with auto budget #%d', $autoBudget->id)); + } + + /** + * @param AutoBudget $autoBudget + * + * @throws FireflyException + * @return bool + */ + private function isMagicDay(AutoBudget $autoBudget): bool + { + switch ($autoBudget->period) { + default: + throw new FireflyException(sprintf('isMagicDay() can\'t handle period "%s"', $autoBudget->period)); + case 'daily': + // every day is magic! + return true; + case 'weekly': + // fire on Monday. + return $this->date->isMonday(); + case 'monthly': + return 1 === $this->date->day; + case 'quarterly': + $format = 'm-d'; + $value = $this->date->format($format); + + return in_array($value, ['01-01', '04-01', '07-01', '10-01'], true); + case 'half_year': + $format = 'm-d'; + $value = $this->date->format($format); + + return in_array($value, ['01-01', '07-01'], true); + break; + case 'yearly': + $format = 'm-d'; + $value = $this->date->format($format); + + return '01-01' === $value; + } + } +} diff --git a/app/Jobs/CreateRecurringTransactions.php b/app/Jobs/CreateRecurringTransactions.php index 6c6d32d54c..965609ed27 100644 --- a/app/Jobs/CreateRecurringTransactions.php +++ b/app/Jobs/CreateRecurringTransactions.php @@ -52,35 +52,26 @@ class CreateRecurringTransactions implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; - /** @var Carbon The current date */ - private $date; - /** @var JournalRepositoryInterface Journal repository */ - private $journalRepository; - /** @var TransactionGroupRepositoryInterface */ - private $groupRepository; - /** @var RecurringRepositoryInterface Recurring transactions repository. */ - private $repository; - /** @var bool Force the transaction to be created no matter what. */ - private $force; - - /** @var int Number of recurrences submitted */ - public $submitted; - /** @var int Number of recurrences actually fired */ - public $executed; /** @var int Transaction groups created */ public $created; - - /** - * @param Carbon $date - */ - public function setDate(Carbon $date): void - { - $date->startOfDay(); - $this->date = $date; - } + /** @var int Number of recurrences actually fired */ + public $executed; + /** @var int Number of recurrences submitted */ + public $submitted; + /** @var Carbon The current date */ + private $date; + /** @var bool Force the transaction to be created no matter what. */ + private $force; + /** @var TransactionGroupRepositoryInterface */ + private $groupRepository; + /** @var JournalRepositoryInterface Journal repository */ + private $journalRepository; + /** @var RecurringRepositoryInterface Recurring transactions repository. */ + private $repository; /** * Create a new job instance. + * * @codeCoverageIgnore * * @param Carbon $date @@ -100,15 +91,6 @@ class CreateRecurringTransactions implements ShouldQueue $this->created = 0; Log::debug(sprintf('Created new CreateRecurringTransactions("%s")', $this->date->format('Y-m-d'))); - - } - - /** - * @param bool $force - */ - public function setForce(bool $force): void - { - $this->force = $force; } /** @@ -157,6 +139,23 @@ class CreateRecurringTransactions implements ShouldQueue app('preferences')->mark(); } + /** + * @param Carbon $date + */ + public function setDate(Carbon $date): void + { + $date->startOfDay(); + $this->date = $date; + } + + /** + * @param bool $force + */ + public function setForce(bool $force): void + { + $this->force = $force; + } + /** * Return recurring transaction is active. * @@ -186,6 +185,20 @@ class CreateRecurringTransactions implements ShouldQueue return $return; } + /** + * @param Collection $recurrences + * + * @return Collection + */ + private function filterRecurrences(Collection $recurrences): Collection + { + return $recurrences->filter( + function (Recurrence $recurrence) { + return $this->validRecurrence($recurrence); + } + ); + } + /** * Get the start date of a recurrence. * @@ -207,7 +220,7 @@ class CreateRecurringTransactions implements ShouldQueue * Get transaction information from a recurring transaction. * * @param Recurrence $recurrence - * @param Carbon $date + * @param Carbon $date * * @return array * @@ -222,7 +235,7 @@ class CreateRecurringTransactions implements ShouldQueue 'type' => strtolower($recurrence->transactionType->type), 'date' => $date, 'user' => $recurrence->user_id, - 'currency_id' => (int)$transaction->transaction_currency_id, + 'currency_id' => (int) $transaction->transaction_currency_id, 'currency_code' => null, 'description' => $recurrence->recurrenceTransactions()->first()->description, 'amount' => $transaction->amount, @@ -239,9 +252,9 @@ class CreateRecurringTransactions implements ShouldQueue 'foreign_amount' => $transaction->foreign_amount, 'reconciled' => false, 'identifier' => $index, - 'recurrence_id' => (int)$recurrence->id, + 'recurrence_id' => (int) $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, @@ -255,30 +268,9 @@ class CreateRecurringTransactions implements ShouldQueue } /** - * Check if the occurences should be executed. - * * @param Recurrence $recurrence - * @param array $occurrences + * @param Carbon $date * - * @return Collection - */ - private function handleOccurrences(Recurrence $recurrence, array $occurrences): Collection - { - $collection = new Collection; - /** @var Carbon $date */ - foreach ($occurrences as $date) { - $result = $this->handleOccurrence($recurrence, $date); - if (null !== $result) { - $collection->push($result); - } - } - - return $collection; - } - - /** - * @param Recurrence $recurrence - * @param Carbon $date * @return TransactionGroup|null */ private function handleOccurrence(Recurrence $recurrence, Carbon $date): ?TransactionGroup @@ -336,6 +328,28 @@ class CreateRecurringTransactions implements ShouldQueue return $group; } + /** + * Check if the occurences should be executed. + * + * @param Recurrence $recurrence + * @param array $occurrences + * + * @return Collection + */ + private function handleOccurrences(Recurrence $recurrence, array $occurrences): Collection + { + $collection = new Collection; + /** @var Carbon $date */ + foreach ($occurrences as $date) { + $result = $this->handleOccurrence($recurrence, $date); + if (null !== $result) { + $collection->push($result); + } + } + + return $collection; + } + /** * Separate method that will loop all repetitions and do something with it. Will return * all created transaction journals. @@ -351,7 +365,9 @@ class CreateRecurringTransactions implements ShouldQueue 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, + 'Now repeating %s with value "%s", skips every %d time(s)', + $repetition->repetition_type, + $repetition->repetition_moment, $repetition->repetition_skip ) ); @@ -367,7 +383,8 @@ class CreateRecurringTransactions implements ShouldQueue count($occurrences), $recurrence->first_date->format('Y-m-d'), $includeWeekend->format('Y-m-d') - ), $this->debugArray($occurrences) + ), + $this->debugArray($occurrences) ); unset($includeWeekend); @@ -404,6 +421,24 @@ class CreateRecurringTransactions implements ShouldQueue return $startDate->gt($this->date); } + /*** + * @param Recurrence $recurrence + * @param TransactionGroup $group + */ + private function linkGroupToPiggies(Recurrence $recurrence, TransactionGroup $group): void + { + /** @var TransactionJournal $journal */ + foreach ($group->transactionJournals as $journal) { + // get piggy bank ID from meta data: + $piggyBank = $this->repository->getPiggyBank($recurrence); + if (null !== $piggyBank) { + /** @var PiggyBankEventFactory $factory */ + $factory = app(PiggyBankEventFactory::class); + $factory->create($journal, $piggyBank); + } + } + } + /** * Return true if the $repeat_until date is in the past. * @@ -479,39 +514,5 @@ class CreateRecurringTransactions implements ShouldQueue } return true; - - } - - /** - * @param Collection $recurrences - * @return Collection - */ - private function filterRecurrences(Collection $recurrences): Collection - { - return $recurrences->filter( - function (Recurrence $recurrence) { - return $this->validRecurrence($recurrence); - } - ); - } - - /*** - * @param Recurrence $recurrence - * @param TransactionGroup $group - */ - private function linkGroupToPiggies(Recurrence $recurrence, TransactionGroup $group): void - { - /** @var TransactionJournal $journal */ - foreach ($group->transactionJournals as $journal) { - // get piggy bank ID from meta data: - $piggyBank = $this->repository->getPiggyBank($recurrence); - if (null !== $piggyBank) { - /** @var PiggyBankEventFactory $factory */ - $factory = app(PiggyBankEventFactory::class); - $factory->create($journal, $piggyBank); - } - - } - } } diff --git a/app/Jobs/MailError.php b/app/Jobs/MailError.php index b0253dc3f7..abcc87a586 100644 --- a/app/Jobs/MailError.php +++ b/app/Jobs/MailError.php @@ -32,6 +32,7 @@ use Mail; /** * Class MailError. + * * @codeCoverageIgnore */ class MailError extends Job implements ShouldQueue diff --git a/app/Mail/ReportNewJournalsMail.php b/app/Mail/ReportNewJournalsMail.php index 8e1424b807..26da94db1d 100644 --- a/app/Mail/ReportNewJournalsMail.php +++ b/app/Mail/ReportNewJournalsMail.php @@ -42,12 +42,10 @@ class ReportNewJournalsMail extends Mailable /** @var string Email address of the user */ public $email; - /** @var string IP address of user (if known) */ - public $ipAddress; - /** @var Collection A collection of groups */ public $groups; - + /** @var string IP address of user (if known) */ + public $ipAddress; /** @var array All groups, transformed to array. */ public $transformed; @@ -72,10 +70,11 @@ class ReportNewJournalsMail extends Mailable */ public function build(): self { - $subject = 1 === $this->groups->count() + $subject = 1 === $this->groups->count() ? 'Firefly III has created a new transaction' : sprintf( - 'Firefly III has created new %d transactions', $this->groups->count() + 'Firefly III has created new %d transactions', + $this->groups->count() ); $this->transform(); diff --git a/app/Models/Account.php b/app/Models/Account.php index 74ba6610cb..118856a481 100644 --- a/app/Models/Account.php +++ b/app/Models/Account.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Models; use Carbon\Carbon; +use Eloquent; use FireflyIII\User; use Illuminate\Database\Eloquent\Builder as EloquentBuilder; use Illuminate\Database\Eloquent\Model; @@ -30,6 +31,7 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\MorphMany; use Illuminate\Database\Eloquent\SoftDeletes; +use Illuminate\Database\Query\Builder; use Illuminate\Support\Collection; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; @@ -50,39 +52,39 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; * @property Collection accountMeta * @property bool encrypted * @property int account_type_id - * @property Collection piggyBanks - * @property string $interest - * @property string $interestPeriod - * @property string accountTypeString - * @property Carbon created_at - * @property Carbon updated_at + * @property Collection piggyBanks + * @property string $interest + * @property string $interestPeriod + * @property string accountTypeString + * @property Carbon created_at + * @property Carbon updated_at * @SuppressWarnings (PHPMD.CouplingBetweenObjects) - * @property \Illuminate\Support\Carbon|null $deleted_at - * @property int $user_id - * @property-read string $edit_name - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Note[] $notes - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Transaction[] $transactions - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Account accountTypeIn($types) + * @property \Illuminate\Support\Carbon|null $deleted_at + * @property int $user_id + * @property-read string $edit_name + * @property-read \Illuminate\Database\Eloquent\Collection|Note[] $notes + * @property-read \Illuminate\Database\Eloquent\Collection|Transaction[] $transactions + * @method static EloquentBuilder|Account accountTypeIn($types) * @method static bool|null forceDelete() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Account newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Account newQuery() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Account onlyTrashed() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Account query() + * @method static EloquentBuilder|Account newModelQuery() + * @method static EloquentBuilder|Account newQuery() + * @method static Builder|Account onlyTrashed() + * @method static EloquentBuilder|Account query() * @method static bool|null restore() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Account whereAccountTypeId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Account whereActive($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Account whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Account whereDeletedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Account whereEncrypted($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Account whereIban($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Account whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Account whereName($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Account whereUpdatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Account whereUserId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Account whereVirtualBalance($value) - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Account withTrashed() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Account withoutTrashed() - * @mixin \Eloquent + * @method static EloquentBuilder|Account whereAccountTypeId($value) + * @method static EloquentBuilder|Account whereActive($value) + * @method static EloquentBuilder|Account whereCreatedAt($value) + * @method static EloquentBuilder|Account whereDeletedAt($value) + * @method static EloquentBuilder|Account whereEncrypted($value) + * @method static EloquentBuilder|Account whereIban($value) + * @method static EloquentBuilder|Account whereId($value) + * @method static EloquentBuilder|Account whereName($value) + * @method static EloquentBuilder|Account whereUpdatedAt($value) + * @method static EloquentBuilder|Account whereUserId($value) + * @method static EloquentBuilder|Account whereVirtualBalance($value) + * @method static Builder|Account withTrashed() + * @method static Builder|Account withoutTrashed() + * @mixin Eloquent */ class Account extends Model { @@ -114,13 +116,13 @@ class Account extends Model * * @param string $value * - * @return Account * @throws NotFoundHttpException + * @return Account */ public static function routeBinder(string $value): Account { if (auth()->check()) { - $accountId = (int)$value; + $accountId = (int) $value; /** @var User $user */ $user = auth()->user(); /** @var Account $account */ @@ -150,15 +152,6 @@ class Account extends Model return $this->belongsTo(AccountType::class); } - /** - * @codeCoverageIgnore - * @return MorphMany - */ - public function locations(): MorphMany - { - return $this->morphMany(Location::class, 'locatable'); - } - /** * Get the account number. * @@ -189,6 +182,15 @@ class Account extends Model return $name; } + /** + * @codeCoverageIgnore + * @return MorphMany + */ + public function locations(): MorphMany + { + return $this->morphMany(Location::class, 'locatable'); + } + /** * @codeCoverageIgnore * Get all of the notes. @@ -231,7 +233,7 @@ class Account extends Model */ public function setVirtualBalanceAttribute($value): void { - $this->attributes['virtual_balance'] = (string)$value; + $this->attributes['virtual_balance'] = (string) $value; } /** diff --git a/app/Models/AccountMeta.php b/app/Models/AccountMeta.php index c8e070c355..66b8fe7b7c 100644 --- a/app/Models/AccountMeta.php +++ b/app/Models/AccountMeta.php @@ -22,29 +22,32 @@ declare(strict_types=1); namespace FireflyIII\Models; +use Eloquent; +use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; +use Illuminate\Support\Carbon; /** * Class AccountMeta. * - * @property string $data - * @property string $name - * @property int $account_id - * @property int $id - * @property \Illuminate\Support\Carbon|null $created_at - * @property \Illuminate\Support\Carbon|null $updated_at - * @property-read \FireflyIII\Models\Account $account - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\AccountMeta newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\AccountMeta newQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\AccountMeta query() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\AccountMeta whereAccountId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\AccountMeta whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\AccountMeta whereData($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\AccountMeta whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\AccountMeta whereName($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\AccountMeta whereUpdatedAt($value) - * @mixin \Eloquent + * @property string $data + * @property string $name + * @property int $account_id + * @property int $id + * @property Carbon|null $created_at + * @property Carbon|null $updated_at + * @property-read Account $account + * @method static Builder|AccountMeta newModelQuery() + * @method static Builder|AccountMeta newQuery() + * @method static Builder|AccountMeta query() + * @method static Builder|AccountMeta whereAccountId($value) + * @method static Builder|AccountMeta whereCreatedAt($value) + * @method static Builder|AccountMeta whereData($value) + * @method static Builder|AccountMeta whereId($value) + * @method static Builder|AccountMeta whereName($value) + * @method static Builder|AccountMeta whereUpdatedAt($value) + * @mixin Eloquent */ class AccountMeta extends Model { diff --git a/app/Models/AccountType.php b/app/Models/AccountType.php index 243de012a6..0debf344a7 100644 --- a/app/Models/AccountType.php +++ b/app/Models/AccountType.php @@ -22,25 +22,29 @@ declare(strict_types=1); namespace FireflyIII\Models; +use Eloquent; +use Illuminate\Database\Eloquent\Builder; +use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; +use Illuminate\Support\Carbon; /** * Class AccountType. * - * @property string $type + * @property string $type * @method whereType(string $type) - * @property int $id - * @property \Illuminate\Support\Carbon|null $created_at - * @property \Illuminate\Support\Carbon|null $updated_at - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Account[] $accounts - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\AccountType newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\AccountType newQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\AccountType query() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\AccountType whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\AccountType whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\AccountType whereUpdatedAt($value) - * @mixin \Eloquent + * @property int $id + * @property Carbon|null $created_at + * @property Carbon|null $updated_at + * @property-read Collection|Account[] $accounts + * @method static Builder|AccountType newModelQuery() + * @method static Builder|AccountType newQuery() + * @method static Builder|AccountType query() + * @method static Builder|AccountType whereCreatedAt($value) + * @method static Builder|AccountType whereId($value) + * @method static Builder|AccountType whereUpdatedAt($value) + * @mixin Eloquent */ class AccountType extends Model { diff --git a/app/Models/Attachment.php b/app/Models/Attachment.php index c052c376bf..a885ff1505 100644 --- a/app/Models/Attachment.php +++ b/app/Models/Attachment.php @@ -23,58 +23,61 @@ declare(strict_types=1); namespace FireflyIII\Models; use Carbon\Carbon; +use Eloquent; use FireflyIII\User; +use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\MorphMany; use Illuminate\Database\Eloquent\Relations\MorphTo; use Illuminate\Database\Eloquent\SoftDeletes; +use Illuminate\Database\Query\Builder; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** * Class Attachment. * - * @property int $id - * @property Carbon $created_at - * @property Carbon $updated_at - * @property string $attachable_type - * @property string $md5 - * @property string $filename - * @property string $title - * @property string $description - * @property string $notes - * @property string $mime - * @property int $size - * @property User $user - * @property bool $uploaded - * @property bool file_exists - * @property \Illuminate\Support\Carbon|null $deleted_at - * @property int $user_id - * @property int $attachable_id - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Attachment[] $attachable + * @property int $id + * @property Carbon $created_at + * @property Carbon $updated_at + * @property string $attachable_type + * @property string $md5 + * @property string $filename + * @property string $title + * @property string $description + * @property string $notes + * @property string $mime + * @property int $size + * @property User $user + * @property bool $uploaded + * @property bool file_exists + * @property \Illuminate\Support\Carbon|null $deleted_at + * @property int $user_id + * @property int $attachable_id + * @property-read Collection|Attachment[] $attachable * @method static bool|null forceDelete() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Attachment newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Attachment newQuery() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Attachment onlyTrashed() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Attachment query() + * @method static \Illuminate\Database\Eloquent\Builder|Attachment newModelQuery() + * @method static \Illuminate\Database\Eloquent\Builder|Attachment newQuery() + * @method static Builder|Attachment onlyTrashed() + * @method static \Illuminate\Database\Eloquent\Builder|Attachment query() * @method static bool|null restore() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Attachment whereAttachableId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Attachment whereAttachableType($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Attachment whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Attachment whereDeletedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Attachment whereDescription($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Attachment whereFilename($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Attachment whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Attachment whereMd5($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Attachment whereMime($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Attachment whereSize($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Attachment whereTitle($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Attachment whereUpdatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Attachment whereUploaded($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Attachment whereUserId($value) - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Attachment withTrashed() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Attachment withoutTrashed() - * @mixin \Eloquent + * @method static \Illuminate\Database\Eloquent\Builder|Attachment whereAttachableId($value) + * @method static \Illuminate\Database\Eloquent\Builder|Attachment whereAttachableType($value) + * @method static \Illuminate\Database\Eloquent\Builder|Attachment whereCreatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|Attachment whereDeletedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|Attachment whereDescription($value) + * @method static \Illuminate\Database\Eloquent\Builder|Attachment whereFilename($value) + * @method static \Illuminate\Database\Eloquent\Builder|Attachment whereId($value) + * @method static \Illuminate\Database\Eloquent\Builder|Attachment whereMd5($value) + * @method static \Illuminate\Database\Eloquent\Builder|Attachment whereMime($value) + * @method static \Illuminate\Database\Eloquent\Builder|Attachment whereSize($value) + * @method static \Illuminate\Database\Eloquent\Builder|Attachment whereTitle($value) + * @method static \Illuminate\Database\Eloquent\Builder|Attachment whereUpdatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|Attachment whereUploaded($value) + * @method static \Illuminate\Database\Eloquent\Builder|Attachment whereUserId($value) + * @method static Builder|Attachment withTrashed() + * @method static Builder|Attachment withoutTrashed() + * @mixin Eloquent */ class Attachment extends Model { @@ -100,13 +103,13 @@ class Attachment extends Model * * @param string $value * - * @return Attachment * @throws NotFoundHttpException + * @return Attachment */ public static function routeBinder(string $value): Attachment { if (auth()->check()) { - $attachmentId = (int)$value; + $attachmentId = (int) $value; /** @var User $user */ $user = auth()->user(); /** @var Attachment $attachment */ @@ -138,7 +141,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); } /** diff --git a/app/Models/AutoBudget.php b/app/Models/AutoBudget.php new file mode 100644 index 0000000000..4d9dd6c834 --- /dev/null +++ b/app/Models/AutoBudget.php @@ -0,0 +1,57 @@ +. + */ + +namespace FireflyIII\Models; + +use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Relations\BelongsTo; +use Illuminate\Database\Eloquent\SoftDeletes; + +/** + * Class AutoBudget + */ +class AutoBudget extends Model +{ + /** @var int When the auto-budget resets every period automatically. */ + public const AUTO_BUDGET_RESET = 1; + /** @var int When the auto-budget adds an amount every period automatically */ + public const AUTO_BUDGET_ROLLOVER = 2; + + use SoftDeletes; + + /** + * @codeCoverageIgnore + * @return BelongsTo + */ + public function budget(): BelongsTo + { + return $this->belongsTo(Budget::class); + } + + /** + * @codeCoverageIgnore + * @return BelongsTo + */ + public function transactionCurrency(): BelongsTo + { + return $this->belongsTo(TransactionCurrency::class); + } +} diff --git a/app/Models/AvailableBudget.php b/app/Models/AvailableBudget.php index 74ed3589af..d046ba27e8 100644 --- a/app/Models/AvailableBudget.php +++ b/app/Models/AvailableBudget.php @@ -23,44 +23,46 @@ declare(strict_types=1); namespace FireflyIII\Models; use Carbon\Carbon; +use Eloquent; use FireflyIII\User; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\SoftDeletes; +use Illuminate\Database\Query\Builder; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** * Class AvailableBudget. * - * @property int $id - * @property Carbon $created_at - * @property Carbon $updated_at - * @property User $user - * @property TransactionCurrency $transactionCurrency - * @property int $transaction_currency_id - * @property Carbon $start_date - * @property Carbon $end_date - * @property string $amount + * @property int $id + * @property Carbon $created_at + * @property Carbon $updated_at + * @property User $user + * @property TransactionCurrency $transactionCurrency + * @property int $transaction_currency_id + * @property Carbon $start_date + * @property Carbon $end_date + * @property string $amount * @property \Illuminate\Support\Carbon|null $deleted_at - * @property int $user_id + * @property int $user_id * @method static bool|null forceDelete() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\AvailableBudget newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\AvailableBudget newQuery() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\AvailableBudget onlyTrashed() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\AvailableBudget query() + * @method static \Illuminate\Database\Eloquent\Builder|AvailableBudget newModelQuery() + * @method static \Illuminate\Database\Eloquent\Builder|AvailableBudget newQuery() + * @method static Builder|AvailableBudget onlyTrashed() + * @method static \Illuminate\Database\Eloquent\Builder|AvailableBudget query() * @method static bool|null restore() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\AvailableBudget whereAmount($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\AvailableBudget whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\AvailableBudget whereDeletedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\AvailableBudget whereEndDate($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\AvailableBudget whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\AvailableBudget whereStartDate($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\AvailableBudget whereTransactionCurrencyId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\AvailableBudget whereUpdatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\AvailableBudget whereUserId($value) - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\AvailableBudget withTrashed() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\AvailableBudget withoutTrashed() - * @mixin \Eloquent + * @method static \Illuminate\Database\Eloquent\Builder|AvailableBudget whereAmount($value) + * @method static \Illuminate\Database\Eloquent\Builder|AvailableBudget whereCreatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|AvailableBudget whereDeletedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|AvailableBudget whereEndDate($value) + * @method static \Illuminate\Database\Eloquent\Builder|AvailableBudget whereId($value) + * @method static \Illuminate\Database\Eloquent\Builder|AvailableBudget whereStartDate($value) + * @method static \Illuminate\Database\Eloquent\Builder|AvailableBudget whereTransactionCurrencyId($value) + * @method static \Illuminate\Database\Eloquent\Builder|AvailableBudget whereUpdatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|AvailableBudget whereUserId($value) + * @method static Builder|AvailableBudget withTrashed() + * @method static Builder|AvailableBudget withoutTrashed() + * @mixin Eloquent */ class AvailableBudget extends Model { @@ -87,13 +89,13 @@ class AvailableBudget extends Model * * @param string $value * - * @return AvailableBudget * @throws NotFoundHttpException + * @return AvailableBudget */ public static function routeBinder(string $value): AvailableBudget { if (auth()->check()) { - $availableBudgetId = (int)$value; + $availableBudgetId = (int) $value; /** @var User $user */ $user = auth()->user(); /** @var AvailableBudget $availableBudget */ diff --git a/app/Models/Bill.php b/app/Models/Bill.php index b4f0439844..a707ffcabc 100644 --- a/app/Models/Bill.php +++ b/app/Models/Bill.php @@ -23,69 +23,71 @@ declare(strict_types=1); namespace FireflyIII\Models; use Carbon\Carbon; +use Eloquent; use FireflyIII\User; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\MorphMany; use Illuminate\Database\Eloquent\SoftDeletes; +use Illuminate\Database\Query\Builder; use Illuminate\Support\Collection; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** * Class Bill. * - * @property bool $active - * @property int $transaction_currency_id - * @property string $amount_min - * @property string $amount_max - * @property int $id - * @property string $name - * @property Collection $notes - * @property TransactionCurrency $transactionCurrency - * @property Carbon $created_at - * @property Carbon $updated_at - * @property Carbon $date - * @property string $repeat_freq - * @property int $skip - * @property bool $automatch - * @property User $user - * @property string $match - * @property bool match_encrypted - * @property bool name_encrypted + * @property bool $active + * @property int $transaction_currency_id + * @property string $amount_min + * @property string $amount_max + * @property int $id + * @property string $name + * @property Collection $notes + * @property TransactionCurrency $transactionCurrency + * @property Carbon $created_at + * @property Carbon $updated_at + * @property Carbon $date + * @property string $repeat_freq + * @property int $skip + * @property bool $automatch + * @property User $user + * @property string $match + * @property bool match_encrypted + * @property bool name_encrypted * @SuppressWarnings (PHPMD.CouplingBetweenObjects) - * @property \Illuminate\Support\Carbon|null $deleted_at - * @property int $user_id - * @property bool $name_encrypted - * @property bool $match_encrypted - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Attachment[] $attachments - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\TransactionJournal[] $transactionJournals + * @property \Illuminate\Support\Carbon|null $deleted_at + * @property int $user_id + * @property bool $name_encrypted + * @property bool $match_encrypted + * @property-read \Illuminate\Database\Eloquent\Collection|Attachment[] $attachments + * @property-read \Illuminate\Database\Eloquent\Collection|TransactionJournal[] $transactionJournals * @method static bool|null forceDelete() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Bill newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Bill newQuery() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Bill onlyTrashed() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Bill query() + * @method static \Illuminate\Database\Eloquent\Builder|Bill newModelQuery() + * @method static \Illuminate\Database\Eloquent\Builder|Bill newQuery() + * @method static Builder|Bill onlyTrashed() + * @method static \Illuminate\Database\Eloquent\Builder|Bill query() * @method static bool|null restore() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Bill whereActive($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Bill whereAmountMax($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Bill whereAmountMin($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Bill whereAutomatch($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Bill whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Bill whereDate($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Bill whereDeletedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Bill whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Bill whereMatch($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Bill whereMatchEncrypted($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Bill whereName($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Bill whereNameEncrypted($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Bill whereRepeatFreq($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Bill whereSkip($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Bill whereTransactionCurrencyId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Bill whereUpdatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Bill whereUserId($value) - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Bill withTrashed() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Bill withoutTrashed() - * @mixin \Eloquent + * @method static \Illuminate\Database\Eloquent\Builder|Bill whereActive($value) + * @method static \Illuminate\Database\Eloquent\Builder|Bill whereAmountMax($value) + * @method static \Illuminate\Database\Eloquent\Builder|Bill whereAmountMin($value) + * @method static \Illuminate\Database\Eloquent\Builder|Bill whereAutomatch($value) + * @method static \Illuminate\Database\Eloquent\Builder|Bill whereCreatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|Bill whereDate($value) + * @method static \Illuminate\Database\Eloquent\Builder|Bill whereDeletedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|Bill whereId($value) + * @method static \Illuminate\Database\Eloquent\Builder|Bill whereMatch($value) + * @method static \Illuminate\Database\Eloquent\Builder|Bill whereMatchEncrypted($value) + * @method static \Illuminate\Database\Eloquent\Builder|Bill whereName($value) + * @method static \Illuminate\Database\Eloquent\Builder|Bill whereNameEncrypted($value) + * @method static \Illuminate\Database\Eloquent\Builder|Bill whereRepeatFreq($value) + * @method static \Illuminate\Database\Eloquent\Builder|Bill whereSkip($value) + * @method static \Illuminate\Database\Eloquent\Builder|Bill whereTransactionCurrencyId($value) + * @method static \Illuminate\Database\Eloquent\Builder|Bill whereUpdatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|Bill whereUserId($value) + * @method static Builder|Bill withTrashed() + * @method static Builder|Bill withoutTrashed() + * @mixin Eloquent */ class Bill extends Model { @@ -120,13 +122,13 @@ class Bill extends Model * * @param string $value * - * @return Bill * @throws NotFoundHttpException + * @return Bill */ public static function routeBinder(string $value): Bill { if (auth()->check()) { - $billId = (int)$value; + $billId = (int) $value; /** @var User $user */ $user = auth()->user(); /** @var Bill $bill */ @@ -163,7 +165,7 @@ class Bill extends Model */ public function setAmountMaxAttribute($value): void { - $this->attributes['amount_max'] = (string)$value; + $this->attributes['amount_max'] = (string) $value; } /** @@ -173,7 +175,7 @@ class Bill extends Model */ public function setAmountMinAttribute($value): void { - $this->attributes['amount_min'] = (string)$value; + $this->attributes['amount_min'] = (string) $value; } /** diff --git a/app/Models/Budget.php b/app/Models/Budget.php index 41b81292ee..ede495ec33 100644 --- a/app/Models/Budget.php +++ b/app/Models/Budget.php @@ -23,50 +23,52 @@ declare(strict_types=1); namespace FireflyIII\Models; use Carbon\Carbon; +use Eloquent; use FireflyIII\User; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\SoftDeletes; +use Illuminate\Database\Query\Builder; use Illuminate\Support\Collection; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** * Class Budget. * - * @property int $id - * @property string $name - * @property bool $active - * @property int $user_id - * @property-read string $email - * @property bool encrypted - * @property Collection budgetlimits - * @property int $order - * @property Carbon created_at - * @property Carbon updated_at - * @property User $user - * @property \Illuminate\Support\Carbon|null $deleted_at - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\TransactionJournal[] $transactionJournals - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Transaction[] $transactions + * @property int $id + * @property string $name + * @property bool $active + * @property int $user_id + * @property-read string $email + * @property bool encrypted + * @property Collection budgetlimits + * @property int $order + * @property Carbon created_at + * @property Carbon updated_at + * @property User $user + * @property \Illuminate\Support\Carbon|null $deleted_at + * @property-read \Illuminate\Database\Eloquent\Collection|TransactionJournal[] $transactionJournals + * @property-read \Illuminate\Database\Eloquent\Collection|Transaction[] $transactions * @method static bool|null forceDelete() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Budget newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Budget newQuery() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Budget onlyTrashed() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Budget query() + * @method static \Illuminate\Database\Eloquent\Builder|Budget newModelQuery() + * @method static \Illuminate\Database\Eloquent\Builder|Budget newQuery() + * @method static Builder|Budget onlyTrashed() + * @method static \Illuminate\Database\Eloquent\Builder|Budget query() * @method static bool|null restore() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Budget whereActive($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Budget whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Budget whereDeletedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Budget whereEncrypted($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Budget whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Budget whereName($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Budget whereOrder($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Budget whereUpdatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Budget whereUserId($value) - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Budget withTrashed() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Budget withoutTrashed() - * @mixin \Eloquent + * @method static \Illuminate\Database\Eloquent\Builder|Budget whereActive($value) + * @method static \Illuminate\Database\Eloquent\Builder|Budget whereCreatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|Budget whereDeletedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|Budget whereEncrypted($value) + * @method static \Illuminate\Database\Eloquent\Builder|Budget whereId($value) + * @method static \Illuminate\Database\Eloquent\Builder|Budget whereName($value) + * @method static \Illuminate\Database\Eloquent\Builder|Budget whereOrder($value) + * @method static \Illuminate\Database\Eloquent\Builder|Budget whereUpdatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|Budget whereUserId($value) + * @method static Builder|Budget withTrashed() + * @method static Builder|Budget withoutTrashed() + * @mixin Eloquent */ class Budget extends Model { @@ -95,13 +97,13 @@ class Budget extends Model * * @param string $value * - * @return Budget * @throws NotFoundHttpException + * @return Budget */ public static function routeBinder(string $value): Budget { if (auth()->check()) { - $budgetId = (int)$value; + $budgetId = (int) $value; /** @var User $user */ $user = auth()->user(); /** @var Budget $budget */ @@ -113,6 +115,15 @@ class Budget extends Model throw new NotFoundHttpException; } + /** + * @codeCoverageIgnore + * @return HasMany + */ + public function autoBudgets(): HasMany + { + return $this->hasMany(AutoBudget::class); + } + /** * @codeCoverageIgnore * @return HasMany diff --git a/app/Models/BudgetLimit.php b/app/Models/BudgetLimit.php index 89c9f2ba33..4b924ff245 100644 --- a/app/Models/BudgetLimit.php +++ b/app/Models/BudgetLimit.php @@ -23,6 +23,8 @@ declare(strict_types=1); namespace FireflyIII\Models; use Carbon\Carbon; +use Eloquent; +use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; @@ -41,18 +43,18 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; * @property string spent * @property int $transaction_currency_id * @property TransactionCurrency $transactionCurrency - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\BudgetLimit newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\BudgetLimit newQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\BudgetLimit query() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\BudgetLimit whereAmount($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\BudgetLimit whereBudgetId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\BudgetLimit whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\BudgetLimit whereEndDate($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\BudgetLimit whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\BudgetLimit whereStartDate($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\BudgetLimit whereTransactionCurrencyId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\BudgetLimit whereUpdatedAt($value) - * @mixin \Eloquent + * @method static Builder|BudgetLimit newModelQuery() + * @method static Builder|BudgetLimit newQuery() + * @method static Builder|BudgetLimit query() + * @method static Builder|BudgetLimit whereAmount($value) + * @method static Builder|BudgetLimit whereBudgetId($value) + * @method static Builder|BudgetLimit whereCreatedAt($value) + * @method static Builder|BudgetLimit whereEndDate($value) + * @method static Builder|BudgetLimit whereId($value) + * @method static Builder|BudgetLimit whereStartDate($value) + * @method static Builder|BudgetLimit whereTransactionCurrencyId($value) + * @method static Builder|BudgetLimit whereUpdatedAt($value) + * @mixin Eloquent */ class BudgetLimit extends Model { @@ -70,20 +72,20 @@ class BudgetLimit extends Model ]; /** @var array Fields that can be filled */ - protected $fillable = ['budget_id', 'start_date', 'end_date', 'amount','transaction_currency_id']; + protected $fillable = ['budget_id', 'start_date', 'end_date', 'amount', 'transaction_currency_id']; /** * Route binder. Converts the key in the URL to the specified object (or throw 404). * * @param string $value * - * @return mixed * @throws NotFoundHttpException + * @return mixed */ public static function routeBinder(string $value): BudgetLimit { 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) diff --git a/app/Models/Category.php b/app/Models/Category.php index 8a0e703a2c..ef570c20a3 100644 --- a/app/Models/Category.php +++ b/app/Models/Category.php @@ -24,45 +24,48 @@ declare(strict_types=1); namespace FireflyIII\Models; use Carbon\Carbon; +use Eloquent; use FireflyIII\User; +use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\SoftDeletes; +use Illuminate\Database\Query\Builder; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** * Class Category. * - * @property string $name - * @property int $id - * @property float $spent // used in category reports - * @property Carbon|null lastActivity - * @property bool encrypted - * @property User $user - * @property Carbon $created_at - * @property Carbon $updated_at - * @property \Illuminate\Support\Carbon|null $deleted_at - * @property int $user_id - * @property bool $encrypted - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\TransactionJournal[] $transactionJournals - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Transaction[] $transactions + * @property string $name + * @property int $id + * @property float $spent // used in category reports + * @property Carbon|null lastActivity + * @property bool encrypted + * @property User $user + * @property Carbon $created_at + * @property Carbon $updated_at + * @property \Illuminate\Support\Carbon|null $deleted_at + * @property int $user_id + * @property bool $encrypted + * @property-read Collection|TransactionJournal[] $transactionJournals + * @property-read Collection|Transaction[] $transactions * @method static bool|null forceDelete() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Category newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Category newQuery() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Category onlyTrashed() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Category query() + * @method static \Illuminate\Database\Eloquent\Builder|Category newModelQuery() + * @method static \Illuminate\Database\Eloquent\Builder|Category newQuery() + * @method static Builder|Category onlyTrashed() + * @method static \Illuminate\Database\Eloquent\Builder|Category query() * @method static bool|null restore() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Category whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Category whereDeletedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Category whereEncrypted($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Category whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Category whereName($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Category whereUpdatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Category whereUserId($value) - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Category withTrashed() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Category withoutTrashed() - * @mixin \Eloquent + * @method static \Illuminate\Database\Eloquent\Builder|Category whereCreatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|Category whereDeletedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|Category whereEncrypted($value) + * @method static \Illuminate\Database\Eloquent\Builder|Category whereId($value) + * @method static \Illuminate\Database\Eloquent\Builder|Category whereName($value) + * @method static \Illuminate\Database\Eloquent\Builder|Category whereUpdatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|Category whereUserId($value) + * @method static Builder|Category withTrashed() + * @method static Builder|Category withoutTrashed() + * @mixin Eloquent */ class Category extends Model { @@ -90,13 +93,13 @@ class Category extends Model * * @param string $value * - * @return Category * @throws NotFoundHttpException + * @return Category */ public static function routeBinder(string $value): Category { if (auth()->check()) { - $categoryId = (int)$value; + $categoryId = (int) $value; /** @var User $user */ $user = auth()->user(); /** @var Category $category */ diff --git a/app/Models/Configuration.php b/app/Models/Configuration.php index 4fa1dcd9c1..1c195f4ffa 100644 --- a/app/Models/Configuration.php +++ b/app/Models/Configuration.php @@ -22,33 +22,36 @@ declare(strict_types=1); namespace FireflyIII\Models; +use Eloquent; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; +use Illuminate\Database\Query\Builder; +use Illuminate\Support\Carbon; /** * Class Configuration. * - * @property string $data - * @property string $name - * @property int $id - * @property \Illuminate\Support\Carbon|null $created_at - * @property \Illuminate\Support\Carbon|null $updated_at - * @property \Illuminate\Support\Carbon|null $deleted_at + * @property string $data + * @property string $name + * @property int $id + * @property Carbon|null $created_at + * @property Carbon|null $updated_at + * @property Carbon|null $deleted_at * @method static bool|null forceDelete() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Configuration newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Configuration newQuery() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Configuration onlyTrashed() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Configuration query() + * @method static \Illuminate\Database\Eloquent\Builder|Configuration newModelQuery() + * @method static \Illuminate\Database\Eloquent\Builder|Configuration newQuery() + * @method static Builder|Configuration onlyTrashed() + * @method static \Illuminate\Database\Eloquent\Builder|Configuration query() * @method static bool|null restore() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Configuration whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Configuration whereData($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Configuration whereDeletedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Configuration whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Configuration whereName($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Configuration whereUpdatedAt($value) - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Configuration withTrashed() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Configuration withoutTrashed() - * @mixin \Eloquent + * @method static \Illuminate\Database\Eloquent\Builder|Configuration whereCreatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|Configuration whereData($value) + * @method static \Illuminate\Database\Eloquent\Builder|Configuration whereDeletedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|Configuration whereId($value) + * @method static \Illuminate\Database\Eloquent\Builder|Configuration whereName($value) + * @method static \Illuminate\Database\Eloquent\Builder|Configuration whereUpdatedAt($value) + * @method static Builder|Configuration withTrashed() + * @method static Builder|Configuration withoutTrashed() + * @mixin Eloquent */ class Configuration extends Model { diff --git a/app/Models/CurrencyExchangeRate.php b/app/Models/CurrencyExchangeRate.php index a702c6c229..c837868eaa 100644 --- a/app/Models/CurrencyExchangeRate.php +++ b/app/Models/CurrencyExchangeRate.php @@ -23,15 +23,17 @@ declare(strict_types=1); namespace FireflyIII\Models; use Carbon\Carbon; +use Eloquent; use FireflyIII\User; +use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; /** * Class CurrencyExchange. * - * @property int $id - * @property Carbon $created_at + * @property int $id + * @property Carbon $created_at * @property Carbon $updated_at * @property TransactionCurrency $fromCurrency * @property TransactionCurrency $toCurrency @@ -39,24 +41,24 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo; * @property Carbon $date * @property int $from_currency_id * @property int $to_currency_id - * @property string|null $deleted_at - * @property int $user_id - * @property float|null $user_rate - * @property-read \FireflyIII\User $user - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\CurrencyExchangeRate newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\CurrencyExchangeRate newQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\CurrencyExchangeRate query() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\CurrencyExchangeRate whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\CurrencyExchangeRate whereDate($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\CurrencyExchangeRate whereDeletedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\CurrencyExchangeRate whereFromCurrencyId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\CurrencyExchangeRate whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\CurrencyExchangeRate whereRate($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\CurrencyExchangeRate whereToCurrencyId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\CurrencyExchangeRate whereUpdatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\CurrencyExchangeRate whereUserId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\CurrencyExchangeRate whereUserRate($value) - * @mixin \Eloquent + * @property string|null $deleted_at + * @property int $user_id + * @property float|null $user_rate + * @property-read User $user + * @method static Builder|CurrencyExchangeRate newModelQuery() + * @method static Builder|CurrencyExchangeRate newQuery() + * @method static Builder|CurrencyExchangeRate query() + * @method static Builder|CurrencyExchangeRate whereCreatedAt($value) + * @method static Builder|CurrencyExchangeRate whereDate($value) + * @method static Builder|CurrencyExchangeRate whereDeletedAt($value) + * @method static Builder|CurrencyExchangeRate whereFromCurrencyId($value) + * @method static Builder|CurrencyExchangeRate whereId($value) + * @method static Builder|CurrencyExchangeRate whereRate($value) + * @method static Builder|CurrencyExchangeRate whereToCurrencyId($value) + * @method static Builder|CurrencyExchangeRate whereUpdatedAt($value) + * @method static Builder|CurrencyExchangeRate whereUserId($value) + * @method static Builder|CurrencyExchangeRate whereUserRate($value) + * @mixin Eloquent */ class CurrencyExchangeRate extends Model { diff --git a/app/Models/ImportJob.php b/app/Models/ImportJob.php index 2d495b20e2..774e784c37 100644 --- a/app/Models/ImportJob.php +++ b/app/Models/ImportJob.php @@ -23,7 +23,10 @@ declare(strict_types=1); namespace FireflyIII\Models; use Carbon\Carbon; +use Eloquent; use FireflyIII\User; +use Illuminate\Database\Eloquent\Builder; +use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\MorphMany; @@ -32,41 +35,43 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** * Class ImportJob. * - * @property array $transactions - * @property array $configuration - * @property User $user - * @property int $user_id - * @property string $status - * @property string $stage - * @property string $key - * @property string $provider - * @property string $file_type - * @property int $tag_id - * @property Tag $tag - * @property array $errors - * @property array extended_status - * @property int id - * @property Carbon $created_at - * @property Carbon $updated_at - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Attachment[] $attachments - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\ImportJob newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\ImportJob newQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\ImportJob query() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\ImportJob whereConfiguration($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\ImportJob whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\ImportJob whereErrors($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\ImportJob whereExtendedStatus($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\ImportJob whereFileType($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\ImportJob whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\ImportJob whereKey($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\ImportJob whereProvider($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\ImportJob whereStage($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\ImportJob whereStatus($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\ImportJob whereTagId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\ImportJob whereTransactions($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\ImportJob whereUpdatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\ImportJob whereUserId($value) - * @mixin \Eloquent + * @codeCoverageIgnore + * @deprecated + * @property array $transactions + * @property array $configuration + * @property User $user + * @property int $user_id + * @property string $status + * @property string $stage + * @property string $key + * @property string $provider + * @property string $file_type + * @property int $tag_id + * @property Tag $tag + * @property array $errors + * @property array extended_status + * @property int id + * @property Carbon $created_at + * @property Carbon $updated_at + * @property-read Collection|Attachment[] $attachments + * @method static Builder|ImportJob newModelQuery() + * @method static Builder|ImportJob newQuery() + * @method static Builder|ImportJob query() + * @method static Builder|ImportJob whereConfiguration($value) + * @method static Builder|ImportJob whereCreatedAt($value) + * @method static Builder|ImportJob whereErrors($value) + * @method static Builder|ImportJob whereExtendedStatus($value) + * @method static Builder|ImportJob whereFileType($value) + * @method static Builder|ImportJob whereId($value) + * @method static Builder|ImportJob whereKey($value) + * @method static Builder|ImportJob whereProvider($value) + * @method static Builder|ImportJob whereStage($value) + * @method static Builder|ImportJob whereStatus($value) + * @method static Builder|ImportJob whereTagId($value) + * @method static Builder|ImportJob whereTransactions($value) + * @method static Builder|ImportJob whereUpdatedAt($value) + * @method static Builder|ImportJob whereUserId($value) + * @mixin Eloquent */ class ImportJob extends Model { @@ -94,9 +99,9 @@ class ImportJob extends Model * * @param $value * + * @throws NotFoundHttpException * @return mixed * - * @throws NotFoundHttpException */ public static function routeBinder(string $value): ImportJob { diff --git a/app/Models/LinkType.php b/app/Models/LinkType.php index 0d989310cd..c9e941308e 100644 --- a/app/Models/LinkType.php +++ b/app/Models/LinkType.php @@ -23,42 +23,45 @@ declare(strict_types=1); namespace FireflyIII\Models; use Carbon\Carbon; +use Eloquent; +use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\SoftDeletes; +use Illuminate\Database\Query\Builder; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** * FireflyIII\Models\LinkType * - * @property int $journalCount - * @property string $inward - * @property string $outward - * @property string $name - * @property bool $editable - * @property Carbon $created_at - * @property Carbon $updated_at - * @property int $id + * @property int $journalCount + * @property string $inward + * @property string $outward + * @property string $name + * @property bool $editable + * @property Carbon $created_at + * @property Carbon $updated_at + * @property int $id * Class LinkType - * @property \Illuminate\Support\Carbon|null $deleted_at - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\TransactionJournalLink[] $transactionJournalLinks + * @property \Illuminate\Support\Carbon|null $deleted_at + * @property-read Collection|TransactionJournalLink[] $transactionJournalLinks * @method static bool|null forceDelete() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\LinkType newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\LinkType newQuery() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\LinkType onlyTrashed() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\LinkType query() + * @method static \Illuminate\Database\Eloquent\Builder|LinkType newModelQuery() + * @method static \Illuminate\Database\Eloquent\Builder|LinkType newQuery() + * @method static Builder|LinkType onlyTrashed() + * @method static \Illuminate\Database\Eloquent\Builder|LinkType query() * @method static bool|null restore() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\LinkType whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\LinkType whereDeletedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\LinkType whereEditable($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\LinkType whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\LinkType whereInward($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\LinkType whereName($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\LinkType whereOutward($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\LinkType whereUpdatedAt($value) - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\LinkType withTrashed() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\LinkType withoutTrashed() - * @mixin \Eloquent + * @method static \Illuminate\Database\Eloquent\Builder|LinkType whereCreatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|LinkType whereDeletedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|LinkType whereEditable($value) + * @method static \Illuminate\Database\Eloquent\Builder|LinkType whereId($value) + * @method static \Illuminate\Database\Eloquent\Builder|LinkType whereInward($value) + * @method static \Illuminate\Database\Eloquent\Builder|LinkType whereName($value) + * @method static \Illuminate\Database\Eloquent\Builder|LinkType whereOutward($value) + * @method static \Illuminate\Database\Eloquent\Builder|LinkType whereUpdatedAt($value) + * @method static Builder|LinkType withTrashed() + * @method static Builder|LinkType withoutTrashed() + * @mixin Eloquent */ class LinkType extends Model { @@ -84,14 +87,14 @@ class LinkType extends Model * * @param $value * + * @throws NotFoundHttpException * @return LinkType * - * @throws NotFoundHttpException */ public static function routeBinder(string $value): LinkType { if (auth()->check()) { - $linkTypeId = (int)$value; + $linkTypeId = (int) $value; $linkType = self::find($linkTypeId); if (null !== $linkType) { return $linkType; diff --git a/app/Models/Location.php b/app/Models/Location.php index b5a00415ec..78b267f0c5 100644 --- a/app/Models/Location.php +++ b/app/Models/Location.php @@ -49,6 +49,22 @@ class Location extends Model /** @var array Fields that can be filled */ protected $fillable = ['locatable_id', 'locatable_type', 'latitude', 'longitude', 'zoom_level']; + /** + * Add rules for locations. + * + * @param array $rules + * + * @return array + */ + 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['zoom_level'] = 'numeric|min:0|max:80|nullable|required_with:latitude'; + + return $rules; + } + /** * @codeCoverageIgnore * Get all of the accounts. @@ -70,20 +86,4 @@ class Location extends Model return $this->morphTo(); } - /** - * Add rules for locations. - * - * @param array $rules - * - * @return array - */ - 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['zoom_level'] = 'numeric|min:0|max:80|nullable|required_with:latitude'; - - return $rules; - } - } diff --git a/app/Models/Note.php b/app/Models/Note.php index 23449476be..83c4b822ab 100644 --- a/app/Models/Note.php +++ b/app/Models/Note.php @@ -23,39 +23,42 @@ declare(strict_types=1); namespace FireflyIII\Models; use Carbon\Carbon; +use Eloquent; +use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\MorphTo; use Illuminate\Database\Eloquent\SoftDeletes; +use Illuminate\Database\Query\Builder; /** * Class Note. * - * @property int $id - * @property Carbon $created_at - * @property Carbon $updated_at - * @property string $text - * @property string $title - * @property int $noteable_id - * @property \Illuminate\Support\Carbon|null $deleted_at - * @property string $noteable_type - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Note[] $noteable + * @property int $id + * @property Carbon $created_at + * @property Carbon $updated_at + * @property string $text + * @property string $title + * @property int $noteable_id + * @property \Illuminate\Support\Carbon|null $deleted_at + * @property string $noteable_type + * @property-read Collection|Note[] $noteable * @method static bool|null forceDelete() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Note newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Note newQuery() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Note onlyTrashed() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Note query() + * @method static \Illuminate\Database\Eloquent\Builder|Note newModelQuery() + * @method static \Illuminate\Database\Eloquent\Builder|Note newQuery() + * @method static Builder|Note onlyTrashed() + * @method static \Illuminate\Database\Eloquent\Builder|Note query() * @method static bool|null restore() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Note whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Note whereDeletedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Note whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Note whereNoteableId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Note whereNoteableType($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Note whereText($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Note whereTitle($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Note whereUpdatedAt($value) - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Note withTrashed() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Note withoutTrashed() - * @mixin \Eloquent + * @method static \Illuminate\Database\Eloquent\Builder|Note whereCreatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|Note whereDeletedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|Note whereId($value) + * @method static \Illuminate\Database\Eloquent\Builder|Note whereNoteableId($value) + * @method static \Illuminate\Database\Eloquent\Builder|Note whereNoteableType($value) + * @method static \Illuminate\Database\Eloquent\Builder|Note whereText($value) + * @method static \Illuminate\Database\Eloquent\Builder|Note whereTitle($value) + * @method static \Illuminate\Database\Eloquent\Builder|Note whereUpdatedAt($value) + * @method static Builder|Note withTrashed() + * @method static Builder|Note withoutTrashed() + * @mixin Eloquent */ class Note extends Model { @@ -74,6 +77,16 @@ class Note extends Model /** @var array Fields that can be filled */ protected $fillable = ['title', 'text', 'noteable_id', 'noteable_type']; + /** + * @param string|null $value + * + * @return string|null + */ + public function getTextAttribute(?string $value): ?string + { + return null === $value ? null : htmlspecialchars_decode($value, ENT_QUOTES); + } + /** * @codeCoverageIgnore * @@ -93,14 +106,4 @@ class Note extends Model { $this->attributes['text'] = e($value); } - - /** - * @param string|null $value - * - * @return string|null - */ - public function getTextAttribute(?string $value): ?string - { - return null === $value ? null : htmlspecialchars_decode($value, ENT_QUOTES); - } } diff --git a/app/Models/PiggyBank.php b/app/Models/PiggyBank.php index 0ca991c57e..edbe3f4d2e 100644 --- a/app/Models/PiggyBank.php +++ b/app/Models/PiggyBank.php @@ -23,54 +23,57 @@ declare(strict_types=1); namespace FireflyIII\Models; use Carbon\Carbon; +use Eloquent; +use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\MorphMany; use Illuminate\Database\Eloquent\SoftDeletes; +use Illuminate\Database\Query\Builder; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** * Class PiggyBank. * - * @property Carbon $targetdate - * @property Carbon $startdate - * @property string $targetamount - * @property int $id - * @property string $name - * @property Account $account - * @property Carbon $updated_at - * @property Carbon $created_at - * @property int $order - * @property bool $active - * @property int $account_id - * @property bool encrypted - * @property \Illuminate\Support\Carbon|null $deleted_at - * @property bool $encrypted - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Note[] $notes - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\PiggyBankEvent[] $piggyBankEvents - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\PiggyBankRepetition[] $piggyBankRepetitions + * @property Carbon $targetdate + * @property Carbon $startdate + * @property string $targetamount + * @property int $id + * @property string $name + * @property Account $account + * @property Carbon $updated_at + * @property Carbon $created_at + * @property int $order + * @property bool $active + * @property int $account_id + * @property bool encrypted + * @property \Illuminate\Support\Carbon|null $deleted_at + * @property bool $encrypted + * @property-read Collection|Note[] $notes + * @property-read Collection|PiggyBankEvent[] $piggyBankEvents + * @property-read Collection|PiggyBankRepetition[] $piggyBankRepetitions * @method static bool|null forceDelete() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBank newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBank newQuery() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\PiggyBank onlyTrashed() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBank query() + * @method static \Illuminate\Database\Eloquent\Builder|PiggyBank newModelQuery() + * @method static \Illuminate\Database\Eloquent\Builder|PiggyBank newQuery() + * @method static Builder|PiggyBank onlyTrashed() + * @method static \Illuminate\Database\Eloquent\Builder|PiggyBank query() * @method static bool|null restore() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBank whereAccountId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBank whereActive($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBank whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBank whereDeletedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBank whereEncrypted($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBank whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBank whereName($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBank whereOrder($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBank whereStartdate($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBank whereTargetamount($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBank whereTargetdate($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBank whereUpdatedAt($value) - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\PiggyBank withTrashed() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\PiggyBank withoutTrashed() - * @mixin \Eloquent + * @method static \Illuminate\Database\Eloquent\Builder|PiggyBank whereAccountId($value) + * @method static \Illuminate\Database\Eloquent\Builder|PiggyBank whereActive($value) + * @method static \Illuminate\Database\Eloquent\Builder|PiggyBank whereCreatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|PiggyBank whereDeletedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|PiggyBank whereEncrypted($value) + * @method static \Illuminate\Database\Eloquent\Builder|PiggyBank whereId($value) + * @method static \Illuminate\Database\Eloquent\Builder|PiggyBank whereName($value) + * @method static \Illuminate\Database\Eloquent\Builder|PiggyBank whereOrder($value) + * @method static \Illuminate\Database\Eloquent\Builder|PiggyBank whereStartdate($value) + * @method static \Illuminate\Database\Eloquent\Builder|PiggyBank whereTargetamount($value) + * @method static \Illuminate\Database\Eloquent\Builder|PiggyBank whereTargetdate($value) + * @method static \Illuminate\Database\Eloquent\Builder|PiggyBank whereUpdatedAt($value) + * @method static Builder|PiggyBank withTrashed() + * @method static Builder|PiggyBank withoutTrashed() + * @mixin Eloquent */ class PiggyBank extends Model { @@ -102,13 +105,13 @@ class PiggyBank extends Model * * @param string $value * - * @return PiggyBank * @throws NotFoundHttpException + * @return PiggyBank */ public static function routeBinder(string $value): PiggyBank { if (auth()->check()) { - $piggyBankId = (int)$value; + $piggyBankId = (int) $value; $piggyBank = self::where('piggy_banks.id', $piggyBankId) ->leftJoin('accounts', 'accounts.id', '=', 'piggy_banks.account_id') ->where('accounts.user_id', auth()->user()->id)->first(['piggy_banks.*']); @@ -162,6 +165,6 @@ class PiggyBank extends Model */ public function setTargetamountAttribute($value): void { - $this->attributes['targetamount'] = (string)$value; + $this->attributes['targetamount'] = (string) $value; } } diff --git a/app/Models/PiggyBankEvent.php b/app/Models/PiggyBankEvent.php index cb875c2747..dd7e14654a 100644 --- a/app/Models/PiggyBankEvent.php +++ b/app/Models/PiggyBankEvent.php @@ -23,6 +23,8 @@ declare(strict_types=1); namespace FireflyIII\Models; use Carbon\Carbon; +use Eloquent; +use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; @@ -38,17 +40,17 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo; * @property string $amount * @property Carbon created_at * @property Carbon updated_at - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBankEvent newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBankEvent newQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBankEvent query() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBankEvent whereAmount($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBankEvent whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBankEvent whereDate($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBankEvent whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBankEvent wherePiggyBankId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBankEvent whereTransactionJournalId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBankEvent whereUpdatedAt($value) - * @mixin \Eloquent + * @method static Builder|PiggyBankEvent newModelQuery() + * @method static Builder|PiggyBankEvent newQuery() + * @method static Builder|PiggyBankEvent query() + * @method static Builder|PiggyBankEvent whereAmount($value) + * @method static Builder|PiggyBankEvent whereCreatedAt($value) + * @method static Builder|PiggyBankEvent whereDate($value) + * @method static Builder|PiggyBankEvent whereId($value) + * @method static Builder|PiggyBankEvent wherePiggyBankId($value) + * @method static Builder|PiggyBankEvent whereTransactionJournalId($value) + * @method static Builder|PiggyBankEvent whereUpdatedAt($value) + * @mixin Eloquent */ class PiggyBankEvent extends Model { @@ -84,7 +86,7 @@ class PiggyBankEvent extends Model */ public function setAmountAttribute($value): void { - $this->attributes['amount'] = (string)$value; + $this->attributes['amount'] = (string) $value; } /** diff --git a/app/Models/PiggyBankRepetition.php b/app/Models/PiggyBankRepetition.php index 4b89d1d128..39c3e66773 100644 --- a/app/Models/PiggyBankRepetition.php +++ b/app/Models/PiggyBankRepetition.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Models; use Carbon\Carbon; +use Eloquent; use Illuminate\Database\Eloquent\Builder as EloquentBuilder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; @@ -30,27 +31,27 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo; /** * Class PiggyBankRepetition. * - * @property string $currentamount - * @property Carbon $startdate - * @property Carbon $targetdate - * @property int $id + * @property string $currentamount + * @property Carbon $startdate + * @property Carbon $targetdate + * @property int $id * @property \Illuminate\Support\Carbon|null $created_at * @property \Illuminate\Support\Carbon|null $updated_at - * @property int $piggy_bank_id - * @property-read \FireflyIII\Models\PiggyBank $piggyBank - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBankRepetition newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBankRepetition newQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBankRepetition onDates(\Carbon\Carbon $start, \Carbon\Carbon $target) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBankRepetition query() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBankRepetition relevantOnDate(\Carbon\Carbon $date) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBankRepetition whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBankRepetition whereCurrentamount($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBankRepetition whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBankRepetition wherePiggyBankId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBankRepetition whereStartdate($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBankRepetition whereTargetdate($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\PiggyBankRepetition whereUpdatedAt($value) - * @mixin \Eloquent + * @property int $piggy_bank_id + * @property-read PiggyBank $piggyBank + * @method static EloquentBuilder|PiggyBankRepetition newModelQuery() + * @method static EloquentBuilder|PiggyBankRepetition newQuery() + * @method static EloquentBuilder|PiggyBankRepetition onDates(Carbon $start, Carbon $target) + * @method static EloquentBuilder|PiggyBankRepetition query() + * @method static EloquentBuilder|PiggyBankRepetition relevantOnDate(Carbon $date) + * @method static EloquentBuilder|PiggyBankRepetition whereCreatedAt($value) + * @method static EloquentBuilder|PiggyBankRepetition whereCurrentamount($value) + * @method static EloquentBuilder|PiggyBankRepetition whereId($value) + * @method static EloquentBuilder|PiggyBankRepetition wherePiggyBankId($value) + * @method static EloquentBuilder|PiggyBankRepetition whereStartdate($value) + * @method static EloquentBuilder|PiggyBankRepetition whereTargetdate($value) + * @method static EloquentBuilder|PiggyBankRepetition whereUpdatedAt($value) + * @mixin Eloquent */ class PiggyBankRepetition extends Model { @@ -123,6 +124,6 @@ class PiggyBankRepetition extends Model */ public function setCurrentamountAttribute($value): void { - $this->attributes['currentamount'] = (string)$value; + $this->attributes['currentamount'] = (string) $value; } } diff --git a/app/Models/Preference.php b/app/Models/Preference.php index aa727a3831..7136fc914b 100644 --- a/app/Models/Preference.php +++ b/app/Models/Preference.php @@ -23,7 +23,9 @@ declare(strict_types=1); namespace FireflyIII\Models; use Carbon\Carbon; +use Eloquent; use FireflyIII\User; +use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; @@ -37,17 +39,17 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; * @property Carbon $created_at * @property int $id * @property User user - * @property int $user_id - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Preference newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Preference newQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Preference query() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Preference whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Preference whereData($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Preference whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Preference whereName($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Preference whereUpdatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Preference whereUserId($value) - * @mixin \Eloquent + * @property int $user_id + * @method static Builder|Preference newModelQuery() + * @method static Builder|Preference newQuery() + * @method static Builder|Preference query() + * @method static Builder|Preference whereCreatedAt($value) + * @method static Builder|Preference whereData($value) + * @method static Builder|Preference whereId($value) + * @method static Builder|Preference whereName($value) + * @method static Builder|Preference whereUpdatedAt($value) + * @method static Builder|Preference whereUserId($value) + * @mixin Eloquent */ class Preference extends Model { @@ -71,8 +73,8 @@ class Preference extends Model * * @param string $value * - * @return Preference * @throws NotFoundHttpException + * @return Preference */ public static function routeBinder(string $value): Preference { diff --git a/app/Models/Recurrence.php b/app/Models/Recurrence.php index b24b8c3458..0d38528aa5 100644 --- a/app/Models/Recurrence.php +++ b/app/Models/Recurrence.php @@ -24,65 +24,69 @@ declare(strict_types=1); namespace FireflyIII\Models; +use Eloquent; use FireflyIII\User; +use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\MorphMany; use Illuminate\Database\Eloquent\SoftDeletes; +use Illuminate\Database\Query\Builder; +use Illuminate\Support\Carbon; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** * Class Recurrence * - * @property int $id - * @property \Carbon\Carbon $created_at - * @property \Carbon\Carbon $updated_at - * @property int $user_id - * @property int $transaction_type_id - * @property int $transaction_currency_id - * @property string $title - * @property string $description - * @property \Carbon\Carbon $first_date - * @property \Carbon\Carbon $repeat_until - * @property \Carbon\Carbon $latest_date - * @property string $repetition_type - * @property string $repetition_moment - * @property int $repetition_skip - * @property int $repetitions - * @property bool $active - * @property bool $apply_rules - * @property \FireflyIII\User $user - * @property \Illuminate\Support\Collection $recurrenceRepetitions - * @property \Illuminate\Support\Collection $recurrenceMeta - * @property \Illuminate\Support\Collection $recurrenceTransactions - * @property \FireflyIII\Models\TransactionType $transactionType - * @property \Illuminate\Support\Carbon|null $deleted_at - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Note[] $notes - * @property-read \FireflyIII\Models\TransactionCurrency $transactionCurrency + * @property int $id + * @property \Carbon\Carbon $created_at + * @property \Carbon\Carbon $updated_at + * @property int $user_id + * @property int $transaction_type_id + * @property int $transaction_currency_id + * @property string $title + * @property string $description + * @property \Carbon\Carbon $first_date + * @property \Carbon\Carbon $repeat_until + * @property \Carbon\Carbon $latest_date + * @property string $repetition_type + * @property string $repetition_moment + * @property int $repetition_skip + * @property int $repetitions + * @property bool $active + * @property bool $apply_rules + * @property User $user + * @property \Illuminate\Support\Collection $recurrenceRepetitions + * @property \Illuminate\Support\Collection $recurrenceMeta + * @property \Illuminate\Support\Collection $recurrenceTransactions + * @property TransactionType $transactionType + * @property Carbon|null $deleted_at + * @property-read Collection|Note[] $notes + * @property-read TransactionCurrency $transactionCurrency * @method static bool|null forceDelete() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Recurrence newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Recurrence newQuery() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Recurrence onlyTrashed() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Recurrence query() + * @method static \Illuminate\Database\Eloquent\Builder|Recurrence newModelQuery() + * @method static \Illuminate\Database\Eloquent\Builder|Recurrence newQuery() + * @method static Builder|Recurrence onlyTrashed() + * @method static \Illuminate\Database\Eloquent\Builder|Recurrence query() * @method static bool|null restore() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Recurrence whereActive($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Recurrence whereApplyRules($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Recurrence whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Recurrence whereDeletedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Recurrence whereDescription($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Recurrence whereFirstDate($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Recurrence whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Recurrence whereLatestDate($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Recurrence whereRepeatUntil($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Recurrence whereRepetitions($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Recurrence whereTitle($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Recurrence whereTransactionTypeId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Recurrence whereUpdatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Recurrence whereUserId($value) - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Recurrence withTrashed() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Recurrence withoutTrashed() - * @mixin \Eloquent + * @method static \Illuminate\Database\Eloquent\Builder|Recurrence whereActive($value) + * @method static \Illuminate\Database\Eloquent\Builder|Recurrence whereApplyRules($value) + * @method static \Illuminate\Database\Eloquent\Builder|Recurrence whereCreatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|Recurrence whereDeletedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|Recurrence whereDescription($value) + * @method static \Illuminate\Database\Eloquent\Builder|Recurrence whereFirstDate($value) + * @method static \Illuminate\Database\Eloquent\Builder|Recurrence whereId($value) + * @method static \Illuminate\Database\Eloquent\Builder|Recurrence whereLatestDate($value) + * @method static \Illuminate\Database\Eloquent\Builder|Recurrence whereRepeatUntil($value) + * @method static \Illuminate\Database\Eloquent\Builder|Recurrence whereRepetitions($value) + * @method static \Illuminate\Database\Eloquent\Builder|Recurrence whereTitle($value) + * @method static \Illuminate\Database\Eloquent\Builder|Recurrence whereTransactionTypeId($value) + * @method static \Illuminate\Database\Eloquent\Builder|Recurrence whereUpdatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|Recurrence whereUserId($value) + * @method static Builder|Recurrence withTrashed() + * @method static Builder|Recurrence withoutTrashed() + * @mixin Eloquent */ class Recurrence extends Model { @@ -118,13 +122,13 @@ class Recurrence extends Model * * @param string $value * - * @return Recurrence * @throws NotFoundHttpException + * @return Recurrence */ public static function routeBinder(string $value): Recurrence { if (auth()->check()) { - $recurrenceId = (int)$value; + $recurrenceId = (int) $value; /** @var User $user */ $user = auth()->user(); /** @var Recurrence $recurrence */ diff --git a/app/Models/RecurrenceMeta.php b/app/Models/RecurrenceMeta.php index d2b700c373..b77d484f2c 100644 --- a/app/Models/RecurrenceMeta.php +++ b/app/Models/RecurrenceMeta.php @@ -24,37 +24,40 @@ declare(strict_types=1); namespace FireflyIII\Models; +use Eloquent; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\SoftDeletes; +use Illuminate\Database\Query\Builder; +use Illuminate\Support\Carbon; /** * Class RecurrenceMeta * - * @property string $name - * @property string $value - * @property int $id - * @property \Illuminate\Support\Carbon|null $created_at - * @property \Illuminate\Support\Carbon|null $updated_at - * @property \Illuminate\Support\Carbon|null $deleted_at - * @property int $recurrence_id - * @property-read \FireflyIII\Models\Recurrence $recurrence + * @property string $name + * @property string $value + * @property int $id + * @property Carbon|null $created_at + * @property Carbon|null $updated_at + * @property Carbon|null $deleted_at + * @property int $recurrence_id + * @property-read Recurrence $recurrence * @method static bool|null forceDelete() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceMeta newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceMeta newQuery() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\RecurrenceMeta onlyTrashed() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceMeta query() + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceMeta newModelQuery() + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceMeta newQuery() + * @method static Builder|RecurrenceMeta onlyTrashed() + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceMeta query() * @method static bool|null restore() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceMeta whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceMeta whereDeletedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceMeta whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceMeta whereName($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceMeta whereRecurrenceId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceMeta whereUpdatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceMeta whereValue($value) - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\RecurrenceMeta withTrashed() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\RecurrenceMeta withoutTrashed() - * @mixin \Eloquent + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceMeta whereCreatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceMeta whereDeletedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceMeta whereId($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceMeta whereName($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceMeta whereRecurrenceId($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceMeta whereUpdatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceMeta whereValue($value) + * @method static Builder|RecurrenceMeta withTrashed() + * @method static Builder|RecurrenceMeta withoutTrashed() + * @mixin Eloquent */ class RecurrenceMeta extends Model { diff --git a/app/Models/RecurrenceRepetition.php b/app/Models/RecurrenceRepetition.php index 5437a6a7e6..0f4d92fc2f 100644 --- a/app/Models/RecurrenceRepetition.php +++ b/app/Models/RecurrenceRepetition.php @@ -24,41 +24,44 @@ declare(strict_types=1); namespace FireflyIII\Models; +use Carbon\Carbon; +use Eloquent; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\SoftDeletes; +use Illuminate\Database\Query\Builder; /** * Class RecurrenceRepetition * - * @property string $repetition_type - * @property string $repetition_moment - * @property int $repetition_skip - * @property int $weekend - * @property \Carbon\Carbon $created_at - * @property \Carbon\Carbon $deleted_at - * @property \Carbon\Carbon $updated_at - * @property int $id - * @property int $recurrence_id - * @property-read \FireflyIII\Models\Recurrence $recurrence + * @property string $repetition_type + * @property string $repetition_moment + * @property int $repetition_skip + * @property int $weekend + * @property Carbon $created_at + * @property Carbon $deleted_at + * @property Carbon $updated_at + * @property int $id + * @property int $recurrence_id + * @property-read Recurrence $recurrence * @method static bool|null forceDelete() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceRepetition newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceRepetition newQuery() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\RecurrenceRepetition onlyTrashed() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceRepetition query() + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceRepetition newModelQuery() + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceRepetition newQuery() + * @method static Builder|RecurrenceRepetition onlyTrashed() + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceRepetition query() * @method static bool|null restore() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceRepetition whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceRepetition whereDeletedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceRepetition whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceRepetition whereRecurrenceId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceRepetition whereRepetitionMoment($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceRepetition whereRepetitionSkip($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceRepetition whereRepetitionType($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceRepetition whereUpdatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceRepetition whereWeekend($value) - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\RecurrenceRepetition withTrashed() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\RecurrenceRepetition withoutTrashed() - * @mixin \Eloquent + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceRepetition whereCreatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceRepetition whereDeletedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceRepetition whereId($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceRepetition whereRecurrenceId($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceRepetition whereRepetitionMoment($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceRepetition whereRepetitionSkip($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceRepetition whereRepetitionType($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceRepetition whereUpdatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceRepetition whereWeekend($value) + * @method static Builder|RecurrenceRepetition withTrashed() + * @method static Builder|RecurrenceRepetition withoutTrashed() + * @mixin Eloquent */ class RecurrenceRepetition extends Model { diff --git a/app/Models/RecurrenceTransaction.php b/app/Models/RecurrenceTransaction.php index 87ad759a8f..3879a7794f 100644 --- a/app/Models/RecurrenceTransaction.php +++ b/app/Models/RecurrenceTransaction.php @@ -24,54 +24,57 @@ declare(strict_types=1); namespace FireflyIII\Models; +use Eloquent; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\SoftDeletes; +use Illuminate\Database\Query\Builder; +use Illuminate\Support\Carbon; +use Illuminate\Support\Collection; /** * Class RecurrenceTransaction * - * @property int $transaction_currency_id, - * @property int $foreign_currency_id - * @property int $source_id - * @property int $destination_id - * @property string $amount - * @property string $foreign_amount - * @property string $description - * @property \FireflyIII\Models\TransactionCurrency $transactionCurrency - * @property \FireflyIII\Models\TransactionCurrency $foreignCurrency - * @property \FireflyIII\Models\Account $sourceAccount - * @property \FireflyIII\Models\Account $destinationAccount - * @property \Illuminate\Support\Collection $recurrenceTransactionMeta - * @property int $id - * @property Recurrence $recurrence - * @property \Illuminate\Support\Carbon|null $created_at - * @property \Illuminate\Support\Carbon|null $updated_at - * @property \Illuminate\Support\Carbon|null $deleted_at - * @property int $recurrence_id - * @property int $transaction_currency_id + * @property int $transaction_currency_id, + * @property int $foreign_currency_id + * @property int $source_id + * @property int $destination_id + * @property string $amount + * @property string $foreign_amount + * @property string $description + * @property TransactionCurrency $transactionCurrency + * @property TransactionCurrency $foreignCurrency + * @property Account $sourceAccount + * @property Account $destinationAccount + * @property Collection $recurrenceTransactionMeta + * @property int $id + * @property Recurrence $recurrence + * @property Carbon|null $created_at + * @property Carbon|null $updated_at + * @property Carbon|null $deleted_at + * @property int $recurrence_id * @method static bool|null forceDelete() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceTransaction newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceTransaction newQuery() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\RecurrenceTransaction onlyTrashed() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceTransaction query() + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceTransaction newModelQuery() + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceTransaction newQuery() + * @method static Builder|RecurrenceTransaction onlyTrashed() + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceTransaction query() * @method static bool|null restore() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceTransaction whereAmount($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceTransaction whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceTransaction whereDeletedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceTransaction whereDescription($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceTransaction whereDestinationId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceTransaction whereForeignAmount($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceTransaction whereForeignCurrencyId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceTransaction whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceTransaction whereRecurrenceId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceTransaction whereSourceId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceTransaction whereTransactionCurrencyId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceTransaction whereUpdatedAt($value) - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\RecurrenceTransaction withTrashed() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\RecurrenceTransaction withoutTrashed() - * @mixin \Eloquent + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceTransaction whereAmount($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceTransaction whereCreatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceTransaction whereDeletedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceTransaction whereDescription($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceTransaction whereDestinationId($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceTransaction whereForeignAmount($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceTransaction whereForeignCurrencyId($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceTransaction whereId($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceTransaction whereRecurrenceId($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceTransaction whereSourceId($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceTransaction whereTransactionCurrencyId($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceTransaction whereUpdatedAt($value) + * @method static Builder|RecurrenceTransaction withTrashed() + * @method static Builder|RecurrenceTransaction withoutTrashed() + * @mixin Eloquent */ class RecurrenceTransaction extends Model { diff --git a/app/Models/RecurrenceTransactionMeta.php b/app/Models/RecurrenceTransactionMeta.php index af42bc6f36..db4166eebd 100644 --- a/app/Models/RecurrenceTransactionMeta.php +++ b/app/Models/RecurrenceTransactionMeta.php @@ -24,37 +24,40 @@ declare(strict_types=1); namespace FireflyIII\Models; +use Eloquent; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\SoftDeletes; +use Illuminate\Database\Query\Builder; +use Illuminate\Support\Carbon; /** * Class RecurrenceTransactionMeta * - * @property string $name - * @property string $value - * @property int $id - * @property \Illuminate\Support\Carbon|null $created_at - * @property \Illuminate\Support\Carbon|null $updated_at - * @property \Illuminate\Support\Carbon|null $deleted_at - * @property int $rt_id - * @property-read \FireflyIII\Models\RecurrenceTransaction $recurrenceTransaction + * @property string $name + * @property string $value + * @property int $id + * @property Carbon|null $created_at + * @property Carbon|null $updated_at + * @property Carbon|null $deleted_at + * @property int $rt_id + * @property-read RecurrenceTransaction $recurrenceTransaction * @method static bool|null forceDelete() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceTransactionMeta newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceTransactionMeta newQuery() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\RecurrenceTransactionMeta onlyTrashed() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceTransactionMeta query() + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceTransactionMeta newModelQuery() + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceTransactionMeta newQuery() + * @method static Builder|RecurrenceTransactionMeta onlyTrashed() + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceTransactionMeta query() * @method static bool|null restore() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceTransactionMeta whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceTransactionMeta whereDeletedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceTransactionMeta whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceTransactionMeta whereName($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceTransactionMeta whereRtId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceTransactionMeta whereUpdatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RecurrenceTransactionMeta whereValue($value) - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\RecurrenceTransactionMeta withTrashed() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\RecurrenceTransactionMeta withoutTrashed() - * @mixin \Eloquent + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceTransactionMeta whereCreatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceTransactionMeta whereDeletedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceTransactionMeta whereId($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceTransactionMeta whereName($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceTransactionMeta whereRtId($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceTransactionMeta whereUpdatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|RecurrenceTransactionMeta whereValue($value) + * @method static Builder|RecurrenceTransactionMeta withTrashed() + * @method static Builder|RecurrenceTransactionMeta withoutTrashed() + * @mixin Eloquent */ class RecurrenceTransactionMeta extends Model { diff --git a/app/Models/Role.php b/app/Models/Role.php index 2352452643..d573316ec8 100644 --- a/app/Models/Role.php +++ b/app/Models/Role.php @@ -22,30 +22,34 @@ declare(strict_types=1); namespace FireflyIII\Models; +use Eloquent; use FireflyIII\User; +use Illuminate\Database\Eloquent\Builder; +use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsToMany; +use Illuminate\Support\Carbon; /** * Class Role. * - * @property int $id - * @property string $name - * @property \Illuminate\Support\Carbon|null $created_at - * @property \Illuminate\Support\Carbon|null $updated_at - * @property string|null $display_name - * @property string|null $description - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\User[] $users - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Role newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Role newQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Role query() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Role whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Role whereDescription($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Role whereDisplayName($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Role whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Role whereName($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Role whereUpdatedAt($value) - * @mixin \Eloquent + * @property int $id + * @property string $name + * @property Carbon|null $created_at + * @property Carbon|null $updated_at + * @property string|null $display_name + * @property string|null $description + * @property-read Collection|User[] $users + * @method static Builder|Role newModelQuery() + * @method static Builder|Role newQuery() + * @method static Builder|Role query() + * @method static Builder|Role whereCreatedAt($value) + * @method static Builder|Role whereDescription($value) + * @method static Builder|Role whereDisplayName($value) + * @method static Builder|Role whereId($value) + * @method static Builder|Role whereName($value) + * @method static Builder|Role whereUpdatedAt($value) + * @mixin Eloquent */ class Role extends Model { diff --git a/app/Models/Rule.php b/app/Models/Rule.php index b0e72152f0..c2f0295382 100644 --- a/app/Models/Rule.php +++ b/app/Models/Rule.php @@ -23,54 +23,56 @@ declare(strict_types=1); namespace FireflyIII\Models; use Carbon\Carbon; +use Eloquent; use FireflyIII\User; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\SoftDeletes; +use Illuminate\Database\Query\Builder; use Illuminate\Support\Collection; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** * Class Rule. * - * @property bool $stop_processing - * @property int $id - * @property Collection $ruleTriggers - * @property Collection $ruleActions - * @property bool $active - * @property bool $strict - * @property User $user - * @property Carbon $created_at - * @property Carbon $updated_at - * @property string $title - * @property int $order - * @property RuleGroup $ruleGroup - * @property int $rule_group_id - * @property string $description + * @property bool $stop_processing + * @property int $id + * @property Collection $ruleTriggers + * @property Collection $ruleActions + * @property bool $active + * @property bool $strict + * @property User $user + * @property Carbon $created_at + * @property Carbon $updated_at + * @property string $title + * @property int $order + * @property RuleGroup $ruleGroup + * @property int $rule_group_id + * @property string $description * @property \Illuminate\Support\Carbon|null $deleted_at - * @property int $user_id + * @property int $user_id * @method static bool|null forceDelete() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Rule newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Rule newQuery() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Rule onlyTrashed() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Rule query() + * @method static \Illuminate\Database\Eloquent\Builder|Rule newModelQuery() + * @method static \Illuminate\Database\Eloquent\Builder|Rule newQuery() + * @method static Builder|Rule onlyTrashed() + * @method static \Illuminate\Database\Eloquent\Builder|Rule query() * @method static bool|null restore() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Rule whereActive($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Rule whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Rule whereDeletedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Rule whereDescription($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Rule whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Rule whereOrder($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Rule whereRuleGroupId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Rule whereStopProcessing($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Rule whereStrict($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Rule whereTitle($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Rule whereUpdatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Rule whereUserId($value) - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Rule withTrashed() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Rule withoutTrashed() - * @mixin \Eloquent + * @method static \Illuminate\Database\Eloquent\Builder|Rule whereActive($value) + * @method static \Illuminate\Database\Eloquent\Builder|Rule whereCreatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|Rule whereDeletedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|Rule whereDescription($value) + * @method static \Illuminate\Database\Eloquent\Builder|Rule whereId($value) + * @method static \Illuminate\Database\Eloquent\Builder|Rule whereOrder($value) + * @method static \Illuminate\Database\Eloquent\Builder|Rule whereRuleGroupId($value) + * @method static \Illuminate\Database\Eloquent\Builder|Rule whereStopProcessing($value) + * @method static \Illuminate\Database\Eloquent\Builder|Rule whereStrict($value) + * @method static \Illuminate\Database\Eloquent\Builder|Rule whereTitle($value) + * @method static \Illuminate\Database\Eloquent\Builder|Rule whereUpdatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|Rule whereUserId($value) + * @method static Builder|Rule withTrashed() + * @method static Builder|Rule withoutTrashed() + * @mixin Eloquent */ class Rule extends Model { @@ -100,13 +102,13 @@ class Rule extends Model * * @param string $value * - * @return Rule * @throws NotFoundHttpException + * @return Rule */ public static function routeBinder(string $value): Rule { if (auth()->check()) { - $ruleId = (int)$value; + $ruleId = (int) $value; /** @var User $user */ $user = auth()->user(); /** @var Rule $rule */ @@ -147,6 +149,7 @@ class Rule extends Model /** * @param $value + * * @codeCoverageIgnore */ public function setDescriptionAttribute($value): void diff --git a/app/Models/RuleAction.php b/app/Models/RuleAction.php index 8f0e7f4285..07ab612c60 100644 --- a/app/Models/RuleAction.php +++ b/app/Models/RuleAction.php @@ -23,6 +23,8 @@ declare(strict_types=1); namespace FireflyIII\Models; use Carbon\Carbon; +use Eloquent; +use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; @@ -38,20 +40,20 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo; * @property bool $active * @property bool $stop_processing * @property Rule $rule - * @property int $rule_id - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleAction newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleAction newQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleAction query() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleAction whereActionType($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleAction whereActionValue($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleAction whereActive($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleAction whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleAction whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleAction whereOrder($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleAction whereRuleId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleAction whereStopProcessing($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleAction whereUpdatedAt($value) - * @mixin \Eloquent + * @property int $rule_id + * @method static Builder|RuleAction newModelQuery() + * @method static Builder|RuleAction newQuery() + * @method static Builder|RuleAction query() + * @method static Builder|RuleAction whereActionType($value) + * @method static Builder|RuleAction whereActionValue($value) + * @method static Builder|RuleAction whereActive($value) + * @method static Builder|RuleAction whereCreatedAt($value) + * @method static Builder|RuleAction whereId($value) + * @method static Builder|RuleAction whereOrder($value) + * @method static Builder|RuleAction whereRuleId($value) + * @method static Builder|RuleAction whereStopProcessing($value) + * @method static Builder|RuleAction whereUpdatedAt($value) + * @mixin Eloquent */ class RuleAction extends Model { diff --git a/app/Models/RuleGroup.php b/app/Models/RuleGroup.php index f1c87f7eaa..fd9c13208c 100644 --- a/app/Models/RuleGroup.php +++ b/app/Models/RuleGroup.php @@ -23,48 +23,50 @@ declare(strict_types=1); namespace FireflyIII\Models; use Carbon\Carbon; +use Eloquent; use FireflyIII\User; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\SoftDeletes; +use Illuminate\Database\Query\Builder; use Illuminate\Support\Collection; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** * Class RuleGroup. * - * @property bool $active - * @property User $user - * @property Carbon $created_at - * @property Carbon $updated_at - * @property string $title - * @property string $text - * @property int $id - * @property int $order - * @property Collection $rules - * @property string description + * @property bool $active + * @property User $user + * @property Carbon $created_at + * @property Carbon $updated_at + * @property string $title + * @property string $text + * @property int $id + * @property int $order + * @property Collection $rules + * @property string description * @property \Illuminate\Support\Carbon|null $deleted_at - * @property int $user_id + * @property int $user_id * @method static bool|null forceDelete() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleGroup newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleGroup newQuery() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\RuleGroup onlyTrashed() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleGroup query() + * @method static \Illuminate\Database\Eloquent\Builder|RuleGroup newModelQuery() + * @method static \Illuminate\Database\Eloquent\Builder|RuleGroup newQuery() + * @method static Builder|RuleGroup onlyTrashed() + * @method static \Illuminate\Database\Eloquent\Builder|RuleGroup query() * @method static bool|null restore() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleGroup whereActive($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleGroup whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleGroup whereDeletedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleGroup whereDescription($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleGroup whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleGroup whereOrder($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleGroup whereTitle($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleGroup whereUpdatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleGroup whereUserId($value) - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\RuleGroup withTrashed() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\RuleGroup withoutTrashed() - * @property bool $stop_processing - * @mixin \Eloquent + * @method static \Illuminate\Database\Eloquent\Builder|RuleGroup whereActive($value) + * @method static \Illuminate\Database\Eloquent\Builder|RuleGroup whereCreatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|RuleGroup whereDeletedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|RuleGroup whereDescription($value) + * @method static \Illuminate\Database\Eloquent\Builder|RuleGroup whereId($value) + * @method static \Illuminate\Database\Eloquent\Builder|RuleGroup whereOrder($value) + * @method static \Illuminate\Database\Eloquent\Builder|RuleGroup whereTitle($value) + * @method static \Illuminate\Database\Eloquent\Builder|RuleGroup whereUpdatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|RuleGroup whereUserId($value) + * @method static Builder|RuleGroup withTrashed() + * @method static Builder|RuleGroup withoutTrashed() + * @property bool $stop_processing + * @mixin Eloquent */ class RuleGroup extends Model { @@ -92,13 +94,13 @@ class RuleGroup extends Model * * @param string $value * - * @return RuleGroup * @throws NotFoundHttpException + * @return RuleGroup */ public static function routeBinder(string $value): RuleGroup { if (auth()->check()) { - $ruleGroupId = (int)$value; + $ruleGroupId = (int) $value; /** @var User $user */ $user = auth()->user(); /** @var RuleGroup $ruleGroup */ diff --git a/app/Models/RuleTrigger.php b/app/Models/RuleTrigger.php index 5ab3498958..baa63822fc 100644 --- a/app/Models/RuleTrigger.php +++ b/app/Models/RuleTrigger.php @@ -23,35 +23,37 @@ declare(strict_types=1); namespace FireflyIII\Models; use Carbon\Carbon; +use Eloquent; +use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; /** * Class RuleTrigger. * - * @property string $trigger_value - * @property string $trigger_type - * @property int $id - * @property Carbon $created_at - * @property Carbon $updated_at - * @property int $order - * @property bool $active - * @property bool $stop_processing - * @property int $rule_id - * @property-read \FireflyIII\Models\Rule $rule - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleTrigger newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleTrigger newQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleTrigger query() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleTrigger whereActive($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleTrigger whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleTrigger whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleTrigger whereOrder($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleTrigger whereRuleId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleTrigger whereStopProcessing($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleTrigger whereTriggerType($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleTrigger whereTriggerValue($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\RuleTrigger whereUpdatedAt($value) - * @mixin \Eloquent + * @property string $trigger_value + * @property string $trigger_type + * @property int $id + * @property Carbon $created_at + * @property Carbon $updated_at + * @property int $order + * @property bool $active + * @property bool $stop_processing + * @property int $rule_id + * @property-read Rule $rule + * @method static Builder|RuleTrigger newModelQuery() + * @method static Builder|RuleTrigger newQuery() + * @method static Builder|RuleTrigger query() + * @method static Builder|RuleTrigger whereActive($value) + * @method static Builder|RuleTrigger whereCreatedAt($value) + * @method static Builder|RuleTrigger whereId($value) + * @method static Builder|RuleTrigger whereOrder($value) + * @method static Builder|RuleTrigger whereRuleId($value) + * @method static Builder|RuleTrigger whereStopProcessing($value) + * @method static Builder|RuleTrigger whereTriggerType($value) + * @method static Builder|RuleTrigger whereTriggerValue($value) + * @method static Builder|RuleTrigger whereUpdatedAt($value) + * @mixin Eloquent */ class RuleTrigger extends Model { diff --git a/app/Models/Tag.php b/app/Models/Tag.php index 9e0847efcf..0b11ad319d 100644 --- a/app/Models/Tag.php +++ b/app/Models/Tag.php @@ -23,54 +23,56 @@ declare(strict_types=1); namespace FireflyIII\Models; use Carbon\Carbon; +use Eloquent; use FireflyIII\User; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\MorphMany; use Illuminate\Database\Eloquent\SoftDeletes; +use Illuminate\Database\Query\Builder; use Illuminate\Support\Collection; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** * Class Tag. * - * @property Collection $transactionJournals - * @property string $tag - * @property int $id - * @property \Carbon\Carbon $date - * @property int zoomLevel - * @property float latitude - * @property float longitude - * @property string description - * @property string amount_sum - * @property string tagMode - * @property Carbon created_at - * @property Carbon updated_at + * @property Collection $transactionJournals + * @property string $tag + * @property int $id + * @property Carbon $date + * @property int zoomLevel + * @property float latitude + * @property float longitude + * @property string description + * @property string amount_sum + * @property string tagMode + * @property Carbon created_at + * @property Carbon updated_at * @property \Illuminate\Support\Carbon|null $deleted_at - * @property int $user_id - * @property-read \FireflyIII\User $user + * @property int $user_id + * @property-read User $user * @method static bool|null forceDelete() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Tag newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Tag newQuery() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Tag onlyTrashed() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Tag query() + * @method static \Illuminate\Database\Eloquent\Builder|Tag newModelQuery() + * @method static \Illuminate\Database\Eloquent\Builder|Tag newQuery() + * @method static Builder|Tag onlyTrashed() + * @method static \Illuminate\Database\Eloquent\Builder|Tag query() * @method static bool|null restore() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Tag whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Tag whereDate($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Tag whereDeletedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Tag whereDescription($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Tag whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Tag whereLatitude($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Tag whereLongitude($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Tag whereTag($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Tag whereTagMode($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Tag whereUpdatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Tag whereUserId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Tag whereZoomLevel($value) - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Tag withTrashed() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Tag withoutTrashed() - * @mixin \Eloquent + * @method static \Illuminate\Database\Eloquent\Builder|Tag whereCreatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|Tag whereDate($value) + * @method static \Illuminate\Database\Eloquent\Builder|Tag whereDeletedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|Tag whereDescription($value) + * @method static \Illuminate\Database\Eloquent\Builder|Tag whereId($value) + * @method static \Illuminate\Database\Eloquent\Builder|Tag whereLatitude($value) + * @method static \Illuminate\Database\Eloquent\Builder|Tag whereLongitude($value) + * @method static \Illuminate\Database\Eloquent\Builder|Tag whereTag($value) + * @method static \Illuminate\Database\Eloquent\Builder|Tag whereTagMode($value) + * @method static \Illuminate\Database\Eloquent\Builder|Tag whereUpdatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|Tag whereUserId($value) + * @method static \Illuminate\Database\Eloquent\Builder|Tag whereZoomLevel($value) + * @method static Builder|Tag withTrashed() + * @method static Builder|Tag withoutTrashed() + * @mixin Eloquent */ class Tag extends Model { @@ -92,31 +94,22 @@ class Tag extends Model 'longitude' => 'float', ]; /** @var array Fields that can be filled */ - protected $fillable = ['user_id', 'tag', 'date', 'description','tagMode']; + protected $fillable = ['user_id', 'tag', 'date', 'description', 'tagMode']; protected $hidden = ['zoomLevel', 'latitude', 'longitude']; - /** - * @codeCoverageIgnore - * @return MorphMany - */ - public function locations(): MorphMany - { - return $this->morphMany(Location::class, 'locatable'); - } - /** * Route binder. Converts the key in the URL to the specified object (or throw 404). * * @param string $value * - * @return Tag * @throws NotFoundHttpException + * @return Tag */ public static function routeBinder(string $value): Tag { if (auth()->check()) { - $tagId = (int)$value; + $tagId = (int) $value; /** @var User $user */ $user = auth()->user(); /** @var Tag $tag */ @@ -128,6 +121,14 @@ class Tag extends Model throw new NotFoundHttpException; } + /** + * @codeCoverageIgnore + * @return MorphMany + */ + public function locations(): MorphMany + { + return $this->morphMany(Location::class, 'locatable'); + } /** * @codeCoverageIgnore diff --git a/app/Models/Transaction.php b/app/Models/Transaction.php index c5643399fd..1d77960197 100644 --- a/app/Models/Transaction.php +++ b/app/Models/Transaction.php @@ -23,7 +23,9 @@ declare(strict_types=1); namespace FireflyIII\Models; use Carbon\Carbon; +use Eloquent; use Illuminate\Database\Eloquent\Builder; +use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsToMany; @@ -32,102 +34,102 @@ use Illuminate\Database\Eloquent\SoftDeletes; /** * Class Transaction. * - * @property int $journal_id - * @property Carbon $date - * @property string $transaction_description - * @property string $transaction_amount - * @property string $transaction_foreign_amount - * @property string $transaction_type_type - * @property string $foreign_currency_symbol - * @property int $foreign_currency_dp - * @property int $account_id - * @property string $account_name - * @property string $account_iban - * @property string $account_number - * @property string $account_bic - * @property string $account_type - * @property string $account_currency_code - * @property int $opposing_account_id - * @property string $opposing_account_name - * @property string $opposing_account_iban - * @property string $opposing_account_number - * @property string $opposing_account_bic - * @property string $opposing_account_type - * @property string $opposing_currency_code - * @property int $transaction_budget_id - * @property string $transaction_budget_name - * @property int $transaction_journal_budget_id - * @property string $transaction_journal_budget_name - * @property int $transaction_category_id - * @property string $transaction_category_name - * @property int $transaction_journal_category_id - * @property string $transaction_journal_category_name - * @property int $bill_id - * @property string $bill_name - * @property string $bill_name_encrypted - * @property string $notes - * @property string $tags - * @property string $transaction_currency_name - * @property string $transaction_currency_symbol - * @property int $transaction_currency_dp - * @property string $transaction_currency_code - * @property string $description - * @property bool $is_split - * @property int $attachmentCount - * @property int $transaction_currency_id - * @property int $foreign_currency_id - * @property string $amount - * @property string $foreign_amount - * @property TransactionJournal $transactionJournal - * @property Account $account - * @property int $identifier - * @property int $id - * @property TransactionCurrency $transactionCurrency - * @property int $transaction_journal_id - * @property TransactionCurrency $foreignCurrency - * @property string $before // used in audit reports. - * @property string $after // used in audit reports. - * @property int $opposing_id // ID of the opposing transaction, used in collector - * @property bool $encrypted // is the journal encrypted - * @property bool reconciled - * @property string transaction_category_encrypted - * @property string transaction_journal_category_encrypted - * @property string transaction_budget_encrypted - * @property string transaction_journal_budget_encrypted - * @property string type - * @property string name - * @property Carbon created_at - * @property Carbon updated_at - * @property string foreign_currency_code + * @property int $journal_id + * @property Carbon $date + * @property string $transaction_description + * @property string $transaction_amount + * @property string $transaction_foreign_amount + * @property string $transaction_type_type + * @property string $foreign_currency_symbol + * @property int $foreign_currency_dp + * @property int $account_id + * @property string $account_name + * @property string $account_iban + * @property string $account_number + * @property string $account_bic + * @property string $account_type + * @property string $account_currency_code + * @property int $opposing_account_id + * @property string $opposing_account_name + * @property string $opposing_account_iban + * @property string $opposing_account_number + * @property string $opposing_account_bic + * @property string $opposing_account_type + * @property string $opposing_currency_code + * @property int $transaction_budget_id + * @property string $transaction_budget_name + * @property int $transaction_journal_budget_id + * @property string $transaction_journal_budget_name + * @property int $transaction_category_id + * @property string $transaction_category_name + * @property int $transaction_journal_category_id + * @property string $transaction_journal_category_name + * @property int $bill_id + * @property string $bill_name + * @property string $bill_name_encrypted + * @property string $notes + * @property string $tags + * @property string $transaction_currency_name + * @property string $transaction_currency_symbol + * @property int $transaction_currency_dp + * @property string $transaction_currency_code + * @property string $description + * @property bool $is_split + * @property int $attachmentCount + * @property int $transaction_currency_id + * @property int $foreign_currency_id + * @property string $amount + * @property string $foreign_amount + * @property TransactionJournal $transactionJournal + * @property Account $account + * @property int $identifier + * @property int $id + * @property TransactionCurrency $transactionCurrency + * @property int $transaction_journal_id + * @property TransactionCurrency $foreignCurrency + * @property string $before // used in audit reports. + * @property string $after // used in audit reports. + * @property int $opposing_id // ID of the opposing transaction, used in collector + * @property bool $encrypted // is the journal encrypted + * @property bool reconciled + * @property string transaction_category_encrypted + * @property string transaction_journal_category_encrypted + * @property string transaction_budget_encrypted + * @property string transaction_journal_budget_encrypted + * @property string type + * @property string name + * @property Carbon created_at + * @property Carbon updated_at + * @property string foreign_currency_code * @SuppressWarnings (PHPMD.TooManyPublicMethods) * @property \Illuminate\Support\Carbon|null $deleted_at - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Budget[] $budgets - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Category[] $categories - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Transaction after(\Carbon\Carbon $date) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Transaction before(\Carbon\Carbon $date) + * @property-read Collection|Budget[] $budgets + * @property-read Collection|Category[] $categories + * @method static Builder|Transaction after(Carbon $date) + * @method static Builder|Transaction before(Carbon $date) * @method static bool|null forceDelete() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Transaction newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Transaction newQuery() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Transaction onlyTrashed() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Transaction query() + * @method static Builder|Transaction newModelQuery() + * @method static Builder|Transaction newQuery() + * @method static \Illuminate\Database\Query\Builder|Transaction onlyTrashed() + * @method static Builder|Transaction query() * @method static bool|null restore() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Transaction transactionTypes($types) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Transaction whereAccountId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Transaction whereAmount($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Transaction whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Transaction whereDeletedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Transaction whereDescription($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Transaction whereForeignAmount($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Transaction whereForeignCurrencyId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Transaction whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Transaction whereIdentifier($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Transaction whereReconciled($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Transaction whereTransactionCurrencyId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Transaction whereTransactionJournalId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\Transaction whereUpdatedAt($value) - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Transaction withTrashed() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\Transaction withoutTrashed() - * @mixin \Eloquent + * @method static Builder|Transaction transactionTypes($types) + * @method static Builder|Transaction whereAccountId($value) + * @method static Builder|Transaction whereAmount($value) + * @method static Builder|Transaction whereCreatedAt($value) + * @method static Builder|Transaction whereDeletedAt($value) + * @method static Builder|Transaction whereDescription($value) + * @method static Builder|Transaction whereForeignAmount($value) + * @method static Builder|Transaction whereForeignCurrencyId($value) + * @method static Builder|Transaction whereId($value) + * @method static Builder|Transaction whereIdentifier($value) + * @method static Builder|Transaction whereReconciled($value) + * @method static Builder|Transaction whereTransactionCurrencyId($value) + * @method static Builder|Transaction whereTransactionJournalId($value) + * @method static Builder|Transaction whereUpdatedAt($value) + * @method static \Illuminate\Database\Query\Builder|Transaction withTrashed() + * @method static \Illuminate\Database\Query\Builder|Transaction withoutTrashed() + * @mixin Eloquent */ class Transaction extends Model { @@ -280,7 +282,7 @@ class Transaction extends Model */ public function setAmountAttribute($value): void { - $this->attributes['amount'] = (string)$value; + $this->attributes['amount'] = (string) $value; } /** diff --git a/app/Models/TransactionCurrency.php b/app/Models/TransactionCurrency.php index 49a654052b..35aad46c89 100644 --- a/app/Models/TransactionCurrency.php +++ b/app/Models/TransactionCurrency.php @@ -23,44 +23,47 @@ declare(strict_types=1); namespace FireflyIII\Models; use Carbon\Carbon; +use Eloquent; +use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\SoftDeletes; +use Illuminate\Database\Query\Builder; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** * Class TransactionCurrency. * - * @property string $code - * @property string $symbol - * @property int $decimal_places - * @property int $id - * @property string name - * @property bool $enabled - * @property Carbon $created_at - * @property Carbon $updated_at - * @property \Illuminate\Support\Carbon|null $deleted_at - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\BudgetLimit[] $budgetLimits - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\TransactionJournal[] $transactionJournals - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Transaction[] $transactions + * @property string $code + * @property string $symbol + * @property int $decimal_places + * @property int $id + * @property string name + * @property bool $enabled + * @property Carbon $created_at + * @property Carbon $updated_at + * @property \Illuminate\Support\Carbon|null $deleted_at + * @property-read Collection|BudgetLimit[] $budgetLimits + * @property-read Collection|TransactionJournal[] $transactionJournals + * @property-read Collection|Transaction[] $transactions * @method static bool|null forceDelete() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionCurrency newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionCurrency newQuery() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\TransactionCurrency onlyTrashed() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionCurrency query() + * @method static \Illuminate\Database\Eloquent\Builder|TransactionCurrency newModelQuery() + * @method static \Illuminate\Database\Eloquent\Builder|TransactionCurrency newQuery() + * @method static Builder|TransactionCurrency onlyTrashed() + * @method static \Illuminate\Database\Eloquent\Builder|TransactionCurrency query() * @method static bool|null restore() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionCurrency whereCode($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionCurrency whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionCurrency whereDecimalPlaces($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionCurrency whereDeletedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionCurrency whereEnabled($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionCurrency whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionCurrency whereName($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionCurrency whereSymbol($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionCurrency whereUpdatedAt($value) - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\TransactionCurrency withTrashed() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\TransactionCurrency withoutTrashed() - * @mixin \Eloquent + * @method static \Illuminate\Database\Eloquent\Builder|TransactionCurrency whereCode($value) + * @method static \Illuminate\Database\Eloquent\Builder|TransactionCurrency whereCreatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|TransactionCurrency whereDecimalPlaces($value) + * @method static \Illuminate\Database\Eloquent\Builder|TransactionCurrency whereDeletedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|TransactionCurrency whereEnabled($value) + * @method static \Illuminate\Database\Eloquent\Builder|TransactionCurrency whereId($value) + * @method static \Illuminate\Database\Eloquent\Builder|TransactionCurrency whereName($value) + * @method static \Illuminate\Database\Eloquent\Builder|TransactionCurrency whereSymbol($value) + * @method static \Illuminate\Database\Eloquent\Builder|TransactionCurrency whereUpdatedAt($value) + * @method static Builder|TransactionCurrency withTrashed() + * @method static Builder|TransactionCurrency withoutTrashed() + * @mixin Eloquent */ class TransactionCurrency extends Model { @@ -87,13 +90,13 @@ class TransactionCurrency extends Model * * @param string $value * - * @return TransactionCurrency * @throws NotFoundHttpException + * @return TransactionCurrency */ public static function routeBinder(string $value): TransactionCurrency { if (auth()->check()) { - $currencyId = (int)$value; + $currencyId = (int) $value; $currency = self::find($currencyId); if (null !== $currency) { return $currency; diff --git a/app/Models/TransactionGroup.php b/app/Models/TransactionGroup.php index 76f22e8d6f..d3a25c15c2 100644 --- a/app/Models/TransactionGroup.php +++ b/app/Models/TransactionGroup.php @@ -22,45 +22,49 @@ declare(strict_types=1); namespace FireflyIII\Models; +use Eloquent; use FireflyIII\User; +use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\SoftDeletes; +use Illuminate\Database\Query\Builder; +use Illuminate\Support\Carbon; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** * Class TransactionGroup. * - * @property int $id - * @property \Illuminate\Support\Carbon|null $created_at - * @property \Illuminate\Support\Carbon|null $updated_at - * @property \Illuminate\Support\Carbon|null $deleted_at - * @property int $user_id - * @property string|null $title - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\TransactionJournal[] $transactionJournals - * @property-read \FireflyIII\User $user + * @property int $id + * @property Carbon|null $created_at + * @property Carbon|null $updated_at + * @property Carbon|null $deleted_at + * @property int $user_id + * @property string|null $title + * @property-read Collection|TransactionJournal[] $transactionJournals + * @property-read User $user * @method static bool|null forceDelete() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionGroup newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionGroup newQuery() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\TransactionGroup onlyTrashed() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionGroup query() + * @method static \Illuminate\Database\Eloquent\Builder|TransactionGroup newModelQuery() + * @method static \Illuminate\Database\Eloquent\Builder|TransactionGroup newQuery() + * @method static Builder|TransactionGroup onlyTrashed() + * @method static \Illuminate\Database\Eloquent\Builder|TransactionGroup query() * @method static bool|null restore() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionGroup whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionGroup whereDeletedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionGroup whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionGroup whereTitle($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionGroup whereUpdatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionGroup whereUserId($value) - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\TransactionGroup withTrashed() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\TransactionGroup withoutTrashed() - * @mixin \Eloquent + * @method static \Illuminate\Database\Eloquent\Builder|TransactionGroup whereCreatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|TransactionGroup whereDeletedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|TransactionGroup whereId($value) + * @method static \Illuminate\Database\Eloquent\Builder|TransactionGroup whereTitle($value) + * @method static \Illuminate\Database\Eloquent\Builder|TransactionGroup whereUpdatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|TransactionGroup whereUserId($value) + * @method static Builder|TransactionGroup withTrashed() + * @method static Builder|TransactionGroup withoutTrashed() + * @mixin Eloquent * @property string amount * @property string foreign_amount * @property int transaction_group_id - * @property int transaction_journal_id - * @property string transaction_group_title + * @property int transaction_journal_id + * @property string transaction_group_title */ class TransactionGroup extends Model { @@ -89,18 +93,18 @@ class TransactionGroup extends Model * * @param string $value * - * @return TransactionGroup * @throws NotFoundHttpException + * @return TransactionGroup */ public static function routeBinder(string $value): TransactionGroup { if (auth()->check()) { - $groupId = (int)$value; + $groupId = (int) $value; /** @var User $user */ $user = auth()->user(); /** @var TransactionGroup $group */ $group = $user->transactionGroups() - ->with(['transactionJournals','transactionJournals.transactions']) + ->with(['transactionJournals', 'transactionJournals.transactions']) ->where('transaction_groups.id', $groupId)->first(['transaction_groups.*']); if (null !== $group) { return $group; diff --git a/app/Models/TransactionJournal.php b/app/Models/TransactionJournal.php index e12650d8ef..4ef492f952 100644 --- a/app/Models/TransactionJournal.php +++ b/app/Models/TransactionJournal.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Models; use Carbon\Carbon; +use Eloquent; use FireflyIII\Exceptions\FireflyException; use FireflyIII\User; use Illuminate\Database\Eloquent\Builder; @@ -64,50 +65,50 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; * @property int $id * @property TransactionType $transactionType * @property Collection budgets - * @property Bill $bill - * @property Collection transactionJournalMeta - * @property TransactionGroup transactionGroup - * @property int transaction_group_id + * @property Bill $bill + * @property Collection transactionJournalMeta + * @property TransactionGroup transactionGroup + * @property int transaction_group_id * @SuppressWarnings (PHPMD.TooManyPublicMethods) * @SuppressWarnings (PHPMD.CouplingBetweenObjects) - * @property \Illuminate\Support\Carbon|null $created_at - * @property \Illuminate\Support\Carbon|null $updated_at - * @property \Illuminate\Support\Carbon|null $deleted_at - * @property int $tag_count - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Attachment[] $attachments - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Note[] $notes - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\PiggyBankEvent[] $piggyBankEvents - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\TransactionJournalLink[] $sourceJournalLinks - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Category[] $transactionGroups - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournal after(\Carbon\Carbon $date) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournal before(\Carbon\Carbon $date) + * @property \Illuminate\Support\Carbon|null $created_at + * @property \Illuminate\Support\Carbon|null $updated_at + * @property \Illuminate\Support\Carbon|null $deleted_at + * @property int $tag_count + * @property-read \Illuminate\Database\Eloquent\Collection|Attachment[] $attachments + * @property-read \Illuminate\Database\Eloquent\Collection|Note[] $notes + * @property-read \Illuminate\Database\Eloquent\Collection|PiggyBankEvent[] $piggyBankEvents + * @property-read \Illuminate\Database\Eloquent\Collection|TransactionJournalLink[] $sourceJournalLinks + * @property-read \Illuminate\Database\Eloquent\Collection|Category[] $transactionGroups + * @method static EloquentBuilder|TransactionJournal after(Carbon $date) + * @method static EloquentBuilder|TransactionJournal before(Carbon $date) * @method static bool|null forceDelete() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournal newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournal newQuery() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\TransactionJournal onlyTrashed() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournal query() + * @method static EloquentBuilder|TransactionJournal newModelQuery() + * @method static EloquentBuilder|TransactionJournal newQuery() + * @method static \Illuminate\Database\Query\Builder|TransactionJournal onlyTrashed() + * @method static EloquentBuilder|TransactionJournal query() * @method static bool|null restore() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournal transactionTypes($types) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournal whereBillId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournal whereBookDate($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournal whereCompleted($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournal whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournal whereDate($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournal whereDeletedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournal whereDescription($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournal whereEncrypted($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournal whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournal whereInterestDate($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournal whereOrder($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournal whereProcessDate($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournal whereTagCount($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournal whereTransactionCurrencyId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournal whereTransactionTypeId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournal whereUpdatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournal whereUserId($value) - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\TransactionJournal withTrashed() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\TransactionJournal withoutTrashed() - * @mixin \Eloquent + * @method static EloquentBuilder|TransactionJournal transactionTypes($types) + * @method static EloquentBuilder|TransactionJournal whereBillId($value) + * @method static EloquentBuilder|TransactionJournal whereBookDate($value) + * @method static EloquentBuilder|TransactionJournal whereCompleted($value) + * @method static EloquentBuilder|TransactionJournal whereCreatedAt($value) + * @method static EloquentBuilder|TransactionJournal whereDate($value) + * @method static EloquentBuilder|TransactionJournal whereDeletedAt($value) + * @method static EloquentBuilder|TransactionJournal whereDescription($value) + * @method static EloquentBuilder|TransactionJournal whereEncrypted($value) + * @method static EloquentBuilder|TransactionJournal whereId($value) + * @method static EloquentBuilder|TransactionJournal whereInterestDate($value) + * @method static EloquentBuilder|TransactionJournal whereOrder($value) + * @method static EloquentBuilder|TransactionJournal whereProcessDate($value) + * @method static EloquentBuilder|TransactionJournal whereTagCount($value) + * @method static EloquentBuilder|TransactionJournal whereTransactionCurrencyId($value) + * @method static EloquentBuilder|TransactionJournal whereTransactionTypeId($value) + * @method static EloquentBuilder|TransactionJournal whereUpdatedAt($value) + * @method static EloquentBuilder|TransactionJournal whereUserId($value) + * @method static \Illuminate\Database\Query\Builder|TransactionJournal withTrashed() + * @method static \Illuminate\Database\Query\Builder|TransactionJournal withoutTrashed() + * @mixin Eloquent */ class TransactionJournal extends Model { @@ -135,13 +136,14 @@ class TransactionJournal extends Model /** @var array Fields that can be filled */ protected $fillable - = ['user_id', 'transaction_type_id', 'bill_id', 'tag_count','transaction_currency_id', 'description', 'completed', 'order', + = ['user_id', 'transaction_type_id', 'bill_id', 'tag_count', 'transaction_currency_id', 'description', 'completed', 'order', 'date']; /** @var array Hidden from view */ protected $hidden = ['encrypted']; /** * Checks if tables are joined. + * * @codeCoverageIgnore * * @param Builder $query @@ -169,14 +171,14 @@ class TransactionJournal extends Model * * @param string $value * - * @return TransactionJournal * @throws NotFoundHttpException * @throws FireflyException + * @return TransactionJournal */ public static function routeBinder(string $value): TransactionJournal { if (auth()->check()) { - $journalId = (int)$value; + $journalId = (int) $value; /** @var User $user */ $user = auth()->user(); /** @var TransactionJournal $journal */ @@ -225,6 +227,15 @@ class TransactionJournal extends Model return $this->belongsToMany(Category::class); } + /** + * @codeCoverageIgnore + * @return HasMany + */ + public function destJournalLinks(): HasMany + { + return $this->hasMany(TransactionJournalLink::class, 'destination_id'); + } + /** * @codeCoverageIgnore * @return bool @@ -346,15 +357,6 @@ class TransactionJournal extends Model return $this->hasMany(TransactionJournalLink::class, 'source_id'); } - /** - * @codeCoverageIgnore - * @return HasMany - */ - public function destJournalLinks(): HasMany - { - return $this->hasMany(TransactionJournalLink::class, 'destination_id'); - } - /** * @codeCoverageIgnore * @return BelongsToMany diff --git a/app/Models/TransactionJournalLink.php b/app/Models/TransactionJournalLink.php index 3e062364be..2b421f0488 100644 --- a/app/Models/TransactionJournalLink.php +++ b/app/Models/TransactionJournalLink.php @@ -23,6 +23,9 @@ declare(strict_types=1); namespace FireflyIII\Models; use Carbon\Carbon; +use Eloquent; +use Illuminate\Database\Eloquent\Builder; +use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\MorphMany; @@ -31,28 +34,28 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** * Class TransactionJournalLink. * - * @property int $id - * @property Carbon $created_at - * @property Carbon $updated_at - * @property string $comment - * @property TransactionJournal $source - * @property TransactionJournal $destination - * @property LinkType $linkType - * @property int $link_type_id - * @property int $source_id - * @property int $destination_id - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\Note[] $notes - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournalLink newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournalLink newQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournalLink query() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournalLink whereComment($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournalLink whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournalLink whereDestinationId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournalLink whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournalLink whereLinkTypeId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournalLink whereSourceId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournalLink whereUpdatedAt($value) - * @mixin \Eloquent + * @property int $id + * @property Carbon $created_at + * @property Carbon $updated_at + * @property string $comment + * @property TransactionJournal $source + * @property TransactionJournal $destination + * @property LinkType $linkType + * @property int $link_type_id + * @property int $source_id + * @property int $destination_id + * @property-read Collection|Note[] $notes + * @method static Builder|TransactionJournalLink newModelQuery() + * @method static Builder|TransactionJournalLink newQuery() + * @method static Builder|TransactionJournalLink query() + * @method static Builder|TransactionJournalLink whereComment($value) + * @method static Builder|TransactionJournalLink whereCreatedAt($value) + * @method static Builder|TransactionJournalLink whereDestinationId($value) + * @method static Builder|TransactionJournalLink whereId($value) + * @method static Builder|TransactionJournalLink whereLinkTypeId($value) + * @method static Builder|TransactionJournalLink whereSourceId($value) + * @method static Builder|TransactionJournalLink whereUpdatedAt($value) + * @mixin Eloquent */ class TransactionJournalLink extends Model { @@ -74,14 +77,14 @@ class TransactionJournalLink extends Model * * @param string $value * + * @throws NotFoundHttpException * @return mixed * - * @throws NotFoundHttpException */ public static function routeBinder(string $value): TransactionJournalLink { 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') diff --git a/app/Models/TransactionJournalMeta.php b/app/Models/TransactionJournalMeta.php index 01e250c2dc..21d5770741 100644 --- a/app/Models/TransactionJournalMeta.php +++ b/app/Models/TransactionJournalMeta.php @@ -22,39 +22,42 @@ declare(strict_types=1); namespace FireflyIII\Models; +use Eloquent; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\SoftDeletes; +use Illuminate\Database\Query\Builder; +use Illuminate\Support\Carbon; /** * Class TransactionJournalMeta. * - * @property string $name - * @property int $transaction_journal_id - * @property TransactionJournal $transactionJournal - * @property string $data - * @property int $id - * @property \Illuminate\Support\Carbon|null $created_at - * @property \Illuminate\Support\Carbon|null $updated_at - * @property string $hash - * @property \Illuminate\Support\Carbon|null $deleted_at + * @property string $name + * @property int $transaction_journal_id + * @property TransactionJournal $transactionJournal + * @property string $data + * @property int $id + * @property Carbon|null $created_at + * @property Carbon|null $updated_at + * @property string $hash + * @property Carbon|null $deleted_at * @method static bool|null forceDelete() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournalMeta newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournalMeta newQuery() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\TransactionJournalMeta onlyTrashed() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournalMeta query() + * @method static \Illuminate\Database\Eloquent\Builder|TransactionJournalMeta newModelQuery() + * @method static \Illuminate\Database\Eloquent\Builder|TransactionJournalMeta newQuery() + * @method static Builder|TransactionJournalMeta onlyTrashed() + * @method static \Illuminate\Database\Eloquent\Builder|TransactionJournalMeta query() * @method static bool|null restore() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournalMeta whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournalMeta whereData($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournalMeta whereDeletedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournalMeta whereHash($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournalMeta whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournalMeta whereName($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournalMeta whereTransactionJournalId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionJournalMeta whereUpdatedAt($value) - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\TransactionJournalMeta withTrashed() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\TransactionJournalMeta withoutTrashed() - * @mixin \Eloquent + * @method static \Illuminate\Database\Eloquent\Builder|TransactionJournalMeta whereCreatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|TransactionJournalMeta whereData($value) + * @method static \Illuminate\Database\Eloquent\Builder|TransactionJournalMeta whereDeletedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|TransactionJournalMeta whereHash($value) + * @method static \Illuminate\Database\Eloquent\Builder|TransactionJournalMeta whereId($value) + * @method static \Illuminate\Database\Eloquent\Builder|TransactionJournalMeta whereName($value) + * @method static \Illuminate\Database\Eloquent\Builder|TransactionJournalMeta whereTransactionJournalId($value) + * @method static \Illuminate\Database\Eloquent\Builder|TransactionJournalMeta whereUpdatedAt($value) + * @method static Builder|TransactionJournalMeta withTrashed() + * @method static Builder|TransactionJournalMeta withoutTrashed() + * @mixin Eloquent */ class TransactionJournalMeta extends Model { diff --git a/app/Models/TransactionType.php b/app/Models/TransactionType.php index 0ef4c96c90..d99db5aade 100644 --- a/app/Models/TransactionType.php +++ b/app/Models/TransactionType.php @@ -22,34 +22,38 @@ declare(strict_types=1); namespace FireflyIII\Models; +use Eloquent; +use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\SoftDeletes; +use Illuminate\Database\Query\Builder; +use Illuminate\Support\Carbon; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** * Class TransactionType. * - * @property string $type - * @property int $id - * @property \Illuminate\Support\Carbon|null $created_at - * @property \Illuminate\Support\Carbon|null $updated_at - * @property \Illuminate\Support\Carbon|null $deleted_at - * @property-read \Illuminate\Database\Eloquent\Collection|\FireflyIII\Models\TransactionJournal[] $transactionJournals + * @property string $type + * @property int $id + * @property Carbon|null $created_at + * @property Carbon|null $updated_at + * @property Carbon|null $deleted_at + * @property-read Collection|TransactionJournal[] $transactionJournals * @method static bool|null forceDelete() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionType newModelQuery() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionType newQuery() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\TransactionType onlyTrashed() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionType query() + * @method static \Illuminate\Database\Eloquent\Builder|TransactionType newModelQuery() + * @method static \Illuminate\Database\Eloquent\Builder|TransactionType newQuery() + * @method static Builder|TransactionType onlyTrashed() + * @method static \Illuminate\Database\Eloquent\Builder|TransactionType query() * @method static bool|null restore() - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionType whereCreatedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionType whereDeletedAt($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionType whereId($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionType whereType($value) - * @method static \Illuminate\Database\Eloquent\Builder|\FireflyIII\Models\TransactionType whereUpdatedAt($value) - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\TransactionType withTrashed() - * @method static \Illuminate\Database\Query\Builder|\FireflyIII\Models\TransactionType withoutTrashed() - * @mixin \Eloquent + * @method static \Illuminate\Database\Eloquent\Builder|TransactionType whereCreatedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|TransactionType whereDeletedAt($value) + * @method static \Illuminate\Database\Eloquent\Builder|TransactionType whereId($value) + * @method static \Illuminate\Database\Eloquent\Builder|TransactionType whereType($value) + * @method static \Illuminate\Database\Eloquent\Builder|TransactionType whereUpdatedAt($value) + * @method static Builder|TransactionType withTrashed() + * @method static Builder|TransactionType withoutTrashed() + * @mixin Eloquent */ class TransactionType extends Model { @@ -94,8 +98,8 @@ class TransactionType extends Model * * @param string $type * - * @return Model|null|static * @throws NotFoundHttpException + * @return Model|null|static */ public static function routeBinder(string $type): TransactionType { diff --git a/app/Providers/ImportServiceProvider.php b/app/Providers/ImportServiceProvider.php index 5a3e399c73..6e2fcc79a2 100644 --- a/app/Providers/ImportServiceProvider.php +++ b/app/Providers/ImportServiceProvider.php @@ -30,6 +30,7 @@ use Illuminate\Support\ServiceProvider; /** * @codeCoverageIgnore * Class ImportServiceProvider. + * @deprecated */ class ImportServiceProvider extends ServiceProvider { diff --git a/app/Repositories/Budget/BudgetRepository.php b/app/Repositories/Budget/BudgetRepository.php index c6c90a432c..84a7608399 100644 --- a/app/Repositories/Budget/BudgetRepository.php +++ b/app/Repositories/Budget/BudgetRepository.php @@ -26,11 +26,13 @@ use Carbon\Carbon; use DB; use Exception; use FireflyIII\Exceptions\FireflyException; +use FireflyIII\Models\AutoBudget; use FireflyIII\Models\Budget; use FireflyIII\Models\BudgetLimit; use FireflyIII\Models\RecurrenceTransactionMeta; use FireflyIII\Models\RuleAction; use FireflyIII\Models\RuleTrigger; +use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\Services\Internal\Destroy\BudgetDestroyService; use FireflyIII\User; use Illuminate\Database\QueryException; @@ -282,10 +284,60 @@ class BudgetRepository implements BudgetRepositoryInterface 'name' => $data['name'], ] ); - } catch(QueryException $e) { + } catch (QueryException $e) { + Log::error($e->getMessage()); + Log::error($e->getTraceAsString()); throw new FireflyException('400002: Could not store budget.'); } + // try to create associated auto budget: + $type = $data['auto_budget_type'] ?? 0; + if (0 === $type) { + return $newBudget; + } + if ('reset' === $type) { + $type = AutoBudget::AUTO_BUDGET_RESET; + } + if ('rollover' === $type) { + $type = AutoBudget::AUTO_BUDGET_ROLLOVER; + } + $repos = app(CurrencyRepositoryInterface::class); + $currencyId = (int)($data['transaction_currency_id'] ?? 0); + $currencyCode = (string)($data['transaction_currency_code'] ?? ''); + + $currency = $repos->findNull($currencyId); + if(null === $currency) { + $currency = $repos->findByCodeNull($currencyCode); + } + if(null === $currency) { + $currency = app('amount')->getDefaultCurrencyByUser($this->user); + } + + $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->save(); + + // create initial budget limit. + $today = new Carbon; + $start = app('navigation')->startOfPeriod($today, $autoBudget->period); + $end = app('navigation')->startOfPeriod($start, $autoBudget->period); + + $limitRepos = app(BudgetLimitRepositoryInterface::class); + $limitRepos->setUser($this->user); + $limitRepos->store( + [ + 'budget_id' => $newBudget->id, + 'transaction_currency_id' => $autoBudget->transaction_currency_id, + 'start_date' => $start->format('Y-m-d'), + 'end_date' => $end->format('Y-m-d'), + 'amount' => $autoBudget->amount, + ] + ); + return $newBudget; } @@ -301,6 +353,49 @@ class BudgetRepository implements BudgetRepositoryInterface $budget->name = $data['name']; $budget->active = $data['active']; $budget->save(); + + // update or create auto-budget: + $autoBudgetType = $data['auto_budget_type'] ?? 0; + if ('reset' === $autoBudgetType) { + $autoBudgetType = AutoBudget::AUTO_BUDGET_RESET; + } + if ('rollover' === $autoBudgetType) { + $autoBudgetType = AutoBudget::AUTO_BUDGET_ROLLOVER; + } + if ('none' === $autoBudgetType) { + $autoBudgetType = 0; + } + if (0 !== $autoBudgetType) { + $autoBudget = $this->getAutoBudget($budget); + if (null === $autoBudget) { + $autoBudget = new AutoBudget; + $autoBudget->budget()->associate($budget); + } + + $repos = app(CurrencyRepositoryInterface::class); + $currencyId = (int)($data['transaction_currency_id'] ?? 0); + $currencyCode = (string)($data['transaction_currency_code'] ?? ''); + + $currency = $repos->findNull($currencyId); + if(null === $currency) { + $currency = $repos->findByCodeNull($currencyCode); + } + if(null === $currency) { + $currency = app('amount')->getDefaultCurrencyByUser($this->user); + } + + $autoBudget->transaction_currency_id = $currency->id; + $autoBudget->auto_budget_type = $autoBudgetType; + $autoBudget->amount = $data['auto_budget_amount'] ?? '0'; + $autoBudget->period = $data['auto_budget_period'] ?? 'monthly'; + $autoBudget->save(); + } + if (0 === $autoBudgetType) { + $autoBudget = $this->getAutoBudget($budget); + if (null !== $autoBudget) { + $this->destroyAutoBudget($budget); + } + } $this->updateRuleTriggers($oldName, $data['name']); $this->updateRuleActions($oldName, $data['name']); app('preferences')->mark(); @@ -365,4 +460,23 @@ class BudgetRepository implements BudgetRepositoryInterface $budget->delete(); } } + + /** + * @inheritDoc + */ + public function getAutoBudget(Budget $budget): ?AutoBudget + { + return $budget->autoBudgets()->first(); + } + + /** + * @inheritDoc + */ + public function destroyAutoBudget(Budget $budget): void + { + /** @var AutoBudget $autoBudget */ + foreach ($budget->autoBudgets()->get() as $autoBudget) { + $autoBudget->delete(); + } + } } diff --git a/app/Repositories/Budget/BudgetRepositoryInterface.php b/app/Repositories/Budget/BudgetRepositoryInterface.php index b1bf472bc9..c7e008f96f 100644 --- a/app/Repositories/Budget/BudgetRepositoryInterface.php +++ b/app/Repositories/Budget/BudgetRepositoryInterface.php @@ -23,6 +23,7 @@ declare(strict_types=1); namespace FireflyIII\Repositories\Budget; use Carbon\Carbon; +use FireflyIII\Models\AutoBudget; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\Budget; use FireflyIII\User; @@ -38,6 +39,18 @@ interface BudgetRepositoryInterface */ public function destroyAll(): void; + /** + * @param Budget $budget + * + * @return AutoBudget|null + */ + public function getAutoBudget(Budget $budget): ?AutoBudget; + + /** + * @param Budget $budget + */ + public function destroyAutoBudget(Budget $budget): void; + /** * @return bool diff --git a/app/Repositories/ImportJob/ImportJobRepository.php b/app/Repositories/ImportJob/ImportJobRepository.php index 9716a9e4c2..b8ae64da08 100644 --- a/app/Repositories/ImportJob/ImportJobRepository.php +++ b/app/Repositories/ImportJob/ImportJobRepository.php @@ -37,6 +37,8 @@ use Symfony\Component\HttpFoundation\File\UploadedFile; /** * Class ImportJobRepository. + * @codeCoverageIgnore + * @deprecated * */ class ImportJobRepository implements ImportJobRepositoryInterface diff --git a/app/Repositories/ImportJob/ImportJobRepositoryInterface.php b/app/Repositories/ImportJob/ImportJobRepositoryInterface.php index 76dfae1e51..4f585c78de 100644 --- a/app/Repositories/ImportJob/ImportJobRepositoryInterface.php +++ b/app/Repositories/ImportJob/ImportJobRepositoryInterface.php @@ -32,6 +32,8 @@ use Symfony\Component\HttpFoundation\File\UploadedFile; /** * Interface ImportJobRepositoryInterface. + * @codeCoverageIgnore + * @deprecated */ interface ImportJobRepositoryInterface { diff --git a/app/Repositories/Rule/RuleRepository.php b/app/Repositories/Rule/RuleRepository.php index 75c5a32e1f..c9b16dbe8a 100644 --- a/app/Repositories/Rule/RuleRepository.php +++ b/app/Repositories/Rule/RuleRepository.php @@ -475,4 +475,32 @@ class RuleRepository implements RuleRepositoryInterface return true; } + + /** + * @inheritDoc + */ + public function duplicate(Rule $rule): Rule + { + $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->rule_id = $newRule->id; + $newTrigger->save(); + } + + // replicate all actions + /** @var RuleAction $action */ + foreach ($rule->ruleActions as $action) { + $newAction = $action->replicate(); + $newAction->rule_id = $newRule->id; + $newAction->save(); + } + + return $newRule; + } } diff --git a/app/Repositories/Rule/RuleRepositoryInterface.php b/app/Repositories/Rule/RuleRepositoryInterface.php index 1cec41bdf7..a979201e34 100644 --- a/app/Repositories/Rule/RuleRepositoryInterface.php +++ b/app/Repositories/Rule/RuleRepositoryInterface.php @@ -46,6 +46,13 @@ interface RuleRepositoryInterface */ public function destroy(Rule $rule): bool; + /** + * @param Rule $rule + * + * @return Rule + */ + public function duplicate(Rule $rule): Rule; + /** * @param int $ruleId * diff --git a/app/Repositories/TransactionGroup/TransactionGroupRepository.php b/app/Repositories/TransactionGroup/TransactionGroupRepository.php index 15a47653d8..066fc03ff7 100644 --- a/app/Repositories/TransactionGroup/TransactionGroupRepository.php +++ b/app/Repositories/TransactionGroup/TransactionGroupRepository.php @@ -378,52 +378,20 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface { $array = $journal->toArray(); $array['transactions'] = []; - $array['meta'] = []; - $array['tags'] = []; - $array['categories'] = []; - $array['budgets'] = []; - $array['notes'] = []; - $array['locations'] = []; - $array['attachments'] = []; - $array['links'] = []; - $array['piggy_bank_events'] = []; + $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'] = []; // todo + $array['attachments'] = $journal->attachments->toArray(); + $array['links'] = []; // todo + $array['piggy_bank_events'] = $journal->piggyBankEvents->toArray(); /** @var Transaction $transaction */ foreach ($journal->transactions as $transaction) { $array['transactions'][] = $this->expandTransaction($transaction); } - foreach ($journal->transactionJournalMeta as $meta) { - $array['meta'][] = $meta->toArray(); - } - - foreach ($journal->tags as $tag) { - $array['tags'][] = $tag->toArray(); - } - foreach ($journal->categories as $category) { - $array['categories'][] = $category->toArray(); - } - - foreach ($journal->budgets as $budget) { - $array['budgets'][] = $budget->toArray(); - } - foreach ($journal->notes as $note) { - $array['notes'][] = $note->toArray(); - } - - foreach ($journal->attachments as $attachment) { - $array['attachments'][] = $attachment->toArray(); - } - // TODO apparantly this doesnt work. - foreach ($journal->sourceJournalLinks as $link) { - $array['links'][] = $link->toArray(); - } - foreach ($journal->destJournalLinks as $link) { - $array['links'][] = $link->toArray(); - } - - foreach ($journal->piggyBankEvents as $event) { - $array['piggy_bank_events'][] = $event->toArray(); - } return $array; } diff --git a/app/Repositories/TransactionGroup/TransactionGroupRepositoryInterface.php b/app/Repositories/TransactionGroup/TransactionGroupRepositoryInterface.php index ce0a7e0be1..014f49e7d8 100644 --- a/app/Repositories/TransactionGroup/TransactionGroupRepositoryInterface.php +++ b/app/Repositories/TransactionGroup/TransactionGroupRepositoryInterface.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Repositories\TransactionGroup; use FireflyIII\Exceptions\DuplicateTransactionException; +use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\TransactionGroup; use FireflyIII\Support\NullArrayObject; use FireflyIII\User; @@ -135,6 +136,7 @@ interface TransactionGroupRepositoryInterface * * @return TransactionGroup * @throws DuplicateTransactionException + * @throws FireflyException */ public function store(array $data): TransactionGroup; diff --git a/app/Services/Bunq/ApiContext.php b/app/Services/Bunq/ApiContext.php index ea40d966c1..679b5b0b46 100644 --- a/app/Services/Bunq/ApiContext.php +++ b/app/Services/Bunq/ApiContext.php @@ -35,7 +35,9 @@ use Tests\Object\FakeApiContext; * Special class to hide away bunq's static initialisation methods. * * Class ApiContext + * * @codeCoverageIgnore + * @deprecated */ class ApiContext { diff --git a/app/Services/Bunq/MonetaryAccount.php b/app/Services/Bunq/MonetaryAccount.php index 369339731c..27cc131567 100644 --- a/app/Services/Bunq/MonetaryAccount.php +++ b/app/Services/Bunq/MonetaryAccount.php @@ -32,6 +32,7 @@ use FireflyIII\Exceptions\FireflyException; /** * Class MonetaryAccount * @codeCoverageIgnore + * @deprecated */ class MonetaryAccount { diff --git a/app/Services/Bunq/Payment.php b/app/Services/Bunq/Payment.php index 9801cda9de..1ff540e7e9 100644 --- a/app/Services/Bunq/Payment.php +++ b/app/Services/Bunq/Payment.php @@ -32,6 +32,7 @@ use FireflyIII\Exceptions\FireflyException; /** * Class Payment * @codeCoverageIgnore + * @deprecated */ class Payment { diff --git a/app/Services/IP/IPRetrievalInterface.php b/app/Services/IP/IPRetrievalInterface.php index 52f5cda9ef..d8d8899081 100644 --- a/app/Services/IP/IPRetrievalInterface.php +++ b/app/Services/IP/IPRetrievalInterface.php @@ -25,7 +25,8 @@ namespace FireflyIII\Services\IP; /** * Interface IPRetrievalInterface - * + * @codeCoverageIgnore + * @deprecated */ interface IPRetrievalInterface { diff --git a/app/Services/IP/IpifyOrg.php b/app/Services/IP/IpifyOrg.php index 6cb62cdbe2..1bfb54e1f0 100644 --- a/app/Services/IP/IpifyOrg.php +++ b/app/Services/IP/IpifyOrg.php @@ -31,7 +31,9 @@ use RuntimeException; /** * Class IpifyOrg + * * @codeCoverageIgnore + * @deprecated */ class IpifyOrg implements IPRetrievalInterface { diff --git a/app/Services/Internal/Destroy/BudgetDestroyService.php b/app/Services/Internal/Destroy/BudgetDestroyService.php index f1573ab384..745c4886fd 100644 --- a/app/Services/Internal/Destroy/BudgetDestroyService.php +++ b/app/Services/Internal/Destroy/BudgetDestroyService.php @@ -49,12 +49,18 @@ class BudgetDestroyService */ public function destroy(Budget $budget): void { + try { $budget->delete(); } catch (Exception $e) { // @codeCoverageIgnore Log::error(sprintf('Could not delete budget: %s', $e->getMessage())); // @codeCoverageIgnore } + // also delete auto budget: + foreach ($budget->autoBudgets()->get() as $autoBudget) { + $autoBudget->delete(); + } + // also delete all relations between categories and transaction journals: DB::table('budget_transaction_journal')->where('budget_id', (int)$budget->id)->delete(); diff --git a/app/Services/Internal/Update/AccountUpdateService.php b/app/Services/Internal/Update/AccountUpdateService.php index 12794d1a49..f8a88c3b87 100644 --- a/app/Services/Internal/Update/AccountUpdateService.php +++ b/app/Services/Internal/Update/AccountUpdateService.php @@ -76,28 +76,11 @@ class AccountUpdateService { $this->accountRepository->setUser($account->user); $this->user = $account->user; - - // update the account itself: - $account->name = $data['name'] ?? $account->name; - $account->active = $data['active'] ?? $account->active; - $account->iban = $data['iban'] ?? $account->iban; - - // if account type is a liability, the liability type (account type) - // can be updated to another one. - if ($this->isLiability($account) && $this->isLiabilityTypeId((int)($data['account_type_id'] ?? 0))) { - $account->account_type_id = (int)$data['account_type_id']; - } - - // update virtual balance (could be set to zero if empty string). - if (null !== $data['virtual_balance']) { - $account->virtual_balance = '' === trim($data['virtual_balance']) ? '0' : $data['virtual_balance']; - } - - $account->save(); + $account = $this->updateAccount($account, $data); // find currency, or use default currency instead. if (isset($data['currency_id']) && (null !== $data['currency_id'] || null !== $data['currency_code'])) { - $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'] = $currency->id; } @@ -178,4 +161,33 @@ class AccountUpdateService return 1 === AccountType::whereIn('type', [AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE])->where('id', $accountTypeId)->count(); } + + /** + * @param Account $account + * @param array $data + * + * @return Account + */ + private function updateAccount(Account $account, array $data): Account + { + // update the account itself: + $account->name = $data['name'] ?? $account->name; + $account->active = $data['active'] ?? $account->active; + $account->iban = $data['iban'] ?? $account->iban; + + // if account type is a liability, the liability type (account type) + // can be updated to another one. + if ($this->isLiability($account) && $this->isLiabilityTypeId((int) ($data['account_type_id'] ?? 0))) { + $account->account_type_id = (int) $data['account_type_id']; + } + + // update virtual balance (could be set to zero if empty string). + if (null !== $data['virtual_balance']) { + $account->virtual_balance = '' === trim($data['virtual_balance']) ? '0' : $data['virtual_balance']; + } + + $account->save(); + + return $account; + } } diff --git a/app/Services/Internal/Update/GroupCloneService.php b/app/Services/Internal/Update/GroupCloneService.php index fb29887937..e5fb261197 100644 --- a/app/Services/Internal/Update/GroupCloneService.php +++ b/app/Services/Internal/Update/GroupCloneService.php @@ -120,6 +120,11 @@ class GroupCloneService } } + /** + * @param Note $note + * @param TransactionJournal $newJournal + * @param int $oldGroupId + */ private function cloneNote(Note $note, TransactionJournal $newJournal, int $oldGroupId): void { $newNote = $note->replicate(); @@ -139,6 +144,7 @@ class GroupCloneService { $newTransaction = $transaction->replicate(); $newTransaction->transaction_journal_id = $newJournal->id; + $newTransaction->reconciled = false; $newTransaction->save(); } diff --git a/app/Services/Internal/Update/JournalUpdateService.php b/app/Services/Internal/Update/JournalUpdateService.php index cd81e16257..dee9a22552 100644 --- a/app/Services/Internal/Update/JournalUpdateService.php +++ b/app/Services/Internal/Update/JournalUpdateService.php @@ -153,56 +153,14 @@ class JournalUpdateService $this->transactionJournal->save(); $this->transactionJournal->refresh(); - // update category - if ($this->hasFields(['category_id', 'category_name'])) { - Log::debug('Will update category.'); - - $this->storeCategory($this->transactionJournal, new NullArrayObject($this->data)); - } - // update budget - if ($this->hasFields(['budget_id', 'budget_name'])) { - Log::debug('Will update budget.'); - $this->storeBudget($this->transactionJournal, new NullArrayObject($this->data)); - } - // update tags - - if ($this->hasFields(['tags'])) { - Log::debug('Will update tags.'); - $tags = $this->data['tags'] ?? null; - $this->storeTags($this->transactionJournal, $tags); - } - - // update notes. - if ($this->hasFields(['notes'])) { - $notes = '' === (string)$this->data['notes'] ? null : $this->data['notes']; - $this->storeNotes($this->transactionJournal, $notes); - } - // update meta fields. - // first string - if ($this->hasFields($this->metaString)) { - Log::debug('Meta string fields are present.'); - $this->updateMetaFields(); - } - - // then date fields. - if ($this->hasFields($this->metaDate)) { - Log::debug('Meta date fields are present.'); - $this->updateMetaDateFields(); - } - - - // update transactions. - if ($this->hasFields(['currency_id', 'currency_code'])) { - $this->updateCurrency(); - } - if ($this->hasFields(['amount'])) { - $this->updateAmount(); - } - - // amount, foreign currency. - if ($this->hasFields(['foreign_currency_id', 'foreign_currency_code', 'foreign_amount'])) { - $this->updateForeignAmount(); - } + $this->updateCategory(); + $this->updateBudget(); + $this->updateTags(); + $this->updateNotes(); + $this->updateMeta(); + $this->updateCurrency(); + $this->updateAmount(); + $this->updateForeignAmount(); // TODO update hash @@ -477,6 +435,10 @@ class JournalUpdateService */ private function updateAmount(): void { + if (!$this->hasFields(['amount'])) { + return; + } + $value = $this->data['amount'] ?? ''; try { $amount = $this->getAmount($value); @@ -513,19 +475,48 @@ class JournalUpdateService ) && TransactionType::WITHDRAWAL === $type ) { - $billId = (int)($this->data['bill_id'] ?? 0); - $billName = (string)($this->data['bill_name'] ?? ''); + $billId = (int) ($this->data['bill_id'] ?? 0); + $billName = (string) ($this->data['bill_name'] ?? ''); $bill = $this->billRepository->findBill($billId, $billName); $this->transactionJournal->bill_id = null === $bill ? null : $bill->id; Log::debug('Updated bill ID'); } } + /** + * + */ + private function updateBudget(): void + { + // update budget + if ($this->hasFields(['budget_id', 'budget_name'])) { + Log::debug('Will update budget.'); + $this->storeBudget($this->transactionJournal, new NullArrayObject($this->data)); + } + } + + /** + * + */ + private function updateCategory(): void + { + // update category + if ($this->hasFields(['category_id', 'category_name'])) { + Log::debug('Will update category.'); + + $this->storeCategory($this->transactionJournal, new NullArrayObject($this->data)); + } + } + /** * */ private function updateCurrency(): void { + // update transactions. + 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); @@ -568,6 +559,11 @@ class JournalUpdateService */ private function updateForeignAmount(): void { + // amount, foreign currency. + if (!$this->hasFields(['foreign_currency_id', 'foreign_currency_code', 'foreign_amount'])) { + return; + } + $amount = $this->data['foreign_amount'] ?? null; $foreignAmount = $this->getForeignAmount($amount); $source = $this->getSourceTransaction(); @@ -622,6 +618,25 @@ class JournalUpdateService $this->destinationTransaction->refresh(); } + /** + * + */ + private function updateMeta(): void + { + // update meta fields. + // first string + if ($this->hasFields($this->metaString)) { + Log::debug('Meta string fields are present.'); + $this->updateMetaFields(); + } + + // then date fields. + if ($this->hasFields($this->metaDate)) { + Log::debug('Meta date fields are present.'); + $this->updateMetaDateFields(); + } + } + /** * */ @@ -672,6 +687,30 @@ class JournalUpdateService } } + /** + * + */ + private function updateNotes(): void + { + // update notes. + if ($this->hasFields(['notes'])) { + $notes = '' === (string) $this->data['notes'] ? null : $this->data['notes']; + $this->storeNotes($this->transactionJournal, $notes); + } + } + + /** + * + */ + private function updateTags(): void + { + if ($this->hasFields(['tags'])) { + Log::debug('Will update tags.'); + $tags = $this->data['tags'] ?? null; + $this->storeTags($this->transactionJournal, $tags); + } + } + /** * Updates journal transaction type. */ diff --git a/app/Services/Password/PwndVerifierV3.php b/app/Services/Password/PwndVerifierV3.php index b2534d64a1..817d9ccf2c 100644 --- a/app/Services/Password/PwndVerifierV3.php +++ b/app/Services/Password/PwndVerifierV3.php @@ -33,6 +33,8 @@ use RuntimeException; /** * Class PwndVerifierV3 * @codeCoverageIgnore + * @codeCoverageIgnore + * @deprecated */ class PwndVerifierV3 implements Verifier { diff --git a/app/Services/Spectre/Exception/DuplicatedCustomerException.php b/app/Services/Spectre/Exception/DuplicatedCustomerException.php index daccd12f19..8beb4cc17d 100644 --- a/app/Services/Spectre/Exception/DuplicatedCustomerException.php +++ b/app/Services/Spectre/Exception/DuplicatedCustomerException.php @@ -26,6 +26,7 @@ namespace FireflyIII\Services\Spectre\Exception; /** * @codeCoverageIgnore * Class DuplicatedCustomerException + * @deprecated */ class DuplicatedCustomerException extends SpectreException { diff --git a/app/Services/Spectre/Exception/SpectreException.php b/app/Services/Spectre/Exception/SpectreException.php index 02e422f5ae..73e0e22c81 100644 --- a/app/Services/Spectre/Exception/SpectreException.php +++ b/app/Services/Spectre/Exception/SpectreException.php @@ -28,6 +28,7 @@ use Exception; /** * @codeCoverageIgnore * Class SpectreException + * @deprecated */ class SpectreException extends Exception { diff --git a/app/Services/Spectre/Exception/WrongRequestFormatException.php b/app/Services/Spectre/Exception/WrongRequestFormatException.php index 424ccc2356..5dce219a97 100644 --- a/app/Services/Spectre/Exception/WrongRequestFormatException.php +++ b/app/Services/Spectre/Exception/WrongRequestFormatException.php @@ -26,6 +26,7 @@ namespace FireflyIII\Services\Spectre\Exception; /** * @codeCoverageIgnore * Class WrongRequestFormatException + * @deprecated */ class WrongRequestFormatException extends SpectreException { diff --git a/app/Services/Spectre/Object/Account.php b/app/Services/Spectre/Object/Account.php index 3f6233bf98..2da7f1fd11 100644 --- a/app/Services/Spectre/Object/Account.php +++ b/app/Services/Spectre/Object/Account.php @@ -30,6 +30,7 @@ use Carbon\Carbon; * * @codeCoverageIgnore * @SuppressWarnings(PHPMD.ShortVariable) + * @deprecated */ class Account extends SpectreObject { diff --git a/app/Services/Spectre/Object/Attempt.php b/app/Services/Spectre/Object/Attempt.php index 09a5e511b8..434ecfbbd8 100644 --- a/app/Services/Spectre/Object/Attempt.php +++ b/app/Services/Spectre/Object/Attempt.php @@ -32,6 +32,7 @@ use Carbon\Carbon; * @codeCoverageIgnore * @SuppressWarnings(PHPMD.ShortVariable) * @SuppressWarnings(PHPMD.TooManyFields) + * @deprecated */ class Attempt extends SpectreObject { diff --git a/app/Services/Spectre/Object/Customer.php b/app/Services/Spectre/Object/Customer.php index 57183dce1f..b526cd4195 100644 --- a/app/Services/Spectre/Object/Customer.php +++ b/app/Services/Spectre/Object/Customer.php @@ -27,6 +27,7 @@ namespace FireflyIII\Services\Spectre\Object; * * @codeCoverageIgnore * @SuppressWarnings(PHPMD.ShortVariable) + * @deprecated */ class Customer extends SpectreObject { diff --git a/app/Services/Spectre/Object/Holder.php b/app/Services/Spectre/Object/Holder.php index d0d93f6f53..8c2e739342 100644 --- a/app/Services/Spectre/Object/Holder.php +++ b/app/Services/Spectre/Object/Holder.php @@ -27,6 +27,7 @@ namespace FireflyIII\Services\Spectre\Object; * Class Holder * * @codeCoverageIgnore + * @deprecated */ class Holder extends SpectreObject { diff --git a/app/Services/Spectre/Object/Login.php b/app/Services/Spectre/Object/Login.php index 4a475ae8f3..55d176cb24 100644 --- a/app/Services/Spectre/Object/Login.php +++ b/app/Services/Spectre/Object/Login.php @@ -32,6 +32,7 @@ use Carbon\Carbon; * @codeCoverageIgnore * @SuppressWarnings(PHPMD.ShortVariable) * @SuppressWarnings(PHPMD.TooManyFields) + * @deprecated */ class Login extends SpectreObject { diff --git a/app/Services/Spectre/Object/SpectreObject.php b/app/Services/Spectre/Object/SpectreObject.php index 5ec3932760..41030b0ff6 100644 --- a/app/Services/Spectre/Object/SpectreObject.php +++ b/app/Services/Spectre/Object/SpectreObject.php @@ -25,6 +25,7 @@ namespace FireflyIII\Services\Spectre\Object; /** * @codeCoverageIgnore * Class SpectreObject + * @deprecated */ class SpectreObject { diff --git a/app/Services/Spectre/Object/Token.php b/app/Services/Spectre/Object/Token.php index becc575153..f344c2c6be 100644 --- a/app/Services/Spectre/Object/Token.php +++ b/app/Services/Spectre/Object/Token.php @@ -28,6 +28,7 @@ use Carbon\Carbon; /** * @codeCoverageIgnore * Class Token + * @deprecated */ class Token extends SpectreObject { diff --git a/app/Services/Spectre/Object/Transaction.php b/app/Services/Spectre/Object/Transaction.php index 6896558c4b..62fc784d2c 100644 --- a/app/Services/Spectre/Object/Transaction.php +++ b/app/Services/Spectre/Object/Transaction.php @@ -29,6 +29,7 @@ use Carbon\Carbon; * Class Transaction * * @codeCoverageIgnore + * @deprecated * * @SuppressWarnings(PHPMD.ShortVariable) */ diff --git a/app/Services/Spectre/Object/TransactionExtra.php b/app/Services/Spectre/Object/TransactionExtra.php index 1fb9d38ffc..160b1247a0 100644 --- a/app/Services/Spectre/Object/TransactionExtra.php +++ b/app/Services/Spectre/Object/TransactionExtra.php @@ -31,6 +31,7 @@ use Carbon\Carbon; * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.ShortVariable) * @codeCoverageIgnore + * @deprecated */ class TransactionExtra extends SpectreObject { diff --git a/app/Services/Spectre/Request/CreateTokenRequest.php b/app/Services/Spectre/Request/CreateTokenRequest.php index 5c90ce3684..ff47245fd5 100644 --- a/app/Services/Spectre/Request/CreateTokenRequest.php +++ b/app/Services/Spectre/Request/CreateTokenRequest.php @@ -29,7 +29,9 @@ use FireflyIII\Services\Spectre\Object\Token; /** * Class CreateTokenRequest + * * @codeCoverageIgnore + * @deprecated */ class CreateTokenRequest extends SpectreRequest { diff --git a/app/Services/Spectre/Request/ListAccountsRequest.php b/app/Services/Spectre/Request/ListAccountsRequest.php index 66945560e2..95f870018e 100644 --- a/app/Services/Spectre/Request/ListAccountsRequest.php +++ b/app/Services/Spectre/Request/ListAccountsRequest.php @@ -30,7 +30,9 @@ use Log; /** * Class ListAccountsRequest + * * @codeCoverageIgnore + * @deprecated */ class ListAccountsRequest extends SpectreRequest { diff --git a/app/Services/Spectre/Request/ListCustomersRequest.php b/app/Services/Spectre/Request/ListCustomersRequest.php index cbfd846643..6fd6a823c7 100644 --- a/app/Services/Spectre/Request/ListCustomersRequest.php +++ b/app/Services/Spectre/Request/ListCustomersRequest.php @@ -29,7 +29,9 @@ use Log; /** * Class ListCustomersRequest + * * @codeCoverageIgnore + * @deprecated */ class ListCustomersRequest extends SpectreRequest { diff --git a/app/Services/Spectre/Request/ListLoginsRequest.php b/app/Services/Spectre/Request/ListLoginsRequest.php index d5492d91bc..9c310f7dd4 100644 --- a/app/Services/Spectre/Request/ListLoginsRequest.php +++ b/app/Services/Spectre/Request/ListLoginsRequest.php @@ -31,7 +31,9 @@ use Log; /** * Class ListLoginsRequest + * * @codeCoverageIgnore + * @deprecated */ class ListLoginsRequest extends SpectreRequest { diff --git a/app/Services/Spectre/Request/ListTransactionsRequest.php b/app/Services/Spectre/Request/ListTransactionsRequest.php index a6763c1156..015599273a 100644 --- a/app/Services/Spectre/Request/ListTransactionsRequest.php +++ b/app/Services/Spectre/Request/ListTransactionsRequest.php @@ -30,7 +30,9 @@ use Log; /** * Class ListTransactionsRequest + * * @codeCoverageIgnore + * @deprecated */ class ListTransactionsRequest extends SpectreRequest { diff --git a/app/Services/Spectre/Request/NewCustomerRequest.php b/app/Services/Spectre/Request/NewCustomerRequest.php index 9c4e10f687..1c7aa32ffc 100644 --- a/app/Services/Spectre/Request/NewCustomerRequest.php +++ b/app/Services/Spectre/Request/NewCustomerRequest.php @@ -27,7 +27,9 @@ use Log; /** * Class NewCustomerRequest + * * @codeCoverageIgnore + * @deprecated */ class NewCustomerRequest extends SpectreRequest { diff --git a/app/Services/Spectre/Request/SpectreRequest.php b/app/Services/Spectre/Request/SpectreRequest.php index 1298ee7f31..f9e959c237 100644 --- a/app/Services/Spectre/Request/SpectreRequest.php +++ b/app/Services/Spectre/Request/SpectreRequest.php @@ -32,7 +32,9 @@ use RuntimeException; /** * Class SpectreRequest + * * @codeCoverageIgnore + * @deprecated */ abstract class SpectreRequest { diff --git a/app/Services/Ynab/Request/GetAccountsRequest.php b/app/Services/Ynab/Request/GetAccountsRequest.php index 29f7a833ca..147dd287a6 100644 --- a/app/Services/Ynab/Request/GetAccountsRequest.php +++ b/app/Services/Ynab/Request/GetAccountsRequest.php @@ -27,7 +27,9 @@ use Log; /** * Class GetAccountsRequest + * * @codeCoverageIgnore + * @deprecated */ class GetAccountsRequest extends YnabRequest { diff --git a/app/Services/Ynab/Request/GetBudgetsRequest.php b/app/Services/Ynab/Request/GetBudgetsRequest.php index 3e5476de99..b392964a69 100644 --- a/app/Services/Ynab/Request/GetBudgetsRequest.php +++ b/app/Services/Ynab/Request/GetBudgetsRequest.php @@ -27,7 +27,9 @@ use Log; /** * Class GetBudgetsRequest + * * @codeCoverageIgnore + * @deprecated */ class GetBudgetsRequest extends YnabRequest { diff --git a/app/Services/Ynab/Request/GetTransactionsRequest.php b/app/Services/Ynab/Request/GetTransactionsRequest.php index 9a31ac4108..3a3fe1a5ac 100644 --- a/app/Services/Ynab/Request/GetTransactionsRequest.php +++ b/app/Services/Ynab/Request/GetTransactionsRequest.php @@ -27,7 +27,9 @@ use Log; /** * Class GetTransactionsRequest + * * @codeCoverageIgnore + * @deprecated */ class GetTransactionsRequest extends YnabRequest { diff --git a/app/Services/Ynab/Request/YnabRequest.php b/app/Services/Ynab/Request/YnabRequest.php index 8e54242fe0..7a2034342f 100644 --- a/app/Services/Ynab/Request/YnabRequest.php +++ b/app/Services/Ynab/Request/YnabRequest.php @@ -30,7 +30,9 @@ use RuntimeException; /** * Class YnabRequest + * * @codeCoverageIgnore + * @deprecated */ abstract class YnabRequest { diff --git a/app/Support/Amount.php b/app/Support/Amount.php index bbd0cd74ff..6b10c6a627 100644 --- a/app/Support/Amount.php +++ b/app/Support/Amount.php @@ -117,37 +117,16 @@ class Amount * This method will properly format the given number, in color or "black and white", * as a currency, given two things: the currency required and the current locale. * - * @param \FireflyIII\Models\TransactionCurrency $format - * @param string $amount - * @param bool $coloured + * @param TransactionCurrency $format + * @param string $amount + * @param bool $coloured * * @return string * */ public function formatAnything(TransactionCurrency $format, string $amount, bool $coloured = null): string { - $coloured = $coloured ?? true; - $float = round($amount, 12); - $info = $this->getLocaleInfo(); - $formatted = number_format($float, (int)$format->decimal_places, $info['mon_decimal_point'], $info['mon_thousands_sep']); - - $precedes = $amount < 0 ? $info['n_cs_precedes'] : $info['p_cs_precedes']; - $separated = $amount < 0 ? $info['n_sep_by_space'] : $info['p_sep_by_space']; - $space = true === $separated ? ' ' : ''; - $result = false === $precedes ? $formatted . $space . $format->symbol : $format->symbol . $space . $formatted; - - if (true === $coloured) { - if ($amount > 0) { - return sprintf('%s', $result); - } - if ($amount < 0) { - return sprintf('%s', $result); - } - - return sprintf('%s', $result); - } - - return $result; + return $this->formatFlat($format->symbol, (int)$format->decimal_places, $amount, $coloured); } /** @@ -169,14 +148,6 @@ class Amount $float = round($amount, 12); $info = $this->getLocaleInfo(); $formatted = number_format($float, $decimalPlaces, $info['mon_decimal_point'], $info['mon_thousands_sep']); - - // some complicated switches to format the amount correctly: - $info['n_cs_precedes'] = (is_bool($info['n_cs_precedes']) && true === $info['n_cs_precedes']) - || (is_int($info['n_cs_precedes']) && 1 === $info['n_cs_precedes']); - - $info['p_cs_precedes'] = (is_bool($info['p_cs_precedes']) && true === $info['p_cs_precedes']) - || (is_int($info['p_cs_precedes']) && 1 === $info['p_cs_precedes']); - $precedes = $amount < 0 ? $info['n_cs_precedes'] : $info['p_cs_precedes']; $separated = $amount < 0 ? $info['n_sep_by_space'] : $info['p_sep_by_space']; $space = true === $separated ? ' ' : ''; @@ -343,28 +314,30 @@ class Amount */ public function getLocaleInfo(): array { - $locale = explode(',', (string)trans('config.locale')); + $locale = explode(',', (string) trans('config.locale')); $locale = array_map('trim', $locale); setlocale(LC_MONETARY, $locale); $info = localeconv(); // correct variables - $info['n_cs_precedes'] = (is_bool($info['n_cs_precedes']) && true === $info['n_cs_precedes']) - || (is_int($info['n_cs_precedes']) && 1 === $info['n_cs_precedes']); + $info['n_cs_precedes'] = $this->getLocaleField($info, 'n_cs_precedes'); + $info['p_cs_precedes'] = $this->getLocaleField($info, 'p_cs_precedes'); - $info['p_cs_precedes'] = (is_bool($info['p_cs_precedes']) && true === $info['p_cs_precedes']) - || (is_int($info['p_cs_precedes']) && 1 === $info['p_cs_precedes']); - - $info['n_sep_by_space'] = (is_bool($info['n_sep_by_space']) && true === $info['n_sep_by_space']) - || (is_int($info['n_sep_by_space']) && 1 === $info['n_sep_by_space']); - - $info['p_sep_by_space'] = (is_bool($info['p_sep_by_space']) && true === $info['p_sep_by_space']) - || (is_int($info['p_sep_by_space']) && 1 === $info['p_sep_by_space']); - - // n_sep_by_space - // 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'); return $info; + } + /** + * @param array $info + * @param string $field + * + * @return bool + */ + private function getLocaleField(array $info, string $field): bool + { + return (is_bool($info[$field]) && true === $info[$field]) + || (is_int($info[$field]) && 1 === $info[$field]); } /** diff --git a/app/Support/Binder/ImportProvider.php b/app/Support/Binder/ImportProvider.php index 59ead7a4d0..9682f4b04a 100644 --- a/app/Support/Binder/ImportProvider.php +++ b/app/Support/Binder/ImportProvider.php @@ -31,6 +31,8 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** * Class ImportProvider. + * + * @deprecated */ class ImportProvider implements BinderInterface { diff --git a/app/Support/Cronjobs/AbstractCronjob.php b/app/Support/Cronjobs/AbstractCronjob.php index d03280f154..5dd9c524c1 100644 --- a/app/Support/Cronjobs/AbstractCronjob.php +++ b/app/Support/Cronjobs/AbstractCronjob.php @@ -23,8 +23,11 @@ declare(strict_types=1); namespace FireflyIII\Support\Cronjobs; +use Carbon\Carbon; +use Exception; /** * Class AbstractCronjob + * * @codeCoverageIgnore */ abstract class AbstractCronjob @@ -32,6 +35,41 @@ abstract class AbstractCronjob /** @var int */ public $timeBetweenRuns = 43200; + /** @var bool */ + protected $force; + + /** @var Carbon */ + protected $date; + + /** + * AbstractCronjob constructor. + * + * @throws Exception + */ + public function __construct() + { + $this->force = false; + $this->date = new Carbon; + } + + + + /** + * @param bool $force + */ + public function setForce(bool $force): void + { + $this->force = $force; + } + + /** + * @param Carbon $date + */ + public function setDate(Carbon $date): void + { + $this->date = $date; + } + /** * @return bool */ diff --git a/app/Support/Cronjobs/AutoBudgetCronjob.php b/app/Support/Cronjobs/AutoBudgetCronjob.php new file mode 100644 index 0000000000..7dba31599c --- /dev/null +++ b/app/Support/Cronjobs/AutoBudgetCronjob.php @@ -0,0 +1,88 @@ +. + */ + +namespace FireflyIII\Support\Cronjobs; + + +use Carbon\Carbon; +use FireflyIII\Jobs\CreateAutoBudgetLimits; +use FireflyIII\Models\Configuration; +use Log; + +/** + * Class AutoBudgetCronjob + */ +class AutoBudgetCronjob extends AbstractCronjob +{ + + /** + * @inheritDoc + */ + public function fire(): bool + { + /** @var Configuration $config */ + $config = app('fireflyconfig')->get('last_ab_job', 0); + $lastTime = (int)$config->data; + $diff = time() - $lastTime; + $diffForHumans = Carbon::now()->diffForHumans(Carbon::createFromTimestamp($lastTime), true); + if (0 === $lastTime) { + Log::info('Auto budget cron-job has never fired before.'); + } + // less than half a day ago: + if ($lastTime > 0 && $diff <= 43200) { + Log::info(sprintf('It has been %s since the auto budget cron-job has fired.', $diffForHumans)); + if (false === $this->force) { + Log::info('The auto budget cron-job will not fire now.'); + + return false; + } + + // fire job regardless. + if (true === $this->force) { + Log::info('Execution of the auto budget cron-job has been FORCED.'); + } + } + + if ($lastTime > 0 && $diff > 43200) { + Log::info(sprintf('It has been %s since the auto budget cron-job has fired. It will fire now!', $diffForHumans)); + } + + $this->fireAutoBudget(); + + app('preferences')->mark(); + + return true; + } + + /** + * + */ + private function fireAutoBudget(): void + { + 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); + $job->setDate($this->date); + $job->handle(); + app('fireflyconfig')->set('last_ab_job', (int)$this->date->format('U')); + Log::info('Done with auto budget cron job task.'); + } +} \ No newline at end of file diff --git a/app/Support/Cronjobs/RecurringCronjob.php b/app/Support/Cronjobs/RecurringCronjob.php index 8c851d6a92..dfd7fd413b 100644 --- a/app/Support/Cronjobs/RecurringCronjob.php +++ b/app/Support/Cronjobs/RecurringCronjob.php @@ -34,38 +34,6 @@ use Log; */ class RecurringCronjob extends AbstractCronjob { - /** @var bool */ - private $force; - - /** @var Carbon */ - private $date; - - /** - * RecurringCronjob constructor. - * @throws \Exception - */ - public function __construct() - { - $this->force = false; - $this->date = new Carbon; - } - - /** - * @param bool $force - */ - public function setForce(bool $force): void - { - $this->force = $force; - } - - /** - * @param Carbon $date - */ - public function setDate(Carbon $date): void - { - $this->date = $date; - } - /** * @return bool * @throws FireflyException diff --git a/app/Support/FinTS/FinTS.php b/app/Support/FinTS/FinTS.php index 174032f488..91dfbe21ad 100644 --- a/app/Support/FinTS/FinTS.php +++ b/app/Support/FinTS/FinTS.php @@ -28,6 +28,7 @@ use Illuminate\Support\Facades\Crypt; /** * @codeCoverageIgnore + * @deprecated * Class FinTS */ class FinTS diff --git a/app/Support/FinTS/MetadataParser.php b/app/Support/FinTS/MetadataParser.php index ea1155519b..6a079202cd 100644 --- a/app/Support/FinTS/MetadataParser.php +++ b/app/Support/FinTS/MetadataParser.php @@ -25,7 +25,8 @@ namespace FireflyIII\Support\FinTS; use Fhp\Model\StatementOfAccount\Transaction as FinTSTransaction; /** - * + * @deprecated + * @codeCoverageIgnore * Class MetadataParser */ class MetadataParser diff --git a/app/Support/Import/Information/GetSpectreCustomerTrait.php b/app/Support/Import/Information/GetSpectreCustomerTrait.php index 08e356b5f3..c2f0cd9058 100644 --- a/app/Support/Import/Information/GetSpectreCustomerTrait.php +++ b/app/Support/Import/Information/GetSpectreCustomerTrait.php @@ -32,7 +32,9 @@ use Log; /** * Trait GetSpectreCustomerTrait + * * @codeCoverageIgnore + * @deprecated */ trait GetSpectreCustomerTrait { diff --git a/app/Support/Import/Information/GetSpectreTokenTrait.php b/app/Support/Import/Information/GetSpectreTokenTrait.php index 4cfafb8d7e..875c905c8e 100644 --- a/app/Support/Import/Information/GetSpectreTokenTrait.php +++ b/app/Support/Import/Information/GetSpectreTokenTrait.php @@ -31,7 +31,9 @@ use Log; /** * Trait GetSpectreTokenTrait + * * @codeCoverageIgnore + * @deprecated */ trait GetSpectreTokenTrait { diff --git a/app/Support/Import/JobConfiguration/Bunq/BunqJobConfigurationInterface.php b/app/Support/Import/JobConfiguration/Bunq/BunqJobConfigurationInterface.php index fe315a1250..d662694c86 100644 --- a/app/Support/Import/JobConfiguration/Bunq/BunqJobConfigurationInterface.php +++ b/app/Support/Import/JobConfiguration/Bunq/BunqJobConfigurationInterface.php @@ -28,6 +28,8 @@ use Illuminate\Support\MessageBag; /** * Interface BunqJobConfigurationInterface + * @deprecated + * @codeCoverageIgnore */ interface BunqJobConfigurationInterface { diff --git a/app/Support/Import/JobConfiguration/Bunq/ChooseAccountsHandler.php b/app/Support/Import/JobConfiguration/Bunq/ChooseAccountsHandler.php index fc0425cd6b..7cf82b10bb 100644 --- a/app/Support/Import/JobConfiguration/Bunq/ChooseAccountsHandler.php +++ b/app/Support/Import/JobConfiguration/Bunq/ChooseAccountsHandler.php @@ -36,6 +36,8 @@ use Log; /** * Class ChooseAccountsHandler + * @deprecated + * @codeCoverageIgnore */ class ChooseAccountsHandler implements BunqJobConfigurationInterface { diff --git a/app/Support/Import/JobConfiguration/Bunq/NewBunqJobHandler.php b/app/Support/Import/JobConfiguration/Bunq/NewBunqJobHandler.php index 43df0f4245..847da7284d 100644 --- a/app/Support/Import/JobConfiguration/Bunq/NewBunqJobHandler.php +++ b/app/Support/Import/JobConfiguration/Bunq/NewBunqJobHandler.php @@ -30,6 +30,8 @@ use Log; /** * Class NewBunqJobHandler + * @deprecated + * @codeCoverageIgnore */ class NewBunqJobHandler implements BunqJobConfigurationInterface { diff --git a/app/Support/Import/JobConfiguration/File/ConfigureMappingHandler.php b/app/Support/Import/JobConfiguration/File/ConfigureMappingHandler.php index 278bb24905..8be440542a 100644 --- a/app/Support/Import/JobConfiguration/File/ConfigureMappingHandler.php +++ b/app/Support/Import/JobConfiguration/File/ConfigureMappingHandler.php @@ -39,6 +39,8 @@ use Log; /** * Class ConfigureMappingHandler + * @deprecated + * @codeCoverageIgnore */ class ConfigureMappingHandler implements FileConfigurationInterface { diff --git a/app/Support/Import/JobConfiguration/File/ConfigureRolesHandler.php b/app/Support/Import/JobConfiguration/File/ConfigureRolesHandler.php index fbab577bc2..9c4bde5e66 100644 --- a/app/Support/Import/JobConfiguration/File/ConfigureRolesHandler.php +++ b/app/Support/Import/JobConfiguration/File/ConfigureRolesHandler.php @@ -38,6 +38,8 @@ use Log; /** * Class ConfigureRolesHandler + * @deprecated + * @codeCoverageIgnore */ class ConfigureRolesHandler implements FileConfigurationInterface { diff --git a/app/Support/Import/JobConfiguration/File/ConfigureUploadHandler.php b/app/Support/Import/JobConfiguration/File/ConfigureUploadHandler.php index f6cb0da8ab..8bd2a610b5 100644 --- a/app/Support/Import/JobConfiguration/File/ConfigureUploadHandler.php +++ b/app/Support/Import/JobConfiguration/File/ConfigureUploadHandler.php @@ -32,6 +32,8 @@ use Log; /** * Class ConfigureUploadHandler + * @deprecated + * @codeCoverageIgnore */ class ConfigureUploadHandler implements FileConfigurationInterface { diff --git a/app/Support/Import/JobConfiguration/File/FileConfigurationInterface.php b/app/Support/Import/JobConfiguration/File/FileConfigurationInterface.php index f516a8ef3a..ebde2cfc45 100644 --- a/app/Support/Import/JobConfiguration/File/FileConfigurationInterface.php +++ b/app/Support/Import/JobConfiguration/File/FileConfigurationInterface.php @@ -27,6 +27,8 @@ use Illuminate\Support\MessageBag; /** * Class FileConfigurationInterface. + * @deprecated + * @codeCoverageIgnore */ interface FileConfigurationInterface { diff --git a/app/Support/Import/JobConfiguration/File/NewFileJobHandler.php b/app/Support/Import/JobConfiguration/File/NewFileJobHandler.php index f60b2a558f..fe8080df74 100644 --- a/app/Support/Import/JobConfiguration/File/NewFileJobHandler.php +++ b/app/Support/Import/JobConfiguration/File/NewFileJobHandler.php @@ -36,6 +36,8 @@ use Log; /** * Class NewFileJobHandler + * @deprecated + * @codeCoverageIgnore */ class NewFileJobHandler implements FileConfigurationInterface { diff --git a/app/Support/Import/JobConfiguration/FinTS/ChooseAccountHandler.php b/app/Support/Import/JobConfiguration/FinTS/ChooseAccountHandler.php index 7356b0edac..7e75cfe0e8 100644 --- a/app/Support/Import/JobConfiguration/FinTS/ChooseAccountHandler.php +++ b/app/Support/Import/JobConfiguration/FinTS/ChooseAccountHandler.php @@ -35,7 +35,9 @@ use Illuminate\Support\MessageBag; /** * Class ChooseAccountHandler + * * @codeCoverageIgnore + * @deprecated */ class ChooseAccountHandler implements FinTSConfigurationInterface { diff --git a/app/Support/Import/JobConfiguration/FinTS/FinTSConfigurationInterface.php b/app/Support/Import/JobConfiguration/FinTS/FinTSConfigurationInterface.php index ce48e854ef..ef44396f69 100644 --- a/app/Support/Import/JobConfiguration/FinTS/FinTSConfigurationInterface.php +++ b/app/Support/Import/JobConfiguration/FinTS/FinTSConfigurationInterface.php @@ -26,7 +26,8 @@ use FireflyIII\Models\ImportJob; use Illuminate\Support\MessageBag; /** - * + * @deprecated + * @codeCoverageIgnore */ interface FinTSConfigurationInterface { diff --git a/app/Support/Import/JobConfiguration/FinTS/NewFinTSJobHandler.php b/app/Support/Import/JobConfiguration/FinTS/NewFinTSJobHandler.php index 91884c5fa6..67167a61fd 100644 --- a/app/Support/Import/JobConfiguration/FinTS/NewFinTSJobHandler.php +++ b/app/Support/Import/JobConfiguration/FinTS/NewFinTSJobHandler.php @@ -34,6 +34,7 @@ use Illuminate\Support\MessageBag; /** * Class NewFinTSJobHandler * @codeCoverageIgnore + * @deprecated */ class NewFinTSJobHandler implements FinTSConfigurationInterface { diff --git a/app/Support/Import/JobConfiguration/Spectre/AuthenticatedHandler.php b/app/Support/Import/JobConfiguration/Spectre/AuthenticatedHandler.php index 5b9267bb37..9fe4faf428 100644 --- a/app/Support/Import/JobConfiguration/Spectre/AuthenticatedHandler.php +++ b/app/Support/Import/JobConfiguration/Spectre/AuthenticatedHandler.php @@ -31,6 +31,7 @@ use Log; * @codeCoverageIgnore * * Class AuthenticatedHandler + * @deprecated */ class AuthenticatedHandler implements SpectreJobConfigurationInterface { diff --git a/app/Support/Import/JobConfiguration/Spectre/ChooseAccountsHandler.php b/app/Support/Import/JobConfiguration/Spectre/ChooseAccountsHandler.php index e736e468e9..25d57c1ec5 100644 --- a/app/Support/Import/JobConfiguration/Spectre/ChooseAccountsHandler.php +++ b/app/Support/Import/JobConfiguration/Spectre/ChooseAccountsHandler.php @@ -39,7 +39,8 @@ use Log; /** * Class ChooseAccountsHandler - * + * @deprecated + * @codeCoverageIgnore */ class ChooseAccountsHandler implements SpectreJobConfigurationInterface { diff --git a/app/Support/Import/JobConfiguration/Spectre/ChooseLoginHandler.php b/app/Support/Import/JobConfiguration/Spectre/ChooseLoginHandler.php index ba83a61e4e..e42fe7a0f7 100644 --- a/app/Support/Import/JobConfiguration/Spectre/ChooseLoginHandler.php +++ b/app/Support/Import/JobConfiguration/Spectre/ChooseLoginHandler.php @@ -35,7 +35,8 @@ use Log; /** * Class ChooseLoginHandler - * + * @deprecated + * @codeCoverageIgnore */ class ChooseLoginHandler implements SpectreJobConfigurationInterface { diff --git a/app/Support/Import/JobConfiguration/Spectre/DoAuthenticateHandler.php b/app/Support/Import/JobConfiguration/Spectre/DoAuthenticateHandler.php index afd5a945ea..ab0f441dd6 100644 --- a/app/Support/Import/JobConfiguration/Spectre/DoAuthenticateHandler.php +++ b/app/Support/Import/JobConfiguration/Spectre/DoAuthenticateHandler.php @@ -34,7 +34,8 @@ use Log; /** * Class AuthenticateConfig - * + * @deprecated + * @codeCoverageIgnore */ class DoAuthenticateHandler implements SpectreJobConfigurationInterface { diff --git a/app/Support/Import/JobConfiguration/Spectre/NewSpectreJobHandler.php b/app/Support/Import/JobConfiguration/Spectre/NewSpectreJobHandler.php index 13e5ec1ada..b90c8e8007 100644 --- a/app/Support/Import/JobConfiguration/Spectre/NewSpectreJobHandler.php +++ b/app/Support/Import/JobConfiguration/Spectre/NewSpectreJobHandler.php @@ -32,7 +32,7 @@ use Log; * @codeCoverageIgnore * * Class NewSpectreJobHandler - * + * @deprecated */ class NewSpectreJobHandler implements SpectreJobConfigurationInterface { diff --git a/app/Support/Import/JobConfiguration/Spectre/SpectreJobConfigurationInterface.php b/app/Support/Import/JobConfiguration/Spectre/SpectreJobConfigurationInterface.php index fcb02d0e1a..dc7846b0dd 100644 --- a/app/Support/Import/JobConfiguration/Spectre/SpectreJobConfigurationInterface.php +++ b/app/Support/Import/JobConfiguration/Spectre/SpectreJobConfigurationInterface.php @@ -29,7 +29,8 @@ use Illuminate\Support\MessageBag; /** * Interface SpectreJobConfigurationInterface - * + * @deprecated + * @codeCoverageIgnore */ interface SpectreJobConfigurationInterface { diff --git a/app/Support/Import/JobConfiguration/Ynab/NewYnabJobHandler.php b/app/Support/Import/JobConfiguration/Ynab/NewYnabJobHandler.php index ae069e7328..0b6cb4701a 100644 --- a/app/Support/Import/JobConfiguration/Ynab/NewYnabJobHandler.php +++ b/app/Support/Import/JobConfiguration/Ynab/NewYnabJobHandler.php @@ -34,6 +34,8 @@ use RuntimeException; /** * Class NewYnabJobHandler + * @deprecated + * @codeCoverageIgnore */ class NewYnabJobHandler implements YnabJobConfigurationInterface { diff --git a/app/Support/Import/JobConfiguration/Ynab/SelectAccountsHandler.php b/app/Support/Import/JobConfiguration/Ynab/SelectAccountsHandler.php index 04dd3c55e9..dcadd72390 100644 --- a/app/Support/Import/JobConfiguration/Ynab/SelectAccountsHandler.php +++ b/app/Support/Import/JobConfiguration/Ynab/SelectAccountsHandler.php @@ -37,6 +37,8 @@ use Log; /** * Class SelectAccountsHandler + * @deprecated + * @codeCoverageIgnore */ class SelectAccountsHandler implements YnabJobConfigurationInterface { diff --git a/app/Support/Import/JobConfiguration/Ynab/SelectBudgetHandler.php b/app/Support/Import/JobConfiguration/Ynab/SelectBudgetHandler.php index 3a7385f4ca..9a2790d270 100644 --- a/app/Support/Import/JobConfiguration/Ynab/SelectBudgetHandler.php +++ b/app/Support/Import/JobConfiguration/Ynab/SelectBudgetHandler.php @@ -35,6 +35,8 @@ use Log; /** * Class SelectBudgetHandler + * @deprecated + * @codeCoverageIgnore */ class SelectBudgetHandler implements YnabJobConfigurationInterface { diff --git a/app/Support/Import/JobConfiguration/Ynab/YnabJobConfigurationInterface.php b/app/Support/Import/JobConfiguration/Ynab/YnabJobConfigurationInterface.php index 1124799f06..1752b566e6 100644 --- a/app/Support/Import/JobConfiguration/Ynab/YnabJobConfigurationInterface.php +++ b/app/Support/Import/JobConfiguration/Ynab/YnabJobConfigurationInterface.php @@ -28,7 +28,8 @@ use Illuminate\Support\MessageBag; /** * Interface YnabJobConfigurationInterface - * + * @deprecated + * @codeCoverageIgnore */ interface YnabJobConfigurationInterface { diff --git a/app/Support/Import/Placeholder/ColumnValue.php b/app/Support/Import/Placeholder/ColumnValue.php index 79cff0e9b5..81fd343174 100644 --- a/app/Support/Import/Placeholder/ColumnValue.php +++ b/app/Support/Import/Placeholder/ColumnValue.php @@ -27,6 +27,7 @@ namespace FireflyIII\Support\Import\Placeholder; * Class ColumnValue * * @codeCoverageIgnore + * @deprecated */ class ColumnValue { diff --git a/app/Support/Import/Placeholder/ImportTransaction.php b/app/Support/Import/Placeholder/ImportTransaction.php index 9ad6e2b437..63155ff058 100644 --- a/app/Support/Import/Placeholder/ImportTransaction.php +++ b/app/Support/Import/Placeholder/ImportTransaction.php @@ -34,6 +34,7 @@ use Log; /** * Class ImportTransaction * @codeCoverageIgnore + * @deprecated */ class ImportTransaction { diff --git a/app/Support/Import/Routine/Bunq/PaymentConverter.php b/app/Support/Import/Routine/Bunq/PaymentConverter.php index c11daac812..b40363c7a3 100644 --- a/app/Support/Import/Routine/Bunq/PaymentConverter.php +++ b/app/Support/Import/Routine/Bunq/PaymentConverter.php @@ -38,6 +38,8 @@ use Log; /** * Class PaymentConverter + * @deprecated + * @codeCoverageIgnore */ class PaymentConverter { diff --git a/app/Support/Import/Routine/Bunq/StageImportDataHandler.php b/app/Support/Import/Routine/Bunq/StageImportDataHandler.php index 3e28ed1719..199d05b7dd 100644 --- a/app/Support/Import/Routine/Bunq/StageImportDataHandler.php +++ b/app/Support/Import/Routine/Bunq/StageImportDataHandler.php @@ -38,6 +38,8 @@ use Log; /** * Class StageImportDataHandler + * @deprecated + * @codeCoverageIgnore */ class StageImportDataHandler { diff --git a/app/Support/Import/Routine/Bunq/StageNewHandler.php b/app/Support/Import/Routine/Bunq/StageNewHandler.php index b7b35e453d..ab844508bc 100644 --- a/app/Support/Import/Routine/Bunq/StageNewHandler.php +++ b/app/Support/Import/Routine/Bunq/StageNewHandler.php @@ -41,6 +41,8 @@ use Log; /** * Class StageNewHandler + * @deprecated + * @codeCoverageIgnore */ class StageNewHandler { diff --git a/app/Support/Import/Routine/Fake/StageAhoyHandler.php b/app/Support/Import/Routine/Fake/StageAhoyHandler.php index fe8fa979c2..a0a81f392b 100644 --- a/app/Support/Import/Routine/Fake/StageAhoyHandler.php +++ b/app/Support/Import/Routine/Fake/StageAhoyHandler.php @@ -28,6 +28,7 @@ use Log; /** * @codeCoverageIgnore * Class StageAhoyHandler + * @deprecated */ class StageAhoyHandler { diff --git a/app/Support/Import/Routine/Fake/StageFinalHandler.php b/app/Support/Import/Routine/Fake/StageFinalHandler.php index 8beaf52836..f3bea38970 100644 --- a/app/Support/Import/Routine/Fake/StageFinalHandler.php +++ b/app/Support/Import/Routine/Fake/StageFinalHandler.php @@ -30,7 +30,7 @@ use FireflyIII\Models\ImportJob; /** * @codeCoverageIgnore * Class StageFinalHandler - * + * @deprecated */ class StageFinalHandler { diff --git a/app/Support/Import/Routine/Fake/StageNewHandler.php b/app/Support/Import/Routine/Fake/StageNewHandler.php index 0f54e32148..bf274d8f6e 100644 --- a/app/Support/Import/Routine/Fake/StageNewHandler.php +++ b/app/Support/Import/Routine/Fake/StageNewHandler.php @@ -28,6 +28,7 @@ use Log; /** * @codeCoverageIgnore * Class StageNewHandler + * @deprecated */ class StageNewHandler { diff --git a/app/Support/Import/Routine/File/AssetAccountMapper.php b/app/Support/Import/Routine/File/AssetAccountMapper.php index 637accd2c0..b7c4398ae6 100644 --- a/app/Support/Import/Routine/File/AssetAccountMapper.php +++ b/app/Support/Import/Routine/File/AssetAccountMapper.php @@ -32,6 +32,7 @@ use Log; /** * Class AssetAccountMapper * Can also handle liability accounts. + * @deprecated */ class AssetAccountMapper { diff --git a/app/Support/Import/Routine/File/CSVProcessor.php b/app/Support/Import/Routine/File/CSVProcessor.php index 4b69568139..225d16d0d6 100644 --- a/app/Support/Import/Routine/File/CSVProcessor.php +++ b/app/Support/Import/Routine/File/CSVProcessor.php @@ -30,7 +30,8 @@ use Log; /** * Class CSVProcessor - * + * @deprecated + * @codeCoverageIgnore */ class CSVProcessor implements FileProcessorInterface { diff --git a/app/Support/Import/Routine/File/CurrencyMapper.php b/app/Support/Import/Routine/File/CurrencyMapper.php index 08905feef9..89d8aebe90 100644 --- a/app/Support/Import/Routine/File/CurrencyMapper.php +++ b/app/Support/Import/Routine/File/CurrencyMapper.php @@ -30,6 +30,8 @@ use Log; /** * Class CurrencyMapper + * @deprecated + * @codeCoverageIgnore */ class CurrencyMapper { diff --git a/app/Support/Import/Routine/File/FileProcessorInterface.php b/app/Support/Import/Routine/File/FileProcessorInterface.php index f0404feb1c..5835f5ec9a 100644 --- a/app/Support/Import/Routine/File/FileProcessorInterface.php +++ b/app/Support/Import/Routine/File/FileProcessorInterface.php @@ -28,7 +28,8 @@ use FireflyIII\Models\ImportJob; /** * Interface FileProcessorInterface - * + * @deprecated + * @codeCoverageIgnore */ interface FileProcessorInterface { diff --git a/app/Support/Import/Routine/File/ImportableConverter.php b/app/Support/Import/Routine/File/ImportableConverter.php index aae7b45d9b..b512a66122 100644 --- a/app/Support/Import/Routine/File/ImportableConverter.php +++ b/app/Support/Import/Routine/File/ImportableConverter.php @@ -38,6 +38,8 @@ use Log; /** * Class ImportableConverter + * @deprecated + * @codeCoverageIgnore */ class ImportableConverter { diff --git a/app/Support/Import/Routine/File/ImportableCreator.php b/app/Support/Import/Routine/File/ImportableCreator.php index 9730c2eb95..e86230a6c4 100644 --- a/app/Support/Import/Routine/File/ImportableCreator.php +++ b/app/Support/Import/Routine/File/ImportableCreator.php @@ -30,6 +30,7 @@ use FireflyIII\Support\Import\Placeholder\ImportTransaction; * Takes an array of arrays of ColumnValue objects and returns one (1) ImportTransaction * for each line. * + * @deprecated * @codeCoverageIgnore * * Class ImportableCreator diff --git a/app/Support/Import/Routine/File/LineReader.php b/app/Support/Import/Routine/File/LineReader.php index 857510da2a..b859dfcacb 100644 --- a/app/Support/Import/Routine/File/LineReader.php +++ b/app/Support/Import/Routine/File/LineReader.php @@ -36,6 +36,8 @@ use Log; /** * Class LineReader + * @deprecated + * @codeCoverageIgnore */ class LineReader { diff --git a/app/Support/Import/Routine/File/MappedValuesValidator.php b/app/Support/Import/Routine/File/MappedValuesValidator.php index bf8f9162a0..a3a23dc12d 100644 --- a/app/Support/Import/Routine/File/MappedValuesValidator.php +++ b/app/Support/Import/Routine/File/MappedValuesValidator.php @@ -35,6 +35,8 @@ use Log; /** * Class MappedValuesValidator + * @deprecated + * @codeCoverageIgnore */ class MappedValuesValidator { diff --git a/app/Support/Import/Routine/File/MappingConverger.php b/app/Support/Import/Routine/File/MappingConverger.php index b08341caff..3a127ed8e2 100644 --- a/app/Support/Import/Routine/File/MappingConverger.php +++ b/app/Support/Import/Routine/File/MappingConverger.php @@ -31,6 +31,8 @@ use Log; /** * Class MappingConverger + * @deprecated + * @codeCoverageIgnore */ class MappingConverger { diff --git a/app/Support/Import/Routine/File/OFXProcessor.php b/app/Support/Import/Routine/File/OFXProcessor.php index cb709025f2..0cb893f26a 100644 --- a/app/Support/Import/Routine/File/OFXProcessor.php +++ b/app/Support/Import/Routine/File/OFXProcessor.php @@ -35,6 +35,8 @@ use OfxParser\Entities\Transaction; /** * * Class OFXProcessor + * @deprecated + * @codeCoverageIgnore */ class OFXProcessor implements FileProcessorInterface { diff --git a/app/Support/Import/Routine/File/OpposingAccountMapper.php b/app/Support/Import/Routine/File/OpposingAccountMapper.php index 4219e56821..342a121e9e 100644 --- a/app/Support/Import/Routine/File/OpposingAccountMapper.php +++ b/app/Support/Import/Routine/File/OpposingAccountMapper.php @@ -31,6 +31,8 @@ use Log; /** * Class OpposingAccountMapper + * @deprecated + * @codeCoverageIgnore */ class OpposingAccountMapper { diff --git a/app/Support/Import/Routine/FinTS/StageImportDataHandler.php b/app/Support/Import/Routine/FinTS/StageImportDataHandler.php index 26997261fa..e2a0bf416d 100644 --- a/app/Support/Import/Routine/FinTS/StageImportDataHandler.php +++ b/app/Support/Import/Routine/FinTS/StageImportDataHandler.php @@ -41,6 +41,8 @@ use Illuminate\Support\Facades\Log; /** * * Class StageImportDataHandler + * @deprecated + * @codeCoverageIgnore */ class StageImportDataHandler { diff --git a/app/Support/Import/Routine/Spectre/StageAuthenticatedHandler.php b/app/Support/Import/Routine/Spectre/StageAuthenticatedHandler.php index 68e7459735..d3dd29973d 100644 --- a/app/Support/Import/Routine/Spectre/StageAuthenticatedHandler.php +++ b/app/Support/Import/Routine/Spectre/StageAuthenticatedHandler.php @@ -35,6 +35,8 @@ use Log; /** * Class StageAuthenticatedHandler + * @deprecated + * @codeCoverageIgnore */ class StageAuthenticatedHandler { diff --git a/app/Support/Import/Routine/Spectre/StageImportDataHandler.php b/app/Support/Import/Routine/Spectre/StageImportDataHandler.php index e8706d07ca..4ee001ca45 100644 --- a/app/Support/Import/Routine/Spectre/StageImportDataHandler.php +++ b/app/Support/Import/Routine/Spectre/StageImportDataHandler.php @@ -38,6 +38,8 @@ use Log; /** * Class StageImportDataHandler + * @deprecated + * @codeCoverageIgnore * */ class StageImportDataHandler diff --git a/app/Support/Import/Routine/Spectre/StageNewHandler.php b/app/Support/Import/Routine/Spectre/StageNewHandler.php index e675360d8f..74360cc154 100644 --- a/app/Support/Import/Routine/Spectre/StageNewHandler.php +++ b/app/Support/Import/Routine/Spectre/StageNewHandler.php @@ -33,6 +33,8 @@ use Log; /** * Class StageNewHandler + * @deprecated + * @codeCoverageIgnore * */ class StageNewHandler diff --git a/app/Support/Import/Routine/Ynab/GetAccountsHandler.php b/app/Support/Import/Routine/Ynab/GetAccountsHandler.php index 009a974e23..b51aca4ed7 100644 --- a/app/Support/Import/Routine/Ynab/GetAccountsHandler.php +++ b/app/Support/Import/Routine/Ynab/GetAccountsHandler.php @@ -30,6 +30,8 @@ use FireflyIII\Services\Ynab\Request\GetAccountsRequest; /** * Class GetAccountsHandler + * @deprecated + * @codeCoverageIgnore */ class GetAccountsHandler { diff --git a/app/Support/Import/Routine/Ynab/ImportDataHandler.php b/app/Support/Import/Routine/Ynab/ImportDataHandler.php index 95b11075f9..1e8d69b534 100644 --- a/app/Support/Import/Routine/Ynab/ImportDataHandler.php +++ b/app/Support/Import/Routine/Ynab/ImportDataHandler.php @@ -38,6 +38,8 @@ use Log; /** * Class ImportDataHandler + * @deprecated + * @codeCoverageIgnore */ class ImportDataHandler { diff --git a/app/Support/Import/Routine/Ynab/StageGetAccessHandler.php b/app/Support/Import/Routine/Ynab/StageGetAccessHandler.php index 8145ad3b18..c775a00487 100644 --- a/app/Support/Import/Routine/Ynab/StageGetAccessHandler.php +++ b/app/Support/Import/Routine/Ynab/StageGetAccessHandler.php @@ -34,6 +34,8 @@ use RuntimeException; /** * Class StageGetAccessHandler + * @deprecated + * @codeCoverageIgnore */ class StageGetAccessHandler { diff --git a/app/Support/Import/Routine/Ynab/StageGetBudgetsHandler.php b/app/Support/Import/Routine/Ynab/StageGetBudgetsHandler.php index e25aaa57bc..a0e0923966 100644 --- a/app/Support/Import/Routine/Ynab/StageGetBudgetsHandler.php +++ b/app/Support/Import/Routine/Ynab/StageGetBudgetsHandler.php @@ -31,6 +31,8 @@ use Log; /** * Class StageGetBudgetsHandler + * @deprecated + * @codeCoverageIgnore */ class StageGetBudgetsHandler { diff --git a/app/Support/Import/Routine/Ynab/StageGetTransactionsHandler.php b/app/Support/Import/Routine/Ynab/StageGetTransactionsHandler.php index 5d4ec9f781..be8cdd7ff1 100644 --- a/app/Support/Import/Routine/Ynab/StageGetTransactionsHandler.php +++ b/app/Support/Import/Routine/Ynab/StageGetTransactionsHandler.php @@ -28,6 +28,8 @@ use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; /** * Class StageGetTransactionsHandler + * @deprecated + * @codeCoverageIgnore */ class StageGetTransactionsHandler { diff --git a/app/Support/Import/Routine/Ynab/StageMatchAccountsHandler.php b/app/Support/Import/Routine/Ynab/StageMatchAccountsHandler.php index 9ab7a6361e..948b64a5bb 100644 --- a/app/Support/Import/Routine/Ynab/StageMatchAccountsHandler.php +++ b/app/Support/Import/Routine/Ynab/StageMatchAccountsHandler.php @@ -28,6 +28,8 @@ use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface; /** * Class StageMatchAccountsHandler + * @deprecated + * @codeCoverageIgnore */ class StageMatchAccountsHandler { diff --git a/app/Support/Navigation.php b/app/Support/Navigation.php index df0dbe1c50..581e3a4663 100644 --- a/app/Support/Navigation.php +++ b/app/Support/Navigation.php @@ -183,6 +183,7 @@ class Navigation 'quarterly' => 'addMonths', '6M' => 'addMonths', 'half-year' => 'addMonths', + 'half_year' => 'addMonths', 'year' => 'addYear', 'yearly' => 'addYear', '1Y' => 'addYear', @@ -192,10 +193,11 @@ class Navigation '3M' => 3, 'quarterly' => 3, 'half-year' => 6, + 'half_year' => 6, '6M' => 6, ]; - $subDay = ['week', 'weekly', '1W', 'month', 'monthly', '1M', '3M', 'quarter', 'quarterly', '6M', 'half-year', '1Y', 'year', 'yearly']; + $subDay = ['week', 'weekly', '1W', 'month', 'monthly', '1M', '3M', 'quarter', 'quarterly', '6M', 'half-year', 'half_year', '1Y', 'year', 'yearly']; // if the range is custom, the end of the period // is another X days (x is the difference between start) diff --git a/app/Support/Steam.php b/app/Support/Steam.php index 4e6829fffc..da70a85388 100644 --- a/app/Support/Steam.php +++ b/app/Support/Steam.php @@ -59,22 +59,24 @@ class Steam } /** @var AccountRepositoryInterface $repository */ $repository = app(AccountRepositoryInterface::class); - $currency = $repository->getAccountCurrency($account) ?? app('amount')->getDefaultCurrencyByUser($account->user); + $currency = $repository->getAccountCurrency($account) ?? app('amount')->getDefaultCurrencyByUser($account->user); // first part: get all balances in own currency: - $nativeBalance = (string)$account->transactions() - ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') - ->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59')) - ->where('transactions.transaction_currency_id', $currency->id) - ->sum('transactions.amount'); + $transactions = $account->transactions() + ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') + ->where('transaction_journals.date', '<=', $date->format('Y-m-d 23:59:59')) + ->where('transactions.transaction_currency_id', $currency->id) + ->get(['transactions.amount'])->toArray(); + $nativeBalance = $this->sumTransactions($transactions, 'amount'); // get all balances in foreign currency: - $foreignBalance = (string)$account->transactions() - ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') - ->where('transaction_journals.date', '<=', $date->format('Y-m-d')) - ->where('transactions.foreign_currency_id', $currency->id) - ->where('transactions.transaction_currency_id', '!=', $currency->id) - ->sum('transactions.foreign_amount'); + $transactions = $account->transactions() + ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') + ->where('transaction_journals.date', '<=', $date->format('Y-m-d')) + ->where('transactions.foreign_currency_id', $currency->id) + ->where('transactions.transaction_currency_id', '!=', $currency->id) + ->get(['transactions.foreign_amount'])->toArray(); + $foreignBalance = $this->sumTransactions($transactions, 'foreign_amount'); // check: Log::debug(sprintf('Steam::balance. Native balance is "%s"', $nativeBalance)); @@ -86,6 +88,7 @@ class Steam Log::debug(sprintf('Steam::balance. Virtual balance is "%s"', $virtual)); $balance = bcadd($balance, $virtual); + $cache->store($balance); return $balance; @@ -114,20 +117,25 @@ class Steam $repository = app(AccountRepositoryInterface::class); $repository->setUser($account->user); - $currencyId = (int)$repository->getMetaValue($account, 'currency_id'); - $nativeBalance = (string)$account->transactions() - ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') - ->where('transaction_journals.date', '<=', $date->format('Y-m-d')) - ->where('transactions.transaction_currency_id', $currencyId) - ->sum('transactions.amount'); + $currencyId = (int)$repository->getMetaValue($account, 'currency_id'); + + + $transactions = $account->transactions() + ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') + ->where('transaction_journals.date', '<=', $date->format('Y-m-d')) + ->where('transactions.transaction_currency_id', $currencyId) + ->get(['transactions.amount'])->toArray(); + $nativeBalance = $this->sumTransactions($transactions, 'amount'); // get all balances in foreign currency: - $foreignBalance = (string)$account->transactions() - ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') - ->where('transaction_journals.date', '<=', $date->format('Y-m-d')) - ->where('transactions.foreign_currency_id', $currencyId) - ->where('transactions.transaction_currency_id', '!=', $currencyId) - ->sum('transactions.foreign_amount'); + $transactions = $account->transactions() + ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') + ->where('transaction_journals.date', '<=', $date->format('Y-m-d')) + ->where('transactions.foreign_currency_id', $currencyId) + ->where('transactions.transaction_currency_id', '!=', $currencyId) + ->get(['transactions.foreign_amount'])->toArray(); + + $foreignBalance = $this->sumTransactions($transactions, 'foreign_amount'); $balance = bcadd($nativeBalance, $foreignBalance); $cache->store($balance); @@ -135,6 +143,23 @@ class Steam return $balance; } + /** + * @param array $transactions + * @param string $key + * + * @return string + */ + public function sumTransactions(array $transactions, string $key): string + { + $sum = '0'; + /** @var array $transaction */ + foreach ($transactions as $transaction) { + $sum = bcadd($sum, $transaction[$key] ?? '0'); + } + + return $sum; + } + /** * Gets the balance for the given account during the whole range, using this format:. * diff --git a/app/Transformers/BudgetTransformer.php b/app/Transformers/BudgetTransformer.php index 2f4e8eedda..f87630b84a 100644 --- a/app/Transformers/BudgetTransformer.php +++ b/app/Transformers/BudgetTransformer.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Transformers; +use FireflyIII\Models\AutoBudget; use FireflyIII\Models\Budget; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Repositories\Budget\OperationsRepositoryInterface; @@ -37,6 +38,8 @@ class BudgetTransformer extends AbstractTransformer { /** @var OperationsRepositoryInterface */ private $opsRepository; + /** @var BudgetRepositoryInterface */ + private $repository; /** * BudgetTransformer constructor. @@ -46,6 +49,7 @@ class BudgetTransformer extends AbstractTransformer public function __construct() { $this->opsRepository = app(OperationsRepositoryInterface::class); + $this->repository = app(BudgetRepositoryInterface::class); if ('testing' === config('app.env')) { Log::warning(sprintf('%s should not be instantiated in the TEST environment!', get_class($this))); } @@ -61,21 +65,46 @@ class BudgetTransformer extends AbstractTransformer public function transform(Budget $budget): array { $this->opsRepository->setUser($budget->user); - $start = $this->parameters->get('start'); - $end = $this->parameters->get('end'); - $spent = []; + $start = $this->parameters->get('start'); + $end = $this->parameters->get('end'); + $autoBudget = $this->repository->getAutoBudget($budget); + $spent = []; if (null !== $start && null !== $end) { $spent = array_values($this->opsRepository->sumExpenses($start, $end, null, new Collection([$budget]))); } + $abCurrencyId = null; + $abCurrencyCode = null; + $abType = null; + $abAmount = null; + $abPeriod = null; + + $types = [ + AutoBudget::AUTO_BUDGET_RESET => 'reset', + AutoBudget::AUTO_BUDGET_ROLLOVER => 'rollover', + ]; + + if (null !== $autoBudget) { + $abCurrencyId = $autoBudget->transactionCurrency->id; + $abCurrencyCode = $autoBudget->transactionCurrency->code; + $abType = $types[$autoBudget->auto_budget_type]; + $abAmount = $autoBudget->amount; + $abPeriod = $autoBudget->period; + } + $data = [ - 'id' => (int)$budget->id, - 'created_at' => $budget->created_at->toAtomString(), - 'updated_at' => $budget->updated_at->toAtomString(), - 'active' => $budget->active, - 'name' => $budget->name, - 'spent' => $spent, - 'links' => [ + 'id' => (int)$budget->id, + 'created_at' => $budget->created_at->toAtomString(), + 'updated_at' => $budget->updated_at->toAtomString(), + 'active' => $budget->active, + 'name' => $budget->name, + 'auto_budget_type' => $abType, + 'auto_budget_period' => $abPeriod, + 'auto_budget_currency_id' => $abCurrencyId, + 'auto_budget_currency_code' => $abCurrencyCode, + 'auto_budget_amount' => $abAmount, + 'spent' => $spent, + 'links' => [ [ 'rel' => 'self', 'uri' => '/budgets/' . $budget->id, diff --git a/app/Transformers/ImportJobTransformer.php b/app/Transformers/ImportJobTransformer.php index ef2259a2a1..b705e766d4 100644 --- a/app/Transformers/ImportJobTransformer.php +++ b/app/Transformers/ImportJobTransformer.php @@ -29,6 +29,7 @@ use Log; /** * Class ImportJobTransformer + * @deprecated */ class ImportJobTransformer extends AbstractTransformer { diff --git a/app/Transformers/TransactionGroupTransformer.php b/app/Transformers/TransactionGroupTransformer.php index 4731f56e31..336c30aafc 100644 --- a/app/Transformers/TransactionGroupTransformer.php +++ b/app/Transformers/TransactionGroupTransformer.php @@ -24,9 +24,11 @@ declare(strict_types=1); namespace FireflyIII\Transformers; use FireflyIII\Exceptions\FireflyException; +use FireflyIII\Models\Bill; use FireflyIII\Models\Budget; use FireflyIII\Models\Category; use FireflyIII\Models\Transaction; +use FireflyIII\Models\TransactionCurrency; use FireflyIII\Models\TransactionGroup; use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionType; @@ -119,16 +121,119 @@ class TransactionGroupTransformer extends AbstractTransformer ], ], ]; - } catch(FireflyException $e) { + } catch (FireflyException $e) { Log::error($e->getMessage()); Log::error($e->getTraceAsString()); throw new FireflyException(sprintf('Transaction group #%d is broken. Please check out your log files.', $group->id)); } + // do something else. return $result; } + /** + * @param string $type + * @param string $amount + * + * @return string + */ + private function getAmount(string $type, string $amount): string + { + $amount = app('steam')->positive($amount); + if (TransactionType::WITHDRAWAL !== $type) { + $amount = app('steam')->negative($amount); + } + + return $amount; + } + + /** + * @param Bill|null $bill + * + * @return array + */ + private function getBill(?Bill $bill): array + { + $array = [ + 'id' => null, + 'name' => null, + ]; + if (null === $bill) { + return $array; + } + $array['id'] = $bill->id; + $array['name'] = $bill->name; + + return $array; + } + + /** + * @param Budget|null $budget + * + * @return array + */ + private function getBudget(?Budget $budget): array + { + $array = [ + 'id' => null, + 'name' => null, + ]; + if (null === $budget) { + return $array; + } + $array['id'] = $budget->id; + $array['name'] = $budget->name; + + return $array; + } + + /** + * @param Category|null $category + * + * @return array + */ + private function getCategory(?Category $category): array + { + $array = [ + 'id' => null, + 'name' => null, + ]; + if (null === $category) { + return $array; + } + $array['id'] = $category->id; + $array['name'] = $category->name; + + return $array; + } + + /** + * @param NullArrayObject $dates + * + * @return array + */ + private function getDates(NullArrayObject $dates): array + { + $fields = [ + 'interest_date', + 'book_date', + 'process_date', + 'due_date', + 'payment_date', + 'invoice_date', + ]; + $return = []; + foreach ($fields as $field) { + $return[$field] = null; + if (null !== $dates[$field]) { + $return[$field] = $dates[$field]->toAtomString(); + } + } + + return $return; + } + /** * @param TransactionJournal $journal * @@ -149,6 +254,46 @@ class TransactionGroupTransformer extends AbstractTransformer return $result; } + /** + * @param string $type + * @param string|null $foreignAmount + * + * @return string|null + */ + private function getForeignAmount(string $type, ?string $foreignAmount): ?string + { + $result = null; + if (null !== $foreignAmount) { + $result = TransactionType::WITHDRAWAL !== $type ? app('steam')->negative($foreignAmount) : app('steam')->positive($foreignAmount); + } + + return $result; + } + + /** + * @param TransactionCurrency|null $currency + * + * @return array + */ + private function getForeignCurrency(?TransactionCurrency $currency): array + { + $array = [ + 'id' => null, + 'code' => null, + 'symbol' => null, + 'decimal_places' => null, + ]; + if (null === $currency) { + return $array; + } + $array['id'] = $currency->id; + $array['code'] = $currency->code; + $array['symbol'] = $currency->symbol; + $array['decimal_places'] = $currency->decimal_places; + + return $array; + } + /** * @param TransactionJournal $journal * @@ -169,6 +314,97 @@ class TransactionGroupTransformer extends AbstractTransformer return $result; } + /** + * @param TransactionJournal $journal + * + * @return array + * @throws FireflyException + */ + private function transformJournal(TransactionJournal $journal): array + { + $source = $this->getSourceTransaction($journal); + $destination = $this->getDestinationTransaction($journal); + $type = $journal->transactionType->type; + $amount = $this->getAmount($type, $source->amount); + $foreignAmount = $this->getForeignAmount($type, $source->foreign_amount); + $metaFieldData = $this->groupRepos->getMetaFields($journal->id, $this->metaFields); + $metaDates = $this->getDates($this->groupRepos->getMetaDateFields($journal->id, $this->metaDateFields)); + $currency = $source->transactionCurrency; + $foreignCurrency = $this->getForeignCurrency($source->foreignCurrency); + $budget = $this->getBudget($journal->budgets->first()); + $category = $this->getCategory($journal->categories->first()); + $bill = $this->getBill($journal->bill); + + return [ + 'user' => (int)$journal->user_id, + 'transaction_journal_id' => $journal->id, + 'type' => strtolower($type), + 'date' => $journal->date->toAtomString(), + 'order' => $journal->order, + + 'currency_id' => $currency->id, + 'currency_code' => $currency->code, + 'currency_symbol' => $currency->symbol, + 'currency_decimal_places' => $currency->decimal_places, + + 'foreign_currency_id' => $foreignCurrency['id'], + 'foreign_currency_code' => $foreignCurrency['code'], + 'foreign_currency_symbol' => $foreignCurrency['symbol'], + 'foreign_currency_decimal_places' => $foreignCurrency['decimal_places'], + + 'amount' => $amount, + 'foreign_amount' => $foreignAmount, + + 'description' => $journal->description, + + 'source_id' => $source->account_id, + 'source_name' => $source->account->name, + 'source_iban' => $source->account->iban, + 'source_type' => $source->account->accountType->type, + + 'destination_id' => $destination->account_id, + 'destination_name' => $destination->account->name, + 'destination_iban' => $destination->account->iban, + 'destination_type' => $destination->account->accountType->type, + + 'budget_id' => $budget['id'], + 'budget_name' => $budget['name'], + + 'category_id' => $category['id'], + 'category_name' => $category['name'], + + 'bill_id' => $bill['id'], + 'bill_name' => $bill['name'], + + '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'], + + 'sepa_cc' => $metaFieldData['sepa_cc'], + 'sepa_ct_op' => $metaFieldData['sepa_ct_op'], + 'sepa_ct_id' => $metaFieldData['sepa_ct_id'], + 'sepa_db' => $metaFieldData['sepa_ddb'], + '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'], + ]; + } + /** * @param Collection $transactionJournals * @@ -180,101 +416,7 @@ class TransactionGroupTransformer extends AbstractTransformer $result = []; /** @var TransactionJournal $journal */ foreach ($transactionJournals as $journal) { - $source = $this->getSourceTransaction($journal); - $destination = $this->getDestinationTransaction($journal); - $type = $journal->transactionType->type; - - // get amount - $amount = app('steam')->positive($source->amount); - if (TransactionType::WITHDRAWAL !== $type) { - $amount = app('steam')->negative($source->amount); - } - - // get foreign amount: - $foreignAmount = null; - // @codeCoverageIgnoreStart - if (null !== $source->foreign_amount) { - $foreignAmount = TransactionType::WITHDRAWAL !== $type - ? app('steam')->negative($source->foreign_amount) - : app('steam')->positive($source->foreign_amount); - } - // @codeCoverageIgnoreEnd - - $metaFieldData = $this->groupRepos->getMetaFields($journal->id, $this->metaFields); - $metaDateData = $this->groupRepos->getMetaDateFields($journal->id, $this->metaDateFields); - /** @var Budget $budget */ - $budget = $journal->budgets->first(); - /** @var Category $category */ - $category = $journal->categories->first(); - $currency = $source->transactionCurrency; - $result[] = [ - 'user' => (int)$journal->user_id, - 'transaction_journal_id' => $journal->id, - 'type' => strtolower($type), - 'date' => $journal->date->toAtomString(), - 'order' => $journal->order, - - 'currency_id' => $currency->id, - 'currency_code' => $currency->code, - 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => $currency->decimal_places, - - 'foreign_currency_id' => $source->foreignCurrency ? $source->foreignCurrency->id : null, - 'foreign_currency_code' => $source->foreignCurrency ? $source->foreignCurrency->code : null, - 'foreign_currency_symbol' => $source->foreignCurrency ? $source->foreignCurrency->symbol : null, - 'foreign_currency_decimal_places' => $source->foreignCurrency ? $source->foreignCurrency->decimal_places : null, - - 'amount' => $amount, - 'foreign_amount' => $foreignAmount, - - 'description' => $journal->description, - - 'source_id' => $source->account_id, - 'source_name' => $source->account->name, - 'source_iban' => $source->account->iban, - 'source_type' => $source->account->accountType->type, - - 'destination_id' => $destination->account_id, - 'destination_name' => $destination->account->name, - 'destination_iban' => $destination->account->iban, - 'destination_type' => $destination->account->accountType->type, - - 'budget_id' => $budget ? $budget->id : null, - 'budget_name' => $budget ? $budget->name : null, - - 'category_id' => $category ? $category->id : null, - 'category_name' => $category ? $category->name : null, - - 'bill_id' => $journal->bill_id ?: null, - 'bill_name' => $journal->bill ? $journal->bill->name : null, - - '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'], - - 'sepa_cc' => $metaFieldData['sepa_cc'], - 'sepa_ct_op' => $metaFieldData['sepa_ct_op'], - 'sepa_ct_id' => $metaFieldData['sepa_ct_id'], - 'sepa_db' => $metaFieldData['sepa_ddb'], - 'sepa_country' => $metaFieldData['sepa_country'], - 'sepa_ep' => $metaFieldData['sepa_ep'], - 'sepa_ci' => $metaFieldData['sepa_ci'], - 'sepa_batch_id' => $metaFieldData['sepa_batch_id'], - - 'interest_date' => $metaDateData['interest_date'] ? $metaDateData['interest_date']->toAtomString() : null, - 'book_date' => $metaDateData['book_date'] ? $metaDateData['book_date']->toAtomString() : null, - 'process_date' => $metaDateData['process_date'] ? $metaDateData['process_date']->toAtomString() : null, - 'due_date' => $metaDateData['due_date'] ? $metaDateData['due_date']->toAtomString() : null, - 'payment_date' => $metaDateData['payment_date'] ? $metaDateData['payment_date']->toAtomString() : null, - 'invoice_date' => $metaDateData['invoice_date'] ? $metaDateData['invoice_date']->toAtomString() : null, - ]; + $result[] = $this->transformJournal($journal); } return $result; diff --git a/app/Validation/TransactionValidation.php b/app/Validation/TransactionValidation.php index 93f5aefb0d..0a472c7b67 100644 --- a/app/Validation/TransactionValidation.php +++ b/app/Validation/TransactionValidation.php @@ -48,37 +48,52 @@ trait TransactionValidation $transactionType = $data['type'] ?? 'invalid'; + Log::debug(sprintf('Going to loop %d transaction(s)', count($transactions))); + /** + * @var int $index + * @var array $transaction + */ + foreach ($transactions as $index => $transaction) { + $this->validateSingleAccount($validator, $index, $transactionType, $transaction); + } + } + + /** + * @param Validator $validator + * @param int $index + * @param string $transactionType + * @param array $transaction + */ + protected function validateSingleAccount(Validator $validator, int $index, string $transactionType, array $transaction): void + { /** @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; - $accountValidator->setTransactionType($transactionType); + $transactionType = $transaction['type'] ?? $transactionType; + $accountValidator->setTransactionType($transactionType); - // validate source account. - $sourceId = isset($transaction['source_id']) ? (int)$transaction['source_id'] : null; - $sourceName = $transaction['source_name'] ?? null; - $validSource = $accountValidator->validateSource($sourceId, $sourceName); + // validate source account. + $sourceId = isset($transaction['source_id']) ? (int)$transaction['source_id'] : null; + $sourceName = $transaction['source_name'] ?? null; + $validSource = $accountValidator->validateSource($sourceId, $sourceName); - // do something with result: - if (false === $validSource) { - $validator->errors()->add(sprintf('transactions.%d.source_id', $index), $accountValidator->sourceError); - $validator->errors()->add(sprintf('transactions.%d.source_name', $index), $accountValidator->sourceError); + // do something with result: + if (false === $validSource) { + $validator->errors()->add(sprintf('transactions.%d.source_id', $index), $accountValidator->sourceError); + $validator->errors()->add(sprintf('transactions.%d.source_name', $index), $accountValidator->sourceError); - return; - } - // validate destination account - $destinationId = isset($transaction['destination_id']) ? (int)$transaction['destination_id'] : null; - $destinationName = $transaction['destination_name'] ?? null; - $validDestination = $accountValidator->validateDestination($destinationId, $destinationName); - // do something with result: - if (false === $validDestination) { - $validator->errors()->add(sprintf('transactions.%d.destination_id', $index), $accountValidator->destError); - $validator->errors()->add(sprintf('transactions.%d.destination_name', $index), $accountValidator->destError); + return; + } + // validate destination account + $destinationId = isset($transaction['destination_id']) ? (int)$transaction['destination_id'] : null; + $destinationName = $transaction['destination_name'] ?? null; + $validDestination = $accountValidator->validateDestination($destinationId, $destinationName); + // do something with result: + if (false === $validDestination) { + $validator->errors()->add(sprintf('transactions.%d.destination_id', $index), $accountValidator->destError); + $validator->errors()->add(sprintf('transactions.%d.destination_name', $index), $accountValidator->destError); - return; - } + return; } } @@ -92,46 +107,57 @@ trait TransactionValidation Log::debug('Now in validateAccountInformationUpdate()'); $transactions = $this->getTransactionsArray($validator); + /** + * @var int $index + * @var array $transaction + */ + foreach ($transactions as $index => $transaction) { + $this->validateSingleUpdate($validator, $index, $transaction); + } + } + + /** + * @param Validator $validator + * @param int $index + * @param array $transaction + */ + protected function validateSingleUpdate(Validator $validator, int $index, array $transaction): void + { /** @var AccountValidator $accountValidator */ $accountValidator = app(AccountValidator::class); + $originalType = $this->getOriginalType((int)($transaction['transaction_journal_id'] ?? 0)); + $originalData = $this->getOriginalData((int)($transaction['transaction_journal_id'] ?? 0)); + $transactionType = $transaction['type'] ?? $originalType; + $accountValidator->setTransactionType($transactionType); - foreach ($transactions as $index => $transaction) { - $originalType = $this->getOriginalType((int)($transaction['transaction_journal_id'] ?? 0)); - $originalData = $this->getOriginalData((int)($transaction['transaction_journal_id'] ?? 0)); - $transactionType = $transaction['type'] ?? $originalType; - $accountValidator->setTransactionType($transactionType); + // if no account types are given, just skip the check. + if (!isset($transaction['source_id']) + && !isset($transaction['source_name']) + && !isset($transaction['destination_id']) + && !isset($transaction['destination_name'])) { + return; + } - // if no account types are given, just skip the check. - if (!isset($transaction['source_id']) - && !isset($transaction['source_name']) - && !isset($transaction['destination_id']) - && !isset($transaction['destination_name'])) { - continue; - } + // validate source account. + $sourceId = isset($transaction['source_id']) ? (int)$transaction['source_id'] : $originalData['source_id']; + $sourceName = $transaction['source_name'] ?? $originalData['source_name']; + $validSource = $accountValidator->validateSource($sourceId, $sourceName); - // validate source account. - $sourceId = isset($transaction['source_id']) ? (int)$transaction['source_id'] : $originalData['source_id']; - $sourceName = $transaction['source_name'] ?? $originalData['source_name']; - $validSource = $accountValidator->validateSource($sourceId, $sourceName); + // do something with result: + if (false === $validSource) { + $validator->errors()->add(sprintf('transactions.%d.source_id', $index), $accountValidator->sourceError); + $validator->errors()->add(sprintf('transactions.%d.source_name', $index), $accountValidator->sourceError); - // do something with result: - if (false === $validSource) { - $validator->errors()->add(sprintf('transactions.%d.source_id', $index), $accountValidator->sourceError); - $validator->errors()->add(sprintf('transactions.%d.source_name', $index), $accountValidator->sourceError); - - continue; - } - // validate destination account - $destinationId = isset($transaction['destination_id']) ? (int)$transaction['destination_id'] : $originalData['destination_id']; - $destinationName = $transaction['destination_name'] ?? $originalData['destination_name']; - $validDestination = $accountValidator->validateDestination($destinationId, $destinationName); - // do something with result: - if (false === $validDestination) { - $validator->errors()->add(sprintf('transactions.%d.destination_id', $index), $accountValidator->destError); - $validator->errors()->add(sprintf('transactions.%d.destination_name', $index), $accountValidator->destError); - - continue; - } + return; + } + // validate destination account + $destinationId = isset($transaction['destination_id']) ? (int)$transaction['destination_id'] : $originalData['destination_id']; + $destinationName = $transaction['destination_name'] ?? $originalData['destination_name']; + $validDestination = $accountValidator->validateDestination($destinationId, $destinationName); + // do something with result: + if (false === $validDestination) { + $validator->errors()->add(sprintf('transactions.%d.destination_id', $index), $accountValidator->destError); + $validator->errors()->add(sprintf('transactions.%d.destination_name', $index), $accountValidator->destError); } } @@ -265,7 +291,7 @@ trait TransactionValidation $transactions = $this->getTransactionsArray($validator); $types = []; - foreach ($transactions as $index => $transaction) { + foreach ($transactions as $transaction) { $types[] = $transaction['type'] ?? 'invalid'; } $unique = array_unique($types); @@ -277,7 +303,6 @@ trait TransactionValidation $first = $unique[0] ?? 'invalid'; if ('invalid' === $first) { $validator->errors()->add('transactions.0.type', (string)trans('validation.invalid_transaction_type')); - } } @@ -291,7 +316,7 @@ trait TransactionValidation Log::debug('Now in validateTransactionTypesForUpdate()'); $transactions = $this->getTransactionsArray($validator); $types = []; - foreach ($transactions as $index => $transaction) { + 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. diff --git a/bootstrap/app.php b/bootstrap/app.php index 1f310951ec..55559bf577 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -1,7 +1,7 @@ . */ - declare(strict_types=1); use FireflyIII\Providers\ImportServiceProvider; - return [ 'name' => envNonEmpty('APP_NAME', 'Firefly III'), 'env' => envNonEmpty('APP_ENV', 'local'), diff --git a/config/auth.php b/config/auth.php index 5c0516af44..077aac8e09 100644 --- a/config/auth.php +++ b/config/auth.php @@ -1,7 +1,7 @@ [ 'users' => [ - 'driver' => envNonEmpty('LOGIN_PROVIDER', 'eloquent'),//'adldap', + 'driver' => envNonEmpty('LOGIN_PROVIDER', 'eloquent'), //'adldap', 'model' => FireflyIII\User::class, ], ], diff --git a/config/breadcrumbs.php b/config/breadcrumbs.php index d873e66089..a82ac79402 100644 --- a/config/breadcrumbs.php +++ b/config/breadcrumbs.php @@ -2,7 +2,7 @@ /** * breadcrumbs.php - * Copyright (c) 2019 james@firefly-iii.org + * Copyright (c) 2019 james@firefly-iii.org. * * This file is part of Firefly III (https://github.com/firefly-iii). * @@ -23,7 +23,6 @@ declare(strict_types=1); return [ - /* |-------------------------------------------------------------------------- | View Name diff --git a/config/broadcasting.php b/config/broadcasting.php index bb55e20481..fdaad57463 100644 --- a/config/broadcasting.php +++ b/config/broadcasting.php @@ -1,7 +1,7 @@ [ [ 'host' => env('MEMCACHED_HOST', '127.0.0.1'), - 'port' => (int)env('MEMCACHED_PORT', 11211), + 'port' => (int) env('MEMCACHED_PORT', 11211), 'weight' => 100, ], ], diff --git a/config/csv.php b/config/csv.php index db41752d2b..c459762b00 100644 --- a/config/csv.php +++ b/config/csv.php @@ -2,7 +2,7 @@ /** * csv.php - * Copyright (c) 2019 james@firefly-iii.org + * Copyright (c) 2019 james@firefly-iii.org. * * This file is part of Firefly III (https://github.com/firefly-iii). * @@ -23,14 +23,13 @@ declare(strict_types=1); use FireflyIII\Import\Specifics\AbnAmroDescription; +use FireflyIII\Import\Specifics\Belfius; +use FireflyIII\Import\Specifics\IngBelgium; use FireflyIII\Import\Specifics\IngDescription; use FireflyIII\Import\Specifics\PresidentsChoice; use FireflyIII\Import\Specifics\SnsDescription; -use FireflyIII\Import\Specifics\Belfius; -use FireflyIII\Import\Specifics\IngBelgium; return [ - /* * Configuration for the CSV specifics. */ @@ -40,7 +39,7 @@ return [ 'SnsDescription' => SnsDescription::class, 'PresidentsChoice' => PresidentsChoice::class, 'Belfius' => Belfius::class, - 'IngBelgium' => IngBelgium::class + 'IngBelgium' => IngBelgium::class, ], /* @@ -88,7 +87,6 @@ return [ 'converter' => 'Ignore', 'mapper' => null, - ], 'bill-id' => [ 'mappable' => true, diff --git a/config/database.php b/config/database.php index 75b364a2d5..3ec1f3e55b 100644 --- a/config/database.php +++ b/config/database.php @@ -1,7 +1,7 @@ envNonEmpty('DB_CONNECTION', 'pgsql'), 'connections' => [ 'sqlite' => [ diff --git a/config/debugbar.php b/config/debugbar.php index 249bbb080e..746b3f780c 100644 --- a/config/debugbar.php +++ b/config/debugbar.php @@ -1,9 +1,10 @@ env('DEBUGBAR_ENABLED', null), - 'except' => [ - 'telescope*' + 'except' => [ + 'telescope*', ], /* @@ -57,7 +57,7 @@ return [ 'driver' => 'file', // redis, file, pdo, custom 'path' => storage_path('debugbar'), // For file driver 'connection' => null, // Leave null for default connection (Redis/PDO) - 'provider' => '' // Instance of StorageInterface for custom driver + 'provider' => '', // Instance of StorageInterface for custom driver ], /* @@ -87,7 +87,7 @@ return [ | Optionally, you can also send ServerTiming headers on ajax requests for the Chrome DevTools. */ - 'capture_ajax' => true, + 'capture_ajax' => true, 'add_ajax_timing' => false, /* @@ -163,26 +163,26 @@ return [ 'with_params' => true, // Render SQL with the parameters substituted 'backtrace' => true, // Use a backtrace to find the origin of the query in your files. 'timeline' => false, // Add the queries to the timeline - 'explain' => [ // Show EXPLAIN output on queries + 'explain' => [ // Show EXPLAIN output on queries 'enabled' => false, - 'types' => ['SELECT'], // // workaround ['SELECT'] only. https://github.com/barryvdh/laravel-debugbar/issues/888 ['SELECT', 'INSERT', 'UPDATE', 'DELETE']; for MySQL 5.6.3+ + 'types' => ['SELECT'], // // workaround ['SELECT'] only. https://github.com/barryvdh/laravel-debugbar/issues/888 ['SELECT', 'INSERT', 'UPDATE', 'DELETE']; for MySQL 5.6.3+ ], 'hints' => true, // Show hints for common mistakes ], 'mail' => [ - 'full_log' => false + 'full_log' => false, ], 'views' => [ 'data' => true, //Note: Can slow down the application, because the data can be quite large.. ], 'route' => [ - 'label' => true // show complete route on bar + 'label' => true, // show complete route on bar ], 'logs' => [ - 'file' => null + 'file' => null, ], 'cache' => [ - 'values' => true // collect cache values + 'values' => true, // collect cache values ], ], diff --git a/config/filesystems.php b/config/filesystems.php index d033ae2ebf..4db063d31a 100644 --- a/config/filesystems.php +++ b/config/filesystems.php @@ -1,7 +1,7 @@ [ 'local', diff --git a/config/firefly.php b/config/firefly.php index 1de4bac523..7c23ddde8e 100644 --- a/config/firefly.php +++ b/config/firefly.php @@ -1,9 +1,8 @@ false, ], 'feature_flags' => [ - 'export' => true, + 'export' => true, 'telemetry' => false, ], @@ -182,7 +181,6 @@ return [ /* PDF */ 'application/pdf', - /* MS word */ 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', @@ -246,66 +244,61 @@ return [ '1Y' => 'yearly', 'custom' => 'custom', ], - 'subTitlesByIdentifier' => - [ - 'asset' => 'Asset accounts', - 'expense' => 'Expense accounts', - 'revenue' => 'Revenue accounts', - 'cash' => 'Cash accounts', - 'liabilities' => 'Liabilities', - 'liability' => 'Liabilities', - ], - 'subIconsByIdentifier' => - [ - 'asset' => 'fa-money', - 'Asset account' => 'fa-money', - 'Default account' => 'fa-money', - 'Cash account' => 'fa-money', - 'expense' => 'fa-shopping-cart', - 'Expense account' => 'fa-shopping-cart', - 'Beneficiary account' => 'fa-shopping-cart', - 'revenue' => 'fa-download', - 'Revenue account' => 'fa-download', - 'import' => 'fa-download', - 'Import account' => 'fa-download', - 'liabilities' => 'fa-ticket', - ], - 'accountTypesByIdentifier' => - [ - 'asset' => ['Default account', 'Asset account'], - 'expense' => ['Expense account', 'Beneficiary account'], - 'revenue' => ['Revenue account'], - 'import' => ['Import account'], - 'liabilities' => ['Loan', 'Debt', 'Credit card', 'Mortgage'], - ], - 'accountTypeByIdentifier' => - [ - 'asset' => ['Asset account'], - 'expense' => ['Expense account'], - 'revenue' => ['Revenue account'], - 'opening' => ['Initial balance account'], - 'initial' => ['Initial balance account'], - 'import' => ['Import account'], - 'reconcile' => ['Reconciliation account'], - 'liabilities' => ['Loan', 'Debt', 'Mortgage', 'Credit card'], - 'liability' => ['Loan', 'Debt', 'Mortgage', 'Credit card'], - ], - 'shortNamesByFullName' => - [ - 'Default account' => 'asset', - 'Asset account' => 'asset', - 'Import account' => 'import', - 'Expense account' => 'expense', - 'Beneficiary account' => 'expense', - 'Revenue account' => 'revenue', - 'Cash account' => 'cash', - 'Initial balance account' => 'initial-balance', - 'Reconciliation account' => 'reconciliation', - 'Credit card' => 'liabilities', - 'Loan' => 'liabilities', - 'Debt' => 'liabilities', - 'Mortgage' => 'liabilities', - ], + 'subTitlesByIdentifier' => [ + 'asset' => 'Asset accounts', + 'expense' => 'Expense accounts', + 'revenue' => 'Revenue accounts', + 'cash' => 'Cash accounts', + 'liabilities' => 'Liabilities', + 'liability' => 'Liabilities', + ], + 'subIconsByIdentifier' => [ + 'asset' => 'fa-money', + 'Asset account' => 'fa-money', + 'Default account' => 'fa-money', + 'Cash account' => 'fa-money', + 'expense' => 'fa-shopping-cart', + 'Expense account' => 'fa-shopping-cart', + 'Beneficiary account' => 'fa-shopping-cart', + 'revenue' => 'fa-download', + 'Revenue account' => 'fa-download', + 'import' => 'fa-download', + 'Import account' => 'fa-download', + 'liabilities' => 'fa-ticket', + ], + 'accountTypesByIdentifier' => [ + 'asset' => ['Default account', 'Asset account'], + 'expense' => ['Expense account', 'Beneficiary account'], + 'revenue' => ['Revenue account'], + 'import' => ['Import account'], + 'liabilities' => ['Loan', 'Debt', 'Credit card', 'Mortgage'], + ], + 'accountTypeByIdentifier' => [ + 'asset' => ['Asset account'], + 'expense' => ['Expense account'], + 'revenue' => ['Revenue account'], + 'opening' => ['Initial balance account'], + 'initial' => ['Initial balance account'], + 'import' => ['Import account'], + 'reconcile' => ['Reconciliation account'], + 'liabilities' => ['Loan', 'Debt', 'Mortgage', 'Credit card'], + 'liability' => ['Loan', 'Debt', 'Mortgage', 'Credit card'], + ], + 'shortNamesByFullName' => [ + 'Default account' => 'asset', + 'Asset account' => 'asset', + 'Import account' => 'import', + 'Expense account' => 'expense', + 'Beneficiary account' => 'expense', + 'Revenue account' => 'revenue', + 'Cash account' => 'cash', + 'Initial balance account' => 'initial-balance', + 'Reconciliation account' => 'reconciliation', + 'Credit card' => 'liabilities', + 'Loan' => 'liabilities', + 'Debt' => 'liabilities', + 'Mortgage' => 'liabilities', + ], 'shortLiabilityNameByFullName' => [ 'Credit card' => 'creditcard', 'Loan' => 'loan', @@ -313,7 +306,7 @@ return [ 'Mortgage' => 'mortgage', ], /** - * Languages configuration + * Languages configuration. */ 'languages' => [ // currently enabled languages @@ -335,7 +328,7 @@ return [ 'hu_HU' => ['name_locale' => 'Hungarian', 'name_english' => 'Hungarian'], 'sv_SE' => ['name_locale' => 'Svenska', 'name_english' => 'Swedish'], 'fi_FI' => ['name_locale' => 'Suomi', 'name_english' => 'Finnish'], - + 'vi_VN' => ['name_locale' => 'Tiếng Việt', 'name_english' => 'Vietnamese'], // currently disabled languages: // 'bg_BG' => ['name_locale' => 'Български', 'name_english' => 'Bulgarian'], @@ -433,7 +426,6 @@ return [ 'tagOrId' => TagOrId::class, 'configName' => ConfigurationName::class, - ], 'rule-triggers' => [ 'user_action' => UserAction::class, @@ -546,7 +538,6 @@ return [ 'notes_are', ], - 'test-triggers' => [ 'limit' => 10, 'range' => 200, @@ -554,8 +545,8 @@ return [ 'default_currency' => 'EUR', 'default_language' => envNonEmpty('DEFAULT_LANGUAGE', 'en_US'), 'search_modifiers' => ['amount_is', 'amount', 'amount_max', 'amount_min', 'amount_less', 'amount_more', 'source', 'destination', 'category', - 'budget', 'bill', 'type', 'date', 'date_before', 'date_after', 'on', 'before', 'after', 'from', 'to', 'tag', 'created_on', - 'updated_on'], + 'budget', 'bill', 'type', 'date', 'date_before', 'date_after', 'on', 'before', 'after', 'from', 'to', 'tag', 'created_on', + 'updated_on', ], // TODO notes has_attachments 'cer_providers' => [ @@ -568,10 +559,10 @@ return [ 'source' => [ TransactionTypeModel::WITHDRAWAL => [AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE], TransactionTypeModel::DEPOSIT => [AccountType::REVENUE, AccountType::CASH, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE, - AccountType::INITIAL_BALANCE, AccountType::RECONCILIATION], + AccountType::INITIAL_BALANCE, AccountType::RECONCILIATION, ], TransactionTypeModel::TRANSFER => [AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE], TransactionTypeModel::OPENING_BALANCE => [AccountType::INITIAL_BALANCE, AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, - AccountType::MORTGAGE], + AccountType::MORTGAGE, ], TransactionTypeModel::RECONCILIATION => [AccountType::RECONCILIATION, AccountType::ASSET], // in case no transaction type is known yet, it could be anything. 'none' => [ @@ -585,43 +576,43 @@ return [ ], 'destination' => [ TransactionTypeModel::WITHDRAWAL => [AccountType::EXPENSE, AccountType::CASH, AccountType::LOAN, AccountType::DEBT, - AccountType::MORTGAGE], + AccountType::MORTGAGE, ], TransactionTypeModel::DEPOSIT => [AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE], TransactionTypeModel::TRANSFER => [AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE], TransactionTypeModel::OPENING_BALANCE => [AccountType::INITIAL_BALANCE, AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, - AccountType::MORTGAGE], + AccountType::MORTGAGE, ], TransactionTypeModel::RECONCILIATION => [AccountType::RECONCILIATION, AccountType::ASSET], ], ], 'allowed_opposing_types' => [ 'source' => [ AccountType::ASSET => [AccountType::ASSET, AccountType::CASH, AccountType::DEBT, AccountType::EXPENSE, AccountType::INITIAL_BALANCE, - AccountType::LOAN, AccountType::RECONCILIATION], + AccountType::LOAN, AccountType::RECONCILIATION, ], AccountType::CASH => [AccountType::ASSET], AccountType::DEBT => [AccountType::ASSET, AccountType::DEBT, AccountType::EXPENSE, AccountType::INITIAL_BALANCE, AccountType::LOAN, - AccountType::MORTGAGE], + AccountType::MORTGAGE, ], AccountType::EXPENSE => [], // is not allowed as a source. AccountType::INITIAL_BALANCE => [AccountType::ASSET, AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE], AccountType::LOAN => [AccountType::ASSET, AccountType::DEBT, AccountType::EXPENSE, AccountType::INITIAL_BALANCE, AccountType::LOAN, - AccountType::MORTGAGE], + AccountType::MORTGAGE, ], AccountType::MORTGAGE => [AccountType::ASSET, AccountType::DEBT, AccountType::EXPENSE, AccountType::INITIAL_BALANCE, AccountType::LOAN, - AccountType::MORTGAGE], + AccountType::MORTGAGE, ], AccountType::RECONCILIATION => [AccountType::ASSET], AccountType::REVENUE => [AccountType::ASSET, AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE], ], 'destination' => [ AccountType::ASSET => [AccountType::ASSET, AccountType::CASH, AccountType::DEBT, AccountType::INITIAL_BALANCE, AccountType::LOAN, - AccountType::MORTGAGE, AccountType::RECONCILIATION, AccountType::REVENUE], + AccountType::MORTGAGE, AccountType::RECONCILIATION, AccountType::REVENUE, ], AccountType::CASH => [AccountType::ASSET], AccountType::DEBT => [AccountType::ASSET, AccountType::DEBT, AccountType::INITIAL_BALANCE, AccountType::LOAN, AccountType::MORTGAGE, - AccountType::REVENUE], + AccountType::REVENUE, ], AccountType::EXPENSE => [AccountType::ASSET, AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE], AccountType::INITIAL_BALANCE => [AccountType::ASSET, AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE], AccountType::LOAN => [AccountType::ASSET, AccountType::DEBT, AccountType::INITIAL_BALANCE, AccountType::LOAN, AccountType::MORTGAGE, - AccountType::REVENUE], + AccountType::REVENUE, ], AccountType::MORTGAGE => [AccountType::ASSET, AccountType::DEBT, AccountType::INITIAL_BALANCE, AccountType::LOAN, AccountType::MORTGAGE, - AccountType::REVENUE], + AccountType::REVENUE, ], AccountType::RECONCILIATION => [AccountType::ASSET], AccountType::REVENUE => [], // is not allowed as a destination ], @@ -630,29 +621,29 @@ return [ 'allowed_transaction_types' => [ 'source' => [ AccountType::ASSET => [TransactionTypeModel::WITHDRAWAL, TransactionTypeModel::TRANSFER, TransactionTypeModel::OPENING_BALANCE, - TransactionTypeModel::RECONCILIATION], + TransactionTypeModel::RECONCILIATION, ], AccountType::EXPENSE => [], // is not allowed as a source. AccountType::REVENUE => [TransactionTypeModel::DEPOSIT], AccountType::LOAN => [TransactionTypeModel::WITHDRAWAL, TransactionTypeModel::DEPOSIT, TransactionTypeModel::TRANSFER, - TransactionTypeModel::OPENING_BALANCE], + TransactionTypeModel::OPENING_BALANCE, ], AccountType::DEBT => [TransactionTypeModel::WITHDRAWAL, TransactionTypeModel::DEPOSIT, TransactionTypeModel::TRANSFER, - TransactionTypeModel::OPENING_BALANCE], + TransactionTypeModel::OPENING_BALANCE, ], AccountType::MORTGAGE => [TransactionTypeModel::WITHDRAWAL, TransactionTypeModel::DEPOSIT, TransactionTypeModel::TRANSFER, - TransactionTypeModel::OPENING_BALANCE], + TransactionTypeModel::OPENING_BALANCE, ], AccountType::INITIAL_BALANCE => [], // todo fill me in. AccountType::RECONCILIATION => [], // todo fill me in. ], 'destination' => [ AccountType::ASSET => [TransactionTypeModel::DEPOSIT, TransactionTypeModel::TRANSFER, TransactionTypeModel::OPENING_BALANCE, - TransactionTypeModel::RECONCILIATION], + TransactionTypeModel::RECONCILIATION, ], AccountType::EXPENSE => [TransactionTypeModel::WITHDRAWAL], AccountType::REVENUE => [], // is not allowed as destination. AccountType::LOAN => [TransactionTypeModel::WITHDRAWAL, TransactionTypeModel::DEPOSIT, TransactionTypeModel::TRANSFER, - TransactionTypeModel::OPENING_BALANCE], + TransactionTypeModel::OPENING_BALANCE, ], AccountType::DEBT => [TransactionTypeModel::WITHDRAWAL, TransactionTypeModel::DEPOSIT, TransactionTypeModel::TRANSFER, - TransactionTypeModel::OPENING_BALANCE], + TransactionTypeModel::OPENING_BALANCE, ], AccountType::MORTGAGE => [TransactionTypeModel::WITHDRAWAL, TransactionTypeModel::DEPOSIT, TransactionTypeModel::TRANSFER, - TransactionTypeModel::OPENING_BALANCE], + TransactionTypeModel::OPENING_BALANCE, ], AccountType::INITIAL_BALANCE => [], // todo fill me in. AccountType::RECONCILIATION => [], // todo fill me in. ], diff --git a/config/google2fa.php b/config/google2fa.php index 5f65f69f59..91a2557661 100644 --- a/config/google2fa.php +++ b/config/google2fa.php @@ -1,7 +1,7 @@ true, - 'store_in_cookie' => true, ]; diff --git a/config/hashing.php b/config/hashing.php index 597161680b..c3615a8a3a 100644 --- a/config/hashing.php +++ b/config/hashing.php @@ -2,7 +2,7 @@ /** * hashing.php - * Copyright (c) 2019 james@firefly-iii.org + * Copyright (c) 2019 james@firefly-iii.org. * * This file is part of Firefly III (https://github.com/firefly-iii). * @@ -23,7 +23,6 @@ declare(strict_types=1); return [ - /* |-------------------------------------------------------------------------- | Default Hash Driver diff --git a/config/ide-helper.php b/config/ide-helper.php index a09660a922..61a07e1f00 100644 --- a/config/ide-helper.php +++ b/config/ide-helper.php @@ -1,7 +1,7 @@ '_ide_helper', 'format' => 'php', - + 'meta_filename' => '.phpstorm.meta.php', /* @@ -86,9 +85,9 @@ return array( 'include_helpers' => false, - 'helper_files' => array( - base_path().'/vendor/laravel/framework/src/Illuminate/Support/helpers.php', - ), + 'helper_files' => [ + base_path() . '/vendor/laravel/framework/src/Illuminate/Support/helpers.php', + ], /* |-------------------------------------------------------------------------- @@ -100,10 +99,9 @@ return array( | */ - 'model_locations' => array( + 'model_locations' => [ 'app', - ), - + ], /* |-------------------------------------------------------------------------- @@ -114,13 +112,13 @@ return array( | */ - 'extra' => array( - 'Eloquent' => array('Illuminate\Database\Eloquent\Builder', 'Illuminate\Database\Query\Builder'), - 'Session' => array('Illuminate\Session\Store'), - ), + 'extra' => [ + 'Eloquent' => ['Illuminate\Database\Eloquent\Builder', 'Illuminate\Database\Query\Builder'], + 'Session' => ['Illuminate\Session\Store'], + ], - 'magic' => array( - 'Log' => array( + 'magic' => [ + 'Log' => [ 'debug' => 'Monolog\Logger::addDebug', 'info' => 'Monolog\Logger::addInfo', 'notice' => 'Monolog\Logger::addNotice', @@ -129,8 +127,8 @@ return array( 'critical' => 'Monolog\Logger::addCritical', 'alert' => 'Monolog\Logger::addAlert', 'emergency' => 'Monolog\Logger::addEmergency', - ) - ), + ], + ], /* |-------------------------------------------------------------------------- @@ -142,9 +140,9 @@ return array( | */ - 'interfaces' => array( + 'interfaces' => [ - ), + ], /* |-------------------------------------------------------------------------- @@ -172,9 +170,9 @@ return array( | ), | */ - 'custom_db_types' => array( + 'custom_db_types' => [ - ), + ], /* |-------------------------------------------------------------------------- @@ -210,10 +208,10 @@ return array( | Cast the given "real type" to the given "type". | */ - 'type_overrides' => array( + 'type_overrides' => [ 'integer' => 'int', 'boolean' => 'bool', - ), + ], /* |-------------------------------------------------------------------------- @@ -226,4 +224,4 @@ return array( */ 'include_class_docblocks' => false, -); +]; diff --git a/config/import.php b/config/import.php index da6f6581f4..46bf8eb5f3 100644 --- a/config/import.php +++ b/config/import.php @@ -2,7 +2,7 @@ /** * import.php - * Copyright (c) 2019 james@firefly-iii.org + * Copyright (c) 2019 james@firefly-iii.org. * * This file is part of Firefly III (https://github.com/firefly-iii). * diff --git a/config/intro.php b/config/intro.php index 743bbade24..18b5962217 100644 --- a/config/intro.php +++ b/config/intro.php @@ -1,7 +1,7 @@ ['element' => '#box_out_holder'], 'help' => ['element' => '#help', 'position' => 'bottom'], 'sidebar-toggle' => ['element' => '#sidebar-toggle', 'position' => 'bottom'], - 'cash_account' => ['element' => '#all_transactions','position' => 'left'], + 'cash_account' => ['element' => '#all_transactions', 'position' => 'left'], 'outro' => [], ], // accounts: create @@ -42,24 +42,24 @@ return [ ], // transactions: create 'transactions_create_withdrawal' => [ - 'source' => ['element' => 'input[name="source[]"]'], + 'source' => ['element' => 'input[name="source[]"]'], 'destination' => ['element' => 'input[name="destination[]"]'], - 'more_meta' => ['element' => 'input[name="category[]"]'], - 'split_add' => ['element' => '.split_add_btn'], + 'more_meta' => ['element' => 'input[name="category[]"]'], + 'split_add' => ['element' => '.split_add_btn'], ], 'transactions_create_deposit' => [ - 'source' => ['element' => 'input[name="source[]"]'], + 'source' => ['element' => 'input[name="source[]"]'], 'destination' => ['element' => 'input[name="destination[]"]'], - 'more_meta' => ['element' => 'input[name="category[]"]'], - 'split_add' => ['element' => '.split_add_btn'], + 'more_meta' => ['element' => 'input[name="category[]"]'], + 'split_add' => ['element' => '.split_add_btn'], ], 'transactions_create_transfer' => [ - 'source' => ['element' => 'input[name="source[]"]'], + 'source' => ['element' => 'input[name="source[]"]'], 'destination' => ['element' => 'input[name="destination[]"]'], - 'more_meta' => ['element' => 'input[name="category[]"]'], - 'split_add' => ['element' => '.split_add_btn'], + 'more_meta' => ['element' => 'input[name="category[]"]'], + 'split_add' => ['element' => '.split_add_btn'], ], // extra text for asset account creation. @@ -72,7 +72,7 @@ return [ // budgets: index 'budgets_index' => [ 'intro' => [], - 'set_budget' => ['element' => '#availableBar',], + 'set_budget' => ['element' => '#availableBar'], 'see_expenses_bar' => ['element' => '#spentBar'], 'navigate_periods' => ['element' => '#periodNavigator'], 'new_budget' => ['element' => '#createBudgetBox'], @@ -115,7 +115,7 @@ return [ // piggies: index, create, show 'piggy-banks_index' => [ 'saved' => ['element' => '.piggySaved'], - 'button' => ['element' => '.piggyBar',], + 'button' => ['element' => '.piggyBar'], 'accountStatus' => ['element' => '#accountStatus', 'position' => 'top'], ], 'piggy-banks_create' => [ @@ -173,9 +173,9 @@ return [ 'currencies_index' => [ 'intro' => [], 'default' => ['element' => '#default-currency'], - 'buttons' => ['element' => '.buttons',] + 'buttons' => ['element' => '.buttons'], ], 'currencies_create' => [ - 'code' => ['element' => '#ffInput_code',], + 'code' => ['element' => '#ffInput_code'], ], ]; diff --git a/config/ldap.php b/config/ldap.php index b4265b9dc2..5ac78296da 100644 --- a/config/ldap.php +++ b/config/ldap.php @@ -2,7 +2,7 @@ /** * ldap.php - * Copyright (c) 2019 james@firefly-iii.org + * Copyright (c) 2019 james@firefly-iii.org. * * This file is part of Firefly III (https://github.com/firefly-iii). * @@ -37,8 +37,8 @@ if ('FreeIPA' === envNonEmpty('ADLDAP_CONNECTION_SCHEME', 'OpenLDAP')) { if ('ActiveDirectory' === envNonEmpty('ADLDAP_CONNECTION_SCHEME', 'OpenLDAP')) { $schema = ActiveDirectory::class; } -return [ +return [ /* |-------------------------------------------------------------------------- | Connections diff --git a/config/ldap_auth.php b/config/ldap_auth.php index 16ee89cbbd..04ba98b752 100644 --- a/config/ldap_auth.php +++ b/config/ldap_auth.php @@ -2,7 +2,7 @@ /** * ldap_auth.php - * Copyright (c) 2019 james@firefly-iii.org + * Copyright (c) 2019 james@firefly-iii.org. * * This file is part of Firefly III (https://github.com/firefly-iii). * @@ -25,7 +25,6 @@ declare(strict_types=1); use Adldap\Laravel\Scopes\UidScope; use Adldap\Laravel\Scopes\UpnScope; - // default OpenLDAP scopes. $scopes = [ UidScope::class, @@ -39,9 +38,7 @@ if ('ActiveDirectory' === env('ADLDAP_CONNECTION_SCHEME')) { ]; } - return [ - /* |-------------------------------------------------------------------------- | Connection @@ -78,7 +75,6 @@ return [ 'provider' => Adldap\Laravel\Auth\DatabaseUserProvider::class, //'provider' => Adldap\Laravel\Auth\NoDatabaseUserProvider::class, - /* |-------------------------------------------------------------------------- | Model @@ -174,7 +170,7 @@ return [ 'ldap' => [ 'locate_users_by' => envNonEmpty('ADLDAP_DISCOVER_FIELD', 'userprincipalname'), - 'bind_users_by' => envNonEmpty('ADLDAP_AUTH_FIELD', 'distinguishedname'), + 'bind_users_by' => envNonEmpty('ADLDAP_AUTH_FIELD', 'distinguishedname'), ], diff --git a/config/logging.php b/config/logging.php index 9240961a9b..dc1b9c4122 100644 --- a/config/logging.php +++ b/config/logging.php @@ -1,7 +1,7 @@ . */ - declare(strict_types=1); use FireflyIII\Support\Logging\AuditLogger; return [ - /* |-------------------------------------------------------------------------- | Default Log Channel @@ -38,7 +36,7 @@ return [ */ 'default' => envNonEmpty('LOG_CHANNEL', 'stack'), - 'level' => envNonEmpty('APP_LOG_LEVEL', 'info'), + 'level' => envNonEmpty('APP_LOG_LEVEL', 'info'), /* |-------------------------------------------------------------------------- | Log Channels diff --git a/config/mail.php b/config/mail.php index b4c40e74e7..1a3183e064 100644 --- a/config/mail.php +++ b/config/mail.php @@ -1,7 +1,7 @@ ['address' => envNonEmpty('MAIL_FROM', 'changeme@example.com'), 'name' => 'Firefly III Mailer'], - /* |-------------------------------------------------------------------------- | E-Mail Encryption Protocol diff --git a/config/queue.php b/config/queue.php index 092f100aa6..d0b341a312 100644 --- a/config/queue.php +++ b/config/queue.php @@ -1,7 +1,7 @@ [ - 'domain' => env('MAILGUN_DOMAIN'), - 'endpoint' => env('MAILGUN_ENDPOINT','api.mailgun.net'), - 'secret' => env('MAILGUN_SECRET'), + 'domain' => env('MAILGUN_DOMAIN'), + 'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'), + 'secret' => env('MAILGUN_SECRET'), ], 'ses' => [ diff --git a/config/session.php b/config/session.php index f15260bbd8..7458e597fa 100644 --- a/config/session.php +++ b/config/session.php @@ -1,7 +1,7 @@ env('SESSION_DRIVER', 'file'), 'lifetime' => 120, diff --git a/config/twigbridge.php b/config/twigbridge.php index 56dee25508..4f4d170c0e 100644 --- a/config/twigbridge.php +++ b/config/twigbridge.php @@ -1,5 +1,7 @@ [ /* |-------------------------------------------------------------------------- @@ -181,13 +182,12 @@ return [ 'Steam', 'Config', 'Request', - 'Form' => ['is_safe' => ['input', 'select', 'checkbox', 'model', 'open', 'radio', 'textarea', 'file',],], + 'Form' => ['is_safe' => ['input', 'select', 'checkbox', 'model', 'open', 'radio', 'textarea', 'file']], 'ExpandedForm' => [ 'is_safe' => [ 'date', 'text', 'select', 'balance', 'optionsList', 'checkbox', 'amount', 'tags', 'integer', 'textarea', 'location', 'file', 'staticText', 'password', 'nonSelectableAmount', 'number', 'amountNoCurrency', 'percentage', - ], ], 'AccountForm' => [ @@ -201,12 +201,11 @@ return [ 'currencyList', 'currencyListEmpty', 'balanceAll', ], ], - 'PiggyBankForm' => - [ - 'is_safe' => [ - 'piggyBankList', - ], + 'PiggyBankForm' => [ + 'is_safe' => [ + 'piggyBankList', ], + ], 'RuleForm' => [ 'is_safe' => [ 'ruleGroupList', 'ruleGroupListWithEmpty', @@ -214,7 +213,6 @@ return [ ], ], - /* |-------------------------------------------------------------------------- | Functions diff --git a/config/upgrade.php b/config/upgrade.php index 2afd5a541e..fe3d1e0fd2 100644 --- a/config/upgrade.php +++ b/config/upgrade.php @@ -1,7 +1,7 @@ [ - 'upgrade' => - [ - '4.3' => 'Make sure you run the migrations and clear your cache. If you need more help, please check Github or the Firefly III website.', - '4.6.3' => 'This will be the last version to require PHP7.0. Future versions will require PHP7.1 minimum.', - '4.6.4' => 'This version of Firefly III requires PHP7.1.', - '4.7.3' => 'This version of Firefly III handles bills differently. See http://bit.ly/FF3-new-bills for more information.', - '4.7.4' => 'This version of Firefly III has a new import routine. See http://bit.ly/FF3-new-import for more information.', - '4.7.6' => 'This will be the last version to require PHP7.1. Future versions will require PHP7.2 minimum.', - '4.7.7' => 'This version of Firefly III requires PHP7.2.', - '4.7.10' => 'Firefly III no longer encrypts database values. To protect your data, make sure you use TDE or FDE. Read more: https://bit.ly/FF3-encryption', - '4.8.0' => 'This is a huge upgrade for Firefly III. Please expect bugs and errors, and bear with me as I fix them. I tested a lot of things but pretty sure I missed some. Thanks for understanding.', - '4.8.1' => 'This version of Firefly III requires PHP7.3.', - ], - 'install' => - [ - '4.3' => 'Welcome to Firefly! Make sure you follow the installation guide. If you need more help, please check Github or the Firefly III website. The installation guide has a FAQ which you should check out as well.', - '4.6.3' => 'This will be the last version to require PHP7.0. Future versions will require PHP7.1 minimum.', - '4.6.4' => 'This version of Firefly III requires PHP7.1.', - '4.7.3' => 'This version of Firefly III handles bills differently. See http://bit.ly/FF3-new-bills for more information.', - '4.7.4' => 'This version of Firefly III has a new import routine. See http://bit.ly/FF3-new-import for more information.', - '4.7.6' => 'This will be the last version to require PHP7.1. Future versions will require PHP7.2 minimum.', - '4.7.7' => 'This version of Firefly III requires PHP7.2.', - '4.7.10' => 'Firefly III no longer encrypts database values. To protect your data, make sure you use TDE or FDE. Read more: https://bit.ly/FF3-encryption', - '4.8.0' => 'This is a huge upgrade for Firefly III. Please expect bugs and errors, and bear with me as I fix them. I tested a lot of things but pretty sure I missed some. Thanks for understanding.', - '4.8.1' => 'This version of Firefly III requires PHP7.3.', - ], + 'upgrade' => [ + '4.3' => 'Make sure you run the migrations and clear your cache. If you need more help, please check Github or the Firefly III website.', + '4.6.3' => 'This will be the last version to require PHP7.0. Future versions will require PHP7.1 minimum.', + '4.6.4' => 'This version of Firefly III requires PHP7.1.', + '4.7.3' => 'This version of Firefly III handles bills differently. See http://bit.ly/FF3-new-bills for more information.', + '4.7.4' => 'This version of Firefly III has a new import routine. See http://bit.ly/FF3-new-import for more information.', + '4.7.6' => 'This will be the last version to require PHP7.1. Future versions will require PHP7.2 minimum.', + '4.7.7' => 'This version of Firefly III requires PHP7.2.', + '4.7.10' => 'Firefly III no longer encrypts database values. To protect your data, make sure you use TDE or FDE. Read more: https://bit.ly/FF3-encryption', + '4.8.0' => 'This is a huge upgrade for Firefly III. Please expect bugs and errors, and bear with me as I fix them. I tested a lot of things but pretty sure I missed some. Thanks for understanding.', + '4.8.1' => 'This version of Firefly III requires PHP7.3.', + ], + 'install' => [ + '4.3' => 'Welcome to Firefly! Make sure you follow the installation guide. If you need more help, please check Github or the Firefly III website. The installation guide has a FAQ which you should check out as well.', + '4.6.3' => 'This will be the last version to require PHP7.0. Future versions will require PHP7.1 minimum.', + '4.6.4' => 'This version of Firefly III requires PHP7.1.', + '4.7.3' => 'This version of Firefly III handles bills differently. See http://bit.ly/FF3-new-bills for more information.', + '4.7.4' => 'This version of Firefly III has a new import routine. See http://bit.ly/FF3-new-import for more information.', + '4.7.6' => 'This will be the last version to require PHP7.1. Future versions will require PHP7.2 minimum.', + '4.7.7' => 'This version of Firefly III requires PHP7.2.', + '4.7.10' => 'Firefly III no longer encrypts database values. To protect your data, make sure you use TDE or FDE. Read more: https://bit.ly/FF3-encryption', + '4.8.0' => 'This is a huge upgrade for Firefly III. Please expect bugs and errors, and bear with me as I fix them. I tested a lot of things but pretty sure I missed some. Thanks for understanding.', + '4.8.1' => 'This version of Firefly III requires PHP7.3.', + ], ], ]; diff --git a/config/view.php b/config/view.php index 4752755452..42b243edca 100644 --- a/config/view.php +++ b/config/view.php @@ -1,7 +1,7 @@ define( FireflyIII\Models\Account::class, - function (Faker\Generator $faker) { + static function (Faker\Generator $faker) { return [ 'id' => $faker->unique()->numberBetween(1000, 10000), 'user_id' => 1, diff --git a/database/factories/ModelFactory.php b/database/factories/ModelFactory.php index 8a3bc836a6..aea14f83cc 100644 --- a/database/factories/ModelFactory.php +++ b/database/factories/ModelFactory.php @@ -1,7 +1,7 @@ define( FireflyIII\Models\Attachment::class, - function (Faker\Generator $faker) { + static function (Faker\Generator $faker) { return [ 'user_id' => 1, 'attachable_id' => 1, @@ -43,7 +42,7 @@ $factory->define( $factory->define( FireflyIII\Models\CurrencyExchangeRate::class, - function (Faker\Generator $faker) { + static function (Faker\Generator $faker) { return [ 'user_id' => 1, 'from_currency_id' => 1, @@ -57,7 +56,7 @@ $factory->define( $factory->define( FireflyIII\Models\TransactionCurrency::class, - function (Faker\Generator $faker) { + static function (Faker\Generator $faker) { return [ 'name' => $faker->words(1, true), 'code' => 'ABC', @@ -68,7 +67,7 @@ $factory->define( $factory->define( FireflyIII\Models\ImportJob::class, - function (Faker\Generator $faker) { + static function (Faker\Generator $faker) { return [ 'id' => $faker->numberBetween(1, 100), 'user_id' => 1, @@ -89,7 +88,7 @@ $factory->define( $factory->define( FireflyIII\Models\TransactionJournal::class, - function (Faker\Generator $faker) { + static function (Faker\Generator $faker) { return [ 'id' => $faker->unique()->numberBetween(1000, 10000), 'user_id' => 1, @@ -111,7 +110,7 @@ $factory->define( $factory->define( FireflyIII\Models\Bill::class, - function (Faker\Generator $faker) { + static function (Faker\Generator $faker) { return [ 'created_at' => new Carbon, 'updated_at' => new Carbon, @@ -131,7 +130,7 @@ $factory->define( $factory->define( FireflyIII\Models\PiggyBankRepetition::class, - function (Faker\Generator $faker) { + static function (Faker\Generator $faker) { return [ 'id' => $faker->unique()->numberBetween(100, 10000), 'piggy_bank_id' => $faker->numberBetween(1, 10), @@ -144,7 +143,7 @@ $factory->define( $factory->define( FireflyIII\Models\PiggyBank::class, - function (Faker\Generator $faker) { + static function (Faker\Generator $faker) { return [ 'id' => $faker->unique()->numberBetween(100, 10000), 'created_at' => new Carbon, @@ -162,7 +161,7 @@ $factory->define( $factory->define( FireflyIII\Models\Tag::class, - function (Faker\Generator $faker) { + static function (Faker\Generator $faker) { return [ 'id' => $faker->unique()->numberBetween(200, 10000), 'user_id' => 1, @@ -174,7 +173,7 @@ $factory->define( $factory->define( FireflyIII\Models\Category::class, - function (Faker\Generator $faker) { + static function (Faker\Generator $faker) { return [ 'id' => $faker->numberBetween(1, 10), 'name' => $faker->words(3, true), @@ -184,7 +183,7 @@ $factory->define( $factory->define( FireflyIII\Models\Budget::class, - function (Faker\Generator $faker) { + static function (Faker\Generator $faker) { return [ 'id' => $faker->numberBetween(1, 10), 'name' => $faker->words(3, true), @@ -194,7 +193,7 @@ $factory->define( $factory->define( FireflyIII\Models\PiggyBankEvent::class, - function (Faker\Generator $faker) { + static function (Faker\Generator $faker) { return [ 'id' => $faker->numberBetween(1, 10), 'piggy_bank_id' => $faker->numberBetween(1, 10), @@ -207,7 +206,7 @@ $factory->define( $factory->define( FireflyIII\Models\BudgetLimit::class, - function (Faker\Generator $faker) { + static function (Faker\Generator $faker) { return [ 'id' => $faker->numberBetween(1, 10), 'start_date' => '2017-01-01', @@ -220,10 +219,10 @@ $factory->define( $factory->define( FireflyIII\Models\Transaction::class, - function (Faker\Generator $faker) { + static function (Faker\Generator $faker) { return [ - 'transaction_amount' => (string)$faker->randomFloat(2, -100, 100), - 'destination_amount' => (string)$faker->randomFloat(2, -100, 100), + 'transaction_amount' => (string) $faker->randomFloat(2, -100, 100), + 'destination_amount' => (string) $faker->randomFloat(2, -100, 100), 'opposing_account_id' => $faker->numberBetween(1, 10), 'source_id' => $faker->numberBetween(1, 10), 'opposing_account_name' => $faker->words(3, true), @@ -232,7 +231,7 @@ $factory->define( 'destination_id' => $faker->numberBetween(1, 10), 'date' => new Carbon, 'destination_name' => $faker->words(3, true), - 'amount' => (string)$faker->randomFloat(2, -100, 100), + 'amount' => (string) $faker->randomFloat(2, -100, 100), 'budget_id' => 0, 'category' => $faker->words(3, true), 'transaction_journal_id' => $faker->numberBetween(1, 10), diff --git a/database/factories/UserFactory.php b/database/factories/UserFactory.php index 00cdde4797..f449ed01b0 100644 --- a/database/factories/UserFactory.php +++ b/database/factories/UserFactory.php @@ -2,7 +2,7 @@ /** * UserFactory.php - * Copyright (c) 2019 james@firefly-iii.org + * Copyright (c) 2019 james@firefly-iii.org. * * This file is part of Firefly III (https://github.com/firefly-iii). * @@ -36,11 +36,11 @@ use Faker\Generator as Faker; */ $factory->define( - FireflyIII\User::class, function (Faker $faker) { - return [ - 'email' => $faker->unique()->safeEmail, - 'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret - 'remember_token' => str_random(10), - ]; -} + FireflyIII\User::class, static function (Faker $faker) { + return [ + 'email' => $faker->unique()->safeEmail, + 'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret + 'remember_token' => str_random(10), + ]; + } ); diff --git a/database/migrations/2016_06_16_000000_create_support_tables.php b/database/migrations/2016_06_16_000000_create_support_tables.php index c96ff7a169..eb20d428ad 100644 --- a/database/migrations/2016_06_16_000000_create_support_tables.php +++ b/database/migrations/2016_06_16_000000_create_support_tables.php @@ -1,7 +1,7 @@ createConfigurationTable(); } - /** - * - */ private function createAccountTypeTable(): void { if (!Schema::hasTable('account_types')) { Schema::create( 'account_types', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->string('type', 50); @@ -89,7 +86,7 @@ class CreateSupportTables extends Migration if (!Schema::hasTable('configuration')) { Schema::create( 'configuration', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->softDeletes(); @@ -101,15 +98,12 @@ class CreateSupportTables extends Migration } } - /** - * - */ private function createCurrencyTable(): void { if (!Schema::hasTable('transaction_currencies')) { Schema::create( 'transaction_currencies', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->softDeletes(); @@ -124,15 +118,12 @@ class CreateSupportTables extends Migration } } - /** - * - */ private function createJobsTable(): void { if (!Schema::hasTable('jobs')) { Schema::create( 'jobs', - function (Blueprint $table) { + static function (Blueprint $table) { // straight from Laravel $table->bigIncrements('id'); $table->string('queue'); @@ -148,15 +139,12 @@ class CreateSupportTables extends Migration } } - /** - * - */ private function createPasswordTable(): void { if (!Schema::hasTable('password_resets')) { Schema::create( 'password_resets', - function (Blueprint $table) { + static function (Blueprint $table) { // straight from laravel $table->string('email')->index(); $table->string('token')->index(); @@ -166,15 +154,12 @@ class CreateSupportTables extends Migration } } - /** - * - */ private function createPermissionRoleTable(): void { if (!Schema::hasTable('permission_role')) { Schema::create( 'permission_role', - function (Blueprint $table) { + static function (Blueprint $table) { $table->integer('permission_id')->unsigned(); $table->integer('role_id')->unsigned(); @@ -187,15 +172,12 @@ class CreateSupportTables extends Migration } } - /** - * - */ private function createPermissionsTable(): void { if (!Schema::hasTable('permissions')) { Schema::create( 'permissions', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->string('name')->unique(); @@ -206,15 +188,12 @@ class CreateSupportTables extends Migration } } - /** - * - */ private function createRolesTable(): void { if (!Schema::hasTable('roles')) { Schema::create( 'roles', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->string('name')->unique(); @@ -225,15 +204,12 @@ class CreateSupportTables extends Migration } } - /** - * - */ private function createSessionsTable(): void { if (!Schema::hasTable('sessions')) { Schema::create( 'sessions', - function (Blueprint $table) { + static function (Blueprint $table) { $table->string('id')->unique(); $table->integer('user_id')->nullable(); $table->string('ip_address', 45)->nullable(); @@ -245,15 +221,12 @@ class CreateSupportTables extends Migration } } - /** - * - */ private function createTransactionTypeTable(): void { if (!Schema::hasTable('transaction_types')) { Schema::create( 'transaction_types', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->softDeletes(); diff --git a/database/migrations/2016_06_16_000001_create_users_table.php b/database/migrations/2016_06_16_000001_create_users_table.php index f076825544..0056b9f158 100644 --- a/database/migrations/2016_06_16_000001_create_users_table.php +++ b/database/migrations/2016_06_16_000001_create_users_table.php @@ -1,7 +1,7 @@ increments('id'); $table->timestamps(); $table->string('email', 255); diff --git a/database/migrations/2016_06_16_000002_create_main_tables.php b/database/migrations/2016_06_16_000002_create_main_tables.php index 58403dbf3f..d4532a4871 100644 --- a/database/migrations/2016_06_16_000002_create_main_tables.php +++ b/database/migrations/2016_06_16_000002_create_main_tables.php @@ -1,7 +1,7 @@ createTransactionTables(); } - /** - * - */ private function createAccountTables(): void { if (!Schema::hasTable('accounts')) { Schema::create( 'accounts', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->softDeletes(); @@ -112,7 +109,7 @@ class CreateMainTables extends Migration if (!Schema::hasTable('account_meta')) { Schema::create( 'account_meta', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->integer('account_id', false, true); @@ -124,15 +121,12 @@ class CreateMainTables extends Migration } } - /** - * - */ private function createAttachmentsTable(): void { if (!Schema::hasTable('attachments')) { Schema::create( 'attachments', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->softDeletes(); @@ -155,15 +149,12 @@ class CreateMainTables extends Migration } } - /** - * - */ private function createBillsTable(): void { if (!Schema::hasTable('bills')) { Schema::create( 'bills', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->softDeletes(); @@ -195,7 +186,7 @@ class CreateMainTables extends Migration if (!Schema::hasTable('budgets')) { Schema::create( 'budgets', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->softDeletes(); @@ -210,7 +201,7 @@ class CreateMainTables extends Migration if (!Schema::hasTable('budget_limits')) { Schema::create( 'budget_limits', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->integer('budget_id', false, true); @@ -225,7 +216,7 @@ class CreateMainTables extends Migration if (!Schema::hasTable('limit_repetitions')) { Schema::create( 'limit_repetitions', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->integer('budget_limit_id', false, true); @@ -238,15 +229,12 @@ class CreateMainTables extends Migration } } - /** - * - */ private function createCategoriesTable(): void { if (!Schema::hasTable('categories')) { Schema::create( 'categories', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->softDeletes(); @@ -261,15 +249,12 @@ class CreateMainTables extends Migration } } - /** - * - */ private function createExportJobsTable(): void { if (!Schema::hasTable('export_jobs')) { Schema::create( 'export_jobs', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->integer('user_id', false, true); @@ -283,7 +268,7 @@ class CreateMainTables extends Migration if (!Schema::hasTable('import_jobs')) { Schema::create( 'import_jobs', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->integer('user_id')->unsigned(); @@ -297,15 +282,12 @@ class CreateMainTables extends Migration } } - /** - * - */ private function createPiggyBanksTable(): void { if (!Schema::hasTable('piggy_banks')) { Schema::create( 'piggy_banks', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->softDeletes(); @@ -325,7 +307,7 @@ class CreateMainTables extends Migration if (!Schema::hasTable('piggy_bank_repetitions')) { Schema::create( 'piggy_bank_repetitions', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->integer('piggy_bank_id', false, true); @@ -338,15 +320,12 @@ class CreateMainTables extends Migration } } - /** - * - */ private function createPreferencesTable(): void { if (!Schema::hasTable('preferences')) { Schema::create( 'preferences', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->integer('user_id', false, true); @@ -359,15 +338,12 @@ class CreateMainTables extends Migration } } - /** - * - */ private function createRoleTable(): void { if (!Schema::hasTable('role_user')) { Schema::create( 'role_user', - function (Blueprint $table) { + static function (Blueprint $table) { $table->integer('user_id', false, true); $table->integer('role_id', false, true); @@ -389,7 +365,7 @@ class CreateMainTables extends Migration if (!Schema::hasTable('rule_groups')) { Schema::create( 'rule_groups', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->softDeletes(); @@ -407,7 +383,7 @@ class CreateMainTables extends Migration if (!Schema::hasTable('rules')) { Schema::create( 'rules', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->softDeletes(); @@ -430,7 +406,7 @@ class CreateMainTables extends Migration if (!Schema::hasTable('rule_actions')) { Schema::create( 'rule_actions', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->integer('rule_id', false, true); @@ -450,7 +426,7 @@ class CreateMainTables extends Migration if (!Schema::hasTable('rule_triggers')) { Schema::create( 'rule_triggers', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->integer('rule_id', false, true); @@ -469,15 +445,12 @@ class CreateMainTables extends Migration } } - /** - * - */ private function createTagsTable(): void { if (!Schema::hasTable('tags')) { Schema::create( 'tags', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->softDeletes(); @@ -508,7 +481,7 @@ class CreateMainTables extends Migration if (!Schema::hasTable('transaction_journals')) { Schema::create( 'transaction_journals', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->softDeletes(); @@ -536,7 +509,7 @@ class CreateMainTables extends Migration if (!Schema::hasTable('journal_meta')) { Schema::create( 'journal_meta', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->integer('transaction_journal_id', false, true); @@ -551,7 +524,7 @@ class CreateMainTables extends Migration if (!Schema::hasTable('tag_transaction_journal')) { Schema::create( 'tag_transaction_journal', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->integer('tag_id', false, true); $table->integer('transaction_journal_id', false, true); @@ -567,7 +540,7 @@ class CreateMainTables extends Migration if (!Schema::hasTable('budget_transaction_journal')) { Schema::create( 'budget_transaction_journal', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->integer('budget_id', false, true); $table->integer('transaction_journal_id', false, true); @@ -580,7 +553,7 @@ class CreateMainTables extends Migration if (!Schema::hasTable('category_transaction_journal')) { Schema::create( 'category_transaction_journal', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->integer('category_id', false, true); $table->integer('transaction_journal_id', false, true); @@ -593,7 +566,7 @@ class CreateMainTables extends Migration if (!Schema::hasTable('piggy_bank_events')) { Schema::create( 'piggy_bank_events', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->integer('piggy_bank_id', false, true); @@ -610,7 +583,7 @@ class CreateMainTables extends Migration if (!Schema::hasTable('transactions')) { Schema::create( 'transactions', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->softDeletes(); @@ -628,7 +601,7 @@ class CreateMainTables extends Migration if (!Schema::hasTable('budget_transaction')) { Schema::create( 'budget_transaction', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->integer('budget_id', false, true); $table->integer('transaction_id', false, true); @@ -642,7 +615,7 @@ class CreateMainTables extends Migration if (!Schema::hasTable('category_transaction')) { Schema::create( 'category_transaction', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->integer('category_id', false, true); $table->integer('transaction_id', false, true); diff --git a/database/migrations/2016_08_25_091522_changes_for_3101.php b/database/migrations/2016_08_25_091522_changes_for_3101.php index 1c2d9546ed..e5fc0c339e 100644 --- a/database/migrations/2016_08_25_091522_changes_for_3101.php +++ b/database/migrations/2016_08_25_091522_changes_for_3101.php @@ -1,7 +1,7 @@ text('description')->nullable()->change(); } ); Schema::table( 'rules', - function (Blueprint $table) { + static function (Blueprint $table) { $table->text('description')->nullable()->change(); } ); diff --git a/database/migrations/2016_10_09_150037_expand_transactions_table.php b/database/migrations/2016_10_09_150037_expand_transactions_table.php index 571fa68c68..ac13fbd43b 100644 --- a/database/migrations/2016_10_09_150037_expand_transactions_table.php +++ b/database/migrations/2016_10_09_150037_expand_transactions_table.php @@ -1,7 +1,7 @@ dropColumn('identifier'); } ); @@ -50,7 +50,7 @@ class ExpandTransactionsTable extends Migration { Schema::table( 'transactions', - function (Blueprint $table) { + static function (Blueprint $table) { $table->smallInteger('identifier', false, true)->default(0); } ); diff --git a/database/migrations/2016_10_22_075804_changes_for_v410.php b/database/migrations/2016_10_22_075804_changes_for_v410.php index 496ec5b051..8e86c75b0e 100644 --- a/database/migrations/2016_10_22_075804_changes_for_v410.php +++ b/database/migrations/2016_10_22_075804_changes_for_v410.php @@ -1,7 +1,7 @@ increments('id'); $table->timestamps(); $table->softDeletes(); diff --git a/database/migrations/2016_11_24_210552_changes_for_v420.php b/database/migrations/2016_11_24_210552_changes_for_v420.php index 845fea95a2..e9bd35b292 100644 --- a/database/migrations/2016_11_24_210552_changes_for_v420.php +++ b/database/migrations/2016_11_24_210552_changes_for_v420.php @@ -1,7 +1,7 @@ dropSoftDeletes(); } ); @@ -50,7 +50,7 @@ class ChangesForV420 extends Migration { Schema::table( 'journal_meta', - function (Blueprint $table) { + static function (Blueprint $table) { $table->softDeletes(); } ); diff --git a/database/migrations/2016_12_22_150431_changes_for_v430.php b/database/migrations/2016_12_22_150431_changes_for_v430.php index 24ec99978f..715b8810ca 100644 --- a/database/migrations/2016_12_22_150431_changes_for_v430.php +++ b/database/migrations/2016_12_22_150431_changes_for_v430.php @@ -1,7 +1,7 @@ increments('id'); $table->timestamps(); $table->softDeletes(); diff --git a/database/migrations/2016_12_28_203205_changes_for_v431.php b/database/migrations/2016_12_28_203205_changes_for_v431.php index d5e3b8265e..cc68fbd30d 100644 --- a/database/migrations/2016_12_28_203205_changes_for_v431.php +++ b/database/migrations/2016_12_28_203205_changes_for_v431.php @@ -1,7 +1,7 @@ string('repeat_freq', 30)->nullable(); } ); Schema::table( 'budget_limits', - function (Blueprint $table) { + static function (Blueprint $table) { $table->boolean('repeats')->default(0); } ); @@ -50,7 +50,7 @@ class ChangesForV431 extends Migration // change field "start_date" to "startdate" Schema::table( 'budget_limits', - function (Blueprint $table) { + static function (Blueprint $table) { $table->renameColumn('start_date', 'startdate'); } ); @@ -58,14 +58,14 @@ class ChangesForV431 extends Migration // remove date field "end_date" Schema::table( 'budget_limits', - function (Blueprint $table) { + static function (Blueprint $table) { $table->dropColumn('end_date'); } ); // remove decimal places Schema::table( 'transaction_currencies', - function (Blueprint $table) { + static function (Blueprint $table) { $table->dropColumn('decimal_places'); } ); diff --git a/database/migrations/2017_04_13_163623_changes_for_v440.php b/database/migrations/2017_04_13_163623_changes_for_v440.php index d3201c7257..1cf2074fcf 100644 --- a/database/migrations/2017_04_13_163623_changes_for_v440.php +++ b/database/migrations/2017_04_13_163623_changes_for_v440.php @@ -1,7 +1,7 @@ integer('transaction_currency_id', false, true)->after('description')->nullable(); - $table->foreign('transaction_currency_id')->references('id')->on('transaction_currencies')->onDelete('set null'); + $table->integer('transaction_currency_id', false, true)->after('description')->nullable(); + $table->foreign('transaction_currency_id')->references('id')->on('transaction_currencies')->onDelete('set null'); } } ); diff --git a/database/migrations/2017_06_02_105232_changes_for_v450.php b/database/migrations/2017_06_02_105232_changes_for_v450.php index c4b5bcc9e3..da15e5106e 100644 --- a/database/migrations/2017_06_02_105232_changes_for_v450.php +++ b/database/migrations/2017_06_02_105232_changes_for_v450.php @@ -1,7 +1,7 @@ dropColumn('foreign_amount'); - } ); @@ -70,7 +69,7 @@ class ChangesForV450 extends Migration // add "foreign_amount" to transactions Schema::table( 'transactions', - function (Blueprint $table) { + static function (Blueprint $table) { $table->decimal('foreign_amount', 22, 12)->nullable()->after('amount'); } ); @@ -78,7 +77,7 @@ class ChangesForV450 extends Migration // add foreign transaction currency id to transactions (is nullable): Schema::table( 'transactions', - function (Blueprint $table) { + static function (Blueprint $table) { $table->integer('foreign_currency_id', false, true)->default(null)->after('foreign_amount')->nullable(); $table->foreign('foreign_currency_id')->references('id')->on('transaction_currencies')->onDelete('set null'); } diff --git a/database/migrations/2017_08_20_062014_changes_for_v470.php b/database/migrations/2017_08_20_062014_changes_for_v470.php index e9ca3f987b..c64a5df13e 100644 --- a/database/migrations/2017_08_20_062014_changes_for_v470.php +++ b/database/migrations/2017_08_20_062014_changes_for_v470.php @@ -1,7 +1,7 @@ increments('id'); $table->timestamps(); $table->softDeletes(); @@ -65,7 +65,7 @@ class ChangesForV470 extends Migration if (!Schema::hasTable('journal_links')) { Schema::create( 'journal_links', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->integer('link_type_id', false, true); diff --git a/database/migrations/2017_11_04_170844_changes_for_v470a.php b/database/migrations/2017_11_04_170844_changes_for_v470a.php index d9d39e4298..10df289ee7 100644 --- a/database/migrations/2017_11_04_170844_changes_for_v470a.php +++ b/database/migrations/2017_11_04_170844_changes_for_v470a.php @@ -1,7 +1,7 @@ dropColumn('reconciled'); } ); @@ -51,7 +51,7 @@ class ChangesForV470a extends Migration { Schema::table( 'transactions', - function (Blueprint $table) { + static function (Blueprint $table) { $table->boolean('reconciled')->after('deleted_at')->default(0); } ); diff --git a/database/migrations/2018_01_01_000001_create_oauth_auth_codes_table.php b/database/migrations/2018_01_01_000001_create_oauth_auth_codes_table.php index 92f1656fe7..eaffd9ffee 100644 --- a/database/migrations/2018_01_01_000001_create_oauth_auth_codes_table.php +++ b/database/migrations/2018_01_01_000001_create_oauth_auth_codes_table.php @@ -2,7 +2,7 @@ /** * 2018_01_01_000001_create_oauth_auth_codes_table.php - * Copyright (c) 2019 james@firefly-iii.org + * Copyright (c) 2019 james@firefly-iii.org. * * This file is part of Firefly III (https://github.com/firefly-iii). * @@ -27,7 +27,7 @@ use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; /** - * Class CreateOauthAuthCodesTable + * Class CreateOauthAuthCodesTable. */ class CreateOauthAuthCodesTable extends Migration { @@ -46,14 +46,14 @@ class CreateOauthAuthCodesTable extends Migration public function up(): void { Schema::create( - 'oauth_auth_codes', function (Blueprint $table) { - $table->string('id', 100)->primary(); - $table->integer('user_id'); - $table->integer('client_id'); - $table->text('scopes')->nullable(); - $table->boolean('revoked'); - $table->dateTime('expires_at')->nullable(); - } + 'oauth_auth_codes', static function (Blueprint $table) { + $table->string('id', 100)->primary(); + $table->integer('user_id'); + $table->integer('client_id'); + $table->text('scopes')->nullable(); + $table->boolean('revoked'); + $table->dateTime('expires_at')->nullable(); + } ); } } diff --git a/database/migrations/2018_01_01_000002_create_oauth_access_tokens_table.php b/database/migrations/2018_01_01_000002_create_oauth_access_tokens_table.php index d5833f8a7f..526df9cb2e 100644 --- a/database/migrations/2018_01_01_000002_create_oauth_access_tokens_table.php +++ b/database/migrations/2018_01_01_000002_create_oauth_access_tokens_table.php @@ -2,7 +2,7 @@ /** * 2018_01_01_000002_create_oauth_access_tokens_table.php - * Copyright (c) 2019 james@firefly-iii.org + * Copyright (c) 2019 james@firefly-iii.org. * * This file is part of Firefly III (https://github.com/firefly-iii). * @@ -27,7 +27,7 @@ use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; /** - * Class CreateOauthAccessTokensTable + * Class CreateOauthAccessTokensTable. */ class CreateOauthAccessTokensTable extends Migration { @@ -46,16 +46,16 @@ class CreateOauthAccessTokensTable extends Migration public function up(): void { Schema::create( - 'oauth_access_tokens', function (Blueprint $table) { - $table->string('id', 100)->primary(); - $table->integer('user_id')->index()->nullable(); - $table->integer('client_id'); - $table->string('name')->nullable(); - $table->text('scopes')->nullable(); - $table->boolean('revoked'); - $table->timestamps(); - $table->dateTime('expires_at')->nullable(); - } + 'oauth_access_tokens', static function (Blueprint $table) { + $table->string('id', 100)->primary(); + $table->integer('user_id')->index()->nullable(); + $table->integer('client_id'); + $table->string('name')->nullable(); + $table->text('scopes')->nullable(); + $table->boolean('revoked'); + $table->timestamps(); + $table->dateTime('expires_at')->nullable(); + } ); } } diff --git a/database/migrations/2018_01_01_000003_create_oauth_refresh_tokens_table.php b/database/migrations/2018_01_01_000003_create_oauth_refresh_tokens_table.php index 3f1dcad5fc..bbc7f569fa 100644 --- a/database/migrations/2018_01_01_000003_create_oauth_refresh_tokens_table.php +++ b/database/migrations/2018_01_01_000003_create_oauth_refresh_tokens_table.php @@ -2,7 +2,7 @@ /** * 2018_01_01_000003_create_oauth_refresh_tokens_table.php - * Copyright (c) 2019 james@firefly-iii.org + * Copyright (c) 2019 james@firefly-iii.org. * * This file is part of Firefly III (https://github.com/firefly-iii). * @@ -27,7 +27,7 @@ use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; /** - * Class CreateOauthRefreshTokensTable + * Class CreateOauthRefreshTokensTable. */ class CreateOauthRefreshTokensTable extends Migration { @@ -46,12 +46,12 @@ class CreateOauthRefreshTokensTable extends Migration public function up(): void { Schema::create( - 'oauth_refresh_tokens', function (Blueprint $table) { - $table->string('id', 100)->primary(); - $table->string('access_token_id', 100)->index(); - $table->boolean('revoked'); - $table->dateTime('expires_at')->nullable(); - } + 'oauth_refresh_tokens', static function (Blueprint $table) { + $table->string('id', 100)->primary(); + $table->string('access_token_id', 100)->index(); + $table->boolean('revoked'); + $table->dateTime('expires_at')->nullable(); + } ); } } diff --git a/database/migrations/2018_01_01_000004_create_oauth_clients_table.php b/database/migrations/2018_01_01_000004_create_oauth_clients_table.php index b950da01b3..3588b59241 100644 --- a/database/migrations/2018_01_01_000004_create_oauth_clients_table.php +++ b/database/migrations/2018_01_01_000004_create_oauth_clients_table.php @@ -2,7 +2,7 @@ /** * 2018_01_01_000004_create_oauth_clients_table.php - * Copyright (c) 2019 james@firefly-iii.org + * Copyright (c) 2019 james@firefly-iii.org. * * This file is part of Firefly III (https://github.com/firefly-iii). * @@ -27,7 +27,7 @@ use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; /** - * Class CreateOauthClientsTable + * Class CreateOauthClientsTable. */ class CreateOauthClientsTable extends Migration { @@ -46,17 +46,17 @@ class CreateOauthClientsTable extends Migration public function up(): void { Schema::create( - 'oauth_clients', function (Blueprint $table) { - $table->increments('id'); - $table->integer('user_id')->index()->nullable(); - $table->string('name'); - $table->string('secret', 100); - $table->text('redirect'); - $table->boolean('personal_access_client'); - $table->boolean('password_client'); - $table->boolean('revoked'); - $table->timestamps(); - } + 'oauth_clients', static function (Blueprint $table) { + $table->increments('id'); + $table->integer('user_id')->index()->nullable(); + $table->string('name'); + $table->string('secret', 100); + $table->text('redirect'); + $table->boolean('personal_access_client'); + $table->boolean('password_client'); + $table->boolean('revoked'); + $table->timestamps(); + } ); } } diff --git a/database/migrations/2018_01_01_000005_create_oauth_personal_access_clients_table.php b/database/migrations/2018_01_01_000005_create_oauth_personal_access_clients_table.php index b5ba1398a4..69bfe1e1ad 100644 --- a/database/migrations/2018_01_01_000005_create_oauth_personal_access_clients_table.php +++ b/database/migrations/2018_01_01_000005_create_oauth_personal_access_clients_table.php @@ -2,7 +2,7 @@ /** * 2018_01_01_000005_create_oauth_personal_access_clients_table.php - * Copyright (c) 2019 james@firefly-iii.org + * Copyright (c) 2019 james@firefly-iii.org. * * This file is part of Firefly III (https://github.com/firefly-iii). * @@ -27,7 +27,7 @@ use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; /** - * Class CreateOauthPersonalAccessClientsTable + * Class CreateOauthPersonalAccessClientsTable. */ class CreateOauthPersonalAccessClientsTable extends Migration { @@ -37,7 +37,6 @@ class CreateOauthPersonalAccessClientsTable extends Migration public function down(): void { Schema::drop('oauth_personal_access_clients'); - } /** @@ -47,11 +46,11 @@ class CreateOauthPersonalAccessClientsTable extends Migration public function up(): void { Schema::create( - 'oauth_personal_access_clients', function (Blueprint $table) { - $table->increments('id'); - $table->integer('client_id')->index(); - $table->timestamps(); - } + 'oauth_personal_access_clients', static function (Blueprint $table) { + $table->increments('id'); + $table->integer('client_id')->index(); + $table->timestamps(); + } ); } } diff --git a/database/migrations/2018_03_19_141348_changes_for_v472.php b/database/migrations/2018_03_19_141348_changes_for_v472.php index aa65327bc1..e5504ddde5 100644 --- a/database/migrations/2018_03_19_141348_changes_for_v472.php +++ b/database/migrations/2018_03_19_141348_changes_for_v472.php @@ -2,7 +2,7 @@ /** * 2018_03_19_141348_changes_for_v472.php - * Copyright (c) 2019 james@firefly-iii.org + * Copyright (c) 2019 james@firefly-iii.org. * * This file is part of Firefly III (https://github.com/firefly-iii). * @@ -26,7 +26,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; /** - * Class ChangesForV472 + * Class ChangesForV472. */ class ChangesForV472 extends Migration { @@ -39,13 +39,13 @@ class ChangesForV472 extends Migration { Schema::table( 'attachments', - function (Blueprint $table) { + static function (Blueprint $table) { $table->text('notes')->nullable(); } ); Schema::table( 'budgets', - function (Blueprint $table) { + static function (Blueprint $table) { $table->dropColumn('order'); } ); @@ -61,14 +61,14 @@ class ChangesForV472 extends Migration { Schema::table( 'attachments', - function (Blueprint $table) { + static function (Blueprint $table) { $table->dropColumn('notes'); } ); Schema::table( 'budgets', - function (Blueprint $table) { + static function (Blueprint $table) { $table->mediumInteger('order', false, true)->default(0); } ); diff --git a/database/migrations/2018_04_07_210913_changes_for_v473.php b/database/migrations/2018_04_07_210913_changes_for_v473.php index e043108e9d..9f2acb181a 100644 --- a/database/migrations/2018_04_07_210913_changes_for_v473.php +++ b/database/migrations/2018_04_07_210913_changes_for_v473.php @@ -2,7 +2,7 @@ /** * 2018_04_07_210913_changes_for_v473.php - * Copyright (c) 2019 james@firefly-iii.org + * Copyright (c) 2019 james@firefly-iii.org. * * This file is part of Firefly III (https://github.com/firefly-iii). * @@ -27,7 +27,7 @@ use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; /** - * Class ChangesForV473 + * Class ChangesForV473. */ class ChangesForV473 extends Migration { @@ -40,7 +40,7 @@ class ChangesForV473 extends Migration { Schema::table( 'bills', - function (Blueprint $table) { + static function (Blueprint $table) { // cannot drop foreign keys in SQLite: if ('sqlite' !== config('database.default')) { @@ -50,10 +50,9 @@ class ChangesForV473 extends Migration } ); - Schema::table( 'rules', - function (Blueprint $table) { + static function (Blueprint $table) { $table->dropColumn('strict'); } ); @@ -69,14 +68,14 @@ class ChangesForV473 extends Migration { Schema::table( 'bills', - function (Blueprint $table) { + static function (Blueprint $table) { $table->integer('transaction_currency_id', false, true)->nullable()->after('user_id'); $table->foreign('transaction_currency_id')->references('id')->on('transaction_currencies')->onDelete('set null'); } ); Schema::table( 'rules', - function (Blueprint $table) { + static function (Blueprint $table) { $table->boolean('strict')->default(true); } ); diff --git a/database/migrations/2018_04_29_174524_changes_for_v474.php b/database/migrations/2018_04_29_174524_changes_for_v474.php index 3b018da57c..5d76fede07 100644 --- a/database/migrations/2018_04_29_174524_changes_for_v474.php +++ b/database/migrations/2018_04_29_174524_changes_for_v474.php @@ -2,7 +2,7 @@ /** * 2018_04_29_174524_changes_for_v474.php - * Copyright (c) 2019 james@firefly-iii.org + * Copyright (c) 2019 james@firefly-iii.org. * * This file is part of Firefly III (https://github.com/firefly-iii). * @@ -26,7 +26,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; /** - * Class ChangesForV474 + * Class ChangesForV474. */ class ChangesForV474 extends Migration { @@ -54,7 +54,6 @@ class ChangesForV474 extends Migration 'import_jobs', static function (Blueprint $table) { $table->dropColumn('provider'); - } ); @@ -62,7 +61,6 @@ class ChangesForV474 extends Migration 'import_jobs', static function (Blueprint $table) { $table->dropColumn('stage'); - } ); @@ -70,7 +68,6 @@ class ChangesForV474 extends Migration 'import_jobs', static function (Blueprint $table) { $table->dropColumn('transactions'); - } ); @@ -78,7 +75,6 @@ class ChangesForV474 extends Migration 'import_jobs', static function (Blueprint $table) { $table->dropColumn('errors'); - } ); @@ -86,7 +82,6 @@ class ChangesForV474 extends Migration 'import_jobs', static function (Blueprint $table) { $table->dropColumn('tag_id'); - } ); } diff --git a/database/migrations/2018_06_08_200526_changes_for_v475.php b/database/migrations/2018_06_08_200526_changes_for_v475.php index 07311b1040..a16e6266bb 100644 --- a/database/migrations/2018_06_08_200526_changes_for_v475.php +++ b/database/migrations/2018_06_08_200526_changes_for_v475.php @@ -2,7 +2,7 @@ /** * 2018_06_08_200526_changes_for_v475.php - * Copyright (c) 2019 james@firefly-iii.org + * Copyright (c) 2019 james@firefly-iii.org. * * This file is part of Firefly III (https://github.com/firefly-iii). * @@ -26,8 +26,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; /** - * - * Class ChangesForV475 + * Class ChangesForV475. */ class ChangesForV475 extends Migration { @@ -55,97 +54,93 @@ class ChangesForV475 extends Migration public function up(): void { Schema::create( - 'recurrences', function (Blueprint $table) { - $table->increments('id'); - $table->timestamps(); - $table->softDeletes(); - $table->integer('user_id', false, true); - $table->integer('transaction_type_id', false, true); + 'recurrences', static function (Blueprint $table) { + $table->increments('id'); + $table->timestamps(); + $table->softDeletes(); + $table->integer('user_id', false, true); + $table->integer('transaction_type_id', false, true); - $table->string('title', 1024); - $table->text('description'); + $table->string('title', 1024); + $table->text('description'); - $table->date('first_date'); - $table->date('repeat_until')->nullable(); - $table->date('latest_date')->nullable(); - $table->smallInteger('repetitions', false, true); + $table->date('first_date'); + $table->date('repeat_until')->nullable(); + $table->date('latest_date')->nullable(); + $table->smallInteger('repetitions', false, true); - $table->boolean('apply_rules')->default(true); - $table->boolean('active')->default(true); + $table->boolean('apply_rules')->default(true); + $table->boolean('active')->default(true); - $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); - $table->foreign('transaction_type_id')->references('id')->on('transaction_types')->onDelete('cascade'); - } + $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); + $table->foreign('transaction_type_id')->references('id')->on('transaction_types')->onDelete('cascade'); + } ); Schema::create( - 'recurrences_transactions', function (Blueprint $table) { - $table->increments('id'); - $table->timestamps(); - $table->softDeletes(); - $table->integer('recurrence_id', false, true); - $table->integer('transaction_currency_id', false, true); - $table->integer('foreign_currency_id', false, true)->nullable(); - $table->integer('source_id', false, true); - $table->integer('destination_id', false, true); + 'recurrences_transactions', static function (Blueprint $table) { + $table->increments('id'); + $table->timestamps(); + $table->softDeletes(); + $table->integer('recurrence_id', false, true); + $table->integer('transaction_currency_id', false, true); + $table->integer('foreign_currency_id', false, true)->nullable(); + $table->integer('source_id', false, true); + $table->integer('destination_id', false, true); - $table->decimal('amount', 22, 12); - $table->decimal('foreign_amount', 22, 12)->nullable(); - $table->string('description', 1024); + $table->decimal('amount', 22, 12); + $table->decimal('foreign_amount', 22, 12)->nullable(); + $table->string('description', 1024); - - $table->foreign('recurrence_id')->references('id')->on('recurrences')->onDelete('cascade'); - $table->foreign('transaction_currency_id')->references('id')->on('transaction_currencies')->onDelete('cascade'); - $table->foreign('foreign_currency_id')->references('id')->on('transaction_currencies')->onDelete('set null'); - $table->foreign('source_id')->references('id')->on('accounts')->onDelete('cascade'); - $table->foreign('destination_id')->references('id')->on('accounts')->onDelete('cascade'); - } - ); - - - Schema::create( - 'recurrences_repetitions', function (Blueprint $table) { - $table->increments('id'); - $table->timestamps(); - $table->softDeletes(); - $table->integer('recurrence_id', false, true); - $table->string('repetition_type', 50); - $table->string('repetition_moment', 50); - $table->smallInteger('repetition_skip', false, true); - $table->smallInteger('weekend', false, true); - - $table->foreign('recurrence_id')->references('id')->on('recurrences')->onDelete('cascade'); - } + $table->foreign('recurrence_id')->references('id')->on('recurrences')->onDelete('cascade'); + $table->foreign('transaction_currency_id')->references('id')->on('transaction_currencies')->onDelete('cascade'); + $table->foreign('foreign_currency_id')->references('id')->on('transaction_currencies')->onDelete('set null'); + $table->foreign('source_id')->references('id')->on('accounts')->onDelete('cascade'); + $table->foreign('destination_id')->references('id')->on('accounts')->onDelete('cascade'); + } ); Schema::create( - 'recurrences_meta', function (Blueprint $table) { - $table->increments('id'); - $table->timestamps(); - $table->softDeletes(); - $table->integer('recurrence_id', false, true); + 'recurrences_repetitions', static function (Blueprint $table) { + $table->increments('id'); + $table->timestamps(); + $table->softDeletes(); + $table->integer('recurrence_id', false, true); + $table->string('repetition_type', 50); + $table->string('repetition_moment', 50); + $table->smallInteger('repetition_skip', false, true); + $table->smallInteger('weekend', false, true); - $table->string('name', 50); - $table->text('value'); - - $table->foreign('recurrence_id')->references('id')->on('recurrences')->onDelete('cascade'); - } + $table->foreign('recurrence_id')->references('id')->on('recurrences')->onDelete('cascade'); + } ); Schema::create( - 'rt_meta', function (Blueprint $table) { - $table->increments('id'); - $table->timestamps(); - $table->softDeletes(); - $table->integer('rt_id', false, true); + 'recurrences_meta', static function (Blueprint $table) { + $table->increments('id'); + $table->timestamps(); + $table->softDeletes(); + $table->integer('recurrence_id', false, true); - $table->string('name', 50); - $table->text('value'); + $table->string('name', 50); + $table->text('value'); - $table->foreign('rt_id')->references('id')->on('recurrences_transactions')->onDelete('cascade'); - } + $table->foreign('recurrence_id')->references('id')->on('recurrences')->onDelete('cascade'); + } ); + Schema::create( + 'rt_meta', static function (Blueprint $table) { + $table->increments('id'); + $table->timestamps(); + $table->softDeletes(); + $table->integer('rt_id', false, true); + $table->string('name', 50); + $table->text('value'); + + $table->foreign('rt_id')->references('id')->on('recurrences_transactions')->onDelete('cascade'); + } + ); } } diff --git a/database/migrations/2018_09_05_195147_changes_for_v477.php b/database/migrations/2018_09_05_195147_changes_for_v477.php index 71721ea716..df7d51352f 100644 --- a/database/migrations/2018_09_05_195147_changes_for_v477.php +++ b/database/migrations/2018_09_05_195147_changes_for_v477.php @@ -2,7 +2,7 @@ /** * 2018_09_05_195147_changes_for_v477.php - * Copyright (c) 2019 james@firefly-iii.org + * Copyright (c) 2019 james@firefly-iii.org. * * This file is part of Firefly III (https://github.com/firefly-iii). * @@ -26,8 +26,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; /** - * - * Class ChangesForV477 + * Class ChangesForV477. */ class ChangesForV477 extends Migration { @@ -39,15 +38,15 @@ class ChangesForV477 extends Migration public function down(): void { Schema::table( - 'budget_limits', function (Blueprint $table) { + 'budget_limits', static function (Blueprint $table) { // cannot drop foreign keys in SQLite: - if ('sqlite' !== config('database.default')) { - $table->dropForeign('budget_limits_transaction_currency_id_foreign'); - } + if ('sqlite' !== config('database.default')) { + $table->dropForeign('budget_limits_transaction_currency_id_foreign'); + } - $table->dropColumn(['transaction_currency_id']); - } + $table->dropColumn(['transaction_currency_id']); + } ); } @@ -61,7 +60,7 @@ class ChangesForV477 extends Migration { Schema::table( 'budget_limits', - function (Blueprint $table) { + static function (Blueprint $table) { $table->integer('transaction_currency_id', false, true)->nullable()->after('budget_id'); $table->foreign('transaction_currency_id')->references('id')->on('transaction_currencies')->onDelete('set null'); } diff --git a/database/migrations/2018_11_06_172532_changes_for_v479.php b/database/migrations/2018_11_06_172532_changes_for_v479.php index 592a6efc04..2046f6c366 100644 --- a/database/migrations/2018_11_06_172532_changes_for_v479.php +++ b/database/migrations/2018_11_06_172532_changes_for_v479.php @@ -2,7 +2,7 @@ /** * 2018_11_06_172532_changes_for_v479.php - * Copyright (c) 2019 james@firefly-iii.org + * Copyright (c) 2019 james@firefly-iii.org. * * This file is part of Firefly III (https://github.com/firefly-iii). * @@ -26,7 +26,7 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; /** - * Class ChangesForV479 + * Class ChangesForV479. */ class ChangesForV479 extends Migration { @@ -38,9 +38,9 @@ class ChangesForV479 extends Migration public function down() { Schema::table( - 'transaction_currencies', function (Blueprint $table) { - $table->dropColumn(['enabled']); - } + 'transaction_currencies', static function (Blueprint $table) { + $table->dropColumn(['enabled']); + } ); } @@ -54,7 +54,7 @@ class ChangesForV479 extends Migration { Schema::table( 'transaction_currencies', - function (Blueprint $table) { + static function (Blueprint $table) { $table->boolean('enabled')->default(0)->after('deleted_at'); } ); diff --git a/database/migrations/2019_01_28_193833_changes_for_v4710.php b/database/migrations/2019_01_28_193833_changes_for_v4710.php index 1bd5baad6d..fd960fd021 100644 --- a/database/migrations/2019_01_28_193833_changes_for_v4710.php +++ b/database/migrations/2019_01_28_193833_changes_for_v4710.php @@ -2,7 +2,7 @@ /** * 2019_01_28_193833_changes_for_v4710.php - * Copyright (c) 2019 james@firefly-iii.org + * Copyright (c) 2019 james@firefly-iii.org. * * This file is part of Firefly III (https://github.com/firefly-iii). * @@ -49,23 +49,22 @@ class ChangesForV4710 extends Migration { if (!Schema::hasTable('transaction_groups')) { Schema::create( - 'transaction_groups', function (Blueprint $table) { - $table->increments('id'); - $table->timestamps(); - $table->softDeletes(); - $table->integer('user_id', false, true); - $table->string('title', 1024)->nullable(); + 'transaction_groups', static function (Blueprint $table) { + $table->increments('id'); + $table->timestamps(); + $table->softDeletes(); + $table->integer('user_id', false, true); + $table->string('title', 1024)->nullable(); - - $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); - } + $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); + } ); } if (!Schema::hasTable('group_journals')) { Schema::create( 'group_journals', - function (Blueprint $table) { + static function (Blueprint $table) { $table->increments('id'); $table->integer('transaction_group_id', false, true); $table->integer('transaction_journal_id', false, true); @@ -78,6 +77,5 @@ class ChangesForV4710 extends Migration } ); } - } } diff --git a/database/migrations/2019_02_05_055516_changes_for_v4711.php b/database/migrations/2019_02_05_055516_changes_for_v4711.php index f50a4d9a4d..7a2aef0d81 100644 --- a/database/migrations/2019_02_05_055516_changes_for_v4711.php +++ b/database/migrations/2019_02_05_055516_changes_for_v4711.php @@ -2,7 +2,7 @@ /** * 2019_02_05_055516_changes_for_v4711.php - * Copyright (c) 2019 james@firefly-iii.org + * Copyright (c) 2019 james@firefly-iii.org. * * This file is part of Firefly III (https://github.com/firefly-iii). * @@ -55,15 +55,15 @@ class ChangesForV4711 extends Migration * nice. */ Schema::table( - 'transaction_journals', function (Blueprint $table) { - $table->dateTime('date')->change(); - } + 'transaction_journals', static function (Blueprint $table) { + $table->dateTime('date')->change(); + } ); Schema::table( - 'preferences', function (Blueprint $table) { - $table->text('data')->nullable()->change(); - } + 'preferences', static function (Blueprint $table) { + $table->text('data')->nullable()->change(); + } ); } } diff --git a/database/migrations/2019_02_11_170529_changes_for_v4712.php b/database/migrations/2019_02_11_170529_changes_for_v4712.php index 9e47f51f08..3080fe9244 100644 --- a/database/migrations/2019_02_11_170529_changes_for_v4712.php +++ b/database/migrations/2019_02_11_170529_changes_for_v4712.php @@ -1,7 +1,7 @@ dateTime('date')->change(); - } + 'transaction_journals', static function (Blueprint $table) { + $table->dateTime('date')->change(); + } ); } } diff --git a/database/migrations/2019_03_11_223700_fix_ldap_configuration.php b/database/migrations/2019_03_11_223700_fix_ldap_configuration.php index 1fd82f69e5..9c39bc5039 100644 --- a/database/migrations/2019_03_11_223700_fix_ldap_configuration.php +++ b/database/migrations/2019_03_11_223700_fix_ldap_configuration.php @@ -1,7 +1,7 @@ dropColumn(['objectguid']); - } + 'users', static function (Blueprint $table) { + $table->dropColumn(['objectguid']); + } ); } @@ -58,9 +57,9 @@ class FixLdapConfiguration extends Migration * now. To support this, we add the column. */ Schema::table( - 'users', function (Blueprint $table) { - $table->uuid('objectguid')->nullable()->after('id'); - } + 'users', static function (Blueprint $table) { + $table->uuid('objectguid')->nullable()->after('id'); + } ); } } diff --git a/database/migrations/2019_03_22_183214_changes_for_v480.php b/database/migrations/2019_03_22_183214_changes_for_v480.php index 476631b69f..0dce8bde88 100644 --- a/database/migrations/2019_03_22_183214_changes_for_v480.php +++ b/database/migrations/2019_03_22_183214_changes_for_v480.php @@ -1,7 +1,7 @@ dropColumn('stop_processing'); - } + $table->dropColumn('stop_processing'); + } ); Schema::table( 'users', static function (Blueprint $table) { - $table->dropColumn('mfa_secret'); - } + $table->dropColumn('mfa_secret'); + } ); } @@ -69,11 +68,9 @@ class ChangesForV480 extends Migration */ public function up(): void { - Schema::table( 'transaction_journals', static function (Blueprint $table) { - $table->integer('transaction_currency_id', false, true)->nullable()->change(); // add column "group_id" after "transaction_type_id" @@ -86,13 +83,13 @@ class ChangesForV480 extends Migration ); Schema::table( 'rule_groups', static function (Blueprint $table) { - $table->boolean('stop_processing')->default(false); - } + $table->boolean('stop_processing')->default(false); + } ); Schema::table( 'users', static function (Blueprint $table) { - $table->string('mfa_secret', 50)->nullable(); - } + $table->string('mfa_secret', 50)->nullable(); + } ); } } diff --git a/database/migrations/2019_12_28_191351_make_locations_table.php b/database/migrations/2019_12_28_191351_make_locations_table.php index 3feec1f173..4b8cc8359b 100644 --- a/database/migrations/2019_12_28_191351_make_locations_table.php +++ b/database/migrations/2019_12_28_191351_make_locations_table.php @@ -2,7 +2,7 @@ /** * 2019_12_28_191351_make_locations_table.php - * Copyright (c) 2020 james@firefly-iii.org + * Copyright (c) 2020 james@firefly-iii.org. * * This file is part of Firefly III (https://github.com/firefly-iii). * @@ -27,7 +27,7 @@ use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; /** - * Class MakeLocationsTable + * Class MakeLocationsTable. */ class MakeLocationsTable extends Migration { @@ -50,17 +50,17 @@ class MakeLocationsTable extends Migration { Schema::create( 'locations', static function (Blueprint $table) { - $table->bigIncrements('id'); - $table->timestamps(); - $table->softDeletes(); + $table->bigIncrements('id'); + $table->timestamps(); + $table->softDeletes(); - $table->integer('locatable_id', false, true); - $table->string('locatable_type', 255); + $table->integer('locatable_id', false, true); + $table->string('locatable_type', 255); - $table->decimal('latitude', 24, 12)->nullable(); - $table->decimal('longitude', 24, 12)->nullable(); - $table->smallInteger('zoom_level', false, true)->nullable(); - } + $table->decimal('latitude', 24, 12)->nullable(); + $table->decimal('longitude', 24, 12)->nullable(); + $table->smallInteger('zoom_level', false, true)->nullable(); + } ); } } diff --git a/database/migrations/2020_03_13_201950_changes_for_v520.php b/database/migrations/2020_03_13_201950_changes_for_v520.php new file mode 100644 index 0000000000..7fedd4f230 --- /dev/null +++ b/database/migrations/2020_03_13_201950_changes_for_v520.php @@ -0,0 +1,55 @@ +increments('id'); + $table->timestamps(); + $table->softDeletes(); + $table->integer('budget_id', false, true); + $table->integer('transaction_currency_id', false, true); + $table->tinyInteger('auto_budget_type', false, true)->default(1); + $table->decimal('amount', 22, 12); + $table->string('period', 50); + + //$table->string('password', 60); + //$table->string('remember_token', 100)->nullable(); + //$table->string('reset', 32)->nullable(); + //$table->tinyInteger('blocked', false, true)->default('0'); + //$table->string('blocked_code', 25)->nullable(); + + $table->foreign('transaction_currency_id')->references('id')->on('transaction_currencies')->onDelete('cascade'); + $table->foreign('budget_id')->references('id')->on('budgets')->onDelete('cascade'); + } + ); + } + } +} diff --git a/database/seeds/AccountTypeSeeder.php b/database/seeds/AccountTypeSeeder.php index 865f6ff0c6..aa3ca8f5f8 100644 --- a/database/seeds/AccountTypeSeeder.php +++ b/database/seeds/AccountTypeSeeder.php @@ -1,7 +1,7 @@ data = $version; $entry->save(); diff --git a/database/seeds/DatabaseSeeder.php b/database/seeds/DatabaseSeeder.php index 6f61975e7f..d3801a62b1 100644 --- a/database/seeds/DatabaseSeeder.php +++ b/database/seeds/DatabaseSeeder.php @@ -1,7 +1,7 @@ 0&&e-1 in t)}C.fn=C.prototype={jquery:"3.4.1",constructor:C,length:0,toArray:function(){return l.call(this)},get:function(t){return null==t?l.call(this):t<0?this[t+this.length]:this[t]},pushStack:function(t){var e=C.merge(this.constructor(),t);return e.prevObject=this,e},each:function(t){return C.each(this,t)},map:function(t){return this.pushStack(C.map(this,(function(e,n){return t.call(e,n,e)})))},slice:function(){return this.pushStack(l.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(t){var e=this.length,n=+t+(t<0?e:0);return this.pushStack(n>=0&&n+~]|"+q+")"+q+"*"),z=new RegExp(q+"|>"),V=new RegExp(F),Q=new RegExp("^"+H+"$"),X={ID:new RegExp("^#("+H+")"),CLASS:new RegExp("^\\.("+H+")"),TAG:new RegExp("^("+H+"|[*])"),ATTR:new RegExp("^"+M),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+q+"*(even|odd|(([+-]|)(\\d*)n|)"+q+"*(?:([+-]|)"+q+"*(\\d+)|))"+q+"*\\)|)","i"),bool:new RegExp("^(?:"+P+")$","i"),needsContext:new RegExp("^"+q+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+q+"*((?:-\\d)?\\d*)"+q+"*\\)|)(?=[^-]|$)","i")},G=/HTML$/i,Y=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,tt=/[+~]/,et=new RegExp("\\\\([\\da-f]{1,6}"+q+"?|("+q+")|.)","ig"),nt=function(t,e,n){var i="0x"+e-65536;return i!=i||n?e:i<0?String.fromCharCode(i+65536):String.fromCharCode(i>>10|55296,1023&i|56320)},it=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ot=function(t,e){return e?"\0"===t?"�":t.slice(0,-1)+"\\"+t.charCodeAt(t.length-1).toString(16)+" ":"\\"+t},rt=function(){p()},st=xt((function(t){return!0===t.disabled&&"fieldset"===t.nodeName.toLowerCase()}),{dir:"parentNode",next:"legend"});try{I.apply(N=L.call(w.childNodes),w.childNodes),N[w.childNodes.length].nodeType}catch(t){I={apply:N.length?function(t,e){O.apply(t,L.call(e))}:function(t,e){for(var n=t.length,i=0;t[n++]=e[i++];);t.length=n-1}}}function at(t,e,i,o){var r,a,u,c,f,h,m,y=e&&e.ownerDocument,T=e?e.nodeType:9;if(i=i||[],"string"!=typeof t||!t||1!==T&&9!==T&&11!==T)return i;if(!o&&((e?e.ownerDocument||e:w)!==d&&p(e),e=e||d,g)){if(11!==T&&(f=Z.exec(t)))if(r=f[1]){if(9===T){if(!(u=e.getElementById(r)))return i;if(u.id===r)return i.push(u),i}else if(y&&(u=y.getElementById(r))&&b(e,u)&&u.id===r)return i.push(u),i}else{if(f[2])return I.apply(i,e.getElementsByTagName(t)),i;if((r=f[3])&&n.getElementsByClassName&&e.getElementsByClassName)return I.apply(i,e.getElementsByClassName(r)),i}if(n.qsa&&!k[t+" "]&&(!v||!v.test(t))&&(1!==T||"object"!==e.nodeName.toLowerCase())){if(m=t,y=e,1===T&&z.test(t)){for((c=e.getAttribute("id"))?c=c.replace(it,ot):e.setAttribute("id",c=x),a=(h=s(t)).length;a--;)h[a]="#"+c+" "+bt(h[a]);m=h.join(","),y=tt.test(t)&&mt(e.parentNode)||e}try{return I.apply(i,y.querySelectorAll(m)),i}catch(e){k(t,!0)}finally{c===x&&e.removeAttribute("id")}}}return l(t.replace(B,"$1"),e,i,o)}function lt(){var t=[];return function e(n,o){return t.push(n+" ")>i.cacheLength&&delete e[t.shift()],e[n+" "]=o}}function ut(t){return t[x]=!0,t}function ct(t){var e=d.createElement("fieldset");try{return!!t(e)}catch(t){return!1}finally{e.parentNode&&e.parentNode.removeChild(e),e=null}}function ft(t,e){for(var n=t.split("|"),o=n.length;o--;)i.attrHandle[n[o]]=e}function pt(t,e){var n=e&&t,i=n&&1===t.nodeType&&1===e.nodeType&&t.sourceIndex-e.sourceIndex;if(i)return i;if(n)for(;n=n.nextSibling;)if(n===e)return-1;return t?1:-1}function dt(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function ht(t){return function(e){var n=e.nodeName.toLowerCase();return("input"===n||"button"===n)&&e.type===t}}function gt(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&st(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function vt(t){return ut((function(e){return e=+e,ut((function(n,i){for(var o,r=t([],n.length,e),s=r.length;s--;)n[o=r[s]]&&(n[o]=!(i[o]=n[o]))}))}))}function mt(t){return t&&void 0!==t.getElementsByTagName&&t}for(e in n=at.support={},r=at.isXML=function(t){var e=t.namespaceURI,n=(t.ownerDocument||t).documentElement;return!G.test(e||n&&n.nodeName||"HTML")},p=at.setDocument=function(t){var e,o,s=t?t.ownerDocument||t:w;return s!==d&&9===s.nodeType&&s.documentElement?(h=(d=s).documentElement,g=!r(d),w!==d&&(o=d.defaultView)&&o.top!==o&&(o.addEventListener?o.addEventListener("unload",rt,!1):o.attachEvent&&o.attachEvent("onunload",rt)),n.attributes=ct((function(t){return t.className="i",!t.getAttribute("className")})),n.getElementsByTagName=ct((function(t){return t.appendChild(d.createComment("")),!t.getElementsByTagName("*").length})),n.getElementsByClassName=K.test(d.getElementsByClassName),n.getById=ct((function(t){return h.appendChild(t).id=x,!d.getElementsByName||!d.getElementsByName(x).length})),n.getById?(i.filter.ID=function(t){var e=t.replace(et,nt);return function(t){return t.getAttribute("id")===e}},i.find.ID=function(t,e){if(void 0!==e.getElementById&&g){var n=e.getElementById(t);return n?[n]:[]}}):(i.filter.ID=function(t){var e=t.replace(et,nt);return function(t){var n=void 0!==t.getAttributeNode&&t.getAttributeNode("id");return n&&n.value===e}},i.find.ID=function(t,e){if(void 0!==e.getElementById&&g){var n,i,o,r=e.getElementById(t);if(r){if((n=r.getAttributeNode("id"))&&n.value===t)return[r];for(o=e.getElementsByName(t),i=0;r=o[i++];)if((n=r.getAttributeNode("id"))&&n.value===t)return[r]}return[]}}),i.find.TAG=n.getElementsByTagName?function(t,e){return void 0!==e.getElementsByTagName?e.getElementsByTagName(t):n.qsa?e.querySelectorAll(t):void 0}:function(t,e){var n,i=[],o=0,r=e.getElementsByTagName(t);if("*"===t){for(;n=r[o++];)1===n.nodeType&&i.push(n);return i}return r},i.find.CLASS=n.getElementsByClassName&&function(t,e){if(void 0!==e.getElementsByClassName&&g)return e.getElementsByClassName(t)},m=[],v=[],(n.qsa=K.test(d.querySelectorAll))&&(ct((function(t){h.appendChild(t).innerHTML="",t.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+q+"*(?:''|\"\")"),t.querySelectorAll("[selected]").length||v.push("\\["+q+"*(?:value|"+P+")"),t.querySelectorAll("[id~="+x+"-]").length||v.push("~="),t.querySelectorAll(":checked").length||v.push(":checked"),t.querySelectorAll("a#"+x+"+*").length||v.push(".#.+[+~]")})),ct((function(t){t.innerHTML="";var e=d.createElement("input");e.setAttribute("type","hidden"),t.appendChild(e).setAttribute("name","D"),t.querySelectorAll("[name=d]").length&&v.push("name"+q+"*[*^$|!~]?="),2!==t.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),h.appendChild(t).disabled=!0,2!==t.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),t.querySelectorAll("*,:x"),v.push(",.*:")}))),(n.matchesSelector=K.test(y=h.matches||h.webkitMatchesSelector||h.mozMatchesSelector||h.oMatchesSelector||h.msMatchesSelector))&&ct((function(t){n.disconnectedMatch=y.call(t,"*"),y.call(t,"[s!='']:x"),m.push("!=",F)})),v=v.length&&new RegExp(v.join("|")),m=m.length&&new RegExp(m.join("|")),e=K.test(h.compareDocumentPosition),b=e||K.test(h.contains)?function(t,e){var n=9===t.nodeType?t.documentElement:t,i=e&&e.parentNode;return t===i||!(!i||1!==i.nodeType||!(n.contains?n.contains(i):t.compareDocumentPosition&&16&t.compareDocumentPosition(i)))}:function(t,e){if(e)for(;e=e.parentNode;)if(e===t)return!0;return!1},D=e?function(t,e){if(t===e)return f=!0,0;var i=!t.compareDocumentPosition-!e.compareDocumentPosition;return i||(1&(i=(t.ownerDocument||t)===(e.ownerDocument||e)?t.compareDocumentPosition(e):1)||!n.sortDetached&&e.compareDocumentPosition(t)===i?t===d||t.ownerDocument===w&&b(w,t)?-1:e===d||e.ownerDocument===w&&b(w,e)?1:c?R(c,t)-R(c,e):0:4&i?-1:1)}:function(t,e){if(t===e)return f=!0,0;var n,i=0,o=t.parentNode,r=e.parentNode,s=[t],a=[e];if(!o||!r)return t===d?-1:e===d?1:o?-1:r?1:c?R(c,t)-R(c,e):0;if(o===r)return pt(t,e);for(n=t;n=n.parentNode;)s.unshift(n);for(n=e;n=n.parentNode;)a.unshift(n);for(;s[i]===a[i];)i++;return i?pt(s[i],a[i]):s[i]===w?-1:a[i]===w?1:0},d):d},at.matches=function(t,e){return at(t,null,null,e)},at.matchesSelector=function(t,e){if((t.ownerDocument||t)!==d&&p(t),n.matchesSelector&&g&&!k[e+" "]&&(!m||!m.test(e))&&(!v||!v.test(e)))try{var i=y.call(t,e);if(i||n.disconnectedMatch||t.document&&11!==t.document.nodeType)return i}catch(t){k(e,!0)}return at(e,d,null,[t]).length>0},at.contains=function(t,e){return(t.ownerDocument||t)!==d&&p(t),b(t,e)},at.attr=function(t,e){(t.ownerDocument||t)!==d&&p(t);var o=i.attrHandle[e.toLowerCase()],r=o&&A.call(i.attrHandle,e.toLowerCase())?o(t,e,!g):void 0;return void 0!==r?r:n.attributes||!g?t.getAttribute(e):(r=t.getAttributeNode(e))&&r.specified?r.value:null},at.escape=function(t){return(t+"").replace(it,ot)},at.error=function(t){throw new Error("Syntax error, unrecognized expression: "+t)},at.uniqueSort=function(t){var e,i=[],o=0,r=0;if(f=!n.detectDuplicates,c=!n.sortStable&&t.slice(0),t.sort(D),f){for(;e=t[r++];)e===t[r]&&(o=i.push(r));for(;o--;)t.splice(i[o],1)}return c=null,t},o=at.getText=function(t){var e,n="",i=0,r=t.nodeType;if(r){if(1===r||9===r||11===r){if("string"==typeof t.textContent)return t.textContent;for(t=t.firstChild;t;t=t.nextSibling)n+=o(t)}else if(3===r||4===r)return t.nodeValue}else for(;e=t[i++];)n+=o(e);return n},(i=at.selectors={cacheLength:50,createPseudo:ut,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(t){return t[1]=t[1].replace(et,nt),t[3]=(t[3]||t[4]||t[5]||"").replace(et,nt),"~="===t[2]&&(t[3]=" "+t[3]+" "),t.slice(0,4)},CHILD:function(t){return t[1]=t[1].toLowerCase(),"nth"===t[1].slice(0,3)?(t[3]||at.error(t[0]),t[4]=+(t[4]?t[5]+(t[6]||1):2*("even"===t[3]||"odd"===t[3])),t[5]=+(t[7]+t[8]||"odd"===t[3])):t[3]&&at.error(t[0]),t},PSEUDO:function(t){var e,n=!t[6]&&t[2];return X.CHILD.test(t[0])?null:(t[3]?t[2]=t[4]||t[5]||"":n&&V.test(n)&&(e=s(n,!0))&&(e=n.indexOf(")",n.length-e)-n.length)&&(t[0]=t[0].slice(0,e),t[2]=n.slice(0,e)),t.slice(0,3))}},filter:{TAG:function(t){var e=t.replace(et,nt).toLowerCase();return"*"===t?function(){return!0}:function(t){return t.nodeName&&t.nodeName.toLowerCase()===e}},CLASS:function(t){var e=E[t+" "];return e||(e=new RegExp("(^|"+q+")"+t+"("+q+"|$)"))&&E(t,(function(t){return e.test("string"==typeof t.className&&t.className||void 0!==t.getAttribute&&t.getAttribute("class")||"")}))},ATTR:function(t,e,n){return function(i){var o=at.attr(i,t);return null==o?"!="===e:!e||(o+="","="===e?o===n:"!="===e?o!==n:"^="===e?n&&0===o.indexOf(n):"*="===e?n&&o.indexOf(n)>-1:"$="===e?n&&o.slice(-n.length)===n:"~="===e?(" "+o.replace(W," ")+" ").indexOf(n)>-1:"|="===e&&(o===n||o.slice(0,n.length+1)===n+"-"))}},CHILD:function(t,e,n,i,o){var r="nth"!==t.slice(0,3),s="last"!==t.slice(-4),a="of-type"===e;return 1===i&&0===o?function(t){return!!t.parentNode}:function(e,n,l){var u,c,f,p,d,h,g=r!==s?"nextSibling":"previousSibling",v=e.parentNode,m=a&&e.nodeName.toLowerCase(),y=!l&&!a,b=!1;if(v){if(r){for(;g;){for(p=e;p=p[g];)if(a?p.nodeName.toLowerCase()===m:1===p.nodeType)return!1;h=g="only"===t&&!h&&"nextSibling"}return!0}if(h=[s?v.firstChild:v.lastChild],s&&y){for(b=(d=(u=(c=(f=(p=v)[x]||(p[x]={}))[p.uniqueID]||(f[p.uniqueID]={}))[t]||[])[0]===T&&u[1])&&u[2],p=d&&v.childNodes[d];p=++d&&p&&p[g]||(b=d=0)||h.pop();)if(1===p.nodeType&&++b&&p===e){c[t]=[T,d,b];break}}else if(y&&(b=d=(u=(c=(f=(p=e)[x]||(p[x]={}))[p.uniqueID]||(f[p.uniqueID]={}))[t]||[])[0]===T&&u[1]),!1===b)for(;(p=++d&&p&&p[g]||(b=d=0)||h.pop())&&((a?p.nodeName.toLowerCase()!==m:1!==p.nodeType)||!++b||(y&&((c=(f=p[x]||(p[x]={}))[p.uniqueID]||(f[p.uniqueID]={}))[t]=[T,b]),p!==e)););return(b-=o)===i||b%i==0&&b/i>=0}}},PSEUDO:function(t,e){var n,o=i.pseudos[t]||i.setFilters[t.toLowerCase()]||at.error("unsupported pseudo: "+t);return o[x]?o(e):o.length>1?(n=[t,t,"",e],i.setFilters.hasOwnProperty(t.toLowerCase())?ut((function(t,n){for(var i,r=o(t,e),s=r.length;s--;)t[i=R(t,r[s])]=!(n[i]=r[s])})):function(t){return o(t,0,n)}):o}},pseudos:{not:ut((function(t){var e=[],n=[],i=a(t.replace(B,"$1"));return i[x]?ut((function(t,e,n,o){for(var r,s=i(t,null,o,[]),a=t.length;a--;)(r=s[a])&&(t[a]=!(e[a]=r))})):function(t,o,r){return e[0]=t,i(e,null,r,n),e[0]=null,!n.pop()}})),has:ut((function(t){return function(e){return at(t,e).length>0}})),contains:ut((function(t){return t=t.replace(et,nt),function(e){return(e.textContent||o(e)).indexOf(t)>-1}})),lang:ut((function(t){return Q.test(t||"")||at.error("unsupported lang: "+t),t=t.replace(et,nt).toLowerCase(),function(e){var n;do{if(n=g?e.lang:e.getAttribute("xml:lang")||e.getAttribute("lang"))return(n=n.toLowerCase())===t||0===n.indexOf(t+"-")}while((e=e.parentNode)&&1===e.nodeType);return!1}})),target:function(e){var n=t.location&&t.location.hash;return n&&n.slice(1)===e.id},root:function(t){return t===h},focus:function(t){return t===d.activeElement&&(!d.hasFocus||d.hasFocus())&&!!(t.type||t.href||~t.tabIndex)},enabled:gt(!1),disabled:gt(!0),checked:function(t){var e=t.nodeName.toLowerCase();return"input"===e&&!!t.checked||"option"===e&&!!t.selected},selected:function(t){return t.parentNode&&t.parentNode.selectedIndex,!0===t.selected},empty:function(t){for(t=t.firstChild;t;t=t.nextSibling)if(t.nodeType<6)return!1;return!0},parent:function(t){return!i.pseudos.empty(t)},header:function(t){return J.test(t.nodeName)},input:function(t){return Y.test(t.nodeName)},button:function(t){var e=t.nodeName.toLowerCase();return"input"===e&&"button"===t.type||"button"===e},text:function(t){var e;return"input"===t.nodeName.toLowerCase()&&"text"===t.type&&(null==(e=t.getAttribute("type"))||"text"===e.toLowerCase())},first:vt((function(){return[0]})),last:vt((function(t,e){return[e-1]})),eq:vt((function(t,e,n){return[n<0?n+e:n]})),even:vt((function(t,e){for(var n=0;ne?e:n;--i>=0;)t.push(i);return t})),gt:vt((function(t,e,n){for(var i=n<0?n+e:n;++i1?function(e,n,i){for(var o=t.length;o--;)if(!t[o](e,n,i))return!1;return!0}:t[0]}function Tt(t,e,n,i,o){for(var r,s=[],a=0,l=t.length,u=null!=e;a-1&&(r[u]=!(s[u]=f))}}else m=Tt(m===s?m.splice(h,m.length):m),o?o(null,s,m,l):I.apply(s,m)}))}function Et(t){for(var e,n,o,r=t.length,s=i.relative[t[0].type],a=s||i.relative[" "],l=s?1:0,c=xt((function(t){return t===e}),a,!0),f=xt((function(t){return R(e,t)>-1}),a,!0),p=[function(t,n,i){var o=!s&&(i||n!==u)||((e=n).nodeType?c(t,n,i):f(t,n,i));return e=null,o}];l1&&wt(p),l>1&&bt(t.slice(0,l-1).concat({value:" "===t[l-2].type?"*":""})).replace(B,"$1"),n,l0,o=t.length>0,r=function(r,s,a,l,c){var f,h,v,m=0,y="0",b=r&&[],x=[],w=u,C=r||o&&i.find.TAG("*",c),E=T+=null==w?1:Math.random()||.1,S=C.length;for(c&&(u=s===d||s||c);y!==S&&null!=(f=C[y]);y++){if(o&&f){for(h=0,s||f.ownerDocument===d||(p(f),a=!g);v=t[h++];)if(v(f,s||d,a)){l.push(f);break}c&&(T=E)}n&&((f=!v&&f)&&m--,r&&b.push(f))}if(m+=y,n&&y!==m){for(h=0;v=e[h++];)v(b,x,s,a);if(r){if(m>0)for(;y--;)b[y]||x[y]||(x[y]=j.call(l));x=Tt(x)}I.apply(l,x),c&&!r&&x.length>0&&m+e.length>1&&at.uniqueSort(l)}return c&&(T=E,u=w),b};return n?ut(r):r}(r,o))).selector=t}return a},l=at.select=function(t,e,n,o){var r,l,u,c,f,p="function"==typeof t&&t,d=!o&&s(t=p.selector||t);if(n=n||[],1===d.length){if((l=d[0]=d[0].slice(0)).length>2&&"ID"===(u=l[0]).type&&9===e.nodeType&&g&&i.relative[l[1].type]){if(!(e=(i.find.ID(u.matches[0].replace(et,nt),e)||[])[0]))return n;p&&(e=e.parentNode),t=t.slice(l.shift().value.length)}for(r=X.needsContext.test(t)?0:l.length;r--&&(u=l[r],!i.relative[c=u.type]);)if((f=i.find[c])&&(o=f(u.matches[0].replace(et,nt),tt.test(l[0].type)&&mt(e.parentNode)||e))){if(l.splice(r,1),!(t=o.length&&bt(l)))return I.apply(n,o),n;break}}return(p||a(t,d))(o,e,!g,n,!e||tt.test(t)&&mt(e.parentNode)||e),n},n.sortStable=x.split("").sort(D).join("")===x,n.detectDuplicates=!!f,p(),n.sortDetached=ct((function(t){return 1&t.compareDocumentPosition(d.createElement("fieldset"))})),ct((function(t){return t.innerHTML="","#"===t.firstChild.getAttribute("href")}))||ft("type|href|height|width",(function(t,e,n){if(!n)return t.getAttribute(e,"type"===e.toLowerCase()?1:2)})),n.attributes&&ct((function(t){return t.innerHTML="",t.firstChild.setAttribute("value",""),""===t.firstChild.getAttribute("value")}))||ft("value",(function(t,e,n){if(!n&&"input"===t.nodeName.toLowerCase())return t.defaultValue})),ct((function(t){return null==t.getAttribute("disabled")}))||ft(P,(function(t,e,n){var i;if(!n)return!0===t[e]?e.toLowerCase():(i=t.getAttributeNode(e))&&i.specified?i.value:null})),at}(n);C.find=$,C.expr=$.selectors,C.expr[":"]=C.expr.pseudos,C.uniqueSort=C.unique=$.uniqueSort,C.text=$.getText,C.isXMLDoc=$.isXML,C.contains=$.contains,C.escapeSelector=$.escape;var k=function(t,e,n){for(var i=[],o=void 0!==n;(t=t[e])&&9!==t.nodeType;)if(1===t.nodeType){if(o&&C(t).is(n))break;i.push(t)}return i},D=function(t,e){for(var n=[];t;t=t.nextSibling)1===t.nodeType&&t!==e&&n.push(t);return n},A=C.expr.match.needsContext;function N(t,e){return t.nodeName&&t.nodeName.toLowerCase()===e.toLowerCase()}var j=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function O(t,e,n){return y(e)?C.grep(t,(function(t,i){return!!e.call(t,i,t)!==n})):e.nodeType?C.grep(t,(function(t){return t===e!==n})):"string"!=typeof e?C.grep(t,(function(t){return f.call(e,t)>-1!==n})):C.filter(e,t,n)}C.filter=function(t,e,n){var i=e[0];return n&&(t=":not("+t+")"),1===e.length&&1===i.nodeType?C.find.matchesSelector(i,t)?[i]:[]:C.find.matches(t,C.grep(e,(function(t){return 1===t.nodeType})))},C.fn.extend({find:function(t){var e,n,i=this.length,o=this;if("string"!=typeof t)return this.pushStack(C(t).filter((function(){for(e=0;e1?C.uniqueSort(n):n},filter:function(t){return this.pushStack(O(this,t||[],!1))},not:function(t){return this.pushStack(O(this,t||[],!0))},is:function(t){return!!O(this,"string"==typeof t&&A.test(t)?C(t):t||[],!1).length}});var I,L=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/;(C.fn.init=function(t,e,n){var i,o;if(!t)return this;if(n=n||I,"string"==typeof t){if(!(i="<"===t[0]&&">"===t[t.length-1]&&t.length>=3?[null,t,null]:L.exec(t))||!i[1]&&e)return!e||e.jquery?(e||n).find(t):this.constructor(e).find(t);if(i[1]){if(e=e instanceof C?e[0]:e,C.merge(this,C.parseHTML(i[1],e&&e.nodeType?e.ownerDocument||e:s,!0)),j.test(i[1])&&C.isPlainObject(e))for(i in e)y(this[i])?this[i](e[i]):this.attr(i,e[i]);return this}return(o=s.getElementById(i[2]))&&(this[0]=o,this.length=1),this}return t.nodeType?(this[0]=t,this.length=1,this):y(t)?void 0!==n.ready?n.ready(t):t(C):C.makeArray(t,this)}).prototype=C.fn,I=C(s);var R=/^(?:parents|prev(?:Until|All))/,P={children:!0,contents:!0,next:!0,prev:!0};function q(t,e){for(;(t=t[e])&&1!==t.nodeType;);return t}C.fn.extend({has:function(t){var e=C(t,this),n=e.length;return this.filter((function(){for(var t=0;t-1:1===n.nodeType&&C.find.matchesSelector(n,t))){r.push(n);break}return this.pushStack(r.length>1?C.uniqueSort(r):r)},index:function(t){return t?"string"==typeof t?f.call(C(t),this[0]):f.call(this,t.jquery?t[0]:t):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(t,e){return this.pushStack(C.uniqueSort(C.merge(this.get(),C(t,e))))},addBack:function(t){return this.add(null==t?this.prevObject:this.prevObject.filter(t))}}),C.each({parent:function(t){var e=t.parentNode;return e&&11!==e.nodeType?e:null},parents:function(t){return k(t,"parentNode")},parentsUntil:function(t,e,n){return k(t,"parentNode",n)},next:function(t){return q(t,"nextSibling")},prev:function(t){return q(t,"previousSibling")},nextAll:function(t){return k(t,"nextSibling")},prevAll:function(t){return k(t,"previousSibling")},nextUntil:function(t,e,n){return k(t,"nextSibling",n)},prevUntil:function(t,e,n){return k(t,"previousSibling",n)},siblings:function(t){return D((t.parentNode||{}).firstChild,t)},children:function(t){return D(t.firstChild)},contents:function(t){return void 0!==t.contentDocument?t.contentDocument:(N(t,"template")&&(t=t.content||t),C.merge([],t.childNodes))}},(function(t,e){C.fn[t]=function(n,i){var o=C.map(this,e,n);return"Until"!==t.slice(-5)&&(i=n),i&&"string"==typeof i&&(o=C.filter(i,o)),this.length>1&&(P[t]||C.uniqueSort(o),R.test(t)&&o.reverse()),this.pushStack(o)}}));var H=/[^\x20\t\r\n\f]+/g;function M(t){return t}function F(t){throw t}function W(t,e,n,i){var o;try{t&&y(o=t.promise)?o.call(t).done(e).fail(n):t&&y(o=t.then)?o.call(t,e,n):e.apply(void 0,[t].slice(i))}catch(t){n.apply(void 0,[t])}}C.Callbacks=function(t){t="string"==typeof t?function(t){var e={};return C.each(t.match(H)||[],(function(t,n){e[n]=!0})),e}(t):C.extend({},t);var e,n,i,o,r=[],s=[],a=-1,l=function(){for(o=o||t.once,i=e=!0;s.length;a=-1)for(n=s.shift();++a-1;)r.splice(n,1),n<=a&&a--})),this},has:function(t){return t?C.inArray(t,r)>-1:r.length>0},empty:function(){return r&&(r=[]),this},disable:function(){return o=s=[],r=n="",this},disabled:function(){return!r},lock:function(){return o=s=[],n||e||(r=n=""),this},locked:function(){return!!o},fireWith:function(t,n){return o||(n=[t,(n=n||[]).slice?n.slice():n],s.push(n),e||l()),this},fire:function(){return u.fireWith(this,arguments),this},fired:function(){return!!i}};return u},C.extend({Deferred:function(t){var e=[["notify","progress",C.Callbacks("memory"),C.Callbacks("memory"),2],["resolve","done",C.Callbacks("once memory"),C.Callbacks("once memory"),0,"resolved"],["reject","fail",C.Callbacks("once memory"),C.Callbacks("once memory"),1,"rejected"]],i="pending",o={state:function(){return i},always:function(){return r.done(arguments).fail(arguments),this},catch:function(t){return o.then(null,t)},pipe:function(){var t=arguments;return C.Deferred((function(n){C.each(e,(function(e,i){var o=y(t[i[4]])&&t[i[4]];r[i[1]]((function(){var t=o&&o.apply(this,arguments);t&&y(t.promise)?t.promise().progress(n.notify).done(n.resolve).fail(n.reject):n[i[0]+"With"](this,o?[t]:arguments)}))})),t=null})).promise()},then:function(t,i,o){var r=0;function s(t,e,i,o){return function(){var a=this,l=arguments,u=function(){var n,u;if(!(t=r&&(i!==F&&(a=void 0,l=[n]),e.rejectWith(a,l))}};t?c():(C.Deferred.getStackHook&&(c.stackTrace=C.Deferred.getStackHook()),n.setTimeout(c))}}return C.Deferred((function(n){e[0][3].add(s(0,n,y(o)?o:M,n.notifyWith)),e[1][3].add(s(0,n,y(t)?t:M)),e[2][3].add(s(0,n,y(i)?i:F))})).promise()},promise:function(t){return null!=t?C.extend(t,o):o}},r={};return C.each(e,(function(t,n){var s=n[2],a=n[5];o[n[1]]=s.add,a&&s.add((function(){i=a}),e[3-t][2].disable,e[3-t][3].disable,e[0][2].lock,e[0][3].lock),s.add(n[3].fire),r[n[0]]=function(){return r[n[0]+"With"](this===r?void 0:this,arguments),this},r[n[0]+"With"]=s.fireWith})),o.promise(r),t&&t.call(r,r),r},when:function(t){var e=arguments.length,n=e,i=Array(n),o=l.call(arguments),r=C.Deferred(),s=function(t){return function(n){i[t]=this,o[t]=arguments.length>1?l.call(arguments):n,--e||r.resolveWith(i,o)}};if(e<=1&&(W(t,r.done(s(n)).resolve,r.reject,!e),"pending"===r.state()||y(o[n]&&o[n].then)))return r.then();for(;n--;)W(o[n],s(n),r.reject);return r.promise()}});var B=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;C.Deferred.exceptionHook=function(t,e){n.console&&n.console.warn&&t&&B.test(t.name)&&n.console.warn("jQuery.Deferred exception: "+t.message,t.stack,e)},C.readyException=function(t){n.setTimeout((function(){throw t}))};var _=C.Deferred();function U(){s.removeEventListener("DOMContentLoaded",U),n.removeEventListener("load",U),C.ready()}C.fn.ready=function(t){return _.then(t).catch((function(t){C.readyException(t)})),this},C.extend({isReady:!1,readyWait:1,ready:function(t){(!0===t?--C.readyWait:C.isReady)||(C.isReady=!0,!0!==t&&--C.readyWait>0||_.resolveWith(s,[C]))}}),C.ready.then=_.then,"complete"===s.readyState||"loading"!==s.readyState&&!s.documentElement.doScroll?n.setTimeout(C.ready):(s.addEventListener("DOMContentLoaded",U),n.addEventListener("load",U));var z=function(t,e,n,i,o,r,s){var a=0,l=t.length,u=null==n;if("object"===T(n))for(a in o=!0,n)z(t,e,a,n[a],!0,r,s);else if(void 0!==i&&(o=!0,y(i)||(s=!0),u&&(s?(e.call(t,i),e=null):(u=e,e=function(t,e,n){return u.call(C(t),n)})),e))for(;a1,null,!0)},removeData:function(t){return this.each((function(){Z.remove(this,t)}))}}),C.extend({queue:function(t,e,n){var i;if(t)return e=(e||"fx")+"queue",i=K.get(t,e),n&&(!i||Array.isArray(n)?i=K.access(t,e,C.makeArray(n)):i.push(n)),i||[]},dequeue:function(t,e){e=e||"fx";var n=C.queue(t,e),i=n.length,o=n.shift(),r=C._queueHooks(t,e);"inprogress"===o&&(o=n.shift(),i--),o&&("fx"===e&&n.unshift("inprogress"),delete r.stop,o.call(t,(function(){C.dequeue(t,e)}),r)),!i&&r&&r.empty.fire()},_queueHooks:function(t,e){var n=e+"queueHooks";return K.get(t,n)||K.access(t,n,{empty:C.Callbacks("once memory").add((function(){K.remove(t,[e+"queue",n])}))})}}),C.fn.extend({queue:function(t,e){var n=2;return"string"!=typeof t&&(e=t,t="fx",n--),arguments.length\x20\t\r\n\f]*)/i,mt=/^$|^module$|\/(?:java|ecma)script/i,yt={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};function bt(t,e){var n;return n=void 0!==t.getElementsByTagName?t.getElementsByTagName(e||"*"):void 0!==t.querySelectorAll?t.querySelectorAll(e||"*"):[],void 0===e||e&&N(t,e)?C.merge([t],n):n}function xt(t,e){for(var n=0,i=t.length;n-1)o&&o.push(r);else if(u=at(r),s=bt(f.appendChild(r),"script"),u&&xt(s),n)for(c=0;r=s[c++];)mt.test(r.type||"")&&n.push(r);return f}wt=s.createDocumentFragment().appendChild(s.createElement("div")),(Tt=s.createElement("input")).setAttribute("type","radio"),Tt.setAttribute("checked","checked"),Tt.setAttribute("name","t"),wt.appendChild(Tt),m.checkClone=wt.cloneNode(!0).cloneNode(!0).lastChild.checked,wt.innerHTML="",m.noCloneChecked=!!wt.cloneNode(!0).lastChild.defaultValue;var St=/^key/,$t=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,kt=/^([^.]*)(?:\.(.+)|)/;function Dt(){return!0}function At(){return!1}function Nt(t,e){return t===function(){try{return s.activeElement}catch(t){}}()==("focus"===e)}function jt(t,e,n,i,o,r){var s,a;if("object"==typeof e){for(a in"string"!=typeof n&&(i=i||n,n=void 0),e)jt(t,a,n,i,e[a],r);return t}if(null==i&&null==o?(o=n,i=n=void 0):null==o&&("string"==typeof n?(o=i,i=void 0):(o=i,i=n,n=void 0)),!1===o)o=At;else if(!o)return t;return 1===r&&(s=o,(o=function(t){return C().off(t),s.apply(this,arguments)}).guid=s.guid||(s.guid=C.guid++)),t.each((function(){C.event.add(this,e,o,i,n)}))}function Ot(t,e,n){n?(K.set(t,e,!1),C.event.add(t,e,{namespace:!1,handler:function(t){var i,o,r=K.get(this,e);if(1&t.isTrigger&&this[e]){if(r.length)(C.event.special[e]||{}).delegateType&&t.stopPropagation();else if(r=l.call(arguments),K.set(this,e,r),i=n(this,e),this[e](),r!==(o=K.get(this,e))||i?K.set(this,e,!1):o={},r!==o)return t.stopImmediatePropagation(),t.preventDefault(),o.value}else r.length&&(K.set(this,e,{value:C.event.trigger(C.extend(r[0],C.Event.prototype),r.slice(1),this)}),t.stopImmediatePropagation())}})):void 0===K.get(t,e)&&C.event.add(t,e,Dt)}C.event={global:{},add:function(t,e,n,i,o){var r,s,a,l,u,c,f,p,d,h,g,v=K.get(t);if(v)for(n.handler&&(n=(r=n).handler,o=r.selector),o&&C.find.matchesSelector(st,o),n.guid||(n.guid=C.guid++),(l=v.events)||(l=v.events={}),(s=v.handle)||(s=v.handle=function(e){return void 0!==C&&C.event.triggered!==e.type?C.event.dispatch.apply(t,arguments):void 0}),u=(e=(e||"").match(H)||[""]).length;u--;)d=g=(a=kt.exec(e[u])||[])[1],h=(a[2]||"").split(".").sort(),d&&(f=C.event.special[d]||{},d=(o?f.delegateType:f.bindType)||d,f=C.event.special[d]||{},c=C.extend({type:d,origType:g,data:i,handler:n,guid:n.guid,selector:o,needsContext:o&&C.expr.match.needsContext.test(o),namespace:h.join(".")},r),(p=l[d])||((p=l[d]=[]).delegateCount=0,f.setup&&!1!==f.setup.call(t,i,h,s)||t.addEventListener&&t.addEventListener(d,s)),f.add&&(f.add.call(t,c),c.handler.guid||(c.handler.guid=n.guid)),o?p.splice(p.delegateCount++,0,c):p.push(c),C.event.global[d]=!0)},remove:function(t,e,n,i,o){var r,s,a,l,u,c,f,p,d,h,g,v=K.hasData(t)&&K.get(t);if(v&&(l=v.events)){for(u=(e=(e||"").match(H)||[""]).length;u--;)if(d=g=(a=kt.exec(e[u])||[])[1],h=(a[2]||"").split(".").sort(),d){for(f=C.event.special[d]||{},p=l[d=(i?f.delegateType:f.bindType)||d]||[],a=a[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),s=r=p.length;r--;)c=p[r],!o&&g!==c.origType||n&&n.guid!==c.guid||a&&!a.test(c.namespace)||i&&i!==c.selector&&("**"!==i||!c.selector)||(p.splice(r,1),c.selector&&p.delegateCount--,f.remove&&f.remove.call(t,c));s&&!p.length&&(f.teardown&&!1!==f.teardown.call(t,h,v.handle)||C.removeEvent(t,d,v.handle),delete l[d])}else for(d in l)C.event.remove(t,d+e[u],n,i,!0);C.isEmptyObject(l)&&K.remove(t,"handle events")}},dispatch:function(t){var e,n,i,o,r,s,a=C.event.fix(t),l=new Array(arguments.length),u=(K.get(this,"events")||{})[a.type]||[],c=C.event.special[a.type]||{};for(l[0]=a,e=1;e=1))for(;u!==this;u=u.parentNode||this)if(1===u.nodeType&&("click"!==t.type||!0!==u.disabled)){for(r=[],s={},n=0;n-1:C.find(o,this,null,[u]).length),s[o]&&r.push(i);r.length&&a.push({elem:u,handlers:r})}return u=this,l\x20\t\r\n\f]*)[^>]*)\/>/gi,Lt=/\s*$/g;function qt(t,e){return N(t,"table")&&N(11!==e.nodeType?e:e.firstChild,"tr")&&C(t).children("tbody")[0]||t}function Ht(t){return t.type=(null!==t.getAttribute("type"))+"/"+t.type,t}function Mt(t){return"true/"===(t.type||"").slice(0,5)?t.type=t.type.slice(5):t.removeAttribute("type"),t}function Ft(t,e){var n,i,o,r,s,a,l,u;if(1===e.nodeType){if(K.hasData(t)&&(r=K.access(t),s=K.set(e,r),u=r.events))for(o in delete s.handle,s.events={},u)for(n=0,i=u[o].length;n1&&"string"==typeof h&&!m.checkClone&&Rt.test(h))return t.each((function(o){var r=t.eq(o);g&&(e[0]=h.call(this,o,r.html())),Bt(r,e,n,i)}));if(p&&(r=(o=Et(e,t[0].ownerDocument,!1,t,i)).firstChild,1===o.childNodes.length&&(o=r),r||i)){for(a=(s=C.map(bt(o,"script"),Ht)).length;f")},clone:function(t,e,n){var i,o,r,s,a=t.cloneNode(!0),l=at(t);if(!(m.noCloneChecked||1!==t.nodeType&&11!==t.nodeType||C.isXMLDoc(t)))for(s=bt(a),i=0,o=(r=bt(t)).length;i0&&xt(s,!l&&bt(t,"script")),a},cleanData:function(t){for(var e,n,i,o=C.event.special,r=0;void 0!==(n=t[r]);r++)if(Y(n)){if(e=n[K.expando]){if(e.events)for(i in e.events)o[i]?C.event.remove(n,i):C.removeEvent(n,i,e.handle);n[K.expando]=void 0}n[Z.expando]&&(n[Z.expando]=void 0)}}}),C.fn.extend({detach:function(t){return _t(this,t,!0)},remove:function(t){return _t(this,t)},text:function(t){return z(this,(function(t){return void 0===t?C.text(this):this.empty().each((function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=t)}))}),null,t,arguments.length)},append:function(){return Bt(this,arguments,(function(t){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||qt(this,t).appendChild(t)}))},prepend:function(){return Bt(this,arguments,(function(t){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var e=qt(this,t);e.insertBefore(t,e.firstChild)}}))},before:function(){return Bt(this,arguments,(function(t){this.parentNode&&this.parentNode.insertBefore(t,this)}))},after:function(){return Bt(this,arguments,(function(t){this.parentNode&&this.parentNode.insertBefore(t,this.nextSibling)}))},empty:function(){for(var t,e=0;null!=(t=this[e]);e++)1===t.nodeType&&(C.cleanData(bt(t,!1)),t.textContent="");return this},clone:function(t,e){return t=null!=t&&t,e=null==e?t:e,this.map((function(){return C.clone(this,t,e)}))},html:function(t){return z(this,(function(t){var e=this[0]||{},n=0,i=this.length;if(void 0===t&&1===e.nodeType)return e.innerHTML;if("string"==typeof t&&!Lt.test(t)&&!yt[(vt.exec(t)||["",""])[1].toLowerCase()]){t=C.htmlPrefilter(t);try{for(;n=0&&(l+=Math.max(0,Math.ceil(t["offset"+e[0].toUpperCase()+e.slice(1)]-r-l-a-.5))||0),l}function re(t,e,n){var i=zt(t),o=(!m.boxSizingReliable()||n)&&"border-box"===C.css(t,"boxSizing",!1,i),r=o,s=Qt(t,e,i),a="offset"+e[0].toUpperCase()+e.slice(1);if(Ut.test(s)){if(!n)return s;s="auto"}return(!m.boxSizingReliable()&&o||"auto"===s||!parseFloat(s)&&"inline"===C.css(t,"display",!1,i))&&t.getClientRects().length&&(o="border-box"===C.css(t,"boxSizing",!1,i),(r=a in t)&&(s=t[a])),(s=parseFloat(s)||0)+oe(t,e,n||(o?"border":"content"),r,i,s)+"px"}function se(t,e,n,i,o){return new se.prototype.init(t,e,n,i,o)}C.extend({cssHooks:{opacity:{get:function(t,e){if(e){var n=Qt(t,"opacity");return""===n?"1":n}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,gridArea:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnStart:!0,gridRow:!0,gridRowEnd:!0,gridRowStart:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{},style:function(t,e,n,i){if(t&&3!==t.nodeType&&8!==t.nodeType&&t.style){var o,r,s,a=G(e),l=te.test(e),u=t.style;if(l||(e=Kt(a)),s=C.cssHooks[e]||C.cssHooks[a],void 0===n)return s&&"get"in s&&void 0!==(o=s.get(t,!1,i))?o:u[e];"string"===(r=typeof n)&&(o=ot.exec(n))&&o[1]&&(n=ft(t,e,o),r="number"),null!=n&&n==n&&("number"!==r||l||(n+=o&&o[3]||(C.cssNumber[a]?"":"px")),m.clearCloneStyle||""!==n||0!==e.indexOf("background")||(u[e]="inherit"),s&&"set"in s&&void 0===(n=s.set(t,n,i))||(l?u.setProperty(e,n):u[e]=n))}},css:function(t,e,n,i){var o,r,s,a=G(e);return te.test(e)||(e=Kt(a)),(s=C.cssHooks[e]||C.cssHooks[a])&&"get"in s&&(o=s.get(t,!0,n)),void 0===o&&(o=Qt(t,e,i)),"normal"===o&&e in ne&&(o=ne[e]),""===n||n?(r=parseFloat(o),!0===n||isFinite(r)?r||0:o):o}}),C.each(["height","width"],(function(t,e){C.cssHooks[e]={get:function(t,n,i){if(n)return!Zt.test(C.css(t,"display"))||t.getClientRects().length&&t.getBoundingClientRect().width?re(t,e,i):ct(t,ee,(function(){return re(t,e,i)}))},set:function(t,n,i){var o,r=zt(t),s=!m.scrollboxSize()&&"absolute"===r.position,a=(s||i)&&"border-box"===C.css(t,"boxSizing",!1,r),l=i?oe(t,e,i,a,r):0;return a&&s&&(l-=Math.ceil(t["offset"+e[0].toUpperCase()+e.slice(1)]-parseFloat(r[e])-oe(t,e,"border",!1,r)-.5)),l&&(o=ot.exec(n))&&"px"!==(o[3]||"px")&&(t.style[e]=n,n=C.css(t,e)),ie(0,n,l)}}})),C.cssHooks.marginLeft=Xt(m.reliableMarginLeft,(function(t,e){if(e)return(parseFloat(Qt(t,"marginLeft"))||t.getBoundingClientRect().left-ct(t,{marginLeft:0},(function(){return t.getBoundingClientRect().left})))+"px"})),C.each({margin:"",padding:"",border:"Width"},(function(t,e){C.cssHooks[t+e]={expand:function(n){for(var i=0,o={},r="string"==typeof n?n.split(" "):[n];i<4;i++)o[t+rt[i]+e]=r[i]||r[i-2]||r[0];return o}},"margin"!==t&&(C.cssHooks[t+e].set=ie)})),C.fn.extend({css:function(t,e){return z(this,(function(t,e,n){var i,o,r={},s=0;if(Array.isArray(e)){for(i=zt(t),o=e.length;s1)}}),C.Tween=se,se.prototype={constructor:se,init:function(t,e,n,i,o,r){this.elem=t,this.prop=n,this.easing=o||C.easing._default,this.options=e,this.start=this.now=this.cur(),this.end=i,this.unit=r||(C.cssNumber[n]?"":"px")},cur:function(){var t=se.propHooks[this.prop];return t&&t.get?t.get(this):se.propHooks._default.get(this)},run:function(t){var e,n=se.propHooks[this.prop];return this.options.duration?this.pos=e=C.easing[this.easing](t,this.options.duration*t,0,1,this.options.duration):this.pos=e=t,this.now=(this.end-this.start)*e+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):se.propHooks._default.set(this),this}},se.prototype.init.prototype=se.prototype,se.propHooks={_default:{get:function(t){var e;return 1!==t.elem.nodeType||null!=t.elem[t.prop]&&null==t.elem.style[t.prop]?t.elem[t.prop]:(e=C.css(t.elem,t.prop,""))&&"auto"!==e?e:0},set:function(t){C.fx.step[t.prop]?C.fx.step[t.prop](t):1!==t.elem.nodeType||!C.cssHooks[t.prop]&&null==t.elem.style[Kt(t.prop)]?t.elem[t.prop]=t.now:C.style(t.elem,t.prop,t.now+t.unit)}}},se.propHooks.scrollTop=se.propHooks.scrollLeft={set:function(t){t.elem.nodeType&&t.elem.parentNode&&(t.elem[t.prop]=t.now)}},C.easing={linear:function(t){return t},swing:function(t){return.5-Math.cos(t*Math.PI)/2},_default:"swing"},C.fx=se.prototype.init,C.fx.step={};var ae,le,ue=/^(?:toggle|show|hide)$/,ce=/queueHooks$/;function fe(){le&&(!1===s.hidden&&n.requestAnimationFrame?n.requestAnimationFrame(fe):n.setTimeout(fe,C.fx.interval),C.fx.tick())}function pe(){return n.setTimeout((function(){ae=void 0})),ae=Date.now()}function de(t,e){var n,i=0,o={height:t};for(e=e?1:0;i<4;i+=2-e)o["margin"+(n=rt[i])]=o["padding"+n]=t;return e&&(o.opacity=o.width=t),o}function he(t,e,n){for(var i,o=(ge.tweeners[e]||[]).concat(ge.tweeners["*"]),r=0,s=o.length;r1)},removeAttr:function(t){return this.each((function(){C.removeAttr(this,t)}))}}),C.extend({attr:function(t,e,n){var i,o,r=t.nodeType;if(3!==r&&8!==r&&2!==r)return void 0===t.getAttribute?C.prop(t,e,n):(1===r&&C.isXMLDoc(t)||(o=C.attrHooks[e.toLowerCase()]||(C.expr.match.bool.test(e)?ve:void 0)),void 0!==n?null===n?void C.removeAttr(t,e):o&&"set"in o&&void 0!==(i=o.set(t,n,e))?i:(t.setAttribute(e,n+""),n):o&&"get"in o&&null!==(i=o.get(t,e))?i:null==(i=C.find.attr(t,e))?void 0:i)},attrHooks:{type:{set:function(t,e){if(!m.radioValue&&"radio"===e&&N(t,"input")){var n=t.value;return t.setAttribute("type",e),n&&(t.value=n),e}}}},removeAttr:function(t,e){var n,i=0,o=e&&e.match(H);if(o&&1===t.nodeType)for(;n=o[i++];)t.removeAttribute(n)}}),ve={set:function(t,e,n){return!1===e?C.removeAttr(t,n):t.setAttribute(n,n),n}},C.each(C.expr.match.bool.source.match(/\w+/g),(function(t,e){var n=me[e]||C.find.attr;me[e]=function(t,e,i){var o,r,s=e.toLowerCase();return i||(r=me[s],me[s]=o,o=null!=n(t,e,i)?s:null,me[s]=r),o}}));var ye=/^(?:input|select|textarea|button)$/i,be=/^(?:a|area)$/i;function xe(t){return(t.match(H)||[]).join(" ")}function we(t){return t.getAttribute&&t.getAttribute("class")||""}function Te(t){return Array.isArray(t)?t:"string"==typeof t&&t.match(H)||[]}C.fn.extend({prop:function(t,e){return z(this,C.prop,t,e,arguments.length>1)},removeProp:function(t){return this.each((function(){delete this[C.propFix[t]||t]}))}}),C.extend({prop:function(t,e,n){var i,o,r=t.nodeType;if(3!==r&&8!==r&&2!==r)return 1===r&&C.isXMLDoc(t)||(e=C.propFix[e]||e,o=C.propHooks[e]),void 0!==n?o&&"set"in o&&void 0!==(i=o.set(t,n,e))?i:t[e]=n:o&&"get"in o&&null!==(i=o.get(t,e))?i:t[e]},propHooks:{tabIndex:{get:function(t){var e=C.find.attr(t,"tabindex");return e?parseInt(e,10):ye.test(t.nodeName)||be.test(t.nodeName)&&t.href?0:-1}}},propFix:{for:"htmlFor",class:"className"}}),m.optSelected||(C.propHooks.selected={get:function(t){var e=t.parentNode;return e&&e.parentNode&&e.parentNode.selectedIndex,null},set:function(t){var e=t.parentNode;e&&(e.selectedIndex,e.parentNode&&e.parentNode.selectedIndex)}}),C.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],(function(){C.propFix[this.toLowerCase()]=this})),C.fn.extend({addClass:function(t){var e,n,i,o,r,s,a,l=0;if(y(t))return this.each((function(e){C(this).addClass(t.call(this,e,we(this)))}));if((e=Te(t)).length)for(;n=this[l++];)if(o=we(n),i=1===n.nodeType&&" "+xe(o)+" "){for(s=0;r=e[s++];)i.indexOf(" "+r+" ")<0&&(i+=r+" ");o!==(a=xe(i))&&n.setAttribute("class",a)}return this},removeClass:function(t){var e,n,i,o,r,s,a,l=0;if(y(t))return this.each((function(e){C(this).removeClass(t.call(this,e,we(this)))}));if(!arguments.length)return this.attr("class","");if((e=Te(t)).length)for(;n=this[l++];)if(o=we(n),i=1===n.nodeType&&" "+xe(o)+" "){for(s=0;r=e[s++];)for(;i.indexOf(" "+r+" ")>-1;)i=i.replace(" "+r+" "," ");o!==(a=xe(i))&&n.setAttribute("class",a)}return this},toggleClass:function(t,e){var n=typeof t,i="string"===n||Array.isArray(t);return"boolean"==typeof e&&i?e?this.addClass(t):this.removeClass(t):y(t)?this.each((function(n){C(this).toggleClass(t.call(this,n,we(this),e),e)})):this.each((function(){var e,o,r,s;if(i)for(o=0,r=C(this),s=Te(t);e=s[o++];)r.hasClass(e)?r.removeClass(e):r.addClass(e);else void 0!==t&&"boolean"!==n||((e=we(this))&&K.set(this,"__className__",e),this.setAttribute&&this.setAttribute("class",e||!1===t?"":K.get(this,"__className__")||""))}))},hasClass:function(t){var e,n,i=0;for(e=" "+t+" ";n=this[i++];)if(1===n.nodeType&&(" "+xe(we(n))+" ").indexOf(e)>-1)return!0;return!1}});var Ce=/\r/g;C.fn.extend({val:function(t){var e,n,i,o=this[0];return arguments.length?(i=y(t),this.each((function(n){var o;1===this.nodeType&&(null==(o=i?t.call(this,n,C(this).val()):t)?o="":"number"==typeof o?o+="":Array.isArray(o)&&(o=C.map(o,(function(t){return null==t?"":t+""}))),(e=C.valHooks[this.type]||C.valHooks[this.nodeName.toLowerCase()])&&"set"in e&&void 0!==e.set(this,o,"value")||(this.value=o))}))):o?(e=C.valHooks[o.type]||C.valHooks[o.nodeName.toLowerCase()])&&"get"in e&&void 0!==(n=e.get(o,"value"))?n:"string"==typeof(n=o.value)?n.replace(Ce,""):null==n?"":n:void 0}}),C.extend({valHooks:{option:{get:function(t){var e=C.find.attr(t,"value");return null!=e?e:xe(C.text(t))}},select:{get:function(t){var e,n,i,o=t.options,r=t.selectedIndex,s="select-one"===t.type,a=s?null:[],l=s?r+1:o.length;for(i=r<0?l:s?r:0;i-1)&&(n=!0);return n||(t.selectedIndex=-1),r}}}}),C.each(["radio","checkbox"],(function(){C.valHooks[this]={set:function(t,e){if(Array.isArray(e))return t.checked=C.inArray(C(t).val(),e)>-1}},m.checkOn||(C.valHooks[this].get=function(t){return null===t.getAttribute("value")?"on":t.value})})),m.focusin="onfocusin"in n;var Ee=/^(?:focusinfocus|focusoutblur)$/,Se=function(t){t.stopPropagation()};C.extend(C.event,{trigger:function(t,e,i,o){var r,a,l,u,c,f,p,d,g=[i||s],v=h.call(t,"type")?t.type:t,m=h.call(t,"namespace")?t.namespace.split("."):[];if(a=d=l=i=i||s,3!==i.nodeType&&8!==i.nodeType&&!Ee.test(v+C.event.triggered)&&(v.indexOf(".")>-1&&(m=v.split("."),v=m.shift(),m.sort()),c=v.indexOf(":")<0&&"on"+v,(t=t[C.expando]?t:new C.Event(v,"object"==typeof t&&t)).isTrigger=o?2:3,t.namespace=m.join("."),t.rnamespace=t.namespace?new RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,t.result=void 0,t.target||(t.target=i),e=null==e?[t]:C.makeArray(e,[t]),p=C.event.special[v]||{},o||!p.trigger||!1!==p.trigger.apply(i,e))){if(!o&&!p.noBubble&&!b(i)){for(u=p.delegateType||v,Ee.test(u+v)||(a=a.parentNode);a;a=a.parentNode)g.push(a),l=a;l===(i.ownerDocument||s)&&g.push(l.defaultView||l.parentWindow||n)}for(r=0;(a=g[r++])&&!t.isPropagationStopped();)d=a,t.type=r>1?u:p.bindType||v,(f=(K.get(a,"events")||{})[t.type]&&K.get(a,"handle"))&&f.apply(a,e),(f=c&&a[c])&&f.apply&&Y(a)&&(t.result=f.apply(a,e),!1===t.result&&t.preventDefault());return t.type=v,o||t.isDefaultPrevented()||p._default&&!1!==p._default.apply(g.pop(),e)||!Y(i)||c&&y(i[v])&&!b(i)&&((l=i[c])&&(i[c]=null),C.event.triggered=v,t.isPropagationStopped()&&d.addEventListener(v,Se),i[v](),t.isPropagationStopped()&&d.removeEventListener(v,Se),C.event.triggered=void 0,l&&(i[c]=l)),t.result}},simulate:function(t,e,n){var i=C.extend(new C.Event,n,{type:t,isSimulated:!0});C.event.trigger(i,null,e)}}),C.fn.extend({trigger:function(t,e){return this.each((function(){C.event.trigger(t,e,this)}))},triggerHandler:function(t,e){var n=this[0];if(n)return C.event.trigger(t,e,n,!0)}}),m.focusin||C.each({focus:"focusin",blur:"focusout"},(function(t,e){var n=function(t){C.event.simulate(e,t.target,C.event.fix(t))};C.event.special[e]={setup:function(){var i=this.ownerDocument||this,o=K.access(i,e);o||i.addEventListener(t,n,!0),K.access(i,e,(o||0)+1)},teardown:function(){var i=this.ownerDocument||this,o=K.access(i,e)-1;o?K.access(i,e,o):(i.removeEventListener(t,n,!0),K.remove(i,e))}}}));var $e=n.location,ke=Date.now(),De=/\?/;C.parseXML=function(t){var e;if(!t||"string"!=typeof t)return null;try{e=(new n.DOMParser).parseFromString(t,"text/xml")}catch(t){e=void 0}return e&&!e.getElementsByTagName("parsererror").length||C.error("Invalid XML: "+t),e};var Ae=/\[\]$/,Ne=/\r?\n/g,je=/^(?:submit|button|image|reset|file)$/i,Oe=/^(?:input|select|textarea|keygen)/i;function Ie(t,e,n,i){var o;if(Array.isArray(e))C.each(e,(function(e,o){n||Ae.test(t)?i(t,o):Ie(t+"["+("object"==typeof o&&null!=o?e:"")+"]",o,n,i)}));else if(n||"object"!==T(e))i(t,e);else for(o in e)Ie(t+"["+o+"]",e[o],n,i)}C.param=function(t,e){var n,i=[],o=function(t,e){var n=y(e)?e():e;i[i.length]=encodeURIComponent(t)+"="+encodeURIComponent(null==n?"":n)};if(null==t)return"";if(Array.isArray(t)||t.jquery&&!C.isPlainObject(t))C.each(t,(function(){o(this.name,this.value)}));else for(n in t)Ie(n,t[n],e,o);return i.join("&")},C.fn.extend({serialize:function(){return C.param(this.serializeArray())},serializeArray:function(){return this.map((function(){var t=C.prop(this,"elements");return t?C.makeArray(t):this})).filter((function(){var t=this.type;return this.name&&!C(this).is(":disabled")&&Oe.test(this.nodeName)&&!je.test(t)&&(this.checked||!gt.test(t))})).map((function(t,e){var n=C(this).val();return null==n?null:Array.isArray(n)?C.map(n,(function(t){return{name:e.name,value:t.replace(Ne,"\r\n")}})):{name:e.name,value:n.replace(Ne,"\r\n")}})).get()}});var Le=/%20/g,Re=/#.*$/,Pe=/([?&])_=[^&]*/,qe=/^(.*?):[ \t]*([^\r\n]*)$/gm,He=/^(?:GET|HEAD)$/,Me=/^\/\//,Fe={},We={},Be="*/".concat("*"),_e=s.createElement("a");function Ue(t){return function(e,n){"string"!=typeof e&&(n=e,e="*");var i,o=0,r=e.toLowerCase().match(H)||[];if(y(n))for(;i=r[o++];)"+"===i[0]?(i=i.slice(1)||"*",(t[i]=t[i]||[]).unshift(n)):(t[i]=t[i]||[]).push(n)}}function ze(t,e,n,i){var o={},r=t===We;function s(a){var l;return o[a]=!0,C.each(t[a]||[],(function(t,a){var u=a(e,n,i);return"string"!=typeof u||r||o[u]?r?!(l=u):void 0:(e.dataTypes.unshift(u),s(u),!1)})),l}return s(e.dataTypes[0])||!o["*"]&&s("*")}function Ve(t,e){var n,i,o=C.ajaxSettings.flatOptions||{};for(n in e)void 0!==e[n]&&((o[n]?t:i||(i={}))[n]=e[n]);return i&&C.extend(!0,t,i),t}_e.href=$e.href,C.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:$e.href,type:"GET",isLocal:/^(?:about|app|app-storage|.+-extension|file|res|widget):$/.test($e.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Be,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":C.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(t,e){return e?Ve(Ve(t,C.ajaxSettings),e):Ve(C.ajaxSettings,t)},ajaxPrefilter:Ue(Fe),ajaxTransport:Ue(We),ajax:function(t,e){"object"==typeof t&&(e=t,t=void 0),e=e||{};var i,o,r,a,l,u,c,f,p,d,h=C.ajaxSetup({},e),g=h.context||h,v=h.context&&(g.nodeType||g.jquery)?C(g):C.event,m=C.Deferred(),y=C.Callbacks("once memory"),b=h.statusCode||{},x={},w={},T="canceled",E={readyState:0,getResponseHeader:function(t){var e;if(c){if(!a)for(a={};e=qe.exec(r);)a[e[1].toLowerCase()+" "]=(a[e[1].toLowerCase()+" "]||[]).concat(e[2]);e=a[t.toLowerCase()+" "]}return null==e?null:e.join(", ")},getAllResponseHeaders:function(){return c?r:null},setRequestHeader:function(t,e){return null==c&&(t=w[t.toLowerCase()]=w[t.toLowerCase()]||t,x[t]=e),this},overrideMimeType:function(t){return null==c&&(h.mimeType=t),this},statusCode:function(t){var e;if(t)if(c)E.always(t[E.status]);else for(e in t)b[e]=[b[e],t[e]];return this},abort:function(t){var e=t||T;return i&&i.abort(e),S(0,e),this}};if(m.promise(E),h.url=((t||h.url||$e.href)+"").replace(Me,$e.protocol+"//"),h.type=e.method||e.type||h.method||h.type,h.dataTypes=(h.dataType||"*").toLowerCase().match(H)||[""],null==h.crossDomain){u=s.createElement("a");try{u.href=h.url,u.href=u.href,h.crossDomain=_e.protocol+"//"+_e.host!=u.protocol+"//"+u.host}catch(t){h.crossDomain=!0}}if(h.data&&h.processData&&"string"!=typeof h.data&&(h.data=C.param(h.data,h.traditional)),ze(Fe,h,e,E),c)return E;for(p in(f=C.event&&h.global)&&0==C.active++&&C.event.trigger("ajaxStart"),h.type=h.type.toUpperCase(),h.hasContent=!He.test(h.type),o=h.url.replace(Re,""),h.hasContent?h.data&&h.processData&&0===(h.contentType||"").indexOf("application/x-www-form-urlencoded")&&(h.data=h.data.replace(Le,"+")):(d=h.url.slice(o.length),h.data&&(h.processData||"string"==typeof h.data)&&(o+=(De.test(o)?"&":"?")+h.data,delete h.data),!1===h.cache&&(o=o.replace(Pe,"$1"),d=(De.test(o)?"&":"?")+"_="+ke+++d),h.url=o+d),h.ifModified&&(C.lastModified[o]&&E.setRequestHeader("If-Modified-Since",C.lastModified[o]),C.etag[o]&&E.setRequestHeader("If-None-Match",C.etag[o])),(h.data&&h.hasContent&&!1!==h.contentType||e.contentType)&&E.setRequestHeader("Content-Type",h.contentType),E.setRequestHeader("Accept",h.dataTypes[0]&&h.accepts[h.dataTypes[0]]?h.accepts[h.dataTypes[0]]+("*"!==h.dataTypes[0]?", "+Be+"; q=0.01":""):h.accepts["*"]),h.headers)E.setRequestHeader(p,h.headers[p]);if(h.beforeSend&&(!1===h.beforeSend.call(g,E,h)||c))return E.abort();if(T="abort",y.add(h.complete),E.done(h.success),E.fail(h.error),i=ze(We,h,e,E)){if(E.readyState=1,f&&v.trigger("ajaxSend",[E,h]),c)return E;h.async&&h.timeout>0&&(l=n.setTimeout((function(){E.abort("timeout")}),h.timeout));try{c=!1,i.send(x,S)}catch(t){if(c)throw t;S(-1,t)}}else S(-1,"No Transport");function S(t,e,s,a){var u,p,d,x,w,T=e;c||(c=!0,l&&n.clearTimeout(l),i=void 0,r=a||"",E.readyState=t>0?4:0,u=t>=200&&t<300||304===t,s&&(x=function(t,e,n){for(var i,o,r,s,a=t.contents,l=t.dataTypes;"*"===l[0];)l.shift(),void 0===i&&(i=t.mimeType||e.getResponseHeader("Content-Type"));if(i)for(o in a)if(a[o]&&a[o].test(i)){l.unshift(o);break}if(l[0]in n)r=l[0];else{for(o in n){if(!l[0]||t.converters[o+" "+l[0]]){r=o;break}s||(s=o)}r=r||s}if(r)return r!==l[0]&&l.unshift(r),n[r]}(h,E,s)),x=function(t,e,n,i){var o,r,s,a,l,u={},c=t.dataTypes.slice();if(c[1])for(s in t.converters)u[s.toLowerCase()]=t.converters[s];for(r=c.shift();r;)if(t.responseFields[r]&&(n[t.responseFields[r]]=e),!l&&i&&t.dataFilter&&(e=t.dataFilter(e,t.dataType)),l=r,r=c.shift())if("*"===r)r=l;else if("*"!==l&&l!==r){if(!(s=u[l+" "+r]||u["* "+r]))for(o in u)if((a=o.split(" "))[1]===r&&(s=u[l+" "+a[0]]||u["* "+a[0]])){!0===s?s=u[o]:!0!==u[o]&&(r=a[0],c.unshift(a[1]));break}if(!0!==s)if(s&&t.throws)e=s(e);else try{e=s(e)}catch(t){return{state:"parsererror",error:s?t:"No conversion from "+l+" to "+r}}}return{state:"success",data:e}}(h,x,E,u),u?(h.ifModified&&((w=E.getResponseHeader("Last-Modified"))&&(C.lastModified[o]=w),(w=E.getResponseHeader("etag"))&&(C.etag[o]=w)),204===t||"HEAD"===h.type?T="nocontent":304===t?T="notmodified":(T=x.state,p=x.data,u=!(d=x.error))):(d=T,!t&&T||(T="error",t<0&&(t=0))),E.status=t,E.statusText=(e||T)+"",u?m.resolveWith(g,[p,T,E]):m.rejectWith(g,[E,T,d]),E.statusCode(b),b=void 0,f&&v.trigger(u?"ajaxSuccess":"ajaxError",[E,h,u?p:d]),y.fireWith(g,[E,T]),f&&(v.trigger("ajaxComplete",[E,h]),--C.active||C.event.trigger("ajaxStop")))}return E},getJSON:function(t,e,n){return C.get(t,e,n,"json")},getScript:function(t,e){return C.get(t,void 0,e,"script")}}),C.each(["get","post"],(function(t,e){C[e]=function(t,n,i,o){return y(n)&&(o=o||i,i=n,n=void 0),C.ajax(C.extend({url:t,type:e,dataType:o,data:n,success:i},C.isPlainObject(t)&&t))}})),C._evalUrl=function(t,e){return C.ajax({url:t,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,converters:{"text script":function(){}},dataFilter:function(t){C.globalEval(t,e)}})},C.fn.extend({wrapAll:function(t){var e;return this[0]&&(y(t)&&(t=t.call(this[0])),e=C(t,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&e.insertBefore(this[0]),e.map((function(){for(var t=this;t.firstElementChild;)t=t.firstElementChild;return t})).append(this)),this},wrapInner:function(t){return y(t)?this.each((function(e){C(this).wrapInner(t.call(this,e))})):this.each((function(){var e=C(this),n=e.contents();n.length?n.wrapAll(t):e.append(t)}))},wrap:function(t){var e=y(t);return this.each((function(n){C(this).wrapAll(e?t.call(this,n):t)}))},unwrap:function(t){return this.parent(t).not("body").each((function(){C(this).replaceWith(this.childNodes)})),this}}),C.expr.pseudos.hidden=function(t){return!C.expr.pseudos.visible(t)},C.expr.pseudos.visible=function(t){return!!(t.offsetWidth||t.offsetHeight||t.getClientRects().length)},C.ajaxSettings.xhr=function(){try{return new n.XMLHttpRequest}catch(t){}};var Qe={0:200,1223:204},Xe=C.ajaxSettings.xhr();m.cors=!!Xe&&"withCredentials"in Xe,m.ajax=Xe=!!Xe,C.ajaxTransport((function(t){var e,i;if(m.cors||Xe&&!t.crossDomain)return{send:function(o,r){var s,a=t.xhr();if(a.open(t.type,t.url,t.async,t.username,t.password),t.xhrFields)for(s in t.xhrFields)a[s]=t.xhrFields[s];for(s in t.mimeType&&a.overrideMimeType&&a.overrideMimeType(t.mimeType),t.crossDomain||o["X-Requested-With"]||(o["X-Requested-With"]="XMLHttpRequest"),o)a.setRequestHeader(s,o[s]);e=function(t){return function(){e&&(e=i=a.onload=a.onerror=a.onabort=a.ontimeout=a.onreadystatechange=null,"abort"===t?a.abort():"error"===t?"number"!=typeof a.status?r(0,"error"):r(a.status,a.statusText):r(Qe[a.status]||a.status,a.statusText,"text"!==(a.responseType||"text")||"string"!=typeof a.responseText?{binary:a.response}:{text:a.responseText},a.getAllResponseHeaders()))}},a.onload=e(),i=a.onerror=a.ontimeout=e("error"),void 0!==a.onabort?a.onabort=i:a.onreadystatechange=function(){4===a.readyState&&n.setTimeout((function(){e&&i()}))},e=e("abort");try{a.send(t.hasContent&&t.data||null)}catch(t){if(e)throw t}},abort:function(){e&&e()}}})),C.ajaxPrefilter((function(t){t.crossDomain&&(t.contents.script=!1)})),C.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(t){return C.globalEval(t),t}}}),C.ajaxPrefilter("script",(function(t){void 0===t.cache&&(t.cache=!1),t.crossDomain&&(t.type="GET")})),C.ajaxTransport("script",(function(t){var e,n;if(t.crossDomain||t.scriptAttrs)return{send:function(i,o){e=C(" diff --git a/resources/views/v1/accounts/reconcile/edit.twig b/resources/views/v1/accounts/reconcile/edit.twig index 9a02947a4d..575d274051 100644 --- a/resources/views/v1/accounts/reconcile/edit.twig +++ b/resources/views/v1/accounts/reconcile/edit.twig @@ -72,7 +72,10 @@ {% endif %} - + + +
+
{# panel for options #}
diff --git a/resources/views/v1/admin/link/create.twig b/resources/views/v1/admin/link/create.twig index 45272d6079..cf4b130715 100644 --- a/resources/views/v1/admin/link/create.twig +++ b/resources/views/v1/admin/link/create.twig @@ -21,6 +21,8 @@
+
+
{# panel for options #}
diff --git a/resources/views/v1/admin/link/edit.twig b/resources/views/v1/admin/link/edit.twig index 560c69188b..32ffb9a680 100644 --- a/resources/views/v1/admin/link/edit.twig +++ b/resources/views/v1/admin/link/edit.twig @@ -22,6 +22,8 @@
+ +
{# panel for options #} diff --git a/resources/views/v1/admin/users/edit.twig b/resources/views/v1/admin/users/edit.twig index bd4834c61e..7468734f2e 100644 --- a/resources/views/v1/admin/users/edit.twig +++ b/resources/views/v1/admin/users/edit.twig @@ -26,7 +26,9 @@
-
+
+
+
{# panel for options #}
@@ -43,5 +45,5 @@
- {{ Form.close|raw }} + {% endblock %} diff --git a/resources/views/v1/attachments/edit.twig b/resources/views/v1/attachments/edit.twig index d80bde0fba..e2bb7265b7 100644 --- a/resources/views/v1/attachments/edit.twig +++ b/resources/views/v1/attachments/edit.twig @@ -35,7 +35,10 @@ {{ ExpandedForm.textarea('notes',null,{helpText: trans('firefly.field_supports_markdown')}) }}
- + + +
+
{# panel for options #}
diff --git a/resources/views/v1/bills/create.twig b/resources/views/v1/bills/create.twig index bc299a9c54..dcf45256f6 100644 --- a/resources/views/v1/bills/create.twig +++ b/resources/views/v1/bills/create.twig @@ -37,7 +37,10 @@ {{ ExpandedForm.integer('skip',0) }}
- +
+
+
+
{# panel for options #}
diff --git a/resources/views/v1/bills/edit.twig b/resources/views/v1/bills/edit.twig index a1bdb1a002..216b6b7a40 100644 --- a/resources/views/v1/bills/edit.twig +++ b/resources/views/v1/bills/edit.twig @@ -42,6 +42,10 @@
+
+
+
+

{{ 'options'|_ }}

@@ -57,7 +61,7 @@
- {{ Form.close|raw }} + {% endblock %} {% block styles %} diff --git a/resources/views/v1/budgets/create.twig b/resources/views/v1/budgets/create.twig index 52966dd290..7af530501a 100644 --- a/resources/views/v1/budgets/create.twig +++ b/resources/views/v1/budgets/create.twig @@ -21,6 +21,22 @@
+
+ {# panel for auto-budget#} +
+
+

{{ 'optionalFields'|_ }}

+
+
+ {{ ExpandedForm.select('auto_budget_type', autoBudgetTypes,null, {helpText: trans('firefly.auto_budget_help')}) }} + {{ CurrencyForm.currencyList('auto_budget_currency_id') }} + {{ ExpandedForm.amountNoCurrency('auto_budget_amount') }} + {{ ExpandedForm.select('auto_budget_period', autoBudgetPeriods, null) }} +
+
+
+ +
{# panel for options #}
diff --git a/resources/views/v1/budgets/edit.twig b/resources/views/v1/budgets/edit.twig index f8c277b8a3..659cf3b419 100644 --- a/resources/views/v1/budgets/edit.twig +++ b/resources/views/v1/budgets/edit.twig @@ -21,6 +21,22 @@
+
+ {# panel for auto-budget #} +
+
+

{{ 'optionalFields'|_ }}

+
+
+ {{ ExpandedForm.select('auto_budget_type', autoBudgetTypes, autoBudget.auto_budget_type) }} + {{ CurrencyForm.currencyList('auto_budget_currency_id', autoBudget.transaction_currency_id) }} + {{ ExpandedForm.amountNoCurrency('auto_budget_amount', preFilled.auto_budget_amount) }} + {{ ExpandedForm.select('auto_budget_period', autoBudgetPeriods, autoBudget.period) }} +
+
+
+
+
{# panel for options #}
@@ -37,7 +53,7 @@
- {{ Form.close|raw }} + {% endblock %} {% block scripts %} diff --git a/resources/views/v1/budgets/index.twig b/resources/views/v1/budgets/index.twig index 549b6b9bf4..12495926c8 100644 --- a/resources/views/v1/budgets/index.twig +++ b/resources/views/v1/budgets/index.twig @@ -234,6 +234,14 @@
+ {% if budget.auto_budget %} + {% if 1 == budget.auto_budget.auto_budget_type %} + + {% endif %} + {% if 2 == budget.auto_budget.auto_budget_type %} + + {% endif %} + {% endif %} {{ budget.name }} diff --git a/resources/views/v1/categories/create.twig b/resources/views/v1/categories/create.twig index 4c969aabf2..770e93106e 100644 --- a/resources/views/v1/categories/create.twig +++ b/resources/views/v1/categories/create.twig @@ -19,7 +19,8 @@ - + +
{# panel for options #} diff --git a/resources/views/v1/categories/edit.twig b/resources/views/v1/categories/edit.twig index f308b77853..2d7f2c5ac6 100644 --- a/resources/views/v1/categories/edit.twig +++ b/resources/views/v1/categories/edit.twig @@ -19,6 +19,8 @@
+ +
@@ -38,7 +40,7 @@
- {{ Form.close|raw }} + {% endblock %} {% block scripts %} diff --git a/resources/views/v1/currencies/create.twig b/resources/views/v1/currencies/create.twig index 2524659508..bab224ea4d 100644 --- a/resources/views/v1/currencies/create.twig +++ b/resources/views/v1/currencies/create.twig @@ -22,7 +22,8 @@ - + +
{# panel for options #} diff --git a/resources/views/v1/currencies/edit.twig b/resources/views/v1/currencies/edit.twig index 1aec8f112c..221b226329 100644 --- a/resources/views/v1/currencies/edit.twig +++ b/resources/views/v1/currencies/edit.twig @@ -23,7 +23,8 @@
- + +
{# panel for options #} @@ -43,5 +44,5 @@
- {{ Form.close|raw }} + {% endblock %} diff --git a/resources/views/v1/piggy-banks/create.twig b/resources/views/v1/piggy-banks/create.twig index 06d3d5a181..8466c12749 100644 --- a/resources/views/v1/piggy-banks/create.twig +++ b/resources/views/v1/piggy-banks/create.twig @@ -34,7 +34,10 @@ {{ ExpandedForm.textarea('notes', null, {helpText: trans('firefly.field_supports_markdown')} ) }} - + + +
+
{# panel for options #}
diff --git a/resources/views/v1/piggy-banks/edit.twig b/resources/views/v1/piggy-banks/edit.twig index 668d1441a9..8dda406b0c 100644 --- a/resources/views/v1/piggy-banks/edit.twig +++ b/resources/views/v1/piggy-banks/edit.twig @@ -37,7 +37,10 @@ {{ ExpandedForm.textarea('notes', null, {helpText: trans('firefly.field_supports_markdown')}) }}
- +
+
+
+
{# panel for options #}
@@ -55,7 +58,7 @@
- {{ Form.close|raw }} + {% endblock %} {% block scripts %} diff --git a/resources/views/v1/preferences/index.twig b/resources/views/v1/preferences/index.twig index efac47f5b2..3feda66700 100644 --- a/resources/views/v1/preferences/index.twig +++ b/resources/views/v1/preferences/index.twig @@ -30,7 +30,7 @@