diff --git a/.env.example b/.env.example index 87a076a8ed..f2d0531763 100644 --- a/.env.example +++ b/.env.example @@ -142,7 +142,6 @@ MAIL_ENCRYPTION=null MAILGUN_DOMAIN= MAILGUN_SECRET= - # If you are on EU region in mailgun, use api.eu.mailgun.net, otherwise use api.mailgun.net # If you use Docker or similar, you can set this variable from a file by appending it with _FILE MAILGUN_ENDPOINT=api.mailgun.net @@ -176,42 +175,14 @@ MAP_DEFAULT_ZOOM=6 # # Firefly III supports a few authentication methods: # - 'web' (default, uses built in DB) -# - 'ldap' # - 'remote_user_guard' for Authelia etc # Read more about these settings in the documentation. # https://docs.firefly-iii.org/advanced-installation/authentication +# +# LDAP is no longer supported :( +# AUTHENTICATION_GUARD=web -# -# Your LDAP server may speak a dialect. You can choose between 'OpenLDAP' and 'ActiveDirectory' -# Anything else defaults to 'ActiveDirectory' -# -LDAP_DIALECT=OpenLDAP - -# -# LDAP connection settings: -# -LDAP_HOST=ldap.yourserver.com -LDAP_PORT=389 -LDAP_TIMEOUT=5 -LDAP_SSL=false -LDAP_TLS=false - -LDAP_BASE_DN="o=something,dc=site,dc=com" -LDAP_USERNAME="uid=X,ou=,o=,dc=something,dc=com" -LDAP_PASSWORD=super_secret - -LDAP_AUTH_FIELD=uid - -# -# If you wish to only authenticate users from a specific group, use the base DN above. -# -# If you require extra/special filters please use the LDAP_EXTRA_FILTER with a valid DN. -# -# The extra filter will only be applied after the user is authenticated. -# -LDAP_EXTRA_FILTER= - # # Remote user guard settings # @@ -263,6 +234,13 @@ STATIC_CRON_TOKEN= # However if you know what you're doing you can significantly speed up container start times. # Set each value to true to enable, or false to disable. +# Set this to true to build all locales supported by Firefly III. +# This may take quite some time (several minutes) and is generally not recommended. +# If you wish to change or alter the list of locales, start your Docker container with +# `docker run -v locale.gen:/etc/locale.gen -e DKR_BUILD_LOCALE=true` +# and make sure your preferred locales are in your own locale.gen. +DKR_BUILD_LOCALE=false + # Check if the SQLite database exists. Can be skipped if you're not using SQLite. # Won't significantly speed up things. DKR_CHECK_SQLITE=true @@ -291,7 +269,6 @@ DKR_RUN_PASSPORT_INSTALL=true # Leave the following configuration vars as is. # Unless you like to tinker and know what you're doing. APP_NAME=FireflyIII -ADLDAP_CONNECTION=default BROADCAST_DRIVER=log QUEUE_DRIVER=sync CACHE_PREFIX=firefly diff --git a/app/Api/V1/Controllers/Autocomplete/AccountController.php b/app/Api/V1/Controllers/Autocomplete/AccountController.php index e9a6cfd232..7fe5b418cf 100644 --- a/app/Api/V1/Controllers/Autocomplete/AccountController.php +++ b/app/Api/V1/Controllers/Autocomplete/AccountController.php @@ -70,8 +70,9 @@ class AccountController extends Controller * @param AutocompleteRequest $request * * @return JsonResponse - * @throws FireflyException * @throws JsonException + * @throws FireflyException + * @throws FireflyException */ public function accounts(AutocompleteRequest $request): JsonResponse { @@ -81,7 +82,7 @@ class AccountController extends Controller $date = $data['date'] ?? today(config('app.timezone')); $return = []; - $result = $this->repository->searchAccount((string)$query, $types, $data['limit']); + $result = $this->repository->searchAccount((string) $query, $types, $data['limit']); $defaultCurrency = app('amount')->getDefaultCurrency(); /** @var Account $account */ @@ -95,7 +96,7 @@ class AccountController extends Controller } $return[] = [ - 'id' => (string)$account->id, + 'id' => (string) $account->id, 'name' => $account->name, 'name_with_balance' => $nameWithBalance, 'type' => $account->accountType->type, diff --git a/app/Api/V1/Controllers/Autocomplete/BillController.php b/app/Api/V1/Controllers/Autocomplete/BillController.php index 6033d7f6e3..7b4270b725 100644 --- a/app/Api/V1/Controllers/Autocomplete/BillController.php +++ b/app/Api/V1/Controllers/Autocomplete/BillController.php @@ -70,7 +70,7 @@ class BillController extends Controller $filtered = $result->map( static function (Bill $item) { return [ - 'id' => (string)$item->id, + 'id' => (string) $item->id, 'name' => $item->name, ]; } diff --git a/app/Api/V1/Controllers/Autocomplete/BudgetController.php b/app/Api/V1/Controllers/Autocomplete/BudgetController.php index c1ddc3e638..60d56f7fb0 100644 --- a/app/Api/V1/Controllers/Autocomplete/BudgetController.php +++ b/app/Api/V1/Controllers/Autocomplete/BudgetController.php @@ -70,7 +70,7 @@ class BudgetController extends Controller $filtered = $result->map( static function (Budget $item) { return [ - 'id' => (string)$item->id, + 'id' => (string) $item->id, 'name' => $item->name, ]; } diff --git a/app/Api/V1/Controllers/Autocomplete/CategoryController.php b/app/Api/V1/Controllers/Autocomplete/CategoryController.php index 4bf324f815..3e29a7aa33 100644 --- a/app/Api/V1/Controllers/Autocomplete/CategoryController.php +++ b/app/Api/V1/Controllers/Autocomplete/CategoryController.php @@ -70,7 +70,7 @@ class CategoryController extends Controller $filtered = $result->map( static function (Category $item) { return [ - 'id' => (string)$item->id, + 'id' => (string) $item->id, 'name' => $item->name, ]; } diff --git a/app/Api/V1/Controllers/Autocomplete/CurrencyController.php b/app/Api/V1/Controllers/Autocomplete/CurrencyController.php index 4d1f508d67..e0eef2e62a 100644 --- a/app/Api/V1/Controllers/Autocomplete/CurrencyController.php +++ b/app/Api/V1/Controllers/Autocomplete/CurrencyController.php @@ -72,7 +72,7 @@ class CurrencyController extends Controller /** @var TransactionCurrency $currency */ foreach ($collection as $currency) { $result[] = [ - 'id' => (string)$currency->id, + 'id' => (string) $currency->id, 'name' => $currency->name, 'code' => $currency->code, 'symbol' => $currency->symbol, @@ -101,7 +101,7 @@ class CurrencyController extends Controller /** @var TransactionCurrency $currency */ foreach ($collection as $currency) { $result[] = [ - 'id' => (string)$currency->id, + 'id' => (string) $currency->id, 'name' => sprintf('%s (%s)', $currency->name, $currency->code), 'code' => $currency->code, 'symbol' => $currency->symbol, diff --git a/app/Api/V1/Controllers/Autocomplete/ObjectGroupController.php b/app/Api/V1/Controllers/Autocomplete/ObjectGroupController.php index e4328a62ef..aaab2e1594 100644 --- a/app/Api/V1/Controllers/Autocomplete/ObjectGroupController.php +++ b/app/Api/V1/Controllers/Autocomplete/ObjectGroupController.php @@ -72,7 +72,7 @@ class ObjectGroupController extends Controller /** @var ObjectGroup $objectGroup */ foreach ($result as $objectGroup) { $return[] = [ - 'id' => (string)$objectGroup->id, + 'id' => (string) $objectGroup->id, 'name' => $objectGroup->title, 'title' => $objectGroup->title, ]; diff --git a/app/Api/V1/Controllers/Autocomplete/PiggyBankController.php b/app/Api/V1/Controllers/Autocomplete/PiggyBankController.php index 2a903e1318..6efbe495cf 100644 --- a/app/Api/V1/Controllers/Autocomplete/PiggyBankController.php +++ b/app/Api/V1/Controllers/Autocomplete/PiggyBankController.php @@ -78,7 +78,7 @@ class PiggyBankController extends Controller foreach ($piggies as $piggy) { $currency = $this->accountRepository->getAccountCurrency($piggy->account) ?? $defaultCurrency; $response[] = [ - 'id' => (string)$piggy->id, + 'id' => (string) $piggy->id, 'name' => $piggy->name, 'currency_id' => $currency->id, 'currency_name' => $currency->name, @@ -110,7 +110,7 @@ class PiggyBankController extends Controller $currency = $this->accountRepository->getAccountCurrency($piggy->account) ?? $defaultCurrency; $currentAmount = $this->piggyRepository->getRepetition($piggy)->currentamount ?? '0'; $response[] = [ - 'id' => (string)$piggy->id, + 'id' => (string) $piggy->id, 'name' => $piggy->name, 'name_with_balance' => sprintf( '%s (%s / %s)', $piggy->name, app('amount')->formatAnything($currency, $currentAmount, false), diff --git a/app/Api/V1/Controllers/Autocomplete/RecurrenceController.php b/app/Api/V1/Controllers/Autocomplete/RecurrenceController.php index aa133d7192..93e6bbd315 100644 --- a/app/Api/V1/Controllers/Autocomplete/RecurrenceController.php +++ b/app/Api/V1/Controllers/Autocomplete/RecurrenceController.php @@ -69,7 +69,7 @@ class RecurrenceController extends Controller /** @var Recurrence $recurrence */ foreach ($recurrences as $recurrence) { $response[] = [ - 'id' => (string)$recurrence->id, + 'id' => (string) $recurrence->id, 'name' => $recurrence->title, 'description' => $recurrence->description, ]; diff --git a/app/Api/V1/Controllers/Autocomplete/RuleController.php b/app/Api/V1/Controllers/Autocomplete/RuleController.php index dadfd66d75..47c24795ea 100644 --- a/app/Api/V1/Controllers/Autocomplete/RuleController.php +++ b/app/Api/V1/Controllers/Autocomplete/RuleController.php @@ -69,7 +69,7 @@ class RuleController extends Controller /** @var Rule $rule */ foreach ($rules as $rule) { $response[] = [ - 'id' => (string)$rule->id, + 'id' => (string) $rule->id, 'name' => $rule->title, 'description' => $rule->description, ]; diff --git a/app/Api/V1/Controllers/Autocomplete/RuleGroupController.php b/app/Api/V1/Controllers/Autocomplete/RuleGroupController.php index a4fc1cf437..d5f88aa3cf 100644 --- a/app/Api/V1/Controllers/Autocomplete/RuleGroupController.php +++ b/app/Api/V1/Controllers/Autocomplete/RuleGroupController.php @@ -69,7 +69,7 @@ class RuleGroupController extends Controller /** @var RuleGroup $group */ foreach ($groups as $group) { $response[] = [ - 'id' => (string)$group->id, + 'id' => (string) $group->id, 'name' => $group->title, 'description' => $group->description, ]; diff --git a/app/Api/V1/Controllers/Autocomplete/TagController.php b/app/Api/V1/Controllers/Autocomplete/TagController.php index 12e3498415..95e031ebf7 100644 --- a/app/Api/V1/Controllers/Autocomplete/TagController.php +++ b/app/Api/V1/Controllers/Autocomplete/TagController.php @@ -72,7 +72,7 @@ class TagController extends Controller /** @var Tag $tag */ foreach ($result as $tag) { $array[] = [ - 'id' => (string)$tag->id, + 'id' => (string) $tag->id, 'name' => $tag->tag, 'tag' => $tag->tag, ]; diff --git a/app/Api/V1/Controllers/Autocomplete/TransactionController.php b/app/Api/V1/Controllers/Autocomplete/TransactionController.php index 923d9d1602..d24902ae89 100644 --- a/app/Api/V1/Controllers/Autocomplete/TransactionController.php +++ b/app/Api/V1/Controllers/Autocomplete/TransactionController.php @@ -80,8 +80,8 @@ class TransactionController extends Controller /** @var TransactionJournal $journal */ foreach ($filtered as $journal) { $array[] = [ - 'id' => (string)$journal->id, - 'transaction_group_id' => (string)$journal->transaction_group_id, + 'id' => (string) $journal->id, + 'transaction_group_id' => (string) $journal->transaction_group_id, 'name' => $journal->description, 'description' => $journal->description, ]; @@ -104,7 +104,7 @@ class TransactionController extends Controller $result = new Collection; if (is_numeric($data['query'])) { // search for group, not journal. - $firstResult = $this->groupRepository->find((int)$data['query']); + $firstResult = $this->groupRepository->find((int) $data['query']); if (null !== $firstResult) { // group may contain multiple journals, each a result: foreach ($firstResult->transactionJournals as $journal) { @@ -122,8 +122,8 @@ class TransactionController extends Controller /** @var TransactionJournal $journal */ foreach ($result as $journal) { $array[] = [ - 'id' => (string)$journal->id, - 'transaction_group_id' => (string)$journal->transaction_group_id, + 'id' => (string) $journal->id, + 'transaction_group_id' => (string) $journal->transaction_group_id, 'name' => sprintf('#%d: %s', $journal->transaction_group_id, $journal->description), 'description' => sprintf('#%d: %s', $journal->transaction_group_id, $journal->description), ]; diff --git a/app/Api/V1/Controllers/Autocomplete/TransactionTypeController.php b/app/Api/V1/Controllers/Autocomplete/TransactionTypeController.php index 2318c5fdb3..24d09276f8 100644 --- a/app/Api/V1/Controllers/Autocomplete/TransactionTypeController.php +++ b/app/Api/V1/Controllers/Autocomplete/TransactionTypeController.php @@ -70,7 +70,7 @@ class TransactionTypeController extends Controller foreach ($types as $type) { // different key for consistency. $array[] = [ - 'id' => (string)$type->id, + 'id' => (string) $type->id, 'name' => $type->type, 'type' => $type->type, ]; diff --git a/app/Api/V1/Controllers/Chart/AccountController.php b/app/Api/V1/Controllers/Chart/AccountController.php index 27a2a07101..264c1a97a0 100644 --- a/app/Api/V1/Controllers/Chart/AccountController.php +++ b/app/Api/V1/Controllers/Chart/AccountController.php @@ -35,6 +35,9 @@ use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\Support\Http\Api\ApiSupport; use FireflyIII\User; use Illuminate\Http\JsonResponse; +use JsonException; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; /** * Class AccountController @@ -77,6 +80,9 @@ class AccountController extends Controller * * @return JsonResponse * @throws FireflyException + * @throws JsonException + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface */ public function overview(DateRequest $request): JsonResponse { @@ -109,7 +115,7 @@ class AccountController extends Controller } $currentSet = [ 'label' => $account->name, - 'currency_id' => (string)$currency->id, + 'currency_id' => (string) $currency->id, 'currency_code' => $currency->code, 'currency_symbol' => $currency->symbol, 'currency_decimal_places' => $currency->decimal_places, @@ -121,11 +127,11 @@ class AccountController extends Controller ]; $currentStart = clone $start; $range = app('steam')->balanceInRange($account, $start, clone $end); - $previous = round((float)array_values($range)[0], 12); + $previous = round((float) array_values($range)[0], 12); while ($currentStart <= $end) { $format = $currentStart->format('Y-m-d'); $label = $currentStart->toAtomString(); - $balance = array_key_exists($format, $range) ? round((float)$range[$format], 12) : $previous; + $balance = array_key_exists($format, $range) ? round((float) $range[$format], 12) : $previous; $previous = $balance; $currentStart->addDay(); $currentSet['entries'][$label] = $balance; diff --git a/app/Api/V1/Controllers/Controller.php b/app/Api/V1/Controllers/Controller.php index 5a8c0fd9ed..55b1058762 100644 --- a/app/Api/V1/Controllers/Controller.php +++ b/app/Api/V1/Controllers/Controller.php @@ -34,6 +34,8 @@ use Illuminate\Routing\Controller as BaseController; use League\Fractal\Manager; use League\Fractal\Serializer\JsonApiSerializer; use Log; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; use Symfony\Component\HttpFoundation\ParameterBag; /** @@ -74,6 +76,8 @@ abstract class Controller extends BaseController * Method to grab all parameters from the URI. * * @return ParameterBag + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface */ private function getParameters(): ParameterBag { @@ -94,7 +98,7 @@ abstract class Controller extends BaseController $obj = Carbon::parse($date); } catch (InvalidDateException | InvalidFormatException $e) { // don't care - Log::warn(sprintf('Ignored invalid date "%s" in API controller parameter check: %s', (string) $date, $e->getMessage())); + Log::warning(sprintf('Ignored invalid date "%s" in API controller parameter check: %s', $date, $e->getMessage())); } } $bag->set($field, $obj); diff --git a/app/Api/V1/Controllers/Data/Bulk/AccountController.php b/app/Api/V1/Controllers/Data/Bulk/AccountController.php index a1fa0fa6a5..3d80897e83 100644 --- a/app/Api/V1/Controllers/Data/Bulk/AccountController.php +++ b/app/Api/V1/Controllers/Data/Bulk/AccountController.php @@ -66,8 +66,8 @@ class AccountController extends Controller */ public function moveTransactions(MoveTransactionsRequest $request): JsonResponse { - $accountIds = $request->getAll(); - $original = $this->repository->find($accountIds['original_account']); + $accountIds = $request->getAll(); + $original = $this->repository->find($accountIds['original_account']); $destination = $this->repository->find($accountIds['destination_account']); /** @var AccountDestroyService $service */ diff --git a/app/Api/V1/Controllers/Data/Bulk/TransactionController.php b/app/Api/V1/Controllers/Data/Bulk/TransactionController.php index 79435f58b8..f04e698b97 100644 --- a/app/Api/V1/Controllers/Data/Bulk/TransactionController.php +++ b/app/Api/V1/Controllers/Data/Bulk/TransactionController.php @@ -76,8 +76,8 @@ class TransactionController extends Controller // to respond to what is in the $query. // this is OK because only one thing can be in the query at the moment. if ($this->updatesTransactionAccount($params)) { - $original = $this->repository->find((int)$params['where']['account_id']); - $destination = $this->repository->find((int)$params['update']['account_id']); + $original = $this->repository->find((int) $params['where']['account_id']); + $destination = $this->repository->find((int) $params['update']['account_id']); /** @var AccountDestroyService $service */ $service = app(AccountDestroyService::class); diff --git a/app/Api/V1/Controllers/Data/Export/ExportController.php b/app/Api/V1/Controllers/Data/Export/ExportController.php index 58e1ab5090..c6eef16cef 100644 --- a/app/Api/V1/Controllers/Data/Export/ExportController.php +++ b/app/Api/V1/Controllers/Data/Export/ExportController.php @@ -78,9 +78,9 @@ class ExportController extends Controller */ private function returnExport(string $key): LaravelResponse { - $date = date('Y-m-d-H-i-s'); + $date = date('Y-m-d-H-i-s'); $fileName = sprintf('%s-export-%s.csv', $date, $key); - $data = $this->exporter->export(); + $data = $this->exporter->export(); /** @var LaravelResponse $response */ $response = response($data[$key]); @@ -93,7 +93,7 @@ class ExportController extends Controller ->header('Expires', '0') ->header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0') ->header('Pragma', 'public') - ->header('Content-Length', (string)strlen($data[$key])); + ->header('Content-Length', (string) strlen($data[$key])); return $response; } diff --git a/app/Api/V1/Controllers/Insight/Expense/AccountController.php b/app/Api/V1/Controllers/Insight/Expense/AccountController.php index af32ae9e60..cb2f74ca68 100644 --- a/app/Api/V1/Controllers/Insight/Expense/AccountController.php +++ b/app/Api/V1/Controllers/Insight/Expense/AccountController.php @@ -91,11 +91,11 @@ class AccountController extends Controller /** @var array $expense */ foreach ($expenses as $expense) { $result[] = [ - 'id' => (string)$expense['id'], + 'id' => (string) $expense['id'], 'name' => $expense['name'], 'difference' => $expense['sum'], - 'difference_float' => (float)$expense['sum'], - 'currency_id' => (string)$expense['currency_id'], + 'difference_float' => (float) $expense['sum'], + 'currency_id' => (string) $expense['currency_id'], 'currency_code' => $expense['currency_code'], ]; } @@ -123,11 +123,11 @@ class AccountController extends Controller /** @var array $expense */ foreach ($expenses as $expense) { $result[] = [ - 'id' => (string)$expense['id'], + 'id' => (string) $expense['id'], 'name' => $expense['name'], 'difference' => $expense['sum'], - 'difference_float' => (float)$expense['sum'], - 'currency_id' => (string)$expense['currency_id'], + 'difference_float' => (float) $expense['sum'], + 'currency_id' => (string) $expense['currency_id'], 'currency_code' => $expense['currency_code'], ]; } diff --git a/app/Api/V1/Controllers/Insight/Expense/BillController.php b/app/Api/V1/Controllers/Insight/Expense/BillController.php index e79633d264..4bcf455c23 100644 --- a/app/Api/V1/Controllers/Insight/Expense/BillController.php +++ b/app/Api/V1/Controllers/Insight/Expense/BillController.php @@ -85,33 +85,33 @@ class BillController extends Controller $genericSet = $collector->getExtractedJournals(); foreach ($genericSet as $journal) { - $billId = (int)$journal['bill_id']; - $currencyId = (int)$journal['currency_id']; - $foreignCurrencyId = (int)$journal['foreign_currency_id']; + $billId = (int) $journal['bill_id']; + $currencyId = (int) $journal['currency_id']; + $foreignCurrencyId = (int) $journal['foreign_currency_id']; $key = sprintf('%d-%d', $billId, $currencyId); $foreignKey = sprintf('%d-%d', $billId, $foreignCurrencyId); if (0 !== $currencyId) { $response[$key] = $response[$key] ?? [ - 'id' => (string)$billId, + 'id' => (string) $billId, 'name' => $journal['bill_name'], 'difference' => '0', 'difference_float' => 0, - 'currency_id' => (string)$currencyId, + 'currency_id' => (string) $currencyId, 'currency_code' => $journal['currency_code'], ]; $response[$key]['difference'] = bcadd($response[$key]['difference'], $journal['amount']); - $response[$key]['difference_float'] = (float)$response[$key]['difference']; + $response[$key]['difference_float'] = (float) $response[$key]['difference']; } if (0 !== $foreignCurrencyId) { $response[$foreignKey] = $response[$foreignKey] ?? [ 'difference' => '0', 'difference_float' => 0, - 'currency_id' => (string)$foreignCurrencyId, + 'currency_id' => (string) $foreignCurrencyId, 'currency_code' => $journal['foreign_currency_code'], ]; $response[$foreignKey]['difference'] = bcadd($response[$foreignKey]['difference'], $journal['foreign_amount']); - $response[$foreignKey]['difference_float'] = (float)$response[$foreignKey]['difference']; + $response[$foreignKey]['difference_float'] = (float) $response[$foreignKey]['difference']; } } @@ -143,28 +143,28 @@ class BillController extends Controller $genericSet = $collector->getExtractedJournals(); foreach ($genericSet as $journal) { - $currencyId = (int)$journal['currency_id']; - $foreignCurrencyId = (int)$journal['foreign_currency_id']; + $currencyId = (int) $journal['currency_id']; + $foreignCurrencyId = (int) $journal['foreign_currency_id']; if (0 !== $currencyId) { $response[$currencyId] = $response[$currencyId] ?? [ 'difference' => '0', 'difference_float' => 0, - 'currency_id' => (string)$currencyId, + 'currency_id' => (string) $currencyId, 'currency_code' => $journal['currency_code'], ]; $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], $journal['amount']); - $response[$currencyId]['difference_float'] = (float)$response[$currencyId]['difference']; + $response[$currencyId]['difference_float'] = (float) $response[$currencyId]['difference']; } if (0 !== $foreignCurrencyId) { $response[$foreignCurrencyId] = $response[$foreignCurrencyId] ?? [ 'difference' => '0', 'difference_float' => 0, - 'currency_id' => (string)$foreignCurrencyId, + 'currency_id' => (string) $foreignCurrencyId, 'currency_code' => $journal['foreign_currency_code'], ]; $response[$foreignCurrencyId]['difference'] = bcadd($response[$foreignCurrencyId]['difference'], $journal['foreign_amount']); - $response[$foreignCurrencyId]['difference_float'] = (float)$response[$foreignCurrencyId]['difference']; + $response[$foreignCurrencyId]['difference_float'] = (float) $response[$foreignCurrencyId]['difference']; } } diff --git a/app/Api/V1/Controllers/Insight/Expense/BudgetController.php b/app/Api/V1/Controllers/Insight/Expense/BudgetController.php index e8881e09ef..cf135f6abd 100644 --- a/app/Api/V1/Controllers/Insight/Expense/BudgetController.php +++ b/app/Api/V1/Controllers/Insight/Expense/BudgetController.php @@ -88,11 +88,11 @@ class BudgetController extends Controller /** @var array $expense */ foreach ($expenses as $expense) { $result[] = [ - 'id' => (string)$budget->id, + 'id' => (string) $budget->id, 'name' => $budget->name, 'difference' => $expense['sum'], - 'difference_float' => (float)$expense['sum'], - 'currency_id' => (string)$expense['currency_id'], + 'difference_float' => (float) $expense['sum'], + 'currency_id' => (string) $expense['currency_id'], 'currency_code' => $expense['currency_code'], ]; } @@ -120,8 +120,8 @@ class BudgetController extends Controller foreach ($expenses as $expense) { $result[] = [ 'difference' => $expense['sum'], - 'difference_float' => (float)$expense['sum'], - 'currency_id' => (string)$expense['currency_id'], + 'difference_float' => (float) $expense['sum'], + 'currency_id' => (string) $expense['currency_id'], 'currency_code' => $expense['currency_code'], ]; } diff --git a/app/Api/V1/Controllers/Insight/Expense/CategoryController.php b/app/Api/V1/Controllers/Insight/Expense/CategoryController.php index db8f31a2c3..cc2b25fc4a 100644 --- a/app/Api/V1/Controllers/Insight/Expense/CategoryController.php +++ b/app/Api/V1/Controllers/Insight/Expense/CategoryController.php @@ -89,11 +89,11 @@ class CategoryController extends Controller /** @var array $expense */ foreach ($expenses as $expense) { $result[] = [ - 'id' => (string)$category->id, + 'id' => (string) $category->id, 'name' => $category->name, 'difference' => $expense['sum'], - 'difference_float' => (float)$expense['sum'], - 'currency_id' => (string)$expense['currency_id'], + 'difference_float' => (float) $expense['sum'], + 'currency_id' => (string) $expense['currency_id'], 'currency_code' => $expense['currency_code'], ]; } @@ -121,8 +121,8 @@ class CategoryController extends Controller foreach ($expenses as $expense) { $result[] = [ 'difference' => $expense['sum'], - 'difference_float' => (float)$expense['sum'], - 'currency_id' => (string)$expense['currency_id'], + 'difference_float' => (float) $expense['sum'], + 'currency_id' => (string) $expense['currency_id'], 'currency_code' => $expense['currency_code'], ]; } diff --git a/app/Api/V1/Controllers/Insight/Expense/PeriodController.php b/app/Api/V1/Controllers/Insight/Expense/PeriodController.php index a83f6ca66a..6d32267b8f 100644 --- a/app/Api/V1/Controllers/Insight/Expense/PeriodController.php +++ b/app/Api/V1/Controllers/Insight/Expense/PeriodController.php @@ -55,28 +55,28 @@ class PeriodController extends Controller $collector->setTypes([TransactionType::WITHDRAWAL])->setRange($start, $end)->setSourceAccounts($accounts); $genericSet = $collector->getExtractedJournals(); foreach ($genericSet as $journal) { - $currencyId = (int)$journal['currency_id']; - $foreignCurrencyId = (int)$journal['foreign_currency_id']; + $currencyId = (int) $journal['currency_id']; + $foreignCurrencyId = (int) $journal['foreign_currency_id']; if (0 !== $currencyId) { $response[$currencyId] = $response[$currencyId] ?? [ 'difference' => '0', 'difference_float' => 0, - 'currency_id' => (string)$currencyId, + 'currency_id' => (string) $currencyId, 'currency_code' => $journal['currency_code'], ]; $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], $journal['amount']); - $response[$currencyId]['difference_float'] = (float)$response[$currencyId]['difference']; + $response[$currencyId]['difference_float'] = (float) $response[$currencyId]['difference']; } if (0 !== $foreignCurrencyId) { $response[$foreignCurrencyId] = $response[$foreignCurrencyId] ?? [ 'difference' => '0', 'difference_float' => 0, - 'currency_id' => (string)$foreignCurrencyId, + 'currency_id' => (string) $foreignCurrencyId, 'currency_code' => $journal['foreign_currency_code'], ]; $response[$foreignCurrencyId]['difference'] = bcadd($response[$foreignCurrencyId]['difference'], $journal['foreign_amount']); - $response[$foreignCurrencyId]['difference_float'] = (float)$response[$foreignCurrencyId]['difference']; + $response[$foreignCurrencyId]['difference_float'] = (float) $response[$foreignCurrencyId]['difference']; } } diff --git a/app/Api/V1/Controllers/Insight/Expense/TagController.php b/app/Api/V1/Controllers/Insight/Expense/TagController.php index d856d01c3d..9ea0a0fa04 100644 --- a/app/Api/V1/Controllers/Insight/Expense/TagController.php +++ b/app/Api/V1/Controllers/Insight/Expense/TagController.php @@ -79,28 +79,28 @@ class TagController extends Controller $genericSet = $collector->getExtractedJournals(); foreach ($genericSet as $journal) { - $currencyId = (int)$journal['currency_id']; - $foreignCurrencyId = (int)$journal['foreign_currency_id']; + $currencyId = (int) $journal['currency_id']; + $foreignCurrencyId = (int) $journal['foreign_currency_id']; if (0 !== $currencyId) { $response[$currencyId] = $response[$currencyId] ?? [ 'difference' => '0', 'difference_float' => 0, - 'currency_id' => (string)$currencyId, + 'currency_id' => (string) $currencyId, 'currency_code' => $journal['currency_code'], ]; $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], $journal['amount']); - $response[$currencyId]['difference_float'] = (float)$response[$currencyId]['difference']; + $response[$currencyId]['difference_float'] = (float) $response[$currencyId]['difference']; } if (0 !== $foreignCurrencyId) { $response[$foreignCurrencyId] = $response[$foreignCurrencyId] ?? [ 'difference' => '0', 'difference_float' => 0, - 'currency_id' => (string)$foreignCurrencyId, + 'currency_id' => (string) $foreignCurrencyId, 'currency_code' => $journal['foreign_currency_code'], ]; $response[$foreignCurrencyId]['difference'] = bcadd($response[$foreignCurrencyId]['difference'], $journal['foreign_amount']); - $response[$foreignCurrencyId]['difference_float'] = (float)$response[$foreignCurrencyId]['difference']; + $response[$foreignCurrencyId]['difference_float'] = (float) $response[$foreignCurrencyId]['difference']; } } @@ -137,8 +137,8 @@ class TagController extends Controller $genericSet = $collector->getExtractedJournals(); /** @var array $journal */ foreach ($genericSet as $journal) { - $currencyId = (int)$journal['currency_id']; - $foreignCurrencyId = (int)$journal['foreign_currency_id']; + $currencyId = (int) $journal['currency_id']; + $foreignCurrencyId = (int) $journal['foreign_currency_id']; /** @var array $tag */ foreach ($journal['tags'] as $tag) { @@ -149,15 +149,15 @@ class TagController extends Controller // on currency ID if (0 !== $currencyId) { $response[$key] = $response[$key] ?? [ - 'id' => (string)$tagId, + 'id' => (string) $tagId, 'name' => $tag['name'], 'difference' => '0', 'difference_float' => 0, - 'currency_id' => (string)$currencyId, + 'currency_id' => (string) $currencyId, 'currency_code' => $journal['currency_code'], ]; $response[$key]['difference'] = bcadd($response[$key]['difference'], $journal['amount']); - $response[$key]['difference_float'] = (float)$response[$key]['difference']; + $response[$key]['difference_float'] = (float) $response[$key]['difference']; } // on foreign ID @@ -165,11 +165,11 @@ class TagController extends Controller $response[$foreignKey] = $journal[$foreignKey] ?? [ 'difference' => '0', 'difference_float' => 0, - 'currency_id' => (string)$foreignCurrencyId, + 'currency_id' => (string) $foreignCurrencyId, 'currency_code' => $journal['foreign_currency_code'], ]; $response[$foreignKey]['difference'] = bcadd($response[$foreignKey]['difference'], $journal['foreign_amount']); - $response[$foreignKey]['difference_float'] = (float)$response[$foreignKey]['difference']; + $response[$foreignKey]['difference_float'] = (float) $response[$foreignKey]['difference']; } } } diff --git a/app/Api/V1/Controllers/Insight/Income/AccountController.php b/app/Api/V1/Controllers/Insight/Income/AccountController.php index 719a77ab6c..ecad08b6b4 100644 --- a/app/Api/V1/Controllers/Insight/Income/AccountController.php +++ b/app/Api/V1/Controllers/Insight/Income/AccountController.php @@ -90,11 +90,11 @@ class AccountController extends Controller /** @var array $entry */ foreach ($income as $entry) { $result[] = [ - 'id' => (string)$entry['id'], + 'id' => (string) $entry['id'], 'name' => $entry['name'], 'difference' => $entry['sum'], - 'difference_float' => (float)$entry['sum'], - 'currency_id' => (string)$entry['currency_id'], + 'difference_float' => (float) $entry['sum'], + 'currency_id' => (string) $entry['currency_id'], 'currency_code' => $entry['currency_code'], ]; } @@ -122,11 +122,11 @@ class AccountController extends Controller /** @var array $entry */ foreach ($income as $entry) { $result[] = [ - 'id' => (string)$entry['id'], + 'id' => (string) $entry['id'], 'name' => $entry['name'], 'difference' => $entry['sum'], - 'difference_float' => (float)$entry['sum'], - 'currency_id' => (string)$entry['currency_id'], + 'difference_float' => (float) $entry['sum'], + 'currency_id' => (string) $entry['currency_id'], 'currency_code' => $entry['currency_code'], ]; } diff --git a/app/Api/V1/Controllers/Insight/Income/CategoryController.php b/app/Api/V1/Controllers/Insight/Income/CategoryController.php index 47007f432f..79f0c4bf79 100644 --- a/app/Api/V1/Controllers/Insight/Income/CategoryController.php +++ b/app/Api/V1/Controllers/Insight/Income/CategoryController.php @@ -89,11 +89,11 @@ class CategoryController extends Controller /** @var array $expense */ foreach ($expenses as $expense) { $result[] = [ - 'id' => (string)$category->id, + 'id' => (string) $category->id, 'name' => $category->name, 'difference' => $expense['sum'], - 'difference_float' => (float)$expense['sum'], - 'currency_id' => (string)$expense['currency_id'], + 'difference_float' => (float) $expense['sum'], + 'currency_id' => (string) $expense['currency_id'], 'currency_code' => $expense['currency_code'], ]; } @@ -121,8 +121,8 @@ class CategoryController extends Controller foreach ($expenses as $expense) { $result[] = [ 'difference' => $expense['sum'], - 'difference_float' => (float)$expense['sum'], - 'currency_id' => (string)$expense['currency_id'], + 'difference_float' => (float) $expense['sum'], + 'currency_id' => (string) $expense['currency_id'], 'currency_code' => $expense['currency_code'], ]; } diff --git a/app/Api/V1/Controllers/Insight/Income/PeriodController.php b/app/Api/V1/Controllers/Insight/Income/PeriodController.php index 4ec6c12acb..41aa682337 100644 --- a/app/Api/V1/Controllers/Insight/Income/PeriodController.php +++ b/app/Api/V1/Controllers/Insight/Income/PeriodController.php @@ -55,30 +55,30 @@ class PeriodController extends Controller $collector->setTypes([TransactionType::DEPOSIT])->setRange($start, $end)->setDestinationAccounts($accounts); $genericSet = $collector->getExtractedJournals(); foreach ($genericSet as $journal) { - $currencyId = (int)$journal['currency_id']; - $foreignCurrencyId = (int)$journal['foreign_currency_id']; + $currencyId = (int) $journal['currency_id']; + $foreignCurrencyId = (int) $journal['foreign_currency_id']; if (0 !== $currencyId) { $response[$currencyId] = $response[$currencyId] ?? [ 'difference' => '0', 'difference_float' => 0, - 'currency_id' => (string)$currencyId, + 'currency_id' => (string) $currencyId, 'currency_code' => $journal['currency_code'], ]; $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], app('steam')->positive($journal['amount'])); - $response[$currencyId]['difference_float'] = (float)$response[$currencyId]['difference']; + $response[$currencyId]['difference_float'] = (float) $response[$currencyId]['difference']; } if (0 !== $foreignCurrencyId) { $response[$foreignCurrencyId] = $response[$foreignCurrencyId] ?? [ 'difference' => '0', 'difference_float' => 0, - 'currency_id' => (string)$foreignCurrencyId, + 'currency_id' => (string) $foreignCurrencyId, 'currency_code' => $journal['foreign_currency_code'], ]; $response[$foreignCurrencyId]['difference'] = bcadd( $response[$foreignCurrencyId]['difference'], app('steam')->positive($journal['foreign_amount']) ); - $response[$foreignCurrencyId]['difference_float'] = (float)$response[$foreignCurrencyId]['difference']; + $response[$foreignCurrencyId]['difference_float'] = (float) $response[$foreignCurrencyId]['difference']; } } diff --git a/app/Api/V1/Controllers/Insight/Income/TagController.php b/app/Api/V1/Controllers/Insight/Income/TagController.php index 8e58fbf01d..10ea364f8c 100644 --- a/app/Api/V1/Controllers/Insight/Income/TagController.php +++ b/app/Api/V1/Controllers/Insight/Income/TagController.php @@ -80,30 +80,30 @@ class TagController extends Controller $genericSet = $collector->getExtractedJournals(); foreach ($genericSet as $journal) { - $currencyId = (int)$journal['currency_id']; - $foreignCurrencyId = (int)$journal['foreign_currency_id']; + $currencyId = (int) $journal['currency_id']; + $foreignCurrencyId = (int) $journal['foreign_currency_id']; if (0 !== $currencyId) { $response[$currencyId] = $response[$currencyId] ?? [ 'difference' => '0', 'difference_float' => 0, - 'currency_id' => (string)$currencyId, + 'currency_id' => (string) $currencyId, 'currency_code' => $journal['currency_code'], ]; $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], app('steam')->positive($journal['amount'])); - $response[$currencyId]['difference_float'] = (float)$response[$currencyId]['difference']; + $response[$currencyId]['difference_float'] = (float) $response[$currencyId]['difference']; } if (0 !== $foreignCurrencyId) { $response[$foreignCurrencyId] = $response[$foreignCurrencyId] ?? [ 'difference' => '0', 'difference_float' => 0, - 'currency_id' => (string)$foreignCurrencyId, + 'currency_id' => (string) $foreignCurrencyId, 'currency_code' => $journal['foreign_currency_code'], ]; $response[$foreignCurrencyId]['difference'] = bcadd( $response[$foreignCurrencyId]['difference'], app('steam')->positive($journal['foreign_amount']) ); - $response[$foreignCurrencyId]['difference_float'] = (float)$response[$foreignCurrencyId]['difference']; + $response[$foreignCurrencyId]['difference_float'] = (float) $response[$foreignCurrencyId]['difference']; } } @@ -140,8 +140,8 @@ class TagController extends Controller $genericSet = $collector->getExtractedJournals(); /** @var array $journal */ foreach ($genericSet as $journal) { - $currencyId = (int)$journal['currency_id']; - $foreignCurrencyId = (int)$journal['foreign_currency_id']; + $currencyId = (int) $journal['currency_id']; + $foreignCurrencyId = (int) $journal['foreign_currency_id']; /** @var array $tag */ foreach ($journal['tags'] as $tag) { @@ -152,15 +152,15 @@ class TagController extends Controller // on currency ID if (0 !== $currencyId) { $response[$key] = $response[$key] ?? [ - 'id' => (string)$tagId, + 'id' => (string) $tagId, 'name' => $tag['name'], 'difference' => '0', 'difference_float' => 0, - 'currency_id' => (string)$currencyId, + 'currency_id' => (string) $currencyId, 'currency_code' => $journal['currency_code'], ]; $response[$key]['difference'] = bcadd($response[$key]['difference'], app('steam')->positive($journal['amount'])); - $response[$key]['difference_float'] = (float)$response[$key]['difference']; + $response[$key]['difference_float'] = (float) $response[$key]['difference']; } // on foreign ID @@ -168,13 +168,13 @@ class TagController extends Controller $response[$foreignKey] = $journal[$foreignKey] ?? [ 'difference' => '0', 'difference_float' => 0, - 'currency_id' => (string)$foreignCurrencyId, + 'currency_id' => (string) $foreignCurrencyId, 'currency_code' => $journal['foreign_currency_code'], ]; $response[$foreignKey]['difference'] = bcadd( $response[$foreignKey]['difference'], app('steam')->positive($journal['foreign_amount']) ); - $response[$foreignKey]['difference_float'] = (float)$response[$foreignKey]['difference']; + $response[$foreignKey]['difference_float'] = (float) $response[$foreignKey]['difference']; } } } diff --git a/app/Api/V1/Controllers/Insight/Transfer/CategoryController.php b/app/Api/V1/Controllers/Insight/Transfer/CategoryController.php index 43b77675ed..d42772f9be 100644 --- a/app/Api/V1/Controllers/Insight/Transfer/CategoryController.php +++ b/app/Api/V1/Controllers/Insight/Transfer/CategoryController.php @@ -88,11 +88,11 @@ class CategoryController extends Controller /** @var array $expense */ foreach ($expenses as $expense) { $result[] = [ - 'id' => (string)$category->id, + 'id' => (string) $category->id, 'name' => $category->name, 'difference' => $expense['sum'], - 'difference_float' => (float)$expense['sum'], - 'currency_id' => (string)$expense['currency_id'], + 'difference_float' => (float) $expense['sum'], + 'currency_id' => (string) $expense['currency_id'], 'currency_code' => $expense['currency_code'], ]; } @@ -120,8 +120,8 @@ class CategoryController extends Controller foreach ($expenses as $expense) { $result[] = [ 'difference' => $expense['sum'], - 'difference_float' => (float)$expense['sum'], - 'currency_id' => (string)$expense['currency_id'], + 'difference_float' => (float) $expense['sum'], + 'currency_id' => (string) $expense['currency_id'], 'currency_code' => $expense['currency_code'], ]; } diff --git a/app/Api/V1/Controllers/Insight/Transfer/PeriodController.php b/app/Api/V1/Controllers/Insight/Transfer/PeriodController.php index ecb42d4a9f..8f8eab7428 100644 --- a/app/Api/V1/Controllers/Insight/Transfer/PeriodController.php +++ b/app/Api/V1/Controllers/Insight/Transfer/PeriodController.php @@ -55,30 +55,30 @@ class PeriodController extends Controller $collector->setTypes([TransactionType::TRANSFER])->setRange($start, $end)->setDestinationAccounts($accounts); $genericSet = $collector->getExtractedJournals(); foreach ($genericSet as $journal) { - $currencyId = (int)$journal['currency_id']; - $foreignCurrencyId = (int)$journal['foreign_currency_id']; + $currencyId = (int) $journal['currency_id']; + $foreignCurrencyId = (int) $journal['foreign_currency_id']; if (0 !== $currencyId) { $response[$currencyId] = $response[$currencyId] ?? [ 'difference' => '0', 'difference_float' => 0, - 'currency_id' => (string)$currencyId, + 'currency_id' => (string) $currencyId, 'currency_code' => $journal['currency_code'], ]; $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], app('steam')->positive($journal['amount'])); - $response[$currencyId]['difference_float'] = (float)$response[$currencyId]['difference']; + $response[$currencyId]['difference_float'] = (float) $response[$currencyId]['difference']; } if (0 !== $foreignCurrencyId) { $response[$foreignCurrencyId] = $response[$foreignCurrencyId] ?? [ 'difference' => '0', 'difference_float' => 0, - 'currency_id' => (string)$foreignCurrencyId, + 'currency_id' => (string) $foreignCurrencyId, 'currency_code' => $journal['foreign_currency_code'], ]; $response[$foreignCurrencyId]['difference'] = bcadd( $response[$foreignCurrencyId]['difference'], app('steam')->positive($journal['foreign_amount']) ); - $response[$foreignCurrencyId]['difference_float'] = (float)$response[$foreignCurrencyId]['difference']; + $response[$foreignCurrencyId]['difference_float'] = (float) $response[$foreignCurrencyId]['difference']; } } diff --git a/app/Api/V1/Controllers/Insight/Transfer/TagController.php b/app/Api/V1/Controllers/Insight/Transfer/TagController.php index 59404dcbbb..edd0ab859f 100644 --- a/app/Api/V1/Controllers/Insight/Transfer/TagController.php +++ b/app/Api/V1/Controllers/Insight/Transfer/TagController.php @@ -77,30 +77,30 @@ class TagController extends Controller $genericSet = $collector->getExtractedJournals(); foreach ($genericSet as $journal) { - $currencyId = (int)$journal['currency_id']; - $foreignCurrencyId = (int)$journal['foreign_currency_id']; + $currencyId = (int) $journal['currency_id']; + $foreignCurrencyId = (int) $journal['foreign_currency_id']; if (0 !== $currencyId) { $response[$currencyId] = $response[$currencyId] ?? [ 'difference' => '0', 'difference_float' => 0, - 'currency_id' => (string)$currencyId, + 'currency_id' => (string) $currencyId, 'currency_code' => $journal['currency_code'], ]; $response[$currencyId]['difference'] = bcadd($response[$currencyId]['difference'], app('steam')->positive($journal['amount'])); - $response[$currencyId]['difference_float'] = (float)$response[$currencyId]['difference']; + $response[$currencyId]['difference_float'] = (float) $response[$currencyId]['difference']; } if (0 !== $foreignCurrencyId) { $response[$foreignCurrencyId] = $response[$foreignCurrencyId] ?? [ 'difference' => '0', 'difference_float' => 0, - 'currency_id' => (string)$foreignCurrencyId, + 'currency_id' => (string) $foreignCurrencyId, 'currency_code' => $journal['foreign_currency_code'], ]; $response[$foreignCurrencyId]['difference'] = bcadd( $response[$foreignCurrencyId]['difference'], app('steam')->positive($journal['foreign_amount']) ); - $response[$foreignCurrencyId]['difference_float'] = (float)$response[$foreignCurrencyId]['difference']; + $response[$foreignCurrencyId]['difference_float'] = (float) $response[$foreignCurrencyId]['difference']; } } @@ -137,8 +137,8 @@ class TagController extends Controller $genericSet = $collector->getExtractedJournals(); /** @var array $journal */ foreach ($genericSet as $journal) { - $currencyId = (int)$journal['currency_id']; - $foreignCurrencyId = (int)$journal['foreign_currency_id']; + $currencyId = (int) $journal['currency_id']; + $foreignCurrencyId = (int) $journal['foreign_currency_id']; /** @var array $tag */ foreach ($journal['tags'] as $tag) { @@ -149,15 +149,15 @@ class TagController extends Controller // on currency ID if (0 !== $currencyId) { $response[$key] = $response[$key] ?? [ - 'id' => (string)$tagId, + 'id' => (string) $tagId, 'name' => $tag['name'], 'difference' => '0', 'difference_float' => 0, - 'currency_id' => (string)$currencyId, + 'currency_id' => (string) $currencyId, 'currency_code' => $journal['currency_code'], ]; $response[$key]['difference'] = bcadd($response[$key]['difference'], app('steam')->positive($journal['amount'])); - $response[$key]['difference_float'] = (float)$response[$key]['difference']; + $response[$key]['difference_float'] = (float) $response[$key]['difference']; } // on foreign ID @@ -165,13 +165,13 @@ class TagController extends Controller $response[$foreignKey] = $journal[$foreignKey] ?? [ 'difference' => '0', 'difference_float' => 0, - 'currency_id' => (string)$foreignCurrencyId, + 'currency_id' => (string) $foreignCurrencyId, 'currency_code' => $journal['foreign_currency_code'], ]; $response[$foreignKey]['difference'] = bcadd( $response[$foreignKey]['difference'], app('steam')->positive($journal['foreign_amount']) ); - $response[$foreignKey]['difference_float'] = (float)$response[$foreignKey]['difference']; + $response[$foreignKey]['difference_float'] = (float) $response[$foreignKey]['difference']; } } } diff --git a/app/Api/V1/Controllers/Models/Account/ListController.php b/app/Api/V1/Controllers/Models/Account/ListController.php index 9731129957..a56131a639 100644 --- a/app/Api/V1/Controllers/Models/Account/ListController.php +++ b/app/Api/V1/Controllers/Models/Account/ListController.php @@ -82,7 +82,7 @@ class ListController extends Controller public function attachments(Account $account): 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($account); $count = $collection->count(); @@ -118,7 +118,7 @@ class ListController 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); @@ -156,7 +156,7 @@ class ListController 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); diff --git a/app/Api/V1/Controllers/Models/Account/ShowController.php b/app/Api/V1/Controllers/Models/Account/ShowController.php index a5650ebf23..3ad5c13933 100644 --- a/app/Api/V1/Controllers/Models/Account/ShowController.php +++ b/app/Api/V1/Controllers/Models/Account/ShowController.php @@ -84,8 +84,8 @@ class ShowController extends Controller $this->parameters->set('type', $type); // types to get, page size: - $types = $this->mapAccountTypes($this->parameters->get('type')); - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $types = $this->mapAccountTypes($this->parameters->get('type')); + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; // get list of accounts. Count it and split it. $this->repository->resetAccountOrder(); diff --git a/app/Api/V1/Controllers/Models/Account/UpdateController.php b/app/Api/V1/Controllers/Models/Account/UpdateController.php index 49a6f2c794..65221bbeda 100644 --- a/app/Api/V1/Controllers/Models/Account/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Account/UpdateController.php @@ -74,10 +74,10 @@ class UpdateController extends Controller public function update(UpdateRequest $request, Account $account): JsonResponse { Log::debug(sprintf('Now in %s', __METHOD__)); - $data = $request->getUpdateData(); + $data = $request->getUpdateData(); $data['type'] = config('firefly.shortNamesByFullName.' . $account->accountType->type); - $account = $this->repository->update($account, $data); - $manager = $this->getManager(); + $account = $this->repository->update($account, $data); + $manager = $this->getManager(); $account->refresh(); Preferences::mark(); diff --git a/app/Api/V1/Controllers/Models/Attachment/DestroyController.php b/app/Api/V1/Controllers/Models/Attachment/DestroyController.php index bbf72975d9..3fad5d77bd 100644 --- a/app/Api/V1/Controllers/Models/Attachment/DestroyController.php +++ b/app/Api/V1/Controllers/Models/Attachment/DestroyController.php @@ -49,7 +49,7 @@ class DestroyController extends Controller $this->middleware( function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->repository = app(AttachmentRepositoryInterface::class); $this->repository->setUser($user); diff --git a/app/Api/V1/Controllers/Models/Attachment/ShowController.php b/app/Api/V1/Controllers/Models/Attachment/ShowController.php index e724d80d52..55537851c8 100644 --- a/app/Api/V1/Controllers/Models/Attachment/ShowController.php +++ b/app/Api/V1/Controllers/Models/Attachment/ShowController.php @@ -103,7 +103,7 @@ class ShowController extends Controller ->header('Expires', '0') ->header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0') ->header('Pragma', 'public') - ->header('Content-Length', (string)strlen($content)); + ->header('Content-Length', (string) strlen($content)); return $response; } @@ -125,7 +125,7 @@ class ShowController 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 attachments. Count it and split it. $collection = $this->repository->get(); diff --git a/app/Api/V1/Controllers/Models/Attachment/UpdateController.php b/app/Api/V1/Controllers/Models/Attachment/UpdateController.php index fda955b2bf..f5d350b1e4 100644 --- a/app/Api/V1/Controllers/Models/Attachment/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Attachment/UpdateController.php @@ -52,7 +52,7 @@ class UpdateController extends Controller $this->middleware( function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->repository = app(AttachmentRepositoryInterface::class); $this->repository->setUser($user); diff --git a/app/Api/V1/Controllers/Models/AvailableBudget/DestroyController.php b/app/Api/V1/Controllers/Models/AvailableBudget/DestroyController.php index 8eda2dda48..0297e839c7 100644 --- a/app/Api/V1/Controllers/Models/AvailableBudget/DestroyController.php +++ b/app/Api/V1/Controllers/Models/AvailableBudget/DestroyController.php @@ -47,7 +47,7 @@ class DestroyController extends Controller $this->middleware( function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->abRepository = app(AvailableBudgetRepositoryInterface::class); $this->abRepository->setUser($user); diff --git a/app/Api/V1/Controllers/Models/AvailableBudget/ShowController.php b/app/Api/V1/Controllers/Models/AvailableBudget/ShowController.php index 24d7a1608b..210648d109 100644 --- a/app/Api/V1/Controllers/Models/AvailableBudget/ShowController.php +++ b/app/Api/V1/Controllers/Models/AvailableBudget/ShowController.php @@ -77,7 +77,7 @@ class ShowController 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/Models/Bill/ListController.php b/app/Api/V1/Controllers/Models/Bill/ListController.php index b73e94942b..686277b718 100644 --- a/app/Api/V1/Controllers/Models/Bill/ListController.php +++ b/app/Api/V1/Controllers/Models/Bill/ListController.php @@ -81,7 +81,7 @@ class ListController 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(); @@ -118,7 +118,7 @@ class ListController 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); @@ -155,7 +155,7 @@ class ListController 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/Models/Bill/ShowController.php b/app/Api/V1/Controllers/Models/Bill/ShowController.php index 5246af526a..2fba6af816 100644 --- a/app/Api/V1/Controllers/Models/Bill/ShowController.php +++ b/app/Api/V1/Controllers/Models/Bill/ShowController.php @@ -74,7 +74,7 @@ class ShowController extends Controller $this->repository->correctOrder(); $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')); diff --git a/app/Api/V1/Controllers/Models/Bill/StoreController.php b/app/Api/V1/Controllers/Models/Bill/StoreController.php index f28e8fbdfe..7c5cd8b3b5 100644 --- a/app/Api/V1/Controllers/Models/Bill/StoreController.php +++ b/app/Api/V1/Controllers/Models/Bill/StoreController.php @@ -72,8 +72,8 @@ class StoreController extends Controller */ public function store(StoreRequest $request): JsonResponse { - $data = $request->getAll(); - $bill = $this->repository->store($data); + $data = $request->getAll(); + $bill = $this->repository->store($data); $manager = $this->getManager(); /** @var BillTransformer $transformer */ diff --git a/app/Api/V1/Controllers/Models/Bill/UpdateController.php b/app/Api/V1/Controllers/Models/Bill/UpdateController.php index d5fdf38b03..2705e62263 100644 --- a/app/Api/V1/Controllers/Models/Bill/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Bill/UpdateController.php @@ -69,8 +69,8 @@ class UpdateController extends Controller */ public function update(UpdateRequest $request, Bill $bill): JsonResponse { - $data = $request->getAll(); - $bill = $this->repository->update($bill, $data); + $data = $request->getAll(); + $bill = $this->repository->update($bill, $data); $manager = $this->getManager(); /** @var BillTransformer $transformer */ diff --git a/app/Api/V1/Controllers/Models/Budget/ListController.php b/app/Api/V1/Controllers/Models/Budget/ListController.php index 8fdddd2513..ca2f2fe078 100644 --- a/app/Api/V1/Controllers/Models/Budget/ListController.php +++ b/app/Api/V1/Controllers/Models/Budget/ListController.php @@ -83,7 +83,7 @@ class ListController extends Controller public function attachments(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; $collection = $this->repository->getAttachments($budget); $count = $collection->count(); @@ -118,7 +118,7 @@ class ListController 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(); @@ -151,7 +151,7 @@ class ListController 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'); @@ -209,15 +209,13 @@ class ListController extends Controller * * @param Request $request * - * @param Budget $budget - * * @return JsonResponse * @throws FireflyException * @codeCoverageIgnore */ public function withoutBudget(Request $request): 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'); diff --git a/app/Api/V1/Controllers/Models/Budget/ShowController.php b/app/Api/V1/Controllers/Models/Budget/ShowController.php index f2831e1918..d408bccf5e 100644 --- a/app/Api/V1/Controllers/Models/Budget/ShowController.php +++ b/app/Api/V1/Controllers/Models/Budget/ShowController.php @@ -53,7 +53,7 @@ class ShowController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - $this->repository = app(BudgetRepositoryInterface::class); + $this->repository = app(BudgetRepositoryInterface::class); $this->blRepository = app(BudgetLimitRepositoryInterface::class); $this->repository->setUser(auth()->user()); $this->blRepository->setUser(auth()->user()); @@ -78,7 +78,7 @@ class ShowController 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(); diff --git a/app/Api/V1/Controllers/Models/BudgetLimit/ListController.php b/app/Api/V1/Controllers/Models/BudgetLimit/ListController.php index 79a03c0cce..8b2b2276e4 100644 --- a/app/Api/V1/Controllers/Models/BudgetLimit/ListController.php +++ b/app/Api/V1/Controllers/Models/BudgetLimit/ListController.php @@ -81,7 +81,7 @@ class ListController extends Controller */ public function transactions(Request $request, Budget $budget, 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/Models/BudgetLimit/ShowController.php b/app/Api/V1/Controllers/Models/BudgetLimit/ShowController.php index 108a8612d8..ac628b3550 100644 --- a/app/Api/V1/Controllers/Models/BudgetLimit/ShowController.php +++ b/app/Api/V1/Controllers/Models/BudgetLimit/ShowController.php @@ -86,7 +86,7 @@ class ShowController extends Controller { $manager = $this->getManager(); $manager->parseIncludes('budget'); - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; $collection = $this->blRepository->getBudgetLimits($budget, $this->parameters->get('start'), $this->parameters->get('end')); $count = $collection->count(); $budgetLimits = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); @@ -119,7 +119,7 @@ class ShowController extends Controller { $manager = $this->getManager(); $manager->parseIncludes('budget'); - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; $collection = $this->blRepository->getAllBudgetLimits($this->parameters->get('start'), $this->parameters->get('end')); $count = $collection->count(); $budgetLimits = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); @@ -149,7 +149,7 @@ class ShowController extends Controller */ public function show(Request $request, Budget $budget, BudgetLimit $budgetLimit): JsonResponse { - if ((int)$budget->id !== (int)$budgetLimit->budget_id) { + if ((int) $budget->id !== (int) $budgetLimit->budget_id) { throw new FireflyException('20028: The budget limit does not belong to the budget.'); } // continue! diff --git a/app/Api/V1/Controllers/Models/BudgetLimit/UpdateController.php b/app/Api/V1/Controllers/Models/BudgetLimit/UpdateController.php index 54150f26da..9325d3297d 100644 --- a/app/Api/V1/Controllers/Models/BudgetLimit/UpdateController.php +++ b/app/Api/V1/Controllers/Models/BudgetLimit/UpdateController.php @@ -77,7 +77,7 @@ class UpdateController extends Controller public function update(UpdateRequest $request, Budget $budget, BudgetLimit $budgetLimit): JsonResponse { - if ((int)$budget->id !== (int)$budgetLimit->budget_id) { + if ((int) $budget->id !== (int) $budgetLimit->budget_id) { throw new FireflyException('20028: The budget limit does not belong to the budget.'); } $data = $request->getAll(); diff --git a/app/Api/V1/Controllers/Models/Category/ListController.php b/app/Api/V1/Controllers/Models/Category/ListController.php index ceb2fd5d1e..1cfdf8e268 100644 --- a/app/Api/V1/Controllers/Models/Category/ListController.php +++ b/app/Api/V1/Controllers/Models/Category/ListController.php @@ -78,7 +78,7 @@ class ListController extends Controller public function attachments(Category $category): 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($category); $count = $collection->count(); @@ -114,7 +114,7 @@ class ListController 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/Models/Category/ShowController.php b/app/Api/V1/Controllers/Models/Category/ShowController.php index d463a6ce52..0f18d8f831 100644 --- a/app/Api/V1/Controllers/Models/Category/ShowController.php +++ b/app/Api/V1/Controllers/Models/Category/ShowController.php @@ -74,7 +74,7 @@ class ShowController 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(); diff --git a/app/Api/V1/Controllers/Models/Category/UpdateController.php b/app/Api/V1/Controllers/Models/Category/UpdateController.php index 66bfce6859..f7d3532da0 100644 --- a/app/Api/V1/Controllers/Models/Category/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Category/UpdateController.php @@ -69,9 +69,9 @@ class UpdateController extends Controller */ public function update(UpdateRequest $request, Category $category): JsonResponse { - $data = $request->getAll(); + $data = $request->getAll(); $category = $this->repository->update($category, $data); - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var CategoryTransformer $transformer */ $transformer = app(CategoryTransformer::class); diff --git a/app/Api/V1/Controllers/Models/ObjectGroup/DestroyController.php b/app/Api/V1/Controllers/Models/ObjectGroup/DestroyController.php index cc8211b4dd..bbb27aa355 100644 --- a/app/Api/V1/Controllers/Models/ObjectGroup/DestroyController.php +++ b/app/Api/V1/Controllers/Models/ObjectGroup/DestroyController.php @@ -47,7 +47,7 @@ class DestroyController extends Controller $this->middleware( function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->repository = app(ObjectGroupRepositoryInterface::class); $this->repository->setUser($user); diff --git a/app/Api/V1/Controllers/Models/ObjectGroup/ListController.php b/app/Api/V1/Controllers/Models/ObjectGroup/ListController.php index 8ac8308e6f..907500a309 100644 --- a/app/Api/V1/Controllers/Models/ObjectGroup/ListController.php +++ b/app/Api/V1/Controllers/Models/ObjectGroup/ListController.php @@ -53,7 +53,7 @@ class ListController extends Controller $this->middleware( function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->repository = app(ObjectGroupRepositoryInterface::class); $this->repository->setUser($user); @@ -78,7 +78,7 @@ class ListController extends Controller { $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 piggy banks. Count it and split it. $collection = $this->repository->getBills($objectGroup); $count = $collection->count(); @@ -116,7 +116,7 @@ class ListController 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 piggy banks. Count it and split it. $collection = $this->repository->getPiggyBanks($objectGroup); diff --git a/app/Api/V1/Controllers/Models/ObjectGroup/ShowController.php b/app/Api/V1/Controllers/Models/ObjectGroup/ShowController.php index c11d756761..bfc001fa93 100644 --- a/app/Api/V1/Controllers/Models/ObjectGroup/ShowController.php +++ b/app/Api/V1/Controllers/Models/ObjectGroup/ShowController.php @@ -80,7 +80,7 @@ class ShowController 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; $this->repository->resetOrder(); $collection = $this->repository->get(); diff --git a/app/Api/V1/Controllers/Models/ObjectGroup/UpdateController.php b/app/Api/V1/Controllers/Models/ObjectGroup/UpdateController.php index 45a8858f39..ceb2e32dc9 100644 --- a/app/Api/V1/Controllers/Models/ObjectGroup/UpdateController.php +++ b/app/Api/V1/Controllers/Models/ObjectGroup/UpdateController.php @@ -50,7 +50,7 @@ class UpdateController extends Controller $this->middleware( function ($request, $next) { /** @var User $user */ - $user = auth()->user(); + $user = auth()->user(); $this->repository = app(ObjectGroupRepositoryInterface::class); $this->repository->setUser($user); diff --git a/app/Api/V1/Controllers/Models/PiggyBank/ListController.php b/app/Api/V1/Controllers/Models/PiggyBank/ListController.php index 264e5dc528..d7537df365 100644 --- a/app/Api/V1/Controllers/Models/PiggyBank/ListController.php +++ b/app/Api/V1/Controllers/Models/PiggyBank/ListController.php @@ -72,7 +72,7 @@ class ListController extends Controller public function attachments(PiggyBank $piggyBank): 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($piggyBank); $count = $collection->count(); @@ -107,7 +107,7 @@ class ListController 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); diff --git a/app/Api/V1/Controllers/Models/PiggyBank/ShowController.php b/app/Api/V1/Controllers/Models/PiggyBank/ShowController.php index 37e86c867d..ccdcaeebf5 100644 --- a/app/Api/V1/Controllers/Models/PiggyBank/ShowController.php +++ b/app/Api/V1/Controllers/Models/PiggyBank/ShowController.php @@ -73,7 +73,7 @@ class ShowController 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(); diff --git a/app/Api/V1/Controllers/Models/PiggyBank/UpdateController.php b/app/Api/V1/Controllers/Models/PiggyBank/UpdateController.php index e6634cf5e2..41d69b904b 100644 --- a/app/Api/V1/Controllers/Models/PiggyBank/UpdateController.php +++ b/app/Api/V1/Controllers/Models/PiggyBank/UpdateController.php @@ -69,7 +69,7 @@ class UpdateController extends Controller */ public function update(UpdateRequest $request, PiggyBank $piggyBank): JsonResponse { - $data = $request->getAll(); + $data = $request->getAll(); $piggyBank = $this->repository->update($piggyBank, $data); if (array_key_exists('current_amount', $data) && '' !== $data['current_amount']) { diff --git a/app/Api/V1/Controllers/Models/Recurrence/ListController.php b/app/Api/V1/Controllers/Models/Recurrence/ListController.php index 17cf615b66..9b13fc88d7 100644 --- a/app/Api/V1/Controllers/Models/Recurrence/ListController.php +++ b/app/Api/V1/Controllers/Models/Recurrence/ListController.php @@ -78,7 +78,7 @@ class ListController 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); diff --git a/app/Api/V1/Controllers/Models/Recurrence/ShowController.php b/app/Api/V1/Controllers/Models/Recurrence/ShowController.php index ecb7438755..1d53b2528a 100644 --- a/app/Api/V1/Controllers/Models/Recurrence/ShowController.php +++ b/app/Api/V1/Controllers/Models/Recurrence/ShowController.php @@ -74,7 +74,7 @@ class ShowController 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(); diff --git a/app/Api/V1/Controllers/Models/Recurrence/StoreController.php b/app/Api/V1/Controllers/Models/Recurrence/StoreController.php index 03c60fd43a..8ca5672b2a 100644 --- a/app/Api/V1/Controllers/Models/Recurrence/StoreController.php +++ b/app/Api/V1/Controllers/Models/Recurrence/StoreController.php @@ -69,9 +69,9 @@ class StoreController extends Controller */ public function store(StoreRequest $request): JsonResponse { - $data = $request->getAll(); + $data = $request->getAll(); $recurrence = $this->repository->store($data); - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var RecurrenceTransformer $transformer */ $transformer = app(RecurrenceTransformer::class); diff --git a/app/Api/V1/Controllers/Models/Recurrence/UpdateController.php b/app/Api/V1/Controllers/Models/Recurrence/UpdateController.php index 18696ee68e..8e0ec86815 100644 --- a/app/Api/V1/Controllers/Models/Recurrence/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Recurrence/UpdateController.php @@ -69,9 +69,9 @@ class UpdateController extends Controller */ public function update(UpdateRequest $request, Recurrence $recurrence): JsonResponse { - $data = $request->getAll(); + $data = $request->getAll(); $recurrence = $this->repository->update($recurrence, $data); - $manager = $this->getManager(); + $manager = $this->getManager(); /** @var RecurrenceTransformer $transformer */ $transformer = app(RecurrenceTransformer::class); diff --git a/app/Api/V1/Controllers/Models/Rule/ShowController.php b/app/Api/V1/Controllers/Models/Rule/ShowController.php index 6ab5b01e2c..c633aac828 100644 --- a/app/Api/V1/Controllers/Models/Rule/ShowController.php +++ b/app/Api/V1/Controllers/Models/Rule/ShowController.php @@ -78,7 +78,7 @@ class ShowController 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(); diff --git a/app/Api/V1/Controllers/Models/Rule/StoreController.php b/app/Api/V1/Controllers/Models/Rule/StoreController.php index 7d861c71f4..322cf814d5 100644 --- a/app/Api/V1/Controllers/Models/Rule/StoreController.php +++ b/app/Api/V1/Controllers/Models/Rule/StoreController.php @@ -71,7 +71,7 @@ class StoreController extends Controller */ public function store(StoreRequest $request): JsonResponse { - $rule = $this->ruleRepository->store($request->getAll()); + $rule = $this->ruleRepository->store($request->getAll()); $manager = $this->getManager(); /** @var RuleTransformer $transformer */ $transformer = app(RuleTransformer::class); diff --git a/app/Api/V1/Controllers/Models/Rule/UpdateController.php b/app/Api/V1/Controllers/Models/Rule/UpdateController.php index 28859b99de..b8e3996e8b 100644 --- a/app/Api/V1/Controllers/Models/Rule/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Rule/UpdateController.php @@ -73,8 +73,8 @@ class UpdateController extends Controller */ public function update(UpdateRequest $request, Rule $rule): JsonResponse { - $data = $request->getAll(); - $rule = $this->ruleRepository->update($rule, $data); + $data = $request->getAll(); + $rule = $this->ruleRepository->update($rule, $data); $manager = $this->getManager(); /** @var RuleTransformer $transformer */ diff --git a/app/Api/V1/Controllers/Models/RuleGroup/ListController.php b/app/Api/V1/Controllers/Models/RuleGroup/ListController.php index 30e7c3a68b..f730025352 100644 --- a/app/Api/V1/Controllers/Models/RuleGroup/ListController.php +++ b/app/Api/V1/Controllers/Models/RuleGroup/ListController.php @@ -76,7 +76,7 @@ class ListController 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); diff --git a/app/Api/V1/Controllers/Models/RuleGroup/ShowController.php b/app/Api/V1/Controllers/Models/RuleGroup/ShowController.php index 7e77e6fd41..da714489aa 100644 --- a/app/Api/V1/Controllers/Models/RuleGroup/ShowController.php +++ b/app/Api/V1/Controllers/Models/RuleGroup/ShowController.php @@ -76,7 +76,7 @@ class ShowController 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(); diff --git a/app/Api/V1/Controllers/Models/RuleGroup/StoreController.php b/app/Api/V1/Controllers/Models/RuleGroup/StoreController.php index 0487988536..5f87c6866f 100644 --- a/app/Api/V1/Controllers/Models/RuleGroup/StoreController.php +++ b/app/Api/V1/Controllers/Models/RuleGroup/StoreController.php @@ -38,7 +38,7 @@ use League\Fractal\Resource\Item; class StoreController extends Controller { - private AccountRepositoryInterface $accountRepository; + private AccountRepositoryInterface $accountRepository; private RuleGroupRepositoryInterface $ruleGroupRepository; /** diff --git a/app/Api/V1/Controllers/Models/Tag/ListController.php b/app/Api/V1/Controllers/Models/Tag/ListController.php index 51ef7f7307..855a7169f2 100644 --- a/app/Api/V1/Controllers/Models/Tag/ListController.php +++ b/app/Api/V1/Controllers/Models/Tag/ListController.php @@ -81,7 +81,7 @@ class ListController extends Controller public function attachments(Tag $tag): 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($tag); $count = $collection->count(); @@ -116,7 +116,7 @@ class ListController 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); diff --git a/app/Api/V1/Controllers/Models/Tag/ShowController.php b/app/Api/V1/Controllers/Models/Tag/ShowController.php index dc4e58162d..3aede9926f 100644 --- a/app/Api/V1/Controllers/Models/Tag/ShowController.php +++ b/app/Api/V1/Controllers/Models/Tag/ShowController.php @@ -77,7 +77,7 @@ class ShowController 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(); diff --git a/app/Api/V1/Controllers/Models/Tag/StoreController.php b/app/Api/V1/Controllers/Models/Tag/StoreController.php index c31e903c6a..9b2dcff1c5 100644 --- a/app/Api/V1/Controllers/Models/Tag/StoreController.php +++ b/app/Api/V1/Controllers/Models/Tag/StoreController.php @@ -71,7 +71,7 @@ class StoreController extends Controller */ public function store(StoreRequest $request): JsonResponse { - $rule = $this->repository->store($request->getAll()); + $rule = $this->repository->store($request->getAll()); $manager = $this->getManager(); /** @var TagTransformer $transformer */ $transformer = app(TagTransformer::class); diff --git a/app/Api/V1/Controllers/Models/Tag/UpdateController.php b/app/Api/V1/Controllers/Models/Tag/UpdateController.php index 377c362f3f..5646a4b302 100644 --- a/app/Api/V1/Controllers/Models/Tag/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Tag/UpdateController.php @@ -73,7 +73,7 @@ class UpdateController extends Controller */ public function update(UpdateRequest $request, Tag $tag): JsonResponse { - $rule = $this->repository->update($tag, $request->getAll()); + $rule = $this->repository->update($tag, $request->getAll()); $manager = $this->getManager(); /** @var TagTransformer $transformer */ $transformer = app(TagTransformer::class); diff --git a/app/Api/V1/Controllers/Models/Transaction/ListController.php b/app/Api/V1/Controllers/Models/Transaction/ListController.php index 19e9569df1..025836433b 100644 --- a/app/Api/V1/Controllers/Models/Transaction/ListController.php +++ b/app/Api/V1/Controllers/Models/Transaction/ListController.php @@ -79,7 +79,7 @@ class ListController extends Controller public function attachments(TransactionGroup $transactionGroup): 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 = new Collection; foreach ($transactionGroup->transactionJournals as $transactionJournal) { $collection = $this->journalAPIRepository->getAttachments($transactionJournal)->merge($collection); @@ -116,7 +116,7 @@ class ListController extends Controller { $manager = $this->getManager(); $collection = new Collection; - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; foreach ($transactionGroup->transactionJournals as $transactionJournal) { $collection = $this->journalAPIRepository->getPiggyBankEvents($transactionJournal)->merge($collection); } @@ -155,7 +155,7 @@ class ListController extends Controller { $manager = $this->getManager(); $collection = $this->journalAPIRepository->getJournalLinks($transactionJournal); - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; $count = $collection->count(); $journalLinks = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); diff --git a/app/Api/V1/Controllers/Models/Transaction/ShowController.php b/app/Api/V1/Controllers/Models/Transaction/ShowController.php index 20af38f182..c86af23b9b 100644 --- a/app/Api/V1/Controllers/Models/Transaction/ShowController.php +++ b/app/Api/V1/Controllers/Models/Transaction/ShowController.php @@ -59,7 +59,7 @@ class ShowController 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); diff --git a/app/Api/V1/Controllers/Models/TransactionCurrency/DestroyController.php b/app/Api/V1/Controllers/Models/TransactionCurrency/DestroyController.php index f09bbc82d2..261d3eb9e9 100644 --- a/app/Api/V1/Controllers/Models/TransactionCurrency/DestroyController.php +++ b/app/Api/V1/Controllers/Models/TransactionCurrency/DestroyController.php @@ -50,7 +50,7 @@ class DestroyController extends Controller parent::__construct(); $this->middleware( function ($request, $next) { - $this->repository = app(CurrencyRepositoryInterface::class); + $this->repository = app(CurrencyRepositoryInterface::class); $this->userRepository = app(UserRepositoryInterface::class); $this->repository->setUser(auth()->user()); diff --git a/app/Api/V1/Controllers/Models/TransactionCurrency/ListController.php b/app/Api/V1/Controllers/Models/TransactionCurrency/ListController.php index 94a8f80457..21b4ec9880 100644 --- a/app/Api/V1/Controllers/Models/TransactionCurrency/ListController.php +++ b/app/Api/V1/Controllers/Models/TransactionCurrency/ListController.php @@ -109,7 +109,7 @@ class ListController 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 */ @@ -119,7 +119,7 @@ class ListController 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; } @@ -157,7 +157,7 @@ class ListController 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. /** @var AvailableBudgetRepositoryInterface $abRepository */ @@ -198,7 +198,7 @@ class ListController extends Controller /** @var BillRepositoryInterface $billRepos */ $billRepos = app(BillRepositoryInterface::class); - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; $unfiltered = $billRepos->getBills(); // filter and paginate list: @@ -242,7 +242,7 @@ class ListController 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); @@ -275,7 +275,7 @@ class ListController 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 $recurringRepos */ @@ -328,7 +328,7 @@ class ListController 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 $ruleRepos */ @@ -382,7 +382,7 @@ class ListController 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/Models/TransactionCurrency/ShowController.php b/app/Api/V1/Controllers/Models/TransactionCurrency/ShowController.php index 919a8ed085..2cc7c99838 100644 --- a/app/Api/V1/Controllers/Models/TransactionCurrency/ShowController.php +++ b/app/Api/V1/Controllers/Models/TransactionCurrency/ShowController.php @@ -33,6 +33,7 @@ use FireflyIII\Support\Http\Api\TransactionFilter; use FireflyIII\Transformers\CurrencyTransformer; use Illuminate\Http\JsonResponse; use Illuminate\Pagination\LengthAwarePaginator; +use JsonException; use League\Fractal\Pagination\IlluminatePaginatorAdapter; use League\Fractal\Resource\Collection as FractalCollection; use League\Fractal\Resource\Item; @@ -72,11 +73,12 @@ class ShowController extends Controller * * @return JsonResponse * @throws FireflyException + * @throws JsonException * @codeCoverageIgnore */ 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: @@ -106,6 +108,8 @@ class ShowController extends Controller * @param TransactionCurrency $currency * * @return JsonResponse + * @throws FireflyException + * @throws JsonException * @codeCoverageIgnore */ public function show(TransactionCurrency $currency): JsonResponse @@ -130,6 +134,8 @@ class ShowController extends Controller * Show a currency. * * @return JsonResponse + * @throws FireflyException + * @throws JsonException * @codeCoverageIgnore */ public function showDefault(): JsonResponse diff --git a/app/Api/V1/Controllers/Models/TransactionCurrency/StoreController.php b/app/Api/V1/Controllers/Models/TransactionCurrency/StoreController.php index 8902cc47cb..e85ed2ab05 100644 --- a/app/Api/V1/Controllers/Models/TransactionCurrency/StoreController.php +++ b/app/Api/V1/Controllers/Models/TransactionCurrency/StoreController.php @@ -33,6 +33,7 @@ use FireflyIII\Support\Http\Api\AccountFilter; use FireflyIII\Support\Http\Api\TransactionFilter; use FireflyIII\Transformers\CurrencyTransformer; use Illuminate\Http\JsonResponse; +use JsonException; use League\Fractal\Resource\Item; /** @@ -74,6 +75,7 @@ class StoreController extends Controller * * @return JsonResponse * @throws FireflyException + * @throws JsonException */ public function store(StoreRequest $request): JsonResponse { diff --git a/app/Api/V1/Controllers/Models/TransactionCurrency/UpdateController.php b/app/Api/V1/Controllers/Models/TransactionCurrency/UpdateController.php index 211b5cf964..d81fed2b5a 100644 --- a/app/Api/V1/Controllers/Models/TransactionCurrency/UpdateController.php +++ b/app/Api/V1/Controllers/Models/TransactionCurrency/UpdateController.php @@ -75,6 +75,8 @@ class UpdateController extends Controller * @param TransactionCurrency $currency * * @return JsonResponse + * @throws FireflyException + * @throws JsonException * @codeCoverageIgnore */ public function disable(TransactionCurrency $currency): JsonResponse @@ -108,6 +110,8 @@ class UpdateController extends Controller * @param TransactionCurrency $currency * * @return JsonResponse + * @throws FireflyException + * @throws JsonException * @codeCoverageIgnore */ public function enable(TransactionCurrency $currency): JsonResponse diff --git a/app/Api/V1/Controllers/Models/TransactionLink/ShowController.php b/app/Api/V1/Controllers/Models/TransactionLink/ShowController.php index db0a6aaf31..7d34561c7b 100644 --- a/app/Api/V1/Controllers/Models/TransactionLink/ShowController.php +++ b/app/Api/V1/Controllers/Models/TransactionLink/ShowController.php @@ -83,12 +83,12 @@ class ShowController 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. - $collection = $this->repository->getJournalLinks($linkType); - $count = $collection->count(); + $collection = $this->repository->getJournalLinks($linkType); + $count = $collection->count(); $journalLinks = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: diff --git a/app/Api/V1/Controllers/Models/TransactionLinkType/ListController.php b/app/Api/V1/Controllers/Models/TransactionLinkType/ListController.php index dd843887dd..d1ae43c0da 100644 --- a/app/Api/V1/Controllers/Models/TransactionLinkType/ListController.php +++ b/app/Api/V1/Controllers/Models/TransactionLinkType/ListController.php @@ -82,7 +82,7 @@ class ListController 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); diff --git a/app/Api/V1/Controllers/Models/TransactionLinkType/ShowController.php b/app/Api/V1/Controllers/Models/TransactionLinkType/ShowController.php index 5046570c87..5bc8538995 100644 --- a/app/Api/V1/Controllers/Models/TransactionLinkType/ShowController.php +++ b/app/Api/V1/Controllers/Models/TransactionLinkType/ShowController.php @@ -82,7 +82,7 @@ class ShowController 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(); diff --git a/app/Api/V1/Controllers/Search/AccountController.php b/app/Api/V1/Controllers/Search/AccountController.php index 20fea66f3d..2950b6cf17 100644 --- a/app/Api/V1/Controllers/Search/AccountController.php +++ b/app/Api/V1/Controllers/Search/AccountController.php @@ -70,8 +70,8 @@ class AccountController extends Controller { Log::debug('Now in account search()'); $manager = $this->getManager(); - $query = trim((string)$request->get('query')); - $field = trim((string)$request->get('field')); + $query = trim((string) $request->get('query')); + $field = trim((string) $request->get('field')); $type = $request->get('type') ?? 'all'; if ('' === $query || !in_array($field, $this->validFields, true)) { return response(null, 422); diff --git a/app/Api/V1/Controllers/Search/TransactionController.php b/app/Api/V1/Controllers/Search/TransactionController.php index a2464313a3..016af96eda 100644 --- a/app/Api/V1/Controllers/Search/TransactionController.php +++ b/app/Api/V1/Controllers/Search/TransactionController.php @@ -51,10 +51,10 @@ class TransactionController extends Controller public function search(Request $request, SearchInterface $searcher): JsonResponse { $manager = $this->getManager(); - $fullQuery = (string)$request->get('query'); - $page = 0 === (int)$request->get('page') ? 1 : (int)$request->get('page'); - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; - $pageSize = 0 === (int)$request->get('limit') ? $pageSize : (int)$request->get('limit'); + $fullQuery = (string) $request->get('query'); + $page = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page'); + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = 0 === (int) $request->get('limit') ? $pageSize : (int) $request->get('limit'); $searcher->parseQuery($fullQuery); $searcher->setPage($page); $searcher->setLimit($pageSize); diff --git a/app/Api/V1/Controllers/Summary/BasicController.php b/app/Api/V1/Controllers/Summary/BasicController.php index e596549bb9..af1ad594f2 100644 --- a/app/Api/V1/Controllers/Summary/BasicController.php +++ b/app/Api/V1/Controllers/Summary/BasicController.php @@ -113,7 +113,7 @@ class BasicController extends Controller // give new keys $return = []; foreach ($total as $entry) { - if (null === $code || (null !== $code && $code === $entry['currency_code'])) { + if (null === $code || ($code === $entry['currency_code'])) { $return[$entry['key']] = $entry; } } @@ -148,9 +148,11 @@ class BasicController 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')); + $incomes[$currencyId] = bcadd($incomes[$currencyId], + bcmul($transactionJournal['amount'], '-1') + ); $sums[$currencyId] = $sums[$currencyId] ?? '0'; $sums[$currencyId] = bcadd($sums[$currencyId], bcmul($transactionJournal['amount'], '-1')); } @@ -168,7 +170,7 @@ class BasicController 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'; @@ -186,7 +188,7 @@ class BasicController extends Controller $return[] = [ 'key' => sprintf('balance-in-%s', $currency->code), 'title' => trans('firefly.box_balance_in_currency', ['currency' => $currency->symbol]), - 'monetary_value' => round((float)$sums[$currencyId] ?? 0, $currency->decimal_places), + 'monetary_value' => round((float) $sums[$currencyId] ?? 0, $currency->decimal_places), 'currency_id' => $currency->id, 'currency_code' => $currency->code, 'currency_symbol' => $currency->symbol, @@ -199,7 +201,7 @@ class BasicController extends Controller $return[] = [ 'key' => sprintf('spent-in-%s', $currency->code), 'title' => trans('firefly.box_spent_in_currency', ['currency' => $currency->symbol]), - 'monetary_value' => round((float)($expenses[$currencyId] ?? 0), $currency->decimal_places), + 'monetary_value' => round((float) ($expenses[$currencyId] ?? 0), $currency->decimal_places), 'currency_id' => $currency->id, 'currency_code' => $currency->code, 'currency_symbol' => $currency->symbol, @@ -211,7 +213,7 @@ class BasicController extends Controller $return[] = [ 'key' => sprintf('earned-in-%s', $currency->code), 'title' => trans('firefly.box_earned_in_currency', ['currency' => $currency->symbol]), - 'monetary_value' => round((float)($incomes[$currencyId] ?? 0), $currency->decimal_places), + 'monetary_value' => round((float) ($incomes[$currencyId] ?? 0), $currency->decimal_places), 'currency_id' => $currency->id, 'currency_code' => $currency->code, 'currency_symbol' => $currency->symbol, @@ -242,14 +244,14 @@ class BasicController extends Controller $return = []; foreach ($paidAmount as $currencyId => $amount) { $amount = bcmul($amount, '-1'); - $currency = $this->currencyRepos->find((int)$currencyId); + $currency = $this->currencyRepos->find((int) $currencyId); if (null === $currency) { continue; } $return[] = [ 'key' => sprintf('bills-paid-in-%s', $currency->code), 'title' => trans('firefly.box_bill_paid_in_currency', ['currency' => $currency->symbol]), - 'monetary_value' => round((float)$amount, $currency->decimal_places), + 'monetary_value' => round((float) $amount, $currency->decimal_places), 'currency_id' => $currency->id, 'currency_code' => $currency->code, 'currency_symbol' => $currency->symbol, @@ -262,14 +264,14 @@ class BasicController extends Controller foreach ($unpaidAmount as $currencyId => $amount) { $amount = bcmul($amount, '-1'); - $currency = $this->currencyRepos->find((int)$currencyId); + $currency = $this->currencyRepos->find((int) $currencyId); if (null === $currency) { continue; } $return[] = [ 'key' => sprintf('bills-unpaid-in-%s', $currency->code), 'title' => trans('firefly.box_bill_unpaid_in_currency', ['currency' => $currency->symbol]), - 'monetary_value' => round((float)$amount, $currency->decimal_places), + 'monetary_value' => round((float) $amount, $currency->decimal_places), 'currency_id' => $currency->id, 'currency_code' => $currency->code, 'currency_symbol' => $currency->symbol, @@ -307,20 +309,20 @@ class BasicController 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[] = [ 'key' => sprintf('left-to-spend-in-%s', $row['currency_code']), 'title' => trans('firefly.box_left_to_spend_in_currency', ['currency' => $row['currency_symbol']]), - 'monetary_value' => round((float)$leftToSpend, $row['currency_decimal_places']), + 'monetary_value' => round((float) $leftToSpend, $row['currency_decimal_places']), 'currency_id' => $row['currency_id'], 'currency_code' => $row['currency_code'], 'currency_symbol' => $row['currency_symbol'], '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( + 'sub_title' => (string) trans( 'firefly.box_spend_per_day', ['amount' => app('amount')->formatFlat( $row['currency_symbol'], @@ -362,7 +364,7 @@ class BasicController extends Controller function (Account $account) { $includeNetWorth = $this->accountRepository->getMetaValue($account, 'include_net_worth'); - return null === $includeNetWorth ? true : '1' === $includeNetWorth; + return null === $includeNetWorth || '1' === $includeNetWorth; } ); @@ -371,7 +373,7 @@ class BasicController extends Controller foreach ($netWorthSet as $data) { /** @var TransactionCurrency $currency */ $currency = $data['currency']; - $amount = round((float)$data['balance'], $currency->decimal_places); + $amount = round((float) $data['balance'], $currency->decimal_places); if (0.0 === $amount) { continue; } diff --git a/app/Api/V1/Controllers/System/ConfigurationController.php b/app/Api/V1/Controllers/System/ConfigurationController.php index dce33eafbb..552a901336 100644 --- a/app/Api/V1/Controllers/System/ConfigurationController.php +++ b/app/Api/V1/Controllers/System/ConfigurationController.php @@ -30,6 +30,8 @@ use FireflyIII\Repositories\User\UserRepositoryInterface; use FireflyIII\Support\Binder\EitherConfigKey; use Illuminate\Http\JsonResponse; use Log; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; /** * Class ConfigurationController @@ -94,6 +96,8 @@ class ConfigurationController extends Controller * * @return array * @throws FireflyException + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface */ private function getDynamicConfiguration(): array { @@ -104,8 +108,8 @@ class ConfigurationController extends Controller return [ 'is_demo_site' => $isDemoSite?->data, - 'permission_update_check' => null === $updateCheck ? null : (int)$updateCheck->data, - 'last_update_check' => null === $lastCheck ? null : (int)$lastCheck->data, + 'permission_update_check' => null === $updateCheck ? null : (int) $updateCheck->data, + 'last_update_check' => null === $lastCheck ? null : (int) $lastCheck->data, 'single_user_mode' => $singleUser?->data, ]; } diff --git a/app/Api/V1/Controllers/System/UserController.php b/app/Api/V1/Controllers/System/UserController.php index 536f0bc6ba..c36eeb03c2 100644 --- a/app/Api/V1/Controllers/System/UserController.php +++ b/app/Api/V1/Controllers/System/UserController.php @@ -81,7 +81,7 @@ class UserController extends Controller return response()->json([], 500); } - if ($admin->id !== $user->id && $this->repository->hasRole($admin, 'owner')) { + if ($this->repository->hasRole($admin, 'owner')) { $this->repository->destroy($user); return response()->json([], 204); @@ -102,7 +102,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/Controllers/User/PreferencesController.php b/app/Api/V1/Controllers/User/PreferencesController.php index 2eb2533c0d..08650f24ae 100644 --- a/app/Api/V1/Controllers/User/PreferencesController.php +++ b/app/Api/V1/Controllers/User/PreferencesController.php @@ -59,7 +59,7 @@ class PreferencesController extends Controller $collection = app('preferences')->all(); $manager = $this->getManager(); $count = $collection->count(); - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; $preferences = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: diff --git a/app/Api/V1/Controllers/Webhook/AttemptController.php b/app/Api/V1/Controllers/Webhook/AttemptController.php index eaad374f1a..3d80cad8d7 100644 --- a/app/Api/V1/Controllers/Webhook/AttemptController.php +++ b/app/Api/V1/Controllers/Webhook/AttemptController.php @@ -77,7 +77,7 @@ class AttemptController extends Controller } $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->getAttempts($message); $count = $collection->count(); $attempts = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); diff --git a/app/Api/V1/Controllers/Webhook/MessageController.php b/app/Api/V1/Controllers/Webhook/MessageController.php index e6ee8a1c5d..b9fd26272e 100644 --- a/app/Api/V1/Controllers/Webhook/MessageController.php +++ b/app/Api/V1/Controllers/Webhook/MessageController.php @@ -68,7 +68,7 @@ class MessageController extends Controller public function index(Webhook $webhook): 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->getMessages($webhook); $count = $collection->count(); diff --git a/app/Api/V1/Controllers/Webhook/ShowController.php b/app/Api/V1/Controllers/Webhook/ShowController.php index 6baa755cd3..22550f00e3 100644 --- a/app/Api/V1/Controllers/Webhook/ShowController.php +++ b/app/Api/V1/Controllers/Webhook/ShowController.php @@ -70,11 +70,11 @@ class ShowController extends Controller */ public function index(): JsonResponse { - $manager = $this->getManager(); + $manager = $this->getManager(); $collection = $this->repository->all(); - $pageSize = (int)app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; - $count = $collection->count(); - $webhooks = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); + $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; + $count = $collection->count(); + $webhooks = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); // make paginator: $paginator = new LengthAwarePaginator($webhooks, $count, $pageSize, $this->parameters->get('page')); diff --git a/app/Api/V1/Controllers/Webhook/StoreController.php b/app/Api/V1/Controllers/Webhook/StoreController.php index 933b7331dd..a55a8659cd 100644 --- a/app/Api/V1/Controllers/Webhook/StoreController.php +++ b/app/Api/V1/Controllers/Webhook/StoreController.php @@ -64,7 +64,7 @@ class StoreController extends Controller */ public function store(CreateRequest $request): JsonResponse { - $data = $request->getData(); + $data = $request->getData(); $webhook = $this->repository->store($data); $manager = $this->getManager(); /** @var WebhookTransformer $transformer */ diff --git a/app/Api/V1/Requests/Data/Bulk/MoveTransactionsRequest.php b/app/Api/V1/Requests/Data/Bulk/MoveTransactionsRequest.php index f28790f0dd..47ddfb65f9 100644 --- a/app/Api/V1/Requests/Data/Bulk/MoveTransactionsRequest.php +++ b/app/Api/V1/Requests/Data/Bulk/MoveTransactionsRequest.php @@ -74,32 +74,45 @@ class MoveTransactionsRequest extends FormRequest // validate start before end only if both are there. $data = $validator->getData(); if (array_key_exists('original_account', $data) && array_key_exists('destination_account', $data)) { - $repository = app(AccountRepositoryInterface::class); - $repository->setUser(auth()->user()); - $original = $repository->find((int)$data['original_account']); - $destination = $repository->find((int)$data['destination_account']); - if ($original->accountType->type !== $destination->accountType->type) { - $validator->errors()->add('title', (string)trans('validation.same_account_type')); - - return; - } - // get currency pref: - $originalCurrency = $repository->getAccountCurrency($original); - $destinationCurrency = $repository->getAccountCurrency($destination); - if (null === $originalCurrency xor null === $destinationCurrency) { - $validator->errors()->add('title', (string)trans('validation.same_account_currency')); - - return; - } - if (null === $originalCurrency && null === $destinationCurrency) { - // this is OK - return; - } - if ($originalCurrency->code !== $destinationCurrency->code) { - $validator->errors()->add('title', (string)trans('validation.same_account_currency')); - } + $this->validateMove($validator); } } ); } + + /** + * @param Validator $validator + * @return void + */ + private function validateMove(Validator $validator): void { + $data = $validator->getData(); + $repository = app(AccountRepositoryInterface::class); + $repository->setUser(auth()->user()); + $original = $repository->find((int) $data['original_account']); + $destination = $repository->find((int) $data['destination_account']); + + // not the same type: + if ($original->accountType->type !== $destination->accountType->type) { + $validator->errors()->add('title', (string) trans('validation.same_account_type')); + + return; + } + // get currency pref: + $originalCurrency = $repository->getAccountCurrency($original); + $destinationCurrency = $repository->getAccountCurrency($destination); + + // check different scenario's. + if (null === $originalCurrency xor null === $destinationCurrency) { + $validator->errors()->add('title', (string) trans('validation.same_account_currency')); + + return; + } + if (null === $originalCurrency && null === $destinationCurrency) { + // this is OK + return; + } + if ($originalCurrency->code !== $destinationCurrency->code) { + $validator->errors()->add('title', (string) trans('validation.same_account_currency')); + } + } } diff --git a/app/Api/V1/Requests/Data/Export/ExportRequest.php b/app/Api/V1/Requests/Data/Export/ExportRequest.php index 78dccc2a0a..8d27d6c8ed 100644 --- a/app/Api/V1/Requests/Data/Export/ExportRequest.php +++ b/app/Api/V1/Requests/Data/Export/ExportRequest.php @@ -51,7 +51,7 @@ class ExportRequest extends FormRequest $accounts = new Collection; foreach ($parts as $part) { - $accountId = (int)$part; + $accountId = (int) $part; if (0 !== $accountId) { $account = $repository->find($accountId); if (null !== $account && AccountType::ASSET === $account->accountType->type) { diff --git a/app/Api/V1/Requests/Insight/GenericRequest.php b/app/Api/V1/Requests/Insight/GenericRequest.php index 27aed9dc1a..5a10d23e7d 100644 --- a/app/Api/V1/Requests/Insight/GenericRequest.php +++ b/app/Api/V1/Requests/Insight/GenericRequest.php @@ -94,7 +94,7 @@ class GenericRequest extends FormRequest $array = $this->get('accounts'); if (is_array($array)) { foreach ($array as $accountId) { - $accountId = (int)$accountId; + $accountId = (int) $accountId; $account = $repository->find($accountId); if (null !== $account) { $this->accounts->push($account); @@ -126,9 +126,9 @@ class GenericRequest extends FormRequest $array = $this->get('bills'); if (is_array($array)) { foreach ($array as $billId) { - $billId = (int)$billId; + $billId = (int) $billId; $bill = $repository->find($billId); - if (null !== $billId) { + if (null !== $bill) { $this->bills->push($bill); } } @@ -158,9 +158,9 @@ class GenericRequest extends FormRequest $array = $this->get('budgets'); if (is_array($array)) { foreach ($array as $budgetId) { - $budgetId = (int)$budgetId; + $budgetId = (int) $budgetId; $budget = $repository->find($budgetId); - if (null !== $budgetId) { + if (null !== $budget) { $this->budgets->push($budget); } } @@ -190,9 +190,9 @@ class GenericRequest extends FormRequest $array = $this->get('categories'); if (is_array($array)) { foreach ($array as $categoryId) { - $categoryId = (int)$categoryId; + $categoryId = (int) $categoryId; $category = $repository->find($categoryId); - if (null !== $categoryId) { + if (null !== $category) { $this->categories->push($category); } } @@ -280,9 +280,9 @@ class GenericRequest extends FormRequest $array = $this->get('tags'); if (is_array($array)) { foreach ($array as $tagId) { - $tagId = (int)$tagId; + $tagId = (int) $tagId; $tag = $repository->find($tagId); - if (null !== $tagId) { + if (null !== $tag) { $this->tags->push($tag); } } diff --git a/app/Api/V1/Requests/Models/AvailableBudget/Request.php b/app/Api/V1/Requests/Models/AvailableBudget/Request.php index c3277c3ab0..5ffbca27bf 100644 --- a/app/Api/V1/Requests/Models/AvailableBudget/Request.php +++ b/app/Api/V1/Requests/Models/AvailableBudget/Request.php @@ -90,7 +90,7 @@ class Request extends FormRequest $start = new Carbon($data['start']); $end = new Carbon($data['end']); if ($end->isBefore($start)) { - $validator->errors()->add('end', (string)trans('validation.date_after')); + $validator->errors()->add('end', (string) trans('validation.date_after')); } } } diff --git a/app/Api/V1/Requests/Models/Bill/StoreRequest.php b/app/Api/V1/Requests/Models/Bill/StoreRequest.php index d4ea90da3a..5a90f9eab3 100644 --- a/app/Api/V1/Requests/Models/Bill/StoreRequest.php +++ b/app/Api/V1/Requests/Models/Bill/StoreRequest.php @@ -104,10 +104,10 @@ class StoreRequest extends FormRequest $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/Models/Bill/UpdateRequest.php b/app/Api/V1/Requests/Models/Bill/UpdateRequest.php index 5a3fbc91ef..7ab518c0bf 100644 --- a/app/Api/V1/Requests/Models/Bill/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/Bill/UpdateRequest.php @@ -105,10 +105,10 @@ class UpdateRequest extends FormRequest static function (Validator $validator) { $data = $validator->getData(); if (array_key_exists('amount_min', $data) && array_key_exists('amount_max', $data)) { - $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/Models/Budget/StoreRequest.php b/app/Api/V1/Requests/Models/Budget/StoreRequest.php index 1594542073..036b3e3187 100644 --- a/app/Api/V1/Requests/Models/Budget/StoreRequest.php +++ b/app/Api/V1/Requests/Models/Budget/StoreRequest.php @@ -50,6 +50,7 @@ class StoreRequest extends FormRequest 'name' => ['name', 'string'], 'active' => ['active', 'boolean'], 'order' => ['active', 'integer'], + 'notes' => ['notes', 'string'], // auto budget currency: 'currency_id' => ['auto_budget_currency_id', 'integer'], @@ -74,6 +75,7 @@ class StoreRequest extends FormRequest 'active' => [new IsBoolean], 'currency_id' => 'exists:transaction_currencies,id', 'currency_code' => 'exists:transaction_currencies,code', + 'notes' => 'nullable|between:1,65536', // auto budget info 'auto_budget_type' => 'in:reset,rollover,none', 'auto_budget_amount' => 'numeric|min:0|max:1000000000|required_if:auto_budget_type,reset|required_if:auto_budget_type,rollover', diff --git a/app/Api/V1/Requests/Models/Budget/UpdateRequest.php b/app/Api/V1/Requests/Models/Budget/UpdateRequest.php index 8f9ea79f0a..44f7004906 100644 --- a/app/Api/V1/Requests/Models/Budget/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/Budget/UpdateRequest.php @@ -51,6 +51,7 @@ class UpdateRequest extends FormRequest 'name' => ['name', 'string'], 'active' => ['active', 'boolean'], 'order' => ['order', 'integer'], + 'notes' => ['notes', 'string'], 'currency_id' => ['auto_budget_currency_id', 'integer'], 'currency_code' => ['auto_budget_currency_code', 'string'], 'auto_budget_type' => ['auto_budget_type', 'string'], @@ -82,6 +83,7 @@ class UpdateRequest extends FormRequest return [ 'name' => sprintf('between:1,100|uniqueObjectForUser:budgets,name,%d', $budget->id), 'active' => [new IsBoolean], + 'notes' => 'nullable|between:1,65536', 'auto_budget_type' => 'in:reset,rollover,none', 'auto_budget_currency_id' => 'exists:transaction_currencies,id', 'auto_budget_currency_code' => 'exists:transaction_currencies,code', diff --git a/app/Api/V1/Requests/Models/BudgetLimit/UpdateRequest.php b/app/Api/V1/Requests/Models/BudgetLimit/UpdateRequest.php index 26859034b5..fc1cec7ea5 100644 --- a/app/Api/V1/Requests/Models/BudgetLimit/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/BudgetLimit/UpdateRequest.php @@ -90,7 +90,7 @@ class UpdateRequest extends FormRequest $start = new Carbon($data['start']); $end = new Carbon($data['end']); if ($end->isBefore($start)) { - $validator->errors()->add('end', (string)trans('validation.date_after')); + $validator->errors()->add('end', (string) trans('validation.date_after')); } } } diff --git a/app/Api/V1/Requests/Models/Recurrence/StoreRequest.php b/app/Api/V1/Requests/Models/Recurrence/StoreRequest.php index 6beaeaf3f9..5da9c567bf 100644 --- a/app/Api/V1/Requests/Models/Recurrence/StoreRequest.php +++ b/app/Api/V1/Requests/Models/Recurrence/StoreRequest.php @@ -115,10 +115,10 @@ class StoreRequest extends FormRequest $current['moment'] = $repetition['moment']; } if (array_key_exists('skip', $repetition)) { - $current['skip'] = (int)$repetition['skip']; + $current['skip'] = (int) $repetition['skip']; } if (array_key_exists('weekend', $repetition)) { - $current['weekend'] = (int)$repetition['weekend']; + $current['weekend'] = (int) $repetition['weekend']; } $return[] = $current; @@ -135,19 +135,19 @@ class StoreRequest extends FormRequest public function rules(): array { return [ - 'type' => 'required|in:withdrawal,transfer,deposit', - 'title' => 'required|between:1,255|uniqueObjectForUser:recurrences,title', - 'description' => 'between:1,65000', - 'first_date' => 'required|date', - 'apply_rules' => [new IsBoolean], - 'active' => [new IsBoolean], - 'repeat_until' => 'nullable|date', - 'nr_of_repetitions' => 'nullable|numeric|between:1,31', + 'type' => 'required|in:withdrawal,transfer,deposit', + 'title' => 'required|between:1,255|uniqueObjectForUser:recurrences,title', + 'description' => 'between:1,65000', + 'first_date' => 'required|date', + 'apply_rules' => [new IsBoolean], + 'active' => [new IsBoolean], + 'repeat_until' => 'nullable|date', + 'nr_of_repetitions' => 'nullable|numeric|between:1,31', - 'repetitions.*.type' => 'required|in:daily,weekly,ndom,monthly,yearly', - 'repetitions.*.moment' => 'between:0,10', - 'repetitions.*.skip' => 'nullable|numeric|between:0,31', - 'repetitions.*.weekend' => 'numeric|min:1|max:4', + 'repetitions.*.type' => 'required|in:daily,weekly,ndom,monthly,yearly', + 'repetitions.*.moment' => 'between:0,10', + 'repetitions.*.skip' => 'nullable|numeric|between:0,31', + 'repetitions.*.weekend' => 'numeric|min:1|max:4', 'transactions.*.description' => 'required|between:1,255', 'transactions.*.amount' => 'required|numeric|gt:0', @@ -162,11 +162,11 @@ class StoreRequest extends FormRequest 'transactions.*.destination_name' => 'between:1,255|nullable', // new and updated fields: - 'transactions.*.budget_id' => ['nullable','mustExist:budgets,id', new BelongsUser], + 'transactions.*.budget_id' => ['nullable', 'mustExist:budgets,id', new BelongsUser], 'transactions.*.budget_name' => ['between:1,255', 'nullable', new BelongsUser], - 'transactions.*.category_id' => ['nullable','mustExist:categories,id', new BelongsUser], + 'transactions.*.category_id' => ['nullable', 'mustExist:categories,id', new BelongsUser], 'transactions.*.category_name' => 'between:1,255|nullable', - 'transactions.*.piggy_bank_id' => ['nullable','numeric', 'mustExist:piggy_banks,id', new BelongsUser], + 'transactions.*.piggy_bank_id' => ['nullable', 'numeric', 'mustExist:piggy_banks,id', new BelongsUser], 'transactions.*.piggy_bank_name' => ['between:1,255', 'nullable', new BelongsUser], 'transactions.*.tags' => 'nullable|between:1,64000', ]; diff --git a/app/Api/V1/Requests/Models/Recurrence/UpdateRequest.php b/app/Api/V1/Requests/Models/Recurrence/UpdateRequest.php index 0dd9509fec..e008cdad7c 100644 --- a/app/Api/V1/Requests/Models/Recurrence/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/Recurrence/UpdateRequest.php @@ -97,15 +97,15 @@ class UpdateRequest extends FormRequest } if (array_key_exists('moment', $repetition)) { - $current['moment'] = (string)$repetition['moment']; + $current['moment'] = (string) $repetition['moment']; } if (array_key_exists('skip', $repetition)) { - $current['skip'] = (int)$repetition['skip']; + $current['skip'] = (int) $repetition['skip']; } if (array_key_exists('weekend', $repetition)) { - $current['weekend'] = (int)$repetition['weekend']; + $current['weekend'] = (int) $repetition['weekend']; } $return[] = $current; } @@ -150,13 +150,13 @@ class UpdateRequest extends FormRequest $recurrence = $this->route()->parameter('recurrence'); return [ - 'title' => sprintf('between:1,255|uniqueObjectForUser:recurrences,title,%d', $recurrence->id), - 'description' => 'between:1,65000', - 'first_date' => 'date', - 'apply_rules' => [new IsBoolean], - 'active' => [new IsBoolean], - 'repeat_until' => 'nullable|date', - 'nr_of_repetitions' => 'nullable|numeric|between:1,31', + 'title' => sprintf('between:1,255|uniqueObjectForUser:recurrences,title,%d', $recurrence->id), + 'description' => 'between:1,65000', + 'first_date' => 'date', + 'apply_rules' => [new IsBoolean], + 'active' => [new IsBoolean], + 'repeat_until' => 'nullable|date', + 'nr_of_repetitions' => 'nullable|numeric|between:1,31', 'repetitions.*.type' => 'in:daily,weekly,ndom,monthly,yearly', 'repetitions.*.moment' => 'between:0,10', @@ -176,11 +176,11 @@ class UpdateRequest extends FormRequest 'transactions.*.destination_name' => 'between:1,255|nullable', // new and updated fields: - 'transactions.*.budget_id' => ['nullable','mustExist:budgets,id', new BelongsUser], + 'transactions.*.budget_id' => ['nullable', 'mustExist:budgets,id', new BelongsUser], 'transactions.*.budget_name' => ['between:1,255', 'nullable', new BelongsUser], - 'transactions.*.category_id' => ['nullable','mustExist:categories,id', new BelongsUser], + 'transactions.*.category_id' => ['nullable', 'mustExist:categories,id', new BelongsUser], 'transactions.*.category_name' => 'between:1,255|nullable', - 'transactions.*.piggy_bank_id' => ['nullable','numeric', 'mustExist:piggy_banks,id', new BelongsUser], + 'transactions.*.piggy_bank_id' => ['nullable', 'numeric', 'mustExist:piggy_banks,id', new BelongsUser], 'transactions.*.piggy_bank_name' => ['between:1,255', 'nullable', new BelongsUser], 'transactions.*.tags' => 'nullable|between:1,64000', diff --git a/app/Api/V1/Requests/Models/Rule/StoreRequest.php b/app/Api/V1/Requests/Models/Rule/StoreRequest.php index 8664e50e74..ac86fee418 100644 --- a/app/Api/V1/Requests/Models/Rule/StoreRequest.php +++ b/app/Api/V1/Requests/Models/Rule/StoreRequest.php @@ -76,8 +76,8 @@ class StoreRequest extends FormRequest $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')), ]; } } @@ -97,8 +97,8 @@ class StoreRequest extends FormRequest $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')), ]; } } @@ -170,7 +170,22 @@ class StoreRequest extends FormRequest $triggers = $data['triggers'] ?? []; // need at least one trigger if (!is_countable($triggers) || empty($triggers)) { - $validator->errors()->add('title', (string)trans('validation.at_least_one_trigger')); + $validator->errors()->add('title', (string) trans('validation.at_least_one_trigger')); + } + } + + /** + * Adds an error to the validator when there are no repetitions in the array of data. + * + * @param Validator $validator + */ + protected function atLeastOneAction(Validator $validator): void + { + $data = $validator->getData(); + $actions = $data['actions'] ?? []; + // need at least one trigger + if (!is_countable($actions) || empty($actions)) { + $validator->errors()->add('title', (string) trans('validation.at_least_one_action')); } } @@ -199,7 +214,7 @@ class StoreRequest extends FormRequest } } if (true === $allInactive) { - $validator->errors()->add(sprintf('triggers.%d.active', $inactiveIndex), (string)trans('validation.at_least_one_active_trigger')); + $validator->errors()->add(sprintf('triggers.%d.active', $inactiveIndex), (string) trans('validation.at_least_one_active_trigger')); } } @@ -228,22 +243,7 @@ class StoreRequest extends FormRequest } } if (true === $allInactive) { - $validator->errors()->add(sprintf('actions.%d.active', $inactiveIndex), (string)trans('validation.at_least_one_active_action')); - } - } - - /** - * Adds an error to the validator when there are no repetitions in the array of data. - * - * @param Validator $validator - */ - protected function atLeastOneAction(Validator $validator): void - { - $data = $validator->getData(); - $actions = $data['actions'] ?? []; - // need at least one trigger - if (!is_countable($actions) || empty($actions)) { - $validator->errors()->add('title', (string)trans('validation.at_least_one_action')); + $validator->errors()->add(sprintf('actions.%d.active', $inactiveIndex), (string) trans('validation.at_least_one_active_action')); } } } diff --git a/app/Api/V1/Requests/Models/Rule/TestRequest.php b/app/Api/V1/Requests/Models/Rule/TestRequest.php index 6b77117878..640ca7c218 100644 --- a/app/Api/V1/Requests/Models/Rule/TestRequest.php +++ b/app/Api/V1/Requests/Models/Rule/TestRequest.php @@ -55,7 +55,7 @@ class TestRequest extends FormRequest */ 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'); } diff --git a/app/Api/V1/Requests/Models/Rule/TriggerRequest.php b/app/Api/V1/Requests/Models/Rule/TriggerRequest.php index 89d4c359a8..932c54a0b2 100644 --- a/app/Api/V1/Requests/Models/Rule/TriggerRequest.php +++ b/app/Api/V1/Requests/Models/Rule/TriggerRequest.php @@ -55,7 +55,7 @@ class TriggerRequest extends FormRequest */ private function getDate(string $field): ?Carbon { - return null === $this->query($field) ? null : Carbon::createFromFormat('Y-m-d', substr($this->query($field),0,10)); + return null === $this->query($field) ? null : Carbon::createFromFormat('Y-m-d', substr($this->query($field), 0, 10)); } /** diff --git a/app/Api/V1/Requests/Models/Rule/UpdateRequest.php b/app/Api/V1/Requests/Models/Rule/UpdateRequest.php index e9a6764985..6f18a7400c 100644 --- a/app/Api/V1/Requests/Models/Rule/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/Rule/UpdateRequest.php @@ -110,8 +110,8 @@ class UpdateRequest extends FormRequest $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')), ]; } } @@ -185,7 +185,7 @@ class UpdateRequest extends FormRequest $triggers = $data['triggers'] ?? null; // need at least one trigger if (is_array($triggers) && empty($triggers)) { - $validator->errors()->add('title', (string)trans('validation.at_least_one_trigger')); + $validator->errors()->add('title', (string) trans('validation.at_least_one_trigger')); } } @@ -214,7 +214,7 @@ class UpdateRequest extends FormRequest } } if (true === $allInactive) { - $validator->errors()->add(sprintf('triggers.%d.active', $inactiveIndex), (string)trans('validation.at_least_one_active_trigger')); + $validator->errors()->add(sprintf('triggers.%d.active', $inactiveIndex), (string) trans('validation.at_least_one_active_trigger')); } } @@ -229,7 +229,7 @@ class UpdateRequest extends FormRequest $actions = $data['actions'] ?? null; // need at least one action if (is_array($actions) && empty($actions)) { - $validator->errors()->add('title', (string)trans('validation.at_least_one_action')); + $validator->errors()->add('title', (string) trans('validation.at_least_one_action')); } } @@ -259,7 +259,7 @@ class UpdateRequest extends FormRequest } } if (true === $allInactive) { - $validator->errors()->add(sprintf('actions.%d.active', $inactiveIndex), (string)trans('validation.at_least_one_active_action')); + $validator->errors()->add(sprintf('actions.%d.active', $inactiveIndex), (string) trans('validation.at_least_one_active_action')); } } } diff --git a/app/Api/V1/Requests/Models/Transaction/StoreRequest.php b/app/Api/V1/Requests/Models/Transaction/StoreRequest.php index f7dace4d65..69c44249dc 100644 --- a/app/Api/V1/Requests/Models/Transaction/StoreRequest.php +++ b/app/Api/V1/Requests/Models/Transaction/StoreRequest.php @@ -80,73 +80,73 @@ class StoreRequest extends FormRequest $return[] = [ 'type' => $this->clearString($object['type'], false), '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_code' => $this->clearString((string)$object['currency_code'], false), + 'currency_id' => $this->integerFromValue((string) $object['currency_id']), + 'currency_code' => $this->clearString((string) $object['currency_code'], false), // foreign currency info: - 'foreign_currency_id' => $this->integerFromValue((string)$object['foreign_currency_id']), - 'foreign_currency_code' => $this->clearString((string)$object['foreign_currency_code'], false), + 'foreign_currency_id' => $this->integerFromValue((string) $object['foreign_currency_id']), + 'foreign_currency_code' => $this->clearString((string) $object['foreign_currency_code'], false), // amount and foreign amount. Cannot be 0. - 'amount' => $this->clearString((string)$object['amount'], false), - 'foreign_amount' => $this->clearString((string)$object['foreign_amount'], false), + 'amount' => $this->clearString((string) $object['amount'], false), + 'foreign_amount' => $this->clearString((string) $object['foreign_amount'], false), // description. 'description' => $this->clearString($object['description'], false), // source of transaction. If everything is null, assume cash account. - 'source_id' => $this->integerFromValue((string)$object['source_id']), - 'source_name' => $this->clearString((string)$object['source_name'], false), - 'source_iban' => $this->clearString((string)$object['source_iban'], false), - 'source_number' => $this->clearString((string)$object['source_number'], false), - 'source_bic' => $this->clearString((string)$object['source_bic'], false), + 'source_id' => $this->integerFromValue((string) $object['source_id']), + 'source_name' => $this->clearString((string) $object['source_name'], false), + 'source_iban' => $this->clearString((string) $object['source_iban'], false), + 'source_number' => $this->clearString((string) $object['source_number'], false), + 'source_bic' => $this->clearString((string) $object['source_bic'], false), // destination of transaction. If everything is null, assume cash account. - 'destination_id' => $this->integerFromValue((string)$object['destination_id']), - 'destination_name' => $this->clearString((string)$object['destination_name'], false), - 'destination_iban' => $this->clearString((string)$object['destination_iban'], false), - 'destination_number' => $this->clearString((string)$object['destination_number'], false), - 'destination_bic' => $this->clearString((string)$object['destination_bic'], false), + 'destination_id' => $this->integerFromValue((string) $object['destination_id']), + 'destination_name' => $this->clearString((string) $object['destination_name'], false), + 'destination_iban' => $this->clearString((string) $object['destination_iban'], false), + 'destination_number' => $this->clearString((string) $object['destination_number'], false), + 'destination_bic' => $this->clearString((string) $object['destination_bic'], false), // budget info - 'budget_id' => $this->integerFromValue((string)$object['budget_id']), - 'budget_name' => $this->clearString((string)$object['budget_name'], false), + 'budget_id' => $this->integerFromValue((string) $object['budget_id']), + 'budget_name' => $this->clearString((string) $object['budget_name'], false), // category info - 'category_id' => $this->integerFromValue((string)$object['category_id']), - 'category_name' => $this->clearString((string)$object['category_name'], false), + 'category_id' => $this->integerFromValue((string) $object['category_id']), + 'category_name' => $this->clearString((string) $object['category_name'], false), // journal bill reference. Optional. Will only work for withdrawals - 'bill_id' => $this->integerFromValue((string)$object['bill_id']), - 'bill_name' => $this->clearString((string)$object['bill_name'], false), + 'bill_id' => $this->integerFromValue((string) $object['bill_id']), + 'bill_name' => $this->clearString((string) $object['bill_name'], false), // piggy bank reference. Optional. Will only work for transfers - 'piggy_bank_id' => $this->integerFromValue((string)$object['piggy_bank_id']), - 'piggy_bank_name' => $this->clearString((string)$object['piggy_bank_name'], false), + 'piggy_bank_id' => $this->integerFromValue((string) $object['piggy_bank_id']), + 'piggy_bank_name' => $this->clearString((string) $object['piggy_bank_name'], false), // some other interesting properties - 'reconciled' => $this->convertBoolean((string)$object['reconciled']), - 'notes' => $this->clearString((string)$object['notes']), + 'reconciled' => $this->convertBoolean((string) $object['reconciled']), + 'notes' => $this->clearString((string) $object['notes']), 'tags' => $this->arrayFromValue($object['tags']), // all custom fields: - 'internal_reference' => $this->clearString((string)$object['internal_reference'], false), - 'external_id' => $this->clearString((string)$object['external_id'], false), + 'internal_reference' => $this->clearString((string) $object['internal_reference'], false), + 'external_id' => $this->clearString((string) $object['external_id'], false), '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->clearString((string)$object['bunq_payment_id'], false), - 'external_url' => $this->clearString((string)$object['external_url'], false), + 'bunq_payment_id' => $this->clearString((string) $object['bunq_payment_id'], false), + 'external_url' => $this->clearString((string) $object['external_url'], false), - 'sepa_cc' => $this->clearString((string)$object['sepa_cc'], false), - 'sepa_ct_op' => $this->clearString((string)$object['sepa_ct_op'], false), - 'sepa_ct_id' => $this->clearString((string)$object['sepa_ct_id'], false), - 'sepa_db' => $this->clearString((string)$object['sepa_db'], false), - 'sepa_country' => $this->clearString((string)$object['sepa_country'], false), - 'sepa_ep' => $this->clearString((string)$object['sepa_ep'], false), - 'sepa_ci' => $this->clearString((string)$object['sepa_ci'], false), - 'sepa_batch_id' => $this->clearString((string)$object['sepa_batch_id'], false), + 'sepa_cc' => $this->clearString((string) $object['sepa_cc'], false), + 'sepa_ct_op' => $this->clearString((string) $object['sepa_ct_op'], false), + 'sepa_ct_id' => $this->clearString((string) $object['sepa_ct_id'], false), + 'sepa_db' => $this->clearString((string) $object['sepa_db'], false), + 'sepa_country' => $this->clearString((string) $object['sepa_country'], false), + 'sepa_ep' => $this->clearString((string) $object['sepa_ep'], false), + 'sepa_ci' => $this->clearString((string) $object['sepa_ci'], false), + 'sepa_batch_id' => $this->clearString((string) $object['sepa_batch_id'], false), // custom date fields. Must be Carbon objects. Presence is optional. 'interest_date' => $this->dateFromValue($object['interest_date']), 'book_date' => $this->dateFromValue($object['book_date']), @@ -211,7 +211,7 @@ class StoreRequest extends FormRequest // budget, category, bill and piggy 'transactions.*.budget_id' => ['mustExist:budgets,id', new BelongsUser], 'transactions.*.budget_name' => ['between:1,255', 'nullable', new BelongsUser], - 'transactions.*.category_id' => ['mustExist:categories,id', new BelongsUser,'nullable'], + 'transactions.*.category_id' => ['mustExist:categories,id', new BelongsUser, 'nullable'], 'transactions.*.category_name' => 'between:1,255|nullable', 'transactions.*.bill_id' => ['numeric', 'nullable', 'mustExist:bills,id', new BelongsUser], 'transactions.*.bill_name' => ['between:1,255', 'nullable', new BelongsUser], diff --git a/app/Api/V1/Requests/Models/TransactionLink/StoreRequest.php b/app/Api/V1/Requests/Models/TransactionLink/StoreRequest.php index c22b71723b..f9db392594 100644 --- a/app/Api/V1/Requests/Models/TransactionLink/StoreRequest.php +++ b/app/Api/V1/Requests/Models/TransactionLink/StoreRequest.php @@ -102,8 +102,8 @@ class StoreRequest extends FormRequest $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->find($inwardId); $outward = $journalRepos->find($outwardId); diff --git a/app/Api/V1/Requests/Models/TransactionLink/UpdateRequest.php b/app/Api/V1/Requests/Models/TransactionLink/UpdateRequest.php index a22c207bff..ddfbd7fd50 100644 --- a/app/Api/V1/Requests/Models/TransactionLink/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/TransactionLink/UpdateRequest.php @@ -104,8 +104,8 @@ class UpdateRequest extends FormRequest $inwardId = $data['inward_id'] ?? $existing->source_id; $outwardId = $data['outward_id'] ?? $existing->destination_id; - $inward = $journalRepos->find((int)$inwardId); - $outward = $journalRepos->find((int)$outwardId); + $inward = $journalRepos->find((int) $inwardId); + $outward = $journalRepos->find((int) $outwardId); if (null === $inward) { $inward = $existing->source; } diff --git a/app/Api/V1/Requests/System/UserUpdateRequest.php b/app/Api/V1/Requests/System/UserUpdateRequest.php index 7e94a3ad96..adb44107ab 100644 --- a/app/Api/V1/Requests/System/UserUpdateRequest.php +++ b/app/Api/V1/Requests/System/UserUpdateRequest.php @@ -95,7 +95,7 @@ class UserUpdateRequest extends FormRequest { $current = $this->route()->parameter('user'); $validator->after( - static function (Validator $validator) use($current) { + static function (Validator $validator) use ($current) { $isAdmin = auth()->user()->hasRole('owner'); // not admin, and not own user? if (auth()->check() && false === $isAdmin && $current?->id !== auth()->user()->id) { diff --git a/app/Api/V1/Requests/User/PreferenceStoreRequest.php b/app/Api/V1/Requests/User/PreferenceStoreRequest.php index 5e7037c136..18f513fd85 100644 --- a/app/Api/V1/Requests/User/PreferenceStoreRequest.php +++ b/app/Api/V1/Requests/User/PreferenceStoreRequest.php @@ -47,7 +47,7 @@ class PreferenceStoreRequest extends FormRequest $array['data'] = false; } if (is_numeric($array['data'])) { - $array['data'] = (float)$array['data']; + $array['data'] = (float) $array['data']; } return $array; diff --git a/app/Api/V1/Requests/User/PreferenceUpdateRequest.php b/app/Api/V1/Requests/User/PreferenceUpdateRequest.php index 067fd12730..0c6d66bd4f 100644 --- a/app/Api/V1/Requests/User/PreferenceUpdateRequest.php +++ b/app/Api/V1/Requests/User/PreferenceUpdateRequest.php @@ -48,7 +48,7 @@ class PreferenceUpdateRequest extends FormRequest $array['data'] = false; } if (is_numeric($array['data'])) { - $array['data'] = (float)$array['data']; + $array['data'] = (float) $array['data']; } return $array; diff --git a/app/Console/Commands/Correction/CorrectOpeningBalanceCurrencies.php b/app/Console/Commands/Correction/CorrectOpeningBalanceCurrencies.php index 9055e0aa34..6c5fba45c9 100644 --- a/app/Console/Commands/Correction/CorrectOpeningBalanceCurrencies.php +++ b/app/Console/Commands/Correction/CorrectOpeningBalanceCurrencies.php @@ -57,7 +57,6 @@ class CorrectOpeningBalanceCurrencies extends Command * Execute the console command. * * @return int - * @throws JsonException */ public function handle(): int { @@ -136,6 +135,8 @@ class CorrectOpeningBalanceCurrencies extends Command * @param Account $account * * @return TransactionCurrency + * @throws JsonException + * @throws \FireflyIII\Exceptions\FireflyException */ private function getCurrency(Account $account): TransactionCurrency { @@ -155,7 +156,7 @@ class CorrectOpeningBalanceCurrencies extends Command private function setCurrency(TransactionJournal $journal, TransactionCurrency $currency): int { $count = 0; - if ((int)$journal->transaction_currency_id !== (int)$currency->id) { + if ((int) $journal->transaction_currency_id !== (int) $currency->id) { $journal->transaction_currency_id = $currency->id; $journal->save(); $count = 1; @@ -163,7 +164,7 @@ class CorrectOpeningBalanceCurrencies extends Command /** @var Transaction $transaction */ foreach ($journal->transactions as $transaction) { - if ((int)$transaction->transaction_currency_id !== (int)$currency->id) { + if ((int) $transaction->transaction_currency_id !== (int) $currency->id) { $transaction->transaction_currency_id = $currency->id; $transaction->save(); $count = 1; diff --git a/app/Console/Commands/Correction/DeleteEmptyJournals.php b/app/Console/Commands/Correction/DeleteEmptyJournals.php index f73b293a5d..d1b4d4451a 100644 --- a/app/Console/Commands/Correction/DeleteEmptyJournals.php +++ b/app/Console/Commands/Correction/DeleteEmptyJournals.php @@ -73,18 +73,18 @@ class DeleteEmptyJournals extends Command $total = 0; /** @var Transaction $row */ 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(); } catch (Exception $e) { // @phpstan-ignore-line Log::info(sprintf('Could not delete journal: %s', $e->getMessage())); } - 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 359930b51a..9e54af2e0f 100644 --- a/app/Console/Commands/Correction/DeleteOrphanedTransactions.php +++ b/app/Console/Commands/Correction/DeleteOrphanedTransactions.php @@ -84,7 +84,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( @@ -106,7 +106,7 @@ class DeleteOrphanedTransactions extends Command private function deleteFromOrphanedAccounts(): void { $set - = Transaction + = Transaction ::leftJoin('accounts', 'transactions.account_id', '=', 'accounts.id') ->whereNotNull('accounts.deleted_at') ->get(['transactions.*']); @@ -114,7 +114,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(); @@ -124,7 +124,7 @@ class DeleteOrphanedTransactions extends Command } } - 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.', diff --git a/app/Console/Commands/Correction/EnableCurrencies.php b/app/Console/Commands/Correction/EnableCurrencies.php index b0046ee6fa..3e1aaee2d1 100644 --- a/app/Console/Commands/Correction/EnableCurrencies.php +++ b/app/Console/Commands/Correction/EnableCurrencies.php @@ -63,30 +63,30 @@ 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: $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 $transactions = Transaction::groupBy('transaction_currency_id', 'foreign_currency_id')->get(['transaction_currency_id', 'foreign_currency_id']); foreach ($transactions as $entry) { - $found[] = (int)$entry->transaction_currency_id; - $found[] = (int)$entry->foreign_currency_id; + $found[] = (int) $entry->transaction_currency_id; + $found[] = (int) $entry->foreign_currency_id; } // get all from budget 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_values(array_unique($found)); - $found = array_values( + $found = array_values(array_unique($found)); + $found = array_values( array_filter( $found, function (int $currencyId) { return $currencyId !== 0; diff --git a/app/Console/Commands/Correction/FixFrontpageAccounts.php b/app/Console/Commands/Correction/FixFrontpageAccounts.php index a1f5e7e2d2..64372c7db4 100644 --- a/app/Console/Commands/Correction/FixFrontpageAccounts.php +++ b/app/Console/Commands/Correction/FixFrontpageAccounts.php @@ -88,7 +88,7 @@ class FixFrontpageAccounts extends Command if (is_array($data)) { /** @var string $accountId */ foreach ($data as $accountId) { - $accountIdInt = (int)$accountId; + $accountIdInt = (int) $accountId; $account = $repository->find($accountIdInt); if (null !== $account && in_array($account->accountType->type, [AccountType::ASSET, AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE], true) diff --git a/app/Console/Commands/Correction/FixGroupAccounts.php b/app/Console/Commands/Correction/FixGroupAccounts.php index 7b818ce46e..9ed55a330e 100644 --- a/app/Console/Commands/Correction/FixGroupAccounts.php +++ b/app/Console/Commands/Correction/FixGroupAccounts.php @@ -62,8 +62,8 @@ class FixGroupAccounts extends Command ->get(['transaction_group_id', DB::raw('COUNT(transaction_group_id) as the_count')]); /** @var TransactionJournal $journal */ foreach ($res as $journal) { - if ((int)$journal->the_count > 1) { - $groups[] = (int)$journal->transaction_group_id; + if ((int) $journal->the_count > 1) { + $groups[] = (int) $journal->transaction_group_id; } } $handler = new UpdatedGroupEventHandler; diff --git a/app/Console/Commands/Correction/FixIbans.php b/app/Console/Commands/Correction/FixIbans.php index 8cc193c6f5..6ecf3a1a62 100644 --- a/app/Console/Commands/Correction/FixIbans.php +++ b/app/Console/Commands/Correction/FixIbans.php @@ -1,4 +1,25 @@ . + */ + declare(strict_types=1); namespace FireflyIII\Console\Commands\Correction; @@ -37,7 +58,7 @@ class FixIbans extends Command $iban = $account->iban; if (str_contains($iban, ' ')) { - $iban = app('steam')->filterSpaces((string)$account->iban); + $iban = app('steam')->filterSpaces((string) $account->iban); if ('' !== $iban) { $account->iban = $iban; $account->save(); diff --git a/app/Console/Commands/Correction/FixLongDescriptions.php b/app/Console/Commands/Correction/FixLongDescriptions.php index 32fa810ec7..2dfd02d15b 100644 --- a/app/Console/Commands/Correction/FixLongDescriptions.php +++ b/app/Console/Commands/Correction/FixLongDescriptions.php @@ -68,7 +68,7 @@ class FixLongDescriptions extends Command $groups = TransactionGroup::get(['id', 'title']); /** @var TransactionGroup $group */ foreach ($groups as $group) { - if (strlen((string)$group->title) > self::MAX_LENGTH) { + if (strlen((string) $group->title) > self::MAX_LENGTH) { $group->title = substr($group->title, 0, self::MAX_LENGTH); $group->save(); $this->line(sprintf('Truncated description of transaction group #%d', $group->id)); diff --git a/app/Console/Commands/Correction/FixTransactionTypes.php b/app/Console/Commands/Correction/FixTransactionTypes.php index a3a01326e7..02296d3a36 100644 --- a/app/Console/Commands/Correction/FixTransactionTypes.php +++ b/app/Console/Commands/Correction/FixTransactionTypes.php @@ -106,7 +106,7 @@ class FixTransactionTypes extends Command return false; } - $expectedType = (string)config(sprintf('firefly.account_to_transaction.%s.%s', $source->accountType->type, $destination->accountType->type)); + $expectedType = (string) config(sprintf('firefly.account_to_transaction.%s.%s', $source->accountType->type, $destination->accountType->type)); if ($expectedType !== $type) { $this->line(sprintf('Transaction journal #%d was of type "%s" but is corrected to "%s"', $journal->id, $type, $expectedType)); $this->changeJournal($journal, $expectedType); diff --git a/app/Console/Commands/Correction/FixUnevenAmount.php b/app/Console/Commands/Correction/FixUnevenAmount.php index 73deae867c..f02cb4e445 100644 --- a/app/Console/Commands/Correction/FixUnevenAmount.php +++ b/app/Console/Commands/Correction/FixUnevenAmount.php @@ -65,11 +65,11 @@ 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')) { + if (0 !== bccomp((string) $entry->the_sum, '0')) { $message = sprintf('Sum of journal #%d is %s instead of zero.', $entry->transaction_journal_id, $entry->the_sum); $this->warn($message); Log::warning($message); - $this->fixJournal((int)$entry->transaction_journal_id); + $this->fixJournal((int) $entry->transaction_journal_id); $count++; } } @@ -110,7 +110,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 */ diff --git a/app/Console/Commands/DecryptDatabase.php b/app/Console/Commands/DecryptDatabase.php index 60897032f4..465bea2193 100644 --- a/app/Console/Commands/DecryptDatabase.php +++ b/app/Console/Commands/DecryptDatabase.php @@ -109,6 +109,8 @@ class DecryptDatabase extends Command * @param string $table * * @return bool + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ private function isDecrypted(string $table): bool { @@ -120,7 +122,7 @@ class DecryptDatabase extends Command Log::error($e->getMessage()); } if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; @@ -150,7 +152,7 @@ class DecryptDatabase extends Command if (null === $original) { return; } - $id = (int)$row->id; + $id = (int) $row->id; $value = ''; try { @@ -215,7 +217,7 @@ class DecryptDatabase extends Command } /** @var Preference $object */ - $object = Preference::find((int)$id); + $object = Preference::find((int) $id); if (null !== $object) { $object->data = $newValue; $object->save(); diff --git a/app/Console/Commands/Export/ExportData.php b/app/Console/Commands/Export/ExportData.php index c4786d67d0..7aea9a3df4 100644 --- a/app/Console/Commands/Export/ExportData.php +++ b/app/Console/Commands/Export/ExportData.php @@ -202,7 +202,7 @@ class ExportData extends Command $error = true; } } - if(null === $this->option($field)) { + if (null === $this->option($field)) { Log::info(sprintf('No date given in field "%s"', $field)); $error = true; } @@ -234,7 +234,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); } @@ -262,7 +262,7 @@ class ExportData extends Command */ private function getExportDirectory(): string { - $directory = (string)$this->option('export_directory'); + $directory = (string) $this->option('export_directory'); if (null === $directory) { $directory = './'; } diff --git a/app/Console/Commands/Integrity/ReportSum.php b/app/Console/Commands/Integrity/ReportSum.php index a9b6054269..f88fe087d1 100644 --- a/app/Console/Commands/Integrity/ReportSum.php +++ b/app/Console/Commands/Integrity/ReportSum.php @@ -68,7 +68,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 a9bc0f1e78..3e50f177e3 100644 --- a/app/Console/Commands/Integrity/RestoreOAuthKeys.php +++ b/app/Console/Commands/Integrity/RestoreOAuthKeys.php @@ -75,7 +75,7 @@ class RestoreOAuthKeys extends Command if ($this->keysInDatabase() && !$this->keysOnDrive()) { Log::debug('Keys are in DB and keys are not on the drive. Restore.'); $result = $this->restoreKeysFromDB(); - if(true === $result) { + if (true === $result) { $this->line('Restored OAuth keys from database.'); return; diff --git a/app/Console/Commands/ScanAttachments.php b/app/Console/Commands/ScanAttachments.php index c094309b54..0ffc35747e 100644 --- a/app/Console/Commands/ScanAttachments.php +++ b/app/Console/Commands/ScanAttachments.php @@ -27,7 +27,6 @@ use Crypt; use FireflyIII\Models\Attachment; use Illuminate\Console\Command; use Illuminate\Contracts\Encryption\DecryptException; -use Illuminate\Contracts\Filesystem\FileNotFoundException; use Log; use Storage; @@ -61,11 +60,10 @@ class ScanAttachments extends Command $disk = Storage::disk('upload'); /** @var Attachment $attachment */ foreach ($attachments as $attachment) { - $fileName = $attachment->fileName(); - try { - $encryptedContent = $disk->get($fileName); - } catch (FileNotFoundException $e) { - $this->error(sprintf('Could not find data for attachment #%d: %s', $attachment->id, $e->getMessage())); + $fileName = $attachment->fileName(); + $encryptedContent = $disk->get($fileName); + if (null === $encryptedContent) { + Log::error(sprintf('No content for attachment #%d under filename "%s"', $attachment->id, $fileName)); continue; } try { diff --git a/app/Console/Commands/Tools/ApplyRules.php b/app/Console/Commands/Tools/ApplyRules.php index 5ad5c240c2..0e4cf33cfb 100644 --- a/app/Console/Commands/Tools/ApplyRules.php +++ b/app/Console/Commands/Tools/ApplyRules.php @@ -212,7 +212,7 @@ class ApplyRules extends Command $accountRepository = app(AccountRepositoryInterface::class); $accountRepository->setUser($this->getUser()); foreach ($accountList as $accountId) { - $accountId = (int)$accountId; + $accountId = (int) $accountId; $account = $accountRepository->find($accountId); if (null !== $account && in_array($account->accountType->type, $this->acceptedAccounts, true)) { $finalList->push($account); @@ -243,7 +243,7 @@ class ApplyRules extends Command $ruleGroupList = explode(',', $ruleGroupString); foreach ($ruleGroupList as $ruleGroupId) { - $ruleGroup = $this->ruleGroupRepository->find((int)$ruleGroupId); + $ruleGroup = $this->ruleGroupRepository->find((int) $ruleGroupId); if ($ruleGroup->active) { $this->ruleGroupSelection[] = $ruleGroup->id; } @@ -268,7 +268,7 @@ class ApplyRules extends Command $ruleList = explode(',', $ruleString); foreach ($ruleList as $ruleId) { - $rule = $this->ruleRepository->find((int)$ruleId); + $rule = $this->ruleRepository->find((int) $ruleId); if (null !== $rule && $rule->active) { $this->ruleSelection[] = $rule->id; } diff --git a/app/Console/Commands/Tools/Cron.php b/app/Console/Commands/Tools/Cron.php index 720ac0e43c..81cd65fe54 100644 --- a/app/Console/Commands/Tools/Cron.php +++ b/app/Console/Commands/Tools/Cron.php @@ -27,6 +27,7 @@ namespace FireflyIII\Console\Commands\Tools; use Carbon\Carbon; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Support\Cronjobs\AutoBudgetCronjob; +use FireflyIII\Support\Cronjobs\BillWarningCronjob; use FireflyIII\Support\Cronjobs\RecurringCronjob; use Illuminate\Console\Command; use InvalidArgumentException; @@ -66,7 +67,7 @@ class Cron extends Command } catch (InvalidArgumentException $e) { $this->error(sprintf('"%s" is not a valid date', $this->option('date'))); } - $force = (bool)$this->option('force'); + $force = (bool) $this->option('force'); /* * Fire recurring transaction cron job. @@ -90,6 +91,17 @@ class Cron extends Command $this->error($e->getMessage()); } + /* + * Fire bill warning cron job + */ + try { + $this->billWarningCronJob($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.'); return 0; @@ -150,4 +162,32 @@ class Cron extends Command } } + + /** + * @param bool $force + * @param Carbon|null $date + * @throws FireflyException + */ + private function billWarningCronJob(bool $force, ?Carbon $date): void + { + $autoBudget = new BillWarningCronjob; + $autoBudget->setForce($force); + // set date in cron job: + if (null !== $date) { + $autoBudget->setDate($date); + } + + $autoBudget->fire(); + + if ($autoBudget->jobErrored) { + $this->error(sprintf('Error in "bill warnings" cron: %s', $autoBudget->message)); + } + if ($autoBudget->jobFired) { + $this->error(sprintf('"Send bill warnings" cron fired: %s', $autoBudget->message)); + } + if ($autoBudget->jobSucceeded) { + $this->error(sprintf('"Send bill warnings" cron ran with success: %s', $autoBudget->message)); + } + + } } diff --git a/app/Console/Commands/Upgrade/AccountCurrencies.php b/app/Console/Commands/Upgrade/AccountCurrencies.php index 4cad1423e6..617fe579ad 100644 --- a/app/Console/Commands/Upgrade/AccountCurrencies.php +++ b/app/Console/Commands/Upgrade/AccountCurrencies.php @@ -109,12 +109,14 @@ class AccountCurrencies extends Command /** * @return bool * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ private function isExecuted(): bool { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; @@ -127,7 +129,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); @@ -178,13 +180,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; 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)); diff --git a/app/Console/Commands/Upgrade/AppendBudgetLimitPeriods.php b/app/Console/Commands/Upgrade/AppendBudgetLimitPeriods.php index e4e15ac63a..0558fe99c4 100644 --- a/app/Console/Commands/Upgrade/AppendBudgetLimitPeriods.php +++ b/app/Console/Commands/Upgrade/AppendBudgetLimitPeriods.php @@ -72,12 +72,14 @@ class AppendBudgetLimitPeriods extends Command /** * @return bool * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ private function isExecuted(): bool { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); - return (bool)$configVar->data; + return (bool) $configVar->data; } /** diff --git a/app/Console/Commands/Upgrade/BackToJournals.php b/app/Console/Commands/Upgrade/BackToJournals.php index ab66fda7b7..f3b3c61b11 100644 --- a/app/Console/Commands/Upgrade/BackToJournals.php +++ b/app/Console/Commands/Upgrade/BackToJournals.php @@ -86,23 +86,27 @@ class BackToJournals extends Command /** * @return bool * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ private function isMigrated(): bool { $configVar = app('fireflyconfig')->get(MigrateToGroups::CONFIG_NAME, false); - return (bool)$configVar->data; + return (bool) $configVar->data; } /** * @return bool * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ private function isExecuted(): bool { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); - return (bool)$configVar->data; + return (bool) $configVar->data; } /** @@ -179,7 +183,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; } @@ -187,7 +191,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]); } } @@ -258,12 +262,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 af7aa203c8..93b5ac95a1 100644 --- a/app/Console/Commands/Upgrade/BudgetLimitCurrency.php +++ b/app/Console/Commands/Upgrade/BudgetLimitCurrency.php @@ -99,12 +99,14 @@ class BudgetLimitCurrency extends Command /** * @return bool * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ private function isExecuted(): bool { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; diff --git a/app/Console/Commands/Upgrade/CCLiabilities.php b/app/Console/Commands/Upgrade/CCLiabilities.php index 0f9f365de6..d28dc36860 100644 --- a/app/Console/Commands/Upgrade/CCLiabilities.php +++ b/app/Console/Commands/Upgrade/CCLiabilities.php @@ -96,12 +96,14 @@ class CCLiabilities extends Command /** * @return bool * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ private function isExecuted(): bool { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; diff --git a/app/Console/Commands/Upgrade/CreateGroupMemberships.php b/app/Console/Commands/Upgrade/CreateGroupMemberships.php index 43cbc71429..77bfa2c78a 100644 --- a/app/Console/Commands/Upgrade/CreateGroupMemberships.php +++ b/app/Console/Commands/Upgrade/CreateGroupMemberships.php @@ -77,12 +77,14 @@ class CreateGroupMemberships extends Command /** * @return bool * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ private function isExecuted(): bool { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; diff --git a/app/Console/Commands/Upgrade/MigrateAttachments.php b/app/Console/Commands/Upgrade/MigrateAttachments.php index 6d210b95e1..da66743e5f 100644 --- a/app/Console/Commands/Upgrade/MigrateAttachments.php +++ b/app/Console/Commands/Upgrade/MigrateAttachments.php @@ -72,7 +72,7 @@ class MigrateAttachments extends Command foreach ($attachments as $att) { // move description: - $attDescription = (string)$att->description; + $attDescription = (string) $att->description; if ('' !== $attDescription) { // find or create note: @@ -108,12 +108,14 @@ class MigrateAttachments extends Command /** * @return bool * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ private function isExecuted(): bool { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; diff --git a/app/Console/Commands/Upgrade/MigrateJournalNotes.php b/app/Console/Commands/Upgrade/MigrateJournalNotes.php index 698b696f28..8469fa7285 100644 --- a/app/Console/Commands/Upgrade/MigrateJournalNotes.php +++ b/app/Console/Commands/Upgrade/MigrateJournalNotes.php @@ -106,12 +106,14 @@ class MigrateJournalNotes extends Command /** * @return bool * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ private function isExecuted(): bool { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; diff --git a/app/Console/Commands/Upgrade/MigrateRecurrenceMeta.php b/app/Console/Commands/Upgrade/MigrateRecurrenceMeta.php index a4c74d1731..a1b3c2aa80 100644 --- a/app/Console/Commands/Upgrade/MigrateRecurrenceMeta.php +++ b/app/Console/Commands/Upgrade/MigrateRecurrenceMeta.php @@ -84,12 +84,14 @@ class MigrateRecurrenceMeta extends Command /** * @return bool * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ private function isExecuted(): bool { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; diff --git a/app/Console/Commands/Upgrade/MigrateRecurrenceType.php b/app/Console/Commands/Upgrade/MigrateRecurrenceType.php index ad99981512..d86e719aea 100644 --- a/app/Console/Commands/Upgrade/MigrateRecurrenceType.php +++ b/app/Console/Commands/Upgrade/MigrateRecurrenceType.php @@ -77,12 +77,14 @@ class MigrateRecurrenceType extends Command /** * @return bool * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ private function isExecuted(): bool { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; @@ -104,7 +106,7 @@ class MigrateRecurrenceType extends Command private function migrateRecurrence(Recurrence $recurrence): void { - $originalType = (int)$recurrence->transaction_type_id; + $originalType = (int) $recurrence->transaction_type_id; $newType = $this->getInvalidType(); $recurrence->transaction_type_id = $newType->id; $recurrence->save(); diff --git a/app/Console/Commands/Upgrade/MigrateTagLocations.php b/app/Console/Commands/Upgrade/MigrateTagLocations.php index e5162cdbf6..ad36e4a605 100644 --- a/app/Console/Commands/Upgrade/MigrateTagLocations.php +++ b/app/Console/Commands/Upgrade/MigrateTagLocations.php @@ -75,12 +75,14 @@ class MigrateTagLocations extends Command /** * @return bool * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ private function isExecuted(): bool { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; diff --git a/app/Console/Commands/Upgrade/MigrateToGroups.php b/app/Console/Commands/Upgrade/MigrateToGroups.php index dcf11e2cca..7085092e7a 100644 --- a/app/Console/Commands/Upgrade/MigrateToGroups.php +++ b/app/Console/Commands/Upgrade/MigrateToGroups.php @@ -129,12 +129,14 @@ class MigrateToGroups extends Command /** * @return bool * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ private function isMigrated(): bool { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; @@ -328,7 +330,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))); @@ -356,7 +358,7 @@ class MigrateToGroups extends Command if (null !== $budget) { Log::debug(sprintf('Return budget #%d, from transaction #%d', $budget->id, $left->id)); - return (int)$budget->id; + return (int) $budget->id; } // try to get a budget ID from the right transaction: @@ -365,7 +367,7 @@ class MigrateToGroups extends Command if (null !== $budget) { Log::debug(sprintf('Return budget #%d, from transaction #%d', $budget->id, $right->id)); - return (int)$budget->id; + return (int) $budget->id; } Log::debug('Neither left or right have a budget, return NULL'); @@ -389,7 +391,7 @@ class MigrateToGroups extends Command if (null !== $category) { Log::debug(sprintf('Return category #%d, from transaction #%d', $category->id, $left->id)); - return (int)$category->id; + return (int) $category->id; } // try to get a category ID from the left transaction: @@ -398,7 +400,7 @@ class MigrateToGroups extends Command if (null !== $category) { Log::debug(sprintf('Return category #%d, from transaction #%d', $category->id, $category->id)); - return (int)$category->id; + return (int) $category->id; } Log::debug('Neither left or right have a category, return NULL'); diff --git a/app/Console/Commands/Upgrade/MigrateToRules.php b/app/Console/Commands/Upgrade/MigrateToRules.php index 25f96d8c6e..6f726a6ac8 100644 --- a/app/Console/Commands/Upgrade/MigrateToRules.php +++ b/app/Console/Commands/Upgrade/MigrateToRules.php @@ -120,12 +120,14 @@ class MigrateToRules extends Command /** * @return bool * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ private function isExecuted(): bool { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; @@ -146,14 +148,14 @@ class MigrateToRules extends Command /** @var Preference $lang */ $lang = app('preferences')->getForUser($user, 'language', 'en_US'); - $groupTitle = (string)trans('firefly.rulegroup_for_bills_title', [], $lang->data); + $groupTitle = (string) trans('firefly.rulegroup_for_bills_title', [], $lang->data); $ruleGroup = $this->ruleGroupRepository->findByTitle($groupTitle); 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), + 'title' => (string) trans('firefly.rulegroup_for_bills_title', [], $lang->data), + 'description' => (string) trans('firefly.rulegroup_for_bills_description', [], $lang->data), 'active' => true, ] ); @@ -185,8 +187,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' => [ [ diff --git a/app/Console/Commands/Upgrade/OtherCurrenciesCorrections.php b/app/Console/Commands/Upgrade/OtherCurrenciesCorrections.php index e0f86f27fe..4dbe770611 100644 --- a/app/Console/Commands/Upgrade/OtherCurrenciesCorrections.php +++ b/app/Console/Commands/Upgrade/OtherCurrenciesCorrections.php @@ -115,12 +115,14 @@ class OtherCurrenciesCorrections extends Command /** * @return bool * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ private function isExecuted(): bool { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; @@ -187,8 +189,8 @@ class OtherCurrenciesCorrections extends Command } // when mismatch in transaction: - if ((int)$transaction->transaction_currency_id !== (int)$currency->id) { - $transaction->foreign_currency_id = (int)$transaction->transaction_currency_id; + 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(); diff --git a/app/Console/Commands/Upgrade/RenameAccountMeta.php b/app/Console/Commands/Upgrade/RenameAccountMeta.php index 24340ff75c..1591dbe898 100644 --- a/app/Console/Commands/Upgrade/RenameAccountMeta.php +++ b/app/Console/Commands/Upgrade/RenameAccountMeta.php @@ -99,12 +99,14 @@ class RenameAccountMeta extends Command /** * @return bool * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ private function isExecuted(): bool { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; diff --git a/app/Console/Commands/Upgrade/TransactionIdentifier.php b/app/Console/Commands/Upgrade/TransactionIdentifier.php index 5ec7c1a576..752743716c 100644 --- a/app/Console/Commands/Upgrade/TransactionIdentifier.php +++ b/app/Console/Commands/Upgrade/TransactionIdentifier.php @@ -123,12 +123,14 @@ class TransactionIdentifier extends Command /** * @return bool * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ private function isExecuted(): bool { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; @@ -173,7 +175,7 @@ class TransactionIdentifier extends Command private function findOpposing(Transaction $transaction, array $exclude): ?Transaction { // find opposing: - $amount = bcmul((string)$transaction->amount, '-1'); + $amount = bcmul((string) $transaction->amount, '-1'); try { /** @var Transaction $opposing */ diff --git a/app/Console/Commands/Upgrade/TransferCurrenciesCorrections.php b/app/Console/Commands/Upgrade/TransferCurrenciesCorrections.php index 52c9316f3f..6113eb260b 100644 --- a/app/Console/Commands/Upgrade/TransferCurrenciesCorrections.php +++ b/app/Console/Commands/Upgrade/TransferCurrenciesCorrections.php @@ -68,6 +68,9 @@ class TransferCurrenciesCorrections extends Command * Execute the console command. * * @return int + * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function handle(): int { @@ -134,12 +137,14 @@ class TransferCurrenciesCorrections extends Command /** * @return bool * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ private function isExecuted(): bool { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; @@ -368,7 +373,7 @@ class TransferCurrenciesCorrections extends Command if (null === $this->sourceTransaction->transaction_currency_id && null !== $this->sourceCurrency) { $this->sourceTransaction ->transaction_currency_id - = (int)$this->sourceCurrency->id; + = (int) $this->sourceCurrency->id; $message = sprintf( 'Transaction #%d has no currency setting, now set to %s.', $this->sourceTransaction->id, @@ -389,7 +394,7 @@ class TransferCurrenciesCorrections extends Command { if (null !== $this->sourceCurrency && null === $this->sourceTransaction->foreign_amount - && (int)$this->sourceTransaction->transaction_currency_id !== (int)$this->sourceCurrency->id + && (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.', @@ -401,7 +406,7 @@ class TransferCurrenciesCorrections extends Command Log::debug($message); $this->line($message); $this->count++; - $this->sourceTransaction->transaction_currency_id = (int)$this->sourceCurrency->id; + $this->sourceTransaction->transaction_currency_id = (int) $this->sourceCurrency->id; $this->sourceTransaction->save(); } } @@ -415,7 +420,7 @@ class TransferCurrenciesCorrections extends Command if (null === $this->destinationTransaction->transaction_currency_id && null !== $this->destinationCurrency) { $this->destinationTransaction ->transaction_currency_id - = (int)$this->destinationCurrency->id; + = (int) $this->destinationCurrency->id; $message = sprintf( 'Transaction #%d has no currency setting, now set to %s.', $this->destinationTransaction->id, @@ -436,7 +441,7 @@ class TransferCurrenciesCorrections extends Command { if (null !== $this->destinationCurrency && null === $this->destinationTransaction->foreign_amount - && (int)$this->destinationTransaction->transaction_currency_id !== (int)$this->destinationCurrency->id + && (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.', @@ -448,7 +453,7 @@ class TransferCurrenciesCorrections extends Command Log::debug($message); $this->line($message); $this->count++; - $this->destinationTransaction->transaction_currency_id = (int)$this->destinationCurrency->id; + $this->destinationTransaction->transaction_currency_id = (int) $this->destinationCurrency->id; $this->destinationTransaction->save(); } } @@ -460,7 +465,7 @@ class TransferCurrenciesCorrections extends Command */ private function fixInvalidForeignCurrency(): void { - if ((int)$this->destinationCurrency->id === (int)$this->sourceCurrency->id) { + 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; @@ -494,7 +499,7 @@ class TransferCurrenciesCorrections extends Command */ private function fixMismatchedForeignCurrency(): void { - if ((int)$this->sourceCurrency->id !== (int)$this->destinationCurrency->id) { + 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; @@ -514,7 +519,7 @@ class TransferCurrenciesCorrections extends Command 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->foreign_amount = bcmul((string) $this->destinationTransaction->foreign_amount, '-1'); $this->sourceTransaction->save(); $this->count++; Log::debug( @@ -534,7 +539,7 @@ class TransferCurrenciesCorrections extends Command 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->foreign_amount = bcmul((string) $this->sourceTransaction->foreign_amount, '-1'); $this->destinationTransaction->save(); $this->count++; Log::debug( @@ -554,7 +559,7 @@ class TransferCurrenciesCorrections extends Command */ private function fixTransactionJournalCurrency(TransactionJournal $journal): void { - if ((int)$journal->transaction_currency_id !== (int)$this->sourceCurrency->id) { + if ((int) $journal->transaction_currency_id !== (int) $this->sourceCurrency->id) { $oldCurrencyCode = $journal->transactionCurrency->code ?? '(nothing)'; $journal->transaction_currency_id = $this->sourceCurrency->id; $message = sprintf( diff --git a/app/Console/Commands/Upgrade/UpgradeDatabase.php b/app/Console/Commands/Upgrade/UpgradeDatabase.php index d0fee361ef..0f4b60f08f 100644 --- a/app/Console/Commands/Upgrade/UpgradeDatabase.php +++ b/app/Console/Commands/Upgrade/UpgradeDatabase.php @@ -120,9 +120,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/Upgrade/UpgradeLiabilities.php b/app/Console/Commands/Upgrade/UpgradeLiabilities.php index d8780ddf9e..7d971a12f1 100644 --- a/app/Console/Commands/Upgrade/UpgradeLiabilities.php +++ b/app/Console/Commands/Upgrade/UpgradeLiabilities.php @@ -81,12 +81,14 @@ class UpgradeLiabilities extends Command /** * @return bool * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ private function isExecuted(): bool { $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); if (null !== $configVar) { - return (bool)$configVar->data; + return (bool) $configVar->data; } return false; @@ -159,10 +161,10 @@ class UpgradeLiabilities extends Command return; } // source MUST be the liability. - if ((int)$destination->account_id === (int)$account->id) { + if ((int) $destination->account_id === (int) $account->id) { Log::debug(sprintf('Must switch around, because account #%d is the destination.', $destination->account_id)); // so if not, switch things around: - $sourceAccountId = (int)$source->account_id; + $sourceAccountId = (int) $source->account_id; $source->account_id = $destination->account_id; $destination->account_id = $sourceAccountId; $source->save(); diff --git a/app/Console/Commands/UpgradeFireflyInstructions.php b/app/Console/Commands/UpgradeFireflyInstructions.php index 2257339e50..63b19a6315 100644 --- a/app/Console/Commands/UpgradeFireflyInstructions.php +++ b/app/Console/Commands/UpgradeFireflyInstructions.php @@ -54,10 +54,10 @@ class UpgradeFireflyInstructions extends Command public function handle(): int { $this->generateInstallationId(); - 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 ecca77971d..7a8c06e076 100644 --- a/app/Console/Commands/VerifiesAccessToken.php +++ b/app/Console/Commands/VerifiesAccessToken.php @@ -43,7 +43,7 @@ trait VerifiesAccessToken */ public function getUser(): User { - $userId = (int)$this->option('user'); + $userId = (int) $this->option('user'); /** @var UserRepositoryInterface $repository */ $repository = app(UserRepositoryInterface::class); $user = $repository->find($userId); @@ -71,8 +71,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->find($userId); diff --git a/app/Console/Commands/VerifySecurityAlerts.php b/app/Console/Commands/VerifySecurityAlerts.php index c0bd37e3b8..4427f91a4d 100644 --- a/app/Console/Commands/VerifySecurityAlerts.php +++ b/app/Console/Commands/VerifySecurityAlerts.php @@ -25,7 +25,6 @@ declare(strict_types=1); namespace FireflyIII\Console\Commands; use Illuminate\Console\Command; -use Illuminate\Contracts\Filesystem\FileNotFoundException; use Log; use Storage; @@ -51,7 +50,7 @@ class VerifySecurityAlerts extends Command * Execute the console command. * * @return int - * @throws FileNotFoundException + * @throws \League\Flysystem\FilesystemException */ public function handle(): int { diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index 1939ff84af..28fa63e7fb 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -42,7 +42,6 @@ class Kernel extends ConsoleKernel { $this->load(__DIR__ . '/Commands'); - /** @noinspection PhpIncludeInspection */ require base_path('routes/console.php'); } diff --git a/app/Enums/ClauseType.php b/app/Enums/ClauseType.php index 1897aee173..6b78943a0e 100644 --- a/app/Enums/ClauseType.php +++ b/app/Enums/ClauseType.php @@ -30,6 +30,6 @@ namespace FireflyIII\Enums; class ClauseType { public const TRANSACTION = 'transaction'; - public const WHERE = 'where'; public const UPDATE = 'update'; + public const WHERE = 'where'; } diff --git a/app/Events/AdminRequestedTestMessage.php b/app/Events/AdminRequestedTestMessage.php index 78f90858c8..97836998c4 100644 --- a/app/Events/AdminRequestedTestMessage.php +++ b/app/Events/AdminRequestedTestMessage.php @@ -37,21 +37,16 @@ class AdminRequestedTestMessage extends Event { use SerializesModels; - /** @var string The users IP address */ - public $ipAddress; - /** @var User The user */ - public $user; + public User $user; /** * Create a new event instance. * - * @param User $user - * @param string $ipAddress + * @param User $user */ - public function __construct(User $user, string $ipAddress) + public function __construct(User $user) { - Log::debug(sprintf('Triggered AdminRequestedTestMessage for user #%d (%s) and IP %s!', $user->id, $user->email, $ipAddress)); - $this->user = $user; - $this->ipAddress = $ipAddress; + Log::debug(sprintf('Triggered AdminRequestedTestMessage for user #%d (%s)', $user->id, $user->email)); + $this->user = $user; } } diff --git a/app/Events/RequestedReportOnJournals.php b/app/Events/RequestedReportOnJournals.php index fc91987d1c..ac59c8f3a7 100644 --- a/app/Events/RequestedReportOnJournals.php +++ b/app/Events/RequestedReportOnJournals.php @@ -40,10 +40,8 @@ class RequestedReportOnJournals { use Dispatchable, InteractsWithSockets, SerializesModels; - /** @var Collection The transaction groups to report on. */ - public $groups; - /** @var int The ID of the user. */ - public $userId; + public Collection $groups; + public int $userId; /** * Create a new event instance. diff --git a/app/Events/UserChangedEmail.php b/app/Events/UserChangedEmail.php index 8f4f70090d..31777767a2 100644 --- a/app/Events/UserChangedEmail.php +++ b/app/Events/UserChangedEmail.php @@ -36,14 +36,9 @@ class UserChangedEmail extends Event { use SerializesModels; - /** @var string The user's IP address */ - public $ipAddress; - /** @var string The user's new email address */ - public $newEmail; - /** @var string The user's old email address */ - public $oldEmail; - /** @var User The user itself */ - public $user; + public string $newEmail; + public string $oldEmail; + public User $user; /** * UserChangedEmail constructor. @@ -51,13 +46,11 @@ class UserChangedEmail extends Event * @param User $user * @param string $newEmail * @param string $oldEmail - * @param string $ipAddress */ - public function __construct(User $user, string $newEmail, string $oldEmail, string $ipAddress) + public function __construct(User $user, string $newEmail, string $oldEmail) { - $this->user = $user; - $this->ipAddress = $ipAddress; - $this->oldEmail = $oldEmail; - $this->newEmail = $newEmail; + $this->user = $user; + $this->oldEmail = $oldEmail; + $this->newEmail = $newEmail; } } diff --git a/app/Ldap/AttributeHandler.php b/app/Events/WarnUserAboutBill.php similarity index 57% rename from app/Ldap/AttributeHandler.php rename to app/Events/WarnUserAboutBill.php index e3e13c6795..de6ae49021 100644 --- a/app/Ldap/AttributeHandler.php +++ b/app/Events/WarnUserAboutBill.php @@ -1,8 +1,8 @@ email = $ldapUser->getFirstAttribute('mail'); - $database->save(); + $this->bill = $bill; + $this->field = $field; + $this->diff = $diff; } } diff --git a/app/Exceptions/GracefulNotFoundHandler.php b/app/Exceptions/GracefulNotFoundHandler.php index 9a68e1437f..92edf65763 100644 --- a/app/Exceptions/GracefulNotFoundHandler.php +++ b/app/Exceptions/GracefulNotFoundHandler.php @@ -71,9 +71,11 @@ class GracefulNotFoundHandler extends ExceptionHandler return parent::render($request, $e); case 'accounts.show': + case 'accounts.edit': case 'accounts.show.all': return $this->handleAccount($request, $e); case 'transactions.show': + case 'transactions.edit': return $this->handleGroup($request, $e); case 'attachments.show': case 'attachments.edit': @@ -119,7 +121,6 @@ class GracefulNotFoundHandler extends ExceptionHandler $request->session()->reflash(); return redirect(route('rules.index')); - case 'transactions.edit': case 'transactions.mass.edit': case 'transactions.mass.delete': case 'transactions.bulk.edit': @@ -147,7 +148,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) { @@ -175,7 +176,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); @@ -215,7 +216,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) { diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index 9b52ef9dc6..fc07889266 100644 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -153,6 +153,12 @@ class Handler extends ExceptionHandler $userData['id'] = auth()->user()->id; $userData['email'] = auth()->user()->email; } + + $headers = []; + if (request()->headers) { + $headers = request()->headers->all(); + } + $data = [ 'class' => get_class($e), 'errorMessage' => $e->getMessage(), @@ -165,11 +171,12 @@ class Handler extends ExceptionHandler 'url' => request()->fullUrl(), 'userAgent' => request()->userAgent(), 'json' => request()->acceptsJson(), + 'headers' => $headers, ]; // 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); parent::report($e); diff --git a/app/Factory/AccountFactory.php b/app/Factory/AccountFactory.php index 0bd843e5a1..2307f93b10 100644 --- a/app/Factory/AccountFactory.php +++ b/app/Factory/AccountFactory.php @@ -74,6 +74,7 @@ class AccountFactory * * @return Account * @throws FireflyException + * @throws JsonException */ public function findOrCreate(string $accountName, string $accountType): Account { @@ -137,7 +138,7 @@ class AccountFactory */ protected function getAccountType(array $data): ?AccountType { - $accountTypeId = array_key_exists('account_type_id', $data) ? (int)$data['account_type_id'] : 0; + $accountTypeId = array_key_exists('account_type_id', $data) ? (int) $data['account_type_id'] : 0; $accountTypeName = array_key_exists('account_type_name', $data) ? $data['account_type_name'] : null; $result = null; // find by name or ID @@ -182,6 +183,7 @@ class AccountFactory * @param array $data * * @return Account + * @throws FireflyException * @throws JsonException */ private function createAccount(AccountType $type, array $data): Account @@ -200,7 +202,7 @@ class AccountFactory 'iban' => $data['iban'], ]; // fix virtual balance when it's empty - if ('' === (string)$databaseData['virtual_balance']) { + if ('' === (string) $databaseData['virtual_balance']) { $databaseData['virtual_balance'] = null; } // remove virtual balance when not an asset account or a liability @@ -252,9 +254,9 @@ class AccountFactory */ private function cleanMetaDataArray(Account $account, array $data): array { - $currencyId = array_key_exists('currency_id', $data) ? (int)$data['currency_id'] : 0; - $currencyCode = array_key_exists('currency_code', $data) ? (string)$data['currency_code'] : ''; - $accountRole = array_key_exists('account_role', $data) ? (string)$data['account_role'] : null; + $currencyId = array_key_exists('currency_id', $data) ? (int) $data['currency_id'] : 0; + $currencyCode = array_key_exists('currency_code', $data) ? (string) $data['currency_code'] : ''; + $accountRole = array_key_exists('account_role', $data) ? (string) $data['account_role'] : null; $currency = $this->getCurrency($currencyId, $currencyCode); // only asset account may have a role: @@ -301,7 +303,7 @@ class AccountFactory $data[$field] = 1; } - $factory->crud($account, $field, (string)$data[$field]); + $factory->crud($account, $field, (string) $data[$field]); } } } @@ -361,7 +363,6 @@ class AccountFactory * @param array $data * * @throws FireflyException - * @throws JsonException */ private function storeOrder(Account $account, array $data): void { @@ -372,7 +373,7 @@ class AccountFactory $order = $maxOrder + 1; } if (array_key_exists('order', $data)) { - $order = (int)($data['order'] > $maxOrder ? $maxOrder + 1 : $data['order']); + $order = (int) ($data['order'] > $maxOrder ? $maxOrder + 1 : $data['order']); $order = 0 === $order ? $maxOrder + 1 : $order; } diff --git a/app/Factory/AccountMetaFactory.php b/app/Factory/AccountMetaFactory.php index 322d1ea144..9c48b74b82 100644 --- a/app/Factory/AccountMetaFactory.php +++ b/app/Factory/AccountMetaFactory.php @@ -58,11 +58,9 @@ class AccountMetaFactory } // if $data has field and $entry is not null, update $entry: - if (null !== $entry) { - $entry->data = $value; - $entry->save(); - Log::debug(sprintf('Updated meta-field "%s":"%s" for #%d ("%s") ', $field, $value, $account->id, $account->name)); - } + $entry->data = $value; + $entry->save(); + Log::debug(sprintf('Updated meta-field "%s":"%s" for #%d ("%s") ', $field, $value, $account->id, $account->name)); } if ('' === $value && null !== $entry) { try { diff --git a/app/Factory/AttachmentFactory.php b/app/Factory/AttachmentFactory.php index 771aa695fb..96bbd1d55d 100644 --- a/app/Factory/AttachmentFactory.php +++ b/app/Factory/AttachmentFactory.php @@ -52,7 +52,7 @@ class AttachmentFactory // get journal instead of transaction. if (Transaction::class === $model) { /** @var Transaction $transaction */ - $transaction = $this->user->transactions()->find((int)$data['attachable_id']); + $transaction = $this->user->transactions()->find((int) $data['attachable_id']); if (null === $transaction) { throw new FireflyException('Unexpectedly could not find transaction'); } @@ -75,7 +75,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 8bde75a9ea..96ea82bd50 100644 --- a/app/Factory/BillFactory.php +++ b/app/Factory/BillFactory.php @@ -46,12 +46,13 @@ class BillFactory * * @return Bill|null * @throws FireflyException + * @throws \JsonException */ public function create(array $data): ?Bill { Log::debug(sprintf('Now in %s', __METHOD__), $data); $factory = app(TransactionCurrencyFactory::class); - $currency = $factory->find((int)($data['currency_id'] ?? null), (string)($data['currency_code'] ?? null)) ?? + $currency = $factory->find((int) ($data['currency_id'] ?? null), (string) ($data['currency_code'] ?? null)) ?? app('amount')->getDefaultCurrencyByUser($this->user); try { @@ -82,7 +83,7 @@ class BillFactory } if (array_key_exists('notes', $data)) { - $this->updateNote($bill, (string)$data['notes']); + $this->updateNote($bill, (string) $data['notes']); } $objectGroupTitle = $data['object_group_title'] ?? ''; if ('' !== $objectGroupTitle) { @@ -93,7 +94,7 @@ class BillFactory } } // try also with ID: - $objectGroupId = (int)($data['object_group_id'] ?? 0); + $objectGroupId = (int) ($data['object_group_id'] ?? 0); if (0 !== $objectGroupId) { $objectGroup = $this->findObjectGroupById($objectGroupId); if (null !== $objectGroup) { @@ -113,8 +114,8 @@ class BillFactory */ 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 f3ea839f9e..69a25e6b92 100644 --- a/app/Factory/BudgetFactory.php +++ b/app/Factory/BudgetFactory.php @@ -41,8 +41,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 6adc1800a0..8979d5068b 100644 --- a/app/Factory/CategoryFactory.php +++ b/app/Factory/CategoryFactory.php @@ -45,8 +45,8 @@ class CategoryFactory */ 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/PiggyBankFactory.php b/app/Factory/PiggyBankFactory.php index 29a4fb70d9..6709c3fa64 100644 --- a/app/Factory/PiggyBankFactory.php +++ b/app/Factory/PiggyBankFactory.php @@ -41,8 +41,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 790c432a6f..3c02765372 100644 --- a/app/Factory/RecurrenceFactory.php +++ b/app/Factory/RecurrenceFactory.php @@ -84,7 +84,7 @@ class RecurrenceFactory $firstDate = $data['recurrence']['first_date']; } if (array_key_exists('nr_of_repetitions', $data['recurrence'])) { - $repetitions = (int)$data['recurrence']['nr_of_repetitions']; + $repetitions = (int) $data['recurrence']['nr_of_repetitions']; } if (array_key_exists('repeat_until', $data['recurrence'])) { $repeatUntil = $data['recurrence']['repeat_until']; @@ -120,7 +120,7 @@ class RecurrenceFactory $recurrence->save(); if (array_key_exists('notes', $data['recurrence'])) { - $this->updateNote($recurrence, (string)$data['recurrence']['notes']); + $this->updateNote($recurrence, (string) $data['recurrence']['notes']); } diff --git a/app/Factory/TagFactory.php b/app/Factory/TagFactory.php index 406fb4e1ad..66fa91707d 100644 --- a/app/Factory/TagFactory.php +++ b/app/Factory/TagFactory.php @@ -80,9 +80,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 4d6779a911..d29e963fb4 100644 --- a/app/Factory/TransactionCurrencyFactory.php +++ b/app/Factory/TransactionCurrencyFactory.php @@ -43,6 +43,15 @@ class TransactionCurrencyFactory */ public function create(array $data): TransactionCurrency { + // if the code already exists (deleted) + // force delete it and then create the transaction: + $count = TransactionCurrency::withTrashed()->whereCode($data['code'])->count(); + if (1 === $count) { + $old = TransactionCurrency::withTrashed()->whereCode($data['code'])->first(); + $old->forceDelete(); + Log::warning(sprintf('Force deleted old currency with ID #%d and code "%s".', $old->id, $data['code'])); + } + try { /** @var TransactionCurrency $result */ $result = TransactionCurrency::create( @@ -71,8 +80,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/TransactionGroupFactory.php b/app/Factory/TransactionGroupFactory.php index edd1ef438d..970e4d7489 100644 --- a/app/Factory/TransactionGroupFactory.php +++ b/app/Factory/TransactionGroupFactory.php @@ -57,6 +57,7 @@ class TransactionGroupFactory * @return TransactionGroup * @throws DuplicateTransactionException * @throws FireflyException + * @throws \JsonException */ public function create(array $data): TransactionGroup { diff --git a/app/Factory/TransactionJournalFactory.php b/app/Factory/TransactionJournalFactory.php index 0a23e02557..d44a48bd66 100644 --- a/app/Factory/TransactionJournalFactory.php +++ b/app/Factory/TransactionJournalFactory.php @@ -160,11 +160,11 @@ class TransactionJournalFactory $type = $this->typeRepository->findTransactionType(null, $row['type']); $carbon = $row['date'] ?? today(config('app.timezone')); $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 = (string)$row['description']; + $description = (string) $row['description']; /** Manipulate basic fields */ $carbon->setTimezone(config('app.timezone')); @@ -237,7 +237,7 @@ class TransactionJournalFactory $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()); @@ -256,7 +256,7 @@ class TransactionJournalFactory $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()); @@ -307,7 +307,7 @@ class TransactionJournalFactory $json = json_encode($dataRow, JSON_THROW_ON_ERROR); if (false === $json) { - $json = json_encode((string)microtime(), JSON_THROW_ON_ERROR); + $json = json_encode((string) microtime(), JSON_THROW_ON_ERROR); Log::error(sprintf('Could not hash the original row! %s', json_last_error_msg()), $dataRow); } @@ -366,10 +366,10 @@ class TransactionJournalFactory // validate source account. $array = [ - 'id' => $data['source_id'] ? (int)$data['source_id'] : null, - 'name' => $data['source_name'] ? (string)$data['source_name'] : null, - 'iban' => $data['source_iban'] ? (string)$data['source_iban'] : null, - 'number' => $data['source_number'] ? (string)$data['source_number'] : null, + 'id' => $data['source_id'] ? (int) $data['source_id'] : null, + 'name' => $data['source_name'] ? (string) $data['source_name'] : null, + 'iban' => $data['source_iban'] ? (string) $data['source_iban'] : null, + 'number' => $data['source_number'] ? (string) $data['source_number'] : null, ]; $validSource = $this->accountValidator->validateSource($array); @@ -381,10 +381,10 @@ class TransactionJournalFactory // validate destination account $array = [ - 'id' => $data['destination_id'] ? (int)$data['destination_id'] : null, - 'name' => $data['destination_name'] ? (string)$data['destination_name'] : null, - 'iban' => $data['destination_iban'] ? (string)$data['destination_iban'] : null, - 'number' => $data['destination_number'] ? (string)$data['destination_number'] : null, + 'id' => $data['destination_id'] ? (int) $data['destination_id'] : null, + 'name' => $data['destination_name'] ? (string) $data['destination_name'] : null, + 'iban' => $data['destination_iban'] ? (string) $data['destination_iban'] : null, + 'number' => $data['destination_number'] ? (string) $data['destination_number'] : null, ]; $validDestination = $this->accountValidator->validateDestination($array); @@ -417,6 +417,8 @@ class TransactionJournalFactory * @param Account $account * * @return TransactionCurrency + * @throws FireflyException + * @throws JsonException */ private function getCurrency(?TransactionCurrency $currency, Account $account): TransactionCurrency { @@ -526,7 +528,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); @@ -558,7 +560,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'])); diff --git a/app/Factory/TransactionJournalMetaFactory.php b/app/Factory/TransactionJournalMetaFactory.php index c734664e8f..99dc2c746c 100644 --- a/app/Factory/TransactionJournalMetaFactory.php +++ b/app/Factory/TransactionJournalMetaFactory.php @@ -60,7 +60,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/Generator/Chart/Basic/ChartJsGenerator.php b/app/Generator/Chart/Basic/ChartJsGenerator.php index a2d9d2aea7..4aa3f0cb9c 100644 --- a/app/Generator/Chart/Basic/ChartJsGenerator.php +++ b/app/Generator/Chart/Basic/ChartJsGenerator.php @@ -50,7 +50,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); @@ -59,7 +59,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; @@ -165,7 +165,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); } @@ -174,7 +174,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/Report/Account/MonthReportGenerator.php b/app/Generator/Report/Account/MonthReportGenerator.php index a38d7699f2..937548f453 100644 --- a/app/Generator/Report/Account/MonthReportGenerator.php +++ b/app/Generator/Report/Account/MonthReportGenerator.php @@ -64,6 +64,16 @@ class MonthReportGenerator implements ReportGeneratorInterface return $result; } + /** + * Return the preferred period. + * + * @return string + */ + protected function preferredPeriod(): string + { + return 'day'; + } + /** * Set accounts. * @@ -155,14 +165,4 @@ class MonthReportGenerator implements ReportGeneratorInterface { return $this; } - - /** - * Return the preferred period. - * - * @return string - */ - protected function preferredPeriod(): string - { - return 'day'; - } } diff --git a/app/Generator/Report/Audit/MonthReportGenerator.php b/app/Generator/Report/Audit/MonthReportGenerator.php index 1895916c37..7af6f426ca 100644 --- a/app/Generator/Report/Audit/MonthReportGenerator.php +++ b/app/Generator/Report/Audit/MonthReportGenerator.php @@ -49,6 +49,8 @@ class MonthReportGenerator implements ReportGeneratorInterface * Generates the report. * * @return string + * @throws FireflyException + * @throws JsonException * @codeCoverageIgnore */ public function generate(): string @@ -90,6 +92,80 @@ class MonthReportGenerator implements ReportGeneratorInterface return $result; } + /** + * Get the audit report. + * + * @param Account $account + * @param Carbon $date + * + * @return array + * @throws FireflyException + * @throws JsonException + */ + #[ArrayShape(['journals' => "array", 'currency' => "mixed", 'exists' => "bool", 'end' => "string", 'endBalance' => "mixed", 'dayBefore' => "string", + 'dayBeforeBalance' => "mixed"])] public function getAuditReport(Account $account, Carbon $date): array + { + /** @var AccountRepositoryInterface $accountRepository */ + $accountRepository = app(AccountRepositoryInterface::class); + $accountRepository->setUser($account->user); + + /** @var JournalRepositoryInterface $journalRepository */ + $journalRepository = app(JournalRepositoryInterface::class); + $journalRepository->setUser($account->user); + + /** @var GroupCollectorInterface $collector */ + $collector = app(GroupCollectorInterface::class); + $collector->setAccounts(new Collection([$account]))->setRange($this->start, $this->end)->withAccountInformation() + ->withBudgetInformation()->withCategoryInformation()->withBillInformation(); + $journals = $collector->getExtractedJournals(); + $journals = array_reverse($journals, true); + $dayBeforeBalance = app('steam')->balance($account, $date); + $startBalance = $dayBeforeBalance; + $defaultCurrency = app('amount')->getDefaultCurrencyByUser($account->user); + $currency = $accountRepository->getAccountCurrency($account) ?? $defaultCurrency; + + foreach ($journals as $index => $journal) { + $journals[$index]['balance_before'] = $startBalance; + $transactionAmount = $journal['amount']; + + // make sure amount is in the right "direction". + if ($account->id === $journal['destination_account_id']) { + $transactionAmount = app('steam')->positive($journal['amount']); + } + + if ($currency->id === $journal['foreign_currency_id']) { + $transactionAmount = $journal['foreign_amount']; + if ($account->id === $journal['destination_account_id']) { + $transactionAmount = app('steam')->positive($journal['foreign_amount']); + } + } + + $newBalance = bcadd($startBalance, $transactionAmount); + $journals[$index]['balance_after'] = $newBalance; + $startBalance = $newBalance; + + // add meta dates for each journal. + $journals[$index]['interest_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'interest_date'); + $journals[$index]['book_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'book_date'); + $journals[$index]['process_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'process_date'); + $journals[$index]['due_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'due_date'); + $journals[$index]['payment_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'payment_date'); + $journals[$index]['invoice_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'invoice_date'); + + } + $locale = app('steam')->getLocale(); + + return [ + 'journals' => $journals, + 'currency' => $currency, + 'exists' => !empty($journals), + 'end' => $this->end->isoFormat((string) trans('config.month_and_day_moment_js', [], $locale)), + 'endBalance' => app('steam')->balance($account, $this->end), + 'dayBefore' => $date->isoFormat((string) trans('config.month_and_day_moment_js', [], $locale)), + 'dayBeforeBalance' => $dayBeforeBalance, + ]; + } + /** * Account collection setter. * @@ -187,78 +263,4 @@ class MonthReportGenerator implements ReportGeneratorInterface { return $this; } - - /** - * Get the audit report. - * - * @param Account $account - * @param Carbon $date - * - * @return array - * @throws FireflyException - * @throws JsonException - */ - #[ArrayShape(['journals' => "array", 'currency' => "mixed", 'exists' => "bool", 'end' => "string", 'endBalance' => "mixed", 'dayBefore' => "string", - 'dayBeforeBalance' => "mixed"])] public function getAuditReport(Account $account, Carbon $date): array - { - /** @var AccountRepositoryInterface $accountRepository */ - $accountRepository = app(AccountRepositoryInterface::class); - $accountRepository->setUser($account->user); - - /** @var JournalRepositoryInterface $journalRepository */ - $journalRepository = app(JournalRepositoryInterface::class); - $journalRepository->setUser($account->user); - - /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); - $collector->setAccounts(new Collection([$account]))->setRange($this->start, $this->end)->withAccountInformation() - ->withBudgetInformation()->withCategoryInformation()->withBillInformation(); - $journals = $collector->getExtractedJournals(); - $journals = array_reverse($journals, true); - $dayBeforeBalance = app('steam')->balance($account, $date); - $startBalance = $dayBeforeBalance; - $defaultCurrency = app('amount')->getDefaultCurrencyByUser($account->user); - $currency = $accountRepository->getAccountCurrency($account) ?? $defaultCurrency; - - foreach ($journals as $index => $journal) { - $journals[$index]['balance_before'] = $startBalance; - $transactionAmount = $journal['amount']; - - // make sure amount is in the right "direction". - if ($account->id === $journal['destination_account_id']) { - $transactionAmount = app('steam')->positive($journal['amount']); - } - - if ($currency->id === $journal['foreign_currency_id']) { - $transactionAmount = $journal['foreign_amount']; - if ($account->id === $journal['destination_account_id']) { - $transactionAmount = app('steam')->positive($journal['foreign_amount']); - } - } - - $newBalance = bcadd($startBalance, $transactionAmount); - $journals[$index]['balance_after'] = $newBalance; - $startBalance = $newBalance; - - // add meta dates for each journal. - $journals[$index]['interest_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'interest_date'); - $journals[$index]['book_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'book_date'); - $journals[$index]['process_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'process_date'); - $journals[$index]['due_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'due_date'); - $journals[$index]['payment_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'payment_date'); - $journals[$index]['invoice_date'] = $journalRepository->getMetaDateById($journal['transaction_journal_id'], 'invoice_date'); - - } - $locale = app('steam')->getLocale(); - - return [ - 'journals' => $journals, - 'currency' => $currency, - 'exists' => !empty($journals), - 'end' => $this->end->formatLocalized((string)trans('config.month_and_day', [], $locale)), - 'endBalance' => app('steam')->balance($account, $this->end), - 'dayBefore' => $date->formatLocalized((string)trans('config.month_and_day', [], $locale)), - 'dayBeforeBalance' => $dayBeforeBalance, - ]; - } } diff --git a/app/Generator/Webhook/StandardMessageGenerator.php b/app/Generator/Webhook/StandardMessageGenerator.php index a01140490e..65ff06d706 100644 --- a/app/Generator/Webhook/StandardMessageGenerator.php +++ b/app/Generator/Webhook/StandardMessageGenerator.php @@ -66,38 +66,6 @@ class StandardMessageGenerator implements MessageGeneratorInterface $this->run(); } - /** - * @inheritDoc - */ - public function getVersion(): int - { - return $this->version; - } - - /** - * @param Collection $objects - */ - public function setObjects(Collection $objects): void - { - $this->objects = $objects; - } - - /** - * @param int $trigger - */ - public function setTrigger(int $trigger): void - { - $this->trigger = $trigger; - } - - /** - * @param User $user - */ - public function setUser(User $user): void - { - $this->user = $user; - } - /** * @return Collection */ @@ -134,6 +102,8 @@ class StandardMessageGenerator implements MessageGeneratorInterface /** * @param Webhook $webhook * @param Model $model + * @throws FireflyException + * @throws \JsonException */ private function generateMessage(Webhook $webhook, Model $model): void { @@ -197,6 +167,14 @@ class StandardMessageGenerator implements MessageGeneratorInterface $this->storeMessage($webhook, $basicMessage); } + /** + * @inheritDoc + */ + public function getVersion(): int + { + return $this->version; + } + /** * @param TransactionGroup $transactionGroup * @@ -220,9 +198,9 @@ class StandardMessageGenerator implements MessageGeneratorInterface * @param Webhook $webhook * @param array $message * - * @return WebhookMessage + * @return void */ - private function storeMessage(Webhook $webhook, array $message): WebhookMessage + private function storeMessage(Webhook $webhook, array $message): void { $webhookMessage = new WebhookMessage; $webhookMessage->webhook()->associate($webhook); @@ -233,6 +211,29 @@ class StandardMessageGenerator implements MessageGeneratorInterface $webhookMessage->save(); Log::debug(sprintf('Stored new webhook message #%d', $webhookMessage->id)); - return $webhookMessage; + } + + /** + * @param Collection $objects + */ + public function setObjects(Collection $objects): void + { + $this->objects = $objects; + } + + /** + * @param int $trigger + */ + public function setTrigger(int $trigger): void + { + $this->trigger = $trigger; + } + + /** + * @param User $user + */ + public function setUser(User $user): void + { + $this->user = $user; } } diff --git a/app/Handlers/Events/APIEventHandler.php b/app/Handlers/Events/APIEventHandler.php index e871fd26cb..b3fdd0222c 100644 --- a/app/Handlers/Events/APIEventHandler.php +++ b/app/Handlers/Events/APIEventHandler.php @@ -30,7 +30,6 @@ use FireflyIII\Repositories\User\UserRepositoryInterface; use Laravel\Passport\Events\AccessTokenCreated; use Log; use Mail; -use Request; use Session; /** @@ -50,7 +49,7 @@ class APIEventHandler { /** @var UserRepositoryInterface $repository */ $repository = app(UserRepositoryInterface::class); - $user = $repository->find((int)$event->userId); + $user = $repository->find((int) $event->userId); if (null !== $user) { $email = $user->email; @@ -59,18 +58,16 @@ class APIEventHandler $email = config('firefly.site_owner'); } - $ipAddress = Request::ip(); - // see if user has alternative email address: $pref = app('preferences')->getForUser($user, 'remote_guard_alt_email'); if (null !== $pref) { - $email = (string)(is_array($pref->data) ? $email : $pref->data); + $email = (string) (is_array($pref->data) ? $email : $pref->data); } - Log::debug(sprintf('Now in APIEventHandler::accessTokenCreated. Email is %s, IP is %s', $email, $ipAddress)); + Log::debug(sprintf('Now in APIEventHandler::accessTokenCreated. Email is %s', $email)); try { Log::debug('Trying to send message...'); - Mail::to($email)->send(new AccessTokenCreatedMail($email, $ipAddress)); + Mail::to($email)->send(new AccessTokenCreatedMail); } catch (Exception $e) { // @phpstan-ignore-line Log::debug('Send message failed! :('); diff --git a/app/Handlers/Events/AdminEventHandler.php b/app/Handlers/Events/AdminEventHandler.php index 5ed7953a67..d35ab1c2c4 100644 --- a/app/Handlers/Events/AdminEventHandler.php +++ b/app/Handlers/Events/AdminEventHandler.php @@ -51,8 +51,7 @@ class AdminEventHandler // is user even admin? if ($repository->hasRole($event->user, 'owner')) { - $email = $event->user->email; - $ipAddress = $event->ipAddress; + $email = $event->user->email; // if user is demo user, send to owner: if ($event->user->hasRole('demo')) { @@ -65,10 +64,10 @@ class AdminEventHandler $email = $pref->data; } - Log::debug(sprintf('Now in sendTestMessage event handler. Email is %s, IP is %s', $email, $ipAddress)); + Log::debug(sprintf('Now in sendTestMessage event handler. Email is %s', $email)); try { Log::debug('Trying to send message...'); - Mail::to($email)->send(new AdminTestMail($email, $ipAddress)); + Mail::to($email)->send(new AdminTestMail($email)); // Laravel cannot pretend this process failed during testing. } catch (Exception $e) { // @phpstan-ignore-line diff --git a/app/Handlers/Events/AutomationHandler.php b/app/Handlers/Events/AutomationHandler.php index e05d596997..cd72404822 100644 --- a/app/Handlers/Events/AutomationHandler.php +++ b/app/Handlers/Events/AutomationHandler.php @@ -43,7 +43,6 @@ class AutomationHandler * @param RequestedReportOnJournals $event * * @return bool - * @throws FireflyException */ public function reportJournals(RequestedReportOnJournals $event): bool { @@ -58,23 +57,9 @@ class AutomationHandler $repository = app(UserRepositoryInterface::class); $user = $repository->find($event->userId); if (null !== $user && 0 !== $event->groups->count()) { - - $email = $user->email; - - // see if user has alternative email address: - $pref = app('preferences')->getForUser($user, 'remote_guard_alt_email'); - if (null !== $pref) { - $email = $pref->data; - } - - // if user is demo user, send to owner: - if ($user->hasRole('demo')) { - $email = config('firefly.site_owner'); - } - try { Log::debug('Trying to mail...'); - Mail::to($user->email)->send(new ReportNewJournalsMail($email, '127.0.0.1', $event->groups)); + Mail::to($user->email)->send(new ReportNewJournalsMail($event->groups)); } catch (Exception $e) { // @phpstan-ignore-line Log::debug('Send message failed! :('); diff --git a/app/Handlers/Events/BillEventHandler.php b/app/Handlers/Events/BillEventHandler.php new file mode 100644 index 0000000000..21b04d7cce --- /dev/null +++ b/app/Handlers/Events/BillEventHandler.php @@ -0,0 +1,64 @@ +. + */ + +declare(strict_types=1); + +namespace FireflyIII\Handlers\Events; + +use FireflyIII\Events\WarnUserAboutBill; +use FireflyIII\Mail\BillWarningMail; +use Log; +use Mail; + +/** + * Class BillEventHandler + */ +class BillEventHandler +{ + /** + * @param WarnUserAboutBill $event + * @return void + * @throws \FireflyIII\Exceptions\FireflyException + */ + public function warnAboutBill(WarnUserAboutBill $event): void + { + $bill = $event->bill; + $field = $event->field; + $diff = $event->diff; + $user = $bill->user; + $address = $user->email; + $ipAddress = request()?->ip(); + + // see if user has alternative email address: + $pref = app('preferences')->getForUser($user, 'remote_guard_alt_email'); + if (null !== $pref) { + $address = $pref->data; + } + + // send message: + Mail::to($address)->send(new BillWarningMail($bill, $field, $diff, $ipAddress)); + + + Log::debug('warnAboutBill'); + } + +} diff --git a/app/Handlers/Events/LDAPEventHandler.php b/app/Handlers/Events/LDAPEventHandler.php deleted file mode 100644 index 84253d3c79..0000000000 --- a/app/Handlers/Events/LDAPEventHandler.php +++ /dev/null @@ -1,57 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Handlers\Events; - - -use FireflyIII\User; -use LdapRecord\Laravel\Events\Import\Imported; -use Log; - -/** - * Class LDAPEventHandler - */ -class LDAPEventHandler -{ - - /** - * @param Imported $event - */ - public function importedUser(Imported $event) - { - Log::debug(sprintf('Now in %s', __METHOD__)); - /** @var User $user */ - $user = $event->eloquent; - $alternative = User::where('email', $user->email)->where('id', '!=', $user->id)->first(); - if (null !== $alternative) { - Log::debug(sprintf('User #%d is created but user #%d already exists.', $user->id, $alternative->id)); - $alternative->objectguid = $user->objectguid; - $alternative->domain = $user->domain; - $alternative->save(); - $user->delete(); - auth()->logout(); - } - } - -} diff --git a/app/Handlers/Events/UpdatedGroupEventHandler.php b/app/Handlers/Events/UpdatedGroupEventHandler.php index 0fb4958dcf..7000166584 100644 --- a/app/Handlers/Events/UpdatedGroupEventHandler.php +++ b/app/Handlers/Events/UpdatedGroupEventHandler.php @@ -132,12 +132,12 @@ class UpdatedGroupEventHandler ->orderBy('transaction_journals.description', 'DESC') ->first(); - if(null === $first) { + if (null === $first) { Log::warning(sprintf('Group #%d has no transaction journals.', $group->id)); return; } - $all = $group->transactionJournals()->get()->pluck('id')->toArray(); + $all = $group->transactionJournals()->get()->pluck('id')->toArray(); /** @var Account $sourceAccount */ $sourceAccount = $first->transactions()->where('amount', '<', '0')->first()->account; /** @var Account $destAccount */ diff --git a/app/Handlers/Events/UserEventHandler.php b/app/Handlers/Events/UserEventHandler.php index 1089eae7c4..18994a20fa 100644 --- a/app/Handlers/Events/UserEventHandler.php +++ b/app/Handlers/Events/UserEventHandler.php @@ -125,17 +125,17 @@ class UserEventHandler // create a new group. while (true === $groupExists) { $groupExists = UserGroup::where('title', $groupTitle)->count() > 0; - if(false === $groupExists) { + if (false === $groupExists) { $group = UserGroup::create(['title' => $groupTitle]); break; } $groupTitle = sprintf('%s-%d', $user->email, $index); $index++; - if($index > 99) { + if ($index > 99) { throw new FireflyException('Email address can no longer be used for registrations.'); } } - $role = UserRole::where('title', UserRole::OWNER)->first(); + $role = UserRole::where('title', UserRole::OWNER)->first(); if (null === $role) { throw new FireflyException('The user role is unexpectedly empty. Did you run all migrations?'); } @@ -226,14 +226,13 @@ class UserEventHandler */ public function sendEmailChangeConfirmMail(UserChangedEmail $event): bool { - $newEmail = $event->newEmail; - $oldEmail = $event->oldEmail; - $user = $event->user; - $ipAddress = $event->ipAddress; - $token = app('preferences')->getForUser($user, 'email_change_confirm_token', 'invalid'); - $uri = route('profile.confirm-email-change', [$token->data]); + $newEmail = $event->newEmail; + $oldEmail = $event->oldEmail; + $user = $event->user; + $token = app('preferences')->getForUser($user, 'email_change_confirm_token', 'invalid'); + $uri = route('profile.confirm-email-change', [$token->data]); try { - Mail::to($newEmail)->send(new ConfirmEmailChangeMail($newEmail, $oldEmail, $uri, $ipAddress)); + Mail::to($newEmail)->send(new ConfirmEmailChangeMail($newEmail, $oldEmail, $uri)); } catch (Exception $e) { // @phpstan-ignore-line Log::error($e->getMessage()); @@ -252,15 +251,14 @@ class UserEventHandler */ public function sendEmailChangeUndoMail(UserChangedEmail $event): bool { - $newEmail = $event->newEmail; - $oldEmail = $event->oldEmail; - $user = $event->user; - $ipAddress = $event->ipAddress; - $token = app('preferences')->getForUser($user, 'email_change_undo_token', 'invalid'); - $hashed = hash('sha256', sprintf('%s%s', (string)config('app.key'), $oldEmail)); - $uri = route('profile.undo-email-change', [$token->data, $hashed]); + $newEmail = $event->newEmail; + $oldEmail = $event->oldEmail; + $user = $event->user; + $token = app('preferences')->getForUser($user, 'email_change_undo_token', 'invalid'); + $hashed = hash('sha256', sprintf('%s%s', (string) config('app.key'), $oldEmail)); + $uri = route('profile.undo-email-change', [$token->data, $hashed]); try { - Mail::to($oldEmail)->send(new UndoEmailChangeMail($newEmail, $oldEmail, $uri, $ipAddress)); + Mail::to($oldEmail)->send(new UndoEmailChangeMail($newEmail, $oldEmail, $uri)); } catch (Exception $e) { // @phpstan-ignore-line Log::error($e->getMessage()); @@ -334,11 +332,11 @@ class UserEventHandler /** * @param ActuallyLoggedIn $event + * @throws FireflyException */ public function storeUserIPAddress(ActuallyLoggedIn $event): void { Log::debug('Now in storeUserIPAddress'); - /** @var User $user */ $user = $event->user; /** @var array $preference */ try { diff --git a/app/Handlers/Events/VersionCheckEventHandler.php b/app/Handlers/Events/VersionCheckEventHandler.php index f3295ae8bd..6485f1d042 100644 --- a/app/Handlers/Events/VersionCheckEventHandler.php +++ b/app/Handlers/Events/VersionCheckEventHandler.php @@ -44,6 +44,8 @@ class VersionCheckEventHandler * @param RequestedVersionCheckStatus $event * * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function checkForUpdates(RequestedVersionCheckStatus $event): void { @@ -51,7 +53,7 @@ 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.'); $this->warnToCheckForUpdates($event); @@ -90,6 +92,8 @@ class VersionCheckEventHandler * @param RequestedVersionCheckStatus $event * * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ protected function warnToCheckForUpdates(RequestedVersionCheckStatus $event): void { @@ -115,7 +119,7 @@ class VersionCheckEventHandler // last check time was more than a week ago. Log::debug('Have warned about a new version in four weeks!'); - session()->flash('info', (string)trans('firefly.disabled_but_check')); + session()->flash('info', (string) trans('firefly.disabled_but_check')); app('fireflyconfig')->set('last_update_warning', time()); } } diff --git a/app/Helpers/Attachments/AttachmentHelper.php b/app/Helpers/Attachments/AttachmentHelper.php index eb8b861b8a..42a2001d22 100644 --- a/app/Helpers/Attachments/AttachmentHelper.php +++ b/app/Helpers/Attachments/AttachmentHelper.php @@ -28,7 +28,6 @@ use FireflyIII\Models\Attachment; use FireflyIII\Models\PiggyBank; 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; @@ -58,8 +57,8 @@ class AttachmentHelper implements AttachmentHelperInterface */ 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; @@ -77,15 +76,10 @@ class AttachmentHelper implements AttachmentHelperInterface */ public function getAttachmentContent(Attachment $attachment): string { - $encryptedData = ''; - try { - $encryptedData = $this->uploadDisk->get(sprintf('at-%d.data', $attachment->id)); - } catch (FileNotFoundException $e) { - Log::error($e->getMessage()); - } + $encryptedData = (string) $this->uploadDisk->get(sprintf('at-%d.data', $attachment->id)); try { $unencryptedData = Crypt::decrypt($encryptedData); // verified - } catch (DecryptException | FileNotFoundException $e) { + } catch (DecryptException $e) { Log::error(sprintf('Could not decrypt data of attachment #%d: %s', $attachment->id, $e->getMessage())); $unencryptedData = $encryptedData; } @@ -103,7 +97,7 @@ class AttachmentHelper implements AttachmentHelperInterface */ 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); } /** @@ -273,7 +267,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); } @@ -330,7 +324,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); @@ -355,7 +349,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); @@ -387,7 +381,7 @@ class AttachmentHelper implements AttachmentHelperInterface } $result = false; if ($count > 0) { - $msg = (string)trans('validation.file_already_attached', ['name' => $name]); + $msg = (string) trans('validation.file_already_attached', ['name' => $name]); $this->errors->add('attachments', $msg); Log::error($msg); $result = true; diff --git a/app/Helpers/Collector/Extensions/AccountCollection.php b/app/Helpers/Collector/Extensions/AccountCollection.php index 762c47c7a4..41f3aa35b7 100644 --- a/app/Helpers/Collector/Extensions/AccountCollection.php +++ b/app/Helpers/Collector/Extensions/AccountCollection.php @@ -216,9 +216,9 @@ trait AccountCollection $this->query->leftJoin('account_types as dest_account_type', 'dest_account_type.id', '=', 'dest_account.account_type_id'); // and add fields: - $this->fields[] = 'dest_account.name as destination_account_name'; - $this->fields[] = 'dest_account.iban as destination_account_iban'; - $this->fields[] = 'dest_account_type.type as destination_account_type'; + $this->fields[] = 'dest_account.name as destination_account_name'; + $this->fields[] = 'dest_account.iban as destination_account_iban'; + $this->fields[] = 'dest_account_type.type as destination_account_type'; $this->hasAccountInfo = true; } diff --git a/app/Helpers/Collector/Extensions/AmountCollection.php b/app/Helpers/Collector/Extensions/AmountCollection.php index 972b7e9342..99fe7d1742 100644 --- a/app/Helpers/Collector/Extensions/AmountCollection.php +++ b/app/Helpers/Collector/Extensions/AmountCollection.php @@ -86,4 +86,61 @@ trait AmountCollection return $this; } + + /** + * Get transactions with a specific foreign amount. + * + * @param string $amount + * + * @return GroupCollectorInterface + */ + public function foreignAmountIs(string $amount): GroupCollectorInterface + { + $this->query->where( + static function (EloquentBuilder $q) use ($amount) { + $q->whereNotNull('source.foreign_amount'); + $q->where('source.foreign_amount', app('steam')->negative($amount)); + } + ); + + return $this; + } + + /** + * Get transactions where the amount is less than. + * + * @param string $amount + * + * @return GroupCollectorInterface + */ + public function foreignAmountLess(string $amount): GroupCollectorInterface + { + $this->query->where( + function (EloquentBuilder $q) use ($amount) { + $q->whereNotNull('destination.foreign_amount'); + $q->where('destination.foreign_amount', '<=', app('steam')->positive($amount)); + } + ); + + return $this; + } + + /** + * Get transactions where the amount is more than. + * + * @param string $amount + * + * @return GroupCollectorInterface + */ + public function foreignAmountMore(string $amount): GroupCollectorInterface + { + $this->query->where( + function (EloquentBuilder $q) use ($amount) { + $q->whereNotNull('destination.foreign_amount'); + $q->where('destination.foreign_amount', '>=', app('steam')->positive($amount)); + } + ); + + return $this; + } } diff --git a/app/Helpers/Collector/Extensions/AttachmentCollection.php b/app/Helpers/Collector/Extensions/AttachmentCollection.php new file mode 100644 index 0000000000..6479bc01a3 --- /dev/null +++ b/app/Helpers/Collector/Extensions/AttachmentCollection.php @@ -0,0 +1,306 @@ +. + */ + +declare(strict_types=1); + +namespace FireflyIII\Helpers\Collector\Extensions; + +use FireflyIII\Helpers\Collector\GroupCollectorInterface; +use FireflyIII\Models\Attachment; +use FireflyIII\Models\TransactionJournal; +use Illuminate\Database\Eloquent\Builder as EloquentBuilder; +use Log; + +/** + * Trait AttachmentCollection + */ +trait AttachmentCollection +{ + /** + * @param string $name + * @return GroupCollectorInterface + */ + public function attachmentNameContains(string $name): GroupCollectorInterface + { + $this->hasAttachments(); + $this->withAttachmentInformation(); + $filter = function (int $index, array $object) use ($name): bool { + /** @var array $transaction */ + foreach ($object['transactions'] as $transaction) { + /** @var array $attachment */ + foreach ($transaction['attachments'] as $attachment) { + $result = str_contains(strtolower($attachment['filename']), strtolower($name)) || str_contains(strtolower($attachment['title']), strtolower($name)); + if (true === $result) { + return true; + } + } + } + return false; + }; + $this->postFilters[] = $filter; + + return $this; + } + + /** + * Has attachments + * + * @return GroupCollectorInterface + */ + public function hasAttachments(): GroupCollectorInterface + { + Log::debug('Add filter on attachment ID.'); + $this->joinAttachmentTables(); + $this->query->whereNotNull('attachments.attachable_id'); + + return $this; + } + + /** + * Join table to get attachment information. + */ + private function joinAttachmentTables(): void + { + if (false === $this->hasJoinedAttTables) { + // join some extra tables: + $this->hasJoinedAttTables = true; + $this->query->leftJoin('attachments', 'attachments.attachable_id', '=', 'transaction_journals.id') + ->where( + static function (EloquentBuilder $q1) { + $q1->where('attachments.attachable_type', TransactionJournal::class); + //$q1->where('attachments.uploaded', true); + $q1->orWhereNull('attachments.attachable_type'); + } + ); + } + } + + /** + * @inheritDoc + */ + public function withAttachmentInformation(): GroupCollectorInterface + { + $this->fields[] = 'attachments.id as attachment_id'; + $this->fields[] = 'attachments.filename as attachment_filename'; + $this->fields[] = 'attachments.title as attachment_title'; + $this->fields[] = 'attachments.uploaded as attachment_uploaded'; + $this->joinAttachmentTables(); + + return $this; + } + + /** + * @param string $name + * @return GroupCollectorInterface + */ + public function attachmentNameEnds(string $name): GroupCollectorInterface + { + $this->hasAttachments(); + $this->withAttachmentInformation(); + $filter = function (int $index, array $object) use ($name): bool { + /** @var array $transaction */ + foreach ($object['transactions'] as $transaction) { + /** @var array $attachment */ + foreach ($transaction['attachments'] as $attachment) { + $result = str_ends_with(strtolower($attachment['filename']), strtolower($name)) || str_ends_with(strtolower($attachment['title']), strtolower($name)); + if (true === $result) { + return true; + } + } + } + return false; + }; + $this->postFilters[] = $filter; + + return $this; + } + + /** + * @param string $name + * @return GroupCollectorInterface + */ + public function attachmentNameIs(string $name): GroupCollectorInterface + { + $this->hasAttachments(); + $this->withAttachmentInformation(); + $filter = function (int $index, array $object) use ($name): bool { + /** @var array $transaction */ + foreach ($object['transactions'] as $transaction) { + /** @var array $attachment */ + foreach ($transaction['attachments'] as $attachment) { + $result = $attachment['filename'] === $name || $attachment['title'] === $name; + if (true === $result) { + return true; + } + } + } + return false; + }; + $this->postFilters[] = $filter; + + return $this; + } + + /** + * @param string $name + * @return GroupCollectorInterface + */ + public function attachmentNameStarts(string $name): GroupCollectorInterface + { + $this->hasAttachments(); + $this->withAttachmentInformation(); + $filter = function (int $index, array $object) use ($name): bool { + /** @var array $transaction */ + foreach ($object['transactions'] as $transaction) { + /** @var array $attachment */ + foreach ($transaction['attachments'] as $attachment) { + $result = str_starts_with(strtolower($attachment['filename']), strtolower($name)) || str_starts_with(strtolower($attachment['title']), strtolower($name)); + if (true === $result) { + return true; + } + } + } + return false; + }; + $this->postFilters[] = $filter; + + return $this; + } + + /** + * @param string $value + * @return GroupCollectorInterface + */ + public function attachmentNotesAre(string $value): GroupCollectorInterface + { + $this->hasAttachments(); + $this->withAttachmentInformation(); + $filter = function (int $index, array $object) use ($value): bool { + /** @var array $transaction */ + foreach ($object['transactions'] as $transaction) { + /** @var array $attachment */ + foreach ($transaction['attachments'] as $attachment) { + /** @var Attachment $object */ + $object = auth()->user()->attachments()->find($attachment['id']); + $notes = (string) $object->notes()?->first()?->text; + return $notes !== '' && $notes === $value; + } + } + return false; + }; + $this->postFilters[] = $filter; + + return $this; + } + + /** + * @param string $value + * @return GroupCollectorInterface + */ + public function attachmentNotesContains(string $value): GroupCollectorInterface + { + $this->hasAttachments(); + $this->withAttachmentInformation(); + $filter = function (int $index, array $object) use ($value): bool { + /** @var array $transaction */ + foreach ($object['transactions'] as $transaction) { + /** @var array $attachment */ + foreach ($transaction['attachments'] as $attachment) { + /** @var Attachment $object */ + $object = auth()->user()->attachments()->find($attachment['id']); + $notes = (string) $object->notes()?->first()?->text; + return $notes !== '' && str_contains(strtolower($notes), strtolower($value)); + } + } + return false; + }; + $this->postFilters[] = $filter; + + return $this; + } + + /** + * @param string $value + * @return GroupCollectorInterface + */ + public function attachmentNotesEnds(string $value): GroupCollectorInterface + { + $this->hasAttachments(); + $this->withAttachmentInformation(); + $filter = function (int $index, array $object) use ($value): bool { + /** @var array $transaction */ + foreach ($object['transactions'] as $transaction) { + /** @var array $attachment */ + foreach ($transaction['attachments'] as $attachment) { + /** @var Attachment $object */ + $object = auth()->user()->attachments()->find($attachment['id']); + $notes = (string) $object->notes()?->first()?->text; + return $notes !== '' && str_ends_with(strtolower($notes), strtolower($value)); + } + } + return false; + }; + $this->postFilters[] = $filter; + + return $this; + } + + /** + * @param string $value + * @return GroupCollectorInterface + */ + public function attachmentNotesStarts(string $value): GroupCollectorInterface + { + $this->hasAttachments(); + $this->withAttachmentInformation(); + $filter = function (int $index, array $object) use ($value): bool { + /** @var array $transaction */ + foreach ($object['transactions'] as $transaction) { + /** @var array $attachment */ + foreach ($transaction['attachments'] as $attachment) { + /** @var Attachment $object */ + $object = auth()->user()->attachments()->find($attachment['id']); + $notes = (string) $object->notes()?->first()?->text; + return $notes !== '' && str_starts_with(strtolower($notes), strtolower($value)); + } + } + return false; + }; + $this->postFilters[] = $filter; + + return $this; + } + + /** + * Has attachments + * + * @return GroupCollectorInterface + */ + public function hasNoAttachments(): GroupCollectorInterface + { + Log::debug('Add filter on no attachments.'); + $this->joinAttachmentTables(); + $this->query->whereNull('attachments.attachable_id'); + + return $this; + } +} diff --git a/app/Helpers/Collector/Extensions/CollectorProperties.php b/app/Helpers/Collector/Extensions/CollectorProperties.php index c3bf6a3396..544478e881 100644 --- a/app/Helpers/Collector/Extensions/CollectorProperties.php +++ b/app/Helpers/Collector/Extensions/CollectorProperties.php @@ -32,33 +32,20 @@ use Illuminate\Database\Eloquent\Relations\HasMany; */ trait CollectorProperties { - /** @var array The standard fields to select. */ - private $fields; - /** @var bool Will be set to true if query result contains account information. (see function withAccountInformation). */ - private $hasAccountInfo; - /** @var bool Will be true if query result includes bill information. */ - private $hasBillInformation; - /** @var bool Will be true if query result contains budget info. */ - private $hasBudgetInformation; - /** @var bool Will be true if query result contains category info. */ - private $hasCatInformation; - /** @var bool Will be true for attachments */ - private $hasJoinedAttTables; - private bool $hasJoinedMetaTables; - /** @var bool Will be true of the query has the tag info tables joined. */ - private $hasJoinedTagTables; - /** @var bool */ - private $hasNotesInformation; - /** @var array */ - private $integerFields; - /** @var int The maximum number of results. */ - private $limit; - /** @var int The page to return. */ - private $page; - /** @var HasMany The query object. */ - private $query; - /** @var int Total number of results. */ - private $total; - /** @var User The user object. */ - private $user; + private array $fields; + private bool $hasAccountInfo; + private bool $hasBillInformation; + private bool $hasBudgetInformation; + private bool $hasCatInformation; + private bool $hasJoinedAttTables; + private bool $hasJoinedMetaTables; + private bool $hasJoinedTagTables; + private bool $hasNotesInformation; + private array $integerFields; + private ?int $limit; + private ?int $page; + private array $postFilters; + private HasMany $query; + private int $total; + private ?User $user; } diff --git a/app/Helpers/Collector/Extensions/MetaCollection.php b/app/Helpers/Collector/Extensions/MetaCollection.php index ff967fd6e6..dadb4067f7 100644 --- a/app/Helpers/Collector/Extensions/MetaCollection.php +++ b/app/Helpers/Collector/Extensions/MetaCollection.php @@ -38,6 +38,101 @@ use Illuminate\Support\Collection; */ trait MetaCollection { + /** + * @inheritDoc + */ + public function externalIdContains(string $externalId): GroupCollectorInterface + { + $this->joinMetaDataTables(); + $this->query->where('journal_meta.name', '=', 'external_id'); + $this->query->where('journal_meta.data', 'LIKE', sprintf('%%%s%%', $externalId)); + + return $this; + } + + /** + * Join table to get tag information. + */ + protected function joinMetaDataTables(): void + { + if (false === $this->hasJoinedMetaTables) { + $this->hasJoinedMetaTables = true; + $this->query->leftJoin('journal_meta', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id'); + $this->fields[] = 'journal_meta.name as meta_name'; + $this->fields[] = 'journal_meta.data as meta_data'; + } + } + + /** + * @inheritDoc + */ + public function externalIdEnds(string $externalId): GroupCollectorInterface + { + $this->joinMetaDataTables(); + $this->query->where('journal_meta.name', '=', 'external_id'); + $this->query->where('journal_meta.data', 'LIKE', sprintf('%%%s"', $externalId)); + + return $this; + } + + /** + * @inheritDoc + */ + public function externalIdStarts(string $externalId): GroupCollectorInterface + { + $this->joinMetaDataTables(); + $this->query->where('journal_meta.name', '=', 'external_id'); + $this->query->where('journal_meta.data', 'LIKE', sprintf('"%s%%', $externalId)); + + return $this; + } + + /** + * @param string $url + * @return GroupCollectorInterface + */ + public function externalUrlContains(string $url): GroupCollectorInterface + { + $this->joinMetaDataTables(); + $url = json_encode($url); + $url = str_replace('\\', '\\\\', trim($url, '"')); + $this->query->where('journal_meta.name', '=', 'external_url'); + $this->query->where('journal_meta.data', 'LIKE', sprintf('%%%s%%', $url)); + + return $this; + } + + /** + * @param string $url + * @return GroupCollectorInterface + */ + public function externalUrlEnds(string $url): GroupCollectorInterface + { + $this->joinMetaDataTables(); + $url = json_encode($url); + $url = str_replace('\\', '\\\\', ltrim($url, '"')); + $this->query->where('journal_meta.name', '=', 'external_url'); + $this->query->where('journal_meta.data', 'LIKE', sprintf('%%%s', $url)); + + return $this; + } + + /** + * @param string $url + * @return GroupCollectorInterface + */ + public function externalUrlStarts(string $url): GroupCollectorInterface + { + $this->joinMetaDataTables(); + $url = json_encode($url); + $url = str_replace('\\', '\\\\', rtrim($url, '"')); + //var_dump($url); + + $this->query->where('journal_meta.name', '=', 'external_url'); + $this->query->where('journal_meta.data', 'LIKE', sprintf('%s%%', $url)); + + return $this; + } /** * Where has no tags. @@ -52,6 +147,73 @@ trait MetaCollection return $this; } + /** + * @return GroupCollectorInterface + */ + public function withTagInformation(): GroupCollectorInterface + { + $this->fields[] = 'tags.id as tag_id'; + $this->fields[] = 'tags.tag as tag_name'; + $this->fields[] = 'tags.date as tag_date'; + $this->fields[] = 'tags.description as tag_description'; + $this->fields[] = 'tags.latitude as tag_latitude'; + $this->fields[] = 'tags.longitude as tag_longitude'; + $this->fields[] = 'tags.zoomLevel as tag_zoom_level'; + + $this->joinTagTables(); + + return $this; + } + + /** + * Join table to get tag information. + */ + protected 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'); + } + } + + /** + * @inheritDoc + */ + public function internalReferenceContains(string $externalId): GroupCollectorInterface + { + $this->joinMetaDataTables(); + $this->query->where('journal_meta.name', '=', 'internal_reference'); + $this->query->where('journal_meta.data', 'LIKE', sprintf('%%%s%%', $externalId)); + + return $this; + } + + /** + * @inheritDoc + */ + public function internalReferenceEnds(string $externalId): GroupCollectorInterface + { + $this->joinMetaDataTables(); + $this->query->where('journal_meta.name', '=', 'internal_reference'); + $this->query->where('journal_meta.data', 'LIKE', sprintf('%%%s"', $externalId)); + + return $this; + } + + /** + * @inheritDoc + */ + public function internalReferenceStarts(string $externalId): GroupCollectorInterface + { + $this->joinMetaDataTables(); + $this->query->where('journal_meta.name', '=', 'internal_reference'); + $this->query->where('journal_meta.data', 'LIKE', sprintf('"%s%%', $externalId)); + + return $this; + } + /** * @param string $value * @@ -65,6 +227,29 @@ trait MetaCollection return $this; } + /** + * @inheritDoc + */ + public function withNotes(): GroupCollectorInterface + { + if (false === $this->hasNotesInformation) { + // join bill table + $this->query->leftJoin( + 'notes', + static function (JoinClause $join) { + $join->on('notes.noteable_id', '=', 'transaction_journals.id'); + $join->where('notes.noteable_type', '=', 'FireflyIII\Models\TransactionJournal'); + $join->whereNull('notes.deleted_at'); + } + ); + // add fields + $this->fields[] = 'notes.text as notes'; + $this->hasNotesInformation = true; + } + + return $this; + } + /** * @param string $value * @@ -119,6 +304,25 @@ trait MetaCollection return $this; } + /** + * Will include bill name + ID, if any. + * + * @return GroupCollectorInterface + */ + public function withBillInformation(): GroupCollectorInterface + { + if (false === $this->hasBillInformation) { + // join bill table + $this->query->leftJoin('bills', 'bills.id', '=', 'transaction_journals.bill_id'); + // add fields + $this->fields[] = 'bills.id as bill_id'; + $this->fields[] = 'bills.name as bill_name'; + $this->hasBillInformation = true; + } + + return $this; + } + /** * Limit the search to a specific set of bills. * @@ -149,6 +353,27 @@ trait MetaCollection return $this; } + /** + * Will include budget ID + name, if any. + * + * @return GroupCollectorInterface + */ + public function withBudgetInformation(): GroupCollectorInterface + { + if (false === $this->hasBudgetInformation) { + // join link table + $this->query->leftJoin('budget_transaction_journal', 'budget_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id'); + // join cat table + $this->query->leftJoin('budgets', 'budget_transaction_journal.budget_id', '=', 'budgets.id'); + // add fields + $this->fields[] = 'budgets.id as budget_id'; + $this->fields[] = 'budgets.name as budget_name'; + $this->hasBudgetInformation = true; + } + + return $this; + } + /** * Limit the search to a specific set of budgets. * @@ -183,6 +408,27 @@ trait MetaCollection return $this; } + /** + * Will include category ID + name, if any. + * + * @return GroupCollectorInterface + */ + public function withCategoryInformation(): GroupCollectorInterface + { + if (false === $this->hasCatInformation) { + // join link table + $this->query->leftJoin('category_transaction_journal', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id'); + // join cat table + $this->query->leftJoin('categories', 'category_transaction_journal.category_id', '=', 'categories.id'); + // add fields + $this->fields[] = 'categories.id as category_id'; + $this->fields[] = 'categories.name as category_name'; + $this->hasCatInformation = true; + } + + return $this; + } + /** * Limit the search to a specific category. * @@ -203,10 +449,7 @@ trait MetaCollection */ public function setExternalId(string $externalId): GroupCollectorInterface { - if (false === $this->hasJoinedMetaTables) { - $this->hasJoinedMetaTables = true; - $this->query->leftJoin('journal_meta', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id'); - } + $this->joinMetaDataTables(); $this->query->where('journal_meta.name', '=', 'external_id'); $this->query->where('journal_meta.data', '=', sprintf('%s', json_encode($externalId))); @@ -216,33 +459,11 @@ trait MetaCollection /** * @inheritDoc */ - public function withoutExternalUrl(): GroupCollectorInterface + public function setExternalUrl(string $url): GroupCollectorInterface { - if (false === $this->hasJoinedMetaTables) { - $this->hasJoinedMetaTables = true; - $this->query->leftJoin('journal_meta', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id'); - } - $this->query->where(function (Builder $q1) { - $q1->where(function (Builder $q2) { - $q2->where('journal_meta.name', '=', 'external_url'); - $q2->whereNull('journal_meta.data'); - })->orWhereNull('journal_meta.name'); - }); - - return $this; - } - - /** - * @inheritDoc - */ - public function withExternalUrl(): GroupCollectorInterface - { - if (false === $this->hasJoinedMetaTables) { - $this->hasJoinedMetaTables = true; - $this->query->leftJoin('journal_meta', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id'); - } + $this->joinMetaDataTables(); $this->query->where('journal_meta.name', '=', 'external_url'); - $this->query->whereNotNull('journal_meta.data'); + $this->query->where('journal_meta.data', '=', json_encode($url)); return $this; } @@ -252,10 +473,7 @@ trait MetaCollection */ public function setInternalReference(string $internalReference): GroupCollectorInterface { - if (false === $this->hasJoinedMetaTables) { - $this->hasJoinedMetaTables = true; - $this->query->leftJoin('journal_meta', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id'); - } + $this->joinMetaDataTables(); $this->query->where('journal_meta.name', '=', 'internal_reference'); $this->query->where('journal_meta.data', 'LIKE', sprintf('%%%s%%', $internalReference)); @@ -263,6 +481,18 @@ trait MetaCollection return $this; } + /** + * @inheritDoc + */ + public function setRecurrenceId(string $recurringId): GroupCollectorInterface + { + $this->joinMetaDataTables(); + $this->query->where('journal_meta.name', '=', 'recurrence_id'); + $this->query->where('journal_meta.data', '=', sprintf('%s', json_encode($recurringId))); + + return $this; + } + /** * Limit results to a specific tag. * @@ -293,6 +523,35 @@ trait MetaCollection return $this; } + /** + * Without tags + * + * @param Collection $tags + * + * @return GroupCollectorInterface + */ + public function setWithoutSpecificTags(Collection $tags): GroupCollectorInterface + { + $this->withTagInformation(); + + // this method adds a "postFilter" to the collector. + $list = $tags->pluck('tag')->toArray(); + $filter = function (int $index, array $object) use ($list): bool { + foreach ($object['transactions'] as $transaction) { + foreach ($transaction['tags'] as $tag) { + if (in_array($tag['name'], $list)) { + return false; + } + } + } + return true; + }; + $this->postFilters[] = $filter; + + + return $this; + } + /** * @return GroupCollectorInterface */ @@ -305,7 +564,7 @@ trait MetaCollection } /** - * Limit results to transactions without a bill.. + * Limit results to transactions without a bill. * * @return GroupCollectorInterface */ @@ -317,25 +576,6 @@ trait MetaCollection return $this; } - /** - * Will include bill name + ID, if any. - * - * @return GroupCollectorInterface - */ - public function withBillInformation(): GroupCollectorInterface - { - if (false === $this->hasBillInformation) { - // join bill table - $this->query->leftJoin('bills', 'bills.id', '=', 'transaction_journals.bill_id'); - // add fields - $this->fields[] = 'bills.id as bill_id'; - $this->fields[] = 'bills.name as bill_name'; - $this->hasBillInformation = true; - } - - return $this; - } - /** * Limit results to a transactions without a budget.. * @@ -349,27 +589,6 @@ trait MetaCollection return $this; } - /** - * Will include budget ID + name, if any. - * - * @return GroupCollectorInterface - */ - public function withBudgetInformation(): GroupCollectorInterface - { - if (false === $this->hasBudgetInformation) { - // join link table - $this->query->leftJoin('budget_transaction_journal', 'budget_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id'); - // join cat table - $this->query->leftJoin('budgets', 'budget_transaction_journal.budget_id', '=', 'budgets.id'); - // add fields - $this->fields[] = 'budgets.id as budget_id'; - $this->fields[] = 'budgets.name as budget_name'; - $this->hasBudgetInformation = true; - } - - return $this; - } - /** * Limit results to a transactions without a category. * @@ -383,63 +602,14 @@ trait MetaCollection return $this; } - /** - * Will include category ID + name, if any. - * - * @return GroupCollectorInterface - */ - public function withCategoryInformation(): GroupCollectorInterface - { - if (false === $this->hasCatInformation) { - // join link table - $this->query->leftJoin('category_transaction_journal', 'category_transaction_journal.transaction_journal_id', '=', 'transaction_journals.id'); - // join cat table - $this->query->leftJoin('categories', 'category_transaction_journal.category_id', '=', 'categories.id'); - // add fields - $this->fields[] = 'categories.id as category_id'; - $this->fields[] = 'categories.name as category_name'; - $this->hasCatInformation = true; - } - - return $this; - } - /** * @inheritDoc */ - public function withNotes(): GroupCollectorInterface + public function withExternalUrl(): GroupCollectorInterface { - if (false === $this->hasNotesInformation) { - // join bill table - $this->query->leftJoin( - 'notes', - static function (JoinClause $join) { - $join->on('notes.noteable_id', '=', 'transaction_journals.id'); - $join->where('notes.noteable_type', '=', 'FireflyIII\Models\TransactionJournal'); - } - ); - // add fields - $this->fields[] = 'notes.text as notes'; - $this->hasNotesInformation = true; - } - - return $this; - } - - /** - * @return GroupCollectorInterface - */ - public function withTagInformation(): GroupCollectorInterface - { - $this->fields[] = 'tags.id as tag_id'; - $this->fields[] = 'tags.tag as tag_name'; - $this->fields[] = 'tags.date as tag_date'; - $this->fields[] = 'tags.description as tag_description'; - $this->fields[] = 'tags.latitude as tag_latitude'; - $this->fields[] = 'tags.longitude as tag_longitude'; - $this->fields[] = 'tags.zoomLevel as tag_zoom_level'; - - $this->joinTagTables(); + $this->joinMetaDataTables(); + $this->query->where('journal_meta.name', '=', 'external_url'); + $this->query->whereNotNull('journal_meta.data'); return $this; } @@ -482,6 +652,27 @@ trait MetaCollection return $this; } + /** + * @inheritDoc + */ + public function withoutExternalUrl(): GroupCollectorInterface + { + $this->joinMetaDataTables(); + // TODO not sure if this will work properly. + $this->query->where(function (Builder $q1) { + $q1->where(function (Builder $q2) { + $q2->where('journal_meta.name', '=', 'external_url'); + $q2->whereNull('journal_meta.data'); + })->orWhere(function (Builder $q3) { + $q3->where('journal_meta.name', '!=', 'external_url'); + })->orWhere(function (Builder $q4) { + $q4->whereNull('journal_meta.name'); + }); + }); + + return $this; + } + /** * @return GroupCollectorInterface */ @@ -508,17 +699,4 @@ trait MetaCollection return $this; } - - /** - * Join table to get tag information. - */ - protected 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'); - } - } } diff --git a/app/Helpers/Collector/Extensions/TimeCollection.php b/app/Helpers/Collector/Extensions/TimeCollection.php index 938fc29315..bcedb18ae9 100644 --- a/app/Helpers/Collector/Extensions/TimeCollection.php +++ b/app/Helpers/Collector/Extensions/TimeCollection.php @@ -32,6 +32,383 @@ use FireflyIII\Helpers\Collector\GroupCollectorInterface; */ trait TimeCollection { + /** + * @param string $day + * @return GroupCollectorInterface + */ + public function dayAfter(string $day): GroupCollectorInterface + { + $this->query->whereDay('transaction_journals.date', '>=', $day); + return $this; + } + + /** + * @param string $day + * @return GroupCollectorInterface + */ + public function dayBefore(string $day): GroupCollectorInterface + { + $this->query->whereDay('transaction_journals.date', '<=', $day); + return $this; + } + + /** + * @param string $day + * @return GroupCollectorInterface + */ + public function dayIs(string $day): GroupCollectorInterface + { + $this->query->whereDay('transaction_journals.date', '=', $day); + return $this; + } + + /** + * @param string $day + * @param string $field + * @return GroupCollectorInterface + */ + public function metaDayAfter(string $day, string $field): GroupCollectorInterface + { + $this->withMetaDate($field); + $filter = function (int $index, array $object) use ($field, $day): bool { + foreach ($object['transactions'] as $transaction) { + if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon + ) { + return $transaction[$field]->day >= (int) $day; + } + } + + return true; + }; + $this->postFilters[] = $filter; + + return $this; + } + + /** + * @inheritDoc + */ + public function withMetaDate(string $field): GroupCollectorInterface + { + $this->joinMetaDataTables(); + $this->query->where('journal_meta.name', '=', $field); + $this->query->whereNotNull('journal_meta.data'); + + return $this; + } + + /** + * @param string $day + * @param string $field + * @return GroupCollectorInterface + */ + public function metaDayBefore(string $day, string $field): GroupCollectorInterface + { + $this->withMetaDate($field); + $filter = function (int $index, array $object) use ($field, $day): bool { + foreach ($object['transactions'] as $transaction) { + if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon + ) { + return $transaction[$field]->day <= (int) $day; + } + } + + return true; + }; + $this->postFilters[] = $filter; + + return $this; + } + + /** + * @param string $day + * @param string $field + * @return GroupCollectorInterface + */ + public function metaDayIs(string $day, string $field): GroupCollectorInterface + { + $this->withMetaDate($field); + $filter = function (int $index, array $object) use ($field, $day): bool { + foreach ($object['transactions'] as $transaction) { + if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon + ) { + return (int) $day === $transaction[$field]->day; + } + } + + return false; + }; + $this->postFilters[] = $filter; + return $this; + } + + /** + * @param string $month + * @param string $field + * @return GroupCollectorInterface + */ + public function metaMonthAfter(string $month, string $field): GroupCollectorInterface + { + $this->withMetaDate($field); + $filter = function (int $index, array $object) use ($field, $month): bool { + foreach ($object['transactions'] as $transaction) { + if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon + ) { + return $transaction[$field]->month >= (int) $month; + } + } + + return true; + }; + $this->postFilters[] = $filter; + + return $this; + } + + /** + * @param string $month + * @param string $field + * @return GroupCollectorInterface + */ + public function metaMonthBefore(string $month, string $field): GroupCollectorInterface + { + $this->withMetaDate($field); + $filter = function (int $index, array $object) use ($field, $month): bool { + foreach ($object['transactions'] as $transaction) { + if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon + ) { + return $transaction[$field]->month <= (int) $month; + } + } + + return true; + }; + $this->postFilters[] = $filter; + + return $this; + } + + /** + * @param string $month + * @param string $field + * @return GroupCollectorInterface + */ + public function metaMonthIs(string $month, string $field): GroupCollectorInterface + { + $this->withMetaDate($field); + $filter = function (int $index, array $object) use ($field, $month): bool { + foreach ($object['transactions'] as $transaction) { + if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon + ) { + return (int) $month === $transaction[$field]->month; + } + } + + return false; + }; + $this->postFilters[] = $filter; + return $this; + } + + /** + * @param string $year + * @param string $field + * @return GroupCollectorInterface + */ + public function metaYearAfter(string $year, string $field): GroupCollectorInterface + { + $this->withMetaDate($field); + $filter = function (int $index, array $object) use ($field, $year): bool { + foreach ($object['transactions'] as $transaction) { + if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon + ) { + return $transaction[$field]->year >= (int) $year; + } + } + + return true; + }; + $this->postFilters[] = $filter; + + return $this; + } + + /** + * @param string $year + * @param string $field + * @return GroupCollectorInterface + */ + public function metaYearBefore(string $year, string $field): GroupCollectorInterface + { + $this->withMetaDate($field); + $filter = function (int $index, array $object) use ($field, $year): bool { + foreach ($object['transactions'] as $transaction) { + if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon + ) { + return $transaction[$field]->year <= (int) $year; + } + } + + return true; + }; + $this->postFilters[] = $filter; + + return $this; + } + + /** + * @param string $year + * @param string $field + * @return GroupCollectorInterface + */ + public function metaYearIs(string $year, string $field): GroupCollectorInterface + { + $this->withMetaDate($field); + $filter = function (int $index, array $object) use ($field, $year): bool { + foreach ($object['transactions'] as $transaction) { + if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon + ) { + return $year === (string) $transaction[$field]->year; + } + } + + return true; + }; + $this->postFilters[] = $filter; + + return $this; + } + + /** + * @param string $month + * @return GroupCollectorInterface + */ + public function monthAfter(string $month): GroupCollectorInterface + { + $this->query->whereMonth('transaction_journals.date', '>=', $month); + return $this; + + } + + /** + * @param string $month + * @return GroupCollectorInterface + */ + public function monthBefore(string $month): GroupCollectorInterface + { + $this->query->whereMonth('transaction_journals.date', '<=', $month); + return $this; + + } + + /** + * @param string $month + * @return GroupCollectorInterface + */ + public function monthIs(string $month): GroupCollectorInterface + { + $this->query->whereMonth('transaction_journals.date', '=', $month); + return $this; + } + + /** + * @param string $day + * @param string $field + * @return GroupCollectorInterface + */ + public function objectDayAfter(string $day, string $field): GroupCollectorInterface + { + $this->query->whereDay(sprintf('transaction_journals.%s', $field), '>=', $day); + return $this; + } + + /** + * @param string $day + * @param string $field + * @return GroupCollectorInterface + */ + public function objectDayBefore(string $day, string $field): GroupCollectorInterface + { + $this->query->whereDay(sprintf('transaction_journals.%s', $field), '<=', $day); + return $this; + } + + /** + * @param string $day + * @param string $field + * @return GroupCollectorInterface + */ + public function objectDayIs(string $day, string $field): GroupCollectorInterface + { + $this->query->whereDay(sprintf('transaction_journals.%s', $field), '=', $day); + return $this; + } + + /** + * @param string $month + * @param string $field + * @return GroupCollectorInterface + */ + public function objectMonthAfter(string $month, string $field): GroupCollectorInterface + { + $this->query->whereMonth(sprintf('transaction_journals.%s', $field), '>=', $month); + return $this; + } + + /** + * @param string $month + * @param string $field + * @return GroupCollectorInterface + */ + public function objectMonthBefore(string $month, string $field): GroupCollectorInterface + { + $this->query->whereMonth(sprintf('transaction_journals.%s', $field), '<=', $month); + return $this; + } + + /** + * @param string $month + * @param string $field + * @return GroupCollectorInterface + */ + public function objectMonthIs(string $month, string $field): GroupCollectorInterface + { + $this->query->whereMonth(sprintf('transaction_journals.%s', $field), '=', $month); + return $this; + } + + /** + * @param string $year + * @param string $field + * @return GroupCollectorInterface + */ + public function objectYearAfter(string $year, string $field): GroupCollectorInterface + { + $this->query->whereYear(sprintf('transaction_journals.%s', $field), '>=', $year); + return $this; + } + + /** + * @param string $year + * @param string $field + * @return GroupCollectorInterface + */ + public function objectYearBefore(string $year, string $field): GroupCollectorInterface + { + $this->query->whereYear(sprintf('transaction_journals.%s', $field), '<=', $year); + return $this; + } + + /** + * @param string $year + * @param string $field + * @return GroupCollectorInterface + */ + public function objectYearIs(string $year, string $field): GroupCollectorInterface + { + $this->query->whereYear(sprintf('transaction_journals.%s', $field), '=', $year); + return $this; + } /** * Collect transactions after a specific date. @@ -80,6 +457,123 @@ trait TimeCollection return $this; } + /** + * @param Carbon $date + * @param string $field + * @return GroupCollectorInterface + */ + public function setMetaAfter(Carbon $date, string $field): GroupCollectorInterface + { + $this->withMetaDate($field); + $date->startOfDay(); + $filter = function (int $index, array $object) use ($field, $date): bool { + foreach ($object['transactions'] as $transaction) { + if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon + ) { + return $transaction[$field]->gte($date); + } + } + + return true; + }; + $this->postFilters[] = $filter; + + return $this; + } + + /** + * @param Carbon $date + * @param string $field + * @return GroupCollectorInterface + */ + public function setMetaBefore(Carbon $date, string $field): GroupCollectorInterface + { + $this->withMetaDate($field); + $filter = function (int $index, array $object) use ($field, $date): bool { + foreach ($object['transactions'] as $transaction) { + if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon + ) { + return $transaction[$field]->lte($date); + } + } + + return true; + }; + $this->postFilters[] = $filter; + + return $this; + } + + /** + * @param Carbon $start + * @param Carbon $end + * @param string $field + * @return GroupCollectorInterface + */ + public function setMetaDateRange(Carbon $start, Carbon $end, string $field): GroupCollectorInterface + { + if ($end < $start) { + [$start, $end] = [$end, $start]; + } + $end = clone $end; // this is so weird, but it works if $end and $start secretly point to the same object. + $end->endOfDay(); + $start->startOfDay(); + $this->withMetaDate($field); + + $filter = function (int $index, array $object) use ($field, $start, $end): bool { + foreach ($object['transactions'] as $transaction) { + if (array_key_exists($field, $transaction) && $transaction[$field] instanceof Carbon + ) { + return $transaction[$field]->gte($start) && $transaction[$field]->lte($end); + } + } + + return false; + }; + $this->postFilters[] = $filter; + return $this; + + } + + /** + * @param Carbon $date + * @param string $field + * @return GroupCollectorInterface + */ + public function setObjectAfter(Carbon $date, string $field): GroupCollectorInterface + { + $afterStr = $date->format('Y-m-d 00:00:00'); + $this->query->where(sprintf('transaction_journals.%s', $field), '>=', $afterStr); + + return $this; + } + + /** + * @param Carbon $date + * @param string $field + * @return GroupCollectorInterface + */ + public function setObjectBefore(Carbon $date, string $field): GroupCollectorInterface + { + die('a'); + } + + /** + * @param Carbon $start + * @param Carbon $end + * @param string $field + * @return GroupCollectorInterface + */ + public function setObjectRange(Carbon $start, Carbon $end, string $field): GroupCollectorInterface + { + $after = $start->format('Y-m-d 00:00:00'); + $before = $end->format('Y-m-d 23:59:59'); + $this->query->where(sprintf('transaction_journals.%s', $field), '>=', $after); + $this->query->where(sprintf('transaction_journals.%s', $field), '<=', $before); + + return $this; + } + /** * Set the start and end time of the results to return. * @@ -120,22 +614,9 @@ trait TimeCollection return $this; } - public function yearIs(string $year): GroupCollectorInterface + public function yearAfter(string $year): GroupCollectorInterface { - $this->query->whereYear('transaction_journals.date', '=', $year); - return $this; - } - - public function monthIs(string $month): GroupCollectorInterface - { - $this->query->whereMonth('transaction_journals.date', '=', $month); - return $this; - - } - - public function dayIs(string $day): GroupCollectorInterface - { - $this->query->whereDay('transaction_journals.date', '=', $day); + $this->query->whereYear('transaction_journals.date', '>=', $year); return $this; } @@ -145,35 +626,10 @@ trait TimeCollection return $this; } - public function monthBefore(string $month): GroupCollectorInterface + public function yearIs(string $year): GroupCollectorInterface { - $this->query->whereMonth('transaction_journals.date', '<=', $month); - return $this; - - } - - public function dayBefore(string $day): GroupCollectorInterface - { - $this->query->whereDay('transaction_journals.date', '<=', $day); + $this->query->whereYear('transaction_journals.date', '=', $year); return $this; } - public function yearAfter(string $year): GroupCollectorInterface - { - $this->query->whereYear('transaction_journals.date', '>=', $year); - return $this; - } - - public function monthAfter(string $month): GroupCollectorInterface - { - $this->query->whereMonth('transaction_journals.date', '>=', $month); - return $this; - - } - - public function dayAfter(string $day): GroupCollectorInterface - { - $this->query->whereDay('transaction_journals.date', '>=', $day); - return $this; - } } diff --git a/app/Helpers/Collector/GroupCollector.php b/app/Helpers/Collector/GroupCollector.php index 5e252fcbe5..060da5eee1 100644 --- a/app/Helpers/Collector/GroupCollector.php +++ b/app/Helpers/Collector/GroupCollector.php @@ -25,9 +25,11 @@ namespace FireflyIII\Helpers\Collector; use Carbon\Carbon; use Carbon\Exceptions\InvalidDateException; +use Closure; use Exception; use FireflyIII\Helpers\Collector\Extensions\AccountCollection; use FireflyIII\Helpers\Collector\Extensions\AmountCollection; +use FireflyIII\Helpers\Collector\Extensions\AttachmentCollection; use FireflyIII\Helpers\Collector\Extensions\CollectorProperties; use FireflyIII\Helpers\Collector\Extensions\MetaCollection; use FireflyIII\Helpers\Collector\Extensions\TimeCollection; @@ -48,13 +50,18 @@ use Log; */ class GroupCollector implements GroupCollectorInterface { - use CollectorProperties, AccountCollection, AmountCollection, TimeCollection, MetaCollection; + use CollectorProperties, AccountCollection, AmountCollection, TimeCollection, MetaCollection, AttachmentCollection; /** * Group collector constructor. */ public function __construct() { + $this->postFilters = []; + $this->user = null; + $this->limit = null; + $this->page = null; + $this->hasAccountInfo = false; $this->hasCatInformation = false; $this->hasBudgetInformation = false; @@ -198,6 +205,26 @@ class GroupCollector implements GroupCollectorInterface return $this; } + /** + * + */ + public function dumpQuery(): void + { + echo $this->query->select($this->fields)->toSql(); + echo '
';
+        print_r($this->query->getBindings());
+        echo '
'; + } + + /** + * + */ + public function dumpQueryInLogs(): void + { + Log::debug($this->query->select($this->fields)->toSql()); + Log::debug('Bindings', $this->query->getBindings()); + } + /** * @inheritDoc */ @@ -240,7 +267,12 @@ class GroupCollector implements GroupCollectorInterface $result = $this->query->get($this->fields); // now to parse this into an array. - $collection = $this->parseArray($result); + $collection = $this->parseArray($result); + + // filter the array using all available post filters: + $collection = $this->postFilterCollection($collection); + + // count it and continue: $this->total = $collection->count(); // now filter the array according to the page and the limit (if necessary) @@ -253,6 +285,285 @@ class GroupCollector implements GroupCollectorInterface return $collection; } + /** + * @param Collection $collection + * + * @return Collection + */ + private function parseArray(Collection $collection): Collection + { + $groups = []; + /** @var TransactionJournal $augumentedJournal */ + foreach ($collection as $augumentedJournal) { + $groupId = $augumentedJournal->transaction_group_id; + + if (!array_key_exists($groupId, $groups)) { + // make new array + $parsedGroup = $this->parseAugmentedJournal($augumentedJournal); + $groupArray = [ + 'id' => (int) $augumentedJournal->transaction_group_id, + 'user_id' => (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; + $groupArray['transactions'][$journalId] = $parsedGroup; + $groups[$groupId] = $groupArray; + continue; + } + // or parse the rest. + $journalId = (int) $augumentedJournal->transaction_journal_id; + if (array_key_exists($journalId, $groups[$groupId]['transactions'])) { + // append data to existing group + journal (for multiple tags or multiple attachments) + $groups[$groupId]['transactions'][$journalId] = $this->mergeTags($groups[$groupId]['transactions'][$journalId], $augumentedJournal); + $groups[$groupId]['transactions'][$journalId] = $this->mergeAttachments($groups[$groupId]['transactions'][$journalId], $augumentedJournal); + } + + if (!array_key_exists($journalId, $groups[$groupId]['transactions'])) { + // create second, third, fourth split: + $groups[$groupId]['count']++; + $groups[$groupId]['transactions'][$journalId] = $this->parseAugmentedJournal($augumentedJournal); + } + } + + $groups = $this->parseSums($groups); + + return new Collection($groups); + } + + /** + * @param TransactionJournal $augumentedJournal + * + * @return array + */ + private function parseAugmentedJournal(TransactionJournal $augumentedJournal): array + { + $result = $augumentedJournal->toArray(); + $result['tags'] = []; + $result['attachments'] = []; + $result['interest_date'] = null; + $result['payment_date'] = null; + $result['invoice_date'] = null; + $result['book_date'] = null; + $result['due_date'] = null; + $result['process_date'] = null; + try { + $result['date'] = new Carbon($result['date'], 'UTC'); + $result['created_at'] = new Carbon($result['created_at'], 'UTC'); + $result['updated_at'] = new Carbon($result['updated_at'], 'UTC'); + + // this is going to happen a lot: + $result['date']->setTimezone(config('app.timezone')); + $result['created_at']->setTimezone(config('app.timezone')); + $result['updated_at']->setTimezone(config('app.timezone')); + } catch (Exception $e) { // @phpstan-ignore-line + Log::error($e->getMessage()); + } + + // try to process meta date value (if present) + $dates = ['interest_date', 'payment_date', 'invoice_date', 'book_date', 'due_date', 'process_date']; + if (array_key_exists('meta_name', $result) && in_array($result['meta_name'], $dates, true)) { + $name = $result['meta_name']; + if (array_key_exists('meta_data', $result) && '' !== (string) $result['meta_data']) { + $result[$name] = Carbon::createFromFormat('!Y-m-d', substr(json_decode($result['meta_data']), 0, 10)); + } + } + + // convert values to integers: + $result = $this->convertToInteger($result); + + $result['reconciled'] = 1 === (int) $result['reconciled']; + if (array_key_exists('tag_id', $result) && null !== $result['tag_id']) { // assume the other fields are present as well. + $tagId = (int) $augumentedJournal['tag_id']; + $tagDate = null; + try { + $tagDate = Carbon::parse($augumentedJournal['tag_date']); + } catch (InvalidDateException $e) { + Log::debug(sprintf('Could not parse date: %s', $e->getMessage())); + } + + $result['tags'][$tagId] = [ + 'id' => (int) $result['tag_id'], + 'name' => $result['tag_name'], + 'date' => $tagDate, + 'description' => $result['tag_description'], + ]; + } + + // also merge attachments: + if (array_key_exists('attachment_id', $result)) { + $uploaded = 1 === (int) $result['attachment_uploaded']; + $attachmentId = (int) $augumentedJournal['attachment_id']; + if (0 !== $attachmentId && $uploaded) { + $result['attachments'][$attachmentId] = [ + 'id' => $attachmentId, + 'filename' => $augumentedJournal['attachment_filename'], + 'title' => $augumentedJournal['attachment_title'], + ]; + } + } + // unset various fields: + unset($result['tag_id'], $result['meta_data'], $result['meta_name'], + $result['tag_name'], $result['tag_date'], $result['tag_description'], + $result['tag_latitude'], $result['tag_longitude'], $result['tag_zoom_level'], + $result['attachment_filename'], $result['attachment_id'] + + ); + + return $result; + } + + /** + * Convert a selected set of fields to arrays. + * + * @param array $array + * + * @return array + */ + private function convertToInteger(array $array): array + { + foreach ($this->integerFields as $field) { + $array[$field] = array_key_exists($field, $array) ? (int) $array[$field] : null; + } + + return $array; + } + + /** + * @param array $existingJournal + * @param TransactionJournal $newJournal + * + * @return array + */ + private function mergeTags(array $existingJournal, TransactionJournal $newJournal): array + { + $newArray = $newJournal->toArray(); + if (array_key_exists('tag_id', $newArray)) { // 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 array $existingJournal + * @param TransactionJournal $newJournal + * + * @return array + */ + private function mergeAttachments(array $existingJournal, TransactionJournal $newJournal): array + { + $newArray = $newJournal->toArray(); + if (array_key_exists('attachment_id', $newArray)) { + $attachmentId = (int) $newJournal['attachment_id']; + + $existingJournal['attachments'][$attachmentId] = [ + 'id' => $attachmentId, + ]; + } + + return $existingJournal; + } + + /** + * @param array $groups + * + * @return array + */ + private function parseSums(array $groups): array + { + /** + * @var int $groudId + * @var array $group + */ + foreach ($groups as $groudId => $group) { + /** @var array $transaction */ + foreach ($group['transactions'] as $transaction) { + $currencyId = (int) $transaction['currency_id']; + + // set default: + if (!array_key_exists($currencyId, $groups[$groudId]['sums'])) { + $groups[$groudId]['sums'][$currencyId]['currency_id'] = $currencyId; + $groups[$groudId]['sums'][$currencyId]['currency_code'] = $transaction['currency_code']; + $groups[$groudId]['sums'][$currencyId]['currency_symbol'] = $transaction['currency_symbol']; + $groups[$groudId]['sums'][$currencyId]['currency_decimal_places'] = $transaction['currency_decimal_places']; + $groups[$groudId]['sums'][$currencyId]['amount'] = '0'; + } + $groups[$groudId]['sums'][$currencyId]['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']; + + // set default: + if (!array_key_exists($currencyId, $groups[$groudId]['sums'])) { + $groups[$groudId]['sums'][$currencyId]['currency_id'] = $currencyId; + $groups[$groudId]['sums'][$currencyId]['currency_code'] = $transaction['foreign_currency_code']; + $groups[$groudId]['sums'][$currencyId]['currency_symbol'] = $transaction['foreign_currency_symbol']; + $groups[$groudId]['sums'][$currencyId]['currency_decimal_places'] = $transaction['foreign_currency_decimal_places']; + $groups[$groudId]['sums'][$currencyId]['amount'] = '0'; + } + $groups[$groudId]['sums'][$currencyId]['amount'] = bcadd( + $groups[$groudId]['sums'][$currencyId]['amount'], + $transaction['foreign_amount'] ?? '0' + ); + } + } + } + + return $groups; + } + + /** + * @param Collection $collection + * @return Collection + */ + private function postFilterCollection(Collection $collection): Collection + { + $currentCollection = $collection; + /** + * @var int $i + * @var Closure $function + */ + foreach ($this->postFilters as $function) { + + $nextCollection = new Collection; + // loop everything in the current collection + // and save it (or not) in the new collection. + // that new collection is the next current collection + /** + * @var int $index + * @var array $item + */ + foreach ($currentCollection as $ii => $item) { + $result = $function($ii, $item); + if (false === $result) { + // skip other filters, continue to next item. + continue; + } + $nextCollection->push($item); + } + $currentCollection = $nextCollection; + } + return $currentCollection; + } + /** * Same as getGroups but everything is in a paginator. * @@ -269,19 +580,21 @@ class GroupCollector implements GroupCollectorInterface } /** - * Has attachments + * Limit the number of returned entries. + * + * @param int $limit * * @return GroupCollectorInterface */ - public function hasAttachments(): GroupCollectorInterface + public function setLimit(int $limit): GroupCollectorInterface { - Log::debug('Add filter on attachment ID.'); - $this->joinAttachmentTables(); - $this->query->whereNotNull('attachments.attachable_id'); + $this->limit = $limit; + app('log')->debug(sprintf('GroupCollector: The limit is now %d', $limit)); return $this; } + /** * Limit results to a specific currency, either foreign or normal one. * @@ -346,21 +659,6 @@ class GroupCollector implements GroupCollectorInterface return $this; } - /** - * Limit the number of returned entries. - * - * @param int $limit - * - * @return GroupCollectorInterface - */ - public function setLimit(int $limit): GroupCollectorInterface - { - $this->limit = $limit; - app('log')->debug(sprintf('GroupCollector: The limit is now %d', $limit)); - - return $this; - } - /** * Set the page to get. * @@ -456,56 +754,6 @@ class GroupCollector implements GroupCollectorInterface return $this; } - /** - * Automatically include all stuff required to make API calls work. - * - * @return GroupCollectorInterface - */ - public function withAPIInformation(): GroupCollectorInterface - { - // include source + destination account name and type. - $this->withAccountInformation() - // include category ID + name (if any) - ->withCategoryInformation() - // include budget ID + name (if any) - ->withBudgetInformation() - // include bill ID + name (if any) - ->withBillInformation(); - - return $this; - } - - /** - * @inheritDoc - */ - public function withAttachmentInformation(): GroupCollectorInterface - { - $this->fields[] = 'attachments.id as attachment_id'; - $this->fields[] = 'attachments.uploaded as attachment_uploaded'; - $this->joinAttachmentTables(); - - return $this; - } - - /** - * Join table to get attachment information. - */ - private function joinAttachmentTables(): void - { - if (false === $this->hasJoinedAttTables) { - // join some extra tables: - $this->hasJoinedAttTables = true; - $this->query->leftJoin('attachments', 'attachments.attachable_id', '=', 'transaction_journals.id') - ->where( - static function (EloquentBuilder $q1) { - $q1->where('attachments.attachable_type', TransactionJournal::class); - //$q1->where('attachments.uploaded', true); - $q1->orWhereNull('attachments.attachable_type'); - } - ); - } - } - /** * Build the query. */ @@ -550,243 +798,21 @@ class GroupCollector implements GroupCollectorInterface } /** + * Automatically include all stuff required to make API calls work. * + * @return GroupCollectorInterface */ - public function dumpQuery(): void + public function withAPIInformation(): GroupCollectorInterface { - echo $this->query->select($this->fields)->toSql(); - echo '
';
-        print_r($this->query->getBindings());
-        echo '
'; - } + // include source + destination account name and type. + $this->withAccountInformation() + // include category ID + name (if any) + ->withCategoryInformation() + // include budget ID + name (if any) + ->withBudgetInformation() + // include bill ID + name (if any) + ->withBillInformation(); - /** - * - */ - public function dumpQueryInLogs(): void - { - Log::debug($this->query->select($this->fields)->toSql()); - Log::debug('Bindings', $this->query->getBindings()); - } - - /** - * Convert a selected set of fields to arrays. - * - * @param array $array - * - * @return array - */ - private function convertToInteger(array $array): array - { - foreach ($this->integerFields as $field) { - $array[$field] = array_key_exists($field, $array) ? (int) $array[$field] : null; - } - - return $array; - } - - /** - * @param array $existingJournal - * @param TransactionJournal $newJournal - * - * @return array - */ - private function mergeAttachments(array $existingJournal, TransactionJournal $newJournal): array - { - $newArray = $newJournal->toArray(); - if (array_key_exists('attachment_id', $newArray)) { - $attachmentId = (int) $newJournal['attachment_id']; - - $existingJournal['attachments'][$attachmentId] = [ - 'id' => $attachmentId, - ]; - } - - return $existingJournal; - } - - /** - * @param array $existingJournal - * @param TransactionJournal $newJournal - * - * @return array - */ - private function mergeTags(array $existingJournal, TransactionJournal $newJournal): array - { - $newArray = $newJournal->toArray(); - if (array_key_exists('tag_id', $newArray)) { // 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 - * - * @return Collection - */ - private function parseArray(Collection $collection): Collection - { - $groups = []; - /** @var TransactionJournal $augumentedJournal */ - foreach ($collection as $augumentedJournal) { - $groupId = $augumentedJournal->transaction_group_id; - - if (!array_key_exists($groupId, $groups)) { - // make new array - $parsedGroup = $this->parseAugmentedJournal($augumentedJournal); - $groupArray = [ - 'id' => (int) $augumentedJournal->transaction_group_id, - 'user_id' => (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; - $groupArray['transactions'][$journalId] = $parsedGroup; - $groups[$groupId] = $groupArray; - continue; - } - // or parse the rest. - $journalId = (int) $augumentedJournal->transaction_journal_id; - if (array_key_exists($journalId, $groups[$groupId]['transactions'])) { - // append data to existing group + journal (for multiple tags or multiple attachments) - $groups[$groupId]['transactions'][$journalId] = $this->mergeTags($groups[$groupId]['transactions'][$journalId], $augumentedJournal); - $groups[$groupId]['transactions'][$journalId] = $this->mergeAttachments($groups[$groupId]['transactions'][$journalId], $augumentedJournal); - } - - if (!array_key_exists($journalId, $groups[$groupId]['transactions'])) { - // create second, third, fourth split: - $groups[$groupId]['count']++; - $groups[$groupId]['transactions'][$journalId] = $this->parseAugmentedJournal($augumentedJournal); - } - } - - $groups = $this->parseSums($groups); - - return new Collection($groups); - } - - /** - * @param TransactionJournal $augumentedJournal - * - * @return array - */ - private function parseAugmentedJournal(TransactionJournal $augumentedJournal): array - { - $result = $augumentedJournal->toArray(); - $result['tags'] = []; - $result['attachments'] = []; - try { - $result['date'] = new Carbon($result['date'], 'UTC'); - $result['created_at'] = new Carbon($result['created_at'], 'UTC'); - $result['updated_at'] = new Carbon($result['updated_at'], 'UTC'); - - // this is going to happen a lot: - $result['date']->setTimezone(config('app.timezone')); - $result['created_at']->setTimezone(config('app.timezone')); - $result['updated_at']->setTimezone(config('app.timezone')); - } catch (Exception $e) { // @phpstan-ignore-line - Log::error($e->getMessage()); - } - - // convert values to integers: - $result = $this->convertToInteger($result); - - $result['reconciled'] = 1 === (int) $result['reconciled']; - if (array_key_exists('tag_id', $result) && null !== $result['tag_id']) { // assume the other fields are present as well. - $tagId = (int) $augumentedJournal['tag_id']; - $tagDate = null; - try { - $tagDate = Carbon::parse($augumentedJournal['tag_date']); - } catch (InvalidDateException $e) { - Log::debug(sprintf('Could not parse date: %s', $e->getMessage())); - } - - $result['tags'][$tagId] = [ - 'id' => (int) $result['tag_id'], - 'name' => $result['tag_name'], - 'date' => $tagDate, - 'description' => $result['tag_description'], - ]; - } - - // also merge attachments: - if (array_key_exists('attachment_id', $result)) { - $uploaded = 1 === (int)$result['attachment_uploaded']; - $attachmentId = (int) $augumentedJournal['attachment_id']; - if (0 !== $attachmentId && $uploaded) { - $result['attachments'][$attachmentId] = [ - 'id' => $attachmentId, - ]; - } - } - - return $result; - } - - /** - * @param array $groups - * - * @return array - */ - private function parseSums(array $groups): array - { - /** - * @var int $groudId - * @var array $group - */ - foreach ($groups as $groudId => $group) { - /** @var array $transaction */ - foreach ($group['transactions'] as $transaction) { - $currencyId = (int) $transaction['currency_id']; - - // set default: - if (!array_key_exists($currencyId, $groups[$groudId]['sums'])) { - $groups[$groudId]['sums'][$currencyId]['currency_id'] = $currencyId; - $groups[$groudId]['sums'][$currencyId]['currency_code'] = $transaction['currency_code']; - $groups[$groudId]['sums'][$currencyId]['currency_symbol'] = $transaction['currency_symbol']; - $groups[$groudId]['sums'][$currencyId]['currency_decimal_places'] = $transaction['currency_decimal_places']; - $groups[$groudId]['sums'][$currencyId]['amount'] = '0'; - } - $groups[$groudId]['sums'][$currencyId]['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']; - - // set default: - if (!array_key_exists($currencyId, $groups[$groudId]['sums'])) { - $groups[$groudId]['sums'][$currencyId]['currency_id'] = $currencyId; - $groups[$groudId]['sums'][$currencyId]['currency_code'] = $transaction['foreign_currency_code']; - $groups[$groudId]['sums'][$currencyId]['currency_symbol'] = $transaction['foreign_currency_symbol']; - $groups[$groudId]['sums'][$currencyId]['currency_decimal_places'] = $transaction['foreign_currency_decimal_places']; - $groups[$groudId]['sums'][$currencyId]['amount'] = '0'; - } - $groups[$groudId]['sums'][$currencyId]['amount'] = bcadd( - $groups[$groudId]['sums'][$currencyId]['amount'], - $transaction['foreign_amount'] ?? '0' - ); - } - } - } - - return $groups; + return $this; } } diff --git a/app/Helpers/Collector/GroupCollectorInterface.php b/app/Helpers/Collector/GroupCollectorInterface.php index 5216a59242..b950f12f1f 100644 --- a/app/Helpers/Collector/GroupCollectorInterface.php +++ b/app/Helpers/Collector/GroupCollectorInterface.php @@ -58,7 +58,7 @@ interface GroupCollectorInterface public function amountLess(string $amount): GroupCollectorInterface; /** - * Get transactions where the amount is more than. + * Get transactions where the foreign amount is more than. * * @param string $amount * @@ -66,6 +66,72 @@ interface GroupCollectorInterface */ public function amountMore(string $amount): GroupCollectorInterface; + /** + * @param string $name + * @return GroupCollectorInterface + */ + public function attachmentNameContains(string $name): GroupCollectorInterface; + + /** + * @param string $name + * @return GroupCollectorInterface + */ + public function attachmentNameEnds(string $name): GroupCollectorInterface; + + /** + * @param string $name + * @return GroupCollectorInterface + */ + public function attachmentNameIs(string $name): GroupCollectorInterface; + + /** + * @param string $name + * @return GroupCollectorInterface + */ + public function attachmentNameStarts(string $name): GroupCollectorInterface; + + /** + * @param string $value + * @return GroupCollectorInterface + */ + public function attachmentNotesAre(string $value): GroupCollectorInterface; + + /** + * @param string $value + * @return GroupCollectorInterface + */ + public function attachmentNotesContains(string $value): GroupCollectorInterface; + + /** + * @param string $value + * @return GroupCollectorInterface + */ + public function attachmentNotesEnds(string $value): GroupCollectorInterface; + + /** + * @param string $value + * @return GroupCollectorInterface + */ + public function attachmentNotesStarts(string $value): GroupCollectorInterface; + + /** + * @param string $day + * @return GroupCollectorInterface + */ + public function dayAfter(string $day): GroupCollectorInterface; + + /** + * @param string $day + * @return GroupCollectorInterface + */ + public function dayBefore(string $day): GroupCollectorInterface; + + /** + * @param string $day + * @return GroupCollectorInterface + */ + public function dayIs(string $day): GroupCollectorInterface; + /** * End of the description must match: * @@ -111,6 +177,42 @@ interface GroupCollectorInterface */ public function excludeSourceAccounts(Collection $accounts): GroupCollectorInterface; + /** + * @param string $externalId + * @return GroupCollectorInterface + */ + public function externalIdContains(string $externalId): GroupCollectorInterface; + + /** + * @param string $externalId + * @return GroupCollectorInterface + */ + public function externalIdEnds(string $externalId): GroupCollectorInterface; + + /** + * @param string $externalId + * @return GroupCollectorInterface + */ + public function externalIdStarts(string $externalId): GroupCollectorInterface; + + /** + * @param string $url + * @return GroupCollectorInterface + */ + public function externalUrlContains(string $url): GroupCollectorInterface; + + /** + * @param string $url + * @return GroupCollectorInterface + */ + public function externalUrlEnds(string $url): GroupCollectorInterface; + + /** + * @param string $url + * @return GroupCollectorInterface + */ + public function externalUrlStarts(string $url): GroupCollectorInterface; + /** * Ensure the search will find nothing at all, zero results. * @@ -118,6 +220,33 @@ interface GroupCollectorInterface */ public function findNothing(): GroupCollectorInterface; + /** + * Get transactions with a specific foreign amount. + * + * @param string $amount + * + * @return GroupCollectorInterface + */ + public function foreignAmountIs(string $amount): GroupCollectorInterface; + + /** + * Get transactions where the amount is less than. + * + * @param string $amount + * + * @return GroupCollectorInterface + */ + public function foreignAmountLess(string $amount): GroupCollectorInterface; + + /** + * Get transactions where the foreign amount is more than. + * + * @param string $amount + * + * @return GroupCollectorInterface + */ + public function foreignAmountMore(string $amount): GroupCollectorInterface; + /** * Return the transaction journals without group information. Is useful in some instances. * @@ -151,6 +280,112 @@ interface GroupCollectorInterface */ public function hasAttachments(): GroupCollectorInterface; + /** + * Has no attachments + * + * @return GroupCollectorInterface + */ + public function hasNoAttachments(): GroupCollectorInterface; + + /** + * @param string $externalId + * @return GroupCollectorInterface + */ + public function internalReferenceContains(string $externalId): GroupCollectorInterface; + + /** + * @param string $externalId + * @return GroupCollectorInterface + */ + public function internalReferenceEnds(string $externalId): GroupCollectorInterface; + + /** + * @param string $externalId + * @return GroupCollectorInterface + */ + public function internalReferenceStarts(string $externalId): GroupCollectorInterface; + + /** + * @param string $day + * @param string $field + * @return GroupCollectorInterface + */ + public function metaDayAfter(string $day, string $field): GroupCollectorInterface; + + /** + * @param string $day + * @param string $field + * @return GroupCollectorInterface + */ + public function metaDayBefore(string $day, string $field): GroupCollectorInterface; + + /** + * @param string $day + * @param string $field + * @return GroupCollectorInterface + */ + public function metaDayIs(string $day, string $field): GroupCollectorInterface; + + /** + * @param string $month + * @param string $field + * @return GroupCollectorInterface + */ + public function metaMonthAfter(string $month, string $field): GroupCollectorInterface; + + /** + * @param string $month + * @param string $field + * @return GroupCollectorInterface + */ + public function metaMonthBefore(string $month, string $field): GroupCollectorInterface; + + /** + * @param string $month + * @param string $field + * @return GroupCollectorInterface + */ + public function metaMonthIs(string $month, string $field): GroupCollectorInterface; + + /** + * @param string $year + * @param string $field + * @return GroupCollectorInterface + */ + public function metaYearAfter(string $year, string $field): GroupCollectorInterface; + + /** + * @param string $year + * @param string $field + * @return GroupCollectorInterface + */ + public function metaYearBefore(string $year, string $field): GroupCollectorInterface; + + /** + * @param string $year + * @param string $field + * @return GroupCollectorInterface + */ + public function metaYearIs(string $year, string $field): GroupCollectorInterface; + + /** + * @param string $month + * @return GroupCollectorInterface + */ + public function monthAfter(string $month): GroupCollectorInterface; + + /** + * @param string $month + * @return GroupCollectorInterface + */ + public function monthBefore(string $month): GroupCollectorInterface; + + /** + * @param string $month + * @return GroupCollectorInterface + */ + public function monthIs(string $month): GroupCollectorInterface; + /** * @param string $value * @@ -179,6 +414,69 @@ interface GroupCollectorInterface */ public function notesStartWith(string $value): GroupCollectorInterface; + /** + * @param string $day + * @param string $field + * @return GroupCollectorInterface + */ + public function objectDayAfter(string $day, string $field): GroupCollectorInterface; + + /** + * @param string $day + * @param string $field + * @return GroupCollectorInterface + */ + public function objectDayBefore(string $day, string $field): GroupCollectorInterface; + + /** + * @param string $day + * @param string $field + * @return GroupCollectorInterface + */ + public function objectDayIs(string $day, string $field): GroupCollectorInterface; + + /** + * @param string $month + * @param string $field + * @return GroupCollectorInterface + */ + public function objectMonthAfter(string $month, string $field): GroupCollectorInterface; + + /** + * @param string $month + * @param string $field + * @return GroupCollectorInterface + */ + public function objectMonthBefore(string $month, string $field): GroupCollectorInterface; + + /** + * @param string $month + * @param string $field + * @return GroupCollectorInterface + */ + public function objectMonthIs(string $month, string $field): GroupCollectorInterface; + + /** + * @param string $year + * @param string $field + * @return GroupCollectorInterface + */ + public function objectYearAfter(string $year, string $field): GroupCollectorInterface; + + /** + * @param string $year + * @param string $field + * @return GroupCollectorInterface + */ + public function objectYearBefore(string $year, string $field): GroupCollectorInterface; + + /** + * @param string $year + * @param string $field + * @return GroupCollectorInterface + */ + public function objectYearIs(string $year, string $field): GroupCollectorInterface; + /** * Define which accounts can be part of the source and destination transactions. * @@ -306,18 +604,10 @@ interface GroupCollectorInterface public function setExternalId(string $externalId): GroupCollectorInterface; /** - * Transactions without an external URL - * + * @param string $url * @return GroupCollectorInterface */ - public function withoutExternalUrl(): GroupCollectorInterface; - - /** - * Transactions with an external URL - * - * @return GroupCollectorInterface - */ - public function withExternalUrl(): GroupCollectorInterface; + public function setExternalUrl(string $url): GroupCollectorInterface; /** * Limit results to a specific foreign currency. @@ -364,6 +654,57 @@ interface GroupCollectorInterface */ public function setLimit(int $limit): GroupCollectorInterface; + /** + * Collect transactions after a specific date. + * + * @param Carbon $date + * @param string $field + * @return GroupCollectorInterface + */ + public function setMetaAfter(Carbon $date, string $field): GroupCollectorInterface; + + /** + * Collect transactions before a specific date. + * + * @param Carbon $date + * @param string $field + * @return GroupCollectorInterface + */ + public function setMetaBefore(Carbon $date, string $field): GroupCollectorInterface; + + /** + * Set the start and end time of the results to return, based on meta data. + * + * @param Carbon $start + * @param Carbon $end + * @param string $field + * + * @return GroupCollectorInterface + */ + public function setMetaDateRange(Carbon $start, Carbon $end, string $field): GroupCollectorInterface; + + /** + * @param Carbon $date + * @param string $field + * @return GroupCollectorInterface + */ + public function setObjectAfter(Carbon $date, string $field): GroupCollectorInterface; + + /** + * @param Carbon $date + * @param string $field + * @return GroupCollectorInterface + */ + public function setObjectBefore(Carbon $date, string $field): GroupCollectorInterface; + + /** + * @param Carbon $start + * @param Carbon $end + * @param string $field + * @return GroupCollectorInterface + */ + public function setObjectRange(Carbon $start, Carbon $end, string $field): GroupCollectorInterface; + /** * Set the page to get. * @@ -383,6 +724,15 @@ interface GroupCollectorInterface */ public function setRange(Carbon $start, Carbon $end): GroupCollectorInterface; + /** + * Look for specific recurring ID's. + * + * @param string $recurringId + * + * @return GroupCollectorInterface + */ + public function setRecurrenceId(string $recurringId): GroupCollectorInterface; + /** * Search for words in descriptions. * @@ -455,6 +805,15 @@ interface GroupCollectorInterface */ public function setUser(User $user): GroupCollectorInterface; + /** + * Only when does not have these tags + * + * @param Collection $tags + * + * @return GroupCollectorInterface + */ + public function setWithoutSpecificTags(Collection $tags): GroupCollectorInterface; + /** * Either account can be set, but NOT both. This effectively excludes internal transfers. * @@ -534,6 +893,21 @@ interface GroupCollectorInterface */ public function withCategoryInformation(): GroupCollectorInterface; + /** + * Transactions with an external URL + * + * @return GroupCollectorInterface + */ + public function withExternalUrl(): GroupCollectorInterface; + + /** + * Transaction must have meta date field X. + * + * @param string $field + * @return GroupCollectorInterface + */ + public function withMetaDate(string $field): GroupCollectorInterface; + /** * Will include notes. * @@ -569,6 +943,13 @@ interface GroupCollectorInterface */ public function withoutCategory(): GroupCollectorInterface; + /** + * Transactions without an external URL + * + * @return GroupCollectorInterface + */ + public function withoutExternalUrl(): GroupCollectorInterface; + /** * @return GroupCollectorInterface */ @@ -579,15 +960,23 @@ interface GroupCollectorInterface */ public function withoutTags(): GroupCollectorInterface; - - public function yearIs(string $year): GroupCollectorInterface; - public function monthIs(string $month): GroupCollectorInterface; - public function dayIs(string $day): GroupCollectorInterface; - public function yearBefore(string $year): GroupCollectorInterface; - public function monthBefore(string $month): GroupCollectorInterface; - public function dayBefore(string $day): GroupCollectorInterface; + /** + * @param string $year + * @return GroupCollectorInterface + */ public function yearAfter(string $year): GroupCollectorInterface; - public function monthAfter(string $month): GroupCollectorInterface; - public function dayAfter(string $day): GroupCollectorInterface; + + /** + * @param string $year + * @return GroupCollectorInterface + */ + public function yearBefore(string $year): GroupCollectorInterface; + + /** + * @param string $year + * @return GroupCollectorInterface + */ + public function yearIs(string $year): GroupCollectorInterface; + } diff --git a/app/Helpers/Fiscal/FiscalHelper.php b/app/Helpers/Fiscal/FiscalHelper.php index 1298557deb..68af77a004 100644 --- a/app/Helpers/Fiscal/FiscalHelper.php +++ b/app/Helpers/Fiscal/FiscalHelper.php @@ -46,6 +46,9 @@ class FiscalHelper implements FiscalHelperInterface * @param Carbon $date * * @return Carbon date object + * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function endOfFiscalYear(Carbon $date): Carbon { @@ -69,6 +72,8 @@ class FiscalHelper implements FiscalHelperInterface * * @return Carbon date object * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function startOfFiscalYear(Carbon $date): Carbon { @@ -77,7 +82,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 c0e5318f1d..451b56ad08 100644 --- a/app/Helpers/Report/NetWorth.php +++ b/app/Helpers/Report/NetWorth.php @@ -31,7 +31,6 @@ use FireflyIII\Support\CacheProperties; use FireflyIII\User; use Illuminate\Support\Collection; use JsonException; -use Log; /** * @@ -64,6 +63,7 @@ class NetWorth implements NetWorthInterface * * @return array * @throws JsonException + * @throws \FireflyIII\Exceptions\FireflyException */ public function getNetWorthByCurrency(Collection $accounts, Carbon $date): array { @@ -91,7 +91,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)); @@ -102,7 +102,7 @@ class NetWorth implements NetWorthInterface //Log::debug(sprintf('Balance is %s', $balance)); // always subtract virtual balance. - $virtualBalance = (string)$account->virtual_balance; + $virtualBalance = (string) $account->virtual_balance; if ('' !== $virtualBalance) { $balance = bcsub($balance, $virtualBalance); } diff --git a/app/Helpers/Report/PopupReport.php b/app/Helpers/Report/PopupReport.php index d2b36349fe..66bbdd5228 100644 --- a/app/Helpers/Report/PopupReport.php +++ b/app/Helpers/Report/PopupReport.php @@ -77,7 +77,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 */ $collector = app(GroupCollectorInterface::class); @@ -112,7 +112,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 */ $collector = app(GroupCollectorInterface::class); @@ -152,7 +152,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 */ @@ -195,7 +195,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/ReportHelper.php b/app/Helpers/Report/ReportHelper.php index 0c2c2b5e15..d2f9d8c3d9 100644 --- a/app/Helpers/Report/ReportHelper.php +++ b/app/Helpers/Report/ReportHelper.php @@ -141,7 +141,7 @@ class ReportHelper implements ReportHelperInterface $currentEnd = clone $start; $currentEnd->endOfMonth(); $months[$year]['months'][] = [ - 'formatted' => $start->formatLocalized('%B %Y'), + 'formatted' => $start->isoFormat((string) trans('config.month_js')), 'start' => $start->format('Y-m-d'), 'end' => $currentEnd->format('Y-m-d'), 'month' => $start->month, diff --git a/app/Helpers/Update/UpdateTrait.php b/app/Helpers/Update/UpdateTrait.php index fc144807eb..49659e99f7 100644 --- a/app/Helpers/Update/UpdateTrait.php +++ b/app/Helpers/Update/UpdateTrait.php @@ -40,6 +40,8 @@ trait UpdateTrait * * @return array * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function getLatestRelease(): array { diff --git a/app/Http/Controllers/Account/CreateController.php b/app/Http/Controllers/Account/CreateController.php index 4ec43f9159..5aed064c3e 100644 --- a/app/Http/Controllers/Account/CreateController.php +++ b/app/Http/Controllers/Account/CreateController.php @@ -61,7 +61,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); $this->attachments = app(AttachmentHelperInterface::class); @@ -84,7 +84,7 @@ class CreateController extends Controller $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'); @@ -103,9 +103,9 @@ 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 @@ -113,7 +113,7 @@ class CreateController extends Controller 'preFilled', [ 'currency_id' => $defaultCurrency->id, - 'include_net_worth' => $hasOldInput ? (bool)$request->old('include_net_worth') : true, + 'include_net_worth' => $hasOldInput ? (bool) $request->old('include_net_worth') : true, ] ); @@ -137,12 +137,14 @@ class CreateController extends Controller * * @return RedirectResponse|Redirector * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ 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); @@ -161,7 +163,7 @@ class CreateController extends Controller $this->attachments->saveAttachmentsForModel($account, $files); } if (null !== $files && auth()->user()->hasRole('demo')) { - session()->flash('info', (string)trans('firefly.no_att_demo_user')); + session()->flash('info', (string) trans('firefly.no_att_demo_user')); } if (count($this->attachments->getMessages()->get('attachments')) > 0) { @@ -170,7 +172,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); diff --git a/app/Http/Controllers/Account/DeleteController.php b/app/Http/Controllers/Account/DeleteController.php index cedf296bd8..7ea322e34b 100644 --- a/app/Http/Controllers/Account/DeleteController.php +++ b/app/Http/Controllers/Account/DeleteController.php @@ -53,7 +53,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); @@ -76,7 +76,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]); @@ -104,11 +104,11 @@ class DeleteController extends Controller $type = $account->accountType->type; $typeName = config(sprintf('firefly.shortNamesByFullName.%s', $type)); $name = $account->name; - $moveTo = $this->repository->find((int)$request->get('move_account_before_delete')); + $moveTo = $this->repository->find((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 b0b5f5ee21..c3975a210c 100644 --- a/app/Http/Controllers/Account/EditController.php +++ b/app/Http/Controllers/Account/EditController.php @@ -59,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); @@ -86,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(); @@ -111,9 +111,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"). @@ -122,7 +122,7 @@ class EditController extends Controller } $request->session()->forget('accounts.edit.fromUpdate'); - $openingBalanceAmount = (string)$repository->getOpeningBalanceAmount($account); + $openingBalanceAmount = (string) $repository->getOpeningBalanceAmount($account); if ('0' === $openingBalanceAmount) { $openingBalanceAmount = ''; } @@ -143,17 +143,17 @@ class EditController extends Controller 'BIC' => $repository->getMetaValue($account, 'BIC'), 'opening_balance_date' => $openingBalanceDate, 'liability_type_id' => $account->account_type_id, - 'opening_balance' => number_format((float)$openingBalanceAmount, $currency->decimal_places,'.',''), + 'opening_balance' => number_format((float) $openingBalanceAmount, $currency->decimal_places, '.', ''), 'liability_direction' => $this->repository->getMetaValue($account, 'liability_direction'), - 'virtual_balance' => number_format((float)$account->virtual_balance, $currency->decimal_places,'.',''), + 'virtual_balance' => number_format((float) $account->virtual_balance, $currency->decimal_places, '.', ''), 'currency_id' => $currency->id, 'include_net_worth' => $includeNetWorth, 'interest' => $repository->getMetaValue($account, 'interest'), 'interest_period' => $repository->getMetaValue($account, 'interest_period'), 'notes' => $this->repository->getNoteText($account), - 'active' => $hasOldInput ? (bool)$request->old('active') : $account->active, + 'active' => $hasOldInput ? (bool) $request->old('active') : $account->active, ]; - if('' === $openingBalanceAmount) { + if ('' === $openingBalanceAmount) { $preFilled['opening_balance'] = ''; } @@ -194,7 +194,7 @@ 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])); // store new attachment(s): @@ -203,7 +203,7 @@ class EditController extends Controller $this->attachments->saveAttachmentsForModel($account, $files); } if (null !== $files && auth()->user()->hasRole('demo')) { - session()->flash('info', (string)trans('firefly.no_att_demo_user')); + session()->flash('info', (string) trans('firefly.no_att_demo_user')); } if (count($this->attachments->getMessages()->get('attachments')) > 0) { @@ -212,7 +212,7 @@ class EditController extends Controller // redirect $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); diff --git a/app/Http/Controllers/Account/IndexController.php b/app/Http/Controllers/Account/IndexController.php index bbb561c956..2a23f4ee2a 100644 --- a/app/Http/Controllers/Account/IndexController.php +++ b/app/Http/Controllers/Account/IndexController.php @@ -59,7 +59,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); @@ -74,18 +74,21 @@ class IndexController extends Controller * * @return Factory|View * @throws FireflyException + * @throws \JsonException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ 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 */ @@ -105,11 +108,11 @@ class IndexController extends Controller $account->startBalance = $this->isInArray($startBalances, $account->id); $account->endBalance = $this->isInArray($endBalances, $account->id); $account->difference = bcsub($account->endBalance, $account->startBalance); - $account->interest = number_format((float)$this->repository->getMetaValue($account, 'interest'), 4, '.', ''); - $account->interestPeriod = (string)trans(sprintf('firefly.interest_calc_%s', $this->repository->getMetaValue($account, 'interest_period'))); - $account->accountTypeString = (string)trans(sprintf('firefly.account_type_%s', $account->accountType->type)); + $account->interest = number_format((float) $this->repository->getMetaValue($account, 'interest'), 4, '.', ''); + $account->interestPeriod = (string) trans(sprintf('firefly.interest_calc_%s', $this->repository->getMetaValue($account, 'interest_period'))); + $account->accountTypeString = (string) trans(sprintf('firefly.account_type_%s', $account->accountType->type)); $account->current_debt = '0'; - $account->iban = implode(' ', str_split((string)$account->iban, 4)); + $account->iban = implode(' ', str_split((string) $account->iban, 4)); } ); @@ -128,13 +131,16 @@ class IndexController extends Controller * @param string $objectType * * @return Factory|View - * @throws Exception + * @throws FireflyException + * @throws \JsonException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function index(Request $request, string $objectType) { Log::debug(sprintf('Now at %s', __METHOD__)); $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)); @@ -142,8 +148,8 @@ class IndexController extends Controller $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(); @@ -168,15 +174,15 @@ class IndexController extends Controller $account->startBalance = $this->isInArray($startBalances, $account->id); $account->endBalance = $this->isInArray($endBalances, $account->id); $account->difference = bcsub($account->endBalance, $account->startBalance); - $account->interest = number_format((float)$this->repository->getMetaValue($account, 'interest'), 4, '.', ''); - $account->interestPeriod = (string)trans( + $account->interest = number_format((float) $this->repository->getMetaValue($account, 'interest'), 4, '.', ''); + $account->interestPeriod = (string) trans( sprintf('firefly.interest_calc_%s', $this->repository->getMetaValue($account, 'interest_period')) ); - $account->accountTypeString = (string)trans(sprintf('firefly.account_type_%s', $account->accountType->type)); + $account->accountTypeString = (string) trans(sprintf('firefly.account_type_%s', $account->accountType->type)); $account->location = $this->repository->getLocation($account); $account->liability_direction = $this->repository->getMetaValue($account, 'liability_direction'); $account->current_debt = $this->repository->getMetaValue($account, 'current_debt') ?? '-'; - $account->iban = implode(' ', str_split((string)$account->iban, 4)); + $account->iban = implode(' ', str_split((string) $account->iban, 4)); } ); // make paginator: diff --git a/app/Http/Controllers/Account/ReconcileController.php b/app/Http/Controllers/Account/ReconcileController.php index 4ac2b31640..9b9cc02afe 100644 --- a/app/Http/Controllers/Account/ReconcileController.php +++ b/app/Http/Controllers/Account/ReconcileController.php @@ -68,7 +68,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); @@ -86,7 +86,10 @@ class ReconcileController extends Controller * @param Carbon|null $end * * @return Factory|RedirectResponse|Redirector|View - * @throws Exception + * @throws FireflyException + * @throws \JsonException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function reconcile(Account $account, Carbon $start = null, Carbon $end = null) { @@ -95,7 +98,7 @@ class ReconcileController extends Controller } if (AccountType::ASSET !== $account->accountType->type) { - 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))])); @@ -125,10 +128,10 @@ class ReconcileController extends Controller $startDate = clone $start; $startDate->subDay(); - $startBalance = number_format((float)app('steam')->balance($account, $startDate), $currency->decimal_places, '.', ''); - $endBalance = number_format((float)app('steam')->balance($account, $end), $currency->decimal_places, '.', ''); + $startBalance = number_format((float) app('steam')->balance($account, $startDate), $currency->decimal_places, '.', ''); + $endBalance = number_format((float) 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%']); @@ -177,7 +180,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.'); @@ -194,10 +197,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])); @@ -237,7 +240,8 @@ class ReconcileController extends Controller // title: $description = trans( 'firefly.reconciliation_transaction_title', - ['from' => $start->formatLocalized($this->monthAndDayFormat), 'to' => $end->formatLocalized($this->monthAndDayFormat)] + ['from' => $start->isoFormat($this->monthAndDayFormat), + 'to' => $end->isoFormat($this->monthAndDayFormat)] ); $submission = [ 'user' => auth()->user()->id, diff --git a/app/Http/Controllers/Account/ShowController.php b/app/Http/Controllers/Account/ShowController.php index df37b3168b..e3823a4771 100644 --- a/app/Http/Controllers/Account/ShowController.php +++ b/app/Http/Controllers/Account/ShowController.php @@ -64,7 +64,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); @@ -83,8 +83,10 @@ class ShowController extends Controller * @param Carbon|null $end * * @return RedirectResponse|Redirector|Factory|View - * @throws Exception - * + * @throws \FireflyIII\Exceptions\FireflyException + * @throws \JsonException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function show(Request $request, Account $account, Carbon $start = null, Carbon $end = null) { @@ -106,19 +108,19 @@ class ShowController extends Controller $attachments = $this->repository->getAttachments($account); $today = today(config('app.timezone')); $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]); + $fStart = $start->isoFormat($this->monthAndDayFormat); + $fEnd = $end->isoFormat($this->monthAndDayFormat); + $subTitle = (string) trans('firefly.journals_in_period_for_account', ['name' => $account->name, 'start' => $fStart, 'end' => $fEnd]); $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); // if layout = v2, overrule the page title. - if('v1'!==config('firefly.layout')) { - $subTitle = (string)trans('firefly.all_journals_for_account', ['name' => $account->name]); + if ('v1' !== config('firefly.layout')) { + $subTitle = (string) trans('firefly.all_journals_for_account', ['name' => $account->name]); } @@ -164,8 +166,10 @@ class ShowController extends Controller * @param Account $account * * @return RedirectResponse|Redirector|Factory|View - * @throws Exception - * + * @throws \FireflyIII\Exceptions\FireflyException + * @throws \JsonException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function showAll(Request $request, Account $account) { @@ -180,10 +184,10 @@ class ShowController extends Controller $today = today(config('app.timezone')); $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); diff --git a/app/Http/Controllers/Admin/ConfigurationController.php b/app/Http/Controllers/Admin/ConfigurationController.php index 775b20fd21..0b15f2247b 100644 --- a/app/Http/Controllers/Admin/ConfigurationController.php +++ b/app/Http/Controllers/Admin/ConfigurationController.php @@ -47,7 +47,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); @@ -61,10 +61,12 @@ class ConfigurationController extends Controller * * @return Factory|View * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ 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.'); @@ -100,7 +102,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 3b4f76a38b..c6527c210b 100644 --- a/app/Http/Controllers/Admin/HomeController.php +++ b/app/Http/Controllers/Admin/HomeController.php @@ -55,11 +55,13 @@ class HomeController extends Controller * * @return Factory|View * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ 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'; $email = auth()->user()->email; $pref = app('preferences')->get('remote_guard_alt_email'); @@ -82,11 +84,10 @@ class HomeController extends Controller { Log::channel('audit')->info('User sends test message.'); /** @var User $user */ - $user = auth()->user(); - $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')); + $user = auth()->user(); + Log::debug('Now in testMessage() controller.'); + event(new AdminRequestedTestMessage($user)); + 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 0fe0d5be0e..fcb7815f2f 100644 --- a/app/Http/Controllers/Admin/LinkController.php +++ b/app/Http/Controllers/Admin/LinkController.php @@ -52,7 +52,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); @@ -71,7 +71,7 @@ class LinkController extends Controller { 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"). @@ -93,17 +93,17 @@ class LinkController extends Controller 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) { @@ -130,10 +130,10 @@ class LinkController extends Controller { Log::channel('audit')->info(sprintf('User destroyed link type #%d', $linkType->id)); $name = $linkType->name; - $moveTo = $this->repository->find((int)$request->get('move_link_type_before_delete')); + $moveTo = $this->repository->find((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')); @@ -150,11 +150,11 @@ class LinkController extends Controller 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)); @@ -175,7 +175,7 @@ class LinkController extends Controller */ public function index() { - $subTitle = (string)trans('firefly.journal_link_configuration'); + $subTitle = (string) trans('firefly.journal_link_configuration'); $subTitleIcon = 'fa-link'; $linkTypes = $this->repository->get(); @@ -198,7 +198,7 @@ class LinkController extends Controller */ 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); @@ -225,9 +225,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); @@ -249,7 +249,7 @@ class LinkController extends Controller 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')); } @@ -263,10 +263,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/UpdateController.php b/app/Http/Controllers/Admin/UpdateController.php index 1e9b494c45..e5444ba97d 100644 --- a/app/Http/Controllers/Admin/UpdateController.php +++ b/app/Http/Controllers/Admin/UpdateController.php @@ -47,7 +47,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); @@ -61,25 +61,27 @@ class UpdateController extends Controller * * @return Factory|View * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ 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')); @@ -94,14 +96,14 @@ class UpdateController extends Controller */ 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')); } diff --git a/app/Http/Controllers/Admin/UserController.php b/app/Http/Controllers/Admin/UserController.php index 1b67554e90..b2f265e0dd 100644 --- a/app/Http/Controllers/Admin/UserController.php +++ b/app/Http/Controllers/Admin/UserController.php @@ -51,7 +51,7 @@ 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); @@ -77,7 +77,7 @@ class UserController extends Controller return redirect(route('admin.users')); } - $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')); } @@ -97,7 +97,7 @@ class UserController extends Controller return redirect(route('admin.users')); } $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')); } @@ -121,15 +121,15 @@ 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'; $currentUser = auth()->user(); $isAdmin = $this->repository->hasRole($user, 'owner'); $codes = [ - '' => (string)trans('firefly.no_block_code'), - 'bounced' => (string)trans('firefly.block_code_bounced'), - 'expired' => (string)trans('firefly.block_code_expired'), - 'email_changed' => (string)trans('firefly.block_code_email_changed'), + '' => (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', 'canEditDetails', 'subTitle', 'subTitleIcon', 'codes', 'currentUser', 'isAdmin')); @@ -142,7 +142,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(); @@ -166,9 +166,9 @@ class UserController extends Controller */ 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); @@ -215,10 +215,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')) { session()->put('users.edit.fromUpdate', true); diff --git a/app/Http/Controllers/AttachmentController.php b/app/Http/Controllers/AttachmentController.php index 0baccde090..15cb83e236 100644 --- a/app/Http/Controllers/AttachmentController.php +++ b/app/Http/Controllers/AttachmentController.php @@ -57,7 +57,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); @@ -74,7 +74,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'); @@ -96,7 +96,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')); @@ -146,7 +146,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')) { @@ -193,11 +193,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')) { $request->session()->put('attachments.edit.fromUpdate', true); diff --git a/app/Http/Controllers/Auth/ForgotPasswordController.php b/app/Http/Controllers/Auth/ForgotPasswordController.php index bf960ddd66..dbdd2d7af3 100644 --- a/app/Http/Controllers/Auth/ForgotPasswordController.php +++ b/app/Http/Controllers/Auth/ForgotPasswordController.php @@ -86,14 +86,14 @@ 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 // to send the link, we will examine the response then see the message we // need to show to the user. Finally, we'll send out a proper response. $result = $this->broker()->sendResetLink($request->only('email')); - if('passwords.throttled' === $result) { + if ('passwords.throttled' === $result) { Log::error(sprintf('Cowardly refuse to send a password reset message to user #%d because the reset button has been throttled.', $user->id)); } @@ -110,6 +110,8 @@ class ForgotPasswordController extends Controller * * @return Factory|View * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function showLinkRequestForm() { @@ -124,7 +126,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 0aaa0917d5..38b86ca230 100644 --- a/app/Http/Controllers/Auth/LoginController.php +++ b/app/Http/Controllers/Auth/LoginController.php @@ -22,7 +22,6 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\Auth; -use Adldap; use Cookie; use DB; use FireflyIII\Events\ActuallyLoggedIn; @@ -90,15 +89,6 @@ class LoginController extends Controller Log::channel('audit')->info(sprintf('User is trying to login using "%s"', $request->get($this->username()))); Log::info('User is trying to login.'); - $guard = config('auth.defaults.guard'); - - // if the user logs in using LDAP the field is also changed (per LDAP config) - if ('ldap' === $guard) { - Log::debug('User wishes to login using LDAP.'); - $this->username = config('firefly.ldap_auth_field'); - } - - $this->validateLogin($request); Log::debug('Login data is valid.'); @@ -138,6 +128,37 @@ class LoginController extends Controller $this->sendFailedLoginResponse($request); } + /** + * Get the login username to be used by the controller. + * + * @return string + */ + public function username() + { + return $this->username; + } + + /** + * Get the failed login response instance. + * + * @param Request $request + * + * @return void + * + * @throws ValidationException + */ + protected function sendFailedLoginResponse(Request $request) + { + $exception = ValidationException::withMessages( + [ + $this->username() => [trans('auth.failed')], + ] + ); + $exception->redirectTo = route('login'); + + throw $exception; + } + /** * Log the user out of the application. * @@ -175,27 +196,6 @@ class LoginController extends Controller : redirect('/'); } - /** - * Get the failed login response instance. - * - * @param Request $request - * - * @return void - * - * @throws ValidationException - */ - protected function sendFailedLoginResponse(Request $request) - { - $exception = ValidationException::withMessages( - [ - $this->username() => [trans('auth.failed')], - ] - ); - $exception->redirectTo = route('login'); - - throw $exception; - } - /** * Show the application's login form. * @@ -203,6 +203,8 @@ class LoginController extends Controller * * @return Factory|Application|View|Redirector|RedirectResponse * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function showLoginForm(Request $request) { @@ -210,23 +212,12 @@ class LoginController extends Controller $count = DB::table('users')->count(); $guard = config('auth.defaults.guard'); - $title = (string)trans('firefly.login_page_title'); + $title = (string) trans('firefly.login_page_title'); if (0 === $count && 'web' === $guard) { return redirect(route('register')); } - // switch to LDAP settings: - if ('ldap' === $guard) { - Log::debug('User wishes to login using LDAP.'); - $this->username = config('firefly.ldap_auth_field'); - } - - // throw warning if still using login_provider - $ldapWarning = false; - if ('ldap' === config('firefly.login_provider')) { - $ldapWarning = true; - } // is allowed to register, etc. $singleUserMode = app('fireflyconfig')->get('single_user_mode', config('firefly.configuration.single_user_mode'))->data; $allowRegistration = true; @@ -251,16 +242,6 @@ class LoginController extends Controller } $usernameField = $this->username(); - return view('auth.login', compact('allowRegistration', 'email', 'remember', 'ldapWarning', 'allowReset', 'title', 'usernameField')); - } - - /** - * Get the login username to be used by the controller. - * - * @return string - */ - public function username() - { - return $this->username; + return view('auth.login', compact('allowRegistration', 'email', 'remember', 'allowReset', 'title', 'usernameField')); } } diff --git a/app/Http/Controllers/Auth/RegisterController.php b/app/Http/Controllers/Auth/RegisterController.php index 8db7b333e5..c7a5511215 100644 --- a/app/Http/Controllers/Auth/RegisterController.php +++ b/app/Http/Controllers/Auth/RegisterController.php @@ -36,6 +36,8 @@ use Illuminate\Routing\Redirector; use Illuminate\Validation\ValidationException; use Illuminate\View\View; use Log; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; /** * Class RegisterController @@ -85,18 +87,7 @@ class RegisterController extends Controller */ public function register(Request $request) { - // is allowed to? - $allowRegistration = true; - $singleUserMode = app('fireflyconfig')->get('single_user_mode', config('firefly.configuration.single_user_mode'))->data; - $userCount = User::count(); - $guard = config('auth.defaults.guard'); - if (true === $singleUserMode && $userCount > 0 && 'ldap' !== $guard) { - $allowRegistration = false; - } - - if ('ldap' === $guard) { - $allowRegistration = false; - } + $allowRegistration = $this->allowedToRegister(); if (false === $allowRegistration) { throw new FireflyException('Registration is currently not available :('); @@ -105,45 +96,56 @@ class RegisterController extends Controller $this->validator($request->all())->validate(); $user = $this->createUser($request->all()); Log::info(sprintf('Registered new user %s', $user->email)); - event(new RegisteredUser($user, $request->ip())); + event(new RegisteredUser($user)); $this->guard()->login($user); - session()->flash('success', (string)trans('firefly.registered')); + session()->flash('success', (string) trans('firefly.registered')); $this->registered($request, $user); return redirect($this->redirectPath()); } + /** + * @return bool + * @throws FireflyException + */ + protected function allowedToRegister(): bool + { + // is allowed to register? + $allowRegistration = true; + try { + $singleUserMode = app('fireflyconfig')->get('single_user_mode', config('firefly.configuration.single_user_mode'))->data; + } catch (ContainerExceptionInterface|NotFoundExceptionInterface $e) { + $singleUserMode = true; + } + $userCount = User::count(); + $guard = config('auth.defaults.guard'); + if (true === $singleUserMode && $userCount > 0 && 'web' === $guard) { + $allowRegistration = false; + } + if ('web' !== $guard) { + $allowRegistration = false; + } + return $allowRegistration; + } + /** * Show the application registration form. * * @param Request $request * * @return Factory|View + * @throws ContainerExceptionInterface * @throws FireflyException + * @throws NotFoundExceptionInterface */ public function showRegistrationForm(Request $request) { - $allowRegistration = true; $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'); - $guard = config('auth.defaults.guard'); - - if (true === $isDemoSite) { - $allowRegistration = false; - } - - if (true === $singleUserMode && $userCount > 0 && 'ldap' !== $guard) { - $allowRegistration = false; - } - - if ('ldap' === $guard) { - $allowRegistration = false; - } + $pageTitle = (string) trans('firefly.register_page_title'); + $allowRegistration = $this->allowedToRegister(); if (false === $allowRegistration) { $message = 'Registration is currently not available.'; @@ -155,5 +157,4 @@ class RegisterController extends Controller return view('auth.register', compact('isDemoSite', 'email', 'pageTitle')); } - } diff --git a/app/Http/Controllers/Auth/ResetPasswordController.php b/app/Http/Controllers/Auth/ResetPasswordController.php index 03095fdbd6..7b28f677c2 100644 --- a/app/Http/Controllers/Auth/ResetPasswordController.php +++ b/app/Http/Controllers/Auth/ResetPasswordController.php @@ -123,6 +123,8 @@ class ResetPasswordController extends Controller * * @return Factory|View * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function showResetForm(Request $request, $token = null) { @@ -137,7 +139,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 c9fdb334f6..bec3852b4a 100644 --- a/app/Http/Controllers/Auth/TwoFactorController.php +++ b/app/Http/Controllers/Auth/TwoFactorController.php @@ -47,7 +47,7 @@ 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')); } @@ -61,7 +61,7 @@ class TwoFactorController extends Controller { /** @var array $mfaHistory */ $mfaHistory = Preferences::get('mfa_history', [])->data; - $mfaCode = (string)$request->get('one_time_password'); + $mfaCode = (string) $request->get('one_time_password'); // is in history? then refuse to use it. if ($this->inMFAHistory($mfaCode, $mfaHistory)) { diff --git a/app/Http/Controllers/Bill/CreateController.php b/app/Http/Controllers/Bill/CreateController.php index 5eaa4c127b..123f9d2b62 100644 --- a/app/Http/Controllers/Bill/CreateController.php +++ b/app/Http/Controllers/Bill/CreateController.php @@ -54,7 +54,7 @@ class CreateController 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->repository = app(BillRepositoryInterface::class); @@ -77,9 +77,9 @@ class CreateController extends Controller /** @var array $billPeriods */ $billPeriods = config('firefly.bill_periods'); foreach ($billPeriods as $current) { - $periods[$current] = (string)trans('firefly.repeat_freq_' . $current); + $periods[$current] = (string) trans('firefly.repeat_freq_' . $current); } - $subTitle = (string)trans('firefly.create_new_bill'); + $subTitle = (string) trans('firefly.create_new_bill'); $defaultCurrency = app('amount')->getDefaultCurrency(); // put previous url in session if not redirect from store (not "create another"). @@ -101,17 +101,18 @@ class CreateController extends Controller */ public function store(BillStoreRequest $request): RedirectResponse { - $billData = $request->getBillData(); + $billData = $request->getBillData(); + $billData['active'] = true; try { $bill = $this->repository->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 */ @@ -120,7 +121,7 @@ class CreateController extends Controller $this->attachments->saveAttachmentsForModel($bill, $files); } if (null !== $files && auth()->user()->hasRole('demo')) { - session()->flash('info', (string)trans('firefly.no_att_demo_user')); + session()->flash('info', (string) trans('firefly.no_att_demo_user')); } if (count($this->attachments->getMessages()->get('attachments')) > 0) { diff --git a/app/Http/Controllers/Bill/DeleteController.php b/app/Http/Controllers/Bill/DeleteController.php index 071420027d..cc5c3155f8 100644 --- a/app/Http/Controllers/Bill/DeleteController.php +++ b/app/Http/Controllers/Bill/DeleteController.php @@ -53,7 +53,7 @@ class DeleteController 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->repository = app(BillRepositoryInterface::class); @@ -73,7 +73,7 @@ class DeleteController extends Controller { // 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')); } @@ -91,7 +91,7 @@ class DeleteController extends Controller $name = $bill->name; $this->repository->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')); diff --git a/app/Http/Controllers/Bill/EditController.php b/app/Http/Controllers/Bill/EditController.php index aa9a47b16a..14a7d62a3b 100644 --- a/app/Http/Controllers/Bill/EditController.php +++ b/app/Http/Controllers/Bill/EditController.php @@ -53,7 +53,7 @@ class EditController 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->repository = app(BillRepositoryInterface::class); @@ -78,10 +78,10 @@ class EditController 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')) { @@ -89,8 +89,8 @@ class EditController 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); $rules = $this->repository->getRulesForBill($bill); $defaultCurrency = app('amount')->getDefaultCurrency(); @@ -98,9 +98,11 @@ class EditController extends Controller $hasOldInput = null !== $request->old('_token'); $preFilled = [ + 'bill_end_date' => $bill->end_date, + 'extension_date' => $bill->extension_date, 'notes' => $this->repository->getNoteText($bill), 'transaction_currency_id' => $bill->transaction_currency_id, - 'active' => $hasOldInput ? (bool)$request->old('active') : $bill->active, + 'active' => $hasOldInput ? (bool) $request->old('active') : $bill->active, 'object_group' => $bill->objectGroups->first() ? $bill->objectGroups->first()->title : '', ]; @@ -123,7 +125,7 @@ class EditController extends Controller $billData = $request->getBillData(); $bill = $this->repository->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 */ @@ -132,7 +134,7 @@ class EditController extends Controller $this->attachments->saveAttachmentsForModel($bill, $files); } if (null !== $files && auth()->user()->hasRole('demo')) { - session()->flash('info', (string)trans('firefly.no_att_demo_user')); + session()->flash('info', (string) trans('firefly.no_att_demo_user')); } // flash messages @@ -141,7 +143,7 @@ class EditController 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')) { $request->session()->put('bills.edit.fromUpdate', true); diff --git a/app/Http/Controllers/Bill/IndexController.php b/app/Http/Controllers/Bill/IndexController.php index f5cb3bf78e..5fd72fa205 100644 --- a/app/Http/Controllers/Bill/IndexController.php +++ b/app/Http/Controllers/Bill/IndexController.php @@ -55,7 +55,7 @@ class IndexController 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->repository = app(BillRepositoryInterface::class); @@ -92,14 +92,14 @@ class IndexController extends Controller $bills = [ 0 => [ // the index is the order, not the ID. 'object_group_id' => 0, - 'object_group_title' => (string)trans('firefly.default_group_title_name'), + 'object_group_title' => (string) trans('firefly.default_group_title_name'), 'bills' => [], ], ]; /** @var Bill $bill */ foreach ($collection as $bill) { $array = $transformer->transform($bill); - $groupOrder = (int)$array['object_group_order']; + $groupOrder = (int) $array['object_group_order']; // make group array if necessary: $bills[$groupOrder] = $bills[$groupOrder] ?? [ 'object_group_id' => $array['object_group_id'], @@ -136,8 +136,9 @@ class IndexController extends Controller // summarise per currency / per group. $sums = $this->getSums($bills); $totals = $this->getTotals($sums); + $today = now()->startOfDay(); - return view('bills.index', compact('bills', 'sums', 'total', 'totals')); + return view('bills.index', compact('bills', 'sums', 'total', 'totals', 'today')); } /** @@ -145,6 +146,8 @@ class IndexController extends Controller * * @return array * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ private function getSums(array $bills): array { @@ -172,8 +175,8 @@ class IndexController extends Controller ]; // only fill in avg when bill is active. if (count($bill['pay_dates']) > 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[$groupOrder][$currencyId]['avg'] = bcadd($sums[$groupOrder][$currencyId]['avg'], $avg); } // fill in per period regardless: @@ -192,7 +195,7 @@ class IndexController extends Controller */ private function amountPerPeriod(array $bill, string $range): string { - $avg = bcdiv(bcadd((string)$bill['amount_min'], (string)$bill['amount_max']), '2'); + $avg = bcdiv(bcadd((string) $bill['amount_min'], (string) $bill['amount_max']), '2'); Log::debug(sprintf('Amount per period for bill #%d "%s"', $bill['id'], $bill['name'])); Log::debug(sprintf('Average is %s', $avg)); @@ -203,10 +206,10 @@ class IndexController extends Controller 'quarterly' => '4', 'monthly' => '12', 'weekly' => '52.17', - 'daily' => '365.24', + 'daily' => '365.24', ]; - $yearAmount = bcmul($avg, bcdiv($multiplies[$bill['repeat_freq']], (string)($bill['skip'] + 1))); - Log::debug(sprintf('Amount per year is %s (%s * %s / %s)', $yearAmount, $avg, $multiplies[$bill['repeat_freq']], (string)($bill['skip'] + 1))); + $yearAmount = bcmul($avg, bcdiv($multiplies[$bill['repeat_freq']], (string) ($bill['skip'] + 1))); + Log::debug(sprintf('Amount per year is %s (%s * %s / %s)', $yearAmount, $avg, $multiplies[$bill['repeat_freq']], (string) ($bill['skip'] + 1))); // per period: $division = [ @@ -272,8 +275,8 @@ class IndexController extends Controller */ public function setOrder(Request $request, Bill $bill): JsonResponse { - $objectGroupTitle = (string)$request->get('objectGroupTitle'); - $newOrder = (int)$request->get('order'); + $objectGroupTitle = (string) $request->get('objectGroupTitle'); + $newOrder = (int) $request->get('order'); $this->repository->setOrder($bill, $newOrder); if ('' !== $objectGroupTitle) { $this->repository->setObjectGroup($bill, $objectGroupTitle); diff --git a/app/Http/Controllers/Bill/ShowController.php b/app/Http/Controllers/Bill/ShowController.php index 3a42d484ce..dbcfb83502 100644 --- a/app/Http/Controllers/Bill/ShowController.php +++ b/app/Http/Controllers/Bill/ShowController.php @@ -63,7 +63,7 @@ class ShowController 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->repository = app(BillRepositoryInterface::class); @@ -84,7 +84,7 @@ class ShowController extends Controller { $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])); } @@ -94,7 +94,7 @@ class ShowController 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])); } @@ -110,7 +110,7 @@ class ShowController extends Controller // file the rule(s) $ruleEngine->fire(); - $request->session()->flash('success', (string)trans_choice('firefly.rescanned_bill', $total)); + $request->session()->flash('success', (string) trans_choice('firefly.rescanned_bill', $total)); app('preferences')->mark(); return redirect(route('bills.show', [$bill->id])); @@ -123,7 +123,9 @@ class ShowController extends Controller * @param Bill $bill * * @return Factory|View - * @throws FireflyException + * @throws \FireflyIII\Exceptions\FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function show(Request $request, Bill $bill) { @@ -135,8 +137,8 @@ class ShowController 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->repository->getYearAverage($bill, $start); $overallAverage = $this->repository->getOverallAverage($bill); $manager = new Manager(); diff --git a/app/Http/Controllers/Budget/AvailableBudgetController.php b/app/Http/Controllers/Budget/AvailableBudgetController.php index 397f87f3c5..55e5bfbc19 100644 --- a/app/Http/Controllers/Budget/AvailableBudgetController.php +++ b/app/Http/Controllers/Budget/AvailableBudgetController.php @@ -59,7 +59,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-pie-chart'); $this->abRepository = app(AvailableBudgetRepositoryInterface::class); $this->currencyRepos = app(CurrencyRepositoryInterface::class); @@ -96,7 +96,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')); } @@ -128,7 +128,7 @@ class AvailableBudgetController extends Controller return true; } ); - $page = (int)($request->get('page') ?? 1); + $page = (int) ($request->get('page') ?? 1); return view('budgets.available-budgets.create-alternative', compact('start', 'end', 'page', 'currencies')); } @@ -140,7 +140,7 @@ class AvailableBudgetController extends Controller */ public function delete(Request $request) { - $id = (int)$request->get('id'); + $id = (int) $request->get('id'); if (0 !== $id) { $availableBudget = $this->abRepository->findById($id); if (null !== $availableBudget) { @@ -162,7 +162,7 @@ class AvailableBudgetController extends Controller */ public function edit(AvailableBudget $availableBudget, Carbon $start, Carbon $end) { - $availableBudget->amount = number_format((float)$availableBudget->amount, $availableBudget->transactionCurrency->decimal_places, '.', ''); + $availableBudget->amount = number_format((float) $availableBudget->amount, $availableBudget->transactionCurrency->decimal_places, '.', ''); return view('budgets.available-budgets.edit', compact('availableBudget', 'start', 'end')); } @@ -171,6 +171,8 @@ class AvailableBudgetController extends Controller * @param Request $request * * @return RedirectResponse|Redirector + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function store(Request $request) { @@ -185,7 +187,7 @@ class AvailableBudgetController extends Controller } // validate amount - $amount = (string)$request->get('amount'); + $amount = (string) $request->get('amount'); if ('' === $amount) { session()->flash('error', trans('firefly.invalid_amount')); @@ -198,7 +200,7 @@ class AvailableBudgetController extends Controller } // 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')); @@ -239,7 +241,7 @@ class AvailableBudgetController extends Controller public function update(Request $request, AvailableBudget $availableBudget, Carbon $start, Carbon $end) { // validate amount - $amount = (string)$request->get('amount'); + $amount = (string) $request->get('amount'); if ('' === $amount) { session()->flash('error', trans('firefly.invalid_amount')); diff --git a/app/Http/Controllers/Budget/BudgetLimitController.php b/app/Http/Controllers/Budget/BudgetLimitController.php index edf13e6fbf..71b918fa86 100644 --- a/app/Http/Controllers/Budget/BudgetLimitController.php +++ b/app/Http/Controllers/Budget/BudgetLimitController.php @@ -65,7 +65,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-pie-chart'); $this->repository = app(BudgetRepositoryInterface::class); $this->opsRepository = app(OperationsRepositoryInterface::class); @@ -130,14 +130,14 @@ class BudgetLimitController extends Controller { Log::debug('Going to store new budget-limit.', $request->all()); // first search for existing one and update it if necessary. - $currency = $this->currencyRepos->find((int)$request->get('transaction_currency_id')); - $budget = $this->repository->find((int)$request->get('budget_id')); + $currency = $this->currencyRepos->find((int) $request->get('transaction_currency_id')); + $budget = $this->repository->find((int) $request->get('budget_id')); if (null === $currency || null === $budget) { throw new FireflyException('No valid currency or budget.'); } $start = Carbon::createFromFormat('Y-m-d', $request->get('start')); $end = Carbon::createFromFormat('Y-m-d', $request->get('end')); - $amount = (string)$request->get('amount'); + $amount = (string) $request->get('amount'); $start->startOfDay(); $end->startOfDay(); @@ -156,7 +156,7 @@ class BudgetLimitController extends Controller $limit = $this->blRepository->store( [ 'budget_id' => $request->get('budget_id'), - 'currency_id' => (int)$request->get('transaction_currency_id'), + 'currency_id' => (int) $request->get('transaction_currency_id'), 'start_date' => $start, 'end_date' => $end, 'amount' => $amount, @@ -171,7 +171,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']); @@ -192,7 +192,7 @@ class BudgetLimitController extends Controller */ public function update(Request $request, BudgetLimit $budgetLimit): JsonResponse { - $amount = (string)$request->get('amount'); + $amount = (string) $request->get('amount'); if ('' === $amount) { $amount = '0'; } @@ -210,12 +210,12 @@ class BudgetLimitController extends Controller $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']); // left per day formatted. - $array['amount'] = number_format((float)$limit['amount'], $limit->transactionCurrency->decimal_places, '.', ''); + $array['amount'] = number_format((float) $limit['amount'], $limit->transactionCurrency->decimal_places, '.', ''); $array['left_per_day_formatted'] = app('amount')->formatAnything($limit->transactionCurrency, $array['left_per_day']); return response()->json($array); diff --git a/app/Http/Controllers/Budget/CreateController.php b/app/Http/Controllers/Budget/CreateController.php index a7e898f77a..63aaa7db44 100644 --- a/app/Http/Controllers/Budget/CreateController.php +++ b/app/Http/Controllers/Budget/CreateController.php @@ -52,7 +52,7 @@ class CreateController 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-pie-chart'); $this->repository = app(BudgetRepositoryInterface::class); $this->attachments = app(AttachmentHelperInterface::class); @@ -75,23 +75,23 @@ class CreateController extends Controller // 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'), + 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'), + '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, + '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); @@ -101,7 +101,7 @@ class CreateController extends Controller $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', 'autoBudgetTypes', 'autoBudgetPeriods')); } @@ -120,7 +120,7 @@ class CreateController extends Controller $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(); // store attachment(s): @@ -129,7 +129,7 @@ class CreateController extends Controller $this->attachments->saveAttachmentsForModel($budget, $files); } if (null !== $files && auth()->user()->hasRole('demo')) { - session()->flash('info', (string)trans('firefly.no_att_demo_user')); + session()->flash('info', (string) trans('firefly.no_att_demo_user')); } if (count($this->attachments->getMessages()->get('attachments')) > 0) { @@ -138,7 +138,7 @@ class CreateController extends Controller $redirect = redirect($this->getPreviousUri('budgets.create.uri')); - if (1 === (int)$request->get('create_another')) { + if (1 === (int) $request->get('create_another')) { $request->session()->put('budgets.create.fromStore', true); diff --git a/app/Http/Controllers/Budget/DeleteController.php b/app/Http/Controllers/Budget/DeleteController.php index 43d23a49cb..56a2ad3da7 100644 --- a/app/Http/Controllers/Budget/DeleteController.php +++ b/app/Http/Controllers/Budget/DeleteController.php @@ -52,7 +52,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-pie-chart'); $this->repository = app(BudgetRepositoryInterface::class); @@ -70,7 +70,7 @@ class DeleteController extends Controller */ 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'); @@ -90,7 +90,7 @@ class DeleteController extends Controller { $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 1a5c7441b7..d2c77668ea 100644 --- a/app/Http/Controllers/Budget/EditController.php +++ b/app/Http/Controllers/Budget/EditController.php @@ -56,7 +56,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-pie-chart'); $this->repository = app(BudgetRepositoryInterface::class); $this->attachments = app(AttachmentHelperInterface::class); @@ -76,34 +76,34 @@ class EditController extends Controller */ 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'), + 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'), + '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, - 'auto_budget_currency_id' => $hasOldInput ? (int)$request->old('auto_budget_currency_id') : $currency->id, + 'active' => $hasOldInput ? (bool) $request->old('active') : $budget->active, + 'auto_budget_currency_id' => $hasOldInput ? (int) $request->old('auto_budget_currency_id') : $currency->id, ]; if ($autoBudget) { $amount = $hasOldInput ? $request->old('auto_budget_amount') : $autoBudget->amount; - $preFilled['auto_budget_amount'] = number_format((float)$amount, $autoBudget->transactionCurrency->decimal_places, '.', ''); + $preFilled['auto_budget_amount'] = number_format((float) $amount, $autoBudget->transactionCurrency->decimal_places, '.', ''); } // put previous url in session if not redirect from store (not "return_to_edit"). @@ -129,7 +129,7 @@ class EditController extends Controller $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(); @@ -141,14 +141,14 @@ class EditController extends Controller $this->attachments->saveAttachmentsForModel($budget, $files); } if (null !== $files && auth()->user()->hasRole('demo')) { - session()->flash('info', (string)trans('firefly.no_att_demo_user')); + session()->flash('info', (string) trans('firefly.no_att_demo_user')); } if (count($this->attachments->getMessages()->get('attachments')) > 0) { $request->session()->flash('info', $this->attachments->getMessages()->get('attachments')); } - if (1 === (int)$request->get('return_to_edit')) { + if (1 === (int) $request->get('return_to_edit')) { $request->session()->put('budgets.edit.fromUpdate', true); diff --git a/app/Http/Controllers/Budget/IndexController.php b/app/Http/Controllers/Budget/IndexController.php index 1342b0e36d..6986b402d7 100644 --- a/app/Http/Controllers/Budget/IndexController.php +++ b/app/Http/Controllers/Budget/IndexController.php @@ -68,7 +68,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-pie-chart'); $this->repository = app(BudgetRepositoryInterface::class); $this->opsRepository = app(OperationsRepositoryInterface::class); @@ -92,13 +92,16 @@ class IndexController extends Controller * * @return Factory|View * @throws FireflyException + * @throws \JsonException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function index(Request $request, Carbon $start = null, Carbon $end = null) { Log::debug('Start of IndexController::index()'); // collect some basic vars: - $range = (string)app('preferences')->get('viewRange', '1M')->data; + $range = (string) app('preferences')->get('viewRange', '1M')->data; $start = $start ?? session('start', Carbon::now()->startOfMonth()); $end = $end ?? app('navigation')->endOfPeriod($start, $range); $defaultCurrency = app('amount')->getDefaultCurrency(); @@ -131,7 +134,7 @@ class IndexController extends Controller // number of days for consistent budgeting. $activeDaysPassed = $this->activeDaysPassed($start, $end); // see method description. - $activeDaysLeft = $this->activeDaysLeft($start, $end); // see method description. + $activeDaysLeft = $this->activeDaysLeft($start, $end); // see method description. // get all inactive budgets, and simply list them: $inactive = $this->repository->getInactiveBudgets(); @@ -207,9 +210,9 @@ class IndexController extends Controller $currency = $limit->transactionCurrency ?? $defaultCurrency; $array['budgeted'][] = [ 'id' => $limit->id, - 'amount' => number_format((float)$limit->amount, $currency->decimal_places, '.', ''), - 'start_date' => $limit->start_date->formatLocalized($this->monthAndDayFormat), - 'end_date' => $limit->end_date->formatLocalized($this->monthAndDayFormat), + 'amount' => number_format((float) $limit->amount, $currency->decimal_places, '.', ''), + 'start_date' => $limit->start_date->isoFormat($this->monthAndDayFormat), + 'end_date' => $limit->end_date->isoFormat($this->monthAndDayFormat), 'in_range' => $limit->start_date->isSameDay($start) && $limit->end_date->isSameDay($end), 'currency_id' => $currency->id, 'currency_symbol' => $currency->symbol, @@ -307,7 +310,7 @@ class IndexController extends Controller $budgetIds = $request->get('budgetIds'); foreach ($budgetIds as $index => $budgetId) { - $budgetId = (int)$budgetId; + $budgetId = (int) $budgetId; $budget = $repository->find($budgetId); if (null !== $budget) { Log::debug(sprintf('Set budget #%d ("%s") to position %d', $budget->id, $budget->name, $index + 1)); diff --git a/app/Http/Controllers/Budget/ShowController.php b/app/Http/Controllers/Budget/ShowController.php index 3d9d7f774d..a92989f85d 100644 --- a/app/Http/Controllers/Budget/ShowController.php +++ b/app/Http/Controllers/Budget/ShowController.php @@ -60,7 +60,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-pie-chart'); $this->journalRepos = app(JournalRepositoryInterface::class); $this->repository = app(BudgetRepositoryInterface::class); @@ -79,6 +79,9 @@ class ShowController extends Controller * * @return Factory|View * @throws FireflyException + * @throws \JsonException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function noBudget(Request $request, Carbon $start = null, Carbon $end = null) { @@ -88,15 +91,15 @@ class ShowController extends Controller $end = $end ?? session('end'); $subTitle = trans( 'firefly.without_budget_between', - ['start' => $start->formatLocalized($this->monthAndDayFormat), 'end' => $end->formatLocalized($this->monthAndDayFormat)] + ['start' => $start->isoFormat($this->monthAndDayFormat), 'end' => $end->isoFormat($this->monthAndDayFormat)] ); // get first journal ever to set off the budget period overview. $first = $this->journalRepos->firstNull(); $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); @@ -115,16 +118,18 @@ class ShowController extends Controller * * @return Factory|View * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ 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 = today(config('app.timezone')); - $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); @@ -144,14 +149,17 @@ class ShowController extends Controller * * @return Factory|View * @throws FireflyException + * @throws \JsonException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function show(Request $request, Budget $budget) { /** @var Carbon $allStart */ $allStart = session('first', Carbon::now()->startOfYear()); $allEnd = today(); - $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; $attachments = $this->repository->getAttachments($budget); @@ -165,7 +173,7 @@ class ShowController extends Controller $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', 'attachments', 'budget', 'repetition', 'groups', 'subTitle')); } @@ -179,6 +187,9 @@ class ShowController extends Controller * * @return Factory|View * @throws FireflyException + * @throws \JsonException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function showByBudgetLimit(Request $request, Budget $budget, BudgetLimit $budgetLimit) { @@ -186,14 +197,14 @@ class ShowController extends Controller throw new FireflyException('This budget limit is not part of this budget.'); } - $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), + 'start' => $budgetLimit->start_date->isoFormat($this->monthAndDayFormat), + 'end' => $budgetLimit->end_date->isoFormat($this->monthAndDayFormat), 'currency' => $budgetLimit->transactionCurrency->name, ] ); diff --git a/app/Http/Controllers/Category/CreateController.php b/app/Http/Controllers/Category/CreateController.php index c81dc9df32..3ebd4b6c10 100644 --- a/app/Http/Controllers/Category/CreateController.php +++ b/app/Http/Controllers/Category/CreateController.php @@ -53,7 +53,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-bookmark'); $this->repository = app(CategoryRepositoryInterface::class); $this->attachments = app(AttachmentHelperInterface::class); @@ -76,7 +76,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')); } @@ -94,7 +94,7 @@ class CreateController extends Controller $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(); // store attachment(s): @@ -103,7 +103,7 @@ class CreateController extends Controller $this->attachments->saveAttachmentsForModel($category, $files); } if (null !== $files && auth()->user()->hasRole('demo')) { - session()->flash('info', (string)trans('firefly.no_att_demo_user')); + session()->flash('info', (string) trans('firefly.no_att_demo_user')); } if (count($this->attachments->getMessages()->get('attachments')) > 0) { @@ -111,7 +111,7 @@ class CreateController extends Controller } $redirect = redirect(route('categories.index')); - if (1 === (int)$request->get('create_another')) { + if (1 === (int) $request->get('create_another')) { $request->session()->put('categories.create.fromStore', true); diff --git a/app/Http/Controllers/Category/DeleteController.php b/app/Http/Controllers/Category/DeleteController.php index 75e3b4b77c..5648f90e81 100644 --- a/app/Http/Controllers/Category/DeleteController.php +++ b/app/Http/Controllers/Category/DeleteController.php @@ -51,7 +51,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-bookmark'); $this->repository = app(CategoryRepositoryInterface::class); @@ -69,7 +69,7 @@ class DeleteController extends Controller */ 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'); @@ -80,7 +80,7 @@ class DeleteController extends Controller /** * Destroy a category. * - * @param Request $request + * @param Request $request * @param Category $category * * @return RedirectResponse|Redirector @@ -90,7 +90,7 @@ class DeleteController extends Controller $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 ab92c207cb..420c7c4974 100644 --- a/app/Http/Controllers/Category/EditController.php +++ b/app/Http/Controllers/Category/EditController.php @@ -54,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-bookmark'); $this->repository = app(CategoryRepositoryInterface::class); $this->attachments = app(AttachmentHelperInterface::class); @@ -74,7 +74,7 @@ class EditController extends Controller */ 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')) { @@ -102,7 +102,7 @@ class EditController extends Controller $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(); // store new attachment(s): @@ -111,7 +111,7 @@ class EditController extends Controller $this->attachments->saveAttachmentsForModel($category, $files); } if (null !== $files && auth()->user()->hasRole('demo')) { - session()->flash('info', (string)trans('firefly.no_att_demo_user')); + session()->flash('info', (string) trans('firefly.no_att_demo_user')); } if (count($this->attachments->getMessages()->get('attachments')) > 0) { @@ -119,7 +119,7 @@ class EditController extends Controller } $redirect = redirect($this->getPreviousUri('categories.edit.uri')); - if (1 === (int)$request->get('return_to_edit')) { + if (1 === (int) $request->get('return_to_edit')) { $request->session()->put('categories.edit.fromUpdate', true); diff --git a/app/Http/Controllers/Category/IndexController.php b/app/Http/Controllers/Category/IndexController.php index a0bbfd6b00..ee07147caa 100644 --- a/app/Http/Controllers/Category/IndexController.php +++ b/app/Http/Controllers/Category/IndexController.php @@ -52,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-bookmark'); $this->repository = app(CategoryRepositoryInterface::class); @@ -68,11 +68,13 @@ class IndexController extends Controller * * @return Factory|View * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ 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 fa681db856..dcef802333 100644 --- a/app/Http/Controllers/Category/NoCategoryController.php +++ b/app/Http/Controllers/Category/NoCategoryController.php @@ -58,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-bookmark'); $this->journalRepos = app(JournalRepositoryInterface::class); @@ -76,6 +76,9 @@ class NoCategoryController extends Controller * * @return Factory|View * @throws FireflyException + * @throws \JsonException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function show(Request $request, Carbon $start = null, Carbon $end = null) { @@ -84,11 +87,11 @@ 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)] + ['start' => $start->isoFormat($this->monthAndDayFormat), 'end' => $end->isoFormat($this->monthAndDayFormat)] ); $periods = $this->getNoCategoryPeriodOverview($start); @@ -114,6 +117,8 @@ class NoCategoryController extends Controller * * @return Factory|View * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function showAll(Request $request) { @@ -121,10 +126,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 = today(config('app.timezone')); diff --git a/app/Http/Controllers/Category/ShowController.php b/app/Http/Controllers/Category/ShowController.php index 80325cdb26..a3eb24c391 100644 --- a/app/Http/Controllers/Category/ShowController.php +++ b/app/Http/Controllers/Category/ShowController.php @@ -59,7 +59,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-bookmark'); $this->repository = app(CategoryRepositoryInterface::class); @@ -78,6 +78,9 @@ class ShowController extends Controller * * @return Factory|View * @throws FireflyException + * @throws \JsonException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function show(Request $request, Category $category, Carbon $start = null, Carbon $end = null) { @@ -86,16 +89,16 @@ class ShowController extends Controller /** @var Carbon $end */ $end = $end ?? session('end', Carbon::now()->endOfMonth()); $subTitleIcon = 'fa-bookmark'; - $page = (int)$request->get('page'); + $page = (int) $request->get('page'); $attachments = $this->repository->getAttachments($category); - $pageSize = (int)app('preferences')->get('listPageSize', 50)->data; + $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')]); $subTitle = trans( 'firefly.journals_in_period_for_category', - ['name' => $category->name, 'start' => $start->formatLocalized($this->monthAndDayFormat), - 'end' => $end->formatLocalized($this->monthAndDayFormat),] + ['name' => $category->name, 'start' => $start->isoFormat($this->monthAndDayFormat), + 'end' => $end->isoFormat($this->monthAndDayFormat),] ); /** @var GroupCollectorInterface $collector */ @@ -118,18 +121,20 @@ class ShowController extends Controller * * @return Factory|View * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function showAll(Request $request, Category $category) { // default values: $subTitleIcon = 'fa-bookmark'; - $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 ?? today(config('app.timezone')); diff --git a/app/Http/Controllers/Chart/AccountController.php b/app/Http/Controllers/Chart/AccountController.php index b8b03d2a7c..806b4b8a04 100644 --- a/app/Http/Controllers/Chart/AccountController.php +++ b/app/Http/Controllers/Chart/AccountController.php @@ -50,14 +50,9 @@ class AccountController extends Controller { use DateCalculation, AugumentData, ChartGeneration; - /** @var GeneratorInterface Chart generation methods. */ - protected $generator; - - /** @var AccountRepositoryInterface Account repository. */ - private $accountRepository; - - /** @var CurrencyRepositoryInterface */ - private $currencyRepository; + protected GeneratorInterface $generator; + private AccountRepositoryInterface $accountRepository; + private CurrencyRepositoryInterface $currencyRepository; /** * AccountController constructor. @@ -117,10 +112,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. @@ -132,7 +127,7 @@ class AccountController extends Controller $tempData[] = [ 'name' => $accountNames[$accountId], 'difference' => $diff, - 'diff_float' => (float)$diff, + 'diff_float' => (float) $diff, 'currency_id' => $currencyId, ]; } @@ -151,7 +146,7 @@ class AccountController extends Controller foreach ($currencies as $currencyId => $currency) { $dataSet = [ - 'label' => (string)trans('firefly.spent'), + 'label' => (string) trans('firefly.spent'), 'type' => 'bar', 'currency_symbol' => $currency->symbol, 'currency_code' => $currency->code, @@ -180,6 +175,7 @@ class AccountController extends Controller * @param Account $account * * @return JsonResponse + * @throws JsonException */ public function expenseBudgetAll(AccountRepositoryInterface $repository, Account $account): JsonResponse { @@ -197,7 +193,6 @@ class AccountController extends Controller * @param Carbon $end * * @return JsonResponse - * @throws JsonException */ public function expenseBudget(Account $account, Carbon $start, Carbon $end): JsonResponse { @@ -218,7 +213,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 (!array_key_exists($key, $result)) { @@ -238,7 +233,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'], 'currency_code' => $row['currency_code']]; } @@ -255,6 +250,7 @@ class AccountController extends Controller * @param Account $account * * @return JsonResponse + * @throws JsonException */ public function expenseCategoryAll(AccountRepositoryInterface $repository, Account $account): JsonResponse { @@ -272,7 +268,6 @@ class AccountController extends Controller * @param Carbon $end * * @return JsonResponse - * @throws JsonException */ public function expenseCategory(Account $account, Carbon $start, Carbon $end): JsonResponse { @@ -298,7 +293,7 @@ class AccountController extends Controller if (!array_key_exists($key, $result)) { $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'], 'currency_code' => $journal['currency_code'], @@ -311,7 +306,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'], 'currency_code' => $row['currency_code']]; } @@ -328,6 +323,9 @@ class AccountController extends Controller * * @return JsonResponse * @throws FireflyException + * @throws JsonException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function frontpage(AccountRepositoryInterface $repository): JsonResponse { @@ -353,6 +351,7 @@ class AccountController extends Controller * @param Account $account * * @return JsonResponse + * @throws JsonException */ public function incomeCategoryAll(AccountRepositoryInterface $repository, Account $account): JsonResponse { @@ -370,7 +369,6 @@ class AccountController extends Controller * @param Carbon $end * * @return JsonResponse - * @throws JsonException */ public function incomeCategory(Account $account, Carbon $start, Carbon $end): JsonResponse { @@ -410,7 +408,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'], 'currency_code' => $row['currency_code']]; } $data = $this->generator->multiCurrencyPieChart($chartData); @@ -440,7 +438,7 @@ class AccountController extends Controller $cache->addProperty($end); $cache->addProperty($account->id); if ($cache->has()) { - return response()->json($cache->get()); + //return response()->json($cache->get()); } $currencies = $this->accountRepository->getUsedCurrencies($account); @@ -487,14 +485,14 @@ class AccountController extends Controller break; case '1D': // per day the entire period, balance for every day. - $format = (string)trans('config.month_and_day', [], $locale); + $format = (string) trans('config.month_and_day_js', [], $locale); $range = app('steam')->balanceInRange($account, $start, $end, $currency); $previous = array_values($range)[0]; while ($end >= $current) { $theDate = $current->format('Y-m-d'); $balance = $range[$theDate] ?? $previous; - $label = $current->formatLocalized($format); - $entries[$label] = (float)$balance; + $label = $current->isoFormat($format); + $entries[$label] = (float) $balance; $previous = $balance; $current->addDay(); } @@ -504,7 +502,7 @@ class AccountController extends Controller case '1M': case '1Y': while ($end >= $current) { - $balance = (float)app('steam')->balance($account, $current, $currency); + $balance = (float) app('steam')->balance($account, $current, $currency); $label = app('navigation')->periodShow($current, $step); $entries[$label] = $balance; $current = app('navigation')->addPeriod($current, $step, 0); @@ -522,11 +520,13 @@ class AccountController extends Controller * * See reference nr. 55 * - * @param Carbon $start - * @param Carbon $end * @param Collection $accounts * + * @param Carbon $start + * @param Carbon $end * @return JsonResponse + * @throws FireflyException + * @throws JsonException */ public function report(Collection $accounts, Carbon $start, Carbon $end): JsonResponse { @@ -571,10 +571,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. @@ -586,7 +586,7 @@ class AccountController extends Controller $tempData[] = [ 'name' => $accountNames[$accountId], 'difference' => $diff, - 'diff_float' => (float)$diff, + 'diff_float' => (float) $diff, 'currency_id' => $currencyId, ]; } @@ -605,7 +605,7 @@ class AccountController extends Controller foreach ($currencies as $currencyId => $currency) { $dataSet = [ - 'label' => (string)trans('firefly.earned'), + 'label' => (string) trans('firefly.earned'), 'type' => 'bar', 'currency_symbol' => $currency->symbol, 'currency_code' => $currency->code, diff --git a/app/Http/Controllers/Chart/BillController.php b/app/Http/Controllers/Chart/BillController.php index b857e1a85b..6ba30c5dec 100644 --- a/app/Http/Controllers/Chart/BillController.php +++ b/app/Http/Controllers/Chart/BillController.php @@ -58,7 +58,6 @@ class BillController extends Controller * @param BillRepositoryInterface $repository * * @return JsonResponse - * @throws JsonException */ public function frontpage(BillRepositoryInterface $repository): JsonResponse { @@ -76,18 +75,18 @@ class BillController extends Controller $chartData = []; $currencies = []; - $paid = $repository->getBillsPaidInRangePerCurrency($start, $end); // will be a negative amount. + $paid = $repository->getBillsPaidInRangePerCurrency($start, $end); // will be a negative amount. $unpaid = $repository->getBillsUnpaidInRangePerCurrency($start, $end); // will be a positive amount. foreach ($paid as $currencyId => $amount) { $currencies[$currencyId] = $currencies[$currencyId] ?? $currencyRepository->find($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, 'currency_code' => $currencies[$currencyId]->code]; } foreach ($unpaid as $currencyId => $amount) { $currencies[$currencyId] = $currencies[$currencyId] ?? $currencyRepository->find($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, 'currency_code' => $currencies[$currencyId]->code]; } @@ -104,7 +103,7 @@ class BillController extends Controller * @param Bill $bill * * @return JsonResponse - * @throws JsonException + * @throws \FireflyIII\Exceptions\FireflyException */ public function single(Bill $bill): JsonResponse { @@ -136,16 +135,16 @@ class BillController extends Controller ); $chartData = [ - ['type' => 'line', 'label' => (string)trans('firefly.min-amount'), 'currency_symbol' => $bill->transactionCurrency->symbol, + ['type' => 'line', 'label' => (string) trans('firefly.min-amount'), 'currency_symbol' => $bill->transactionCurrency->symbol, 'currency_code' => $bill->transactionCurrency->code, 'entries' => []], - ['type' => 'line', 'label' => (string)trans('firefly.max-amount'), 'currency_symbol' => $bill->transactionCurrency->symbol, + ['type' => 'line', 'label' => (string) trans('firefly.max-amount'), 'currency_symbol' => $bill->transactionCurrency->symbol, 'currency_code' => $bill->transactionCurrency->code, 'entries' => []], - ['type' => 'bar', 'label' => (string)trans('firefly.journal-amount'), 'currency_symbol' => $bill->transactionCurrency->symbol, + ['type' => 'bar', 'label' => (string) trans('firefly.journal-amount'), 'currency_symbol' => $bill->transactionCurrency->symbol, 'currency_code' => $bill->transactionCurrency->code, 'entries' => []], ]; foreach ($journals as $journal) { - $date = $journal['date']->formatLocalized((string)trans('config.month_and_day', [], $locale)); + $date = $journal['date']->isoFormat((string) trans('config.month_and_day_js', [], $locale)); $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 d55ebbbe19..58bb2ece98 100644 --- a/app/Http/Controllers/Chart/BudgetController.php +++ b/app/Http/Controllers/Chart/BudgetController.php @@ -85,7 +85,6 @@ class BudgetController extends Controller * @param Budget $budget * * @return JsonResponse - * @throws JsonException */ public function budget(Budget $budget): JsonResponse { @@ -154,7 +153,6 @@ class BudgetController extends Controller * @return JsonResponse * * @throws FireflyException - * @throws JsonException */ public function budgetLimit(Budget $budget, BudgetLimit $budgetLimit): JsonResponse { @@ -182,14 +180,14 @@ class BudgetController extends Controller while ($start <= $end) { $current = clone $start; $expenses = $this->opsRepository->sumExpenses($current, $current, null, $budgetCollection, $currency); - $spent = $expenses[(int)$currency->id]['sum'] ?? '0'; + $spent = $expenses[(int) $currency->id]['sum'] ?? '0'; $amount = bcadd($amount, $spent); - $format = $start->formatLocalized((string)trans('config.month_and_day', [], $locale)); + $format = $start->isoFormat((string) trans('config.month_and_day_js', [], $locale)); $entries[$format] = $amount; $start->addDay(); } - $data = $this->generator->singleSet((string)trans('firefly.left'), $entries); + $data = $this->generator->singleSet((string) trans('firefly.left'), $entries); // add currency symbol from budget limit: $data['datasets'][0]['currency_symbol'] = $budgetLimit->transactionCurrency->symbol; $data['datasets'][0]['currency_code'] = $budgetLimit->transactionCurrency->code; @@ -205,7 +203,6 @@ class BudgetController extends Controller * @param BudgetLimit|null $budgetLimit * * @return JsonResponse - * @throws JsonException */ public function expenseAsset(Budget $budget, ?BudgetLimit $budgetLimit = null): JsonResponse { @@ -238,7 +235,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'], @@ -251,7 +248,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] = [ @@ -274,7 +271,6 @@ class BudgetController extends Controller * @param BudgetLimit|null $budgetLimit * * @return JsonResponse - * @throws JsonException */ public function expenseCategory(Budget $budget, ?BudgetLimit $budgetLimit = null): JsonResponse { @@ -317,7 +313,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'], @@ -339,7 +335,6 @@ class BudgetController extends Controller * @param BudgetLimit|null $budgetLimit * * @return JsonResponse - * @throws JsonException */ public function expenseExpense(Budget $budget, ?BudgetLimit $budgetLimit = null): JsonResponse { @@ -383,7 +378,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] = [ @@ -403,7 +398,6 @@ class BudgetController extends Controller * Shows a budget list with spent/left/overspent. * * @return JsonResponse - * @throws JsonException */ public function frontpage(): JsonResponse { @@ -441,7 +435,6 @@ class BudgetController extends Controller * @param Carbon $end * * @return JsonResponse - * @throws JsonException */ public function period(Budget $budget, TransactionCurrency $currency, Collection $accounts, Carbon $start, Carbon $end): JsonResponse { @@ -460,14 +453,14 @@ 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, 'currency_code' => $currency->code, ], [ - 'label' => (string)trans('firefly.box_budgeted_in_currency', ['currency' => $currency->name]), + 'label' => (string) trans('firefly.box_budgeted_in_currency', ['currency' => $currency->name]), 'type' => 'bar', 'currency_symbol' => $currency->symbol, 'currency_code' => $currency->code, @@ -478,7 +471,7 @@ class BudgetController extends Controller $currentStart = clone $start; while ($currentStart <= $end) { $currentStart = app('navigation')->startOfPeriod($currentStart, $preferredRange); - $title = $currentStart->formatLocalized($titleFormat); + $title = $currentStart->isoFormat($titleFormat); $currentEnd = app('navigation')->endOfPeriod($currentStart, $preferredRange); // default limit is no limit: @@ -490,13 +483,13 @@ class BudgetController extends Controller // get budget limit in this period for this currency. $limit = $this->blRepository->find($budget, $currency, $currentStart, $currentEnd); if (null !== $limit) { - $chartData[1]['entries'][$title] = round((float)$limit->amount, $currency->decimal_places); + $chartData[1]['entries'][$title] = round((float) $limit->amount, $currency->decimal_places); } // get spent amount in this period for this currency. $sum = $this->opsRepository->sumExpenses($currentStart, $currentEnd, $accounts, new Collection([$budget]), $currency); $amount = app('steam')->positive($sum[$currency->id]['sum'] ?? '0'); - $chartData[0]['entries'][$title] = round((float)$amount, $currency->decimal_places); + $chartData[0]['entries'][$title] = round((float) $amount, $currency->decimal_places); $currentStart = clone $currentEnd; $currentStart->addDay()->startOfDay(); @@ -517,7 +510,6 @@ class BudgetController extends Controller * @param Carbon $end * * @return JsonResponse - * @throws JsonException */ public function periodNoBudget(TransactionCurrency $currency, Collection $accounts, Carbon $start, Carbon $end): JsonResponse { @@ -539,14 +531,14 @@ class BudgetController extends Controller $preferredRange = app('navigation')->preferredRangeFormat($start, $end); while ($currentStart <= $end) { $currentEnd = app('navigation')->endOfPeriod($currentStart, $preferredRange); - $title = $currentStart->formatLocalized($titleFormat); + $title = $currentStart->isoFormat($titleFormat); $sum = $this->nbRepository->sumExpenses($currentStart, $currentEnd, $accounts, $currency); $amount = app('steam')->positive($sum[$currency->id]['sum'] ?? '0'); - $chartData[$title] = round((float)$amount, $currency->decimal_places); + $chartData[$title] = round((float) $amount, $currency->decimal_places); $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 69bf517433..da0bf7db31 100644 --- a/app/Http/Controllers/Chart/BudgetReportController.php +++ b/app/Http/Controllers/Chart/BudgetReportController.php @@ -1,4 +1,5 @@ - sprintf( '%s (%s)', - (string)trans('firefly.spent_in_specific_budget', ['budget' => $budget->name]), + (string) trans('firefly.spent_in_specific_budget', ['budget' => $budget->name]), $currency['currency_name'] ), 'type' => 'bar', @@ -212,7 +213,7 @@ class BudgetReportController extends Controller foreach ($currency['budgets'] as $currentBudget) { foreach ($currentBudget['transaction_journals'] as $journal) { - $key = $journal['date']->formatLocalized($format); + $key = $journal['date']->isoFormat($format); $amount = app('steam')->positive($journal['amount']); $chartData[$spentKey]['entries'][$key] = $chartData[$spentKey]['entries'][$key] ?? '0'; $chartData[$spentKey]['entries'][$key] = bcadd($chartData[$spentKey]['entries'][$key], $amount); @@ -239,7 +240,7 @@ class BudgetReportController extends Controller $currentStart = clone $start; while ($currentStart <= $end) { $currentEnd = app('navigation')->endOfPeriod($currentStart, $preferredRange); - $key = $currentStart->formatLocalized($format); + $key = $currentStart->isoFormat($format); $return[$key] = '0'; $currentStart = clone $currentEnd; $currentStart->addDay()->startOfDay(); diff --git a/app/Http/Controllers/Chart/CategoryController.php b/app/Http/Controllers/Chart/CategoryController.php index 09c56ad6e5..ffe0194b98 100644 --- a/app/Http/Controllers/Chart/CategoryController.php +++ b/app/Http/Controllers/Chart/CategoryController.php @@ -71,7 +71,8 @@ class CategoryController extends Controller * * @return JsonResponse * @throws FireflyException - * @throws JsonException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function all(Category $category): JsonResponse { @@ -118,7 +119,6 @@ class CategoryController extends Controller * See reference nr. 60 * * @return JsonResponse - * @throws JsonException */ public function frontPage(): JsonResponse { @@ -151,7 +151,6 @@ class CategoryController extends Controller * @param Carbon $end * * @return JsonResponse - * @throws JsonException */ public function reportPeriod(Category $category, Collection $accounts, Carbon $start, Carbon $end): JsonResponse { @@ -198,7 +197,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); @@ -217,7 +216,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 @@ -225,7 +224,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 @@ -240,7 +239,7 @@ class CategoryController extends Controller $outSet = $expenses[$currencyId]['categories'][$categoryId] ?? ['transaction_journals' => []]; foreach ($outSet['transaction_journals'] as $journal) { $amount = app('steam')->positive($journal['amount']); - $date = $journal['date']->formatLocalized($format); + $date = $journal['date']->isoFormat($format); $chartData[$outKey]['entries'][$date] = $chartData[$outKey]['entries'][$date] ?? '0'; $chartData[$outKey]['entries'][$date] = bcadd($amount, $chartData[$outKey]['entries'][$date]); @@ -249,7 +248,7 @@ class CategoryController extends Controller $inSet = $income[$currencyId]['categories'][$categoryId] ?? ['transaction_journals' => []]; foreach ($inSet['transaction_journals'] as $journal) { $amount = app('steam')->positive($journal['amount']); - $date = $journal['date']->formatLocalized($format); + $date = $journal['date']->isoFormat($format); $chartData[$inKey]['entries'][$date] = $chartData[$inKey]['entries'][$date] ?? '0'; $chartData[$inKey]['entries'][$date] = bcadd($amount, $chartData[$inKey]['entries'][$date]); } @@ -267,7 +266,6 @@ class CategoryController extends Controller * @param Carbon $end * * @return JsonResponse - * @throws JsonException */ public function reportPeriodNoCategory(Collection $accounts, Carbon $start, Carbon $end): JsonResponse { @@ -295,7 +293,8 @@ class CategoryController extends Controller * * @return JsonResponse * @throws FireflyException - * @throws JsonException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function specificPeriod(Category $category, Carbon $date): JsonResponse { diff --git a/app/Http/Controllers/Chart/CategoryReportController.php b/app/Http/Controllers/Chart/CategoryReportController.php index 8e5e359859..84a73c343d 100644 --- a/app/Http/Controllers/Chart/CategoryReportController.php +++ b/app/Http/Controllers/Chart/CategoryReportController.php @@ -265,7 +265,7 @@ class CategoryReportController extends Controller $chartData[$spentKey] = $chartData[$spentKey] ?? [ 'label' => sprintf( '%s (%s)', - (string)trans('firefly.spent_in_specific_category', ['category' => $category->name]), + (string) trans('firefly.spent_in_specific_category', ['category' => $category->name]), $currency['currency_name'] ), 'type' => 'bar', @@ -277,7 +277,7 @@ class CategoryReportController extends Controller foreach ($currency['categories'] as $currentCategory) { foreach ($currentCategory['transaction_journals'] as $journal) { - $key = $journal['date']->formatLocalized($format); + $key = $journal['date']->isoFormat($format); $amount = app('steam')->positive($journal['amount']); $chartData[$spentKey]['entries'][$key] = $chartData[$spentKey]['entries'][$key] ?? '0'; $chartData[$spentKey]['entries'][$key] = bcadd($chartData[$spentKey]['entries'][$key], $amount); @@ -292,7 +292,7 @@ class CategoryReportController extends Controller $chartData[$spentKey] = $chartData[$spentKey] ?? [ 'label' => sprintf( '%s (%s)', - (string)trans('firefly.earned_in_specific_category', ['category' => $category->name]), + (string) trans('firefly.earned_in_specific_category', ['category' => $category->name]), $currency['currency_name'] ), 'type' => 'bar', @@ -304,7 +304,7 @@ class CategoryReportController extends Controller foreach ($currency['categories'] as $currentCategory) { foreach ($currentCategory['transaction_journals'] as $journal) { - $key = $journal['date']->formatLocalized($format); + $key = $journal['date']->isoFormat($format); $amount = app('steam')->positive($journal['amount']); $chartData[$spentKey]['entries'][$key] = $chartData[$spentKey]['entries'][$key] ?? '0'; $chartData[$spentKey]['entries'][$key] = bcadd($chartData[$spentKey]['entries'][$key], $amount); @@ -333,7 +333,7 @@ class CategoryReportController extends Controller $currentStart = clone $start; while ($currentStart <= $end) { $currentEnd = app('navigation')->endOfPeriod($currentStart, $preferredRange); - $key = $currentStart->formatLocalized($format); + $key = $currentStart->isoFormat($format); $return[$key] = '0'; $currentStart = clone $currentEnd; $currentStart->addDay()->startOfDay(); diff --git a/app/Http/Controllers/Chart/DoubleReportController.php b/app/Http/Controllers/Chart/DoubleReportController.php index 13a86622d6..b1f7fa6a08 100644 --- a/app/Http/Controllers/Chart/DoubleReportController.php +++ b/app/Http/Controllers/Chart/DoubleReportController.php @@ -199,7 +199,7 @@ class DoubleReportController extends Controller $chartData[$spentKey] = $chartData[$spentKey] ?? [ 'label' => sprintf( '%s (%s)', - (string)trans('firefly.spent_in_specific_double', ['account' => $name]), + (string) trans('firefly.spent_in_specific_double', ['account' => $name]), $currency['currency_name'] ), 'type' => 'bar', @@ -210,7 +210,7 @@ class DoubleReportController extends Controller ]; foreach ($currency['transaction_journals'] as $journal) { - $key = $journal['date']->formatLocalized($format); + $key = $journal['date']->isoFormat($format); $amount = app('steam')->positive($journal['amount']); $chartData[$spentKey]['entries'][$key] = $chartData[$spentKey]['entries'][$key] ?? '0'; $chartData[$spentKey]['entries'][$key] = bcadd($chartData[$spentKey]['entries'][$key], $amount); @@ -225,7 +225,7 @@ class DoubleReportController extends Controller $chartData[$earnedKey] = $chartData[$earnedKey] ?? [ 'label' => sprintf( '%s (%s)', - (string)trans('firefly.earned_in_specific_double', ['account' => $name]), + (string) trans('firefly.earned_in_specific_double', ['account' => $name]), $currency['currency_name'] ), 'type' => 'bar', @@ -236,7 +236,7 @@ class DoubleReportController extends Controller ]; foreach ($currency['transaction_journals'] as $journal) { - $key = $journal['date']->formatLocalized($format); + $key = $journal['date']->isoFormat($format); $amount = app('steam')->positive($journal['amount']); $chartData[$earnedKey]['entries'][$key] = $chartData[$earnedKey]['entries'][$key] ?? '0'; $chartData[$earnedKey]['entries'][$key] = bcadd($chartData[$earnedKey]['entries'][$key], $amount); @@ -289,7 +289,7 @@ class DoubleReportController extends Controller $currentStart = clone $start; while ($currentStart <= $end) { $currentEnd = app('navigation')->endOfPeriod($currentStart, $preferredRange); - $key = $currentStart->formatLocalized($format); + $key = $currentStart->isoFormat($format); $return[$key] = '0'; $currentStart = clone $currentEnd; $currentStart->addDay()->startOfDay(); diff --git a/app/Http/Controllers/Chart/ExpenseReportController.php b/app/Http/Controllers/Chart/ExpenseReportController.php index 697cfb6ee4..3a30860805 100644 --- a/app/Http/Controllers/Chart/ExpenseReportController.php +++ b/app/Http/Controllers/Chart/ExpenseReportController.php @@ -113,27 +113,27 @@ class ExpenseReportController extends Controller /** @var Account $exp */ $exp = $combination->first(); $chartData[$exp->id . '-in'] = [ - 'label' => sprintf('%s (%s)', $name, (string)trans('firefly.income')), + 'label' => sprintf('%s (%s)', $name, (string) trans('firefly.income')), 'type' => 'bar', 'yAxisID' => 'y-axis-0', 'entries' => [], ]; $chartData[$exp->id . '-out'] = [ - 'label' => sprintf('%s (%s)', $name, (string)trans('firefly.expenses')), + 'label' => sprintf('%s (%s)', $name, (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, (string)trans('firefly.sum_of_income')), + 'label' => sprintf('%s (%s)', $name, (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, (string)trans('firefly.sum_of_expenses')), + 'label' => sprintf('%s (%s)', $name, (string) trans('firefly.sum_of_expenses')), 'type' => 'line', 'fill' => false, 'yAxisID' => 'y-axis-1', @@ -151,7 +151,7 @@ class ExpenseReportController extends Controller // get expenses grouped by opposing name: $expenses = $this->groupByName($this->getExpensesForOpposing($accounts, $all, $currentStart, $currentEnd)); $income = $this->groupByName($this->getIncomeForOpposing($accounts, $all, $currentStart, $currentEnd)); - $label = $currentStart->formatLocalized($format); + $label = $currentStart->isoFormat($format); foreach ($combined as $name => $combination) { // first is always expense account: diff --git a/app/Http/Controllers/Chart/PiggyBankController.php b/app/Http/Controllers/Chart/PiggyBankController.php index 54ddd642f9..7efc12d07a 100644 --- a/app/Http/Controllers/Chart/PiggyBankController.php +++ b/app/Http/Controllers/Chart/PiggyBankController.php @@ -64,7 +64,7 @@ class PiggyBankController extends Controller * @param PiggyBank $piggyBank * * @return JsonResponse - * @throws JsonException + * @throws \FireflyIII\Exceptions\FireflyException */ public function history(PiggyBankRepositoryInterface $repository, PiggyBank $piggyBank): JsonResponse { @@ -100,7 +100,7 @@ class PiggyBankController extends Controller } ); $currentSum = $filtered->sum('amount'); - $label = $oldest->formatLocalized((string)trans('config.month_and_day', [], $locale)); + $label = $oldest->isoFormat((string) trans('config.month_and_day_js', [], $locale)); $chartData[$label] = $currentSum; $oldest = app('navigation')->addPeriod($oldest, $step, 0); } @@ -110,7 +110,7 @@ class PiggyBankController extends Controller } ); $finalSum = $finalFiltered->sum('amount'); - $finalLabel = $today->formatLocalized((string)trans('config.month_and_day', [], $locale)); + $finalLabel = $today->isoFormat((string) trans('config.month_and_day_js', [], $locale)); $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 3062386453..8eb910ac80 100644 --- a/app/Http/Controllers/Chart/ReportController.php +++ b/app/Http/Controllers/Chart/ReportController.php @@ -69,7 +69,7 @@ class ReportController extends Controller * @param Carbon $end * * @return JsonResponse - * @throws JsonException + * @throws \FireflyIII\Exceptions\FireflyException */ public function netWorth(Collection $accounts, Carbon $start, Carbon $end): JsonResponse { @@ -114,7 +114,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', [], $locale)); + $label = $current->isoFormat((string) trans('config.month_and_day_js', [], $locale)); if (!array_key_exists($currencyId, $chartData)) { $chartData[$currencyId] = [ 'label' => 'Net worth in ' . $netWorthItem['currency']->name, @@ -179,13 +179,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, @@ -217,7 +217,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'], @@ -226,7 +226,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'], @@ -239,9 +239,9 @@ class ReportController extends Controller $currentStart = clone $start; while ($currentStart <= $end) { $key = $currentStart->format($format); - $title = $currentStart->formatLocalized($titleFormat); - $income['entries'][$title] = round((float)($currency[$key]['earned'] ?? '0'), $currency['currency_decimal_places']); - $expense['entries'][$title] = round((float)($currency[$key]['spent'] ?? '0'), $currency['currency_decimal_places']); + $title = $currentStart->isoFormat($titleFormat); + $income['entries'][$title] = round((float) ($currency[$key]['earned'] ?? '0'), $currency['currency_decimal_places']); + $expense['entries'][$title] = round((float) ($currency[$key]['spent'] ?? '0'), $currency['currency_decimal_places']); $currentStart = app('navigation')->addPeriod($currentStart, $preferredRange, 0); } diff --git a/app/Http/Controllers/Chart/TagReportController.php b/app/Http/Controllers/Chart/TagReportController.php index 3a77762e19..75a452165a 100644 --- a/app/Http/Controllers/Chart/TagReportController.php +++ b/app/Http/Controllers/Chart/TagReportController.php @@ -270,7 +270,7 @@ class TagReportController extends Controller $chartData[$spentKey] = $chartData[$spentKey] ?? [ 'label' => sprintf( '%s (%s)', - (string)trans('firefly.spent_in_specific_tag', ['tag' => $tag->tag]), + (string) trans('firefly.spent_in_specific_tag', ['tag' => $tag->tag]), $currency['currency_name'] ), 'type' => 'bar', @@ -282,7 +282,7 @@ class TagReportController extends Controller foreach ($currency['tags'] as $currentTag) { foreach ($currentTag['transaction_journals'] as $journal) { - $key = $journal['date']->formatLocalized($format); + $key = $journal['date']->isoFormat($format); $amount = app('steam')->positive($journal['amount']); $chartData[$spentKey]['entries'][$key] = $chartData[$spentKey]['entries'][$key] ?? '0'; $chartData[$spentKey]['entries'][$key] = bcadd($chartData[$spentKey]['entries'][$key], $amount); @@ -297,7 +297,7 @@ class TagReportController extends Controller $chartData[$spentKey] = $chartData[$spentKey] ?? [ 'label' => sprintf( '%s (%s)', - (string)trans('firefly.earned_in_specific_tag', ['tag' => $tag->tag]), + (string) trans('firefly.earned_in_specific_tag', ['tag' => $tag->tag]), $currency['currency_name'] ), 'type' => 'bar', @@ -309,7 +309,7 @@ class TagReportController extends Controller foreach ($currency['tags'] as $currentTag) { foreach ($currentTag['transaction_journals'] as $journal) { - $key = $journal['date']->formatLocalized($format); + $key = $journal['date']->isoFormat($format); $amount = app('steam')->positive($journal['amount']); $chartData[$spentKey]['entries'][$key] = $chartData[$spentKey]['entries'][$key] ?? '0'; $chartData[$spentKey]['entries'][$key] = bcadd($chartData[$spentKey]['entries'][$key], $amount); @@ -338,7 +338,7 @@ class TagReportController extends Controller $currentStart = clone $start; while ($currentStart <= $end) { $currentEnd = app('navigation')->endOfPeriod($currentStart, $preferredRange); - $key = $currentStart->formatLocalized($format); + $key = $currentStart->isoFormat($format); $return[$key] = '0'; $currentStart = clone $currentEnd; $currentStart->addDay()->startOfDay(); diff --git a/app/Http/Controllers/Chart/TransactionController.php b/app/Http/Controllers/Chart/TransactionController.php index c7c7dac871..6aae2bf3db 100644 --- a/app/Http/Controllers/Chart/TransactionController.php +++ b/app/Http/Controllers/Chart/TransactionController.php @@ -57,7 +57,6 @@ class TransactionController extends Controller * @param Carbon $end * * @return JsonResponse - * @throws JsonException */ public function budgets(Carbon $start, Carbon $end) { @@ -80,7 +79,7 @@ class TransactionController extends Controller // group by category. /** @var array $journal */ foreach ($result as $journal) { - $budget = $journal['budget_name'] ?? (string)trans('firefly.no_budget'); + $budget = $journal['budget_name'] ?? (string) trans('firefly.no_budget'); $title = sprintf('%s (%s)', $budget, $journal['currency_symbol']); $data[$title] = $data[$title] ?? [ 'amount' => '0', @@ -102,7 +101,6 @@ class TransactionController extends Controller * * @return JsonResponse * @throws FireflyException - * @throws JsonException */ public function categories(string $objectType, Carbon $start, Carbon $end) { @@ -138,7 +136,7 @@ class TransactionController extends Controller // group by category. /** @var array $journal */ foreach ($result as $journal) { - $category = $journal['category_name'] ?? (string)trans('firefly.no_category'); + $category = $journal['category_name'] ?? (string) trans('firefly.no_category'); $title = sprintf('%s (%s)', $category, $journal['currency_symbol']); $data[$title] = $data[$title] ?? [ 'amount' => '0', @@ -161,7 +159,6 @@ class TransactionController extends Controller * * @return JsonResponse * @throws FireflyException - * @throws JsonException */ public function destinationAccounts(string $objectType, Carbon $start, Carbon $end) { @@ -219,7 +216,6 @@ class TransactionController extends Controller * * @return JsonResponse * @throws FireflyException - * @throws JsonException */ public function sourceAccounts(string $objectType, Carbon $start, Carbon $end) { diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php index 5031532dfb..2fd0eb6eeb 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -92,9 +92,9 @@ abstract class Controller extends BaseController function ($request, $next): mixed { $locale = app('steam')->getLocale(); // translations for specific strings: - $this->monthFormat = (string)trans('config.month', [], $locale); - $this->monthAndDayFormat = (string)trans('config.month_and_day', [], $locale); - $this->dateTimeFormat = (string)trans('config.date_time', [], $locale); + $this->monthFormat = (string) trans('config.month_js', [], $locale); + $this->monthAndDayFormat = (string) trans('config.month_and_day_js', [], $locale); + $this->dateTimeFormat = (string) trans('config.date_time_js', [], $locale); // get shown-intro-preference: if (auth()->check()) { diff --git a/app/Http/Controllers/CurrencyController.php b/app/Http/Controllers/CurrencyController.php index f8e59c9f8e..f8b7c71e50 100644 --- a/app/Http/Controllers/CurrencyController.php +++ b/app/Http/Controllers/CurrencyController.php @@ -56,7 +56,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); @@ -78,13 +78,13 @@ class CurrencyController extends Controller /** @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')) { @@ -107,7 +107,7 @@ class CurrencyController extends Controller */ public function defaultCurrency(Request $request) { - $currencyId = (int)$request->get('id'); + $currencyId = (int) $request->get('id'); if ($currencyId > 0) { // valid currency? $currency = $this->repository->find($currencyId); @@ -117,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')); } @@ -140,7 +140,7 @@ class CurrencyController extends Controller $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'))])); 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')); @@ -149,7 +149,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)); @@ -158,7 +158,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')); @@ -178,7 +178,7 @@ class CurrencyController extends Controller $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'))])); Log::channel('audit')->info(sprintf('Tried to delete currency %s but is not site owner.', $currency->code)); return redirect(route('currencies.index')); @@ -186,14 +186,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')); @@ -202,70 +202,63 @@ 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')); } /** - * @param Request $request - * @param TransactionCurrency $currency - * + * @param Request $request + * @return JsonResponse * @throws FireflyException */ public function disableCurrency(Request $request): JsonResponse { - $currencyId = (int)$request->get('id'); - if ($currencyId > 0) { - // valid currency? - $currency = $this->repository->find($currencyId); - if (null !== $currency) { - app('preferences')->mark(); + $currencyId = (int) $request->get('id'); + $currency = $this->repository->find($currencyId); - /** @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'))])); - Log::channel('audit')->info(sprintf('Tried to disable currency %s but is not site owner.', $currency->code)); - return response()->json([]); - - } - - if ($this->repository->currencyInUse($currency)) { - - $location = $this->repository->currencyInUseAt($currency); - $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)); - return response()->json([]); - } - - $this->repository->disable($currency); - Log::channel('audit')->info(sprintf('Disabled currency %s.', $currency->code)); - // if no currencies are enabled, enable the first one in the DB (usually the EUR) - if (0 === $this->repository->get()->count()) { - /** @var TransactionCurrency $first */ - $first = $this->repository->getAll()->first(); - if (null === $first) { - throw new FireflyException('No currencies found.'); - } - Log::channel('audit')->info(sprintf('Auto-enabled currency %s.', $first->code)); - $this->repository->enable($first); - app('preferences')->set('currencyPreference', $first->code); - app('preferences')->mark(); - } - - if ('EUR' === $currency->code) { - session()->flash('warning', (string)trans('firefly.disable_EUR_side_effects')); - } - - session()->flash('success', (string)trans('firefly.currency_is_now_disabled', ['name' => $currency->name])); - } + // valid currency? + if (null === $currency) { + return response()->json([]); } - return response()->json([]); + app('preferences')->mark(); + + // user must be "owner" + /** @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'))])); + Log::channel('audit')->info(sprintf('Tried to disable currency %s but is not site owner.', $currency->code)); + return response()->json([]); + + } + + // currency cannot be in use. + if ($this->repository->currencyInUse($currency)) { + + $location = $this->repository->currencyInUseAt($currency); + $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)); + return response()->json([]); + } + + // currency disabled! + $this->repository->disable($currency); + Log::channel('audit')->info(sprintf('Disabled currency %s.', $currency->code)); + + $this->repository->ensureMinimalEnabledCurrencies(); + + // extra warning + if ('EUR' === $currency->code) { + session()->flash('warning', (string) trans('firefly.disable_EUR_side_effects')); + } + + session()->flash('success', (string) trans('firefly.currency_is_now_disabled', ['name' => $currency->name])); + } /** @@ -282,7 +275,7 @@ class CurrencyController extends Controller $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'))])); Log::channel('audit')->info(sprintf('Tried to edit currency %s but is not owner.', $currency->code)); return redirect(route('currencies.index')); @@ -290,13 +283,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); @@ -312,13 +305,12 @@ class CurrencyController extends Controller } /** - * @param TransactionCurrency $currency - * + * @param Request $request * @return RedirectResponse|Redirector */ public function enableCurrency(Request $request) { - $currencyId = (int)$request->get('id'); + $currencyId = (int) $request->get('id'); if ($currencyId > 0) { // valid currency? $currency = $this->repository->find($currencyId); @@ -326,7 +318,7 @@ class CurrencyController extends Controller 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)); } } @@ -341,13 +333,15 @@ class CurrencyController extends Controller * * @return Factory|View * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ 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); @@ -357,7 +351,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; } @@ -391,15 +385,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')); 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')) { $request->session()->put('currencies.create.fromStore', true); @@ -430,7 +424,7 @@ class CurrencyController extends Controller } 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'))])); Log::channel('audit')->info('Tried to update (POST) currency without admin rights.', $data); return redirect(route('currencies.index')); @@ -438,10 +432,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')) { $request->session()->put('currencies.edit.fromUpdate', true); diff --git a/app/Http/Controllers/DebugController.php b/app/Http/Controllers/DebugController.php index 39b87ed9b6..c96cad13f6 100644 --- a/app/Http/Controllers/DebugController.php +++ b/app/Http/Controllers/DebugController.php @@ -120,50 +120,53 @@ class DebugController extends Controller */ public function index(Request $request) { - $search = ['~', '#']; - $replace = ['\~', '# ']; - - $now = Carbon::now()->format('Y-m-d H:i:s e'); - $installationIdConfig = app('fireflyconfig')->get('installation_id', ''); - $installationId = $installationIdConfig ? $installationIdConfig->data : ''; - $phpVersion = str_replace($search, $replace, PHP_VERSION); - $phpOs = str_replace($search, $replace, PHP_OS); - $interface = PHP_SAPI; - $drivers = implode(', ', DB::availableDrivers()); - $currentDriver = DB::getDriverName(); - $userAgent = $request->header('user-agent'); - $trustedProxies = config('firefly.trusted_proxies'); - $displayErrors = ini_get('display_errors'); - $errorReporting = $this->errorReporting((int)ini_get('error_reporting')); - $appEnv = config('app.env'); - $appDebug = var_export(config('app.debug'), true); - $logChannel = config('logging.default'); - $appLogLevel = config('logging.level'); - $cacheDriver = config('cache.default'); - $loginProvider = config('auth.providers.users.driver'); - $bcscale = bcscale(); - $layout = env('FIREFLY_III_LAYOUT'); - $tz = env('TZ'); - $buildNr = '(unknown)'; - $buildDate = '(unknown)'; - + // basic scope information: + $now = Carbon::now()->format('Y-m-d H:i:s e'); + $buildNr = '(unknown)'; + $buildDate = '(unknown)'; + $expectedDBversion = config('firefly.db_version'); + $foundDBversion = FireflyConfig::get('db_version', 1)->data; if (file_exists('/var/www/counter-main.txt')) { $buildNr = trim(file_get_contents('/var/www/counter-main.txt')); } if (file_exists('/var/www/build-date-main.txt')) { $buildDate = trim(file_get_contents('/var/www/build-date-main.txt')); } + $phpVersion = PHP_VERSION; + $phpOs = PHP_OS; + + // system information + $tz = env('TZ'); + $appEnv = config('app.env'); + $appDebug = var_export(config('app.debug'), true); + $cacheDriver = config('cache.default'); + $logChannel = config('logging.default'); + $appLogLevel = config('logging.level'); + $displayErrors = ini_get('display_errors'); + $errorReporting = $this->errorReporting((int) ini_get('error_reporting')); + $interface = PHP_SAPI; + $defaultLanguage = (string) config('firefly.default_language'); + $defaultLocale = (string) config('firefly.default_locale'); + $bcscale = bcscale(); + $drivers = implode(', ', DB::availableDrivers()); + $currentDriver = DB::getDriverName(); + $trustedProxies = config('firefly.trusted_proxies'); + + // user info + $loginProvider = config('auth.providers.users.driver'); + $userGuard = config('auth.defaults.guard'); + $remoteHeader = $userGuard === 'remote_user_guard' ? config('auth.guard_header') : 'N/A'; + $remoteMailHeader = $userGuard === 'remote_user_guard' ? config('auth.guard_email') : 'N/A'; + $userLanguage = app('steam')->getLanguage(); + $userLocale = app('steam')->getLocale(); + $userAgent = $request->header('user-agent'); + $stateful = join(', ', config('sanctum.stateful')); + // expected + found DB version: - $expectedDBversion = config('firefly.db_version'); - $foundDBversion = FireflyConfig::get('db_version', 1)->data; // some new vars. - $defaultLanguage = (string)config('firefly.default_language'); - $defaultLocale = (string)config('firefly.default_locale'); - $userLanguage = app('steam')->getLanguage(); - $userLocale = app('steam')->getLocale(); - $isDocker = env('IS_DOCKER', false); + $isDocker = env('IS_DOCKER', false); // set languages, see what happens: $original = setlocale(LC_ALL, 0); @@ -209,19 +212,21 @@ class DebugController extends Controller 'appEnv', 'appDebug', 'logChannel', + 'stateful', 'tz', 'appLogLevel', + 'remoteHeader', + 'remoteMailHeader', 'now', 'drivers', 'currentDriver', + 'userGuard', 'loginProvider', 'buildNr', 'buildDate', 'bcscale', - 'layout', 'userAgent', 'displayErrors', - 'installationId', 'errorReporting', 'phpOs', 'interface', @@ -260,7 +265,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) { diff --git a/app/Http/Controllers/Export/IndexController.php b/app/Http/Controllers/Export/IndexController.php index 192831b30f..f21893777e 100644 --- a/app/Http/Controllers/Export/IndexController.php +++ b/app/Http/Controllers/Export/IndexController.php @@ -54,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']); @@ -85,7 +85,7 @@ class IndexController extends Controller $generator->setStart($firstDate); $result = $generator->export(); - $name = sprintf('%s_transaction_export.csv', date('Y_m_d')); + $name = sprintf('%s_transaction_export.csv', date('Y_m_d')); $quoted = sprintf('"%s"', addcslashes($name, '"\\')); // headers for CSV file. /** @var LaravelResponse $response */ diff --git a/app/Http/Controllers/HomeController.php b/app/Http/Controllers/HomeController.php index 8ffc94b11c..07e635b5d8 100644 --- a/app/Http/Controllers/HomeController.php +++ b/app/Http/Controllers/HomeController.php @@ -72,7 +72,7 @@ class HomeController extends Controller Log::debug('Received dateRange', ['start' => $request->get('start'), 'end' => $request->get('end'), 'label' => $request->get('label')]); // check if the label is "everything" or "Custom range" which will betray // a possible problem with the budgets. - if ($label === (string)trans('firefly.everything') || $label === (string)trans('firefly.customRange')) { + if ($label === (string) trans('firefly.everything') || $label === (string) trans('firefly.customRange')) { $isCustomRange = true; Log::debug('Range is now marked as "custom".'); } @@ -80,7 +80,7 @@ class HomeController extends Controller $diff = $start->diffInDays($end) + 1; 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); @@ -99,6 +99,7 @@ class HomeController extends Controller * @param AccountRepositoryInterface $repository * * @return mixed + * @throws \FireflyIII\Exceptions\FireflyException */ public function index(AccountRepositoryInterface $repository): mixed { @@ -112,7 +113,7 @@ class HomeController extends Controller if (0 === $count) { return redirect(route('new-user.index')); } - $subTitle = (string)trans('firefly.welcome_back'); + $subTitle = (string) trans('firefly.welcome_back'); $transactions = []; $frontPage = app('preferences')->getFresh('frontPageAccounts', $repository->getAccountsByType([AccountType::ASSET])->pluck('id')->toArray()); /** @var Carbon $start */ diff --git a/app/Http/Controllers/JavascriptController.php b/app/Http/Controllers/JavascriptController.php index 0e4e5bd307..72d37453bd 100644 --- a/app/Http/Controllers/JavascriptController.php +++ b/app/Http/Controllers/JavascriptController.php @@ -48,6 +48,8 @@ class JavascriptController extends Controller * * @return Response * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function accounts(AccountRepositoryInterface $repository, CurrencyRepositoryInterface $currencyRepository): Response { @@ -56,14 +58,14 @@ class JavascriptController extends Controller ); $preference = app('preferences')->get('currencyPreference', config('firefly.default_currency', 'EUR')); /** @noinspection NullPointerExceptionInspection */ - $default = $currencyRepository->findByCodeNull((string)$preference->data); + $default = $currencyRepository->findByCodeNull((string) $preference->data); $data = ['accounts' => []]; /** @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]; @@ -107,10 +109,13 @@ class JavascriptController extends Controller * * @return Response * @throws FireflyException + * @throws \JsonException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function variables(Request $request, AccountRepositoryInterface $repository, CurrencyRepositoryInterface $currencyRepository): Response { - $account = $repository->find((int)$request->get('account')); + $account = $repository->find((int) $request->get('account')); $currency = app('amount')->getDefaultCurrency(); if (null !== $account) { $currency = $repository->getAccountCurrency($account) ?? $currency; @@ -122,7 +127,7 @@ class JavascriptController extends Controller /** @noinspection NullPointerExceptionInspection */ $lang = $pref->data; $dateRange = $this->getDateRangeConfig(); - $uid = substr(hash('sha256', sprintf('%s-%s-%s', (string)config('app.key'), auth()->user()->id, auth()->user()->email)), 0, 12); + $uid = substr(hash('sha256', sprintf('%s-%s-%s', (string) config('app.key'), auth()->user()->id, auth()->user()->email)), 0, 12); $data = [ 'currencyCode' => $currency->code, diff --git a/app/Http/Controllers/Json/BoxController.php b/app/Http/Controllers/Json/BoxController.php index 07cc1c0b75..9a8ac019e8 100644 --- a/app/Http/Controllers/Json/BoxController.php +++ b/app/Http/Controllers/Json/BoxController.php @@ -52,7 +52,6 @@ class BoxController extends Controller * 2) if the user has no available amount set this period: spent per day * * @return JsonResponse - * @throws JsonException */ public function available(): JsonResponse { @@ -66,7 +65,7 @@ class BoxController extends Controller $end = session('end', Carbon::now()->endOfMonth()); $today = today(config('app.timezone')); $display = 2; // see method docs. - $boxTitle = (string)trans('firefly.spent'); + $boxTitle = (string) trans('firefly.spent'); $cache = new CacheProperties; $cache->addProperty($start); @@ -74,7 +73,7 @@ class BoxController extends Controller $cache->addProperty($today); $cache->addProperty('box-available'); if ($cache->has()) { - return response()->json($cache->get()); + //return response()->json($cache->get()); } $leftPerDayAmount = '0'; $leftToSpendAmount = '0'; @@ -93,21 +92,21 @@ 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'; $days = $today->between($start, $end) ? $today->diffInDays($start) + 1 : $end->diffInDays($start) + 1; - $spentPerDay = bcdiv($spentAmount, (string)$days); + $spentPerDay = bcdiv($spentAmount, (string) $days); if ($availableBudgets->count() > 0) { $display = 0; // assume user overspent - $boxTitle = (string)trans('firefly.overspent'); - $totalAvailableSum = (string)$availableBudgets->sum('amount'); + $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); } } @@ -131,7 +130,6 @@ class BoxController extends Controller * @param CurrencyRepositoryInterface $repository * * @return JsonResponse - * @throws JsonException */ public function balance(CurrencyRepositoryInterface $repository): JsonResponse { @@ -161,7 +159,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)); @@ -177,7 +175,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/BudgetController.php b/app/Http/Controllers/Json/BudgetController.php index 523463a5eb..af1ff647a1 100644 --- a/app/Http/Controllers/Json/BudgetController.php +++ b/app/Http/Controllers/Json/BudgetController.php @@ -64,7 +64,7 @@ class BudgetController 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-pie-chart'); $this->repository = app(BudgetRepositoryInterface::class); $this->opsRepository = app(OperationsRepositoryInterface::class); diff --git a/app/Http/Controllers/Json/FrontpageController.php b/app/Http/Controllers/Json/FrontpageController.php index 60bf987c54..1f6a0902f8 100644 --- a/app/Http/Controllers/Json/FrontpageController.php +++ b/app/Http/Controllers/Json/FrontpageController.php @@ -50,7 +50,10 @@ class FrontpageController extends Controller $amount = $repository->getCurrentAmount($piggyBank); if (1 === bccomp($amount, '0')) { // percentage! - $pct = round(($amount / $piggyBank->targetamount) * 100); + $pct = 0; + if (0.0 !== (float) $piggyBank->targetamount) { + $pct = round(($amount / $piggyBank->targetamount) * 100); + } $entry = [ 'id' => $piggyBank->id, diff --git a/app/Http/Controllers/Json/IntroController.php b/app/Http/Controllers/Json/IntroController.php index 7714e0d56c..1c6c796bc5 100644 --- a/app/Http/Controllers/Json/IntroController.php +++ b/app/Http/Controllers/Json/IntroController.php @@ -118,7 +118,7 @@ class IntroController extends Controller 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 8a70872254..6ff13ad21f 100644 --- a/app/Http/Controllers/Json/ReconcileController.php +++ b/app/Http/Controllers/Json/ReconcileController.php @@ -63,7 +63,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); @@ -76,12 +76,14 @@ class ReconcileController extends Controller /** * Overview of reconciliation. * - * @param Request $request - * @param Account $account - * @param Carbon $start - * @param Carbon $end + * @param Request $request + * @param Account|null $account + * @param Carbon|null $start + * @param Carbon|null $end * * @return JsonResponse + * @throws FireflyException + * @throws JsonException */ public function overview(Request $request, Account $account = null, Carbon $start = null, Carbon $end = null): JsonResponse { @@ -216,9 +218,9 @@ class ReconcileController extends Controller /** * Returns a list of transactions in a modal. * - * @param Account $account - * @param Carbon $start - * @param Carbon $end + * @param Account $account + * @param Carbon|null $start + * @param Carbon|null $end * * @return JsonResponse * @throws FireflyException @@ -236,8 +238,8 @@ class ReconcileController extends Controller $startDate->subDay(); $currency = $this->accountRepos->getAccountCurrency($account) ?? app('amount')->getDefaultCurrency(); - $startBalance = round((float)app('steam')->balance($account, $startDate), $currency->decimal_places); - $endBalance = round((float)app('steam')->balance($account, $end), $currency->decimal_places); + $startBalance = round((float) app('steam')->balance($account, $startDate), $currency->decimal_places); + $endBalance = round((float) app('steam')->balance($account, $end), $currency->decimal_places); // get the transactions $selectionStart = clone $start; diff --git a/app/Http/Controllers/Json/RecurrenceController.php b/app/Http/Controllers/Json/RecurrenceController.php index bdd6ee25d4..01b5e56212 100644 --- a/app/Http/Controllers/Json/RecurrenceController.php +++ b/app/Http/Controllers/Json/RecurrenceController.php @@ -73,10 +73,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(); @@ -100,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; switch ($endsAt) { @@ -143,36 +143,39 @@ class RecurrenceController extends Controller * @param Request $request * * @return JsonResponse + * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function suggest(Request $request): JsonResponse { $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'); + $preSelected = (string) $request->get('pre_select'); $locale = app('steam')->getLocale(); 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('past = true? %s', var_export('true' === (string) $request->get('past'), true))); $result = []; - if ($date > $today || 'true' === (string)$request->get('past')) { + 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', [], $locale)); + $yearlyDate = $date->isoFormat((string) trans('config.month_and_day_no_year_js', [], $locale)); $result = [ - 'daily' => ['label' => (string)trans('firefly.recurring_daily'), 'selected' => str_starts_with($preSelected, 'daily')], - $weekly => ['label' => (string)trans('firefly.recurring_weekly', ['weekday' => $dayOfWeek]), + 'daily' => ['label' => (string) trans('firefly.recurring_daily'), 'selected' => str_starts_with($preSelected, 'daily')], + $weekly => ['label' => (string) trans('firefly.recurring_weekly', ['weekday' => $dayOfWeek]), 'selected' => str_starts_with($preSelected, 'weekly')], - $monthly => ['label' => (string)trans('firefly.recurring_monthly', ['dayOfMonth' => $date->day]), + $monthly => ['label' => (string) trans('firefly.recurring_monthly', ['dayOfMonth' => $date->day]), 'selected' => str_starts_with($preSelected, 'monthly')], - $ndom => ['label' => (string)trans('firefly.recurring_ndom', ['weekday' => $dayOfWeek, 'dayOfMonth' => $date->weekOfMonth]), + $ndom => ['label' => (string) trans('firefly.recurring_ndom', ['weekday' => $dayOfWeek, 'dayOfMonth' => $date->weekOfMonth]), 'selected' => str_starts_with($preSelected, 'ndom')], - $yearly => ['label' => (string)trans('firefly.recurring_yearly', ['date' => $yearlyDate]), + $yearly => ['label' => (string) trans('firefly.recurring_yearly', ['date' => $yearlyDate]), 'selected' => str_starts_with($preSelected, 'yearly')], ]; } diff --git a/app/Http/Controllers/Json/RuleController.php b/app/Http/Controllers/Json/RuleController.php index c2e52d35f6..63d6f5487e 100644 --- a/app/Http/Controllers/Json/RuleController.php +++ b/app/Http/Controllers/Json/RuleController.php @@ -43,11 +43,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(); @@ -69,13 +69,13 @@ class RuleController extends Controller */ public function trigger(Request $request): JsonResponse { - $count = (int)$request->get('count') > 0 ? (int)$request->get('count') : 1; - $operators = config('firefly.search.operators'); + $count = (int) $request->get('count') > 0 ? (int) $request->get('count') : 1; + $operators = config('search.operators'); $triggers = []; foreach ($operators as $key => $operator) { if ('user_action' !== $key && false === $operator['alias']) { - $triggers[$key] = (string)trans(sprintf('firefly.rule_trigger_%s_choice', $key)); + $triggers[$key] = (string) trans(sprintf('firefly.rule_trigger_%s_choice', $key)); } } asort($triggers); diff --git a/app/Http/Controllers/NewUserController.php b/app/Http/Controllers/NewUserController.php index 8409172ef5..4bd8c84a9e 100644 --- a/app/Http/Controllers/NewUserController.php +++ b/app/Http/Controllers/NewUserController.php @@ -66,7 +66,7 @@ class NewUserController extends Controller */ 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'); @@ -84,7 +84,7 @@ class NewUserController extends Controller /** * Store his new settings. * - * @param NewUserFormRequest $request + * @param NewUserFormRequest $request * @param CurrencyRepositoryInterface $currencyRepository * * @return RedirectResponse|Redirector @@ -101,7 +101,7 @@ class NewUserController extends Controller // set language preference: app('preferences')->set('language', $language); // Store currency preference from input: - $currency = $currencyRepository->find((int)$request->input('amount_currency_id_bank_balance')); + $currency = $currencyRepository->find((int) $request->input('amount_currency_id_bank_balance')); // if is null, set to EUR: if (null === $currency) { @@ -109,9 +109,9 @@ class NewUserController extends Controller } $currencyRepository->enable($currency); - $this->createAssetAccount($request, $currency); // create normal asset account + $this->createAssetAccount($request, $currency); // create normal asset account $this->createSavingsAccount($request, $currency, $language); // create savings account - $this->createCashWalletAccount($currency, $language); // create cash wallet account + $this->createCashWalletAccount($currency, $language); // create cash wallet account // store currency preference: app('preferences')->set('currencyPreference', $currency->code); @@ -128,7 +128,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/ObjectGroup/DeleteController.php b/app/Http/Controllers/ObjectGroup/DeleteController.php index fca9f77954..c2341289d8 100644 --- a/app/Http/Controllers/ObjectGroup/DeleteController.php +++ b/app/Http/Controllers/ObjectGroup/DeleteController.php @@ -50,7 +50,7 @@ class DeleteController extends Controller $this->middleware( function ($request, $next) { app('view')->share('mainTitleIcon', 'fa-envelope-o'); - app('view')->share('title', (string)trans('firefly.object_groups_page_title')); + app('view')->share('title', (string) trans('firefly.object_groups_page_title')); $this->repository = app(ObjectGroupRepositoryInterface::class); @@ -68,7 +68,7 @@ class DeleteController extends Controller */ public function delete(ObjectGroup $objectGroup) { - $subTitle = (string)trans('firefly.delete_object_group', ['title' => $objectGroup->title]); + $subTitle = (string) trans('firefly.delete_object_group', ['title' => $objectGroup->title]); $piggyBanks = $objectGroup->piggyBanks()->count(); // put previous url in session @@ -86,7 +86,7 @@ class DeleteController extends Controller */ public function destroy(ObjectGroup $objectGroup): RedirectResponse { - session()->flash('success', (string)trans('firefly.deleted_object_group', ['title' => $objectGroup->title])); + session()->flash('success', (string) trans('firefly.deleted_object_group', ['title' => $objectGroup->title])); app('preferences')->mark(); $this->repository->destroy($objectGroup); diff --git a/app/Http/Controllers/ObjectGroup/EditController.php b/app/Http/Controllers/ObjectGroup/EditController.php index 74871f8b41..c389328adc 100644 --- a/app/Http/Controllers/ObjectGroup/EditController.php +++ b/app/Http/Controllers/ObjectGroup/EditController.php @@ -53,7 +53,7 @@ class EditController extends Controller $this->middleware( function ($request, $next) { app('view')->share('mainTitleIcon', 'fa-envelope-o'); - app('view')->share('title', (string)trans('firefly.object_groups_page_title')); + app('view')->share('title', (string) trans('firefly.object_groups_page_title')); $this->repository = app(ObjectGroupRepositoryInterface::class); @@ -71,7 +71,7 @@ class EditController extends Controller */ public function edit(ObjectGroup $objectGroup) { - $subTitle = (string)trans('firefly.edit_object_group', ['title' => $objectGroup->title]); + $subTitle = (string) trans('firefly.edit_object_group', ['title' => $objectGroup->title]); $subTitleIcon = 'fa-pencil'; if (true !== session('object-groups.edit.fromUpdate')) { @@ -95,12 +95,12 @@ class EditController extends Controller $data = $request->getObjectGroupData(); $piggyBank = $this->repository->update($objectGroup, $data); - session()->flash('success', (string)trans('firefly.updated_object_group', ['title' => $objectGroup->title])); + session()->flash('success', (string) trans('firefly.updated_object_group', ['title' => $objectGroup->title])); app('preferences')->mark(); $redirect = redirect($this->getPreviousUri('object-groups.edit.uri')); - if (1 === (int)$request->get('return_to_edit')) { + if (1 === (int) $request->get('return_to_edit')) { session()->put('object-groups.edit.fromUpdate', true); diff --git a/app/Http/Controllers/ObjectGroup/IndexController.php b/app/Http/Controllers/ObjectGroup/IndexController.php index 02039ed001..918535cd13 100644 --- a/app/Http/Controllers/ObjectGroup/IndexController.php +++ b/app/Http/Controllers/ObjectGroup/IndexController.php @@ -53,7 +53,7 @@ class IndexController extends Controller $this->middleware( function ($request, $next) { app('view')->share('mainTitleIcon', 'fa-envelope-o'); - app('view')->share('title', (string)trans('firefly.object_groups_page_title')); + app('view')->share('title', (string) trans('firefly.object_groups_page_title')); $this->repository = app(ObjectGroupRepositoryInterface::class); return $next($request); @@ -68,7 +68,7 @@ class IndexController extends Controller { $this->repository->deleteEmpty(); $this->repository->resetOrder(); - $subTitle = (string)trans('firefly.object_groups_index'); + $subTitle = (string) trans('firefly.object_groups_index'); $objectGroups = $this->repository->get(); return view('object-groups.index', compact('subTitle', 'objectGroups')); @@ -83,7 +83,7 @@ class IndexController extends Controller public function setOrder(Request $request, ObjectGroup $objectGroup) { Log::debug(sprintf('Found object group #%d "%s"', $objectGroup->id, $objectGroup->title)); - $newOrder = (int)$request->get('order'); + $newOrder = (int) $request->get('order'); $this->repository->setOrder($objectGroup, $newOrder); return response()->json([]); diff --git a/app/Http/Controllers/PiggyBank/AmountController.php b/app/Http/Controllers/PiggyBank/AmountController.php index 7de19b79ea..0489c76a12 100644 --- a/app/Http/Controllers/PiggyBank/AmountController.php +++ b/app/Http/Controllers/PiggyBank/AmountController.php @@ -55,7 +55,7 @@ class AmountController 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-bullseye'); $this->piggyRepos = app(PiggyBankRepositoryInterface::class); @@ -77,9 +77,12 @@ class AmountController extends Controller { $leftOnAccount = $this->piggyRepos->leftOnAccount($piggyBank, today(config('app.timezone'))); $savedSoFar = $this->piggyRepos->getCurrentAmount($piggyBank); - $leftToSave = bcsub($piggyBank->targetamount, $savedSoFar); - $maxAmount = min($leftOnAccount, $leftToSave); - $currency = $this->accountRepos->getAccountCurrency($piggyBank->account) ?? app('amount')->getDefaultCurrency(); + $maxAmount = $leftOnAccount; + if (0.000 !== (float) $piggyBank->targetamount) { + $leftToSave = bcsub($piggyBank->targetamount, $savedSoFar); + $maxAmount = min($leftOnAccount, $leftToSave); + } + $currency = $this->accountRepos->getAccountCurrency($piggyBank->account) ?? app('amount')->getDefaultCurrency(); return view('piggy-banks.add', compact('piggyBank', 'maxAmount', 'currency')); } @@ -97,9 +100,13 @@ class AmountController extends Controller $date = session('end', today(config('app.timezone'))); $leftOnAccount = $this->piggyRepos->leftOnAccount($piggyBank, $date); $savedSoFar = $this->piggyRepos->getCurrentAmount($piggyBank); - $leftToSave = bcsub($piggyBank->targetamount, $savedSoFar); - $maxAmount = min($leftOnAccount, $leftToSave); - $currency = $this->accountRepos->getAccountCurrency($piggyBank->account) ?? app('amount')->getDefaultCurrency(); + $maxAmount = $leftOnAccount; + + if (0.000 !== (float) $piggyBank->targetamount) { + $leftToSave = bcsub($piggyBank->targetamount, $savedSoFar); + $maxAmount = min($leftOnAccount, $leftToSave); + } + $currency = $this->accountRepos->getAccountCurrency($piggyBank->account) ?? app('amount')->getDefaultCurrency(); return view('piggy-banks.add-mobile', compact('piggyBank', 'maxAmount', 'currency')); } @@ -125,7 +132,7 @@ class AmountController extends Controller $this->piggyRepos->createEvent($piggyBank, $amount); session()->flash( 'success', - (string)trans( + (string) trans( 'firefly.added_amount_to_piggy', ['amount' => app('amount')->formatAnything($currency, $amount, false), 'name' => $piggyBank->name] ) @@ -138,7 +145,7 @@ class AmountController 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)] ) @@ -167,7 +174,7 @@ class AmountController 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] ) @@ -176,11 +183,11 @@ class AmountController extends Controller return redirect(route('piggy-banks.index')); } - $amount = number_format((float)$request->get('amount'), 12, '.', ''); + $amount = number_format((float) $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)] ) diff --git a/app/Http/Controllers/PiggyBank/CreateController.php b/app/Http/Controllers/PiggyBank/CreateController.php index af55861808..556c7e39b3 100644 --- a/app/Http/Controllers/PiggyBank/CreateController.php +++ b/app/Http/Controllers/PiggyBank/CreateController.php @@ -53,7 +53,7 @@ class CreateController 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-bullseye'); $this->attachments = app(AttachmentHelperInterface::class); @@ -71,7 +71,7 @@ class CreateController extends Controller */ 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"). @@ -99,7 +99,7 @@ class CreateController 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(); // store attachment(s): @@ -109,7 +109,7 @@ class CreateController extends Controller $this->attachments->saveAttachmentsForModel($piggyBank, $files); } if (null !== $files && auth()->user()->hasRole('demo')) { - session()->flash('info', (string)trans('firefly.no_att_demo_user')); + session()->flash('info', (string) trans('firefly.no_att_demo_user')); } if (count($this->attachments->getMessages()->get('attachments')) > 0) { @@ -117,7 +117,7 @@ class CreateController extends Controller } $redirect = redirect($this->getPreviousUri('piggy-banks.create.uri')); - if (1 === (int)$request->get('create_another')) { + if (1 === (int) $request->get('create_another')) { session()->put('piggy-banks.create.fromStore', true); diff --git a/app/Http/Controllers/PiggyBank/DeleteController.php b/app/Http/Controllers/PiggyBank/DeleteController.php index 3782cacd4b..726b081775 100644 --- a/app/Http/Controllers/PiggyBank/DeleteController.php +++ b/app/Http/Controllers/PiggyBank/DeleteController.php @@ -50,7 +50,7 @@ class DeleteController 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-bullseye'); $this->piggyRepos = app(PiggyBankRepositoryInterface::class); @@ -69,7 +69,7 @@ class DeleteController extends Controller */ 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'); @@ -86,7 +86,7 @@ class DeleteController 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); diff --git a/app/Http/Controllers/PiggyBank/EditController.php b/app/Http/Controllers/PiggyBank/EditController.php index 3cdefe2e8e..4dba83a586 100644 --- a/app/Http/Controllers/PiggyBank/EditController.php +++ b/app/Http/Controllers/PiggyBank/EditController.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Http\Controllers\PiggyBank; +use Amount; use FireflyIII\Helpers\Attachments\AttachmentHelperInterface; use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Requests\PiggyBankUpdateRequest; @@ -40,9 +41,9 @@ use Illuminate\View\View; */ class EditController extends Controller { + private AccountRepositoryInterface $accountRepository; private AttachmentHelperInterface $attachments; private PiggyBankRepositoryInterface $piggyRepos; - private AccountRepositoryInterface $accountRepository; /** * PiggyBankController constructor. @@ -55,11 +56,11 @@ class EditController 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-bullseye'); - $this->attachments = app(AttachmentHelperInterface::class); - $this->piggyRepos = app(PiggyBankRepositoryInterface::class); + $this->attachments = app(AttachmentHelperInterface::class); + $this->piggyRepos = app(PiggyBankRepositoryInterface::class); $this->accountRepository = app(AccountRepositoryInterface::class); return $next($request); } @@ -75,24 +76,28 @@ class EditController extends Controller */ 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; $note = $piggyBank->notes()->first(); // Flash some data to fill the form. $targetDate = $piggyBank->targetdate?->format('Y-m-d'); $startDate = $piggyBank->startdate?->format('Y-m-d'); - $currency = $this->accountRepository->getAccountCurrency($piggyBank->account); + $currency = $this->accountRepository->getAccountCurrency($piggyBank->account); + if (null === $currency) { + $currency = Amount::getDefaultCurrency(); + } $preFilled = ['name' => $piggyBank->name, 'account_id' => $piggyBank->account_id, - 'targetamount' => number_format((float)$piggyBank->targetamount, $currency->decimal_places,'.',''), + 'targetamount' => number_format((float) $piggyBank->targetamount, $currency->decimal_places, '.', ''), 'targetdate' => $targetDate, 'startdate' => $startDate, 'object_group' => $piggyBank->objectGroups->first() ? $piggyBank->objectGroups->first()->title : '', 'notes' => null === $note ? '' : $note->text, ]; + if (0.0 === (float) $piggyBank->targetamount) { + $preFilled['targetamount'] = ''; + } session()->flash('preFilled', $preFilled); // put previous url in session if not redirect from store (not "return_to_edit"). @@ -117,7 +122,7 @@ class EditController extends Controller $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(); // store new attachment(s): @@ -127,7 +132,7 @@ class EditController extends Controller $this->attachments->saveAttachmentsForModel($piggyBank, $files); } if (null !== $files && auth()->user()->hasRole('demo')) { - session()->flash('info', (string)trans('firefly.no_att_demo_user')); + session()->flash('info', (string) trans('firefly.no_att_demo_user')); } if (count($this->attachments->getMessages()->get('attachments')) > 0) { @@ -135,7 +140,7 @@ class EditController extends Controller } $redirect = redirect($this->getPreviousUri('piggy-banks.edit.uri')); - if (1 === (int)$request->get('return_to_edit')) { + if (1 === (int) $request->get('return_to_edit')) { session()->put('piggy-banks.edit.fromUpdate', true); diff --git a/app/Http/Controllers/PiggyBank/IndexController.php b/app/Http/Controllers/PiggyBank/IndexController.php index 3ee182e62f..b512b16f3f 100644 --- a/app/Http/Controllers/PiggyBank/IndexController.php +++ b/app/Http/Controllers/PiggyBank/IndexController.php @@ -57,7 +57,7 @@ class IndexController 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-bullseye'); $this->piggyRepos = app(PiggyBankRepositoryInterface::class); @@ -74,6 +74,8 @@ class IndexController extends Controller * @param Request $request * * @return Factory|View + * @throws \FireflyIII\Exceptions\FireflyException + * @throws \JsonException */ public function index(Request $request) { @@ -101,7 +103,7 @@ class IndexController extends Controller /** @var PiggyBank $piggy */ foreach ($collection as $piggy) { $array = $transformer->transform($piggy); - $groupOrder = (int)$array['object_group_order']; + $groupOrder = (int) $array['object_group_order']; // make group array if necessary: $piggyBanks[$groupOrder] = $piggyBanks[$groupOrder] ?? [ 'object_group_id' => $array['object_group_id'] ?? 0, @@ -110,7 +112,7 @@ class IndexController extends Controller ]; $account = $accountTransformer->transform($piggy->account); - $accountId = (int)$account['id']; + $accountId = (int) $account['id']; $array['attachments'] = $this->piggyRepos->getAttachments($piggy); if (!array_key_exists($accountId, $accounts)) { // create new: @@ -165,10 +167,10 @@ class IndexController extends Controller // current_amount // left_to_save // save_per_month - $sums[$groupId][$currencyId]['target'] = bcadd($sums[$groupId][$currencyId]['target'], (string)$piggy['target_amount']); - $sums[$groupId][$currencyId]['saved'] = bcadd($sums[$groupId][$currencyId]['saved'], (string)$piggy['current_amount']); - $sums[$groupId][$currencyId]['left_to_save'] = bcadd($sums[$groupId][$currencyId]['left_to_save'], (string)$piggy['left_to_save']); - $sums[$groupId][$currencyId]['save_per_month'] = bcadd($sums[$groupId][$currencyId]['save_per_month'], (string)$piggy['save_per_month']); + $sums[$groupId][$currencyId]['target'] = bcadd($sums[$groupId][$currencyId]['target'], (string) $piggy['target_amount']); + $sums[$groupId][$currencyId]['saved'] = bcadd($sums[$groupId][$currencyId]['saved'], (string) $piggy['current_amount']); + $sums[$groupId][$currencyId]['left_to_save'] = bcadd($sums[$groupId][$currencyId]['left_to_save'], (string) $piggy['left_to_save']); + $sums[$groupId][$currencyId]['save_per_month'] = bcadd($sums[$groupId][$currencyId]['save_per_month'], (string) $piggy['save_per_month']); } } foreach ($piggyBanks as $groupOrder => $group) { @@ -189,8 +191,8 @@ class IndexController extends Controller */ public function setOrder(Request $request, PiggyBank $piggyBank): JsonResponse { - $objectGroupTitle = (string)$request->get('objectGroupTitle'); - $newOrder = (int)$request->get('order'); + $objectGroupTitle = (string) $request->get('objectGroupTitle'); + $newOrder = (int) $request->get('order'); $this->piggyRepos->setOrder($piggyBank, $newOrder); if ('' !== $objectGroupTitle) { $this->piggyRepos->setObjectGroup($piggyBank, $objectGroupTitle); diff --git a/app/Http/Controllers/PiggyBank/ShowController.php b/app/Http/Controllers/PiggyBank/ShowController.php index bb5c71482f..6aba89dfdd 100644 --- a/app/Http/Controllers/PiggyBank/ShowController.php +++ b/app/Http/Controllers/PiggyBank/ShowController.php @@ -51,7 +51,7 @@ class ShowController 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-bullseye'); $this->piggyRepos = app(PiggyBankRepositoryInterface::class); diff --git a/app/Http/Controllers/PreferencesController.php b/app/Http/Controllers/PreferencesController.php index 58a877c01c..737ad506bc 100644 --- a/app/Http/Controllers/PreferencesController.php +++ b/app/Http/Controllers/PreferencesController.php @@ -51,7 +51,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); @@ -66,6 +66,8 @@ class PreferencesController extends Controller * * @return Factory|View * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function index(AccountRepositoryInterface $repository) { @@ -114,7 +116,7 @@ class PreferencesController extends Controller Log::error($e->getMessage()); $locales = []; } - $locales = ['equal' => (string)trans('firefly.equal_to_language')] + $locales; + $locales = ['equal' => (string) trans('firefly.equal_to_language')] + $locales; // an important fallback is that the frontPageAccount array gets refilled automatically // when it turns up empty. if (empty($frontPageAccounts->data)) { @@ -147,6 +149,8 @@ class PreferencesController extends Controller * * @return RedirectResponse|Redirector * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function postIndex(Request $request) { @@ -154,7 +158,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); } @@ -167,8 +171,8 @@ class PreferencesController extends Controller session()->forget('range'); // custom fiscal year - $customFiscalYear = 1 === (int)$request->get('customFiscalYear'); - $string = strtotime((string)$request->get('fiscalYearStart')); + $customFiscalYear = 1 === (int) $request->get('customFiscalYear'); + $string = strtotime((string) $request->get('fiscalYearStart')); if (false !== $string) { $fiscalYearStart = date('m-d', $string); app('preferences')->set('customFiscalYear', $customFiscalYear); @@ -178,7 +182,7 @@ class PreferencesController extends Controller // 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); } @@ -220,7 +224,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/ProfileController.php b/app/Http/Controllers/ProfileController.php index c2d2a47bda..9ec9402403 100644 --- a/app/Http/Controllers/ProfileController.php +++ b/app/Http/Controllers/ProfileController.php @@ -78,7 +78,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); @@ -110,7 +110,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')); @@ -132,7 +132,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')); @@ -147,6 +147,8 @@ class ProfileController extends Controller * @throws IncompatibleWithGoogleAuthenticatorException * @throws InvalidCharactersException * @throws SecretKeyTooShortException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function code(Request $request) { @@ -229,7 +231,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')); } @@ -249,7 +251,7 @@ class ProfileController extends Controller return redirect(route('profile.index')); } $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')); @@ -274,8 +276,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')); } @@ -304,7 +306,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')); } @@ -314,6 +316,8 @@ class ProfileController extends Controller * * @return Factory|View * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function index() { @@ -351,7 +355,7 @@ class ProfileController extends Controller public function logoutOtherSessions() { if (!$this->internalAuth) { - session()->flash('info', (string)trans('firefly.external_auth_disabled')); + session()->flash('info', (string) trans('firefly.external_auth_disabled')); return redirect(route('profile.index')); } @@ -409,7 +413,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(); } @@ -419,7 +423,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')); } @@ -427,14 +431,12 @@ class ProfileController extends Controller // now actually update user: $repository->changeEmail($user, $newEmail); - // call event. - $ipAddress = $request->ip(); - event(new UserChangedEmail($user, $newEmail, $oldEmail, $ipAddress)); + event(new UserChangedEmail($user, $newEmail, $oldEmail)); // 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')); } @@ -469,7 +471,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')); } @@ -481,6 +483,8 @@ class ProfileController extends Controller * * @return RedirectResponse|Redirector * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function postCode(TokenFormRequest $request) { @@ -498,7 +502,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. @@ -525,6 +529,8 @@ class ProfileController extends Controller * @param string $mfaCode * * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ private function addToMFAHistory(string $mfaCode): void { @@ -579,7 +585,7 @@ class ProfileController extends Controller } 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')); } @@ -603,7 +609,7 @@ class ProfileController extends Controller public function postLogoutOtherSessions(Request $request) { if (!$this->internalAuth) { - session()->flash('info', (string)trans('firefly.external_auth_disabled')); + session()->flash('info', (string) trans('firefly.external_auth_disabled')); return redirect(route('profile.index')); } @@ -613,11 +619,11 @@ class ProfileController extends Controller ]; if (Auth::once($creds)) { Auth::logoutOtherDevices($request->get('password')); - session()->flash('info', (string)trans('firefly.other_sessions_logged_out')); + session()->flash('info', (string) trans('firefly.other_sessions_logged_out')); return redirect(route('profile.index')); } - session()->flash('error', (string)trans('auth.failed')); + session()->flash('error', (string) trans('auth.failed')); return redirect(route('profile.index')); @@ -643,7 +649,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')); } @@ -683,7 +689,7 @@ class ProfileController extends Controller /** @var string $match */ $match = null; foreach ($set as $entry) { - $hashed = hash('sha256', sprintf('%s%s', (string)config('app.key'), $entry->data)); + $hashed = hash('sha256', sprintf('%s%s', (string) config('app.key'), $entry->data)); if ($hashed === $hash) { $match = $entry->data; break; @@ -698,7 +704,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 fac24c57fe..6b7b755e4d 100644 --- a/app/Http/Controllers/Recurring/CreateController.php +++ b/app/Http/Controllers/Recurring/CreateController.php @@ -63,8 +63,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->budgetRepos = app(BudgetRepositoryInterface::class); @@ -98,22 +98,22 @@ 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'), ]; $hasOldInput = null !== $request->old('_token'); // flash some data $preFilled = [ 'first_date' => $tomorrow->format('Y-m-d'), 'transaction_type' => $hasOldInput ? $request->old('transaction_type') : 'withdrawal', - 'active' => $hasOldInput ? (bool)$request->old('active') : true, - 'apply_rules' => $hasOldInput ? (bool)$request->old('apply_rules') : true, + 'active' => $hasOldInput ? (bool) $request->old('active') : true, + 'apply_rules' => $hasOldInput ? (bool) $request->old('apply_rules') : true, ]; $request->session()->flash('preFilled', $preFilled); @@ -143,15 +143,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'), ]; @@ -184,8 +184,8 @@ class CreateController extends Controller 'category' => $request->old('category'), 'budget_id' => $request->old('budget_id'), 'bill_id' => $request->old('bill_id'), - 'active' => (bool)$request->old('active'), - 'apply_rules' => (bool)$request->old('apply_rules'), + 'active' => (bool) $request->old('active'), + 'apply_rules' => (bool) $request->old('apply_rules'), ]; } if (false === $hasOldInput) { @@ -236,7 +236,7 @@ class CreateController extends Controller 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(); // store attachment(s): @@ -246,7 +246,7 @@ class CreateController extends Controller $this->attachments->saveAttachmentsForModel($recurrence, $files); } if (null !== $files && auth()->user()->hasRole('demo')) { - session()->flash('info', (string)trans('firefly.no_att_demo_user')); + session()->flash('info', (string) trans('firefly.no_att_demo_user')); } if (count($this->attachments->getMessages()->get('attachments')) > 0) { @@ -254,7 +254,7 @@ class CreateController extends Controller } $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); diff --git a/app/Http/Controllers/Recurring/DeleteController.php b/app/Http/Controllers/Recurring/DeleteController.php index f40cad7007..67793ce6ef 100644 --- a/app/Http/Controllers/Recurring/DeleteController.php +++ b/app/Http/Controllers/Recurring/DeleteController.php @@ -53,7 +53,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); @@ -71,7 +71,7 @@ class DeleteController extends Controller */ 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'); @@ -92,7 +92,7 @@ class DeleteController extends Controller 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 bafbac99fb..ab4fd9d231 100644 --- a/app/Http/Controllers/Recurring/EditController.php +++ b/app/Http/Controllers/Recurring/EditController.php @@ -64,8 +64,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->budgetRepos = app(BudgetRepositoryInterface::class); @@ -118,9 +118,9 @@ class EditController extends Controller $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'; @@ -130,22 +130,22 @@ 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 = [ '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'], ]; - $array['first_date'] = substr((string)$array['first_date'], 0, 10); - $array['repeat_until'] = substr((string)$array['repeat_until'], 0, 10); + $array['first_date'] = substr((string) $array['first_date'], 0, 10); + $array['repeat_until'] = substr((string) $array['repeat_until'], 0, 10); $array['transactions'][0]['tags'] = implode(',', $array['transactions'][0]['tags'] ?? []); return view( @@ -171,7 +171,7 @@ class EditController extends Controller $data = $request->getAll(); $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])); // store new attachment(s): $files = $request->hasFile('attachments') ? $request->file('attachments') : null; @@ -179,7 +179,7 @@ class EditController extends Controller $this->attachments->saveAttachmentsForModel($recurrence, $files); } if (null !== $files && auth()->user()->hasRole('demo')) { - session()->flash('info', (string)trans('firefly.no_att_demo_user')); + session()->flash('info', (string) trans('firefly.no_att_demo_user')); } if (count($this->attachments->getMessages()->get('attachments')) > 0) { @@ -187,7 +187,7 @@ class EditController extends Controller } 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 bf1f1e2842..aad08bff71 100644 --- a/app/Http/Controllers/Recurring/IndexController.php +++ b/app/Http/Controllers/Recurring/IndexController.php @@ -58,7 +58,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->recurringRepos = app(RecurringRepositoryInterface::class); @@ -75,12 +75,13 @@ class IndexController extends Controller * * @return Factory|View * @throws FireflyException - * + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ 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->recurringRepos->get(); $today = today(config('app.timezone')); $year = today(config('app.timezone')); diff --git a/app/Http/Controllers/Recurring/ShowController.php b/app/Http/Controllers/Recurring/ShowController.php index be1ed927b1..94b94afcd9 100644 --- a/app/Http/Controllers/Recurring/ShowController.php +++ b/app/Http/Controllers/Recurring/ShowController.php @@ -59,7 +59,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); @@ -94,7 +94,7 @@ 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', 'today')); } diff --git a/app/Http/Controllers/Report/AccountController.php b/app/Http/Controllers/Report/AccountController.php index bb773e54ba..b3485536c8 100644 --- a/app/Http/Controllers/Report/AccountController.php +++ b/app/Http/Controllers/Report/AccountController.php @@ -45,7 +45,6 @@ class AccountController extends Controller * @param Carbon $end * * @return mixed|string - * @throws JsonException */ public function general(Collection $accounts, Carbon $start, Carbon $end) { diff --git a/app/Http/Controllers/Report/BillController.php b/app/Http/Controllers/Report/BillController.php index e248b12c33..d374020f13 100644 --- a/app/Http/Controllers/Report/BillController.php +++ b/app/Http/Controllers/Report/BillController.php @@ -43,7 +43,6 @@ class BillController extends Controller * @param Carbon $end * * @return mixed|string - * @throws JsonException */ public function overview(Collection $accounts, Carbon $start, Carbon $end) { // chart properties for cache: diff --git a/app/Http/Controllers/Report/BudgetController.php b/app/Http/Controllers/Report/BudgetController.php index 4f61005931..331396c26d 100644 --- a/app/Http/Controllers/Report/BudgetController.php +++ b/app/Http/Controllers/Report/BudgetController.php @@ -186,8 +186,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']; } } } @@ -266,7 +266,7 @@ class BudgetController extends Controller $total = $sums[$currencyId]['sum'] ?? '0'; $pct = '0'; if (0 !== bccomp($sum, '0') && 0 !== bccomp($total, '9')) { - $pct = round((float)bcmul(bcdiv($sum, $total), '100')); + $pct = round((float) bcmul(bcdiv($sum, $total), '100')); } $report[$budgetId]['currencies'][$currencyId]['sum_pct'] = $pct; } @@ -348,7 +348,7 @@ 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($periods)); + $report[$key]['avg'] = bcdiv($report[$key]['sum'], (string) count($periods)); } } } @@ -383,9 +383,9 @@ 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), + 'date' => $journal['date']->isoFormat($this->monthAndDayFormat), 'date_sort' => $journal['date']->format('Y-m-d'), 'destination_account_name' => $journal['destination_account_name'], 'destination_account_id' => $journal['destination_account_id'], diff --git a/app/Http/Controllers/Report/CategoryController.php b/app/Http/Controllers/Report/CategoryController.php index 41b9193e4c..945b0868a7 100644 --- a/app/Http/Controllers/Report/CategoryController.php +++ b/app/Http/Controllers/Report/CategoryController.php @@ -300,8 +300,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']; } } } @@ -352,8 +352,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']; } } } @@ -672,7 +672,7 @@ class CategoryController extends Controller try { - $result = (string)view('reports.partials.categories', compact('report'))->render(); + $result = (string) view('reports.partials.categories', compact('report'))->render(); $cache->store($result); } catch (Throwable $e) { // @phpstan-ignore-line Log::error(sprintf('Could not render category::expenses: %s', $e->getMessage())); @@ -700,9 +700,9 @@ 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), + 'date' => $journal['date']->isoFormat($this->monthAndDayFormat), 'date_sort' => $journal['date']->format('Y-m-d'), 'destination_account_name' => $journal['destination_account_name'], 'destination_account_id' => $journal['destination_account_id'], @@ -750,9 +750,9 @@ 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), + 'date' => $journal['date']->isoFormat($this->monthAndDayFormat), 'date_sort' => $journal['date']->format('Y-m-d'), 'source_account_name' => $journal['source_account_name'], 'source_account_id' => $journal['source_account_id'], diff --git a/app/Http/Controllers/Report/DoubleController.php b/app/Http/Controllers/Report/DoubleController.php index 387639f318..5472e9741b 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 @@ -435,9 +435,9 @@ 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), + 'date' => $journal['date']->isoFormat($this->monthAndDayFormat), 'date_sort' => $journal['date']->format('Y-m-d'), 'destination_account_name' => $journal['destination_account_name'], 'destination_account_id' => $journal['destination_account_id'], @@ -485,9 +485,9 @@ 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), + 'date' => $journal['date']->isoFormat($this->monthAndDayFormat), 'date_sort' => $journal['date']->format('Y-m-d'), 'destination_account_name' => $journal['destination_account_name'], 'destination_account_id' => $journal['destination_account_id'], diff --git a/app/Http/Controllers/Report/OperationsController.php b/app/Http/Controllers/Report/OperationsController.php index 9c0a0f1ca0..aba2fd000b 100644 --- a/app/Http/Controllers/Report/OperationsController.php +++ b/app/Http/Controllers/Report/OperationsController.php @@ -67,7 +67,6 @@ class OperationsController extends Controller * @param Carbon $end * * @return mixed|string - * @throws JsonException */ public function expenses(Collection $accounts, Carbon $start, Carbon $end) { @@ -103,7 +102,6 @@ class OperationsController extends Controller * @param Carbon $end * * @return string - * @throws JsonException */ public function income(Collection $accounts, Carbon $start, Carbon $end): string { @@ -139,7 +137,6 @@ class OperationsController extends Controller * @param Carbon $end * * @return mixed|string - * @throws JsonException */ public function operations(Collection $accounts, Carbon $start, Carbon $end) { diff --git a/app/Http/Controllers/Report/TagController.php b/app/Http/Controllers/Report/TagController.php index 476f9f8b3f..bf263bb2a5 100644 --- a/app/Http/Controllers/Report/TagController.php +++ b/app/Http/Controllers/Report/TagController.php @@ -293,8 +293,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']; } } } @@ -345,8 +345,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']; } } } @@ -492,9 +492,9 @@ 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), + 'date' => $journal['date']->isoFormat($this->monthAndDayFormat), 'date_sort' => $journal['date']->format('Y-m-d'), 'destination_account_name' => $journal['destination_account_name'], 'destination_account_id' => $journal['destination_account_id'], @@ -542,9 +542,9 @@ 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), + 'date' => $journal['date']->isoFormat($this->monthAndDayFormat), 'date_sort' => $journal['date']->format('Y-m-d'), 'source_account_name' => $journal['source_account_name'], 'source_account_id' => $journal['source_account_id'], diff --git a/app/Http/Controllers/ReportController.php b/app/Http/Controllers/ReportController.php index 9f5ad667b8..49b5219120 100644 --- a/app/Http/Controllers/ReportController.php +++ b/app/Http/Controllers/ReportController.php @@ -64,7 +64,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-bar-chart'); app('view')->share('subTitleIcon', 'fa-calendar'); $this->helper = app(ReportHelperInterface::class); @@ -89,7 +89,7 @@ class ReportController extends Controller public function auditReport(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(); @@ -98,8 +98,8 @@ class ReportController extends Controller trans( 'firefly.report_audit', [ - 'start' => $start->formatLocalized($this->monthAndDayFormat), - 'end' => $end->formatLocalized($this->monthAndDayFormat), + 'start' => $start->isoFormat($this->monthAndDayFormat), + 'end' => $end->isoFormat($this->monthAndDayFormat), ] ) ); @@ -125,7 +125,7 @@ class ReportController extends Controller 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')); + return view('error')->with('message', (string) trans('firefly.end_after_start_date')); } $this->repository->cleanupBudgets(); @@ -134,8 +134,8 @@ class ReportController extends Controller trans( 'firefly.report_budget', [ - 'start' => $start->formatLocalized($this->monthAndDayFormat), - 'end' => $end->formatLocalized($this->monthAndDayFormat), + 'start' => $start->isoFormat($this->monthAndDayFormat), + 'end' => $end->isoFormat($this->monthAndDayFormat), ] ) ); @@ -162,7 +162,7 @@ class ReportController extends Controller 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')); + return view('error')->with('message', (string) trans('firefly.end_after_start_date')); } $this->repository->cleanupBudgets(); @@ -171,8 +171,8 @@ class ReportController extends Controller trans( 'firefly.report_category', [ - 'start' => $start->formatLocalized($this->monthAndDayFormat), - 'end' => $end->formatLocalized($this->monthAndDayFormat), + 'start' => $start->isoFormat($this->monthAndDayFormat), + 'end' => $end->isoFormat($this->monthAndDayFormat), ] ) ); @@ -198,7 +198,7 @@ class ReportController extends Controller 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(); @@ -208,8 +208,8 @@ class ReportController extends Controller trans( 'firefly.report_default', [ - 'start' => $start->formatLocalized($this->monthAndDayFormat), - 'end' => $end->formatLocalized($this->monthAndDayFormat), + 'start' => $start->isoFormat($this->monthAndDayFormat), + 'end' => $end->isoFormat($this->monthAndDayFormat), ] ) ); @@ -243,7 +243,8 @@ class ReportController extends Controller 'subTitle', trans( 'firefly.report_double', - ['start' => $start->formatLocalized($this->monthAndDayFormat), 'end' => $end->formatLocalized($this->monthAndDayFormat)] + ['start' => $start->isoFormat($this->monthAndDayFormat), + 'end' => $end->isoFormat($this->monthAndDayFormat)] ) ); @@ -261,6 +262,8 @@ class ReportController extends Controller * * @return Factory|View * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function index(AccountRepositoryInterface $repository) { @@ -341,37 +344,37 @@ class ReportController extends Controller 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')); } $uri = match ($reportType) { @@ -400,7 +403,7 @@ class ReportController extends Controller 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')); + return view('error')->with('message', (string) trans('firefly.end_after_start_date')); } $this->repository->cleanupBudgets(); @@ -409,8 +412,8 @@ class ReportController extends Controller trans( 'firefly.report_tag', [ - 'start' => $start->formatLocalized($this->monthAndDayFormat), - 'end' => $end->formatLocalized($this->monthAndDayFormat), + 'start' => $start->isoFormat($this->monthAndDayFormat), + 'end' => $end->isoFormat($this->monthAndDayFormat), ] ) ); diff --git a/app/Http/Controllers/Rule/CreateController.php b/app/Http/Controllers/Rule/CreateController.php index b0b7e8265b..f9f8be07a8 100644 --- a/app/Http/Controllers/Rule/CreateController.php +++ b/app/Http/Controllers/Rule/CreateController.php @@ -60,7 +60,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); @@ -88,7 +88,7 @@ class CreateController extends Controller $oldActions = []; // build triggers from query, if present. - $query = (string)$request->get('from_query'); + $query = (string) $request->get('from_query'); if ('' !== $query) { $search = app(SearchInterface::class); $search->parseQuery($query); @@ -96,7 +96,7 @@ class CreateController extends Controller $operators = $search->getOperators()->toArray(); if ('' !== $words) { session()->flash('warning', trans('firefly.rule_from_search_words', ['string' => $words])); - array_push($operators, ['type' => 'description_contains', 'value' => $words]); + $operators[] = ['type' => 'description_contains', 'value' => $words]; } $oldTriggers = $this->parseFromOperators($operators); } @@ -112,9 +112,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 @@ -142,13 +142,13 @@ class CreateController extends Controller */ 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(); $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. @@ -168,7 +168,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); @@ -193,10 +193,10 @@ 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->description)])); + $request->session()->flash('info', (string) trans('firefly.instructions_rule_from_journal', ['name' => e($journal->description)])); $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); @@ -207,8 +207,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]), ]; // restore actions and triggers from old input: @@ -236,13 +236,12 @@ class CreateController extends Controller } /** - * @param Rule $rule - * + * @param Request $request * @return JsonResponse */ public function duplicate(Request $request): JsonResponse { - $ruleId = (int)$request->get('id'); + $ruleId = (int) $request->get('id'); $rule = $this->ruleRepos->find($ruleId); if (null !== $rule) { $this->ruleRepos->duplicate($rule); @@ -263,22 +262,22 @@ class CreateController extends Controller { $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')])); + if ('true' === $request->get('return_to_bill') && (int) $request->get('bill_id') > 0) { + return redirect(route('bills.show', [(int) $request->get('bill_id')])); } // 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')); } $redirect = redirect($this->getPreviousUri('rules.create.uri')); - if (1 === (int)$request->get('create_another')) { + if (1 === (int) $request->get('create_another')) { session()->put('rules.create.fromStore', true); $redirect = redirect(route('rules.create', [$data['rule_group_id']]))->withInput(); diff --git a/app/Http/Controllers/Rule/DeleteController.php b/app/Http/Controllers/Rule/DeleteController.php index 436e711b25..7d89bd123f 100644 --- a/app/Http/Controllers/Rule/DeleteController.php +++ b/app/Http/Controllers/Rule/DeleteController.php @@ -49,7 +49,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); @@ -68,7 +68,7 @@ class DeleteController extends Controller */ 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'); @@ -88,7 +88,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 9c6021240c..a7aeec0682 100644 --- a/app/Http/Controllers/Rule/EditController.php +++ b/app/Http/Controllers/Rule/EditController.php @@ -59,7 +59,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); @@ -85,7 +85,7 @@ class EditController extends Controller $oldTriggers = []; // build triggers from query, if present. - $query = (string)$request->get('from_query'); + $query = (string) $request->get('from_query'); if ('' !== $query) { $search = app(SearchInterface::class); $search->parseQuery($query); @@ -93,7 +93,7 @@ class EditController extends Controller $operators = $search->getOperators()->toArray(); if ('' !== $words) { session()->flash('warning', trans('firefly.rule_from_search_words', ['string' => $words])); - array_push($operators, ['type' => 'description_contains', 'value' => $words]); + $operators[] = ['type' => 'description_contains', 'value' => $words]; } $oldTriggers = $this->parseFromOperators($operators); } @@ -115,15 +115,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')) { @@ -144,13 +144,13 @@ class EditController extends Controller private function parseFromOperators(array $submittedOperators): array { // See reference nr. 65 - $operators = config('firefly.search.operators'); + $operators = config('search.operators'); $renderedEntries = []; $triggers = []; foreach ($operators as $key => $operator) { if ('user_action' !== $key && false === $operator['alias']) { - $triggers[$key] = (string)trans(sprintf('firefly.rule_trigger_%s_choice', $key)); + $triggers[$key] = (string) trans(sprintf('firefly.rule_trigger_%s_choice', $key)); } } asort($triggers); @@ -191,10 +191,10 @@ class EditController extends Controller $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')) { session()->put('rules.edit.fromUpdate', true); diff --git a/app/Http/Controllers/Rule/IndexController.php b/app/Http/Controllers/Rule/IndexController.php index 98e13cc412..ee3f33ed3a 100644 --- a/app/Http/Controllers/Rule/IndexController.php +++ b/app/Http/Controllers/Rule/IndexController.php @@ -54,7 +54,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); @@ -79,16 +79,16 @@ class IndexController extends Controller } /** - * @param Request $request - * @param Rule $rule + * @param Request $request + * @param Rule $rule * @param RuleGroup $ruleGroup * * @return JsonResponse */ public function moveRule(Request $request, Rule $rule, RuleGroup $ruleGroup): JsonResponse { - $order = (int)$request->get('order'); - $this->ruleRepos->moveRule($rule, $ruleGroup, (int)$order); + $order = (int) $request->get('order'); + $this->ruleRepos->moveRule($rule, $ruleGroup, (int) $order); return response()->json([]); } diff --git a/app/Http/Controllers/Rule/SelectController.php b/app/Http/Controllers/Rule/SelectController.php index 2fc48d7f11..999b46343c 100644 --- a/app/Http/Controllers/Rule/SelectController.php +++ b/app/Http/Controllers/Rule/SelectController.php @@ -58,7 +58,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'); return $next($request); @@ -97,7 +97,7 @@ class SelectController extends Controller $newRuleEngine->fire(); $resultCount = $newRuleEngine->getResults(); - session()->flash('success', (string)trans_choice('firefly.applied_rule_selection', $resultCount, ['title' => $rule->title])); + session()->flash('success', (string) trans_choice('firefly.applied_rule_selection', $resultCount, ['title' => $rule->title])); return redirect()->route('rules.index'); } @@ -119,7 +119,7 @@ class SelectController extends Controller // 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')); } @@ -145,7 +145,7 @@ class SelectController extends Controller // warn if nothing. if (empty($textTriggers)) { - return response()->json(['html' => '', 'warning' => (string)trans('firefly.warning_no_valid_triggers')]); + return response()->json(['html' => '', 'warning' => (string) trans('firefly.warning_no_valid_triggers')]); } foreach ($textTriggers as $textTrigger) { @@ -169,7 +169,7 @@ class SelectController extends Controller // Warn the user if only a subset of transactions is returned $warning = ''; if (empty($collection)) { - $warning = (string)trans('firefly.warning_no_matching_transactions'); + $warning = (string) trans('firefly.warning_no_matching_transactions'); } // Return json response @@ -200,7 +200,7 @@ class SelectController extends Controller $triggers = $rule->ruleTriggers; if (empty($triggers)) { - return response()->json(['html' => '', 'warning' => (string)trans('firefly.warning_no_valid_triggers')]); + return response()->json(['html' => '', 'warning' => (string) trans('firefly.warning_no_valid_triggers')]); } // create new rule engine: $newRuleEngine = app(RuleEngineInterface::class); @@ -212,7 +212,7 @@ class SelectController extends Controller $warning = ''; if (empty($collection)) { - $warning = (string)trans('firefly.warning_no_matching_transactions'); + $warning = (string) trans('firefly.warning_no_matching_transactions'); } // Return json response diff --git a/app/Http/Controllers/RuleGroup/CreateController.php b/app/Http/Controllers/RuleGroup/CreateController.php index 65c44183db..4e58e6a68b 100644 --- a/app/Http/Controllers/RuleGroup/CreateController.php +++ b/app/Http/Controllers/RuleGroup/CreateController.php @@ -50,7 +50,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); @@ -68,7 +68,7 @@ class CreateController extends Controller 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')) { @@ -88,14 +88,14 @@ class CreateController extends Controller */ public function store(RuleGroupFormRequest $request) { - $data = $request->getRuleGroupData(); + $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')) { session()->put('rule-groups.create.fromStore', true); diff --git a/app/Http/Controllers/RuleGroup/DeleteController.php b/app/Http/Controllers/RuleGroup/DeleteController.php index ae87833d8e..d21000ea80 100644 --- a/app/Http/Controllers/RuleGroup/DeleteController.php +++ b/app/Http/Controllers/RuleGroup/DeleteController.php @@ -51,7 +51,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); @@ -70,7 +70,7 @@ class DeleteController extends Controller */ 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'); @@ -81,7 +81,7 @@ class DeleteController extends Controller /** * Actually destroy the rule group. * - * @param Request $request + * @param Request $request * @param RuleGroup $ruleGroup * * @return RedirectResponse|Redirector @@ -91,10 +91,10 @@ class DeleteController extends Controller $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 cca24c8f57..d87122cc64 100644 --- a/app/Http/Controllers/RuleGroup/EditController.php +++ b/app/Http/Controllers/RuleGroup/EditController.php @@ -52,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,39 +62,6 @@ class EditController extends Controller ); } - /** - * Move a rule group in either direction. - * - * @param Request $request - * - * @return JsonResponse - */ - public function moveGroup(Request $request): JsonResponse - { - $groupId = (int)$request->get('id'); - $ruleGroup= $this->repository->find($groupId); - if(null !== $ruleGroup) { - $direction = $request->get('direction'); - if('down' === $direction) { - $maxOrder = $this->repository->maxOrder(); - $order = (int)$ruleGroup->order; - if ($order < $maxOrder) { - $newOrder = $order + 1; - $this->repository->setOrder($ruleGroup, $newOrder); - } - } - if('up' === $direction) { - $order = (int)$ruleGroup->order; - if ($order > 1) { - $newOrder = $order - 1; - $this->repository->setOrder($ruleGroup, $newOrder); - } - } - } - return new JsonResponse(['OK']); - } - - /** * Edit a rule group. * @@ -105,11 +72,11 @@ class EditController extends Controller */ 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, + 'active' => $hasOldInput ? (bool) $request->old('active') : $ruleGroup->active, ]; // put previous url in session if not redirect from store (not "return_to_edit"). if (true !== session('rule-groups.edit.fromUpdate')) { @@ -121,6 +88,38 @@ class EditController extends Controller return view('rules.rule-group.edit', compact('ruleGroup', 'subTitle')); } + /** + * Move a rule group in either direction. + * + * @param Request $request + * + * @return JsonResponse + */ + public function moveGroup(Request $request): JsonResponse + { + $groupId = (int) $request->get('id'); + $ruleGroup = $this->repository->find($groupId); + if (null !== $ruleGroup) { + $direction = $request->get('direction'); + if ('down' === $direction) { + $maxOrder = $this->repository->maxOrder(); + $order = (int) $ruleGroup->order; + if ($order < $maxOrder) { + $newOrder = $order + 1; + $this->repository->setOrder($ruleGroup, $newOrder); + } + } + if ('up' === $direction) { + $order = (int) $ruleGroup->order; + if ($order > 1) { + $newOrder = $order - 1; + $this->repository->setOrder($ruleGroup, $newOrder); + } + } + } + return new JsonResponse(['OK']); + } + /** * Update the rule group. * @@ -134,15 +133,15 @@ class EditController extends Controller $data = [ 'title' => $request->string('title'), 'description' => $request->stringWithNewlines('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')) { session()->put('rule-groups.edit.fromUpdate', true); diff --git a/app/Http/Controllers/RuleGroup/ExecutionController.php b/app/Http/Controllers/RuleGroup/ExecutionController.php index 4868f9d0b3..39d0bc89b8 100644 --- a/app/Http/Controllers/RuleGroup/ExecutionController.php +++ b/app/Http/Controllers/RuleGroup/ExecutionController.php @@ -53,7 +53,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->ruleGroupRepository = app(RuleGroupRepositoryInterface::class); @@ -95,7 +95,7 @@ class ExecutionController extends Controller $newRuleEngine->fire(); // 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'); } @@ -111,7 +111,7 @@ class ExecutionController extends Controller { $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 6eaaed9634..c532600228 100644 --- a/app/Http/Controllers/SearchController.php +++ b/app/Http/Controllers/SearchController.php @@ -46,7 +46,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); } @@ -68,9 +68,9 @@ class SearchController extends Controller if (is_array($request->get('search'))) { $fullQuery = ''; } - $fullQuery = (string)$fullQuery; - $page = 0 === (int)$request->get('page') ? 1 : (int)$request->get('page'); - $ruleId = (int)$request->get('rule'); + $fullQuery = (string) $fullQuery; + $page = 0 === (int) $request->get('page') ? 1 : (int) $request->get('page'); + $ruleId = (int) $request->get('rule'); $ruleChanged = false; // find rule, check if query is different, offer to update. @@ -89,7 +89,7 @@ class SearchController extends Controller $query = $searcher->getWordsAsString(); $operators = $searcher->getOperators(); $invalidOperators = $searcher->getInvalidOperators(); - $subTitle = (string)trans('breadcrumbs.search_result', ['query' => $fullQuery]); + $subTitle = (string) trans('breadcrumbs.search_result', ['query' => $fullQuery]); return view('search.index', compact('query', 'operators', 'page', 'rule', 'fullQuery', 'subTitle', 'ruleId', 'ruleChanged', 'invalidOperators')); } @@ -104,8 +104,8 @@ class SearchController extends Controller */ 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); diff --git a/app/Http/Controllers/System/InstallController.php b/app/Http/Controllers/System/InstallController.php index aabaca5514..5777c8285e 100644 --- a/app/Http/Controllers/System/InstallController.php +++ b/app/Http/Controllers/System/InstallController.php @@ -47,8 +47,8 @@ class InstallController extends Controller { use GetConfigurationData; - public const FORBIDDEN_ERROR = 'Internal PHP function "proc_close" is disabled for your installation. Auto-migration is not possible.'; public const BASEDIR_ERROR = 'Firefly III cannot execute the upgrade commands. It is not allowed to because of an open_basedir restriction.'; + public const FORBIDDEN_ERROR = 'Internal PHP function "proc_close" is disabled for your installation. Auto-migration is not possible.'; public const OTHER_ERROR = 'An unknown error prevented Firefly III from executing the upgrade commands. Sorry.'; private string $lastError; private array $upgradeCommands; @@ -127,10 +127,10 @@ class InstallController extends Controller 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'); } @@ -142,7 +142,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 d7d5c7092c..fc8e26e495 100644 --- a/app/Http/Controllers/TagController.php +++ b/app/Http/Controllers/TagController.php @@ -56,7 +56,7 @@ class TagController extends Controller $this->middleware( function ($request, $next) { - app('view')->share('title', (string)trans('firefly.tags')); + app('view')->share('title', (string) trans('firefly.tags')); app('view')->share('mainTitleIcon', 'fa-tag'); $this->attachmentsHelper = app(AttachmentHelperInterface::class); @@ -74,7 +74,7 @@ class TagController extends Controller */ public function create(Request $request) { - $subTitle = (string)trans('firefly.new_tag'); + $subTitle = (string) trans('firefly.new_tag'); $subTitleIcon = 'fa-tag'; // location info: @@ -106,7 +106,7 @@ class TagController extends Controller */ 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'); @@ -126,7 +126,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')); @@ -141,7 +141,7 @@ class TagController extends Controller */ 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); @@ -202,20 +202,20 @@ class TagController extends Controller { $tags = $request->get('tags'); if (null === $tags || !is_array($tags)) { - session()->flash('info', (string)trans('firefly.select_tags_to_delete')); + session()->flash('info', (string) trans('firefly.select_tags_to_delete')); return redirect(route('tags.index')); } $count = 0; foreach ($tags as $tagId) { - $tagId = (int)$tagId; + $tagId = (int) $tagId; $tag = $this->repository->find($tagId); if (null !== $tag) { $this->repository->destroy($tag); $count++; } } - session()->flash('success', (string)trans_choice('firefly.deleted_x_tags', $count)); + session()->flash('success', (string) trans_choice('firefly.deleted_x_tags', $count)); return redirect(route('tags.index')); } @@ -230,21 +230,23 @@ class TagController extends Controller * * @return Factory|View * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ 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); $attachments = $this->repository->getAttachments($tag); $subTitle = trans( 'firefly.journals_in_period_for_tag', - ['tag' => $tag->tag, 'start' => $start->formatLocalized($this->monthAndDayFormat), - 'end' => $end->formatLocalized($this->monthAndDayFormat),] + ['tag' => $tag->tag, 'start' => $start->isoFormat($this->monthAndDayFormat), + 'end' => $end->isoFormat($this->monthAndDayFormat),] ); $startPeriod = $this->repository->firstUseDate($tag); @@ -273,15 +275,17 @@ class TagController extends Controller * * @return Factory|View * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ 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) ?? today(config('app.timezone')); $end = $this->repository->lastUseDate($tag) ?? today(config('app.timezone')); $attachments = $this->repository->getAttachments($tag); @@ -313,7 +317,7 @@ 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(); // store attachment(s): @@ -323,14 +327,14 @@ class TagController extends Controller $this->attachmentsHelper->saveAttachmentsForModel($result, $files); } if (null !== $files && auth()->user()->hasRole('demo')) { - session()->flash('info', (string)trans('firefly.no_att_demo_user')); + session()->flash('info', (string) trans('firefly.no_att_demo_user')); } if (count($this->attachmentsHelper->getMessages()->get('attachments')) > 0) { $request->session()->flash('info', $this->attachmentsHelper->getMessages()->get('attachments')); } $redirect = redirect($this->getPreviousUri('tags.create.uri')); - if (1 === (int)$request->get('create_another')) { + if (1 === (int) $request->get('create_another')) { session()->put('tags.create.fromStore', true); @@ -354,7 +358,7 @@ class TagController extends Controller $data = $request->collectTagData(); $tag = $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(); // store new attachment(s): @@ -364,14 +368,14 @@ class TagController extends Controller $this->attachmentsHelper->saveAttachmentsForModel($tag, $files); } if (null !== $files && auth()->user()->hasRole('demo')) { - session()->flash('info', (string)trans('firefly.no_att_demo_user')); + session()->flash('info', (string) trans('firefly.no_att_demo_user')); } if (count($this->attachmentsHelper->getMessages()->get('attachments')) > 0) { $request->session()->flash('info', $this->attachmentsHelper->getMessages()->get('attachments')); } $redirect = redirect($this->getPreviousUri('tags.edit.uri')); - if (1 === (int)$request->get('return_to_edit')) { + if (1 === (int) $request->get('return_to_edit')) { session()->put('tags.edit.fromUpdate', true); diff --git a/app/Http/Controllers/Transaction/BulkController.php b/app/Http/Controllers/Transaction/BulkController.php index d1fbce2a75..326251eed0 100644 --- a/app/Http/Controllers/Transaction/BulkController.php +++ b/app/Http/Controllers/Transaction/BulkController.php @@ -55,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-exchange'); return $next($request); @@ -74,7 +74,7 @@ class BulkController extends Controller */ 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,16 +97,16 @@ class BulkController extends Controller */ public function update(BulkEditJournalRequest $request) { - $journalIds = $request->get('journals'); - $journalIds = is_array($journalIds) ? $journalIds : []; - $ignoreCategory = 1 === (int)$request->get('ignore_category'); - $ignoreBudget = 1 === (int)$request->get('ignore_budget'); - $tagsAction = $request->get('tags_action'); + $journalIds = $request->get('journals'); + $journalIds = is_array($journalIds) ? $journalIds : []; + $ignoreCategory = 1 === (int) $request->get('ignore_category'); + $ignoreBudget = 1 === (int) $request->get('ignore_budget'); + $tagsAction = $request->get('tags_action'); $count = 0; foreach ($journalIds as $journalId) { - $journalId = (int)$journalId; + $journalId = (int) $journalId; $journal = $this->repository->find($journalId); if (null !== $journal) { $resultA = $this->updateJournalBudget($journal, $ignoreBudget, $request->integer('budget_id')); @@ -118,7 +118,7 @@ class BulkController extends Controller } } app('preferences')->mark(); - $request->session()->flash('success', (string)trans_choice('firefly.mass_edited_transactions_success', $count)); + $request->session()->flash('success', (string) trans_choice('firefly.mass_edited_transactions_success', $count)); // redirect to previous URL: return redirect($this->getPreviousUri('transactions.bulk-edit.uri')); diff --git a/app/Http/Controllers/Transaction/ConvertController.php b/app/Http/Controllers/Transaction/ConvertController.php index b27c139266..6fe58158ac 100644 --- a/app/Http/Controllers/Transaction/ConvertController.php +++ b/app/Http/Controllers/Transaction/ConvertController.php @@ -70,7 +70,7 @@ class ConvertController extends Controller function ($request, $next) { $this->repository = app(JournalRepositoryInterface::class); $this->accountRepository = app(AccountRepositoryInterface::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); @@ -103,7 +103,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: @@ -119,7 +119,7 @@ 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])); } @@ -156,7 +156,7 @@ class ConvertController extends Controller // group accounts: /** @var Account $account */ foreach ($accountList as $account) { - $role = (string)$this->accountRepository->getMetaValue($account, 'account_role'); + $role = (string) $this->accountRepository->getMetaValue($account, 'account_role'); $name = $account->name; if ('' === $role) { $role = 'no_account_type'; @@ -176,7 +176,7 @@ class ConvertController extends Controller $role = 'revenue_account'; } - $key = (string)trans('firefly.opt_group_' . $role); + $key = (string) trans('firefly.opt_group_' . $role); $grouped[$key][$account->id] = $name; } @@ -197,7 +197,7 @@ class ConvertController extends Controller // group accounts: /** @var Account $account */ foreach ($accountList as $account) { - $role = (string)$this->accountRepository->getMetaValue($account, 'account_role'); + $role = (string) $this->accountRepository->getMetaValue($account, 'account_role'); $name = $account->name; if ('' === $role) { $role = 'no_account_type'; @@ -217,7 +217,7 @@ class ConvertController extends Controller $role = 'expense_account'; } - $key = (string)trans('firefly.opt_group_' . $role); + $key = (string) trans('firefly.opt_group_' . $role); $grouped[$key][$account->id] = $name; } @@ -240,7 +240,7 @@ class ConvertController extends Controller $balance = app('steam')->balance($account, today()); $currency = $this->accountRepository->getAccountCurrency($account) ?? $defaultCurrency; $role = 'l_' . $account->accountType->type; - $key = (string)trans('firefly.opt_group_' . $role); + $key = (string) trans('firefly.opt_group_' . $role); $grouped[$key][$account->id] = $account->name . ' (' . app('amount')->formatAnything($currency, $balance, false) . ')'; } @@ -262,12 +262,12 @@ class ConvertController extends Controller foreach ($accountList as $account) { $balance = app('steam')->balance($account, today()); $currency = $this->accountRepository->getAccountCurrency($account) ?? $defaultCurrency; - $role = (string)$this->accountRepository->getMetaValue($account, 'account_role'); + $role = (string) $this->accountRepository->getMetaValue($account, 'account_role'); if ('' === $role) { $role = 'no_account_type'; } - $key = (string)trans('firefly.opt_group_' . $role); + $key = (string) trans('firefly.opt_group_' . $role); $grouped[$key][$account->id] = $account->name . ' (' . app('amount')->formatAnything($currency, $balance, false) . ')'; } @@ -305,7 +305,7 @@ class ConvertController extends Controller // correct transfers: $group->refresh(); - session()->flash('success', (string)trans('firefly.converted_to_' . $destinationType->type)); + session()->flash('success', (string) trans('firefly.converted_to_' . $destinationType->type)); event(new UpdatedTransactionGroup($group)); return redirect(route('transactions.show', [$group->id])); @@ -332,10 +332,10 @@ 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; - $sourceName = '' === $sourceName ? null : (string)$sourceName; - $destinationId = '' === $destinationId || null === $destinationId ? null : (int)$destinationId; - $destinationName = '' === $destinationName ? null : (string)$destinationName; + $sourceId = '' === $sourceId || null === $sourceId ? null : (int) $sourceId; + $sourceName = '' === $sourceName ? null : (string) $sourceName; + $destinationId = '' === $destinationId || null === $destinationId ? null : (int) $destinationId; + $destinationName = '' === $destinationName ? null : (string) $destinationName; $validSource = $validator->validateSource(['id' => $sourceId, 'name' => $sourceName,]); $validDestination = $validator->validateDestination(['id' => $destinationId, 'name' => $destinationName,]); diff --git a/app/Http/Controllers/Transaction/CreateController.php b/app/Http/Controllers/Transaction/CreateController.php index f57160fed3..cd8ae3c017 100644 --- a/app/Http/Controllers/Transaction/CreateController.php +++ b/app/Http/Controllers/Transaction/CreateController.php @@ -52,7 +52,7 @@ class CreateController 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-exchange'); $this->repository = app(TransactionGroupRepositoryInterface::class); @@ -68,7 +68,7 @@ class CreateController extends Controller */ public function cloneGroup(Request $request): JsonResponse { - $groupId = (int)$request->get('id'); + $groupId = (int) $request->get('id'); if (0 !== $groupId) { $group = $this->repository->find($groupId); if (null !== $group) { @@ -100,19 +100,22 @@ class CreateController extends Controller * * @return Factory|View * @throws FireflyException + * @throws \JsonException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ 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 $accountRepository */ $accountRepository = app(AccountRepositoryInterface::class); $cash = $accountRepository->getCashAccount(); $preFilled = session()->has('preFilled') ? session('preFilled') : []; - $subTitle = (string)trans(sprintf('breadcrumbs.create_%s', strtolower((string)$objectType))); + $subTitle = (string) trans(sprintf('breadcrumbs.create_%s', strtolower((string) $objectType))); $subTitleIcon = 'fa-plus'; $optionalFields = app('preferences')->get('transaction_journal_optional_fields', [])->data; $allowedOpposingTypes = config('firefly.allowed_opposing_types'); diff --git a/app/Http/Controllers/Transaction/DeleteController.php b/app/Http/Controllers/Transaction/DeleteController.php index 1b01269edb..9941c1e23e 100644 --- a/app/Http/Controllers/Transaction/DeleteController.php +++ b/app/Http/Controllers/Transaction/DeleteController.php @@ -32,7 +32,6 @@ use Illuminate\Http\RedirectResponse; use Illuminate\Routing\Redirector; use Log; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; -use URL; /** * Class DeleteController @@ -53,7 +52,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-exchange'); $this->repository = app(TransactionGroupRepositoryInterface::class); @@ -83,7 +82,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 = app('steam')->getSafePreviousUrl(route('index')); // put previous url in session Log::debug('Will try to remember previous URI'); @@ -110,7 +109,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 fa755c250b..f7351aac60 100644 --- a/app/Http/Controllers/Transaction/EditController.php +++ b/app/Http/Controllers/Transaction/EditController.php @@ -49,7 +49,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-exchange'); return $next($request); @@ -71,11 +71,11 @@ class EditController extends Controller } /** @var AccountRepositoryInterface $repository */ - $repository = app(AccountRepositoryInterface::class); + $repository = app(AccountRepositoryInterface::class); $allowedOpposingTypes = config('firefly.allowed_opposing_types'); - $accountToTypes = config('firefly.account_to_transaction'); - $expectedSourceTypes = config('firefly.expected_source_types'); - $allowedSourceDests = config('firefly.source_dests'); + $accountToTypes = config('firefly.account_to_transaction'); + $expectedSourceTypes = config('firefly.expected_source_types'); + $allowedSourceDests = config('firefly.source_dests'); // $defaultCurrency = app('amount')->getDefaultCurrency(); diff --git a/app/Http/Controllers/Transaction/IndexController.php b/app/Http/Controllers/Transaction/IndexController.php index adc0eaa590..77808e48dd 100644 --- a/app/Http/Controllers/Transaction/IndexController.php +++ b/app/Http/Controllers/Transaction/IndexController.php @@ -55,7 +55,7 @@ class IndexController extends Controller $this->middleware( function ($request, $next) { app('view')->share('mainTitleIcon', 'fa-exchange'); - app('view')->share('title', (string)trans('firefly.transactions')); + app('view')->share('title', (string) trans('firefly.transactions')); $this->repository = app(JournalRepositoryInterface::class); @@ -73,7 +73,9 @@ class IndexController extends Controller * @param Carbon|null $end * * @return Factory|View - * @throws Exception + * @throws \FireflyIII\Exceptions\FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function index(Request $request, string $objectType, Carbon $start = null, Carbon $end = null) { @@ -83,8 +85,8 @@ class IndexController extends Controller $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'); @@ -97,9 +99,9 @@ class IndexController extends Controller [$start, $end] = $end < $start ? [$end, $start] : [$start, $end]; $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]); + $startStr = $start->isoFormat($this->monthAndDayFormat); + $endStr = $end->isoFormat($this->monthAndDayFormat); + $subTitle = (string) trans(sprintf('firefly.title_%s_between', $objectType), ['start' => $startStr, 'end' => $endStr]); $firstJournal = $this->repository->firstNull(); $startPeriod = null === $firstJournal ? new Carbon : $firstJournal->date; @@ -130,20 +132,22 @@ class IndexController extends Controller * @param string $objectType * * @return Factory|View - * @throws Exception + * @throws \FireflyIII\Exceptions\FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function indexAll(Request $request, string $objectType) { $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; $path = route('transactions.index.all', [$objectType]); $first = $this->repository->firstNull(); $start = null === $first ? new Carbon : $first->date; $last = $this->repository->getLast(); $end = $last ? $last->date : today(config('app.timezone')); - $subTitle = (string)trans('firefly.all_' . $objectType); + $subTitle = (string) trans('firefly.all_' . $objectType); /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); diff --git a/app/Http/Controllers/Transaction/LinkController.php b/app/Http/Controllers/Transaction/LinkController.php index 7f8c3d5c9d..531dcc8c1c 100644 --- a/app/Http/Controllers/Transaction/LinkController.php +++ b/app/Http/Controllers/Transaction/LinkController.php @@ -34,14 +34,13 @@ use Illuminate\Http\Request; use Illuminate\Routing\Redirector; use Illuminate\View\View; use Log; -use URL; /** * Class LinkController. */ class LinkController extends Controller { - private JournalRepositoryInterface $journalRepository; + private JournalRepositoryInterface $journalRepository; private LinkTypeRepositoryInterface $repository; /** @@ -55,7 +54,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-exchange'); $this->journalRepository = app(JournalRepositoryInterface::class); @@ -76,7 +75,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')); @@ -93,10 +92,10 @@ class LinkController extends Controller { $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')); } /** @@ -126,7 +125,7 @@ class LinkController extends Controller Log::debug('We are here (store)'); $other = $this->journalRepository->find($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])); } @@ -134,19 +133,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])); } @@ -154,13 +153,12 @@ class LinkController extends Controller /** * Switch link from A <> B to B <> A. * - * @param TransactionJournalLink $link - * + * @param Request $request * @return RedirectResponse|Redirector */ public function switchLink(Request $request) { - $linkId = (int)$request->get('id'); + $linkId = (int) $request->get('id'); $this->repository->switchLinkById($linkId); return redirect(app('steam')->getSafePreviousUrl()); diff --git a/app/Http/Controllers/Transaction/MassController.php b/app/Http/Controllers/Transaction/MassController.php index 5b9fafd21d..541a75e5cb 100644 --- a/app/Http/Controllers/Transaction/MassController.php +++ b/app/Http/Controllers/Transaction/MassController.php @@ -61,7 +61,7 @@ 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-exchange'); $this->repository = app(JournalRepositoryInterface::class); @@ -79,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'); @@ -104,15 +104,15 @@ class MassController extends Controller foreach ($ids as $journalId) { /** @var TransactionJournal $journal */ - $journal = $this->repository->find((int)$journalId); - if (null !== $journal && (int)$journalId === $journal->id) { + $journal = $this->repository->find((int) $journalId); + if (null !== $journal && (int) $journalId === $journal->id) { $this->repository->destroyJournal($journal); ++$count; } } } app('preferences')->mark(); - session()->flash('success', (string)trans_choice('firefly.mass_deleted_transactions_success', $count)); + session()->flash('success', (string) trans_choice('firefly.mass_deleted_transactions_success', $count)); // redirect to previous URL: return redirect($this->getPreviousUri('transactions.mass-delete.uri')); @@ -127,7 +127,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 $accountRepository */ $accountRepository = app(AccountRepositoryInterface::class); @@ -146,7 +146,7 @@ class MassController extends Controller // reverse amounts foreach ($journals as $index => $journal) { - $journals[$index]['amount'] = number_format((float) app('steam')->positive($journal['amount']), $journal['currency_decimal_places'],'.',''); + $journals[$index]['amount'] = number_format((float) app('steam')->positive($journal['amount']), $journal['currency_decimal_places'], '.', ''); $journals[$index]['foreign_amount'] = null === $journal['foreign_amount'] ? null : app('steam')->positive($journal['foreign_amount']); } @@ -174,7 +174,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++; @@ -184,7 +184,7 @@ class MassController extends Controller } app('preferences')->mark(); - session()->flash('success', (string)trans_choice('firefly.mass_edited_transactions_success', $count)); + session()->flash('success', (string) trans_choice('firefly.mass_edited_transactions_success', $count)); // redirect to previous URL: return redirect($this->getPreviousUri('transactions.mass-edit.uri')); @@ -273,7 +273,7 @@ class MassController extends Controller return null; } - return (string)$value[$journalId]; + return (string) $value[$journalId]; } /** @@ -294,6 +294,6 @@ class MassController extends Controller return null; } - return (int)$value[$journalId]; + return (int) $value[$journalId]; } } diff --git a/app/Http/Controllers/Transaction/ShowController.php b/app/Http/Controllers/Transaction/ShowController.php index 2642bcdf3a..ed1aee98fb 100644 --- a/app/Http/Controllers/Transaction/ShowController.php +++ b/app/Http/Controllers/Transaction/ShowController.php @@ -54,7 +54,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); @@ -89,7 +89,7 @@ class ShowController extends Controller 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); diff --git a/app/Http/Middleware/Authenticate.php b/app/Http/Middleware/Authenticate.php index 136a3a3262..341c605609 100644 --- a/app/Http/Middleware/Authenticate.php +++ b/app/Http/Middleware/Authenticate.php @@ -98,10 +98,10 @@ class Authenticate /** @noinspection PhpUndefinedMethodInspection */ /** @var User $user */ $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/Installer.php b/app/Http/Middleware/Installer.php index a9184ae5d2..b5f6cee268 100644 --- a/app/Http/Middleware/Installer.php +++ b/app/Http/Middleware/Installer.php @@ -145,8 +145,8 @@ 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( @@ -172,8 +172,8 @@ 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( diff --git a/app/Http/Middleware/InterestingMessage.php b/app/Http/Middleware/InterestingMessage.php index 074e956bac..508eeb579c 100644 --- a/app/Http/Middleware/InterestingMessage.php +++ b/app/Http/Middleware/InterestingMessage.php @@ -102,7 +102,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; @@ -118,17 +118,17 @@ class InterestingMessage $title = $count > 1 ? $group->title : $journal->description; if ('created' === $message) { session()->flash('success_url', route('transactions.show', [$transactionGroupId])); - session()->flash('success', (string)trans('firefly.stored_journal', ['description' => $title])); + session()->flash('success', (string) trans('firefly.stored_journal', ['description' => $title])); } if ('updated' === $message) { $type = strtolower($journal->transactionType->type); session()->flash('success_url', route('transactions.show', [$transactionGroupId])); - session()->flash('success', (string)trans(sprintf('firefly.updated_%s', $type), ['description' => $title])); + session()->flash('success', (string) trans(sprintf('firefly.updated_%s', $type), ['description' => $title])); } if ('no_change' === $message) { $type = strtolower($journal->transactionType->type); session()->flash('warning_url', route('transactions.show', [$transactionGroupId])); - session()->flash('warning', (string)trans(sprintf('firefly.no_changes_%s', $type), ['description' => $title])); + session()->flash('warning', (string) trans(sprintf('firefly.no_changes_%s', $type), ['description' => $title])); } } @@ -163,13 +163,13 @@ class InterestingMessage return; } if ('deleted' === $message) { - session()->flash('success', (string)trans('firefly.account_deleted', ['name' => $account->name])); + session()->flash('success', (string) trans('firefly.account_deleted', ['name' => $account->name])); } if ('created' === $message) { - session()->flash('success', (string)trans('firefly.stored_new_account', ['name' => $account->name])); + session()->flash('success', (string) trans('firefly.stored_new_account', ['name' => $account->name])); } if ('updated' === $message) { - session()->flash('success', (string)trans('firefly.updated_account', ['name' => $account->name])); + session()->flash('success', (string) trans('firefly.updated_account', ['name' => $account->name])); } } @@ -204,10 +204,10 @@ class InterestingMessage return; } if ('deleted' === $message) { - session()->flash('success', (string)trans('firefly.deleted_bill', ['name' => $bill->name])); + session()->flash('success', (string) trans('firefly.deleted_bill', ['name' => $bill->name])); } if ('created' === $message) { - session()->flash('success', (string)trans('firefly.stored_new_bill', ['name' => $bill->name])); + session()->flash('success', (string) trans('firefly.stored_new_bill', ['name' => $bill->name])); } } } diff --git a/app/Http/Middleware/IsDemoUser.php b/app/Http/Middleware/IsDemoUser.php index 1ce1bf9647..f3d915530f 100644 --- a/app/Http/Middleware/IsDemoUser.php +++ b/app/Http/Middleware/IsDemoUser.php @@ -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/Range.php b/app/Http/Middleware/Range.php index 4a64f3989d..45351ff4bf 100644 --- a/app/Http/Middleware/Range.php +++ b/app/Http/Middleware/Range.php @@ -113,12 +113,12 @@ class Range } // save some formats: - $monthAndDayFormat = (string)trans('config.month_and_day', [], $locale); - $dateTimeFormat = (string)trans('config.date_time', [], $locale); + $monthAndDayFormat = (string) trans('config.month_and_day_js', [], $locale); + $dateTimeFormat = (string) trans('config.date_time_js', [], $locale); $defaultCurrency = app('amount')->getDefaultCurrency(); // also format for moment JS: - $madMomentJS = (string)trans('config.month_and_day_moment_js', [], $locale); + $madMomentJS = (string) trans('config.month_and_day_moment_js', [], $locale); app('view')->share('madMomentJS', $madMomentJS); app('view')->share('monthAndDayFormat', $monthAndDayFormat); diff --git a/app/Http/Middleware/SecureHeaders.php b/app/Http/Middleware/SecureHeaders.php index b2c5040815..462c6e7ee0 100644 --- a/app/Http/Middleware/SecureHeaders.php +++ b/app/Http/Middleware/SecureHeaders.php @@ -64,8 +64,8 @@ class SecureHeaders $route = $request->route(); $customUrl = ''; - $authGuard = (string)config('firefly.authentication_guard'); - $logoutUrl = (string)config('firefly.custom_logout_url'); + $authGuard = (string) config('firefly.authentication_guard'); + $logoutUrl = (string) config('firefly.custom_logout_url'); if ('remote_user_guard' === $authGuard && '' !== $logoutUrl) { $customUrl = $logoutUrl; } @@ -115,8 +115,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 1b8d974f1c..20d1d7d4e6 100644 --- a/app/Http/Middleware/StartFireflySession.php +++ b/app/Http/Middleware/StartFireflySession.php @@ -25,7 +25,6 @@ namespace FireflyIII\Http\Middleware; use Illuminate\Contracts\Session\Session; use Illuminate\Http\Request; use Illuminate\Session\Middleware\StartSession; -use Log; /** * Class StartFireflySession. diff --git a/app/Http/Middleware/TrustProxies.php b/app/Http/Middleware/TrustProxies.php index 9ae5ff8773..022d1a1858 100644 --- a/app/Http/Middleware/TrustProxies.php +++ b/app/Http/Middleware/TrustProxies.php @@ -22,8 +22,8 @@ declare(strict_types=1); namespace FireflyIII\Http\Middleware; -use Fideloper\Proxy\TrustProxies as Middleware; -use Illuminate\Contracts\Config\Repository; +use Illuminate\Http\Middleware\TrustProxies as Middleware; +use Symfony\Component\HttpFoundation\Request; /** * Class TrustProxies @@ -32,14 +32,19 @@ use Illuminate\Contracts\Config\Repository; */ class TrustProxies extends Middleware { + // After... + protected $headers = + Request::HEADER_X_FORWARDED_FOR | + Request::HEADER_X_FORWARDED_HOST | + Request::HEADER_X_FORWARDED_PORT | + Request::HEADER_X_FORWARDED_PROTO | + Request::HEADER_X_FORWARDED_AWS_ELB; + /** * TrustProxies constructor. - * - * @param Repository $config */ - public function __construct(Repository $config) + public function __construct() { - $this->proxies = (string)config('firefly.trusted_proxies'); - parent::__construct($config); + $this->proxies = (string) config('firefly.trusted_proxies'); } } diff --git a/app/Http/Requests/BillStoreRequest.php b/app/Http/Requests/BillStoreRequest.php index aec73c412a..ec1d0f1077 100644 --- a/app/Http/Requests/BillStoreRequest.php +++ b/app/Http/Requests/BillStoreRequest.php @@ -47,6 +47,8 @@ class BillStoreRequest extends FormRequest 'currency_code' => '', 'amount_max' => $this->string('amount_max'), 'date' => $this->getCarbonDate('date'), + 'end_date' => $this->getCarbonDate('bill_end_date'), + 'extension_date' => $this->getCarbonDate('extension_date'), 'repeat_freq' => $this->string('repeat_freq'), 'skip' => $this->integer('skip'), 'notes' => $this->stringWithNewlines('notes'), @@ -68,6 +70,8 @@ class BillStoreRequest extends FormRequest 'amount_max' => 'required|numeric|gt:0|max:1000000000', 'transaction_currency_id' => 'required|exists:transaction_currencies,id', 'date' => 'required|date', + 'bill_end_date' => 'nullable|date', + 'extension_date' => 'nullable|date', 'repeat_freq' => sprintf('required|in:%s', join(',', config('firefly.bill_periods'))), 'skip' => 'required|integer|gte:0|lte:31', 'active' => 'boolean', diff --git a/app/Http/Requests/BillUpdateRequest.php b/app/Http/Requests/BillUpdateRequest.php index 259fe629d3..359dfc7bf0 100644 --- a/app/Http/Requests/BillUpdateRequest.php +++ b/app/Http/Requests/BillUpdateRequest.php @@ -48,6 +48,8 @@ class BillUpdateRequest extends FormRequest 'currency_code' => '', 'amount_max' => $this->string('amount_max'), 'date' => $this->getCarbonDate('date'), + 'end_date' => $this->getCarbonDate('bill_end_date'), + 'extension_date' => $this->getCarbonDate('extension_date'), 'repeat_freq' => $this->string('repeat_freq'), 'skip' => $this->integer('skip'), 'notes' => $this->stringWithNewlines('notes'), @@ -72,6 +74,8 @@ class BillUpdateRequest extends FormRequest 'amount_max' => 'required|numeric|gt:0|max:1000000000', 'transaction_currency_id' => 'required|exists:transaction_currencies,id', 'date' => 'required|date', + 'bill_end_date' => 'nullable|date', + 'extension_date' => 'nullable|date', 'repeat_freq' => sprintf('required|in:%s', join(',', config('firefly.bill_periods'))), 'skip' => 'required|integer|gte:0|lte:31', 'active' => 'boolean', diff --git a/app/Http/Requests/CurrencyFormRequest.php b/app/Http/Requests/CurrencyFormRequest.php index a73fcc91c9..ce85fe0f43 100644 --- a/app/Http/Requests/CurrencyFormRequest.php +++ b/app/Http/Requests/CurrencyFormRequest.php @@ -59,9 +59,9 @@ class CurrencyFormRequest extends FormRequest { // fixed $rules = [ - 'name' => 'required|max:48|min:1|unique:transaction_currencies,name', - 'code' => 'required|min:3|max:51|unique:transaction_currencies,code', - 'symbol' => 'required|min:1|max:51|unique:transaction_currencies,symbol', + 'name' => 'required|max:48|min:1|uniqueCurrencyName', + 'code' => 'required|min:3|max:51|uniqueCurrencyCode', + 'symbol' => 'required|min:1|max:51|uniqueCurrencySymbol', 'decimal_places' => 'required|min:0|max:12|numeric', 'enabled' => 'in:0,1', ]; diff --git a/app/Http/Requests/JournalLinkRequest.php b/app/Http/Requests/JournalLinkRequest.php index 9b99deff7b..fd7370e2ba 100644 --- a/app/Http/Requests/JournalLinkRequest.php +++ b/app/Http/Requests/JournalLinkRequest.php @@ -44,7 +44,7 @@ class JournalLinkRequest extends FormRequest $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/PiggyBankStoreRequest.php b/app/Http/Requests/PiggyBankStoreRequest.php index 109e64e860..9e5a62b96f 100644 --- a/app/Http/Requests/PiggyBankStoreRequest.php +++ b/app/Http/Requests/PiggyBankStoreRequest.php @@ -61,7 +61,7 @@ class PiggyBankStoreRequest extends FormRequest return [ 'name' => 'required|between:1,255|uniquePiggyBankForUser', 'account_id' => 'required|belongsToUser:accounts', - 'targetamount' => 'required|numeric|gte:0.01|max:1000000000', + 'targetamount' => 'nullable|numeric|max:1000000000', 'startdate' => 'date', 'targetdate' => 'date|nullable', 'order' => 'integer|min:1', diff --git a/app/Http/Requests/PiggyBankUpdateRequest.php b/app/Http/Requests/PiggyBankUpdateRequest.php index 2aa30af498..c15dfa9ca9 100644 --- a/app/Http/Requests/PiggyBankUpdateRequest.php +++ b/app/Http/Requests/PiggyBankUpdateRequest.php @@ -65,7 +65,7 @@ class PiggyBankUpdateRequest extends FormRequest return [ 'name' => sprintf('required|between:1,255|uniquePiggyBankForUser:%d', $piggy->id), 'account_id' => 'required|belongsToUser:accounts', - 'targetamount' => 'required|numeric|gte:0.01|max:1000000000', + 'targetamount' => 'nullable|numeric|max:1000000000', 'startdate' => 'date', 'targetdate' => 'date|nullable', 'order' => 'integer|min:1', diff --git a/app/Http/Requests/RecurrenceFormRequest.php b/app/Http/Requests/RecurrenceFormRequest.php index 7ffcddb415..9d481118f6 100644 --- a/app/Http/Requests/RecurrenceFormRequest.php +++ b/app/Http/Requests/RecurrenceFormRequest.php @@ -313,16 +313,16 @@ class RecurrenceFormRequest extends FormRequest default: throw new FireflyException(sprintf('Cannot handle transaction type "%s"', $this->string('transaction_type'))); 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; } // validate source account. @@ -330,7 +330,7 @@ class RecurrenceFormRequest extends FormRequest // 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); @@ -341,7 +341,7 @@ class RecurrenceFormRequest extends FormRequest $validDestination = $accountValidator->validateDestination(['id' => $destinationId,]); // 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 b28ea86c46..01ad7ff42a 100644 --- a/app/Http/Requests/ReportFormRequest.php +++ b/app/Http/Requests/ReportFormRequest.php @@ -55,7 +55,7 @@ class ReportFormRequest extends FormRequest $collection = new Collection; if (is_array($set)) { foreach ($set as $accountId) { - $account = $repository->find((int)$accountId); + $account = $repository->find((int) $accountId); if (null !== $account) { $collection->push($account); } @@ -78,7 +78,7 @@ class ReportFormRequest extends FormRequest $collection = new Collection; if (is_array($set)) { foreach ($set as $budgetId) { - $budget = $repository->find((int)$budgetId); + $budget = $repository->find((int) $budgetId); if (null !== $budget) { $collection->push($budget); } @@ -101,7 +101,7 @@ class ReportFormRequest extends FormRequest $collection = new Collection; if (is_array($set)) { foreach ($set as $categoryId) { - $category = $repository->find((int)$categoryId); + $category = $repository->find((int) $categoryId); if (null !== $category) { $collection->push($category); } @@ -124,7 +124,7 @@ class ReportFormRequest extends FormRequest $collection = new Collection; if (is_array($set)) { foreach ($set as $accountId) { - $account = $repository->find((int)$accountId); + $account = $repository->find((int) $accountId); if (null !== $account) { $collection->push($account); } @@ -145,7 +145,7 @@ class ReportFormRequest extends FormRequest { $date = today(config('app.timezone')); $range = $this->get('daterange'); - $parts = explode(' - ', (string)$range); + $parts = explode(' - ', (string) $range); if (2 === count($parts)) { $string = $parts[1]; // validate as date @@ -179,7 +179,7 @@ class ReportFormRequest extends FormRequest { $date = today(config('app.timezone')); $range = $this->get('daterange'); - $parts = explode(' - ', (string)$range); + $parts = explode(' - ', (string) $range); if (2 === count($parts)) { $string = $parts[0]; // validate as date @@ -223,7 +223,7 @@ class ReportFormRequest extends FormRequest $collection->push($tag); continue; } - $tag = $repository->find((int)$tagTag); + $tag = $repository->find((int) $tagTag); if (null !== $tag) { $collection->push($tag); } diff --git a/app/Http/Requests/RuleFormRequest.php b/app/Http/Requests/RuleFormRequest.php index df558c61d2..640f9ddb8b 100644 --- a/app/Http/Requests/RuleFormRequest.php +++ b/app/Http/Requests/RuleFormRequest.php @@ -69,7 +69,7 @@ class RuleFormRequest extends FormRequest $return[] = [ 'type' => $trigger['type'] ?? 'invalid', 'value' => $trigger['value'] ?? '', - 'stop_processing' => 1 === (int)$stopProcessing, + 'stop_processing' => 1 === (int) $stopProcessing, ]; } } @@ -90,7 +90,7 @@ class RuleFormRequest extends FormRequest $return[] = [ 'type' => $action['type'] ?? 'invalid', 'value' => $action['value'] ?? '', - 'stop_processing' => 1 === (int)$stopProcessing, + 'stop_processing' => 1 === (int) $stopProcessing, ]; } } diff --git a/app/Jobs/CreateAutoBudgetLimits.php b/app/Jobs/CreateAutoBudgetLimits.php index d66fd58c08..2f30b0fd53 100644 --- a/app/Jobs/CreateAutoBudgetLimits.php +++ b/app/Jobs/CreateAutoBudgetLimits.php @@ -130,7 +130,7 @@ class CreateAutoBudgetLimits implements ShouldQueue // find budget limit: $budgetLimit = $this->findBudgetLimit($autoBudget->budget, $start, $end); - if (null === $budgetLimit && AutoBudget::AUTO_BUDGET_RESET === (int)$autoBudget->auto_budget_type) { + if (null === $budgetLimit && AutoBudget::AUTO_BUDGET_RESET === (int) $autoBudget->auto_budget_type) { // that's easy: create one. // do nothing else. $this->createBudgetLimit($autoBudget, $start, $end); @@ -139,7 +139,7 @@ class CreateAutoBudgetLimits implements ShouldQueue return; } - if (null === $budgetLimit && AutoBudget::AUTO_BUDGET_ROLLOVER === (int)$autoBudget->auto_budget_type) { + if (null === $budgetLimit && AutoBudget::AUTO_BUDGET_ROLLOVER === (int) $autoBudget->auto_budget_type) { // budget limit exists already, $this->createRollover($autoBudget); Log::debug(sprintf('Done with auto budget #%d', $autoBudget->id)); @@ -277,7 +277,7 @@ class CreateAutoBudgetLimits implements ShouldQueue $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; + $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)); diff --git a/app/Jobs/CreateRecurringTransactions.php b/app/Jobs/CreateRecurringTransactions.php index 370abf6eaa..f9ea125eab 100644 --- a/app/Jobs/CreateRecurringTransactions.php +++ b/app/Jobs/CreateRecurringTransactions.php @@ -250,6 +250,7 @@ class CreateRecurringTransactions implements ShouldQueue private function hasNotStartedYet(Recurrence $recurrence): bool { $startDate = $this->getStartDate($recurrence); + Log::debug(sprintf('Start date is %s', $startDate->format('Y-m-d'))); return $startDate->gt($this->date); } @@ -290,6 +291,8 @@ class CreateRecurringTransactions implements ShouldQueue * @param Recurrence $recurrence * * @return Collection + * @throws DuplicateTransactionException + * @throws FireflyException */ private function handleRepetitions(Recurrence $recurrence): Collection { @@ -429,7 +432,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' => $transactions->first()->description, 'amount' => $transaction->amount, @@ -446,9 +449,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, diff --git a/app/Jobs/MailError.php b/app/Jobs/MailError.php index e5657705fd..2f8b56ddba 100644 --- a/app/Jobs/MailError.php +++ b/app/Jobs/MailError.php @@ -60,7 +60,8 @@ class MailError extends Job implements ShouldQueue $this->exception = $exceptionData; $debug = $exceptionData; unset($debug['stackTrace']); - Log::error('Exception is: ' . json_encode($debug)); + unset($debug['headers']); + Log::error(sprintf('Exception is: %s', json_encode($debug))); } /** @@ -81,7 +82,7 @@ class MailError extends Job implements ShouldQueue $args, function (Message $message) use ($email) { if ('mail@example.com' !== $email) { - $message->to($email, $email)->subject((string)trans('email.error_subject')); + $message->to($email, $email)->subject((string) trans('email.error_subject')); } } ); diff --git a/app/Jobs/SendWebhookMessage.php b/app/Jobs/SendWebhookMessage.php index bcc9808f3f..26923829da 100644 --- a/app/Jobs/SendWebhookMessage.php +++ b/app/Jobs/SendWebhookMessage.php @@ -24,7 +24,6 @@ declare(strict_types=1); namespace FireflyIII\Jobs; -use Log; use FireflyIII\Models\WebhookMessage; use FireflyIII\Services\Webhook\WebhookSenderInterface; use Illuminate\Bus\Queueable; @@ -32,6 +31,7 @@ use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; +use Log; /** * Class SendWebhookMessage diff --git a/app/Jobs/WarnAboutBills.php b/app/Jobs/WarnAboutBills.php new file mode 100644 index 0000000000..36ce43ab3b --- /dev/null +++ b/app/Jobs/WarnAboutBills.php @@ -0,0 +1,174 @@ +. + */ + +declare(strict_types=1); + +namespace FireflyIII\Jobs; + +use Carbon\Carbon; +use FireflyIII\Events\WarnUserAboutBill; +use FireflyIII\Models\Bill; +use Illuminate\Bus\Queueable; +use Illuminate\Contracts\Queue\ShouldQueue; +use Illuminate\Foundation\Bus\Dispatchable; +use Illuminate\Queue\InteractsWithQueue; +use Illuminate\Queue\SerializesModels; +use Log; + +/** + * Class WarnAboutBills + */ +class WarnAboutBills implements ShouldQueue +{ + use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; + + private Carbon $date; + private bool $force; + + + /** + * Create a new job instance. + * + * @codeCoverageIgnore + * + * @param Carbon|null $date + */ + public function __construct(?Carbon $date) + { + if (null !== $date) { + $newDate = clone $date; + $newDate->startOfDay(); + $this->date = $newDate; + } + if (null === $date) { + $newDate = new Carbon; + $newDate->startOfDay(); + $this->date = $newDate; + } + $this->force = false; + + Log::debug(sprintf('Created new WarnAboutBills("%s")', $this->date->format('Y-m-d'))); + } + + /** + * Execute the job. + */ + public function handle(): void + { + Log::debug(sprintf('Now at start of WarnAboutBills() job for %s.', $this->date->format('D d M Y'))); + $bills = Bill::all(); + /** @var Bill $bill */ + foreach ($bills as $bill) { + Log::debug(sprintf('Now checking bill #%d ("%s")', $bill->id, $bill->name)); + if ($this->hasDateFields($bill)) { + if ($this->needsWarning($bill, 'end_date')) { + $this->sendWarning($bill, 'end_date'); + } + if ($this->needsWarning($bill, 'extension_date')) { + $this->sendWarning($bill, 'extension_date'); + } + } + } + Log::debug('Done with handle()'); + + // clear cache: + app('preferences')->mark(); + } + + /** + * @param Bill $bill + * @return bool + */ + private function hasDateFields(Bill $bill): bool + { + if (false === $bill->active) { + Log::debug('Bill is not active.'); + return false; + } + if (null === $bill->end_date && null === $bill->extension_date) { + Log::debug('Bill has no date fields.'); + return false; + } + return true; + } + + /** + * @param Bill $bill + * @param string $field + * @return bool + */ + private function needsWarning(Bill $bill, string $field): bool + { + if (null === $bill->$field) { + return false; + } + $diff = $this->getDiff($bill, $field); + $list = config('firefly.bill_reminder_periods'); + Log::debug(sprintf('Difference in days for field "%s" ("%s") is %d day(s)', $field, $bill->$field->format('Y-m-d'), $diff)); + if (in_array($diff, $list, true)) { + return true; + } + return false; + } + + /** + * @param Bill $bill + * @param string $field + * @return int + */ + private function getDiff(Bill $bill, string $field): int + { + $today = clone $this->date; + $carbon = clone $bill->$field; + return $today->diffInDays($carbon, false); + } + + /** + * @param Bill $bill + * @param string $field + * @return void + */ + private function sendWarning(Bill $bill, string $field): void + { + $diff = $this->getDiff($bill, $field); + Log::debug('Will now send warning!'); + event(new WarnUserAboutBill($bill, $field, $diff)); + } + + /** + * @param Carbon $date + */ + public function setDate(Carbon $date): void + { + $newDate = clone $date; + $newDate->startOfDay(); + $this->date = $newDate; + } + + /** + * @param bool $force + */ + public function setForce(bool $force): void + { + $this->force = $force; + } +} diff --git a/app/Ldap/Rules/UserDefinedRule.php b/app/Ldap/Rules/UserDefinedRule.php deleted file mode 100644 index 1ccbbd8f75..0000000000 --- a/app/Ldap/Rules/UserDefinedRule.php +++ /dev/null @@ -1,88 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Ldap\Rules; - -use LdapRecord\Laravel\Auth\Rule; -use LdapRecord\Models\Attributes\DistinguishedName; -use LdapRecord\Query\ObjectNotFoundException; -use Log; - -/** - * Class UserDefinedRule - */ -class UserDefinedRule extends Rule -{ - /** - * Check if the rule passes validation. - * - * @return bool - * @throws ObjectNotFoundException - */ - public function isValid() - { - $extraFilter = config('ldap.extra_filter'); - Log::debug(sprintf('UserDefinedRule with extra filter "%s"', $extraFilter)); - - if (empty($extraFilter)) { - Log::debug('Extra filter is empty, return true.'); - - return true; - } - Log::debug('Extra filter is not empty, continue.'); - - // group class: - // use ; - $openLDAP = class_exists(\LdapRecord\Models\OpenLDAP\Group::class) ? \LdapRecord\Models\OpenLDAP\Group::class : ''; - $activeDirectory = class_exists(\LdapRecord\Models\ActiveDirectory\Group::class) ? \LdapRecord\Models\ActiveDirectory\Group::class : ''; - $groupClass = config('ldap.dialect') === 'OpenLDAP' ? $openLDAP : $activeDirectory; - - Log::debug(sprintf('Will use dialect group class "%s"', $groupClass)); - - - // We've been given an invalid group filter. We will assume the - // developer is using some group ANR attribute, and attempt - // to check the user's membership with the resulting group. - if (!DistinguishedName::isValid($extraFilter)) { - Log::debug('UserDefinedRule: Is not valid DN'); - - return $this->user->groups()->recursive()->exists($groupClass::findByAnrOrFail($extraFilter)); - } - - $head = strtolower(DistinguishedName::make($extraFilter)->head()); - Log::debug(sprintf('UserDefinedRule: Head is "%s"', $head)); - // If the head of the DN we've been given is an OU, we will assume - // the developer is looking to filter users based on hierarchy. - // Otherwise, we'll attempt locating a group by the given - // group filter and checking the users group membership. - if ('ou' === $head) { - Log::debug('UserDefinedRule: Will return if user is a descendant of.'); - - return $this->user->isDescendantOf($extraFilter); - } - Log::debug('UserDefinedRule: Will return if user exists in group.'); - - return $this->user->groups()->recursive()->exists($groupClass::findOrFail($extraFilter)); - } -} diff --git a/app/Ldap/Scopes/UserDefinedScope.php b/app/Ldap/Scopes/UserDefinedScope.php deleted file mode 100644 index cccaa71ae1..0000000000 --- a/app/Ldap/Scopes/UserDefinedScope.php +++ /dev/null @@ -1,49 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Ldap\Scopes; - -use LdapRecord\Models\Model; -use LdapRecord\Models\Scope; -use LdapRecord\Query\Model\Builder; -use Log; - - -/** - * Class UserDefinedScope - */ -class UserDefinedScope implements Scope -{ - /** - * Apply the scope to the given query. - * - * @param Builder $query - * @param Model $model - * - * @return void - */ - public function apply(Builder $query, Model $model) - { - } -} diff --git a/app/Mail/AccessTokenCreatedMail.php b/app/Mail/AccessTokenCreatedMail.php index 88fccc3b4b..8450f76298 100644 --- a/app/Mail/AccessTokenCreatedMail.php +++ b/app/Mail/AccessTokenCreatedMail.php @@ -37,21 +37,11 @@ class AccessTokenCreatedMail extends Mailable use Queueable, SerializesModels; - /** @var string Email address of admin */ - public $email; - /** @var string IP address of admin */ - public $ipAddress; - /** * AccessTokenCreatedMail constructor. - * - * @param string $email - * @param string $ipAddress */ - public function __construct(string $email, string $ipAddress) + public function __construct() { - $this->email = $email; - $this->ipAddress = $ipAddress; } /** @@ -61,7 +51,8 @@ class AccessTokenCreatedMail extends Mailable */ public function build(): self { - return $this->view('emails.access-token-created-html')->text('emails.access-token-created-text') - ->subject((string)trans('email.access_token_created_subject')); + return $this + ->markdown('emails.token-created') + ->subject((string) trans('email.access_token_created_subject')); } } diff --git a/app/Mail/AdminTestMail.php b/app/Mail/AdminTestMail.php index b9fe1bc168..023a57adc2 100644 --- a/app/Mail/AdminTestMail.php +++ b/app/Mail/AdminTestMail.php @@ -37,21 +37,16 @@ class AdminTestMail extends Mailable { use Queueable, SerializesModels; - /** @var string Email address of admin */ - public $email; - /** @var string IP address of admin */ - public $ipAddress; + public string $email; /** * ConfirmEmailChangeMail constructor. * * @param string $email - * @param string $ipAddress */ - public function __construct(string $email, string $ipAddress) + public function __construct(string $email) { - $this->email = $email; - $this->ipAddress = $ipAddress; + $this->email = $email; } /** @@ -61,7 +56,8 @@ class AdminTestMail extends Mailable */ public function build(): self { - return $this->view('emails.admin-test-html')->text('emails.admin-test-text') - ->subject((string)trans('email.admin_test_subject')); + return $this + ->markdown('emails.admin-test') + ->subject((string) trans('email.admin_test_subject')); } } diff --git a/app/Mail/BillWarningMail.php b/app/Mail/BillWarningMail.php new file mode 100644 index 0000000000..de7e413066 --- /dev/null +++ b/app/Mail/BillWarningMail.php @@ -0,0 +1,70 @@ +. + */ + +declare(strict_types=1); + +namespace FireflyIII\Mail; + +use FireflyIII\Models\Bill; +use Illuminate\Bus\Queueable; +use Illuminate\Mail\Mailable; +use Illuminate\Queue\SerializesModels; + +class BillWarningMail extends Mailable +{ + use Queueable, SerializesModels; + + public Bill $bill; + public int $diff; + public string $field; + + /** + * ConfirmEmailChangeMail constructor. + * + * @param Bill $bill + * @param string $field + * @param int $diff + */ + public function __construct(Bill $bill, string $field, int $diff) + { + $this->bill = $bill; + $this->field = $field; + $this->diff = $diff; + } + + /** + * Build the message. + * + * @return $this + */ + public function build(): self + { + $subject = (string) trans(sprintf('email.bill_warning_subject_%s', $this->field), ['diff' => $this->diff, 'name' => $this->bill->name]); + if (0 === $this->diff) { + $subject = (string) trans(sprintf('email.bill_warning_subject_now_%s', $this->field), ['diff' => $this->diff, 'name' => $this->bill->name]); + } + + return $this + ->markdown('emails.bill-warning') + ->subject($subject); + } +} diff --git a/app/Mail/ConfirmEmailChangeMail.php b/app/Mail/ConfirmEmailChangeMail.php index d557fbe989..bdd6110ff7 100644 --- a/app/Mail/ConfirmEmailChangeMail.php +++ b/app/Mail/ConfirmEmailChangeMail.php @@ -37,29 +37,22 @@ class ConfirmEmailChangeMail extends Mailable { use Queueable, SerializesModels; - /** @var string IP address of user */ - public $ipAddress; - /** @var string New email address */ - public $newEmail; - /** @var string Old email address */ - public $oldEmail; - /** @var string Confirmation link */ - public $uri; + public string $newEmail; + public string $oldEmail; + public string $url; /** * ConfirmEmailChangeMail constructor. * * @param string $newEmail * @param string $oldEmail - * @param string $uri - * @param string $ipAddress + * @param string $url */ - public function __construct(string $newEmail, string $oldEmail, string $uri, string $ipAddress) + public function __construct(string $newEmail, string $oldEmail, string $url) { - $this->newEmail = $newEmail; - $this->oldEmail = $oldEmail; - $this->uri = $uri; - $this->ipAddress = $ipAddress; + $this->newEmail = $newEmail; + $this->oldEmail = $oldEmail; + $this->url = $url; } /** @@ -69,7 +62,10 @@ class ConfirmEmailChangeMail extends Mailable */ public function build(): self { - return $this->view('emails.confirm-email-change-html')->text('emails.confirm-email-change-text') - ->subject((string)trans('email.email_change_subject')); + return $this + //->view('emails.confirm-email-change-html') + //->text('emails.confirm-email-change-text') + ->markdown('emails.confirm-email-change') + ->subject((string) trans('email.email_change_subject')); } } diff --git a/app/Mail/NewIPAddressWarningMail.php b/app/Mail/NewIPAddressWarningMail.php index bf27fd2a29..f387f1c84d 100644 --- a/app/Mail/NewIPAddressWarningMail.php +++ b/app/Mail/NewIPAddressWarningMail.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Mail; +use Exception; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; @@ -56,15 +57,19 @@ class NewIPAddressWarningMail extends Mailable */ public function build(): self { - // time - $this->time = now()->formatLocalized((string)trans('config.date_time')); + $this->time = now(config('app.timezone'))->isoFormat((string) trans('config.date_time_js')); $this->host = ''; - $hostName = gethostbyaddr($this->ipAddress); + try { + $hostName = gethostbyaddr($this->ipAddress); + } catch (Exception $e) { + $hostName = $this->ipAddress; + } if ($hostName !== $this->ipAddress) { $this->host = $hostName; } - return $this->view('emails.new-ip-html')->text('emails.new-ip-text') - ->subject((string)trans('email.login_from_new_ip')); + return $this + ->markdown('emails.new-ip') + ->subject((string) trans('email.login_from_new_ip')); } } diff --git a/app/Mail/OAuthTokenCreatedMail.php b/app/Mail/OAuthTokenCreatedMail.php index 495b3b2163..796f980fc4 100644 --- a/app/Mail/OAuthTokenCreatedMail.php +++ b/app/Mail/OAuthTokenCreatedMail.php @@ -37,25 +37,16 @@ class OAuthTokenCreatedMail extends Mailable { use Queueable, SerializesModels; - /** @var Client The client */ - public $client; - /** @var string Email address of admin */ - public $email; - /** @var string IP address of admin */ - public $ipAddress; + public Client $client; /** * OAuthTokenCreatedMail constructor. * - * @param string $email - * @param string $ipAddress * @param Client $client */ - public function __construct(string $email, string $ipAddress, Client $client) + public function __construct(Client $client) { - $this->email = $email; - $this->ipAddress = $ipAddress; - $this->client = $client; + $this->client = $client; } /** @@ -65,7 +56,8 @@ class OAuthTokenCreatedMail extends Mailable */ public function build(): self { - return $this->view('emails.oauth-client-created-html')->text('emails.oauth-client-created-text') - ->subject((string)trans('email.oauth_created_subject')); + return $this + ->markdown('emails.oauth-client-created') + ->subject((string) trans('email.oauth_created_subject')); } } diff --git a/app/Mail/RegisteredUser.php b/app/Mail/RegisteredUser.php index 6bb66a6ece..1ab61c951f 100644 --- a/app/Mail/RegisteredUser.php +++ b/app/Mail/RegisteredUser.php @@ -38,21 +38,16 @@ class RegisteredUser extends Mailable { use Queueable, SerializesModels; - /** @var string Email address of user */ - public $address; - /** @var string IP address of user */ - public $ipAddress; + public string $address; /** * Create a new message instance. * * @param string $address - * @param string $ipAddress */ - public function __construct(string $address, string $ipAddress) + public function __construct(string $address) { - $this->address = $address; - $this->ipAddress = $ipAddress; + $this->address = $address; } /** @@ -62,6 +57,8 @@ class RegisteredUser extends Mailable */ public function build(): self { - return $this->view('emails.registered-html')->text('emails.registered-text')->subject((string)trans('email.registered_subject')); + return $this + ->markdown('emails.registered') + ->subject((string) trans('email.registered_subject')); } } diff --git a/app/Mail/ReportNewJournalsMail.php b/app/Mail/ReportNewJournalsMail.php index dd19c46d2b..feff32bdea 100644 --- a/app/Mail/ReportNewJournalsMail.php +++ b/app/Mail/ReportNewJournalsMail.php @@ -40,23 +40,17 @@ class ReportNewJournalsMail extends Mailable { use Queueable, SerializesModels; - public string $email; public Collection $groups; - public string $ipAddress; public array $transformed; /** * ConfirmEmailChangeMail constructor. * - * @param string $email - * @param string $ipAddress * @param Collection $groups */ - public function __construct(string $email, string $ipAddress, Collection $groups) + public function __construct(Collection $groups) { - $this->email = $email; - $this->ipAddress = $ipAddress; - $this->groups = $groups; + $this->groups = $groups; } /** @@ -68,8 +62,9 @@ class ReportNewJournalsMail extends Mailable { $this->transform(); - return $this->view('emails.report-new-journals-html')->text('emails.report-new-journals-text') - ->subject((string)trans_choice('email.new_journals_subject', $this->groups->count())); + return $this + ->markdown('emails.report-new-journals') + ->subject((string) trans_choice('email.new_journals_subject', $this->groups->count())); } private function transform(): void diff --git a/app/Mail/RequestedNewPassword.php b/app/Mail/RequestedNewPassword.php index b02d4ebe69..2aedd0aa4a 100644 --- a/app/Mail/RequestedNewPassword.php +++ b/app/Mail/RequestedNewPassword.php @@ -37,21 +37,16 @@ class RequestedNewPassword extends Mailable { use Queueable, SerializesModels; - /** @var string IP address of user */ - public $ipAddress; - /** @var string URI of password change link */ - public $url; + public string $url; /** * RequestedNewPassword constructor. * * @param string $url - * @param string $ipAddress */ - public function __construct(string $url, string $ipAddress) + public function __construct(string $url) { - $this->url = $url; - $this->ipAddress = $ipAddress; + $this->url = $url; } /** @@ -61,6 +56,8 @@ class RequestedNewPassword extends Mailable */ public function build(): self { - return $this->view('emails.password-html')->text('emails.password-text')->subject((string)trans('email.reset_pw_subject')); + return $this + ->markdown('emails.password') + ->subject((string) trans('email.reset_pw_subject')); } } diff --git a/app/Mail/UndoEmailChangeMail.php b/app/Mail/UndoEmailChangeMail.php index 647917b1c2..c4247fd8af 100644 --- a/app/Mail/UndoEmailChangeMail.php +++ b/app/Mail/UndoEmailChangeMail.php @@ -35,29 +35,22 @@ class UndoEmailChangeMail extends Mailable { use Queueable, SerializesModels; - /** @var string IP address of user */ - public $ipAddress; - /** @var string New email address */ - public $newEmail; - /** @var string Old email address */ - public $oldEmail; - /** @var string URI to undo */ - public $uri; + public string $newEmail; + public string $oldEmail; + public string $url; /** * UndoEmailChangeMail constructor. * * @param string $newEmail * @param string $oldEmail - * @param string $uri - * @param string $ipAddress + * @param string $url */ - public function __construct(string $newEmail, string $oldEmail, string $uri, string $ipAddress) + public function __construct(string $newEmail, string $oldEmail, string $url) { - $this->newEmail = $newEmail; - $this->oldEmail = $oldEmail; - $this->uri = $uri; - $this->ipAddress = $ipAddress; + $this->newEmail = $newEmail; + $this->oldEmail = $oldEmail; + $this->url = $url; } /** @@ -67,7 +60,8 @@ class UndoEmailChangeMail extends Mailable */ public function build(): self { - return $this->view('emails.undo-email-change-html')->text('emails.undo-email-change-text') - ->subject((string)trans('email.email_change_subject')); + return $this + ->markdown('emails.undo-email-change') + ->subject((string) trans('email.email_change_subject')); } } diff --git a/app/Models/Account.php b/app/Models/Account.php index 938f6a3d57..652ef27de7 100644 --- a/app/Models/Account.php +++ b/app/Models/Account.php @@ -138,7 +138,7 @@ class Account extends Model 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 */ @@ -266,7 +266,7 @@ class Account extends Model */ public function setVirtualBalanceAttribute($value): void { - $value = (string)$value; + $value = (string) $value; if ('' === $value) { $value = null; } diff --git a/app/Models/AccountType.php b/app/Models/AccountType.php index c2c90132d7..859ff0b710 100644 --- a/app/Models/AccountType.php +++ b/app/Models/AccountType.php @@ -49,34 +49,34 @@ use Illuminate\Support\Carbon; */ class AccountType extends Model { - /** @var string */ - public const DEFAULT = 'Default account'; - /** @var string */ - public const CASH = 'Cash account'; /** @var string */ public const ASSET = 'Asset account'; /** @var string */ - public const EXPENSE = 'Expense account'; - /** @var string */ - public const REVENUE = 'Revenue account'; - /** @var string */ - public const INITIAL_BALANCE = 'Initial balance account'; - /** @var string */ public const BENEFICIARY = 'Beneficiary account'; /** @var string */ - public const IMPORT = 'Import account'; - /** @var string */ - public const RECONCILIATION = 'Reconciliation account'; - /** @var string */ - public const LOAN = 'Loan'; - /** @var string */ - public const DEBT = 'Debt'; - /** @var string */ - public const MORTGAGE = 'Mortgage'; + public const CASH = 'Cash account'; /** @var string */ public const CREDITCARD = 'Credit card'; /** @var string */ + public const DEBT = 'Debt'; + /** @var string */ + public const DEFAULT = 'Default account'; + /** @var string */ + public const EXPENSE = 'Expense account'; + /** @var string */ + public const IMPORT = 'Import account'; + /** @var string */ + public const INITIAL_BALANCE = 'Initial balance account'; + /** @var string */ public const LIABILITY_CREDIT = 'Liability credit account'; + /** @var string */ + public const LOAN = 'Loan'; + /** @var string */ + public const MORTGAGE = 'Mortgage'; + /** @var string */ + public const RECONCILIATION = 'Reconciliation account'; + /** @var string */ + public const REVENUE = 'Revenue account'; /** * The attributes that should be casted to native types. * diff --git a/app/Models/Attachment.php b/app/Models/Attachment.php index 686ae491ce..0aeb20f065 100644 --- a/app/Models/Attachment.php +++ b/app/Models/Attachment.php @@ -111,7 +111,7 @@ class Attachment extends Model 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 */ @@ -143,7 +143,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/AvailableBudget.php b/app/Models/AvailableBudget.php index c2d514457c..8685e4ceb7 100644 --- a/app/Models/AvailableBudget.php +++ b/app/Models/AvailableBudget.php @@ -96,7 +96,7 @@ class AvailableBudget extends Model 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 d0af591be6..ecd0cc1d7b 100644 --- a/app/Models/Bill.php +++ b/app/Models/Bill.php @@ -139,7 +139,7 @@ class Bill extends Model 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 */ @@ -184,7 +184,7 @@ class Bill extends Model */ public function setAmountMaxAttribute($value): void { - $this->attributes['amount_max'] = (string)$value; + $this->attributes['amount_max'] = (string) $value; } /** @@ -194,7 +194,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 590695cc76..96a7dce142 100644 --- a/app/Models/Budget.php +++ b/app/Models/Budget.php @@ -38,26 +38,26 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; /** * FireflyIII\Models\Budget * - * @property int $id - * @property Carbon|null $created_at - * @property Carbon|null $updated_at - * @property Carbon|null $deleted_at - * @property int $user_id - * @property string $name - * @property bool $active - * @property bool $encrypted - * @property int $order - * @property-read Collection|Attachment[] $attachments - * @property-read int|null $attachments_count - * @property-read Collection|AutoBudget[] $autoBudgets - * @property-read int|null $auto_budgets_count - * @property-read Collection|BudgetLimit[] $budgetlimits - * @property-read int|null $budgetlimits_count - * @property-read Collection|TransactionJournal[] $transactionJournals - * @property-read int|null $transaction_journals_count - * @property-read Collection|Transaction[] $transactions - * @property-read int|null $transactions_count - * @property-read 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 $name + * @property bool $active + * @property bool $encrypted + * @property int $order + * @property-read Collection|Attachment[] $attachments + * @property-read int|null $attachments_count + * @property-read Collection|AutoBudget[] $autoBudgets + * @property-read int|null $auto_budgets_count + * @property-read Collection|BudgetLimit[] $budgetlimits + * @property-read int|null $budgetlimits_count + * @property-read Collection|TransactionJournal[] $transactionJournals + * @property-read int|null $transaction_journals_count + * @property-read Collection|Transaction[] $transactions + * @property-read int|null $transactions_count + * @property-read User $user * @method static \Illuminate\Database\Eloquent\Builder|Budget newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|Budget newQuery() * @method static Builder|Budget onlyTrashed() @@ -74,9 +74,11 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; * @method static Builder|Budget withTrashed() * @method static Builder|Budget withoutTrashed() * @mixin Eloquent - * @property string $email - * @property int|null $user_group_id + * @property string $email + * @property int|null $user_group_id * @method static \Illuminate\Database\Eloquent\Builder|Budget whereUserGroupId($value) + * @property-read Collection|Note[] $notes + * @property-read int|null $notes_count */ class Budget extends Model { @@ -111,7 +113,7 @@ class Budget extends Model 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 */ @@ -150,6 +152,15 @@ class Budget extends Model return $this->hasMany(BudgetLimit::class); } + /** + * @codeCoverageIgnore + * Get all of the notes. + */ + public function notes(): MorphMany + { + return $this->morphMany(Note::class, 'noteable'); + } + /** * @codeCoverageIgnore * @return BelongsToMany diff --git a/app/Models/BudgetLimit.php b/app/Models/BudgetLimit.php index 77bb3eee4c..2c398d4223 100644 --- a/app/Models/BudgetLimit.php +++ b/app/Models/BudgetLimit.php @@ -90,7 +90,7 @@ class BudgetLimit extends Model 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 f7620877a9..369ded30b0 100644 --- a/app/Models/Category.php +++ b/app/Models/Category.php @@ -104,7 +104,7 @@ class Category extends Model 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/LinkType.php b/app/Models/LinkType.php index cf6abf70a9..8f1d0f1ce7 100644 --- a/app/Models/LinkType.php +++ b/app/Models/LinkType.php @@ -93,7 +93,7 @@ class LinkType extends Model 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/ObjectGroup.php b/app/Models/ObjectGroup.php index 4578efc14e..b641c1bd16 100644 --- a/app/Models/ObjectGroup.php +++ b/app/Models/ObjectGroup.php @@ -90,7 +90,7 @@ class ObjectGroup extends Model public static function routeBinder(string $value): ObjectGroup { if (auth()->check()) { - $objectGroupId = (int)$value; + $objectGroupId = (int) $value; /** @var ObjectGroup $objectGroup */ $objectGroup = self::where('object_groups.id', $objectGroupId) ->where('object_groups.user_id', auth()->user()->id)->first(); diff --git a/app/Models/PiggyBank.php b/app/Models/PiggyBank.php index 2288ae7ef6..3526816a63 100644 --- a/app/Models/PiggyBank.php +++ b/app/Models/PiggyBank.php @@ -115,7 +115,7 @@ class PiggyBank extends Model 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.*']); @@ -186,6 +186,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 f3b71fe2af..0429630ee8 100644 --- a/app/Models/PiggyBankEvent.php +++ b/app/Models/PiggyBankEvent.php @@ -86,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 839c15cf99..de87bac9c1 100644 --- a/app/Models/PiggyBankRepetition.php +++ b/app/Models/PiggyBankRepetition.php @@ -31,14 +31,14 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo; /** * FireflyIII\Models\PiggyBankRepetition * - * @property int $id + * @property int $id * @property \Illuminate\Support\Carbon|null $created_at * @property \Illuminate\Support\Carbon|null $updated_at - * @property int $piggy_bank_id + * @property int $piggy_bank_id * @property \Illuminate\Support\Carbon|null $startdate * @property \Illuminate\Support\Carbon|null $targetdate - * @property string $currentamount - * @property-read PiggyBank $piggyBank + * @property string $currentamount + * @property-read PiggyBank $piggyBank * @method static EloquentBuilder|PiggyBankRepetition newModelQuery() * @method static EloquentBuilder|PiggyBankRepetition newQuery() * @method static EloquentBuilder|PiggyBankRepetition onDates(Carbon $start, Carbon $target) @@ -124,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/Recurrence.php b/app/Models/Recurrence.php index f96ff20744..6a723f3b78 100644 --- a/app/Models/Recurrence.php +++ b/app/Models/Recurrence.php @@ -130,7 +130,7 @@ class Recurrence extends Model 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/Rule.php b/app/Models/Rule.php index 732b3d6cd2..55bd858171 100644 --- a/app/Models/Rule.php +++ b/app/Models/Rule.php @@ -111,7 +111,7 @@ class Rule extends Model 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 */ diff --git a/app/Models/RuleGroup.php b/app/Models/RuleGroup.php index b88d5f7bcf..aa2a370b71 100644 --- a/app/Models/RuleGroup.php +++ b/app/Models/RuleGroup.php @@ -102,7 +102,7 @@ class RuleGroup extends Model 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/Tag.php b/app/Models/Tag.php index 8aa8b656b7..3168dd3634 100644 --- a/app/Models/Tag.php +++ b/app/Models/Tag.php @@ -113,7 +113,7 @@ class Tag extends Model 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 */ diff --git a/app/Models/Transaction.php b/app/Models/Transaction.php index 5f2d3019e7..58d4d9a6cf 100644 --- a/app/Models/Transaction.php +++ b/app/Models/Transaction.php @@ -236,7 +236,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 4b2c12bb04..3af5058281 100644 --- a/app/Models/TransactionCurrency.php +++ b/app/Models/TransactionCurrency.php @@ -97,7 +97,7 @@ class TransactionCurrency extends Model 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 10a356b41d..aac8eac199 100644 --- a/app/Models/TransactionGroup.php +++ b/app/Models/TransactionGroup.php @@ -94,7 +94,7 @@ class TransactionGroup extends Model 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 */ diff --git a/app/Models/TransactionJournal.php b/app/Models/TransactionJournal.php index af8e072e96..b39283b1af 100644 --- a/app/Models/TransactionJournal.php +++ b/app/Models/TransactionJournal.php @@ -160,7 +160,7 @@ class TransactionJournal extends Model 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 */ diff --git a/app/Models/TransactionJournalLink.php b/app/Models/TransactionJournalLink.php index f7ecd1b5d2..c37dbcdb4b 100644 --- a/app/Models/TransactionJournalLink.php +++ b/app/Models/TransactionJournalLink.php @@ -87,7 +87,7 @@ class TransactionJournalLink extends Model 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/TransactionType.php b/app/Models/TransactionType.php index 6d37d908be..6a6a68b759 100644 --- a/app/Models/TransactionType.php +++ b/app/Models/TransactionType.php @@ -58,20 +58,20 @@ class TransactionType extends Model { use SoftDeletes; - /** @var string */ - public const WITHDRAWAL = 'Withdrawal'; /** @var string */ public const DEPOSIT = 'Deposit'; /** @var string */ - public const TRANSFER = 'Transfer'; + public const INVALID = 'Invalid'; + /** @var string */ + public const LIABILITY_CREDIT = 'Liability credit'; /** @var string */ public const OPENING_BALANCE = 'Opening balance'; /** @var string */ public const RECONCILIATION = 'Reconciliation'; /** @var string */ - public const INVALID = 'Invalid'; + public const TRANSFER = 'Transfer'; /** @var string */ - public const LIABILITY_CREDIT = 'Liability credit'; + public const WITHDRAWAL = 'Withdrawal'; /** @var string[] */ protected $casts = [ diff --git a/app/Models/UserRole.php b/app/Models/UserRole.php index ca51556d1c..ce16b69013 100644 --- a/app/Models/UserRole.php +++ b/app/Models/UserRole.php @@ -53,14 +53,14 @@ use Illuminate\Support\Carbon; */ class UserRole extends Model { - public const READ_ONLY = 'ro'; - public const CHANGE_TRANSACTIONS = 'change_tx'; - public const CHANGE_RULES = 'change_rules'; public const CHANGE_PIGGY_BANKS = 'change_piggies'; public const CHANGE_REPETITIONS = 'change_reps'; - public const VIEW_REPORTS = 'view_reports'; + public const CHANGE_RULES = 'change_rules'; + public const CHANGE_TRANSACTIONS = 'change_tx'; public const FULL = 'full'; public const OWNER = 'owner'; + public const READ_ONLY = 'ro'; + public const VIEW_REPORTS = 'view_reports'; protected $fillable = ['title']; /** diff --git a/app/Models/Webhook.php b/app/Models/Webhook.php index 1eb3fcb069..f036fb3abe 100644 --- a/app/Models/Webhook.php +++ b/app/Models/Webhook.php @@ -80,17 +80,17 @@ class Webhook extends Model // dont forget to update the config in firefly.php // triggers - public const TRIGGER_STORE_TRANSACTION = 100; - public const TRIGGER_UPDATE_TRANSACTION = 110; - public const TRIGGER_DESTROY_TRANSACTION = 120; - - // actions - public const RESPONSE_TRANSACTIONS = 200; + public const DELIVERY_JSON = 300; public const RESPONSE_ACCOUNTS = 210; public const RESPONSE_NONE = 220; + // actions + public const RESPONSE_TRANSACTIONS = 200; + public const TRIGGER_DESTROY_TRANSACTION = 120; + public const TRIGGER_STORE_TRANSACTION = 100; + // delivery - public const DELIVERY_JSON = 300; + public const TRIGGER_UPDATE_TRANSACTION = 110; protected $casts = [ 'active' => 'boolean', @@ -111,7 +111,7 @@ class Webhook extends Model public static function routeBinder(string $value): Webhook { if (auth()->check()) { - $webhookId = (int)$value; + $webhookId = (int) $value; /** @var User $user */ $user = auth()->user(); /** @var Webhook $webhook */ diff --git a/app/Models/WebhookAttempt.php b/app/Models/WebhookAttempt.php index 5397402480..112c5bb468 100644 --- a/app/Models/WebhookAttempt.php +++ b/app/Models/WebhookAttempt.php @@ -75,7 +75,7 @@ class WebhookAttempt extends Model public static function routeBinder(string $value): WebhookAttempt { if (auth()->check()) { - $attemptId = (int)$value; + $attemptId = (int) $value; /** @var User $user */ $user = auth()->user(); /** @var WebhookAttempt $attempt */ diff --git a/app/Models/WebhookMessage.php b/app/Models/WebhookMessage.php index 23d5b5cb93..83e3e5da3f 100644 --- a/app/Models/WebhookMessage.php +++ b/app/Models/WebhookMessage.php @@ -89,7 +89,7 @@ class WebhookMessage extends Model public static function routeBinder(string $value): WebhookMessage { if (auth()->check()) { - $messageId = (int)$value; + $messageId = (int) $value; /** @var User $user */ $user = auth()->user(); /** @var WebhookMessage $message */ diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 8675bd9ec3..d496885df3 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -22,7 +22,6 @@ declare(strict_types=1); namespace FireflyIII\Providers; -use Adldap\Laravel\Middleware\WindowsAuthenticate; use Illuminate\Support\Facades\Schema; use Illuminate\Support\ServiceProvider; use Laravel\Passport\Passport; @@ -46,9 +45,6 @@ class AppServiceProvider extends ServiceProvider if ('heroku' === config('app.env')) { URL::forceScheme('https'); } - if (config('ldap_auth.identifiers.windows.enabled', false)) { - $this->app['router']->pushMiddlewareToGroup('web', WindowsAuthenticate::class); - } Sanctum::ignoreMigrations(); } diff --git a/app/Providers/BroadcastServiceProvider.php b/app/Providers/BroadcastServiceProvider.php index 86f8353db3..99b4a17e1f 100644 --- a/app/Providers/BroadcastServiceProvider.php +++ b/app/Providers/BroadcastServiceProvider.php @@ -38,7 +38,6 @@ class BroadcastServiceProvider extends ServiceProvider { Broadcast::routes(); - /** @noinspection PhpIncludeInspection */ require base_path('routes/channels.php'); } } diff --git a/app/Providers/EventServiceProvider.php b/app/Providers/EventServiceProvider.php index 84258e961c..0e867b4732 100644 --- a/app/Providers/EventServiceProvider.php +++ b/app/Providers/EventServiceProvider.php @@ -37,6 +37,7 @@ use FireflyIII\Events\StoredTransactionGroup; use FireflyIII\Events\UpdatedAccount; use FireflyIII\Events\UpdatedTransactionGroup; use FireflyIII\Events\UserChangedEmail; +use FireflyIII\Events\WarnUserAboutBill; use FireflyIII\Mail\OAuthTokenCreatedMail; use FireflyIII\Models\PiggyBank; use FireflyIII\Models\PiggyBankRepetition; @@ -45,10 +46,8 @@ use Illuminate\Auth\Events\Login; use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider; use Laravel\Passport\Client; use Laravel\Passport\Events\AccessTokenCreated; -use LdapRecord\Laravel\Events\Import\Imported; use Log; use Mail; -use Request; use Session; /** @@ -76,7 +75,7 @@ class EventServiceProvider extends ServiceProvider 'FireflyIII\Handlers\Events\UserEventHandler@checkSingleUserIsAdmin', 'FireflyIII\Handlers\Events\UserEventHandler@demoUserBackToEnglish', ], - ActuallyLoggedIn::class => [ + ActuallyLoggedIn::class => [ 'FireflyIII\Handlers\Events\UserEventHandler@storeUserIPAddress', ], DetectedNewIPAddress::class => [ @@ -136,9 +135,9 @@ class EventServiceProvider extends ServiceProvider 'FireflyIII\Handlers\Events\UpdatedAccountEventHandler@recalculateCredit', ], - // LDAP related events: - Imported::class => [ - 'FireflyIII\Handlers\Events\LDAPEventHandler@importedUser', + // bill related events: + WarnUserAboutBill::class => [ + 'FireflyIII\Handlers\Events\BillEventHandler@warnAboutBill', ], ]; @@ -171,15 +170,14 @@ class EventServiceProvider extends ServiceProvider static function (Client $oauthClient) { /** @var UserRepositoryInterface $repository */ $repository = app(UserRepositoryInterface::class); - $user = $repository->find((int)$oauthClient->user_id); + $user = $repository->find((int) $oauthClient->user_id); if (null === $user) { Log::info('OAuth client generated but no user associated.'); return; } - $email = $user->email; - $ipAddress = Request::ip(); + $email = $user->email; // see if user has alternative email address: $pref = app('preferences')->getForUser($user, 'remote_guard_alt_email'); @@ -187,10 +185,10 @@ class EventServiceProvider extends ServiceProvider $email = $pref->data; } - Log::debug(sprintf('Now in EventServiceProvider::registerCreateEvents. Email is %s, IP is %s', $email, $ipAddress)); + Log::debug(sprintf('Now in EventServiceProvider::registerCreateEvents. Email is %s', $email)); try { Log::debug('Trying to send message...'); - Mail::to($email)->send(new OAuthTokenCreatedMail($email, $ipAddress, $oauthClient)); + Mail::to($email)->send(new OAuthTokenCreatedMail($oauthClient)); } catch (Exception $e) { // @phpstan-ignore-line Log::debug('Send message failed! :('); Log::error($e->getMessage()); diff --git a/app/Repositories/Account/AccountRepository.php b/app/Repositories/Account/AccountRepository.php index 72a0701f5f..ad05157167 100644 --- a/app/Repositories/Account/AccountRepository.php +++ b/app/Repositories/Account/AccountRepository.php @@ -198,21 +198,6 @@ class AccountRepository implements AccountRepositoryInterface return $account; } - /** - * @param Account $account - * - * @return TransactionCurrency|null - */ - public function getAccountCurrency(Account $account): ?TransactionCurrency - { - $currencyId = (int)$this->getMetaValue($account, 'currency_id'); - if ($currencyId > 0) { - return TransactionCurrency::find($currencyId); - } - - return null; - } - /** * Return account type or null if not found. * @@ -244,38 +229,6 @@ class AccountRepository implements AccountRepositoryInterface return $query->get(['accounts.*']); } - /** - * @param array $types - * @param array|null $sort - * - * @return Collection - */ - public function getAccountsByType(array $types, ?array $sort = []): Collection - { - $res = array_intersect([AccountType::ASSET, AccountType::MORTGAGE, AccountType::LOAN, AccountType::DEBT], $types); - $query = $this->user->accounts(); - if (!empty($types)) { - $query->accountTypeIn($types); - } - - // add sort parameters. At this point they're filtered to allowed fields to sort by: - if (!empty($sort)) { - foreach ($sort as $param) { - $query->orderBy($param[0], $param[1]); - } - } - - if (empty($sort)) { - if (!empty($res)) { - $query->orderBy('accounts.order', 'ASC'); - } - $query->orderBy('accounts.active', 'DESC'); - $query->orderBy('accounts.name', 'ASC'); - } - - return $query->get(['accounts.*']); - } - /** * @param array $types * @@ -384,31 +337,6 @@ class AccountRepository implements AccountRepositoryInterface return $account->locations()->first(); } - /** - * Return meta value for account. Null if not found. - * - * @param Account $account - * @param string $field - * - * @return null|string - */ - public function getMetaValue(Account $account, string $field): ?string - { - $result = $account->accountMeta->filter( - function (AccountMeta $meta) use ($field) { - return strtolower($meta->name) === strtolower($field); - } - ); - if (0 === $result->count()) { - return null; - } - if (1 === $result->count()) { - return (string)$result->first()->data; - } - - return null; - } - /** * Get note text or null. * @@ -427,20 +355,6 @@ class AccountRepository implements AccountRepositoryInterface return $note->text; } - /** - * @param Account $account - * - * @return TransactionJournal|null - */ - public function getOpeningBalance(Account $account): ?TransactionJournal - { - return TransactionJournal - ::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') - ->where('transactions.account_id', $account->id) - ->transactionTypes([TransactionType::OPENING_BALANCE]) - ->first(['transaction_journals.*']); - } - /** * Returns the amount of the opening balance for this account. * @@ -463,7 +377,7 @@ class AccountRepository implements AccountRepositoryInterface return null; } - return (string)$transaction->amount; + return (string) $transaction->amount; } /** @@ -498,6 +412,20 @@ class AccountRepository implements AccountRepositoryInterface return $journal?->transactionGroup; } + /** + * @param Account $account + * + * @return TransactionJournal|null + */ + public function getOpeningBalance(Account $account): ?TransactionJournal + { + return TransactionJournal + ::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') + ->where('transactions.account_id', $account->id) + ->transactionTypes([TransactionType::OPENING_BALANCE]) + ->first(['transaction_journals.*']); + } + /** * @param Account $account * @@ -514,6 +442,7 @@ class AccountRepository implements AccountRepositoryInterface * @return Account|null * * @throws FireflyException + * @throws JsonException */ public function getReconciliation(Account $account): ?Account { @@ -550,6 +479,46 @@ class AccountRepository implements AccountRepositoryInterface return $factory->create($data); } + /** + * @param Account $account + * + * @return TransactionCurrency|null + */ + public function getAccountCurrency(Account $account): ?TransactionCurrency + { + $currencyId = (int) $this->getMetaValue($account, 'currency_id'); + if ($currencyId > 0) { + return TransactionCurrency::find($currencyId); + } + + return null; + } + + /** + * Return meta value for account. Null if not found. + * + * @param Account $account + * @param string $field + * + * @return null|string + */ + public function getMetaValue(Account $account, string $field): ?string + { + $result = $account->accountMeta->filter( + function (AccountMeta $meta) use ($field) { + return strtolower($meta->name) === strtolower($field); + } + ); + if (0 === $result->count()) { + return null; + } + if (1 === $result->count()) { + return (string) $result->first()->data; + } + + return null; + } + /** * @inheritDoc */ @@ -558,8 +527,8 @@ class AccountRepository implements AccountRepositoryInterface $info = $account->transactions()->get(['transaction_currency_id', 'foreign_currency_id'])->toArray(); $currencyIds = []; foreach ($info as $entry) { - $currencyIds[] = (int)$entry['transaction_currency_id']; - $currencyIds[] = (int)$entry['foreign_currency_id']; + $currencyIds[] = (int) $entry['transaction_currency_id']; + $currencyIds[] = (int) $entry['foreign_currency_id']; } $currencyIds = array_unique($currencyIds); @@ -590,19 +559,65 @@ class AccountRepository implements AccountRepositoryInterface AccountType::MORTGAGE => [AccountType::LOAN, AccountType::DEBT, AccountType::CREDITCARD, AccountType::MORTGAGE], ]; if (array_key_exists(ucfirst($type), $sets)) { - $order = (int)$this->getAccountsByType($sets[ucfirst($type)])->max('order'); + $order = (int) $this->getAccountsByType($sets[ucfirst($type)])->max('order'); Log::debug(sprintf('Return max order of "%s" set: %d', $type, $order)); return $order; } $specials = [AccountType::CASH, AccountType::INITIAL_BALANCE, AccountType::IMPORT, AccountType::RECONCILIATION]; - $order = (int)$this->getAccountsByType($specials)->max('order'); + $order = (int) $this->getAccountsByType($specials)->max('order'); Log::debug(sprintf('Return max order of "%s" set (specials!): %d', $type, $order)); return $order; } + /** + * @param array $types + * @param array|null $sort + * + * @return Collection + */ + public function getAccountsByType(array $types, ?array $sort = []): Collection + { + $res = array_intersect([AccountType::ASSET, AccountType::MORTGAGE, AccountType::LOAN, AccountType::DEBT], $types); + $query = $this->user->accounts(); + if (!empty($types)) { + $query->accountTypeIn($types); + } + + // add sort parameters. At this point they're filtered to allowed fields to sort by: + if (!empty($sort)) { + foreach ($sort as $param) { + $query->orderBy($param[0], $param[1]); + } + } + + if (empty($sort)) { + if (!empty($res)) { + $query->orderBy('accounts.order', 'ASC'); + } + $query->orderBy('accounts.active', 'DESC'); + $query->orderBy('accounts.name', 'ASC'); + } + + return $query->get(['accounts.*']); + } + + /** + * Returns the date of the very first transaction in this account. + * + * @param Account $account + * + * @return Carbon|null + */ + public function oldestJournalDate(Account $account): ?Carbon + { + $journal = $this->oldestJournal($account); + + return $journal?->date; + } + /** * Returns the date of the very first transaction in this account. * @@ -620,26 +635,12 @@ class AccountRepository implements AccountRepositoryInterface ->orderBy('transaction_journals.id', 'ASC') ->first(['transaction_journals.id']); if (null !== $first) { - return TransactionJournal::find((int)$first->id); + return TransactionJournal::find((int) $first->id); } return null; } - /** - * Returns the date of the very first transaction in this account. - * - * @param Account $account - * - * @return Carbon|null - */ - public function oldestJournalDate(Account $account): ?Carbon - { - $journal = $this->oldestJournal($account); - - return $journal?->date; - } - /** * @inheritDoc */ @@ -661,7 +662,7 @@ class AccountRepository implements AccountRepositoryInterface $account->order = 0; continue; } - if ($index !== (int)$account->order) { + if ($index !== (int) $account->order) { Log::debug(sprintf('Account #%d ("%s"): order should %d be but is %d.', $account->id, $account->name, $index, $account->order)); $account->order = $index; $account->save(); @@ -754,6 +755,7 @@ class AccountRepository implements AccountRepositoryInterface * * @return Account * @throws FireflyException + * @throws JsonException */ public function store(array $data): Account { @@ -770,7 +772,6 @@ class AccountRepository implements AccountRepositoryInterface * * @return Account * @throws FireflyException - * @throws JsonException */ public function update(Account $account, array $data): Account { diff --git a/app/Repositories/Account/AccountTasker.php b/app/Repositories/Account/AccountTasker.php index c0702b41f1..d57725ec61 100644 --- a/app/Repositories/Account/AccountTasker.php +++ b/app/Repositories/Account/AccountTasker.php @@ -45,6 +45,8 @@ class AccountTasker implements AccountTaskerInterface * @param Carbon $end * * @return array + * @throws \FireflyIII\Exceptions\FireflyException + * @throws \JsonException */ public function getAccountReport(Collection $accounts, Carbon $start, Carbon $end): array { @@ -138,7 +140,7 @@ class AccountTasker implements AccountTaskerInterface // Obtain a list of columns $sum = []; foreach ($report['accounts'] as $accountId => $row) { - $sum[$accountId] = (float)$row['sum']; + $sum[$accountId] = (float) $row['sum']; } array_multisort($sum, SORT_ASC, $report['accounts']); @@ -146,6 +148,69 @@ class AccountTasker implements AccountTaskerInterface return $report; } + /** + * @param array $array + * + * @return array + * @throws \FireflyIII\Exceptions\FireflyException + * @throws \JsonException + */ + private function groupExpenseByDestination(array $array): array + { + $defaultCurrency = app('amount')->getDefaultCurrencyByUser($this->user); + /** @var CurrencyRepositoryInterface $currencyRepos */ + $currencyRepos = app(CurrencyRepositoryInterface::class); + $currencies = [$defaultCurrency->id => $defaultCurrency,]; + $report = [ + 'accounts' => [], + 'sums' => [], + ]; + + /** @var array $journal */ + foreach ($array as $journal) { + $sourceId = (int) $journal['destination_account_id']; + $currencyId = (int) $journal['currency_id']; + $key = sprintf('%s-%s', $sourceId, $currencyId); + $currencies[$currencyId] = $currencies[$currencyId] ?? $currencyRepos->find($currencyId); + $report['accounts'][$key] = $report['accounts'][$key] ?? [ + 'id' => $sourceId, + 'name' => $journal['destination_account_name'], + 'sum' => '0', + 'average' => '0', + 'count' => 0, + 'currency_id' => $currencies[$currencyId]->id, + 'currency_name' => $currencies[$currencyId]->name, + 'currency_symbol' => $currencies[$currencyId]->symbol, + 'currency_code' => $currencies[$currencyId]->code, + 'currency_decimal_places' => $currencies[$currencyId]->decimal_places, + ]; + $report['accounts'][$key]['sum'] = bcadd($report['accounts'][$key]['sum'], $journal['amount']); + + Log::debug(sprintf('Sum for %s is now %s', $journal['destination_account_name'], $report['accounts'][$key]['sum'])); + + ++$report['accounts'][$key]['count']; + } + + // do averages and sums. + foreach (array_keys($report['accounts']) as $key) { + if ($report['accounts'][$key]['count'] > 1) { + $report['accounts'][$key]['average'] = bcdiv($report['accounts'][$key]['sum'], (string) $report['accounts'][$key]['count']); + } + $currencyId = $report['accounts'][$key]['currency_id']; + $report['sums'][$currencyId] = $report['sums'][$currencyId] ?? [ + 'sum' => '0', + 'currency_id' => $report['accounts'][$key]['currency_id'], + 'currency_name' => $report['accounts'][$key]['currency_name'], + 'currency_symbol' => $report['accounts'][$key]['currency_symbol'], + 'currency_code' => $report['accounts'][$key]['currency_code'], + 'currency_decimal_places' => $report['accounts'][$key]['currency_decimal_places'], + ]; + $report['sums'][$currencyId]['sum'] = bcadd($report['sums'][$currencyId]['sum'], $report['accounts'][$key]['sum']); + } + + return $report; + } + /** * @param Carbon $start * @param Carbon $end @@ -170,7 +235,7 @@ class AccountTasker implements AccountTaskerInterface // Obtain a list of columns $sum = []; foreach ($report['accounts'] as $accountId => $row) { - $sum[$accountId] = (float)$row['sum']; + $sum[$accountId] = (float) $row['sum']; } array_multisort($sum, SORT_DESC, $report['accounts']); @@ -178,79 +243,12 @@ class AccountTasker implements AccountTaskerInterface return $report; } - /** - * @param User $user - */ - public function setUser(User $user): void - { - $this->user = $user; - } - - /** - * @param array $array - * - * @return array - */ - private function groupExpenseByDestination(array $array): array - { - $defaultCurrency = app('amount')->getDefaultCurrencyByUser($this->user); - /** @var CurrencyRepositoryInterface $currencyRepos */ - $currencyRepos = app(CurrencyRepositoryInterface::class); - $currencies = [$defaultCurrency->id => $defaultCurrency,]; - $report = [ - 'accounts' => [], - 'sums' => [], - ]; - - /** @var array $journal */ - foreach ($array as $journal) { - $sourceId = (int)$journal['destination_account_id']; - $currencyId = (int)$journal['currency_id']; - $key = sprintf('%s-%s', $sourceId, $currencyId); - $currencies[$currencyId] = $currencies[$currencyId] ?? $currencyRepos->find($currencyId); - $report['accounts'][$key] = $report['accounts'][$key] ?? [ - 'id' => $sourceId, - 'name' => $journal['destination_account_name'], - 'sum' => '0', - 'average' => '0', - 'count' => 0, - 'currency_id' => $currencies[$currencyId]->id, - 'currency_name' => $currencies[$currencyId]->name, - 'currency_symbol' => $currencies[$currencyId]->symbol, - 'currency_code' => $currencies[$currencyId]->code, - 'currency_decimal_places' => $currencies[$currencyId]->decimal_places, - ]; - $report['accounts'][$key]['sum'] = bcadd($report['accounts'][$key]['sum'], $journal['amount']); - - Log::debug(sprintf('Sum for %s is now %s', $journal['destination_account_name'], $report['accounts'][$key]['sum'])); - - ++$report['accounts'][$key]['count']; - } - - // do averages and sums. - foreach (array_keys($report['accounts']) as $key) { - if ($report['accounts'][$key]['count'] > 1) { - $report['accounts'][$key]['average'] = bcdiv($report['accounts'][$key]['sum'], (string)$report['accounts'][$key]['count']); - } - $currencyId = $report['accounts'][$key]['currency_id']; - $report['sums'][$currencyId] = $report['sums'][$currencyId] ?? [ - 'sum' => '0', - 'currency_id' => $report['accounts'][$key]['currency_id'], - 'currency_name' => $report['accounts'][$key]['currency_name'], - 'currency_symbol' => $report['accounts'][$key]['currency_symbol'], - 'currency_code' => $report['accounts'][$key]['currency_code'], - 'currency_decimal_places' => $report['accounts'][$key]['currency_decimal_places'], - ]; - $report['sums'][$currencyId]['sum'] = bcadd($report['sums'][$currencyId]['sum'], $report['accounts'][$key]['sum']); - } - - return $report; - } - /** * @param array $array * * @return array + * @throws \FireflyIII\Exceptions\FireflyException + * @throws \JsonException */ private function groupIncomeBySource(array $array): array { @@ -265,8 +263,8 @@ class AccountTasker implements AccountTaskerInterface /** @var array $journal */ foreach ($array as $journal) { - $sourceId = (int)$journal['source_account_id']; - $currencyId = (int)$journal['currency_id']; + $sourceId = (int) $journal['source_account_id']; + $currencyId = (int) $journal['currency_id']; $key = sprintf('%s-%s', $sourceId, $currencyId); if (!array_key_exists($key, $report['accounts'])) { $currencies[$currencyId] = $currencies[$currencyId] ?? $currencyRepos->find($currencyId); @@ -290,7 +288,7 @@ class AccountTasker implements AccountTaskerInterface // do averages and sums. foreach (array_keys($report['accounts']) as $key) { if ($report['accounts'][$key]['count'] > 1) { - $report['accounts'][$key]['average'] = bcdiv($report['accounts'][$key]['sum'], (string)$report['accounts'][$key]['count']); + $report['accounts'][$key]['average'] = bcdiv($report['accounts'][$key]['sum'], (string) $report['accounts'][$key]['count']); } $currencyId = $report['accounts'][$key]['currency_id']; $report['sums'][$currencyId] = $report['sums'][$currencyId] ?? [ @@ -306,4 +304,12 @@ class AccountTasker implements AccountTaskerInterface return $report; } + + /** + * @param User $user + */ + public function setUser(User $user): void + { + $this->user = $user; + } } diff --git a/app/Repositories/Account/OperationsRepository.php b/app/Repositories/Account/OperationsRepository.php index 0fbbca6fed..5f7b342f80 100644 --- a/app/Repositories/Account/OperationsRepository.php +++ b/app/Repositories/Account/OperationsRepository.php @@ -56,109 +56,6 @@ class OperationsRepository implements OperationsRepositoryInterface return $this->sortByCurrency($journals, 'negative'); } - /** - * This method returns a list of all the deposit transaction journals (as arrays) set in that period - * which have the specified accounts. It's grouped per currency, with as few details in the array - * as possible. Amounts are always positive. - * - * @param Carbon $start - * @param Carbon $end - * @param Collection|null $accounts - * - * @return array - */ - public function listIncome(Carbon $start, Carbon $end, ?Collection $accounts = null): array - { - $journals = $this->getTransactions($start, $end, $accounts, TransactionType::DEPOSIT); - - return $this->sortByCurrency($journals, 'positive'); - - } - - /** - * @param User $user - */ - public function setUser(User $user): void - { - $this->user = $user; - } - - /** - * @inheritDoc - */ - public function sumExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $expense = null, ?TransactionCurrency $currency = null - ): array { - $journals = $this->getTransactionsForSum(TransactionType::WITHDRAWAL, $start, $end, $accounts, $expense, $currency); - - return $this->groupByCurrency($journals, 'negative'); - - } - - /** - * @inheritDoc - */ - public function sumExpensesByDestination( - Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $expense = null, ?TransactionCurrency $currency = null - ): array { - $journals = $this->getTransactionsForSum(TransactionType::WITHDRAWAL, $start, $end, $accounts, $expense, $currency); - - return $this->groupByDirection($journals, 'destination', 'negative'); - } - - /** - * @inheritDoc - */ - public function sumExpensesBySource( - Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $expense = null, ?TransactionCurrency $currency = null - ): array { - $journals = $this->getTransactionsForSum(TransactionType::WITHDRAWAL, $start, $end, $accounts, $expense, $currency); - - return $this->groupByDirection($journals, 'source', 'negative'); - } - - /** - * @inheritDoc - */ - public function sumIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $revenue = null, ?TransactionCurrency $currency = null - ): array { - $journals = $this->getTransactionsForSum(TransactionType::DEPOSIT, $start, $end, $accounts, $revenue, $currency); - - return $this->groupByCurrency($journals, 'positive'); - } - - /** - * @inheritDoc - */ - public function sumIncomeByDestination( - Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $revenue = null, ?TransactionCurrency $currency = null - ): array { - $journals = $this->getTransactionsForSum(TransactionType::DEPOSIT, $start, $end, $accounts, $revenue, $currency); - - return $this->groupByDirection($journals, 'destination', 'positive'); - } - - /** - * @inheritDoc - */ - public function sumIncomeBySource( - Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $revenue = null, ?TransactionCurrency $currency = null - ): array { - $journals = $this->getTransactionsForSum(TransactionType::DEPOSIT, $start, $end, $accounts, $revenue, $currency); - - return $this->groupByDirection($journals, 'source', 'positive'); - } - - /** - * @inheritDoc - */ - public function sumTransfers(Carbon $start, Carbon $end, ?Collection $accounts = null, ?TransactionCurrency $currency = null): array - { - $journals = $this->getTransactionsForSum(TransactionType::TRANSFER, $start, $end, $accounts, null, $currency); - - return $this->groupByEither($journals); - } - - /** * Collect transactions with some parameters * @@ -190,8 +87,8 @@ class OperationsRepository implements OperationsRepositoryInterface { $array = []; foreach ($journals as $journal) { - $currencyId = (int)$journal['currency_id']; - $journalId = (int)$journal['transaction_journal_id']; + $currencyId = (int) $journal['currency_id']; + $journalId = (int) $journal['transaction_journal_id']; $array[$currencyId] = $array[$currencyId] ?? [ 'currency_id' => $journal['currency_id'], @@ -203,7 +100,7 @@ class OperationsRepository implements OperationsRepositoryInterface ]; $array[$currencyId]['transaction_journals'][$journalId] = [ - 'amount' => app('steam')->$direction((string)$journal['amount']), + 'amount' => app('steam')->$direction((string) $journal['amount']), 'date' => $journal['date'], 'transaction_journal_id' => $journalId, 'budget_name' => $journal['budget_name'], @@ -223,6 +120,45 @@ class OperationsRepository implements OperationsRepositoryInterface return $array; } + /** + * This method returns a list of all the deposit transaction journals (as arrays) set in that period + * which have the specified accounts. It's grouped per currency, with as few details in the array + * as possible. Amounts are always positive. + * + * @param Carbon $start + * @param Carbon $end + * @param Collection|null $accounts + * + * @return array + */ + public function listIncome(Carbon $start, Carbon $end, ?Collection $accounts = null): array + { + $journals = $this->getTransactions($start, $end, $accounts, TransactionType::DEPOSIT); + + return $this->sortByCurrency($journals, 'positive'); + + } + + /** + * @param User $user + */ + public function setUser(User $user): void + { + $this->user = $user; + } + + /** + * @inheritDoc + */ + public function sumExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $expense = null, ?TransactionCurrency $currency = null + ): array + { + $journals = $this->getTransactionsForSum(TransactionType::WITHDRAWAL, $start, $end, $accounts, $expense, $currency); + + return $this->groupByCurrency($journals, 'negative'); + + } + /** * @param Carbon $start * @param Carbon $end @@ -236,7 +172,8 @@ class OperationsRepository implements OperationsRepositoryInterface private function getTransactionsForSum( string $type, Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $opposing = null, ?TransactionCurrency $currency = null - ): array { + ): array + { $start->startOfDay(); $end->endOfDay(); @@ -314,7 +251,7 @@ class OperationsRepository implements OperationsRepositoryInterface $array = []; foreach ($journals as $journal) { - $currencyId = (int)$journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $array[$currencyId] = $array[$currencyId] ?? [ 'sum' => '0', 'currency_id' => $currencyId, @@ -326,7 +263,7 @@ class OperationsRepository implements OperationsRepositoryInterface $array[$currencyId]['sum'] = bcadd($array[$currencyId]['sum'], app('steam')->$direction($journal['amount'])); // also do foreign amount: - $foreignId = (int)$journal['foreign_currency_id']; + $foreignId = (int) $journal['foreign_currency_id']; if (0 !== $foreignId) { $array[$foreignId] = $array[$foreignId] ?? [ 'sum' => '0', @@ -343,6 +280,18 @@ class OperationsRepository implements OperationsRepositoryInterface return $array; } + /** + * @inheritDoc + */ + public function sumExpensesByDestination( + Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $expense = null, ?TransactionCurrency $currency = null + ): array + { + $journals = $this->getTransactionsForSum(TransactionType::WITHDRAWAL, $start, $end, $accounts, $expense, $currency); + + return $this->groupByDirection($journals, 'destination', 'negative'); + } + /** * @param array $journals * @param string $direction @@ -368,10 +317,10 @@ class OperationsRepository implements OperationsRepositoryInterface 'currency_code' => $journal['currency_code'], 'currency_decimal_places' => $journal['currency_decimal_places'], ]; - $array[$key]['sum'] = bcadd($array[$key]['sum'], app('steam')->$method((string)$journal['amount'])); + $array[$key]['sum'] = bcadd($array[$key]['sum'], app('steam')->$method((string) $journal['amount'])); // also do foreign amount: - if (0 !== (int)$journal['foreign_currency_id']) { + if (0 !== (int) $journal['foreign_currency_id']) { $key = sprintf('%s-%s', $journal[$idKey], $journal['foreign_currency_id']); $array[$key] = $array[$key] ?? [ 'id' => $journal[$idKey], @@ -383,13 +332,70 @@ class OperationsRepository implements OperationsRepositoryInterface 'currency_code' => $journal['foreign_currency_code'], 'currency_decimal_places' => $journal['foreign_currency_decimal_places'], ]; - $array[$key]['sum'] = bcadd($array[$key]['sum'], app('steam')->$method((string)$journal['foreign_amount'])); + $array[$key]['sum'] = bcadd($array[$key]['sum'], app('steam')->$method((string) $journal['foreign_amount'])); } } return $array; } + /** + * @inheritDoc + */ + public function sumExpensesBySource( + Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $expense = null, ?TransactionCurrency $currency = null + ): array + { + $journals = $this->getTransactionsForSum(TransactionType::WITHDRAWAL, $start, $end, $accounts, $expense, $currency); + + return $this->groupByDirection($journals, 'source', 'negative'); + } + + /** + * @inheritDoc + */ + public function sumIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $revenue = null, ?TransactionCurrency $currency = null + ): array + { + $journals = $this->getTransactionsForSum(TransactionType::DEPOSIT, $start, $end, $accounts, $revenue, $currency); + + return $this->groupByCurrency($journals, 'positive'); + } + + /** + * @inheritDoc + */ + public function sumIncomeByDestination( + Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $revenue = null, ?TransactionCurrency $currency = null + ): array + { + $journals = $this->getTransactionsForSum(TransactionType::DEPOSIT, $start, $end, $accounts, $revenue, $currency); + + return $this->groupByDirection($journals, 'destination', 'positive'); + } + + /** + * @inheritDoc + */ + public function sumIncomeBySource( + Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $revenue = null, ?TransactionCurrency $currency = null + ): array + { + $journals = $this->getTransactionsForSum(TransactionType::DEPOSIT, $start, $end, $accounts, $revenue, $currency); + + return $this->groupByDirection($journals, 'source', 'positive'); + } + + /** + * @inheritDoc + */ + public function sumTransfers(Carbon $start, Carbon $end, ?Collection $accounts = null, ?TransactionCurrency $currency = null): array + { + $journals = $this->getTransactionsForSum(TransactionType::TRANSFER, $start, $end, $accounts, null, $currency); + + return $this->groupByEither($journals); + } + /** * @param array $journals * @@ -404,9 +410,9 @@ class OperationsRepository implements OperationsRepositoryInterface } $final = []; foreach ($return as $array) { - $array['difference_float'] = (float)$array['difference']; - $array['in_float'] = (float)$array['in']; - $array['out_float'] = (float)$array['out']; + $array['difference_float'] = (float) $array['difference']; + $array['in_float'] = (float) $array['in']; + $array['out_float'] = (float) $array['out']; $final[] = $array; } @@ -430,7 +436,7 @@ class OperationsRepository implements OperationsRepositoryInterface // source first $return[$sourceKey] = $return[$sourceKey] ?? [ - 'id' => (string)$sourceId, + 'id' => (string) $sourceId, 'name' => $journal['source_account_name'], 'difference' => '0', 'difference_float' => 0, @@ -438,13 +444,13 @@ class OperationsRepository implements OperationsRepositoryInterface 'in_float' => 0, 'out' => '0', 'out_float' => 0, - 'currency_id' => (string)$currencyId, + 'currency_id' => (string) $currencyId, 'currency_code' => $journal['currency_code'], ]; // dest next: $return[$destKey] = $return[$destKey] ?? [ - 'id' => (string)$destinationId, + 'id' => (string) $destinationId, 'name' => $journal['destination_account_name'], 'difference' => '0', 'difference_float' => 0, @@ -452,7 +458,7 @@ class OperationsRepository implements OperationsRepositoryInterface 'in_float' => 0, 'out' => '0', 'out_float' => 0, - 'currency_id' => (string)$currencyId, + 'currency_id' => (string) $currencyId, 'currency_code' => $journal['currency_code'], ]; @@ -474,7 +480,7 @@ class OperationsRepository implements OperationsRepositoryInterface // same as above: // source first $return[$sourceKey] = $return[$sourceKey] ?? [ - 'id' => (string)$sourceId, + 'id' => (string) $sourceId, 'name' => $journal['source_account_name'], 'difference' => '0', 'difference_float' => 0, @@ -482,13 +488,13 @@ class OperationsRepository implements OperationsRepositoryInterface 'in_float' => 0, 'out' => '0', 'out_float' => 0, - 'currency_id' => (string)$currencyId, + 'currency_id' => (string) $currencyId, 'currency_code' => $journal['foreign_currency_code'], ]; // dest next: $return[$destKey] = $return[$destKey] ?? [ - 'id' => (string)$destinationId, + 'id' => (string) $destinationId, 'name' => $journal['destination_account_name'], 'difference' => '0', 'difference_float' => 0, @@ -496,7 +502,7 @@ class OperationsRepository implements OperationsRepositoryInterface 'in_float' => 0, 'out' => '0', 'out_float' => 0, - 'currency_id' => (string)$currencyId, + 'currency_id' => (string) $currencyId, 'currency_code' => $journal['foreign_currency_code'], ]; // source account? money goes out! (same as above) diff --git a/app/Repositories/Attachment/AttachmentRepository.php b/app/Repositories/Attachment/AttachmentRepository.php index d5d4627c3c..b6dc30e99d 100644 --- a/app/Repositories/Attachment/AttachmentRepository.php +++ b/app/Repositories/Attachment/AttachmentRepository.php @@ -31,10 +31,8 @@ use FireflyIII\Models\Attachment; use FireflyIII\Models\Note; use FireflyIII\User; use Illuminate\Contracts\Encryption\DecryptException; -use Illuminate\Contracts\Filesystem\FileNotFoundException; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Storage; -use Log; /** * Class AttachmentRepository. @@ -101,12 +99,7 @@ class AttachmentRepository implements AttachmentRepositoryInterface $unencryptedContent = ''; if ($disk->exists($file)) { - $encryptedContent = ''; - try { - $encryptedContent = $disk->get($file); - } catch (FileNotFoundException $e) { - Log::error($e->getMessage()); - } + $encryptedContent = (string) $disk->get($file); try { $unencryptedContent = Crypt::decrypt($encryptedContent); // verified @@ -129,7 +122,7 @@ class AttachmentRepository implements AttachmentRepositoryInterface { $note = $attachment->notes()->first(); if (null !== $note) { - return (string)$note->text; + return (string) $note->text; } return null; @@ -175,20 +168,20 @@ class AttachmentRepository implements AttachmentRepositoryInterface $attachment->title = $data['title']; } - if (array_key_exists('filename', $data) && '' !== (string)$data['filename'] && $data['filename'] !== $attachment->filename) { + if (array_key_exists('filename', $data) && '' !== (string) $data['filename'] && $data['filename'] !== $attachment->filename) { $attachment->filename = $data['filename']; } // update model (move attachment) // should be validated already: if (array_key_exists('attachable_type', $data) && array_key_exists('attachable_id', $data)) { - $attachment->attachable_id = (int)$data['attachable_id']; + $attachment->attachable_id = (int) $data['attachable_id']; $attachment->attachable_type = sprintf('FireflyIII\\Models\\%s', $data['attachable_type']); } $attachment->save(); $attachment->refresh(); if (array_key_exists('notes', $data)) { - $this->updateNote($attachment, (string)$data['notes']); + $this->updateNote($attachment, (string) $data['notes']); } return $attachment; diff --git a/app/Repositories/Bill/BillRepository.php b/app/Repositories/Bill/BillRepository.php index 188007cd12..9fc2ac0ed5 100644 --- a/app/Repositories/Bill/BillRepository.php +++ b/app/Repositories/Bill/BillRepository.php @@ -55,6 +55,36 @@ class BillRepository implements BillRepositoryInterface private User $user; + /** + * @inheritDoc + */ + public function billEndsWith(string $query, int $limit): Collection + { + $search = $this->user->bills(); + if ('' !== $query) { + $search->where('name', 'LIKE', sprintf('%%%s', $query)); + } + $search->orderBy('name', 'ASC') + ->where('active', true); + + return $search->take($limit)->get(); + } + + /** + * @inheritDoc + */ + public function billStartsWith(string $query, int $limit): Collection + { + $search = $this->user->bills(); + if ('' !== $query) { + $search->where('name', 'LIKE', sprintf('%s%%', $query)); + } + $search->orderBy('name', 'ASC') + ->where('active', true); + + return $search->take($limit)->get(); + } + /** * Correct order of piggies in case of issues. */ @@ -63,7 +93,7 @@ class BillRepository implements BillRepositoryInterface $set = $this->user->bills()->orderBy('order', 'ASC')->get(); $current = 1; foreach ($set as $bill) { - if ((int)$bill->order !== $current) { + if ((int) $bill->order !== $current) { $bill->order = $current; $bill->save(); } @@ -95,18 +125,6 @@ class BillRepository implements BillRepositoryInterface $this->user->bills()->delete(); } - /** - * Find a bill by ID. - * - * @param int $billId - * - * @return Bill|null - */ - public function find(int $billId): ?Bill - { - return $this->user->bills()->find($billId); - } - /** * Find bill by parameters. * @@ -118,7 +136,7 @@ class BillRepository implements BillRepositoryInterface public function findBill(?int $billId, ?string $billName): ?Bill { if (null !== $billId) { - $searchResult = $this->find((int)$billId); + $searchResult = $this->find((int) $billId); if (null !== $searchResult) { Log::debug(sprintf('Found bill based on #%d, will return it.', $billId)); @@ -126,7 +144,7 @@ class BillRepository implements BillRepositoryInterface } } if (null !== $billName) { - $searchResult = $this->findByName((string)$billName); + $searchResult = $this->findByName((string) $billName); if (null !== $searchResult) { Log::debug(sprintf('Found bill based on "%s", will return it.', $billName)); @@ -138,6 +156,18 @@ class BillRepository implements BillRepositoryInterface return null; } + /** + * Find a bill by ID. + * + * @param int $billId + * + * @return Bill|null + */ + public function find(int $billId): ?Bill + { + return $this->user->bills()->find($billId); + } + /** * Find a bill by name. * @@ -150,17 +180,6 @@ class BillRepository implements BillRepositoryInterface return $this->user->bills()->where('name', $name)->first(['bills.*']); } - /** - * @return Collection - */ - public function getActiveBills(): Collection - { - return $this->user->bills() - ->where('active', true) - ->orderBy('bills.name', 'ASC') - ->get(['bills.*', DB::raw('((bills.amount_min + bills.amount_max) / 2) AS expectedAmount'),]); - } - /** * Get all attachments. * @@ -249,7 +268,7 @@ class BillRepository implements BillRepositoryInterface $set = $bill->transactionJournals()->after($start)->before($end)->get(['transaction_journals.*']); if ($set->count() > 0) { $journalIds = $set->pluck('id')->toArray(); - $amount = (string)Transaction::whereIn('transaction_journal_id', $journalIds)->where('amount', '<', 0)->sum('amount'); + $amount = (string) Transaction::whereIn('transaction_journal_id', $journalIds)->where('amount', '<', 0)->sum('amount'); $sum = bcadd($sum, $amount); //Log::debug(sprintf('Total > 0, so add to sum %f, which becomes %f', $amount, $sum)); } @@ -258,6 +277,17 @@ class BillRepository implements BillRepositoryInterface return $sum; } + /** + * @return Collection + */ + public function getActiveBills(): Collection + { + return $this->user->bills() + ->where('active', true) + ->orderBy('bills.name', 'ASC') + ->get(['bills.*', DB::raw('((bills.amount_min + bills.amount_max) / 2) AS expectedAmount'),]); + } + /** * Get the total amount of money paid for the users active bills in the date range given, * grouped per currency. @@ -275,10 +305,10 @@ class BillRepository implements BillRepositoryInterface foreach ($bills as $bill) { /** @var Collection $set */ $set = $bill->transactionJournals()->after($start)->before($end)->get(['transaction_journals.*']); - $currencyId = (int)$bill->transaction_currency_id; + $currencyId = (int) $bill->transaction_currency_id; if ($set->count() > 0) { $journalIds = $set->pluck('id')->toArray(); - $amount = (string)Transaction::whereIn('transaction_journal_id', $journalIds)->where('amount', '<', 0)->sum('amount'); + $amount = (string) Transaction::whereIn('transaction_journal_id', $journalIds)->where('amount', '<', 0)->sum('amount'); $return[$currencyId] = $return[$currencyId] ?? '0'; $return[$currencyId] = bcadd($amount, $return[$currencyId]); //Log::debug(sprintf('Total > 0, so add to sum %f, which becomes %f (currency %d)', $amount, $return[$currencyId], $currencyId)); @@ -311,7 +341,7 @@ class BillRepository implements BillRepositoryInterface if ($total > 0) { $average = bcdiv(bcadd($bill->amount_max, $bill->amount_min), '2'); - $multi = bcmul($average, (string)$total); + $multi = bcmul($average, (string) $total); $sum = bcadd($sum, $multi); //Log::debug(sprintf('Total > 0, so add to sum %f, which becomes %f', $multi, $sum)); } @@ -320,6 +350,71 @@ class BillRepository implements BillRepositoryInterface return $sum; } + /** + * Between start and end, tells you on which date(s) the bill is expected to hit. + * + * @param Bill $bill + * @param Carbon $start + * @param Carbon $end + * + * @return Collection + * @throws JsonException + */ + public function getPayDatesInRange(Bill $bill, Carbon $start, Carbon $end): Collection + { + $set = new Collection; + $currentStart = clone $start; + //Log::debug(sprintf('Now at bill "%s" (%s)', $bill->name, $bill->repeat_freq)); + //Log::debug(sprintf('First currentstart is %s', $currentStart->format('Y-m-d'))); + + while ($currentStart <= $end) { + //Log::debug(sprintf('Currentstart is now %s.', $currentStart->format('Y-m-d'))); + $nextExpectedMatch = $this->nextDateMatch($bill, $currentStart); + //Log::debug(sprintf('Next Date match after %s is %s', $currentStart->format('Y-m-d'), $nextExpectedMatch->format('Y-m-d'))); + if ($nextExpectedMatch > $end) {// If nextExpectedMatch is after end, we continue + break; + } + $set->push(clone $nextExpectedMatch); + //Log::debug(sprintf('Now %d dates in set.', $set->count())); + $nextExpectedMatch->addDay(); + + //Log::debug(sprintf('Currentstart (%s) has become %s.', $currentStart->format('Y-m-d'), $nextExpectedMatch->format('Y-m-d'))); + + $currentStart = clone $nextExpectedMatch; + } + + return $set; + } + + /** + * Given a bill and a date, this method will tell you at which moment this bill expects its next + * transaction. Whether or not it is there already, is not relevant. + * + * @param Bill $bill + * @param Carbon $date + * + * @return Carbon + */ + public function nextDateMatch(Bill $bill, Carbon $date): Carbon + { + $cache = new CacheProperties; + $cache->addProperty($bill->id); + $cache->addProperty('nextDateMatch'); + $cache->addProperty($date); + if ($cache->has()) { + return $cache->get(); + } + // find the most recent date for this bill NOT in the future. Cache this date: + $start = clone $bill->date; + + while ($start < $date) { + $start = app('navigation')->addPeriod($start, $bill->repeat_freq, $bill->skip); + } + $cache->store($start); + + return $start; + } + /** * Get the total amount of money due for the users active bills in the date range given. * @@ -338,13 +433,13 @@ class BillRepository implements BillRepositoryInterface $dates = $this->getPayDatesInRange($bill, $start, $end); $count = $bill->transactionJournals()->after($start)->before($end)->count(); $total = $dates->count() - $count; - $currencyId = (int)$bill->transaction_currency_id; + $currencyId = (int) $bill->transaction_currency_id; //Log::debug(sprintf('Dates = %d, journalCount = %d, total = %d', $dates->count(), $count, $total)); if ($total > 0) { $average = bcdiv(bcadd($bill->amount_max, $bill->amount_min), '2'); - $multi = bcmul($average, (string)$total); + $multi = bcmul($average, (string) $total); $return[$currencyId] = $return[$currencyId] ?? '0'; $return[$currencyId] = bcadd($return[$currencyId], $multi); //Log::debug(sprintf('Total > 0, so add to sum %f, which becomes %f (for currency %d)', $multi, $return[$currencyId], $currencyId)); @@ -378,7 +473,7 @@ class BillRepository implements BillRepositoryInterface /** @var Note $note */ $note = $bill->notes()->first(); if (null !== $note) { - return (string)$note->text; + return (string) $note->text; } return ''; @@ -403,7 +498,7 @@ class BillRepository implements BillRepositoryInterface foreach ($journals as $journal) { /** @var Transaction $transaction */ $transaction = $journal->transactions()->where('amount', '<', 0)->first(); - $currencyId = (int)$journal->transaction_currency_id; + $currencyId = (int) $journal->transaction_currency_id; $currency = $journal->transactionCurrency; $result[$currencyId] = $result[$currencyId] ?? [ 'sum' => '0', @@ -424,7 +519,7 @@ class BillRepository implements BillRepositoryInterface * @var array $arr */ foreach ($result as $currencyId => $arr) { - $result[$currencyId]['avg'] = bcdiv($arr['sum'], (string)$arr['count']); + $result[$currencyId]['avg'] = bcdiv($arr['sum'], (string) $arr['count']); } return $result; @@ -464,41 +559,6 @@ class BillRepository implements BillRepositoryInterface ); } - /** - * Between start and end, tells you on which date(s) the bill is expected to hit. - * - * @param Bill $bill - * @param Carbon $start - * @param Carbon $end - * - * @return Collection - */ - public function getPayDatesInRange(Bill $bill, Carbon $start, Carbon $end): Collection - { - $set = new Collection; - $currentStart = clone $start; - //Log::debug(sprintf('Now at bill "%s" (%s)', $bill->name, $bill->repeat_freq)); - //Log::debug(sprintf('First currentstart is %s', $currentStart->format('Y-m-d'))); - - while ($currentStart <= $end) { - //Log::debug(sprintf('Currentstart is now %s.', $currentStart->format('Y-m-d'))); - $nextExpectedMatch = $this->nextDateMatch($bill, $currentStart); - //Log::debug(sprintf('Next Date match after %s is %s', $currentStart->format('Y-m-d'), $nextExpectedMatch->format('Y-m-d'))); - if ($nextExpectedMatch > $end) {// If nextExpectedMatch is after end, we continue - break; - } - $set->push(clone $nextExpectedMatch); - //Log::debug(sprintf('Now %d dates in set.', $set->count())); - $nextExpectedMatch->addDay(); - - //Log::debug(sprintf('Currentstart (%s) has become %s.', $currentStart->format('Y-m-d'), $nextExpectedMatch->format('Y-m-d'))); - - $currentStart = clone $nextExpectedMatch; - } - - return $set; - } - /** * Return all rules for one bill * @@ -572,7 +632,7 @@ class BillRepository implements BillRepositoryInterface if (null === $transaction) { continue; } - $currencyId = (int)$journal->transaction_currency_id; + $currencyId = (int) $journal->transaction_currency_id; $currency = $journal->transactionCurrency; $result[$currencyId] = $result[$currencyId] ?? [ 'sum' => '0', @@ -593,7 +653,7 @@ class BillRepository implements BillRepositoryInterface * @var array $arr */ foreach ($result as $currencyId => $arr) { - $result[$currencyId]['avg'] = bcdiv($arr['sum'], (string)$arr['count']); + $result[$currencyId]['avg'] = bcdiv($arr['sum'], (string) $arr['count']); } return $result; @@ -609,43 +669,13 @@ class BillRepository implements BillRepositoryInterface { /** @var Transaction $transaction */ foreach ($transactions as $transaction) { - $journal = $bill->user->transactionJournals()->find((int)$transaction['transaction_journal_id']); + $journal = $bill->user->transactionJournals()->find((int) $transaction['transaction_journal_id']); $journal->bill_id = $bill->id; $journal->save(); Log::debug(sprintf('Linked journal #%d to bill #%d', $journal->id, $bill->id)); } } - /** - * Given a bill and a date, this method will tell you at which moment this bill expects its next - * transaction. Whether or not it is there already, is not relevant. - * - * @param Bill $bill - * @param Carbon $date - * - * @return Carbon - * @throws JsonException - */ - public function nextDateMatch(Bill $bill, Carbon $date): Carbon - { - $cache = new CacheProperties; - $cache->addProperty($bill->id); - $cache->addProperty('nextDateMatch'); - $cache->addProperty($date); - if ($cache->has()) { - return $cache->get(); - } - // find the most recent date for this bill NOT in the future. Cache this date: - $start = clone $bill->date; - - while ($start < $date) { - $start = app('navigation')->addPeriod($start, $bill->repeat_freq, $bill->skip); - } - $cache->store($start); - - return $start; - } - /** * Given the date in $date, this method will return a moment in the future where the bill is expected to be paid. * diff --git a/app/Repositories/Bill/BillRepositoryInterface.php b/app/Repositories/Bill/BillRepositoryInterface.php index 030cb479c1..fcae8ee822 100644 --- a/app/Repositories/Bill/BillRepositoryInterface.php +++ b/app/Repositories/Bill/BillRepositoryInterface.php @@ -35,6 +35,22 @@ use Illuminate\Support\Collection; interface BillRepositoryInterface { + /** + * @param string $query + * @param int $limit + * + * @return Collection + */ + public function billEndsWith(string $query, int $limit): Collection; + + /** + * @param string $query + * @param int $limit + * + * @return Collection + */ + public function billStartsWith(string $query, int $limit): Collection; + /** * Add correct order to bills. */ diff --git a/app/Repositories/Budget/AvailableBudgetRepository.php b/app/Repositories/Budget/AvailableBudgetRepository.php index 690e9ca75b..0c45754e0e 100644 --- a/app/Repositories/Budget/AvailableBudgetRepository.php +++ b/app/Repositories/Budget/AvailableBudgetRepository.php @@ -124,7 +124,7 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface ->where('start_date', $start->format('Y-m-d')) ->where('end_date', $end->format('Y-m-d'))->first(); if (null !== $availableBudget) { - $amount = (string)$availableBudget->amount; + $amount = (string) $availableBudget->amount; } return $amount; diff --git a/app/Repositories/Budget/BudgetLimitRepository.php b/app/Repositories/Budget/BudgetLimitRepository.php index cb4df10b1c..423a7a5451 100644 --- a/app/Repositories/Budget/BudgetLimitRepository.php +++ b/app/Repositories/Budget/BudgetLimitRepository.php @@ -147,6 +147,22 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface ->where('end_date', $end->format('Y-m-d'))->first(); } + /** + * @param TransactionCurrency $currency + * @param Carbon|null $start + * @param Carbon|null $end + * + * @return Collection + */ + public function getAllBudgetLimitsByCurrency(TransactionCurrency $currency, Carbon $start = null, Carbon $end = null): Collection + { + return $this->getAllBudgetLimits($start, $end)->filter( + static function (BudgetLimit $budgetLimit) use ($currency) { + return $budgetLimit->transaction_currency_id === $currency->id; + } + ); + } + /** * @param Carbon|null $start * @param Carbon|null $end @@ -215,22 +231,6 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface )->get(['budget_limits.*']); } - /** - * @param TransactionCurrency $currency - * @param Carbon|null $start - * @param Carbon|null $end - * - * @return Collection - */ - public function getAllBudgetLimitsByCurrency(TransactionCurrency $currency, Carbon $start = null, Carbon $end = null): Collection - { - return $this->getAllBudgetLimits($start, $end)->filter( - static function (BudgetLimit $budgetLimit) use ($currency) { - return $budgetLimit->transaction_currency_id === $currency->id; - } - ); - } - /** * @param Budget $budget * @param Carbon|null $start @@ -304,6 +304,7 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface * * @return BudgetLimit * @throws FireflyException + * @throws \JsonException */ public function store(array $data): BudgetLimit { @@ -318,7 +319,7 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface $currency->save(); // find the budget: - $budget = $this->user->budgets()->find((int)$data['budget_id']); + $budget = $this->user->budgets()->find((int) $data['budget_id']); if (null === $budget) { throw new FireflyException('200004: Budget does not exist.'); } @@ -352,6 +353,8 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface * @param array $data * * @return BudgetLimit + * @throws FireflyException + * @throws \JsonException */ public function update(BudgetLimit $budgetLimit, array $data): BudgetLimit { diff --git a/app/Repositories/Budget/BudgetRepository.php b/app/Repositories/Budget/BudgetRepository.php index 0a189ba555..705d1ab03c 100644 --- a/app/Repositories/Budget/BudgetRepository.php +++ b/app/Repositories/Budget/BudgetRepository.php @@ -30,6 +30,7 @@ use FireflyIII\Models\Attachment; use FireflyIII\Models\AutoBudget; use FireflyIII\Models\Budget; use FireflyIII\Models\BudgetLimit; +use FireflyIII\Models\Note; use FireflyIII\Models\RecurrenceTransactionMeta; use FireflyIII\Models\RuleAction; use FireflyIII\Models\RuleTrigger; @@ -47,8 +48,37 @@ use Storage; */ class BudgetRepository implements BudgetRepositoryInterface { - /** @var User */ - private $user; + private User $user; + + /** + * @inheritDoc + */ + public function budgetEndsWith(string $query, int $limit): Collection + { + $search = $this->user->budgets(); + if ('' !== $query) { + $search->where('name', 'LIKE', sprintf('%%%s', $query)); + } + $search->orderBy('order', 'ASC') + ->orderBy('name', 'ASC')->where('active', true); + + return $search->take($limit)->get(); + } + + /** + * @inheritDoc + */ + public function budgetStartsWith(string $query, int $limit): Collection + { + $search = $this->user->budgets(); + if ('' !== $query) { + $search->where('name', 'LIKE', sprintf('%s%%', $query)); + } + $search->orderBy('order', 'ASC') + ->orderBy('name', 'ASC')->where('active', true); + + return $search->take($limit)->get(); + } /** * @return bool @@ -76,6 +106,17 @@ class BudgetRepository implements BudgetRepositoryInterface return true; } + /** + * @return Collection + */ + public function getActiveBudgets(): Collection + { + return $this->user->budgets()->where('active', true) + ->orderBy('order', 'ASC') + ->orderBy('name', 'ASC') + ->get(); + } + /** * @param Budget $budget * @@ -98,14 +139,23 @@ class BudgetRepository implements BudgetRepositoryInterface $budgets = $this->getBudgets(); /** @var Budget $budget */ foreach ($budgets as $budget) { - DB::table('budget_transaction')->where('budget_id', (int)$budget->id)->delete(); - DB::table('budget_transaction_journal')->where('budget_id', (int)$budget->id)->delete(); - RecurrenceTransactionMeta::where('name', 'budget_id')->where('value', (string)$budget->id)->delete(); - RuleAction::where('action_type', 'set_budget')->where('action_value', (string)$budget->id)->delete(); + DB::table('budget_transaction')->where('budget_id', (int) $budget->id)->delete(); + DB::table('budget_transaction_journal')->where('budget_id', (int) $budget->id)->delete(); + RecurrenceTransactionMeta::where('name', 'budget_id')->where('value', (string) $budget->id)->delete(); + RuleAction::where('action_type', 'set_budget')->where('action_value', (string) $budget->id)->delete(); $budget->delete(); } } + /** + * @return Collection + */ + public function getBudgets(): Collection + { + return $this->user->budgets()->orderBy('order', 'ASC') + ->orderBy('name', 'ASC')->get(); + } + /** * @inheritDoc */ @@ -117,18 +167,6 @@ class BudgetRepository implements BudgetRepositoryInterface } } - /** - * Find a budget or return NULL - * - * @param int|null $budgetId |null - * - * @return Budget|null - */ - public function find(int $budgetId = null): ?Budget - { - return $this->user->budgets()->find($budgetId); - } - /** * @param int|null $budgetId * @param string|null $budgetName @@ -139,10 +177,10 @@ class BudgetRepository implements BudgetRepositoryInterface { Log::debug('Now in findBudget()'); Log::debug(sprintf('Searching for budget with ID #%d...', $budgetId)); - $result = $this->find((int)$budgetId); + $result = $this->find((int) $budgetId); if (null === $result && null !== $budgetName && '' !== $budgetName) { Log::debug(sprintf('Searching for budget with name %s...', $budgetName)); - $result = $this->findByName((string)$budgetName); + $result = $this->findByName((string) $budgetName); } if (null !== $result) { Log::debug(sprintf('Found budget #%d: %s', $result->id, $result->name)); @@ -152,6 +190,18 @@ class BudgetRepository implements BudgetRepositoryInterface return $result; } + /** + * Find a budget or return NULL + * + * @param int|null $budgetId |null + * + * @return Budget|null + */ + public function find(int $budgetId = null): ?Budget + { + return $this->user->budgets()->find($budgetId); + } + /** * Find budget by name. * @@ -187,17 +237,6 @@ class BudgetRepository implements BudgetRepositoryInterface return null; } - /** - * @return Collection - */ - public function getActiveBudgets(): Collection - { - return $this->user->budgets()->where('active', true) - ->orderBy('order', 'ASC') - ->orderBy('name', 'ASC') - ->get(); - } - /** * @inheritDoc */ @@ -219,23 +258,6 @@ class BudgetRepository implements BudgetRepositoryInterface ); } - /** - * @inheritDoc - */ - public function getAutoBudget(Budget $budget): ?AutoBudget - { - return $budget->autoBudgets()->first(); - } - - /** - * @return Collection - */ - public function getBudgets(): Collection - { - return $this->user->budgets()->orderBy('order', 'ASC') - ->orderBy('name', 'ASC')->get(); - } - /** * Get all budgets with these ID's. * @@ -258,9 +280,17 @@ class BudgetRepository implements BudgetRepositoryInterface ->orderBy('name', 'ASC')->where('active', 0)->get(); } - public function getMaxOrder(): int + /** + * @inheritDoc + */ + public function getNoteText(Budget $budget): ?string { - return (int)$this->user->budgets()->max('order'); + $note = $budget->notes()->first(); + if (null === $note) { + return null; + } + + return $note->text; } /** @@ -305,6 +335,7 @@ class BudgetRepository implements BudgetRepositoryInterface * * @return Budget * @throws FireflyException + * @throws \JsonException */ public function store(array $data): Budget { @@ -323,6 +354,12 @@ class BudgetRepository implements BudgetRepositoryInterface Log::error($e->getTraceAsString()); throw new FireflyException('400002: Could not store budget.', 0, $e); } + + // set notes + if (array_key_exists('notes', $data)) { + $this->setNoteText($newBudget, (string) $data['notes']); + } + if (!array_key_exists('auto_budget_type', $data) || !array_key_exists('auto_budget_amount', $data) || !array_key_exists('auto_budget_period', $data)) { return $newBudget; } @@ -344,10 +381,10 @@ class BudgetRepository implements BudgetRepositoryInterface $repos = app(CurrencyRepositoryInterface::class); $currency = null; if (array_key_exists('currency_id', $data)) { - $currency = $repos->find((int)$data['currency_id']); + $currency = $repos->find((int) $data['currency_id']); } if (array_key_exists('currency_code', $data)) { - $currency = $repos->findByCode((string)$data['currency_code']); + $currency = $repos->findByCode((string) $data['currency_code']); } if (null === $currency) { $currency = app('amount')->getDefaultCurrencyByUser($this->user); @@ -381,6 +418,38 @@ class BudgetRepository implements BudgetRepositoryInterface return $newBudget; } + public function getMaxOrder(): int + { + return (int) $this->user->budgets()->max('order'); + } + + /** + * @param Budget $budget + * @param string $text + * @return void + */ + private function setNoteText(Budget $budget, string $text): void + { + $dbNote = $budget->notes()->first(); + if ('' !== $text) { + if (null === $dbNote) { + $dbNote = new Note; + $dbNote->noteable()->associate($budget); + } + $dbNote->text = trim($text); + $dbNote->save(); + + return; + } + if (null !== $dbNote) { + try { + $dbNote->delete(); + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException + } + } + } + /** * @param Budget $budget * @param array $data @@ -400,6 +469,9 @@ class BudgetRepository implements BudgetRepositoryInterface if (array_key_exists('active', $data)) { $budget->active = $data['active']; } + if (array_key_exists('notes', $data)) { + $this->setNoteText($budget, (string) $data['notes']); + } $budget->save(); // update or create auto-budget: @@ -467,9 +539,19 @@ class BudgetRepository implements BudgetRepositoryInterface } } + /** + * @inheritDoc + */ + public function getAutoBudget(Budget $budget): ?AutoBudget + { + return $budget->autoBudgets()->first(); + } + /** * @param Budget $budget * @param array $data + * @throws FireflyException + * @throws \JsonException */ private function updateAutoBudget(Budget $budget, array $data): void { @@ -490,8 +572,8 @@ class BudgetRepository implements BudgetRepositoryInterface // set or update the currency. if (array_key_exists('currency_id', $data) || array_key_exists('currency_code', $data)) { $repos = app(CurrencyRepositoryInterface::class); - $currencyId = (int)($data['currency_id'] ?? 0); - $currencyCode = (string)($data['currency_code'] ?? ''); + $currencyId = (int) ($data['currency_id'] ?? 0); + $currencyCode = (string) ($data['currency_code'] ?? ''); $currency = $repos->find($currencyId); if (null === $currency) { $currency = $repos->findByCodeNull($currencyCode); diff --git a/app/Repositories/Budget/BudgetRepositoryInterface.php b/app/Repositories/Budget/BudgetRepositoryInterface.php index d3f30b2f1e..d06d560530 100644 --- a/app/Repositories/Budget/BudgetRepositoryInterface.php +++ b/app/Repositories/Budget/BudgetRepositoryInterface.php @@ -34,6 +34,22 @@ use Illuminate\Support\Collection; */ interface BudgetRepositoryInterface { + /** + * @param string $query + * @param int $limit + * + * @return Collection + */ + public function budgetEndsWith(string $query, int $limit): Collection; + + /** + * @param string $query + * @param int $limit + * + * @return Collection + */ + public function budgetStartsWith(string $query, int $limit): Collection; + /** * @return bool */ @@ -134,6 +150,12 @@ interface BudgetRepositoryInterface */ public function getMaxOrder(): int; + /** + * @param Budget $budget + * @return string|null + */ + public function getNoteText(Budget $budget): ?string; + /** * @param string $query * @param int $limit @@ -168,4 +190,5 @@ interface BudgetRepositoryInterface * @return Budget */ public function update(Budget $budget, array $data): Budget; + } diff --git a/app/Repositories/Budget/NoBudgetRepository.php b/app/Repositories/Budget/NoBudgetRepository.php index eb2dd385f9..9a0d1df208 100644 --- a/app/Repositories/Budget/NoBudgetRepository.php +++ b/app/Repositories/Budget/NoBudgetRepository.php @@ -61,7 +61,7 @@ class NoBudgetRepository implements NoBudgetRepositoryInterface /** @var array $journal */ foreach ($journals as $journal) { - $currencyId = (int)$journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $data[$currencyId] = $data[$currencyId] ?? [ 'id' => 0, @@ -133,12 +133,12 @@ class NoBudgetRepository implements NoBudgetRepositoryInterface /** @var TransactionCurrency $currency */ $currency = $currencies[$code]; $return[] = [ - 'currency_id' => (string)$currency['id'], + 'currency_id' => (string) $currency['id'], 'currency_code' => $code, 'currency_name' => $currency['name'], 'currency_symbol' => $currency['symbol'], 'currency_decimal_places' => $currency['decimal_places'], - 'amount' => number_format((float)$spent, $currency['decimal_places'], '.', ''), + 'amount' => number_format((float) $spent, $currency['decimal_places'], '.', ''), ]; } @@ -176,7 +176,7 @@ class NoBudgetRepository implements NoBudgetRepositoryInterface $array = []; foreach ($journals as $journal) { - $currencyId = (int)$journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $array[$currencyId] = $array[$currencyId] ?? [ 'sum' => '0', 'currency_id' => $currencyId, diff --git a/app/Repositories/Budget/OperationsRepository.php b/app/Repositories/Budget/OperationsRepository.php index ea82a15aa0..cf2777b26d 100644 --- a/app/Repositories/Budget/OperationsRepository.php +++ b/app/Repositories/Budget/OperationsRepository.php @@ -25,9 +25,11 @@ namespace FireflyIII\Repositories\Budget; use Carbon\Carbon; use FireflyIII\Helpers\Collector\GroupCollectorInterface; +use FireflyIII\Models\Account; use FireflyIII\Models\Budget; use FireflyIII\Models\TransactionCurrency; use FireflyIII\Models\TransactionType; +use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\User; use Illuminate\Support\Collection; use Log; @@ -56,15 +58,15 @@ class OperationsRepository implements OperationsRepositoryInterface foreach ($budget->budgetlimits as $limit) { $diff = $limit->start_date->diffInDays($limit->end_date); $diff = 0 === $diff ? 1 : $diff; - $amount = (string)$limit->amount; - $perDay = bcdiv($amount, (string)$diff); + $amount = (string) $limit->amount; + $perDay = bcdiv($amount, (string) $diff); $total = bcadd($total, $perDay); $count++; Log::debug(sprintf('Found %d budget limits. Per day is %s, total is %s', $count, $perDay, $total)); } $avg = $total; if ($count > 0) { - $avg = bcdiv($total, (string)$count); + $avg = bcdiv($total, (string) $count); } Log::debug(sprintf('%s / %d = %s = average.', $total, $count, $avg)); @@ -98,9 +100,9 @@ class OperationsRepository implements OperationsRepositoryInterface /** @var array $journal */ foreach ($journals as $journal) { // prep data array for currency: - $budgetId = (int)$journal['budget_id']; + $budgetId = (int) $journal['budget_id']; $budgetName = $journal['budget_name']; - $currencyId = (int)$journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $key = sprintf('%d-%d', $budgetId, $currencyId); $data[$key] = $data[$key] ?? [ @@ -152,9 +154,9 @@ class OperationsRepository implements OperationsRepositoryInterface $array = []; foreach ($journals as $journal) { - $currencyId = (int)$journal['currency_id']; - $budgetId = (int)$journal['budget_id']; - $budgetName = (string)$journal['budget_name']; + $currencyId = (int) $journal['currency_id']; + $budgetId = (int) $journal['budget_id']; + $budgetName = (string) $journal['budget_name']; // catch "no category" entries. if (0 === $budgetId) { @@ -180,7 +182,7 @@ class OperationsRepository implements OperationsRepositoryInterface // add journal to array: // only a subset of the fields. - $journalId = (int)$journal['transaction_journal_id']; + $journalId = (int) $journal['transaction_journal_id']; $array[$currencyId]['budgets'][$budgetId]['transaction_journals'][$journalId] = [ 'amount' => app('steam')->negative($journal['amount']), 'destination_account_id' => $journal['destination_account_id'], @@ -198,6 +200,19 @@ class OperationsRepository implements OperationsRepositoryInterface return $array; } + /** + * @return Collection + */ + private function getBudgets(): Collection + { + /** @var BudgetRepositoryInterface $repos */ + $repos = app(BudgetRepositoryInterface::class); + + return $repos->getActiveBudgets(); + } + + /** @noinspection MoreThanThreeArgumentsInspection */ + /** * @param User $user */ @@ -206,8 +221,6 @@ class OperationsRepository implements OperationsRepositoryInterface $this->user = $user; } - /** @noinspection MoreThanThreeArgumentsInspection */ - /** * @param Collection $budgets * @param Collection $accounts @@ -257,12 +270,12 @@ class OperationsRepository implements OperationsRepositoryInterface /** @var TransactionCurrency $currency */ $currency = $currencies[$code]; $return[] = [ - 'currency_id' => (string)$currency['id'], + 'currency_id' => (string) $currency['id'], 'currency_code' => $code, 'currency_name' => $currency['name'], 'currency_symbol' => $currency['symbol'], 'currency_decimal_places' => $currency['decimal_places'], - 'amount' => number_format((float)$spent, $currency['decimal_places'], '.', ''), + 'amount' => number_format((float) $spent, $currency['decimal_places'], '.', ''), ]; } @@ -279,13 +292,35 @@ class OperationsRepository implements OperationsRepositoryInterface * @return array */ public function sumExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $budgets = null, ?TransactionCurrency $currency = null - ): array { + ): array + { Log::debug(sprintf('Now in %s', __METHOD__)); $start->startOfDay(); $end->endOfDay(); + + // this collector excludes all transfers TO + // liabilities (which are also withdrawals) + // because those expenses only become expenses + // once they move from the liability to the friend. + // TODO this filter must be somewhere in AccountRepositoryInterface because I suspect its needed more often (A113) + $repository = app(AccountRepositoryInterface::class); + $repository->setUser($this->user); + $subset = $repository->getAccountsByType(config('firefly.valid_liabilities')); + $selection = new Collection; + /** @var Account $account */ + foreach ($subset as $account) { + if ('credit' === $repository->getMetaValue($account, 'liability_direction')) { + $selection->push($account); + } + } + + /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); - $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionType::WITHDRAWAL]); + $collector->setUser($this->user) + ->setRange($start, $end) + ->excludeDestinationAccounts($selection) + ->setTypes([TransactionType::WITHDRAWAL]); if (null !== $accounts) { $collector->setAccounts($accounts); @@ -318,7 +353,7 @@ class OperationsRepository implements OperationsRepositoryInterface $array = []; foreach ($journals as $journal) { - $currencyId = (int)$journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $array[$currencyId] = $array[$currencyId] ?? [ 'sum' => '0', 'currency_id' => $currencyId, @@ -330,7 +365,7 @@ class OperationsRepository implements OperationsRepositoryInterface $array[$currencyId]['sum'] = bcadd($array[$currencyId]['sum'], app('steam')->negative($journal['amount'])); // also do foreign amount: - $foreignId = (int)$journal['foreign_currency_id']; + $foreignId = (int) $journal['foreign_currency_id']; if (0 !== $foreignId) { $array[$foreignId] = $array[$foreignId] ?? [ 'sum' => '0', @@ -347,17 +382,6 @@ class OperationsRepository implements OperationsRepositoryInterface return $array; } - /** - * @return Collection - */ - private function getBudgets(): Collection - { - /** @var BudgetRepositoryInterface $repos */ - $repos = app(BudgetRepositoryInterface::class); - - return $repos->getActiveBudgets(); - } - /** * For now, simply refer to whichever repository holds this function. * See reference nr. 14 diff --git a/app/Repositories/Category/CategoryRepository.php b/app/Repositories/Category/CategoryRepository.php index c94a7be944..030bbc63e6 100644 --- a/app/Repositories/Category/CategoryRepository.php +++ b/app/Repositories/Category/CategoryRepository.php @@ -46,6 +46,32 @@ class CategoryRepository implements CategoryRepositoryInterface { private User $user; + /** + * @inheritDoc + */ + public function categoryEndsWith(string $query, int $limit): Collection + { + $search = $this->user->categories(); + if ('' !== $query) { + $search->where('name', 'LIKE', sprintf('%%%s', $query)); + } + + return $search->take($limit)->get(); + } + + /** + * @inheritDoc + */ + public function categoryStartsWith(string $query, int $limit): Collection + { + $search = $this->user->categories(); + if ('' !== $query) { + $search->where('name', 'LIKE', sprintf('%s%%', $query)); + } + + return $search->take($limit)->get(); + } + /** * @param Category $category * @@ -78,6 +104,44 @@ class CategoryRepository implements CategoryRepositoryInterface } } + /** + * Returns a list of all the categories belonging to a user. + * + * @return Collection + */ + public function getCategories(): Collection + { + return $this->user->categories()->with(['attachments'])->orderBy('name', 'ASC')->get(); + } + + /** + * @param int|null $categoryId + * @param string|null $categoryName + * + * @return Category|null + * @throws FireflyException + */ + public function findCategory(?int $categoryId, ?string $categoryName): ?Category + { + Log::debug('Now in findCategory()'); + Log::debug(sprintf('Searching for category with ID #%d...', $categoryId)); + $result = $this->find((int) $categoryId); + if (null === $result) { + Log::debug(sprintf('Searching for category with name %s...', $categoryName)); + $result = $this->findByName((string) $categoryName); + if (null === $result && '' !== (string) $categoryName) { + // create it! + $result = $this->store(['name' => $categoryName]); + } + } + if (null !== $result) { + Log::debug(sprintf('Found category #%d: %s', $result->id, $result->name)); + } + Log::debug(sprintf('Found category result is null? %s', var_export(null === $result, true))); + + return $result; + } + /** * Find a category or return NULL * @@ -103,31 +167,54 @@ class CategoryRepository implements CategoryRepositoryInterface } /** - * @param int|null $categoryId - * @param string|null $categoryName + * @param array $data * - * @return Category|null + * @return Category * @throws FireflyException */ - public function findCategory(?int $categoryId, ?string $categoryName): ?Category + public function store(array $data): Category { - Log::debug('Now in findCategory()'); - Log::debug(sprintf('Searching for category with ID #%d...', $categoryId)); - $result = $this->find((int)$categoryId); - if (null === $result) { - Log::debug(sprintf('Searching for category with name %s...', $categoryName)); - $result = $this->findByName((string)$categoryName); - if (null === $result && '' !== (string)$categoryName) { - // create it! - $result = $this->store(['name' => $categoryName]); - } - } - if (null !== $result) { - Log::debug(sprintf('Found category #%d: %s', $result->id, $result->name)); - } - Log::debug(sprintf('Found category result is null? %s', var_export(null === $result, true))); + /** @var CategoryFactory $factory */ + $factory = app(CategoryFactory::class); + $factory->setUser($this->user); - return $result; + $category = $factory->findOrCreate(null, $data['name']); + + if (null === $category) { + throw new FireflyException(sprintf('400003: Could not store new category with name "%s"', $data['name'])); + } + + if (array_key_exists('notes', $data) && '' === $data['notes']) { + $this->removeNotes($category); + } + if (array_key_exists('notes', $data) && '' !== $data['notes']) { + $this->updateNotes($category, $data['notes']); + } + + return $category; + + } + + /** + * @param Category $category + */ + public function removeNotes(Category $category): void + { + $category->notes()->delete(); + } + + /** + * @inheritDoc + */ + public function updateNotes(Category $category, string $notes): void + { + $dbNote = $category->notes()->first(); + if (null === $dbNote) { + $dbNote = new Note; + $dbNote->noteable()->associate($category); + } + $dbNote->text = trim($notes); + $dbNote->save(); } /** @@ -158,6 +245,43 @@ class CategoryRepository implements CategoryRepositoryInterface return $firstJournalDate; } + /** + * @param Category $category + * + * @return Carbon|null + */ + private function getFirstJournalDate(Category $category): ?Carbon + { + $query = $category->transactionJournals()->orderBy('date', 'ASC'); + $result = $query->first(['transaction_journals.*']); + + if (null !== $result) { + return $result->date; + } + + return null; + } + + /** + * @param Category $category + * + * @return Carbon|null + */ + private function getFirstTransactionDate(Category $category): ?Carbon + { + // check transactions: + $query = $category->transactions() + ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') + ->orderBy('transaction_journals.date', 'ASC'); + + $lastTransaction = $query->first(['transaction_journals.*']); + if (null !== $lastTransaction) { + return new Carbon($lastTransaction->date); + } + + return null; + } + /** * @inheritDoc */ @@ -191,16 +315,6 @@ class CategoryRepository implements CategoryRepositoryInterface return $this->user->categories()->whereIn('id', $categoryIds)->get(); } - /** - * Returns a list of all the categories belonging to a user. - * - * @return Collection - */ - public function getCategories(): Collection - { - return $this->user->categories()->with(['attachments'])->orderBy('name', 'ASC')->get(); - } - /** * @inheritDoc */ @@ -243,134 +357,6 @@ class CategoryRepository implements CategoryRepositoryInterface return $lastJournalDate; } - /** - * @param Category $category - */ - public function removeNotes(Category $category): void - { - $category->notes()->delete(); - } - - /** - * @param string $query - * @param int $limit - * - * @return Collection - */ - public function searchCategory(string $query, int $limit): Collection - { - $search = $this->user->categories(); - if ('' !== $query) { - $search->where('name', 'LIKE', sprintf('%%%s%%', $query)); - } - - return $search->take($limit)->get(); - } - - /** - * @param User $user - */ - public function setUser(User $user): void - { - $this->user = $user; - } - - /** - * @param array $data - * - * @return Category - * @throws FireflyException - */ - public function store(array $data): Category - { - /** @var CategoryFactory $factory */ - $factory = app(CategoryFactory::class); - $factory->setUser($this->user); - - $category = $factory->findOrCreate(null, $data['name']); - - if (null === $category) { - throw new FireflyException(sprintf('400003: Could not store new category with name "%s"', $data['name'])); - } - - if (array_key_exists('notes', $data) && '' === $data['notes']) { - $this->removeNotes($category); - } - if (array_key_exists('notes', $data) && '' !== $data['notes']) { - $this->updateNotes($category, $data['notes']); - } - - return $category; - - } - - /** - * @param Category $category - * @param array $data - * - * @return Category - * @throws Exception - */ - public function update(Category $category, array $data): Category - { - /** @var CategoryUpdateService $service */ - $service = app(CategoryUpdateService::class); - $service->setUser($this->user); - - return $service->update($category, $data); - } - - /** - * @inheritDoc - */ - public function updateNotes(Category $category, string $notes): void - { - $dbNote = $category->notes()->first(); - if (null === $dbNote) { - $dbNote = new Note; - $dbNote->noteable()->associate($category); - } - $dbNote->text = trim($notes); - $dbNote->save(); - } - - /** - * @param Category $category - * - * @return Carbon|null - */ - private function getFirstJournalDate(Category $category): ?Carbon - { - $query = $category->transactionJournals()->orderBy('date', 'ASC'); - $result = $query->first(['transaction_journals.*']); - - if (null !== $result) { - return $result->date; - } - - return null; - } - - /** - * @param Category $category - * - * @return Carbon|null - */ - private function getFirstTransactionDate(Category $category): ?Carbon - { - // check transactions: - $query = $category->transactions() - ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') - ->orderBy('transaction_journals.date', 'ASC'); - - $lastTransaction = $query->first(['transaction_journals.*']); - if (null !== $lastTransaction) { - return new Carbon($lastTransaction->date); - } - - return null; - } - /** * @param Category $category * @param Collection $accounts @@ -420,4 +406,44 @@ class CategoryRepository implements CategoryRepositoryInterface return null; } + + /** + * @param string $query + * @param int $limit + * + * @return Collection + */ + public function searchCategory(string $query, int $limit): Collection + { + $search = $this->user->categories(); + if ('' !== $query) { + $search->where('name', 'LIKE', sprintf('%%%s%%', $query)); + } + + return $search->take($limit)->get(); + } + + /** + * @param User $user + */ + public function setUser(User $user): void + { + $this->user = $user; + } + + /** + * @param Category $category + * @param array $data + * + * @return Category + * @throws Exception + */ + public function update(Category $category, array $data): Category + { + /** @var CategoryUpdateService $service */ + $service = app(CategoryUpdateService::class); + $service->setUser($this->user); + + return $service->update($category, $data); + } } diff --git a/app/Repositories/Category/CategoryRepositoryInterface.php b/app/Repositories/Category/CategoryRepositoryInterface.php index 007153ba61..d26dd08bf3 100644 --- a/app/Repositories/Category/CategoryRepositoryInterface.php +++ b/app/Repositories/Category/CategoryRepositoryInterface.php @@ -34,6 +34,22 @@ use Illuminate\Support\Collection; interface CategoryRepositoryInterface { + /** + * @param string $query + * @param int $limit + * + * @return Collection + */ + public function categoryEndsWith(string $query, int $limit): Collection; + + /** + * @param string $query + * @param int $limit + * + * @return Collection + */ + public function categoryStartsWith(string $query, int $limit): Collection; + /** * @param Category $category * diff --git a/app/Repositories/Category/NoCategoryRepository.php b/app/Repositories/Category/NoCategoryRepository.php index d24e528f8b..10d86f127b 100644 --- a/app/Repositories/Category/NoCategoryRepository.php +++ b/app/Repositories/Category/NoCategoryRepository.php @@ -60,7 +60,7 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface $array = []; foreach ($journals as $journal) { - $currencyId = (int)$journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $array[$currencyId] = $array[$currencyId] ?? [ 'categories' => [], 'currency_id' => $currencyId, @@ -72,13 +72,13 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface // info about the non-existent category: $array[$currencyId]['categories'][0] = $array[$currencyId]['categories'][0] ?? [ 'id' => 0, - 'name' => (string)trans('firefly.noCategory'), + 'name' => (string) trans('firefly.noCategory'), 'transaction_journals' => [], ]; // add journal to array: // only a subset of the fields. - $journalId = (int)$journal['transaction_journal_id']; + $journalId = (int) $journal['transaction_journal_id']; $array[$currencyId]['categories'][0]['transaction_journals'][$journalId] = [ 'amount' => app('steam')->negative($journal['amount']), @@ -113,7 +113,7 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface $array = []; foreach ($journals as $journal) { - $currencyId = (int)$journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $array[$currencyId] = $array[$currencyId] ?? [ 'categories' => [], 'currency_id' => $currencyId, @@ -126,12 +126,12 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface // info about the non-existent category: $array[$currencyId]['categories'][0] = $array[$currencyId]['categories'][0] ?? [ 'id' => 0, - 'name' => (string)trans('firefly.noCategory'), + 'name' => (string) trans('firefly.noCategory'), 'transaction_journals' => [], ]; // add journal to array: // only a subset of the fields. - $journalId = (int)$journal['transaction_journal_id']; + $journalId = (int) $journal['transaction_journal_id']; $array[$currencyId]['categories'][0]['transaction_journals'][$journalId] = [ 'amount' => app('steam')->positive($journal['amount']), @@ -173,7 +173,7 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface $array = []; foreach ($journals as $journal) { - $currencyId = (int)$journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $array[$currencyId] = $array[$currencyId] ?? [ 'sum' => '0', 'currency_id' => $currencyId, @@ -210,7 +210,7 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface $array = []; foreach ($journals as $journal) { - $currencyId = (int)$journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $array[$currencyId] = $array[$currencyId] ?? [ 'sum' => '0', 'currency_id' => $currencyId, @@ -241,7 +241,7 @@ class NoCategoryRepository implements NoCategoryRepositoryInterface $array = []; foreach ($journals as $journal) { - $currencyId = (int)$journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $array[$currencyId] = $array[$currencyId] ?? [ 'sum' => '0', 'currency_id' => $currencyId, diff --git a/app/Repositories/Category/OperationsRepository.php b/app/Repositories/Category/OperationsRepository.php index 7c72218355..510de53ef9 100644 --- a/app/Repositories/Category/OperationsRepository.php +++ b/app/Repositories/Category/OperationsRepository.php @@ -70,9 +70,9 @@ class OperationsRepository implements OperationsRepositoryInterface $array = []; foreach ($journals as $journal) { - $currencyId = (int)$journal['currency_id']; - $categoryId = (int)$journal['category_id']; - $categoryName = (string)$journal['category_name']; + $currencyId = (int) $journal['currency_id']; + $categoryId = (int) $journal['category_id']; + $categoryName = (string) $journal['category_name']; // catch "no category" entries. if (0 === $categoryId) { @@ -98,7 +98,7 @@ class OperationsRepository implements OperationsRepositoryInterface // add journal to array: // only a subset of the fields. - $journalId = (int)$journal['transaction_journal_id']; + $journalId = (int) $journal['transaction_journal_id']; $array[$currencyId]['categories'][$categoryId]['transaction_journals'][$journalId] = [ 'amount' => app('steam')->negative($journal['amount']), 'date' => $journal['date'], @@ -116,6 +116,16 @@ class OperationsRepository implements OperationsRepositoryInterface return $array; } + /** + * Returns a list of all the categories belonging to a user. + * + * @return Collection + */ + private function getCategories(): Collection + { + return $this->user->categories()->get(); + } + /** * This method returns a list of all the deposit transaction journals (as arrays) set in that period * which have the specified category set to them. It's grouped per currency, with as few details in the array @@ -147,13 +157,13 @@ class OperationsRepository implements OperationsRepositoryInterface $array = []; foreach ($journals as $journal) { - $currencyId = (int)$journal['currency_id']; - $categoryId = (int)$journal['category_id']; - $categoryName = (string)$journal['category_name']; + $currencyId = (int) $journal['currency_id']; + $categoryId = (int) $journal['category_id']; + $categoryName = (string) $journal['category_name']; // catch "no category" entries. if (0 === $categoryId) { - $categoryName = (string)trans('firefly.no_category'); + $categoryName = (string) trans('firefly.no_category'); } // info about the currency: @@ -175,7 +185,7 @@ class OperationsRepository implements OperationsRepositoryInterface // add journal to array: // only a subset of the fields. - $journalId = (int)$journal['transaction_journal_id']; + $journalId = (int) $journal['transaction_journal_id']; $array[$currencyId]['categories'][$categoryId]['transaction_journals'][$journalId] = [ 'amount' => app('steam')->positive($journal['amount']), 'date' => $journal['date'], @@ -192,6 +202,138 @@ class OperationsRepository implements OperationsRepositoryInterface return $array; } + /** + * @inheritDoc + */ + public function listTransferredIn(Carbon $start, Carbon $end, Collection $accounts, ?Collection $categories = null): array + { + /** @var GroupCollectorInterface $collector */ + $collector = app(GroupCollectorInterface::class); + $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionType::TRANSFER]) + ->setDestinationAccounts($accounts)->excludeSourceAccounts($accounts); + if (null !== $categories && $categories->count() > 0) { + $collector->setCategories($categories); + } + if (null === $categories || (null !== $categories && 0 === $categories->count())) { + $collector->setCategories($this->getCategories()); + } + $collector->withCategoryInformation()->withAccountInformation()->withBudgetInformation(); + $journals = $collector->getExtractedJournals(); + $array = []; + + foreach ($journals as $journal) { + $currencyId = (int) $journal['currency_id']; + $categoryId = (int) $journal['category_id']; + $categoryName = (string) $journal['category_name']; + + // catch "no category" entries. + if (0 === $categoryId) { + continue; + } + + // info about the currency: + $array[$currencyId] = $array[$currencyId] ?? [ + 'categories' => [], + 'currency_id' => $currencyId, + 'currency_name' => $journal['currency_name'], + 'currency_symbol' => $journal['currency_symbol'], + 'currency_code' => $journal['currency_code'], + 'currency_decimal_places' => $journal['currency_decimal_places'], + ]; + + // info about the categories: + $array[$currencyId]['categories'][$categoryId] = $array[$currencyId]['categories'][$categoryId] ?? [ + 'id' => $categoryId, + 'name' => $categoryName, + 'transaction_journals' => [], + ]; + + // add journal to array: + // only a subset of the fields. + $journalId = (int) $journal['transaction_journal_id']; + $array[$currencyId]['categories'][$categoryId]['transaction_journals'][$journalId] = [ + 'amount' => app('steam')->positive($journal['amount']), + 'date' => $journal['date'], + 'source_account_id' => $journal['source_account_id'], + 'category_name' => $journal['category_name'], + 'source_account_name' => $journal['source_account_name'], + 'destination_account_id' => $journal['destination_account_id'], + 'destination_account_name' => $journal['destination_account_name'], + 'description' => $journal['description'], + 'transaction_group_id' => $journal['transaction_group_id'], + ]; + + } + + return $array; + } + + /** + * @inheritDoc + */ + public function listTransferredOut(Carbon $start, Carbon $end, Collection $accounts, ?Collection $categories = null): array + { + /** @var GroupCollectorInterface $collector */ + $collector = app(GroupCollectorInterface::class); + $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionType::TRANSFER]) + ->setSourceAccounts($accounts)->excludeDestinationAccounts($accounts); + if (null !== $categories && $categories->count() > 0) { + $collector->setCategories($categories); + } + if (null === $categories || (null !== $categories && 0 === $categories->count())) { + $collector->setCategories($this->getCategories()); + } + $collector->withCategoryInformation()->withAccountInformation()->withBudgetInformation(); + $journals = $collector->getExtractedJournals(); + $array = []; + + foreach ($journals as $journal) { + $currencyId = (int) $journal['currency_id']; + $categoryId = (int) $journal['category_id']; + $categoryName = (string) $journal['category_name']; + + // catch "no category" entries. + if (0 === $categoryId) { + continue; + } + + // info about the currency: + $array[$currencyId] = $array[$currencyId] ?? [ + 'categories' => [], + 'currency_id' => $currencyId, + 'currency_name' => $journal['currency_name'], + 'currency_symbol' => $journal['currency_symbol'], + 'currency_code' => $journal['currency_code'], + 'currency_decimal_places' => $journal['currency_decimal_places'], + ]; + + // info about the categories: + $array[$currencyId]['categories'][$categoryId] = $array[$currencyId]['categories'][$categoryId] ?? [ + 'id' => $categoryId, + 'name' => $categoryName, + 'transaction_journals' => [], + ]; + + // add journal to array: + // only a subset of the fields. + $journalId = (int) $journal['transaction_journal_id']; + $array[$currencyId]['categories'][$categoryId]['transaction_journals'][$journalId] = [ + 'amount' => app('steam')->negative($journal['amount']), + 'date' => $journal['date'], + 'source_account_id' => $journal['source_account_id'], + 'category_name' => $journal['category_name'], + 'source_account_name' => $journal['source_account_name'], + 'destination_account_id' => $journal['destination_account_id'], + 'destination_account_name' => $journal['destination_account_name'], + 'description' => $journal['description'], + 'transaction_group_id' => $journal['transaction_group_id'], + ]; + + } + + return $array; + } + /** * @param User $user */ @@ -229,14 +371,14 @@ class OperationsRepository implements OperationsRepositoryInterface $array = []; foreach ($journals as $journal) { - $currencyId = (int)$journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $array[$currencyId] = $array[$currencyId] ?? [ 'sum' => '0', 'currency_id' => $currencyId, 'currency_name' => $journal['currency_name'], 'currency_symbol' => $journal['currency_symbol'], 'currency_code' => $journal['currency_code'], - 'currency_decimal_places' => (int)$journal['currency_decimal_places'], + 'currency_decimal_places' => (int) $journal['currency_decimal_places'], ]; $array[$currencyId]['sum'] = bcadd($array[$currencyId]['sum'], app('steam')->negative($journal['amount'])); } @@ -272,7 +414,7 @@ class OperationsRepository implements OperationsRepositoryInterface $array = []; foreach ($journals as $journal) { - $currencyId = (int)$journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $array[$currencyId] = $array[$currencyId] ?? [ 'sum' => '0', 'currency_id' => $currencyId, @@ -315,7 +457,7 @@ class OperationsRepository implements OperationsRepositoryInterface $array = []; foreach ($journals as $journal) { - $currencyId = (int)$journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $array[$currencyId] = $array[$currencyId] ?? [ 'sum' => '0', 'currency_id' => $currencyId, @@ -329,146 +471,4 @@ class OperationsRepository implements OperationsRepositoryInterface return $array; } - - /** - * Returns a list of all the categories belonging to a user. - * - * @return Collection - */ - private function getCategories(): Collection - { - return $this->user->categories()->get(); - } - - /** - * @inheritDoc - */ - public function listTransferredIn(Carbon $start, Carbon $end, Collection $accounts, ?Collection $categories = null): array - { - /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); - $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionType::TRANSFER]) - ->setDestinationAccounts($accounts)->excludeSourceAccounts($accounts); - if (null !== $categories && $categories->count() > 0) { - $collector->setCategories($categories); - } - if (null === $categories || (null !== $categories && 0 === $categories->count())) { - $collector->setCategories($this->getCategories()); - } - $collector->withCategoryInformation()->withAccountInformation()->withBudgetInformation(); - $journals = $collector->getExtractedJournals(); - $array = []; - - foreach ($journals as $journal) { - $currencyId = (int)$journal['currency_id']; - $categoryId = (int)$journal['category_id']; - $categoryName = (string)$journal['category_name']; - - // catch "no category" entries. - if (0 === $categoryId) { - continue; - } - - // info about the currency: - $array[$currencyId] = $array[$currencyId] ?? [ - 'categories' => [], - 'currency_id' => $currencyId, - 'currency_name' => $journal['currency_name'], - 'currency_symbol' => $journal['currency_symbol'], - 'currency_code' => $journal['currency_code'], - 'currency_decimal_places' => $journal['currency_decimal_places'], - ]; - - // info about the categories: - $array[$currencyId]['categories'][$categoryId] = $array[$currencyId]['categories'][$categoryId] ?? [ - 'id' => $categoryId, - 'name' => $categoryName, - 'transaction_journals' => [], - ]; - - // add journal to array: - // only a subset of the fields. - $journalId = (int)$journal['transaction_journal_id']; - $array[$currencyId]['categories'][$categoryId]['transaction_journals'][$journalId] = [ - 'amount' => app('steam')->positive($journal['amount']), - 'date' => $journal['date'], - 'source_account_id' => $journal['source_account_id'], - 'category_name' => $journal['category_name'], - 'source_account_name' => $journal['source_account_name'], - 'destination_account_id' => $journal['destination_account_id'], - 'destination_account_name' => $journal['destination_account_name'], - 'description' => $journal['description'], - 'transaction_group_id' => $journal['transaction_group_id'], - ]; - - } - - return $array; - } - - /** - * @inheritDoc - */ - public function listTransferredOut(Carbon $start, Carbon $end, Collection $accounts, ?Collection $categories = null): array - { - /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); - $collector->setUser($this->user)->setRange($start, $end)->setTypes([TransactionType::TRANSFER]) - ->setSourceAccounts($accounts)->excludeDestinationAccounts($accounts); - if (null !== $categories && $categories->count() > 0) { - $collector->setCategories($categories); - } - if (null === $categories || (null !== $categories && 0 === $categories->count())) { - $collector->setCategories($this->getCategories()); - } - $collector->withCategoryInformation()->withAccountInformation()->withBudgetInformation(); - $journals = $collector->getExtractedJournals(); - $array = []; - - foreach ($journals as $journal) { - $currencyId = (int)$journal['currency_id']; - $categoryId = (int)$journal['category_id']; - $categoryName = (string)$journal['category_name']; - - // catch "no category" entries. - if (0 === $categoryId) { - continue; - } - - // info about the currency: - $array[$currencyId] = $array[$currencyId] ?? [ - 'categories' => [], - 'currency_id' => $currencyId, - 'currency_name' => $journal['currency_name'], - 'currency_symbol' => $journal['currency_symbol'], - 'currency_code' => $journal['currency_code'], - 'currency_decimal_places' => $journal['currency_decimal_places'], - ]; - - // info about the categories: - $array[$currencyId]['categories'][$categoryId] = $array[$currencyId]['categories'][$categoryId] ?? [ - 'id' => $categoryId, - 'name' => $categoryName, - 'transaction_journals' => [], - ]; - - // add journal to array: - // only a subset of the fields. - $journalId = (int)$journal['transaction_journal_id']; - $array[$currencyId]['categories'][$categoryId]['transaction_journals'][$journalId] = [ - 'amount' => app('steam')->negative($journal['amount']), - 'date' => $journal['date'], - 'source_account_id' => $journal['source_account_id'], - 'category_name' => $journal['category_name'], - 'source_account_name' => $journal['source_account_name'], - 'destination_account_id' => $journal['destination_account_id'], - 'destination_account_name' => $journal['destination_account_name'], - 'description' => $journal['description'], - 'transaction_group_id' => $journal['transaction_group_id'], - ]; - - } - - return $array; - } } diff --git a/app/Repositories/Category/OperationsRepositoryInterface.php b/app/Repositories/Category/OperationsRepositoryInterface.php index 38eab4b695..0f24e11ad5 100644 --- a/app/Repositories/Category/OperationsRepositoryInterface.php +++ b/app/Repositories/Category/OperationsRepositoryInterface.php @@ -47,6 +47,20 @@ interface OperationsRepositoryInterface */ public function listExpenses(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array; + /** + * This method returns a list of all the deposit transaction journals (as arrays) set in that period + * which have the specified category set to them. It's grouped per currency, with as few details in the array + * as possible. Amounts are always positive. + * + * @param Carbon $start + * @param Carbon $end + * @param Collection|null $accounts + * @param Collection|null $categories + * + * @return array + */ + public function listIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array; + /** * This method returns a list of all the transfer transaction journals (as arrays) set in that period * which have the specified category set to them, transferred INTO the listed accounts. @@ -55,7 +69,7 @@ interface OperationsRepositoryInterface * * @param Carbon $start * @param Carbon $end - * @param Collection $accounts + * @param Collection $accounts * @param Collection|null $categories * * @return array @@ -70,27 +84,13 @@ interface OperationsRepositoryInterface * * @param Carbon $start * @param Carbon $end - * @param Collection $accounts + * @param Collection $accounts * @param Collection|null $categories * * @return array */ public function listTransferredOut(Carbon $start, Carbon $end, Collection $accounts, ?Collection $categories = null): array; - /** - * This method returns a list of all the deposit transaction journals (as arrays) set in that period - * which have the specified category set to them. It's grouped per currency, with as few details in the array - * as possible. Amounts are always positive. - * - * @param Carbon $start - * @param Carbon $end - * @param Collection|null $accounts - * @param Collection|null $categories - * - * @return array - */ - public function listIncome(Carbon $start, Carbon $end, ?Collection $accounts = null, ?Collection $categories = null): array; - /** * @param User $user */ diff --git a/app/Repositories/Currency/CurrencyRepository.php b/app/Repositories/Currency/CurrencyRepository.php index 456008442b..4619703cfc 100644 --- a/app/Repositories/Currency/CurrencyRepository.php +++ b/app/Repositories/Currency/CurrencyRepository.php @@ -39,6 +39,7 @@ use FireflyIII\Services\Internal\Destroy\CurrencyDestroyService; use FireflyIII\Services\Internal\Update\CurrencyUpdateService; use FireflyIII\User; use Illuminate\Support\Collection; +use JsonException; use Log; /** @@ -48,19 +49,6 @@ class CurrencyRepository implements CurrencyRepositoryInterface { private User $user; - /** - * @param TransactionCurrency $currency - * - * @return int - */ - public function countJournals(TransactionCurrency $currency): int - { - $count = $currency->transactions()->whereNull('deleted_at')->count() + $currency->transactionJournals()->whereNull('deleted_at')->count(); - - // also count foreign: - return $count + Transaction::where('foreign_currency_id', $currency->id)->count(); - } - /** * @param TransactionCurrency $currency * @@ -98,7 +86,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface } // is being used in accounts: - $meta = AccountMeta::where('name', 'currency_id')->where('data', json_encode((string)$currency->id))->count(); + $meta = AccountMeta::where('name', 'currency_id')->where('data', json_encode((string) $currency->id))->count(); if ($meta > 0) { Log::info(sprintf('Used in %d accounts as currency_id, return true. ', $meta)); @@ -127,7 +115,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface $meta = AccountMeta ::leftJoin('accounts', 'accounts.id', '=', 'account_meta.account_id') ->whereNull('accounts.deleted_at') - ->where('account_meta.name', 'currency_id')->where('account_meta.data', json_encode((int)$currency->id))->count(); + ->where('account_meta.name', 'currency_id')->where('account_meta.data', json_encode((int) $currency->id))->count(); if ($meta > 0) { Log::info(sprintf('Used in %d accounts as currency_id, return true. ', $meta)); @@ -163,6 +151,27 @@ class CurrencyRepository implements CurrencyRepositoryInterface return null; } + /** + * @param TransactionCurrency $currency + * + * @return int + */ + public function countJournals(TransactionCurrency $currency): int + { + $count = $currency->transactions()->whereNull('deleted_at')->count() + $currency->transactionJournals()->whereNull('deleted_at')->count(); + + // also count foreign: + return $count + Transaction::where('foreign_currency_id', $currency->id)->count(); + } + + /** + * @return Collection + */ + public function getAll(): Collection + { + return TransactionCurrency::orderBy('code', 'ASC')->get(); + } + /** * @param TransactionCurrency $currency * @@ -193,37 +202,22 @@ class CurrencyRepository implements CurrencyRepositoryInterface } /** - * @param TransactionCurrency $currency - * Enables a currency + * @inheritDoc */ - public function enable(TransactionCurrency $currency): void + public function ensureMinimalEnabledCurrencies(): void { - $currency->enabled = true; - $currency->save(); - } - - /** - * Find by ID, return NULL if not found. - * - * @param int $currencyId - * - * @return TransactionCurrency|null - */ - public function find(int $currencyId): ?TransactionCurrency - { - return TransactionCurrency::find($currencyId); - } - - /** - * Find by currency code, return NULL if unfound. - * - * @param string $currencyCode - * - * @return TransactionCurrency|null - */ - public function findByCode(string $currencyCode): ?TransactionCurrency - { - return TransactionCurrency::where('code', $currencyCode)->first(); + // if no currencies are enabled, enable the first one in the DB (usually the EUR) + if (0 === $this->get()->count()) { + /** @var TransactionCurrency $first */ + $first = $this->getAll()->first(); + if (null === $first) { + throw new FireflyException('No currencies found. You broke Firefly III'); + } + Log::channel('audit')->info(sprintf('Auto-enabled currency %s.', $first->code)); + $this->enable($first); + app('preferences')->set('currencyPreference', $first->code); + app('preferences')->mark(); + } } /** @@ -299,6 +293,8 @@ class CurrencyRepository implements CurrencyRepositoryInterface * @param string|null $currencyCode * * @return TransactionCurrency + * @throws FireflyException + * @throws JsonException */ public function findCurrency(?int $currencyId, ?string $currencyCode): TransactionCurrency { @@ -333,10 +329,10 @@ class CurrencyRepository implements CurrencyRepositoryInterface public function findCurrencyNull(?int $currencyId, ?string $currencyCode): ?TransactionCurrency { Log::debug('Now in findCurrencyNull()'); - $result = $this->find((int)$currencyId); + $result = $this->find((int) $currencyId); if (null === $result) { Log::debug(sprintf('Searching for currency with code %s...', $currencyCode)); - $result = $this->findByCode((string)$currencyCode); + $result = $this->findByCode((string) $currencyCode); } if (null !== $result && false === $result->enabled) { Log::debug(sprintf('Also enabled currency %s', $result->code)); @@ -347,19 +343,45 @@ class CurrencyRepository implements CurrencyRepositoryInterface } /** - * @return Collection + * Find by ID, return NULL if not found. + * + * @param int $currencyId + * + * @return TransactionCurrency|null */ - public function get(): Collection + public function find(int $currencyId): ?TransactionCurrency { - return TransactionCurrency::where('enabled', true)->orderBy('code', 'ASC')->get(); + return TransactionCurrency::find($currencyId); + } + + /** + * Find by currency code, return NULL if unfound. + * + * @param string $currencyCode + * + * @return TransactionCurrency|null + */ + public function findByCode(string $currencyCode): ?TransactionCurrency + { + return TransactionCurrency::where('code', $currencyCode)->first(); + } + + /** + * @param TransactionCurrency $currency + * Enables a currency + */ + public function enable(TransactionCurrency $currency): void + { + $currency->enabled = true; + $currency->save(); } /** * @return Collection */ - public function getAll(): Collection + public function get(): Collection { - return TransactionCurrency::orderBy('code', 'ASC')->get(); + return TransactionCurrency::where('enabled', true)->orderBy('code', 'ASC')->get(); } /** diff --git a/app/Repositories/Currency/CurrencyRepositoryInterface.php b/app/Repositories/Currency/CurrencyRepositoryInterface.php index 7c50d812de..35efcb3b76 100644 --- a/app/Repositories/Currency/CurrencyRepositoryInterface.php +++ b/app/Repositories/Currency/CurrencyRepositoryInterface.php @@ -35,7 +35,6 @@ use Illuminate\Support\Collection; */ interface CurrencyRepositoryInterface { - /** * @param TransactionCurrency $currency * @@ -80,6 +79,11 @@ interface CurrencyRepositoryInterface */ public function enable(TransactionCurrency $currency): void; + /** + * @return void + */ + public function ensureMinimalEnabledCurrencies(): void; + /** * Find by ID, return NULL if not found. * diff --git a/app/Repositories/Journal/JournalAPIRepository.php b/app/Repositories/Journal/JournalAPIRepository.php index 7bee05f256..ea86e6f1e2 100644 --- a/app/Repositories/Journal/JournalAPIRepository.php +++ b/app/Repositories/Journal/JournalAPIRepository.php @@ -69,9 +69,9 @@ class JournalAPIRepository implements JournalAPIRepositoryInterface return $set->each( static function (Attachment $attachment) use ($disk) { - $notes = $attachment->notes()->first(); + $notes = $attachment->notes()->first(); $attachment->file_exists = $disk->exists($attachment->fileName()); - $attachment->notes = $notes ? $notes->text : ''; + $attachment->notes = $notes ? $notes->text : ''; return $attachment; } diff --git a/app/Repositories/Journal/JournalCLIRepository.php b/app/Repositories/Journal/JournalCLIRepository.php index 8f35ff4b22..28aa64bff2 100644 --- a/app/Repositories/Journal/JournalCLIRepository.php +++ b/app/Repositories/Journal/JournalCLIRepository.php @@ -118,7 +118,6 @@ class JournalCLIRepository implements JournalCLIRepositoryInterface * @param string $field * * @return null|Carbon - * @throws JsonException */ public function getMetaDate(TransactionJournal $journal, string $field): ?Carbon { @@ -162,7 +161,6 @@ class JournalCLIRepository implements JournalCLIRepositoryInterface * @param string $field * * @return null|string - * @throws JsonException */ public function getMetaField(TransactionJournal $journal, string $field): ?string { @@ -190,7 +188,7 @@ class JournalCLIRepository implements JournalCLIRepositoryInterface } // return when something else: - $return = (string)$value; + $return = (string) $value; try { $cache->store($return); } catch (Exception $e) { // @phpstan-ignore-line @@ -232,8 +230,8 @@ class JournalCLIRepository implements JournalCLIRepositoryInterface $journalIds = []; /** @var stdClass $row */ foreach ($result as $row) { - if ((int)$row->transaction_count > 2) { - $journalIds[] = (int)$row->id; + if ((int) $row->transaction_count > 2) { + $journalIds[] = (int) $row->id; } } $journalIds = array_unique($journalIds); diff --git a/app/Repositories/Journal/JournalRepository.php b/app/Repositories/Journal/JournalRepository.php index ab33d71f2f..5e682539d6 100644 --- a/app/Repositories/Journal/JournalRepository.php +++ b/app/Repositories/Journal/JournalRepository.php @@ -130,7 +130,6 @@ class JournalRepository implements JournalRepositoryInterface * @param TransactionJournal $journal * * @return string - * @throws JsonException */ public function getJournalTotal(TransactionJournal $journal): string { @@ -143,7 +142,7 @@ class JournalRepository implements JournalRepositoryInterface // saves on queries: $amount = $journal->transactions()->where('amount', '>', 0)->get()->sum('amount'); - $amount = (string)$amount; + $amount = (string) $amount; $cache->store($amount); return $amount; @@ -187,7 +186,6 @@ class JournalRepository implements JournalRepositoryInterface * @param string $field * * @return null|Carbon - * @throws JsonException */ public function getMetaDateById(int $journalId, string $field): ?Carbon { diff --git a/app/Repositories/LinkType/LinkTypeRepository.php b/app/Repositories/LinkType/LinkTypeRepository.php index 1b23de45ef..c7ecd437c7 100644 --- a/app/Repositories/LinkType/LinkTypeRepository.php +++ b/app/Repositories/LinkType/LinkTypeRepository.php @@ -80,30 +80,6 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface return true; } - /** - * @param int $linkTypeId - * - * @return LinkType|null - */ - public function find(int $linkTypeId): ?LinkType - { - return LinkType::find($linkTypeId); - } - - /** - * @param string|null $name - * - * @return LinkType|null - */ - public function findByName(string $name = null): ?LinkType - { - if (null === $name) { - return null; - } - - return LinkType::where('name', $name)->first(); - } - /** * Check if link exists between journals. * @@ -121,24 +97,6 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface return $count + $opposingCount > 0; } - /** - * See if such a link already exists (and get it). - * - * @param LinkType $linkType - * @param TransactionJournal $inward - * @param TransactionJournal $outward - * - * @return TransactionJournalLink|null - */ - public function findSpecificLink(LinkType $linkType, TransactionJournal $inward, TransactionJournal $outward): ?TransactionJournalLink - { - return TransactionJournalLink - ::where('link_type_id', $linkType->id) - ->where('source_id', $inward->id) - ->where('destination_id', $outward->id)->first(); - - } - /** * @return Collection */ @@ -188,6 +146,16 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface return $query->get(['journal_links.*']); } + public function getLink(TransactionJournal $one, TransactionJournal $two): ?TransactionJournalLink + { + $left = TransactionJournalLink::whereDestinationId($one->id)->whereSourceId($two->id)->first(); + if (null !== $left) { + return $left; + } + + return TransactionJournalLink::whereDestinationId($two->id)->whereSourceId($one->id)->first(); + } + /** * Return list of existing connections. * @@ -245,7 +213,7 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface */ public function storeLink(array $information, TransactionJournal $inward, TransactionJournal $outward): ?TransactionJournalLink { - $linkType = $this->find((int)($information['link_type_id'] ?? 0)); + $linkType = $this->find((int) ($information['link_type_id'] ?? 0)); if (null === $linkType) { $linkType = $this->findByName($information['link_type_name']); @@ -277,11 +245,96 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface $link->save(); // make note in noteable: - $this->setNoteText($link, (string)$information['notes']); + $this->setNoteText($link, (string) $information['notes']); return $link; } + /** + * @param int $linkTypeId + * + * @return LinkType|null + */ + public function find(int $linkTypeId): ?LinkType + { + return LinkType::find($linkTypeId); + } + + /** + * @param string|null $name + * + * @return LinkType|null + */ + public function findByName(string $name = null): ?LinkType + { + if (null === $name) { + return null; + } + + return LinkType::where('name', $name)->first(); + } + + /** + * See if such a link already exists (and get it). + * + * @param LinkType $linkType + * @param TransactionJournal $inward + * @param TransactionJournal $outward + * + * @return TransactionJournalLink|null + */ + public function findSpecificLink(LinkType $linkType, TransactionJournal $inward, TransactionJournal $outward): ?TransactionJournalLink + { + return TransactionJournalLink + ::where('link_type_id', $linkType->id) + ->where('source_id', $inward->id) + ->where('destination_id', $outward->id)->first(); + + } + + /** + * @param TransactionJournalLink $link + * @param string $text + * + * @throws Exception + */ + private function setNoteText(TransactionJournalLink $link, string $text): void + { + $dbNote = $link->notes()->first(); + if ('' !== $text) { + if (null === $dbNote) { + $dbNote = new Note(); + $dbNote->noteable()->associate($link); + } + $dbNote->text = trim($text); + $dbNote->save(); + + return; + } + if (null !== $dbNote && '' === $text) { + try { + $dbNote->delete(); + } catch (Exception $e) { // @phpstan-ignore-line + // @ignoreException + } + } + + } + + /** + * @inheritDoc + */ + public function switchLinkById(int $linkId): bool + { + /** @var TransactionJournalLink $link */ + $link = TransactionJournalLink::find($linkId); + if (null !== $link && $link->source->user->id === $this->user->id) { + $this->switchLink($link); + } + + return true; + } + /** * @param TransactionJournalLink $link * @@ -305,13 +358,13 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface */ public function update(LinkType $linkType, array $data): LinkType { - if (array_key_exists('name', $data) && '' !== (string)$data['name']) { + if (array_key_exists('name', $data) && '' !== (string) $data['name']) { $linkType->name = $data['name']; } - if (array_key_exists('inward', $data) && '' !== (string)$data['inward']) { + if (array_key_exists('inward', $data) && '' !== (string) $data['inward']) { $linkType->inward = $data['inward']; } - if (array_key_exists('outward', $data) && '' !== (string)$data['outward']) { + if (array_key_exists('outward', $data) && '' !== (string) $data['outward']) { $linkType->outward = $data['outward']; } $linkType->save(); @@ -350,57 +403,4 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface return $journalLink; } - - /** - * @param TransactionJournalLink $link - * @param string $text - * - * @throws Exception - */ - private function setNoteText(TransactionJournalLink $link, string $text): void - { - $dbNote = $link->notes()->first(); - if ('' !== $text) { - if (null === $dbNote) { - $dbNote = new Note(); - $dbNote->noteable()->associate($link); - } - $dbNote->text = trim($text); - $dbNote->save(); - - return; - } - if (null !== $dbNote && '' === $text) { - try { - $dbNote->delete(); - } catch (Exception $e) { // @phpstan-ignore-line - // @ignoreException - } - } - - } - - public function getLink(TransactionJournal $one, TransactionJournal $two): ?TransactionJournalLink - { - $left = TransactionJournalLink::whereDestinationId($one->id)->whereSourceId($two->id)->first(); - if (null !== $left) { - return $left; - } - - return TransactionJournalLink::whereDestinationId($two->id)->whereSourceId($one->id)->first(); - } - - /** - * @inheritDoc - */ - public function switchLinkById(int $linkId): bool - { - /** @var TransactionJournalLink $link */ - $link = TransactionJournalLink::find($linkId); - if (null !== $link && $link->source->user->id === $this->user->id) { - $this->switchLink($link); - } - - return true; - } } diff --git a/app/Repositories/ObjectGroup/CreatesObjectGroups.php b/app/Repositories/ObjectGroup/CreatesObjectGroups.php index 69fadd48d0..da4f22897b 100644 --- a/app/Repositories/ObjectGroup/CreatesObjectGroups.php +++ b/app/Repositories/ObjectGroup/CreatesObjectGroups.php @@ -67,7 +67,7 @@ trait CreatesObjectGroups */ protected function getObjectGroupMaxOrder(): int { - return (int)$this->user->objectGroups()->max('order'); + return (int) $this->user->objectGroups()->max('order'); } /** diff --git a/app/Repositories/ObjectGroup/ObjectGroupRepository.php b/app/Repositories/ObjectGroup/ObjectGroupRepository.php index b86efc0bb4..72758404d7 100644 --- a/app/Repositories/ObjectGroup/ObjectGroupRepository.php +++ b/app/Repositories/ObjectGroup/ObjectGroupRepository.php @@ -52,6 +52,17 @@ class ObjectGroupRepository implements ObjectGroupRepositoryInterface } } + /** + * @inheritDoc + */ + public function get(): Collection + { + return $this->user->objectGroups() + ->with(['piggyBanks', 'bills']) + ->orderBy('order', 'ASC') + ->orderBy('title', 'ASC')->get(); + } + /** * @inheritDoc */ @@ -81,17 +92,6 @@ class ObjectGroupRepository implements ObjectGroupRepositoryInterface $objectGroup->delete(); } - /** - * @inheritDoc - */ - public function get(): Collection - { - return $this->user->objectGroups() - ->with(['piggyBanks', 'bills']) - ->orderBy('order', 'ASC') - ->orderBy('title', 'ASC')->get(); - } - /** * @inheritDoc */ @@ -118,7 +118,7 @@ class ObjectGroupRepository implements ObjectGroupRepositoryInterface $index = 1; /** @var ObjectGroup $objectGroup */ foreach ($list as $objectGroup) { - if ($index !== (int)$objectGroup->order) { + if ($index !== (int) $objectGroup->order) { Log::debug( sprintf('objectGroup #%d ("%s"): order should %d be but is %d.', $objectGroup->id, $objectGroup->title, $index, $objectGroup->order) ); @@ -151,12 +151,38 @@ class ObjectGroupRepository implements ObjectGroupRepositoryInterface return $dbQuery->take($limit)->get(['object_groups.*']); } + /** + * @param User $user + */ + public function setUser(User $user): void + { + $this->user = $user; + } + + /** + * @inheritDoc + */ + public function update(ObjectGroup $objectGroup, array $data): ObjectGroup + { + if (array_key_exists('title', $data)) { + $objectGroup->title = $data['title']; + } + + if (array_key_exists('order', $data)) { + $this->setOrder($objectGroup, (int) $data['order']); + } + + $objectGroup->save(); + + return $objectGroup; + } + /** * @inheritDoc */ public function setOrder(ObjectGroup $objectGroup, int $newOrder): ObjectGroup { - $oldOrder = (int)$objectGroup->order; + $oldOrder = (int) $objectGroup->order; if ($newOrder > $oldOrder) { $this->user->objectGroups()->where('object_groups.order', '<=', $newOrder)->where('object_groups.order', '>', $oldOrder) @@ -179,30 +205,4 @@ class ObjectGroupRepository implements ObjectGroupRepositoryInterface return $objectGroup; } - - /** - * @param User $user - */ - public function setUser(User $user): void - { - $this->user = $user; - } - - /** - * @inheritDoc - */ - public function update(ObjectGroup $objectGroup, array $data): ObjectGroup - { - if (array_key_exists('title', $data)) { - $objectGroup->title = $data['title']; - } - - if (array_key_exists('order', $data)) { - $this->setOrder($objectGroup, (int)$data['order']); - } - - $objectGroup->save(); - - return $objectGroup; - } } diff --git a/app/Repositories/PiggyBank/ModifiesPiggyBanks.php b/app/Repositories/PiggyBank/ModifiesPiggyBanks.php index 3a631be562..99f093f9a5 100644 --- a/app/Repositories/PiggyBank/ModifiesPiggyBanks.php +++ b/app/Repositories/PiggyBank/ModifiesPiggyBanks.php @@ -90,11 +90,16 @@ trait ModifiesPiggyBanks { $today = today(config('app.timezone')); $leftOnAccount = $this->leftOnAccount($piggyBank, $today); - $savedSoFar = (string)$this->getRepetition($piggyBank)->currentamount; - $leftToSave = bcsub($piggyBank->targetamount, $savedSoFar); - $maxAmount = 1 === bccomp($leftOnAccount, $leftToSave) ? $leftToSave : $leftOnAccount; - $compare = bccomp($amount, $maxAmount); - $result = $compare <= 0; + $savedSoFar = (string) $this->getRepetition($piggyBank)->currentamount; + $maxAmount = $leftOnAccount; + $leftToSave = null; + if (0.0 !== (float) $piggyBank->targetamount) { + $leftToSave = bcsub($piggyBank->targetamount, $savedSoFar); + $maxAmount = 1 === bccomp($leftOnAccount, $leftToSave) ? $leftToSave : $leftOnAccount; + } + + $compare = bccomp($amount, $maxAmount); + $result = $compare <= 0; Log::debug(sprintf('Left on account: %s on %s', $leftOnAccount, $today->format('Y-m-d'))); Log::debug(sprintf('Saved so far: %s', $savedSoFar)); @@ -122,21 +127,6 @@ trait ModifiesPiggyBanks return bccomp($amount, $savedSoFar) <= 0; } - /** - * @param PiggyBank $piggyBank - * @param string $amount - * - * @return PiggyBankEvent - */ - public function createEvent(PiggyBank $piggyBank, string $amount): PiggyBankEvent - { - if (0 === bccomp('0', $amount)) { - return new PiggyBankEvent; - } - - return PiggyBankEvent::create(['date' => Carbon::now(), 'amount' => $amount, 'piggy_bank_id' => $piggyBank->id]); - } - /** * @param PiggyBank $piggyBank * @param string $amount @@ -190,6 +180,21 @@ trait ModifiesPiggyBanks return true; } + /** + * @param PiggyBank $piggyBank + * @param string $amount + * + * @return PiggyBankEvent + */ + public function createEvent(PiggyBank $piggyBank, string $amount): PiggyBankEvent + { + if (0 === bccomp('0', $amount)) { + return new PiggyBankEvent; + } + + return PiggyBankEvent::create(['date' => Carbon::now(), 'amount' => $amount, 'piggy_bank_id' => $piggyBank->id]); + } + /** * @inheritDoc */ @@ -200,23 +205,6 @@ trait ModifiesPiggyBanks return $piggyBank; } - /** - * Correct order of piggies in case of issues. - */ - public function resetOrder(): void - { - $set = $this->user->piggyBanks()->orderBy('piggy_banks.order', 'ASC')->get(['piggy_banks.*']); - $current = 1; - foreach ($set as $piggyBank) { - if ((int)$piggyBank->order !== $current) { - Log::debug(sprintf('Piggy bank #%d ("%s") was at place %d but should be on %d', $piggyBank->id, $piggyBank->name, $piggyBank->order, $current)); - $piggyBank->order = $current; - $piggyBank->save(); - } - $current++; - } - } - /** * @param PiggyBank $piggyBank * @param string $amount @@ -257,34 +245,6 @@ trait ModifiesPiggyBanks } - /** - * @inheritDoc - */ - public function setOrder(PiggyBank $piggyBank, int $newOrder): bool - { - $oldOrder = (int)$piggyBank->order; - Log::debug(sprintf('Will move piggy bank #%d ("%s") from %d to %d', $piggyBank->id, $piggyBank->name, $oldOrder, $newOrder)); - if ($newOrder > $oldOrder) { - $this->user->piggyBanks()->where('piggy_banks.order', '<=', $newOrder)->where('piggy_banks.order', '>', $oldOrder) - ->where('piggy_banks.id', '!=', $piggyBank->id) - ->decrement('piggy_banks.order'); - $piggyBank->order = $newOrder; - Log::debug(sprintf('Order of piggy #%d ("%s") is now %d', $piggyBank->id, $piggyBank->name, $newOrder)); - $piggyBank->save(); - - return true; - } - - $this->user->piggyBanks()->where('piggy_banks.order', '>=', $newOrder)->where('piggy_banks.order', '<', $oldOrder) - ->where('piggy_banks.id', '!=', $piggyBank->id) - ->increment('piggy_banks.order'); - $piggyBank->order = $newOrder; - Log::debug(sprintf('Order of piggy #%d ("%s") is now %d', $piggyBank->id, $piggyBank->name, $newOrder)); - $piggyBank->save(); - - return true; - } - /** * @param array $data * @@ -332,7 +292,7 @@ trait ModifiesPiggyBanks } // try also with ID - $objectGroupId = (int)($data['object_group_id'] ?? 0); + $objectGroupId = (int) ($data['object_group_id'] ?? 0); if (0 !== $objectGroupId) { $objectGroup = $this->findObjectGroupById($objectGroupId); if (null !== $objectGroup) { @@ -345,70 +305,48 @@ trait ModifiesPiggyBanks } /** - * @param PiggyBank $piggyBank - * @param array $data - * - * @return PiggyBank + * Correct order of piggies in case of issues. */ - public function update(PiggyBank $piggyBank, array $data): PiggyBank + public function resetOrder(): void { - $piggyBank = $this->updateProperties($piggyBank, $data); - if (array_key_exists('notes', $data)) { - $this->updateNote($piggyBank, (string)$data['notes']); - } - - // update the order of the piggy bank: - $oldOrder = (int)$piggyBank->order; - $newOrder = (int)($data['order'] ?? $oldOrder); - if ($oldOrder !== $newOrder) { - $this->setOrder($piggyBank, $newOrder); - } - - // if the piggy bank is now smaller than the current relevant rep, - // remove money from the rep. - $repetition = $this->getRepetition($piggyBank); - if (null !== $repetition && $repetition->currentamount > $piggyBank->targetamount) { - $diff = bcsub($piggyBank->targetamount, $repetition->currentamount); - $this->createEvent($piggyBank, $diff); - - $repetition->currentamount = $piggyBank->targetamount; - $repetition->save(); - } - - // update using name: - if (array_key_exists('object_group_title', $data)) { - $objectGroupTitle = (string)$data['object_group_title']; - if ('' !== $objectGroupTitle) { - $objectGroup = $this->findOrCreateObjectGroup($objectGroupTitle); - if (null !== $objectGroup) { - $piggyBank->objectGroups()->sync([$objectGroup->id]); - $piggyBank->save(); - } - - return $piggyBank; - } - // remove if name is empty. Should be overruled by ID. - if ('' === $objectGroupTitle) { - $piggyBank->objectGroups()->sync([]); + $set = $this->user->piggyBanks()->orderBy('piggy_banks.order', 'ASC')->get(['piggy_banks.*']); + $current = 1; + foreach ($set as $piggyBank) { + if ((int) $piggyBank->order !== $current) { + Log::debug(sprintf('Piggy bank #%d ("%s") was at place %d but should be on %d', $piggyBank->id, $piggyBank->name, $piggyBank->order, $current)); + $piggyBank->order = $current; $piggyBank->save(); } + $current++; + } + } + + /** + * @inheritDoc + */ + public function setOrder(PiggyBank $piggyBank, int $newOrder): bool + { + $oldOrder = (int) $piggyBank->order; + Log::debug(sprintf('Will move piggy bank #%d ("%s") from %d to %d', $piggyBank->id, $piggyBank->name, $oldOrder, $newOrder)); + if ($newOrder > $oldOrder) { + $this->user->piggyBanks()->where('piggy_banks.order', '<=', $newOrder)->where('piggy_banks.order', '>', $oldOrder) + ->where('piggy_banks.id', '!=', $piggyBank->id) + ->decrement('piggy_banks.order'); + $piggyBank->order = $newOrder; + Log::debug(sprintf('Order of piggy #%d ("%s") is now %d', $piggyBank->id, $piggyBank->name, $newOrder)); + $piggyBank->save(); + + return true; } - // try also with ID: - if (array_key_exists('object_group_id', $data)) { - $objectGroupId = (int)($data['object_group_id'] ?? 0); - if (0 !== $objectGroupId) { - $objectGroup = $this->findObjectGroupById($objectGroupId); - if (null !== $objectGroup) { - $piggyBank->objectGroups()->sync([$objectGroup->id]); - $piggyBank->save(); - } + $this->user->piggyBanks()->where('piggy_banks.order', '>=', $newOrder)->where('piggy_banks.order', '<', $oldOrder) + ->where('piggy_banks.id', '!=', $piggyBank->id) + ->increment('piggy_banks.order'); + $piggyBank->order = $newOrder; + Log::debug(sprintf('Order of piggy #%d ("%s") is now %d', $piggyBank->id, $piggyBank->name, $newOrder)); + $piggyBank->save(); - return $piggyBank; - } - } - - return $piggyBank; + return true; } /** @@ -442,6 +380,73 @@ trait ModifiesPiggyBanks return true; } + /** + * @param PiggyBank $piggyBank + * @param array $data + * + * @return PiggyBank + */ + public function update(PiggyBank $piggyBank, array $data): PiggyBank + { + $piggyBank = $this->updateProperties($piggyBank, $data); + if (array_key_exists('notes', $data)) { + $this->updateNote($piggyBank, (string) $data['notes']); + } + + // update the order of the piggy bank: + $oldOrder = (int) $piggyBank->order; + $newOrder = (int) ($data['order'] ?? $oldOrder); + if ($oldOrder !== $newOrder) { + $this->setOrder($piggyBank, $newOrder); + } + + // if the piggy bank is now smaller than the current relevant rep, + // remove money from the rep. + $repetition = $this->getRepetition($piggyBank); + if (null !== $repetition && $repetition->currentamount > $piggyBank->targetamount) { + $diff = bcsub($piggyBank->targetamount, $repetition->currentamount); + $this->createEvent($piggyBank, $diff); + + $repetition->currentamount = $piggyBank->targetamount; + $repetition->save(); + } + + // update using name: + if (array_key_exists('object_group_title', $data)) { + $objectGroupTitle = (string) $data['object_group_title']; + if ('' !== $objectGroupTitle) { + $objectGroup = $this->findOrCreateObjectGroup($objectGroupTitle); + if (null !== $objectGroup) { + $piggyBank->objectGroups()->sync([$objectGroup->id]); + $piggyBank->save(); + } + + return $piggyBank; + } + // remove if name is empty. Should be overruled by ID. + if ('' === $objectGroupTitle) { + $piggyBank->objectGroups()->sync([]); + $piggyBank->save(); + } + } + + // try also with ID: + if (array_key_exists('object_group_id', $data)) { + $objectGroupId = (int) ($data['object_group_id'] ?? 0); + if (0 !== $objectGroupId) { + $objectGroup = $this->findObjectGroupById($objectGroupId); + if (null !== $objectGroup) { + $piggyBank->objectGroups()->sync([$objectGroup->id]); + $piggyBank->save(); + } + + return $piggyBank; + } + } + + return $piggyBank; + } + /** * @param PiggyBank $piggyBank * @param array $data @@ -454,7 +459,7 @@ trait ModifiesPiggyBanks $piggyBank->name = $data['name']; } if (array_key_exists('account_id', $data) && 0 !== $data['account_id']) { - $piggyBank->account_id = (int)$data['account_id']; + $piggyBank->account_id = (int) $data['account_id']; } if (array_key_exists('targetamount', $data) && '' !== $data['targetamount']) { $piggyBank->targetamount = $data['targetamount']; diff --git a/app/Repositories/PiggyBank/PiggyBankRepository.php b/app/Repositories/PiggyBank/PiggyBankRepository.php index 62acee3803..452f0b6f0a 100644 --- a/app/Repositories/PiggyBank/PiggyBankRepository.php +++ b/app/Repositories/PiggyBank/PiggyBankRepository.php @@ -54,6 +54,37 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface $this->user->piggyBanks()->delete(); } + /** + * @param int|null $piggyBankId + * @param string|null $piggyBankName + * + * @return PiggyBank|null + */ + public function findPiggyBank(?int $piggyBankId, ?string $piggyBankName): ?PiggyBank + { + Log::debug('Searching for piggy information.'); + + if (null !== $piggyBankId) { + $searchResult = $this->find((int) $piggyBankId); + if (null !== $searchResult) { + Log::debug(sprintf('Found piggy based on #%d, will return it.', $piggyBankId)); + + return $searchResult; + } + } + if (null !== $piggyBankName) { + $searchResult = $this->findByName((string) $piggyBankName); + if (null !== $searchResult) { + Log::debug(sprintf('Found piggy based on "%s", will return it.', $piggyBankName)); + + return $searchResult; + } + } + Log::debug('Found nothing'); + + return null; + } + /** * @param int $piggyBankId * @@ -76,37 +107,6 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface return $this->user->piggyBanks()->where('piggy_banks.name', $name)->first(['piggy_banks.*']); } - /** - * @param int|null $piggyBankId - * @param string|null $piggyBankName - * - * @return PiggyBank|null - */ - public function findPiggyBank(?int $piggyBankId, ?string $piggyBankName): ?PiggyBank - { - Log::debug('Searching for piggy information.'); - - if (null !== $piggyBankId) { - $searchResult = $this->find((int)$piggyBankId); - if (null !== $searchResult) { - Log::debug(sprintf('Found piggy based on #%d, will return it.', $piggyBankId)); - - return $searchResult; - } - } - if (null !== $piggyBankName) { - $searchResult = $this->findByName((string)$piggyBankName); - if (null !== $searchResult) { - Log::debug(sprintf('Found piggy based on "%s", will return it.', $piggyBankName)); - - return $searchResult; - } - } - Log::debug('Found nothing'); - - return null; - } - /** * @inheritDoc */ @@ -142,7 +142,17 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface return '0'; } - return (string)$rep->currentamount; + return (string) $rep->currentamount; + } + + /** + * @param PiggyBank $piggyBank + * + * @return PiggyBankRepetition|null + */ + public function getRepetition(PiggyBank $piggyBank): ?PiggyBankRepetition + { + return $piggyBank->piggyBankRepetitions()->first(); } /** @@ -163,7 +173,8 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface * @param TransactionJournal $journal * * @return string - * + * @throws \FireflyIII\Exceptions\FireflyException + * @throws \JsonException */ public function getExactAmount(PiggyBank $piggyBank, PiggyBankRepetition $repetition, TransactionJournal $journal): string { @@ -210,11 +221,11 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface // currency of the account + the piggy bank currency are almost the same. // which amount from the transaction matches? $amount = null; - if ((int)$source->transaction_currency_id === (int)$currency->id) { + if ((int) $source->transaction_currency_id === (int) $currency->id) { Log::debug('Use normal amount'); $amount = app('steam')->$operator($source->amount); } - if ((int)$source->foreign_currency_id === (int)$currency->id) { + if ((int) $source->foreign_currency_id === (int) $currency->id) { Log::debug('Use foreign amount'); $amount = app('steam')->$operator($source->foreign_amount); } @@ -225,7 +236,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface } Log::debug(sprintf('The currency is %s and the amount is %s', $currency->code, $amount)); - $room = bcsub((string)$piggyBank->targetamount, (string)$repetition->currentamount); + $room = bcsub((string) $piggyBank->targetamount, (string) $repetition->currentamount); $compare = bcmul($repetition->currentamount, '-1'); Log::debug(sprintf('Will add/remove %f to piggy bank #%d ("%s")', $amount, $piggyBank->id, $piggyBank->name)); @@ -248,7 +259,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface return $compare; } - return (string)$amount; + return (string) $amount; } /** @@ -256,7 +267,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface */ public function getMaxOrder(): int { - return (int)$this->user->piggyBanks()->max('piggy_banks.order'); + return (int) $this->user->piggyBanks()->max('piggy_banks.order'); } /** @@ -277,14 +288,6 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface return $note->text; } - /** - * @return Collection - */ - public function getPiggyBanks(): Collection - { - return $this->user->piggyBanks()->with(['account', 'objectGroups'])->orderBy('order', 'ASC')->get(); - } - /** * Also add amount in name. * @@ -307,13 +310,11 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface } /** - * @param PiggyBank $piggyBank - * - * @return PiggyBankRepetition|null + * @return Collection */ - public function getRepetition(PiggyBank $piggyBank): ?PiggyBankRepetition + public function getPiggyBanks(): Collection { - return $piggyBank->piggyBankRepetitions()->first(); + return $this->user->piggyBanks()->with(['account', 'objectGroups'])->orderBy('order', 'ASC')->get(); } /** @@ -338,7 +339,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface // more than 1 month to go and still need money to save: if ($diffInMonths > 0 && 1 === bccomp($remainingAmount, '0')) { - $savePerMonth = bcdiv($remainingAmount, (string)$diffInMonths); + $savePerMonth = bcdiv($remainingAmount, (string) $diffInMonths); } // less than 1 month to go but still need money to save: @@ -357,6 +358,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface * @param Carbon $date * * @return string + * @throws \JsonException */ public function leftOnAccount(PiggyBank $piggyBank, Carbon $date): string { diff --git a/app/Repositories/Recurring/RecurringRepository.php b/app/Repositories/Recurring/RecurringRepository.php index 8e2216d3c4..e1ba67d01d 100644 --- a/app/Repositories/Recurring/RecurringRepository.php +++ b/app/Repositories/Recurring/RecurringRepository.php @@ -107,6 +107,22 @@ class RecurringRepository implements RecurringRepositoryInterface ->get(); } + /** + * @inheritDoc + */ + public function getBillId(RecurrenceTransaction $recTransaction): ?int + { + $return = null; + /** @var RecurrenceTransactionMeta $meta */ + foreach ($recTransaction->recurrenceTransactionMeta as $meta) { + if ('bill_id' === $meta->name) { + $return = (int) $meta->value; + } + } + + return $return; + } + /** * Get the budget ID from a recurring transaction transaction. * @@ -120,7 +136,7 @@ class RecurringRepository implements RecurringRepositoryInterface /** @var RecurrenceTransactionMeta $meta */ foreach ($recTransaction->recurrenceTransactionMeta as $meta) { if ('budget_id' === $meta->name) { - $return = (int)$meta->value; + $return = (int) $meta->value; } } @@ -140,7 +156,7 @@ class RecurringRepository implements RecurringRepositoryInterface /** @var RecurrenceTransactionMeta $meta */ foreach ($recTransaction->recurrenceTransactionMeta as $meta) { if ('category_id' === $meta->name) { - $return = (int)$meta->value; + $return = (int) $meta->value; } } @@ -160,7 +176,7 @@ class RecurringRepository implements RecurringRepositoryInterface /** @var RecurrenceTransactionMeta $meta */ foreach ($recTransaction->recurrenceTransactionMeta as $meta) { if ('category_name' === $meta->name) { - $return = (string)$meta->value; + $return = (string) $meta->value; } } @@ -206,7 +222,7 @@ class RecurringRepository implements RecurringRepositoryInterface return TransactionJournalMeta::leftJoin('transaction_journals', 'transaction_journals.id', '=', 'journal_meta.transaction_journal_id') ->where('transaction_journals.user_id', $this->user->id) ->where('journal_meta.name', '=', 'recurrence_id') - ->where('journal_meta.data', '=', json_encode((string)$recurrence->id)) + ->where('journal_meta.data', '=', json_encode((string) $recurrence->id)) ->get(['journal_meta.transaction_journal_id'])->pluck('transaction_journal_id')->toArray(); } @@ -222,51 +238,12 @@ class RecurringRepository implements RecurringRepositoryInterface /** @var Note $note */ $note = $recurrence->notes()->first(); if (null !== $note) { - return (string)$note->text; + return (string) $note->text; } return ''; } - /** - * Generate events in the date range. - * - * @param RecurrenceRepetition $repetition - * @param Carbon $start - * @param Carbon $end - * - * @return array - * - */ - public function getOccurrencesInRange(RecurrenceRepetition $repetition, Carbon $start, Carbon $end): array - { - $occurrences = []; - $mutator = clone $start; - $mutator->startOfDay(); - $skipMod = $repetition->repetition_skip + 1; - Log::debug(sprintf('Calculating occurrences for rep type "%s"', $repetition->repetition_type)); - Log::debug(sprintf('Mutator is now: %s', $mutator->format('Y-m-d'))); - - if ('daily' === $repetition->repetition_type) { - $occurrences = $this->getDailyInRange($mutator, $end, $skipMod); - } - if ('weekly' === $repetition->repetition_type) { - $occurrences = $this->getWeeklyInRange($mutator, $end, $skipMod, $repetition->repetition_moment); - } - if ('monthly' === $repetition->repetition_type) { - $occurrences = $this->getMonthlyInRange($mutator, $end, $skipMod, $repetition->repetition_moment); - } - if ('ndom' === $repetition->repetition_type) { - $occurrences = $this->getNdomInRange($mutator, $end, $skipMod, $repetition->repetition_moment); - } - if ('yearly' === $repetition->repetition_type) { - $occurrences = $this->getYearlyInRange($mutator, $end, $skipMod, $repetition->repetition_moment); - } - - // filter out all the weekend days: - return $this->filterWeekends($repetition, $occurrences); - } - /** * @param RecurrenceTransaction $transaction * @@ -278,7 +255,7 @@ class RecurringRepository implements RecurringRepositoryInterface /** @var RecurrenceTransactionMeta $metaEntry */ foreach ($meta as $metaEntry) { if ('piggy_bank_id' === $metaEntry->name) { - return (int)$metaEntry->value; + return (int) $metaEntry->value; } } @@ -320,11 +297,11 @@ class RecurringRepository implements RecurringRepositoryInterface ->whereNull('transaction_journals.deleted_at') ->where('transaction_journals.user_id', $this->user->id) ->where('name', 'recurrence_id') - ->where('data', json_encode((string)$recurrence->id)) + ->where('data', json_encode((string) $recurrence->id)) ->get()->pluck('transaction_journal_id')->toArray(); $search = []; foreach ($journalMeta as $journalId) { - $search[] = (int)$journalId; + $search[] = (int) $journalId; } /** @var GroupCollectorInterface $collector */ $collector = app(GroupCollectorInterface::class); @@ -349,12 +326,12 @@ class RecurringRepository implements RecurringRepositoryInterface ->whereNull('transaction_journals.deleted_at') ->where('transaction_journals.user_id', $this->user->id) ->where('name', 'recurrence_id') - ->where('data', json_encode((string)$recurrence->id)) + ->where('data', json_encode((string) $recurrence->id)) ->get()->pluck('transaction_journal_id')->toArray(); $search = []; foreach ($journalMeta as $journalId) { - $search[] = (int)$journalId; + $search[] = (int) $journalId; } if (empty($search)) { @@ -449,6 +426,27 @@ class RecurringRepository implements RecurringRepositoryInterface return $this->filterMaxDate($repeatUntil, $occurrences); } + /** + * @param Carbon|null $max + * @param array $occurrences + * + * @return array + */ + private function filterMaxDate(?Carbon $max, array $occurrences): array + { + if (null === $max) { + return $occurrences; + } + $filtered = []; + foreach ($occurrences as $date) { + if ($date->lte($max)) { + $filtered[] = $date; + } + } + + return $filtered; + } + /** * Parse the repetition in a string that is user readable. * @@ -464,25 +462,25 @@ class RecurringRepository implements RecurringRepositoryInterface $pref = app('preferences')->getForUser($this->user, 'language', config('firefly.default_language', 'en_US')); $language = $pref->data; if ('daily' === $repetition->repetition_type) { - return (string)trans('firefly.recurring_daily', [], $language); + return (string) trans('firefly.recurring_daily', [], $language); } if ('weekly' === $repetition->repetition_type) { $dayOfWeek = trans(sprintf('config.dow_%s', $repetition->repetition_moment), [], $language); if ($repetition->repetition_skip > 0) { - return (string)trans('firefly.recurring_weekly_skip', ['weekday' => $dayOfWeek, 'skip' => $repetition->repetition_skip + 1], $language); + return (string) trans('firefly.recurring_weekly_skip', ['weekday' => $dayOfWeek, 'skip' => $repetition->repetition_skip + 1], $language); } - return (string)trans('firefly.recurring_weekly', ['weekday' => $dayOfWeek], $language); + return (string) trans('firefly.recurring_weekly', ['weekday' => $dayOfWeek], $language); } if ('monthly' === $repetition->repetition_type) { if ($repetition->repetition_skip > 0) { - return (string)trans( + return (string) trans( 'firefly.recurring_monthly_skip', ['dayOfMonth' => $repetition->repetition_moment, 'skip' => $repetition->repetition_skip + 1], $language ); } - return (string)trans( + return (string) trans( 'firefly.recurring_monthly', ['dayOfMonth' => $repetition->repetition_moment, 'skip' => $repetition->repetition_skip - 1], $language ); } @@ -491,7 +489,7 @@ class RecurringRepository implements RecurringRepositoryInterface // first part is number of week, second is weekday. $dayOfWeek = trans(sprintf('config.dow_%s', $parts[1]), [], $language); - return (string)trans('firefly.recurring_ndom', ['weekday' => $dayOfWeek, 'dayOfMonth' => $parts[0]], $language); + return (string) trans('firefly.recurring_ndom', ['weekday' => $dayOfWeek, 'dayOfMonth' => $parts[0]], $language); } if ('yearly' === $repetition->repetition_type) { // @@ -499,9 +497,9 @@ class RecurringRepository implements RecurringRepositoryInterface $repDate = Carbon::createFromFormat('Y-m-d', $repetition->repetition_moment); $diffInYears = $today->diffInYears($repDate); $repDate->addYears($diffInYears); // technically not necessary. - $string = $repDate->formatLocalized((string)trans('config.month_and_day_no_year')); + $string = $repDate->isoFormat((string) trans('config.month_and_day_no_year_js')); - return (string)trans('firefly.recurring_yearly', ['date' => $string], $language); + return (string) trans('firefly.recurring_yearly', ['date' => $string], $language); } return ''; @@ -558,16 +556,16 @@ class RecurringRepository implements RecurringRepositoryInterface public function totalTransactions(Recurrence $recurrence, RecurrenceRepetition $repetition): int { // if repeat = null just return 0. - if (null === $recurrence->repeat_until && 0 === (int)$recurrence->repetitions) { + if (null === $recurrence->repeat_until && 0 === (int) $recurrence->repetitions) { return 0; } // expect X transactions then stop. Return that number - if (null === $recurrence->repeat_until && 0 !== (int)$recurrence->repetitions) { - return (int)$recurrence->repetitions; + if (null === $recurrence->repeat_until && 0 !== (int) $recurrence->repetitions) { + return (int) $recurrence->repetitions; } // need to calculate, this depends on the repetition: - if (null !== $recurrence->repeat_until && 0 === (int)$recurrence->repetitions) { + if (null !== $recurrence->repeat_until && 0 === (int) $recurrence->repetitions) { $occurrences = $this->getOccurrencesInRange($repetition, $recurrence->first_date ?? today(), $recurrence->repeat_until); return count($occurrences); @@ -576,6 +574,45 @@ class RecurringRepository implements RecurringRepositoryInterface return 0; } + /** + * Generate events in the date range. + * + * @param RecurrenceRepetition $repetition + * @param Carbon $start + * @param Carbon $end + * + * @return array + * + */ + public function getOccurrencesInRange(RecurrenceRepetition $repetition, Carbon $start, Carbon $end): array + { + $occurrences = []; + $mutator = clone $start; + $mutator->startOfDay(); + $skipMod = $repetition->repetition_skip + 1; + Log::debug(sprintf('Calculating occurrences for rep type "%s"', $repetition->repetition_type)); + Log::debug(sprintf('Mutator is now: %s', $mutator->format('Y-m-d'))); + + if ('daily' === $repetition->repetition_type) { + $occurrences = $this->getDailyInRange($mutator, $end, $skipMod); + } + if ('weekly' === $repetition->repetition_type) { + $occurrences = $this->getWeeklyInRange($mutator, $end, $skipMod, $repetition->repetition_moment); + } + if ('monthly' === $repetition->repetition_type) { + $occurrences = $this->getMonthlyInRange($mutator, $end, $skipMod, $repetition->repetition_moment); + } + if ('ndom' === $repetition->repetition_type) { + $occurrences = $this->getNdomInRange($mutator, $end, $skipMod, $repetition->repetition_moment); + } + if ('yearly' === $repetition->repetition_type) { + $occurrences = $this->getYearlyInRange($mutator, $end, $skipMod, $repetition->repetition_moment); + } + + // filter out all the weekend days: + return $this->filterWeekends($repetition, $occurrences); + } + /** * Update a recurring transaction. * @@ -592,41 +629,4 @@ class RecurringRepository implements RecurringRepositoryInterface return $service->update($recurrence, $data); } - - /** - * @param Carbon|null $max - * @param array $occurrences - * - * @return array - */ - private function filterMaxDate(?Carbon $max, array $occurrences): array - { - if (null === $max) { - return $occurrences; - } - $filtered = []; - foreach ($occurrences as $date) { - if ($date->lte($max)) { - $filtered[] = $date; - } - } - - return $filtered; - } - - /** - * @inheritDoc - */ - public function getBillId(RecurrenceTransaction $recTransaction): ?int - { - $return = null; - /** @var RecurrenceTransactionMeta $meta */ - foreach ($recTransaction->recurrenceTransactionMeta as $meta) { - if ('bill_id' === $meta->name) { - $return = (int)$meta->value; - } - } - - return $return; - } } diff --git a/app/Repositories/Recurring/RecurringRepositoryInterface.php b/app/Repositories/Recurring/RecurringRepositoryInterface.php index 037791c4a6..08ceab085a 100644 --- a/app/Repositories/Recurring/RecurringRepositoryInterface.php +++ b/app/Repositories/Recurring/RecurringRepositoryInterface.php @@ -64,6 +64,15 @@ interface RecurringRepositoryInterface */ public function getAll(): Collection; + /** + * Get the category from a recurring transaction transaction. + * + * @param RecurrenceTransaction $recTransaction + * + * @return null|int + */ + public function getBillId(RecurrenceTransaction $recTransaction): ?int; + /** * Get the budget ID from a recurring transaction transaction. * @@ -82,15 +91,6 @@ interface RecurringRepositoryInterface */ public function getCategoryId(RecurrenceTransaction $recTransaction): ?int; - /** - * Get the category from a recurring transaction transaction. - * - * @param RecurrenceTransaction $recTransaction - * - * @return null|int - */ - public function getBillId(RecurrenceTransaction $recTransaction): ?int; - /** * Get the category from a recurring transaction transaction. * diff --git a/app/Repositories/Rule/RuleRepository.php b/app/Repositories/Rule/RuleRepository.php index 1c869ca6f4..7305677f64 100644 --- a/app/Repositories/Rule/RuleRepository.php +++ b/app/Repositories/Rule/RuleRepository.php @@ -76,7 +76,7 @@ class RuleRepository implements RuleRepositoryInterface public function duplicate(Rule $rule): Rule { $newRule = $rule->replicate(); - $newRule->title = (string)trans('firefly.rule_copy_of', ['title' => $rule->title]); + $newRule->title = (string) trans('firefly.rule_copy_of', ['title' => $rule->title]); $newRule->save(); // replicate all triggers @@ -135,7 +135,7 @@ class RuleRepository implements RuleRepositoryInterface */ public function getHighestOrderInRuleGroup(RuleGroup $ruleGroup): int { - return (int)$ruleGroup->rules()->max('order'); + return (int) $ruleGroup->rules()->max('order'); } /** @@ -186,7 +186,7 @@ class RuleRepository implements RuleRepositoryInterface if ('user_action' === $trigger->trigger_type) { continue; } - $needsContext = config(sprintf('firefly.search.operators.%s.needs_context', $trigger->trigger_type)) ?? true; + $needsContext = config(sprintf('search.operators.%s.needs_context', $trigger->trigger_type)) ?? true; if (false === $needsContext) { $params[] = sprintf('%s:true', OperatorQuerySearch::getRootOperator($trigger->trigger_type)); } @@ -253,43 +253,6 @@ class RuleRepository implements RuleRepositoryInterface return $filtered; } - /** - * @inheritDoc - */ - public function maxOrder(RuleGroup $ruleGroup): int - { - return (int)$ruleGroup->rules()->max('order'); - } - - /** - * @inheritDoc - */ - public function moveRule(Rule $rule, RuleGroup $ruleGroup, int $order): Rule - { - if ($rule->rule_group_id !== $ruleGroup->id) { - $rule->rule_group_id = $ruleGroup->id; - } - $rule->save(); - $rule->refresh(); - $this->setOrder($rule, $order); - - return $rule; - } - - /** - * @param RuleGroup $ruleGroup - * - * @return bool - */ - public function resetRuleOrder(RuleGroup $ruleGroup): bool - { - $groupRepository = app(RuleGroupRepositoryInterface::class); - $groupRepository->setUser($ruleGroup->user); - $groupRepository->resetRuleOrder($ruleGroup); - - return true; - } - /** * @inheritDoc */ @@ -305,42 +268,6 @@ class RuleRepository implements RuleRepositoryInterface return $search->take($limit)->get(['id', 'title', 'description']); } - /** - * @inheritDoc - */ - public function setOrder(Rule $rule, int $newOrder): void - { - $oldOrder = (int)$rule->order; - $groupId = (int)$rule->rule_group_id; - $maxOrder = $this->maxOrder($rule->ruleGroup); - $newOrder = $newOrder > $maxOrder ? $maxOrder + 1 : $newOrder; - Log::debug(sprintf('New order will be %d', $newOrder)); - - if ($newOrder > $oldOrder) { - $this->user->rules() - ->where('rules.rule_group_id', $groupId) - ->where('rules.order', '<=', $newOrder) - ->where('rules.order', '>', $oldOrder) - ->where('rules.id', '!=', $rule->id) - ->decrement('rules.order'); - $rule->order = $newOrder; - Log::debug(sprintf('Order of rule #%d ("%s") is now %d', $rule->id, $rule->title, $newOrder)); - $rule->save(); - - return; - } - - $this->user->rules() - ->where('rules.rule_group_id', $groupId) - ->where('rules.order', '>=', $newOrder) - ->where('rules.order', '<', $oldOrder) - ->where('rules.id', '!=', $rule->id) - ->increment('rules.order'); - $rule->order = $newOrder; - Log::debug(sprintf('Order of rule #%d ("%s") is now %d', $rule->id, $rule->title, $newOrder)); - $rule->save(); - } - /** * @param User $user */ @@ -404,23 +331,112 @@ class RuleRepository implements RuleRepositoryInterface } /** - * @param Rule $rule - * @param array $values - * - * @return RuleAction + * @param string $moment + * @param Rule $rule */ - public function storeAction(Rule $rule, array $values): RuleAction + private function setRuleTrigger(string $moment, Rule $rule): void { - $ruleAction = new RuleAction; - $ruleAction->rule()->associate($rule); - $ruleAction->order = $values['order']; - $ruleAction->active = $values['active']; - $ruleAction->stop_processing = $values['stop_processing']; - $ruleAction->action_type = $values['action']; - $ruleAction->action_value = $values['value'] ?? ''; - $ruleAction->save(); + /** @var RuleTrigger|null $trigger */ + $trigger = $rule->ruleTriggers()->where('trigger_type', 'user_action')->first(); + if (null !== $trigger) { + $trigger->trigger_value = $moment; + $trigger->save(); + + return; + } + $trigger = new RuleTrigger; + $trigger->order = 0; + $trigger->trigger_type = 'user_action'; + $trigger->trigger_value = $moment; + $trigger->rule_id = $rule->id; + $trigger->active = true; + $trigger->stop_processing = false; + $trigger->save(); + } + + /** + * @param RuleGroup $ruleGroup + * + * @return bool + */ + public function resetRuleOrder(RuleGroup $ruleGroup): bool + { + $groupRepository = app(RuleGroupRepositoryInterface::class); + $groupRepository->setUser($ruleGroup->user); + $groupRepository->resetRuleOrder($ruleGroup); + + return true; + } + + /** + * @inheritDoc + */ + public function setOrder(Rule $rule, int $newOrder): void + { + $oldOrder = (int) $rule->order; + $groupId = (int) $rule->rule_group_id; + $maxOrder = $this->maxOrder($rule->ruleGroup); + $newOrder = $newOrder > $maxOrder ? $maxOrder + 1 : $newOrder; + Log::debug(sprintf('New order will be %d', $newOrder)); + + if ($newOrder > $oldOrder) { + $this->user->rules() + ->where('rules.rule_group_id', $groupId) + ->where('rules.order', '<=', $newOrder) + ->where('rules.order', '>', $oldOrder) + ->where('rules.id', '!=', $rule->id) + ->decrement('rules.order'); + $rule->order = $newOrder; + Log::debug(sprintf('Order of rule #%d ("%s") is now %d', $rule->id, $rule->title, $newOrder)); + $rule->save(); + + return; + } + + $this->user->rules() + ->where('rules.rule_group_id', $groupId) + ->where('rules.order', '>=', $newOrder) + ->where('rules.order', '<', $oldOrder) + ->where('rules.id', '!=', $rule->id) + ->increment('rules.order'); + $rule->order = $newOrder; + Log::debug(sprintf('Order of rule #%d ("%s") is now %d', $rule->id, $rule->title, $newOrder)); + $rule->save(); + } + + /** + * @inheritDoc + */ + public function maxOrder(RuleGroup $ruleGroup): int + { + return (int) $ruleGroup->rules()->max('order'); + } + + /** + * @param Rule $rule + * @param array $data + * + * @return void + */ + private function storeTriggers(Rule $rule, array $data): void + { + $order = 1; + foreach ($data['triggers'] as $trigger) { + $value = $trigger['value'] ?? ''; + $stopProcessing = $trigger['stop_processing'] ?? false; + $active = $trigger['active'] ?? true; + + $triggerValues = [ + 'action' => $trigger['type'], + 'value' => $value, + 'stop_processing' => $stopProcessing, + 'order' => $order, + 'active' => $active, + ]; + $this->storeTrigger($rule, $triggerValues); + ++$order; + } - return $ruleAction; } /** @@ -443,6 +459,52 @@ class RuleRepository implements RuleRepositoryInterface return $ruleTrigger; } + /** + * @param Rule $rule + * @param array $data + * + * @return void + */ + private function storeActions(Rule $rule, array $data): void + { + $order = 1; + foreach ($data['actions'] as $action) { + $value = $action['value'] ?? ''; + $stopProcessing = $action['stop_processing'] ?? false; + $active = $action['active'] ?? true; + $actionValues = [ + 'action' => $action['type'], + 'value' => $value, + 'stop_processing' => $stopProcessing, + 'order' => $order, + 'active' => $active, + ]; + $this->storeAction($rule, $actionValues); + ++$order; + } + + } + + /** + * @param Rule $rule + * @param array $values + * + * @return RuleAction + */ + public function storeAction(Rule $rule, array $values): RuleAction + { + $ruleAction = new RuleAction; + $ruleAction->rule()->associate($rule); + $ruleAction->order = $values['order']; + $ruleAction->active = $values['active']; + $ruleAction->stop_processing = $values['stop_processing']; + $ruleAction->action_type = $values['action']; + $ruleAction->action_value = $values['value'] ?? ''; + $ruleAction->save(); + + return $ruleAction; + } + /** * @param Rule $rule * @param array $data @@ -471,7 +533,7 @@ class RuleRepository implements RuleRepositoryInterface // update the order: $this->resetRuleOrder($group); if (array_key_exists('order', $data)) { - $this->moveRule($rule, $group, (int)$data['order']); + $this->moveRule($rule, $group, (int) $data['order']); } @@ -502,81 +564,17 @@ class RuleRepository implements RuleRepositoryInterface } /** - * @param string $moment - * @param Rule $rule + * @inheritDoc */ - private function setRuleTrigger(string $moment, Rule $rule): void + public function moveRule(Rule $rule, RuleGroup $ruleGroup, int $order): Rule { - /** @var RuleTrigger|null $trigger */ - $trigger = $rule->ruleTriggers()->where('trigger_type', 'user_action')->first(); - if (null !== $trigger) { - $trigger->trigger_value = $moment; - $trigger->save(); - - return; + if ($rule->rule_group_id !== $ruleGroup->id) { + $rule->rule_group_id = $ruleGroup->id; } - $trigger = new RuleTrigger; - $trigger->order = 0; - $trigger->trigger_type = 'user_action'; - $trigger->trigger_value = $moment; - $trigger->rule_id = $rule->id; - $trigger->active = true; - $trigger->stop_processing = false; - $trigger->save(); - } + $rule->save(); + $rule->refresh(); + $this->setOrder($rule, $order); - /** - * @param Rule $rule - * @param array $data - * - * @return bool - */ - private function storeTriggers(Rule $rule, array $data): bool - { - $order = 1; - foreach ($data['triggers'] as $trigger) { - $value = $trigger['value'] ?? ''; - $stopProcessing = $trigger['stop_processing'] ?? false; - $active = $trigger['active'] ?? true; - - $triggerValues = [ - 'action' => $trigger['type'], - 'value' => $value, - 'stop_processing' => $stopProcessing, - 'order' => $order, - 'active' => $active, - ]; - $this->storeTrigger($rule, $triggerValues); - ++$order; - } - - return true; - } - - /** - * @param Rule $rule - * @param array $data - * - * @return bool - */ - private function storeActions(Rule $rule, array $data): bool - { - $order = 1; - foreach ($data['actions'] as $action) { - $value = $action['value'] ?? ''; - $stopProcessing = $action['stop_processing'] ?? false; - $active = $action['active'] ?? true; - $actionValues = [ - 'action' => $action['type'], - 'value' => $value, - 'stop_processing' => $stopProcessing, - 'order' => $order, - 'active' => $active, - ]; - $this->storeAction($rule, $actionValues); - ++$order; - } - - return true; + return $rule; } } diff --git a/app/Repositories/RuleGroup/RuleGroupRepository.php b/app/Repositories/RuleGroup/RuleGroupRepository.php index 9bdb1f4d33..2c0b109b13 100644 --- a/app/Repositories/RuleGroup/RuleGroupRepository.php +++ b/app/Repositories/RuleGroup/RuleGroupRepository.php @@ -99,6 +99,108 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface return true; } + /** + * @return bool + */ + public function resetOrder(): bool + { + $set = $this->user + ->ruleGroups() + ->whereNull('deleted_at') + ->orderBy('order', 'ASC') + ->orderBy('title', 'DESC') + ->get(); + $count = 1; + /** @var RuleGroup $entry */ + foreach ($set as $entry) { + if ($entry->order !== $count) { + $entry->order = $count; + $entry->save(); + } + + // also update rules in group. + $this->resetRuleOrder($entry); + + ++$count; + } + + return true; + } + + /** + * @param RuleGroup $ruleGroup + * + * @return bool + */ + public function resetRuleOrder(RuleGroup $ruleGroup): bool + { + $set = $ruleGroup->rules() + ->orderBy('order', 'ASC') + ->orderBy('title', 'DESC') + ->orderBy('updated_at', 'DESC') + ->get(['rules.*']); + $count = 1; + /** @var Rule $entry */ + foreach ($set as $entry) { + if ((int) $entry->order !== $count) { + Log::debug(sprintf('Rule #%d was on spot %d but must be on spot %d', $entry->id, $entry->order, $count)); + $entry->order = $count; + $entry->save(); + } + $this->resetRuleActionOrder($entry); + $this->resetRuleTriggerOrder($entry); + + ++$count; + } + + return true; + } + + /** + * @param Rule $rule + */ + private function resetRuleActionOrder(Rule $rule): void + { + $actions = $rule->ruleActions() + ->orderBy('order', 'ASC') + ->orderBy('active', 'DESC') + ->orderBy('action_type', 'ASC') + ->get(); + $index = 1; + /** @var RuleAction $action */ + foreach ($actions as $action) { + if ((int) $action->order !== $index) { + $action->order = $index; + $action->save(); + Log::debug(sprintf('Rule action #%d was on spot %d but must be on spot %d', $action->id, $action->order, $index)); + } + $index++; + } + } + + /** + * @param Rule $rule + */ + private function resetRuleTriggerOrder(Rule $rule): void + { + $triggers = $rule->ruleTriggers() + ->orderBy('order', 'ASC') + ->orderBy('active', 'DESC') + ->orderBy('trigger_type', 'ASC') + ->get(); + $index = 1; + /** @var RuleTrigger $trigger */ + foreach ($triggers as $trigger) { + $order = (int) $trigger->order; + if ($order !== $index) { + $trigger->order = $index; + $trigger->save(); + Log::debug(sprintf('Rule trigger #%d was on spot %d but must be on spot %d', $trigger->id, $order, $index)); + } + $index++; + } + } + /** * @inheritDoc */ @@ -112,6 +214,14 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface } } + /** + * @return Collection + */ + public function get(): Collection + { + return $this->user->ruleGroups()->orderBy('order', 'ASC')->get(); + } + /** * @param int $ruleGroupId * @@ -132,14 +242,6 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface return $this->user->ruleGroups()->where('title', $title)->first(); } - /** - * @return Collection - */ - public function get(): Collection - { - return $this->user->ruleGroups()->orderBy('order', 'ASC')->get(); - } - /** * @return Collection */ @@ -249,7 +351,7 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface { $entry = $this->user->ruleGroups()->max('order'); - return (int)$entry; + return (int) $entry; } /** @@ -321,64 +423,7 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface */ public function maxOrder(): int { - return (int)$this->user->ruleGroups()->where('active', true)->max('order'); - } - - /** - * @return bool - */ - public function resetOrder(): bool - { - $set = $this->user - ->ruleGroups() - ->whereNull('deleted_at') - ->orderBy('order', 'ASC') - ->orderBy('title', 'DESC') - ->get(); - $count = 1; - /** @var RuleGroup $entry */ - foreach ($set as $entry) { - if ($entry->order !== $count) { - $entry->order = $count; - $entry->save(); - } - - // also update rules in group. - $this->resetRuleOrder($entry); - - ++$count; - } - - return true; - } - - /** - * @param RuleGroup $ruleGroup - * - * @return bool - */ - public function resetRuleOrder(RuleGroup $ruleGroup): bool - { - $set = $ruleGroup->rules() - ->orderBy('order', 'ASC') - ->orderBy('title', 'DESC') - ->orderBy('updated_at', 'DESC') - ->get(['rules.*']); - $count = 1; - /** @var Rule $entry */ - foreach ($set as $entry) { - if ((int)$entry->order !== $count) { - Log::debug(sprintf('Rule #%d was on spot %d but must be on spot %d', $entry->id, $entry->order, $count)); - $entry->order = $count; - $entry->save(); - } - $this->resetRuleActionOrder($entry); - $this->resetRuleTriggerOrder($entry); - - ++$count; - } - - return true; + return (int) $this->user->ruleGroups()->where('active', true)->max('order'); } /** @@ -396,32 +441,6 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface return $search->take($limit)->get(['id', 'title', 'description']); } - /** - * @inheritDoc - */ - public function setOrder(RuleGroup $ruleGroup, int $newOrder): void - { - $oldOrder = (int)$ruleGroup->order; - - if ($newOrder > $oldOrder) { - $this->user->ruleGroups()->where('rule_groups.order', '<=', $newOrder)->where('rule_groups.order', '>', $oldOrder) - ->where('rule_groups.id', '!=', $ruleGroup->id) - ->decrement('order'); - $ruleGroup->order = $newOrder; - Log::debug(sprintf('Order of group #%d ("%s") is now %d', $ruleGroup->id, $ruleGroup->title, $newOrder)); - $ruleGroup->save(); - - return; - } - - $this->user->ruleGroups()->where('rule_groups.order', '>=', $newOrder)->where('rule_groups.order', '<', $oldOrder) - ->where('rule_groups.id', '!=', $ruleGroup->id) - ->increment('order'); - $ruleGroup->order = $newOrder; - Log::debug(sprintf('Order of group #%d ("%s") is now %d', $ruleGroup->id, $ruleGroup->title, $newOrder)); - $ruleGroup->save(); - } - /** * @param User $user */ @@ -455,6 +474,32 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface return $newRuleGroup; } + /** + * @inheritDoc + */ + public function setOrder(RuleGroup $ruleGroup, int $newOrder): void + { + $oldOrder = (int) $ruleGroup->order; + + if ($newOrder > $oldOrder) { + $this->user->ruleGroups()->where('rule_groups.order', '<=', $newOrder)->where('rule_groups.order', '>', $oldOrder) + ->where('rule_groups.id', '!=', $ruleGroup->id) + ->decrement('order'); + $ruleGroup->order = $newOrder; + Log::debug(sprintf('Order of group #%d ("%s") is now %d', $ruleGroup->id, $ruleGroup->title, $newOrder)); + $ruleGroup->save(); + + return; + } + + $this->user->ruleGroups()->where('rule_groups.order', '>=', $newOrder)->where('rule_groups.order', '<', $oldOrder) + ->where('rule_groups.id', '!=', $ruleGroup->id) + ->increment('order'); + $ruleGroup->order = $newOrder; + Log::debug(sprintf('Order of group #%d ("%s") is now %d', $ruleGroup->id, $ruleGroup->title, $newOrder)); + $ruleGroup->save(); + } + /** * @param RuleGroup $ruleGroup * @param array $data @@ -476,56 +521,11 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface // order if (array_key_exists('order', $data) && $ruleGroup->order !== $data['order']) { $this->resetOrder(); - $this->setOrder($ruleGroup, (int)$data['order']); + $this->setOrder($ruleGroup, (int) $data['order']); } $ruleGroup->save(); return $ruleGroup; } - - /** - * @param Rule $rule - */ - private function resetRuleActionOrder(Rule $rule): void - { - $actions = $rule->ruleActions() - ->orderBy('order', 'ASC') - ->orderBy('active', 'DESC') - ->orderBy('action_type', 'ASC') - ->get(); - $index = 1; - /** @var RuleAction $action */ - foreach ($actions as $action) { - if ((int)$action->order !== $index) { - $action->order = $index; - $action->save(); - Log::debug(sprintf('Rule action #%d was on spot %d but must be on spot %d', $action->id, $action->order, $index)); - } - $index++; - } - } - - /** - * @param Rule $rule - */ - private function resetRuleTriggerOrder(Rule $rule): void - { - $triggers = $rule->ruleTriggers() - ->orderBy('order', 'ASC') - ->orderBy('active', 'DESC') - ->orderBy('trigger_type', 'ASC') - ->get(); - $index = 1; - /** @var RuleTrigger $trigger */ - foreach ($triggers as $trigger) { - $order = (int)$trigger->order; - if ($order !== $index) { - $trigger->order = $index; - $trigger->save(); - Log::debug(sprintf('Rule trigger #%d was on spot %d but must be on spot %d', $trigger->id, $order, $index)); - } - $index++; - } - } } diff --git a/app/Repositories/Tag/OperationsRepository.php b/app/Repositories/Tag/OperationsRepository.php index 10f15b7f7f..7b923bbc06 100644 --- a/app/Repositories/Tag/OperationsRepository.php +++ b/app/Repositories/Tag/OperationsRepository.php @@ -70,7 +70,7 @@ class OperationsRepository implements OperationsRepositoryInterface $array = []; $listedJournals = []; foreach ($journals as $journal) { - $currencyId = (int)$journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $array[$currencyId] = $array[$currencyId] ?? [ 'tags' => [], 'currency_id' => $currencyId, @@ -82,9 +82,9 @@ class OperationsRepository implements OperationsRepositoryInterface // may have multiple tags: foreach ($journal['tags'] as $tag) { - $tagId = (int)$tag['id']; - $tagName = (string)$tag['name']; - $journalId = (int)$journal['transaction_journal_id']; + $tagId = (int) $tag['id']; + $tagName = (string) $tag['name']; + $journalId = (int) $journal['transaction_journal_id']; if (in_array($journalId, $listedJournals, true)) { continue; @@ -114,6 +114,18 @@ class OperationsRepository implements OperationsRepositoryInterface return $array; } + /** + * @return Collection + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface + */ + private function getTags(): Collection + { + $repository = app(TagRepositoryInterface::class); + + return $repository->get(); + } + /** * This method returns a list of all the deposit transaction journals (as arrays) set in that period * which have the specified tag(s) set to them. It's grouped per currency, with as few details in the array @@ -146,7 +158,7 @@ class OperationsRepository implements OperationsRepositoryInterface $listedJournals = []; foreach ($journals as $journal) { - $currencyId = (int)$journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $array[$currencyId] = $array[$currencyId] ?? [ 'tags' => [], 'currency_id' => $currencyId, @@ -158,9 +170,9 @@ class OperationsRepository implements OperationsRepositoryInterface // may have multiple tags: foreach ($journal['tags'] as $tag) { - $tagId = (int)$tag['id']; - $tagName = (string)$tag['name']; - $journalId = (int)$journal['transaction_journal_id']; + $tagId = (int) $tag['id']; + $tagName = (string) $tag['name']; + $journalId = (int) $journal['transaction_journal_id']; if (in_array($journalId, $listedJournals, true)) { continue; @@ -172,7 +184,7 @@ class OperationsRepository implements OperationsRepositoryInterface 'name' => $tagName, 'transaction_journals' => [], ]; - $journalId = (int)$journal['transaction_journal_id']; + $journalId = (int) $journal['transaction_journal_id']; $array[$currencyId]['tags'][$tagId]['transaction_journals'][$journalId] = [ 'amount' => app('steam')->positive($journal['amount']), 'date' => $journal['date'], @@ -229,14 +241,4 @@ class OperationsRepository implements OperationsRepositoryInterface { throw new FireflyException(sprintf('%s is not yet implemented.', __METHOD__)); } - - /** - * @return Collection - */ - private function getTags(): Collection - { - $repository = app(TagRepositoryInterface::class); - - return $repository->get(); - } } diff --git a/app/Repositories/Tag/TagRepository.php b/app/Repositories/Tag/TagRepository.php index 616932d492..aa65cb596e 100644 --- a/app/Repositories/Tag/TagRepository.php +++ b/app/Repositories/Tag/TagRepository.php @@ -81,6 +81,14 @@ class TagRepository implements TagRepositoryInterface } } + /** + * @return Collection + */ + public function get(): Collection + { + return $this->user->tags()->orderBy('tag', 'ASC')->get(); + } + /** * @param Tag $tag * @param Carbon $start @@ -134,14 +142,6 @@ class TagRepository implements TagRepositoryInterface return null; } - /** - * @return Collection - */ - public function get(): Collection - { - return $this->user->tags()->orderBy('tag', 'ASC')->get(); - } - /** * @inheritDoc */ @@ -162,14 +162,6 @@ class TagRepository implements TagRepositoryInterface ); } - /** - * @inheritDoc - */ - public function getLocation(Tag $tag): ?Location - { - return $tag->locations()->first(); - } - /** * @param int|null $year * @@ -338,7 +330,7 @@ class TagRepository implements TagRepositoryInterface /** @var array $journal */ foreach ($journals as $journal) { - $currencyId = (int)$journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $sums[$currencyId] = $sums[$currencyId] ?? [ 'currency_id' => $currencyId, 'currency_name' => $journal['currency_name'], @@ -352,7 +344,7 @@ class TagRepository implements TagRepositoryInterface ]; // add amount to correct type: - $amount = app('steam')->positive((string)$journal['amount']); + $amount = app('steam')->positive((string) $journal['amount']); $type = $journal['transaction_type_type']; if (TransactionType::WITHDRAWAL === $type) { $amount = bcmul($amount, '-1'); @@ -373,7 +365,7 @@ class TagRepository implements TagRepositoryInterface TransactionType::OPENING_BALANCE => '0', ]; // add foreign amount to correct type: - $amount = app('steam')->positive((string)$journal['foreign_amount']); + $amount = app('steam')->positive((string) $journal['foreign_amount']); $type = $journal['transaction_type_type']; if (TransactionType::WITHDRAWAL === $type) { $amount = bcmul($amount, '-1'); @@ -458,4 +450,12 @@ class TagRepository implements TagRepositoryInterface return $tag; } + /** + * @inheritDoc + */ + public function getLocation(Tag $tag): ?Location + { + return $tag->locations()->first(); + } + } diff --git a/app/Repositories/TransactionGroup/TransactionGroupRepository.php b/app/Repositories/TransactionGroup/TransactionGroupRepository.php index 5a8c8037e7..47a8dfe4b2 100644 --- a/app/Repositories/TransactionGroup/TransactionGroupRepository.php +++ b/app/Repositories/TransactionGroup/TransactionGroupRepository.php @@ -40,6 +40,7 @@ use FireflyIII\Models\TransactionGroup; use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionJournalLink; use FireflyIII\Models\TransactionType; +use FireflyIII\Repositories\Attachment\AttachmentRepositoryInterface; use FireflyIII\Services\Internal\Destroy\TransactionGroupDestroyService; use FireflyIII\Services\Internal\Update\GroupUpdateService; use FireflyIII\Support\NullArrayObject; @@ -55,6 +56,18 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface { private User $user; + /** + * @inheritDoc + */ + public function countAttachments(int $journalId): int + { + /** @var TransactionJournal $journal */ + $journal = $this->user->transactionJournals()->find($journalId); + + return $journal->attachments()->count(); + + } + /** * @param TransactionGroup $group */ @@ -79,6 +92,56 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface return $result; } + /** + * @param TransactionJournal $journal + * + * @return array + */ + private function expandJournal(TransactionJournal $journal): array + { + $array = $journal->toArray(); + $array['transactions'] = []; + $array['meta'] = $journal->transactionJournalMeta->toArray(); + $array['tags'] = $journal->tags->toArray(); + $array['categories'] = $journal->categories->toArray(); + $array['budgets'] = $journal->budgets->toArray(); + $array['notes'] = $journal->notes->toArray(); + $array['locations'] = []; + $array['attachments'] = $journal->attachments->toArray(); + $array['links'] = []; + $array['piggy_bank_events'] = $journal->piggyBankEvents->toArray(); + + /** @var Transaction $transaction */ + foreach ($journal->transactions as $transaction) { + $array['transactions'][] = $this->expandTransaction($transaction); + } + + return $array; + } + + /** + * @param Transaction $transaction + * + * @return array + */ + private function expandTransaction(Transaction $transaction): array + { + $array = $transaction->toArray(); + $array['account'] = $transaction->account->toArray(); + $array['budgets'] = []; + $array['categories'] = []; + + foreach ($transaction->categories as $category) { + $array['categories'][] = $category->toArray(); + } + + foreach ($transaction->budgets as $budget) { + $array['budgets'][] = $budget->toArray(); + } + + return $array; + } + /** * Find a transaction group by its ID. * @@ -100,6 +163,8 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface */ public function getAttachments(TransactionGroup $group): array { + $repository = app(AttachmentRepositoryInterface::class); + $repository->setUser($this->user); $journals = $group->transactionJournals->pluck('id')->toArray(); $set = Attachment::whereIn('attachable_id', $journals) ->where('attachable_type', TransactionJournal::class) @@ -109,10 +174,11 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface $result = []; /** @var Attachment $attachment */ foreach ($set as $attachment) { - $journalId = (int)$attachment->attachable_id; + $journalId = (int) $attachment->attachable_id; $result[$journalId] = $result[$journalId] ?? []; $current = $attachment->toArray(); $current['file_exists'] = true; + $current['notes'] = $repository->getNoteText($attachment); $current['journal_title'] = $attachment->attachable->description; // @phpstan-ignore-line $result[$journalId][] = $current; @@ -155,7 +221,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface 'link' => $entry->outward, 'group' => $entry->destination->transaction_group_id, 'description' => $entry->destination->description, - 'editable' => 1===$entry->editable, + 'editable' => 1 === $entry->editable, 'amount' => $amount, 'foreign_amount' => $foreignAmount, ]; @@ -168,7 +234,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface 'link' => $entry->inward, 'group' => $entry->source->transaction_group_id, 'description' => $entry->source->description, - 'editable' => 1===$entry->editable, + 'editable' => 1 === $entry->editable, 'amount' => $amount, 'foreign_amount' => $foreignAmount, ]; @@ -178,6 +244,56 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface return $return; } + /** + * @param TransactionJournal $journal + * + * @return string + */ + private function getFormattedAmount(TransactionJournal $journal): string + { + /** @var Transaction $transaction */ + $transaction = $journal->transactions->first(); + $currency = $transaction->transactionCurrency; + $type = $journal->transactionType->type; + $amount = app('steam')->positive($transaction->amount); + $return = ''; + if (TransactionType::WITHDRAWAL === $type) { + $return = app('amount')->formatAnything($currency, app('steam')->negative($amount)); + } + if (TransactionType::WITHDRAWAL !== $type) { + $return = app('amount')->formatAnything($currency, $amount); + + } + + return $return; + } + + /** + * @param TransactionJournal $journal + * + * @return string + */ + private function getFormattedForeignAmount(TransactionJournal $journal): string + { + /** @var Transaction $transaction */ + $transaction = $journal->transactions->first(); + if (null === $transaction->foreign_amount) { + return ''; + } + $currency = $transaction->foreignCurrency; + $type = $journal->transactionType->type; + $amount = app('steam')->positive($transaction->foreign_amount); + $return = ''; + if (TransactionType::WITHDRAWAL === $type) { + $return = app('amount')->formatAnything($currency, app('steam')->negative($amount)); + } + if (TransactionType::WITHDRAWAL !== $type) { + $return = app('amount')->formatAnything($currency, $amount); + } + + return $return; + } + /** * @inheritDoc */ @@ -268,6 +384,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface * * @return array * @throws FireflyException + * @throws \JsonException */ public function getPiggyEvents(TransactionGroup $group): array { @@ -295,7 +412,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface $currencyCode = app('preferences')->getForUser($this->user, 'currencyPreference', 'EUR')->data; $currency = TransactionCurrency::where('code', $currencyCode)->first(); } - $journalId = (int)$row->transaction_journal_id; + $journalId = (int) $row->transaction_journal_id; $return[$journalId] = $return[$journalId] ?? []; $return[$journalId][] = [ @@ -386,116 +503,4 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface return $service->update($transactionGroup, $data); } - - /** - * @param TransactionJournal $journal - * - * @return array - */ - private function expandJournal(TransactionJournal $journal): array - { - $array = $journal->toArray(); - $array['transactions'] = []; - $array['meta'] = $journal->transactionJournalMeta->toArray(); - $array['tags'] = $journal->tags->toArray(); - $array['categories'] = $journal->categories->toArray(); - $array['budgets'] = $journal->budgets->toArray(); - $array['notes'] = $journal->notes->toArray(); - $array['locations'] = []; - $array['attachments'] = $journal->attachments->toArray(); - $array['links'] = []; - $array['piggy_bank_events'] = $journal->piggyBankEvents->toArray(); - - /** @var Transaction $transaction */ - foreach ($journal->transactions as $transaction) { - $array['transactions'][] = $this->expandTransaction($transaction); - } - - return $array; - } - - /** - * @param Transaction $transaction - * - * @return array - */ - private function expandTransaction(Transaction $transaction): array - { - $array = $transaction->toArray(); - $array['account'] = $transaction->account->toArray(); - $array['budgets'] = []; - $array['categories'] = []; - - foreach ($transaction->categories as $category) { - $array['categories'][] = $category->toArray(); - } - - foreach ($transaction->budgets as $budget) { - $array['budgets'][] = $budget->toArray(); - } - - return $array; - } - - /** - * @param TransactionJournal $journal - * - * @return string - */ - private function getFormattedAmount(TransactionJournal $journal): string - { - /** @var Transaction $transaction */ - $transaction = $journal->transactions->first(); - $currency = $transaction->transactionCurrency; - $type = $journal->transactionType->type; - $amount = app('steam')->positive($transaction->amount); - $return = ''; - if (TransactionType::WITHDRAWAL === $type) { - $return = app('amount')->formatAnything($currency, app('steam')->negative($amount)); - } - if (TransactionType::WITHDRAWAL !== $type) { - $return = app('amount')->formatAnything($currency, $amount); - - } - - return $return; - } - - /** - * @param TransactionJournal $journal - * - * @return string - */ - private function getFormattedForeignAmount(TransactionJournal $journal): string - { - /** @var Transaction $transaction */ - $transaction = $journal->transactions->first(); - if (null === $transaction->foreign_amount) { - return ''; - } - $currency = $transaction->foreignCurrency; - $type = $journal->transactionType->type; - $amount = app('steam')->positive($transaction->foreign_amount); - $return = ''; - if (TransactionType::WITHDRAWAL === $type) { - $return = app('amount')->formatAnything($currency, app('steam')->negative($amount)); - } - if (TransactionType::WITHDRAWAL !== $type) { - $return = app('amount')->formatAnything($currency, $amount); - } - - return $return; - } - - /** - * @inheritDoc - */ - public function countAttachments(int $journalId): int - { - /** @var TransactionJournal $journal */ - $journal = $this->user->transactionJournals()->find($journalId); - - return $journal->attachments()->count(); - - } } diff --git a/app/Repositories/TransactionGroup/TransactionGroupRepositoryInterface.php b/app/Repositories/TransactionGroup/TransactionGroupRepositoryInterface.php index fc01fc13d6..fed0bca69c 100644 --- a/app/Repositories/TransactionGroup/TransactionGroupRepositoryInterface.php +++ b/app/Repositories/TransactionGroup/TransactionGroupRepositoryInterface.php @@ -36,6 +36,13 @@ use Illuminate\Support\Collection; */ interface TransactionGroupRepositoryInterface { + /** + * @param int $journalId + * + * @return int + */ + public function countAttachments(int $journalId): int; + /** * @param TransactionGroup $group */ @@ -86,13 +93,6 @@ interface TransactionGroupRepositoryInterface */ public function getLocation(int $journalId): ?Location; - /** - * @param int $journalId - * - * @return int - */ - public function countAttachments(int $journalId): int; - /** * Return object with all found meta field things as Carbon objects. * diff --git a/app/Repositories/TransactionType/TransactionTypeRepository.php b/app/Repositories/TransactionType/TransactionTypeRepository.php index d5aa7c9dc0..68db902f6f 100644 --- a/app/Repositories/TransactionType/TransactionTypeRepository.php +++ b/app/Repositories/TransactionType/TransactionTypeRepository.php @@ -33,18 +33,6 @@ use Log; class TransactionTypeRepository implements TransactionTypeRepositoryInterface { - /** - * @param string $type - * - * @return TransactionType|null - */ - public function findByType(string $type): ?TransactionType - { - $search = ucfirst($type); - - return TransactionType::whereType($search)->first(); - } - /** * @param TransactionType|null $type * @param string|null $typeString @@ -69,6 +57,18 @@ class TransactionTypeRepository implements TransactionTypeRepositoryInterface return $search; } + /** + * @param string $type + * + * @return TransactionType|null + */ + public function findByType(string $type): ?TransactionType + { + $search = ucfirst($type); + + return TransactionType::whereType($search)->first(); + } + /** * @param string $query * @param int $limit diff --git a/app/Repositories/User/UserRepository.php b/app/Repositories/User/UserRepository.php index c5daeccac5..d841a6bc46 100644 --- a/app/Repositories/User/UserRepository.php +++ b/app/Repositories/User/UserRepository.php @@ -39,39 +39,6 @@ use Str; */ class UserRepository implements UserRepositoryInterface { - /** - * @return Collection - */ - public function all(): Collection - { - return User::orderBy('id', 'DESC')->get(['users.*']); - } - - /** - * @param User $user - * @param string $role - * - * @return bool - */ - public function attachRole(User $user, string $role): bool - { - $roleObject = Role::where('name', $role)->first(); - if (null === $roleObject) { - Log::error(sprintf('Could not find role "%s" in attachRole()', $role)); - - return false; - } - - try { - $user->roles()->attach($roleObject); - } catch (QueryException $e) { - // don't care - Log::error(sprintf('Query exception when giving user a role: %s', $e->getMessage())); - } - - return true; - } - /** * This updates the users email address and records some things so it can be confirmed or undone later. * The user is blocked until the change is confirmed. @@ -144,6 +111,14 @@ class UserRepository implements UserRepositoryInterface return $this->all()->count(); } + /** + * @return Collection + */ + public function all(): Collection + { + return User::orderBy('id', 'DESC')->get(['users.*']); + } + /** * @param string $name * @param string $displayName @@ -173,6 +148,22 @@ class UserRepository implements UserRepositoryInterface return true; } + /** + * @inheritDoc + */ + public function deleteEmptyGroups(): void + { + $groups = UserGroup::get(); + /** @var UserGroup $group */ + foreach ($groups as $group) { + $count = $group->groupMemberships()->count(); + if (0 === $count) { + Log::info(sprintf('Deleted empty group #%d ("%s")', $group->id, $group->title)); + $group->delete(); + } + } + } + /** * @param int $userId * @@ -203,16 +194,6 @@ class UserRepository implements UserRepositoryInterface return User::orderBy('id', 'ASC')->first(); } - /** - * @param string $role - * - * @return Role|null - */ - public function getRole(string $role): ?Role - { - return Role::where('name', $role)->first(); - } - /** * @param User $user * @@ -243,7 +224,7 @@ class UserRepository implements UserRepositoryInterface // two factor: $return['has_2fa'] = $user->mfa_secret !== null; $return['is_admin'] = $this->hasRole($user, 'owner'); - $return['blocked'] = 1 === (int)$user->blocked; + $return['blocked'] = 1 === (int) $user->blocked; $return['blocked_code'] = $user->blocked_code; $return['accounts'] = $user->accounts()->count(); $return['journals'] = $user->transactionJournals()->count(); @@ -284,21 +265,6 @@ class UserRepository implements UserRepositoryInterface return false; } - /** - * Remove any role the user has. - * - * @param User $user - * @param string $role - */ - public function removeRole(User $user, string $role): void - { - $roleObj = $this->getRole($role); - if (null === $roleObj) { - return; - } - $user->roles()->detach($roleObj->id); - } - /** * Set MFA code. * @@ -334,6 +300,31 @@ class UserRepository implements UserRepositoryInterface return $user; } + /** + * @param User $user + * @param string $role + * + * @return bool + */ + public function attachRole(User $user, string $role): bool + { + $roleObject = Role::where('name', $role)->first(); + if (null === $roleObject) { + Log::error(sprintf('Could not find role "%s" in attachRole()', $role)); + + return false; + } + + try { + $user->roles()->attach($roleObject); + } catch (QueryException $e) { + // don't care + Log::error(sprintf('Query exception when giving user a role: %s', $e->getMessage())); + } + + return true; + } + /** * @param User $user */ @@ -402,18 +393,27 @@ class UserRepository implements UserRepositoryInterface } /** - * @inheritDoc + * Remove any role the user has. + * + * @param User $user + * @param string $role */ - public function deleteEmptyGroups(): void + public function removeRole(User $user, string $role): void { - $groups = UserGroup::get(); - /** @var UserGroup $group */ - foreach ($groups as $group) { - $count = $group->groupMemberships()->count(); - if (0 === $count) { - Log::info(sprintf('Deleted empty group #%d ("%s")', $group->id, $group->title)); - $group->delete(); - } + $roleObj = $this->getRole($role); + if (null === $roleObj) { + return; } + $user->roles()->detach($roleObj->id); + } + + /** + * @param string $role + * + * @return Role|null + */ + public function getRole(string $role): ?Role + { + return Role::where('name', $role)->first(); } } diff --git a/app/Repositories/User/UserRepositoryInterface.php b/app/Repositories/User/UserRepositoryInterface.php index 6d087cfa43..410162b2e4 100644 --- a/app/Repositories/User/UserRepositoryInterface.php +++ b/app/Repositories/User/UserRepositoryInterface.php @@ -39,11 +39,6 @@ interface UserRepositoryInterface */ public function all(): Collection; - /** - * - */ - public function deleteEmptyGroups(): void; - /** * Gives a user a role. * @@ -100,6 +95,11 @@ interface UserRepositoryInterface */ public function createRole(string $name, string $displayName, string $description): Role; + /** + * + */ + public function deleteEmptyGroups(): void; + /** * @param User $user * diff --git a/app/Rules/BelongsUser.php b/app/Rules/BelongsUser.php index 027b6b8dbe..e8050c4d27 100644 --- a/app/Rules/BelongsUser.php +++ b/app/Rules/BelongsUser.php @@ -58,7 +58,7 @@ class BelongsUser implements Rule */ public function message(): string { - return (string)trans('validation.belongs_user'); + return (string) trans('validation.belongs_user'); } /** @@ -77,19 +77,19 @@ class BelongsUser implements Rule if (!auth()->check()) { return true; } - $attribute = (string)$attribute; + $attribute = (string) $attribute; Log::debug(sprintf('Going to validate %s', $attribute)); return match ($attribute) { - 'piggy_bank_id' => $this->validatePiggyBankId((int)$value), + 'piggy_bank_id' => $this->validatePiggyBankId((int) $value), 'piggy_bank_name' => $this->validatePiggyBankName($value), - 'bill_id' => $this->validateBillId((int)$value), - 'transaction_journal_id' => $this->validateJournalId((int)$value), + 'bill_id' => $this->validateBillId((int) $value), + 'transaction_journal_id' => $this->validateJournalId((int) $value), 'bill_name' => $this->validateBillName($value), - 'budget_id' => $this->validateBudgetId((int)$value), - 'category_id' => $this->validateCategoryId((int)$value), + 'budget_id' => $this->validateBudgetId((int) $value), + 'category_id' => $this->validateCategoryId((int) $value), 'budget_name' => $this->validateBudgetName($value), - 'source_id', 'destination_id' => $this->validateAccountId((int)$value), + 'source_id', 'destination_id' => $this->validateAccountId((int) $value), default => throw new FireflyException(sprintf('Rule BelongUser cannot handle "%s"', $attribute)), }; } @@ -161,7 +161,7 @@ class BelongsUser implements Rule } $count = 0; foreach ($objects as $object) { - $objectValue = trim((string)$object->$field); + $objectValue = trim((string) $object->$field); Log::debug(sprintf('Comparing object "%s" with value "%s"', $objectValue, $value)); if ($objectValue === $value) { $count++; diff --git a/app/Rules/IsAssetAccountId.php b/app/Rules/IsAssetAccountId.php index ebf1659cd3..f30a327b58 100644 --- a/app/Rules/IsAssetAccountId.php +++ b/app/Rules/IsAssetAccountId.php @@ -53,7 +53,7 @@ class IsAssetAccountId implements Rule */ public function passes($attribute, $value): bool { - $accountId = (int)$value; + $accountId = (int) $value; $account = Account::with('accountType')->find($accountId); if (null === $account) { return false; diff --git a/app/Rules/IsBoolean.php b/app/Rules/IsBoolean.php index f2157f1abd..cf8331948f 100644 --- a/app/Rules/IsBoolean.php +++ b/app/Rules/IsBoolean.php @@ -39,7 +39,7 @@ class IsBoolean implements Rule */ public function message(): string { - return (string)trans('validation.boolean'); + return (string) trans('validation.boolean'); } /** diff --git a/app/Rules/IsDateOrTime.php b/app/Rules/IsDateOrTime.php index 6eee28a3c7..cd888864b5 100644 --- a/app/Rules/IsDateOrTime.php +++ b/app/Rules/IsDateOrTime.php @@ -44,7 +44,7 @@ class IsDateOrTime implements Rule */ public function message() { - return (string)trans('validation.date_or_time'); + return (string) trans('validation.date_or_time'); } /** @@ -57,7 +57,7 @@ class IsDateOrTime implements Rule */ public function passes($attribute, $value): bool { - $value = (string)$value; + $value = (string) $value; if ('' === $value) { return false; } diff --git a/app/Rules/IsTransferAccount.php b/app/Rules/IsTransferAccount.php index 16897ed59a..27103b1c8d 100644 --- a/app/Rules/IsTransferAccount.php +++ b/app/Rules/IsTransferAccount.php @@ -41,7 +41,7 @@ class IsTransferAccount implements Rule */ public function message(): string { - return (string)trans('validation.not_transfer_account'); + return (string) trans('validation.not_transfer_account'); } /** @@ -60,15 +60,15 @@ class IsTransferAccount implements Rule $validator->setTransactionType(TransactionType::TRANSFER); $validator->setUser(auth()->user()); - $validAccount = $validator->validateSource(['name' => (string)$value,]); + $validAccount = $validator->validateSource(['name' => (string) $value,]); if (true === $validAccount) { Log::debug('Found account based on name. Return true.'); // found by name, use repos to return. return true; } - $validAccount = $validator->validateSource(['id' => (int)$value,]); - Log::debug(sprintf('Search by id (%d), result is %s.', (int)$value, var_export($validAccount, true))); + $validAccount = $validator->validateSource(['id' => (int) $value,]); + Log::debug(sprintf('Search by id (%d), result is %s.', (int) $value, var_export($validAccount, true))); return false !== $validAccount; } diff --git a/app/Rules/IsValidAttachmentModel.php b/app/Rules/IsValidAttachmentModel.php index d2e0349693..1b6ec0dd56 100644 --- a/app/Rules/IsValidAttachmentModel.php +++ b/app/Rules/IsValidAttachmentModel.php @@ -85,7 +85,7 @@ class IsValidAttachmentModel implements Rule */ public function message(): string { - return (string)trans('validation.model_id_invalid'); + return (string) trans('validation.model_id_invalid'); } /** @@ -118,7 +118,7 @@ class IsValidAttachmentModel implements Rule } $method = $methods[$this->model]; - return $this->$method((int)$value); + return $this->$method((int) $value); } /** @@ -229,6 +229,6 @@ class IsValidAttachmentModel implements Rule $repository = app(JournalAPIRepositoryInterface::class); $repository->setUser(auth()->user()); - return null !== $repository->findTransaction((int)$value); + return null !== $repository->findTransaction((int) $value); } } diff --git a/app/Rules/IsValidBulkClause.php b/app/Rules/IsValidBulkClause.php index 7a8bda7692..9b35893fb8 100644 --- a/app/Rules/IsValidBulkClause.php +++ b/app/Rules/IsValidBulkClause.php @@ -42,7 +42,7 @@ class IsValidBulkClause implements Rule public function __construct(string $type) { $this->rules = config(sprintf('bulk.%s', $type)); - $this->error = (string)trans('firefly.belongs_user'); + $this->error = (string) trans('firefly.belongs_user'); } /** @@ -61,7 +61,7 @@ class IsValidBulkClause implements Rule */ public function passes($attribute, $value): bool { - $result = $this->basicValidation((string)$value); + $result = $this->basicValidation((string) $value); if (false === $result) { return false; } @@ -81,14 +81,14 @@ class IsValidBulkClause implements Rule try { $array = json_decode($value, true, 8, JSON_THROW_ON_ERROR); } catch (JsonException $e) { - $this->error = (string)trans('validation.json'); + $this->error = (string) trans('validation.json'); return false; } $clauses = ['where', 'update']; foreach ($clauses as $clause) { if (!array_key_exists($clause, $array)) { - $this->error = (string)trans(sprintf('validation.missing_%s', $clause)); + $this->error = (string) trans(sprintf('validation.missing_%s', $clause)); return false; } @@ -98,7 +98,7 @@ class IsValidBulkClause implements Rule */ foreach ($array[$clause] as $arrayKey => $arrayValue) { if (!array_key_exists($arrayKey, $this->rules[$clause])) { - $this->error = (string)trans(sprintf('validation.invalid_%s_key', $clause)); + $this->error = (string) trans(sprintf('validation.invalid_%s_key', $clause)); return false; } diff --git a/app/Rules/LessThanPiggyTarget.php b/app/Rules/LessThanPiggyTarget.php index e19589ea74..9e4567ec55 100644 --- a/app/Rules/LessThanPiggyTarget.php +++ b/app/Rules/LessThanPiggyTarget.php @@ -38,7 +38,7 @@ class LessThanPiggyTarget implements Rule */ public function message(): string { - return (string)trans('validation.current_target_amount'); + return (string) trans('validation.current_target_amount'); } /** diff --git a/app/Rules/UniqueAccountNumber.php b/app/Rules/UniqueAccountNumber.php index f8b4102c6b..94a2354a43 100644 --- a/app/Rules/UniqueAccountNumber.php +++ b/app/Rules/UniqueAccountNumber.php @@ -72,7 +72,7 @@ class UniqueAccountNumber implements Rule */ public function message(): string { - return (string)trans('validation.unique_account_number_for_user'); + return (string) trans('validation.unique_account_number_for_user'); } /** diff --git a/app/Rules/UniqueIban.php b/app/Rules/UniqueIban.php index e6e37f98de..ae94b4f528 100644 --- a/app/Rules/UniqueIban.php +++ b/app/Rules/UniqueIban.php @@ -69,7 +69,7 @@ class UniqueIban implements Rule */ public function message(): string { - return (string)trans('validation.unique_iban_for_user'); + return (string) trans('validation.unique_iban_for_user'); } /** diff --git a/app/Rules/ValidJournals.php b/app/Rules/ValidJournals.php index 888e5697c7..e9575a4bc8 100644 --- a/app/Rules/ValidJournals.php +++ b/app/Rules/ValidJournals.php @@ -42,7 +42,7 @@ class ValidJournals implements Rule */ public function message(): string { - return (string)trans('validation.invalid_selection'); + return (string) trans('validation.invalid_selection'); } /** diff --git a/app/Rules/ValidRecurrenceRepetitionType.php b/app/Rules/ValidRecurrenceRepetitionType.php index 6f1655f8e5..bbe95af3b2 100644 --- a/app/Rules/ValidRecurrenceRepetitionType.php +++ b/app/Rules/ValidRecurrenceRepetitionType.php @@ -40,7 +40,7 @@ class ValidRecurrenceRepetitionType implements Rule */ public function message(): string { - return (string)trans('validation.valid_recurrence_rep_type'); + return (string) trans('validation.valid_recurrence_rep_type'); } /** @@ -54,7 +54,7 @@ class ValidRecurrenceRepetitionType implements Rule */ public function passes($attribute, $value): bool { - $value = (string)$value; + $value = (string) $value; if ('daily' === $value) { return true; } diff --git a/app/Rules/ValidRecurrenceRepetitionValue.php b/app/Rules/ValidRecurrenceRepetitionValue.php index 14ba5cca50..f9a4f8b50f 100644 --- a/app/Rules/ValidRecurrenceRepetitionValue.php +++ b/app/Rules/ValidRecurrenceRepetitionValue.php @@ -43,7 +43,7 @@ class ValidRecurrenceRepetitionValue implements Rule */ public function message(): string { - return (string)trans('validation.valid_recurrence_rep_type'); + return (string) trans('validation.valid_recurrence_rep_type'); } /** @@ -57,7 +57,7 @@ class ValidRecurrenceRepetitionValue implements Rule */ public function passes($attribute, $value): bool { - $value = (string)$value; + $value = (string) $value; if ('daily' === $value) { return true; @@ -93,7 +93,7 @@ class ValidRecurrenceRepetitionValue implements Rule */ private function validateMonthly(string $value): bool { - $dayOfMonth = (int)substr($value, 8); + $dayOfMonth = (int) substr($value, 8); return $dayOfMonth > 0 && $dayOfMonth < 32; } @@ -110,8 +110,8 @@ class ValidRecurrenceRepetitionValue implements Rule if (2 !== count($parameters)) { return false; } - $nthDay = (int)($parameters[0] ?? 0.0); - $dayOfWeek = (int)($parameters[1] ?? 0.0); + $nthDay = (int) ($parameters[0] ?? 0.0); + $dayOfWeek = (int) ($parameters[1] ?? 0.0); if ($nthDay < 1 || $nthDay > 5) { return false; } @@ -126,7 +126,7 @@ class ValidRecurrenceRepetitionValue implements Rule */ private function validateWeekly(string $value): bool { - $dayOfWeek = (int)substr($value, 7); + $dayOfWeek = (int) substr($value, 7); return $dayOfWeek > 0 && $dayOfWeek < 8; } diff --git a/app/Services/FireflyIIIOrg/Update/UpdateRequest.php b/app/Services/FireflyIIIOrg/Update/UpdateRequest.php index 7aed47deb5..a569d497cc 100644 --- a/app/Services/FireflyIIIOrg/Update/UpdateRequest.php +++ b/app/Services/FireflyIIIOrg/Update/UpdateRequest.php @@ -46,7 +46,7 @@ class UpdateRequest implements UpdateRequestInterface Log::debug(sprintf('Now in getUpdateInformation(%s)', $channel)); $information = [ 'level' => 'error', - 'message' => (string)trans('firefly.unknown_error'), + 'message' => (string) trans('firefly.unknown_error'), ]; // try get array from update server: @@ -76,7 +76,7 @@ class UpdateRequest implements UpdateRequestInterface 'version' => config('firefly.version'), 'date' => Carbon::today()->startOfDay(), 'level' => 'error', - 'message' => (string)trans('firefly.unknown_error'), + 'message' => (string) trans('firefly.unknown_error'), ]; $uri = config('firefly.update_endpoint'); @@ -101,12 +101,12 @@ class UpdateRequest implements UpdateRequestInterface if (200 !== $res->getStatusCode()) { Log::error(sprintf('Response status from server is %d.', $res->getStatusCode())); - Log::error((string)$res->getBody()); + Log::error((string) $res->getBody()); $return['message'] = sprintf('Error: %d', $res->getStatusCode()); return $return; } - $body = (string)$res->getBody(); + $body = (string) $res->getBody(); try { $json = json_decode($body, true, 512, JSON_THROW_ON_ERROR); @@ -144,7 +144,7 @@ class UpdateRequest implements UpdateRequestInterface Log::debug('Now in parseResult()', $information); $return = [ 'level' => 'error', - 'message' => (string)trans('firefly.unknown_error'), + 'message' => (string) trans('firefly.unknown_error'), ]; $current = config('firefly.version'); $latest = $information['version']; @@ -155,7 +155,7 @@ class UpdateRequest implements UpdateRequestInterface // -1: you're running a newer version: if (-1 === $compare) { $return['level'] = 'info'; - $return['message'] = (string)trans('firefly.update_newer_version_alert', ['your_version' => $current, 'new_version' => $latest]); + $return['message'] = (string) trans('firefly.update_newer_version_alert', ['your_version' => $current, 'new_version' => $latest]); Log::debug('User is running a newer version', $return); return $return; @@ -163,7 +163,7 @@ class UpdateRequest implements UpdateRequestInterface // running the current version: if (0 === $compare) { $return['level'] = 'info'; - $return['message'] = (string)trans('firefly.update_current_version_alert', ['version' => $current]); + $return['message'] = (string) trans('firefly.update_current_version_alert', ['version' => $current]); Log::debug('User is the current version.', $return); return $return; @@ -177,10 +177,10 @@ class UpdateRequest implements UpdateRequestInterface // it's still very fresh, and user wants a stable release: if ($diff <= $expectedDiff) { $return['level'] = 'info'; - $return['message'] = (string)trans( + $return['message'] = (string) trans( 'firefly.just_new_release', ['version' => $latest, - 'date' => $released->formatLocalized((string)trans('config.month_and_day')), + 'date' => $released->isoFormat((string) trans('config.month_and_day_js')), 'days' => $expectedDiff, ] ); @@ -191,14 +191,12 @@ class UpdateRequest implements UpdateRequestInterface // its been around for a while: $return['level'] = 'success'; - $return['message'] = (string)trans( + $return['message'] = (string) trans( 'firefly.update_new_version_alert', [ 'your_version' => $current, 'new_version' => $latest, - 'date' => $released->formatLocalized( - (string)trans('config.month_and_day') - )] + 'date' => $released->isoFormat((string) trans('config.month_and_day_js'))] ); Log::debug('New release is old enough.'); diff --git a/app/Services/Internal/Destroy/AccountDestroyService.php b/app/Services/Internal/Destroy/AccountDestroyService.php index aed55bb705..ee5aafe5b0 100644 --- a/app/Services/Internal/Destroy/AccountDestroyService.php +++ b/app/Services/Internal/Destroy/AccountDestroyService.php @@ -41,7 +41,7 @@ use stdClass; class AccountDestroyService { /** - * @param Account $account + * @param Account $account * @param Account|null $moveTo * * @return void @@ -87,7 +87,7 @@ class AccountDestroyService ->where('transaction_types.type', TransactionType::OPENING_BALANCE) ->get(['transactions.transaction_journal_id']); if ($set->count() > 0) { - $journalId = (int)$set->first()->transaction_journal_id; + $journalId = (int) $set->first()->transaction_journal_id; Log::debug(sprintf('Found opening balance journal with ID #%d', $journalId)); // get transactions with this journal (should be just one): @@ -133,8 +133,8 @@ class AccountDestroyService $user = $account->user; /** @var stdClass $row */ foreach ($collection as $row) { - if ((int)$row->the_count > 1) { - $journalId = (int)$row->transaction_journal_id; + if ((int) $row->the_count > 1) { + $journalId = (int) $row->transaction_journal_id; $journal = $user->transactionJournals()->find($journalId); if (null !== $journal) { Log::debug(sprintf('Deleted journal #%d because it has the same source as destination.', $journal->id)); @@ -192,7 +192,7 @@ class AccountDestroyService /** @var RecurrenceDestroyService $destroyService */ $destroyService = app(RecurrenceDestroyService::class); foreach ($recurrences as $recurrenceId) { - $destroyService->destroyById((int)$recurrenceId); + $destroyService->destroyById((int) $recurrenceId); } } diff --git a/app/Services/Internal/Destroy/BudgetDestroyService.php b/app/Services/Internal/Destroy/BudgetDestroyService.php index f1335cd7c1..e7b1deb515 100644 --- a/app/Services/Internal/Destroy/BudgetDestroyService.php +++ b/app/Services/Internal/Destroy/BudgetDestroyService.php @@ -52,10 +52,10 @@ class BudgetDestroyService } // also delete all relations between categories and transaction journals: - DB::table('budget_transaction_journal')->where('budget_id', (int)$budget->id)->delete(); + DB::table('budget_transaction_journal')->where('budget_id', (int) $budget->id)->delete(); // also delete all relations between categories and transactions: - DB::table('budget_transaction')->where('budget_id', (int)$budget->id)->delete(); + DB::table('budget_transaction')->where('budget_id', (int) $budget->id)->delete(); // also delete all budget limits $budget->budgetlimits()->delete(); diff --git a/app/Services/Internal/Destroy/CategoryDestroyService.php b/app/Services/Internal/Destroy/CategoryDestroyService.php index adb3f92f2c..63c97ec7a2 100644 --- a/app/Services/Internal/Destroy/CategoryDestroyService.php +++ b/app/Services/Internal/Destroy/CategoryDestroyService.php @@ -46,9 +46,9 @@ class CategoryDestroyService } // also delete all relations between categories and transaction journals: - DB::table('category_transaction_journal')->where('category_id', (int)$category->id)->delete(); + DB::table('category_transaction_journal')->where('category_id', (int) $category->id)->delete(); // also delete all relations between categories and transactions: - DB::table('category_transaction')->where('category_id', (int)$category->id)->delete(); + DB::table('category_transaction')->where('category_id', (int) $category->id)->delete(); } } diff --git a/app/Services/Internal/Support/AccountServiceTrait.php b/app/Services/Internal/Support/AccountServiceTrait.php index e760f29d5e..1cea2563ff 100644 --- a/app/Services/Internal/Support/AccountServiceTrait.php +++ b/app/Services/Internal/Support/AccountServiceTrait.php @@ -146,7 +146,7 @@ trait AccountServiceTrait $data[$field] = 1; } - $factory->crud($account, $field, (string)$data[$field]); + $factory->crud($account, $field, (string) $data[$field]); } } } @@ -192,7 +192,7 @@ trait AccountServiceTrait */ public function validOBData(array $data): bool { - $data['opening_balance'] = (string)($data['opening_balance'] ?? ''); + $data['opening_balance'] = (string) ($data['opening_balance'] ?? ''); if ('' !== $data['opening_balance'] && 0 === bccomp($data['opening_balance'], '0')) { $data['opening_balance'] = ''; } @@ -367,6 +367,8 @@ trait AccountServiceTrait * @param string $currencyCode * * @return TransactionCurrency + * @throws FireflyException + * @throws \JsonException */ protected function getCurrency(int $currencyId, string $currencyCode): TransactionCurrency { @@ -512,6 +514,63 @@ trait AccountServiceTrait return $group; } + /** + * See reference nr. 99 + * + * @param TransactionGroup $group + * + * @return TransactionJournal + * @throws FireflyException + */ + private function getObJournal(TransactionGroup $group): TransactionJournal + { + /** @var TransactionJournal $journal */ + $journal = $group->transactionJournals()->first(); + if (null === $journal) { + throw new FireflyException(sprintf('Group #%d has no OB journal', $group->id)); + } + + return $journal; + } + + /** + * See reference nr. 98 + * + * @param TransactionJournal $journal + * @param Account $account + * + * @return Transaction + * @throws FireflyException + */ + private function getOBTransaction(TransactionJournal $journal, Account $account): Transaction + { + /** @var Transaction $transaction */ + $transaction = $journal->transactions()->where('account_id', '!=', $account->id)->first(); + if (null === $transaction) { + throw new FireflyException(sprintf('Could not get OB transaction for journal #%d', $journal->id)); + } + + return $transaction; + } + + /** + * @param TransactionJournal $journal + * @param Account $account + * + * @return Transaction + * @throws FireflyException + */ + private function getNotOBTransaction(TransactionJournal $journal, Account $account): Transaction + { + /** @var Transaction $transaction */ + $transaction = $journal->transactions()->where('account_id', $account->id)->first(); + if (null === $transaction) { + throw new FireflyException(sprintf('Could not get non-OB transaction for journal #%d', $journal->id)); + } + + return $transaction; + } + /** * Update or create the opening balance group. * Since opening balance and date can still be empty strings, it may fail. @@ -667,61 +726,4 @@ trait AccountServiceTrait return $group; } - - /** - * See reference nr. 99 - * - * @param TransactionGroup $group - * - * @return TransactionJournal - * @throws FireflyException - */ - private function getObJournal(TransactionGroup $group): TransactionJournal - { - /** @var TransactionJournal $journal */ - $journal = $group->transactionJournals()->first(); - if (null === $journal) { - throw new FireflyException(sprintf('Group #%d has no OB journal', $group->id)); - } - - return $journal; - } - - /** - * See reference nr. 98 - * - * @param TransactionJournal $journal - * @param Account $account - * - * @return Transaction - * @throws FireflyException - */ - private function getOBTransaction(TransactionJournal $journal, Account $account): Transaction - { - /** @var Transaction $transaction */ - $transaction = $journal->transactions()->where('account_id', '!=', $account->id)->first(); - if (null === $transaction) { - throw new FireflyException(sprintf('Could not get OB transaction for journal #%d', $journal->id)); - } - - return $transaction; - } - - /** - * @param TransactionJournal $journal - * @param Account $account - * - * @return Transaction - * @throws FireflyException - */ - private function getNotOBTransaction(TransactionJournal $journal, Account $account): Transaction - { - /** @var Transaction $transaction */ - $transaction = $journal->transactions()->where('account_id', $account->id)->first(); - if (null === $transaction) { - throw new FireflyException(sprintf('Could not get non-OB transaction for journal #%d', $journal->id)); - } - - return $transaction; - } } diff --git a/app/Services/Internal/Support/CreditRecalculateService.php b/app/Services/Internal/Support/CreditRecalculateService.php index 20d9ba78db..e67346304d 100644 --- a/app/Services/Internal/Support/CreditRecalculateService.php +++ b/app/Services/Internal/Support/CreditRecalculateService.php @@ -205,7 +205,7 @@ class CreditRecalculateService $factory->crud($account, 'start_of_debt', $startOfDebt); // get direction of liability: - $direction = (string)$this->repository->getMetaValue($account, 'liability_direction'); + $direction = (string) $this->repository->getMetaValue($account, 'liability_direction'); // now loop all transactions (except opening balance and credit thing) $transactions = $account->transactions()->get(); @@ -246,7 +246,7 @@ class CreditRecalculateService // to a credit-liability doesn't increase the amount (yet) if ( $type === TransactionType::WITHDRAWAL - && (int)$account->id === (int)$transaction->account_id + && (int) $account->id === (int) $transaction->account_id && 1 === bccomp($transaction->amount, '0') && 'credit' === $direction ) { @@ -258,7 +258,7 @@ class CreditRecalculateService // likewise deposit into a credit debt does not change the amount if ( $type === TransactionType::DEPOSIT - && (int)$account->id === (int)$transaction->account_id + && (int) $account->id === (int) $transaction->account_id && -1 === bccomp($transaction->amount, '0') && 'credit' === $direction ) { diff --git a/app/Services/Internal/Support/JournalServiceTrait.php b/app/Services/Internal/Support/JournalServiceTrait.php index 3d60e2add8..f9907647f5 100644 --- a/app/Services/Internal/Support/JournalServiceTrait.php +++ b/app/Services/Internal/Support/JournalServiceTrait.php @@ -98,7 +98,7 @@ trait JournalServiceTrait $search = null; // first attempt, find by ID. if (null !== $data['id']) { - $search = $this->accountRepository->find((int)$data['id']); + $search = $this->accountRepository->find((int) $data['id']); if (null !== $search && in_array($search->accountType->type, $types, true)) { Log::debug( sprintf('Found "account_id" object: #%d, "%s" of type %s', $search->id, $search->name, $search->accountType->type) @@ -109,32 +109,6 @@ trait JournalServiceTrait return $search; } - /** - * @param Account|null $account - * @param array $data - * @param array $types - * - * @return Account|null - */ - private function findAccountByName(?Account $account, array $data, array $types): ?Account - { - // second attempt, find by name. - if (null === $account && null !== $data['name']) { - // find by preferred type. - $source = $this->accountRepository->findByName($data['name'], [$types[0]]); - // or any expected type. - $source = $source ?? $this->accountRepository->findByName($data['name'], $types); - - if (null !== $source) { - Log::debug(sprintf('Found "account_name" object: #%d, %s', $source->id, $source->name)); - - $account = $source; - } - } - - return $account; - } - /** * @param Account|null $account * @param array $data @@ -175,10 +149,10 @@ trait JournalServiceTrait if (null === $account && null !== $data['number'] && '' !== (string) $data['number']) { Log::debug(sprintf('Searching for account number "%s".', $data['number'])); // find by preferred type. - $source = $this->accountRepository->findByAccountNumber((string)$data['number'], [$types[0]]); + $source = $this->accountRepository->findByAccountNumber((string) $data['number'], [$types[0]]); // or any expected type. - $source = $source ?? $this->accountRepository->findByAccountNumber((string)$data['number'], $types); + $source = $source ?? $this->accountRepository->findByAccountNumber((string) $data['number'], $types); if (null !== $source) { Log::debug(sprintf('Found account: #%d, %s', $source->id, $source->name)); @@ -190,6 +164,32 @@ trait JournalServiceTrait return $account; } + /** + * @param Account|null $account + * @param array $data + * @param array $types + * + * @return Account|null + */ + private function findAccountByName(?Account $account, array $data, array $types): ?Account + { + // second attempt, find by name. + if (null === $account && null !== $data['name']) { + // find by preferred type. + $source = $this->accountRepository->findByName($data['name'], [$types[0]]); + // or any expected type. + $source = $source ?? $this->accountRepository->findByName($data['name'], $types); + + if (null !== $source) { + Log::debug(sprintf('Found "account_name" object: #%d, %s', $source->id, $source->name)); + + $account = $source; + } + } + + return $account; + } + /** * @param Account|null $account * @param array $data @@ -218,12 +218,12 @@ trait JournalServiceTrait throw new FireflyException(sprintf('TransactionFactory: Cannot create asset account with these values: %s', json_encode($data))); } // fix name of account if only IBAN is given: - if ('' === (string)$data['name'] && '' !== (string)$data['iban']) { + if ('' === (string) $data['name'] && '' !== (string) $data['iban']) { Log::debug(sprintf('Account name is now IBAN ("%s")', $data['iban'])); $data['name'] = $data['iban']; } // fix name of account if only number is given: - if ('' === (string)$data['name'] && '' !== (string)$data['number']) { + if ('' === (string) $data['name'] && '' !== (string) $data['number']) { Log::debug(sprintf('Account name is now account number ("%s")', $data['number'])); $data['name'] = $data['number']; } @@ -379,7 +379,7 @@ trait JournalServiceTrait */ protected function storeNotes(TransactionJournal $journal, ?string $notes): void { - $notes = (string)$notes; + $notes = (string) $notes; $note = $journal->notes()->first(); if ('' !== $notes) { if (null === $note) { @@ -422,7 +422,7 @@ trait JournalServiceTrait } Log::debug('Start of loop.'); foreach ($tags as $string) { - $string = (string)$string; + $string = (string) $string; Log::debug(sprintf('Now at tag "%s"', $string)); if ('' !== $string) { $tag = $this->tagFactory->findOrCreate($string); diff --git a/app/Services/Internal/Support/RecurringTransactionTrait.php b/app/Services/Internal/Support/RecurringTransactionTrait.php index 73fa6604aa..c78e035be8 100644 --- a/app/Services/Internal/Support/RecurringTransactionTrait.php +++ b/app/Services/Internal/Support/RecurringTransactionTrait.php @@ -108,6 +108,7 @@ trait RecurringTransactionTrait * @param array $transactions * * @throws FireflyException + * @throws \JsonException */ protected function createTransactions(Recurrence $recurrence, array $transactions): void { @@ -144,7 +145,7 @@ trait RecurringTransactionTrait if (!$validator->validateDestination(['id' => $destination->id])) { throw new FireflyException(sprintf('Destination invalid: %s', $validator->destError)); } - if (array_key_exists('foreign_amount', $array) && '' === (string)$array['foreign_amount']) { + if (array_key_exists('foreign_amount', $array) && '' === (string) $array['foreign_amount']) { unset($array['foreign_amount']); } // See reference nr. 100 @@ -156,25 +157,25 @@ trait RecurringTransactionTrait 'source_id' => $source->id, 'destination_id' => $destination->id, 'amount' => $array['amount'], - 'foreign_amount' => array_key_exists('foreign_amount', $array) ? (string)$array['foreign_amount'] : null, + 'foreign_amount' => array_key_exists('foreign_amount', $array) ? (string) $array['foreign_amount'] : null, 'description' => $array['description'], ] ); $transaction->save(); if (array_key_exists('budget_id', $array)) { - $this->setBudget($transaction, (int)$array['budget_id']); + $this->setBudget($transaction, (int) $array['budget_id']); } if (array_key_exists('bill_id', $array)) { - $this->setBill($transaction, (int)$array['bill_id']); + $this->setBill($transaction, (int) $array['bill_id']); } if (array_key_exists('category_id', $array)) { - $this->setCategory($transaction, (int)$array['category_id']); + $this->setCategory($transaction, (int) $array['category_id']); } // same for piggy bank if (array_key_exists('piggy_bank_id', $array)) { - $this->updatePiggyBank($transaction, (int)$array['piggy_bank_id']); + $this->updatePiggyBank($transaction, (int) $array['piggy_bank_id']); } if (array_key_exists('tags', $array) && is_array($array['tags'])) { @@ -194,14 +195,14 @@ trait RecurringTransactionTrait protected function findAccount(array $expectedTypes, ?int $accountId, ?string $accountName): Account { $result = null; - $accountId = (int)$accountId; - $accountName = (string)$accountName; + $accountId = (int) $accountId; + $accountName = (string) $accountName; /** @var AccountRepositoryInterface $repository */ $repository = app(AccountRepositoryInterface::class); $repository->setUser($this->user); // if user has submitted an account ID, search for it. - $result = $repository->find((int)$accountId); + $result = $repository->find((int) $accountId); if (null !== $result) { return $result; } diff --git a/app/Services/Internal/Update/AccountUpdateService.php b/app/Services/Internal/Update/AccountUpdateService.php index 1e92b4a4a2..2adaf3c1da 100644 --- a/app/Services/Internal/Update/AccountUpdateService.php +++ b/app/Services/Internal/Update/AccountUpdateService.php @@ -89,7 +89,7 @@ class AccountUpdateService // find currency, or use default currency instead. if (array_key_exists('currency_id', $data) || array_key_exists('currency_code', $data)) { - $currency = $this->getCurrency((int)($data['currency_id'] ?? null), (string)($data['currency_code'] ?? null)); + $currency = $this->getCurrency((int) ($data['currency_id'] ?? null), (string) ($data['currency_code'] ?? null)); unset($data['currency_code'], $data['currency_id']); $data['currency_id'] = $currency->id; } @@ -108,7 +108,7 @@ class AccountUpdateService // update note: if (array_key_exists('notes', $data) && null !== $data['notes']) { - $this->updateNote($account, (string)$data['notes']); + $this->updateNote($account, (string) $data['notes']); } // update preferences if inactive: @@ -135,21 +135,19 @@ class AccountUpdateService $account->active = $data['active']; } if (array_key_exists('iban', $data)) { - $account->iban = app('steam')->filterSpaces((string)$data['iban']); + $account->iban = app('steam')->filterSpaces((string) $data['iban']); } // set liability, but account must already be a liability. //$liabilityType = $data['liability_type'] ?? ''; if ($this->isLiability($account) && array_key_exists('liability_type', $data)) { $type = $this->getAccountType($data['liability_type']); - if (null !== $type) { - $account->account_type_id = $type->id; - } + $account->account_type_id = $type->id; } // set liability, alternative method used in v1 layout: if ($this->isLiability($account) && array_key_exists('account_type_id', $data)) { - $type = AccountType::find((int)$data['account_type_id']); + $type = AccountType::find((int) $data['account_type_id']); if (null !== $type && in_array($type->type, config('firefly.valid_liabilities'), true)) { $account->account_type_id = $type->id; @@ -210,7 +208,7 @@ class AccountUpdateService return $account; } // get account type ID's because a join and an update is hard: - $oldOrder = (int)$account->order; + $oldOrder = (int) $account->order; $newOrder = $data['order']; Log::debug(sprintf('Order is set to be updated from %s to %s', $oldOrder, $newOrder)); $list = $this->getTypeIds([AccountType::MORTGAGE, AccountType::LOAN, AccountType::DEBT]); @@ -248,7 +246,7 @@ class AccountUpdateService foreach ($array as $type) { /** @var AccountType $type */ $type = AccountType::whereType($type)->first(); - $return[] = (int)$type->id; + $return[] = (int) $type->id; } return $return; @@ -357,12 +355,12 @@ class AccountUpdateService $array = $preference->data; Log::debug('Old array is: ', $array); Log::debug(sprintf('Must remove : %d', $account->id)); - $removeAccountId = (int)$account->id; + $removeAccountId = (int) $account->id; $new = []; foreach ($array as $value) { - if ((int)$value !== $removeAccountId) { + if ((int) $value !== $removeAccountId) { Log::debug(sprintf('Will include: %d', $value)); - $new[] = (int)$value; + $new[] = (int) $value; } } Log::debug('Final new array is', $new); diff --git a/app/Services/Internal/Update/BillUpdateService.php b/app/Services/Internal/Update/BillUpdateService.php index 49430f51be..500538cc44 100644 --- a/app/Services/Internal/Update/BillUpdateService.php +++ b/app/Services/Internal/Update/BillUpdateService.php @@ -49,6 +49,8 @@ class BillUpdateService * @param array $data * * @return Bill + * @throws \FireflyIII\Exceptions\FireflyException + * @throws \JsonException */ public function update(Bill $bill, array $data): Bill { @@ -56,7 +58,7 @@ class BillUpdateService if (array_key_exists('currency_id', $data) || array_key_exists('currency_code', $data)) { $factory = app(TransactionCurrencyFactory::class); - $currency = $factory->find((int)($data['currency_id'] ?? null), $data['currency_code'] ?? null) ?? + $currency = $factory->find((int) ($data['currency_id'] ?? null), $data['currency_code'] ?? null) ?? app('amount')->getDefaultCurrencyByUser($bill->user); // enable the currency if it isn't. @@ -78,14 +80,14 @@ class BillUpdateService ]; // update note: if (array_key_exists('notes', $data)) { - $this->updateNote($bill, (string)$data['notes']); + $this->updateNote($bill, (string) $data['notes']); } // update order. if (array_key_exists('order', $data)) { // update the order of the piggy bank: - $oldOrder = (int)$bill->order; - $newOrder = (int)($data['order'] ?? $oldOrder); + $oldOrder = (int) $bill->order; + $newOrder = (int) ($data['order'] ?? $oldOrder); if ($oldOrder !== $newOrder) { $this->updateOrder($bill, $oldOrder, $newOrder); } @@ -117,7 +119,7 @@ class BillUpdateService } if (array_key_exists('object_group_id', $data)) { // try also with ID: - $objectGroupId = (int)($data['object_group_id'] ?? 0); + $objectGroupId = (int) ($data['object_group_id'] ?? 0); if (0 !== $objectGroupId) { $objectGroup = $this->findObjectGroupById($objectGroupId); if (null !== $objectGroup) { @@ -144,20 +146,20 @@ class BillUpdateService */ private function updateBillProperties(Bill $bill, array $data): Bill { - if (array_key_exists('name', $data) && '' !== (string)$data['name']) { + if (array_key_exists('name', $data) && '' !== (string) $data['name']) { $bill->name = $data['name']; } - if (array_key_exists('amount_min', $data) && '' !== (string)$data['amount_min']) { + if (array_key_exists('amount_min', $data) && '' !== (string) $data['amount_min']) { $bill->amount_min = $data['amount_min']; } - if (array_key_exists('amount_max', $data) && '' !== (string)$data['amount_max']) { + if (array_key_exists('amount_max', $data) && '' !== (string) $data['amount_max']) { $bill->amount_max = $data['amount_max']; } - if (array_key_exists('date', $data) && '' !== (string)$data['date']) { + if (array_key_exists('date', $data) && '' !== (string) $data['date']) { $bill->date = $data['date']; } - if (array_key_exists('repeat_freq', $data) && '' !== (string)$data['repeat_freq']) { + if (array_key_exists('repeat_freq', $data) && '' !== (string) $data['repeat_freq']) { $bill->repeat_freq = $data['repeat_freq']; } if (array_key_exists('skip', $data)) { @@ -166,6 +168,12 @@ class BillUpdateService if (array_key_exists('active', $data)) { $bill->active = $data['active']; } + if (array_key_exists('end_date', $data)) { + $bill->end_date = $data['end_date']; + } + if (array_key_exists('extension_date', $data)) { + $bill->extension_date = $data['extension_date']; + } $bill->match = 'EMPTY'; $bill->automatch = true; diff --git a/app/Services/Internal/Update/CurrencyUpdateService.php b/app/Services/Internal/Update/CurrencyUpdateService.php index f84a1b78f2..4c6219d97c 100644 --- a/app/Services/Internal/Update/CurrencyUpdateService.php +++ b/app/Services/Internal/Update/CurrencyUpdateService.php @@ -40,15 +40,15 @@ class CurrencyUpdateService */ public function update(TransactionCurrency $currency, array $data): TransactionCurrency { - if (array_key_exists('code', $data) && '' !== (string)$data['code']) { + if (array_key_exists('code', $data) && '' !== (string) $data['code']) { $currency->code = $data['code']; } - if (array_key_exists('symbol', $data) && '' !== (string)$data['symbol']) { + if (array_key_exists('symbol', $data) && '' !== (string) $data['symbol']) { $currency->symbol = $data['symbol']; } - if (array_key_exists('name', $data) && '' !== (string)$data['name']) { + if (array_key_exists('name', $data) && '' !== (string) $data['name']) { $currency->name = $data['name']; } diff --git a/app/Services/Internal/Update/GroupCloneService.php b/app/Services/Internal/Update/GroupCloneService.php index cd6bb7e107..92386d9365 100644 --- a/app/Services/Internal/Update/GroupCloneService.php +++ b/app/Services/Internal/Update/GroupCloneService.php @@ -48,7 +48,7 @@ class GroupCloneService $newGroup = $group->replicate(); $newGroup->save(); foreach ($group->transactionJournals as $journal) { - $this->cloneJournal($journal, $newGroup, (int)$group->id); + $this->cloneJournal($journal, $newGroup, (int) $group->id); } return $newGroup; diff --git a/app/Services/Internal/Update/GroupUpdateService.php b/app/Services/Internal/Update/GroupUpdateService.php index 45b4cd2c32..c97f6daf78 100644 --- a/app/Services/Internal/Update/GroupUpdateService.php +++ b/app/Services/Internal/Update/GroupUpdateService.php @@ -43,6 +43,7 @@ class GroupUpdateService * @param array $data * * @return TransactionGroup + * @throws DuplicateTransactionException * @throws FireflyException */ public function update(TransactionGroup $transactionGroup, array $data): TransactionGroup @@ -191,8 +192,9 @@ class GroupUpdateService * * @return TransactionJournal|null * - * @throws FireflyException * @throws DuplicateTransactionException + * @throws FireflyException + * @throws \JsonException */ private function createTransactionJournal(TransactionGroup $transactionGroup, array $data): ?TransactionJournal { diff --git a/app/Services/Internal/Update/JournalUpdateService.php b/app/Services/Internal/Update/JournalUpdateService.php index d16d0b8ac4..61ed19b2f2 100644 --- a/app/Services/Internal/Update/JournalUpdateService.php +++ b/app/Services/Internal/Update/JournalUpdateService.php @@ -215,7 +215,7 @@ class JournalUpdateService $validator->setTransactionType($expectedType); $validator->setUser($this->transactionJournal->user); - $result = $validator->validateSource(['id' =>$sourceId]); + $result = $validator->validateSource(['id' => $sourceId]); Log::debug(sprintf('hasValidSourceAccount(%d, "%s") will return %s', $sourceId, $sourceName, var_export($result, true))); // See reference nr. 95 @@ -359,7 +359,7 @@ class JournalUpdateService } $sourceInfo = [ - 'id' => (int)($this->data['source_id'] ?? null), + 'id' => (int) ($this->data['source_id'] ?? null), 'name' => $this->data['source_name'] ?? null, 'iban' => $this->data['source_iban'] ?? null, 'number' => $this->data['source_number'] ?? null, @@ -424,7 +424,7 @@ class JournalUpdateService } $destInfo = [ - 'id' => (int)($this->data['destination_id'] ?? null), + 'id' => (int) ($this->data['destination_id'] ?? null), 'name' => $this->data['destination_name'] ?? null, 'iban' => $this->data['destination_iban'] ?? null, 'number' => $this->data['destination_number'] ?? null, @@ -487,8 +487,8 @@ 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 = $bill?->id; Log::debug('Updated bill ID'); @@ -502,7 +502,7 @@ class JournalUpdateService */ private function updateField(string $fieldName): void { - if (array_key_exists($fieldName, $this->data) && '' !== (string)$this->data[$fieldName]) { + if (array_key_exists($fieldName, $this->data) && '' !== (string) $this->data[$fieldName]) { $value = $this->data[$fieldName]; if ('date' === $fieldName) { @@ -579,7 +579,7 @@ class JournalUpdateService { // update notes. if ($this->hasFields(['notes'])) { - $notes = '' === (string)$this->data['notes'] ? null : $this->data['notes']; + $notes = '' === (string) $this->data['notes'] ? null : $this->data['notes']; $this->storeNotes($this->transactionJournal, $notes); } } @@ -636,7 +636,7 @@ class JournalUpdateService foreach ($this->metaDate as $field) { if ($this->hasFields([$field])) { try { - $value = '' === (string)$this->data[$field] ? null : new Carbon($this->data[$field]); + $value = '' === (string) $this->data[$field] ? null : new Carbon($this->data[$field]); } catch (Exception $e) { // @phpstan-ignore-line Log::debug(sprintf('%s is not a valid date value: %s', $this->data[$field], $e->getMessage())); diff --git a/app/Services/Internal/Update/RecurrenceUpdateService.php b/app/Services/Internal/Update/RecurrenceUpdateService.php index 9fa6af232f..f099d2ec09 100644 --- a/app/Services/Internal/Update/RecurrenceUpdateService.php +++ b/app/Services/Internal/Update/RecurrenceUpdateService.php @@ -78,7 +78,7 @@ class RecurrenceUpdateService $recurrence->repetitions = 0; } if (array_key_exists('nr_of_repetitions', $info)) { - if (0 !== (int)$info['nr_of_repetitions']) { + if (0 !== (int) $info['nr_of_repetitions']) { $recurrence->repeat_until = null; } $recurrence->repetitions = $info['nr_of_repetitions']; @@ -257,7 +257,7 @@ class RecurrenceUpdateService unset($current['currency_id'], $current['currency_code']); } if (null !== $currency) { - $current['currency_id'] = (int)$currency->id; + $current['currency_id'] = (int) $currency->id; } if (array_key_exists('foreign_currency_id', $current) || array_key_exists('foreign_currency_code', $current)) { $foreignCurrency = $currencyFactory->find($current['foreign_currency_id'] ?? null, $currency['foreign_currency_code'] ?? null); @@ -266,7 +266,7 @@ class RecurrenceUpdateService unset($current['foreign_currency_id'], $currency['foreign_currency_code']); } if (null !== $foreignCurrency) { - $current['foreign_currency_id'] = (int)$foreignCurrency->id; + $current['foreign_currency_id'] = (int) $foreignCurrency->id; } // update fields @@ -287,27 +287,27 @@ class RecurrenceUpdateService } // update meta data if (array_key_exists('budget_id', $current)) { - $this->setBudget($match, (int)$current['budget_id']); + $this->setBudget($match, (int) $current['budget_id']); } if (array_key_exists('bill_id', $current)) { - $this->setBill($match, (int)$current['bill_id']); + $this->setBill($match, (int) $current['bill_id']); } // reset category if name is set but empty: // can be removed when v1 is retired. - if (array_key_exists('category_name', $current) && '' === (string)$current['category_name']) { + if (array_key_exists('category_name', $current) && '' === (string) $current['category_name']) { $current['category_name'] = null; $current['category_id'] = 0; } if (array_key_exists('category_id', $current)) { - $this->setCategory($match, (int)$current['category_id']); + $this->setCategory($match, (int) $current['category_id']); } if (array_key_exists('tags', $current) && is_array($current['tags'])) { $this->updateTags($match, $current['tags']); } if (array_key_exists('piggy_bank_id', $current)) { - $this->updatePiggyBank($match, (int)$current['piggy_bank_id']); + $this->updatePiggyBank($match, (int) $current['piggy_bank_id']); } } } diff --git a/app/Services/Password/PwndVerifierV2.php b/app/Services/Password/PwndVerifierV2.php index 6ebdae729b..8c286f08c7 100644 --- a/app/Services/Password/PwndVerifierV2.php +++ b/app/Services/Password/PwndVerifierV2.php @@ -62,7 +62,7 @@ class PwndVerifierV2 implements Verifier try { $client = new Client(); $res = $client->request('GET', $uri, $opt); - } catch (GuzzleException | RequestException $e) { + } catch (GuzzleException|RequestException $e) { Log::error(sprintf('Could not verify password security: %s', $e->getMessage())); return true; diff --git a/app/Services/Webhook/StandardWebhookSender.php b/app/Services/Webhook/StandardWebhookSender.php index 673d299912..94e7f7b78f 100644 --- a/app/Services/Webhook/StandardWebhookSender.php +++ b/app/Services/Webhook/StandardWebhookSender.php @@ -59,7 +59,7 @@ class StandardWebhookSender implements WebhookSenderInterface try { $signature = $signatureGenerator->generate($this->message); - } catch(FireflyException $e) { + } catch (FireflyException $e) { Log::error('Did not send message because of a Firefly III Exception.'); Log::error($e->getMessage()); Log::error($e->getTraceAsString()); diff --git a/app/Support/Amount.php b/app/Support/Amount.php index 077c44de71..4ef63ea5bc 100644 --- a/app/Support/Amount.php +++ b/app/Support/Amount.php @@ -51,7 +51,7 @@ class Amount */ public function formatAnything(TransactionCurrency $format, string $amount, bool $coloured = null): string { - return $this->formatFlat($format->symbol, (int)$format->decimal_places, $amount, $coloured); + return $this->formatFlat($format->symbol, (int) $format->decimal_places, $amount, $coloured); } /** @@ -65,6 +65,7 @@ class Amount * * @return string * + * @throws FireflyException * @noinspection MoreThanThreeArgumentsInspection */ public function formatFlat(string $symbol, int $decimalPlaces, string $amount, bool $coloured = null): string @@ -77,7 +78,7 @@ class Amount $fmt->setSymbol(NumberFormatter::CURRENCY_SYMBOL, $symbol); $fmt->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, $decimalPlaces); $fmt->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $decimalPlaces); - $result = $fmt->format((float)$amount); + $result = $fmt->format((float) $amount); if (true === $coloured) { if ($amount > 0) { @@ -112,7 +113,8 @@ class Amount /** * @return string * @throws FireflyException - * @throws JsonException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function getCurrencyCode(): string { @@ -131,11 +133,13 @@ class Amount } $cache->store(config('firefly.default_currency', 'EUR')); - return (string)config('firefly.default_currency', 'EUR'); + return (string) config('firefly.default_currency', 'EUR'); } /** * @return TransactionCurrency + * @throws FireflyException + * @throws JsonException */ public function getDefaultCurrency(): TransactionCurrency { @@ -150,7 +154,6 @@ class Amount * * @return TransactionCurrency * @throws FireflyException - * @throws JsonException */ public function getDefaultCurrencyByUser(User $user): TransactionCurrency { @@ -164,7 +167,7 @@ class Amount $currencyPrefStr = $currencyPreference ? $currencyPreference->data : 'EUR'; // at this point the currency preference could be encrypted, if coming from an old version. - $currencyCode = $this->tryDecrypt((string)$currencyPrefStr); + $currencyCode = $this->tryDecrypt((string) $currencyPrefStr); // could still be json encoded: /** @var TransactionCurrency|null $currency */ @@ -221,6 +224,7 @@ class Amount /** * @return array + * @throws FireflyException */ private function getLocaleInfo(): array { diff --git a/app/Support/Authentication/RemoteUserGuard.php b/app/Support/Authentication/RemoteUserGuard.php index 81846576f3..c77435c832 100644 --- a/app/Support/Authentication/RemoteUserGuard.php +++ b/app/Support/Authentication/RemoteUserGuard.php @@ -81,7 +81,7 @@ class RemoteUserGuard implements Guard $header = config('auth.guard_email'); if (null !== $header) { - $emailAddress = (string)(request()->server($header) ?? null); + $emailAddress = (string) (request()->server($header) ?? null); $preference = app('preferences')->getForUser($retrievedUser, 'remote_guard_alt_email'); if (null !== $emailAddress && null === $preference && $emailAddress !== $userID) { @@ -93,6 +93,14 @@ class RemoteUserGuard implements Guard $this->user = $retrievedUser; } + /** + * @inheritDoc + */ + public function guest(): bool + { + return !$this->check(); + } + /** * @inheritDoc */ @@ -104,9 +112,17 @@ class RemoteUserGuard implements Guard /** * @inheritDoc */ - public function guest(): bool + public function user(): ?User { - return !$this->check(); + return $this->user; + } + + /** + * @inheritDoc + */ + public function hasUser() + { + // TODO: Implement hasUser() method. } /** @@ -125,14 +141,6 @@ class RemoteUserGuard implements Guard $this->user = $user; } - /** - * @inheritDoc - */ - public function user(): ?User - { - return $this->user; - } - /** * @inheritDoc */ diff --git a/app/Support/Authentication/RemoteUserProvider.php b/app/Support/Authentication/RemoteUserProvider.php index 4a660214ca..7d152665d2 100644 --- a/app/Support/Authentication/RemoteUserProvider.php +++ b/app/Support/Authentication/RemoteUserProvider.php @@ -57,10 +57,10 @@ class RemoteUserProvider implements UserProvider Log::debug(sprintf('User with email "%s" not found. Will be created.', $identifier)); $user = User::create( [ - 'blocked' => false, + 'blocked' => false, 'blocked_code' => null, - 'email' => $identifier, - 'password' => bcrypt(Str::random(64)), + 'email' => $identifier, + 'password' => bcrypt(Str::random(64)), ] ); } diff --git a/app/Support/Binder/CLIToken.php b/app/Support/Binder/CLIToken.php index 4e14c59d0f..7877c20280 100644 --- a/app/Support/Binder/CLIToken.php +++ b/app/Support/Binder/CLIToken.php @@ -49,7 +49,7 @@ class CLIToken implements BinderInterface $users = $repository->all(); // check for static token - if ($value === config('firefly.static_cron_token') && 32 === strlen((string)config('firefly.static_cron_token'))) { + if ($value === config('firefly.static_cron_token') && 32 === strlen((string) config('firefly.static_cron_token'))) { return $value; } diff --git a/app/Support/Binder/EitherConfigKey.php b/app/Support/Binder/EitherConfigKey.php index 69bbfa38f3..476ac8613e 100644 --- a/app/Support/Binder/EitherConfigKey.php +++ b/app/Support/Binder/EitherConfigKey.php @@ -53,7 +53,7 @@ class EitherConfigKey // triggers and actions: 'firefly.rule-actions', 'firefly.context-rule-actions', - 'firefly.search.operators' + 'search.operators', ]; /** diff --git a/app/Support/Binder/TagList.php b/app/Support/Binder/TagList.php index c5440988ee..daa29e434e 100644 --- a/app/Support/Binder/TagList.php +++ b/app/Support/Binder/TagList.php @@ -69,7 +69,7 @@ class TagList implements BinderInterface if (in_array(strtolower($tag->tag), $list, true)) { return true; } - if (in_array((string)$tag->id, $list, true)) { + if (in_array((string) $tag->id, $list, true)) { return true; } diff --git a/app/Support/Binder/TagOrId.php b/app/Support/Binder/TagOrId.php index cbf631ce26..42e33edd0e 100644 --- a/app/Support/Binder/TagOrId.php +++ b/app/Support/Binder/TagOrId.php @@ -48,7 +48,7 @@ class TagOrId implements BinderInterface $result = $repository->findByTag($value); if (null === $result) { - $result = $repository->find((int)$value); + $result = $repository->find((int) $value); } if (null !== $result) { return $result; diff --git a/app/Support/CacheProperties.php b/app/Support/CacheProperties.php index 0d95c386a5..37a1db4cb3 100644 --- a/app/Support/CacheProperties.php +++ b/app/Support/CacheProperties.php @@ -95,7 +95,7 @@ class CacheProperties $content .= json_encode($property, JSON_THROW_ON_ERROR); } catch (JsonException $e) { // @ignoreException - $content .= hash('sha256', (string)time()); + $content .= hash('sha256', (string) time()); } } $this->hash = substr(hash('sha256', $content), 0, 16); diff --git a/app/Support/Chart/Budget/FrontpageChartGenerator.php b/app/Support/Chart/Budget/FrontpageChartGenerator.php index e2d5dc435f..0163a4b30d 100644 --- a/app/Support/Chart/Budget/FrontpageChartGenerator.php +++ b/app/Support/Chart/Budget/FrontpageChartGenerator.php @@ -64,9 +64,9 @@ class FrontpageChartGenerator { $budgets = $this->budgetRepository->getActiveBudgets(); $data = [ - ['label' => (string)trans('firefly.spent_in_budget'), 'entries' => [], 'type' => 'bar'], - ['label' => (string)trans('firefly.left_to_spend'), 'entries' => [], 'type' => 'bar'], - ['label' => (string)trans('firefly.overspent'), 'entries' => [], 'type' => 'bar'], + ['label' => (string) trans('firefly.spent_in_budget'), 'entries' => [], 'type' => 'bar'], + ['label' => (string) trans('firefly.left_to_spend'), 'entries' => [], 'type' => 'bar'], + ['label' => (string) trans('firefly.overspent'), 'entries' => [], 'type' => 'bar'], ]; // loop al budgets: @@ -158,7 +158,7 @@ class FrontpageChartGenerator /** @var array $entry */ foreach ($spent as $entry) { // only spent the entry where the entry's currency matches the budget limit's currency - if ($entry['currency_id'] === (int)$limit->transaction_currency_id) { + if ($entry['currency_id'] === (int) $limit->transaction_currency_id) { $data = $this->processRow($data, $budget, $limit, $entry); } } @@ -187,8 +187,8 @@ class FrontpageChartGenerator '%s (%s) (%s - %s)', $budget->name, $entry['currency_name'], - $limit->start_date->formatLocalized($this->monthAndDayFormat), - $limit->end_date->formatLocalized($this->monthAndDayFormat) + $limit->start_date->isoFormat($this->monthAndDayFormat), + $limit->end_date->isoFormat($this->monthAndDayFormat) ); } $sumSpent = bcmul($entry['sum'], '-1'); // spent @@ -220,6 +220,7 @@ class FrontpageChartGenerator * A basic setter for the user. Also updates the repositories with the right user. * * @param User $user + * @throws \FireflyIII\Exceptions\FireflyException */ public function setUser(User $user): void { @@ -229,6 +230,6 @@ class FrontpageChartGenerator $this->opsRepository->setUser($user); $locale = app('steam')->getLocale(); - $this->monthAndDayFormat = (string)trans('config.month_and_day', [], $locale); + $this->monthAndDayFormat = (string) trans('config.month_and_day_js', [], $locale); } } diff --git a/app/Support/Chart/Category/FrontpageChartGenerator.php b/app/Support/Chart/Category/FrontpageChartGenerator.php index 9aeb91d2de..d12cf4c633 100644 --- a/app/Support/Chart/Category/FrontpageChartGenerator.php +++ b/app/Support/Chart/Category/FrontpageChartGenerator.php @@ -114,8 +114,8 @@ class FrontpageChartGenerator $tempData[] = [ 'name' => $category->name, 'sum' => $currency['sum'], - 'sum_float' => round((float)$currency['sum'], $currency['currency_decimal_places']), - 'currency_id' => (int)$currency['currency_id'], + 'sum_float' => round((float) $currency['sum'], $currency['currency_decimal_places']), + 'currency_id' => (int) $currency['currency_id'], ]; } @@ -127,7 +127,7 @@ class FrontpageChartGenerator */ private function addCurrency(array $currency): void { - $currencyId = (int)$currency['currency_id']; + $currencyId = (int) $currency['currency_id']; $this->currencies[$currencyId] = $this->currencies[$currencyId] ?? [ 'currency_id' => $currencyId, @@ -152,8 +152,8 @@ class FrontpageChartGenerator $tempData[] = [ 'name' => trans('firefly.no_category'), 'sum' => $currency['sum'], - 'sum_float' => round((float)$currency['sum'], $currency['currency_decimal_places'] ?? 2), - 'currency_id' => (int)$currency['currency_id'], + 'sum_float' => round((float) $currency['sum'], $currency['currency_decimal_places'] ?? 2), + 'currency_id' => (int) $currency['currency_id'], ]; } @@ -175,7 +175,7 @@ class FrontpageChartGenerator foreach ($this->currencies as $currencyId => $currency) { $key = sprintf('spent-%d', $currencyId); $return[$key] = [ - 'label' => sprintf('%s (%s)', (string)trans('firefly.spent'), $currency['currency_name']), + 'label' => sprintf('%s (%s)', (string) trans('firefly.spent'), $currency['currency_name']), 'type' => 'bar', 'currency_symbol' => $currency['currency_symbol'], 'entries' => $names, diff --git a/app/Support/Chart/Category/WholePeriodChartGenerator.php b/app/Support/Chart/Category/WholePeriodChartGenerator.php index ffd0a4ce9d..867cb3f337 100644 --- a/app/Support/Chart/Category/WholePeriodChartGenerator.php +++ b/app/Support/Chart/Category/WholePeriodChartGenerator.php @@ -77,14 +77,14 @@ class WholePeriodChartGenerator $code = $currency['currency_code']; $name = $currency['currency_name']; $chartData[sprintf('spent-in-%s', $code)] = [ - 'label' => (string)trans('firefly.box_spent_in_currency', ['currency' => $name]), + 'label' => (string) trans('firefly.box_spent_in_currency', ['currency' => $name]), 'entries' => [], 'type' => 'bar', 'backgroundColor' => 'rgba(219, 68, 55, 0.5)', // red ]; $chartData[sprintf('earned-in-%s', $code)] = [ - 'label' => (string)trans('firefly.box_earned_in_currency', ['currency' => $name]), + 'label' => (string) trans('firefly.box_earned_in_currency', ['currency' => $name]), 'entries' => [], 'type' => 'bar', 'backgroundColor' => 'rgba(0, 141, 76, 0.5)', // green @@ -105,8 +105,8 @@ class WholePeriodChartGenerator $earnedInfoKey = sprintf('earned-in-%s', $code); $spentAmount = $spent[$key][$currencyId]['sum'] ?? '0'; $earnedAmount = $earned[$key][$currencyId]['sum'] ?? '0'; - $chartData[$spentInfoKey]['entries'][$label] = round((float)$spentAmount, $currency['currency_decimal_places']); - $chartData[$earnedInfoKey]['entries'][$label] = round((float)$earnedAmount, $currency['currency_decimal_places']); + $chartData[$spentInfoKey]['entries'][$label] = round((float) $spentAmount, $currency['currency_decimal_places']); + $chartData[$earnedInfoKey]['entries'][$label] = round((float) $earnedAmount, $currency['currency_decimal_places']); } $current = app('navigation')->addPeriod($current, $step, 0); } diff --git a/app/Support/Cronjobs/AbstractCronjob.php b/app/Support/Cronjobs/AbstractCronjob.php index 1783889cb9..1625a45726 100644 --- a/app/Support/Cronjobs/AbstractCronjob.php +++ b/app/Support/Cronjobs/AbstractCronjob.php @@ -32,10 +32,10 @@ use Carbon\Carbon; */ abstract class AbstractCronjob { - public bool $jobErrored; - public bool $jobFired; - public bool $jobSucceeded; - public ?string $message; + public bool $jobErrored; + public bool $jobFired; + public bool $jobSucceeded; + public ?string $message; public int $timeBetweenRuns = 43200; protected Carbon $date; protected bool $force; diff --git a/app/Support/Cronjobs/AutoBudgetCronjob.php b/app/Support/Cronjobs/AutoBudgetCronjob.php index ada8681278..615d5b5789 100644 --- a/app/Support/Cronjobs/AutoBudgetCronjob.php +++ b/app/Support/Cronjobs/AutoBudgetCronjob.php @@ -42,7 +42,7 @@ class AutoBudgetCronjob extends AbstractCronjob { /** @var Configuration $config */ $config = app('fireflyconfig')->get('last_ab_job', 0); - $lastTime = (int)$config->data; + $lastTime = (int) $config->data; $diff = time() - $lastTime; $diffForHumans = Carbon::now()->diffForHumans(Carbon::createFromTimestamp($lastTime), null, true); if (0 === $lastTime) { @@ -89,7 +89,7 @@ class AutoBudgetCronjob extends AbstractCronjob $this->jobSucceeded = true; $this->message = 'Auto-budget cron job fired successfully.'; - app('fireflyconfig')->set('last_ab_job', (int)$this->date->format('U')); + app('fireflyconfig')->set('last_ab_job', (int) $this->date->format('U')); Log::info('Done with auto budget cron job task.'); } } diff --git a/app/Support/Cronjobs/BillWarningCronjob.php b/app/Support/Cronjobs/BillWarningCronjob.php new file mode 100644 index 0000000000..79ce30f5af --- /dev/null +++ b/app/Support/Cronjobs/BillWarningCronjob.php @@ -0,0 +1,104 @@ +. + */ + +declare(strict_types=1); + +namespace FireflyIII\Support\Cronjobs; + +use Carbon\Carbon; +use FireflyIII\Exceptions\FireflyException; +use FireflyIII\Jobs\WarnAboutBills; +use FireflyIII\Models\Configuration; +use Log; + +/** + * Class BillWarningCronjob + */ +class BillWarningCronjob extends AbstractCronjob +{ + /** + * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface + */ + public function fire(): void + { + Log::debug(sprintf('Now in %s', __METHOD__)); + /** @var Configuration $config */ + $config = app('fireflyconfig')->get('last_bw_job', 0); + $lastTime = (int) $config->data; + $diff = time() - $lastTime; + $diffForHumans = Carbon::now()->diffForHumans(Carbon::createFromTimestamp($lastTime), null, true); + + if (0 === $lastTime) { + Log::info('The bill warning 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 bill warning cron-job has fired.', $diffForHumans)); + if (false === $this->force) { + Log::info('The cron-job will not fire now.'); + $this->message = sprintf('It has been %s since the bill warning cron-job has fired. It will not fire now.', $diffForHumans); + $this->jobFired = false; + $this->jobErrored = false; + $this->jobSucceeded = false; + + return; + } + + // fire job regardless. + if (true === $this->force) { + Log::info('Execution of the bill warning cron-job has been FORCED.'); + } + } + + if ($lastTime > 0 && $diff > 43200) { + Log::info(sprintf('It has been %s since the bill warning cron-job has fired. It will fire now!', $diffForHumans)); + } + + $this->fireWarnings(); + + app('preferences')->mark(); + } + + /** + * + */ + private function fireWarnings(): void + { + Log::info(sprintf('Will now fire bill warning job task for date "%s".', $this->date->format('Y-m-d H:i:s'))); + /** @var WarnAboutBills $job */ + $job = app(WarnAboutBills::class); + $job->setDate($this->date); + $job->setForce($this->force); + $job->handle(); + + // get stuff from job: + $this->jobFired = true; + $this->jobErrored = false; + $this->jobSucceeded = true; + $this->message = 'Bill warning cron job fired successfully.'; + + app('fireflyconfig')->set('last_bw_job', (int) $this->date->format('U')); + Log::info(sprintf('Marked the last time this job has run as "%s" (%d)', $this->date->format('Y-m-d H:i:s'), (int) $this->date->format('U'))); + Log::info('Done with bill warning cron job task.'); + } +} diff --git a/app/Support/Cronjobs/RecurringCronjob.php b/app/Support/Cronjobs/RecurringCronjob.php index 665a15bc27..b71bdf4f3d 100644 --- a/app/Support/Cronjobs/RecurringCronjob.php +++ b/app/Support/Cronjobs/RecurringCronjob.php @@ -36,13 +36,15 @@ class RecurringCronjob extends AbstractCronjob { /** * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function fire(): void { Log::debug(sprintf('Now in %s', __METHOD__)); /** @var Configuration $config */ $config = app('fireflyconfig')->get('last_rt_job', 0); - $lastTime = (int)$config->data; + $lastTime = (int) $config->data; $diff = time() - $lastTime; $diffForHumans = Carbon::now()->diffForHumans(Carbon::createFromTimestamp($lastTime), null, true); @@ -95,8 +97,8 @@ class RecurringCronjob extends AbstractCronjob $this->jobSucceeded = true; $this->message = 'Recurring transactions cron job fired successfully.'; - app('fireflyconfig')->set('last_rt_job', (int)$this->date->format('U')); - Log::info(sprintf('Marked the last time this job has run as "%s" (%d)', $this->date->format('Y-m-d H:i:s'), (int)$this->date->format('U'))); + app('fireflyconfig')->set('last_rt_job', (int) $this->date->format('U')); + Log::info(sprintf('Marked the last time this job has run as "%s" (%d)', $this->date->format('Y-m-d H:i:s'), (int) $this->date->format('U'))); Log::info('Done with recurring cron job task.'); } } diff --git a/app/Support/Domain.php b/app/Support/Domain.php index 94beefa05e..ced5cd7ae7 100644 --- a/app/Support/Domain.php +++ b/app/Support/Domain.php @@ -50,6 +50,6 @@ class Domain */ public static function getRuleTriggers(): array { - return array_keys(config('firefly.search.operators')); + return array_keys(config('search.operators')); } } diff --git a/app/Support/ExpandedForm.php b/app/Support/ExpandedForm.php index 73651c9fd9..8a90790dda 100644 --- a/app/Support/ExpandedForm.php +++ b/app/Support/ExpandedForm.php @@ -214,7 +214,7 @@ class ExpandedForm $fields = ['title', 'name', 'description']; /** @var Eloquent $entry */ foreach ($set as $entry) { - $entryId = (int)$entry->id; // @phpstan-ignore-line + $entryId = (int) $entry->id; // @phpstan-ignore-line $current = $entry->toArray(); $title = null; foreach ($fields as $field) { diff --git a/app/Support/Export/ExportDataGenerator.php b/app/Support/Export/ExportDataGenerator.php index 08521111e0..683572f018 100644 --- a/app/Support/Export/ExportDataGenerator.php +++ b/app/Support/Export/ExportDataGenerator.php @@ -590,6 +590,8 @@ class ExportDataGenerator /** * @return string * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ private function exportTags(): string { diff --git a/app/Support/FireflyConfig.php b/app/Support/FireflyConfig.php index eb9b9c0ce2..c7aeeadac0 100644 --- a/app/Support/FireflyConfig.php +++ b/app/Support/FireflyConfig.php @@ -69,7 +69,7 @@ class FireflyConfig try { /** @var Configuration|null $config */ $config = Configuration::where('name', $name)->first(['id', 'name', 'data']); - } catch (QueryException | Exception $e) { // @phpstan-ignore-line + } catch (QueryException|Exception $e) { // @phpstan-ignore-line throw new FireflyException(sprintf('Could not poll the database: %s', $e->getMessage())); } @@ -96,7 +96,7 @@ class FireflyConfig { try { $config = Configuration::whereName($name)->whereNull('deleted_at')->first(); - } catch (QueryException | Exception $e) { // @phpstan-ignore-line + } catch (QueryException|Exception $e) { // @phpstan-ignore-line $item = new Configuration; $item->name = $name; $item->data = $value; diff --git a/app/Support/Form/AccountForm.php b/app/Support/Form/AccountForm.php index c51d2770dc..740a2c6896 100644 --- a/app/Support/Form/AccountForm.php +++ b/app/Support/Form/AccountForm.php @@ -56,8 +56,8 @@ class AccountForm $repository = $this->getAccountRepository(); $grouped = $this->getAccountsGrouped($types, $repository); $cash = $repository->getCashAccount(); - $key = (string)trans('firefly.cash_account_type'); - $grouped[$key][$cash->id] = sprintf('(%s)', (string)trans('firefly.cash')); + $key = (string) trans('firefly.cash_account_type'); + $grouped[$key][$cash->id] = sprintf('(%s)', (string) trans('firefly.cash')); return $this->select($name, $grouped, $value, $options); } @@ -73,7 +73,7 @@ class AccountForm /** @var Account $account */ foreach ($accountList as $account) { - $role = (string)$repository->getMetaValue($account, 'account_role'); + $role = (string) $repository->getMetaValue($account, 'account_role'); if (in_array($account->accountType->type, $liabilityTypes, true)) { $role = sprintf('l_%s', $account->accountType->type); } elseif ('' === $role) { @@ -85,7 +85,7 @@ class AccountForm $role = 'no_account_type'; } } - $key = (string)trans(sprintf('firefly.opt_group_%s', $role)); + $key = (string) trans(sprintf('firefly.opt_group_%s', $role)); $grouped[$key][$account->id] = $account->name; } @@ -108,8 +108,8 @@ class AccountForm $grouped = $this->getAccountsGrouped($types, $repository); $cash = $repository->getCashAccount(); - $key = (string)trans('firefly.cash_account_type'); - $grouped[$key][$cash->id] = sprintf('(%s)', (string)trans('firefly.cash')); + $key = (string) trans('firefly.cash_account_type'); + $grouped[$key][$cash->id] = sprintf('(%s)', (string) trans('firefly.cash')); return $this->select($name, $grouped, $value, $options); } diff --git a/app/Support/Form/CurrencyForm.php b/app/Support/Form/CurrencyForm.php index 619ed23cf5..042478a958 100644 --- a/app/Support/Form/CurrencyForm.php +++ b/app/Support/Form/CurrencyForm.php @@ -77,7 +77,7 @@ class CurrencyForm $preFilled = []; } $key = 'amount_currency_id_' . $name; - $sentCurrencyId = array_key_exists($key, $preFilled) ? (int)$preFilled[$key] : $defaultCurrency->id; + $sentCurrencyId = array_key_exists($key, $preFilled) ? (int) $preFilled[$key] : $defaultCurrency->id; Log::debug(sprintf('Sent currency ID is %d', $sentCurrencyId)); @@ -92,7 +92,7 @@ class CurrencyForm // make sure value is formatted nicely: if (null !== $value && '' !== $value) { - $value = round((float)$value, $defaultCurrency->decimal_places); + $value = round((float) $value, $defaultCurrency->decimal_places); } try { $html = view('form.' . $view, compact('defaultCurrency', 'currencies', 'classes', 'name', 'label', 'value', 'options'))->render(); @@ -146,7 +146,7 @@ class CurrencyForm $preFilled = []; } $key = 'amount_currency_id_' . $name; - $sentCurrencyId = array_key_exists($key, $preFilled) ? (int)$preFilled[$key] : $defaultCurrency->id; + $sentCurrencyId = array_key_exists($key, $preFilled) ? (int) $preFilled[$key] : $defaultCurrency->id; Log::debug(sprintf('Sent currency ID is %d', $sentCurrencyId)); @@ -161,7 +161,7 @@ class CurrencyForm // make sure value is formatted nicely: if (null !== $value && '' !== $value) { - $value = round((float)$value, $defaultCurrency->decimal_places); + $value = round((float) $value, $defaultCurrency->decimal_places); } try { $html = view('form.' . $view, compact('defaultCurrency', 'currencies', 'classes', 'name', 'label', 'value', 'options'))->render(); @@ -215,7 +215,7 @@ class CurrencyForm // get all currencies: $list = $currencyRepos->get(); $array = [ - 0 => (string)trans('firefly.no_currency'), + 0 => (string) trans('firefly.no_currency'), ]; /** @var TransactionCurrency $currency */ foreach ($list as $currency) { diff --git a/app/Support/Form/FormSupport.php b/app/Support/Form/FormSupport.php index df9f3cd928..0abf922be0 100644 --- a/app/Support/Form/FormSupport.php +++ b/app/Support/Form/FormSupport.php @@ -76,7 +76,7 @@ trait FormSupport } $name = str_replace('[]', '', $name); - return (string)trans('form.' . $name); + return (string) trans('form.' . $name); } /** diff --git a/app/Support/Form/PiggyBankForm.php b/app/Support/Form/PiggyBankForm.php index e4165cb49b..3d836661be 100644 --- a/app/Support/Form/PiggyBankForm.php +++ b/app/Support/Form/PiggyBankForm.php @@ -50,7 +50,7 @@ class PiggyBankForm /** @var PiggyBankRepositoryInterface $repository */ $repository = app(PiggyBankRepositoryInterface::class); $piggyBanks = $repository->getPiggyBanksWithAmount(); - $title = (string)trans('firefly.default_group_title_name'); + $title = (string) trans('firefly.default_group_title_name'); $array = []; $subList = [ 0 => [ @@ -58,7 +58,7 @@ class PiggyBankForm 'title' => $title, ], 'piggies' => [ - (string)trans('firefly.none_in_select_list'), + (string) trans('firefly.none_in_select_list'), ], ], ]; diff --git a/app/Support/Form/RuleForm.php b/app/Support/Form/RuleForm.php index a757d5b983..87f0b29ff9 100644 --- a/app/Support/Form/RuleForm.php +++ b/app/Support/Form/RuleForm.php @@ -76,11 +76,11 @@ class RuleForm // get all currencies: $list = $groupRepos->get(); $array = [ - 0 => (string)trans('firefly.none_in_select_list'), + 0 => (string) trans('firefly.none_in_select_list'), ]; /** @var RuleGroup $group */ foreach ($list as $group) { - if (array_key_exists('hidden', $options) && (int)$options['hidden'] !== $group->id) { + if (array_key_exists('hidden', $options) && (int) $options['hidden'] !== $group->id) { $array[$group->id] = $group->title; } } diff --git a/app/Support/Http/Controllers/AugumentData.php b/app/Support/Http/Controllers/AugumentData.php index 644d5d39a7..8cf762f790 100644 --- a/app/Support/Http/Controllers/AugumentData.php +++ b/app/Support/Http/Controllers/AugumentData.php @@ -123,7 +123,7 @@ trait AugumentData $return = []; foreach ($accountIds as $combinedId) { $parts = explode('-', $combinedId); - $accountId = (int)$parts[0]; + $accountId = (int) $parts[0]; if (array_key_exists($accountId, $grouped)) { $return[$accountId] = $grouped[$accountId][0]['name']; } @@ -152,7 +152,7 @@ trait AugumentData $return[$budgetId] = $grouped[$budgetId][0]['name']; } } - $return[0] = (string)trans('firefly.no_budget'); + $return[0] = (string) trans('firefly.no_budget'); return $return; } @@ -173,12 +173,12 @@ trait AugumentData $return = []; foreach ($categoryIds as $combinedId) { $parts = explode('-', $combinedId); - $categoryId = (int)$parts[0]; + $categoryId = (int) $parts[0]; if (array_key_exists($categoryId, $grouped)) { $return[$categoryId] = $grouped[$categoryId][0]['name']; } } - $return[0] = (string)trans('firefly.no_category'); + $return[0] = (string) trans('firefly.no_category'); return $return; } @@ -191,7 +191,6 @@ trait AugumentData * @param Carbon $end * * @return Collection - * @throws JsonException */ protected function getLimits(Budget $budget, Carbon $start, Carbon $end): Collection // get data + augment with info { @@ -222,7 +221,7 @@ trait AugumentData $currentStart = clone $entry->start_date; $currentEnd = clone $entry->end_date; $expenses = $opsRepository->sumExpenses($currentStart, $currentEnd, null, $budgetCollection, $currency); - $spent = $expenses[(int)$currency->id]['sum'] ?? '0'; + $spent = $expenses[(int) $currency->id]['sum'] ?? '0'; $entry->spent = $spent; $limits->push($entry); @@ -285,7 +284,7 @@ trait AugumentData ]; // loop to support multi currency foreach ($journals as $journal) { - $currencyId = (int)$journal['currency_id']; + $currencyId = (int) $journal['currency_id']; // if not set, set to zero: if (!array_key_exists($currencyId, $sum['per_currency'])) { diff --git a/app/Support/Http/Controllers/ChartGeneration.php b/app/Support/Http/Controllers/ChartGeneration.php index 930269e701..0db3129191 100644 --- a/app/Support/Http/Controllers/ChartGeneration.php +++ b/app/Support/Http/Controllers/ChartGeneration.php @@ -77,7 +77,7 @@ trait ChartGeneration /** @var Account $account */ foreach ($accounts as $account) { // See reference nr. 33 - $currency = $repository->find((int)$accountRepos->getMetaValue($account, 'currency_id')); + $currency = $repository->find((int) $accountRepos->getMetaValue($account, 'currency_id')); if (null === $currency) { $currency = $default; } @@ -92,7 +92,7 @@ trait ChartGeneration $previous = array_values($range)[0]; while ($currentStart <= $end) { $format = $currentStart->format('Y-m-d'); - $label = trim($currentStart->formatLocalized((string)trans('config.month_and_day', [], $locale))); + $label = trim($currentStart->isoFormat((string) trans('config.month_and_day_js', [], $locale))); $balance = $range[$format] ?? $previous; $previous = $balance; $currentStart->addDay(); diff --git a/app/Support/Http/Controllers/CreateStuff.php b/app/Support/Http/Controllers/CreateStuff.php index 039d5c853c..4ec6aec618 100644 --- a/app/Support/Http/Controllers/CreateStuff.php +++ b/app/Support/Http/Controllers/CreateStuff.php @@ -83,7 +83,7 @@ trait CreateStuff /** @var AccountRepositoryInterface $repository */ $repository = app(AccountRepositoryInterface::class); $assetAccount = [ - 'name' => (string)trans('firefly.cash_wallet', [], $language), + 'name' => (string) trans('firefly.cash_wallet', [], $language), 'iban' => null, 'account_type_name' => 'asset', 'virtual_balance' => 0, @@ -150,7 +150,7 @@ trait CreateStuff /** @var AccountRepositoryInterface $repository */ $repository = app(AccountRepositoryInterface::class); $savingsAccount = [ - 'name' => (string)trans('firefly.new_savings_account', ['bank_name' => $request->get('bank_name')], $language), + 'name' => (string) trans('firefly.new_savings_account', ['bank_name' => $request->get('bank_name')], $language), 'iban' => null, 'account_type_name' => 'asset', 'account_type_id' => null, diff --git a/app/Support/Http/Controllers/GetConfigurationData.php b/app/Support/Http/Controllers/GetConfigurationData.php index eb473a1f47..dd931499cb 100644 --- a/app/Support/Http/Controllers/GetConfigurationData.php +++ b/app/Support/Http/Controllers/GetConfigurationData.php @@ -52,7 +52,7 @@ trait GetConfigurationData E_COMPILE_ERROR | E_RECOVERABLE_ERROR | E_ERROR | E_CORE_ERROR => 'E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR', ]; - return $array[$value] ?? (string)$value; + return $array[$value] ?? (string) $value; } /** @@ -72,7 +72,7 @@ trait GetConfigurationData $currentStep = $options; // get the text: - $currentStep['intro'] = (string)trans('intro.' . $route . '_' . $key); + $currentStep['intro'] = (string) trans('intro.' . $route . '_' . $key); // save in array: $steps[] = $currentStep; @@ -88,17 +88,19 @@ trait GetConfigurationData * * @return array * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ protected function getDateRangeConfig(): array // get configuration + get preferences. { - $viewRange = (string)app('preferences')->get('viewRange', '1M')->data; + $viewRange = (string) app('preferences')->get('viewRange', '1M')->data; /** @var Carbon $start */ $start = session('start'); /** @var Carbon $end */ $end = session('end'); /** @var Carbon $first */ $first = session('first'); - $title = sprintf('%s - %s', $start->formatLocalized($this->monthAndDayFormat), $end->formatLocalized($this->monthAndDayFormat)); + $title = sprintf('%s - %s', $start->isoFormat($this->monthAndDayFormat), $end->isoFormat($this->monthAndDayFormat)); $isCustom = true === session('is_custom_range', false); $today = today(config('app.timezone')); $ranges = [ @@ -132,31 +134,31 @@ trait GetConfigurationData /** @var Carbon $todayEnd */ $todayEnd = app('navigation')->endOfPeriod($todayStart, $viewRange); if ($todayStart->ne($start) || $todayEnd->ne($end)) { - $ranges[ucfirst((string)trans('firefly.today'))] = [$todayStart, $todayEnd]; + $ranges[ucfirst((string) trans('firefly.today'))] = [$todayStart, $todayEnd]; } // last seven days: $seven = Carbon::now()->subDays(7); - $index = (string)trans('firefly.last_seven_days'); + $index = (string) trans('firefly.last_seven_days'); $ranges[$index] = [$seven, new Carbon]; // last 30 days: $thirty = Carbon::now()->subDays(30); - $index = (string)trans('firefly.last_thirty_days'); + $index = (string) trans('firefly.last_thirty_days'); $ranges[$index] = [$thirty, new Carbon]; // everything - $index = (string)trans('firefly.everything'); + $index = (string) trans('firefly.everything'); $ranges[$index] = [$first, new Carbon]; return [ 'title' => $title, 'configuration' => [ - 'apply' => (string)trans('firefly.apply'), - 'cancel' => (string)trans('firefly.cancel'), - 'from' => (string)trans('firefly.from'), - 'to' => (string)trans('firefly.to'), - 'customRange' => (string)trans('firefly.customRange'), + 'apply' => (string) trans('firefly.apply'), + 'cancel' => (string) trans('firefly.cancel'), + 'from' => (string) trans('firefly.from'), + 'to' => (string) trans('firefly.to'), + 'customRange' => (string) trans('firefly.customRange'), 'start' => $start->format('Y-m-d'), 'end' => $end->format('Y-m-d'), 'ranges' => $ranges, @@ -187,7 +189,7 @@ trait GetConfigurationData $currentStep = $options; // get the text: - $currentStep['intro'] = (string)trans('intro.' . $route . '_' . $specificPage . '_' . $key); + $currentStep['intro'] = (string) trans('intro.' . $route . '_' . $specificPage . '_' . $key); // save in array: $steps[] = $currentStep; @@ -205,7 +207,7 @@ trait GetConfigurationData protected function verifyRecurringCronJob(): void { $config = app('fireflyconfig')->get('last_rt_job', 0); - $lastTime = (int)$config->data; + $lastTime = (int) $config->data; $now = time(); Log::debug(sprintf('verifyRecurringCronJob: last time is %d ("%s"), now is %d', $lastTime, $config->data, $now)); if (0 === $lastTime) { diff --git a/app/Support/Http/Controllers/ModelInformation.php b/app/Support/Http/Controllers/ModelInformation.php index 27cb567527..9164a6098f 100644 --- a/app/Support/Http/Controllers/ModelInformation.php +++ b/app/Support/Http/Controllers/ModelInformation.php @@ -83,9 +83,9 @@ trait ModelInformation $mortgage = $repository->getAccountTypeByType(AccountType::MORTGAGE); /** @noinspection NullPointerExceptionInspection */ $liabilityTypes = [ - $debt->id => (string)trans(sprintf('firefly.account_type_%s', AccountType::DEBT)), - $loan->id => (string)trans(sprintf('firefly.account_type_%s', AccountType::LOAN)), - $mortgage->id => (string)trans(sprintf('firefly.account_type_%s', AccountType::MORTGAGE)), + $debt->id => (string) trans(sprintf('firefly.account_type_%s', AccountType::DEBT)), + $loan->id => (string) trans(sprintf('firefly.account_type_%s', AccountType::LOAN)), + $mortgage->id => (string) trans(sprintf('firefly.account_type_%s', AccountType::MORTGAGE)), ]; asort($liabilityTypes); @@ -100,7 +100,7 @@ trait ModelInformation { $roles = []; foreach (config('firefly.accountRoles') as $role) { - $roles[$role] = (string)trans(sprintf('firefly.account_role_%s', $role)); + $roles[$role] = (string) trans(sprintf('firefly.account_role_%s', $role)); } return $roles; @@ -116,12 +116,12 @@ trait ModelInformation protected function getTriggersForBill(Bill $bill): array // get info and augument { // See reference nr. 39 - $operators = config('firefly.search.operators'); + $operators = config('search.operators'); $triggers = []; foreach ($operators as $key => $operator) { if ('user_action' !== $key && false === $operator['alias']) { - $triggers[$key] = (string)trans(sprintf('firefly.rule_trigger_%s_choice', $key)); + $triggers[$key] = (string) trans(sprintf('firefly.rule_trigger_%s_choice', $key)); } } asort($triggers); @@ -130,8 +130,8 @@ trait ModelInformation $billTriggers = ['currency_is', 'amount_more', 'amount_less', 'description_contains']; $values = [ $bill->transactionCurrency()->first()->name, - round((float)$bill->amount_min, 24), - round((float)$bill->amount_max, 24), + round((float) $bill->amount_min, 24), + round((float) $bill->amount_max, 24), $bill->name, ]; foreach ($billTriggers as $index => $trigger) { @@ -168,12 +168,12 @@ trait ModelInformation private function getTriggersForJournal(TransactionJournal $journal): array { // See reference nr. 40 - $operators = config('firefly.search.operators'); + $operators = config('search.operators'); $triggers = []; foreach ($operators as $key => $operator) { if ('user_action' !== $key && false === $operator['alias']) { - $triggers[$key] = (string)trans(sprintf('firefly.rule_trigger_%s_choice', $key)); + $triggers[$key] = (string) trans(sprintf('firefly.rule_trigger_%s_choice', $key)); } } asort($triggers); diff --git a/app/Support/Http/Controllers/PeriodOverview.php b/app/Support/Http/Controllers/PeriodOverview.php index f67ed67074..9ae5ce2700 100644 --- a/app/Support/Http/Controllers/PeriodOverview.php +++ b/app/Support/Http/Controllers/PeriodOverview.php @@ -79,7 +79,8 @@ trait PeriodOverview * * @return array * @throws FireflyException - * @throws JsonException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ protected function getAccountPeriodOverview(Account $account, Carbon $start, Carbon $end): array { @@ -93,7 +94,7 @@ trait PeriodOverview $cache->addProperty('account-show-period-entries'); $cache->addProperty($account->id); if ($cache->has()) { - return $cache->get(); + // return $cache->get(); } /** @var array $dates */ $dates = app('navigation')->blockPeriods($start, $end, $range); @@ -183,7 +184,7 @@ trait PeriodOverview $return = []; /** @var array $journal */ foreach ($journals as $journal) { - if ($account->id === (int)$journal['source_account_id']) { + if ($account->id === (int) $journal['source_account_id']) { $return[] = $journal; } } @@ -205,7 +206,7 @@ trait PeriodOverview $return = []; /** @var array $journal */ foreach ($journals as $journal) { - if ($account->id === (int)$journal['destination_account_id']) { + if ($account->id === (int) $journal['destination_account_id']) { $return[] = $journal; } } @@ -224,7 +225,7 @@ trait PeriodOverview $return = []; /** @var array $journal */ foreach ($journals as $journal) { - $currencyId = (int)$journal['currency_id']; + $currencyId = (int) $journal['currency_id']; $foreignCurrencyId = $journal['foreign_currency_id']; if (!array_key_exists($currencyId, $return)) { $return[$currencyId] = [ @@ -245,7 +246,7 @@ trait PeriodOverview $return[$foreignCurrencyId] = [ 'amount' => '0', 'count' => 0, - 'currency_id' => (int)$foreignCurrencyId, + 'currency_id' => (int) $foreignCurrencyId, 'currency_name' => $journal['foreign_currency_name'], 'currency_code' => $journal['foreign_currency_code'], 'currency_symbol' => $journal['foreign_currency_symbol'], @@ -271,7 +272,8 @@ trait PeriodOverview * * @return array * @throws FireflyException - * @throws JsonException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ protected function getCategoryPeriodOverview(Category $category, Carbon $start, Carbon $end): array { @@ -350,7 +352,8 @@ trait PeriodOverview * * @return array * @throws FireflyException - * @throws JsonException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ protected function getNoBudgetPeriodOverview(Carbon $start, Carbon $end): array { @@ -404,7 +407,8 @@ trait PeriodOverview * * @return array * @throws FireflyException - * @throws JsonException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ protected function getNoCategoryPeriodOverview(Carbon $theDate): array { @@ -485,7 +489,8 @@ trait PeriodOverview * * @return array * @throws FireflyException - * @throws JsonException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ protected function getTagPeriodOverview(Tag $tag, Carbon $start, Carbon $end): array // period overview for tags. { @@ -560,7 +565,8 @@ trait PeriodOverview * * @return array * @throws FireflyException - * @throws JsonException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ protected function getTransactionPeriodOverview(string $transactionType, Carbon $start, Carbon $end): array { diff --git a/app/Support/Http/Controllers/RenderPartialViews.php b/app/Support/Http/Controllers/RenderPartialViews.php index a6dec719a8..3990c7bbc2 100644 --- a/app/Support/Http/Controllers/RenderPartialViews.php +++ b/app/Support/Http/Controllers/RenderPartialViews.php @@ -59,10 +59,10 @@ trait RenderPartialViews /** @var BudgetRepositoryInterface $budgetRepository */ $budgetRepository = app(BudgetRepositoryInterface::class); - $budget = $budgetRepository->find((int)$attributes['budgetId']); + $budget = $budgetRepository->find((int) $attributes['budgetId']); $accountRepos = app(AccountRepositoryInterface::class); - $account = $accountRepos->find((int)$attributes['accountId']); + $account = $accountRepos->find((int) $attributes['accountId']); $journals = $popupHelper->balanceForBudget($budget, $account, $attributes); @@ -112,7 +112,7 @@ trait RenderPartialViews /** @var PopupReportInterface $popupHelper */ $popupHelper = app(PopupReportInterface::class); - $budget = $budgetRepository->find((int)$attributes['budgetId']); + $budget = $budgetRepository->find((int) $attributes['budgetId']); if (null === $budget) { $budget = new Budget; } @@ -142,7 +142,7 @@ trait RenderPartialViews /** @var CategoryRepositoryInterface $categoryRepository */ $categoryRepository = app(CategoryRepositoryInterface::class); - $category = $categoryRepository->find((int)$attributes['categoryId']); + $category = $categoryRepository->find((int) $attributes['categoryId']); $journals = $popupHelper->byCategory($category, $attributes); try { @@ -232,7 +232,7 @@ trait RenderPartialViews /** @var PopupReportInterface $popupHelper */ $popupHelper = app(PopupReportInterface::class); - $account = $accountRepository->find((int)$attributes['accountId']); + $account = $accountRepository->find((int) $attributes['accountId']); if (null === $account) { return 'This is an unknown account. Apologies.'; @@ -299,12 +299,12 @@ trait RenderPartialViews protected function getCurrentTriggers(Rule $rule): array // get info from object and present. { // See reference nr. 38 - $operators = config('firefly.search.operators'); + $operators = config('search.operators'); $triggers = []; foreach ($operators as $key => $operator) { if ('user_action' !== $key && false === $operator['alias']) { - $triggers[$key] = (string)trans(sprintf('firefly.rule_trigger_%s_choice', $key)); + $triggers[$key] = (string) trans(sprintf('firefly.rule_trigger_%s_choice', $key)); } } asort($triggers); @@ -354,7 +354,7 @@ trait RenderPartialViews /** @var PopupReportInterface $popupHelper */ $popupHelper = app(PopupReportInterface::class); - $account = $accountRepository->find((int)$attributes['accountId']); + $account = $accountRepository->find((int) $attributes['accountId']); if (null === $account) { return 'This is an unknown category. Apologies.'; diff --git a/app/Support/Http/Controllers/RequestInformation.php b/app/Support/Http/Controllers/RequestInformation.php index f019723da1..a39eb32d21 100644 --- a/app/Support/Http/Controllers/RequestInformation.php +++ b/app/Support/Http/Controllers/RequestInformation.php @@ -73,7 +73,7 @@ trait RequestInformation $triggers[] = [ 'type' => $triggerInfo['type'] ?? '', 'value' => $triggerInfo['value'] ?? '', - 'stop_processing' => 1 === (int)($triggerInfo['stop_processing'] ?? '0'), + 'stop_processing' => 1 === (int) ($triggerInfo['stop_processing'] ?? '0'), ]; } } @@ -86,6 +86,8 @@ trait RequestInformation * * @return bool * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ final protected function hasSeenDemo(): bool // get request info + get preference { @@ -198,11 +200,11 @@ trait RequestInformation final protected function validatePassword(User $user, string $current, string $new): bool //get request info { if (!Hash::check($current, $user->password)) { - throw new ValidationException((string)trans('firefly.invalid_current_password')); + throw new ValidationException((string) trans('firefly.invalid_current_password')); } if ($current === $new) { - throw new ValidationException((string)trans('firefly.should_change')); + throw new ValidationException((string) trans('firefly.should_change')); } return true; diff --git a/app/Support/Http/Controllers/RuleManagement.php b/app/Support/Http/Controllers/RuleManagement.php index bc84899558..2144fa036d 100644 --- a/app/Support/Http/Controllers/RuleManagement.php +++ b/app/Support/Http/Controllers/RuleManagement.php @@ -55,7 +55,7 @@ trait RuleManagement [ 'oldAction' => $oldAction['type'], 'oldValue' => $oldAction['value'], - 'oldChecked' => 1 === (int)($oldAction['stop_processing'] ?? '0'), + 'oldChecked' => 1 === (int) ($oldAction['stop_processing'] ?? '0'), 'count' => $index + 1, ] )->render(); @@ -79,12 +79,12 @@ trait RuleManagement protected function getPreviousTriggers(Request $request): array { // See reference nr. 34 - $operators = config('firefly.search.operators'); + $operators = config('search.operators'); $triggers = []; foreach ($operators as $key => $operator) { if ('user_action' !== $key && false === $operator['alias']) { - $triggers[$key] = (string)trans(sprintf('firefly.rule_trigger_%s_choice', $key)); + $triggers[$key] = (string) trans(sprintf('firefly.rule_trigger_%s_choice', $key)); } } asort($triggers); @@ -100,7 +100,7 @@ trait RuleManagement [ 'oldTrigger' => OperatorQuerySearch::getRootOperator($oldTrigger['type']), 'oldValue' => $oldTrigger['value'], - 'oldChecked' => 1 === (int)($oldTrigger['stop_processing'] ?? '0'), + 'oldChecked' => 1 === (int) ($oldTrigger['stop_processing'] ?? '0'), 'count' => $index + 1, 'triggers' => $triggers, ] @@ -124,13 +124,13 @@ trait RuleManagement protected function parseFromOperators(array $submittedOperators): array { // See reference nr. 35 - $operators = config('firefly.search.operators'); + $operators = config('search.operators'); $renderedEntries = []; $triggers = []; foreach ($operators as $key => $operator) { if ('user_action' !== $key && false === $operator['alias']) { - $triggers[$key] = (string)trans(sprintf('firefly.rule_trigger_%s_choice', $key)); + $triggers[$key] = (string) trans(sprintf('firefly.rule_trigger_%s_choice', $key)); } } asort($triggers); @@ -167,8 +167,8 @@ trait RuleManagement $repository = app(RuleGroupRepositoryInterface::class); if (0 === $repository->count()) { $data = [ - 'title' => (string)trans('firefly.default_rule_group_name'), - 'description' => (string)trans('firefly.default_rule_group_description'), + 'title' => (string) trans('firefly.default_rule_group_name'), + 'description' => (string) trans('firefly.default_rule_group_description'), 'active' => true, ]; diff --git a/app/Support/Http/Controllers/UserNavigation.php b/app/Support/Http/Controllers/UserNavigation.php index a9c3508cf1..72dd2829ee 100644 --- a/app/Support/Http/Controllers/UserNavigation.php +++ b/app/Support/Http/Controllers/UserNavigation.php @@ -54,7 +54,7 @@ trait UserNavigation final protected function getPreviousUri(string $identifier): string { Log::debug(sprintf('Trying to retrieve URL stored under "%s"', $identifier)); - $url = (string)session($identifier); + $url = (string) session($identifier); Log::debug(sprintf('The URL is %s', $url)); return app('steam')->getSafeUrl($url, route('index')); diff --git a/app/Support/Navigation.php b/app/Support/Navigation.php index 437c0e23e0..0e34b48f1d 100644 --- a/app/Support/Navigation.php +++ b/app/Support/Navigation.php @@ -333,6 +333,7 @@ class Navigation * @param Carbon $end * * @return array + * @throws FireflyException */ public function listOfPeriods(Carbon $start, Carbon $end): array { @@ -340,23 +341,23 @@ class Navigation // define period to increment $increment = 'addDay'; $format = $this->preferredCarbonFormat($start, $end); - $displayFormat = (string)trans('config.month_and_day', [], $locale); + $displayFormat = (string) trans('config.month_and_day_js', [], $locale); // increment by month (for year) if ($start->diffInMonths($end) > 1) { $increment = 'addMonth'; - $displayFormat = (string)trans('config.month'); + $displayFormat = (string) trans('config.month_js'); } // increment by year (for multi year) if ($start->diffInMonths($end) > 12) { $increment = 'addYear'; - $displayFormat = (string)trans('config.year'); + $displayFormat = (string) trans('config.year_js'); } $begin = clone $start; $entries = []; while ($begin < $end) { $formatted = $begin->format($format); - $displayed = $begin->formatLocalized($displayFormat); + $displayed = $begin->isoFormat($displayFormat); $entries[$formatted] = $displayed; $begin->$increment(); } @@ -397,23 +398,23 @@ class Navigation { $date = clone $theDate; $formatMap = [ - '1D' => (string)trans('config.specific_day'), - 'daily' => (string)trans('config.specific_day'), - 'custom' => (string)trans('config.specific_day'), - '1W' => (string)trans('config.week_in_year'), - 'week' => (string)trans('config.week_in_year'), - 'weekly' => (string)trans('config.week_in_year'), - '1M' => (string)trans('config.month'), - 'month' => (string)trans('config.month'), - 'monthly' => (string)trans('config.month'), - '1Y' => (string)trans('config.year'), - 'year' => (string)trans('config.year'), - 'yearly' => (string)trans('config.year'), - '6M' => (string)trans('config.half_year'), + '1D' => (string) trans('config.specific_day_js'), + 'daily' => (string) trans('config.specific_day_js'), + 'custom' => (string) trans('config.specific_day_js'), + '1W' => (string) trans('config.week_in_year_js'), + 'week' => (string) trans('config.week_in_year_js'), + 'weekly' => (string) trans('config.week_in_year_js'), + '1M' => (string) trans('config.month_js'), + 'month' => (string) trans('config.month_js'), + 'monthly' => (string) trans('config.month_js'), + '1Y' => (string) trans('config.year_js'), + 'year' => (string) trans('config.year_js'), + 'yearly' => (string) trans('config.year_js'), + '6M' => (string) trans('config.half_year_js'), ]; if (array_key_exists($repeatFrequency, $formatMap)) { - return $date->formatLocalized((string)$formatMap[$repeatFrequency]); + return $date->isoFormat((string) $formatMap[$repeatFrequency]); } if ('3M' === $repeatFrequency || 'quarter' === $repeatFrequency) { $quarter = ceil($theDate->month / 3); @@ -436,17 +437,18 @@ class Navigation * @param Carbon $end * * @return string + * @throws FireflyException */ public function preferredCarbonLocalizedFormat(Carbon $start, Carbon $end): string { $locale = app('steam')->getLocale(); - $format = (string)trans('config.month_and_day', [], $locale); + $format = (string) trans('config.month_and_day_js', [], $locale); if ($start->diffInMonths($end) > 1) { - $format = (string)trans('config.month', [], $locale); + $format = (string) trans('config.month_js', [], $locale); } if ($start->diffInMonths($end) > 12) { - $format = (string)trans('config.year', [], $locale); + $format = (string) trans('config.year_js', [], $locale); } return $format; diff --git a/app/Support/ParseDateString.php b/app/Support/ParseDateString.php index 6d5e41cbe8..b04870b01b 100644 --- a/app/Support/ParseDateString.php +++ b/app/Support/ParseDateString.php @@ -114,7 +114,7 @@ class ParseDateString return new Carbon('1984-09-17'); } // maybe a year, nothing else? - if (4 === strlen($date) && is_numeric($date) && (int)$date > 1000 && (int)$date <= 3000) { + if (4 === strlen($date) && is_numeric($date) && (int) $date > 1000 && (int) $date <= 3000) { return new Carbon(sprintf('%d-01-01', $date)); } @@ -194,7 +194,7 @@ class ParseDateString } $direction = str_starts_with($part, '+') ? 1 : 0; $period = $part[strlen($part) - 1]; - $number = (int)substr($part, 1, -1); + $number = (int) substr($part, 1, -1); if (!array_key_exists($period, $functions[$direction])) { Log::error(sprintf('No method for direction %d and period "%s".', $direction, $period)); continue; diff --git a/app/Support/Report/Budget/BudgetReportGenerator.php b/app/Support/Report/Budget/BudgetReportGenerator.php index 4931d578a7..31f376b78e 100644 --- a/app/Support/Report/Budget/BudgetReportGenerator.php +++ b/app/Support/Report/Budget/BudgetReportGenerator.php @@ -110,8 +110,8 @@ class BudgetReportGenerator */ private function processBudgetExpenses(array $expenses, array $budget): void { - $budgetId = (int)$budget['id']; - $currencyId = (int)$expenses['currency_id']; + $budgetId = (int) $budget['id']; + $currencyId = (int) $expenses['currency_id']; foreach ($budget['transaction_journals'] as $journal) { $sourceAccountId = $journal['source_account_id']; @@ -167,7 +167,7 @@ class BudgetReportGenerator */ private function processBudget(Budget $budget): void { - $budgetId = (int)$budget->id; + $budgetId = (int) $budget->id; $this->report['budgets'][$budgetId] = $this->report['budgets'][$budgetId] ?? [ 'budget_id' => $budgetId, 'budget_name' => $budget->name, @@ -191,10 +191,10 @@ class BudgetReportGenerator */ private function processLimit(Budget $budget, BudgetLimit $limit): void { - $budgetId = (int)$budget->id; - $limitId = (int)$limit->id; + $budgetId = (int) $budget->id; + $limitId = (int) $limit->id; $limitCurrency = $limit->transactionCurrency ?? $this->currency; - $currencyId = (int)$limitCurrency->id; + $currencyId = (int) $limitCurrency->id; $expenses = $this->opsRepository->sumExpenses($limit->start_date, $limit->end_date, $this->accounts, new Collection([$budget])); $spent = $expenses[$currencyId]['sum'] ?? '0'; $left = -1 === bccomp(bcadd($limit->amount, $spent), '0') ? '0' : bcadd($limit->amount, $spent); @@ -253,7 +253,7 @@ class BudgetReportGenerator foreach ($noBudget as $noBudgetEntry) { // currency information: - $nbCurrencyId = (int)($noBudgetEntry['currency_id'] ?? $this->currency->id); + $nbCurrencyId = (int) ($noBudgetEntry['currency_id'] ?? $this->currency->id); $nbCurrencyCode = $noBudgetEntry['currency_code'] ?? $this->currency->code; $nbCurrencyName = $noBudgetEntry['currency_name'] ?? $this->currency->name; $nbCurrencySymbol = $noBudgetEntry['currency_symbol'] ?? $this->currency->symbol; @@ -298,9 +298,9 @@ class BudgetReportGenerator // make percentages based on total amount. foreach ($this->report['budgets'] as $budgetId => $data) { foreach ($data['budget_limits'] as $limitId => $entry) { - $budgetId = (int)$budgetId; - $limitId = (int)$limitId; - $currencyId = (int)$entry['currency_id']; + $budgetId = (int) $budgetId; + $limitId = (int) $limitId; + $currencyId = (int) $entry['currency_id']; $spent = $entry['spent']; $totalSpent = $this->report['sums'][$currencyId]['spent'] ?? '0'; $spentPct = '0'; @@ -309,10 +309,10 @@ class BudgetReportGenerator $budgetedPct = '0'; if (0 !== bccomp($spent, '0') && 0 !== bccomp($totalSpent, '0')) { - $spentPct = round((float)bcmul(bcdiv($spent, $totalSpent), '100')); + $spentPct = round((float) bcmul(bcdiv($spent, $totalSpent), '100')); } if (0 !== bccomp($budgeted, '0') && 0 !== bccomp($totalBudgeted, '0')) { - $budgetedPct = round((float)bcmul(bcdiv($budgeted, $totalBudgeted), '100')); + $budgetedPct = round((float) bcmul(bcdiv($budgeted, $totalBudgeted), '100')); } $this->report['sums'][$currencyId]['budgeted'] = $this->report['sums'][$currencyId]['budgeted'] ?? '0'; $this->report['budgets'][$budgetId]['budget_limits'][$limitId]['spent_pct'] = $spentPct; @@ -363,6 +363,8 @@ class BudgetReportGenerator /** * @param User $user + * @throws \FireflyIII\Exceptions\FireflyException + * @throws \JsonException */ public function setUser(User $user): void { diff --git a/app/Support/Report/Category/CategoryReportGenerator.php b/app/Support/Report/Category/CategoryReportGenerator.php index 5d6c25d0a6..efd064d6b3 100644 --- a/app/Support/Report/Category/CategoryReportGenerator.php +++ b/app/Support/Report/Category/CategoryReportGenerator.php @@ -64,12 +64,12 @@ class CategoryReportGenerator */ public function operations(): void { - $earnedWith = $this->opsRepository->listIncome($this->start, $this->end, $this->accounts); - $spentWith = $this->opsRepository->listExpenses($this->start, $this->end, $this->accounts); + $earnedWith = $this->opsRepository->listIncome($this->start, $this->end, $this->accounts); + $spentWith = $this->opsRepository->listExpenses($this->start, $this->end, $this->accounts); // also transferred out and transferred into these accounts in this category: - $transferredIn = $this->opsRepository->listTransferredIn($this->start, $this->end, $this->accounts); - $transferredOut = $this->opsRepository->listTransferredOut($this->start, $this->end, $this->accounts); + $transferredIn = $this->opsRepository->listTransferredIn($this->start, $this->end, $this->accounts); + $transferredOut = $this->opsRepository->listTransferredOut($this->start, $this->end, $this->accounts); $earnedWithout = $this->noCatRepository->listIncome($this->start, $this->end, $this->accounts); $spentWithout = $this->noCatRepository->listExpenses($this->start, $this->end, $this->accounts); diff --git a/app/Support/Repositories/Recurring/CalculateRangeOccurrences.php b/app/Support/Repositories/Recurring/CalculateRangeOccurrences.php index 87d1f78ee7..d5160b32ef 100644 --- a/app/Support/Repositories/Recurring/CalculateRangeOccurrences.php +++ b/app/Support/Repositories/Recurring/CalculateRangeOccurrences.php @@ -72,7 +72,7 @@ trait CalculateRangeOccurrences { $return = []; $attempts = 0; - $dayOfMonth = (int)$moment; + $dayOfMonth = (int) $moment; if ($start->day > $dayOfMonth) { // day has passed already, add a month. $start->addMonth(); @@ -140,7 +140,7 @@ trait CalculateRangeOccurrences Log::debug('Rep is weekly.'); // monday = 1 // sunday = 7 - $dayOfWeek = (int)$moment; + $dayOfWeek = (int) $moment; Log::debug(sprintf('DoW in repetition is %d, in mutator is %d', $dayOfWeek, $start->dayOfWeekIso)); if ($start->dayOfWeekIso > $dayOfWeek) { // day has already passed this week, add one week: diff --git a/app/Support/Repositories/Recurring/CalculateXOccurrences.php b/app/Support/Repositories/Recurring/CalculateXOccurrences.php index e8ff1fc664..166fa78fcc 100644 --- a/app/Support/Repositories/Recurring/CalculateXOccurrences.php +++ b/app/Support/Repositories/Recurring/CalculateXOccurrences.php @@ -77,7 +77,7 @@ trait CalculateXOccurrences $mutator = clone $date; $total = 0; $attempts = 0; - $dayOfMonth = (int)$moment; + $dayOfMonth = (int) $moment; if ($mutator->day > $dayOfMonth) { // day has passed already, add a month. $mutator->addMonth(); @@ -155,7 +155,7 @@ trait CalculateXOccurrences // monday = 1 // sunday = 7 $mutator->addDay(); // always assume today has passed. - $dayOfWeek = (int)$moment; + $dayOfWeek = (int) $moment; if ($mutator->dayOfWeekIso > $dayOfWeek) { // day has already passed this week, add one week: $mutator->addWeek(); diff --git a/app/Support/Repositories/Recurring/CalculateXOccurrencesSince.php b/app/Support/Repositories/Recurring/CalculateXOccurrencesSince.php index b3d4c56a35..b46a5dfebc 100644 --- a/app/Support/Repositories/Recurring/CalculateXOccurrencesSince.php +++ b/app/Support/Repositories/Recurring/CalculateXOccurrencesSince.php @@ -82,7 +82,7 @@ trait CalculateXOccurrencesSince $mutator = clone $date; $total = 0; $attempts = 0; - $dayOfMonth = (int)$moment; + $dayOfMonth = (int) $moment; $dayOfMonth = 0 === $dayOfMonth ? 1 : $dayOfMonth; if ($mutator->day > $dayOfMonth) { Log::debug(sprintf('%d is after %d, add a month. Mutator is now', $mutator->day, $dayOfMonth)); @@ -169,7 +169,7 @@ trait CalculateXOccurrencesSince // sunday = 7 // Removed assumption today has passed, see issue https://github.com/firefly-iii/firefly-iii/issues/4798 //$mutator->addDay(); // always assume today has passed. - $dayOfWeek = (int)$moment; + $dayOfWeek = (int) $moment; if ($mutator->dayOfWeekIso > $dayOfWeek) { // day has already passed this week, add one week: $mutator->addWeek(); diff --git a/app/Support/Repositories/Recurring/FiltersWeekends.php b/app/Support/Repositories/Recurring/FiltersWeekends.php index 32af55143f..04afa7dd81 100644 --- a/app/Support/Repositories/Recurring/FiltersWeekends.php +++ b/app/Support/Repositories/Recurring/FiltersWeekends.php @@ -47,7 +47,7 @@ trait FiltersWeekends protected function filterWeekends(RecurrenceRepetition $repetition, array $dates): array { Log::debug(sprintf('Now in %s', __METHOD__)); - if ((int)$repetition->weekend === RecurrenceRepetition::WEEKEND_DO_NOTHING) { + if ((int) $repetition->weekend === RecurrenceRepetition::WEEKEND_DO_NOTHING) { Log::debug('Repetition will not be filtered on weekend days.'); return $dates; diff --git a/app/Support/Request/AppendsLocationData.php b/app/Support/Request/AppendsLocationData.php index 4f05f031e7..77b7e7e3e1 100644 --- a/app/Support/Request/AppendsLocationData.php +++ b/app/Support/Request/AppendsLocationData.php @@ -30,6 +30,15 @@ use Log; */ trait AppendsLocationData { + /** + * Abstract method. + * + * @param $key + * + * @return bool + */ + abstract public function has($key); + /** * Read the submitted Request data and add new or updated Location data to the array. * @@ -148,25 +157,6 @@ trait AppendsLocationData return false; } - /** - * Abstract method stolen from "InteractsWithInput". - * - * @param null $key - * @param bool $default - * - * @return mixed - */ - abstract public function boolean($key = null, $default = false); - - /** - * Abstract method. - * - * @param $key - * - * @return bool - */ - abstract public function has($key); - /** * Abstract method. * @@ -183,6 +173,16 @@ trait AppendsLocationData */ abstract public function routeIs(...$patterns); + /** + * Abstract method stolen from "InteractsWithInput". + * + * @param null $key + * @param bool $default + * + * @return mixed + */ + abstract public function boolean($key = null, $default = false); + /** * @param string|null $prefix * diff --git a/app/Support/Request/ConvertsDataTypes.php b/app/Support/Request/ConvertsDataTypes.php index f7399e6dba..695978ee86 100644 --- a/app/Support/Request/ConvertsDataTypes.php +++ b/app/Support/Request/ConvertsDataTypes.php @@ -41,7 +41,7 @@ trait ConvertsDataTypes */ public function integer(string $field): int { - return (int)$this->get($field); + return (int) $this->get($field); } /** @@ -53,7 +53,7 @@ trait ConvertsDataTypes */ public function string(string $field): string { - return $this->clearString((string)($this->get($field) ?? ''), false); + return $this->clearString((string) ($this->get($field) ?? ''), false); } /** @@ -131,7 +131,7 @@ trait ConvertsDataTypes */ public function stringWithNewlines(string $field): string { - return $this->clearString((string)($this->get($field) ?? '')); + return $this->clearString((string) ($this->get($field) ?? '')); } /** @@ -180,28 +180,6 @@ trait ConvertsDataTypes return false; } - /** - * Return date or NULL. - * - * @param string $field - * - * @return Carbon|null - */ - protected function getCarbonDate(string $field): ?Carbon - { - $result = null; - try { - $result = $this->get($field) ? new Carbon($this->get($field)) : null; - } catch (InvalidFormatException $e) { - // @ignoreException - } - if (null === $result) { - Log::debug(sprintf('Exception when parsing date "%s".', $this->get($field))); - } - - return $result; - } - /** * @param string|null $string * @@ -245,7 +223,7 @@ trait ConvertsDataTypes return null; } - return (float)$res; + return (float) $res; } /** @@ -269,6 +247,28 @@ trait ConvertsDataTypes return $return; } + /** + * Return date or NULL. + * + * @param string $field + * + * @return Carbon|null + */ + protected function getCarbonDate(string $field): ?Carbon + { + $result = null; + try { + $result = $this->get($field) ? new Carbon($this->get($field)) : null; + } catch (InvalidFormatException $e) { + // @ignoreException + } + if (null === $result) { + Log::debug(sprintf('Exception when parsing date "%s".', $this->get($field))); + } + + return $result; + } + /** * Parse to integer * @@ -285,7 +285,7 @@ trait ConvertsDataTypes return null; } - return (int)$string; + return (int) $string; } /** @@ -301,12 +301,12 @@ trait ConvertsDataTypes return null; } - $value = (string)$this->get($field); + $value = (string) $this->get($field); if ('' === $value) { return null; } - return (int)$value; + return (int) $value; } } diff --git a/app/Support/Request/GetRecurrenceData.php b/app/Support/Request/GetRecurrenceData.php index 9b8ffe0dc5..38602e28f2 100644 --- a/app/Support/Request/GetRecurrenceData.php +++ b/app/Support/Request/GetRecurrenceData.php @@ -42,7 +42,7 @@ trait GetRecurrenceData $return['amount'] = $transaction['amount']; } if (array_key_exists('currency_id', $transaction)) { - $return['currency_id'] = (int)$transaction['currency_id']; + $return['currency_id'] = (int) $transaction['currency_id']; } if (array_key_exists('currency_code', $transaction)) { $return['currency_code'] = $transaction['currency_code']; @@ -53,17 +53,17 @@ trait GetRecurrenceData $return['foreign_amount'] = $transaction['foreign_amount']; } if (array_key_exists('foreign_currency_id', $transaction)) { - $return['foreign_currency_id'] = (int)$transaction['foreign_currency_id']; + $return['foreign_currency_id'] = (int) $transaction['foreign_currency_id']; } if (array_key_exists('foreign_currency_code', $transaction)) { $return['foreign_currency_code'] = $transaction['foreign_currency_code']; } // source + dest if (array_key_exists('source_id', $transaction)) { - $return['source_id'] = (int)$transaction['source_id']; + $return['source_id'] = (int) $transaction['source_id']; } if (array_key_exists('destination_id', $transaction)) { - $return['destination_id'] = (int)$transaction['destination_id']; + $return['destination_id'] = (int) $transaction['destination_id']; } // description if (array_key_exists('description', $transaction)) { @@ -71,17 +71,17 @@ trait GetRecurrenceData } if (array_key_exists('piggy_bank_id', $transaction)) { - $return['piggy_bank_id'] = (int)$transaction['piggy_bank_id']; + $return['piggy_bank_id'] = (int) $transaction['piggy_bank_id']; } if (array_key_exists('tags', $transaction)) { $return['tags'] = $transaction['tags']; } if (array_key_exists('budget_id', $transaction)) { - $return['budget_id'] = (int)$transaction['budget_id']; + $return['budget_id'] = (int) $transaction['budget_id']; } if (array_key_exists('category_id', $transaction)) { - $return['category_id'] = (int)$transaction['category_id']; + $return['category_id'] = (int) $transaction['category_id']; } return $return; diff --git a/app/Support/Request/GetRuleConfiguration.php b/app/Support/Request/GetRuleConfiguration.php index 9826382f8a..9c7e8ef1fb 100644 --- a/app/Support/Request/GetRuleConfiguration.php +++ b/app/Support/Request/GetRuleConfiguration.php @@ -34,7 +34,7 @@ trait GetRuleConfiguration */ protected function getTriggers(): array { - return array_keys(config('firefly.search.operators')); + return array_keys(config('search.operators')); } /** @@ -42,7 +42,7 @@ trait GetRuleConfiguration */ protected function getTriggersWithContext(): array { - $list = config('firefly.search.operators'); + $list = config('search.operators'); $return = []; foreach ($list as $key => $info) { if (true === $info['needs_context']) { diff --git a/app/Support/Search/AccountSearch.php b/app/Support/Search/AccountSearch.php index 5a111c40ea..9ace498a2b 100644 --- a/app/Support/Search/AccountSearch.php +++ b/app/Support/Search/AccountSearch.php @@ -37,14 +37,13 @@ class AccountSearch implements GenericSearchInterface /** @var string */ public const SEARCH_ALL = 'all'; /** @var string */ - public const SEARCH_NAME = 'name'; - /** @var string */ public const SEARCH_IBAN = 'iban'; /** @var string */ - public const SEARCH_NUMBER = 'number'; - /** @var string */ public const SEARCH_ID = 'id'; - + /** @var string */ + public const SEARCH_NAME = 'name'; + /** @var string */ + public const SEARCH_NUMBER = 'number'; private string $field; private string $query; private array $types; @@ -57,16 +56,15 @@ class AccountSearch implements GenericSearchInterface /** * @return Collection - * @throws JsonException */ public function search(): Collection { - $searchQuery = $this->user->accounts() - ->leftJoin('account_types', 'accounts.account_type_id', '=', 'account_types.id') - ->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id') - ->whereIn('account_types.type', $this->types); - $like = sprintf('%%%s%%', $this->query); + $searchQuery = $this->user->accounts() + ->leftJoin('account_types', 'accounts.account_type_id', '=', 'account_types.id') + ->leftJoin('account_meta', 'accounts.id', '=', 'account_meta.account_id') + ->whereIn('account_types.type', $this->types); + $like = sprintf('%%%s%%', $this->query); $originalQuery = $this->query; switch ($this->field) { default: @@ -88,7 +86,7 @@ class AccountSearch implements GenericSearchInterface ); break; case self::SEARCH_ID: - $searchQuery->where('accounts.id', '=', (int)$originalQuery); + $searchQuery->where('accounts.id', '=', (int) $originalQuery); break; case self::SEARCH_NAME: $searchQuery->where('accounts.name', 'LIKE', $like); diff --git a/app/Support/Search/OperatorQuerySearch.php b/app/Support/Search/OperatorQuerySearch.php index 66b5274665..510d2b2c9f 100644 --- a/app/Support/Search/OperatorQuerySearch.php +++ b/app/Support/Search/OperatorQuerySearch.php @@ -92,7 +92,7 @@ class OperatorQuerySearch implements SearchInterface $this->invalidOperators = []; $this->limit = 25; $this->date = today(config('app.timezone')); - $this->validOperators = array_keys(config('firefly.search.operators')); + $this->validOperators = array_keys(config('search.operators')); $this->startTime = microtime(true); $this->accountRepository = app(AccountRepositoryInterface::class); $this->categoryRepository = app(CategoryRepositoryInterface::class); @@ -156,7 +156,7 @@ class OperatorQuerySearch implements SearchInterface $parser = new QueryParser(); try { $query1 = $parser->parse($query); - } catch (TypeError | LogicException $e) { + } catch (TypeError|LogicException $e) { Log::error($e->getMessage()); Log::error(sprintf('Could not parse search: "%s".', $query)); throw new FireflyException('Invalid search value. See the logs.', 0, $e); @@ -170,73 +170,6 @@ class OperatorQuerySearch implements SearchInterface $this->collector->setSearchWords($this->words); } - /** - * @inheritDoc - * @codeCoverageIgnore - */ - public function searchTime(): float - { - return microtime(true) - $this->startTime; - } - - /** - * @inheritDoc - */ - public function searchTransactions(): LengthAwarePaginator - { - if (empty($this->getWords()) && empty($this->getOperators())) { - return new LengthAwarePaginator([], 0, 5, 1); - } - - return $this->collector->getPaginatedGroups(); - } - - /** - * @param Carbon $date - */ - public function setDate(Carbon $date): void - { - $this->date = $date; - } - - /** - * @param int $limit - */ - public function setLimit(int $limit): void - { - $this->limit = $limit; - $this->collector->setLimit($this->limit); - } - - /** - * @inheritDoc - * @codeCoverageIgnore - */ - public function setPage(int $page): void - { - $this->page = $page; - $this->collector->setPage($this->page); - } - - /** - * @inheritDoc - * @codeCoverageIgnore - */ - public function setUser(User $user): void - { - $this->accountRepository->setUser($user); - $this->billRepository->setUser($user); - $this->categoryRepository->setUser($user); - $this->budgetRepository->setUser($user); - $this->tagRepository->setUser($user); - $this->collector = app(GroupCollectorInterface::class); - $this->collector->setUser($user); - $this->collector->withAccountInformation()->withCategoryInformation()->withBudgetInformation(); - - $this->setLimit((int)app('preferences')->getForUser($user, 'listPageSize', 50)->data); - - } - /** * @param Node $searchNode * @@ -253,7 +186,7 @@ class OperatorQuerySearch implements SearchInterface case Subquery::class: // loop all notes in subquery: foreach ($searchNode->getNodes() as $subNode) { // @phpstan-ignore-line - $this->handleSearchNode($subNode); // let's hope it's not too recursive! + $this->handleSearchNode($subNode); // let's hope it's not too recursive! } break; case Word::class: @@ -265,7 +198,7 @@ class OperatorQuerySearch implements SearchInterface case Emoticon::class: case Emoji::class: case Mention::class: - $allWords = (string)$searchNode->getValue(); + $allWords = (string) $searchNode->getValue(); Log::debug(sprintf('Add words "%s" to search string, because Node class is "%s"', $allWords, $class)); $this->words[] = $allWords; break; @@ -276,11 +209,11 @@ class OperatorQuerySearch implements SearchInterface $operator = strtolower($searchNode->getValue()); $value = $searchNode->getNode()->getValue(); // must be valid operator: - if (in_array($operator, $this->validOperators, true) && $this->updateCollector($operator, (string)$value)) { + if (in_array($operator, $this->validOperators, true) && $this->updateCollector($operator, (string) $value)) { $this->operators->push( [ 'type' => self::getRootOperator($operator), - 'value' => (string)$value, + 'value' => (string) $value, ] ); Log::debug(sprintf('Added operator type "%s"', $operator)); @@ -289,7 +222,7 @@ class OperatorQuerySearch implements SearchInterface Log::debug(sprintf('Added INVALID operator type "%s"', $operator)); $this->invalidOperators[] = [ 'type' => $operator, - 'value' => (string)$value, + 'value' => (string) $value, ]; } } @@ -322,6 +255,30 @@ class OperatorQuerySearch implements SearchInterface // // all account related searches: // + case 'account_is': + $this->searchAccount($value, 3, 4); + break; + case 'account_contains': + $this->searchAccount($value, 3, 3); + break; + case 'account_ends': + $this->searchAccount($value, 3, 2); + break; + case 'account_starts': + $this->searchAccount($value, 3, 1); + break; + case 'account_nr_is': + $this->searchAccountNr($value, 3, 4); + break; + case 'account_nr_contains': + $this->searchAccountNr($value, 3, 3); + break; + case 'account_nr_ends': + $this->searchAccountNr($value, 3, 2); + break; + case 'account_nr_starts': + $this->searchAccountNr($value, 3, 1); + break; case 'source_account_starts': $this->searchAccount($value, 1, 1); break; @@ -347,7 +304,7 @@ class OperatorQuerySearch implements SearchInterface $this->searchAccount($value, 1, 3); break; case 'source_account_id': - $account = $this->accountRepository->find((int)$value); + $account = $this->accountRepository->find((int) $value); if (null !== $account) { $this->collector->setSourceAccounts(new Collection([$account])); } @@ -389,7 +346,7 @@ class OperatorQuerySearch implements SearchInterface $this->searchAccount($value, 2, 3); break; case 'destination_account_id': - $account = $this->accountRepository->find((int)$value); + $account = $this->accountRepository->find((int) $value); if (null !== $account) { $this->collector->setDestinationAccounts(new Collection([$account])); } @@ -401,7 +358,7 @@ class OperatorQuerySearch implements SearchInterface $parts = explode(',', $value); $collection = new Collection; foreach ($parts as $accountId) { - $account = $this->accountRepository->find((int)$accountId); + $account = $this->accountRepository->find((int) $accountId); if (null !== $account) { $collection->push($account); } @@ -472,6 +429,10 @@ class OperatorQuerySearch implements SearchInterface Log::debug('Set collector to filter on attachments.'); $this->collector->hasAttachments(); break; + case 'has_no_attachments': + Log::debug('Set collector to filter on NO attachments.'); + $this->collector->hasNoAttachments(); + break; // // categories case 'has_no_category': @@ -481,6 +442,32 @@ class OperatorQuerySearch implements SearchInterface $this->collector->withCategory(); break; case 'category_is': + $category = $this->categoryRepository->findByName($value); + if (null !== $category) { + $this->collector->setCategory($category); + break; + } + $this->collector->findNothing(); + break; + case 'category_ends': + $result = $this->categoryRepository->categoryEndsWith($value, 1337); + if ($result->count() > 0) { + $this->collector->setCategories($result); + } + if (0 === $result->count()) { + $this->collector->findNothing(); + } + break; + case 'category_starts': + $result = $this->categoryRepository->categoryStartsWith($value, 1337); + if ($result->count() > 0) { + $this->collector->setCategories($result); + } + if (0 === $result->count()) { + $this->collector->findNothing(); + } + break; + case 'category_contains': $result = $this->categoryRepository->searchCategory($value, 1337); if ($result->count() > 0) { $this->collector->setCategories($result); @@ -498,7 +485,7 @@ class OperatorQuerySearch implements SearchInterface case 'has_any_budget': $this->collector->withBudget(); break; - case 'budget_is': + case 'budget_contains': $result = $this->budgetRepository->searchBudget($value, 1337); if ($result->count() > 0) { $this->collector->setBudgets($result); @@ -507,6 +494,32 @@ class OperatorQuerySearch implements SearchInterface $this->collector->findNothing(); } break; + case 'budget_is': + $budget = $this->budgetRepository->findByName($value); + if (null !== $budget) { + $this->collector->setBudget($budget); + break; + } + $this->collector->findNothing(); + break; + case 'budget_ends': + $result = $this->budgetRepository->budgetEndsWith($value, 1337); + if ($result->count() > 0) { + $this->collector->setBudgets($result); + } + if (0 === $result->count()) { + $this->collector->findNothing(); + } + break; + case 'budget_starts': + $result = $this->budgetRepository->budgetStartsWith($value, 1337); + if ($result->count() > 0) { + $this->collector->setBudgets($result); + } + if (0 === $result->count()) { + $this->collector->findNothing(); + } + break; // // bill // @@ -516,8 +529,33 @@ class OperatorQuerySearch implements SearchInterface case 'has_any_bill': $this->collector->withBill(); break; - case 'bill_is': + case 'bill_contains': $result = $this->billRepository->searchBill($value, 1337); + if ($result->count() > 0) { + $this->collector->setBills($result); + break; + } + $this->collector->findNothing(); + break; + case 'bill_is': + $bill = $this->billRepository->findByName($value); + if (null !== $bill) { + $this->collector->setBill($bill); + break; + } + $this->collector->findNothing(); + break; + case 'bill_ends': + $result = $this->billRepository->billEndsWith($value, 1337); + if ($result->count() > 0) { + $this->collector->setBills($result); + } + if (0 === $result->count()) { + $this->collector->findNothing(); + } + break; + case 'bill_starts': + $result = $this->billRepository->billStartsWith($value, 1337); if ($result->count() > 0) { $this->collector->setBills($result); } @@ -545,19 +583,25 @@ class OperatorQuerySearch implements SearchInterface $this->collector->findNothing(); } break; + case 'tag_is_not': + $result = $this->tagRepository->searchTag($value); + if ($result->count() > 0) { + $this->collector->setWithoutSpecificTags($result); + } + break; // // notes // - case 'notes_contain': + case 'notes_contains': $this->collector->notesContain($value); break; - case 'notes_start': + case 'notes_starts': $this->collector->notesStartWith($value); break; - case 'notes_end': + case 'notes_ends': $this->collector->notesEndWith($value); break; - case 'notes_are': + case 'notes_is': $this->collector->notesExactly($value); break; case 'no_notes': @@ -569,31 +613,56 @@ class OperatorQuerySearch implements SearchInterface // // amount // - case 'amount_exactly': + case 'amount_is': // strip comma's, make dots. - $value = str_replace(',', '.', (string)$value); + $value = str_replace(',', '.', (string) $value); $amount = app('steam')->positive($value); Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $amount)); $this->collector->amountIs($amount); break; + case 'foreign_amount_is': + + // strip comma's, make dots. + $value = str_replace(',', '.', (string) $value); + + $amount = app('steam')->positive($value); + Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $amount)); + $this->collector->foreignAmountIs($amount); + break; case 'amount_less': // strip comma's, make dots. - $value = str_replace(',', '.', (string)$value); + $value = str_replace(',', '.', (string) $value); $amount = app('steam')->positive($value); Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $amount)); $this->collector->amountLess($amount); break; + case 'foreign_amount_less': + // strip comma's, make dots. + $value = str_replace(',', '.', (string) $value); + + $amount = app('steam')->positive($value); + Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $amount)); + $this->collector->foreignAmountLess($amount); + break; case 'amount_more': Log::debug(sprintf('Now handling operator "%s"', $operator)); // strip comma's, make dots. - $value = str_replace(',', '.', (string)$value); + $value = str_replace(',', '.', (string) $value); $amount = app('steam')->positive($value); Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $amount)); $this->collector->amountMore($amount); break; + case 'foreign_amount_more': + Log::debug(sprintf('Now handling operator "%s"', $operator)); + // strip comma's, make dots. + $value = str_replace(',', '.', (string) $value); + $amount = app('steam')->positive($value); + Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $amount)); + $this->collector->foreignAmountMore($amount); + break; // // transaction type // @@ -604,7 +673,7 @@ class OperatorQuerySearch implements SearchInterface // // dates // - case 'date_is': + case 'date_on': $range = $this->parseDateRange($value); $this->setExactDateParams($range); return false; @@ -616,16 +685,110 @@ class OperatorQuerySearch implements SearchInterface $range = $this->parseDateRange($value); $this->setDateAfterParams($range); return false; - case 'created_on': + case 'interest_date_on': + $range = $this->parseDateRange($value); + $this->setExactMetaDateParams('interest_date', $range); + return false; + case 'interest_date_before': + $range = $this->parseDateRange($value); + $this->setMetaDateBeforeParams('interest_date', $range); + return false; + case 'interest_date_after': + $range = $this->parseDateRange($value); + $this->setMetaDateAfterParams('interest_date', $range); + return false; + + case 'book_date_on': + $range = $this->parseDateRange($value); + $this->setExactMetaDateParams('book_date', $range); + return false; + case 'book_date_before': + $range = $this->parseDateRange($value); + $this->setMetaDateBeforeParams('book_date', $range); + return false; + case 'book_date_after': + $range = $this->parseDateRange($value); + $this->setMetaDateAfterParams('book_date', $range); + return false; + + case 'process_date_on': + $range = $this->parseDateRange($value); + $this->setExactMetaDateParams('process_date', $range); + return false; + case 'process_date_before': + $range = $this->parseDateRange($value); + $this->setMetaDateBeforeParams('process_date', $range); + return false; + case 'process_date_after': + $range = $this->parseDateRange($value); + $this->setMetaDateAfterParams('process_date', $range); + return false; + case 'due_date_on': + $range = $this->parseDateRange($value); + $this->setExactMetaDateParams('due_date', $range); + return false; + case 'due_date_before': + $range = $this->parseDateRange($value); + $this->setMetaDateBeforeParams('due_date', $range); + return false; + case 'due_date_after': + $range = $this->parseDateRange($value); + $this->setMetaDateAfterParams('due_date', $range); + return false; + case 'payment_date_on': + $range = $this->parseDateRange($value); + $this->setExactMetaDateParams('payment_date', $range); + return false; + case 'payment_date_before': + $range = $this->parseDateRange($value); + $this->setMetaDateBeforeParams('payment_date', $range); + return false; + case 'payment_date_after': + $range = $this->parseDateRange($value); + $this->setMetaDateAfterParams('payment_date', $range); + return false; + case 'invoice_date_on': + $range = $this->parseDateRange($value); + $this->setExactMetaDateParams('invoice_date', $range); + return false; + case 'invoice_date_before': + $range = $this->parseDateRange($value); + $this->setMetaDateBeforeParams('invoice_date', $range); + return false; + case 'invoice_date_after': + $range = $this->parseDateRange($value); + $this->setMetaDateAfterParams('invoice_date', $range); + return false; + case 'created_at_on': Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $value)); - $createdAt = new Carbon($value); - $this->collector->setCreatedAt($createdAt); - break; - case 'updated_on': + $range = $this->parseDateRange($value); + $this->setExactObjectDateParams('created_at', $range); + return false; + case 'created_at_before': Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $value)); - $updatedAt = new Carbon($value); - $this->collector->setUpdatedAt($updatedAt); - break; + $range = $this->parseDateRange($value); + $this->setObjectDateBeforeParams('created_at', $range); + return false; + case 'created_at_after': + Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $value)); + $range = $this->parseDateRange($value); + $this->setObjectDateAfterParams('created_at', $range); + return false; + case 'updated_at_on': + Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $value)); + $range = $this->parseDateRange($value); + $this->setExactObjectDateParams('updated_at', $range); + return false; + case 'updated_at_before': + Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $value)); + $range = $this->parseDateRange($value); + $this->setObjectDateBeforeParams('updated_at', $range); + return false; + case 'updated_at_after': + Log::debug(sprintf('Set "%s" using collector with value "%s"', $operator, $value)); + $range = $this->parseDateRange($value); + $this->setObjectDateAfterParams('updated_at', $range); + return false; // // external URL // @@ -635,15 +798,73 @@ class OperatorQuerySearch implements SearchInterface case 'any_external_url': $this->collector->withExternalUrl(); break; + case 'external_url_is': + $this->collector->setExternalUrl($value); + break; + case 'external_url_contains': + $this->collector->externalUrlContains($value); + break; + case 'external_url_starts': + $this->collector->externalUrlStarts($value); + break; + case 'external_url_ends': + $this->collector->externalUrlEnds($value); + break; // // other fields // - case 'external_id': + case 'external_id_is': $this->collector->setExternalId($value); break; - case 'internal_reference': + case 'recurrence_id': + $this->collector->setRecurrenceId($value); + break; + case 'external_id_contains': + $this->collector->externalIdContains($value); + break; + case 'external_id_starts': + $this->collector->externalIdStarts($value); + break; + case 'external_id_ends': + $this->collector->externalIdEnds($value); + break; + case 'internal_reference_is': $this->collector->setInternalReference($value); break; + case 'internal_reference_contains': + $this->collector->internalReferenceContains($value); + break; + case 'internal_reference_starts': + $this->collector->internalReferenceStarts($value); + break; + case 'internal_reference_ends': + $this->collector->internalReferenceEnds($value); + break; + case 'attachment_name_is': + $this->collector->attachmentNameIs($value); + break; + case 'attachment_name_contains': + $this->collector->attachmentNameContains($value); + break; + case 'attachment_name_starts': + $this->collector->attachmentNameStarts($value); + break; + case 'attachment_name_ends': + $this->collector->attachmentNameEnds($value); + break; + case 'attachment_notes_are': + $this->collector->attachmentNotesAre($value); + break; + case 'attachment_notes_contains': + $this->collector->attachmentNotesContains($value); + break; + case 'attachment_notes_starts': + $this->collector->attachmentNotesStarts($value); + break; + case 'attachment_notes_ends': + $this->collector->attachmentNotesEnds($value); + break; + } return true; @@ -657,7 +878,7 @@ class OperatorQuerySearch implements SearchInterface */ public static function getRootOperator(string $operator): string { - $config = config(sprintf('firefly.search.operators.%s', $operator)); + $config = config(sprintf('search.operators.%s', $operator)); if (null === $config) { throw new FireflyException(sprintf('No configuration for search operator "%s"', $operator)); } @@ -672,7 +893,7 @@ class OperatorQuerySearch implements SearchInterface } /** - * searchDirection: 1 = source (default), 2 = destination + * searchDirection: 1 = source (default), 2 = destination, 3 = both * stringPosition: 1 = start (default), 2 = end, 3 = contains, 4 = is * * @param string $value @@ -693,6 +914,11 @@ class OperatorQuerySearch implements SearchInterface $searchTypes = [AccountType::ASSET, AccountType::MORTGAGE, AccountType::LOAN, AccountType::DEBT, AccountType::EXPENSE]; $collectorMethod = 'setDestinationAccounts'; } + // either account could be: + if (3 === $searchDirection) { + $searchTypes = [AccountType::ASSET, AccountType::MORTGAGE, AccountType::LOAN, AccountType::DEBT, AccountType::EXPENSE, AccountType::REVENUE]; + $collectorMethod = 'setAccounts'; + } // string position (default): starts with: $stringMethod = 'str_starts_with'; @@ -733,7 +959,7 @@ class OperatorQuerySearch implements SearchInterface } /** - * searchDirection: 1 = source (default), 2 = destination + * searchDirection: 1 = source (default), 2 = destination, 3 = both * stringPosition: 1 = start (default), 2 = end, 3 = contains, 4 = is * * @param string $value @@ -754,6 +980,13 @@ class OperatorQuerySearch implements SearchInterface $searchTypes = [AccountType::ASSET, AccountType::MORTGAGE, AccountType::LOAN, AccountType::DEBT, AccountType::EXPENSE]; $collectorMethod = 'setDestinationAccounts'; } + + // either account could be: + if (3 === $searchDirection) { + $searchTypes = [AccountType::ASSET, AccountType::MORTGAGE, AccountType::LOAN, AccountType::DEBT, AccountType::EXPENSE, AccountType::REVENUE]; + $collectorMethod = 'setAccounts'; + } + // string position (default): starts with: $stringMethod = 'str_starts_with'; @@ -782,7 +1015,7 @@ class OperatorQuerySearch implements SearchInterface $filtered = $accounts->filter( function (Account $account) use ($value, $stringMethod) { // either IBAN or account number! - $ibanMatch = $stringMethod(strtolower((string)$account->iban), strtolower((string)$value)); + $ibanMatch = $stringMethod(strtolower((string) $account->iban), strtolower((string) $value)); $accountNrMatch = false; /** @var AccountMeta $meta */ foreach ($account->accountMeta as $meta) { @@ -852,14 +1085,6 @@ class OperatorQuerySearch implements SearchInterface ]; } - /** - * @return array - */ - public function getWords(): array - { - return $this->words; - } - /** * @param array $range * @@ -878,22 +1103,22 @@ class OperatorQuerySearch implements SearchInterface case 'exact': Log::debug(sprintf('Set date_is_exact value "%s"', $value->format('Y-m-d'))); $this->collector->setRange($value, $value); - $this->operators->push(['type' => 'date_is', 'value' => $value->format('Y-m-d'),]); + $this->operators->push(['type' => 'date_on', 'value' => $value->format('Y-m-d'),]); break; case 'year': Log::debug(sprintf('Set date_is_exact YEAR value "%s"', $value)); $this->collector->yearIs($value); - $this->operators->push(['type' => 'date_is_year', 'value' => $value,]); + $this->operators->push(['type' => 'date_on_year', 'value' => $value,]); break; case 'month': Log::debug(sprintf('Set date_is_exact MONTH value "%s"', $value)); $this->collector->monthIs($value); - $this->operators->push(['type' => 'date_is_month', 'value' => $value,]); + $this->operators->push(['type' => 'date_on_month', 'value' => $value,]); break; case 'day': Log::debug(sprintf('Set date_is_exact DAY value "%s"', $value)); $this->collector->dayIs($value); - $this->operators->push(['type' => 'date_is_day', 'value' => $value,]); + $this->operators->push(['type' => 'date_on_day', 'value' => $value,]); break; } } @@ -974,4 +1199,316 @@ class OperatorQuerySearch implements SearchInterface } } } + + /** + * @param string $field + * @param array $range + * @return void + * @throws FireflyException + */ + private function setExactMetaDateParams(string $field, array $range): void + { + Log::debug('Now in setExactMetaDateParams()'); + /** + * @var string $key + * @var Carbon|string $value + */ + foreach ($range as $key => $value) { + switch ($key) { + default: + throw new FireflyException(sprintf('Cannot handle key "%s" in setExactMetaDateParams()', $key)); + case 'exact': + Log::debug(sprintf('Set %s_is_exact value "%s"', $field, $value->format('Y-m-d'))); + $this->collector->setMetaDateRange($value, $value, $field); + $this->operators->push(['type' => sprintf('%s_on', $field), 'value' => $value->format('Y-m-d'),]); + break; + case 'year': + Log::debug(sprintf('Set %s_is_exact YEAR value "%s"', $field, $value)); + $this->collector->metaYearIs($value, $field); + $this->operators->push(['type' => sprintf('%s_on_year', $field), 'value' => $value,]); + break; + case 'month': + Log::debug(sprintf('Set %s_is_exact MONTH value "%s"', $field, $value)); + $this->collector->metaMonthIs($value, $field); + $this->operators->push(['type' => sprintf('%s_on_month', $field), 'value' => $value,]); + break; + case 'day': + Log::debug(sprintf('Set %s_is_exact DAY value "%s"', $field, $value)); + $this->collector->metaDayIs($value, $field); + $this->operators->push(['type' => sprintf('%s_on_day', $field), 'value' => $value,]); + break; + } + } + } + + /** + * @param string $field + * @param array $range + * @return void + * @throws FireflyException + */ + private function setMetaDateBeforeParams(string $field, array $range): void + { + /** + * @var string $key + * @var Carbon|string $value + */ + foreach ($range as $key => $value) { + switch ($key) { + default: + throw new FireflyException(sprintf('Cannot handle key "%s" in setMetaDateBeforeParams()', $key)); + case 'exact': + $this->collector->setMetaBefore($value, $field); + $this->operators->push(['type' => sprintf('%s_before', $field), 'value' => $value->format('Y-m-d'),]); + break; + case 'year': + Log::debug(sprintf('Set %s_is_before YEAR value "%s"', $field, $value)); + $this->collector->metaYearBefore($value, $field); + $this->operators->push(['type' => sprintf('%s_before_year', $field), 'value' => $value,]); + break; + case 'month': + Log::debug(sprintf('Set %s_is_before MONTH value "%s"', $field, $value)); + $this->collector->metaMonthBefore($value, $field); + $this->operators->push(['type' => sprintf('%s_before_month', $field), 'value' => $value,]); + break; + case 'day': + Log::debug(sprintf('Set %s_is_before DAY value "%s"', $field, $value)); + $this->collector->metaDayBefore($value, $field); + $this->operators->push(['type' => sprintf('%s_before_day', $field), 'value' => $value,]); + break; + } + } + } + + /** + * @param string $field + * @param array $range + * @return void + * @throws FireflyException + */ + private function setMetaDateAfterParams(string $field, array $range): void + { + /** + * @var string $key + * @var Carbon|string $value + */ + foreach ($range as $key => $value) { + switch ($key) { + default: + throw new FireflyException(sprintf('Cannot handle key "%s" in setMetaDateAfterParams()', $key)); + case 'exact': + $this->collector->setMetaAfter($value, $field); + $this->operators->push(['type' => sprintf('%s_after', $field), 'value' => $value->format('Y-m-d'),]); + break; + case 'year': + Log::debug(sprintf('Set %s_is_after YEAR value "%s"', $field, $value)); + $this->collector->metaYearAfter($value, $field); + $this->operators->push(['type' => sprintf('%s_after_year', $field), 'value' => $value,]); + break; + case 'month': + Log::debug(sprintf('Set %s_is_after MONTH value "%s"', $field, $value)); + $this->collector->metaMonthAfter($value, $field); + $this->operators->push(['type' => sprintf('%s_after_month', $field), 'value' => $value,]); + break; + case 'day': + Log::debug(sprintf('Set %s_is_after DAY value "%s"', $field, $value)); + $this->collector->metaDayAfter($value, $field); + $this->operators->push(['type' => sprintf('%s_after_day', $field), 'value' => $value,]); + break; + } + } + } + + /** + * @param string $field + * @param array $range + * @return void + * @throws FireflyException + */ + private function setExactObjectDateParams(string $field, array $range): void + { + /** + * @var string $key + * @var Carbon|string $value + */ + foreach ($range as $key => $value) { + switch ($key) { + default: + throw new FireflyException(sprintf('Cannot handle key "%s" in setExactObjectDateParams()', $key)); + case 'exact': + Log::debug(sprintf('Set %s_is_exact value "%s"', $field, $value->format('Y-m-d'))); + $this->collector->setObjectRange($value, clone $value, $field); + $this->operators->push(['type' => sprintf('%s_on', $field), 'value' => $value->format('Y-m-d'),]); + break; + case 'year': + Log::debug(sprintf('Set %s_is_exact YEAR value "%s"', $field, $value)); + $this->collector->objectYearIs($value, $field); + $this->operators->push(['type' => sprintf('%s_on_year', $field), 'value' => $value,]); + break; + case 'month': + Log::debug(sprintf('Set %s_is_exact MONTH value "%s"', $field, $value)); + $this->collector->objectMonthIs($value, $field); + $this->operators->push(['type' => sprintf('%s_on_month', $field), 'value' => $value,]); + break; + case 'day': + Log::debug(sprintf('Set %s_is_exact DAY value "%s"', $field, $value)); + $this->collector->objectDayIs($value, $field); + $this->operators->push(['type' => sprintf('%s_on_day', $field), 'value' => $value,]); + break; + } + } + } + + /** + * @param string $field + * @param array $range + * + * @throws FireflyException + */ + private function setObjectDateBeforeParams(string $field, array $range) + { + /** + * @var string $key + * @var Carbon|string $value + */ + foreach ($range as $key => $value) { + switch ($key) { + default: + throw new FireflyException(sprintf('Cannot handle key "%s" in setDateAfterParams()', $key)); + case 'exact': + $this->collector->setObjectBefore($value, $field); + $this->operators->push(['type' => sprintf('%s_before', $field), 'value' => $value->format('Y-m-d'),]); + break; + case 'year': + Log::debug(sprintf('Set date_is_before YEAR value "%s"', $value)); + $this->collector->objectYearBefore($value, $field); + $this->operators->push(['type' => sprintf('%s_before_year', $field), 'value' => $value,]); + break; + case 'month': + Log::debug(sprintf('Set date_is_before MONTH value "%s"', $value)); + $this->collector->objectMonthBefore($value, $field); + $this->operators->push(['type' => sprintf('%s_before_month', $field), 'value' => $value,]); + break; + case 'day': + Log::debug(sprintf('Set date_is_before DAY value "%s"', $value)); + $this->collector->objectDayBefore($value, $field); + $this->operators->push(['type' => sprintf('%s_before_day', $field), 'value' => $value,]); + break; + } + } + } + + /** + * @param string $field + * @param array $range + * + * @throws FireflyException + */ + private function setObjectDateAfterParams(string $field, array $range) + { + /** + * @var string $key + * @var Carbon|string $value + */ + foreach ($range as $key => $value) { + switch ($key) { + default: + throw new FireflyException(sprintf('Cannot handle key "%s" in setDateAfterParams()', $key)); + case 'exact': + $this->collector->setObjectAfter($value, $field); + $this->operators->push(['type' => sprintf('%s_after', $field), 'value' => $value->format('Y-m-d'),]); + break; + case 'year': + Log::debug(sprintf('Set date_is_after YEAR value "%s"', $value)); + $this->collector->objectYearAfter($value, $field); + $this->operators->push(['type' => sprintf('%s_after_year', $field), 'value' => $value,]); + break; + case 'month': + Log::debug(sprintf('Set date_is_after MONTH value "%s"', $value)); + $this->collector->objectMonthAfter($value, $field); + $this->operators->push(['type' => sprintf('%s_after_month', $field), 'value' => $value,]); + break; + case 'day': + Log::debug(sprintf('Set date_is_after DAY value "%s"', $value)); + $this->collector->objectDayAfter($value, $field); + $this->operators->push(['type' => sprintf('%s_after_day', $field), 'value' => $value,]); + break; + } + } + } + + /** + * @inheritDoc + * @codeCoverageIgnore + */ + public function searchTime(): float + { + return microtime(true) - $this->startTime; + } + + /** + * @inheritDoc + */ + public function searchTransactions(): LengthAwarePaginator + { + if (empty($this->getWords()) && empty($this->getOperators())) { + return new LengthAwarePaginator([], 0, 5, 1); + } + + return $this->collector->getPaginatedGroups(); + } + + /** + * @return array + */ + public function getWords(): array + { + return $this->words; + } + + /** + * @param Carbon $date + */ + public function setDate(Carbon $date): void + { + $this->date = $date; + } + + /** + * @inheritDoc + * @codeCoverageIgnore + */ + public function setPage(int $page): void + { + $this->page = $page; + $this->collector->setPage($this->page); + } + + /** + * @inheritDoc + * @codeCoverageIgnore + */ + public function setUser(User $user): void + { + $this->accountRepository->setUser($user); + $this->billRepository->setUser($user); + $this->categoryRepository->setUser($user); + $this->budgetRepository->setUser($user); + $this->tagRepository->setUser($user); + $this->collector = app(GroupCollectorInterface::class); + $this->collector->setUser($user); + $this->collector->withAccountInformation()->withCategoryInformation()->withBudgetInformation(); + + $this->setLimit((int) app('preferences')->getForUser($user, 'listPageSize', 50)->data); + + } + + /** + * @param int $limit + */ + public function setLimit(int $limit): void + { + $this->limit = $limit; + $this->collector->setLimit($this->limit); + } } diff --git a/app/Support/Steam.php b/app/Support/Steam.php index 9eaeb77f94..43d2be481e 100644 --- a/app/Support/Steam.php +++ b/app/Support/Steam.php @@ -43,59 +43,11 @@ use Str; class Steam { - /** - * Returns the previous URL but refuses to send you to specific URLs. - * - * - outside domain - * - to JS files, API or JSON routes - * - * Uses the session's previousUrl() function as inspired by GitHub user @z1r0- - * - * session()->previousUrl() uses getSafeUrl() so we can safely return it: - * - * @return string - */ - public function getSafePreviousUrl(): string - { - //Log::debug(sprintf('getSafePreviousUrl: "%s"', session()->previousUrl())); - return session()->previousUrl() ?? route('index'); - } - - /** - * Make sure URL is safe. - * - * @param string $unknownUrl - * @param string $safeUrl - * - * @return string - */ - public function getSafeUrl(string $unknownUrl, string $safeUrl): string - { - //Log::debug(sprintf('getSafeUrl(%s, %s)', $unknownUrl, $safeUrl)); - $returnUrl = $safeUrl; - $unknownHost = parse_url($unknownUrl, PHP_URL_HOST); - $safeHost = parse_url($safeUrl, PHP_URL_HOST); - - if (null !== $unknownHost && $unknownHost === $safeHost) { - $returnUrl = $unknownUrl; - } - - // URL must not lead to weird pages - $forbiddenWords = ['jscript', 'json', 'debug', 'serviceworker', 'offline', 'delete', '/login', '/attachments/view']; - if (Str::contains($returnUrl, $forbiddenWords)) { - $returnUrl = $safeUrl; - } - - return $returnUrl; - } - - /** * @param Account $account * @param Carbon $date * * @return string - * @throws JsonException */ public function balanceIgnoreVirtual(Account $account, Carbon $date): string { @@ -250,6 +202,7 @@ class Steam * @param TransactionCurrency|null $currency * * @return string + * @throws FireflyException * @throws JsonException */ public function balance(Account $account, Carbon $date, ?TransactionCurrency $currency = null): string @@ -299,7 +252,6 @@ class Steam * @param Carbon $date * * @return array - * @throws FireflyException * @throws JsonException */ public function balancesByAccounts(Collection $accounts, Carbon $date): array @@ -364,7 +316,6 @@ class Steam * @param Carbon $date * * @return array - * @throws JsonException */ public function balancePerCurrency(Account $account, Carbon $date): array { @@ -391,6 +342,65 @@ class Steam return $return; } + /** + * @param string $string + * + * @return string + */ + public function filterSpaces(string $string): string + { + $search = [ + "\u{0001}", // start of heading + "\u{0002}", // start of text + "\u{0003}", // end of text + "\u{0004}", // end of transmission + "\u{0005}", // enquiry + "\u{0006}", // ACK + "\u{0007}", // BEL + "\u{0008}", // backspace + "\u{000E}", // shift out + "\u{000F}", // shift in + "\u{0010}", // data link escape + "\u{0011}", // DC1 + "\u{0012}", // DC2 + "\u{0013}", // DC3 + "\u{0014}", // DC4 + "\u{0015}", // NAK + "\u{0016}", // SYN + "\u{0017}", // ETB + "\u{0018}", // CAN + "\u{0019}", // EM + "\u{001A}", // SUB + "\u{001B}", // escape + "\u{001C}", // file separator + "\u{001D}", // group separator + "\u{001E}", // record separator + "\u{001F}", // unit separator + "\u{007F}", // DEL + "\u{00A0}", // non-breaking space + "\u{1680}", // ogham space mark + "\u{180E}", // mongolian vowel separator + "\u{2000}", // en quad + "\u{2001}", // em quad + "\u{2002}", // en space + "\u{2003}", // em space + "\u{2004}", // three-per-em space + "\u{2005}", // four-per-em space + "\u{2006}", // six-per-em space + "\u{2007}", // figure space + "\u{2008}", // punctuation space + "\u{2009}", // thin space + "\u{200A}", // hair space + "\u{200B}", // zero width space + "\u{202F}", // narrow no-break space + "\u{3000}", // ideographic space + "\u{FEFF}", // zero width no -break space + "\x20", // plain old normal space + ]; + + return str_replace($search, '', $string); + } + /** * @param array $accounts * @@ -419,6 +429,8 @@ class Steam * * @return string * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function getLocale(): string // get preference { @@ -440,6 +452,8 @@ class Steam * * @return string * @throws FireflyException + * @throws \Psr\Container\ContainerExceptionInterface + * @throws \Psr\Container\NotFoundExceptionInterface */ public function getLanguage(): string // get preference { @@ -463,6 +477,52 @@ class Steam ]; } + /** + * Returns the previous URL but refuses to send you to specific URLs. + * + * - outside domain + * - to JS files, API or JSON routes + * + * Uses the session's previousUrl() function as inspired by GitHub user @z1r0- + * + * session()->previousUrl() uses getSafeUrl() so we can safely return it: + * + * @return string + */ + public function getSafePreviousUrl(): string + { + //Log::debug(sprintf('getSafePreviousUrl: "%s"', session()->previousUrl())); + return session()->previousUrl() ?? route('index'); + } + + /** + * Make sure URL is safe. + * + * @param string $unknownUrl + * @param string $safeUrl + * + * @return string + */ + public function getSafeUrl(string $unknownUrl, string $safeUrl): string + { + //Log::debug(sprintf('getSafeUrl(%s, %s)', $unknownUrl, $safeUrl)); + $returnUrl = $safeUrl; + $unknownHost = parse_url($unknownUrl, PHP_URL_HOST); + $safeHost = parse_url($safeUrl, PHP_URL_HOST); + + if (null !== $unknownHost && $unknownHost === $safeHost) { + $returnUrl = $unknownUrl; + } + + // URL must not lead to weird pages + $forbiddenWords = ['jscript', 'json', 'debug', 'serviceworker', 'offline', 'delete', '/login', '/attachments/view']; + if (Str::contains($returnUrl, $forbiddenWords)) { + $returnUrl = $safeUrl; + } + + return $returnUrl; + } + /** * @param string $amount * @@ -473,6 +533,8 @@ class Steam if ('' === $amount) { return '0'; } + $amount = $this->floatalize($amount); + if (1 === bccomp($amount, '0')) { $amount = bcmul($amount, '-1'); } @@ -480,6 +542,34 @@ class Steam return $amount; } + /** + * https://framework.zend.com/downloads/archives + * + * Convert a scientific notation to float + * Additionally fixed a problem with PHP <= 5.2.x with big integers + * + * @param string $value + * @return string + */ + public function floatalize(string $value): string + { + $value = strtoupper($value); + if (!str_contains($value, 'E')) { + return $value; + } + + $number = substr($value, 0, strpos($value, 'E')); + if (str_contains($number, '.')) { + $post = strlen(substr($number, strpos($number, '.') + 1)); + $mantis = substr($value, strpos($value, 'E') + 1); + if ($mantis < 0) { + $post += abs((int) $mantis); + } + return number_format((float) $value, $post, '.', ''); + } + return number_format((float) $value, 0, '.', ''); + } + /** * @param string|null $amount * @@ -543,63 +633,4 @@ class Steam return $amount; } - - /** - * @param string $string - * - * @return string - */ - public function filterSpaces(string $string): string - { - $search = [ - "\u{0001}", // start of heading - "\u{0002}", // start of text - "\u{0003}", // end of text - "\u{0004}", // end of transmission - "\u{0005}", // enquiry - "\u{0006}", // ACK - "\u{0007}", // BEL - "\u{0008}", // backspace - "\u{000E}", // shift out - "\u{000F}", // shift in - "\u{0010}", // data link escape - "\u{0011}", // DC1 - "\u{0012}", // DC2 - "\u{0013}", // DC3 - "\u{0014}", // DC4 - "\u{0015}", // NAK - "\u{0016}", // SYN - "\u{0017}", // ETB - "\u{0018}", // CAN - "\u{0019}", // EM - "\u{001A}", // SUB - "\u{001B}", // escape - "\u{001C}", // file separator - "\u{001D}", // group separator - "\u{001E}", // record separator - "\u{001F}", // unit separator - "\u{007F}", // DEL - "\u{00A0}", // non-breaking space - "\u{1680}", // ogham space mark - "\u{180E}", // mongolian vowel separator - "\u{2000}", // en quad - "\u{2001}", // em quad - "\u{2002}", // en space - "\u{2003}", // em space - "\u{2004}", // three-per-em space - "\u{2005}", // four-per-em space - "\u{2006}", // six-per-em space - "\u{2007}", // figure space - "\u{2008}", // punctuation space - "\u{2009}", // thin space - "\u{200A}", // hair space - "\u{200B}", // zero width space - "\u{202F}", // narrow no-break space - "\u{3000}", // ideographic space - "\u{FEFF}", // zero width no -break space - "\x20", // plain old normal space - ]; - - return str_replace($search, '', $string); - } } diff --git a/app/Support/System/GeneratesInstallationId.php b/app/Support/System/GeneratesInstallationId.php index 417a2672f3..f03dc048c5 100644 --- a/app/Support/System/GeneratesInstallationId.php +++ b/app/Support/System/GeneratesInstallationId.php @@ -53,7 +53,7 @@ trait GeneratesInstallationId if (null === $config) { $uuid4 = Uuid::uuid4(); - $uniqueId = (string)$uuid4; + $uniqueId = (string) $uuid4; Log::info(sprintf('Created Firefly III installation ID %s', $uniqueId)); app('fireflyconfig')->set('installation_id', $uniqueId); } diff --git a/app/Support/System/OAuthKeys.php b/app/Support/System/OAuthKeys.php index 97e0dcc8d5..1eff32208e 100644 --- a/app/Support/System/OAuthKeys.php +++ b/app/Support/System/OAuthKeys.php @@ -72,9 +72,9 @@ class OAuthKeys // better check if keys are in the database: if (app('fireflyconfig')->has(self::PRIVATE_KEY) && app('fireflyconfig')->has(self::PUBLIC_KEY)) { try { - $privateKey = (string)app('fireflyconfig')->get(self::PRIVATE_KEY)?->data; - $publicKey = (string)app('fireflyconfig')->get(self::PUBLIC_KEY)?->data; - } catch (ContainerExceptionInterface | NotFoundExceptionInterface | FireflyException $e) { + $privateKey = (string) app('fireflyconfig')->get(self::PRIVATE_KEY)?->data; + $publicKey = (string) app('fireflyconfig')->get(self::PUBLIC_KEY)?->data; + } catch (ContainerExceptionInterface|NotFoundExceptionInterface|FireflyException $e) { Log::error(sprintf('Could not validate keysInDatabase(): %s', $e->getMessage())); Log::error($e->getTraceAsString()); } @@ -119,15 +119,18 @@ class OAuthKeys /** * @return bool + * @throws ContainerExceptionInterface + * @throws FireflyException + * @throws NotFoundExceptionInterface */ public static function restoreKeysFromDB(): bool { - $privateKey = (string)app('fireflyconfig')->get(self::PRIVATE_KEY)?->data; - $publicKey = (string)app('fireflyconfig')->get(self::PUBLIC_KEY)?->data; + $privateKey = (string) app('fireflyconfig')->get(self::PRIVATE_KEY)?->data; + $publicKey = (string) app('fireflyconfig')->get(self::PUBLIC_KEY)?->data; try { $privateContent = Crypt::decrypt($privateKey); $publicContent = Crypt::decrypt($publicKey); - } catch(DecryptException $e) { + } catch (DecryptException $e) { Log::error('Could not decrypt pub/private keypair.'); Log::error($e->getMessage()); @@ -137,8 +140,8 @@ class OAuthKeys return false; } - $private = storage_path('oauth-private.key'); - $public = storage_path('oauth-public.key'); + $private = storage_path('oauth-private.key'); + $public = storage_path('oauth-public.key'); file_put_contents($private, $privateContent); file_put_contents($public, $publicContent); return true; diff --git a/app/Support/Twig/AmountFormat.php b/app/Support/Twig/AmountFormat.php index b874ba32ac..5cc326111d 100644 --- a/app/Support/Twig/AmountFormat.php +++ b/app/Support/Twig/AmountFormat.php @@ -45,18 +45,6 @@ class AmountFormat extends AbstractExtension ]; } - /** - * {@inheritdoc} - */ - public function getFunctions(): array - { - return [ - $this->formatAmountByAccount(), - $this->formatAmountBySymbol(), - $this->formatAmountByCurrency(), - ]; - } - /** * @return TwigFilter */ @@ -89,6 +77,18 @@ class AmountFormat extends AbstractExtension ); } + /** + * {@inheritdoc} + */ + public function getFunctions(): array + { + return [ + $this->formatAmountByAccount(), + $this->formatAmountBySymbol(), + $this->formatAmountByCurrency(), + ]; + } + /** * Will format the amount by the currency related to the given account. * diff --git a/app/Support/Twig/General.php b/app/Support/Twig/General.php index 29e3b58c51..e1e53b521f 100644 --- a/app/Support/Twig/General.php +++ b/app/Support/Twig/General.php @@ -53,24 +53,6 @@ class General extends AbstractExtension ]; } - /** - * {@inheritdoc} - */ - public function getFunctions(): array - { - return [ - $this->phpdate(), - $this->activeRouteStrict(), - $this->activeRoutePartial(), - $this->activeRoutePartialObjectType(), - $this->menuOpenRoutePartial(), - $this->formatDate(), - $this->getMetaField(), - $this->hasRole(), - $this->getRootSearchOperator(), - ]; - } - /** * Show account balance. Only used on the front page of Firefly III. * @@ -92,24 +74,6 @@ class General extends AbstractExtension ); } - /** - * Show URL host name - * - * @return TwigFilter - */ - protected function phpHostName(): TwigFilter - { - return new TwigFilter( - 'phphost', - static function (string $string): string { - $proto = (string)parse_url($string, PHP_URL_SCHEME); - $host = (string)parse_url($string, PHP_URL_HOST); - - return e(sprintf('%s://%s', $proto, $host)); - } - ); - } - /** * Used to convert 1024 to 1kb etc. * @@ -231,7 +195,7 @@ class General extends AbstractExtension ] ); - return (string)$converter->convertToHtml($text); + return (string) $converter->convert($text); }, ['is_safe' => ['html']] ); } @@ -244,11 +208,48 @@ class General extends AbstractExtension return new TwigFilter( 'floatval', static function ($value): float { - return (float)$value; + return (float) $value; } ); } + /** + * Show URL host name + * + * @return TwigFilter + */ + protected function phpHostName(): TwigFilter + { + return new TwigFilter( + 'phphost', + static function (string $string): string { + $proto = (string) parse_url($string, PHP_URL_SCHEME); + $host = (string) parse_url($string, PHP_URL_HOST); + + return e(sprintf('%s://%s', $proto, $host)); + } + ); + } + + /** + * {@inheritdoc} + */ + public function getFunctions(): array + { + return [ + $this->phpdate(), + $this->activeRouteStrict(), + $this->activeRoutePartial(), + $this->activeRoutePartialObjectType(), + $this->menuOpenRoutePartial(), + $this->formatDate(), + $this->getMetaField(), + $this->hasRole(), + $this->getRootSearchOperator(), + $this->carbonize(), + ]; + } + /** * Basic example thing for some views. * @@ -369,7 +370,7 @@ class General extends AbstractExtension function (string $date, string $format): string { $carbon = new Carbon($date); - return $carbon->formatLocalized($format); + return $carbon->isoFormat($format); } ); } @@ -424,4 +425,17 @@ class General extends AbstractExtension } ); } + + /** + * @return TwigFunction + */ + protected function carbonize(): TwigFunction + { + return new TwigFunction( + 'carbonize', + static function (string $date): Carbon { + return new Carbon($date); + } + ); + } } diff --git a/app/Support/Twig/Rule.php b/app/Support/Twig/Rule.php index 45e197a9bd..564547b325 100644 --- a/app/Support/Twig/Rule.php +++ b/app/Support/Twig/Rule.php @@ -52,8 +52,8 @@ class Rule extends AbstractExtension 'allJournalTriggers', static function () { return [ - 'store-journal' => (string)trans('firefly.rule_trigger_store_journal'), - 'update-journal' => (string)trans('firefly.rule_trigger_update_journal'), + 'store-journal' => (string) trans('firefly.rule_trigger_store_journal'), + 'update-journal' => (string) trans('firefly.rule_trigger_update_journal'), ]; } ); @@ -67,11 +67,11 @@ class Rule extends AbstractExtension return new TwigFunction( 'allRuleTriggers', static function () { - $ruleTriggers = array_keys(config('firefly.search.operators')); + $ruleTriggers = array_keys(config('search.operators')); $possibleTriggers = []; foreach ($ruleTriggers as $key) { if ('user_action' !== $key) { - $possibleTriggers[$key] = (string)trans('firefly.rule_trigger_' . $key . '_choice'); + $possibleTriggers[$key] = (string) trans('firefly.rule_trigger_' . $key . '_choice'); } } unset($ruleTriggers); @@ -94,7 +94,7 @@ class Rule extends AbstractExtension $ruleActions = array_keys(Config::get('firefly.rule-actions')); $possibleActions = []; foreach ($ruleActions as $key) { - $possibleActions[$key] = (string)trans('firefly.rule_action_' . $key . '_choice'); + $possibleActions[$key] = (string) trans('firefly.rule_action_' . $key . '_choice'); } unset($ruleActions); asort($possibleActions); diff --git a/app/Support/Twig/TransactionGroupTwig.php b/app/Support/Twig/TransactionGroupTwig.php index 31e9c558b1..2c0a38fbb4 100644 --- a/app/Support/Twig/TransactionGroupTwig.php +++ b/app/Support/Twig/TransactionGroupTwig.php @@ -96,7 +96,7 @@ class TransactionGroupTwig extends AbstractExtension $colored = false; } - $result = app('amount')->formatFlat($array['currency_symbol'], (int)$array['currency_decimal_places'], $amount, $colored); + $result = app('amount')->formatFlat($array['currency_symbol'], (int) $array['currency_decimal_places'], $amount, $colored); if ($type === TransactionType::TRANSFER) { $result = sprintf('%s', $result); } @@ -151,7 +151,7 @@ class TransactionGroupTwig extends AbstractExtension if ($type === TransactionType::TRANSFER) { $colored = false; } - $result = app('amount')->formatFlat($array['foreign_currency_symbol'], (int)$array['foreign_currency_decimal_places'], $amount, $colored); + $result = app('amount')->formatFlat($array['foreign_currency_symbol'], (int) $array['foreign_currency_decimal_places'], $amount, $colored); if ($type === TransactionType::TRANSFER) { $result = sprintf('%s', $result); } @@ -203,7 +203,7 @@ class TransactionGroupTwig extends AbstractExtension if ($type === TransactionType::TRANSFER) { $colored = false; } - $result = app('amount')->formatFlat($currency->symbol, (int)$currency->decimal_places, $amount, $colored); + $result = app('amount')->formatFlat($currency->symbol, (int) $currency->decimal_places, $amount, $colored); if ($type === TransactionType::TRANSFER) { $result = sprintf('%s', $result); } @@ -246,7 +246,7 @@ class TransactionGroupTwig extends AbstractExtension if ($type === TransactionType::TRANSFER) { $colored = false; } - $result = app('amount')->formatFlat($currency->symbol, (int)$currency->decimal_places, $amount, $colored); + $result = app('amount')->formatFlat($currency->symbol, (int) $currency->decimal_places, $amount, $colored); if ($type === TransactionType::TRANSFER) { $result = sprintf('%s', $result); } diff --git a/app/Support/Twig/Translation.php b/app/Support/Twig/Translation.php index 96dcd50083..752fd27c79 100644 --- a/app/Support/Twig/Translation.php +++ b/app/Support/Twig/Translation.php @@ -40,7 +40,7 @@ class Translation extends AbstractExtension new TwigFilter( '_', static function ($name) { - return (string)trans(sprintf('firefly.%s', $name)); + return (string) trans(sprintf('firefly.%s', $name)); }, ['is_safe' => ['html']] ), @@ -65,7 +65,7 @@ class Translation extends AbstractExtension return new TwigFunction( 'journalLinkTranslation', static function (string $direction, string $original) { - $key = sprintf('firefly.%s_%s', $original, $direction); + $key = sprintf('firefly.%s_%s', $original, $direction); $translation = trans($key); if ($key === $translation) { return $original; diff --git a/app/TransactionRules/Actions/AppendNotes.php b/app/TransactionRules/Actions/AppendNotes.php index 608515f777..62350cbd44 100644 --- a/app/TransactionRules/Actions/AppendNotes.php +++ b/app/TransactionRules/Actions/AppendNotes.php @@ -52,12 +52,12 @@ class AppendNotes implements ActionInterface { $dbNote = Note :: - where('noteable_id', (int)$journal['transaction_journal_id']) + where('noteable_id', (int) $journal['transaction_journal_id']) ->where('noteable_type', TransactionJournal::class) ->first(['notes.*']); if (null === $dbNote) { $dbNote = new Note; - $dbNote->noteable_id = (int)$journal['transaction_journal_id']; + $dbNote->noteable_id = (int) $journal['transaction_journal_id']; $dbNote->noteable_type = TransactionJournal::class; $dbNote->text = ''; } diff --git a/app/TransactionRules/Actions/LinkToBill.php b/app/TransactionRules/Actions/LinkToBill.php index c813ef58eb..5de381a3ab 100644 --- a/app/TransactionRules/Actions/LinkToBill.php +++ b/app/TransactionRules/Actions/LinkToBill.php @@ -58,7 +58,7 @@ class LinkToBill implements ActionInterface /** @var BillRepositoryInterface $repository */ $repository = app(BillRepositoryInterface::class); $repository->setUser($user); - $billName = (string)$this->action->action_value; + $billName = (string) $this->action->action_value; $bill = $repository->findByName($billName); if (null !== $bill && $journal['transaction_type_type'] === TransactionType::WITHDRAWAL) { diff --git a/app/TransactionRules/Actions/PrependNotes.php b/app/TransactionRules/Actions/PrependNotes.php index 569b332dce..4a9f97a426 100644 --- a/app/TransactionRules/Actions/PrependNotes.php +++ b/app/TransactionRules/Actions/PrependNotes.php @@ -52,12 +52,12 @@ class PrependNotes implements ActionInterface { $dbNote = Note :: - where('noteable_id', (int)$journal['transaction_journal_id']) + where('noteable_id', (int) $journal['transaction_journal_id']) ->where('noteable_type', TransactionJournal::class) ->first(['notes.*']); if (null === $dbNote) { $dbNote = new Note; - $dbNote->noteable_id = (int)$journal['transaction_journal_id']; + $dbNote->noteable_id = (int) $journal['transaction_journal_id']; $dbNote->noteable_type = TransactionJournal::class; $dbNote->text = ''; } diff --git a/app/TransactionRules/Actions/SetDestinationAccount.php b/app/TransactionRules/Actions/SetDestinationAccount.php index bcb1a776a5..4f70ed6e36 100644 --- a/app/TransactionRules/Actions/SetDestinationAccount.php +++ b/app/TransactionRules/Actions/SetDestinationAccount.php @@ -58,7 +58,7 @@ class SetDestinationAccount implements ActionInterface $user = User::find($journal['user_id']); $type = $journal['transaction_type_type']; /** @var TransactionJournal|null $object */ - $object = $user->transactionJournals()->find((int)$journal['transaction_journal_id']); + $object = $user->transactionJournals()->find((int) $journal['transaction_journal_id']); $this->repository = app(AccountRepositoryInterface::class); if (null === $object) { @@ -66,7 +66,7 @@ class SetDestinationAccount implements ActionInterface return false; } - + $type = $object->transactionType->type; $this->repository->setUser($user); // if this is a transfer or a deposit, the new destination account must be an asset account or a default account, and it MUST exist: @@ -95,7 +95,7 @@ class SetDestinationAccount implements ActionInterface return false; } - if (null !== $newAccount && (int)$newAccount->id === (int)$source->account_id) { + if (null !== $newAccount && (int) $newAccount->id === (int) $source->account_id) { Log::error( sprintf( 'New destination account ID #%d and current source account ID #%d are the same. Do nothing.', $newAccount->id, diff --git a/app/TransactionRules/Actions/SetSourceAccount.php b/app/TransactionRules/Actions/SetSourceAccount.php index 42e6c83356..21d4b60561 100644 --- a/app/TransactionRules/Actions/SetSourceAccount.php +++ b/app/TransactionRules/Actions/SetSourceAccount.php @@ -58,15 +58,14 @@ class SetSourceAccount implements ActionInterface $user = User::find($journal['user_id']); $type = $journal['transaction_type_type']; /** @var TransactionJournal|null $object */ - $object = $user->transactionJournals()->find((int)$journal['transaction_journal_id']); + $object = $user->transactionJournals()->find((int) $journal['transaction_journal_id']); $this->repository = app(AccountRepositoryInterface::class); - if (null === $object) { Log::error('Could not find journal.'); return false; } - + $type = $object->transactionType->type; $this->repository->setUser($user); // if this is a transfer or a withdrawal, the new source account must be an asset account or a default account, and it MUST exist: @@ -93,7 +92,7 @@ class SetSourceAccount implements ActionInterface return false; } - if (null !== $newAccount && (int)$newAccount->id === (int)$destination->account_id) { + if (null !== $newAccount && (int) $newAccount->id === (int) $destination->account_id) { Log::error( sprintf( 'New source account ID #%d and current destination account ID #%d are the same. Do nothing.', $newAccount->id, diff --git a/app/TransactionRules/Actions/UpdatePiggybank.php b/app/TransactionRules/Actions/UpdatePiggybank.php index 6e4dcc0392..614c771b0f 100644 --- a/app/TransactionRules/Actions/UpdatePiggybank.php +++ b/app/TransactionRules/Actions/UpdatePiggybank.php @@ -61,7 +61,7 @@ class UpdatePiggybank implements ActionInterface // refresh the transaction type. $user = User::find($journal['user_id']); $journalObj = $user->transactionJournals()->find($journal['transaction_journal_id']); - $type = TransactionType::find((int)$journalObj->transaction_type_id); + $type = TransactionType::find((int) $journalObj->transaction_type_id); $journal['transaction_type_type'] = $type->type; if (TransactionType::TRANSFER !== $journal['transaction_type_type']) { @@ -86,13 +86,13 @@ class UpdatePiggybank implements ActionInterface /** @var Transaction $destination */ $destination = Transaction::where('transaction_journal_id', $journal['transaction_journal_id'])->where('amount', '>', 0)->first(); - if ((int)$source->account_id === (int)$piggyBank->account_id) { + if ((int) $source->account_id === (int) $piggyBank->account_id) { Log::debug('Piggy bank account is linked to source, so remove amount.'); $this->removeAmount($journal, $piggyBank, $destination->amount); return true; } - if ((int)$destination->account_id === (int)$piggyBank->account_id) { + if ((int) $destination->account_id === (int) $piggyBank->account_id) { Log::debug('Piggy bank account is linked to source, so add amount.'); $this->addAmount($journal, $piggyBank, $destination->amount); diff --git a/app/TransactionRules/Engine/SearchRuleEngine.php b/app/TransactionRules/Engine/SearchRuleEngine.php index 113dedddb7..8afcae7b81 100644 --- a/app/TransactionRules/Engine/SearchRuleEngine.php +++ b/app/TransactionRules/Engine/SearchRuleEngine.php @@ -86,84 +86,6 @@ class SearchRuleEngine implements RuleEngineInterface return $collection->unique(); } - /** - * @inheritDoc - * @throws FireflyException - */ - public function fire(): void - { - $this->resultCount = []; - Log::debug('SearchRuleEngine::fire()!'); - - // if rules and no rule groups, file each rule separately. - if (0 !== $this->rules->count()) { - Log::debug(sprintf('SearchRuleEngine:: found %d rule(s) to fire.', $this->rules->count())); - foreach ($this->rules as $rule) { - $this->fireRule($rule); - } - Log::debug('SearchRuleEngine:: done processing all rules!'); - - return; - } - if (0 !== $this->groups->count()) { - Log::debug(sprintf('SearchRuleEngine:: found %d rule group(s) to fire.', $this->groups->count())); - // fire each group: - /** @var RuleGroup $group */ - foreach ($this->groups as $group) { - $this->fireGroup($group); - } - } - Log::debug('SearchRuleEngine:: done processing all rules!'); - } - - /** - * Return the number of changed transactions from the previous "fire" action. - * - * @return int - */ - public function getResults(): int - { - return count($this->resultCount); - } - - /** - * @inheritDoc - */ - public function setRuleGroups(Collection $ruleGroups): void - { - Log::debug(__METHOD__); - foreach ($ruleGroups as $group) { - if ($group instanceof RuleGroup) { - Log::debug(sprintf('Adding a rule group to the SearchRuleEngine: #%d ("%s")', $group->id, $group->title)); - $this->groups->push($group); - } - } - } - - /** - * @inheritDoc - */ - public function setRules(Collection $rules): void - { - - Log::debug(__METHOD__); - foreach ($rules as $rule) { - if ($rule instanceof Rule) { - Log::debug(sprintf('Adding a rule to the SearchRuleEngine: #%d ("%s")', $rule->id, $rule->title)); - $this->rules->push($rule); - } - } - } - - /** - * @inheritDoc - */ - public function setUser(User $user): void - { - $this->user = $user; - $this->operators = []; - } - /** * Finds the transactions a strict rule will execute on. * @@ -186,7 +108,7 @@ class SearchRuleEngine implements RuleEngineInterface } // if needs no context, value is different: - $needsContext = config(sprintf('firefly.search.operators.%s.needs_context', $ruleTrigger->trigger_type)) ?? true; + $needsContext = config(sprintf('search.operators.%s.needs_context', $ruleTrigger->trigger_type)) ?? true; if (false === $needsContext) { Log::debug(sprintf('SearchRuleEngine:: add a rule trigger: %s:true', $ruleTrigger->trigger_type)); $searchArray[$ruleTrigger->trigger_type][] = 'true'; @@ -266,7 +188,7 @@ class SearchRuleEngine implements RuleEngineInterface $journalId = 0; foreach ($array as $triggerName => $values) { if ('journal_id' === $triggerName && is_array($values) && 1 === count($values)) { - $journalId = (int)trim(($values[0] ?? '"0"'), '"'); // follows format "123". + $journalId = (int) trim(($values[0] ?? '"0"'), '"'); // follows format "123". Log::debug(sprintf('Found journal ID #%d', $journalId)); } } @@ -310,7 +232,7 @@ class SearchRuleEngine implements RuleEngineInterface continue; } $searchArray = []; - $needsContext = config(sprintf('firefly.search.operators.%s.needs_context', $ruleTrigger->trigger_type)) ?? true; + $needsContext = config(sprintf('search.operators.%s.needs_context', $ruleTrigger->trigger_type)) ?? true; if (false === $needsContext) { Log::debug(sprintf('SearchRuleEngine:: non strict, will search for: %s:true', $ruleTrigger->trigger_type)); $searchArray[$ruleTrigger->trigger_type] = 'true'; @@ -365,6 +287,36 @@ class SearchRuleEngine implements RuleEngineInterface return $unique; } + /** + * @inheritDoc + * @throws FireflyException + */ + public function fire(): void + { + $this->resultCount = []; + Log::debug('SearchRuleEngine::fire()!'); + + // if rules and no rule groups, file each rule separately. + if (0 !== $this->rules->count()) { + Log::debug(sprintf('SearchRuleEngine:: found %d rule(s) to fire.', $this->rules->count())); + foreach ($this->rules as $rule) { + $this->fireRule($rule); + } + Log::debug('SearchRuleEngine:: done processing all rules!'); + + return; + } + if (0 !== $this->groups->count()) { + Log::debug(sprintf('SearchRuleEngine:: found %d rule group(s) to fire.', $this->groups->count())); + // fire each group: + /** @var RuleGroup $group */ + foreach ($this->groups as $group) { + $this->fireGroup($group); + } + } + Log::debug('SearchRuleEngine:: done processing all rules!'); + } + /** * Returns true if the rule has been triggered. * @@ -460,7 +412,7 @@ class SearchRuleEngine implements RuleEngineInterface $actions = $rule->ruleActions()->get(); /** @var RuleAction $ruleAction */ foreach ($actions as $ruleAction) { - if(false === $ruleAction->active) { + if (false === $ruleAction->active) { continue; } $break = $this->processRuleAction($ruleAction, $transaction); @@ -530,10 +482,10 @@ class SearchRuleEngine implements RuleEngineInterface /** * @param RuleGroup $group * - * @return bool + * @return void * @throws FireflyException */ - private function fireGroup(RuleGroup $group): bool + private function fireGroup(RuleGroup $group): void { $all = false; Log::debug(sprintf('Going to fire group #%d with %d rule(s)', $group->id, $group->rules->count())); @@ -547,10 +499,57 @@ class SearchRuleEngine implements RuleEngineInterface if (true === $result && true === $rule->stop_processing) { Log::debug(sprintf('The rule was triggered and rule->stop_processing = true, so group #%d will stop processing further rules.', $group->id)); - return true; + return; } } - return $all; + } + + /** + * Return the number of changed transactions from the previous "fire" action. + * + * @return int + */ + public function getResults(): int + { + return count($this->resultCount); + } + + /** + * @inheritDoc + */ + public function setRuleGroups(Collection $ruleGroups): void + { + Log::debug(__METHOD__); + foreach ($ruleGroups as $group) { + if ($group instanceof RuleGroup) { + Log::debug(sprintf('Adding a rule group to the SearchRuleEngine: #%d ("%s")', $group->id, $group->title)); + $this->groups->push($group); + } + } + } + + /** + * @inheritDoc + */ + public function setRules(Collection $rules): void + { + + Log::debug(__METHOD__); + foreach ($rules as $rule) { + if ($rule instanceof Rule) { + Log::debug(sprintf('Adding a rule to the SearchRuleEngine: #%d ("%s")', $rule->id, $rule->title)); + $this->rules->push($rule); + } + } + } + + /** + * @inheritDoc + */ + public function setUser(User $user): void + { + $this->user = $user; + $this->operators = []; } } diff --git a/app/Transformers/AccountTransformer.php b/app/Transformers/AccountTransformer.php index 2d99589767..19649aaedb 100644 --- a/app/Transformers/AccountTransformer.php +++ b/app/Transformers/AccountTransformer.php @@ -53,7 +53,6 @@ class AccountTransformer extends AbstractTransformer * @param Account $account * * @return array - * @throws FireflyException * @throws JsonException */ public function transform(Account $account): array @@ -62,8 +61,8 @@ class AccountTransformer extends AbstractTransformer // get account type: $fullType = $account->accountType->type; - $accountType = (string)config(sprintf('firefly.shortNamesByFullName.%s', $fullType)); - $liabilityType = (string)config(sprintf('firefly.shortLiabilityNameByFullName.%s', $fullType)); + $accountType = (string) config(sprintf('firefly.shortNamesByFullName.%s', $fullType)); + $liabilityType = (string) config(sprintf('firefly.shortLiabilityNameByFullName.%s', $fullType)); $liabilityType = '' === $liabilityType ? null : strtolower($liabilityType); $liabilityDirection = $this->repository->getMetaValue($account, 'liability_direction'); @@ -77,7 +76,7 @@ class AccountTransformer extends AbstractTransformer [$openingBalance, $openingBalanceDate] = $this->getOpeningBalance($account, $accountType); [$interest, $interestPeriod] = $this->getInterest($account, $accountType); - $openingBalance = number_format((float)$openingBalance, $decimalPlaces, '.', ''); + $openingBalance = number_format((float) $openingBalance, $decimalPlaces, '.', ''); $includeNetWorth = '0' !== $this->repository->getMetaValue($account, 'include_net_worth'); $longitude = null; $latitude = null; @@ -86,17 +85,17 @@ class AccountTransformer extends AbstractTransformer if (null !== $location) { $longitude = $location->longitude; $latitude = $location->latitude; - $zoomLevel = (int)$location->zoom_level; + $zoomLevel = (int) $location->zoom_level; } // no order for some accounts: - $order = (int)$account->order; + $order = (int) $account->order; if (!in_array(strtolower($accountType), ['liability', 'liabilities', 'asset'])) { $order = null; } return [ - 'id' => (string)$account->id, + 'id' => (string) $account->id, 'created_at' => $account->created_at->toAtomString(), 'updated_at' => $account->updated_at->toAtomString(), 'active' => $account->active, @@ -108,7 +107,7 @@ class AccountTransformer extends AbstractTransformer 'currency_code' => $currencyCode, 'currency_symbol' => $currencySymbol, 'currency_decimal_places' => $decimalPlaces, - 'current_balance' => number_format((float)app('steam')->balance($account, $date), $decimalPlaces, '.', ''), + 'current_balance' => number_format((float) app('steam')->balance($account, $date), $decimalPlaces, '.', ''), 'current_balance_date' => $date->toAtomString(), 'notes' => $this->repository->getNoteText($account), 'monthly_payment_date' => $monthlyPaymentDate, @@ -116,7 +115,7 @@ class AccountTransformer extends AbstractTransformer 'account_number' => $this->repository->getMetaValue($account, 'account_number'), 'iban' => '' === $account->iban ? null : $account->iban, 'bic' => $this->repository->getMetaValue($account, 'BIC'), - 'virtual_balance' => number_format((float)$account->virtual_balance, $decimalPlaces, '.', ''), + 'virtual_balance' => number_format((float) $account->virtual_balance, $decimalPlaces, '.', ''), 'opening_balance' => $openingBalance, 'opening_balance_date' => $openingBalanceDate, 'liability_type' => $liabilityType, @@ -147,7 +146,7 @@ class AccountTransformer extends AbstractTransformer private function getAccountRole(Account $account, string $accountType): ?string { $accountRole = $this->repository->getMetaValue($account, 'account_role'); - if ('asset' !== $accountType || '' === (string)$accountRole) { + if ('asset' !== $accountType || '' === (string) $accountRole) { $accountRole = null; } @@ -171,6 +170,8 @@ class AccountTransformer extends AbstractTransformer * @param Account $account * * @return array + * @throws FireflyException + * @throws JsonException */ private function getCurrency(Account $account): array { @@ -180,7 +181,7 @@ class AccountTransformer extends AbstractTransformer if (null === $currency) { $currency = app('amount')->getDefaultCurrencyByUser($account->user); } - $currencyId = (string)$currency->id; + $currencyId = (string) $currency->id; $currencyCode = $currency->code; $decimalPlaces = $currency->decimal_places; $currencySymbol = $currency->symbol; diff --git a/app/Transformers/AttachmentTransformer.php b/app/Transformers/AttachmentTransformer.php index 5d858ddd25..430feeb9b1 100644 --- a/app/Transformers/AttachmentTransformer.php +++ b/app/Transformers/AttachmentTransformer.php @@ -55,10 +55,10 @@ class AttachmentTransformer extends AbstractTransformer $this->repository->setUser($attachment->user); return [ - 'id' => (string)$attachment->id, + 'id' => (string) $attachment->id, 'created_at' => $attachment->created_at->toAtomString(), 'updated_at' => $attachment->updated_at->toAtomString(), - 'attachable_id' => (string)$attachment->attachable_id, + 'attachable_id' => (string) $attachment->attachable_id, 'attachable_type' => str_replace('FireflyIII\\Models\\', '', $attachment->attachable_type), 'md5' => $attachment->md5, 'filename' => $attachment->filename, @@ -67,7 +67,7 @@ class AttachmentTransformer extends AbstractTransformer 'title' => $attachment->title, 'notes' => $this->repository->getNoteText($attachment), 'mime' => $attachment->mime, - 'size' => (int)$attachment->size, + 'size' => (int) $attachment->size, 'links' => [ [ 'rel' => 'self', diff --git a/app/Transformers/AvailableBudgetTransformer.php b/app/Transformers/AvailableBudgetTransformer.php index 69ed09f4fa..b9fd050673 100644 --- a/app/Transformers/AvailableBudgetTransformer.php +++ b/app/Transformers/AvailableBudgetTransformer.php @@ -62,14 +62,14 @@ class AvailableBudgetTransformer extends AbstractTransformer $currency = $availableBudget->transactionCurrency; $data = [ - 'id' => (string)$availableBudget->id, + 'id' => (string) $availableBudget->id, 'created_at' => $availableBudget->created_at->toAtomString(), 'updated_at' => $availableBudget->updated_at->toAtomString(), - 'currency_id' => (string)$currency->id, + 'currency_id' => (string) $currency->id, 'currency_code' => $currency->code, 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => (int)$currency->decimal_places, - 'amount' => number_format((float)$availableBudget->amount, $currency->decimal_places, '.', ''), + 'currency_decimal_places' => (int) $currency->decimal_places, + 'amount' => number_format((float) $availableBudget->amount, $currency->decimal_places, '.', ''), 'start' => $availableBudget->start_date->toAtomString(), 'end' => $availableBudget->end_date->endOfDay()->toAtomString(), 'spent_in_budgets' => [], diff --git a/app/Transformers/BillTransformer.php b/app/Transformers/BillTransformer.php index b56417b7ce..9885840f30 100644 --- a/app/Transformers/BillTransformer.php +++ b/app/Transformers/BillTransformer.php @@ -24,6 +24,7 @@ declare(strict_types=1); namespace FireflyIII\Transformers; use Carbon\Carbon; +use Carbon\CarbonInterface; use FireflyIII\Models\Bill; use FireflyIII\Models\ObjectGroup; use FireflyIII\Models\TransactionJournal; @@ -71,8 +72,8 @@ class BillTransformer extends AbstractTransformer /** @var ObjectGroup $objectGroup */ $objectGroup = $bill->objectGroups->first(); if (null !== $objectGroup) { - $objectGroupId = (int)$objectGroup->id; - $objectGroupOrder = (int)$objectGroup->order; + $objectGroupId = (int) $objectGroup->id; + $objectGroupOrder = (int) $objectGroup->order; $objectGroupTitle = $objectGroup->title; } @@ -101,30 +102,30 @@ class BillTransformer extends AbstractTransformer $current = $payDatesFormatted[0] ?? null; if (null !== $current && !$temp->isToday()) { $temp2 = Carbon::createFromFormat('Y-m-d\TH:i:sP', $current); - $nextExpectedMatchDiff = $temp2->diffForHumans(today(), Carbon::DIFF_RELATIVE_TO_NOW); + $nextExpectedMatchDiff = $temp2->diffForHumans(today(), CarbonInterface::DIFF_RELATIVE_TO_NOW); } unset($temp, $temp2); return [ - 'id' => (int)$bill->id, + 'id' => (int) $bill->id, 'created_at' => $bill->created_at->toAtomString(), 'updated_at' => $bill->updated_at->toAtomString(), - 'currency_id' => (string)$bill->transaction_currency_id, + 'currency_id' => (string) $bill->transaction_currency_id, 'currency_code' => $currency->code, 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => (int)$currency->decimal_places, + 'currency_decimal_places' => (int) $currency->decimal_places, 'name' => $bill->name, - 'amount_min' => number_format((float)$bill->amount_min, $currency->decimal_places, '.', ''), - 'amount_max' => number_format((float)$bill->amount_max, $currency->decimal_places, '.', ''), + 'amount_min' => number_format((float) $bill->amount_min, $currency->decimal_places, '.', ''), + 'amount_max' => number_format((float) $bill->amount_max, $currency->decimal_places, '.', ''), 'date' => $bill->date->toAtomString(), 'end_date' => $bill->end_date?->toAtomString(), 'extension_date' => $bill->extension_date?->toAtomString(), 'repeat_freq' => $bill->repeat_freq, - 'skip' => (int)$bill->skip, + 'skip' => (int) $bill->skip, 'active' => $bill->active, - 'order' => (int)$bill->order, + 'order' => (int) $bill->order, 'notes' => $notes, - 'object_group_id' => $objectGroupId ? (string)$objectGroupId : null, + 'object_group_id' => $objectGroupId ? (string) $objectGroupId : null, 'object_group_order' => $objectGroupOrder, 'object_group_title' => $objectGroupTitle, @@ -202,8 +203,8 @@ class BillTransformer extends AbstractTransformer $result = []; foreach ($set as $entry) { $result[] = [ - 'transaction_group_id' => (int)$entry->transaction_group_id, - 'transaction_journal_id' => (int)$entry->id, + 'transaction_group_id' => (int) $entry->transaction_group_id, + 'transaction_journal_id' => (int) $entry->id, 'date' => $entry->date->format('Y-m-d'), ]; } @@ -267,7 +268,7 @@ class BillTransformer extends AbstractTransformer $nextExpectedMatch->addDay(); $currentStart = clone $nextExpectedMatch; $loop++; - if($loop > 4) { + if ($loop > 4) { break; } } diff --git a/app/Transformers/BudgetLimitTransformer.php b/app/Transformers/BudgetLimitTransformer.php index dfcc2e43ba..efea0b5d7f 100644 --- a/app/Transformers/BudgetLimitTransformer.php +++ b/app/Transformers/BudgetLimitTransformer.php @@ -34,7 +34,7 @@ use League\Fractal\Resource\Item; class BudgetLimitTransformer extends AbstractTransformer { /** @var string[] */ - protected $availableIncludes + protected array $availableIncludes = [ 'budget', ]; @@ -74,22 +74,22 @@ class BudgetLimitTransformer extends AbstractTransformer $currencySymbol = null; if (null !== $currency) { $amount = $budgetLimit->amount; - $currencyId = (int)$currency->id; + $currencyId = (int) $currency->id; $currencyName = $currency->name; $currencyCode = $currency->code; $currencySymbol = $currency->symbol; $currencyDecimalPlaces = $currency->decimal_places; } - $amount = number_format((float)$amount, $currencyDecimalPlaces, '.', ''); + $amount = number_format((float) $amount, $currencyDecimalPlaces, '.', ''); return [ - 'id' => (string)$budgetLimit->id, + 'id' => (string) $budgetLimit->id, 'created_at' => $budgetLimit->created_at->toAtomString(), 'updated_at' => $budgetLimit->updated_at->toAtomString(), 'start' => $budgetLimit->start_date->toAtomString(), 'end' => $budgetLimit->end_date->endOfDay()->toAtomString(), - 'budget_id' => (string)$budgetLimit->budget_id, - 'currency_id' => (string)$currencyId, + 'budget_id' => (string) $budgetLimit->budget_id, + 'currency_id' => (string) $currencyId, 'currency_code' => $currencyCode, 'currency_name' => $currencyName, 'currency_decimal_places' => $currencyDecimalPlaces, diff --git a/app/Transformers/BudgetTransformer.php b/app/Transformers/BudgetTransformer.php index 7203cc5d83..3f5cf67e95 100644 --- a/app/Transformers/BudgetTransformer.php +++ b/app/Transformers/BudgetTransformer.php @@ -73,6 +73,7 @@ class BudgetTransformer extends AbstractTransformer $abType = null; $abAmount = null; $abPeriod = null; + $notes = $this->repository->getNoteText($budget); $types = [ AutoBudget::AUTO_BUDGET_RESET => 'reset', @@ -80,20 +81,21 @@ class BudgetTransformer extends AbstractTransformer ]; if (null !== $autoBudget) { - $abCurrencyId = (string)$autoBudget->transactionCurrency->id; + $abCurrencyId = (string) $autoBudget->transactionCurrency->id; $abCurrencyCode = $autoBudget->transactionCurrency->code; $abType = $types[$autoBudget->auto_budget_type]; - $abAmount = number_format((float)$autoBudget->amount, $autoBudget->transactionCurrency->decimal_places, '.', ''); + $abAmount = number_format((float) $autoBudget->amount, $autoBudget->transactionCurrency->decimal_places, '.', ''); $abPeriod = $autoBudget->period; } return [ - 'id' => (string)$budget->id, + 'id' => (string) $budget->id, 'created_at' => $budget->created_at->toAtomString(), 'updated_at' => $budget->updated_at->toAtomString(), 'active' => $budget->active, 'name' => $budget->name, - 'order' => $budget->order, + 'order' => $budget->order, + 'notes' => $notes, 'auto_budget_type' => $abType, 'auto_budget_period' => $abPeriod, 'auto_budget_currency_id' => $abCurrencyId, @@ -118,7 +120,7 @@ class BudgetTransformer extends AbstractTransformer { $return = []; foreach ($array as $data) { - $data['sum'] = number_format((float)$data['sum'], (int)$data['currency_decimal_places'], '.', ''); + $data['sum'] = number_format((float) $data['sum'], (int) $data['currency_decimal_places'], '.', ''); $return[] = $data; } diff --git a/app/Transformers/CategoryTransformer.php b/app/Transformers/CategoryTransformer.php index 129e95d357..295b30fa01 100644 --- a/app/Transformers/CategoryTransformer.php +++ b/app/Transformers/CategoryTransformer.php @@ -70,7 +70,7 @@ class CategoryTransformer extends AbstractTransformer $notes = $this->repository->getNoteText($category); return [ - 'id' => (int)$category->id, + 'id' => (int) $category->id, 'created_at' => $category->created_at->toAtomString(), 'updated_at' => $category->updated_at->toAtomString(), 'name' => $category->name, @@ -95,7 +95,7 @@ class CategoryTransformer extends AbstractTransformer { $return = []; foreach ($array as $data) { - $data['sum'] = number_format((float)$data['sum'], (int)$data['currency_decimal_places'], '.', ''); + $data['sum'] = number_format((float) $data['sum'], (int) $data['currency_decimal_places'], '.', ''); $return[] = $data; } diff --git a/app/Transformers/CurrencyTransformer.php b/app/Transformers/CurrencyTransformer.php index 0c3e1b7966..ab78269e8e 100644 --- a/app/Transformers/CurrencyTransformer.php +++ b/app/Transformers/CurrencyTransformer.php @@ -43,11 +43,11 @@ class CurrencyTransformer extends AbstractTransformer $isDefault = false; $defaultCurrency = $this->parameters->get('defaultCurrency'); if (null !== $defaultCurrency) { - $isDefault = (int)$defaultCurrency->id === (int)$currency->id; + $isDefault = (int) $defaultCurrency->id === (int) $currency->id; } return [ - 'id' => (int)$currency->id, + 'id' => (int) $currency->id, 'created_at' => $currency->created_at->toAtomString(), 'updated_at' => $currency->updated_at->toAtomString(), 'default' => $isDefault, @@ -55,7 +55,7 @@ class CurrencyTransformer extends AbstractTransformer 'name' => $currency->name, 'code' => $currency->code, 'symbol' => $currency->symbol, - 'decimal_places' => (int)$currency->decimal_places, + 'decimal_places' => (int) $currency->decimal_places, 'links' => [ [ 'rel' => 'self', diff --git a/app/Transformers/LinkTypeTransformer.php b/app/Transformers/LinkTypeTransformer.php index 13f3b36eb5..b1e1097ed5 100644 --- a/app/Transformers/LinkTypeTransformer.php +++ b/app/Transformers/LinkTypeTransformer.php @@ -41,7 +41,7 @@ class LinkTypeTransformer extends AbstractTransformer public function transform(LinkType $linkType): array { return [ - 'id' => (int)$linkType->id, + 'id' => (int) $linkType->id, 'created_at' => $linkType->created_at->toAtomString(), 'updated_at' => $linkType->updated_at->toAtomString(), 'name' => $linkType->name, diff --git a/app/Transformers/ObjectGroupTransformer.php b/app/Transformers/ObjectGroupTransformer.php index d8c19bc2bd..48cb6d48cf 100644 --- a/app/Transformers/ObjectGroupTransformer.php +++ b/app/Transformers/ObjectGroupTransformer.php @@ -56,11 +56,11 @@ class ObjectGroupTransformer extends AbstractTransformer $this->repository->setUser($objectGroup->user); return [ - 'id' => (string)$objectGroup->id, + 'id' => (string) $objectGroup->id, 'created_at' => $objectGroup->created_at->toAtomString(), 'updated_at' => $objectGroup->updated_at->toAtomString(), 'title' => $objectGroup->title, - 'order' => (int)$objectGroup->order, + 'order' => (int) $objectGroup->order, 'links' => [ [ 'rel' => 'self', diff --git a/app/Transformers/PiggyBankEventTransformer.php b/app/Transformers/PiggyBankEventTransformer.php index 7f5af318fe..80da4595c1 100644 --- a/app/Transformers/PiggyBankEventTransformer.php +++ b/app/Transformers/PiggyBankEventTransformer.php @@ -55,6 +55,8 @@ class PiggyBankEventTransformer extends AbstractTransformer * @param PiggyBankEvent $event * * @return array + * @throws \FireflyIII\Exceptions\FireflyException + * @throws \JsonException */ public function transform(PiggyBankEvent $event): array { @@ -72,22 +74,22 @@ class PiggyBankEventTransformer extends AbstractTransformer // get associated journal and transaction, if any: $journalId = $event->transaction_journal_id; $groupId = null; - if (0 !== (int)$journalId) { - $groupId = (int)$event->transactionJournal->transaction_group_id; - $journalId = (int)$journalId; + if (0 !== (int) $journalId) { + $groupId = (int) $event->transactionJournal->transaction_group_id; + $journalId = (int) $journalId; } return [ - 'id' => (string)$event->id, + 'id' => (string) $event->id, 'created_at' => $event->created_at->toAtomString(), 'updated_at' => $event->updated_at->toAtomString(), - 'amount' => number_format((float)$event->amount, $currency->decimal_places, '.', ''), - 'currency_id' => (string)$currency->id, + 'amount' => number_format((float) $event->amount, $currency->decimal_places, '.', ''), + 'currency_id' => (string) $currency->id, 'currency_code' => $currency->code, 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => (int)$currency->decimal_places, - 'transaction_journal_id' => $journalId ? (string)$journalId : null, - 'transaction_group_id' => $groupId ? (string)$groupId : null, + 'currency_decimal_places' => (int) $currency->decimal_places, + 'transaction_journal_id' => $journalId ? (string) $journalId : null, + 'transaction_group_id' => $groupId ? (string) $groupId : null, 'links' => [ [ 'rel' => 'self', diff --git a/app/Transformers/PiggyBankTransformer.php b/app/Transformers/PiggyBankTransformer.php index 43abb9da39..7a66774b43 100644 --- a/app/Transformers/PiggyBankTransformer.php +++ b/app/Transformers/PiggyBankTransformer.php @@ -56,6 +56,8 @@ class PiggyBankTransformer extends AbstractTransformer * @param PiggyBank $piggyBank * * @return array + * @throws \FireflyIII\Exceptions\FireflyException + * @throws \JsonException */ public function transform(PiggyBank $piggyBank): array { @@ -79,47 +81,55 @@ class PiggyBankTransformer extends AbstractTransformer /** @var ObjectGroup $objectGroup */ $objectGroup = $piggyBank->objectGroups->first(); if (null !== $objectGroup) { - $objectGroupId = (int)$objectGroup->id; - $objectGroupOrder = (int)$objectGroup->order; + $objectGroupId = (int) $objectGroup->id; + $objectGroupOrder = (int) $objectGroup->order; $objectGroupTitle = $objectGroup->title; } // get currently saved amount: $currentAmountStr = $this->piggyRepos->getCurrentAmount($piggyBank); - $currentAmount = number_format((float)$currentAmountStr, $currency->decimal_places, '.', ''); + $currentAmount = number_format((float) $currentAmountStr, $currency->decimal_places, '.', ''); - // left to save: - $leftToSave = bcsub($piggyBank->targetamount, $currentAmountStr); + // Amounts, depending on 0.0 state of target amount + $percentage = null; + $targetAmountString = null; + $leftToSaveString = null; + $savePerMonth = null; + if (0.000 !== (float) $piggyBank->targetamount) { + $leftToSave = bcsub($piggyBank->targetamount, $currentAmountStr); + $targetAmount = (string) $piggyBank->targetamount; + $targetAmount = 1 === bccomp('0.01', $targetAmount) ? '0.01' : $targetAmount; + $percentage = (int) (0 !== bccomp('0', $currentAmountStr) ? $currentAmountStr / $targetAmount * 100 : 0); + $targetAmountString = number_format((float) $targetAmount, $currency->decimal_places, '.', ''); + $leftToSaveString = number_format((float) $leftToSave, $currency->decimal_places, '.', ''); + $savePerMonth = number_format((float) $this->piggyRepos->getSuggestedMonthlyAmount($piggyBank), $currency->decimal_places, '.', ''); + } $startDate = $piggyBank->startdate?->toAtomString(); $targetDate = $piggyBank->targetdate?->toAtomString(); - // target and percentage: - $targetAmount = $piggyBank->targetamount; - $targetAmount = 1 === bccomp('0.01', (string)$targetAmount) ? '0.01' : $targetAmount; - $percentage = (int)(0 !== bccomp('0', $currentAmountStr) ? $currentAmountStr / $targetAmount * 100 : 0); return [ - 'id' => (string)$piggyBank->id, + 'id' => (string) $piggyBank->id, 'created_at' => $piggyBank->created_at->toAtomString(), 'updated_at' => $piggyBank->updated_at->toAtomString(), - 'account_id' => (string)$piggyBank->account_id, + 'account_id' => (string) $piggyBank->account_id, 'account_name' => $piggyBank->account->name, 'name' => $piggyBank->name, - 'currency_id' => (string)$currency->id, + 'currency_id' => (string) $currency->id, 'currency_code' => $currency->code, 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => (int)$currency->decimal_places, - 'target_amount' => number_format((float)$targetAmount, $currency->decimal_places, '.', ''), + 'currency_decimal_places' => (int) $currency->decimal_places, + 'target_amount' => $targetAmountString, 'percentage' => $percentage, 'current_amount' => $currentAmount, - 'left_to_save' => number_format((float)$leftToSave, $currency->decimal_places, '.', ''), - 'save_per_month' => number_format((float)$this->piggyRepos->getSuggestedMonthlyAmount($piggyBank), $currency->decimal_places, '.', ''), + 'left_to_save' => $leftToSaveString, + 'save_per_month' => $savePerMonth, 'start_date' => $startDate, 'target_date' => $targetDate, - 'order' => (int)$piggyBank->order, + 'order' => (int) $piggyBank->order, 'active' => true, 'notes' => $notes, - 'object_group_id' => $objectGroupId ? (string)$objectGroupId : null, + 'object_group_id' => $objectGroupId ? (string) $objectGroupId : null, 'object_group_order' => $objectGroupOrder, 'object_group_title' => $objectGroupTitle, 'links' => [ diff --git a/app/Transformers/PreferenceTransformer.php b/app/Transformers/PreferenceTransformer.php index c085fbffd7..402966786f 100644 --- a/app/Transformers/PreferenceTransformer.php +++ b/app/Transformers/PreferenceTransformer.php @@ -40,7 +40,7 @@ class PreferenceTransformer extends AbstractTransformer public function transform(Preference $preference): array { return [ - 'id' => (int)$preference->id, + 'id' => (int) $preference->id, 'created_at' => $preference->created_at->toAtomString(), 'updated_at' => $preference->updated_at->toAtomString(), 'name' => $preference->name, diff --git a/app/Transformers/RecurrenceTransformer.php b/app/Transformers/RecurrenceTransformer.php index 0bbbb4d37b..5e171eb140 100644 --- a/app/Transformers/RecurrenceTransformer.php +++ b/app/Transformers/RecurrenceTransformer.php @@ -80,14 +80,14 @@ class RecurrenceTransformer extends AbstractTransformer $this->budgetRepos->setUser($recurrence->user); Log::debug('Set user.'); - $shortType = (string)config(sprintf('firefly.transactionTypesToShort.%s', $recurrence->transactionType->type)); + $shortType = (string) config(sprintf('firefly.transactionTypesToShort.%s', $recurrence->transactionType->type)); $notes = $this->repository->getNoteText($recurrence); - $reps = 0 === (int)$recurrence->repetitions ? null : (int)$recurrence->repetitions; + $reps = 0 === (int) $recurrence->repetitions ? null : (int) $recurrence->repetitions; Log::debug('Get basic data.'); // basic data. return [ - 'id' => (string)$recurrence->id, + 'id' => (string) $recurrence->id, 'created_at' => $recurrence->created_at->toAtomString(), 'updated_at' => $recurrence->updated_at->toAtomString(), 'type' => $shortType, @@ -126,13 +126,13 @@ class RecurrenceTransformer extends AbstractTransformer /** @var RecurrenceRepetition $repetition */ foreach ($recurrence->recurrenceRepetitions as $repetition) { $repetitionArray = [ - 'id' => (string)$repetition->id, + 'id' => (string) $repetition->id, 'created_at' => $repetition->created_at->toAtomString(), 'updated_at' => $repetition->updated_at->toAtomString(), 'type' => $repetition->repetition_type, 'moment' => $repetition->repetition_moment, - 'skip' => (int)$repetition->repetition_skip, - 'weekend' => (int)$repetition->weekend, + 'skip' => (int) $repetition->repetition_skip, + 'weekend' => (int) $repetition->weekend, 'description' => $this->repository->repetitionDescription($repetition), 'occurrences' => [], ]; @@ -171,10 +171,10 @@ class RecurrenceTransformer extends AbstractTransformer $foreignCurrencyDp = null; $foreignCurrencyId = null; if (null !== $transaction->foreign_currency_id) { - $foreignCurrencyId = (int)$transaction->foreign_currency_id; + $foreignCurrencyId = (int) $transaction->foreign_currency_id; $foreignCurrencyCode = $transaction->foreignCurrency->code; $foreignCurrencySymbol = $transaction->foreignCurrency->symbol; - $foreignCurrencyDp = (int)$transaction->foreignCurrency->decimal_places; + $foreignCurrencyDp = (int) $transaction->foreignCurrency->decimal_places; } // source info: @@ -184,7 +184,7 @@ class RecurrenceTransformer extends AbstractTransformer $sourceIban = null; if (null !== $sourceAccount) { $sourceName = $sourceAccount->name; - $sourceId = (int)$sourceAccount->id; + $sourceId = (int) $sourceAccount->id; $sourceType = $sourceAccount->accountType->type; $sourceIban = $sourceAccount->iban; } @@ -194,29 +194,29 @@ class RecurrenceTransformer extends AbstractTransformer $destinationIban = null; if (null !== $destinationAccount) { $destinationName = $destinationAccount->name; - $destinationId = (int)$destinationAccount->id; + $destinationId = (int) $destinationAccount->id; $destinationType = $destinationAccount->accountType->type; $destinationIban = $destinationAccount->iban; } - $amount = number_format((float)$transaction->amount, $transaction->transactionCurrency->decimal_places, '.', ''); + $amount = number_format((float) $transaction->amount, $transaction->transactionCurrency->decimal_places, '.', ''); $foreignAmount = null; if (null !== $transaction->foreign_currency_id && null !== $transaction->foreign_amount) { - $foreignAmount = number_format((float)$transaction->foreign_amount, $foreignCurrencyDp, '.', ''); + $foreignAmount = number_format((float) $transaction->foreign_amount, $foreignCurrencyDp, '.', ''); } $transactionArray = [ - 'currency_id' => (string)$transaction->transaction_currency_id, + 'currency_id' => (string) $transaction->transaction_currency_id, 'currency_code' => $transaction->transactionCurrency->code, 'currency_symbol' => $transaction->transactionCurrency->symbol, - 'currency_decimal_places' => (int)$transaction->transactionCurrency->decimal_places, - 'foreign_currency_id' => null === $foreignCurrencyId ? null : (string)$foreignCurrencyId, + 'currency_decimal_places' => (int) $transaction->transactionCurrency->decimal_places, + 'foreign_currency_id' => null === $foreignCurrencyId ? null : (string) $foreignCurrencyId, 'foreign_currency_code' => $foreignCurrencyCode, 'foreign_currency_symbol' => $foreignCurrencySymbol, 'foreign_currency_decimal_places' => $foreignCurrencyDp, - 'source_id' => (string)$sourceId, + 'source_id' => (string) $sourceId, 'source_name' => $sourceName, 'source_iban' => $sourceIban, 'source_type' => $sourceType, - 'destination_id' => (string)$destinationId, + 'destination_id' => (string) $destinationId, 'destination_name' => $destinationName, 'destination_iban' => $destinationIban, 'destination_type' => $destinationType, @@ -264,9 +264,9 @@ class RecurrenceTransformer extends AbstractTransformer default: throw new FireflyException(sprintf('Recurrence transformer cant handle field "%s"', $transactionMeta->name)); case 'bill_id': - $bill = $this->billRepos->find((int)$transactionMeta->value); + $bill = $this->billRepos->find((int) $transactionMeta->value); if (null !== $bill) { - $array['bill_id'] = (string)$bill->id; + $array['bill_id'] = (string) $bill->id; $array['bill_name'] = $bill->name; } break; @@ -274,30 +274,30 @@ class RecurrenceTransformer extends AbstractTransformer $array['tags'] = json_decode($transactionMeta->value); break; case 'piggy_bank_id': - $piggy = $this->piggyRepos->find((int)$transactionMeta->value); + $piggy = $this->piggyRepos->find((int) $transactionMeta->value); if (null !== $piggy) { - $array['piggy_bank_id'] = (string)$piggy->id; + $array['piggy_bank_id'] = (string) $piggy->id; $array['piggy_bank_name'] = $piggy->name; } break; case 'category_id': - $category = $this->factory->findOrCreate((int)$transactionMeta->value, null); + $category = $this->factory->findOrCreate((int) $transactionMeta->value, null); if (null !== $category) { - $array['category_id'] = (string)$category->id; + $array['category_id'] = (string) $category->id; $array['category_name'] = $category->name; } break; case 'category_name': $category = $this->factory->findOrCreate(null, $transactionMeta->value); if (null !== $category) { - $array['category_id'] = (string)$category->id; + $array['category_id'] = (string) $category->id; $array['category_name'] = $category->name; } break; case 'budget_id': - $budget = $this->budgetRepos->find((int)$transactionMeta->value); + $budget = $this->budgetRepos->find((int) $transactionMeta->value); if (null !== $budget) { - $array['budget_id'] = (string)$budget->id; + $array['budget_id'] = (string) $budget->id; $array['budget_name'] = $budget->name; } break; diff --git a/app/Transformers/RuleGroupTransformer.php b/app/Transformers/RuleGroupTransformer.php index 7e608b922c..61748c86f6 100644 --- a/app/Transformers/RuleGroupTransformer.php +++ b/app/Transformers/RuleGroupTransformer.php @@ -41,7 +41,7 @@ class RuleGroupTransformer extends AbstractTransformer public function transform(RuleGroup $ruleGroup): array { return [ - 'id' => (int)$ruleGroup->id, + 'id' => (int) $ruleGroup->id, 'created_at' => $ruleGroup->created_at->toAtomString(), 'updated_at' => $ruleGroup->updated_at->toAtomString(), 'title' => $ruleGroup->title, diff --git a/app/Transformers/RuleTransformer.php b/app/Transformers/RuleTransformer.php index 970884912d..b338bb767b 100644 --- a/app/Transformers/RuleTransformer.php +++ b/app/Transformers/RuleTransformer.php @@ -60,21 +60,21 @@ class RuleTransformer extends AbstractTransformer $this->ruleRepository->setUser($rule->user); return [ - 'id' => (string)$rule->id, - 'created_at' => $rule->created_at->toAtomString(), - 'updated_at' => $rule->updated_at->toAtomString(), - 'rule_group_id' => (string)$rule->rule_group_id, - 'rule_group_title' => (string)$rule->ruleGroup->title, - 'title' => $rule->title, - 'description' => $rule->description, - 'order' => (int)$rule->order, - 'active' => $rule->active, - 'strict' => $rule->strict, - 'stop_processing' => $rule->stop_processing, - 'trigger' => $this->getRuleTrigger($rule), - 'triggers' => $this->triggers($rule), - 'actions' => $this->actions($rule), - 'links' => [ + 'id' => (string) $rule->id, + 'created_at' => $rule->created_at->toAtomString(), + 'updated_at' => $rule->updated_at->toAtomString(), + 'rule_group_id' => (string) $rule->rule_group_id, + 'rule_group_title' => (string) $rule->ruleGroup->title, + 'title' => $rule->title, + 'description' => $rule->description, + 'order' => (int) $rule->order, + 'active' => $rule->active, + 'strict' => $rule->strict, + 'stop_processing' => $rule->stop_processing, + 'trigger' => $this->getRuleTrigger($rule), + 'triggers' => $this->triggers($rule), + 'actions' => $this->actions($rule), + 'links' => [ [ 'rel' => 'self', 'uri' => '/rules/' . $rule->id, @@ -121,7 +121,7 @@ class RuleTransformer extends AbstractTransformer continue; } $result[] = [ - 'id' => (string)$ruleTrigger->id, + 'id' => (string) $ruleTrigger->id, 'created_at' => $ruleTrigger->created_at->toAtomString(), 'updated_at' => $ruleTrigger->updated_at->toAtomString(), 'type' => $ruleTrigger->trigger_type, @@ -147,7 +147,7 @@ class RuleTransformer extends AbstractTransformer /** @var RuleAction $ruleAction */ foreach ($actions as $ruleAction) { $result[] = [ - 'id' => (string)$ruleAction->id, + 'id' => (string) $ruleAction->id, 'created_at' => $ruleAction->created_at->toAtomString(), 'updated_at' => $ruleAction->updated_at->toAtomString(), 'type' => $ruleAction->action_type, diff --git a/app/Transformers/TagTransformer.php b/app/Transformers/TagTransformer.php index 56978c9793..b4c09c6560 100644 --- a/app/Transformers/TagTransformer.php +++ b/app/Transformers/TagTransformer.php @@ -52,11 +52,11 @@ class TagTransformer extends AbstractTransformer if (null !== $location) { $latitude = $location->latitude; $longitude = $location->longitude; - $zoomLevel = (int)$location->zoom_level; + $zoomLevel = (int) $location->zoom_level; } return [ - 'id' => (int)$tag->id, + 'id' => (int) $tag->id, 'created_at' => $tag->created_at->toAtomString(), 'updated_at' => $tag->updated_at->toAtomString(), 'tag' => $tag->tag, diff --git a/app/Transformers/TransactionGroupTransformer.php b/app/Transformers/TransactionGroupTransformer.php index e628f653af..eba066edb1 100644 --- a/app/Transformers/TransactionGroupTransformer.php +++ b/app/Transformers/TransactionGroupTransformer.php @@ -75,10 +75,10 @@ class TransactionGroupTransformer extends AbstractTransformer $first = new NullArrayObject(reset($group['transactions'])); return [ - 'id' => (int)$first['transaction_group_id'], + 'id' => (int) $first['transaction_group_id'], 'created_at' => $first['created_at']->toAtomString(), 'updated_at' => $first['updated_at']->toAtomString(), - 'user' => (string)$data['user_id'], + 'user' => (string) $data['user_id'], 'group_title' => $data['title'], 'transactions' => $this->transformTransactions($data), 'links' => [ @@ -123,13 +123,13 @@ class TransactionGroupTransformer extends AbstractTransformer $foreignAmount = app('steam')->positive($row['foreign_amount']); } - $metaFieldData = $this->groupRepos->getMetaFields((int)$row['transaction_journal_id'], $this->metaFields); - $metaDateData = $this->groupRepos->getMetaDateFields((int)$row['transaction_journal_id'], $this->metaDateFields); + $metaFieldData = $this->groupRepos->getMetaFields((int) $row['transaction_journal_id'], $this->metaFields); + $metaDateData = $this->groupRepos->getMetaDateFields((int) $row['transaction_journal_id'], $this->metaDateFields); $longitude = null; $latitude = null; $zoomLevel = null; - $location = $this->getLocationById((int)$row['transaction_journal_id']); + $location = $this->getLocationById((int) $row['transaction_journal_id']); if (null !== $location) { $longitude = $location->longitude; $latitude = $location->latitude; @@ -137,17 +137,17 @@ class TransactionGroupTransformer extends AbstractTransformer } return [ - 'user' => (string)$row['user_id'], - 'transaction_journal_id' => (string)$row['transaction_journal_id'], + 'user' => (string) $row['user_id'], + 'transaction_journal_id' => (string) $row['transaction_journal_id'], 'type' => strtolower($type), 'date' => $row['date']->toAtomString(), 'order' => $row['order'], - 'currency_id' => (string)$row['currency_id'], + 'currency_id' => (string) $row['currency_id'], 'currency_code' => $row['currency_code'], 'currency_name' => $row['currency_name'], 'currency_symbol' => $row['currency_symbol'], - 'currency_decimal_places' => (int)$row['currency_decimal_places'], + 'currency_decimal_places' => (int) $row['currency_decimal_places'], 'foreign_currency_id' => $this->stringFromArray($transaction, 'foreign_currency_id', null), 'foreign_currency_code' => $row['foreign_currency_code'], @@ -159,12 +159,12 @@ class TransactionGroupTransformer extends AbstractTransformer 'description' => $row['description'], - 'source_id' => (string)$row['source_account_id'], + 'source_id' => (string) $row['source_account_id'], 'source_name' => $row['source_account_name'], 'source_iban' => $row['source_account_iban'], 'source_type' => $row['source_account_type'], - 'destination_id' => (string)$row['destination_account_id'], + 'destination_id' => (string) $row['destination_account_id'], 'destination_name' => $row['destination_account_name'], 'destination_iban' => $row['destination_account_iban'], 'destination_type' => $row['destination_account_type'], @@ -179,8 +179,8 @@ class TransactionGroupTransformer extends AbstractTransformer 'bill_name' => $row['bill_name'], 'reconciled' => $row['reconciled'], - 'notes' => $this->groupRepos->getNoteText((int)$row['transaction_journal_id']), - 'tags' => $this->groupRepos->getTags((int)$row['transaction_journal_id']), + 'notes' => $this->groupRepos->getNoteText((int) $row['transaction_journal_id']), + 'tags' => $this->groupRepos->getTags((int) $row['transaction_journal_id']), 'internal_reference' => $metaFieldData['internal_reference'], 'external_id' => $metaFieldData['external_id'], @@ -213,7 +213,7 @@ class TransactionGroupTransformer extends AbstractTransformer 'latitude' => $latitude, 'zoom_level' => $zoomLevel, - 'has_attachments' => $this->hasAttachments((int)$row['transaction_journal_id']), + 'has_attachments' => $this->hasAttachments((int) $row['transaction_journal_id']), ]; } @@ -230,11 +230,11 @@ class TransactionGroupTransformer extends AbstractTransformer return null; } if (array_key_exists($key, $array) && null !== $array[$key]) { - return (string)$array[$key]; + return (string) $array[$key]; } if (null !== $default) { - return (string)$default; + return (string) $default; } return null; @@ -250,16 +250,6 @@ class TransactionGroupTransformer extends AbstractTransformer return $this->groupRepos->getLocation($journalId); } - /** - * @param int $journalId - * - * @return bool - */ - private function hasAttachments(int $journalId): bool - { - return $this->groupRepos->countAttachments($journalId) > 0; - } - /** * @param array $array * @param string $key @@ -269,7 +259,7 @@ class TransactionGroupTransformer extends AbstractTransformer private function integerFromArray(array $array, string $key): ?int { if (array_key_exists($key, $array)) { - return (int)$array[$key]; + return (int) $array[$key]; } return null; @@ -290,6 +280,16 @@ class TransactionGroupTransformer extends AbstractTransformer return $object[$key]->toAtomString(); } + /** + * @param int $journalId + * + * @return bool + */ + private function hasAttachments(int $journalId): bool + { + return $this->groupRepos->countAttachments($journalId) > 0; + } + /** * @param TransactionGroup $group * @@ -300,10 +300,10 @@ class TransactionGroupTransformer extends AbstractTransformer { try { $result = [ - 'id' => (int)$group->id, + 'id' => (int) $group->id, 'created_at' => $group->created_at->toAtomString(), 'updated_at' => $group->updated_at->toAtomString(), - 'user' => (int)$group->user_id, + 'user' => (int) $group->user_id, 'group_title' => $group->title, 'transactions' => $this->transformJournals($group->transactionJournals), 'links' => [ @@ -363,7 +363,7 @@ class TransactionGroupTransformer extends AbstractTransformer $bill = $this->getBill($journal->bill); if (null !== $foreignAmount && null !== $foreignCurrency) { - $foreignAmount = number_format((float)$foreignAmount, $foreignCurrency['decimal_places'] ?? 0, '.', ''); + $foreignAmount = number_format((float) $foreignAmount, $foreignCurrency['decimal_places'] ?? 0, '.', ''); } $longitude = null; @@ -377,33 +377,33 @@ class TransactionGroupTransformer extends AbstractTransformer } return [ - 'user' => (int)$journal->user_id, - 'transaction_journal_id' => (int)$journal->id, + 'user' => (int) $journal->user_id, + 'transaction_journal_id' => (int) $journal->id, 'type' => strtolower($type), 'date' => $journal->date->toAtomString(), 'order' => $journal->order, - 'currency_id' => (int)$currency->id, + 'currency_id' => (int) $currency->id, 'currency_code' => $currency->code, 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => (int)$currency->decimal_places, + 'currency_decimal_places' => (int) $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' => number_format((float)$amount, $currency->decimal_places, '.', ''), + 'amount' => number_format((float) $amount, $currency->decimal_places, '.', ''), 'foreign_amount' => $foreignAmount, 'description' => $journal->description, - 'source_id' => (int)$source->account_id, + 'source_id' => (int) $source->account_id, 'source_name' => $source->account->name, 'source_iban' => $source->account->iban, 'source_type' => $source->account->accountType->type, - 'destination_id' => (int)$destination->account_id, + 'destination_id' => (int) $destination->account_id, 'destination_name' => $destination->account->name, 'destination_iban' => $destination->account->iban, 'destination_type' => $destination->account->accountType->type, @@ -461,7 +461,7 @@ class TransactionGroupTransformer extends AbstractTransformer { $result = $journal->transactions->first( static function (Transaction $transaction) { - return (float)$transaction->amount < 0; + return (float) $transaction->amount < 0; } ); if (null === $result) { @@ -481,7 +481,7 @@ class TransactionGroupTransformer extends AbstractTransformer { $result = $journal->transactions->first( static function (Transaction $transaction) { - return (float)$transaction->amount > 0; + return (float) $transaction->amount > 0; } ); if (null === $result) { @@ -565,10 +565,10 @@ class TransactionGroupTransformer extends AbstractTransformer if (null === $currency) { return $array; } - $array['id'] = (int)$currency->id; + $array['id'] = (int) $currency->id; $array['code'] = $currency->code; $array['symbol'] = $currency->symbol; - $array['decimal_places'] = (int)$currency->decimal_places; + $array['decimal_places'] = (int) $currency->decimal_places; return $array; } @@ -587,7 +587,7 @@ class TransactionGroupTransformer extends AbstractTransformer if (null === $budget) { return $array; } - $array['id'] = (int)$budget->id; + $array['id'] = (int) $budget->id; $array['name'] = $budget->name; return $array; @@ -607,7 +607,7 @@ class TransactionGroupTransformer extends AbstractTransformer if (null === $category) { return $array; } - $array['id'] = (int)$category->id; + $array['id'] = (int) $category->id; $array['name'] = $category->name; return $array; @@ -627,7 +627,7 @@ class TransactionGroupTransformer extends AbstractTransformer if (null === $bill) { return $array; } - $array['id'] = (string)$bill->id; + $array['id'] = (string) $bill->id; $array['name'] = $bill->name; return $array; diff --git a/app/Transformers/TransactionLinkTransformer.php b/app/Transformers/TransactionLinkTransformer.php index b9f3ede0bf..e8a865e93d 100644 --- a/app/Transformers/TransactionLinkTransformer.php +++ b/app/Transformers/TransactionLinkTransformer.php @@ -55,12 +55,12 @@ class TransactionLinkTransformer extends AbstractTransformer $notes = $this->repository->getLinkNoteText($link); return [ - 'id' => (string)$link->id, + 'id' => (string) $link->id, 'created_at' => $link->created_at->toAtomString(), 'updated_at' => $link->updated_at->toAtomString(), - 'inward_id' => (string)$link->source_id, - 'outward_id' => (string)$link->destination_id, - 'link_type_id' => (string)$link->link_type_id, + 'inward_id' => (string) $link->source_id, + 'outward_id' => (string) $link->destination_id, + 'link_type_id' => (string) $link->link_type_id, 'notes' => '' === $notes ? null : $notes, 'links' => [ [ diff --git a/app/Transformers/UserTransformer.php b/app/Transformers/UserTransformer.php index 39277ad186..8b8ca5b5ee 100644 --- a/app/Transformers/UserTransformer.php +++ b/app/Transformers/UserTransformer.php @@ -46,11 +46,11 @@ class UserTransformer extends AbstractTransformer $this->repository = $this->repository ?? app(UserRepositoryInterface::class); return [ - 'id' => (int)$user->id, + 'id' => (int) $user->id, 'created_at' => $user->created_at->toAtomString(), 'updated_at' => $user->updated_at->toAtomString(), 'email' => $user->email, - 'blocked' => 1 === (int)$user->blocked, + 'blocked' => 1 === (int) $user->blocked, 'blocked_code' => '' === $user->blocked_code ? null : $user->blocked_code, 'role' => $this->repository->getRoleByUser($user), 'links' => [ diff --git a/app/Transformers/WebhookAttemptTransformer.php b/app/Transformers/WebhookAttemptTransformer.php index 082828e8ce..a271a917d3 100644 --- a/app/Transformers/WebhookAttemptTransformer.php +++ b/app/Transformers/WebhookAttemptTransformer.php @@ -40,11 +40,11 @@ class WebhookAttemptTransformer extends AbstractTransformer public function transform(WebhookAttempt $attempt): array { return [ - 'id' => (string)$attempt->id, + 'id' => (string) $attempt->id, 'created_at' => $attempt->created_at->toAtomString(), 'updated_at' => $attempt->updated_at->toAtomString(), - 'webhook_message_id' => (string)$attempt->webhook_message_id, - 'status_code' => (int)$attempt->status_code, + 'webhook_message_id' => (string) $attempt->webhook_message_id, + 'status_code' => (int) $attempt->status_code, 'logs' => $attempt->logs, 'response' => $attempt->response, ]; diff --git a/app/Transformers/WebhookMessageTransformer.php b/app/Transformers/WebhookMessageTransformer.php index e4f25d938f..9ed9c76d16 100644 --- a/app/Transformers/WebhookMessageTransformer.php +++ b/app/Transformers/WebhookMessageTransformer.php @@ -50,12 +50,12 @@ class WebhookMessageTransformer extends AbstractTransformer } return [ - 'id' => (string)$message->id, + 'id' => (string) $message->id, 'created_at' => $message->created_at->toAtomString(), 'updated_at' => $message->updated_at->toAtomString(), 'sent' => $message->sent, 'errored' => $message->errored, - 'webhook_id' => (string)$message->webhook_id, + 'webhook_id' => (string) $message->webhook_id, 'uuid' => $message->uuid, 'message' => $json, ]; diff --git a/app/Transformers/WebhookTransformer.php b/app/Transformers/WebhookTransformer.php index 730fa61a89..bc43d58c6c 100644 --- a/app/Transformers/WebhookTransformer.php +++ b/app/Transformers/WebhookTransformer.php @@ -52,7 +52,7 @@ class WebhookTransformer extends AbstractTransformer public function transform(Webhook $webhook): array { return [ - 'id' => (int)$webhook->id, + 'id' => (int) $webhook->id, 'created_at' => $webhook->created_at->toAtomString(), 'updated_at' => $webhook->updated_at->toAtomString(), 'active' => $webhook->active, diff --git a/app/User.php b/app/User.php index 0e69a6ca17..5c0da04984 100644 --- a/app/User.php +++ b/app/User.php @@ -200,7 +200,7 @@ class User extends Authenticatable public static function routeBinder(string $value): User { if (auth()->check()) { - $userId = (int)$value; + $userId = (int) $value; $user = self::find($userId); if (null !== $user) { return $user; @@ -302,8 +302,9 @@ class User extends Authenticatable /** * Get the models LDAP domain. - * * @return string + * @deprecated + * */ public function getLdapDomain() { @@ -312,8 +313,9 @@ class User extends Authenticatable /** * Get the database column name of the domain. - * * @return string + * @deprecated + * */ public function getLdapDomainColumn() { @@ -322,8 +324,9 @@ class User extends Authenticatable /** * Get the models LDAP GUID. - * * @return string + * @deprecated + * */ public function getLdapGuid() { @@ -332,8 +335,9 @@ class User extends Authenticatable /** * Get the models LDAP GUID database column name. - * * @return string + * @deprecated + * */ public function getLdapGuidColumn() { @@ -452,10 +456,11 @@ class User extends Authenticatable /** * Set the models LDAP domain. - * * @param string $domain * * @return void + * @deprecated + * */ public function setLdapDomain($domain) { @@ -464,10 +469,10 @@ class User extends Authenticatable /** * Set the models LDAP GUID. - * * @param string $guid * * @return void + * @deprecated */ public function setLdapGuid($guid) { diff --git a/app/Validation/Account/DepositValidation.php b/app/Validation/Account/DepositValidation.php index 2987e85a5c..9e71bde252 100644 --- a/app/Validation/Account/DepositValidation.php +++ b/app/Validation/Account/DepositValidation.php @@ -40,7 +40,7 @@ trait DepositValidation abstract protected function canCreateTypes(array $accountTypes): bool; /** - * @param array $validTypes + * @param array $validTypes * @param array $data * * @return Account|null @@ -65,7 +65,7 @@ trait DepositValidation if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) { // if both values are NULL we return false, // because the destination of a deposit can't be created. - $this->destError = (string)trans('validation.deposit_dest_need_data'); + $this->destError = (string) trans('validation.deposit_dest_need_data'); Log::error('Both values are NULL, cant create deposit destination.'); $result = false; } @@ -80,7 +80,7 @@ trait DepositValidation $search = $this->findExistingAccount($validTypes, $array); if (null === $search) { Log::debug('findExistingAccount() returned NULL, so the result is false.'); - $this->destError = (string)trans('validation.deposit_dest_bad_data', ['id' => $accountId, 'name' => $accountName]); + $this->destError = (string) trans('validation.deposit_dest_bad_data', ['id' => $accountId, 'name' => $accountName]); $result = false; } if (null !== $search) { @@ -114,7 +114,7 @@ trait DepositValidation // if both values are NULL return false, // because the source of a deposit can't be created. // (this never happens). - $this->sourceError = (string)trans('validation.deposit_source_need_data'); + $this->sourceError = (string) trans('validation.deposit_source_need_data'); $result = false; } diff --git a/app/Validation/Account/LiabilityValidation.php b/app/Validation/Account/LiabilityValidation.php index 019792f58e..683eabe2d2 100644 --- a/app/Validation/Account/LiabilityValidation.php +++ b/app/Validation/Account/LiabilityValidation.php @@ -48,7 +48,7 @@ trait LiabilityValidation $validTypes = config('firefly.valid_liabilities'); if (null === $accountId) { - $this->sourceError = (string)trans('validation.lc_destination_need_data'); + $this->sourceError = (string) trans('validation.lc_destination_need_data'); $result = false; } @@ -82,7 +82,7 @@ trait LiabilityValidation protected function validateLCSource(array $array): bool { $accountName = array_key_exists('name', $array) ? $array['name'] : null; - $result = true; + $result = true; Log::debug('Now in validateLCDestination', $array); if ('' === $accountName || null === $accountName) { $result = false; diff --git a/app/Validation/Account/OBValidation.php b/app/Validation/Account/OBValidation.php index 9b4b09841a..60b107da9a 100644 --- a/app/Validation/Account/OBValidation.php +++ b/app/Validation/Account/OBValidation.php @@ -57,7 +57,7 @@ trait OBValidation if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) { // if both values are NULL we return false, // because the destination of a deposit can't be created. - $this->destError = (string)trans('validation.ob_dest_need_data'); + $this->destError = (string) trans('validation.ob_dest_need_data'); Log::error('Both values are NULL, cant create OB destination.'); $result = false; } @@ -72,7 +72,7 @@ trait OBValidation $search = $this->findExistingAccount($validTypes, $array); if (null === $search) { Log::debug('findExistingAccount() returned NULL, so the result is false.', $validTypes); - $this->destError = (string)trans('validation.ob_dest_bad_data', ['id' => $accountId, 'name' => $accountName]); + $this->destError = (string) trans('validation.ob_dest_bad_data', ['id' => $accountId, 'name' => $accountName]); $result = false; } if (null !== $search) { @@ -108,7 +108,7 @@ trait OBValidation // if both values are NULL return false, // because the source of a deposit can't be created. // (this never happens). - $this->sourceError = (string)trans('validation.ob_source_need_data'); + $this->sourceError = (string) trans('validation.ob_source_need_data'); $result = false; } diff --git a/app/Validation/Account/ReconciliationValidation.php b/app/Validation/Account/ReconciliationValidation.php index 87048e7331..c0e3ddae9a 100644 --- a/app/Validation/Account/ReconciliationValidation.php +++ b/app/Validation/Account/ReconciliationValidation.php @@ -33,8 +33,9 @@ use Log; */ trait ReconciliationValidation { - public ?Account $destination; - public ?Account $source; + public ?Account $destination; + public ?Account $source; + /** * @param array $array * @@ -42,7 +43,7 @@ trait ReconciliationValidation */ protected function validateReconciliationDestination(array $array): bool { - $accountId = array_key_exists('id', $array) ? $array['id'] : null; + $accountId = array_key_exists('id', $array) ? $array['id'] : null; Log::debug('Now in validateReconciliationDestination', $array); if (null === $accountId) { Log::debug('Return FALSE'); @@ -51,7 +52,7 @@ trait ReconciliationValidation } $result = $this->accountRepository->find($accountId); if (null === $result) { - $this->destError = (string)trans('validation.deposit_dest_bad_data', ['id' => $accountId, 'name' => '']); + $this->destError = (string) trans('validation.deposit_dest_bad_data', ['id' => $accountId, 'name' => '']); Log::debug('Return FALSE'); return false; @@ -76,7 +77,7 @@ trait ReconciliationValidation return true; } - $this->destError = (string)trans('validation.deposit_dest_wrong_type'); + $this->destError = (string) trans('validation.deposit_dest_wrong_type'); Log::debug('Return FALSE'); return false; @@ -89,7 +90,7 @@ trait ReconciliationValidation */ protected function validateReconciliationSource(array $array): bool { - $accountId = array_key_exists('id', $array) ? $array['id'] : null; + $accountId = array_key_exists('id', $array) ? $array['id'] : null; Log::debug('In validateReconciliationSource', $array); if (null === $accountId) { Log::debug('Return FALSE'); diff --git a/app/Validation/Account/TransferValidation.php b/app/Validation/Account/TransferValidation.php index 3360500f60..06e49a8665 100644 --- a/app/Validation/Account/TransferValidation.php +++ b/app/Validation/Account/TransferValidation.php @@ -39,7 +39,7 @@ trait TransferValidation abstract protected function canCreateTypes(array $accountTypes): bool; /** - * @param array $validTypes + * @param array $validTypes * @param array $data * * @return Account|null @@ -61,16 +61,16 @@ trait TransferValidation if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) { // if both values are NULL we return false, // because the destination of a transfer can't be created. - $this->destError = (string)trans('validation.transfer_dest_need_data'); + $this->destError = (string) trans('validation.transfer_dest_need_data'); Log::error('Both values are NULL, cant create transfer destination.'); return false; } // or try to find the account: - $search = $this->findExistingAccount($validTypes,$array); + $search = $this->findExistingAccount($validTypes, $array); if (null === $search) { - $this->destError = (string)trans('validation.transfer_dest_bad_data', ['id' => $accountId, 'name' => $accountName]); + $this->destError = (string) trans('validation.transfer_dest_bad_data', ['id' => $accountId, 'name' => $accountName]); return false; } @@ -102,7 +102,7 @@ trait TransferValidation if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) { // if both values are NULL we return false, // because the source of a withdrawal can't be created. - $this->sourceError = (string)trans('validation.transfer_source_need_data'); + $this->sourceError = (string) trans('validation.transfer_source_need_data'); Log::warning('Not a valid source, need more data.'); return false; @@ -111,7 +111,7 @@ trait TransferValidation // otherwise try to find the account: $search = $this->findExistingAccount($validTypes, $array); if (null === $search) { - $this->sourceError = (string)trans('validation.transfer_source_bad_data', ['id' => $accountId, 'name' => $accountName]); + $this->sourceError = (string) trans('validation.transfer_source_bad_data', ['id' => $accountId, 'name' => $accountName]); Log::warning('Not a valid source, cant find it.', $validTypes); return false; diff --git a/app/Validation/Account/WithdrawalValidation.php b/app/Validation/Account/WithdrawalValidation.php index 15919be9e2..5200b16e7c 100644 --- a/app/Validation/Account/WithdrawalValidation.php +++ b/app/Validation/Account/WithdrawalValidation.php @@ -40,7 +40,7 @@ trait WithdrawalValidation abstract protected function canCreateTypes(array $accountTypes): bool; /** - * @param array $validTypes + * @param array $validTypes * @param array $data * * @return Account|null @@ -62,7 +62,7 @@ trait WithdrawalValidation if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) { // if both values are NULL we return TRUE // because we assume the user doesnt want to submit / change anything. - $this->sourceError = (string)trans('validation.withdrawal_source_need_data'); + $this->sourceError = (string) trans('validation.withdrawal_source_need_data'); Log::warning('[a] Not a valid source. Need more data.'); return false; @@ -71,7 +71,7 @@ trait WithdrawalValidation // otherwise try to find the account: $search = $this->findExistingAccount($validTypes, $array); if (null === $search) { - $this->sourceError = (string)trans('validation.withdrawal_source_bad_data', ['id' => $accountId, 'name' => $accountName]); + $this->sourceError = (string) trans('validation.withdrawal_source_bad_data', ['id' => $accountId, 'name' => $accountName]); Log::warning('Not a valid source. Cant find it.', $validTypes); return false; @@ -97,7 +97,7 @@ trait WithdrawalValidation if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) { // if both values are NULL return false, // because the destination of a withdrawal can never be created automatically. - $this->destError = (string)trans('validation.withdrawal_dest_need_data'); + $this->destError = (string) trans('validation.withdrawal_dest_need_data'); return false; } @@ -110,7 +110,7 @@ trait WithdrawalValidation if (in_array($type, $validTypes, true)) { return true; } - $this->destError = (string)trans('validation.withdrawal_dest_bad_data', ['id' => $accountId, 'name' => $accountName]); + $this->destError = (string) trans('validation.withdrawal_dest_bad_data', ['id' => $accountId, 'name' => $accountName]); return false; } @@ -136,7 +136,7 @@ trait WithdrawalValidation if (null === $accountId && null === $accountName && false === $this->canCreateTypes($validTypes)) { // if both values are NULL we return false, // because the source of a withdrawal can't be created. - $this->sourceError = (string)trans('validation.withdrawal_source_need_data'); + $this->sourceError = (string) trans('validation.withdrawal_source_need_data'); Log::warning('[b] Not a valid source. Need more data.'); return false; @@ -145,7 +145,7 @@ trait WithdrawalValidation // otherwise try to find the account: $search = $this->findExistingAccount($validTypes, $array); if (null === $search) { - $this->sourceError = (string)trans('validation.withdrawal_source_bad_data', ['id' => $accountId, 'name' => $accountName]); + $this->sourceError = (string) trans('validation.withdrawal_source_bad_data', ['id' => $accountId, 'name' => $accountName]); Log::warning('Not a valid source. Cant find it.', $validTypes); return false; diff --git a/app/Validation/AccountValidator.php b/app/Validation/AccountValidator.php index 1dd6387b3e..16bb89c58c 100644 --- a/app/Validation/AccountValidator.php +++ b/app/Validation/AccountValidator.php @@ -198,6 +198,21 @@ class AccountValidator return false; } + /** + * @param string $accountType + * + * @return bool + */ + protected function canCreateType(string $accountType): bool + { + $canCreate = [AccountType::EXPENSE, AccountType::REVENUE, AccountType::INITIAL_BALANCE, AccountType::LIABILITY_CREDIT]; + if (in_array($accountType, $canCreate, true)) { + return true; + } + + return false; + } + /** * @param array $validTypes * @param array $data @@ -244,19 +259,4 @@ class AccountValidator return null; } - /** - * @param string $accountType - * - * @return bool - */ - protected function canCreateType(string $accountType): bool - { - $canCreate = [AccountType::EXPENSE, AccountType::REVENUE, AccountType::INITIAL_BALANCE, AccountType::LIABILITY_CREDIT]; - if (in_array($accountType, $canCreate, true)) { - return true; - } - - return false; - } - } diff --git a/app/Validation/Api/Data/Bulk/ValidatesBulkTransactionQuery.php b/app/Validation/Api/Data/Bulk/ValidatesBulkTransactionQuery.php index a4e5146fc4..b67d03384d 100644 --- a/app/Validation/Api/Data/Bulk/ValidatesBulkTransactionQuery.php +++ b/app/Validation/Api/Data/Bulk/ValidatesBulkTransactionQuery.php @@ -50,26 +50,26 @@ trait ValidatesBulkTransactionQuery // find both accounts, must be same type. // already validated: belongs to this user. $repository = app(AccountRepositoryInterface::class); - $source = $repository->find((int)$json['where']['account_id']); - $dest = $repository->find((int)$json['update']['account_id']); + $source = $repository->find((int) $json['where']['account_id']); + $dest = $repository->find((int) $json['update']['account_id']); if (null === $source) { - $validator->errors()->add('query', sprintf((string)trans('validation.invalid_query_data'), 'where', 'account_id')); + $validator->errors()->add('query', sprintf((string) trans('validation.invalid_query_data'), 'where', 'account_id')); return; } if (null === $dest) { - $validator->errors()->add('query', sprintf((string)trans('validation.invalid_query_data'), 'update', 'account_id')); + $validator->errors()->add('query', sprintf((string) trans('validation.invalid_query_data'), 'update', 'account_id')); return; } if ($source->accountType->type !== $dest->accountType->type) { - $validator->errors()->add('query', (string)trans('validation.invalid_query_account_type')); + $validator->errors()->add('query', (string) trans('validation.invalid_query_account_type')); return; } // must have same currency: if ($repository->getAccountCurrency($source)->id !== $repository->getAccountCurrency($dest)->id) { - $validator->errors()->add('query', (string)trans('validation.invalid_query_currency')); + $validator->errors()->add('query', (string) trans('validation.invalid_query_currency')); } } } diff --git a/app/Validation/CurrencyValidation.php b/app/Validation/CurrencyValidation.php index 0c48b2a5a2..a1cc7cf921 100644 --- a/app/Validation/CurrencyValidation.php +++ b/app/Validation/CurrencyValidation.php @@ -55,7 +55,7 @@ trait CurrencyValidation ) { $validator->errors()->add( 'transactions.' . $index . '.foreign_amount', - (string)trans('validation.require_currency_info') + (string) trans('validation.require_currency_info') ); } // if the currency is present, then the amount must be present as well. @@ -65,7 +65,7 @@ trait CurrencyValidation )) { $validator->errors()->add( 'transactions.' . $index . '.foreign_amount', - (string)trans('validation.require_currency_amount') + (string) trans('validation.require_currency_amount') ); } } diff --git a/app/Validation/FireflyValidator.php b/app/Validation/FireflyValidator.php index 69f6b11762..5229b915d7 100644 --- a/app/Validation/FireflyValidator.php +++ b/app/Validation/FireflyValidator.php @@ -53,6 +53,7 @@ use function is_string; */ class FireflyValidator extends Validator { + /** * @param mixed $attribute * @param mixed $value @@ -84,7 +85,7 @@ class FireflyValidator extends Validator { $field = $parameters[1] ?? 'id'; - if (0 === (int)$value) { + if (0 === (int) $value) { return true; } $count = DB::table($parameters[0])->where('user_id', auth()->user()->id)->where($field, $value)->count(); @@ -202,7 +203,7 @@ class FireflyValidator extends Validator return false; } - return 1 === (int)$checksum; + return 1 === (int) $checksum; } /** @@ -217,7 +218,7 @@ class FireflyValidator extends Validator /** @var mixed $compare */ $compare = $parameters[0] ?? '0'; - return bccomp((string)$value, (string)$compare) < 0; + return bccomp((string) $value, (string) $compare) < 0; } /** @@ -232,7 +233,7 @@ class FireflyValidator extends Validator /** @var mixed $compare */ $compare = $parameters[0] ?? '0'; - return bccomp((string)$value, (string)$compare) > 0; + return bccomp((string) $value, (string) $compare) > 0; } /** @@ -246,7 +247,7 @@ class FireflyValidator extends Validator { $field = $parameters[1] ?? 'id'; - if (0 === (int)$value) { + if (0 === (int) $value) { return true; } $count = DB::table($parameters[0])->where($field, $value)->count(); @@ -266,7 +267,7 @@ class FireflyValidator extends Validator // first, get the index from this string: $value = $value ?? ''; $parts = explode('.', $attribute); - $index = (int)($parts[1] ?? '0'); + $index = (int) ($parts[1] ?? '0'); // get the name of the trigger from the data array: $actionType = $this->data['actions'][$index]['type'] ?? 'invalid'; @@ -330,7 +331,7 @@ class FireflyValidator extends Validator { // first, get the index from this string: $parts = explode('.', $attribute); - $index = (int)($parts[1] ?? '0'); + $index = (int) ($parts[1] ?? '0'); // get the name of the trigger from the data array: $triggerType = $this->data['triggers'][$index]['type'] ?? 'invalid'; @@ -358,7 +359,7 @@ class FireflyValidator extends Validator // check if it's an existing account. if (in_array($triggerType, ['destination_account_id', 'source_account_id'])) { - return is_numeric($value) && (int)$value > 0; + return is_numeric($value) && (int) $value > 0; } // check transaction type. @@ -396,7 +397,7 @@ class FireflyValidator extends Validator { $verify = false; if (array_key_exists('verify_password', $this->data)) { - $verify = 1 === (int)$this->data['verify_password']; + $verify = 1 === (int) $this->data['verify_password']; } if ($verify) { /** @var Verifier $service */ @@ -433,7 +434,7 @@ class FireflyValidator extends Validator } $parameterId = $parameters[0] ?? null; if (null !== $parameterId) { - return $this->validateByParameterId((int)$parameterId, $value); + return $this->validateByParameterId((int) $parameterId, $value); } if (array_key_exists('id', $this->data)) { return $this->validateByAccountId($value); @@ -483,7 +484,7 @@ class FireflyValidator extends Validator } $accountTypes = AccountType::whereIn('type', $search)->get(); - $ignore = (int)($parameters[0] ?? 0.0); + $ignore = (int) ($parameters[0] ?? 0.0); $accountTypeIds = $accountTypes->pluck('id')->toArray(); /** @var Collection $set */ $set = auth()->user()->accounts()->whereIn('account_type_id', $accountTypeIds)->where('id', '!=', $ignore)->get(); @@ -506,7 +507,7 @@ class FireflyValidator extends Validator private function validateByAccountTypeId($value, $parameters): bool { $type = AccountType::find($this->data['account_type_id'])->first(); - $ignore = (int)($parameters[0] ?? 0.0); + $ignore = (int) ($parameters[0] ?? 0.0); /** @var Collection $set */ $set = auth()->user()->accounts()->where('account_type_id', $type->id)->where('id', '!=', $ignore)->get(); @@ -580,9 +581,9 @@ class FireflyValidator extends Validator */ public function validateUniqueAccountNumberForUser($attribute, $value, $parameters): bool { - $accountId = (int)($this->data['id'] ?? 0.0); + $accountId = (int) ($this->data['id'] ?? 0.0); if (0 === $accountId) { - $accountId = (int)($parameters[0] ?? 0.0); + $accountId = (int) ($parameters[0] ?? 0.0); } $query = AccountMeta::leftJoin('accounts', 'accounts.id', '=', 'account_meta.account_id') @@ -606,6 +607,47 @@ class FireflyValidator extends Validator return true; } + /** + * @param $attribute + * @param $value + * @return bool + */ + public function validateUniqueCurrencyCode($attribute, $value): bool + { + return $this->validateUniqueCurrency('code', (string) $attribute, (string) $value); + } + + /** + * @param $attribute + * @param $value + * @return bool + */ + public function validateUniqueCurrencyName($attribute, $value): bool + { + return $this->validateUniqueCurrency('name', (string) $attribute, (string) $value); + } + + /** + * @param string $field + * @param string $attribute + * @param string $value + * @return bool + */ + public function validateUniqueCurrency(string $field, string $attribute, string $value): bool + { + return 0 === DB::table('transaction_currencies')->where($field, $value)->whereNull('deleted_at')->count(); + } + + /** + * @param $attribute + * @param $value + * @return bool + */ + public function validateUniqueCurrencySymbol($attribute, $value): bool + { + return $this->validateUniqueCurrency('symbol', (string) $attribute, (string) $value); + } + /** * @param mixed $value * @param mixed $parameters @@ -615,7 +657,7 @@ class FireflyValidator extends Validator */ public function validateUniqueExistingWebhook($value, $parameters, $something): bool { - $existingId = (int)($something[0] ?? 0); + $existingId = (int) ($something[0] ?? 0); $trigger = 0; $response = 0; $delivery = 0; @@ -671,15 +713,15 @@ class FireflyValidator extends Validator public function validateUniqueObjectForUser($attribute, $value, $parameters): bool { [$table, $field] = $parameters; - $exclude = (int)($parameters[2] ?? 0.0); + $exclude = (int) ($parameters[2] ?? 0.0); /* * If other data (in $this->getData()) contains * ID field, set that field to be the $exclude. */ $data = $this->getData(); - if (!array_key_exists(2, $parameters) && array_key_exists('id', $data) && (int)$data['id'] > 0) { - $exclude = (int)$data['id']; + if (!array_key_exists(2, $parameters) && array_key_exists('id', $data) && (int) $data['id'] > 0) { + $exclude = (int) $data['id']; } // get entries from table $set = DB::table($table)->where('user_id', auth()->user()->id)->whereNull('deleted_at') @@ -711,7 +753,7 @@ class FireflyValidator extends Validator ->where('object_groups.user_id', auth()->user()->id) ->where('object_groups.title', $value); if (null !== $exclude) { - $query->where('object_groups.id', '!=', (int)$exclude); + $query->where('object_groups.id', '!=', (int) $exclude); } return 0 === $query->count(); @@ -732,7 +774,7 @@ class FireflyValidator extends Validator $query = DB::table('piggy_banks')->whereNull('piggy_banks.deleted_at') ->leftJoin('accounts', 'accounts.id', '=', 'piggy_banks.account_id')->where('accounts.user_id', auth()->user()->id); if (null !== $exclude) { - $query->where('piggy_banks.id', '!=', (int)$exclude); + $query->where('piggy_banks.id', '!=', (int) $exclude); } $query->where('piggy_banks.name', $value); diff --git a/app/Validation/GroupValidation.php b/app/Validation/GroupValidation.php index 745adada79..d4802bcc9e 100644 --- a/app/Validation/GroupValidation.php +++ b/app/Validation/GroupValidation.php @@ -43,6 +43,36 @@ trait GroupValidation */ abstract protected function getTransactionsArray(Validator $validator): array; + /** + * @param Validator $validator + */ + protected function preventNoAccountInfo(Validator $validator): void + { + $transactions = $this->getTransactionsArray($validator); + $keys = ['source_id', 'destination_id', 'source_name', 'destination_name', 'source_iban', 'destination_iban', 'source_number', 'destination_number']; + /** @var array $transaction */ + foreach ($transactions as $index => $transaction) { + $hasAccountInfo = false; + $hasJournalId = array_key_exists('transaction_journal_id', $transaction); + foreach ($keys as $key) { + if (array_key_exists($key, $transaction) && '' !== (string) $transaction[$key]) { + $hasAccountInfo = true; + } + } + // set errors: + if (false === $hasAccountInfo && !$hasJournalId) { + $validator->errors()->add( + sprintf('transactions.%d.source_id', $index), (string) trans('validation.generic_no_source') + ); + $validator->errors()->add( + sprintf('transactions.%d.destination_id', $index), (string) trans('validation.generic_no_destination') + ); + } + } + + // only an issue if there is no transaction_journal_id + } + /** * Adds an error to the "description" field when the user has submitted no descriptions and no * journal description. @@ -83,36 +113,6 @@ trait GroupValidation } } - /** - * @param Validator $validator - */ - protected function preventNoAccountInfo(Validator $validator): void - { - $transactions = $this->getTransactionsArray($validator); - $keys = ['source_id', 'destination_id', 'source_name', 'destination_name', 'source_iban', 'destination_iban', 'source_number', 'destination_number']; - /** @var array $transaction */ - foreach ($transactions as $index => $transaction) { - $hasAccountInfo = false; - $hasJournalId = array_key_exists('transaction_journal_id', $transaction); - foreach ($keys as $key) { - if (array_key_exists($key, $transaction) && '' !== (string) $transaction[$key]) { - $hasAccountInfo = true; - } - } - // set errors: - if (false === $hasAccountInfo && !$hasJournalId) { - $validator->errors()->add( - sprintf('transactions.%d.source_id', $index), (string) trans('validation.generic_no_source') - ); - $validator->errors()->add( - sprintf('transactions.%d.destination_id', $index), (string) trans('validation.generic_no_destination') - ); - } - } - - // only an issue if there is no transaction_journal_id - } - /** * This method validates if the user has submitted transaction journal ID's for each array they submit, if they've submitted more than 1 transaction * journal. This check is necessary because Firefly III isn't able to distinguish between journals without the ID. diff --git a/app/Validation/RecurrenceValidation.php b/app/Validation/RecurrenceValidation.php index fa5160fbc3..d4400760ee 100644 --- a/app/Validation/RecurrenceValidation.php +++ b/app/Validation/RecurrenceValidation.php @@ -91,7 +91,7 @@ trait RecurrenceValidation continue; } // validate source account. - $sourceId = array_key_exists('source_id', $transaction) ? (int)$transaction['source_id'] : null; + $sourceId = array_key_exists('source_id', $transaction) ? (int) $transaction['source_id'] : null; $sourceName = $transaction['source_name'] ?? null; $validSource = $accountValidator->validateSource(['id' => $sourceId, 'name' => $sourceName]); @@ -103,7 +103,7 @@ trait RecurrenceValidation return; } // validate destination account - $destinationId = array_key_exists('destination_id', $transaction) ? (int)$transaction['destination_id'] : null; + $destinationId = array_key_exists('destination_id', $transaction) ? (int) $transaction['destination_id'] : null; $destinationName = $transaction['destination_name'] ?? null; $validDestination = $accountValidator->validateDestination(['id' => $destinationId, 'name' => $destinationName,]); // do something with result: @@ -127,7 +127,7 @@ trait RecurrenceValidation $repetitions = $data['repetitions'] ?? []; // need at least one transaction if (!is_countable($repetitions) || empty($repetitions)) { - $validator->errors()->add('repetitions', (string)trans('validation.at_least_one_repetition')); + $validator->errors()->add('repetitions', (string) trans('validation.at_least_one_repetition')); } } @@ -145,7 +145,7 @@ trait RecurrenceValidation } // need at least one transaction if (empty($repetitions)) { - $validator->errors()->add('repetitions', (string)trans('validation.at_least_one_repetition')); + $validator->errors()->add('repetitions', (string) trans('validation.at_least_one_repetition')); } } @@ -162,15 +162,15 @@ trait RecurrenceValidation $repeatUntil = $data['repeat_until'] ?? null; if (null !== $repetitions && null !== $repeatUntil) { // expect a date OR count: - $validator->errors()->add('repeat_until', (string)trans('validation.require_repeat_until')); - $validator->errors()->add('nr_of_repetitions', (string)trans('validation.require_repeat_until')); + $validator->errors()->add('repeat_until', (string) trans('validation.require_repeat_until')); + $validator->errors()->add('nr_of_repetitions', (string) trans('validation.require_repeat_until')); } } public function validateRecurringConfig(Validator $validator) { $data = $validator->getData(); - $reps = array_key_exists('nr_of_repetitions', $data) ? (int)$data['nr_of_repetitions'] : null; + $reps = array_key_exists('nr_of_repetitions', $data) ? (int) $data['nr_of_repetitions'] : null; $repeatUntil = array_key_exists('repeat_until', $data) ? new Carbon($data['repeat_until']) : null; if (null === $reps && null === $repeatUntil) { @@ -193,7 +193,7 @@ trait RecurrenceValidation $data = $validator->getData(); $repetitions = $data['repetitions'] ?? []; if (!is_array($repetitions)) { - $validator->errors()->add(sprintf('repetitions.%d.type', 0), (string)trans('validation.valid_recurrence_rep_type')); + $validator->errors()->add(sprintf('repetitions.%d.type', 0), (string) trans('validation.valid_recurrence_rep_type')); return; } @@ -211,23 +211,23 @@ trait RecurrenceValidation $repetition['moment'] = $repetition['moment'] ?? 'invalid'; switch ($repetition['type'] ?? 'empty') { default: - $validator->errors()->add(sprintf('repetitions.%d.type', $index), (string)trans('validation.valid_recurrence_rep_type')); + $validator->errors()->add(sprintf('repetitions.%d.type', $index), (string) trans('validation.valid_recurrence_rep_type')); return; case 'daily': - $this->validateDaily($validator, $index, (string)$repetition['moment']); + $this->validateDaily($validator, $index, (string) $repetition['moment']); break; case 'monthly': - $this->validateMonthly($validator, $index, (int)$repetition['moment']); + $this->validateMonthly($validator, $index, (int) $repetition['moment']); break; case 'ndom': - $this->validateNdom($validator, $index, (string)$repetition['moment']); + $this->validateNdom($validator, $index, (string) $repetition['moment']); break; case 'weekly': - $this->validateWeekly($validator, $index, (int)$repetition['moment']); + $this->validateWeekly($validator, $index, (int) $repetition['moment']); break; case 'yearly': - $this->validateYearly($validator, $index, (string)$repetition['moment']); + $this->validateYearly($validator, $index, (string) $repetition['moment']); break; } } @@ -243,7 +243,7 @@ trait RecurrenceValidation protected function validateDaily(Validator $validator, int $index, string $moment): void { if ('' !== $moment) { - $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string)trans('validation.valid_recurrence_rep_moment')); + $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string) trans('validation.valid_recurrence_rep_moment')); } } @@ -257,7 +257,7 @@ trait RecurrenceValidation protected function validateMonthly(Validator $validator, int $index, int $dayOfMonth): void { if ($dayOfMonth < 1 || $dayOfMonth > 31) { - $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string)trans('validation.valid_recurrence_rep_moment')); + $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string) trans('validation.valid_recurrence_rep_moment')); } } @@ -273,19 +273,19 @@ trait RecurrenceValidation { $parameters = explode(',', $moment); if (2 !== count($parameters)) { - $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string)trans('validation.valid_recurrence_rep_moment')); + $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string) trans('validation.valid_recurrence_rep_moment')); return; } - $nthDay = (int)($parameters[0] ?? 0.0); - $dayOfWeek = (int)($parameters[1] ?? 0.0); + $nthDay = (int) ($parameters[0] ?? 0.0); + $dayOfWeek = (int) ($parameters[1] ?? 0.0); if ($nthDay < 1 || $nthDay > 5) { - $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string)trans('validation.valid_recurrence_rep_moment')); + $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string) trans('validation.valid_recurrence_rep_moment')); return; } if ($dayOfWeek < 1 || $dayOfWeek > 7) { - $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string)trans('validation.valid_recurrence_rep_moment')); + $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string) trans('validation.valid_recurrence_rep_moment')); } } @@ -299,7 +299,7 @@ trait RecurrenceValidation protected function validateWeekly(Validator $validator, int $index, int $dayOfWeek): void { if ($dayOfWeek < 1 || $dayOfWeek > 7) { - $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string)trans('validation.valid_recurrence_rep_moment')); + $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string) trans('validation.valid_recurrence_rep_moment')); } } @@ -316,7 +316,7 @@ trait RecurrenceValidation Carbon::createFromFormat('Y-m-d', $moment); } catch (InvalidArgumentException $e) { Log::debug(sprintf('Invalid argument for Carbon: %s', $e->getMessage())); - $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string)trans('validation.valid_recurrence_rep_moment')); + $validator->errors()->add(sprintf('repetitions.%d.moment', $index), (string) trans('validation.valid_recurrence_rep_moment')); } } } diff --git a/app/Validation/TransactionValidation.php b/app/Validation/TransactionValidation.php index 0289c6ab60..25c7c303bd 100644 --- a/app/Validation/TransactionValidation.php +++ b/app/Validation/TransactionValidation.php @@ -100,10 +100,10 @@ trait TransactionValidation $accountValidator->setTransactionType($transactionType); // validate source account. - $sourceId = array_key_exists('source_id', $transaction) ? (int)$transaction['source_id'] : null; - $sourceName = array_key_exists('source_name', $transaction) ? (string)$transaction['source_name'] : null; - $sourceIban = array_key_exists('source_iban', $transaction) ? (string)$transaction['source_iban'] : null; - $sourceNumber = array_key_exists('source_number', $transaction) ? (string)$transaction['source_number'] : null; + $sourceId = array_key_exists('source_id', $transaction) ? (int) $transaction['source_id'] : null; + $sourceName = array_key_exists('source_name', $transaction) ? (string) $transaction['source_name'] : null; + $sourceIban = array_key_exists('source_iban', $transaction) ? (string) $transaction['source_iban'] : null; + $sourceNumber = array_key_exists('source_number', $transaction) ? (string) $transaction['source_number'] : null; $array = [ 'id' => $sourceId, 'name' => $sourceName, @@ -120,10 +120,10 @@ trait TransactionValidation return; } // validate destination account - $destinationId = array_key_exists('destination_id', $transaction) ? (int)$transaction['destination_id'] : null; - $destinationName = array_key_exists('destination_name', $transaction) ? (string)$transaction['destination_name'] : null; - $destinationIban = array_key_exists('destination_iban', $transaction) ? (string)$transaction['destination_iban'] : null; - $destinationNumber = array_key_exists('destination_number', $transaction) ? (string)$transaction['destination_number'] : null; + $destinationId = array_key_exists('destination_id', $transaction) ? (int) $transaction['destination_id'] : null; + $destinationName = array_key_exists('destination_name', $transaction) ? (string) $transaction['destination_name'] : null; + $destinationIban = array_key_exists('destination_iban', $transaction) ? (string) $transaction['destination_iban'] : null; + $destinationNumber = array_key_exists('destination_number', $transaction) ? (string) $transaction['destination_number'] : null; $array = [ 'id' => $destinationId, 'name' => $destinationName, @@ -188,7 +188,7 @@ trait TransactionValidation // validate if the submitted source and / or name are valid if (array_key_exists('source_id', $transaction) || array_key_exists('source_name', $transaction)) { Log::debug('Will try to validate source account information.'); - $sourceId = (int)($transaction['source_id'] ?? 0); + $sourceId = (int) ($transaction['source_id'] ?? 0); $sourceName = $transaction['source_name'] ?? null; $validSource = $accountValidator->validateSource(['id' => $sourceId, 'name' => $sourceName]); @@ -216,7 +216,7 @@ trait TransactionValidation $accountValidator->source = $source; } } - $destinationId = (int)($transaction['destination_id'] ?? 0); + $destinationId = (int) ($transaction['destination_id'] ?? 0); $destinationName = $transaction['destination_name'] ?? null; $array = ['id' => $destinationId, 'name' => $destinationName,]; $validDestination = $accountValidator->validateDestination($array); @@ -257,7 +257,7 @@ trait TransactionValidation } /** @var TransactionJournal $journal */ foreach ($transactionGroup->transactionJournals as $journal) { - if ((int)$journal->id === (int)$transaction['transaction_journal_id']) { + if ((int) $journal->id === (int) $transaction['transaction_journal_id']) { return $journal->transactions()->where('amount', '<', 0)->first()->account; } } @@ -277,7 +277,7 @@ trait TransactionValidation // need at least one transaction if (empty($transactions)) { - $validator->errors()->add('transactions', (string)trans('validation.at_least_one_transaction')); + $validator->errors()->add('transactions', (string) trans('validation.at_least_one_transaction')); } } @@ -292,7 +292,7 @@ trait TransactionValidation $transactions = $this->getTransactionsArray($validator); // need at least one transaction if (empty($transactions)) { - $validator->errors()->add('transactions.0.description', (string)trans('validation.at_least_one_transaction')); + $validator->errors()->add('transactions.0.description', (string) trans('validation.at_least_one_transaction')); Log::debug('Added error: at_least_one_transaction.'); return; @@ -308,7 +308,7 @@ trait TransactionValidation $transactions = $this->getTransactionsArray($validator); foreach ($transactions as $key => $value) { if (!is_int($key)) { - $validator->errors()->add('transactions.0.description', (string)trans('validation.at_least_one_transaction')); + $validator->errors()->add('transactions.0.description', (string) trans('validation.at_least_one_transaction')); Log::debug('Added error: at_least_one_transaction.'); return; @@ -332,13 +332,13 @@ trait TransactionValidation } $unique = array_unique($types); if (count($unique) > 1) { - $validator->errors()->add('transactions.0.type', (string)trans('validation.transaction_types_equal')); + $validator->errors()->add('transactions.0.type', (string) trans('validation.transaction_types_equal')); return; } $first = $unique[0] ?? 'invalid'; if ('invalid' === $first) { - $validator->errors()->add('transactions.0.type', (string)trans('validation.invalid_transaction_type')); + $validator->errors()->add('transactions.0.type', (string) trans('validation.invalid_transaction_type')); } } @@ -353,14 +353,14 @@ trait TransactionValidation $transactions = $this->getTransactionsArray($validator); $types = []; foreach ($transactions as $transaction) { - $originalType = $this->getOriginalType((int)($transaction['transaction_journal_id'] ?? 0)); + $originalType = $this->getOriginalType((int) ($transaction['transaction_journal_id'] ?? 0)); // if type is not set, fall back to the type of the journal, if one is given. $types[] = $transaction['type'] ?? $originalType; } $unique = array_unique($types); if (count($unique) > 1) { Log::warning('Add error for mismatch transaction types.'); - $validator->errors()->add('transactions.0.type', (string)trans('validation.transaction_types_equal')); + $validator->errors()->add('transactions.0.type', (string) trans('validation.transaction_types_equal')); return; } @@ -411,18 +411,18 @@ trait TransactionValidation default: case 'withdrawal': if (count($sources) > 1) { - $validator->errors()->add('transactions.0.source_id', (string)trans('validation.all_accounts_equal')); + $validator->errors()->add('transactions.0.source_id', (string) trans('validation.all_accounts_equal')); } break; case 'deposit': if (count($dests) > 1) { - $validator->errors()->add('transactions.0.destination_id', (string)trans('validation.all_accounts_equal')); + $validator->errors()->add('transactions.0.destination_id', (string) trans('validation.all_accounts_equal')); } break; case'transfer': if (count($sources) > 1 || count($dests) > 1) { - $validator->errors()->add('transactions.0.source_id', (string)trans('validation.all_accounts_equal')); - $validator->errors()->add('transactions.0.destination_id', (string)trans('validation.all_accounts_equal')); + $validator->errors()->add('transactions.0.source_id', (string) trans('validation.all_accounts_equal')); + $validator->errors()->add('transactions.0.destination_id', (string) trans('validation.all_accounts_equal')); } break; } @@ -453,14 +453,14 @@ trait TransactionValidation $result = $this->compareAccountData($type, $comparison); if (false === $result) { if ('withdrawal' === $type) { - $validator->errors()->add('transactions.0.source_id', (string)trans('validation.all_accounts_equal')); + $validator->errors()->add('transactions.0.source_id', (string) trans('validation.all_accounts_equal')); } if ('deposit' === $type) { - $validator->errors()->add('transactions.0.destination_id', (string)trans('validation.all_accounts_equal')); + $validator->errors()->add('transactions.0.destination_id', (string) trans('validation.all_accounts_equal')); } if ('transfer' === $type) { - $validator->errors()->add('transactions.0.source_id', (string)trans('validation.all_accounts_equal')); - $validator->errors()->add('transactions.0.destination_id', (string)trans('validation.all_accounts_equal')); + $validator->errors()->add('transactions.0.source_id', (string) trans('validation.all_accounts_equal')); + $validator->errors()->add('transactions.0.destination_id', (string) trans('validation.all_accounts_equal')); } Log::warning('Add error about equal accounts.'); @@ -483,7 +483,7 @@ trait TransactionValidation /** @var array $transaction */ foreach ($transactions as $transaction) { // source or destination may be omitted. If this is the case, use the original source / destination name + ID. - $originalData = $this->getOriginalData((int)($transaction['transaction_journal_id'] ?? 0)); + $originalData = $this->getOriginalData((int) ($transaction['transaction_journal_id'] ?? 0)); // get field. $comparison[$field][] = $transaction[$field] ?? $originalData[$field]; diff --git a/changelog.md b/changelog.md index 5512ac21cd..f18105f38c 100644 --- a/changelog.md +++ b/changelog.md @@ -2,6 +2,44 @@ All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/). +## 5.7.0 - 2022-04-04 + +- ⚠️ This release no longer supports LDAP. +- ⚠️ This is the last release that supports PHP 8.0 +- 👍 Want to try the new v3 layout? At your own risk, browse to `/v3/`. + +Please refer to the [documentation](https://docs.firefly-iii.org/firefly-iii/) and support channels if you run into problems: + +- [Gitter.im](https://gitter.im/firefly-iii/firefly-iii) +- [Twitter](https://twitter.com/Firefly_III/) +- [GitHub Issues](https://github.com/firefly-iii/firefly-iii/issues) +- [GitHub Discussions](https://github.com/firefly-iii/firefly-iii/discussions) + +### Added +- Error email message now includes HTTP headers. +- [Issue 5373](https://github.com/firefly-iii/firefly-iii/issues/5373) You can give budgets notes, although they're not visible yet. +- [Issue 5648](https://github.com/firefly-iii/firefly-iii/issues/5648) The Docker image supports custom locales, see `.env.example` for instructions. +- [Issue 3984](https://github.com/firefly-iii/firefly-iii/issues/3984) [issue 5636](https://github.com/firefly-iii/firefly-iii/issues/5636) [issue 4903](https://github.com/firefly-iii/firefly-iii/issues/4903) [issue 5326](https://github.com/firefly-iii/firefly-iii/issues/5326) Lots of new search and rule operators. For the full list, see [search.php](https://github.com/firefly-iii/firefly-iii/blob/main/config/search.php) (a bit technical). +- [Issue 5269](https://github.com/firefly-iii/firefly-iii/issues/5269) It's possible to add piggy banks that have no explicit target amount goal. +- [Issue 4893](https://github.com/firefly-iii/firefly-iii/issues/4893) Bills can be given an end date and an extension date and will warn you about those dates. + +### Changed +- [Issue 5757](https://github.com/firefly-iii/firefly-iii/issues/5757) Upgrade to Laravel 9. + +### Deprecated +- [Issue 5911](https://github.com/firefly-iii/firefly-iii/issues/5911) Removed support for LDAP. + +### Fixed +- [Issue 5810](https://github.com/firefly-iii/firefly-iii/issues/5810) Could not search for `no_notes:true` in some cases. +- [Issue 5869](https://github.com/firefly-iii/firefly-iii/issues/5869) Converting transactions would sometimes fail. +- [Issue 5870](https://github.com/firefly-iii/firefly-iii/issues/5870) Fixed broken link to instructions. +- [Issue 5903](https://github.com/firefly-iii/firefly-iii/issues/5903) API budget limits was broken due to upgraded package. +- [Issue 5852](https://github.com/firefly-iii/firefly-iii/issues/5852) It was not possible to recreate a currency. +- [Issue 5882](https://github.com/firefly-iii/firefly-iii/issues/5882) `no_external_url:true` was broken. +- [Issue 5770](https://github.com/firefly-iii/firefly-iii/issues/5770) Liabilities spent amount would be doubled. +- [Issue 4013](https://github.com/firefly-iii/firefly-iii/issues/4013) Date in email message was not localized. +- [Issue 5949](https://github.com/firefly-iii/firefly-iii/issues/5949) Deleting a transaction would sometimes send you back to a 404. + ## 5.6.16 - 2022-03-01 ### Fixed diff --git a/composer.json b/composer.json index ddb3444823..f66df744d2 100644 --- a/composer.json +++ b/composer.json @@ -49,7 +49,7 @@ "support": { "email": "james@firefly-iii.org", "issues": "https://github.com/firefly-iii/firefly-iii/issues", - "forum": "https://reddit.com/r/FireflyIII", + "forum": "https://gitter.im/firefly-iii/firefly-iii", "wiki": "https://github.com/firefly-iii/help/wiki", "source": "https://github.com/firefly-iii/firefly-iii", "docs": "https://docs.firefly-iii.org/" @@ -62,10 +62,6 @@ { "type": "github", "url": "https://github.com/sponsors/JC5" - }, - { - "type": "paypal", - "url": "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=L62W7DVD5ETPC&source=url" } ], "require": { @@ -73,7 +69,6 @@ "ext-bcmath": "*", "ext-curl": "*", "ext-fileinfo": "*", - "ext-gd": "*", "ext-iconv": "*", "ext-intl": "*", "ext-json": "*", @@ -89,12 +84,11 @@ "bacon/bacon-qr-code": "2.*", "diglactic/laravel-breadcrumbs": "^7.1", "doctrine/dbal": "3.*", - "fideloper/proxy": "4.*", "gdbots/query-parser": "^2.0", "guzzlehttp/guzzle": "^7.4", - "jc5/google2fa-laravel": "2.0.6", + "jc5/google2fa-laravel": "^2.0", "jc5/recovery": "^2", - "laravel/framework": "^8.83", + "laravel/framework": "^9", "laravel/passport": "10.*", "laravel/sanctum": "^2.14", "laravel/ui": "^3.4", @@ -102,12 +96,16 @@ "league/commonmark": "2.*", "league/csv": "^9.7", "league/fractal": "0.*", + "nunomaduro/collision": "^6.1", "pragmarx/google2fa": "^8.0", "predis/predis": "^1.1", "psr/log": "<3", - "ramsey/uuid": "^4.2", - "rcrowe/twigbridge": "^0.13", - "spatie/data-transfer-object": "^3.7" + "ramsey/uuid": "^4.3", + "rcrowe/twigbridge": "^0.14", + "spatie/data-transfer-object": "^3.7", + "spatie/laravel-ignition": "^1.0", + "symfony/http-client": "^6.0", + "symfony/mailgun-mailer": "^6.0" }, "require-dev": { "barryvdh/laravel-debugbar": "^3.6", @@ -118,8 +116,6 @@ "phpunit/phpunit": "^9.5" }, "suggest": { - "directorytree/ldaprecord-laravel": "If you want to login using LDAP.", - "ext-ldap": "Needed to support LDAP." }, "autoload": { "psr-4": { diff --git a/composer.lock b/composer.lock index 4e74c7dc57..0d6dce87cd 100644 --- a/composer.lock +++ b/composer.lock @@ -4,20 +4,20 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "b18d0182615f53ac1b5c84c9aa9832d6", + "content-hash": "1c676a0a4c48460c6fcd9800be95736b", "packages": [ { "name": "bacon/bacon-qr-code", - "version": "2.0.6", + "version": "2.0.7", "source": { "type": "git", "url": "https://github.com/Bacon/BaconQrCode.git", - "reference": "0069435e2a01a57193b25790f105a5d3168653c1" + "reference": "d70c840f68657ce49094b8d91f9ee0cc07fbf66c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Bacon/BaconQrCode/zipball/0069435e2a01a57193b25790f105a5d3168653c1", - "reference": "0069435e2a01a57193b25790f105a5d3168653c1", + "url": "https://api.github.com/repos/Bacon/BaconQrCode/zipball/d70c840f68657ce49094b8d91f9ee0cc07fbf66c", + "reference": "d70c840f68657ce49094b8d91f9ee0cc07fbf66c", "shasum": "" }, "require": { @@ -56,9 +56,9 @@ "homepage": "https://github.com/Bacon/BaconQrCode", "support": { "issues": "https://github.com/Bacon/BaconQrCode/issues", - "source": "https://github.com/Bacon/BaconQrCode/tree/2.0.6" + "source": "https://github.com/Bacon/BaconQrCode/tree/2.0.7" }, - "time": "2022-02-04T20:16:05+00:00" + "time": "2022-03-14T02:02:36+00:00" }, { "name": "brick/math", @@ -480,16 +480,16 @@ }, { "name": "doctrine/dbal", - "version": "3.3.2", + "version": "3.3.4", "source": { "type": "git", "url": "https://github.com/doctrine/dbal.git", - "reference": "35eae239ef515d55ebb24e9d4715cad09a4f58ed" + "reference": "83f779beaea1893c0bece093ab2104c6d15a7f26" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/doctrine/dbal/zipball/35eae239ef515d55ebb24e9d4715cad09a4f58ed", - "reference": "35eae239ef515d55ebb24e9d4715cad09a4f58ed", + "url": "https://api.github.com/repos/doctrine/dbal/zipball/83f779beaea1893c0bece093ab2104c6d15a7f26", + "reference": "83f779beaea1893c0bece093ab2104c6d15a7f26", "shasum": "" }, "require": { @@ -504,14 +504,14 @@ "require-dev": { "doctrine/coding-standard": "9.0.0", "jetbrains/phpstorm-stubs": "2021.1", - "phpstan/phpstan": "1.4.0", + "phpstan/phpstan": "1.4.6", "phpstan/phpstan-strict-rules": "^1.1", - "phpunit/phpunit": "9.5.11", + "phpunit/phpunit": "9.5.16", "psalm/plugin-phpunit": "0.16.1", "squizlabs/php_codesniffer": "3.6.2", "symfony/cache": "^5.2|^6.0", "symfony/console": "^2.7|^3.0|^4.0|^5.0|^6.0", - "vimeo/psalm": "4.16.1" + "vimeo/psalm": "4.22.0" }, "suggest": { "symfony/console": "For helpful console commands such as SQL execution and import of files." @@ -571,7 +571,7 @@ ], "support": { "issues": "https://github.com/doctrine/dbal/issues", - "source": "https://github.com/doctrine/dbal/tree/3.3.2" + "source": "https://github.com/doctrine/dbal/tree/3.3.4" }, "funding": [ { @@ -587,7 +587,7 @@ "type": "tidelift" } ], - "time": "2022-02-05T16:33:45+00:00" + "time": "2022-03-20T18:37:29+00:00" }, { "name": "doctrine/deprecations", @@ -819,16 +819,16 @@ }, { "name": "doctrine/lexer", - "version": "1.2.2", + "version": "1.2.3", "source": { "type": "git", "url": "https://github.com/doctrine/lexer.git", - "reference": "9c50f840f257bbb941e6f4a0e94ccf5db5c3f76c" + "reference": "c268e882d4dbdd85e36e4ad69e02dc284f89d229" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/doctrine/lexer/zipball/9c50f840f257bbb941e6f4a0e94ccf5db5c3f76c", - "reference": "9c50f840f257bbb941e6f4a0e94ccf5db5c3f76c", + "url": "https://api.github.com/repos/doctrine/lexer/zipball/c268e882d4dbdd85e36e4ad69e02dc284f89d229", + "reference": "c268e882d4dbdd85e36e4ad69e02dc284f89d229", "shasum": "" }, "require": { @@ -836,7 +836,7 @@ }, "require-dev": { "doctrine/coding-standard": "^9.0", - "phpstan/phpstan": "1.3", + "phpstan/phpstan": "^1.3", "phpunit/phpunit": "^7.5 || ^8.5 || ^9.5", "vimeo/psalm": "^4.11" }, @@ -875,7 +875,7 @@ ], "support": { "issues": "https://github.com/doctrine/lexer/issues", - "source": "https://github.com/doctrine/lexer/tree/1.2.2" + "source": "https://github.com/doctrine/lexer/tree/1.2.3" }, "funding": [ { @@ -891,7 +891,7 @@ "type": "tidelift" } ], - "time": "2022-01-12T08:27:12+00:00" + "time": "2022-02-28T11:07:21+00:00" }, { "name": "dragonmantank/cron-expression", @@ -956,27 +956,27 @@ }, { "name": "egulias/email-validator", - "version": "2.1.25", + "version": "3.1.2", "source": { "type": "git", "url": "https://github.com/egulias/EmailValidator.git", - "reference": "0dbf5d78455d4d6a41d186da50adc1122ec066f4" + "reference": "ee0db30118f661fb166bcffbf5d82032df484697" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/egulias/EmailValidator/zipball/0dbf5d78455d4d6a41d186da50adc1122ec066f4", - "reference": "0dbf5d78455d4d6a41d186da50adc1122ec066f4", + "url": "https://api.github.com/repos/egulias/EmailValidator/zipball/ee0db30118f661fb166bcffbf5d82032df484697", + "reference": "ee0db30118f661fb166bcffbf5d82032df484697", "shasum": "" }, "require": { - "doctrine/lexer": "^1.0.1", - "php": ">=5.5", - "symfony/polyfill-intl-idn": "^1.10" + "doctrine/lexer": "^1.2", + "php": ">=7.2", + "symfony/polyfill-intl-idn": "^1.15" }, "require-dev": { - "dominicsayers/isemail": "^3.0.7", - "phpunit/phpunit": "^4.8.36|^7.5.15", - "satooshi/php-coveralls": "^1.0.1" + "php-coveralls/php-coveralls": "^2.2", + "phpunit/phpunit": "^8.5.8|^9.3.3", + "vimeo/psalm": "^4" }, "suggest": { "ext-intl": "PHP Internationalization Libraries are required to use the SpoofChecking validation" @@ -984,7 +984,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "2.1.x-dev" + "dev-master": "3.0.x-dev" } }, "autoload": { @@ -1012,7 +1012,7 @@ ], "support": { "issues": "https://github.com/egulias/EmailValidator/issues", - "source": "https://github.com/egulias/EmailValidator/tree/2.1.25" + "source": "https://github.com/egulias/EmailValidator/tree/3.1.2" }, "funding": [ { @@ -1020,7 +1020,7 @@ "type": "github" } ], - "time": "2020-12-29T14:50:06+00:00" + "time": "2021-10-11T09:18:27+00:00" }, { "name": "facade/ignition-contracts", @@ -1076,39 +1076,41 @@ "time": "2020-10-16T08:27:54+00:00" }, { - "name": "fideloper/proxy", - "version": "4.4.1", + "name": "filp/whoops", + "version": "2.14.5", "source": { "type": "git", - "url": "https://github.com/fideloper/TrustedProxy.git", - "reference": "c073b2bd04d1c90e04dc1b787662b558dd65ade0" + "url": "https://github.com/filp/whoops.git", + "reference": "a63e5e8f26ebbebf8ed3c5c691637325512eb0dc" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/fideloper/TrustedProxy/zipball/c073b2bd04d1c90e04dc1b787662b558dd65ade0", - "reference": "c073b2bd04d1c90e04dc1b787662b558dd65ade0", + "url": "https://api.github.com/repos/filp/whoops/zipball/a63e5e8f26ebbebf8ed3c5c691637325512eb0dc", + "reference": "a63e5e8f26ebbebf8ed3c5c691637325512eb0dc", "shasum": "" }, "require": { - "illuminate/contracts": "^5.0|^6.0|^7.0|^8.0|^9.0", - "php": ">=5.4.0" + "php": "^5.5.9 || ^7.0 || ^8.0", + "psr/log": "^1.0.1 || ^2.0 || ^3.0" }, "require-dev": { - "illuminate/http": "^5.0|^6.0|^7.0|^8.0|^9.0", - "mockery/mockery": "^1.0", - "phpunit/phpunit": "^6.0" + "mockery/mockery": "^0.9 || ^1.0", + "phpunit/phpunit": "^4.8.36 || ^5.7.27 || ^6.5.14 || ^7.5.20 || ^8.5.8 || ^9.3.3", + "symfony/var-dumper": "^2.6 || ^3.0 || ^4.0 || ^5.0" + }, + "suggest": { + "symfony/var-dumper": "Pretty print complex values better with var-dumper available", + "whoops/soap": "Formats errors as SOAP responses" }, "type": "library", "extra": { - "laravel": { - "providers": [ - "Fideloper\\Proxy\\TrustedProxyServiceProvider" - ] + "branch-alias": { + "dev-master": "2.7-dev" } }, "autoload": { "psr-4": { - "Fideloper\\Proxy\\": "src/" + "Whoops\\": "src/Whoops/" } }, "notification-url": "https://packagist.org/downloads/", @@ -1117,21 +1119,32 @@ ], "authors": [ { - "name": "Chris Fidao", - "email": "fideloper@gmail.com" + "name": "Filipe Dobreira", + "homepage": "https://github.com/filp", + "role": "Developer" } ], - "description": "Set trusted proxies for Laravel", + "description": "php error handling for cool kids", + "homepage": "https://filp.github.io/whoops/", "keywords": [ - "load balancing", - "proxy", - "trusted proxy" + "error", + "exception", + "handling", + "library", + "throwable", + "whoops" ], "support": { - "issues": "https://github.com/fideloper/TrustedProxy/issues", - "source": "https://github.com/fideloper/TrustedProxy/tree/4.4.1" + "issues": "https://github.com/filp/whoops/issues", + "source": "https://github.com/filp/whoops/tree/2.14.5" }, - "time": "2020-10-22T13:48:01+00:00" + "funding": [ + { + "url": "https://github.com/denis-sokolov", + "type": "github" + } + ], + "time": "2022-01-07T12:00:00+00:00" }, { "name": "firebase/php-jwt", @@ -1190,6 +1203,77 @@ }, "time": "2021-11-08T20:18:51+00:00" }, + { + "name": "fruitcake/php-cors", + "version": "v1.2.0", + "source": { + "type": "git", + "url": "https://github.com/fruitcake/php-cors.git", + "reference": "58571acbaa5f9f462c9c77e911700ac66f446d4e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/fruitcake/php-cors/zipball/58571acbaa5f9f462c9c77e911700ac66f446d4e", + "reference": "58571acbaa5f9f462c9c77e911700ac66f446d4e", + "shasum": "" + }, + "require": { + "php": "^7.4|^8.0", + "symfony/http-foundation": "^4.4|^5.4|^6" + }, + "require-dev": { + "phpstan/phpstan": "^1.4", + "phpunit/phpunit": "^9", + "squizlabs/php_codesniffer": "^3.5" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.1-dev" + } + }, + "autoload": { + "psr-4": { + "Fruitcake\\Cors\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fruitcake", + "homepage": "https://fruitcake.nl" + }, + { + "name": "Barryvdh", + "email": "barryvdh@gmail.com" + } + ], + "description": "Cross-origin resource sharing library for the Symfony HttpFoundation", + "homepage": "https://github.com/fruitcake/php-cors", + "keywords": [ + "cors", + "laravel", + "symfony" + ], + "support": { + "issues": "https://github.com/fruitcake/php-cors/issues", + "source": "https://github.com/fruitcake/php-cors/tree/v1.2.0" + }, + "funding": [ + { + "url": "https://fruitcake.nl", + "type": "custom" + }, + { + "url": "https://github.com/barryvdh", + "type": "github" + } + ], + "time": "2022-02-20T15:07:15+00:00" + }, { "name": "gdbots/query-parser", "version": "v2.0.2", @@ -1293,16 +1377,16 @@ }, { "name": "guzzlehttp/guzzle", - "version": "7.4.1", + "version": "7.4.2", "source": { "type": "git", "url": "https://github.com/guzzle/guzzle.git", - "reference": "ee0a041b1760e6a53d2a39c8c34115adc2af2c79" + "reference": "ac1ec1cd9b5624694c3a40be801d94137afb12b4" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/guzzle/guzzle/zipball/ee0a041b1760e6a53d2a39c8c34115adc2af2c79", - "reference": "ee0a041b1760e6a53d2a39c8c34115adc2af2c79", + "url": "https://api.github.com/repos/guzzle/guzzle/zipball/ac1ec1cd9b5624694c3a40be801d94137afb12b4", + "reference": "ac1ec1cd9b5624694c3a40be801d94137afb12b4", "shasum": "" }, "require": { @@ -1397,7 +1481,7 @@ ], "support": { "issues": "https://github.com/guzzle/guzzle/issues", - "source": "https://github.com/guzzle/guzzle/tree/7.4.1" + "source": "https://github.com/guzzle/guzzle/tree/7.4.2" }, "funding": [ { @@ -1413,7 +1497,7 @@ "type": "tidelift" } ], - "time": "2021-12-06T18:43:05+00:00" + "time": "2022-03-20T14:16:28+00:00" }, { "name": "guzzlehttp/promises", @@ -1616,21 +1700,21 @@ }, { "name": "jc5/google2fa-laravel", - "version": "2.0.6", + "version": "v2.0.8", "source": { "type": "git", "url": "https://github.com/JC5/google2fa-laravel.git", - "reference": "271957317a84d36276c698e85db3ea33551e321d" + "reference": "0205b0e58b90ee41e6d108d4c26ad9d0f7997baa" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/JC5/google2fa-laravel/zipball/271957317a84d36276c698e85db3ea33551e321d", - "reference": "271957317a84d36276c698e85db3ea33551e321d", + "url": "https://api.github.com/repos/JC5/google2fa-laravel/zipball/0205b0e58b90ee41e6d108d4c26ad9d0f7997baa", + "reference": "0205b0e58b90ee41e6d108d4c26ad9d0f7997baa", "shasum": "" }, "require": { "laravel/framework": ">=5.4.36", - "php": ">=7.3", + "php": ">=8", "pragmarx/google2fa-qrcode": "^1.0" }, "require-dev": { @@ -1668,7 +1752,7 @@ }, "notification-url": "https://packagist.org/downloads/", "license": [ - "BSD-3-Clause" + "MIT" ], "authors": [ { @@ -1691,33 +1775,33 @@ ], "support": { "issues": "https://github.com/JC5/google2fa-laravel/issues", - "source": "https://github.com/JC5/google2fa-laravel/tree/2.0.6" + "source": "https://github.com/JC5/google2fa-laravel/tree/v2.0.8" }, - "time": "2021-07-10T05:21:50+00:00" + "time": "2022-03-30T16:00:00+00:00" }, { "name": "jc5/recovery", - "version": "v2.1.0", + "version": "v2.2.0", "source": { "type": "git", "url": "https://github.com/JC5/recovery.git", - "reference": "33e7f314fdf0c43db34a17e5757d19190815b363" + "reference": "ad69cb910a92e1aeb75fd7eaa65701cc5b0416f3" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/JC5/recovery/zipball/33e7f314fdf0c43db34a17e5757d19190815b363", - "reference": "33e7f314fdf0c43db34a17e5757d19190815b363", + "url": "https://api.github.com/repos/JC5/recovery/zipball/ad69cb910a92e1aeb75fd7eaa65701cc5b0416f3", + "reference": "ad69cb910a92e1aeb75fd7eaa65701cc5b0416f3", "shasum": "" }, "require": { "ext-json": "*", - "php": "^7.4|^8.0", + "php": ">=8.0", "pragmarx/random": "~0.1" }, "require-dev": { "phpunit/phpunit": ">=5.4.3", "squizlabs/php_codesniffer": "^2.3", - "tightenco/collect": "^5" + "tightenco/collect": "^5.0" }, "suggest": { "tightenco/collect": "Allows to generate recovery codes as collections" @@ -1765,62 +1849,61 @@ "two factor auth" ], "support": { - "source": "https://github.com/JC5/recovery/tree/v2.1.0" + "source": "https://github.com/JC5/recovery/tree/v2.2.0" }, - "time": "2021-01-23T06:04:19+00:00" + "time": "2022-03-31T05:55:34+00:00" }, { "name": "laravel/framework", - "version": "v8.83.2", + "version": "v9.6.0", "source": { "type": "git", "url": "https://github.com/laravel/framework.git", - "reference": "b91b3b5b39fbbdc763746f5714e08d50a4dd7857" + "reference": "47940a1a8774b96696ed57e6736ccea4a880c057" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/framework/zipball/b91b3b5b39fbbdc763746f5714e08d50a4dd7857", - "reference": "b91b3b5b39fbbdc763746f5714e08d50a4dd7857", + "url": "https://api.github.com/repos/laravel/framework/zipball/47940a1a8774b96696ed57e6736ccea4a880c057", + "reference": "47940a1a8774b96696ed57e6736ccea4a880c057", "shasum": "" }, "require": { - "doctrine/inflector": "^1.4|^2.0", - "dragonmantank/cron-expression": "^3.0.2", - "egulias/email-validator": "^2.1.10", - "ext-json": "*", + "doctrine/inflector": "^2.0", + "dragonmantank/cron-expression": "^3.1", + "egulias/email-validator": "^3.1", "ext-mbstring": "*", "ext-openssl": "*", + "fruitcake/php-cors": "^1.2", "laravel/serializable-closure": "^1.0", - "league/commonmark": "^1.3|^2.0.2", - "league/flysystem": "^1.1", + "league/commonmark": "^2.2", + "league/flysystem": "^3.0", "monolog/monolog": "^2.0", "nesbot/carbon": "^2.53.1", - "opis/closure": "^3.6", - "php": "^7.3|^8.0", - "psr/container": "^1.0", - "psr/log": "^1.0|^2.0", - "psr/simple-cache": "^1.0", + "php": "^8.0.2", + "psr/container": "^1.1.1|^2.0.1", + "psr/log": "^1.0|^2.0|^3.0", + "psr/simple-cache": "^1.0|^2.0|^3.0", "ramsey/uuid": "^4.2.2", - "swiftmailer/swiftmailer": "^6.3", - "symfony/console": "^5.4", - "symfony/error-handler": "^5.4", - "symfony/finder": "^5.4", - "symfony/http-foundation": "^5.4", - "symfony/http-kernel": "^5.4", - "symfony/mime": "^5.4", - "symfony/process": "^5.4", - "symfony/routing": "^5.4", - "symfony/var-dumper": "^5.4", + "symfony/console": "^6.0", + "symfony/error-handler": "^6.0", + "symfony/finder": "^6.0", + "symfony/http-foundation": "^6.0", + "symfony/http-kernel": "^6.0", + "symfony/mailer": "^6.0", + "symfony/mime": "^6.0", + "symfony/process": "^6.0", + "symfony/routing": "^6.0", + "symfony/var-dumper": "^6.0", "tijsverkoyen/css-to-inline-styles": "^2.2.2", "vlucas/phpdotenv": "^5.4.1", - "voku/portable-ascii": "^1.6.1" + "voku/portable-ascii": "^2.0" }, "conflict": { "tightenco/collect": "<5.5.33" }, "provide": { - "psr/container-implementation": "1.0", - "psr/simple-cache-implementation": "1.0" + "psr/container-implementation": "1.1|2.0", + "psr/simple-cache-implementation": "1.0|2.0|3.0" }, "replace": { "illuminate/auth": "self.version", @@ -1828,6 +1911,7 @@ "illuminate/bus": "self.version", "illuminate/cache": "self.version", "illuminate/collections": "self.version", + "illuminate/conditionable": "self.version", "illuminate/config": "self.version", "illuminate/console": "self.version", "illuminate/container": "self.version", @@ -1858,19 +1942,22 @@ "require-dev": { "aws/aws-sdk-php": "^3.198.1", "doctrine/dbal": "^2.13.3|^3.1.4", - "filp/whoops": "^2.14.3", - "guzzlehttp/guzzle": "^6.5.5|^7.0.1", - "league/flysystem-cached-adapter": "^1.0", + "fakerphp/faker": "^1.9.2", + "guzzlehttp/guzzle": "^7.2", + "league/flysystem-aws-s3-v3": "^3.0", + "league/flysystem-ftp": "^3.0", + "league/flysystem-sftp-v3": "^3.0", "mockery/mockery": "^1.4.4", - "orchestra/testbench-core": "^6.27", + "orchestra/testbench-core": "^7.1", "pda/pheanstalk": "^4.0", - "phpunit/phpunit": "^8.5.19|^9.5.8", + "phpstan/phpstan": "^1.4.7", + "phpunit/phpunit": "^9.5.8", "predis/predis": "^1.1.9", - "symfony/cache": "^5.4" + "symfony/cache": "^6.0" }, "suggest": { "ably/ably-php": "Required to use the Ably broadcast driver (^1.0).", - "aws/aws-sdk-php": "Required to use the SQS queue driver, DynamoDb failed job storage and SES mail driver (^3.198.1).", + "aws/aws-sdk-php": "Required to use the SQS queue driver, DynamoDb failed job storage, and SES mail driver (^3.198.1).", "brianium/paratest": "Required to run tests in parallel (^6.0).", "doctrine/dbal": "Required to rename columns and drop SQLite columns (^2.13.3|^3.1.4).", "ext-bcmath": "Required to use the multiple_of validation rule.", @@ -1882,27 +1969,29 @@ "ext-redis": "Required to use the Redis cache and queue drivers (^4.0|^5.0).", "fakerphp/faker": "Required to use the eloquent factory builder (^1.9.1).", "filp/whoops": "Required for friendly error pages in development (^2.14.3).", - "guzzlehttp/guzzle": "Required to use the HTTP Client, Mailgun mail driver and the ping methods on schedules (^6.5.5|^7.0.1).", + "guzzlehttp/guzzle": "Required to use the HTTP Client and the ping methods on schedules (^7.2).", "laravel/tinker": "Required to use the tinker console command (^2.0).", - "league/flysystem-aws-s3-v3": "Required to use the Flysystem S3 driver (^1.0).", - "league/flysystem-cached-adapter": "Required to use the Flysystem cache (^1.0).", - "league/flysystem-sftp": "Required to use the Flysystem SFTP driver (^1.0).", + "league/flysystem-aws-s3-v3": "Required to use the Flysystem S3 driver (^3.0).", + "league/flysystem-ftp": "Required to use the Flysystem FTP driver (^3.0).", + "league/flysystem-sftp-v3": "Required to use the Flysystem SFTP driver (^3.0).", "mockery/mockery": "Required to use mocking (^1.4.4).", "nyholm/psr7": "Required to use PSR-7 bridging features (^1.2).", "pda/pheanstalk": "Required to use the beanstalk queue driver (^4.0).", - "phpunit/phpunit": "Required to use assertions and run tests (^8.5.19|^9.5.8).", + "phpunit/phpunit": "Required to use assertions and run tests (^9.5.8).", "predis/predis": "Required to use the predis connector (^1.1.9).", "psr/http-message": "Required to allow Storage::put to accept a StreamInterface (^1.0).", - "pusher/pusher-php-server": "Required to use the Pusher broadcast driver (^4.0|^5.0|^6.0|^7.0).", - "symfony/cache": "Required to PSR-6 cache bridge (^5.4).", - "symfony/filesystem": "Required to enable support for relative symbolic links (^5.4).", - "symfony/psr-http-message-bridge": "Required to use PSR-7 bridging features (^2.0).", - "wildbit/swiftmailer-postmark": "Required to use Postmark mail driver (^3.0)." + "pusher/pusher-php-server": "Required to use the Pusher broadcast driver (^6.0|^7.0).", + "symfony/cache": "Required to PSR-6 cache bridge (^6.0).", + "symfony/filesystem": "Required to enable support for relative symbolic links (^6.0).", + "symfony/http-client": "Required to enable support for the Symfony API mail transports (^6.0).", + "symfony/mailgun-mailer": "Required to enable support for the Mailgun mail transport (^6.0).", + "symfony/postmark-mailer": "Required to enable support for the Postmark mail transport (^6.0).", + "symfony/psr-http-message-bridge": "Required to use PSR-7 bridging features (^2.0)." }, "type": "library", "extra": { "branch-alias": { - "dev-master": "8.x-dev" + "dev-master": "9.x-dev" } }, "autoload": { @@ -1916,7 +2005,8 @@ "Illuminate\\": "src/Illuminate/", "Illuminate\\Support\\": [ "src/Illuminate/Macroable/", - "src/Illuminate/Collections/" + "src/Illuminate/Collections/", + "src/Illuminate/Conditionable/" ] } }, @@ -1940,34 +2030,34 @@ "issues": "https://github.com/laravel/framework/issues", "source": "https://github.com/laravel/framework" }, - "time": "2022-02-22T15:10:17+00:00" + "time": "2022-03-29T14:41:26+00:00" }, { "name": "laravel/passport", - "version": "v10.3.2", + "version": "v10.3.3", "source": { "type": "git", "url": "https://github.com/laravel/passport.git", - "reference": "c56207e9a37c849da0164842a609a9f38747e95b" + "reference": "1039d8b4aa71c45dbea2f140b131cae8802237e7" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/passport/zipball/c56207e9a37c849da0164842a609a9f38747e95b", - "reference": "c56207e9a37c849da0164842a609a9f38747e95b", + "url": "https://api.github.com/repos/laravel/passport/zipball/1039d8b4aa71c45dbea2f140b131cae8802237e7", + "reference": "1039d8b4aa71c45dbea2f140b131cae8802237e7", "shasum": "" }, "require": { "ext-json": "*", "firebase/php-jwt": "^5.0", - "illuminate/auth": "^8.2|^9.0", - "illuminate/console": "^8.2|^9.0", - "illuminate/container": "^8.2|^9.0", - "illuminate/contracts": "^8.2|^9.0", - "illuminate/cookie": "^8.2|^9.0", - "illuminate/database": "^8.2|^9.0", - "illuminate/encryption": "^8.2|^9.0", - "illuminate/http": "^8.2|^9.0", - "illuminate/support": "^8.2|^9.0", + "illuminate/auth": "^8.37|^9.0", + "illuminate/console": "^8.37|^9.0", + "illuminate/container": "^8.37|^9.0", + "illuminate/contracts": "^8.37|^9.0", + "illuminate/cookie": "^8.37|^9.0", + "illuminate/database": "^8.37|^9.0", + "illuminate/encryption": "^8.37|^9.0", + "illuminate/http": "^8.37|^9.0", + "illuminate/support": "^8.37|^9.0", "lcobucci/jwt": "^3.4|^4.0", "league/oauth2-server": "^8.2", "nyholm/psr7": "^1.3", @@ -2017,24 +2107,25 @@ "issues": "https://github.com/laravel/passport/issues", "source": "https://github.com/laravel/passport" }, - "time": "2022-02-15T21:44:15+00:00" + "time": "2022-02-23T15:04:04+00:00" }, { "name": "laravel/sanctum", - "version": "v2.14.2", + "version": "v2.15.0", "source": { "type": "git", "url": "https://github.com/laravel/sanctum.git", - "reference": "dc5d749ba9bfcfd68d8f5c272238f88bea223e66" + "reference": "5be160413b6f37dcf8758663edeab12d0e806f56" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laravel/sanctum/zipball/dc5d749ba9bfcfd68d8f5c272238f88bea223e66", - "reference": "dc5d749ba9bfcfd68d8f5c272238f88bea223e66", + "url": "https://api.github.com/repos/laravel/sanctum/zipball/5be160413b6f37dcf8758663edeab12d0e806f56", + "reference": "5be160413b6f37dcf8758663edeab12d0e806f56", "shasum": "" }, "require": { "ext-json": "*", + "illuminate/console": "^6.9|^7.0|^8.0|^9.0", "illuminate/contracts": "^6.9|^7.0|^8.0|^9.0", "illuminate/database": "^6.9|^7.0|^8.0|^9.0", "illuminate/support": "^6.9|^7.0|^8.0|^9.0", @@ -2081,7 +2172,7 @@ "issues": "https://github.com/laravel/sanctum/issues", "source": "https://github.com/laravel/sanctum" }, - "time": "2022-02-16T14:40:23+00:00" + "time": "2022-03-28T13:53:05+00:00" }, { "name": "laravel/serializable-closure", @@ -2735,54 +2826,48 @@ }, { "name": "league/flysystem", - "version": "1.1.9", + "version": "3.0.13", "source": { "type": "git", "url": "https://github.com/thephpleague/flysystem.git", - "reference": "094defdb4a7001845300334e7c1ee2335925ef99" + "reference": "15dc1ccb2db8daef507c4d3e501565bae42a9f0e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/thephpleague/flysystem/zipball/094defdb4a7001845300334e7c1ee2335925ef99", - "reference": "094defdb4a7001845300334e7c1ee2335925ef99", + "url": "https://api.github.com/repos/thephpleague/flysystem/zipball/15dc1ccb2db8daef507c4d3e501565bae42a9f0e", + "reference": "15dc1ccb2db8daef507c4d3e501565bae42a9f0e", "shasum": "" }, "require": { - "ext-fileinfo": "*", - "league/mime-type-detection": "^1.3", - "php": "^7.2.5 || ^8.0" + "league/mime-type-detection": "^1.0.0", + "php": "^8.0.2" }, "conflict": { - "league/flysystem-sftp": "<1.0.6" + "aws/aws-sdk-php": "3.209.31 || 3.210.0", + "guzzlehttp/guzzle": "<7.0", + "guzzlehttp/ringphp": "<1.1.1", + "symfony/http-client": "<5.2" }, "require-dev": { - "phpspec/prophecy": "^1.11.1", - "phpunit/phpunit": "^8.5.8" - }, - "suggest": { - "ext-ftp": "Allows you to use FTP server storage", - "ext-openssl": "Allows you to use FTPS server storage", - "league/flysystem-aws-s3-v2": "Allows you to use S3 storage with AWS SDK v2", - "league/flysystem-aws-s3-v3": "Allows you to use S3 storage with AWS SDK v3", - "league/flysystem-azure": "Allows you to use Windows Azure Blob storage", - "league/flysystem-cached-adapter": "Flysystem adapter decorator for metadata caching", - "league/flysystem-eventable-filesystem": "Allows you to use EventableFilesystem", - "league/flysystem-rackspace": "Allows you to use Rackspace Cloud Files", - "league/flysystem-sftp": "Allows you to use SFTP server storage via phpseclib", - "league/flysystem-webdav": "Allows you to use WebDAV storage", - "league/flysystem-ziparchive": "Allows you to use ZipArchive adapter", - "spatie/flysystem-dropbox": "Allows you to use Dropbox storage", - "srmklive/flysystem-dropbox-v2": "Allows you to use Dropbox storage for PHP 5 applications" + "async-aws/s3": "^1.5", + "async-aws/simple-s3": "^1.0", + "aws/aws-sdk-php": "^3.198.1", + "composer/semver": "^3.0", + "ext-fileinfo": "*", + "ext-ftp": "*", + "ext-zip": "*", + "friendsofphp/php-cs-fixer": "^3.5", + "google/cloud-storage": "^1.23", + "microsoft/azure-storage-blob": "^1.1", + "phpseclib/phpseclib": "^2.0", + "phpstan/phpstan": "^0.12.26", + "phpunit/phpunit": "^9.5.11", + "sabre/dav": "^4.3.1" }, "type": "library", - "extra": { - "branch-alias": { - "dev-master": "1.1-dev" - } - }, "autoload": { "psr-4": { - "League\\Flysystem\\": "src/" + "League\\Flysystem\\": "src" } }, "notification-url": "https://packagist.org/downloads/", @@ -2792,65 +2877,67 @@ "authors": [ { "name": "Frank de Jonge", - "email": "info@frenky.net" + "email": "info@frankdejonge.nl" } ], - "description": "Filesystem abstraction: Many filesystems, one API.", + "description": "File storage abstraction for PHP", "keywords": [ - "Cloud Files", "WebDAV", - "abstraction", "aws", "cloud", - "copy.com", - "dropbox", - "file systems", + "file", "files", "filesystem", "filesystems", "ftp", - "rackspace", - "remote", "s3", "sftp", "storage" ], "support": { "issues": "https://github.com/thephpleague/flysystem/issues", - "source": "https://github.com/thephpleague/flysystem/tree/1.1.9" + "source": "https://github.com/thephpleague/flysystem/tree/3.0.13" }, "funding": [ { "url": "https://offset.earth/frankdejonge", - "type": "other" + "type": "custom" + }, + { + "url": "https://github.com/frankdejonge", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/league/flysystem", + "type": "tidelift" } ], - "time": "2021-12-09T09:40:50+00:00" + "time": "2022-04-02T08:55:13+00:00" }, { "name": "league/fractal", - "version": "0.19.2", + "version": "0.20", "source": { "type": "git", "url": "https://github.com/thephpleague/fractal.git", - "reference": "06dc15f6ba38f2dde2f919d3095d13b571190a7c" + "reference": "419b0cbf5c23a06886a583c2fc0530db2360a70f" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/thephpleague/fractal/zipball/06dc15f6ba38f2dde2f919d3095d13b571190a7c", - "reference": "06dc15f6ba38f2dde2f919d3095d13b571190a7c", + "url": "https://api.github.com/repos/thephpleague/fractal/zipball/419b0cbf5c23a06886a583c2fc0530db2360a70f", + "reference": "419b0cbf5c23a06886a583c2fc0530db2360a70f", "shasum": "" }, "require": { - "php": ">=5.4" + "php": ">=7.4" }, "require-dev": { "doctrine/orm": "^2.5", "illuminate/contracts": "~5.0", - "mockery/mockery": "~0.9", + "mockery/mockery": "^1.3", "pagerfanta/pagerfanta": "~1.0.0", - "phpunit/phpunit": "^4.8.35 || ^7.5", - "squizlabs/php_codesniffer": "~1.5|~2.0|~3.4", + "phpunit/phpunit": "^9.5", + "squizlabs/php_codesniffer": "~3.4", "zendframework/zend-paginator": "~2.3" }, "suggest": { @@ -2861,7 +2948,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "0.13-dev" + "dev-master": "0.20.x-dev" } }, "autoload": { @@ -2891,9 +2978,9 @@ ], "support": { "issues": "https://github.com/thephpleague/fractal/issues", - "source": "https://github.com/thephpleague/fractal/tree/0.19.2" + "source": "https://github.com/thephpleague/fractal/tree/0.20" }, - "time": "2020-01-24T23:17:29+00:00" + "time": "2022-03-07T23:12:17+00:00" }, { "name": "league/mime-type-detection", @@ -3040,16 +3127,16 @@ }, { "name": "monolog/monolog", - "version": "2.3.5", + "version": "2.4.0", "source": { "type": "git", "url": "https://github.com/Seldaek/monolog.git", - "reference": "fd4380d6fc37626e2f799f29d91195040137eba9" + "reference": "d7fd7450628561ba697b7097d86db72662f54aef" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Seldaek/monolog/zipball/fd4380d6fc37626e2f799f29d91195040137eba9", - "reference": "fd4380d6fc37626e2f799f29d91195040137eba9", + "url": "https://api.github.com/repos/Seldaek/monolog/zipball/d7fd7450628561ba697b7097d86db72662f54aef", + "reference": "d7fd7450628561ba697b7097d86db72662f54aef", "shasum": "" }, "require": { @@ -3071,7 +3158,7 @@ "phpstan/phpstan": "^0.12.91", "phpunit/phpunit": "^8.5", "predis/predis": "^1.1", - "rollbar/rollbar": "^1.3", + "rollbar/rollbar": "^1.3 || ^2 || ^3", "ruflin/elastica": ">=0.90@dev", "swiftmailer/swiftmailer": "^5.3|^6.0" }, @@ -3123,7 +3210,7 @@ ], "support": { "issues": "https://github.com/Seldaek/monolog/issues", - "source": "https://github.com/Seldaek/monolog/tree/2.3.5" + "source": "https://github.com/Seldaek/monolog/tree/2.4.0" }, "funding": [ { @@ -3135,7 +3222,7 @@ "type": "tidelift" } ], - "time": "2021-10-01T21:08:31+00:00" + "time": "2022-03-14T12:44:37+00:00" }, { "name": "nesbot/carbon", @@ -3380,6 +3467,93 @@ }, "time": "2022-01-24T11:29:14+00:00" }, + { + "name": "nunomaduro/collision", + "version": "v6.1.0", + "source": { + "type": "git", + "url": "https://github.com/nunomaduro/collision.git", + "reference": "df09e21a5e5d5a7d51a8b9ecd44d3dd150d97fec" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nunomaduro/collision/zipball/df09e21a5e5d5a7d51a8b9ecd44d3dd150d97fec", + "reference": "df09e21a5e5d5a7d51a8b9ecd44d3dd150d97fec", + "shasum": "" + }, + "require": { + "facade/ignition-contracts": "^1.0.2", + "filp/whoops": "^2.14.5", + "php": "^8.0.0", + "symfony/console": "^6.0.2" + }, + "require-dev": { + "brianium/paratest": "^6.4.1", + "laravel/framework": "^9.0", + "nunomaduro/larastan": "^1.0.2", + "nunomaduro/mock-final-classes": "^1.1.0", + "orchestra/testbench": "^7.0.0", + "phpunit/phpunit": "^9.5.11" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-develop": "6.x-dev" + }, + "laravel": { + "providers": [ + "NunoMaduro\\Collision\\Adapters\\Laravel\\CollisionServiceProvider" + ] + } + }, + "autoload": { + "psr-4": { + "NunoMaduro\\Collision\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nuno Maduro", + "email": "enunomaduro@gmail.com" + } + ], + "description": "Cli error handling for console/command-line PHP applications.", + "keywords": [ + "artisan", + "cli", + "command-line", + "console", + "error", + "handling", + "laravel", + "laravel-zero", + "php", + "symfony" + ], + "support": { + "issues": "https://github.com/nunomaduro/collision/issues", + "source": "https://github.com/nunomaduro/collision" + }, + "funding": [ + { + "url": "https://www.paypal.com/paypalme/enunomaduro", + "type": "custom" + }, + { + "url": "https://github.com/nunomaduro", + "type": "github" + }, + { + "url": "https://www.patreon.com/nunomaduro", + "type": "patreon" + } + ], + "time": "2022-01-18T17:49:08+00:00" + }, { "name": "nyholm/psr7", "version": "1.5.0", @@ -3457,71 +3631,6 @@ ], "time": "2022-02-02T18:37:57+00:00" }, - { - "name": "opis/closure", - "version": "3.6.3", - "source": { - "type": "git", - "url": "https://github.com/opis/closure.git", - "reference": "3d81e4309d2a927abbe66df935f4bb60082805ad" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/opis/closure/zipball/3d81e4309d2a927abbe66df935f4bb60082805ad", - "reference": "3d81e4309d2a927abbe66df935f4bb60082805ad", - "shasum": "" - }, - "require": { - "php": "^5.4 || ^7.0 || ^8.0" - }, - "require-dev": { - "jeremeamia/superclosure": "^2.0", - "phpunit/phpunit": "^4.0 || ^5.0 || ^6.0 || ^7.0 || ^8.0 || ^9.0" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "3.6.x-dev" - } - }, - "autoload": { - "files": [ - "functions.php" - ], - "psr-4": { - "Opis\\Closure\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Marius Sarca", - "email": "marius.sarca@gmail.com" - }, - { - "name": "Sorin Sarca", - "email": "sarca_sorin@hotmail.com" - } - ], - "description": "A library that can be used to serialize closures (anonymous functions) and arbitrary objects.", - "homepage": "https://opis.io/closure", - "keywords": [ - "anonymous functions", - "closure", - "function", - "serializable", - "serialization", - "serialize" - ], - "support": { - "issues": "https://github.com/opis/closure/issues", - "source": "https://github.com/opis/closure/tree/3.6.3" - }, - "time": "2022-01-27T09:35:39+00:00" - }, { "name": "paragonie/constant_time_encoding", "version": "v2.5.0", @@ -4173,22 +4282,27 @@ }, { "name": "psr/container", - "version": "1.1.2", + "version": "2.0.2", "source": { "type": "git", "url": "https://github.com/php-fig/container.git", - "reference": "513e0666f7216c7459170d56df27dfcefe1689ea" + "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/php-fig/container/zipball/513e0666f7216c7459170d56df27dfcefe1689ea", - "reference": "513e0666f7216c7459170d56df27dfcefe1689ea", + "url": "https://api.github.com/repos/php-fig/container/zipball/c71ecc56dfe541dbd90c5360474fbc405f8d5963", + "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963", "shasum": "" }, "require": { "php": ">=7.4.0" }, "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, "autoload": { "psr-4": { "Psr\\Container\\": "src/" @@ -4215,9 +4329,9 @@ ], "support": { "issues": "https://github.com/php-fig/container/issues", - "source": "https://github.com/php-fig/container/tree/1.1.2" + "source": "https://github.com/php-fig/container/tree/2.0.2" }, - "time": "2021-11-05T16:50:12+00:00" + "time": "2021-11-05T16:47:00+00:00" }, { "name": "psr/event-dispatcher", @@ -4481,25 +4595,25 @@ }, { "name": "psr/simple-cache", - "version": "1.0.1", + "version": "3.0.0", "source": { "type": "git", "url": "https://github.com/php-fig/simple-cache.git", - "reference": "408d5eafb83c57f6365a3ca330ff23aa4a5fa39b" + "reference": "764e0b3939f5ca87cb904f570ef9be2d78a07865" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/php-fig/simple-cache/zipball/408d5eafb83c57f6365a3ca330ff23aa4a5fa39b", - "reference": "408d5eafb83c57f6365a3ca330ff23aa4a5fa39b", + "url": "https://api.github.com/repos/php-fig/simple-cache/zipball/764e0b3939f5ca87cb904f570ef9be2d78a07865", + "reference": "764e0b3939f5ca87cb904f570ef9be2d78a07865", "shasum": "" }, "require": { - "php": ">=5.3.0" + "php": ">=8.0.0" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.0.x-dev" + "dev-master": "3.0.x-dev" } }, "autoload": { @@ -4514,7 +4628,7 @@ "authors": [ { "name": "PHP-FIG", - "homepage": "http://www.php-fig.org/" + "homepage": "https://www.php-fig.org/" } ], "description": "Common interfaces for simple caching", @@ -4526,9 +4640,9 @@ "simple-cache" ], "support": { - "source": "https://github.com/php-fig/simple-cache/tree/master" + "source": "https://github.com/php-fig/simple-cache/tree/3.0.0" }, - "time": "2017-10-23T01:57:42+00:00" + "time": "2021-10-29T13:26:27+00:00" }, { "name": "ralouphie/getallheaders", @@ -4655,25 +4769,24 @@ }, { "name": "ramsey/uuid", - "version": "4.2.3", + "version": "4.3.1", "source": { "type": "git", "url": "https://github.com/ramsey/uuid.git", - "reference": "fc9bb7fb5388691fd7373cd44dcb4d63bbcf24df" + "reference": "8505afd4fea63b81a85d3b7b53ac3cb8dc347c28" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/ramsey/uuid/zipball/fc9bb7fb5388691fd7373cd44dcb4d63bbcf24df", - "reference": "fc9bb7fb5388691fd7373cd44dcb4d63bbcf24df", + "url": "https://api.github.com/repos/ramsey/uuid/zipball/8505afd4fea63b81a85d3b7b53ac3cb8dc347c28", + "reference": "8505afd4fea63b81a85d3b7b53ac3cb8dc347c28", "shasum": "" }, "require": { "brick/math": "^0.8 || ^0.9", + "ext-ctype": "*", "ext-json": "*", - "php": "^7.2 || ^8.0", - "ramsey/collection": "^1.0", - "symfony/polyfill-ctype": "^1.8", - "symfony/polyfill-php80": "^1.14" + "php": "^8.0", + "ramsey/collection": "^1.0" }, "replace": { "rhumsaa/uuid": "self.version" @@ -4710,20 +4823,17 @@ }, "type": "library", "extra": { - "branch-alias": { - "dev-main": "4.x-dev" - }, "captainhook": { "force-install": true } }, "autoload": { - "psr-4": { - "Ramsey\\Uuid\\": "src/" - }, "files": [ "src/functions.php" - ] + ], + "psr-4": { + "Ramsey\\Uuid\\": "src/" + } }, "notification-url": "https://packagist.org/downloads/", "license": [ @@ -4737,7 +4847,7 @@ ], "support": { "issues": "https://github.com/ramsey/uuid/issues", - "source": "https://github.com/ramsey/uuid/tree/4.2.3" + "source": "https://github.com/ramsey/uuid/tree/4.3.1" }, "funding": [ { @@ -4749,20 +4859,20 @@ "type": "tidelift" } ], - "time": "2021-09-25T23:10:38+00:00" + "time": "2022-03-27T21:42:02+00:00" }, { "name": "rcrowe/twigbridge", - "version": "v0.13.1", + "version": "v0.14.0", "source": { "type": "git", "url": "https://github.com/rcrowe/TwigBridge.git", - "reference": "ea5b2e18caca6c341fb8ceff2ce8e4fddb77d0df" + "reference": "f4968efb99537cc1b37c5bf20280614aadc31825" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/rcrowe/TwigBridge/zipball/ea5b2e18caca6c341fb8ceff2ce8e4fddb77d0df", - "reference": "ea5b2e18caca6c341fb8ceff2ce8e4fddb77d0df", + "url": "https://api.github.com/repos/rcrowe/TwigBridge/zipball/f4968efb99537cc1b37c5bf20280614aadc31825", + "reference": "f4968efb99537cc1b37c5bf20280614aadc31825", "shasum": "" }, "require": { @@ -4823,9 +4933,71 @@ ], "support": { "issues": "https://github.com/rcrowe/TwigBridge/issues", - "source": "https://github.com/rcrowe/TwigBridge/tree/v0.13.1" + "source": "https://github.com/rcrowe/TwigBridge/tree/v0.14.0" }, - "time": "2022-02-10T13:51:53+00:00" + "time": "2022-03-08T17:21:17+00:00" + }, + { + "name": "spatie/backtrace", + "version": "1.2.1", + "source": { + "type": "git", + "url": "https://github.com/spatie/backtrace.git", + "reference": "4ee7d41aa5268107906ea8a4d9ceccde136dbd5b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/spatie/backtrace/zipball/4ee7d41aa5268107906ea8a4d9ceccde136dbd5b", + "reference": "4ee7d41aa5268107906ea8a4d9ceccde136dbd5b", + "shasum": "" + }, + "require": { + "php": "^7.3|^8.0" + }, + "require-dev": { + "ext-json": "*", + "phpunit/phpunit": "^9.3", + "symfony/var-dumper": "^5.1" + }, + "type": "library", + "autoload": { + "psr-4": { + "Spatie\\Backtrace\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Freek Van de Herten", + "email": "freek@spatie.be", + "homepage": "https://spatie.be", + "role": "Developer" + } + ], + "description": "A better backtrace", + "homepage": "https://github.com/spatie/backtrace", + "keywords": [ + "Backtrace", + "spatie" + ], + "support": { + "issues": "https://github.com/spatie/backtrace/issues", + "source": "https://github.com/spatie/backtrace/tree/1.2.1" + }, + "funding": [ + { + "url": "https://github.com/sponsors/spatie", + "type": "github" + }, + { + "url": "https://spatie.be/open-source/support-us", + "type": "other" + } + ], + "time": "2021-11-09T10:57:15+00:00" }, { "name": "spatie/data-transfer-object", @@ -4891,43 +5063,105 @@ "time": "2021-12-30T20:31:10+00:00" }, { - "name": "swiftmailer/swiftmailer", - "version": "v6.3.0", + "name": "spatie/flare-client-php", + "version": "1.1.0", "source": { "type": "git", - "url": "https://github.com/swiftmailer/swiftmailer.git", - "reference": "8a5d5072dca8f48460fce2f4131fcc495eec654c" + "url": "https://github.com/spatie/flare-client-php.git", + "reference": "ceab058852a1278d9f57a7b95f1c348e4956d866" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/swiftmailer/swiftmailer/zipball/8a5d5072dca8f48460fce2f4131fcc495eec654c", - "reference": "8a5d5072dca8f48460fce2f4131fcc495eec654c", + "url": "https://api.github.com/repos/spatie/flare-client-php/zipball/ceab058852a1278d9f57a7b95f1c348e4956d866", + "reference": "ceab058852a1278d9f57a7b95f1c348e4956d866", "shasum": "" }, "require": { - "egulias/email-validator": "^2.0|^3.1", - "php": ">=7.0.0", - "symfony/polyfill-iconv": "^1.0", - "symfony/polyfill-intl-idn": "^1.10", - "symfony/polyfill-mbstring": "^1.0" + "illuminate/pipeline": "^8.0|^9.0", + "php": "^8.0", + "spatie/backtrace": "^1.2", + "symfony/http-foundation": "^5.0|^6.0", + "symfony/mime": "^5.2|^6.0", + "symfony/process": "^5.2|^6.0", + "symfony/var-dumper": "^5.2|^6.0" }, "require-dev": { - "mockery/mockery": "^1.0", - "symfony/phpunit-bridge": "^4.4|^5.4" - }, - "suggest": { - "ext-intl": "Needed to support internationalized email addresses" + "dms/phpunit-arraysubset-asserts": "^0.3.0", + "pestphp/pest": "^1.20", + "phpstan/extension-installer": "^1.1", + "phpstan/phpstan-deprecation-rules": "^1.0", + "phpstan/phpstan-phpunit": "^1.0", + "spatie/phpunit-snapshot-assertions": "^4.0" }, "type": "library", - "extra": { - "branch-alias": { - "dev-master": "6.2-dev" - } - }, "autoload": { "files": [ - "lib/swift_required.php" - ] + "src/helpers.php" + ], + "psr-4": { + "Spatie\\FlareClient\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Send PHP errors to Flare", + "homepage": "https://github.com/spatie/flare-client-php", + "keywords": [ + "exception", + "flare", + "reporting", + "spatie" + ], + "support": { + "issues": "https://github.com/spatie/flare-client-php/issues", + "source": "https://github.com/spatie/flare-client-php/tree/1.1.0" + }, + "funding": [ + { + "url": "https://github.com/spatie", + "type": "github" + } + ], + "time": "2022-03-11T13:21:28+00:00" + }, + { + "name": "spatie/ignition", + "version": "1.2.7", + "source": { + "type": "git", + "url": "https://github.com/spatie/ignition.git", + "reference": "2f059cf42b48f7c522efbba1c05ad59fc2c1a3f2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/spatie/ignition/zipball/2f059cf42b48f7c522efbba1c05ad59fc2c1a3f2", + "reference": "2f059cf42b48f7c522efbba1c05ad59fc2c1a3f2", + "shasum": "" + }, + "require": { + "ext-json": "*", + "ext-mbstring": "*", + "monolog/monolog": "^2.0", + "php": "^8.0", + "spatie/flare-client-php": "^1.1", + "symfony/console": "^5.4|^6.0", + "symfony/var-dumper": "^5.4|^6.0" + }, + "require-dev": { + "mockery/mockery": "^1.4", + "pestphp/pest": "^1.20", + "phpstan/extension-installer": "^1.1", + "phpstan/phpstan-deprecation-rules": "^1.0", + "phpstan/phpstan-phpunit": "^1.0", + "symfony/process": "^5.4|^6.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Spatie\\Ignition\\": "src" + } }, "notification-url": "https://packagist.org/downloads/", "license": [ @@ -4935,79 +5169,161 @@ ], "authors": [ { - "name": "Chris Corbyn" - }, - { - "name": "Fabien Potencier", - "email": "fabien@symfony.com" + "name": "Spatie", + "email": "info@spatie.be", + "role": "Developer" } ], - "description": "Swiftmailer, free feature-rich PHP mailer", - "homepage": "https://swiftmailer.symfony.com", + "description": "A beautiful error page for PHP applications.", + "homepage": "https://flareapp.io/ignition", "keywords": [ - "email", - "mail", - "mailer" + "error", + "flare", + "laravel", + "page" ], "support": { - "issues": "https://github.com/swiftmailer/swiftmailer/issues", - "source": "https://github.com/swiftmailer/swiftmailer/tree/v6.3.0" + "docs": "https://flareapp.io/docs/ignition-for-laravel/introduction", + "forum": "https://twitter.com/flareappio", + "issues": "https://github.com/spatie/ignition/issues", + "source": "https://github.com/spatie/ignition" }, "funding": [ { - "url": "https://github.com/fabpot", + "url": "https://github.com/spatie", "type": "github" - }, - { - "url": "https://tidelift.com/funding/github/packagist/swiftmailer/swiftmailer", - "type": "tidelift" } ], - "abandoned": "symfony/mailer", - "time": "2021-10-18T15:26:12+00:00" + "time": "2022-03-29T08:48:34+00:00" }, { - "name": "symfony/console", - "version": "v5.4.3", + "name": "spatie/laravel-ignition", + "version": "1.2.0", "source": { "type": "git", - "url": "https://github.com/symfony/console.git", - "reference": "a2a86ec353d825c75856c6fd14fac416a7bdb6b8" + "url": "https://github.com/spatie/laravel-ignition.git", + "reference": "2b54c8c66f2d280f25e15064ebe3d5e3eda19820" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/console/zipball/a2a86ec353d825c75856c6fd14fac416a7bdb6b8", - "reference": "a2a86ec353d825c75856c6fd14fac416a7bdb6b8", + "url": "https://api.github.com/repos/spatie/laravel-ignition/zipball/2b54c8c66f2d280f25e15064ebe3d5e3eda19820", + "reference": "2b54c8c66f2d280f25e15064ebe3d5e3eda19820", "shasum": "" }, "require": { - "php": ">=7.2.5", - "symfony/deprecation-contracts": "^2.1|^3", - "symfony/polyfill-mbstring": "~1.0", - "symfony/polyfill-php73": "^1.9", - "symfony/polyfill-php80": "^1.16", - "symfony/service-contracts": "^1.1|^2|^3", - "symfony/string": "^5.1|^6.0" - }, - "conflict": { - "psr/log": ">=3", - "symfony/dependency-injection": "<4.4", - "symfony/dotenv": "<5.1", - "symfony/event-dispatcher": "<4.4", - "symfony/lock": "<4.4", - "symfony/process": "<4.4" - }, - "provide": { - "psr/log-implementation": "1.0|2.0" + "ext-curl": "*", + "ext-json": "*", + "ext-mbstring": "*", + "illuminate/support": "^8.77|^9.0", + "monolog/monolog": "^2.3", + "php": "^8.0", + "spatie/flare-client-php": "^1.0.1", + "spatie/ignition": "^1.2.4", + "symfony/console": "^5.0|^6.0", + "symfony/var-dumper": "^5.0|^6.0" }, "require-dev": { - "psr/log": "^1|^2", - "symfony/config": "^4.4|^5.0|^6.0", - "symfony/dependency-injection": "^4.4|^5.0|^6.0", - "symfony/event-dispatcher": "^4.4|^5.0|^6.0", - "symfony/lock": "^4.4|^5.0|^6.0", - "symfony/process": "^4.4|^5.0|^6.0", - "symfony/var-dumper": "^4.4|^5.0|^6.0" + "filp/whoops": "^2.14", + "livewire/livewire": "^2.8|dev-develop", + "mockery/mockery": "^1.4", + "nunomaduro/larastan": "^1.0", + "orchestra/testbench": "^6.23|^7.0", + "pestphp/pest": "^1.20", + "phpstan/extension-installer": "^1.1", + "phpstan/phpstan-deprecation-rules": "^1.0", + "phpstan/phpstan-phpunit": "^1.0", + "spatie/laravel-ray": "^1.27" + }, + "type": "library", + "extra": { + "laravel": { + "providers": [ + "Spatie\\LaravelIgnition\\IgnitionServiceProvider" + ], + "aliases": { + "Flare": "Spatie\\LaravelIgnition\\Facades\\Flare" + } + } + }, + "autoload": { + "files": [ + "src/helpers.php" + ], + "psr-4": { + "Spatie\\LaravelIgnition\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Spatie", + "email": "info@spatie.be", + "role": "Developer" + } + ], + "description": "A beautiful error page for Laravel applications.", + "homepage": "https://flareapp.io/ignition", + "keywords": [ + "error", + "flare", + "laravel", + "page" + ], + "support": { + "docs": "https://flareapp.io/docs/ignition-for-laravel/introduction", + "forum": "https://twitter.com/flareappio", + "issues": "https://github.com/spatie/laravel-ignition/issues", + "source": "https://github.com/spatie/laravel-ignition" + }, + "funding": [ + { + "url": "https://github.com/spatie", + "type": "github" + } + ], + "time": "2022-04-01T21:01:58+00:00" + }, + { + "name": "symfony/console", + "version": "v6.0.7", + "source": { + "type": "git", + "url": "https://github.com/symfony/console.git", + "reference": "70dcf7b2ca2ea08ad6ebcc475f104a024fb5632e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/console/zipball/70dcf7b2ca2ea08ad6ebcc475f104a024fb5632e", + "reference": "70dcf7b2ca2ea08ad6ebcc475f104a024fb5632e", + "shasum": "" + }, + "require": { + "php": ">=8.0.2", + "symfony/polyfill-mbstring": "~1.0", + "symfony/service-contracts": "^1.1|^2|^3", + "symfony/string": "^5.4|^6.0" + }, + "conflict": { + "symfony/dependency-injection": "<5.4", + "symfony/dotenv": "<5.4", + "symfony/event-dispatcher": "<5.4", + "symfony/lock": "<5.4", + "symfony/process": "<5.4" + }, + "provide": { + "psr/log-implementation": "1.0|2.0|3.0" + }, + "require-dev": { + "psr/log": "^1|^2|^3", + "symfony/config": "^5.4|^6.0", + "symfony/dependency-injection": "^5.4|^6.0", + "symfony/event-dispatcher": "^5.4|^6.0", + "symfony/lock": "^5.4|^6.0", + "symfony/process": "^5.4|^6.0", + "symfony/var-dumper": "^5.4|^6.0" }, "suggest": { "psr/log": "For using the console logger", @@ -5047,7 +5363,7 @@ "terminal" ], "support": { - "source": "https://github.com/symfony/console/tree/v5.4.3" + "source": "https://github.com/symfony/console/tree/v6.0.7" }, "funding": [ { @@ -5063,7 +5379,7 @@ "type": "tidelift" } ], - "time": "2022-01-26T16:28:35+00:00" + "time": "2022-03-31T17:18:25+00:00" }, { "name": "symfony/css-selector", @@ -5199,27 +5515,27 @@ }, { "name": "symfony/error-handler", - "version": "v5.4.3", + "version": "v6.0.7", "source": { "type": "git", "url": "https://github.com/symfony/error-handler.git", - "reference": "c4ffc2cd919950d13c8c9ce32a70c70214c3ffc5" + "reference": "e600c54e5b30555eecea3ffe4314e58f832e78ee" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/error-handler/zipball/c4ffc2cd919950d13c8c9ce32a70c70214c3ffc5", - "reference": "c4ffc2cd919950d13c8c9ce32a70c70214c3ffc5", + "url": "https://api.github.com/repos/symfony/error-handler/zipball/e600c54e5b30555eecea3ffe4314e58f832e78ee", + "reference": "e600c54e5b30555eecea3ffe4314e58f832e78ee", "shasum": "" }, "require": { - "php": ">=7.2.5", + "php": ">=8.0.2", "psr/log": "^1|^2|^3", - "symfony/var-dumper": "^4.4|^5.0|^6.0" + "symfony/var-dumper": "^5.4|^6.0" }, "require-dev": { "symfony/deprecation-contracts": "^2.1|^3", - "symfony/http-kernel": "^4.4|^5.0|^6.0", - "symfony/serializer": "^4.4|^5.0|^6.0" + "symfony/http-kernel": "^5.4|^6.0", + "symfony/serializer": "^5.4|^6.0" }, "bin": [ "Resources/bin/patch-type-declarations" @@ -5250,7 +5566,7 @@ "description": "Provides tools to manage errors and ease debugging PHP code", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/error-handler/tree/v5.4.3" + "source": "https://github.com/symfony/error-handler/tree/v6.0.7" }, "funding": [ { @@ -5266,7 +5582,7 @@ "type": "tidelift" } ], - "time": "2022-01-02T09:53:40+00:00" + "time": "2022-03-18T16:21:55+00:00" }, { "name": "symfony/event-dispatcher", @@ -5432,22 +5748,20 @@ }, { "name": "symfony/finder", - "version": "v5.4.3", + "version": "v6.0.3", "source": { "type": "git", "url": "https://github.com/symfony/finder.git", - "reference": "231313534dded84c7ecaa79d14bc5da4ccb69b7d" + "reference": "8661b74dbabc23223f38c9b99d3f8ade71170430" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/finder/zipball/231313534dded84c7ecaa79d14bc5da4ccb69b7d", - "reference": "231313534dded84c7ecaa79d14bc5da4ccb69b7d", + "url": "https://api.github.com/repos/symfony/finder/zipball/8661b74dbabc23223f38c9b99d3f8ade71170430", + "reference": "8661b74dbabc23223f38c9b99d3f8ade71170430", "shasum": "" }, "require": { - "php": ">=7.2.5", - "symfony/deprecation-contracts": "^2.1|^3", - "symfony/polyfill-php80": "^1.16" + "php": ">=8.0.2" }, "type": "library", "autoload": { @@ -5475,7 +5789,7 @@ "description": "Finds files and directories via an intuitive fluent interface", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/finder/tree/v5.4.3" + "source": "https://github.com/symfony/finder/tree/v6.0.3" }, "funding": [ { @@ -5491,33 +5805,194 @@ "type": "tidelift" } ], - "time": "2022-01-26T16:34:36+00:00" + "time": "2022-01-26T17:23:29+00:00" }, { - "name": "symfony/http-foundation", - "version": "v5.4.3", + "name": "symfony/http-client", + "version": "v6.0.7", "source": { "type": "git", - "url": "https://github.com/symfony/http-foundation.git", - "reference": "ef409ff341a565a3663157d4324536746d49a0c7" + "url": "https://github.com/symfony/http-client.git", + "reference": "a7930c47248b9b57e9d0b8da100ffc1e031536dc" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/http-foundation/zipball/ef409ff341a565a3663157d4324536746d49a0c7", - "reference": "ef409ff341a565a3663157d4324536746d49a0c7", + "url": "https://api.github.com/repos/symfony/http-client/zipball/a7930c47248b9b57e9d0b8da100ffc1e031536dc", + "reference": "a7930c47248b9b57e9d0b8da100ffc1e031536dc", "shasum": "" }, "require": { - "php": ">=7.2.5", + "php": ">=8.0.2", + "psr/log": "^1|^2|^3", + "symfony/http-client-contracts": "^3", + "symfony/service-contracts": "^1.0|^2|^3" + }, + "provide": { + "php-http/async-client-implementation": "*", + "php-http/client-implementation": "*", + "psr/http-client-implementation": "1.0", + "symfony/http-client-implementation": "3.0" + }, + "require-dev": { + "amphp/amp": "^2.5", + "amphp/http-client": "^4.2.1", + "amphp/http-tunnel": "^1.0", + "amphp/socket": "^1.1", + "guzzlehttp/promises": "^1.4", + "nyholm/psr7": "^1.0", + "php-http/httplug": "^1.0|^2.0", + "psr/http-client": "^1.0", + "symfony/dependency-injection": "^5.4|^6.0", + "symfony/http-kernel": "^5.4|^6.0", + "symfony/process": "^5.4|^6.0", + "symfony/stopwatch": "^5.4|^6.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\HttpClient\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Provides powerful methods to fetch HTTP resources synchronously or asynchronously", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/http-client/tree/v6.0.7" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2022-04-01T12:27:43+00:00" + }, + { + "name": "symfony/http-client-contracts", + "version": "v3.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/http-client-contracts.git", + "reference": "265f03fed057044a8e4dc159aa33596d0f48ed3f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/http-client-contracts/zipball/265f03fed057044a8e4dc159aa33596d0f48ed3f", + "reference": "265f03fed057044a8e4dc159aa33596d0f48ed3f", + "shasum": "" + }, + "require": { + "php": ">=8.0.2" + }, + "suggest": { + "symfony/http-client-implementation": "" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.0-dev" + }, + "thanks": { + "name": "symfony/contracts", + "url": "https://github.com/symfony/contracts" + } + }, + "autoload": { + "psr-4": { + "Symfony\\Contracts\\HttpClient\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Generic abstractions related to HTTP clients", + "homepage": "https://symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "support": { + "source": "https://github.com/symfony/http-client-contracts/tree/v3.0.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2021-11-03T13:44:55+00:00" + }, + { + "name": "symfony/http-foundation", + "version": "v6.0.7", + "source": { + "type": "git", + "url": "https://github.com/symfony/http-foundation.git", + "reference": "c816b26f03b6902dba79b352c84a17f53d815f0d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/http-foundation/zipball/c816b26f03b6902dba79b352c84a17f53d815f0d", + "reference": "c816b26f03b6902dba79b352c84a17f53d815f0d", + "shasum": "" + }, + "require": { + "php": ">=8.0.2", "symfony/deprecation-contracts": "^2.1|^3", - "symfony/polyfill-mbstring": "~1.1", - "symfony/polyfill-php80": "^1.16" + "symfony/polyfill-mbstring": "~1.1" }, "require-dev": { "predis/predis": "~1.0", - "symfony/cache": "^4.4|^5.0|^6.0", - "symfony/expression-language": "^4.4|^5.0|^6.0", - "symfony/mime": "^4.4|^5.0|^6.0" + "symfony/cache": "^5.4|^6.0", + "symfony/expression-language": "^5.4|^6.0", + "symfony/mime": "^5.4|^6.0" }, "suggest": { "symfony/mime": "To use the file extension guesser" @@ -5548,7 +6023,7 @@ "description": "Defines an object-oriented layer for the HTTP specification", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/http-foundation/tree/v5.4.3" + "source": "https://github.com/symfony/http-foundation/tree/v6.0.7" }, "funding": [ { @@ -5564,67 +6039,64 @@ "type": "tidelift" } ], - "time": "2022-01-02T09:53:40+00:00" + "time": "2022-03-24T14:13:59+00:00" }, { "name": "symfony/http-kernel", - "version": "v5.4.4", + "version": "v6.0.7", "source": { "type": "git", "url": "https://github.com/symfony/http-kernel.git", - "reference": "49f40347228c773688a0488feea0175aa7f4d268" + "reference": "9c03dab07a6aa336ffaadc15352b1d14f4ce01f5" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/http-kernel/zipball/49f40347228c773688a0488feea0175aa7f4d268", - "reference": "49f40347228c773688a0488feea0175aa7f4d268", + "url": "https://api.github.com/repos/symfony/http-kernel/zipball/9c03dab07a6aa336ffaadc15352b1d14f4ce01f5", + "reference": "9c03dab07a6aa336ffaadc15352b1d14f4ce01f5", "shasum": "" }, "require": { - "php": ">=7.2.5", - "psr/log": "^1|^2", - "symfony/deprecation-contracts": "^2.1|^3", - "symfony/error-handler": "^4.4|^5.0|^6.0", - "symfony/event-dispatcher": "^5.0|^6.0", - "symfony/http-foundation": "^5.3.7|^6.0", - "symfony/polyfill-ctype": "^1.8", - "symfony/polyfill-php73": "^1.9", - "symfony/polyfill-php80": "^1.16" + "php": ">=8.0.2", + "psr/log": "^1|^2|^3", + "symfony/error-handler": "^5.4|^6.0", + "symfony/event-dispatcher": "^5.4|^6.0", + "symfony/http-foundation": "^5.4|^6.0", + "symfony/polyfill-ctype": "^1.8" }, "conflict": { "symfony/browser-kit": "<5.4", - "symfony/cache": "<5.0", - "symfony/config": "<5.0", - "symfony/console": "<4.4", - "symfony/dependency-injection": "<5.3", - "symfony/doctrine-bridge": "<5.0", - "symfony/form": "<5.0", - "symfony/http-client": "<5.0", - "symfony/mailer": "<5.0", - "symfony/messenger": "<5.0", - "symfony/translation": "<5.0", - "symfony/twig-bridge": "<5.0", - "symfony/validator": "<5.0", + "symfony/cache": "<5.4", + "symfony/config": "<5.4", + "symfony/console": "<5.4", + "symfony/dependency-injection": "<5.4", + "symfony/doctrine-bridge": "<5.4", + "symfony/form": "<5.4", + "symfony/http-client": "<5.4", + "symfony/mailer": "<5.4", + "symfony/messenger": "<5.4", + "symfony/translation": "<5.4", + "symfony/twig-bridge": "<5.4", + "symfony/validator": "<5.4", "twig/twig": "<2.13" }, "provide": { - "psr/log-implementation": "1.0|2.0" + "psr/log-implementation": "1.0|2.0|3.0" }, "require-dev": { "psr/cache": "^1.0|^2.0|^3.0", "symfony/browser-kit": "^5.4|^6.0", - "symfony/config": "^5.0|^6.0", - "symfony/console": "^4.4|^5.0|^6.0", - "symfony/css-selector": "^4.4|^5.0|^6.0", - "symfony/dependency-injection": "^5.3|^6.0", - "symfony/dom-crawler": "^4.4|^5.0|^6.0", - "symfony/expression-language": "^4.4|^5.0|^6.0", - "symfony/finder": "^4.4|^5.0|^6.0", + "symfony/config": "^5.4|^6.0", + "symfony/console": "^5.4|^6.0", + "symfony/css-selector": "^5.4|^6.0", + "symfony/dependency-injection": "^5.4|^6.0", + "symfony/dom-crawler": "^5.4|^6.0", + "symfony/expression-language": "^5.4|^6.0", + "symfony/finder": "^5.4|^6.0", "symfony/http-client-contracts": "^1.1|^2|^3", - "symfony/process": "^4.4|^5.0|^6.0", - "symfony/routing": "^4.4|^5.0|^6.0", - "symfony/stopwatch": "^4.4|^5.0|^6.0", - "symfony/translation": "^4.4|^5.0|^6.0", + "symfony/process": "^5.4|^6.0", + "symfony/routing": "^5.4|^6.0", + "symfony/stopwatch": "^5.4|^6.0", + "symfony/translation": "^5.4|^6.0", "symfony/translation-contracts": "^1.1|^2|^3", "twig/twig": "^2.13|^3.0.4" }, @@ -5660,7 +6132,7 @@ "description": "Provides a structured process for converting a Request into a Response", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/http-kernel/tree/v5.4.4" + "source": "https://github.com/symfony/http-kernel/tree/v6.0.7" }, "funding": [ { @@ -5676,42 +6148,179 @@ "type": "tidelift" } ], - "time": "2022-01-29T18:08:07+00:00" + "time": "2022-04-02T06:35:11+00:00" }, { - "name": "symfony/mime", - "version": "v5.4.3", + "name": "symfony/mailer", + "version": "v6.0.7", "source": { "type": "git", - "url": "https://github.com/symfony/mime.git", - "reference": "e1503cfb5c9a225350f549d3bb99296f4abfb80f" + "url": "https://github.com/symfony/mailer.git", + "reference": "f7343f94e7afecca2ad840b078f9d80200e1bd27" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/mime/zipball/e1503cfb5c9a225350f549d3bb99296f4abfb80f", - "reference": "e1503cfb5c9a225350f549d3bb99296f4abfb80f", + "url": "https://api.github.com/repos/symfony/mailer/zipball/f7343f94e7afecca2ad840b078f9d80200e1bd27", + "reference": "f7343f94e7afecca2ad840b078f9d80200e1bd27", "shasum": "" }, "require": { - "php": ">=7.2.5", - "symfony/deprecation-contracts": "^2.1|^3", + "egulias/email-validator": "^2.1.10|^3", + "php": ">=8.0.2", + "psr/event-dispatcher": "^1", + "psr/log": "^1|^2|^3", + "symfony/event-dispatcher": "^5.4|^6.0", + "symfony/mime": "^5.4|^6.0", + "symfony/service-contracts": "^1.1|^2|^3" + }, + "conflict": { + "symfony/http-kernel": "<5.4" + }, + "require-dev": { + "symfony/http-client-contracts": "^1.1|^2|^3", + "symfony/messenger": "^5.4|^6.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Mailer\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Helps sending emails", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/mailer/tree/v6.0.7" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2022-03-18T16:06:28+00:00" + }, + { + "name": "symfony/mailgun-mailer", + "version": "v6.0.7", + "source": { + "type": "git", + "url": "https://github.com/symfony/mailgun-mailer.git", + "reference": "f0d032c26683b26f4bc26864e09b1e08fa55226e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/mailgun-mailer/zipball/f0d032c26683b26f4bc26864e09b1e08fa55226e", + "reference": "f0d032c26683b26f4bc26864e09b1e08fa55226e", + "shasum": "" + }, + "require": { + "php": ">=8.0.2", + "symfony/mailer": "^5.4|^6.0" + }, + "require-dev": { + "symfony/http-client": "^5.4|^6.0" + }, + "type": "symfony-mailer-bridge", + "autoload": { + "psr-4": { + "Symfony\\Component\\Mailer\\Bridge\\Mailgun\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony Mailgun Mailer Bridge", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/mailgun-mailer/tree/v6.0.7" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2022-03-24T17:11:42+00:00" + }, + { + "name": "symfony/mime", + "version": "v6.0.7", + "source": { + "type": "git", + "url": "https://github.com/symfony/mime.git", + "reference": "74266e396f812a2301536397a6360b6e6913c0d8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/mime/zipball/74266e396f812a2301536397a6360b6e6913c0d8", + "reference": "74266e396f812a2301536397a6360b6e6913c0d8", + "shasum": "" + }, + "require": { + "php": ">=8.0.2", "symfony/polyfill-intl-idn": "^1.10", - "symfony/polyfill-mbstring": "^1.0", - "symfony/polyfill-php80": "^1.16" + "symfony/polyfill-mbstring": "^1.0" }, "conflict": { "egulias/email-validator": "~3.0.0", "phpdocumentor/reflection-docblock": "<3.2.2", "phpdocumentor/type-resolver": "<1.4.0", - "symfony/mailer": "<4.4" + "symfony/mailer": "<5.4" }, "require-dev": { "egulias/email-validator": "^2.1.10|^3.1", "phpdocumentor/reflection-docblock": "^3.0|^4.0|^5.0", - "symfony/dependency-injection": "^4.4|^5.0|^6.0", - "symfony/property-access": "^4.4|^5.1|^6.0", - "symfony/property-info": "^4.4|^5.1|^6.0", - "symfony/serializer": "^5.2|^6.0" + "symfony/dependency-injection": "^5.4|^6.0", + "symfony/property-access": "^5.4|^6.0", + "symfony/property-info": "^5.4|^6.0", + "symfony/serializer": "^5.4|^6.0" }, "type": "library", "autoload": { @@ -5743,7 +6352,7 @@ "mime-type" ], "support": { - "source": "https://github.com/symfony/mime/tree/v5.4.3" + "source": "https://github.com/symfony/mime/tree/v6.0.7" }, "funding": [ { @@ -5759,11 +6368,11 @@ "type": "tidelift" } ], - "time": "2022-01-02T09:53:40+00:00" + "time": "2022-03-13T20:10:05+00:00" }, { "name": "symfony/polyfill-ctype", - "version": "v1.24.0", + "version": "v1.25.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-ctype.git", @@ -5825,7 +6434,7 @@ "portable" ], "support": { - "source": "https://github.com/symfony/polyfill-ctype/tree/v1.24.0" + "source": "https://github.com/symfony/polyfill-ctype/tree/v1.25.0" }, "funding": [ { @@ -5843,92 +6452,9 @@ ], "time": "2021-10-20T20:35:02+00:00" }, - { - "name": "symfony/polyfill-iconv", - "version": "v1.24.0", - "source": { - "type": "git", - "url": "https://github.com/symfony/polyfill-iconv.git", - "reference": "f1aed619e28cb077fc83fac8c4c0383578356e40" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-iconv/zipball/f1aed619e28cb077fc83fac8c4c0383578356e40", - "reference": "f1aed619e28cb077fc83fac8c4c0383578356e40", - "shasum": "" - }, - "require": { - "php": ">=7.1" - }, - "provide": { - "ext-iconv": "*" - }, - "suggest": { - "ext-iconv": "For best performance" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-main": "1.23-dev" - }, - "thanks": { - "name": "symfony/polyfill", - "url": "https://github.com/symfony/polyfill" - } - }, - "autoload": { - "files": [ - "bootstrap.php" - ], - "psr-4": { - "Symfony\\Polyfill\\Iconv\\": "" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Nicolas Grekas", - "email": "p@tchwork.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "Symfony polyfill for the Iconv extension", - "homepage": "https://symfony.com", - "keywords": [ - "compatibility", - "iconv", - "polyfill", - "portable", - "shim" - ], - "support": { - "source": "https://github.com/symfony/polyfill-iconv/tree/v1.24.0" - }, - "funding": [ - { - "url": "https://symfony.com/sponsor", - "type": "custom" - }, - { - "url": "https://github.com/fabpot", - "type": "github" - }, - { - "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", - "type": "tidelift" - } - ], - "time": "2022-01-04T09:04:05+00:00" - }, { "name": "symfony/polyfill-intl-grapheme", - "version": "v1.24.0", + "version": "v1.25.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-intl-grapheme.git", @@ -5989,7 +6515,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-intl-grapheme/tree/v1.24.0" + "source": "https://github.com/symfony/polyfill-intl-grapheme/tree/v1.25.0" }, "funding": [ { @@ -6009,7 +6535,7 @@ }, { "name": "symfony/polyfill-intl-idn", - "version": "v1.24.0", + "version": "v1.25.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-intl-idn.git", @@ -6076,7 +6602,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-intl-idn/tree/v1.24.0" + "source": "https://github.com/symfony/polyfill-intl-idn/tree/v1.25.0" }, "funding": [ { @@ -6096,7 +6622,7 @@ }, { "name": "symfony/polyfill-intl-normalizer", - "version": "v1.24.0", + "version": "v1.25.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-intl-normalizer.git", @@ -6160,7 +6686,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-intl-normalizer/tree/v1.24.0" + "source": "https://github.com/symfony/polyfill-intl-normalizer/tree/v1.25.0" }, "funding": [ { @@ -6180,7 +6706,7 @@ }, { "name": "symfony/polyfill-mbstring", - "version": "v1.24.0", + "version": "v1.25.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-mbstring.git", @@ -6243,7 +6769,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.24.0" + "source": "https://github.com/symfony/polyfill-mbstring/tree/v1.25.0" }, "funding": [ { @@ -6263,7 +6789,7 @@ }, { "name": "symfony/polyfill-php72", - "version": "v1.24.0", + "version": "v1.25.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-php72.git", @@ -6319,7 +6845,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-php72/tree/v1.24.0" + "source": "https://github.com/symfony/polyfill-php72/tree/v1.25.0" }, "funding": [ { @@ -6337,97 +6863,18 @@ ], "time": "2021-05-27T09:17:38+00:00" }, - { - "name": "symfony/polyfill-php73", - "version": "v1.24.0", - "source": { - "type": "git", - "url": "https://github.com/symfony/polyfill-php73.git", - "reference": "cc5db0e22b3cb4111010e48785a97f670b350ca5" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php73/zipball/cc5db0e22b3cb4111010e48785a97f670b350ca5", - "reference": "cc5db0e22b3cb4111010e48785a97f670b350ca5", - "shasum": "" - }, - "require": { - "php": ">=7.1" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-main": "1.23-dev" - }, - "thanks": { - "name": "symfony/polyfill", - "url": "https://github.com/symfony/polyfill" - } - }, - "autoload": { - "files": [ - "bootstrap.php" - ], - "psr-4": { - "Symfony\\Polyfill\\Php73\\": "" - }, - "classmap": [ - "Resources/stubs" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Nicolas Grekas", - "email": "p@tchwork.com" - }, - { - "name": "Symfony Community", - "homepage": "https://symfony.com/contributors" - } - ], - "description": "Symfony polyfill backporting some PHP 7.3+ features to lower PHP versions", - "homepage": "https://symfony.com", - "keywords": [ - "compatibility", - "polyfill", - "portable", - "shim" - ], - "support": { - "source": "https://github.com/symfony/polyfill-php73/tree/v1.24.0" - }, - "funding": [ - { - "url": "https://symfony.com/sponsor", - "type": "custom" - }, - { - "url": "https://github.com/fabpot", - "type": "github" - }, - { - "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", - "type": "tidelift" - } - ], - "time": "2021-06-05T21:20:04+00:00" - }, { "name": "symfony/polyfill-php80", - "version": "v1.24.0", + "version": "v1.25.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-php80.git", - "reference": "57b712b08eddb97c762a8caa32c84e037892d2e9" + "reference": "4407588e0d3f1f52efb65fbe92babe41f37fe50c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/57b712b08eddb97c762a8caa32c84e037892d2e9", - "reference": "57b712b08eddb97c762a8caa32c84e037892d2e9", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/4407588e0d3f1f52efb65fbe92babe41f37fe50c", + "reference": "4407588e0d3f1f52efb65fbe92babe41f37fe50c", "shasum": "" }, "require": { @@ -6481,7 +6928,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-php80/tree/v1.24.0" + "source": "https://github.com/symfony/polyfill-php80/tree/v1.25.0" }, "funding": [ { @@ -6497,11 +6944,11 @@ "type": "tidelift" } ], - "time": "2021-09-13T13:58:33+00:00" + "time": "2022-03-04T08:16:47+00:00" }, { "name": "symfony/polyfill-php81", - "version": "v1.24.0", + "version": "v1.25.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-php81.git", @@ -6560,7 +7007,7 @@ "shim" ], "support": { - "source": "https://github.com/symfony/polyfill-php81/tree/v1.24.0" + "source": "https://github.com/symfony/polyfill-php81/tree/v1.25.0" }, "funding": [ { @@ -6580,21 +7027,20 @@ }, { "name": "symfony/process", - "version": "v5.4.3", + "version": "v6.0.7", "source": { "type": "git", "url": "https://github.com/symfony/process.git", - "reference": "553f50487389a977eb31cf6b37faae56da00f753" + "reference": "e13f6757e267d687e20ec5b26ccfcbbe511cd8f4" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/process/zipball/553f50487389a977eb31cf6b37faae56da00f753", - "reference": "553f50487389a977eb31cf6b37faae56da00f753", + "url": "https://api.github.com/repos/symfony/process/zipball/e13f6757e267d687e20ec5b26ccfcbbe511cd8f4", + "reference": "e13f6757e267d687e20ec5b26ccfcbbe511cd8f4", "shasum": "" }, "require": { - "php": ">=7.2.5", - "symfony/polyfill-php80": "^1.16" + "php": ">=8.0.2" }, "type": "library", "autoload": { @@ -6622,7 +7068,7 @@ "description": "Executes commands in sub-processes", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/process/tree/v5.4.3" + "source": "https://github.com/symfony/process/tree/v6.0.7" }, "funding": [ { @@ -6638,7 +7084,7 @@ "type": "tidelift" } ], - "time": "2022-01-26T16:28:35+00:00" + "time": "2022-03-18T16:21:55+00:00" }, { "name": "symfony/psr-http-message-bridge", @@ -6730,37 +7176,35 @@ }, { "name": "symfony/routing", - "version": "v5.4.3", + "version": "v6.0.5", "source": { "type": "git", "url": "https://github.com/symfony/routing.git", - "reference": "44b29c7a94e867ccde1da604792f11a469958981" + "reference": "a738b152426ac7fcb94bdab8188264652238bef1" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/routing/zipball/44b29c7a94e867ccde1da604792f11a469958981", - "reference": "44b29c7a94e867ccde1da604792f11a469958981", + "url": "https://api.github.com/repos/symfony/routing/zipball/a738b152426ac7fcb94bdab8188264652238bef1", + "reference": "a738b152426ac7fcb94bdab8188264652238bef1", "shasum": "" }, "require": { - "php": ">=7.2.5", - "symfony/deprecation-contracts": "^2.1|^3", - "symfony/polyfill-php80": "^1.16" + "php": ">=8.0.2" }, "conflict": { "doctrine/annotations": "<1.12", - "symfony/config": "<5.3", - "symfony/dependency-injection": "<4.4", - "symfony/yaml": "<4.4" + "symfony/config": "<5.4", + "symfony/dependency-injection": "<5.4", + "symfony/yaml": "<5.4" }, "require-dev": { "doctrine/annotations": "^1.12", "psr/log": "^1|^2|^3", - "symfony/config": "^5.3|^6.0", - "symfony/dependency-injection": "^4.4|^5.0|^6.0", - "symfony/expression-language": "^4.4|^5.0|^6.0", - "symfony/http-foundation": "^4.4|^5.0|^6.0", - "symfony/yaml": "^4.4|^5.0|^6.0" + "symfony/config": "^5.4|^6.0", + "symfony/dependency-injection": "^5.4|^6.0", + "symfony/expression-language": "^5.4|^6.0", + "symfony/http-foundation": "^5.4|^6.0", + "symfony/yaml": "^5.4|^6.0" }, "suggest": { "symfony/config": "For using the all-in-one router or any loader", @@ -6800,7 +7244,7 @@ "url" ], "support": { - "source": "https://github.com/symfony/routing/tree/v5.4.3" + "source": "https://github.com/symfony/routing/tree/v6.0.5" }, "funding": [ { @@ -6816,25 +7260,25 @@ "type": "tidelift" } ], - "time": "2022-01-02T09:53:40+00:00" + "time": "2022-01-31T19:46:53+00:00" }, { "name": "symfony/service-contracts", - "version": "v2.4.1", + "version": "v3.0.0", "source": { "type": "git", "url": "https://github.com/symfony/service-contracts.git", - "reference": "d664541b99d6fb0247ec5ff32e87238582236204" + "reference": "36715ebf9fb9db73db0cb24263c79077c6fe8603" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/service-contracts/zipball/d664541b99d6fb0247ec5ff32e87238582236204", - "reference": "d664541b99d6fb0247ec5ff32e87238582236204", + "url": "https://api.github.com/repos/symfony/service-contracts/zipball/36715ebf9fb9db73db0cb24263c79077c6fe8603", + "reference": "36715ebf9fb9db73db0cb24263c79077c6fe8603", "shasum": "" }, "require": { - "php": ">=7.2.5", - "psr/container": "^1.1" + "php": ">=8.0.2", + "psr/container": "^2.0" }, "conflict": { "ext-psr": "<1.1|>=2" @@ -6845,7 +7289,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-main": "2.4-dev" + "dev-main": "3.0-dev" }, "thanks": { "name": "symfony/contracts", @@ -6882,7 +7326,7 @@ "standards" ], "support": { - "source": "https://github.com/symfony/service-contracts/tree/v2.4.1" + "source": "https://github.com/symfony/service-contracts/tree/v3.0.0" }, "funding": [ { @@ -6898,7 +7342,7 @@ "type": "tidelift" } ], - "time": "2021-11-04T16:37:19+00:00" + "time": "2021-11-04T17:53:12+00:00" }, { "name": "symfony/string", @@ -6987,16 +7431,16 @@ }, { "name": "symfony/translation", - "version": "v6.0.3", + "version": "v6.0.7", "source": { "type": "git", "url": "https://github.com/symfony/translation.git", - "reference": "71bb15335798f8c4da110911bcf2d2fead7a430d" + "reference": "b2792b39d74cf41ea3065f27fd2ddf0b556ac7a1" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/translation/zipball/71bb15335798f8c4da110911bcf2d2fead7a430d", - "reference": "71bb15335798f8c4da110911bcf2d2fead7a430d", + "url": "https://api.github.com/repos/symfony/translation/zipball/b2792b39d74cf41ea3065f27fd2ddf0b556ac7a1", + "reference": "b2792b39d74cf41ea3065f27fd2ddf0b556ac7a1", "shasum": "" }, "require": { @@ -7062,7 +7506,7 @@ "description": "Provides tools to internationalize your application", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/translation/tree/v6.0.3" + "source": "https://github.com/symfony/translation/tree/v6.0.7" }, "funding": [ { @@ -7078,7 +7522,7 @@ "type": "tidelift" } ], - "time": "2022-01-07T00:29:03+00:00" + "time": "2022-03-31T17:18:25+00:00" }, { "name": "symfony/translation-contracts", @@ -7160,32 +7604,31 @@ }, { "name": "symfony/var-dumper", - "version": "v5.4.3", + "version": "v6.0.6", "source": { "type": "git", "url": "https://github.com/symfony/var-dumper.git", - "reference": "970a01f208bf895c5f327ba40b72288da43adec4" + "reference": "38358405ae948963c50a3aae3dfea598223ba15e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/var-dumper/zipball/970a01f208bf895c5f327ba40b72288da43adec4", - "reference": "970a01f208bf895c5f327ba40b72288da43adec4", + "url": "https://api.github.com/repos/symfony/var-dumper/zipball/38358405ae948963c50a3aae3dfea598223ba15e", + "reference": "38358405ae948963c50a3aae3dfea598223ba15e", "shasum": "" }, "require": { - "php": ">=7.2.5", - "symfony/polyfill-mbstring": "~1.0", - "symfony/polyfill-php80": "^1.16" + "php": ">=8.0.2", + "symfony/polyfill-mbstring": "~1.0" }, "conflict": { "phpunit/phpunit": "<5.4.3", - "symfony/console": "<4.4" + "symfony/console": "<5.4" }, "require-dev": { "ext-iconv": "*", - "symfony/console": "^4.4|^5.0|^6.0", - "symfony/process": "^4.4|^5.0|^6.0", - "symfony/uid": "^5.1|^6.0", + "symfony/console": "^5.4|^6.0", + "symfony/process": "^5.4|^6.0", + "symfony/uid": "^5.4|^6.0", "twig/twig": "^2.13|^3.0.4" }, "suggest": { @@ -7229,7 +7672,7 @@ "dump" ], "support": { - "source": "https://github.com/symfony/var-dumper/tree/v5.4.3" + "source": "https://github.com/symfony/var-dumper/tree/v6.0.6" }, "funding": [ { @@ -7245,7 +7688,7 @@ "type": "tidelift" } ], - "time": "2022-01-17T16:30:37+00:00" + "time": "2022-03-02T12:58:14+00:00" }, { "name": "tijsverkoyen/css-to-inline-styles", @@ -7302,16 +7745,16 @@ }, { "name": "twig/twig", - "version": "v3.3.8", + "version": "v3.3.9", "source": { "type": "git", "url": "https://github.com/twigphp/Twig.git", - "reference": "972d8604a92b7054828b539f2febb0211dd5945c" + "reference": "6ff9b0e440fa66f97f207e181c41340ddfa5683d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/twigphp/Twig/zipball/972d8604a92b7054828b539f2febb0211dd5945c", - "reference": "972d8604a92b7054828b539f2febb0211dd5945c", + "url": "https://api.github.com/repos/twigphp/Twig/zipball/6ff9b0e440fa66f97f207e181c41340ddfa5683d", + "reference": "6ff9b0e440fa66f97f207e181c41340ddfa5683d", "shasum": "" }, "require": { @@ -7362,7 +7805,7 @@ ], "support": { "issues": "https://github.com/twigphp/Twig/issues", - "source": "https://github.com/twigphp/Twig/tree/v3.3.8" + "source": "https://github.com/twigphp/Twig/tree/v3.3.9" }, "funding": [ { @@ -7374,7 +7817,7 @@ "type": "tidelift" } ], - "time": "2022-02-04T06:59:48+00:00" + "time": "2022-03-25T09:37:52+00:00" }, { "name": "vlucas/phpdotenv", @@ -7458,16 +7901,16 @@ }, { "name": "voku/portable-ascii", - "version": "1.6.1", + "version": "2.0.1", "source": { "type": "git", "url": "https://github.com/voku/portable-ascii.git", - "reference": "87337c91b9dfacee02452244ee14ab3c43bc485a" + "reference": "b56450eed252f6801410d810c8e1727224ae0743" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/voku/portable-ascii/zipball/87337c91b9dfacee02452244ee14ab3c43bc485a", - "reference": "87337c91b9dfacee02452244ee14ab3c43bc485a", + "url": "https://api.github.com/repos/voku/portable-ascii/zipball/b56450eed252f6801410d810c8e1727224ae0743", + "reference": "b56450eed252f6801410d810c8e1727224ae0743", "shasum": "" }, "require": { @@ -7504,7 +7947,7 @@ ], "support": { "issues": "https://github.com/voku/portable-ascii/issues", - "source": "https://github.com/voku/portable-ascii/tree/1.6.1" + "source": "https://github.com/voku/portable-ascii/tree/2.0.1" }, "funding": [ { @@ -7528,7 +7971,7 @@ "type": "tidelift" } ], - "time": "2022-01-24T18:55:24+00:00" + "time": "2022-03-08T17:03:00+00:00" }, { "name": "webmozart/assert", @@ -7677,21 +8120,21 @@ }, { "name": "barryvdh/laravel-ide-helper", - "version": "v2.12.2", + "version": "v2.12.3", "source": { "type": "git", "url": "https://github.com/barryvdh/laravel-ide-helper.git", - "reference": "7917cce7c991c7203545ea2e59a1dd366d1b60af" + "reference": "3ba1e2573b38f72107b8aacc4ee177fcab30a550" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/barryvdh/laravel-ide-helper/zipball/7917cce7c991c7203545ea2e59a1dd366d1b60af", - "reference": "7917cce7c991c7203545ea2e59a1dd366d1b60af", + "url": "https://api.github.com/repos/barryvdh/laravel-ide-helper/zipball/3ba1e2573b38f72107b8aacc4ee177fcab30a550", + "reference": "3ba1e2573b38f72107b8aacc4ee177fcab30a550", "shasum": "" }, "require": { "barryvdh/reflection-docblock": "^2.0.6", - "composer/pcre": "^1.0", + "composer/pcre": "^1 || ^2 || ^3", "doctrine/dbal": "^2.6 || ^3", "ext-json": "*", "illuminate/console": "^8 || ^9", @@ -7755,7 +8198,7 @@ ], "support": { "issues": "https://github.com/barryvdh/laravel-ide-helper/issues", - "source": "https://github.com/barryvdh/laravel-ide-helper/tree/v2.12.2" + "source": "https://github.com/barryvdh/laravel-ide-helper/tree/v2.12.3" }, "funding": [ { @@ -7767,7 +8210,7 @@ "type": "github" } ], - "time": "2022-02-08T19:30:33+00:00" + "time": "2022-03-06T14:33:42+00:00" }, { "name": "barryvdh/reflection-docblock", @@ -7823,30 +8266,30 @@ }, { "name": "composer/pcre", - "version": "1.0.1", + "version": "3.0.0", "source": { "type": "git", "url": "https://github.com/composer/pcre.git", - "reference": "67a32d7d6f9f560b726ab25a061b38ff3a80c560" + "reference": "e300eb6c535192decd27a85bc72a9290f0d6b3bd" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/composer/pcre/zipball/67a32d7d6f9f560b726ab25a061b38ff3a80c560", - "reference": "67a32d7d6f9f560b726ab25a061b38ff3a80c560", + "url": "https://api.github.com/repos/composer/pcre/zipball/e300eb6c535192decd27a85bc72a9290f0d6b3bd", + "reference": "e300eb6c535192decd27a85bc72a9290f0d6b3bd", "shasum": "" }, "require": { - "php": "^5.3.2 || ^7.0 || ^8.0" + "php": "^7.4 || ^8.0" }, "require-dev": { "phpstan/phpstan": "^1.3", "phpstan/phpstan-strict-rules": "^1.1", - "symfony/phpunit-bridge": "^4.2 || ^5" + "symfony/phpunit-bridge": "^5" }, "type": "library", "extra": { "branch-alias": { - "dev-main": "1.x-dev" + "dev-main": "3.x-dev" } }, "autoload": { @@ -7874,7 +8317,7 @@ ], "support": { "issues": "https://github.com/composer/pcre/issues", - "source": "https://github.com/composer/pcre/tree/1.0.1" + "source": "https://github.com/composer/pcre/tree/3.0.0" }, "funding": [ { @@ -7890,33 +8333,34 @@ "type": "tidelift" } ], - "time": "2022-01-21T20:24:37+00:00" + "time": "2022-02-25T20:21:48+00:00" }, { "name": "doctrine/instantiator", - "version": "1.4.0", + "version": "1.4.1", "source": { "type": "git", "url": "https://github.com/doctrine/instantiator.git", - "reference": "d56bf6102915de5702778fe20f2de3b2fe570b5b" + "reference": "10dcfce151b967d20fde1b34ae6640712c3891bc" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/doctrine/instantiator/zipball/d56bf6102915de5702778fe20f2de3b2fe570b5b", - "reference": "d56bf6102915de5702778fe20f2de3b2fe570b5b", + "url": "https://api.github.com/repos/doctrine/instantiator/zipball/10dcfce151b967d20fde1b34ae6640712c3891bc", + "reference": "10dcfce151b967d20fde1b34ae6640712c3891bc", "shasum": "" }, "require": { "php": "^7.1 || ^8.0" }, "require-dev": { - "doctrine/coding-standard": "^8.0", + "doctrine/coding-standard": "^9", "ext-pdo": "*", "ext-phar": "*", - "phpbench/phpbench": "^0.13 || 1.0.0-alpha2", - "phpstan/phpstan": "^0.12", - "phpstan/phpstan-phpunit": "^0.12", - "phpunit/phpunit": "^7.0 || ^8.0 || ^9.0" + "phpbench/phpbench": "^0.16 || ^1", + "phpstan/phpstan": "^1.4", + "phpstan/phpstan-phpunit": "^1", + "phpunit/phpunit": "^7.5 || ^8.5 || ^9.5", + "vimeo/psalm": "^4.22" }, "type": "library", "autoload": { @@ -7943,7 +8387,7 @@ ], "support": { "issues": "https://github.com/doctrine/instantiator/issues", - "source": "https://github.com/doctrine/instantiator/tree/1.4.0" + "source": "https://github.com/doctrine/instantiator/tree/1.4.1" }, "funding": [ { @@ -7959,7 +8403,7 @@ "type": "tidelift" } ], - "time": "2020-11-10T18:47:58+00:00" + "time": "2022-03-03T08:28:38+00:00" }, { "name": "fakerphp/faker", @@ -8028,77 +8472,6 @@ }, "time": "2022-02-02T17:38:57+00:00" }, - { - "name": "filp/whoops", - "version": "2.14.5", - "source": { - "type": "git", - "url": "https://github.com/filp/whoops.git", - "reference": "a63e5e8f26ebbebf8ed3c5c691637325512eb0dc" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/filp/whoops/zipball/a63e5e8f26ebbebf8ed3c5c691637325512eb0dc", - "reference": "a63e5e8f26ebbebf8ed3c5c691637325512eb0dc", - "shasum": "" - }, - "require": { - "php": "^5.5.9 || ^7.0 || ^8.0", - "psr/log": "^1.0.1 || ^2.0 || ^3.0" - }, - "require-dev": { - "mockery/mockery": "^0.9 || ^1.0", - "phpunit/phpunit": "^4.8.36 || ^5.7.27 || ^6.5.14 || ^7.5.20 || ^8.5.8 || ^9.3.3", - "symfony/var-dumper": "^2.6 || ^3.0 || ^4.0 || ^5.0" - }, - "suggest": { - "symfony/var-dumper": "Pretty print complex values better with var-dumper available", - "whoops/soap": "Formats errors as SOAP responses" - }, - "type": "library", - "extra": { - "branch-alias": { - "dev-master": "2.7-dev" - } - }, - "autoload": { - "psr-4": { - "Whoops\\": "src/Whoops/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Filipe Dobreira", - "homepage": "https://github.com/filp", - "role": "Developer" - } - ], - "description": "php error handling for cool kids", - "homepage": "https://filp.github.io/whoops/", - "keywords": [ - "error", - "exception", - "handling", - "library", - "throwable", - "whoops" - ], - "support": { - "issues": "https://github.com/filp/whoops/issues", - "source": "https://github.com/filp/whoops/tree/2.14.5" - }, - "funding": [ - { - "url": "https://github.com/denis-sokolov", - "type": "github" - } - ], - "time": "2022-01-07T12:00:00+00:00" - }, { "name": "hamcrest/hamcrest-php", "version": "v2.0.1", @@ -8290,25 +8663,29 @@ }, { "name": "myclabs/deep-copy", - "version": "1.10.2", + "version": "1.11.0", "source": { "type": "git", "url": "https://github.com/myclabs/DeepCopy.git", - "reference": "776f831124e9c62e1a2c601ecc52e776d8bb7220" + "reference": "14daed4296fae74d9e3201d2c4925d1acb7aa614" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/776f831124e9c62e1a2c601ecc52e776d8bb7220", - "reference": "776f831124e9c62e1a2c601ecc52e776d8bb7220", + "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/14daed4296fae74d9e3201d2c4925d1acb7aa614", + "reference": "14daed4296fae74d9e3201d2c4925d1acb7aa614", "shasum": "" }, "require": { "php": "^7.1 || ^8.0" }, + "conflict": { + "doctrine/collections": "<1.6.8", + "doctrine/common": "<2.13.3 || >=3,<3.2.2" + }, "require-dev": { - "doctrine/collections": "^1.0", - "doctrine/common": "^2.6", - "phpunit/phpunit": "^7.1" + "doctrine/collections": "^1.6.8", + "doctrine/common": "^2.13.3 || ^3.2.2", + "phpunit/phpunit": "^7.5.20 || ^8.5.23 || ^9.5.13" }, "type": "library", "autoload": { @@ -8333,7 +8710,7 @@ ], "support": { "issues": "https://github.com/myclabs/DeepCopy/issues", - "source": "https://github.com/myclabs/DeepCopy/tree/1.10.2" + "source": "https://github.com/myclabs/DeepCopy/tree/1.11.0" }, "funding": [ { @@ -8341,7 +8718,7 @@ "type": "tidelift" } ], - "time": "2020-11-13T09:40:50+00:00" + "time": "2022-03-03T13:19:32+00:00" }, { "name": "nikic/php-parser", @@ -8622,16 +8999,16 @@ }, { "name": "phpdocumentor/type-resolver", - "version": "1.6.0", + "version": "1.6.1", "source": { "type": "git", "url": "https://github.com/phpDocumentor/TypeResolver.git", - "reference": "93ebd0014cab80c4ea9f5e297ea48672f1b87706" + "reference": "77a32518733312af16a44300404e945338981de3" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/phpDocumentor/TypeResolver/zipball/93ebd0014cab80c4ea9f5e297ea48672f1b87706", - "reference": "93ebd0014cab80c4ea9f5e297ea48672f1b87706", + "url": "https://api.github.com/repos/phpDocumentor/TypeResolver/zipball/77a32518733312af16a44300404e945338981de3", + "reference": "77a32518733312af16a44300404e945338981de3", "shasum": "" }, "require": { @@ -8666,9 +9043,9 @@ "description": "A PSR-5 based resolver of Class names, Types and Structural Element Names", "support": { "issues": "https://github.com/phpDocumentor/TypeResolver/issues", - "source": "https://github.com/phpDocumentor/TypeResolver/tree/1.6.0" + "source": "https://github.com/phpDocumentor/TypeResolver/tree/1.6.1" }, - "time": "2022-01-04T19:58:01+00:00" + "time": "2022-03-15T21:29:03+00:00" }, { "name": "phpspec/prophecy", @@ -8739,16 +9116,16 @@ }, { "name": "phpunit/php-code-coverage", - "version": "9.2.13", + "version": "9.2.15", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/php-code-coverage.git", - "reference": "deac8540cb7bd40b2b8cfa679b76202834fd04e8" + "reference": "2e9da11878c4202f97915c1cb4bb1ca318a63f5f" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/deac8540cb7bd40b2b8cfa679b76202834fd04e8", - "reference": "deac8540cb7bd40b2b8cfa679b76202834fd04e8", + "url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/2e9da11878c4202f97915c1cb4bb1ca318a63f5f", + "reference": "2e9da11878c4202f97915c1cb4bb1ca318a63f5f", "shasum": "" }, "require": { @@ -8804,7 +9181,7 @@ ], "support": { "issues": "https://github.com/sebastianbergmann/php-code-coverage/issues", - "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/9.2.13" + "source": "https://github.com/sebastianbergmann/php-code-coverage/tree/9.2.15" }, "funding": [ { @@ -8812,7 +9189,7 @@ "type": "github" } ], - "time": "2022-02-23T17:02:38+00:00" + "time": "2022-03-07T09:28:20+00:00" }, { "name": "phpunit/php-file-iterator", @@ -9057,16 +9434,16 @@ }, { "name": "phpunit/phpunit", - "version": "9.5.16", + "version": "9.5.20", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/phpunit.git", - "reference": "5ff8c545a50226c569310a35f4fa89d79f1ddfdc" + "reference": "12bc8879fb65aef2138b26fc633cb1e3620cffba" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/5ff8c545a50226c569310a35f4fa89d79f1ddfdc", - "reference": "5ff8c545a50226c569310a35f4fa89d79f1ddfdc", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/12bc8879fb65aef2138b26fc633cb1e3620cffba", + "reference": "12bc8879fb65aef2138b26fc633cb1e3620cffba", "shasum": "" }, "require": { @@ -9096,7 +9473,7 @@ "sebastian/global-state": "^5.0.1", "sebastian/object-enumerator": "^4.0.3", "sebastian/resource-operations": "^3.0.3", - "sebastian/type": "^2.3.4", + "sebastian/type": "^3.0", "sebastian/version": "^3.0.2" }, "require-dev": { @@ -9144,7 +9521,7 @@ ], "support": { "issues": "https://github.com/sebastianbergmann/phpunit/issues", - "source": "https://github.com/sebastianbergmann/phpunit/tree/9.5.16" + "source": "https://github.com/sebastianbergmann/phpunit/tree/9.5.20" }, "funding": [ { @@ -9156,7 +9533,7 @@ "type": "github" } ], - "time": "2022-02-23T17:10:58+00:00" + "time": "2022-04-01T12:37:26+00:00" }, { "name": "sebastian/cli-parser", @@ -9524,16 +9901,16 @@ }, { "name": "sebastian/environment", - "version": "5.1.3", + "version": "5.1.4", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/environment.git", - "reference": "388b6ced16caa751030f6a69e588299fa09200ac" + "reference": "1b5dff7bb151a4db11d49d90e5408e4e938270f7" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/388b6ced16caa751030f6a69e588299fa09200ac", - "reference": "388b6ced16caa751030f6a69e588299fa09200ac", + "url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/1b5dff7bb151a4db11d49d90e5408e4e938270f7", + "reference": "1b5dff7bb151a4db11d49d90e5408e4e938270f7", "shasum": "" }, "require": { @@ -9575,7 +9952,7 @@ ], "support": { "issues": "https://github.com/sebastianbergmann/environment/issues", - "source": "https://github.com/sebastianbergmann/environment/tree/5.1.3" + "source": "https://github.com/sebastianbergmann/environment/tree/5.1.4" }, "funding": [ { @@ -9583,7 +9960,7 @@ "type": "github" } ], - "time": "2020-09-28T05:52:38+00:00" + "time": "2022-04-03T09:37:03+00:00" }, { "name": "sebastian/exporter", @@ -10015,28 +10392,28 @@ }, { "name": "sebastian/type", - "version": "2.3.4", + "version": "3.0.0", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/type.git", - "reference": "b8cd8a1c753c90bc1a0f5372170e3e489136f914" + "reference": "b233b84bc4465aff7b57cf1c4bc75c86d00d6dad" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/type/zipball/b8cd8a1c753c90bc1a0f5372170e3e489136f914", - "reference": "b8cd8a1c753c90bc1a0f5372170e3e489136f914", + "url": "https://api.github.com/repos/sebastianbergmann/type/zipball/b233b84bc4465aff7b57cf1c4bc75c86d00d6dad", + "reference": "b233b84bc4465aff7b57cf1c4bc75c86d00d6dad", "shasum": "" }, "require": { "php": ">=7.3" }, "require-dev": { - "phpunit/phpunit": "^9.3" + "phpunit/phpunit": "^9.5" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "2.3-dev" + "dev-master": "3.0-dev" } }, "autoload": { @@ -10059,7 +10436,7 @@ "homepage": "https://github.com/sebastianbergmann/type", "support": { "issues": "https://github.com/sebastianbergmann/type/issues", - "source": "https://github.com/sebastianbergmann/type/tree/2.3.4" + "source": "https://github.com/sebastianbergmann/type/tree/3.0.0" }, "funding": [ { @@ -10067,7 +10444,7 @@ "type": "github" } ], - "time": "2021-06-15T12:49:02+00:00" + "time": "2022-03-15T09:54:48+00:00" }, { "name": "sebastian/version", @@ -10251,7 +10628,6 @@ "ext-bcmath": "*", "ext-curl": "*", "ext-fileinfo": "*", - "ext-gd": "*", "ext-iconv": "*", "ext-intl": "*", "ext-json": "*", diff --git a/config/app.php b/config/app.php index b789433432..cd05e2bab3 100644 --- a/config/app.php +++ b/config/app.php @@ -144,9 +144,9 @@ return [ 'Google2FA' => PragmaRX\Google2FALaravel\Facade::class, 'Twig' => TwigBridge\Facade\Twig::class, - 'Arr' => Illuminate\Support\Arr::class, + 'Arr' => Illuminate\Support\Arr::class, 'Http' => Illuminate\Support\Facades\Http::class, - 'Str' => Illuminate\Support\Str::class, + 'Str' => Illuminate\Support\Str::class, ], 'asset_url' => env('ASSET_URL', null), diff --git a/config/auth.php b/config/auth.php index 974c68a8f6..92fad546f9 100644 --- a/config/auth.php +++ b/config/auth.php @@ -21,20 +21,8 @@ declare(strict_types=1); -use FireflyIII\Ldap\AttributeHandler; -use FireflyIII\Ldap\Rules\UserDefinedRule; - -# select ldap model based on configuration option -switch(env('LDAP_DIALECT')) { - case 'ActiveDirectory': - $ldapModel = class_exists(LdapRecord\Models\ActiveDirectory\User::class) ? LdapRecord\Models\ActiveDirectory\User::class : ''; - break; - case 'FreeIPA': - $ldapModel = class_exists(LdapRecord\Models\FreeIPA\User::class) ? LdapRecord\Models\FreeIPA\User::class : ''; - break; - default: - # default to openLDAP - $ldapModel = class_exists(LdapRecord\Models\OpenLDAP\User::class) ? LdapRecord\Models\OpenLDAP\User::class : ''; +if ('ldap' === strtolower((string) env('AUTHENTICATION_GUARD'))) { + die('LDAP is no longer supported by Firefly III v5.7+. Sorry about that. You will have to switch to "remote_user_guard", and use tools like Authelia or Keycloak to use LDAP together with Firefly III.'); } return [ @@ -78,10 +66,6 @@ return [ 'driver' => 'session', 'provider' => 'users', ], - 'ldap' => [ - 'driver' => 'session', - 'provider' => 'ldap', - ], 'remote_user_guard' => [ 'driver' => 'remote_user_guard', 'provider' => 'remote_user_provider', @@ -111,26 +95,13 @@ return [ 'providers' => [ 'users' => [ - 'driver' => 'eloquent', - 'model' => FireflyIII\User::class, + 'driver' => 'eloquent', + 'model' => FireflyIII\User::class, ], 'remote_user_provider' => [ 'driver' => 'remote_user_provider', 'model' => FireflyIII\User::class, ], - - 'ldap' => [ - 'driver' => 'ldap', - 'model' => $ldapModel, - 'rules' => [ - UserDefinedRule::class, - ], - 'database' => [ - 'model' => FireflyIII\User::class, - 'sync_passwords' => false, - 'sync_attributes' => AttributeHandler::class, - ], - ], ], /* diff --git a/config/breadcrumbs.php b/config/breadcrumbs.php index 73dbe7b8ae..0cfb2b1185 100644 --- a/config/breadcrumbs.php +++ b/config/breadcrumbs.php @@ -61,7 +61,7 @@ return [ | */ - 'files' => base_path('routes/breadcrumbs.php'), + 'files' => base_path('routes/breadcrumbs.php'), /* |-------------------------------------------------------------------------- @@ -73,13 +73,13 @@ return [ */ // When route-bound breadcrumbs are used but the current route doesn't have a name (UnnamedRouteException) - 'unnamed-route-exception' => true, + 'unnamed-route-exception' => true, // When route-bound breadcrumbs are used and the matching breadcrumb doesn't exist (InvalidBreadcrumbException) 'missing-route-bound-breadcrumb-exception' => true, // When a named breadcrumb is used but doesn't exist (InvalidBreadcrumbException) - 'invalid-named-breadcrumb-exception' => true, + 'invalid-named-breadcrumb-exception' => true, /* |-------------------------------------------------------------------------- @@ -91,9 +91,9 @@ return [ */ // Manager - 'manager-class' => Diglactic\Breadcrumbs\Manager::class, + 'manager-class' => Diglactic\Breadcrumbs\Manager::class, // Generator - 'generator-class' => Diglactic\Breadcrumbs\Generator::class, + 'generator-class' => Diglactic\Breadcrumbs\Generator::class, ]; diff --git a/config/bulk.php b/config/bulk.php index cf0458ee2d..8a92da4205 100644 --- a/config/bulk.php +++ b/config/bulk.php @@ -26,7 +26,7 @@ use FireflyIII\Enums\ClauseType; return [ ClauseType::TRANSACTION => [ - ClauseType::WHERE => [ + ClauseType::WHERE => [ 'source_account_id' => 'required|numeric|belongsToUser:accounts,id', ], ClauseType::UPDATE => [ diff --git a/config/cache.php b/config/cache.php index 9510722577..69ed690ca4 100644 --- a/config/cache.php +++ b/config/cache.php @@ -55,7 +55,7 @@ return [ ], 'array' => [ - 'driver' => 'array', + 'driver' => 'array', 'serialize' => false, ], @@ -89,16 +89,16 @@ return [ ], ], - 'redis' => [ + 'redis' => [ 'driver' => 'redis', 'connection' => 'default', ], 'dynamodb' => [ - 'driver' => 'dynamodb', - 'key' => env('AWS_ACCESS_KEY_ID'), - 'secret' => env('AWS_SECRET_ACCESS_KEY'), - 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), - 'table' => env('DYNAMODB_CACHE_TABLE', 'cache'), + 'driver' => 'dynamodb', + 'key' => env('AWS_ACCESS_KEY_ID'), + 'secret' => env('AWS_SECRET_ACCESS_KEY'), + 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), + 'table' => env('DYNAMODB_CACHE_TABLE', 'cache'), 'endpoint' => env('DYNAMODB_ENDPOINT'), ], ], diff --git a/config/database.php b/config/database.php index 3972ed7281..6d017ae602 100644 --- a/config/database.php +++ b/config/database.php @@ -50,7 +50,7 @@ $mysql_ssl_ciphers = envNonEmpty('MYSQL_SSL_CIPHER', null); $mysql_ssl_verify = envNonEmpty('MYSQL_SSL_VERIFY_SERVER_CERT', null); $mySqlSSLOptions = []; -$useSSL = envNonEmpty('MYSQL_USE_SSL', false); +$useSSL = envNonEmpty('MYSQL_USE_SSL', false); if (false !== $useSSL && null !== $useSSL) { if (null !== $mysql_ssl_ca_dir) { $mySqlSSLOptions[PDO::MYSQL_ATTR_SSL_CAPATH] = $mysql_ssl_ca_dir; @@ -75,7 +75,7 @@ if (false !== $useSSL && null !== $useSSL) { return [ 'default' => envNonEmpty('DB_CONNECTION', 'mysql'), 'connections' => [ - 'sqlite' => [ + 'sqlite' => [ 'driver' => 'sqlite', 'database' => envNonEmpty('DB_DATABASE', storage_path('database/database.sqlite')), 'prefix' => '', @@ -85,7 +85,7 @@ return [ 'database' => envNonEmpty('DB_DATABASE', storage_path('database/test_db.sqlite')), 'prefix' => '', ], - 'mysql' => [ + 'mysql' => [ 'driver' => 'mysql', 'host' => envNonEmpty('DB_HOST', $host), 'port' => envNonEmpty('DB_PORT', $port), @@ -100,7 +100,7 @@ return [ 'engine' => 'InnoDB', 'options' => $mySqlSSLOptions, ], - 'pgsql' => [ + 'pgsql' => [ 'driver' => 'pgsql', 'host' => envNonEmpty('DB_HOST', $host), 'port' => envNonEmpty('DB_PORT', $port), @@ -109,13 +109,13 @@ return [ 'password' => env('DB_PASSWORD', $password), 'charset' => 'utf8', 'prefix' => '', - 'schema' => envNonEmpty('PGSQL_SCHEMA', 'public'), + 'search_path' => envNonEmpty('PGSQL_SCHEMA', 'public'), 'sslmode' => envNonEmpty('PGSQL_SSL_MODE', 'prefer'), 'sslcert' => envNonEmpty('PGSQL_SSL_CERT'), 'sslkey' => envNonEmpty('PGSQL_SSL_KEY'), 'sslrootcert' => envNonEmpty('PGSQL_SSL_ROOT_CERT'), ], - 'sqlsrv' => [ + 'sqlsrv' => [ 'driver' => 'sqlsrv', 'host' => env('DB_HOST', 'localhost'), 'port' => env('DB_PORT', '1433'), diff --git a/config/filesystems.php b/config/filesystems.php index 10dbdfacbe..8deff7ba8f 100644 --- a/config/filesystems.php +++ b/config/filesystems.php @@ -33,21 +33,7 @@ return [ | */ - 'default' => env('FILESYSTEM_DRIVER', 'local'), - - /* - |-------------------------------------------------------------------------- - | Default Cloud Filesystem Disk - |-------------------------------------------------------------------------- - | - | Many applications store files both locally and in the cloud. For this - | reason, you may specify a default "cloud" driver here. This driver - | will be bound as the Cloud disk implementation in the container. - | - */ - - 'cloud' => env('FILESYSTEM_CLOUD', 's3'), - + 'default' => env('FILESYSTEM_DISK', 'local'), /* |-------------------------------------------------------------------------- | Filesystem Disks @@ -66,35 +52,35 @@ return [ */ 'disks' => [ - 'local' => [ + 'local' => [ 'driver' => 'local', 'root' => storage_path('app'), ], // local storage configuration for upload and export: - 'upload' => [ + 'upload' => [ 'driver' => 'local', 'root' => storage_path('upload'), ], - 'export' => [ + 'export' => [ 'driver' => 'local', 'root' => storage_path('export'), ], // various other paths: - 'database' => [ + 'database' => [ 'driver' => 'local', 'root' => storage_path('database'), ], - 'seeds' => [ + 'seeds' => [ 'driver' => 'local', 'root' => base_path('resources/seeds'), ], - 'stubs' => [ + 'stubs' => [ 'driver' => 'local', 'root' => base_path('resources/stubs'), ], - 'resources' => [ + 'resources' => [ 'driver' => 'local', 'root' => base_path('resources'), ], diff --git a/config/firefly.php b/config/firefly.php index 5bba14568b..41739d66e3 100644 --- a/config/firefly.php +++ b/config/firefly.php @@ -101,8 +101,8 @@ return [ 'webhooks' => false, 'handle_debts' => true, ], - 'version' => '5.6.16', - 'api_version' => '1.5.5', + 'version' => '5.7.0', + 'api_version' => '1.5.6', 'db_version' => 18, // generic settings @@ -133,11 +133,10 @@ return [ 'tracker_site_id' => env('TRACKER_SITE_ID', ''), 'tracker_url' => env('TRACKER_URL', ''), - // LDAP and authentication settings + // authentication settings 'login_provider' => envNonEmpty('LOGIN_PROVIDER', 'eloquent'), 'authentication_guard' => envNonEmpty('AUTHENTICATION_GUARD', 'web'), 'custom_logout_url' => envNonEmpty('CUSTOM_LOGOUT_URL', ''), - 'ldap_auth_field' => env('LDAP_AUTH_FIELD', env('ADLDAP_AUTH_FIELD', 'distinguishedname')), // static config (cannot be changed by user) 'update_endpoint' => 'https://version.firefly-iii.org/index.json', @@ -206,9 +205,9 @@ return [ 'language' => 'en_US', 'locale' => 'equal', ], - 'default_currency' => 'EUR', - 'default_language' => envNonEmpty('DEFAULT_LANGUAGE', 'en_US'), - 'default_locale' => envNonEmpty('DEFAULT_LOCALE', 'equal'), + 'default_currency' => 'EUR', + 'default_language' => envNonEmpty('DEFAULT_LANGUAGE', 'en_US'), + 'default_locale' => envNonEmpty('DEFAULT_LOCALE', 'equal'), // "value must be in this list" values 'valid_attachment_models' => [ @@ -222,7 +221,8 @@ return [ TransactionJournal::class, Recurrence::class, ], - 'valid_view_ranges' => ['1D', '1W', '1M', '3M', '6M', '1Y',], + 'bill_reminder_periods' => [90, 30, 14, 7, 0], + 'valid_view_ranges' => ['1D', '1W', '1M', '3M', '6M', '1Y',], 'allowedMimes' => [ /* plain files */ 'text/plain', @@ -391,7 +391,7 @@ return [ 'transfers' => 'fa-exchange', ], - 'bindables' => [ + 'bindables' => [ // models 'account' => Account::class, 'attachment' => Attachment::class, @@ -443,7 +443,7 @@ return [ 'eitherConfigKey' => EitherConfigKey::class, ], - 'rule-actions' => [ + 'rule-actions' => [ 'set_category' => SetCategory::class, 'clear_category' => ClearCategory::class, 'set_budget' => SetBudget::class, @@ -467,7 +467,7 @@ return [ 'update_piggy' => UpdatePiggybank::class, 'delete_transaction' => DeleteTransaction::class, ], - 'context-rule-actions' => [ + 'context-rule-actions' => [ 'set_category', 'set_budget', 'add_tag', @@ -486,181 +486,12 @@ return [ 'convert_transfer', ], - 'test-triggers' => [ + 'test-triggers' => [ 'limit' => 10, 'range' => 200, ], - 'search' => [ - 'operators' => [ - 'user_action' => ['alias' => false, 'needs_context' => true,], - 'description_starts' => ['alias' => false, 'needs_context' => true,], - 'description_ends' => ['alias' => false, 'needs_context' => true,], - 'description_contains' => ['alias' => false, 'needs_context' => true,], - 'description_is' => ['alias' => false, 'needs_context' => true,], - 'description' => ['alias' => true, 'alias_for' => 'description_contains', 'needs_context' => true,], - - 'currency_is' => ['alias' => false, 'needs_context' => true,], - 'foreign_currency_is' => ['alias' => false, 'needs_context' => true,], - - 'has_attachments' => ['alias' => false, 'needs_context' => false,], - 'has_no_category' => ['alias' => false, 'needs_context' => false,], - 'has_any_category' => ['alias' => false, 'needs_context' => false,], - 'has_no_budget' => ['alias' => false, 'needs_context' => false,], - 'has_any_budget' => ['alias' => false, 'needs_context' => false,], - 'has_no_bill' => ['alias' => false, 'needs_context' => false,], - 'has_any_bill' => ['alias' => false, 'needs_context' => false,], - 'has_no_tag' => ['alias' => false, 'needs_context' => false,], - 'has_any_tag' => ['alias' => false, 'needs_context' => false,], - 'notes_contain' => ['alias' => false, 'needs_context' => true,], - 'notes_start' => ['alias' => false, 'needs_context' => true,], - 'notes_end' => ['alias' => false, 'needs_context' => true,], - 'notes_are' => ['alias' => false, 'needs_context' => true,], - 'no_notes' => ['alias' => false, 'needs_context' => false,], - 'any_notes' => ['alias' => false, 'needs_context' => false,], - 'no_external_url' => ['alias' => false, 'needs_context' => false,], - 'any_external_url' => ['alias' => false, 'needs_context' => false,], - - // one exact (or array of) journals: - 'id' => ['alias' => false, 'trigger_class' => null, 'needs_context' => true,], - 'journal_id' => ['alias' => false, 'trigger_class' => null, 'needs_context' => true,], - - // exact amount - 'amount_exactly' => ['alias' => false, 'needs_context' => true,], - 'amount_is' => ['alias' => true, 'alias_for' => 'amount_exactly', 'needs_context' => true,], - 'amount' => ['alias' => true, 'alias_for' => 'amount_exactly', 'needs_context' => true,], - - // is less than - 'amount_less' => ['alias' => false, 'needs_context' => true,], - 'amount_max' => ['alias' => true, 'alias_for' => 'amount_less', 'needs_context' => true,], - - // is more than - 'amount_more' => ['alias' => false, 'needs_context' => true,], - 'amount_min' => ['alias' => true, 'alias_for' => 'amount_more', 'needs_context' => true,], - - // source account name is + alias: - 'source_account_is' => ['alias' => false, 'needs_context' => true,], - 'from_account_is' => ['alias' => true, 'alias_for' => 'source_account_is', 'needs_context' => true,], - - // source or dest is cash account? - 'source_is_cash' => ['alias' => false, 'needs_context' => false], - 'destination_is_cash' => ['alias' => false, 'needs_context' => false], - 'account_is_cash' => ['alias' => false, 'needs_context' => false], - - // source account name contains + alias - 'source_account_contains' => ['alias' => false, 'needs_context' => true,], - 'from_account_contains' => ['alias' => true, 'alias_for' => 'source_account_contains', 'needs_context' => true,], - 'source' => ['alias' => true, 'alias_for' => 'source_account_contains', 'needs_context' => true,], - 'from' => ['alias' => true, 'alias_for' => 'source_account_contains', 'needs_context' => true,], - - // source account name starts with + alias - 'source_account_starts' => ['alias' => false, 'needs_context' => true,], - 'from_account_starts' => ['alias' => true, 'alias_for' => 'source_account_starts', 'needs_context' => true,], - - // source account name ends with + alias - 'source_account_ends' => ['alias' => false, 'needs_context' => true,], - 'from_account_ends' => ['alias' => true, 'alias_for' => 'source_account_ends', 'needs_context' => true,], - - // source account ID + alias - 'source_account_id' => ['alias' => false, 'needs_context' => true,], - 'from_account_id' => ['alias' => true, 'alias_for' => 'source_account_id', 'needs_context' => true,], - - // source account number is - 'source_account_nr_is' => ['alias' => false, 'needs_context' => true,], - 'from_account_nr_is' => ['alias' => true, 'alias_for' => 'source_account_nr_is', 'needs_context' => true,], - - // source account number contains - 'source_account_nr_contains' => ['alias' => false, 'needs_context' => true,], - 'from_account_nr_contains' => ['alias' => true, 'alias_for' => 'source_account_nr_contains', 'needs_context' => true,], - - // source account number starts with - 'source_account_nr_starts' => ['alias' => false, 'needs_context' => true,], - 'from_account_nr_starts' => ['alias' => true, 'alias_for' => 'source_account_nr_starts', 'needs_context' => true,], - - // source account number ends with - 'source_account_nr_ends' => ['alias' => false, 'needs_context' => true,], - 'from_account_nr_ends' => ['alias' => true, 'alias_for' => 'source_account_nr_ends', 'needs_context' => true,], - - // destination account name is + alias - 'destination_account_is' => ['alias' => false, 'needs_context' => true,], - 'to_account_is' => ['alias' => true, 'alias_for' => 'destination_account_is', 'needs_context' => true,], - - // destination account name contains + alias - 'destination_account_contains' => ['alias' => false, 'needs_context' => true,], - 'to_account_contains' => ['alias' => true, 'alias_for' => 'destination_account_contains', 'needs_context' => true,], - 'destination' => ['alias' => true, 'alias_for' => 'destination_account_contains', 'needs_context' => true,], - 'to' => ['alias' => true, 'alias_for' => 'destination_account_contains', 'needs_context' => true,], - - // destination account name starts with + alias - 'destination_account_starts' => ['alias' => false, 'needs_context' => true,], - 'to_account_starts' => ['alias' => true, 'alias_for' => 'destination_account_starts', 'needs_context' => true,], - - // destination account name ends with + alias - 'destination_account_ends' => ['alias' => false, 'needs_context' => true,], - 'to_account_ends' => ['alias' => true, 'alias_for' => 'destination_account_ends', 'needs_context' => true,], - - // destination account ID + alias - 'destination_account_id' => ['alias' => false, 'needs_context' => true,], - 'to_account_id' => ['alias' => true, 'alias_for' => 'destination_account_id', 'needs_context' => true,], - - // destination account number is - 'destination_account_nr_is' => ['alias' => false, 'needs_context' => true,], - 'to_account_nr_is' => ['alias' => true, 'alias_for' => 'destination_account_nr_is', 'needs_context' => true,], - - // destination account number contains - 'destination_account_nr_contains' => ['alias' => false, 'needs_context' => true,], - 'to_account_nr_contains' => ['alias' => true, 'alias_for' => 'destination_account_nr_contains', 'needs_context' => true,], - - // destination account number starts with - 'destination_account_nr_starts' => ['alias' => false, 'needs_context' => true,], - 'to_account_nr_starts' => ['alias' => true, 'alias_for' => 'destination_account_nr_starts', 'needs_context' => true,], - - // destination account number ends with - 'destination_account_nr_ends' => ['alias' => false, 'needs_context' => true,], - 'to_account_nr_ends' => ['alias' => true, 'alias_for' => 'destination_account_nr_ends', 'needs_context' => true,], - - // any account id is - 'account_id' => ['alias' => false, 'needs_context' => true,], - - // category - 'category_is' => ['alias' => false, 'needs_context' => true,], - 'category' => ['alias' => true, 'alias_for' => 'category_is', 'needs_context' => true,], - - // budget - 'budget_is' => ['alias' => false, 'needs_context' => true,], - 'budget' => ['alias' => true, 'alias_for' => 'budget_is', 'needs_context' => true,], - - // bill - 'bill_is' => ['alias' => false, 'needs_context' => true,], - 'bill' => ['alias' => true, 'alias_for' => 'bill_is', 'needs_context' => true,], - - // type - 'transaction_type' => ['alias' => false, 'needs_context' => true,], - 'type' => ['alias' => true, 'alias_for' => 'transaction_type', 'needs_context' => true,], - - // date: - 'date_is' => ['alias' => false, 'needs_context' => true,], - 'date' => ['alias' => true, 'alias_for' => 'date_is', 'needs_context' => true,], - 'on' => ['alias' => true, 'alias_for' => 'date_is', 'needs_context' => true,], - 'date_before' => ['alias' => false, 'needs_context' => true,], - 'before' => ['alias' => true, 'alias_for' => 'date_before', 'needs_context' => true,], - 'date_after' => ['alias' => false, 'needs_context' => true,], - 'after' => ['alias' => true, 'alias_for' => 'date_after', 'needs_context' => true,], - - // other interesting fields - 'tag_is' => ['alias' => false, 'needs_context' => true,], - 'tag' => ['alias' => true, 'alias_for' => 'tag_is', 'needs_context' => true,], - 'created_on' => ['alias' => false, 'needs_context' => true,], - 'created_at' => ['alias' => true, 'alias_for' => 'created_on', 'needs_context' => true,], - 'updated_on' => ['alias' => false, 'needs_context' => true,], - 'updated_at' => ['alias' => true, 'alias_for' => 'updated_on', 'needs_context' => true,], - 'external_id' => ['alias' => false, 'needs_context' => true,], - 'internal_reference' => ['alias' => false, 'needs_context' => true,], - - ], - ], - // expected source types for each transaction type, in order of preference. 'expected_source_types' => [ 'source' => [ diff --git a/config/google2fa.php b/config/google2fa.php index 34e719a2e1..553c4a6014 100644 --- a/config/google2fa.php +++ b/config/google2fa.php @@ -21,6 +21,8 @@ declare(strict_types=1); +use PragmaRX\Google2FALaravel\Support\Constants; + return [ /* * Auth container binding @@ -92,4 +94,6 @@ return [ 'store_in_cookie' => true, + 'qrcode_image_backend' => Constants::QRCODE_IMAGE_BACKEND_SVG, + ]; diff --git a/config/intro.php b/config/intro.php index 4fd93513e5..b364b9f7b5 100644 --- a/config/intro.php +++ b/config/intro.php @@ -45,7 +45,7 @@ return [ 'basic_info' => ['element' => '#transaction-info', 'position' => 'right'], 'amount_info' => ['element' => '#amount-info', 'position' => 'bottom'], 'optional_info' => ['element' => '#optional-info', 'position' => 'left'], - 'split' => ['element' => '.split_add_btn','position' => 'top'], + 'split' => ['element' => '.split_add_btn', 'position' => 'top'], ], 'transactions_create_withdrawal' => [ diff --git a/config/ldap.php b/config/ldap.php deleted file mode 100644 index 6d00ca1a16..0000000000 --- a/config/ldap.php +++ /dev/null @@ -1,97 +0,0 @@ -. - */ - -declare(strict_types=1); - -return [ - - /* - |-------------------------------------------------------------------------- - | Default LDAP Connection Name - |-------------------------------------------------------------------------- - | - | Here you may specify which of the LDAP connections below you wish - | to use as your default connection for all LDAP operations. Of - | course you may add as many connections you'd like below. - | - */ - - 'default' => env('LDAP_CONNECTION', 'default'), - 'extra_filter' => env('LDAP_EXTRA_FILTER'), - 'dialect' => env('LDAP_DIALECT'), - - /* - |-------------------------------------------------------------------------- - | LDAP Connections - |-------------------------------------------------------------------------- - | - | Below you may configure each LDAP connection your application requires - | access to. Be sure to include a valid base DN - otherwise you may - | not receive any results when performing LDAP search operations. - | - */ - - 'connections' => [ - - 'default' => [ - 'hosts' => [env('LDAP_HOST', '127.0.0.1')], - 'username' => env('LDAP_USERNAME', 'cn=user,dc=local,dc=com'), - 'password' => env('LDAP_PASSWORD', 'secret'), - 'port' => env('LDAP_PORT', 389), - 'base_dn' => env('LDAP_BASE_DN', 'dc=local,dc=com'), - 'timeout' => env('LDAP_TIMEOUT', 5), - 'use_ssl' => env('LDAP_SSL', false), - 'use_tls' => env('LDAP_TLS', false), - ], - - ], - - /* - |-------------------------------------------------------------------------- - | LDAP Logging - |-------------------------------------------------------------------------- - | - | When LDAP logging is enabled, all LDAP search and authentication - | operations are logged using the default application logging - | driver. This can assist in debugging issues and more. - | - */ - - 'logging' => env('LDAP_LOGGING', true), - - /* - |-------------------------------------------------------------------------- - | LDAP Cache - |-------------------------------------------------------------------------- - | - | LDAP caching enables the ability of caching search results using the - | query builder. This is great for running expensive operations that - | may take many seconds to complete, such as a pagination request. - | - */ - - 'cache' => [ - 'enabled' => env('LDAP_CACHE', false), - 'driver' => env('CACHE_DRIVER', 'file'), - ], - -]; diff --git a/config/logging.php b/config/logging.php index fe22ffa672..228f6c1de1 100644 --- a/config/logging.php +++ b/config/logging.php @@ -54,22 +54,22 @@ return [ 'channels' => [ // default channels for 'stack' and audit logs: - 'stack' => [ + 'stack' => [ 'driver' => 'stack', 'channels' => ['daily', 'stdout'], ], - 'audit' => [ + 'audit' => [ 'driver' => 'stack', 'channels' => ['audit_daily', 'audit_stdout'], ], - 'scoped' => [ + 'scoped' => [ 'driver' => 'custom', - 'via' => FireflyIII\Logging\CreateCustomLogger::class, + 'via' => FireflyIII\Logging\CreateCustomLogger::class, ], - 'papertrail' => [ - 'driver' => 'monolog', - 'level' => envNonEmpty('APP_LOG_LEVEL', 'info'), - 'handler' => SyslogUdpHandler::class, + 'papertrail' => [ + 'driver' => 'monolog', + 'level' => envNonEmpty('APP_LOG_LEVEL', 'info'), + 'handler' => SyslogUdpHandler::class, 'handler_with' => [ 'host' => env('PAPERTRAIL_HOST'), 'port' => env('PAPERTRAIL_PORT'), @@ -77,21 +77,21 @@ return [ ], // single laravel log file: - 'single' => [ + 'single' => [ 'driver' => 'single', 'path' => storage_path('logs/laravel.log'), 'level' => envNonEmpty('APP_LOG_LEVEL', 'info'), ], // stdout, used in stack 'stack' by default: - 'stdout' => [ + 'stdout' => [ 'driver' => 'single', 'path' => 'php://stdout', 'level' => envNonEmpty('APP_LOG_LEVEL', 'info'), ], // daily, used in stack 'stack' by default: - 'daily' => [ + 'daily' => [ 'driver' => 'daily', 'path' => storage_path('logs/ff3-' . PHP_SAPI . '.log'), 'level' => envNonEmpty('APP_LOG_LEVEL', 'info'), @@ -99,14 +99,14 @@ return [ ], // the audit log destinations: - 'audit_daily' => [ + 'audit_daily' => [ 'driver' => 'daily', 'path' => storage_path('logs/ff3-audit.log'), 'tap' => [AuditLogger::class], 'level' => envNonEmpty('AUDIT_LOG_LEVEL', 'info'), 'days' => 90, ], - 'audit_stdout' => [ + 'audit_stdout' => [ 'driver' => 'single', 'path' => 'php://stdout', 'tap' => [AuditLogger::class], @@ -114,13 +114,13 @@ return [ ], // syslog destination - 'syslog' => [ + 'syslog' => [ 'driver' => 'syslog', 'level' => envNonEmpty('APP_LOG_LEVEL', 'info'), ], // errorlog destination - 'errorlog' => [ + 'errorlog' => [ 'driver' => 'errorlog', 'level' => envNonEmpty('APP_LOG_LEVEL', 'info'), ], diff --git a/config/mail.php b/config/mail.php index 3f3f50eb10..10afa09e7f 100644 --- a/config/mail.php +++ b/config/mail.php @@ -23,23 +23,23 @@ declare(strict_types=1); return [ -/* -|-------------------------------------------------------------------------- -| Default Mailer -|-------------------------------------------------------------------------- -| -| This option controls the default mailer that is used to send any email -| messages sent by your application. Alternative mailers may be setup -| and used as needed; however, this mailer will be used by default. -| -*/ + /* + |-------------------------------------------------------------------------- + | Default Mailer + |-------------------------------------------------------------------------- + | + | This option controls the default mailer that is used to send any email + | messages sent by your application. Alternative mailers may be setup + | and used as needed; however, this mailer will be used by default. + | + */ 'default' => env('MAIL_MAILER', 'smtp'), 'mailers' => [ 'smtp' => [ 'transport' => 'smtp', - 'host' => env('MAIL_HOST', 'smtp.mailtrap.io'), - 'port' => env('MAIL_PORT', 2525), + 'host' => env('MAIL_HOST', 'smtp.mailtrap.io'), + 'port' => env('MAIL_PORT', 2525), 'encryption' => env('MAIL_ENCRYPTION', 'tls'), 'username' => env('MAIL_USERNAME'), 'password' => env('MAIL_PASSWORD'), @@ -62,7 +62,7 @@ return [ 'transport' => 'sendmail', 'path' => '/usr/sbin/sendmail -bs', ], - 'log' => [ + 'log' => [ 'transport' => 'log', 'channel' => env('MAIL_LOG_CHANNEL', 'stack'), 'level' => 'notice', @@ -73,7 +73,7 @@ return [ ], ], - 'from' => ['address' => envNonEmpty('MAIL_FROM', 'changeme@example.com'), 'name' => 'Firefly III Mailer'], + 'from' => ['address' => envNonEmpty('MAIL_FROM', 'changeme@example.com'), 'name' => 'Firefly III Mailer'], 'markdown' => [ 'theme' => 'default', diff --git a/config/sanctum.php b/config/sanctum.php index 194cceb0d6..d0b57a048f 100644 --- a/config/sanctum.php +++ b/config/sanctum.php @@ -1,6 +1,30 @@ . + */ + declare(strict_types=1); +use FireflyIII\Http\Middleware\EncryptCookies; +use FireflyIII\Http\Middleware\VerifyCsrfToken; + return [ /* @@ -14,15 +38,7 @@ return [ | */ - 'stateful' => explode( - ',', env( - 'SANCTUM_STATEFUL_DOMAINS', sprintf( - '%s%s', - 'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1', - env('APP_URL') ? ',' . parse_url(env('APP_URL'), PHP_URL_HOST) : '' - ) - ) - ), + 'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', '')), /* |-------------------------------------------------------------------------- @@ -36,7 +52,7 @@ return [ | */ - 'guard' => ['web'], + 'guard' => [env('AUTHENTICATION_GUARD', 'web')], /* |-------------------------------------------------------------------------- @@ -63,8 +79,8 @@ return [ */ 'middleware' => [ - 'verify_csrf_token' => \FireflyIII\Http\Middleware\VerifyCsrfToken::class, - 'encrypt_cookies' => \FireflyIII\Http\Middleware\EncryptCookies::class, + 'verify_csrf_token' => VerifyCsrfToken::class, + 'encrypt_cookies' => EncryptCookies::class, ], ]; diff --git a/config/search.php b/config/search.php new file mode 100644 index 0000000000..a81cd55eaa --- /dev/null +++ b/config/search.php @@ -0,0 +1,233 @@ +. + */ + +declare(strict_types=1); + +return [ + 'operators' => [ + 'user_action' => ['alias' => false, 'needs_context' => true,], + 'account_id' => ['alias' => false, 'needs_context' => true,], + 'source_account_id' => ['alias' => false, 'needs_context' => true,], + 'destination_account_id' => ['alias' => false, 'needs_context' => true,], + 'transaction_type' => ['alias' => false, 'needs_context' => true,], + 'type' => ['alias' => true, 'alias_for' => 'transaction_type', 'needs_context' => true,], + 'tag_is' => ['alias' => false, 'needs_context' => true,], + 'tag_is_not' => ['alias' => false, 'needs_context' => true,], + 'tag' => ['alias' => true, 'alias_for' => 'tag_is', 'needs_context' => true,], + 'description_is' => ['alias' => false, 'needs_context' => true,], + 'description' => ['alias' => true, 'alias_for' => 'description_is', 'needs_context' => true,], + 'description_contains' => ['alias' => false, 'needs_context' => true,], + 'description_ends' => ['alias' => false, 'needs_context' => true,], + 'description_starts' => ['alias' => false, 'needs_context' => true,], + 'notes_is' => ['alias' => false, 'needs_context' => true,], + 'notes_are' => ['alias' => true, 'alias_for' => 'notes_is', 'needs_context' => true,], + 'notes_contains' => ['alias' => false, 'needs_context' => true,], + 'notes_contain' => ['alias' => true, 'alias_for' => 'notes_contains', 'needs_context' => true,], + 'notes' => ['alias' => true, 'alias_for' => 'notes_contains', 'needs_context' => true,], + 'notes_ends' => ['alias' => false, 'needs_context' => true,], + 'notes_end' => ['alias' => true, 'alias_for' => 'notes_ends', 'needs_context' => true,], + 'notes_starts' => ['alias' => false, 'needs_context' => true,], + 'notes_start' => ['alias' => true, 'alias_for' => 'notes_starts', 'needs_context' => true,], + 'source_account_is' => ['alias' => false, 'needs_context' => true,], + 'from_account_is' => ['alias' => true, 'alias_for' => 'source_account_is', 'needs_context' => true,], + 'source_account_contains' => ['alias' => false, 'needs_context' => true,], + 'source' => ['alias' => true, 'alias_for' => 'source_account_contains', 'needs_context' => true,], + 'from' => ['alias' => true, 'alias_for' => 'source_account_contains', 'needs_context' => true,], + 'from_account_contains' => ['alias' => true, 'alias_for' => 'source_account_contains', 'needs_context' => true,], + 'source_account_ends' => ['alias' => false, 'needs_context' => true,], + 'from_account_ends' => ['alias' => true, 'alias_for' => 'source_account_ends', 'needs_context' => true,], + 'source_account_starts' => ['alias' => false, 'needs_context' => true,], + 'from_account_starts' => ['alias' => true, 'alias_for' => 'source_account_starts', 'needs_context' => true,], + 'source_account_nr_is' => ['alias' => false, 'needs_context' => true,], + 'from_account_nr_is' => ['alias' => true, 'alias_for' => 'source_account_nr_is', 'needs_context' => true,], + 'source_account_nr_contains' => ['alias' => false, 'needs_context' => true,], + 'from_account_nr_contains' => ['alias' => true, 'alias_for' => 'source_account_nr_contains', 'needs_context' => true,], + 'source_account_nr_ends' => ['alias' => false, 'needs_context' => true,], + 'from_account_nr_ends' => ['alias' => true, 'alias_for' => 'source_account_nr_ends', 'needs_context' => true,], + 'source_account_nr_starts' => ['alias' => false, 'needs_context' => true,], + 'from_account_nr_starts' => ['alias' => true, 'alias_for' => 'source_account_nr_starts', 'needs_context' => true,], + 'destination_account_is' => ['alias' => false, 'needs_context' => true,], + 'to_account_is' => ['alias' => true, 'alias_for' => 'destination_account_is', 'needs_context' => true,], + 'destination_account_contains' => ['alias' => false, 'needs_context' => true,], + 'destination' => ['alias' => true, 'alias_for' => 'destination_account_contains', 'needs_context' => true,], + 'to' => ['alias' => true, 'alias_for' => 'destination_account_contains', 'needs_context' => true,], + 'to_account_contains' => ['alias' => true, 'alias_for' => 'destination_account_contains', 'needs_context' => true,], + 'destination_account_ends' => ['alias' => false, 'needs_context' => true,], + 'to_account_ends' => ['alias' => true, 'alias_for' => 'destination_account_ends', 'needs_context' => true,], + 'destination_account_starts' => ['alias' => false, 'needs_context' => true,], + 'to_account_starts' => ['alias' => true, 'alias_for' => 'destination_account_starts', 'needs_context' => true,], + 'destination_account_nr_is' => ['alias' => false, 'needs_context' => true,], + 'to_account_nr_is' => ['alias' => true, 'alias_for' => 'destination_account_nr_is', 'needs_context' => true,], + 'destination_account_nr_contains' => ['alias' => false, 'needs_context' => true,], + 'to_account_nr_contains' => ['alias' => true, 'alias_for' => 'destination_account_nr_contains', 'needs_context' => true,], + 'destination_account_nr_ends' => ['alias' => false, 'needs_context' => true,], + 'to_account_nr_ends' => ['alias' => true, 'alias_for' => 'destination_account_nr_ends', 'needs_context' => true,], + 'destination_account_nr_starts' => ['alias' => false, 'needs_context' => true,], + 'to_account_nr_starts' => ['alias' => true, 'alias_for' => 'destination_account_nr_starts', 'needs_context' => true,], + 'account_is' => ['alias' => false, 'needs_context' => true,], + 'account_contains' => ['alias' => false, 'needs_context' => true,], + 'account_ends' => ['alias' => false, 'needs_context' => true,], + 'account_starts' => ['alias' => false, 'needs_context' => true,], + 'account_nr_is' => ['alias' => false, 'needs_context' => true,], + 'account_nr_contains' => ['alias' => false, 'needs_context' => true,], + 'account_nr_ends' => ['alias' => false, 'needs_context' => true,], + 'account_nr_starts' => ['alias' => false, 'needs_context' => true,], + 'category_is' => ['alias' => false, 'needs_context' => true,], + 'category_contains' => ['alias' => false, 'needs_context' => true,], + 'category' => ['alias' => true, 'alias_for' => 'category_contains', 'needs_context' => true,], + 'category_ends' => ['alias' => false, 'needs_context' => true,], + 'category_starts' => ['alias' => false, 'needs_context' => true,], + 'budget_is' => ['alias' => false, 'needs_context' => true,], + 'budget_contains' => ['alias' => false, 'needs_context' => true,], + 'budget' => ['alias' => true, 'alias_for' => 'budget_contains', 'needs_context' => true,], + 'budget_ends' => ['alias' => false, 'needs_context' => true,], + 'budget_starts' => ['alias' => false, 'needs_context' => true,], + 'bill_is' => ['alias' => false, 'needs_context' => true,], + 'bill_contains' => ['alias' => false, 'needs_context' => true,], + 'bill' => ['alias' => true, 'alias_for' => 'bill_contains', 'needs_context' => true,], + 'bill_ends' => ['alias' => false, 'needs_context' => true,], + 'bill_starts' => ['alias' => false, 'needs_context' => true,], + 'external_id_is' => ['alias' => false, 'needs_context' => true,], + 'external_id_contains' => ['alias' => false, 'needs_context' => true,], + 'external_id' => ['alias' => true, 'alias_for' => 'external_id_contains', 'needs_context' => true,], + 'external_id_ends' => ['alias' => false, 'needs_context' => true,], + 'external_id_starts' => ['alias' => false, 'needs_context' => true,], + 'internal_reference_is' => ['alias' => false, 'needs_context' => true,], + 'internal_reference_contains' => ['alias' => false, 'needs_context' => true,], + 'internal_reference' => ['alias' => true, 'alias_for' => 'internal_reference_contains', 'needs_context' => true,], + 'internal_reference_ends' => ['alias' => false, 'needs_context' => true,], + 'internal_reference_starts' => ['alias' => false, 'needs_context' => true,], + 'external_url_is' => ['alias' => false, 'needs_context' => true,], + 'external_url_contains' => ['alias' => false, 'needs_context' => true,], + 'external_url' => ['alias' => true, 'alias_for' => 'external_url_contains', 'needs_context' => true,], + 'external_url_ends' => ['alias' => false, 'needs_context' => true,], + 'external_url_starts' => ['alias' => false, 'needs_context' => true,], + 'has_attachments' => ['alias' => false, 'needs_context' => false,], + 'has_any_category' => ['alias' => false, 'needs_context' => false,], + 'has_any_budget' => ['alias' => false, 'needs_context' => false,], + 'has_any_bill' => ['alias' => false, 'needs_context' => false,], + 'has_any_tag' => ['alias' => false, 'needs_context' => false,], + 'any_notes' => ['alias' => false, 'needs_context' => false,], + 'has_any_notes' => ['alias' => true, 'alias_for' => 'any_notes', 'needs_context' => false,], + 'any_external_url' => ['alias' => false, 'needs_context' => false,], + 'has_any_external_url' => ['alias' => true, 'alias_for' => 'any_external_url', 'needs_context' => false,], + 'has_no_attachments' => ['alias' => false, 'needs_context' => false,], + 'has_no_category' => ['alias' => false, 'needs_context' => false,], + 'has_no_budget' => ['alias' => false, 'needs_context' => false,], + 'has_no_bill' => ['alias' => false, 'needs_context' => false,], + 'has_no_tag' => ['alias' => false, 'needs_context' => false,], + 'no_notes' => ['alias' => false, 'needs_context' => false,], + 'no_external_url' => ['alias' => false, 'needs_context' => false,], + 'source_is_cash' => ['alias' => false, 'needs_context' => false,], + 'destination_is_cash' => ['alias' => false, 'needs_context' => false,], + 'account_is_cash' => ['alias' => false, 'needs_context' => false,], + 'currency_is' => ['alias' => false, 'needs_context' => true,], + 'foreign_currency_is' => ['alias' => false, 'needs_context' => true,], + 'id' => ['alias' => false, 'trigger_class' => '', 'needs_context' => true,], + 'journal_id' => ['alias' => false, 'trigger_class' => '', 'needs_context' => true,], + 'recurrence_id' => ['alias' => false, 'trigger_class' => '', 'needs_context' => true,], + 'date_on' => ['alias' => false, 'needs_context' => true,], + 'date' => ['alias' => true, 'alias_for' => 'date_on', 'needs_context' => true,], + 'date_is' => ['alias' => true, 'alias_for' => 'date_on', 'needs_context' => true,], + 'on' => ['alias' => true, 'alias_for' => 'date_on', 'needs_context' => true,], + 'date_before' => ['alias' => false, 'needs_context' => true,], + 'before' => ['alias' => true, 'alias_for' => 'date_before', 'needs_context' => true,], + 'date_after' => ['alias' => false, 'needs_context' => true,], + 'after' => ['alias' => true, 'alias_for' => 'date_after', 'needs_context' => true,], + 'interest_date_on' => ['alias' => false, 'needs_context' => true,], + 'interest_date' => ['alias' => true, 'alias_for' => 'interest_date_on', 'needs_context' => true,], + 'interest_date_is' => ['alias' => true, 'alias_for' => 'interest_date_on', 'needs_context' => true,], + 'interest_date_before' => ['alias' => false, 'needs_context' => true,], + 'interest_date_after' => ['alias' => false, 'needs_context' => true,], + 'book_date_on' => ['alias' => false, 'needs_context' => true,], + 'book_date' => ['alias' => true, 'alias_for' => 'book_date_on', 'needs_context' => true,], + 'book_date_is' => ['alias' => true, 'alias_for' => 'book_date_on', 'needs_context' => true,], + 'book_date_before' => ['alias' => false, 'needs_context' => true,], + 'book_date_after' => ['alias' => false, 'needs_context' => true,], + 'process_date_on' => ['alias' => false, 'needs_context' => true,], + 'process_date' => ['alias' => true, 'alias_for' => 'process_date_on', 'needs_context' => true,], + 'process_date_is' => ['alias' => true, 'alias_for' => 'process_date_on', 'needs_context' => true,], + 'process_date_before' => ['alias' => false, 'needs_context' => true,], + 'process_date_after' => ['alias' => false, 'needs_context' => true,], + 'due_date_on' => ['alias' => false, 'needs_context' => true,], + 'due_date' => ['alias' => true, 'alias_for' => 'due_date_on', 'needs_context' => true,], + 'due_date_is' => ['alias' => true, 'alias_for' => 'due_date_on', 'needs_context' => true,], + 'due_date_before' => ['alias' => false, 'needs_context' => true,], + 'due_date_after' => ['alias' => false, 'needs_context' => true,], + 'payment_date_on' => ['alias' => false, 'needs_context' => true,], + 'payment_date' => ['alias' => true, 'alias_for' => 'payment_date_on', 'needs_context' => true,], + 'payment_date_is' => ['alias' => true, 'alias_for' => 'payment_date_on', 'needs_context' => true,], + 'payment_date_before' => ['alias' => false, 'needs_context' => true,], + 'payment_date_after' => ['alias' => false, 'needs_context' => true,], + 'invoice_date_on' => ['alias' => false, 'needs_context' => true,], + 'invoice_date' => ['alias' => true, 'alias_for' => 'invoice_date_on', 'needs_context' => true,], + 'invoice_date_is' => ['alias' => true, 'alias_for' => 'invoice_date_on', 'needs_context' => true,], + 'invoice_date_before' => ['alias' => false, 'needs_context' => true,], + 'invoice_date_after' => ['alias' => false, 'needs_context' => true,], + 'created_at_on' => ['alias' => false, 'needs_context' => true,], + 'created_at' => ['alias' => true, 'alias_for' => 'created_at_on', 'needs_context' => true,], + 'created_at_is' => ['alias' => true, 'alias_for' => 'created_at_on', 'needs_context' => true,], + 'created_at_before' => ['alias' => false, 'needs_context' => true,], + 'created_at_after' => ['alias' => false, 'needs_context' => true,], + 'updated_at_on' => ['alias' => false, 'needs_context' => true,], + 'updated_at' => ['alias' => true, 'alias_for' => 'updated_at_on', 'needs_context' => true,], + 'updated_at_is' => ['alias' => true, 'alias_for' => 'updated_at_on', 'needs_context' => true,], + 'updated_at_before' => ['alias' => false, 'needs_context' => true,], + 'updated_at_after' => ['alias' => false, 'needs_context' => true,], + 'created_on_on' => ['alias' => true, 'alias_for' => 'created_at_on', 'needs_context' => true,], + 'created_on' => ['alias' => true, 'alias_for' => 'created_at', 'needs_context' => true,], + 'created_on_before' => ['alias' => true, 'alias_for' => 'created_at_before', 'needs_context' => true,], + 'created_on_after' => ['alias' => true, 'alias_for' => 'created_at_after', 'needs_context' => true,], + 'updated_on_on' => ['alias' => true, 'alias_for' => 'updated_at_on', 'needs_context' => true,], + 'updated_on' => ['alias' => true, 'alias_for' => 'updated_at', 'needs_context' => true,], + 'updated_on_before' => ['alias' => true, 'alias_for' => 'updated_at_before', 'needs_context' => true,], + 'updated_on_after' => ['alias' => true, 'alias_for' => 'updated_at_after', 'needs_context' => true,], + 'amount_is' => ['alias' => false, 'needs_context' => true,], + 'amount' => ['alias' => true, 'alias_for' => 'amount_is', 'needs_context' => true,], + 'amount_exactly' => ['alias' => true, 'alias_for' => 'amount_is', 'needs_context' => true,], + 'amount_less' => ['alias' => false, 'needs_context' => true,], + 'amount_max' => ['alias' => true, 'alias_for' => 'amount_less', 'needs_context' => true,], + 'amount_more' => ['alias' => false, 'needs_context' => true,], + 'amount_min' => ['alias' => true, 'alias_for' => 'amount_more', 'needs_context' => true,], + 'foreign_amount_is' => ['alias' => false, 'needs_context' => true,], + 'foreign_amount' => ['alias' => true, 'alias_for' => 'foreign_amount_is', 'needs_context' => true,], + 'foreign_amount_less' => ['alias' => false, 'needs_context' => true,], + 'foreign_amount_max' => ['alias' => true, 'alias_for' => 'foreign_amount_less', 'needs_context' => true,], + 'foreign_amount_more' => ['alias' => false, 'needs_context' => true,], + 'foreign_amount_min' => ['alias' => true, 'alias_for' => 'foreign_amount_more', 'needs_context' => true,], + 'attachment_name_is' => ['alias' => false, 'needs_context' => true], + 'attachment' => ['alias' => true, 'alias_for' => 'attachment_name_is', 'needs_context' => true], + 'attachment_is' => ['alias' => true, 'alias_for' => 'attachment_name_is', 'needs_context' => true], + 'attachment_name' => ['alias' => true, 'alias_for' => 'attachment_name_is', 'needs_context' => true], + 'attachment_name_contains' => ['alias' => false, 'needs_context' => true], + 'attachment_name_starts' => ['alias' => false, 'needs_context' => true], + 'attachment_name_ends' => ['alias' => false, 'needs_context' => true], + 'attachment_notes' => ['alias' => true, 'alias_for' => 'attachment_notes_are', 'needs_context' => true], + 'attachment_notes_are' => ['alias' => false, 'needs_context' => true], + 'attachment_notes_contains' => ['alias' => false, 'needs_context' => true], + 'attachment_notes_contain' => ['alias' => true, 'alias_for' => 'attachment_notes_contains', 'needs_context' => true], + 'attachment_notes_starts' => ['alias' => false, 'needs_context' => true], + 'attachment_notes_start' => ['alias' => true, 'alias_for' => 'attachment_notes_starts', 'needs_context' => true], + 'attachment_notes_ends' => ['alias' => false, 'needs_context' => true], + 'attachment_notes_end' => ['alias' => true, 'alias_for' => 'attachment_notes_ends', 'needs_context' => true], + ], +]; diff --git a/config/session.php b/config/session.php index f3cb244e20..4de1115cfd 100644 --- a/config/session.php +++ b/config/session.php @@ -36,5 +36,5 @@ return [ 'domain' => env('COOKIE_DOMAIN', null), 'secure' => env('COOKIE_SECURE', null), 'http_only' => true, - 'same_site' => env('COOKIE_SAMESITE','lax'), + 'same_site' => env('COOKIE_SAMESITE', 'lax'), ]; diff --git a/config/twigbridge.php b/config/twigbridge.php index ec2f5bceb6..a56206bb83 100644 --- a/config/twigbridge.php +++ b/config/twigbridge.php @@ -1,6 +1,4 @@ . */ +declare(strict_types=1); + + /** * This file is part of the TwigBridge package. * @@ -30,6 +31,7 @@ declare(strict_types=1); * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ + use FireflyIII\Support\Twig\AmountFormat; use FireflyIII\Support\Twig\General; use FireflyIII\Support\Twig\Rule; @@ -57,15 +59,15 @@ use TwigBridge\Extension\Loader\Globals; return [ 'twig' => [ - 'extension' => 'twig', - 'environment' => [ - 'debug' => env('APP_DEBUG', false), - 'charset' => 'utf-8', - 'cache' => null, - 'auto_reload' => true, + 'extension' => 'twig', + 'environment' => [ + 'debug' => env('APP_DEBUG', false), + 'charset' => 'utf-8', + 'cache' => null, + 'auto_reload' => true, 'strict_variables' => false, - 'autoescape' => 'html', - 'optimizations' => -1, + 'autoescape' => 'html', + 'optimizations' => -1, ], /* |-------------------------------------------------------------------------- @@ -89,7 +91,7 @@ return [ | NOTE: these will be overwritten if you pass data into the view with the same key. | */ - 'globals' => [], + 'globals' => [], ], 'extensions' => [ @@ -104,7 +106,7 @@ return [ | `Twig\Extension\DebugExtension` is enabled automatically if twig.debug is TRUE. | */ - 'enabled' => [ + 'enabled' => [ Facades::class, Filters::class, Functions::class, @@ -154,7 +156,7 @@ return [ | in order to be marked as safe. | */ - 'facades' => [ + 'facades' => [ 'Breadcrumbs' => [ 'is_safe' => [ 'render', @@ -173,7 +175,7 @@ return [ 'ExpandedForm' => [ 'is_safe' => [ 'date', 'text', 'select', 'balance', 'optionsList', 'checkbox', 'amount', 'tags', 'integer', 'textarea', 'location', 'file', 'staticText', - 'password', 'nonSelectableAmount', 'number', 'amountNoCurrency', 'percentage','objectGroup' + 'password', 'nonSelectableAmount', 'number', 'amountNoCurrency', 'percentage', 'objectGroup', ], ], @@ -262,7 +264,7 @@ return [ | | */ - 'filters' => [ + 'filters' => [ 'get' => 'data_get', ], ], diff --git a/config/upgrade.php b/config/upgrade.php index c5d244c343..423dbfc272 100644 --- a/config/upgrade.php +++ b/config/upgrade.php @@ -34,7 +34,7 @@ return [ '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.', - '5.3.0' => 'This version of Firefly III requires PHP7.4.' + '5.3.0' => 'This version of Firefly III requires PHP7.4.', ], '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.', @@ -47,7 +47,7 @@ return [ '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.', - '5.3.0' => 'This version of Firefly III requires PHP7.4.' + '5.3.0' => 'This version of Firefly III requires PHP7.4.', ], ], ]; diff --git a/database/migrations/2021_08_28_073733_user_groups.php b/database/migrations/2021_08_28_073733_user_groups.php index e66494b814..70afc7d990 100644 --- a/database/migrations/2021_08_28_073733_user_groups.php +++ b/database/migrations/2021_08_28_073733_user_groups.php @@ -47,7 +47,7 @@ class UserGroups extends Migration foreach ($this->tables as $tableName) { Schema::table( $tableName, function (Blueprint $table) use ($tableName) { - + $table->dropForeign(sprintf('%s_to_ugi', $tableName)); if (Schema::hasColumn($tableName, 'user_group_id')) { $table->dropColumn('user_group_id'); diff --git a/database/migrations/2021_12_27_000001_create_local_personal_access_tokens_table.php b/database/migrations/2021_12_27_000001_create_local_personal_access_tokens_table.php index 2112b66b3e..76c4519124 100644 --- a/database/migrations/2021_12_27_000001_create_local_personal_access_tokens_table.php +++ b/database/migrations/2021_12_27_000001_create_local_personal_access_tokens_table.php @@ -1,4 +1,25 @@ . + */ + declare(strict_types=1); use Illuminate\Database\Migrations\Migration; @@ -10,6 +31,16 @@ use Illuminate\Support\Facades\Schema; */ class CreateLocalPersonalAccessTokensTable extends Migration { + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('personal_access_tokens'); + } + /** * Run the migrations. * @@ -29,14 +60,4 @@ class CreateLocalPersonalAccessTokensTable extends Migration }); } } - - /** - * Reverse the migrations. - * - * @return void - */ - public function down() - { - Schema::dropIfExists('personal_access_tokens'); - } } diff --git a/database/seeders/AccountTypeSeeder.php b/database/seeders/AccountTypeSeeder.php index 2356d5aa0c..e917f3ba94 100644 --- a/database/seeders/AccountTypeSeeder.php +++ b/database/seeders/AccountTypeSeeder.php @@ -46,7 +46,7 @@ class AccountTypeSeeder extends Seeder AccountType::RECONCILIATION, AccountType::DEBT, AccountType::MORTGAGE, - AccountType::LIABILITY_CREDIT + AccountType::LIABILITY_CREDIT, ]; foreach ($types as $type) { try { diff --git a/database/seeders/ConfigSeeder.php b/database/seeders/ConfigSeeder.php index 7005d71345..d0b100792d 100644 --- a/database/seeders/ConfigSeeder.php +++ b/database/seeders/ConfigSeeder.php @@ -49,7 +49,7 @@ class ConfigSeeder extends Seeder ); } if (null !== $entry) { - $version = (int)config('firefly.db_version'); + $version = (int) config('firefly.db_version'); $entry->data = $version; $entry->save(); diff --git a/database/seeders/TransactionTypeSeeder.php b/database/seeders/TransactionTypeSeeder.php index 07aacd5ab0..d3dd66be5d 100644 --- a/database/seeders/TransactionTypeSeeder.php +++ b/database/seeders/TransactionTypeSeeder.php @@ -40,7 +40,7 @@ class TransactionTypeSeeder extends Seeder TransactionType::OPENING_BALANCE, TransactionType::RECONCILIATION, TransactionType::INVALID, - TransactionType::LIABILITY_CREDIT + TransactionType::LIABILITY_CREDIT, ]; foreach ($types as $type) { diff --git a/frontend/.eslintrc.js b/frontend/.eslintrc.js index 3f5b7e048a..fdd68ea42d 100644 --- a/frontend/.eslintrc.js +++ b/frontend/.eslintrc.js @@ -1,3 +1,23 @@ +/* + * .eslintrc.js + * Copyright (c) 2022 james@firefly-iii.org + * + * This file is part of Firefly III (https://github.com/firefly-iii). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + const { resolve } = require('path'); module.exports = { // https://eslint.org/docs/user-guide/configuring#configuration-cascading-and-hierarchy diff --git a/frontend/.postcssrc.js b/frontend/.postcssrc.js index 1174fe52b7..3e3fe5cb92 100644 --- a/frontend/.postcssrc.js +++ b/frontend/.postcssrc.js @@ -1,3 +1,23 @@ +/* + * .postcssrc.js + * Copyright (c) 2022 james@firefly-iii.org + * + * This file is part of Firefly III (https://github.com/firefly-iii). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + // https://github.com/michael-ciniawsky/postcss-load-config module.exports = { diff --git a/frontend/babel.config.js b/frontend/babel.config.js index fe9cae62e4..88ca4e7820 100644 --- a/frontend/babel.config.js +++ b/frontend/babel.config.js @@ -1,3 +1,23 @@ +/* + * babel.config.js + * Copyright (c) 2022 james@firefly-iii.org + * + * This file is part of Firefly III (https://github.com/firefly-iii). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + /* eslint-env node */ module.exports = api => { diff --git a/frontend/package.json b/frontend/package.json index e61c2ff310..476f2e76cb 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -11,13 +11,13 @@ }, "dependencies": { "@popperjs/core": "^2.11.2", - "@quasar/extras": "^1.12.5", + "@quasar/extras": "^1.13.5", "apexcharts": "^3.32.1", "axios": "^0.21.1", "axios-cache-adapter": "^2.7.3", "core-js": "^3.6.5", "date-fns": "^2.28.0", - "quasar": "^2.5.5", + "quasar": "^2.6.5", "vue": "3", "vue-i18n": "^9.0.0", "vue-router": "^4.0.0", diff --git a/frontend/public/maskable-icon.svg b/frontend/public/maskable-icon.svg index 0ca6cc1be0..46ca2a846f 100644 --- a/frontend/public/maskable-icon.svg +++ b/frontend/public/maskable-icon.svg @@ -1,3 +1,23 @@ + + diff --git a/frontend/public/safari-pinned-tab.svg b/frontend/public/safari-pinned-tab.svg index 108c659acf..36c7d4ecc4 100644 --- a/frontend/public/safari-pinned-tab.svg +++ b/frontend/public/safari-pinned-tab.svg @@ -1,4 +1,24 @@ + + . + */ + /* * This file runs in a Node context (it's NOT transpiled by Babel), so use only * the ES6 features that are supported by your Node version. https://node.green/ diff --git a/frontend/src/App.vue b/frontend/src/App.vue index 349912d43f..9e7fc72915 100644 --- a/frontend/src/App.vue +++ b/frontend/src/App.vue @@ -1,3 +1,23 @@ + + diff --git a/frontend/src/api/accounts/destroy.js b/frontend/src/api/accounts/destroy.js deleted file mode 100644 index 3b784bf218..0000000000 --- a/frontend/src/api/accounts/destroy.js +++ /dev/null @@ -1,28 +0,0 @@ -/* - * post.js - * Copyright (c) 2022 james@firefly-iii.org - * - * This file is part of Firefly III (https://github.com/firefly-iii). - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ - -import {api} from "boot/axios"; - -export default class Destroy { - destroy(identifier) { - let url = '/api/v1/accounts/' + identifier; - return api.delete(url); - } -} diff --git a/frontend/src/api/accounts/get.js b/frontend/src/api/accounts/get.js index 6d9cb854ed..e6cf5163fd 100644 --- a/frontend/src/api/accounts/get.js +++ b/frontend/src/api/accounts/get.js @@ -18,18 +18,34 @@ * along with this program. If not, see . */ -import {api} from "boot/axios"; +import Api from "src/api/root/api"; -export default class Get { - get(identifier, date) { - let url = '/api/v1/accounts/' + identifier; - if(!date) { - return api.get(url); - } - return api.get(url, {params: {date: date}}); +export default class Get extends Api { + constructor() { + super('accounts'); // call the super class constructor and pass in the name parameter } - transactions(identifier, page, cacheKey) { - let url = '/api/v1/accounts/' + identifier + '/transactions'; - return api.get(url, {params: {page: page, cache: cacheKey}}); + + /** + * + * @param identifier + * @param date + * @returns {Promise>} + */ + get(identifier, date) { + let params = {date: date}; + if(!date) { + return this.apiGet(identifier); + } + return this.apiGet(identifier, params); + } + + /** + * + * @param identifier + * @param page + * @returns {Promise>} + */ + transactions(identifier, page) { + return this.apiGetChildren('transactions', identifier, page); } } diff --git a/frontend/src/api/accounts/list.js b/frontend/src/api/accounts/list.js index 90a0fea825..72b5f4e20b 100644 --- a/frontend/src/api/accounts/list.js +++ b/frontend/src/api/accounts/list.js @@ -19,10 +19,27 @@ */ import {api} from "boot/axios"; +import Api from "src/api/root/api"; + +export default class List extends Api{ + constructor() { + super('accounts'); + } -export default class List { list(type, page, cacheKey) { let url = '/api/v1/accounts'; return api.get(url, {params: {page: page, cache: cacheKey, type: type}}); + // console.log('list'); + // + // + // let params = { + // type: type, + // page: page + // } + // this.apiList(page, params).then((response) => { + // console.log('response OK'); + // }).catch((err) => { + // console.error('api list failed'); + // }); } } diff --git a/frontend/src/api/budgets/destroy.js b/frontend/src/api/budgets/destroy.js deleted file mode 100644 index 3b17de392a..0000000000 --- a/frontend/src/api/budgets/destroy.js +++ /dev/null @@ -1,28 +0,0 @@ -/* - * post.js - * Copyright (c) 2022 james@firefly-iii.org - * - * This file is part of Firefly III (https://github.com/firefly-iii). - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ - -import {api} from "boot/axios"; - -export default class Destroy { - destroy(identifier) { - let url = 'api/v1/budgets/' + identifier; - return api.delete(url); - } -} diff --git a/frontend/src/api/categories/destroy.js b/frontend/src/api/categories/destroy.js deleted file mode 100644 index dcb150dc0d..0000000000 --- a/frontend/src/api/categories/destroy.js +++ /dev/null @@ -1,28 +0,0 @@ -/* - * post.js - * Copyright (c) 2022 james@firefly-iii.org - * - * This file is part of Firefly III (https://github.com/firefly-iii). - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ - -import {api} from "boot/axios"; - -export default class Destroy { - destroy(identifier) { - let url = '/api/v1/categories/' + identifier; - return api.delete(url); - } -} diff --git a/frontend/src/api/currencies/destroy.js b/frontend/src/api/currencies/destroy.js deleted file mode 100644 index f9ec216790..0000000000 --- a/frontend/src/api/currencies/destroy.js +++ /dev/null @@ -1,28 +0,0 @@ -/* - * post.js - * Copyright (c) 2022 james@firefly-iii.org - * - * This file is part of Firefly III (https://github.com/firefly-iii). - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ - -import {api} from "boot/axios"; - -export default class Destroy { - destroy(identifier) { - let url = '/api/v1/currencies/' + identifier; - return api.delete(url); - } -} diff --git a/frontend/src/api/rules/destroy.js b/frontend/src/api/generic/destroy.js similarity index 82% rename from frontend/src/api/rules/destroy.js rename to frontend/src/api/generic/destroy.js index 025f961208..90e32cb0dd 100644 --- a/frontend/src/api/rules/destroy.js +++ b/frontend/src/api/generic/destroy.js @@ -1,5 +1,5 @@ /* - * post.js + * destroy.js * Copyright (c) 2022 james@firefly-iii.org * * This file is part of Firefly III (https://github.com/firefly-iii). @@ -18,11 +18,10 @@ * along with this program. If not, see . */ -import {api} from "boot/axios"; +import Api from "src/api/root/api"; -export default class Destroy { - destroy(identifier) { - let url = '/api/v1/rules/' + identifier; - return api.delete(url); +export default class Destroy extends Api { + constructor(path) { + super(path); } } diff --git a/frontend/src/api/groups/destroy.js b/frontend/src/api/groups/destroy.js deleted file mode 100644 index a21e6ba7d1..0000000000 --- a/frontend/src/api/groups/destroy.js +++ /dev/null @@ -1,28 +0,0 @@ -/* - * post.js - * Copyright (c) 2022 james@firefly-iii.org - * - * This file is part of Firefly III (https://github.com/firefly-iii). - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ - -import {api} from "boot/axios"; - -export default class Destroy { - destroy(identifier) { - let url = '/api/v1/object_groups/' + identifier; - return api.delete(url); - } -} diff --git a/frontend/src/api/piggy-banks/destroy.js b/frontend/src/api/piggy-banks/destroy.js deleted file mode 100644 index f7d7a24744..0000000000 --- a/frontend/src/api/piggy-banks/destroy.js +++ /dev/null @@ -1,28 +0,0 @@ -/* - * post.js - * Copyright (c) 2022 james@firefly-iii.org - * - * This file is part of Firefly III (https://github.com/firefly-iii). - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ - -import {api} from "boot/axios"; - -export default class Destroy { - destroy(identifier) { - let url = '/api/v1/piggy_banks/' + identifier; - return api.delete(url); - } -} diff --git a/frontend/src/api/recurring/destroy.js b/frontend/src/api/recurring/destroy.js deleted file mode 100644 index ffb61a8ac7..0000000000 --- a/frontend/src/api/recurring/destroy.js +++ /dev/null @@ -1,28 +0,0 @@ -/* - * post.js - * Copyright (c) 2022 james@firefly-iii.org - * - * This file is part of Firefly III (https://github.com/firefly-iii). - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ - -import {api} from "boot/axios"; - -export default class Destroy { - destroy(identifier) { - let url = '/api/v1/recurrences/' + identifier; - return api.delete(url); - } -} diff --git a/frontend/src/api/root/api.js b/frontend/src/api/root/api.js new file mode 100644 index 0000000000..b2a9f0eae7 --- /dev/null +++ b/frontend/src/api/root/api.js @@ -0,0 +1,130 @@ +/* + * api.js + * Copyright (c) 2022 james@firefly-iii.org + * + * This file is part of Firefly III (https://github.com/firefly-iii). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import {api} from "boot/axios"; + +/** + * + */ +export default class Api { + root = '/api/v1/'; + path = ''; + + constructor(path) { + this.path = path; + } + + apiPath() { + return this.root + this.path; + } + + apiPathId(identifier) { + return this.root + this.path + '/' + identifier; + } + + /** + * + * @param identifier + * @param params + * @returns {Promise>} + */ + apiGet(identifier, params) { + let url = this.apiPathId(identifier); + if (params) { + return api.get(url, {params: params}); + } + return api.get(url); + } + + /** + * This is a generic method that works for all DELETE operations. + * + * @param identifier + * @returns {Promise>} + */ + destroy(identifier) { + let url = this.apiPathId(identifier); + return api.delete(url); + } + + apiPathChildren(identifier, type) { + return this.apiPathId(identifier) + '/' + type; + } + + apiGetChildren(type, identifier, page) { + let url = this.apiPathChildren(identifier, type); + let cacheKey = 'still-todo'; + // needs a cache key. Based on type. + return api.get(url, {params: {page: page, cache: cacheKey}}); + } + + + /** + * + * @param page + * @param params + * @returns {Promise>} + */ + apiList(page, params) { + let type = 'transactions'; + let identifier = '1'; + + let cacheKey = 'still-todo'; + let url = this.apiPathChildren(identifier, type); + + // needs a cache key. Based on type. + return api.get(url, {params: {page: page, cache: cacheKey}}); + + + // let identifier = 'abc'; + // // test: + // let type= 'expense'; + + // let type ='accounts'; + // + // this.store.getters["fireflyiii/getScopedCacheKey"](type); + // let cacheKey = 'def'; + // let url = this.apiPath(); + // + // // needs a cache key. Based on type. + // return api.get(url, {params: {page: page, cache: cacheKey}}); + + // + // + // console.log('apiList'); + // let cacheKey; + // + // //let $q = useQuasar(); + // //const store = useStore(); + // cacheKey = 'OK'; + // console.log('path: ' + this.path); + // //cacheKey = $store.getters["fireflyiii/getScopedCacheKey"](this.path); + // //store.getters["fireflyiii/getScopedCacheKey"](this.path) + // let cache = { + // cache: cacheKey + // }; + // let merged = {...params, ...cache}; + // console.log(merged); + // let url = this.apiPath(); + // console.log(url); + // return api.get(url, {params: merged}); + } + +} diff --git a/frontend/src/api/rule-groups/destroy.js b/frontend/src/api/rule-groups/destroy.js deleted file mode 100644 index f72620bf1a..0000000000 --- a/frontend/src/api/rule-groups/destroy.js +++ /dev/null @@ -1,28 +0,0 @@ -/* - * post.js - * Copyright (c) 2022 james@firefly-iii.org - * - * This file is part of Firefly III (https://github.com/firefly-iii). - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ - -import {api} from "boot/axios"; - -export default class Destroy { - destroy(identifier) { - let url = '/api/v1/rule_groups/' + identifier; - return api.delete(url); - } -} diff --git a/frontend/src/api/system/about.js b/frontend/src/api/system/about.js index 44e29a0c20..e895bf64bf 100644 --- a/frontend/src/api/system/about.js +++ b/frontend/src/api/system/about.js @@ -1,3 +1,23 @@ +/* + * about.js + * Copyright (c) 2022 james@firefly-iii.org + * + * This file is part of Firefly III (https://github.com/firefly-iii). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + import {api} from "boot/axios"; //import createAuthRefreshInterceptor from 'axios-auth-refresh'; diff --git a/frontend/src/api/system/configuration.js b/frontend/src/api/system/configuration.js index 1de0d58580..e57913ea55 100644 --- a/frontend/src/api/system/configuration.js +++ b/frontend/src/api/system/configuration.js @@ -1,4 +1,24 @@ +/* + * configuration.js + * Copyright (c) 2022 james@firefly-iii.org + * + * This file is part of Firefly III (https://github.com/firefly-iii). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + import {api} from "boot/axios"; export default class Configuration { diff --git a/frontend/src/api/system/user.js b/frontend/src/api/system/user.js index 3ff9d421e0..36d1e8464f 100644 --- a/frontend/src/api/system/user.js +++ b/frontend/src/api/system/user.js @@ -1,3 +1,23 @@ +/* + * user.js + * Copyright (c) 2022 james@firefly-iii.org + * + * This file is part of Firefly III (https://github.com/firefly-iii). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + import {api} from "boot/axios"; export default class AboutUser { diff --git a/frontend/src/api/transactions/destroy.js b/frontend/src/api/transactions/destroy.js deleted file mode 100644 index 1eca9641a6..0000000000 --- a/frontend/src/api/transactions/destroy.js +++ /dev/null @@ -1,28 +0,0 @@ -/* - * post.js - * Copyright (c) 2022 james@firefly-iii.org - * - * This file is part of Firefly III (https://github.com/firefly-iii). - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ - -import {api} from "boot/axios"; - -export default class Destroy { - destroy(identifier) { - let url = '/api/v1/transactions/' + identifier; - return api.delete(url); - } -} diff --git a/frontend/src/api/webhooks/destroy.js b/frontend/src/api/webhooks/destroy.js deleted file mode 100644 index b99a699a89..0000000000 --- a/frontend/src/api/webhooks/destroy.js +++ /dev/null @@ -1,28 +0,0 @@ -/* - * post.js - * Copyright (c) 2022 james@firefly-iii.org - * - * This file is part of Firefly III (https://github.com/firefly-iii). - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ - -import {api} from "boot/axios"; - -export default class Destroy { - destroy(identifier) { - let url = '/api/v1/webhooks/' + identifier; - return api.delete(url); - } -} diff --git a/frontend/src/boot/axios.js b/frontend/src/boot/axios.js index b5067a1205..37e2ffc6be 100644 --- a/frontend/src/boot/axios.js +++ b/frontend/src/boot/axios.js @@ -1,3 +1,23 @@ +/* + * axios.js + * Copyright (c) 2022 james@firefly-iii.org + * + * This file is part of Firefly III (https://github.com/firefly-iii). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + import {boot} from 'quasar/wrappers' import axios from 'axios' import {setupCache} from 'axios-cache-adapter' diff --git a/frontend/src/boot/i18n.js b/frontend/src/boot/i18n.js index bd1290d665..9d105e14bd 100644 --- a/frontend/src/boot/i18n.js +++ b/frontend/src/boot/i18n.js @@ -1,3 +1,23 @@ +/* + * i18n.js + * Copyright (c) 2022 james@firefly-iii.org + * + * This file is part of Firefly III (https://github.com/firefly-iii). + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + import { boot } from 'quasar/wrappers' import { createI18n } from 'vue-i18n' import messages from 'src/i18n' diff --git a/frontend/src/components/CompositionComponent.vue b/frontend/src/components/CompositionComponent.vue index 67914640a3..0e7be94537 100644 --- a/frontend/src/components/CompositionComponent.vue +++ b/frontend/src/components/CompositionComponent.vue @@ -1,3 +1,23 @@ + +

{{ title }}

diff --git a/frontend/src/components/EssentialLink.vue b/frontend/src/components/EssentialLink.vue index c2899650e4..37f4fbef43 100644 --- a/frontend/src/components/EssentialLink.vue +++ b/frontend/src/components/EssentialLink.vue @@ -1,3 +1,23 @@ + +