diff --git a/.ci/php-cs-fixer/composer.lock b/.ci/php-cs-fixer/composer.lock index 7b92c774d2..04ea32ba02 100644 --- a/.ci/php-cs-fixer/composer.lock +++ b/.ci/php-cs-fixer/composer.lock @@ -1257,16 +1257,16 @@ }, { "name": "symfony/console", - "version": "v7.3.1", + "version": "v7.3.2", "source": { "type": "git", "url": "https://github.com/symfony/console.git", - "reference": "9e27aecde8f506ba0fd1d9989620c04a87697101" + "reference": "5f360ebc65c55265a74d23d7fe27f957870158a1" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/console/zipball/9e27aecde8f506ba0fd1d9989620c04a87697101", - "reference": "9e27aecde8f506ba0fd1d9989620c04a87697101", + "url": "https://api.github.com/repos/symfony/console/zipball/5f360ebc65c55265a74d23d7fe27f957870158a1", + "reference": "5f360ebc65c55265a74d23d7fe27f957870158a1", "shasum": "" }, "require": { @@ -1331,7 +1331,7 @@ "terminal" ], "support": { - "source": "https://github.com/symfony/console/tree/v7.3.1" + "source": "https://github.com/symfony/console/tree/v7.3.2" }, "funding": [ { @@ -1342,12 +1342,16 @@ "url": "https://github.com/fabpot", "type": "github" }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, { "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "type": "tidelift" } ], - "time": "2025-06-27T19:55:54+00:00" + "time": "2025-07-30T17:13:41+00:00" }, { "name": "symfony/deprecation-contracts", @@ -1574,16 +1578,16 @@ }, { "name": "symfony/filesystem", - "version": "v7.3.0", + "version": "v7.3.2", "source": { "type": "git", "url": "https://github.com/symfony/filesystem.git", - "reference": "b8dce482de9d7c9fe2891155035a7248ab5c7fdb" + "reference": "edcbb768a186b5c3f25d0643159a787d3e63b7fd" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/filesystem/zipball/b8dce482de9d7c9fe2891155035a7248ab5c7fdb", - "reference": "b8dce482de9d7c9fe2891155035a7248ab5c7fdb", + "url": "https://api.github.com/repos/symfony/filesystem/zipball/edcbb768a186b5c3f25d0643159a787d3e63b7fd", + "reference": "edcbb768a186b5c3f25d0643159a787d3e63b7fd", "shasum": "" }, "require": { @@ -1620,7 +1624,7 @@ "description": "Provides basic utilities for the filesystem", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/filesystem/tree/v7.3.0" + "source": "https://github.com/symfony/filesystem/tree/v7.3.2" }, "funding": [ { @@ -1631,25 +1635,29 @@ "url": "https://github.com/fabpot", "type": "github" }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, { "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "type": "tidelift" } ], - "time": "2024-10-25T15:15:23+00:00" + "time": "2025-07-07T08:17:47+00:00" }, { "name": "symfony/finder", - "version": "v7.3.0", + "version": "v7.3.2", "source": { "type": "git", "url": "https://github.com/symfony/finder.git", - "reference": "ec2344cf77a48253bbca6939aa3d2477773ea63d" + "reference": "2a6614966ba1074fa93dae0bc804227422df4dfe" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/finder/zipball/ec2344cf77a48253bbca6939aa3d2477773ea63d", - "reference": "ec2344cf77a48253bbca6939aa3d2477773ea63d", + "url": "https://api.github.com/repos/symfony/finder/zipball/2a6614966ba1074fa93dae0bc804227422df4dfe", + "reference": "2a6614966ba1074fa93dae0bc804227422df4dfe", "shasum": "" }, "require": { @@ -1684,7 +1692,7 @@ "description": "Finds files and directories via an intuitive fluent interface", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/finder/tree/v7.3.0" + "source": "https://github.com/symfony/finder/tree/v7.3.2" }, "funding": [ { @@ -1695,25 +1703,29 @@ "url": "https://github.com/fabpot", "type": "github" }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, { "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "type": "tidelift" } ], - "time": "2024-12-30T19:00:26+00:00" + "time": "2025-07-15T13:41:35+00:00" }, { "name": "symfony/options-resolver", - "version": "v7.3.0", + "version": "v7.3.2", "source": { "type": "git", "url": "https://github.com/symfony/options-resolver.git", - "reference": "afb9a8038025e5dbc657378bfab9198d75f10fca" + "reference": "119bcf13e67dbd188e5dbc74228b1686f66acd37" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/options-resolver/zipball/afb9a8038025e5dbc657378bfab9198d75f10fca", - "reference": "afb9a8038025e5dbc657378bfab9198d75f10fca", + "url": "https://api.github.com/repos/symfony/options-resolver/zipball/119bcf13e67dbd188e5dbc74228b1686f66acd37", + "reference": "119bcf13e67dbd188e5dbc74228b1686f66acd37", "shasum": "" }, "require": { @@ -1751,7 +1763,7 @@ "options" ], "support": { - "source": "https://github.com/symfony/options-resolver/tree/v7.3.0" + "source": "https://github.com/symfony/options-resolver/tree/v7.3.2" }, "funding": [ { @@ -1762,12 +1774,16 @@ "url": "https://github.com/fabpot", "type": "github" }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, { "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "type": "tidelift" } ], - "time": "2025-04-04T13:12:05+00:00" + "time": "2025-07-15T11:36:08+00:00" }, { "name": "symfony/polyfill-ctype", @@ -2452,16 +2468,16 @@ }, { "name": "symfony/string", - "version": "v7.3.0", + "version": "v7.3.2", "source": { "type": "git", "url": "https://github.com/symfony/string.git", - "reference": "f3570b8c61ca887a9e2938e85cb6458515d2b125" + "reference": "42f505aff654e62ac7ac2ce21033818297ca89ca" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/string/zipball/f3570b8c61ca887a9e2938e85cb6458515d2b125", - "reference": "f3570b8c61ca887a9e2938e85cb6458515d2b125", + "url": "https://api.github.com/repos/symfony/string/zipball/42f505aff654e62ac7ac2ce21033818297ca89ca", + "reference": "42f505aff654e62ac7ac2ce21033818297ca89ca", "shasum": "" }, "require": { @@ -2519,7 +2535,7 @@ "utf8" ], "support": { - "source": "https://github.com/symfony/string/tree/v7.3.0" + "source": "https://github.com/symfony/string/tree/v7.3.2" }, "funding": [ { @@ -2530,12 +2546,16 @@ "url": "https://github.com/fabpot", "type": "github" }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, { "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "type": "tidelift" } ], - "time": "2025-04-20T20:19:01+00:00" + "time": "2025-07-10T08:47:49+00:00" } ], "packages-dev": [], diff --git a/app/Api/V1/Controllers/Autocomplete/AccountController.php b/app/Api/V1/Controllers/Autocomplete/AccountController.php index 3cecdb08a0..56de438135 100644 --- a/app/Api/V1/Controllers/Autocomplete/AccountController.php +++ b/app/Api/V1/Controllers/Autocomplete/AccountController.php @@ -93,14 +93,14 @@ class AccountController extends Controller /** @var Account $account */ foreach ($result as $account) { $nameWithBalance = $account->name; - $currency = $this->repository->getAccountCurrency($account) ?? $this->nativeCurrency; + $currency = $this->repository->getAccountCurrency($account) ?? $this->primaryCurrency; $useCurrency = $currency; if (in_array($account->accountType->type, $this->balanceTypes, true)) { // this one is correct. Log::debug(sprintf('accounts: Call finalAccountBalance with date/time "%s"', $date->toIso8601String())); $balance = Steam::finalAccountBalance($account, $date); - $key = $this->convertToNative && $currency->id !== $this->nativeCurrency->id ? 'native_balance' : 'balance'; - $useCurrency = $this->convertToNative && $currency->id !== $this->nativeCurrency->id ? $this->nativeCurrency : $currency; + $key = $this->convertToPrimary && $currency->id !== $this->primaryCurrency->id ? 'pc_balance' : 'balance'; + $useCurrency = $this->convertToPrimary && $currency->id !== $this->primaryCurrency->id ? $this->primaryCurrency : $currency; $amount = $balance[$key] ?? '0'; $nameWithBalance = sprintf( '%s (%s)', diff --git a/app/Api/V1/Controllers/Chart/AccountController.php b/app/Api/V1/Controllers/Chart/AccountController.php index 60334c6b17..5d8aacc0ec 100644 --- a/app/Api/V1/Controllers/Chart/AccountController.php +++ b/app/Api/V1/Controllers/Chart/AccountController.php @@ -87,7 +87,7 @@ class AccountController extends Controller // move date to end of day $queryParameters['start']->startOfDay(); $queryParameters['end']->endOfDay(); - Log::debug(sprintf('dashboard(), convert to native: %s', var_export($this->convertToNative, true))); + Log::debug(sprintf('dashboard(), convert to primary: %s', var_export($this->convertToPrimary, true))); // loop each account, and collect info: /** @var Account $account */ @@ -107,11 +107,11 @@ class AccountController extends Controller Log::debug(sprintf('Now in %s(array, #%d)', __METHOD__, $account->id)); $currency = $this->repository->getAccountCurrency($account); $currentStart = clone $params['start']; - $range = Steam::finalAccountBalanceInRange($account, $params['start'], clone $params['end'], $this->convertToNative); + $range = Steam::finalAccountBalanceInRange($account, $params['start'], clone $params['end'], $this->convertToPrimary); $previous = array_values($range)[0]['balance']; - $nativePrevious = null; + $pcPrevious = null; if (!$currency instanceof TransactionCurrency) { $currency = $this->default; } @@ -131,13 +131,13 @@ class AccountController extends Controller 'period' => '1D', 'entries' => [], ]; - if ($this->convertToNative) { - $currentSet['native_entries'] = []; - $currentSet['native_currency_id'] = (string)$this->nativeCurrency->id; - $currentSet['native_currency_code'] = $this->nativeCurrency->code; - $currentSet['native_currency_symbol'] = $this->nativeCurrency->symbol; - $currentSet['native_currency_decimal_places'] = $this->nativeCurrency->decimal_places; - $nativePrevious = array_values($range)[0]['native_balance']; + if ($this->convertToPrimary) { + $currentSet['pc_entries'] = []; + $currentSet['primary_currency_id'] = (string)$this->primaryCurrency->id; + $currentSet['primary_currency_code'] = $this->primaryCurrency->code; + $currentSet['primary_currency_symbol'] = $this->primaryCurrency->symbol; + $currentSet['primary_currency_decimal_places'] = $this->primaryCurrency->decimal_places; + $pcPrevious = array_values($range)[0]['pc_balance']; } @@ -149,12 +149,12 @@ class AccountController extends Controller $currentSet['entries'][$label] = $balance; - // do the same for the native balance, if relevant: - $nativeBalance = null; - if ($this->convertToNative) { - $nativeBalance = array_key_exists($format, $range) ? $range[$format]['native_balance'] : $nativePrevious; - $nativePrevious = $nativeBalance; - $currentSet['native_entries'][$label] = $nativeBalance; + // do the same for the primary currency balance, if relevant: + $pcBalance = null; + if ($this->convertToPrimary) { + $pcBalance = array_key_exists($format, $range) ? $range[$format]['pc_balance'] : $pcPrevious; + $pcPrevious = $pcBalance; + $currentSet['pc_entries'][$label] = $pcBalance; } $currentStart->addDay(); @@ -191,11 +191,11 @@ class AccountController extends Controller /** @var Account $account */ foreach ($accounts as $account) { Log::debug(sprintf('Rendering chart data for account %s (%d)', $account->name, $account->id)); - $currency = $this->repository->getAccountCurrency($account) ?? $this->nativeCurrency; + $currency = $this->repository->getAccountCurrency($account) ?? $this->primaryCurrency; $currentStart = clone $start; - $range = Steam::finalAccountBalanceInRange($account, $start, clone $end, $this->convertToNative); + $range = Steam::finalAccountBalanceInRange($account, $start, clone $end, $this->convertToPrimary); $previous = array_values($range)[0]['balance']; - $nativePrevious = null; + $pcPrevious = null; $currentSet = [ 'label' => $account->name, 'currency_id' => (string)$currency->id, @@ -209,18 +209,18 @@ class AccountController extends Controller 'entries' => [], ]; - // add "native_entries" if convertToNative is true: - if ($this->convertToNative) { - $currentSet['native_entries'] = []; - $currentSet['native_currency_id'] = (string)$this->nativeCurrency->id; - $currentSet['native_currency_code'] = $this->nativeCurrency->code; - $currentSet['native_currency_symbol'] = $this->nativeCurrency->symbol; - $currentSet['native_currency_decimal_places'] = $this->nativeCurrency->decimal_places; - $nativePrevious = array_values($range)[0]['native_balance']; + // add "pc_entries" if convertToPrimary is true: + if ($this->convertToPrimary) { + $currentSet['pc_entries'] = []; + $currentSet['primary_currency_id'] = (string)$this->primaryCurrency->id; + $currentSet['primary_currency_code'] = $this->primaryCurrency->code; + $currentSet['primary_currency_symbol'] = $this->primaryCurrency->symbol; + $currentSet['primary_currency_decimal_places'] = $this->primaryCurrency->decimal_places; + $pcPrevious = array_values($range)[0]['pc_balance']; } - // also get the native balance if convertToNative is true: + // also get the primary balance if convertToPrimary is true: while ($currentStart <= $end) { $format = $currentStart->format('Y-m-d'); $label = $currentStart->toAtomString(); @@ -230,12 +230,12 @@ class AccountController extends Controller $previous = $balance; $currentSet['entries'][$label] = $balance; - // do the same for the native balance, if relevant: - $nativeBalance = null; - if ($this->convertToNative) { - $nativeBalance = array_key_exists($format, $range) ? $range[$format]['native_balance'] : $nativePrevious; - $nativePrevious = $nativeBalance; - $currentSet['native_entries'][$label] = $nativeBalance; + // do the same for the primary balance, if relevant: + $pcBalance = null; + if ($this->convertToPrimary) { + $pcBalance = array_key_exists($format, $range) ? $range[$format]['pc_balance'] : $pcPrevious; + $pcPrevious = $pcBalance; + $currentSet['pc_entries'][$label] = $pcBalance; } $currentStart->addDay(); diff --git a/app/Api/V1/Controllers/Chart/BudgetController.php b/app/Api/V1/Controllers/Chart/BudgetController.php index 7035ffe65d..19532d66b1 100644 --- a/app/Api/V1/Controllers/Chart/BudgetController.php +++ b/app/Api/V1/Controllers/Chart/BudgetController.php @@ -264,7 +264,7 @@ class BudgetController extends Controller $compare = bccomp($limit->amount, (string)app('steam')->positive($result[$limitCurrencyId]['spent'])); $result[$limitCurrencyId]['budgeted'] = $limit->amount; if (1 === $compare) { - // convert this amount into the native currency: + // convert this amount into the primary currency: $result[$limitCurrencyId]['left'] = bcadd($limit->amount, (string)$result[$limitCurrencyId]['spent']); } if ($compare <= 0) { @@ -283,17 +283,17 @@ class BudgetController extends Controller /** @var BudgetLimit $current */ foreach ($limits as $current) { - if (true === $this->convertToNative) { - if ($current->transaction_currency_id === $this->nativeCurrency->id) { + if (true === $this->convertToPrimary) { + if ($current->transaction_currency_id === $this->primaryCurrency->id) { // simply add it. $amount = bcadd($amount, (string)$current->amount); Log::debug(sprintf('Set amount in limit to %s', $amount)); } - if ($current->transaction_currency_id !== $this->nativeCurrency->id) { + if ($current->transaction_currency_id !== $this->primaryCurrency->id) { // convert and then add it. - $converted = $converter->convert($current->transactionCurrency, $this->nativeCurrency, $limit->start_date, $limit->amount); + $converted = $converter->convert($current->transactionCurrency, $this->primaryCurrency, $limit->start_date, $limit->amount); $amount = bcadd($amount, $converted); - Log::debug(sprintf('Budgeted in limit #%d: %s %s, converted to %s %s', $current->id, $current->transactionCurrency->code, $current->amount, $this->nativeCurrency->code, $converted)); + Log::debug(sprintf('Budgeted in limit #%d: %s %s, converted to %s %s', $current->id, $current->transactionCurrency->code, $current->amount, $this->primaryCurrency->code, $converted)); Log::debug(sprintf('Set amount in limit to %s', $amount)); } } @@ -301,7 +301,7 @@ class BudgetController extends Controller $limit = $current; } } - if (null !== $limit && true === $this->convertToNative) { + if (null !== $limit && true === $this->convertToPrimary) { // convert and add all amounts. $limit->amount = app('steam')->positive($amount); Log::debug(sprintf('Final amount in limit with converted amount %s', $limit->amount)); diff --git a/app/Api/V1/Controllers/Chart/CategoryController.php b/app/Api/V1/Controllers/Chart/CategoryController.php index 874cad31f1..d67589c2ab 100644 --- a/app/Api/V1/Controllers/Chart/CategoryController.php +++ b/app/Api/V1/Controllers/Chart/CategoryController.php @@ -111,14 +111,14 @@ class CategoryController extends Controller $amount = app('steam')->positive($journal['amount']); // overrule if necessary: - if ($this->convertToNative && $journalCurrencyId !== $this->nativeCurrency->id) { - $currencyId = (int)$this->nativeCurrency->id; - $currencyName = (string)$this->nativeCurrency->name; - $currencyCode = (string)$this->nativeCurrency->code; - $currencySymbol = (string)$this->nativeCurrency->symbol; - $currencyDecimalPlaces = (int)$this->nativeCurrency->decimal_places; - $convertedAmount = $converter->convert($currency, $this->nativeCurrency, $journal['date'], $amount); - Log::debug(sprintf('Converted %s %s to %s %s', $journal['currency_code'], $amount, $this->nativeCurrency->code, $convertedAmount)); + if ($this->convertToPrimary && $journalCurrencyId !== $this->primaryCurrency->id) { + $currencyId = (int)$this->primaryCurrency->id; + $currencyName = (string)$this->primaryCurrency->name; + $currencyCode = (string)$this->primaryCurrency->code; + $currencySymbol = (string)$this->primaryCurrency->symbol; + $currencyDecimalPlaces = (int)$this->primaryCurrency->decimal_places; + $convertedAmount = $converter->convert($currency, $this->primaryCurrency, $journal['date'], $amount); + Log::debug(sprintf('Converted %s %s to %s %s', $journal['currency_code'], $amount, $this->primaryCurrency->code, $convertedAmount)); $amount = $convertedAmount; } diff --git a/app/Api/V1/Controllers/Controller.php b/app/Api/V1/Controllers/Controller.php index 13c06b5972..0bbdb3a248 100644 --- a/app/Api/V1/Controllers/Controller.php +++ b/app/Api/V1/Controllers/Controller.php @@ -68,8 +68,8 @@ abstract class Controller extends BaseController /** @var array */ protected array $allowedSort; - protected bool $convertToNative = false; - protected TransactionCurrency $nativeCurrency; + protected bool $convertToPrimary = false; + protected TransactionCurrency $primaryCurrency; protected ParameterBag $parameters; /** @@ -84,8 +84,8 @@ abstract class Controller extends BaseController $this->parameters = $this->getParameters(); if (auth()->check()) { $language = Steam::getLanguage(); - $this->convertToNative = Amount::convertToNative(); - $this->nativeCurrency = Amount::getNativeCurrency(); + $this->convertToPrimary = Amount::convertToPrimary(); + $this->primaryCurrency = Amount::getPrimaryCurrency(); app()->setLocale($language); } diff --git a/app/Api/V1/Controllers/Insight/Expense/BillController.php b/app/Api/V1/Controllers/Insight/Expense/BillController.php index 4858e0c965..9fd29558b0 100644 --- a/app/Api/V1/Controllers/Insight/Expense/BillController.php +++ b/app/Api/V1/Controllers/Insight/Expense/BillController.php @@ -69,8 +69,8 @@ class BillController extends Controller $bills = $request->getBills(); $start = $request->getStart(); $end = $request->getEnd(); - $convertToNative = Amount::convertToNative(); - $default = Amount::getNativeCurrency(); + $convertToPrimary = Amount::convertToPrimary(); + $primary = Amount::getPrimaryCurrency(); $response = []; // get all bills: @@ -90,14 +90,14 @@ class BillController extends Controller $currencyCode = $journal['currency_code']; $field = 'amount'; - // use the native amount if the user wants to convert to native currency - if ($convertToNative && $currencyId !== $default->id) { - $currencyId = $default->id; - $currencyCode = $default->code; - $field = 'native_amount'; + // use the primary amount if the user wants to convert to primary currency + if ($convertToPrimary && $currencyId !== $primary->id) { + $currencyId = $primary->id; + $currencyCode = $primary->code; + $field = 'pc_amount'; } // use foreign amount when the foreign currency IS the default currency. - if ($convertToNative && $journal['currency_id'] !== $default->id && $default->id === $journal['foreign_currency_id']) { + if ($convertToPrimary && $journal['currency_id'] !== $primary->id && $primary->id === $journal['foreign_currency_id']) { $field = 'foreign_amount'; } Log::debug(sprintf('Journal #%d in bill #%d will use %s (%s %s)', $journal['transaction_group_id'], $billId, $field, $currencyCode, $journal[$field] ?? '0')); @@ -132,8 +132,8 @@ class BillController extends Controller $accounts = $request->getAssetAccounts(); $start = $request->getStart(); $end = $request->getEnd(); - $convertToNative = Amount::convertToNative(); - $default = Amount::getNativeCurrency(); + $convertToPrimary = Amount::convertToPrimary(); + $primary = Amount::getPrimaryCurrency(); $response = []; // collect all expenses in this period (regardless of type) by the given bills and accounts. @@ -148,14 +148,14 @@ class BillController extends Controller $currencyCode = $journal['currency_code']; $field = 'amount'; - // use the native amount if the user wants to convert to native currency - if ($convertToNative && $currencyId !== $default->id) { - $currencyId = $default->id; - $currencyCode = $default->code; - $field = 'native_amount'; + // use the primary amount if the user wants to convert to primary currency + if ($convertToPrimary && $currencyId !== $primary->id) { + $currencyId = $primary->id; + $currencyCode = $primary->code; + $field = 'pc_amount'; } // use foreign amount when the foreign currency IS the default currency. - if ($convertToNative && $journal['currency_id'] !== $default->id && $default->id === $journal['foreign_currency_id']) { + if ($convertToPrimary && $journal['currency_id'] !== $primary->id && $primary->id === $journal['foreign_currency_id']) { $field = 'foreign_amount'; } Log::debug(sprintf('Journal #%d will use %s (%s %s)', $journal['transaction_group_id'], $field, $currencyCode, $journal[$field] ?? '0')); diff --git a/app/Api/V1/Controllers/Insight/Expense/PeriodController.php b/app/Api/V1/Controllers/Insight/Expense/PeriodController.php index 3b5316dd10..d0f383e254 100644 --- a/app/Api/V1/Controllers/Insight/Expense/PeriodController.php +++ b/app/Api/V1/Controllers/Insight/Expense/PeriodController.php @@ -47,8 +47,8 @@ class PeriodController extends Controller $start = $request->getStart(); $end = $request->getEnd(); $response = []; - $convertToNative = Amount::convertToNative(); - $default = Amount::getNativeCurrency(); + $convertToPrimary = Amount::convertToPrimary(); + $primary = Amount::getPrimaryCurrency(); // collect all expenses in this period (regardless of type) $collector = app(GroupCollectorInterface::class); @@ -59,19 +59,19 @@ class PeriodController extends Controller $amount = '0'; $currencyId = (int) $journal['currency_id']; $currencyCode = $journal['currency_code']; - if ($convertToNative) { + if ($convertToPrimary) { $amount = Amount::getAmountFromJournal($journal); - if ($default->id !== (int) $journal['currency_id'] && $default->id !== (int) $journal['foreign_currency_id']) { - $currencyId = $default->id; - $currencyCode = $default->code; + if ($primary->id !== (int) $journal['currency_id'] && $primary->id !== (int) $journal['foreign_currency_id']) { + $currencyId = $primary->id; + $currencyCode = $primary->code; } - if ($default->id !== (int) $journal['currency_id'] && $default->id === (int) $journal['foreign_currency_id']) { + if ($primary->id !== (int) $journal['currency_id'] && $primary->id === (int) $journal['foreign_currency_id']) { $currencyId = $journal['foreign_currency_id']; $currencyCode = $journal['foreign_currency_code']; } Log::debug(sprintf('[a] Add amount %s %s', $currencyCode, $amount)); } - if (!$convertToNative) { + if (!$convertToPrimary) { // ignore the amount in foreign currency. Log::debug(sprintf('[b] Add amount %s %s', $currencyCode, $journal['amount'])); $amount = $journal['amount']; diff --git a/app/Api/V1/Controllers/Insight/Expense/TagController.php b/app/Api/V1/Controllers/Insight/Expense/TagController.php index 2e140656fe..c0fb8c8290 100644 --- a/app/Api/V1/Controllers/Insight/Expense/TagController.php +++ b/app/Api/V1/Controllers/Insight/Expense/TagController.php @@ -68,8 +68,8 @@ class TagController extends Controller $start = $request->getStart(); $end = $request->getEnd(); $response = []; - $convertToNative = Amount::convertToNative(); - $default = Amount::getNativeCurrency(); + $convertToPrimary = Amount::convertToPrimary(); + $primary = Amount::getPrimaryCurrency(); // collect all expenses in this period (regardless of type) by the given bills and accounts. $collector = app(GroupCollectorInterface::class); @@ -83,19 +83,19 @@ class TagController extends Controller $amount = '0'; $currencyId = (int) $journal['currency_id']; $currencyCode = $journal['currency_code']; - if ($convertToNative) { + if ($convertToPrimary) { $amount = Amount::getAmountFromJournal($journal); - if ($default->id !== (int) $journal['currency_id'] && $default->id !== (int) $journal['foreign_currency_id']) { - $currencyId = $default->id; - $currencyCode = $default->code; + if ($primary->id !== (int) $journal['currency_id'] && $primary->id !== (int) $journal['foreign_currency_id']) { + $currencyId = $primary->id; + $currencyCode = $primary->code; } - if ($default->id !== (int) $journal['currency_id'] && $default->id === (int) $journal['foreign_currency_id']) { + if ($primary->id !== (int) $journal['currency_id'] && $primary->id === (int) $journal['foreign_currency_id']) { $currencyId = $journal['foreign_currency_id']; $currencyCode = $journal['foreign_currency_code']; } Log::debug(sprintf('[a] Add amount %s %s', $currencyCode, $amount)); } - if (!$convertToNative) { + if (!$convertToPrimary) { // ignore the amount in foreign currency. Log::debug(sprintf('[b] Add amount %s %s', $currencyCode, $journal['amount'])); $amount = $journal['amount']; diff --git a/app/Api/V1/Controllers/Insight/Income/PeriodController.php b/app/Api/V1/Controllers/Insight/Income/PeriodController.php index d11e93829b..d24ccfe981 100644 --- a/app/Api/V1/Controllers/Insight/Income/PeriodController.php +++ b/app/Api/V1/Controllers/Insight/Income/PeriodController.php @@ -46,8 +46,8 @@ class PeriodController extends Controller $start = $request->getStart(); $end = $request->getEnd(); $response = []; - $convertToNative = Amount::convertToNative(); - $default = Amount::getNativeCurrency(); + $convertToPrimary = Amount::convertToPrimary(); + $primary = Amount::getPrimaryCurrency(); // collect all expenses in this period (regardless of type) $collector = app(GroupCollectorInterface::class); @@ -57,15 +57,15 @@ class PeriodController extends Controller // currency $currencyId = $journal['currency_id']; $currencyCode = $journal['currency_code']; - $field = $convertToNative && $currencyId !== $default->id ? 'native_amount' : 'amount'; + $field = $convertToPrimary && $currencyId !== $primary->id ? 'pc_amount' : 'amount'; // perhaps use default currency instead? - if ($convertToNative && $journal['currency_id'] !== $default->id) { - $currencyId = $default->id; - $currencyCode = $default->code; + if ($convertToPrimary && $journal['currency_id'] !== $primary->id) { + $currencyId = $primary->id; + $currencyCode = $primary->code; } // use foreign amount when the foreign currency IS the default currency. - if ($convertToNative && $journal['currency_id'] !== $default->id && $default->id === $journal['foreign_currency_id']) { + if ($convertToPrimary && $journal['currency_id'] !== $primary->id && $primary->id === $journal['foreign_currency_id']) { $field = 'foreign_amount'; } diff --git a/app/Api/V1/Controllers/Insight/Income/TagController.php b/app/Api/V1/Controllers/Insight/Income/TagController.php index 1f127f298d..65690326b0 100644 --- a/app/Api/V1/Controllers/Insight/Income/TagController.php +++ b/app/Api/V1/Controllers/Insight/Income/TagController.php @@ -68,8 +68,8 @@ class TagController extends Controller $start = $request->getStart(); $end = $request->getEnd(); $response = []; - $convertToNative = Amount::convertToNative(); - $default = Amount::getNativeCurrency(); + $convertToPrimary = Amount::convertToPrimary(); + $primary = Amount::getPrimaryCurrency(); // collect all expenses in this period (regardless of type) by the given bills and accounts. $collector = app(GroupCollectorInterface::class); @@ -82,15 +82,15 @@ class TagController extends Controller // currency $currencyId = $journal['currency_id']; $currencyCode = $journal['currency_code']; - $field = $convertToNative && $currencyId !== $default->id ? 'native_amount' : 'amount'; + $field = $convertToPrimary && $currencyId !== $primary->id ? 'pc_amount' : 'amount'; // perhaps use default currency instead? - if ($convertToNative && $journal['currency_id'] !== $default->id) { - $currencyId = $default->id; - $currencyCode = $default->code; + if ($convertToPrimary && $journal['currency_id'] !== $primary->id) { + $currencyId = $primary->id; + $currencyCode = $primary->code; } // use foreign amount when the foreign currency IS the default currency. - if ($convertToNative && $journal['currency_id'] !== $default->id && $default->id === $journal['foreign_currency_id']) { + if ($convertToPrimary && $journal['currency_id'] !== $primary->id && $primary->id === $journal['foreign_currency_id']) { $field = 'foreign_amount'; } diff --git a/app/Api/V1/Controllers/Insight/Transfer/PeriodController.php b/app/Api/V1/Controllers/Insight/Transfer/PeriodController.php index d35c2b74df..87e5738f3e 100644 --- a/app/Api/V1/Controllers/Insight/Transfer/PeriodController.php +++ b/app/Api/V1/Controllers/Insight/Transfer/PeriodController.php @@ -46,8 +46,8 @@ class PeriodController extends Controller $start = $request->getStart(); $end = $request->getEnd(); $response = []; - $convertToNative = Amount::convertToNative(); - $default = Amount::getNativeCurrency(); + $convertToPrimary = Amount::convertToPrimary(); + $primary = Amount::getPrimaryCurrency(); // collect all expenses in this period (regardless of type) $collector = app(GroupCollectorInterface::class); @@ -57,15 +57,15 @@ class PeriodController extends Controller // currency $currencyId = $journal['currency_id']; $currencyCode = $journal['currency_code']; - $field = $convertToNative && $currencyId !== $default->id ? 'native_amount' : 'amount'; + $field = $convertToPrimary && $currencyId !== $primary->id ? 'pc_amount' : 'amount'; // perhaps use default currency instead? - if ($convertToNative && $journal['currency_id'] !== $default->id) { - $currencyId = $default->id; - $currencyCode = $default->code; + if ($convertToPrimary && $journal['currency_id'] !== $primary->id) { + $currencyId = $primary->id; + $currencyCode = $primary->code; } // use foreign amount when the foreign currency IS the default currency. - if ($convertToNative && $journal['currency_id'] !== $default->id && $default->id === $journal['foreign_currency_id']) { + if ($convertToPrimary && $journal['currency_id'] !== $primary->id && $primary->id === $journal['foreign_currency_id']) { $field = 'foreign_amount'; } diff --git a/app/Api/V1/Controllers/Insight/Transfer/TagController.php b/app/Api/V1/Controllers/Insight/Transfer/TagController.php index f0c02a2df5..4af2c733ca 100644 --- a/app/Api/V1/Controllers/Insight/Transfer/TagController.php +++ b/app/Api/V1/Controllers/Insight/Transfer/TagController.php @@ -66,8 +66,8 @@ class TagController extends Controller $start = $request->getStart(); $end = $request->getEnd(); $response = []; - $convertToNative = Amount::convertToNative(); - $default = Amount::getNativeCurrency(); + $convertToPrimary = Amount::convertToPrimary(); + $primary = Amount::getPrimaryCurrency(); // collect all expenses in this period (regardless of type) by the given bills and accounts. @@ -81,15 +81,15 @@ class TagController extends Controller // currency $currencyId = $journal['currency_id']; $currencyCode = $journal['currency_code']; - $field = $convertToNative && $currencyId !== $default->id ? 'native_amount' : 'amount'; + $field = $convertToPrimary && $currencyId !== $primary->id ? 'pc_amount' : 'amount'; // perhaps use default currency instead? - if ($convertToNative && $journal['currency_id'] !== $default->id) { - $currencyId = $default->id; - $currencyCode = $default->code; + if ($convertToPrimary && $journal['currency_id'] !== $primary->id) { + $currencyId = $primary->id; + $currencyCode = $primary->code; } // use foreign amount when the foreign currency IS the default currency. - if ($convertToNative && $journal['currency_id'] !== $default->id && $default->id === $journal['foreign_currency_id']) { + if ($convertToPrimary && $journal['currency_id'] !== $primary->id && $primary->id === $journal['foreign_currency_id']) { $field = 'foreign_amount'; } diff --git a/app/Api/V1/Controllers/Models/Account/ShowController.php b/app/Api/V1/Controllers/Models/Account/ShowController.php index 3fe8919495..4d7a836f78 100644 --- a/app/Api/V1/Controllers/Models/Account/ShowController.php +++ b/app/Api/V1/Controllers/Models/Account/ShowController.php @@ -97,7 +97,7 @@ class ShowController extends Controller $admin = auth()->user(); $enrichment = new AccountEnrichment(); $enrichment->setUser($admin); - $enrichment->setNative($this->nativeCurrency); + $enrichment->setPrimary($this->primaryCurrency); $accounts = $enrichment->enrich($accounts); // make paginator: @@ -132,7 +132,7 @@ class ShowController extends Controller $admin = auth()->user(); $enrichment = new AccountEnrichment(); $enrichment->setUser($admin); - $enrichment->setNative($this->nativeCurrency); + $enrichment->setPrimary($this->primaryCurrency); $account = $enrichment->enrichSingle($account); diff --git a/app/Api/V1/Controllers/Models/Account/StoreController.php b/app/Api/V1/Controllers/Models/Account/StoreController.php index 3b8b21d17e..800aab67aa 100644 --- a/app/Api/V1/Controllers/Models/Account/StoreController.php +++ b/app/Api/V1/Controllers/Models/Account/StoreController.php @@ -76,7 +76,7 @@ class StoreController extends Controller $admin = auth()->user(); $enrichment = new AccountEnrichment(); $enrichment->setUser($admin); - $enrichment->setNative($this->nativeCurrency); + $enrichment->setPrimary($this->primaryCurrency); $account = $enrichment->enrichSingle($account); /** @var AccountTransformer $transformer */ diff --git a/app/Api/V1/Controllers/Models/Account/UpdateController.php b/app/Api/V1/Controllers/Models/Account/UpdateController.php index 40dc574663..51de7f0427 100644 --- a/app/Api/V1/Controllers/Models/Account/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Account/UpdateController.php @@ -81,7 +81,7 @@ class UpdateController extends Controller $admin = auth()->user(); $enrichment = new AccountEnrichment(); $enrichment->setUser($admin); - $enrichment->setNative($this->nativeCurrency); + $enrichment->setPrimary($this->primaryCurrency); $account = $enrichment->enrichSingle($account); /** @var AccountTransformer $transformer */ diff --git a/app/Api/V1/Controllers/Models/Bill/ShowController.php b/app/Api/V1/Controllers/Models/Bill/ShowController.php index 2b2988aa79..4b18216168 100644 --- a/app/Api/V1/Controllers/Models/Bill/ShowController.php +++ b/app/Api/V1/Controllers/Models/Bill/ShowController.php @@ -83,8 +83,8 @@ class ShowController extends Controller $admin = auth()->user(); $enrichment = new SubscriptionEnrichment(); $enrichment->setUser($admin); - $enrichment->setConvertToNative($this->convertToNative); - $enrichment->setNative($this->nativeCurrency); + $enrichment->setConvertToPrimary($this->convertToPrimary); + $enrichment->setPrimary($this->primaryCurrency); $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); $bills = $enrichment->enrich($bills); @@ -114,8 +114,8 @@ class ShowController extends Controller $admin = auth()->user(); $enrichment = new SubscriptionEnrichment(); $enrichment->setUser($admin); - $enrichment->setConvertToNative($this->convertToNative); - $enrichment->setNative($this->nativeCurrency); + $enrichment->setConvertToPrimary($this->convertToPrimary); + $enrichment->setPrimary($this->primaryCurrency); $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); $bill = $enrichment->enrichSingle($bill); diff --git a/app/Api/V1/Controllers/Models/Bill/StoreController.php b/app/Api/V1/Controllers/Models/Bill/StoreController.php index 98b02558b2..3d2f2a238b 100644 --- a/app/Api/V1/Controllers/Models/Bill/StoreController.php +++ b/app/Api/V1/Controllers/Models/Bill/StoreController.php @@ -79,8 +79,8 @@ class StoreController extends Controller $admin = auth()->user(); $enrichment = new SubscriptionEnrichment(); $enrichment->setUser($admin); - $enrichment->setConvertToNative($this->convertToNative); - $enrichment->setNative($this->nativeCurrency); + $enrichment->setConvertToPrimary($this->convertToPrimary); + $enrichment->setPrimary($this->primaryCurrency); $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); $bill = $enrichment->enrichSingle($bill); diff --git a/app/Api/V1/Controllers/Models/Bill/UpdateController.php b/app/Api/V1/Controllers/Models/Bill/UpdateController.php index f41907b137..79b6659524 100644 --- a/app/Api/V1/Controllers/Models/Bill/UpdateController.php +++ b/app/Api/V1/Controllers/Models/Bill/UpdateController.php @@ -74,8 +74,8 @@ class UpdateController extends Controller $admin = auth()->user(); $enrichment = new SubscriptionEnrichment(); $enrichment->setUser($admin); - $enrichment->setConvertToNative($this->convertToNative); - $enrichment->setNative($this->nativeCurrency); + $enrichment->setConvertToPrimary($this->convertToPrimary); + $enrichment->setPrimary($this->primaryCurrency); $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); $bill = $enrichment->enrichSingle($bill); diff --git a/app/Api/V1/Controllers/Models/ObjectGroup/ListController.php b/app/Api/V1/Controllers/Models/ObjectGroup/ListController.php index e24ed1013b..709b92369d 100644 --- a/app/Api/V1/Controllers/Models/ObjectGroup/ListController.php +++ b/app/Api/V1/Controllers/Models/ObjectGroup/ListController.php @@ -85,8 +85,8 @@ class ListController extends Controller $admin = auth()->user(); $enrichment = new SubscriptionEnrichment(); $enrichment->setUser($admin); - $enrichment->setConvertToNative($this->convertToNative); - $enrichment->setNative($this->nativeCurrency); + $enrichment->setConvertToPrimary($this->convertToPrimary); + $enrichment->setPrimary($this->primaryCurrency); $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); $bills = $enrichment->enrich($bills); diff --git a/app/Api/V1/Controllers/Models/PiggyBank/ListController.php b/app/Api/V1/Controllers/Models/PiggyBank/ListController.php index 610927fe9b..615896eee3 100644 --- a/app/Api/V1/Controllers/Models/PiggyBank/ListController.php +++ b/app/Api/V1/Controllers/Models/PiggyBank/ListController.php @@ -84,7 +84,7 @@ class ListController extends Controller $admin = auth()->user(); $enrichment = new AccountEnrichment(); $enrichment->setUser($admin); - $enrichment->setNative($this->nativeCurrency); + $enrichment->setPrimary($this->primaryCurrency); $accounts = $enrichment->enrich($accounts); // make paginator: diff --git a/app/Api/V1/Controllers/Models/TransactionCurrency/ListController.php b/app/Api/V1/Controllers/Models/TransactionCurrency/ListController.php index 6e5331a67c..07376b4b47 100644 --- a/app/Api/V1/Controllers/Models/TransactionCurrency/ListController.php +++ b/app/Api/V1/Controllers/Models/TransactionCurrency/ListController.php @@ -108,7 +108,7 @@ class ListController extends Controller $admin = auth()->user(); $enrichment = new AccountEnrichment(); $enrichment->setUser($admin); - $enrichment->setNative($this->nativeCurrency); + $enrichment->setPrimary($this->primaryCurrency); $accounts = $enrichment->enrich($accounts); // make paginator: @@ -188,8 +188,8 @@ class ListController extends Controller $admin = auth()->user(); $enrichment = new SubscriptionEnrichment(); $enrichment->setUser($admin); - $enrichment->setConvertToNative($this->convertToNative); - $enrichment->setNative($this->nativeCurrency); + $enrichment->setConvertToPrimary($this->convertToPrimary); + $enrichment->setPrimary($this->primaryCurrency); $enrichment->setStart($this->parameters->get('start')); $enrichment->setEnd($this->parameters->get('end')); $bills = $enrichment->enrichSingle($bills); diff --git a/app/Api/V1/Controllers/Models/TransactionCurrency/ShowController.php b/app/Api/V1/Controllers/Models/TransactionCurrency/ShowController.php index 2283b5da50..73b6b1de3e 100644 --- a/app/Api/V1/Controllers/Models/TransactionCurrency/ShowController.php +++ b/app/Api/V1/Controllers/Models/TransactionCurrency/ShowController.php @@ -107,7 +107,7 @@ class ShowController extends Controller /** @var User $user */ $user = auth()->user(); $manager = $this->getManager(); - $this->parameters->set('nativeCurrency', $this->nativeCurrency); + $this->parameters->set('primaryCurrency', $this->primaryCurrency); // update fields with user info. $currency->refreshForUser($user); @@ -122,9 +122,6 @@ class ShowController extends Controller } /** - * This endpoint is documented at: - * https://api-docs.firefly-iii.org/?urls.primaryName=2.0.0%20(v1)#/currencies/getNativeCurrency - * * Show a currency. * * @throws FireflyException @@ -134,7 +131,7 @@ class ShowController extends Controller /** @var User $user */ $user = auth()->user(); $manager = $this->getManager(); - $currency = $this->nativeCurrency; + $currency = $this->primaryCurrency; // update fields with user info. $currency->refreshForUser($user); diff --git a/app/Api/V1/Controllers/Models/TransactionCurrency/UpdateController.php b/app/Api/V1/Controllers/Models/TransactionCurrency/UpdateController.php index 16c6ba78cf..2516a34c67 100644 --- a/app/Api/V1/Controllers/Models/TransactionCurrency/UpdateController.php +++ b/app/Api/V1/Controllers/Models/TransactionCurrency/UpdateController.php @@ -99,11 +99,6 @@ class UpdateController extends Controller } /** - * This endpoint is documented at: - * https://api-docs.firefly-iii.org/?urls.primaryName=2.0.0%20(v1)#/currencies/nativeCurrency - * - * Make the currency a default currency. - * * @throws FireflyException */ public function makeDefault(TransactionCurrency $currency): JsonResponse diff --git a/app/Api/V1/Controllers/Search/AccountController.php b/app/Api/V1/Controllers/Search/AccountController.php index 634c666db3..018646f68a 100644 --- a/app/Api/V1/Controllers/Search/AccountController.php +++ b/app/Api/V1/Controllers/Search/AccountController.php @@ -89,7 +89,7 @@ class AccountController extends Controller $admin = auth()->user(); $enrichment = new AccountEnrichment(); $enrichment->setUser($admin); - $enrichment->setNative($this->nativeCurrency); + $enrichment->setPrimary($this->primaryCurrency); $accounts = $enrichment->enrich($accounts); /** @var AccountTransformer $transformer */ diff --git a/app/Api/V1/Controllers/Summary/BasicController.php b/app/Api/V1/Controllers/Summary/BasicController.php index 02b7bc0405..b64d5c7f3f 100644 --- a/app/Api/V1/Controllers/Summary/BasicController.php +++ b/app/Api/V1/Controllers/Summary/BasicController.php @@ -127,13 +127,13 @@ class BasicController extends Controller { Log::debug('getBalanceInformation'); // some config settings - $convertToNative = Amount::convertToNative(); - $default = Amount::getNativeCurrency(); + $convertToPrimary = Amount::convertToPrimary(); + $primary = Amount::getPrimaryCurrency(); // prep some arrays: $sums = []; $return = []; $currencies = [ - $default->id => $default, + $primary->id => $primary, ]; // collect income of user using the new group collector. @@ -151,32 +151,32 @@ class BasicController extends Controller $set = $collector->setRange($start, $end)->setPage($this->parameters->get('page'))->setTypes([TransactionTypeEnum::WITHDRAWAL->value])->getExtractedJournals(); $expenses = $summarizer->groupByCurrencyId($set, 'negative', false); - // if convert to native, do so right now. - if ($convertToNative) { + // if convert to primary, do so right now. + if ($convertToPrimary) { $newExpenses = [ - $default->id => [ - 'currency_id' => $default->id, - 'currency_code' => $default->code, - 'currency_symbol' => $default->symbol, - 'currency_decimal_places' => $default->decimal_places, + $primary->id => [ + 'currency_id' => $primary->id, + 'currency_code' => $primary->code, + 'currency_symbol' => $primary->symbol, + 'currency_decimal_places' => $primary->decimal_places, 'sum' => '0', ], ]; $newIncomes = [ - $default->id => [ - 'currency_id' => $default->id, - 'currency_code' => $default->code, - 'currency_symbol' => $default->symbol, - 'currency_decimal_places' => $default->decimal_places, + $primary->id => [ + 'currency_id' => $primary->id, + 'currency_code' => $primary->code, + 'currency_symbol' => $primary->symbol, + 'currency_decimal_places' => $primary->decimal_places, 'sum' => '0', ], ]; $sums = [ - $default->id => [ - 'currency_id' => $default->id, - 'currency_code' => $default->code, - 'currency_symbol' => $default->symbol, - 'currency_decimal_places' => $default->decimal_places, + $primary->id => [ + 'currency_id' => $primary->id, + 'currency_code' => $primary->code, + 'currency_symbol' => $primary->symbol, + 'currency_decimal_places' => $primary->decimal_places, 'sum' => '0', ], ]; @@ -188,36 +188,36 @@ class BasicController extends Controller // loop over either one. foreach ($array as $entry) { - // if it is the native currency already. - if ($entry['currency_id'] === $default->id) { - $sums[$default->id]['sum'] = bcadd((string) $entry['sum'], $sums[$default->id]['sum']); + // if it is the primary currency already. + if ($entry['currency_id'] === $primary->id) { + $sums[$primary->id]['sum'] = bcadd((string) $entry['sum'], $sums[$primary->id]['sum']); // don't forget to add it to newExpenses and newIncome if (0 === $index) { - $newExpenses[$default->id]['sum'] = bcadd($newExpenses[$default->id]['sum'], (string) $entry['sum']); + $newExpenses[$primary->id]['sum'] = bcadd($newExpenses[$primary->id]['sum'], (string) $entry['sum']); } if (1 === $index) { - $newIncomes[$default->id]['sum'] = bcadd($newIncomes[$default->id]['sum'], (string) $entry['sum']); + $newIncomes[$primary->id]['sum'] = bcadd($newIncomes[$primary->id]['sum'], (string) $entry['sum']); } continue; } $currencies[$entry['currency_id']] ??= $this->currencyRepos->find($entry['currency_id']); - $convertedSum = $converter->convert($currencies[$entry['currency_id']], $default, $start, $entry['sum']); - $sums[$default->id]['sum'] = bcadd($sums[$default->id]['sum'], $convertedSum); + $convertedSum = $converter->convert($currencies[$entry['currency_id']], $primary, $start, $entry['sum']); + $sums[$primary->id]['sum'] = bcadd($sums[$primary->id]['sum'], $convertedSum); if (0 === $index) { - $newExpenses[$default->id]['sum'] = bcadd($newExpenses[$default->id]['sum'], $convertedSum); + $newExpenses[$primary->id]['sum'] = bcadd($newExpenses[$primary->id]['sum'], $convertedSum); } if (1 === $index) { - $newIncomes[$default->id]['sum'] = bcadd($newIncomes[$default->id]['sum'], $convertedSum); + $newIncomes[$primary->id]['sum'] = bcadd($newIncomes[$primary->id]['sum'], $convertedSum); } } } $incomes = $newIncomes; $expenses = $newExpenses; } - if (!$convertToNative) { + if (!$convertToPrimary) { foreach ([$expenses, $incomes] as $array) { foreach ($array as $entry) { $currencyId = $entry['currency_id']; @@ -279,7 +279,7 @@ class BasicController extends Controller ]; } if (0 === count($return)) { - $currency = $this->nativeCurrency; + $currency = $this->primaryCurrency; // create objects for big array. $return[] = [ 'key' => sprintf('balance-in-%s', $currency->code), @@ -333,26 +333,26 @@ class BasicController extends Controller $paidAmount = $this->billRepository->sumPaidInRange($start, $end); $unpaidAmount = $this->billRepository->sumUnpaidInRange($start, $end); $currencies = [ - $this->nativeCurrency->id => $this->nativeCurrency, + $this->primaryCurrency->id => $this->primaryCurrency, ]; - if ($this->convertToNative) { + if ($this->convertToPrimary) { $converter = new ExchangeRateConverter(); $newPaidAmount = [[ - 'id' => $this->nativeCurrency->id, - 'name' => $this->nativeCurrency->name, - 'symbol' => $this->nativeCurrency->symbol, - 'code' => $this->nativeCurrency->code, - 'decimal_places' => $this->nativeCurrency->decimal_places, + 'id' => $this->primaryCurrency->id, + 'name' => $this->primaryCurrency->name, + 'symbol' => $this->primaryCurrency->symbol, + 'code' => $this->primaryCurrency->code, + 'decimal_places' => $this->primaryCurrency->decimal_places, 'sum' => '0', ]]; $newUnpaidAmount = [[ - 'id' => $this->nativeCurrency->id, - 'name' => $this->nativeCurrency->name, - 'symbol' => $this->nativeCurrency->symbol, - 'code' => $this->nativeCurrency->code, - 'decimal_places' => $this->nativeCurrency->decimal_places, + 'id' => $this->primaryCurrency->id, + 'name' => $this->primaryCurrency->name, + 'symbol' => $this->primaryCurrency->symbol, + 'code' => $this->primaryCurrency->code, + 'decimal_places' => $this->primaryCurrency->decimal_places, 'sum' => '0', ]]; foreach ([$paidAmount, $unpaidAmount] as $index => $array) { @@ -360,25 +360,25 @@ class BasicController extends Controller $currencyId = (int) $item['id']; if (0 === $index) { // paid amount - if ($currencyId === $this->nativeCurrency->id) { + if ($currencyId === $this->primaryCurrency->id) { $newPaidAmount[0]['sum'] = bcadd($newPaidAmount[0]['sum'], (string) $item['sum']); continue; } $currencies[$currencyId] ??= $this->currencyRepos->find($currencyId); - $convertedAmount = $converter->convert($currencies[$currencyId], $this->nativeCurrency, $start, $item['sum']); + $convertedAmount = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $item['sum']); $newPaidAmount[0]['sum'] = bcadd($newPaidAmount[0]['sum'], $convertedAmount); continue; } // unpaid amount - if ($currencyId === $this->nativeCurrency->id) { + if ($currencyId === $this->primaryCurrency->id) { $newUnpaidAmount[0]['sum'] = bcadd($newUnpaidAmount[0]['sum'], (string) $item['sum']); continue; } $currencies[$currencyId] ??= $this->currencyRepos->find($currencyId); - $convertedAmount = $converter->convert($currencies[$currencyId], $this->nativeCurrency, $start, $item['sum']); + $convertedAmount = $converter->convert($currencies[$currencyId], $this->primaryCurrency, $start, $item['sum']); $newUnpaidAmount[0]['sum'] = bcadd($newUnpaidAmount[0]['sum'], $convertedAmount); } } @@ -432,7 +432,7 @@ class BasicController extends Controller Log::debug(sprintf('Done with getBillInformation("%s", "%s")', $start->format('Y-m-d'), $end->format('Y-m-d-'))); if (0 === count($return)) { - $currency = $this->nativeCurrency; + $currency = $this->primaryCurrency; unset($info, $amount); $return[] = [ @@ -577,7 +577,7 @@ class BasicController extends Controller // $amount = '0'; // // $days // // fill in by money spent, just count it. - // $currency = $this->nativeCurrency; + // $currency = $this->primaryCurrency; // $return[$currency->id] = [ // 'key' => sprintf('left-to-spend-in-%s', $currency->code), // 'title' => trans('firefly.box_left_to_spend_in_currency', ['currency' => $currency->symbol]), @@ -626,7 +626,7 @@ class BasicController extends Controller $netWorthSet = $netWorthHelper->byAccounts($filtered, $end); $return = []; foreach ($netWorthSet as $key => $data) { - if ('native' === $key) { + if ('pc' === $key) { continue; } $amount = $data['balance']; @@ -649,14 +649,14 @@ class BasicController extends Controller } if (0 === count($return)) { $return[] = [ - 'key' => sprintf('net-worth-in-%s', $this->nativeCurrency->code), - 'title' => trans('firefly.box_net_worth_in_currency', ['currency' => $this->nativeCurrency->symbol]), + 'key' => sprintf('net-worth-in-%s', $this->primaryCurrency->code), + 'title' => trans('firefly.box_net_worth_in_currency', ['currency' => $this->primaryCurrency->symbol]), 'monetary_value' => '0', - 'currency_id' => (string) $this->nativeCurrency->id, - 'currency_code' => $this->nativeCurrency->code, - 'currency_symbol' => $this->nativeCurrency->symbol, - 'currency_decimal_places' => $this->nativeCurrency->decimal_places, - 'value_parsed' => app('amount')->formatFlat($this->nativeCurrency->symbol, $this->nativeCurrency->decimal_places, '0', false), + 'currency_id' => (string) $this->primaryCurrency->id, + 'currency_code' => $this->primaryCurrency->code, + 'currency_symbol' => $this->primaryCurrency->symbol, + 'currency_decimal_places' => $this->primaryCurrency->decimal_places, + 'value_parsed' => app('amount')->formatFlat($this->primaryCurrency->symbol, $this->primaryCurrency->decimal_places, '0', false), 'local_icon' => 'line-chart', 'sub_title' => '', ]; diff --git a/app/Api/V1/Controllers/User/PreferencesController.php b/app/Api/V1/Controllers/User/PreferencesController.php index 091bc389f7..d2040588e3 100644 --- a/app/Api/V1/Controllers/User/PreferencesController.php +++ b/app/Api/V1/Controllers/User/PreferencesController.php @@ -85,7 +85,7 @@ class PreferencesController extends Controller $manager = $this->getManager(); if ('currencyPreference' === $preference->name) { - throw new FireflyException('Please use api/v1/currencies/native instead.'); + throw new FireflyException('Please use api/v1/currencies/primary instead.'); } /** @var PreferenceTransformer $transformer */ @@ -132,7 +132,7 @@ class PreferencesController extends Controller public function update(PreferenceUpdateRequest $request, Preference $preference): JsonResponse { if ('currencyPreference' === $preference->name) { - throw new FireflyException('Please use api/v1/currencies/native instead.'); + throw new FireflyException('Please use api/v1/currencies/primary instead.'); } $manager = $this->getManager(); diff --git a/app/Api/V1/Requests/Models/UserGroup/UpdateRequest.php b/app/Api/V1/Requests/Models/UserGroup/UpdateRequest.php index d14e47a982..3ed9995765 100644 --- a/app/Api/V1/Requests/Models/UserGroup/UpdateRequest.php +++ b/app/Api/V1/Requests/Models/UserGroup/UpdateRequest.php @@ -40,8 +40,8 @@ class UpdateRequest extends FormRequest { $fields = [ 'title' => ['title', 'convertString'], - 'native_currency_id' => ['native_currency_id', 'convertInteger'], - 'native_currency_code' => ['native_currency_code', 'convertString'], + 'primary_currency_id' => ['primary_currency_id', 'convertInteger'], + 'primary_currency_code' => ['primary_currency_code', 'convertString'], ]; return $this->getAllData($fields); @@ -54,8 +54,8 @@ class UpdateRequest extends FormRequest { return [ 'title' => ['required', 'min:1', 'max:255'], - 'native_currency_id' => 'exists:transaction_currencies,id', - 'native_currency_code' => 'exists:transaction_currencies,code', + 'primary_currency_id' => 'exists:transaction_currencies,id', + 'primary_currency_code' => 'exists:transaction_currencies,code', ]; } } diff --git a/app/Api/V2/Controllers/Autocomplete/AccountController.php b/app/Api/V2/Controllers/Autocomplete/AccountController.php deleted file mode 100644 index b267c1a09c..0000000000 --- a/app/Api/V2/Controllers/Autocomplete/AccountController.php +++ /dev/null @@ -1,140 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Autocomplete; - -use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Api\V2\Request\Autocomplete\AutocompleteRequest; -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\Account; -use FireflyIII\Models\AccountBalance; -use FireflyIII\Models\TransactionCurrency; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; -use FireflyIII\Support\Http\Api\ExchangeRateConverter; -use Illuminate\Http\JsonResponse; -use Illuminate\Support\Facades\Log; - -/** - * Class AccountController - */ -class AccountController extends Controller -{ - private ExchangeRateConverter $converter; - private TransactionCurrency $default; - private AccountRepositoryInterface $repository; - - /** - * AccountController constructor. - */ - public function __construct() - { - parent::__construct(); - $this->middleware( - function ($request, $next) { - $userGroup = $this->validateUserGroup($request); - $this->repository = app(AccountRepositoryInterface::class); - $this->repository->setUserGroup($userGroup); - $this->default = app('amount')->getNativeCurrency(); - $this->converter = app(ExchangeRateConverter::class); - - return $next($request); - } - ); - } - - /** - * Documentation: https://api-docs.firefly-iii.org/?urls.primaryName=2.1.0%20(v2)#/autocomplete/getAccountsAC - */ - public function accounts(AutocompleteRequest $request): JsonResponse - { - $params = $request->getParameters(); - $result = $this->repository->searchAccount($params['query'], $params['account_types'], $params['size']); - $return = []; - - /** @var Account $account */ - foreach ($result as $account) { - $return[] = $this->parseAccount($account); - } - - return response()->json($return); - } - - private function parseAccount(Account $account): array - { - $currency = $this->repository->getAccountCurrency($account); - - return [ - 'id' => (string) $account->id, - 'title' => $account->name, - 'meta' => [ - 'type' => $account->accountType->type, - // TODO is multi currency property. - 'currency_id' => $currency instanceof TransactionCurrency ? (string) $currency->id : null, - 'currency_code' => $currency?->code, - 'currency_symbol' => $currency?->symbol, - 'currency_decimal_places' => $currency?->decimal_places, - 'account_balances' => $this->getAccountBalances($account), - ], - ]; - } - - private function getAccountBalances(Account $account): array - { - $return = []; - $balances = $this->repository->getAccountBalances($account); - - /** @var AccountBalance $balance */ - foreach ($balances as $balance) { - try { - $return[] = $this->parseAccountBalance($balance); - } catch (FireflyException $e) { - Log::error(sprintf('Could not parse convert account balance: %s', $e->getMessage())); - } - } - - return $return; - } - - /** - * @throws FireflyException - */ - private function parseAccountBalance(AccountBalance $balance): array - { - $currency = $balance->transactionCurrency; - - return [ - 'title' => $balance->title, - 'native_amount' => $this->converter->convert($currency, $this->default, today(), $balance->balance), - 'amount' => app('steam')->bcround($balance->balance, $currency->decimal_places), - 'currency_id' => (string) $currency->id, - 'currency_code' => $currency->code, - 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => $currency->decimal_places, - 'native_currency_id' => (string) $this->default->id, - 'native_currency_code' => $this->default->code, - 'native_currency_symbol' => $this->default->symbol, - 'native_currency_decimal_places' => $this->default->decimal_places, - ]; - } -} diff --git a/app/Api/V2/Controllers/Autocomplete/CategoryController.php b/app/Api/V2/Controllers/Autocomplete/CategoryController.php deleted file mode 100644 index ea3635be5f..0000000000 --- a/app/Api/V2/Controllers/Autocomplete/CategoryController.php +++ /dev/null @@ -1,73 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Autocomplete; - -use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Api\V2\Request\Autocomplete\AutocompleteRequest; -use FireflyIII\Models\Category; -use FireflyIII\Repositories\Category\CategoryRepositoryInterface; -use Illuminate\Http\JsonResponse; - -/** - * Class CategoryController - */ -class CategoryController extends Controller -{ - private CategoryRepositoryInterface $repository; - - /** - * AccountController constructor. - */ - public function __construct() - { - parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(CategoryRepositoryInterface::class); - $this->repository->setUserGroup($this->validateUserGroup($request)); - - return $next($request); - } - ); - } - - /** - * Documentation: https://api-docs.firefly-iii.org/?urls.primaryName=2.1.0%20(v2)#/autocomplete/getCategoriesAC - */ - public function categories(AutocompleteRequest $request): JsonResponse - { - $queryParameters = $request->getParameters(); - $result = $this->repository->searchCategory($queryParameters['query'], $queryParameters['size']); - $filtered = $result->map( - static fn (Category $item) => [ - 'id' => (string) $item->id, - 'title' => $item->name, - 'meta' => [], - ] - ); - - return response()->json($filtered); - } -} diff --git a/app/Api/V2/Controllers/Autocomplete/TagController.php b/app/Api/V2/Controllers/Autocomplete/TagController.php deleted file mode 100644 index 92a620bcdd..0000000000 --- a/app/Api/V2/Controllers/Autocomplete/TagController.php +++ /dev/null @@ -1,75 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Autocomplete; - -use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Api\V2\Request\Autocomplete\AutocompleteRequest; -use FireflyIII\Models\Tag; -use FireflyIII\Repositories\Tag\TagRepositoryInterface; -use Illuminate\Http\JsonResponse; - -/** - * Class TagController - */ -class TagController extends Controller -{ - private TagRepositoryInterface $repository; - - /** - * AccountController constructor. - */ - public function __construct() - { - parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(TagRepositoryInterface::class); - $this->repository->setUserGroup($this->validateUserGroup($request)); - - return $next($request); - } - ); - } - - /** - * Documentation: https://api-docs.firefly-iii.org/?urls.primaryName=2.1.0%20(v2)#/autocomplete/getTagsAC - */ - public function tags(AutocompleteRequest $request): JsonResponse - { - $queryParameters = $request->getParameters(); - $result = $this->repository->searchTag($queryParameters['query']); - $filtered = $result->map( - static fn (Tag $item) => [ - 'id' => (string) $item->id, - 'title' => $item->tag, - 'value' => (string) $item->id, - 'label' => $item->tag, - 'meta' => [], - ] - ); - - return response()->json($filtered); - } -} diff --git a/app/Api/V2/Controllers/Autocomplete/TransactionController.php b/app/Api/V2/Controllers/Autocomplete/TransactionController.php deleted file mode 100644 index 3ff8780201..0000000000 --- a/app/Api/V2/Controllers/Autocomplete/TransactionController.php +++ /dev/null @@ -1,81 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Autocomplete; - -use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Api\V2\Request\Autocomplete\AutocompleteRequest; -use FireflyIII\Models\TransactionJournal; -use FireflyIII\Repositories\Journal\JournalRepositoryInterface; -use Illuminate\Http\JsonResponse; - -/** - * Class TransactionController - */ -class TransactionController extends Controller -{ - private JournalRepositoryInterface $repository; - - /** - * AccountController constructor. - */ - public function __construct() - { - parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(JournalRepositoryInterface::class); - $this->repository->setUserGroup($this->validateUserGroup($request)); - - return $next($request); - } - ); - } - - /** - * Documentation: https://api-docs.firefly-iii.org/?urls.primaryName=2.1.0%20(v2)#/autocomplete/getTransactionsAC - */ - public function transactionDescriptions(AutocompleteRequest $request): JsonResponse - { - $queryParameters = $request->getParameters(); - $result = $this->repository->searchJournalDescriptions($queryParameters['query'], $queryParameters['size']); - - // limit and unique - $filtered = $result->unique('description'); - $array = []; - - /** @var TransactionJournal $journal */ - foreach ($filtered as $journal) { - $array[] = [ - 'id' => (string) $journal->id, - 'title' => $journal->description, - 'meta' => [ - 'transaction_group_id' => (string) $journal->transaction_group_id, - ], - ]; - } - - return response()->json($array); - } -} diff --git a/app/Api/V2/Controllers/Chart/AccountController.php b/app/Api/V2/Controllers/Chart/AccountController.php deleted file mode 100644 index 7f273cae3f..0000000000 --- a/app/Api/V2/Controllers/Chart/AccountController.php +++ /dev/null @@ -1,140 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Chart; - -use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Api\V2\Request\Chart\ChartRequest; -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\Account; -use FireflyIII\Models\TransactionCurrency; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; -use FireflyIII\Support\Chart\ChartData; -use FireflyIII\Support\Facades\Steam; -use FireflyIII\Support\Http\Api\CleansChartData; -use FireflyIII\Support\Http\Api\CollectsAccountsFromFilter; -use FireflyIII\Support\Http\Api\ValidatesUserGroupTrait; -use Illuminate\Http\JsonResponse; - -/** - * Class AccountController - */ -class AccountController extends Controller -{ - use CleansChartData; - use CollectsAccountsFromFilter; - use ValidatesUserGroupTrait; - - private ChartData $chartData; - private TransactionCurrency $default; - private AccountRepositoryInterface $repository; - - public function __construct() - { - parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(AccountRepositoryInterface::class); - $this->repository->setUserGroup($this->validateUserGroup($request)); - $this->chartData = new ChartData(); - $this->default = app('amount')->getNativeCurrency(); - - return $next($request); - } - ); - } - - /** - * TODO fix documentation - * - * @throws FireflyException - */ - public function dashboard(ChartRequest $request): JsonResponse - { - $queryParameters = $request->getParameters(); - $accounts = $this->getAccountList($queryParameters); - - // move date to end of day - $queryParameters['start']->startOfDay(); - $queryParameters['end']->endOfDay(); - - // loop each account, and collect info: - /** @var Account $account */ - foreach ($accounts as $account) { - $this->renderAccountData($queryParameters, $account); - } - - return response()->json($this->chartData->render()); - } - - /** - * @throws FireflyException - */ - private function renderAccountData(array $params, Account $account): void - { - $currency = $this->repository->getAccountCurrency($account); - if (!$currency instanceof TransactionCurrency) { - $currency = $this->default; - } - $currentSet = [ - 'label' => $account->name, - - // the currency that belongs to the account. - 'currency_id' => (string) $currency->id, - 'currency_code' => $currency->code, - 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => $currency->decimal_places, - - // the default currency of the user (could be the same!) - 'native_currency_id' => (string) $this->default->id, - 'native_currency_code' => $this->default->code, - 'native_currency_symbol' => $this->default->symbol, - 'native_currency_decimal_places' => $this->default->decimal_places, - 'date' => $params['start']->toAtomString(), - 'start' => $params['start']->toAtomString(), - 'end' => $params['end']->toAtomString(), - 'period' => '1D', - 'entries' => [], - 'native_entries' => [], - ]; - $currentStart = clone $params['start']; - $range = Steam::finalAccountBalanceInRange($account, $params['start'], clone $params['end'], $this->convertToNative); - - $previous = array_values($range)[0]['balance']; - $previousNative = array_values($range)[0]['native_balance']; - while ($currentStart <= $params['end']) { - $format = $currentStart->format('Y-m-d'); - $label = $currentStart->toAtomString(); - $balance = array_key_exists($format, $range) ? $range[$format]['balance'] : $previous; - $balanceNative = array_key_exists($format, $range) ? $range[$format]['balance_native'] : $previousNative; - $previous = $balance; - $previousNative = $balanceNative; - - $currentStart->addDay(); - $currentSet['entries'][$label] = $balance; - $currentSet['native_entries'][$label] = $balanceNative; - } - $this->chartData->add($currentSet); - } -} diff --git a/app/Api/V2/Controllers/Chart/BalanceController.php b/app/Api/V2/Controllers/Chart/BalanceController.php deleted file mode 100644 index 85aec5c6e3..0000000000 --- a/app/Api/V2/Controllers/Chart/BalanceController.php +++ /dev/null @@ -1,116 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Chart; - -use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Api\V2\Request\Chart\ChartRequest; -use FireflyIII\Enums\TransactionTypeEnum; -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Helpers\Collector\GroupCollectorInterface; -use FireflyIII\Models\TransactionCurrency; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; -use FireflyIII\Support\Chart\ChartData; -use FireflyIII\Support\Http\Api\AccountBalanceGrouped; -use FireflyIII\Support\Http\Api\CleansChartData; -use FireflyIII\Support\Http\Api\CollectsAccountsFromFilter; -use Illuminate\Http\JsonResponse; - -/** - * Class BalanceController - */ -class BalanceController extends Controller -{ - use CleansChartData; - use CollectsAccountsFromFilter; - - private ChartData $chartData; - private GroupCollectorInterface $collector; - private AccountRepositoryInterface $repository; - - // private TransactionCurrency $default; - - public function __construct() - { - parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(AccountRepositoryInterface::class); - $this->collector = app(GroupCollectorInterface::class); - $userGroup = $this->validateUserGroup($request); - $this->repository->setUserGroup($userGroup); - $this->collector->setUserGroup($userGroup); - $this->chartData = new ChartData(); - // $this->default = app('amount')->getNativeCurrency(); - - return $next($request); - } - ); - } - - /** - * The code is practically a duplicate of ReportController::operations. - * - * Currency is up to the account/transactions in question, but conversion to the default - * currency is possible. - * - * If the transaction being processed is already in native currency OR if the - * foreign amount is in the native currency, the amount will not be converted. - * - * @throws FireflyException - */ - public function balance(ChartRequest $request): JsonResponse - { - $queryParameters = $request->getParameters(); - $accounts = $this->getAccountList($queryParameters); - - // prepare for currency conversion and data collection: - /** @var TransactionCurrency $default */ - $default = app('amount')->getNativeCurrency(); - - // get journals for entire period: - - $this->collector->setRange($queryParameters['start'], $queryParameters['end']) - ->withAccountInformation() - ->setXorAccounts($accounts) - ->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::RECONCILIATION->value, TransactionTypeEnum::TRANSFER->value]) - ; - $journals = $this->collector->getExtractedJournals(); - - $object = new AccountBalanceGrouped(); - $object->setPreferredRange($queryParameters['period']); - $object->setDefault($default); - $object->setAccounts($accounts); - $object->setJournals($journals); - $object->setStart($queryParameters['start']); - $object->setEnd($queryParameters['end']); - $object->groupByCurrencyAndPeriod(); - $data = $object->convertToChartData(); - foreach ($data as $entry) { - $this->chartData->add($entry); - } - - return response()->json($this->chartData->render()); - } -} diff --git a/app/Api/V2/Controllers/Chart/BudgetController.php b/app/Api/V2/Controllers/Chart/BudgetController.php deleted file mode 100644 index 9ef001cc77..0000000000 --- a/app/Api/V2/Controllers/Chart/BudgetController.php +++ /dev/null @@ -1,293 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Chart; - -use Carbon\Carbon; -use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Api\V2\Request\Generic\DateRequest; -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\Budget; -use FireflyIII\Models\BudgetLimit; -use FireflyIII\Models\TransactionCurrency; -use FireflyIII\Repositories\Budget\BudgetLimitRepositoryInterface; -use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; -use FireflyIII\Repositories\Budget\OperationsRepositoryInterface; -use FireflyIII\Support\Http\Api\CleansChartData; -use FireflyIII\Support\Http\Api\ExchangeRateConverter; -use FireflyIII\Support\Http\Api\ValidatesUserGroupTrait; -use Illuminate\Http\JsonResponse; -use Illuminate\Support\Collection; -use Illuminate\Support\Facades\Log; - -/** - * Class BudgetController - */ -class BudgetController extends Controller -{ - use CleansChartData; - use ValidatesUserGroupTrait; - - protected OperationsRepositoryInterface $opsRepository; - private BudgetLimitRepositoryInterface $blRepository; - private array $currencies = []; - private TransactionCurrency $currency; - private BudgetRepositoryInterface $repository; - - public function __construct() - { - parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(BudgetRepositoryInterface::class); - $this->blRepository = app(BudgetLimitRepositoryInterface::class); - $this->opsRepository = app(OperationsRepositoryInterface::class); - $this->currency = app('amount')->getNativeCurrency(); - $userGroup = $this->validateUserGroup($request); - $this->repository->setUserGroup($userGroup); - $this->opsRepository->setUserGroup($userGroup); - - return $next($request); - } - ); - } - - /** - * TODO see autocomplete/accountcontroller - */ - public function dashboard(DateRequest $request): JsonResponse - { - $params = $request->getAll(); - - /** @var Carbon $start */ - $start = $params['start']; - - /** @var Carbon $end */ - $end = $params['end']; - - // code from FrontpageChartGenerator, but not in separate class - $budgets = $this->repository->getActiveBudgets(); - $data = []; - - /** @var Budget $budget */ - foreach ($budgets as $budget) { - // could return multiple arrays, so merge. - $data = array_merge($data, $this->processBudget($budget, $start, $end)); - } - - return response()->json($this->clean($data)); - } - - /** - * @throws FireflyException - */ - private function processBudget(Budget $budget, Carbon $start, Carbon $end): array - { - // get all limits: - $limits = $this->blRepository->getBudgetLimits($budget, $start, $end); - $rows = []; - - // if no limits - if (0 === $limits->count()) { - // return as a single item in an array - $rows = $this->noBudgetLimits($budget, $start, $end); - } - if ($limits->count() > 0) { - $rows = $this->budgetLimits($budget, $limits); - } - // is always an array - $return = []; - foreach ($rows as $row) { - $current = [ - 'label' => $budget->name, - 'currency_id' => (string) $row['currency_id'], - 'currency_code' => $row['currency_code'], - 'currency_name' => $row['currency_name'], - 'currency_decimal_places' => $row['currency_decimal_places'], - 'native_currency_id' => (string) $row['native_currency_id'], - 'native_currency_code' => $row['native_currency_code'], - 'native_currency_name' => $row['native_currency_name'], - 'native_currency_decimal_places' => $row['native_currency_decimal_places'], - 'period' => null, - 'start' => $row['start'], - 'end' => $row['end'], - 'entries' => [ - 'spent' => $row['spent'], - 'left' => $row['left'], - 'overspent' => $row['overspent'], - ], - 'native_entries' => [ - 'spent' => $row['native_spent'], - 'left' => $row['native_left'], - 'overspent' => $row['native_overspent'], - ], - ]; - $return[] = $current; - } - - return $return; - } - - /** - * When no budget limits are present, the expenses of the whole period are collected and grouped. - * This is grouped per currency. Because there is no limit set, "left to spend" and "overspent" are empty. - * - * @throws FireflyException - */ - private function noBudgetLimits(Budget $budget, Carbon $start, Carbon $end): array - { - $spent = $this->opsRepository->listExpenses($start, $end, null, new Collection([$budget])); - - return $this->processExpenses($budget->id, $spent, $start, $end); - } - - /** - * Shared between the "noBudgetLimits" function and "processLimit". Will take a single set of expenses and return - * its info. - * - * @param array> $array - * - * @throws FireflyException - */ - private function processExpenses(int $budgetId, array $array, Carbon $start, Carbon $end): array - { - Log::debug(sprintf('Created new ExchangeRateConverter in %s', __METHOD__)); - $converter = new ExchangeRateConverter(); - $return = []; - - /** - * This array contains the expenses in this budget. Grouped per currency. - * The grouping is on the main currency only. - * - * @var int $currencyId - * @var array $block - */ - foreach ($array as $currencyId => $block) { - $this->currencies[$currencyId] ??= TransactionCurrency::find($currencyId); - $return[$currencyId] ??= [ - 'currency_id' => (string) $currencyId, - 'currency_code' => $block['currency_code'], - 'currency_name' => $block['currency_name'], - 'currency_symbol' => $block['currency_symbol'], - 'currency_decimal_places' => (int) $block['currency_decimal_places'], - 'native_currency_id' => (string) $this->currency->id, - 'native_currency_code' => $this->currency->code, - 'native_currency_name' => $this->currency->name, - 'native_currency_symbol' => $this->currency->symbol, - 'native_currency_decimal_places' => $this->currency->decimal_places, - 'start' => $start->toAtomString(), - 'end' => $end->toAtomString(), - 'spent' => '0', - 'native_spent' => '0', - 'left' => '0', - 'native_left' => '0', - 'overspent' => '0', - 'native_overspent' => '0', - ]; - $currentBudgetArray = $block['budgets'][$budgetId]; - - // var_dump($return); - /** @var array $journal */ - foreach ($currentBudgetArray['transaction_journals'] as $journal) { - // convert the amount to the native currency. - $rate = $converter->getCurrencyRate($this->currencies[$currencyId], $this->currency, $journal['date']); - $convertedAmount = bcmul((string) $journal['amount'], $rate); - if ($journal['foreign_currency_id'] === $this->currency->id) { - $convertedAmount = $journal['foreign_amount']; - } - - $return[$currencyId]['spent'] = bcadd($return[$currencyId]['spent'], (string) $journal['amount']); - $return[$currencyId]['native_spent'] = bcadd($return[$currencyId]['native_spent'], (string) $convertedAmount); - } - } - $converter->summarize(); - - return $return; - } - - /** - * Function that processes each budget limit (per budget). - * - * If you have a budget limit in EUR, only transactions in EUR will be considered. - * If you have a budget limit in GBP, only transactions in GBP will be considered. - * - * If you have a budget limit in EUR, and a transaction in GBP, it will not be considered for the EUR budget limit. - * - * @throws FireflyException - */ - private function budgetLimits(Budget $budget, Collection $limits): array - { - app('log')->debug(sprintf('Now in budgetLimits(#%d)', $budget->id)); - $data = []; - - /** @var BudgetLimit $limit */ - foreach ($limits as $limit) { - $data = array_merge($data, $this->processLimit($budget, $limit)); - } - - return $data; - } - - /** - * @throws FireflyException - */ - private function processLimit(Budget $budget, BudgetLimit $limit): array - { - Log::debug(sprintf('Created new ExchangeRateConverter in %s', __METHOD__)); - $end = clone $limit->end_date; - $end->endOfDay(); - $spent = $this->opsRepository->listExpenses($limit->start_date, $end, null, new Collection([$budget])); - $limitCurrencyId = $limit->transaction_currency_id; - $limitCurrency = $limit->transactionCurrency; - $converter = new ExchangeRateConverter(); - $filtered = []; - $rate = $converter->getCurrencyRate($limitCurrency, $this->currency, $limit->start_date); - $convertedLimitAmount = bcmul($limit->amount, $rate); - - /** @var array $entry */ - foreach ($spent as $currencyId => $entry) { - // only spent the entry where the entry's currency matches the budget limit's currency - // so $filtered will only have 1 or 0 entries - if ($entry['currency_id'] === $limitCurrencyId) { - $filtered[$currencyId] = $entry; - } - } - $result = $this->processExpenses($budget->id, $filtered, $limit->start_date, $end); - if (1 === count($result)) { - $compare = bccomp($limit->amount, (string) app('steam')->positive($result[$limitCurrencyId]['spent'])); - if (1 === $compare) { - // convert this amount into the native currency: - $result[$limitCurrencyId]['left'] = bcadd($limit->amount, (string) $result[$limitCurrencyId]['spent']); - $result[$limitCurrencyId]['native_left'] = bcadd($convertedLimitAmount, (string) $result[$limitCurrencyId]['native_spent']); - } - if ($compare <= 0) { - $result[$limitCurrencyId]['overspent'] = app('steam')->positive(bcadd($limit->amount, (string) $result[$limitCurrencyId]['spent'])); - $result[$limitCurrencyId]['native_overspent'] = app('steam')->positive(bcadd($convertedLimitAmount, (string) $result[$limitCurrencyId]['native_spent'])); - } - } - $converter->summarize(); - - return $result; - } -} diff --git a/app/Api/V2/Controllers/Chart/CategoryController.php b/app/Api/V2/Controllers/Chart/CategoryController.php deleted file mode 100644 index e259739805..0000000000 --- a/app/Api/V2/Controllers/Chart/CategoryController.php +++ /dev/null @@ -1,142 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Chart; - -use Carbon\Carbon; -use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Api\V2\Request\Generic\DateRequest; -use FireflyIII\Enums\AccountTypeEnum; -use FireflyIII\Enums\TransactionTypeEnum; -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Helpers\Collector\GroupCollectorInterface; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; -use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; -use FireflyIII\Support\Http\Api\CleansChartData; -use FireflyIII\Support\Http\Api\ExchangeRateConverter; -use FireflyIII\Support\Http\Api\ValidatesUserGroupTrait; -use Illuminate\Http\JsonResponse; -use Illuminate\Support\Facades\Log; - -/** - * Class BudgetController - */ -class CategoryController extends Controller -{ - use CleansChartData; - use ValidatesUserGroupTrait; - - private AccountRepositoryInterface $accountRepos; - private CurrencyRepositoryInterface $currencyRepos; - - public function __construct() - { - parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->accountRepos = app(AccountRepositoryInterface::class); - $this->currencyRepos = app(CurrencyRepositoryInterface::class); - $this->accountRepos->setUserGroup($this->validateUserGroup($request)); - - return $next($request); - } - ); - } - - /** - * TODO may be worth to move to a handler but the data is simple enough. - * TODO see autoComplete/account controller - * - * @throws FireflyException - * - * @SuppressWarnings("PHPMD.UnusedFormalParameter") - */ - public function dashboard(DateRequest $request): JsonResponse - { - Log::debug(sprintf('Created new ExchangeRateConverter in %s', __METHOD__)); - - /** @var Carbon $start */ - $start = $this->parameters->get('start'); - - /** @var Carbon $end */ - $end = $this->parameters->get('end'); - $accounts = $this->accountRepos->getAccountsByType([AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::ASSET->value, AccountTypeEnum::DEFAULT->value]); - $default = app('amount')->getNativeCurrency(); - $converter = new ExchangeRateConverter(); - $currencies = []; - $return = []; - - // get journals for entire period: - /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); - $collector->setRange($start, $end)->withAccountInformation(); - $collector->setXorAccounts($accounts)->withCategoryInformation(); - $collector->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::RECONCILIATION->value]); - $journals = $collector->getExtractedJournals(); - - /** @var array $journal */ - foreach ($journals as $journal) { - $currencyId = (int) $journal['currency_id']; - $currency = $currencies[$currencyId] ?? $this->currencyRepos->find($currencyId); - $currencies[$currencyId] = $currency; - $categoryName = $journal['category_name'] ?? (string) trans('firefly.no_category'); - $amount = app('steam')->positive($journal['amount']); - $nativeAmount = $converter->convert($default, $currency, $journal['date'], $amount); - $key = sprintf('%s-%s', $categoryName, $currency->code); - if ((int) $journal['foreign_currency_id'] === $default->id) { - $nativeAmount = app('steam')->positive($journal['foreign_amount']); - } - // create arrays - $return[$key] ??= [ - 'label' => $categoryName, - 'currency_id' => (string) $currency->id, - 'currency_code' => $currency->code, - 'currency_name' => $currency->name, - 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => $currency->decimal_places, - 'native_currency_id' => (string) $default->id, - 'native_currency_code' => $default->code, - 'native_currency_name' => $default->name, - 'native_currency_symbol' => $default->symbol, - 'native_currency_decimal_places' => $default->decimal_places, - 'period' => null, - 'start' => $start->toAtomString(), - 'end' => $end->toAtomString(), - 'amount' => '0', - 'native_amount' => '0', - ]; - - // add monies - $return[$key]['amount'] = bcadd($return[$key]['amount'], (string) $amount); - $return[$key]['native_amount'] = bcadd($return[$key]['native_amount'], (string) $nativeAmount); - } - $return = array_values($return); - - // order by native amount - usort($return, static fn (array $a, array $b) => (float) $a['native_amount'] < (float) $b['native_amount'] ? 1 : -1); - $converter->summarize(); - - return response()->json($this->clean($return)); - } -} diff --git a/app/Api/V2/Controllers/Controller.php b/app/Api/V2/Controllers/Controller.php deleted file mode 100644 index 6117197914..0000000000 --- a/app/Api/V2/Controllers/Controller.php +++ /dev/null @@ -1,195 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers; - -use Carbon\Carbon; -use Carbon\Exceptions\InvalidDateException; -use Carbon\Exceptions\InvalidFormatException; -use FireflyIII\Enums\UserRoleEnum; -use FireflyIII\Support\Http\Api\ValidatesUserGroupTrait; -use FireflyIII\Transformers\AbstractTransformer; -use Illuminate\Database\Eloquent\Model; -use Illuminate\Pagination\LengthAwarePaginator; -use Illuminate\Routing\Controller as BaseController; -use League\Fractal\Manager; -use League\Fractal\Pagination\IlluminatePaginatorAdapter; -use League\Fractal\Resource\Collection as FractalCollection; -use League\Fractal\Resource\Item; -use League\Fractal\Serializer\JsonApiSerializer; -use Psr\Container\ContainerExceptionInterface; -use Symfony\Component\HttpFoundation\Exception\BadRequestException; -use Symfony\Component\HttpFoundation\ParameterBag; - -/** - * Class Controller - * - * @SuppressWarnings("PHPMD.CouplingBetweenObjects") - * @SuppressWarnings("PHPMD.NumberOfChildren") - */ -class Controller extends BaseController -{ - use ValidatesUserGroupTrait; - - protected const string CONTENT_TYPE = 'application/vnd.api+json'; - protected array $acceptedRoles = [UserRoleEnum::READ_ONLY]; - protected bool $convertToNative = false; - protected ParameterBag $parameters; - - public function __construct() - { - $this->middleware( - function ($request, $next) { - $this->parameters = $this->getParameters(); - - return $next($request); - } - ); - } - - /** - * TODO duplicate from V1 controller - * Method to grab all parameters from the URL. - * - * @SuppressWarnings("PHPMD.NPathComplexity") - */ - private function getParameters(): ParameterBag - { - $bag = new ParameterBag(); - $bag->set('limit', 50); - - try { - $page = (int) request()->get('page'); - } catch (ContainerExceptionInterface) { - $page = 1; - } - - $integers = ['limit', 'administration']; - $dates = ['start', 'end', 'date']; - - if ($page < 1) { - $page = 1; - } - if ($page > 2 ** 16) { - $page = 2 ** 16; - } - $bag->set('page', $page); - - // some date fields: - foreach ($dates as $field) { - $date = null; - $obj = null; - - try { - $date = request()->query->get($field); - } catch (BadRequestException $e) { - app('log')->error(sprintf('Request field "%s" contains a non-scalar value. Value set to NULL.', $field)); - app('log')->error($e->getMessage()); - app('log')->error($e->getTraceAsString()); - } - if (null !== $date) { - try { - $obj = Carbon::parse((string) $date, config('app.timezone')); - } catch (InvalidDateException|InvalidFormatException $e) { - // don't care - app('log')->warning(sprintf('Ignored invalid date "%s" in API v2 controller parameter check: %s', substr((string) $date, 0, 20), $e->getMessage())); - } - // out of range? set to null. - if ($obj instanceof Carbon && ($obj->year <= 1970 || $obj->year > 2038)) { - app('log')->warning(sprintf('Refuse to use date "%s" in API v2 controller parameter check: %s', $field, $obj->toAtomString())); - $obj = null; - } - } - if (null !== $date && 'end' === $field) { - $obj->endOfDay(); - } - $bag->set($field, $obj); - } - - // integer fields: - foreach ($integers as $integer) { - try { - $value = request()->query->get($integer); - } catch (BadRequestException $e) { - app('log')->error(sprintf('Request field "%s" contains a non-scalar value. Value set to NULL.', $integer)); - app('log')->error($e->getMessage()); - $value = null; - } - if (null !== $value) { - $bag->set($integer, (int) $value); - } - if (null === $value && 'limit' === $integer && auth()->check()) { - // set default for user: - $pageSize = (int) app('preferences')->getForUser(auth()->user(), 'listPageSize', 50)->data; - $bag->set($integer, $pageSize); - } - } - - // sort fields: - // return $this->getSortParameters($bag); - - return $bag; - } - - final protected function jsonApiList(string $key, LengthAwarePaginator $paginator, AbstractTransformer $transformer): array - { - $manager = new Manager(); - $baseUrl = request()->getSchemeAndHttpHost().'/api/v2'; - - // TODO add stuff to path? - - $manager->setSerializer(new JsonApiSerializer($baseUrl)); - - $objects = $paginator->getCollection(); - - // the transformer, at this point, needs to collect information that ALL items in the collection - // require, like meta-data and stuff like that, and save it for later. - // $objects = $transformer->collectMetaData($objects); - $paginator->setCollection($objects); - - $resource = new FractalCollection($objects, $transformer, $key); - $resource->setPaginator(new IlluminatePaginatorAdapter($paginator)); - - return $manager->createData($resource)->toArray(); - } - - /** - * Returns a JSON API object and returns it. - * - * @param array|Model $object - */ - final protected function jsonApiObject(string $key, array|Model $object, AbstractTransformer $transformer): array - { - // create some objects: - $manager = new Manager(); - $baseUrl = request()->getSchemeAndHttpHost().'/api/v2'; - $manager->setSerializer(new JsonApiSerializer($baseUrl)); - - // $transformer->collectMetaData(new Collection([$object])); - - $resource = new Item($object, $transformer, $key); - - return $manager->createData($resource)->toArray(); - } -} diff --git a/app/Api/V2/Controllers/Data/Bulk/AccountController.php b/app/Api/V2/Controllers/Data/Bulk/AccountController.php deleted file mode 100644 index 3dbfd0343d..0000000000 --- a/app/Api/V2/Controllers/Data/Bulk/AccountController.php +++ /dev/null @@ -1,32 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Data\Bulk; - -use FireflyIII\Api\V2\Controllers\Controller; - -/** - * Class AccountController - */ -class AccountController extends Controller {} diff --git a/app/Api/V2/Controllers/Data/Export/AccountController.php b/app/Api/V2/Controllers/Data/Export/AccountController.php deleted file mode 100644 index 4526f0f399..0000000000 --- a/app/Api/V2/Controllers/Data/Export/AccountController.php +++ /dev/null @@ -1,32 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Data\Export; - -use FireflyIII\Api\V2\Controllers\Controller; - -/** - * Class AccountController - */ -class AccountController extends Controller {} diff --git a/app/Api/V2/Controllers/Data/MassDestroy/AccountController.php b/app/Api/V2/Controllers/Data/MassDestroy/AccountController.php deleted file mode 100644 index 6d11f3473e..0000000000 --- a/app/Api/V2/Controllers/Data/MassDestroy/AccountController.php +++ /dev/null @@ -1,32 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Data\MassDestroy; - -use FireflyIII\Api\V2\Controllers\Controller; - -/** - * Class AccountController - */ -class AccountController extends Controller {} diff --git a/app/Api/V2/Controllers/Model/Account/IndexController.php b/app/Api/V2/Controllers/Model/Account/IndexController.php deleted file mode 100644 index a2960e6673..0000000000 --- a/app/Api/V2/Controllers/Model/Account/IndexController.php +++ /dev/null @@ -1,97 +0,0 @@ -middleware( - function ($request, $next) { - $this->repository = app(AccountRepositoryInterface::class); - // new way of user group validation - $userGroup = $this->validateUserGroup($request); - $this->repository->setUserGroup($userGroup); - - return $next($request); - } - ); - } - - /** - * TODO the sort instructions need proper repeatable documentation. - * TODO see autocomplete/account controller for list. - */ - public function index(IndexRequest $request): JsonResponse - { - $this->repository->resetAccountOrder(); - $types = $request->getAccountTypes(); - $sorting = $request->getSortInstructions('accounts'); - $filters = $request->getFilterInstructions('accounts'); - $accounts = $this->repository->getAccountsByType($types, $sorting); - $pageSize = $this->parameters->get('limit'); - $count = $accounts->count(); - - // depending on the sort parameters, this list must not be split, because the - // order is calculated in the account transformer and by that time it's too late. - $first = array_key_first($sorting); - $disablePagination = in_array($first, ['last_activity', 'balance', 'balance_difference'], true); - Log::debug(sprintf('Will disable pagination in account index v2? %s', var_export($disablePagination, true))); - if (!$disablePagination) { - $accounts = $accounts->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); - } - $paginator = new LengthAwarePaginator($accounts, $count, $pageSize, $this->parameters->get('page')); - $transformer = new AccountTransformer(); - - $this->parameters->set('disablePagination', $disablePagination); - $this->parameters->set('pageSize', $pageSize); - $this->parameters->set('sort', $sorting); - - $this->parameters->set('filters', $filters); - $transformer->setParameters($this->parameters); // give params to transformer - - return response() - ->json($this->jsonApiList('accounts', $paginator, $transformer)) - ->header('Content-Type', self::CONTENT_TYPE) - ; - } -} diff --git a/app/Api/V2/Controllers/Model/Account/ShowController.php b/app/Api/V2/Controllers/Model/Account/ShowController.php deleted file mode 100644 index 13d1f0cd8e..0000000000 --- a/app/Api/V2/Controllers/Model/Account/ShowController.php +++ /dev/null @@ -1,76 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Model\Account; - -use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Enums\UserRoleEnum; -use FireflyIII\Models\Account; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; -use FireflyIII\Transformers\AccountTransformer; -use Illuminate\Http\JsonResponse; - -/** - * Show = show a single account. - * Index = show all accounts - * Class ShowController - */ -class ShowController extends Controller -{ - public const string RESOURCE_KEY = 'accounts'; - protected array $acceptedRoles = [UserRoleEnum::READ_ONLY, UserRoleEnum::MANAGE_TRANSACTIONS]; - private AccountRepositoryInterface $repository; - - /** - * AccountController constructor. - */ - public function __construct() - { - parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(AccountRepositoryInterface::class); - // new way of user group validation - $userGroup = $this->validateUserGroup($request); - $this->repository->setUserGroup($userGroup); - - return $next($request); - } - ); - } - - /** - * TODO this endpoint is not yet reachable. - */ - public function show(Account $account): JsonResponse - { - $transformer = new AccountTransformer(); - $transformer->setParameters($this->parameters); - - return response() - ->api($this->jsonApiObject('accounts', $account, $transformer)) - ->header('Content-Type', self::CONTENT_TYPE) - ; - } -} diff --git a/app/Api/V2/Controllers/Model/Account/UpdateController.php b/app/Api/V2/Controllers/Model/Account/UpdateController.php deleted file mode 100644 index 49c0f8d5b9..0000000000 --- a/app/Api/V2/Controllers/Model/Account/UpdateController.php +++ /dev/null @@ -1,76 +0,0 @@ -middleware( - function ($request, $next) { - $this->repository = app(AccountRepositoryInterface::class); - $this->repository->setUserGroup($this->validateUserGroup($request)); - - return $next($request); - } - ); - } - - /** - * TODO this endpoint is not yet reachable. - */ - public function update(UpdateRequest $request, Account $account): JsonResponse - { - app('log')->debug(sprintf('Now in %s', __METHOD__)); - $data = $request->getUpdateData(); - $data['type'] = config('firefly.shortNamesByFullName.'.$account->accountType->type); - $account = $this->repository->update($account, $data); - $account->refresh(); - app('preferences')->mark(); - - $transformer = new AccountTransformer(); - $transformer->setParameters($this->parameters); - - return response() - ->api($this->jsonApiObject('accounts', $account, $transformer)) - ->header('Content-Type', self::CONTENT_TYPE) - ; - } -} diff --git a/app/Api/V2/Controllers/Model/Bill/IndexController.php b/app/Api/V2/Controllers/Model/Bill/IndexController.php deleted file mode 100644 index bf09a6360b..0000000000 --- a/app/Api/V2/Controllers/Model/Bill/IndexController.php +++ /dev/null @@ -1,75 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Model\Bill; - -use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Repositories\Bill\BillRepositoryInterface; -use FireflyIII\Support\Http\Api\ValidatesUserGroupTrait; -use FireflyIII\Transformers\BillTransformer; -use Illuminate\Http\JsonResponse; -use Illuminate\Pagination\LengthAwarePaginator; - -/** - * Class ShowController - */ -class IndexController extends Controller -{ - use ValidatesUserGroupTrait; - - private BillRepositoryInterface $repository; - - public function __construct() - { - parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(BillRepositoryInterface::class); - $this->repository->setUserGroup($this->validateUserGroup($request)); - - return $next($request); - } - ); - } - - /** - * TODO see autocomplete/accountcontroller for list. - */ - public function index(): JsonResponse - { - $this->repository->correctOrder(); - $bills = $this->repository->getBills(); - $pageSize = $this->parameters->get('limit'); - $count = $bills->count(); - $bills = $bills->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); - $paginator = new LengthAwarePaginator($bills, $count, $pageSize, $this->parameters->get('page')); - $transformer = new BillTransformer(); - $transformer->setParameters($this->parameters); // give params to transformer - - return response() - ->json($this->jsonApiList('subscriptions', $paginator, $transformer)) - ->header('Content-Type', self::CONTENT_TYPE) - ; - } -} diff --git a/app/Api/V2/Controllers/Model/Bill/ShowController.php b/app/Api/V2/Controllers/Model/Bill/ShowController.php deleted file mode 100644 index 16327e3f02..0000000000 --- a/app/Api/V2/Controllers/Model/Bill/ShowController.php +++ /dev/null @@ -1,69 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Model\Bill; - -use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Models\Bill; -use FireflyIII\Repositories\Bill\BillRepositoryInterface; -use FireflyIII\Support\Http\Api\ValidatesUserGroupTrait; -use FireflyIII\Transformers\BillTransformer; -use Illuminate\Http\JsonResponse; - -/** - * Class ShowController - */ -class ShowController extends Controller -{ - use ValidatesUserGroupTrait; - - private BillRepositoryInterface $repository; - - public function __construct() - { - parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(BillRepositoryInterface::class); - $this->repository->setUserGroup($this->validateUserGroup($request)); - - return $next($request); - } - ); - } - - /** - * TODO this endpoint is not documented - */ - public function show(Bill $bill): JsonResponse - { - $transformer = new BillTransformer(); - $transformer->setParameters($this->parameters); - - return response() - ->api($this->jsonApiObject('subscriptions', $bill, $transformer)) - ->header('Content-Type', self::CONTENT_TYPE) - ; - } -} diff --git a/app/Api/V2/Controllers/Model/Bill/SumController.php b/app/Api/V2/Controllers/Model/Bill/SumController.php deleted file mode 100644 index 69b0dcc7aa..0000000000 --- a/app/Api/V2/Controllers/Model/Bill/SumController.php +++ /dev/null @@ -1,86 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Model\Bill; - -use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Api\V2\Request\Generic\DateRequest; -use FireflyIII\Repositories\Bill\BillRepositoryInterface; -use FireflyIII\Support\Http\Api\ValidatesUserGroupTrait; -use Illuminate\Http\JsonResponse; - -/** - * Class SumController - */ -class SumController extends Controller -{ - use ValidatesUserGroupTrait; - - private BillRepositoryInterface $repository; - - public function __construct() - { - parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(BillRepositoryInterface::class); - $this->repository->setUserGroup($this->validateUserGroup($request)); - - return $next($request); - } - ); - } - - /** - * This endpoint is documented at: - * https://api-docs.firefly-iii.org/?urls.primaryName=2.0.0%20(v2)#/transactions-sum/getBillsPaidTrSum - * - * TODO see autocomplete/accountcontroller for list. - * - * @SuppressWarnings("PHPMD.UnusedFormalParameter") - */ - public function paid(DateRequest $request): JsonResponse - { - $result = $this->repository->sumPaidInRange($this->parameters->get('start'), $this->parameters->get('end')); - - // convert to JSON response: - return response()->api(array_values($result)); - } - - /** - * This endpoint is documented at: - * https://api-docs.firefly-iii.org/?urls.primaryName=2.0.0%20(v2)#/transactions-sum/getBillsUnpaidTrSum - * - * TODO see autocomplete/accountcontroller for list. - * - * @SuppressWarnings("PHPMD.UnusedFormalParameter") - */ - public function unpaid(DateRequest $request): JsonResponse - { - $result = $this->repository->sumUnpaidInRange($this->parameters->get('start'), $this->parameters->get('end')); - - // convert to JSON response: - return response()->api(array_values($result)); - } -} diff --git a/app/Api/V2/Controllers/Model/Budget/IndexController.php b/app/Api/V2/Controllers/Model/Budget/IndexController.php deleted file mode 100644 index d2a8eb6e6e..0000000000 --- a/app/Api/V2/Controllers/Model/Budget/IndexController.php +++ /dev/null @@ -1,71 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Model\Budget; - -use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; -use FireflyIII\Transformers\BudgetTransformer; -use Illuminate\Http\JsonResponse; -use Illuminate\Pagination\LengthAwarePaginator; - -/** - * Class IndexController - */ -class IndexController extends Controller -{ - private BudgetRepositoryInterface $repository; - - public function __construct() - { - parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(BudgetRepositoryInterface::class); - - return $next($request); - } - ); - } - - /** - * This endpoint is documented at: - * https://api-docs.firefly-iii.org/?urls.primaryName=2.0.0%20(v2)#/budgets/listBudgets - */ - public function index(): JsonResponse - { - $pageSize = $this->parameters->get('limit'); - $collection = $this->repository->getActiveBudgets(); - $total = $collection->count(); - $collection->slice($pageSize * $this->parameters->get('page'), $pageSize); - - $paginator = new LengthAwarePaginator($collection, $total, $pageSize, $this->parameters->get('page')); - $transformer = new BudgetTransformer(); - - return response() - ->api($this->jsonApiList('budgets', $paginator, $transformer)) - ->header('Content-Type', self::CONTENT_TYPE) - ; - } -} diff --git a/app/Api/V2/Controllers/Model/Budget/ShowController.php b/app/Api/V2/Controllers/Model/Budget/ShowController.php deleted file mode 100644 index 566cc992f9..0000000000 --- a/app/Api/V2/Controllers/Model/Budget/ShowController.php +++ /dev/null @@ -1,94 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Model\Budget; - -use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Api\V2\Request\Generic\DateRequest; -use FireflyIII\Models\Budget; -use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; -use FireflyIII\Transformers\BudgetTransformer; -use Illuminate\Http\JsonResponse; - -/** - * Class ShowController - * TODO lots of deprecated code here. - */ -class ShowController extends Controller -{ - private BudgetRepositoryInterface $repository; - - public function __construct() - { - parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(BudgetRepositoryInterface::class); - - return $next($request); - } - ); - } - - /** - * 2023-10-29 removed the cerSum reference, not sure where this is used atm - * so removed from api.php. Also applies to "spent" method. - * - * This endpoint is documented at: - * TODO add URL - */ - public function budgeted(DateRequest $request, Budget $budget): JsonResponse - { - $data = $request->getAll(); - $result = $this->repository->budgetedInPeriodForBudget($budget, $data['start'], $data['end']); - - return response()->json($result); - } - - /** - * Show a budget. - */ - public function show(Budget $budget): JsonResponse - { - $transformer = new BudgetTransformer(); - $transformer->setParameters($this->parameters); - - return response() - ->api($this->jsonApiObject('budgets', $budget, $transformer)) - ->header('Content-Type', self::CONTENT_TYPE) - ; - } - - /** - * This endpoint is documented at: - * TODO add URL - */ - public function spent(DateRequest $request, Budget $budget): JsonResponse - { - $data = $request->getAll(); - $result = $this->repository->spentInPeriodForBudget($budget, $data['start'], $data['end']); - - return response()->json($result); - } -} diff --git a/app/Api/V2/Controllers/Model/Budget/SumController.php b/app/Api/V2/Controllers/Model/Budget/SumController.php deleted file mode 100644 index 0147fd061c..0000000000 --- a/app/Api/V2/Controllers/Model/Budget/SumController.php +++ /dev/null @@ -1,74 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Model\Budget; - -use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Api\V2\Request\Generic\DateRequest; -use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; -use Illuminate\Http\JsonResponse; - -/** - * Class SumController - */ -class SumController extends Controller -{ - private BudgetRepositoryInterface $repository; - - public function __construct() - { - parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(BudgetRepositoryInterface::class); - - return $next($request); - } - ); - } - - /** - * This endpoint is documented at: - * https://api-docs.firefly-iii.org/?urls.primaryName=2.0.0%20(v2)#/budgets/getBudgetedForBudget - */ - public function budgeted(DateRequest $request): JsonResponse - { - $data = $request->getAll(); - $result = $this->repository->budgetedInPeriod($data['start'], $data['end']); - - return response()->json($result); - } - - /** - * This endpoint is documented at: - * https://api-docs.firefly-iii.org/?urls.primaryName=2.0.0%20(v2)#/budgets/getSpentForBudget - */ - public function spent(DateRequest $request): JsonResponse - { - $data = $request->getAll(); - $result = $this->repository->spentInPeriod($data['start'], $data['end']); - - return response()->json($result); - } -} diff --git a/app/Api/V2/Controllers/Model/BudgetLimit/IndexController.php b/app/Api/V2/Controllers/Model/BudgetLimit/IndexController.php deleted file mode 100644 index 1a54aa4ef9..0000000000 --- a/app/Api/V2/Controllers/Model/BudgetLimit/IndexController.php +++ /dev/null @@ -1,66 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Model\BudgetLimit; - -use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Models\Budget; -use FireflyIII\Repositories\Budget\BudgetLimitRepositoryInterface; -use FireflyIII\Transformers\BudgetLimitTransformer; -use Illuminate\Http\JsonResponse; -use Illuminate\Pagination\LengthAwarePaginator; - -class IndexController extends Controller -{ - private BudgetLimitRepositoryInterface $repository; - - public function __construct() - { - parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(BudgetLimitRepositoryInterface::class); - - return $next($request); - } - ); - } - - /** - * This endpoint is documented at: - * TODO add URL - */ - public function index(Budget $budget): JsonResponse - { - $pageSize = $this->parameters->get('limit'); - $collection = $this->repository->getBudgetLimits($budget); - $total = $collection->count(); - $collection->slice($pageSize * $this->parameters->get('page'), $pageSize); - - $paginator = new LengthAwarePaginator($collection, $total, $pageSize, $this->parameters->get('page')); - $transformer = new BudgetLimitTransformer(); - - return response()->api($this->jsonApiList('budget-limits', $paginator, $transformer))->header('Content-Type', self::CONTENT_TYPE); - } -} diff --git a/app/Api/V2/Controllers/Model/BudgetLimit/ListController.php b/app/Api/V2/Controllers/Model/BudgetLimit/ListController.php deleted file mode 100644 index b87ba89314..0000000000 --- a/app/Api/V2/Controllers/Model/BudgetLimit/ListController.php +++ /dev/null @@ -1,71 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Model\BudgetLimit; - -use FireflyIII\Api\V2\Controllers\Controller; -use Illuminate\Http\JsonResponse; - -/** - * Class ListController - */ -class ListController extends Controller -{ - // private BudgetLimitRepositoryInterface $repository; - // - // public function __construct() - // { - // parent::__construct(); - // $this->middleware( - // function ($request, $next) { - // $this->repository = app(BudgetLimitRepositoryInterface::class); - // - // return $next($request); - // } - // ); - // } - - /** - * This endpoint is documented at: - * https://api-docs.firefly-iii.org/?urls.primaryName=2.0.0%20(v2)#/budgets/listBudgetLimitByBudget - * // DateRequest $request, Budget $budget - */ - public function index(): JsonResponse - { - return response()->json(); - // throw new FireflyException('Needs refactoring, move to IndexController.'); - // $pageSize = $this->parameters->get('limit'); - // $dates = $request->getAll(); - // $collection = $this->repository->getBudgetLimits($budget, $dates['start'], $dates['end']); - // $total = $collection->count(); - // $collection->slice($pageSize * $this->parameters->get('page'), $pageSize); - // - // $paginator = new LengthAwarePaginator($collection, $total, $pageSize, $this->parameters->get('page')); - // $transformer = new BudgetLimitTransformer(); - // - // return response() - // ->api($this->jsonApiList('budget-limits', $paginator, $transformer)) - // ->header('Content-Type', self::CONTENT_TYPE); - } -} diff --git a/app/Api/V2/Controllers/Model/Currency/IndexController.php b/app/Api/V2/Controllers/Model/Currency/IndexController.php deleted file mode 100644 index 80657188b4..0000000000 --- a/app/Api/V2/Controllers/Model/Currency/IndexController.php +++ /dev/null @@ -1,72 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Model\Currency; - -use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; -use FireflyIII\Transformers\CurrencyTransformer; -use Illuminate\Http\JsonResponse; -use Illuminate\Pagination\LengthAwarePaginator; - -/** - * Class IndexController - */ -class IndexController extends Controller -{ - private CurrencyRepositoryInterface $repository; - - public function __construct() - { - parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(CurrencyRepositoryInterface::class); - - return $next($request); - } - ); - } - - /** - * TODO This endpoint is not yet documented. - * - * Display a listing of the resource. - */ - public function index(): JsonResponse - { - $bills = $this->repository->getAll(); - $pageSize = $this->parameters->get('limit'); - $count = $bills->count(); - $bills = $bills->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); - $paginator = new LengthAwarePaginator($bills, $count, $pageSize, $this->parameters->get('page')); - $transformer = new CurrencyTransformer(); - $transformer->setParameters($this->parameters); // give params to transformer - - return response() - ->json($this->jsonApiList('currencies', $paginator, $transformer)) - ->header('Content-Type', self::CONTENT_TYPE) - ; - } -} diff --git a/app/Api/V2/Controllers/Model/PiggyBank/IndexController.php b/app/Api/V2/Controllers/Model/PiggyBank/IndexController.php deleted file mode 100644 index 7577edf95a..0000000000 --- a/app/Api/V2/Controllers/Model/PiggyBank/IndexController.php +++ /dev/null @@ -1,74 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Model\PiggyBank; - -use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface; -use FireflyIII\Support\Http\Api\ValidatesUserGroupTrait; -use FireflyIII\Transformers\PiggyBankTransformer; -use Illuminate\Http\JsonResponse; -use Illuminate\Pagination\LengthAwarePaginator; - -/** - * Class ShowController - */ -class IndexController extends Controller -{ - use ValidatesUserGroupTrait; - - private PiggyBankRepositoryInterface $repository; - - public function __construct() - { - parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(PiggyBankRepositoryInterface::class); - $this->repository->setUserGroup($this->validateUserGroup($request)); - - return $next($request); - } - ); - } - - /** - * TODO see autocomplete/accountcontroller for list. - */ - public function index(): JsonResponse - { - $piggies = $this->repository->getPiggyBanks(); - $pageSize = $this->parameters->get('limit'); - $count = $piggies->count(); - $piggies = $piggies->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); - $paginator = new LengthAwarePaginator($piggies, $count, $pageSize, $this->parameters->get('page')); - $transformer = new PiggyBankTransformer(); - $transformer->setParameters($this->parameters); // give params to transformer - - return response() - ->json($this->jsonApiList('piggy-banks', $paginator, $transformer)) - ->header('Content-Type', self::CONTENT_TYPE) - ; - } -} diff --git a/app/Api/V2/Controllers/Model/Transaction/ShowController.php b/app/Api/V2/Controllers/Model/Transaction/ShowController.php deleted file mode 100644 index 185bd41774..0000000000 --- a/app/Api/V2/Controllers/Model/Transaction/ShowController.php +++ /dev/null @@ -1,44 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Model\Transaction; - -use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Models\TransactionGroup; -use FireflyIII\Transformers\TransactionGroupTransformer; -use Illuminate\Http\JsonResponse; - -class ShowController extends Controller -{ - /** - * TODO this endpoint is not yet reachable. - */ - public function show(TransactionGroup $transactionGroup): JsonResponse - { - $transformer = new TransactionGroupTransformer(); - $transformer->setParameters($this->parameters); - - return response()->api($this->jsonApiObject('transactions', $transactionGroup, $transformer))->header('Content-Type', self::CONTENT_TYPE); - } -} diff --git a/app/Api/V2/Controllers/Model/Transaction/StoreController.php b/app/Api/V2/Controllers/Model/Transaction/StoreController.php deleted file mode 100644 index 9c9d61592b..0000000000 --- a/app/Api/V2/Controllers/Model/Transaction/StoreController.php +++ /dev/null @@ -1,130 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Model\Transaction; - -use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Api\V2\Request\Model\Transaction\StoreRequest; -use FireflyIII\Events\StoredTransactionGroup; -use FireflyIII\Exceptions\DuplicateTransactionException; -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Helpers\Collector\GroupCollectorInterface; -use FireflyIII\Repositories\TransactionGroup\TransactionGroupRepositoryInterface; -use FireflyIII\Rules\IsDuplicateTransaction; -use FireflyIII\Transformers\TransactionGroupTransformer; -use FireflyIII\User; -use Illuminate\Http\JsonResponse; -use Illuminate\Support\Facades\Validator; -use Illuminate\Validation\ValidationException; - -/** - * Class StoreController - */ -class StoreController extends Controller -{ - private TransactionGroupRepositoryInterface $groupRepository; - - /** - * TransactionController constructor. - */ - public function __construct() - { - parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->groupRepository = app(TransactionGroupRepositoryInterface::class); - - return $next($request); - } - ); - } - - /** - * TODO this method is practically the same as the V1 method and borrows as much code as possible. - * - * @throws FireflyException - * @throws ValidationException - */ - public function post(StoreRequest $request): JsonResponse - { - app('log')->debug('Now in API v2 StoreController::store()'); - $data = $request->getAll(); - $userGroup = $request->getUserGroup(); - $data['user_group'] = $userGroup; - - - // overrule user group and see where we end up. - // what happens when we refer to a budget that is not in this user group? - - app('log')->channel('audit')->info('Store new transaction over API.', $data); - - try { - $transactionGroup = $this->groupRepository->store($data); - } catch (DuplicateTransactionException $e) { - app('log')->warning('Caught a duplicate transaction. Return error message.'); - $validator = Validator::make( - ['transactions' => [['description' => $e->getMessage()]]], - ['transactions.0.description' => new IsDuplicateTransaction()] - ); - - throw new ValidationException($validator); - } catch (FireflyException $e) { - app('log')->warning('Caught an exception. Return error message.'); - app('log')->error($e->getMessage()); - $message = sprintf('Internal exception: %s', $e->getMessage()); - $validator = Validator::make(['transactions' => [['description' => $message]]], ['transactions.0.description' => new IsDuplicateTransaction()]); - - throw new ValidationException($validator); - } - app('preferences')->mark(); - $applyRules = $data['apply_rules'] ?? true; - $fireWebhooks = $data['fire_webhooks'] ?? true; - event(new StoredTransactionGroup($transactionGroup, $applyRules, $fireWebhooks)); - - /** @var User $admin */ - $admin = auth()->user(); - - // use new group collector: - /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); - $collector - ->setUser($admin) - // filter on transaction group. - ->setTransactionGroup($transactionGroup) - ; - - $selectedGroup = $collector->getGroups()->first(); - if (null === $selectedGroup) { - throw new FireflyException('200032: Cannot find transaction. Possibly, a rule deleted this transaction after its creation.'); - } - - $transformer = new TransactionGroupTransformer(); - $transformer->setParameters($this->parameters); - - return response() - ->api($this->jsonApiObject('transactions', $selectedGroup, $transformer)) - ->header('Content-Type', self::CONTENT_TYPE) - ; - } -} diff --git a/app/Api/V2/Controllers/Model/Transaction/UpdateController.php b/app/Api/V2/Controllers/Model/Transaction/UpdateController.php deleted file mode 100644 index b27ade514f..0000000000 --- a/app/Api/V2/Controllers/Model/Transaction/UpdateController.php +++ /dev/null @@ -1,94 +0,0 @@ -middleware( - function ($request, $next) { - $this->groupRepository = app(TransactionGroupRepositoryInterface::class); - - return $next($request); - } - ); - } - - /** - * This endpoint is documented at: - * https://api-docs.firefly-iii.org/?urls.primaryName=2.0.0%20(v1)#/transactions/updateTransaction - * - * Update a transaction. - * - * @throws FireflyException - */ - public function update(UpdateRequest $request, TransactionGroup $transactionGroup): JsonResponse - { - app('log')->debug('Now in update routine for transaction group [v2]!'); - $data = $request->getAll(); - $transactionGroup = $this->groupRepository->update($transactionGroup, $data); - $applyRules = $data['apply_rules'] ?? true; - $fireWebhooks = $data['fire_webhooks'] ?? true; - - event(new UpdatedTransactionGroup($transactionGroup, $applyRules, $fireWebhooks, true)); - app('preferences')->mark(); - - /** @var User $admin */ - $admin = auth()->user(); - - // use new group collector: - /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); - $collector->setUser($admin)->setTransactionGroup($transactionGroup); - - $selectedGroup = $collector->getGroups()->first(); - if (null === $selectedGroup) { - throw new FireflyException('200032: Cannot find transaction. Possibly, a rule deleted this transaction after its creation.'); - } - - $transformer = new TransactionGroupTransformer(); - $transformer->setParameters($this->parameters); - - return response()->api($this->jsonApiObject('transactions', $selectedGroup, $transformer))->header('Content-Type', self::CONTENT_TYPE); - } -} diff --git a/app/Api/V2/Controllers/Model/TransactionCurrency/IndexController.php b/app/Api/V2/Controllers/Model/TransactionCurrency/IndexController.php deleted file mode 100644 index 7609a298a1..0000000000 --- a/app/Api/V2/Controllers/Model/TransactionCurrency/IndexController.php +++ /dev/null @@ -1,85 +0,0 @@ -middleware( - function ($request, $next) { - $this->repository = app(CurrencyRepositoryInterface::class); - // new way of user group validation - $userGroup = $this->validateUserGroup($request); - $this->repository->setUserGroup($userGroup); - - return $next($request); - } - ); - } - - public function index(IndexRequest $request): JsonResponse - { - $settings = $request->getAll(); - $currencies = new Collection(); - if (true === $settings['enabled']) { - $currencies = $this->repository->get(); - } - if (true !== $settings['enabled']) { - $currencies = $this->repository->getAll(); - } - - $pageSize = $this->parameters->get('limit'); - $count = $currencies->count(); - - // depending on the sort parameters, this list must not be split, because the - // order is calculated in the account transformer and by that time it's too late. - $accounts = $currencies->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); - $paginator = new LengthAwarePaginator($accounts, $count, $pageSize, $this->parameters->get('page')); - $transformer = new CurrencyTransformer(); - - $this->parameters->set('pageSize', $pageSize); - $transformer->setParameters($this->parameters); // give params to transformer - - return response() - ->json($this->jsonApiList(self::RESOURCE_KEY, $paginator, $transformer)) - ->header('Content-Type', self::CONTENT_TYPE) - ; - } -} diff --git a/app/Api/V2/Controllers/Model/TransactionCurrency/ShowController.php b/app/Api/V2/Controllers/Model/TransactionCurrency/ShowController.php deleted file mode 100644 index 7486f17cee..0000000000 --- a/app/Api/V2/Controllers/Model/TransactionCurrency/ShowController.php +++ /dev/null @@ -1,80 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Model\TransactionCurrency; - -use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Models\TransactionCurrency; -use FireflyIII\Models\UserGroup; -use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; -use FireflyIII\Transformers\CurrencyTransformer; -use Illuminate\Http\JsonResponse; - -/** - * Class ShowController - */ -class ShowController extends Controller -{ - public const string RESOURCE_KEY = 'transaction-currencies'; - - private CurrencyRepositoryInterface $repository; - - public function __construct() - { - parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(CurrencyRepositoryInterface::class); - // new way of user group validation - $userGroup = $this->validateUserGroup($request); - $this->repository->setUserGroup($userGroup); - - return $next($request); - } - ); - } - - public function show(TransactionCurrency $currency): JsonResponse - { - $groups = $currency->userGroups()->where('user_groups.id', $this->repository->getUserGroup()->id)->get(); - $enabled = $groups->count() > 0; - $default = false; - - /** @var UserGroup $group */ - foreach ($groups as $group) { - $default = 1 === $group->pivot->group_default; - } - $currency->userGroupEnabled = $enabled; - $currency->userGroupNative = $default; - - - $transformer = new CurrencyTransformer(); - $transformer->setParameters($this->parameters); - - return response() - ->api($this->jsonApiObject(self::RESOURCE_KEY, $currency, $transformer)) - ->header('Content-Type', self::CONTENT_TYPE) - ; - } -} diff --git a/app/Api/V2/Controllers/Search/AccountController.php b/app/Api/V2/Controllers/Search/AccountController.php deleted file mode 100644 index af87a73b5a..0000000000 --- a/app/Api/V2/Controllers/Search/AccountController.php +++ /dev/null @@ -1,32 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Search; - -use FireflyIII\Api\V2\Controllers\Controller; - -/** - * Class AccountController - */ -class AccountController extends Controller {} diff --git a/app/Api/V2/Controllers/Summary/BasicController.php b/app/Api/V2/Controllers/Summary/BasicController.php deleted file mode 100644 index feb3798cef..0000000000 --- a/app/Api/V2/Controllers/Summary/BasicController.php +++ /dev/null @@ -1,412 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Summary; - -use Exception; -use Carbon\Carbon; -use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Api\V2\Request\Generic\DateRequest; -use FireflyIII\Enums\AccountTypeEnum; -use FireflyIII\Enums\TransactionTypeEnum; -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Helpers\Collector\GroupCollectorInterface; -use FireflyIII\Helpers\Report\NetWorthInterface; -use FireflyIII\Models\Account; -use FireflyIII\Models\UserGroup; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; -use FireflyIII\Repositories\Bill\BillRepositoryInterface; -use FireflyIII\Repositories\Budget\AvailableBudgetRepositoryInterface; -use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; -use FireflyIII\Repositories\Budget\OperationsRepositoryInterface; -use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; -use FireflyIII\Support\Http\Api\ExchangeRateConverter; -use FireflyIII\Support\Http\Api\SummaryBalanceGrouped; -use FireflyIII\Support\Http\Api\ValidatesUserGroupTrait; -use FireflyIII\User; -use Illuminate\Http\JsonResponse; -use Illuminate\Support\Facades\Log; - -/** - * Class BasicController - */ -class BasicController extends Controller -{ - use ValidatesUserGroupTrait; - - private AvailableBudgetRepositoryInterface $abRepository; - private AccountRepositoryInterface $accountRepository; - private BillRepositoryInterface $billRepository; - private BudgetRepositoryInterface $budgetRepository; - private CurrencyRepositoryInterface $currencyRepos; - private OperationsRepositoryInterface $opsRepository; - - /** - * BasicController constructor. - */ - public function __construct() - { - parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->abRepository = app(AvailableBudgetRepositoryInterface::class); - $this->accountRepository = app(AccountRepositoryInterface::class); - $this->billRepository = app(BillRepositoryInterface::class); - $this->budgetRepository = app(BudgetRepositoryInterface::class); - $this->currencyRepos = app(CurrencyRepositoryInterface::class); - $this->opsRepository = app(OperationsRepositoryInterface::class); - - $userGroup = $this->validateUserGroup($request); - $this->abRepository->setUserGroup($userGroup); - $this->accountRepository->setUserGroup($userGroup); - $this->billRepository->setUserGroup($userGroup); - $this->budgetRepository->setUserGroup($userGroup); - $this->opsRepository->setUserGroup($userGroup); - - return $next($request); - } - ); - } - - /** - * This endpoint is documented at: - * https://api-docs.firefly-iii.org/?urls.primaryName=2.0.0%20(v2)#/summary/getBasicSummary - * - * @throws Exception - * - * @SuppressWarnings("PHPMD.UnusedFormalParameter") - */ - public function basic(DateRequest $request): JsonResponse - { - // parameters for boxes: - $start = $this->parameters->get('start'); - $end = $this->parameters->get('end'); - - // balance information: - $balanceData = $this->getBalanceInformation($start, $end); - $billData = $this->getBillInformation($start, $end); - $spentData = $this->getLeftToSpendInfo($start, $end); - $netWorthData = $this->getNetWorthInfo($start, $end); - $total = array_merge($balanceData, $billData, $spentData, $netWorthData); - - return response()->json($total); - } - - /** - * @throws FireflyException - */ - private function getBalanceInformation(Carbon $start, Carbon $end): array - { - $object = new SummaryBalanceGrouped(); - $default = app('amount')->getNativeCurrency(); - - $object->setDefault($default); - - /** @var User $user */ - $user = auth()->user(); - - // collect income of user using the new group collector. - /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); - $collector - ->setRange($start, $end) - ->setUserGroup($user->userGroup) - // set page to retrieve - ->setPage($this->parameters->get('page')) - // set types of transactions to return. - ->setTypes([TransactionTypeEnum::DEPOSIT->value]) - ->setRange($start, $end) - ; - - $set = $collector->getExtractedJournals(); - $object->groupTransactions('income', $set); - - // collect expenses of user using the new group collector. - /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); - $collector - ->setRange($start, $end) - ->setUserGroup($user->userGroup) - // set page to retrieve - ->setPage($this->parameters->get('page')) - // set types of transactions to return. - ->setTypes([TransactionTypeEnum::WITHDRAWAL->value]) - ->setRange($start, $end) - ; - $set = $collector->getExtractedJournals(); - $object->groupTransactions('expense', $set); - - return $object->groupData(); - } - - private function getBillInformation(Carbon $start, Carbon $end): array - { - /* - * Since both this method and the chart use the exact same data, we can suffice - * with calling the one method in the bill repository that will get this amount. - */ - $paidAmount = $this->billRepository->sumPaidInRange($start, $end); - $unpaidAmount = $this->billRepository->sumUnpaidInRange($start, $end); - - $return = []; - - /** - * @var array $info - */ - foreach ($paidAmount as $info) { - $amount = bcmul((string) $info['sum'], '-1'); - $nativeAmount = bcmul((string) $info['native_sum'], '-1'); - $return[] = [ - 'key' => sprintf('bills-paid-in-%s', $info['currency_code']), - 'value' => $amount, - 'currency_id' => (string) $info['currency_id'], - 'currency_code' => $info['currency_code'], - 'currency_symbol' => $info['currency_symbol'], - 'currency_decimal_places' => $info['currency_decimal_places'], - ]; - $return[] = [ - 'key' => 'bills-paid-in-native', - 'value' => $nativeAmount, - 'currency_id' => (string) $info['native_currency_id'], - 'currency_code' => $info['native_currency_code'], - 'currency_symbol' => $info['native_currency_symbol'], - 'currency_decimal_places' => $info['native_currency_decimal_places'], - ]; - } - - /** - * @var array $info - */ - foreach ($unpaidAmount as $info) { - $amount = bcmul((string) $info['sum'], '-1'); - $nativeAmount = bcmul((string) $info['native_sum'], '-1'); - $return[] = [ - 'key' => sprintf('bills-unpaid-in-%s', $info['currency_code']), - 'value' => $amount, - 'currency_id' => (string) $info['currency_id'], - 'currency_code' => $info['currency_code'], - 'currency_symbol' => $info['currency_symbol'], - 'currency_decimal_places' => $info['currency_decimal_places'], - ]; - $return[] = [ - 'key' => 'bills-unpaid-in-native', - 'value' => $nativeAmount, - 'currency_id' => (string) $info['native_currency_id'], - 'currency_code' => $info['native_currency_code'], - 'currency_symbol' => $info['native_currency_symbol'], - 'currency_decimal_places' => $info['native_currency_decimal_places'], - ]; - } - - return $return; - } - - /** - * @SuppressWarnings("PHPMD.ExcessiveMethodLength") - */ - private function getLeftToSpendInfo(Carbon $start, Carbon $end): array - { - Log::debug(sprintf('Created new ExchangeRateConverter in %s', __METHOD__)); - app('log')->debug('Now in getLeftToSpendInfo'); - $return = []; - $today = today(config('app.timezone')); - $available = $this->abRepository->getAvailableBudgetWithCurrency($start, $end); - $budgets = $this->budgetRepository->getActiveBudgets(); - $spent = $this->opsRepository->listExpenses($start, $end, null, $budgets); - $default = app('amount')->getNativeCurrency(); - $currencies = []; - $converter = new ExchangeRateConverter(); - - // native info: - $nativeLeft = [ - 'key' => 'left-to-spend-in-native', - 'value' => '0', - 'currency_id' => (string) $default->id, - 'currency_code' => $default->code, - 'currency_symbol' => $default->symbol, - 'currency_decimal_places' => $default->decimal_places, - ]; - $nativePerDay = [ - 'key' => 'left-per-day-to-spend-in-native', - 'value' => '0', - 'currency_id' => (string) $default->id, - 'currency_code' => $default->code, - 'currency_symbol' => $default->symbol, - 'currency_decimal_places' => $default->decimal_places, - ]; - - /** - * @var int $currencyId - * @var array $row - */ - foreach ($spent as $currencyId => $row) { - app('log')->debug(sprintf('Processing spent array in currency #%d', $currencyId)); - $spent = '0'; - $spentNative = '0'; - - // get the sum from the array of transactions (double loop but who cares) - /** @var array $budget */ - foreach ($row['budgets'] as $budget) { - app('log')->debug(sprintf('Processing expenses in budget "%s".', $budget['name'])); - - /** @var array $journal */ - foreach ($budget['transaction_journals'] as $journal) { - $journalCurrencyId = $journal['currency_id']; - $currency = $currencies[$journalCurrencyId] ?? $this->currencyRepos->find($journalCurrencyId); - $currencies[$currencyId] = $currency; - $amount = app('steam')->negative($journal['amount']); - $amountNative = $converter->convert($default, $currency, $start, $amount); - if ((int) $journal['foreign_currency_id'] === $default->id) { - $amountNative = $journal['foreign_amount']; - } - $spent = bcadd($spent, (string) $amount); - $spentNative = bcadd($spentNative, (string) $amountNative); - } - app('log')->debug(sprintf('Total spent in budget "%s" is %s', $budget['name'], $spent)); - } - - // either an amount was budgeted or 0 is available. - $currency = $currencies[$currencyId] ?? $this->currencyRepos->find($currencyId); - $currencies[$currencyId] = $currency; - $amount = $available[$currencyId]['amount'] ?? '0'; - $amountNative = $available[$currencyId]['native_amount'] ?? '0'; - $left = bcadd($amount, $spent); - $leftNative = bcadd($amountNative, $spentNative); - app('log')->debug(sprintf('Available amount is %s', $amount)); - app('log')->debug(sprintf('Amount left is %s', $left)); - - // how much left per day? - $days = (int) $today->diffInDays($end, true) + 1; - $perDay = '0'; - $perDayNative = '0'; - if (0 !== $days && bccomp($left, '0') > -1) { - $perDay = bcdiv($left, (string) $days); - } - if (0 !== $days && bccomp($leftNative, '0') > -1) { - $perDayNative = bcdiv($leftNative, (string) $days); - } - - // left - $return[] = [ - 'key' => sprintf('left-to-spend-in-%s', $row['currency_code']), - 'value' => $left, - 'currency_id' => (string) $row['currency_id'], - 'currency_code' => $row['currency_code'], - 'currency_symbol' => $row['currency_symbol'], - 'currency_decimal_places' => (int) $row['currency_decimal_places'], - ]; - // left (native) - $nativeLeft['value'] = $leftNative; - - // left per day: - $return[] = [ - 'key' => sprintf('left-per-day-to-spend-in-%s', $row['currency_code']), - 'value' => $perDay, - 'currency_id' => (string) $row['currency_id'], - 'currency_code' => $row['currency_code'], - 'currency_symbol' => $row['currency_symbol'], - 'currency_decimal_places' => (int) $row['currency_decimal_places'], - ]; - - // left per day (native) - $nativePerDay['value'] = $perDayNative; - } - $return[] = $nativeLeft; - $return[] = $nativePerDay; - $converter->summarize(); - - return $return; - } - - private function getNetWorthInfo(Carbon $start, Carbon $end): array - { - /** @var UserGroup $userGroup */ - $userGroup = auth()->user()->userGroup; - $date = today(config('app.timezone'))->startOfDay(); - // start and end in the future? use $end - if ($this->notInDateRange($date, $start, $end)) { - /** @var Carbon $date */ - $date = session('end', today(config('app.timezone'))->endOfMonth()); - } - - /** @var NetWorthInterface $netWorthHelper */ - $netWorthHelper = app(NetWorthInterface::class); - $netWorthHelper->setUserGroup($userGroup); - $allAccounts = $this->accountRepository->getActiveAccountsByType( - [AccountTypeEnum::ASSET->value, AccountTypeEnum::DEFAULT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::DEBT->value] - ); - - // filter list on preference of being included. - $filtered = $allAccounts->filter( - function (Account $account) { - $includeNetWorth = $this->accountRepository->getMetaValue($account, 'include_net_worth'); - - return null === $includeNetWorth || '1' === $includeNetWorth; - } - ); - - $netWorthSet = $netWorthHelper->byAccounts($filtered, $date); - $return = []; - // in native amount - $return[] = [ - 'key' => 'net-worth-in-native', - 'value' => $netWorthSet['native']['balance'], - 'currency_id' => (string) $netWorthSet['native']['currency_id'], - 'currency_code' => $netWorthSet['native']['currency_code'], - 'currency_symbol' => $netWorthSet['native']['currency_symbol'], - 'currency_decimal_places' => $netWorthSet['native']['currency_decimal_places'], - ]; - foreach ($netWorthSet as $key => $data) { - if ('native' === $key) { - continue; - } - $return[] = [ - 'key' => sprintf('net-worth-in-%s', $data['currency_code']), - 'value' => $data['balance'], - 'currency_id' => (string) $data['currency_id'], - 'currency_code' => $data['currency_code'], - 'currency_symbol' => $data['currency_symbol'], - 'currency_decimal_places' => $data['currency_decimal_places'], - ]; - } - - return $return; - } - - /** - * Check if date is outside session range. - */ - protected function notInDateRange(Carbon $date, Carbon $start, Carbon $end): bool // Validate a preference - { - if ($start->greaterThanOrEqualTo($date) && $end->greaterThanOrEqualTo($date)) { - return true; - } - // start and end in the past? use $end - if ($start->lessThanOrEqualTo($date) && $end->lessThanOrEqualTo($date)) { - return true; - } - - return false; - } -} diff --git a/app/Api/V2/Controllers/Summary/NetWorthController.php b/app/Api/V2/Controllers/Summary/NetWorthController.php deleted file mode 100644 index f2c023620a..0000000000 --- a/app/Api/V2/Controllers/Summary/NetWorthController.php +++ /dev/null @@ -1,86 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Summary; - -use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Api\V2\Request\Generic\SingleDateRequest; -use FireflyIII\Enums\AccountTypeEnum; -use FireflyIII\Helpers\Report\NetWorthInterface; -use FireflyIII\Models\Account; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; -use FireflyIII\Support\Http\Api\ValidatesUserGroupTrait; -use Illuminate\Http\JsonResponse; - -/** - * Class NetWorthController - */ -class NetWorthController extends Controller -{ - use ValidatesUserGroupTrait; - - private NetWorthInterface $netWorth; - private AccountRepositoryInterface $repository; - - public function __construct() - { - parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->netWorth = app(NetWorthInterface::class); - $this->repository = app(AccountRepositoryInterface::class); - // new way of user group validation - $userGroup = $this->validateUserGroup($request); - $this->netWorth->setUserGroup($userGroup); - $this->repository->setUserGroup($userGroup); - - return $next($request); - } - ); - } - - /** - * This endpoint is documented at: - * https://api-docs.firefly-iii.org/?urls.primaryName=2.0.0%20(v2)#/net-worth/getNetWorth - */ - public function get(SingleDateRequest $request): JsonResponse - { - $date = $request->getDate(); - $accounts = $this->repository->getAccountsByType([AccountTypeEnum::ASSET->value, AccountTypeEnum::DEFAULT->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::MORTGAGE->value]); - - // filter list on preference of being included. - $filtered = $accounts->filter( - function (Account $account) { - $includeNetWorth = $this->repository->getMetaValue($account, 'include_net_worth'); - - return null === $includeNetWorth || '1' === $includeNetWorth; - } - ); - - // skip accounts that should not be in the net worth - $result = $this->netWorth->byAccounts($filtered, $date); - - return response()->api($result); - } -} diff --git a/app/Api/V2/Controllers/System/ConfigurationController.php b/app/Api/V2/Controllers/System/ConfigurationController.php deleted file mode 100644 index e7c9b63ec6..0000000000 --- a/app/Api/V2/Controllers/System/ConfigurationController.php +++ /dev/null @@ -1,30 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\System; - -/** - * Class ConfigurationController - */ -class ConfigurationController {} diff --git a/app/Api/V2/Controllers/System/DebugController.php b/app/Api/V2/Controllers/System/DebugController.php deleted file mode 100644 index d87a51973c..0000000000 --- a/app/Api/V2/Controllers/System/DebugController.php +++ /dev/null @@ -1,32 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\System; - -use FireflyIII\Api\V2\Controllers\Controller; - -/** - * Class DebugController - */ -class DebugController extends Controller {} diff --git a/app/Api/V2/Controllers/System/PreferencesController.php b/app/Api/V2/Controllers/System/PreferencesController.php deleted file mode 100644 index ad7ee52a27..0000000000 --- a/app/Api/V2/Controllers/System/PreferencesController.php +++ /dev/null @@ -1,48 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\System; - -use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Models\Preference; -use FireflyIII\Transformers\PreferenceTransformer; -use Illuminate\Http\JsonResponse; - -/** - * Class PreferencesController - */ -class PreferencesController extends Controller -{ - /** - * This endpoint is documented at: - * https://api-docs.firefly-iii.org/?urls.primaryName=2.0.0%20(v2)#/preferences/getPreference - */ - public function get(Preference $preference): JsonResponse - { - return response() - ->json($this->jsonApiObject('preferences', $preference, new PreferenceTransformer())) - ->header('Content-Type', self::CONTENT_TYPE) - ; - } -} diff --git a/app/Api/V2/Controllers/System/VersionUpdateController.php b/app/Api/V2/Controllers/System/VersionUpdateController.php deleted file mode 100644 index 979bdb1ece..0000000000 --- a/app/Api/V2/Controllers/System/VersionUpdateController.php +++ /dev/null @@ -1,32 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\System; - -use FireflyIII\Api\V2\Controllers\Controller; - -/** - * Class VersionUpdateController - */ -class VersionUpdateController extends Controller {} diff --git a/app/Api/V2/Controllers/Transaction/List/AccountController.php b/app/Api/V2/Controllers/Transaction/List/AccountController.php deleted file mode 100644 index 7ba12c9940..0000000000 --- a/app/Api/V2/Controllers/Transaction/List/AccountController.php +++ /dev/null @@ -1,89 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Transaction\List; - -use Carbon\Carbon; -use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Api\V2\Request\Model\Transaction\ListRequest; -use FireflyIII\Helpers\Collector\GroupCollectorInterface; -use FireflyIII\Models\Account; -use FireflyIII\Support\Http\Api\TransactionFilter; -use FireflyIII\Transformers\TransactionGroupTransformer; -use Illuminate\Http\JsonResponse; -use Illuminate\Support\Collection; - -/** - * Class AccountController - */ -class AccountController extends Controller -{ - use TransactionFilter; - - /** - * This endpoint is documented at: - * https://api-docs.firefly-iii.org/?urls.primaryName=2.0.0%20(v2)#/accounts/listTransactionByAccount - */ - public function list(ListRequest $request, Account $account): JsonResponse - { - // collect transactions: - $page = $request->getPage(); - $page = max($page, 1); - $pageSize = $this->parameters->get('limit'); - - /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); - $collector->setAccounts(new Collection([$account])) - ->withAPIInformation() - ->setLimit($pageSize) - ->setPage($page) - ->setTypes($request->getTransactionTypes()) - ; - - $start = $request->getStartDate(); - $end = $request->getEndDate(); - if ($start instanceof Carbon) { - app('log')->debug(sprintf('Set start date to %s', $start->toIso8601String())); - $collector->setStart($start); - } - if ($end instanceof Carbon) { - app('log')->debug(sprintf('Set end date to %s', $start->toIso8601String())); - $collector->setEnd($end); - } - - $paginator = $collector->getPaginatedGroups(); - $paginator->setPath( - sprintf( - '%s?%s', - route('api.v2.accounts.transactions', [$account->id]), - $request->buildParams($pageSize) - ) - ); - - return response() - ->json($this->jsonApiList('transactions', $paginator, new TransactionGroupTransformer())) - ->header('Content-Type', self::CONTENT_TYPE) - ; - } -} diff --git a/app/Api/V2/Controllers/Transaction/List/TransactionController.php b/app/Api/V2/Controllers/Transaction/List/TransactionController.php deleted file mode 100644 index 0e630d7444..0000000000 --- a/app/Api/V2/Controllers/Transaction/List/TransactionController.php +++ /dev/null @@ -1,120 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Transaction\List; - -use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Api\V2\Request\Model\Transaction\InfiniteListRequest; -use FireflyIII\Api\V2\Request\Model\Transaction\ListRequest; -use FireflyIII\Helpers\Collector\GroupCollectorInterface; -use FireflyIII\Transformers\TransactionGroupTransformer; -use Illuminate\Http\JsonResponse; - -/** - * Class TransactionController - */ -class TransactionController extends Controller -{ - public function infiniteList(InfiniteListRequest $request): JsonResponse - { - // get sort instructions - $instructions = $request->getSortInstructions('transactions'); - - // collect transactions: - /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); - $collector->setUserGroup(auth()->user()->userGroup) - ->withAPIInformation() - ->setStartRow($request->getStartRow()) - ->setEndRow($request->getEndRow()) - ->setTypes($request->getTransactionTypes()) - ->setSorting($instructions) - ; - - $start = $this->parameters->get('start'); - $end = $this->parameters->get('end'); - if (null !== $start) { - $collector->setStart($start); - } - if (null !== $end) { - $collector->setEnd($end); - } - - $paginator = $collector->getPaginatedGroups(); - $params = $request->buildParams(); - $paginator->setPath( - sprintf( - '%s?%s', - route('api.v2.infinite.transactions.list'), - $params - ) - ); - - return response() - ->json($this->jsonApiList('transactions', $paginator, new TransactionGroupTransformer())) - ->header('Content-Type', self::CONTENT_TYPE) - ; - } - - public function list(ListRequest $request): JsonResponse - { - // collect transactions: - $pageSize = $this->parameters->get('limit'); - $page = $request->getPage(); - $page = max($page, 1); - - /** @var GroupCollectorInterface $collector */ - $collector = app(GroupCollectorInterface::class); - $collector->setUserGroup(auth()->user()->userGroup) - ->withAPIInformation() - ->setLimit($pageSize) - ->setPage($page) - ->setTypes($request->getTransactionTypes()) - ; - - $start = $this->parameters->get('start'); - $end = $this->parameters->get('end'); - if (null !== $start) { - $collector->setStart($start); - } - if (null !== $end) { - $collector->setEnd($end); - } - - $paginator = $collector->getPaginatedGroups(); - $params = $request->buildParams($pageSize); - $paginator->setPath( - sprintf( - '%s?%s', - route('api.v2.transactions.list'), - $params - ) - ); - - return response() - ->json($this->jsonApiList('transactions', $paginator, new TransactionGroupTransformer())) - ->header('Content-Type', self::CONTENT_TYPE) - ; - } -} diff --git a/app/Api/V2/Controllers/Transaction/Sum/BillController.php b/app/Api/V2/Controllers/Transaction/Sum/BillController.php deleted file mode 100644 index 19428e98e2..0000000000 --- a/app/Api/V2/Controllers/Transaction/Sum/BillController.php +++ /dev/null @@ -1,32 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\Transaction\Sum; - -use FireflyIII\Api\V2\Controllers\Controller; - -/** - * Class BillController - */ -class BillController extends Controller {} diff --git a/app/Api/V2/Controllers/UserGroup/DestroyController.php b/app/Api/V2/Controllers/UserGroup/DestroyController.php deleted file mode 100644 index 216d00b9e9..0000000000 --- a/app/Api/V2/Controllers/UserGroup/DestroyController.php +++ /dev/null @@ -1,68 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\UserGroup; - -use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Enums\UserRoleEnum; -use FireflyIII\Models\UserGroup; -use FireflyIII\Repositories\UserGroup\UserGroupRepositoryInterface; -use FireflyIII\User; -use Illuminate\Http\JsonResponse; -use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; - -/** - * Class DestroyController - */ -class DestroyController extends Controller -{ - private UserGroupRepositoryInterface $repository; - - public function __construct() - { - parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(UserGroupRepositoryInterface::class); - - return $next($request); - } - ); - } - - public function destroy(UserGroup $userGroup): JsonResponse - { - /** @var User $user */ - $user = auth()->user(); - // to access this function: must be group owner or sysadmin. - // need owner role or system owner role to delete user group. - $access = $user->hasSpecificRoleInGroup($userGroup, UserRoleEnum::OWNER) || $user->hasRole('owner'); - if (false === $access) { - throw new NotFoundHttpException(); - } - $this->repository->destroy($userGroup); - - return response()->json([], 204); - } -} diff --git a/app/Api/V2/Controllers/UserGroup/IndexController.php b/app/Api/V2/Controllers/UserGroup/IndexController.php deleted file mode 100644 index 5aabec109a..0000000000 --- a/app/Api/V2/Controllers/UserGroup/IndexController.php +++ /dev/null @@ -1,74 +0,0 @@ -middleware( - function ($request, $next) { - $this->repository = app(UserGroupRepositoryInterface::class); - - return $next($request); - } - ); - } - - /** - * TODO see autocomplete/accountcontroller for list. - */ - public function index(IndexRequest $request): JsonResponse - { - $administrations = $this->repository->get(); - $pageSize = $this->parameters->get('limit'); - $count = $administrations->count(); - $administrations = $administrations->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); - $paginator = new LengthAwarePaginator($administrations, $count, $pageSize, $this->parameters->get('page')); - $transformer = new UserGroupTransformer(); - - $transformer->setParameters($this->parameters); // give params to transformer - - return response() - ->json($this->jsonApiList(self::RESOURCE_KEY, $paginator, $transformer)) - ->header('Content-Type', self::CONTENT_TYPE) - ; - } -} diff --git a/app/Api/V2/Controllers/UserGroup/ShowController.php b/app/Api/V2/Controllers/UserGroup/ShowController.php deleted file mode 100644 index 9b535aaf10..0000000000 --- a/app/Api/V2/Controllers/UserGroup/ShowController.php +++ /dev/null @@ -1,88 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\UserGroup; - -use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Models\UserGroup; -use FireflyIII\Repositories\UserGroup\UserGroupRepositoryInterface; -use FireflyIII\Transformers\UserGroupTransformer; -use Illuminate\Http\JsonResponse; -use Illuminate\Pagination\LengthAwarePaginator; -use Illuminate\Support\Collection; - -/** - * Class ShowController - */ -class ShowController extends Controller -{ - private UserGroupRepositoryInterface $repository; - - public function __construct() - { - parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(UserGroupRepositoryInterface::class); - - return $next($request); - } - ); - } - - public function index(): JsonResponse - { - $collection = new Collection(); - $pageSize = $this->parameters->get('limit'); - // if the user has the system owner role, get all. Otherwise, get only the users' groups. - if (!auth()->user()->hasRole('owner')) { - $collection = $this->repository->get(); - } - if (auth()->user()->hasRole('owner')) { - $collection = $this->repository->getAll(); - } - $count = $collection->count(); - $userGroups = $collection->slice(($this->parameters->get('page') - 1) * $pageSize, $pageSize); - - $paginator = new LengthAwarePaginator($userGroups, $count, $pageSize, $this->parameters->get('page')); - $transformer = new UserGroupTransformer(); - $transformer->setParameters($this->parameters); // give params to transformer - - return response() - ->json($this->jsonApiList('user-groups', $paginator, $transformer)) - ->header('Content-Type', self::CONTENT_TYPE) - ; - } - - public function show(UserGroup $userGroup): JsonResponse - { - $transformer = new UserGroupTransformer(); - $transformer->setParameters($this->parameters); - - return response() - ->api($this->jsonApiObject('user-groups', $userGroup, $transformer)) - ->header('Content-Type', self::CONTENT_TYPE) - ; - } -} diff --git a/app/Api/V2/Controllers/UserGroup/StoreController.php b/app/Api/V2/Controllers/UserGroup/StoreController.php deleted file mode 100644 index a84add787d..0000000000 --- a/app/Api/V2/Controllers/UserGroup/StoreController.php +++ /dev/null @@ -1,64 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\UserGroup; - -use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Api\V2\Request\UserGroup\StoreRequest; -use FireflyIII\Repositories\UserGroup\UserGroupRepositoryInterface; -use FireflyIII\Transformers\UserGroupTransformer; -use Illuminate\Http\JsonResponse; - -/** - * Class StoreController - */ -class StoreController extends Controller -{ - private UserGroupRepositoryInterface $repository; - - public function __construct() - { - parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(UserGroupRepositoryInterface::class); - - return $next($request); - } - ); - } - - public function store(StoreRequest $request): JsonResponse - { - $all = $request->getAll(); - $userGroup = $this->repository->store($all); - $transformer = new UserGroupTransformer(); - $transformer->setParameters($this->parameters); - - return response() - ->api($this->jsonApiObject('user-groups', $userGroup, $transformer)) - ->header('Content-Type', self::CONTENT_TYPE) - ; - } -} diff --git a/app/Api/V2/Controllers/UserGroup/UpdateController.php b/app/Api/V2/Controllers/UserGroup/UpdateController.php deleted file mode 100644 index c881eeb887..0000000000 --- a/app/Api/V2/Controllers/UserGroup/UpdateController.php +++ /dev/null @@ -1,90 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Controllers\UserGroup; - -use FireflyIII\Api\V2\Controllers\Controller; -use FireflyIII\Api\V2\Request\UserGroup\UpdateMembershipRequest; -use FireflyIII\Api\V2\Request\UserGroup\UpdateRequest; -use FireflyIII\Models\UserGroup; -use FireflyIII\Repositories\UserGroup\UserGroupRepositoryInterface; -use FireflyIII\Transformers\UserGroupTransformer; -use Illuminate\Http\JsonResponse; - -/** - * Class UpdateController - */ -class UpdateController extends Controller -{ - // basic update van group - // add user, add rights, remove user, remove rights. - - private UserGroupRepositoryInterface $repository; - - public function __construct() - { - parent::__construct(); - $this->middleware( - function ($request, $next) { - $this->repository = app(UserGroupRepositoryInterface::class); - - return $next($request); - } - ); - } - - public function update(UpdateRequest $request, UserGroup $userGroup): JsonResponse - { - $all = $request->getAll(); - $userGroup = $this->repository->update($userGroup, $all); - $transformer = new UserGroupTransformer(); - $transformer->setParameters($this->parameters); - - return response() - ->api($this->jsonApiObject('user-groups', $userGroup, $transformer)) - ->header('Content-Type', self::CONTENT_TYPE) - ; - } - - public function updateMembership(UpdateMembershipRequest $request, UserGroup $userGroup): JsonResponse - { - $all = $request->getAll(); - $userGroup = $this->repository->updateMembership($userGroup, $all); - $transformer = new UserGroupTransformer(); - $transformer->setParameters($this->parameters); - - return response() - ->api($this->jsonApiObject('user-groups', $userGroup, $transformer)) - ->header('Content-Type', self::CONTENT_TYPE) - ; - } - - public function useUserGroup(UserGroup $userGroup): JsonResponse - { - // group validation is already in place, so can just update the user. - $this->repository->useUserGroup($userGroup); - - return response()->json([], 204); - } -} diff --git a/app/Api/V2/Request/Autocomplete/AutocompleteRequest.php b/app/Api/V2/Request/Autocomplete/AutocompleteRequest.php deleted file mode 100644 index dbc934b394..0000000000 --- a/app/Api/V2/Request/Autocomplete/AutocompleteRequest.php +++ /dev/null @@ -1,97 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Request\Autocomplete; - -use FireflyIII\Enums\AccountTypeEnum; -use FireflyIII\Support\Http\Api\AccountFilter; -use FireflyIII\Support\Request\ChecksLogin; -use FireflyIII\Support\Request\ConvertsDataTypes; -use Illuminate\Foundation\Http\FormRequest; - -/** - * Class AutocompleteRequest - */ -class AutocompleteRequest extends FormRequest -{ - use AccountFilter; - use ChecksLogin; - use ConvertsDataTypes; - - /** - * Loops over all possible query parameters (these are shared over ALL auto complete requests) - * and returns a validated array of parameters. - * - * The advantage is a single class. But you may also submit "account types" to an endpoint that doesn't use these. - */ - public function getParameters(): array - { - $array = [ - 'date' => $this->convertDateTime('date'), - 'query' => $this->clearString((string) $this->get('query')), - 'size' => $this->integerFromValue('size'), - 'page' => $this->integerFromValue('page'), - 'account_types' => $this->arrayFromValue($this->get('account_types')), - 'transaction_types' => $this->arrayFromValue($this->get('transaction_types')), - ]; - $array['size'] = $array['size'] < 1 || $array['size'] > 100 ? 15 : $array['size']; - $array['page'] = max($array['page'], 1); - if (null === $array['account_types']) { - $array['account_types'] = []; - } - if (null === $array['transaction_types']) { - $array['transaction_types'] = []; - } - - // remove 'initial balance' from allowed types. its internal - $array['account_types'] = array_diff($array['account_types'], [AccountTypeEnum::INITIAL_BALANCE->value, AccountTypeEnum::RECONCILIATION->value, AccountTypeEnum::CREDITCARD->value]); - $array['account_types'] = $this->getAccountTypeParameter($array['account_types']); - - return $array; - } - - private function getAccountTypeParameter(array $types): array - { - $return = []; - foreach ($types as $type) { - $return = array_merge($return, $this->mapAccountTypes($type)); - } - - return array_unique($return); - } - - public function rules(): array - { - $valid = array_keys($this->types); - - return [ - 'date' => 'nullable|date|after:1970-01-02|before:2038-01-17', - 'query' => 'nullable|string', - 'size' => 'nullable|integer|min:1|max:100', - 'page' => 'nullable|integer|min:1', - 'account_types' => sprintf('nullable|in:%s', implode(',', $valid)), - 'transaction_types' => 'nullable|in:todo', - ]; - } -} diff --git a/app/Api/V2/Request/Chart/BalanceChartRequest.php b/app/Api/V2/Request/Chart/BalanceChartRequest.php deleted file mode 100644 index 46c80d5f46..0000000000 --- a/app/Api/V2/Request/Chart/BalanceChartRequest.php +++ /dev/null @@ -1,90 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Request\Chart; - -use Illuminate\Contracts\Validation\Validator; -use FireflyIII\Enums\UserRoleEnum; -use FireflyIII\Support\Http\Api\ValidatesUserGroupTrait; -use FireflyIII\Support\Request\ChecksLogin; -use FireflyIII\Support\Request\ConvertsDataTypes; -use Illuminate\Foundation\Http\FormRequest; -use Illuminate\Support\Facades\Log; - -/** - * Class BalanceChartRequest - */ -class BalanceChartRequest extends FormRequest -{ - use ChecksLogin; - use ConvertsDataTypes; - use ValidatesUserGroupTrait; - - protected array $acceptedRoles = [UserRoleEnum::READ_ONLY]; - - /** - * Get all data from the request. - */ - public function getAll(): array - { - return [ - 'accounts' => $this->getAccountList(), - 'period' => $this->convertString('period'), - ]; - } - - /** - * The rules that the incoming request must be matched against. - */ - public function rules(): array - { - return [ - 'start' => 'required|date|after:1970-01-02|before:2038-01-17', - 'end' => 'required|date|after_or_equal:start|before:2038-01-17|after:1970-01-02', - 'accounts.*' => 'required|exists:accounts,id', - 'period' => sprintf('required|in:%s', implode(',', config('firefly.valid_view_ranges'))), - ]; - } - - public function withValidator(Validator $validator): void - { - $validator->after( - static function (Validator $validator): void { - // validate transaction query data. - $data = $validator->getData(); - if (!array_key_exists('accounts', $data)) { - $validator->errors()->add('accounts', trans('validation.filled', ['attribute' => 'accounts'])); - - return; - } - if (!is_array($data['accounts'])) { - $validator->errors()->add('accounts', trans('validation.filled', ['attribute' => 'accounts'])); - } - } - ); - if ($validator->fails()) { - Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray()); - } - } -} diff --git a/app/Api/V2/Request/Chart/ChartRequest.php b/app/Api/V2/Request/Chart/ChartRequest.php deleted file mode 100644 index d719129c6f..0000000000 --- a/app/Api/V2/Request/Chart/ChartRequest.php +++ /dev/null @@ -1,92 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Request\Chart; - -use Illuminate\Contracts\Validation\Validator; -use FireflyIII\Enums\UserRoleEnum; -use FireflyIII\Support\Http\Api\ValidatesUserGroupTrait; -use FireflyIII\Support\Request\ChecksLogin; -use FireflyIII\Support\Request\ConvertsDataTypes; -use Illuminate\Foundation\Http\FormRequest; -use Illuminate\Support\Facades\Log; - -/** - * Class ChartRequest - */ -class ChartRequest extends FormRequest -{ - use ChecksLogin; - use ConvertsDataTypes; - use ValidatesUserGroupTrait; - - protected array $acceptedRoles = [UserRoleEnum::READ_ONLY]; - - public function getParameters(): array - { - // $queryParameters = QueryParameters::cast($this->all()); - return [ - 'start' => $this->convertDateTime('start')?->startOfDay(), - 'end' => $this->convertDateTime('end')?->endOfDay(), - 'preselected' => $this->convertString('preselected', 'empty'), - 'period' => $this->convertString('period', '1M'), - 'accounts' => $this->arrayFromValue($this->get('accounts')), - ]; - } - - /** - * The rules that the incoming request must be matched against. - */ - public function rules(): array - { - return [ - 'start' => 'required|date|after:1970-01-02|before:2038-01-17|before_or_equal:end', - 'end' => 'required|date|after:1970-01-02|before:2038-01-17|after_or_equal:start', - 'preselected' => sprintf('nullable|in:%s', implode(',', config('firefly.preselected_accounts'))), - 'period' => sprintf('nullable|in:%s', implode(',', config('firefly.valid_view_ranges'))), - 'accounts.*' => 'exists:accounts,id', - ]; - - } - - public function withValidator(Validator $validator): void - { - $validator->after( - static function (Validator $validator): void { - // validate transaction query data. - $data = $validator->getData(); - if (!array_key_exists('accounts', $data)) { - // $validator->errors()->add('accounts', trans('validation.filled', ['attribute' => 'accounts'])); - return; - } - if (!is_array($data['accounts'])) { - $validator->errors()->add('accounts', trans('validation.filled', ['attribute' => 'accounts'])); - } - } - ); - if ($validator->fails()) { - Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray()); - } - } -} diff --git a/app/Api/V2/Request/Chart/DashboardChartRequest.php b/app/Api/V2/Request/Chart/DashboardChartRequest.php deleted file mode 100644 index 08f1845ff1..0000000000 --- a/app/Api/V2/Request/Chart/DashboardChartRequest.php +++ /dev/null @@ -1,89 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Request\Chart; - -use Illuminate\Contracts\Validation\Validator; -use FireflyIII\Enums\UserRoleEnum; -use FireflyIII\Support\Http\Api\ValidatesUserGroupTrait; -use FireflyIII\Support\Request\ChecksLogin; -use FireflyIII\Support\Request\ConvertsDataTypes; -use Illuminate\Foundation\Http\FormRequest; -use Illuminate\Support\Facades\Log; - -/** - * Class DashboardChartRequest - */ -class DashboardChartRequest extends FormRequest -{ - use ChecksLogin; - use ConvertsDataTypes; - use ValidatesUserGroupTrait; - - protected array $acceptedRoles = [UserRoleEnum::READ_ONLY]; - - /** - * Get all data from the request. - */ - public function getAll(): array - { - return [ - 'accounts' => $this->getAccountList(), - 'preselected' => $this->convertString('preselected'), - ]; - } - - /** - * The rules that the incoming request must be matched against. - */ - public function rules(): array - { - return [ - 'start' => 'required|date|after:1970-01-02|before:2038-01-17', - 'end' => 'required|date|after_or_equal:start|before:2038-01-17|after:1970-01-02', - 'preselected' => sprintf('in:%s', implode(',', config('firefly.preselected_accounts'))), - 'accounts.*' => 'exists:accounts,id', - ]; - } - - public function withValidator(Validator $validator): void - { - $validator->after( - static function (Validator $validator): void { - // validate transaction query data. - $data = $validator->getData(); - if (!array_key_exists('accounts', $data)) { - // $validator->errors()->add('accounts', trans('validation.filled', ['attribute' => 'accounts'])); - return; - } - if (!is_array($data['accounts'])) { - $validator->errors()->add('accounts', trans('validation.filled', ['attribute' => 'accounts'])); - } - } - ); - if ($validator->fails()) { - Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray()); - } - } -} diff --git a/app/Api/V2/Request/Generic/DateRequest.php b/app/Api/V2/Request/Generic/DateRequest.php deleted file mode 100644 index 54ee20d068..0000000000 --- a/app/Api/V2/Request/Generic/DateRequest.php +++ /dev/null @@ -1,62 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Request\Generic; - -use FireflyIII\Support\Request\ChecksLogin; -use FireflyIII\Support\Request\ConvertsDataTypes; -use Illuminate\Foundation\Http\FormRequest; - -/** - * Request class for end points that require date parameters. - * - * Class DateRequest - */ -class DateRequest extends FormRequest -{ - use ChecksLogin; - use ConvertsDataTypes; - - /** - * Get all data from the request. - */ - public function getAll(): array - { - return [ - 'start' => $this->getCarbonDate('start')->startOfDay(), - 'end' => $this->getCarbonDate('end')->endOfDay(), - ]; - } - - /** - * The rules that the incoming request must be matched against. - */ - public function rules(): array - { - return [ - 'start' => 'required|date|after:1970-01-02|before:2038-01-17', - 'end' => 'required|date|after_or_equal:start|before:2038-01-17|after:1970-01-02', - ]; - } -} diff --git a/app/Api/V2/Request/Generic/SingleDateRequest.php b/app/Api/V2/Request/Generic/SingleDateRequest.php deleted file mode 100644 index 12bd373c80..0000000000 --- a/app/Api/V2/Request/Generic/SingleDateRequest.php +++ /dev/null @@ -1,59 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Request\Generic; - -use Carbon\Carbon; -use FireflyIII\Support\Request\ChecksLogin; -use FireflyIII\Support\Request\ConvertsDataTypes; -use Illuminate\Foundation\Http\FormRequest; - -/** - * Request class for end points that require a date parameter. - * - * Class SingleDateRequest - */ -class SingleDateRequest extends FormRequest -{ - use ChecksLogin; - use ConvertsDataTypes; - - /** - * Get all data from the request. - */ - public function getDate(): Carbon - { - return $this->getCarbonDate('date'); - } - - /** - * The rules that the incoming request must be matched against. - */ - public function rules(): array - { - return [ - 'date' => 'required|date|after:1970-01-02|before:2038-01-17', - ]; - } -} diff --git a/app/Api/V2/Request/Model/Account/IndexRequest.php b/app/Api/V2/Request/Model/Account/IndexRequest.php deleted file mode 100644 index 64a748175c..0000000000 --- a/app/Api/V2/Request/Model/Account/IndexRequest.php +++ /dev/null @@ -1,71 +0,0 @@ -get('type', 'default'); - - return $this->mapAccountTypes($type); - } - - public function getDate(): Carbon - { - return $this->getCarbonDate('date'); - } - - /** - * The rules that the incoming request must be matched against. - */ - public function rules(): array - { - return [ - 'date' => 'date|after:1970-01-02|before:2038-01-17', - 'start' => 'date|after:1970-01-02|before:2038-01-17|before:end|required_with:end', - 'end' => 'date|after:1970-01-02|before:2038-01-17|after:start|required_with:start', - ]; - } -} diff --git a/app/Api/V2/Request/Model/Account/UpdateRequest.php b/app/Api/V2/Request/Model/Account/UpdateRequest.php deleted file mode 100644 index 19086211b3..0000000000 --- a/app/Api/V2/Request/Model/Account/UpdateRequest.php +++ /dev/null @@ -1,117 +0,0 @@ - ['name', 'convertString'], - 'active' => ['active', 'boolean'], - 'include_net_worth' => ['include_net_worth', 'boolean'], - 'account_type_name' => ['type', 'convertString'], - 'virtual_balance' => ['virtual_balance', 'convertString'], - 'iban' => ['iban', 'convertString'], - 'BIC' => ['bic', 'convertString'], - 'account_number' => ['account_number', 'convertString'], - 'account_role' => ['account_role', 'convertString'], - 'liability_type' => ['liability_type', 'convertString'], - 'opening_balance' => ['opening_balance', 'convertString'], - 'opening_balance_date' => ['opening_balance_date', 'convertDateTime'], - 'cc_type' => ['credit_card_type', 'convertString'], - 'cc_monthly_payment_date' => ['monthly_payment_date', 'convertDateTime'], - 'notes' => ['notes', 'stringWithNewlines'], - 'interest' => ['interest', 'convertString'], - 'interest_period' => ['interest_period', 'convertString'], - 'order' => ['order', 'convertInteger'], - 'currency_id' => ['currency_id', 'convertInteger'], - 'currency_code' => ['currency_code', 'convertString'], - 'liability_direction' => ['liability_direction', 'convertString'], - 'liability_amount' => ['liability_amount', 'convertString'], - 'liability_start_date' => ['liability_start_date', 'date'], - ]; - $data = $this->getAllData($fields); - - return $this->appendLocationData($data, null); - } - - /** - * TODO is a duplicate of the v1 UpdateRequest method. - * - * The rules that the incoming request must be matched against. - */ - public function rules(): array - { - /** @var Account $account */ - $account = $this->route()->parameter('account'); - $accountRoles = implode(',', config('firefly.accountRoles')); - $types = implode(',', array_keys(config('firefly.subTitlesByIdentifier'))); - $ccPaymentTypes = implode(',', array_keys(config('firefly.ccTypes'))); - - $rules = [ - 'name' => sprintf('min:1|max:1024|uniqueAccountForUser:%d', $account->id), - 'type' => sprintf('in:%s', $types), - 'iban' => ['iban', 'nullable', new UniqueIban($account, $this->convertString('type'))], - 'bic' => 'bic|nullable', - 'account_number' => ['min:1', 'max:255', 'nullable', new UniqueAccountNumber($account, $this->convertString('type'))], - 'opening_balance' => 'numeric|required_with:opening_balance_date|nullable', - 'opening_balance_date' => 'date|required_with:opening_balance|nullable', - 'virtual_balance' => 'numeric|nullable', - 'order' => 'numeric|nullable', - 'currency_id' => 'numeric|exists:transaction_currencies,id', - 'currency_code' => 'min:3|max:51|exists:transaction_currencies,code', - 'active' => [new IsBoolean()], - 'include_net_worth' => [new IsBoolean()], - 'account_role' => sprintf('in:%s|nullable|required_if:type,asset', $accountRoles), - 'credit_card_type' => sprintf('in:%s|nullable|required_if:account_role,ccAsset', $ccPaymentTypes), - 'monthly_payment_date' => 'date|nullable|required_if:account_role,ccAsset|required_if:credit_card_type,monthlyFull', - 'liability_type' => 'required_if:type,liability|in:loan,debt,mortgage', - 'liability_direction' => 'required_if:type,liability|in:credit,debit', - 'interest' => 'required_if:type,liability|min:0|max:100|numeric', - 'interest_period' => 'required_if:type,liability|in:daily,monthly,yearly', - 'notes' => 'min:0|max:32768', - ]; - - return Location::requestRules($rules); - } -} diff --git a/app/Api/V2/Request/Model/Transaction/InfiniteListRequest.php b/app/Api/V2/Request/Model/Transaction/InfiniteListRequest.php deleted file mode 100644 index e54a4d836d..0000000000 --- a/app/Api/V2/Request/Model/Transaction/InfiniteListRequest.php +++ /dev/null @@ -1,118 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Request\Model\Transaction; - -use Carbon\Carbon; -use FireflyIII\Support\Http\Api\AccountFilter; -use FireflyIII\Support\Http\Api\TransactionFilter; -use FireflyIII\Support\Request\ChecksLogin; -use FireflyIII\Support\Request\ConvertsDataTypes; -use FireflyIII\Support\Request\GetSortInstructions; -use Illuminate\Foundation\Http\FormRequest; - -/** - * Class InfiniteListRequest - * Used specifically to list transactions. - */ -class InfiniteListRequest extends FormRequest -{ - use AccountFilter; - use ChecksLogin; - use ConvertsDataTypes; - use GetSortInstructions; - use TransactionFilter; - - public function buildParams(): string - { - $array = [ - 'start_row' => $this->getStartRow(), - 'end_row' => $this->getEndRow(), - ]; - - $start = $this->getStartDate(); - $end = $this->getEndDate(); - if ($start instanceof Carbon && $end instanceof Carbon) { - $array['start'] = $start->format('Y-m-d'); - $array['end'] = $end->format('Y-m-d'); - } - - return http_build_query($array); - } - - public function getStartRow(): int - { - $startRow = $this->convertInteger('start_row'); - - return $startRow < 0 || $startRow > 4294967296 ? 0 : $startRow; - } - - public function getEndRow(): int - { - $endRow = $this->convertInteger('end_row'); - - return $endRow <= 0 || $endRow > 4294967296 ? 100 : $endRow; - } - - public function getStartDate(): ?Carbon - { - return $this->getCarbonDate('start'); - } - - public function getEndDate(): ?Carbon - { - return $this->getCarbonDate('end'); - } - - public function getAccountTypes(): array - { - $type = (string) $this->get('type', 'default'); - - return $this->mapAccountTypes($type); - } - - public function getPage(): int - { - $page = $this->convertInteger('page'); - - return 0 === $page || $page > 65536 ? 1 : $page; - } - - public function getTransactionTypes(): array - { - $type = (string) $this->get('type', 'default'); - - return $this->mapTransactionTypes($type); - } - - public function rules(): array - { - return [ - 'start' => 'date|after:1970-01-02|before:2038-01-17', - 'end' => 'date|after:start|after:1970-01-02|before:2038-01-17', - 'start_row' => 'integer|min:0|max:4294967296', - 'end_row' => 'integer|min:0|max:4294967296|gt:start_row', - ]; - } -} diff --git a/app/Api/V2/Request/Model/Transaction/ListRequest.php b/app/Api/V2/Request/Model/Transaction/ListRequest.php deleted file mode 100644 index 70d4ae70c2..0000000000 --- a/app/Api/V2/Request/Model/Transaction/ListRequest.php +++ /dev/null @@ -1,91 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Request\Model\Transaction; - -use Carbon\Carbon; -use FireflyIII\Support\Http\Api\TransactionFilter; -use FireflyIII\Support\Request\ChecksLogin; -use FireflyIII\Support\Request\ConvertsDataTypes; -use Illuminate\Foundation\Http\FormRequest; - -/** - * Class ListRequest - * Used specifically to list transactions. - */ -class ListRequest extends FormRequest -{ - use ChecksLogin; - use ConvertsDataTypes; - use TransactionFilter; - - public function buildParams(int $pageSize): string - { - $array = [ - 'page' => $this->getPage(), - 'limit' => $pageSize, - ]; - - $start = $this->getStartDate(); - $end = $this->getEndDate(); - if ($start instanceof Carbon && $end instanceof Carbon) { - $array['start'] = $start->format('Y-m-d'); - $array['end'] = $end->format('Y-m-d'); - } - - return http_build_query($array); - } - - public function getPage(): int - { - $page = $this->convertInteger('page'); - - return 0 === $page || $page > 65536 ? 1 : $page; - } - - public function getStartDate(): ?Carbon - { - return $this->getCarbonDate('start'); - } - - public function getEndDate(): ?Carbon - { - return $this->getCarbonDate('end'); - } - - public function getTransactionTypes(): array - { - $type = (string) $this->get('type', 'default'); - - return $this->mapTransactionTypes($type); - } - - public function rules(): array - { - return [ - 'start' => 'date|after:1970-01-02|before:2038-01-17', - 'end' => 'date|after:start|after:1970-01-02|before:2038-01-17', - ]; - } -} diff --git a/app/Api/V2/Request/Model/Transaction/StoreRequest.php b/app/Api/V2/Request/Model/Transaction/StoreRequest.php deleted file mode 100644 index 18cc85d5a2..0000000000 --- a/app/Api/V2/Request/Model/Transaction/StoreRequest.php +++ /dev/null @@ -1,317 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Request\Model\Transaction; - -use Illuminate\Contracts\Validation\Validator; -use FireflyIII\Enums\UserRoleEnum; -use FireflyIII\Models\UserGroup; -use FireflyIII\Rules\BelongsUserGroup; -use FireflyIII\Rules\IsBoolean; -use FireflyIII\Rules\IsDateOrTime; -use FireflyIII\Rules\IsValidPositiveAmount; -use FireflyIII\Support\NullArrayObject; -use FireflyIII\Support\Request\AppendsLocationData; -use FireflyIII\Support\Request\ChecksLogin; -use FireflyIII\Support\Request\ConvertsDataTypes; -use FireflyIII\User; -use FireflyIII\Validation\CurrencyValidation; -use FireflyIII\Validation\GroupValidation; -use FireflyIII\Validation\TransactionValidation; -use Illuminate\Foundation\Http\FormRequest; -use Illuminate\Support\Facades\Log; - -/** - * Class StoreRequest - * - * TODO this class is basically the same as the v1 request. However, it does not accept - * TODO models, objects and references that are NOT part of the designated user group (aka administration). - * TODO this distinction is already made in the CheckLogin trait, where there is also a convenient function - * TODO to grab the current UserGroup. This code is slightly different from other v2 apis that use - * TODO the "administration_id", those will have to be updated later on. - */ -class StoreRequest extends FormRequest -{ - use AppendsLocationData; - use ChecksLogin; - - use ConvertsDataTypes; - use CurrencyValidation; - use GroupValidation; - use TransactionValidation; - - protected array $acceptedRoles = [UserRoleEnum::MANAGE_TRANSACTIONS]; - - /** - * Get all data. - */ - public function getAll(): array - { - app('log')->debug('V2: Get all data in TransactionStoreRequest'); - - return [ - 'group_title' => $this->convertString('group_title'), - 'error_if_duplicate_hash' => $this->boolean('error_if_duplicate_hash'), - 'apply_rules' => $this->boolean('apply_rules', true), - 'fire_webhooks' => $this->boolean('fire_webhooks', true), - 'transactions' => $this->getTransactionData(), - ]; - } - - /** - * Get transaction data. - */ - private function getTransactionData(): array - { - $return = []; - - /** - * @var array $transaction - */ - foreach ($this->get('transactions') as $transaction) { - $object = new NullArrayObject($transaction); - $result = [ - 'type' => $this->clearString($object['type']), - 'date' => $this->dateFromValue($object['date']), - 'order' => $this->integerFromValue((string) $object['order']), - - 'currency_id' => $this->integerFromValue((string) $object['currency_id']), - 'currency_code' => $this->clearString((string) $object['currency_code']), - - // foreign currency info: - 'foreign_currency_id' => $this->integerFromValue((string) $object['foreign_currency_id']), - 'foreign_currency_code' => $this->clearString((string) $object['foreign_currency_code']), - - // amount and foreign amount. Cannot be 0. - 'amount' => $this->clearString((string) $object['amount']), - 'foreign_amount' => $this->clearString((string) $object['foreign_amount']), - - // description. - 'description' => $this->clearString($object['description']), - - // source of transaction. If everything is null, assume cash account. - 'source_id' => $this->integerFromValue((string) $object['source_id']), - 'source_name' => $this->clearString((string) $object['source_name']), - 'source_iban' => $this->clearString((string) $object['source_iban']), - 'source_number' => $this->clearString((string) $object['source_number']), - 'source_bic' => $this->clearString((string) $object['source_bic']), - - // destination of transaction. If everything is null, assume cash account. - 'destination_id' => $this->integerFromValue((string) $object['destination_id']), - 'destination_name' => $this->clearString((string) $object['destination_name']), - 'destination_iban' => $this->clearString((string) $object['destination_iban']), - 'destination_number' => $this->clearString((string) $object['destination_number']), - 'destination_bic' => $this->clearString((string) $object['destination_bic']), - - // budget info - 'budget_id' => $this->integerFromValue((string) $object['budget_id']), - 'budget_name' => $this->clearString((string) $object['budget_name']), - - // category info - 'category_id' => $this->integerFromValue((string) $object['category_id']), - 'category_name' => $this->clearString((string) $object['category_name']), - - // journal bill reference. Optional. Will only work for withdrawals - 'bill_id' => $this->integerFromValue((string) $object['bill_id']), - 'bill_name' => $this->clearString((string) $object['bill_name']), - - // 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']), - - // some other interesting properties - 'reconciled' => $this->convertBoolean((string) $object['reconciled']), - 'notes' => $this->clearStringKeepNewlines((string) $object['notes']), - 'tags' => $this->arrayFromValue($object['tags']), - - // all custom fields: - 'internal_reference' => $this->clearString((string) $object['internal_reference']), - 'external_id' => $this->clearString((string) $object['external_id']), - 'original_source' => sprintf('ff3-v%s', config('firefly.version')), - 'recurrence_id' => $this->integerFromValue($object['recurrence_id']), - 'bunq_payment_id' => $this->clearString((string) $object['bunq_payment_id']), - 'external_url' => $this->clearString((string) $object['external_url']), - - 'sepa_cc' => $this->clearString((string) $object['sepa_cc']), - 'sepa_ct_op' => $this->clearString((string) $object['sepa_ct_op']), - 'sepa_ct_id' => $this->clearString((string) $object['sepa_ct_id']), - 'sepa_db' => $this->clearString((string) $object['sepa_db']), - 'sepa_country' => $this->clearString((string) $object['sepa_country']), - 'sepa_ep' => $this->clearString((string) $object['sepa_ep']), - 'sepa_ci' => $this->clearString((string) $object['sepa_ci']), - 'sepa_batch_id' => $this->clearString((string) $object['sepa_batch_id']), - // custom date fields. Must be Carbon objects. Presence is optional. - 'interest_date' => $this->dateFromValue($object['interest_date']), - 'book_date' => $this->dateFromValue($object['book_date']), - 'process_date' => $this->dateFromValue($object['process_date']), - 'due_date' => $this->dateFromValue($object['due_date']), - 'payment_date' => $this->dateFromValue($object['payment_date']), - 'invoice_date' => $this->dateFromValue($object['invoice_date']), - ]; - $result = $this->addFromromTransactionStore($transaction, $result); - $return[] = $result; - } - - return $return; - } - - /** - * The rules that the incoming request must be matched against. - */ - public function rules(): array - { - app('log')->debug('V2: Collect rules of TransactionStoreRequest'); - - // at this point the userGroup can't be NULL because the - // authorize() method will complain. Loudly. - /** @var UserGroup $userGroup */ - $userGroup = $this->getUserGroup(); - - return [ - // basic fields for group: - 'group_title' => 'min:1|max:1000|nullable', - 'error_if_duplicate_hash' => [new IsBoolean()], - 'apply_rules' => [new IsBoolean()], - - // transaction rules (in array for splits): - 'transactions.*.type' => 'required|in:withdrawal,deposit,transfer,opening-balance,reconciliation', - 'transactions.*.date' => ['required', new IsDateOrTime()], - 'transactions.*.order' => 'numeric|min:0', - - // currency info - 'transactions.*.currency_id' => 'numeric|exists:transaction_currencies,id|nullable', - 'transactions.*.currency_code' => 'min:3|max:51|exists:transaction_currencies,code|nullable', - 'transactions.*.foreign_currency_id' => 'numeric|exists:transaction_currencies,id|nullable', - 'transactions.*.foreign_currency_code' => 'min:3|max:51|exists:transaction_currencies,code|nullable', - - // amount - 'transactions.*.amount' => ['required', new IsValidPositiveAmount()], - 'transactions.*.foreign_amount' => ['nullable', new IsValidPositiveAmount()], - - // description - 'transactions.*.description' => 'nullable|min:1|max:1000', - - // source of transaction - 'transactions.*.source_id' => ['numeric', 'nullable', new BelongsUserGroup($userGroup)], - 'transactions.*.source_name' => 'min:1|max:255|nullable', - 'transactions.*.source_iban' => 'min:1|max:255|nullable|iban', - 'transactions.*.source_number' => 'min:1|max:255|nullable', - 'transactions.*.source_bic' => 'min:1|max:255|nullable|bic', - - // destination of transaction - 'transactions.*.destination_id' => ['numeric', 'nullable', new BelongsUserGroup($userGroup)], - 'transactions.*.destination_name' => 'min:1|max:255|nullable', - 'transactions.*.destination_iban' => 'min:1|max:255|nullable|iban', - 'transactions.*.destination_number' => 'min:1|max:255|nullable', - 'transactions.*.destination_bic' => 'min:1|max:255|nullable|bic', - - // budget, category, bill and piggy - 'transactions.*.budget_id' => ['mustExist:budgets,id', new BelongsUserGroup($userGroup)], - 'transactions.*.budget_name' => ['min:1', 'max:255', 'nullable', new BelongsUserGroup($userGroup)], - 'transactions.*.category_id' => ['mustExist:categories,id', new BelongsUserGroup($userGroup), 'nullable'], - 'transactions.*.category_name' => 'min:1|max:255|nullable', - 'transactions.*.bill_id' => ['numeric', 'nullable', 'mustExist:bills,id', new BelongsUserGroup($userGroup)], - 'transactions.*.bill_name' => ['min:1', 'max:255', 'nullable', new BelongsUserGroup($userGroup)], - 'transactions.*.piggy_bank_id' => ['numeric', 'nullable', 'mustExist:piggy_banks,id', new BelongsUserGroup($userGroup)], - 'transactions.*.piggy_bank_name' => ['min:1', 'max:255', 'nullable', new BelongsUserGroup($userGroup)], - - // other interesting fields - 'transactions.*.reconciled' => [new IsBoolean()], - 'transactions.*.notes' => 'min:1|max:32768|nullable', - 'transactions.*.tags' => 'min:0|max:255', - 'transactions.*.tags.*' => 'min:0|max:255', - - // meta info fields - 'transactions.*.internal_reference' => 'min:1|max:255|nullable', - 'transactions.*.external_id' => 'min:1|max:255|nullable', - 'transactions.*.recurrence_id' => 'min:1|max:255|nullable', - 'transactions.*.bunq_payment_id' => 'min:1|max:255|nullable', - 'transactions.*.external_url' => 'min:1|max:255|nullable|url', - - // SEPA fields: - 'transactions.*.sepa_cc' => 'min:1|max:255|nullable', - 'transactions.*.sepa_ct_op' => 'min:1|max:255|nullable', - 'transactions.*.sepa_ct_id' => 'min:1|max:255|nullable', - 'transactions.*.sepa_db' => 'min:1|max:255|nullable', - 'transactions.*.sepa_country' => 'min:1|max:255|nullable', - 'transactions.*.sepa_ep' => 'min:1|max:255|nullable', - 'transactions.*.sepa_ci' => 'min:1|max:255|nullable', - 'transactions.*.sepa_batch_id' => 'min:1|max:255|nullable', - - // dates - 'transactions.*.interest_date' => 'date|nullable', - 'transactions.*.book_date' => 'date|nullable', - 'transactions.*.process_date' => 'date|nullable', - 'transactions.*.due_date' => 'date|nullable', - 'transactions.*.payment_date' => 'date|nullable', - 'transactions.*.invoice_date' => 'date|nullable', - - // TODO include location and ability to process it. - ]; - } - - /** - * Configure the validator instance. - */ - public function withValidator(Validator $validator): void - { - /** @var User $user */ - $user = auth()->user(); - - /** @var UserGroup $userGroup */ - $userGroup = $this->getUserGroup(); - $validator->after( - function (Validator $validator) use ($user, $userGroup): void { - // must be valid array. - $this->validateTransactionArray($validator); // does not need group validation. - - // must submit at least one transaction. - app('log')->debug('Now going to validateOneTransaction'); - $this->validateOneTransaction($validator); // does not need group validation. - app('log')->debug('Now done with validateOneTransaction'); - - // all journals must have a description - $this->validateDescriptions($validator); // does not need group validation. - - // all transaction types must be equal: - $this->validateTransactionTypes($validator); // does not need group validation. - - // validate foreign currency info - $this->validateForeignCurrencyInformation($validator); // does not need group validation. - - // validate all account info - $this->validateAccountInformation($validator, $user, $userGroup); - - // validate source/destination is equal, depending on the transaction journal type. - $this->validateEqualAccounts($validator); - - // the group must have a description if > 1 journal. - $this->validateGroupDescription($validator); - } - ); - if ($validator->fails()) { - Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray()); - } - } -} diff --git a/app/Api/V2/Request/Model/Transaction/UpdateRequest.php b/app/Api/V2/Request/Model/Transaction/UpdateRequest.php deleted file mode 100644 index ea4727a1bc..0000000000 --- a/app/Api/V2/Request/Model/Transaction/UpdateRequest.php +++ /dev/null @@ -1,371 +0,0 @@ -integerFields = ['order', 'currency_id', 'foreign_currency_id', 'transaction_journal_id', 'source_id', 'destination_id', 'budget_id', 'category_id', 'bill_id', 'recurrence_id']; - $this->dateFields = ['date', 'interest_date', 'book_date', 'process_date', 'due_date', 'payment_date', 'invoice_date']; - $this->textareaFields = ['notes']; - // not really floats, for validation. - $this->floatFields = ['amount', 'foreign_amount']; - $this->stringFields = ['type', 'currency_code', 'foreign_currency_code', 'description', 'source_name', 'source_iban', 'source_number', 'source_bic', 'destination_name', 'destination_iban', 'destination_number', 'destination_bic', 'budget_name', 'category_name', 'bill_name', 'internal_reference', 'external_id', 'bunq_payment_id', 'sepa_cc', 'sepa_ct_op', 'sepa_ct_id', 'sepa_db', 'sepa_country', 'sepa_ep', 'sepa_ci', 'sepa_batch_id', 'external_url']; - $this->booleanFields = ['reconciled']; - $this->arrayFields = ['tags']; - $data = []; - if ($this->has('transactions')) { - $data['transactions'] = $this->getTransactionData(); - } - if ($this->has('apply_rules')) { - $data['apply_rules'] = $this->boolean('apply_rules', true); - } - if ($this->has('fire_webhooks')) { - $data['fire_webhooks'] = $this->boolean('fire_webhooks', true); - } - if ($this->has('group_title')) { - $data['group_title'] = $this->convertString('group_title'); - } - - return $data; - } - - /** - * Get transaction data. - * - * @throws FireflyException - */ - private function getTransactionData(): array - { - Log::debug(sprintf('Now in %s', __METHOD__)); - $return = []; - - /** @var null|array $transactions */ - $transactions = $this->get('transactions'); - - if (!is_countable($transactions)) { - return $return; - } - - /** @var null|array $transaction */ - foreach ($transactions as $transaction) { - if (!is_array($transaction)) { - throw new FireflyException('Invalid data submitted: transaction is not array.'); - } - // default response is to update nothing in the transaction: - $current = []; - $current = $this->getIntegerData($current, $transaction); - $current = $this->getStringData($current, $transaction); - $current = $this->getNlStringData($current, $transaction); - $current = $this->getDateData($current, $transaction); - $current = $this->getBooleanData($current, $transaction); - $current = $this->getArrayData($current, $transaction); - $current = $this->getFloatData($current, $transaction); - $return[] = $current; - } - - return $return; - } - - /** - * For each field, add it to the array if a reference is present in the request: - * - * @param array $current - * @param array $transaction - */ - private function getIntegerData(array $current, array $transaction): array - { - foreach ($this->integerFields as $fieldName) { - if (array_key_exists($fieldName, $transaction)) { - $current[$fieldName] = $this->integerFromValue((string) $transaction[$fieldName]); - } - } - - return $current; - } - - /** - * @param array $current - * @param array $transaction - */ - private function getStringData(array $current, array $transaction): array - { - foreach ($this->stringFields as $fieldName) { - if (array_key_exists($fieldName, $transaction)) { - $current[$fieldName] = $this->clearString((string) $transaction[$fieldName]); - } - } - - return $current; - } - - /** - * @param array $current - * @param array $transaction - */ - private function getNlStringData(array $current, array $transaction): array - { - foreach ($this->textareaFields as $fieldName) { - if (array_key_exists($fieldName, $transaction)) { - $current[$fieldName] = $this->clearStringKeepNewlines((string) $transaction[$fieldName]); // keep newlines - } - } - - return $current; - } - - /** - * @param array $current - * @param array $transaction - */ - private function getDateData(array $current, array $transaction): array - { - foreach ($this->dateFields as $fieldName) { - Log::debug(sprintf('Now at date field %s', $fieldName)); - if (array_key_exists($fieldName, $transaction)) { - Log::debug(sprintf('New value: "%s"', $transaction[$fieldName])); - $current[$fieldName] = $this->dateFromValue((string) $transaction[$fieldName]); - } - } - - return $current; - } - - /** - * @param array $current - * @param array $transaction - */ - private function getBooleanData(array $current, array $transaction): array - { - foreach ($this->booleanFields as $fieldName) { - if (array_key_exists($fieldName, $transaction)) { - $current[$fieldName] = $this->convertBoolean((string) $transaction[$fieldName]); - } - } - - return $current; - } - - /** - * @param array $current - * @param array $transaction - */ - private function getArrayData(array $current, array $transaction): array - { - foreach ($this->arrayFields as $fieldName) { - if (array_key_exists($fieldName, $transaction)) { - $current[$fieldName] = $this->arrayFromValue($transaction[$fieldName]); - } - } - - return $current; - } - - /** - * @param array $current - * @param array $transaction - */ - private function getFloatData(array $current, array $transaction): array - { - foreach ($this->floatFields as $fieldName) { - if (array_key_exists($fieldName, $transaction)) { - $value = $transaction[$fieldName]; - if (is_float($value)) { - $current[$fieldName] = sprintf('%.12f', $value); - } - if (!is_float($value)) { - $current[$fieldName] = (string) $value; - } - } - } - - return $current; - } - - /** - * The rules that the incoming request must be matched against. - */ - #[Override] - public function rules(): array - { - Log::debug(sprintf('Now in %s', __METHOD__)); - $validProtocols = config('firefly.valid_url_protocols'); - - return [ - // basic fields for group: - 'group_title' => 'min:1|max:1000|nullable', - 'apply_rules' => [new IsBoolean()], - - // transaction rules (in array for splits): - 'transactions.*.type' => 'in:withdrawal,deposit,transfer,opening-balance,reconciliation', - 'transactions.*.date' => [new IsDateOrTime()], - 'transactions.*.order' => 'numeric|min:0', - - // group id: - 'transactions.*.transaction_journal_id' => ['nullable', 'numeric', new BelongsUser()], - - // currency info - 'transactions.*.currency_id' => 'numeric|exists:transaction_currencies,id|nullable', - 'transactions.*.currency_code' => 'min:3|max:51|exists:transaction_currencies,code|nullable', - 'transactions.*.foreign_currency_id' => 'nullable|numeric|exists:transaction_currencies,id', - 'transactions.*.foreign_currency_code' => 'nullable|min:3|max:51|exists:transaction_currencies,code', - - // amount - 'transactions.*.amount' => ['nullable', new IsValidPositiveAmount()], - 'transactions.*.foreign_amount' => ['nullable', new IsValidZeroOrMoreAmount()], - - // description - 'transactions.*.description' => 'nullable|min:1|max:1000', - - // source of transaction - 'transactions.*.source_id' => ['numeric', 'nullable', new BelongsUser()], - 'transactions.*.source_name' => 'min:1|max:255|nullable', - - // destination of transaction - 'transactions.*.destination_id' => ['numeric', 'nullable', new BelongsUser()], - 'transactions.*.destination_name' => 'min:1|max:255|nullable', - - // budget, category, bill and piggy - 'transactions.*.budget_id' => ['mustExist:budgets,id', new BelongsUser(), 'nullable'], - 'transactions.*.budget_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], - 'transactions.*.category_id' => ['mustExist:categories,id', new BelongsUser(), 'nullable'], - 'transactions.*.category_name' => 'min:1|max:255|nullable', - 'transactions.*.bill_id' => ['numeric', 'nullable', 'mustExist:bills,id', new BelongsUser()], - 'transactions.*.bill_name' => ['min:1', 'max:255', 'nullable', new BelongsUser()], - - // other interesting fields - 'transactions.*.reconciled' => [new IsBoolean()], - 'transactions.*.notes' => 'min:1|max:32768|nullable', - 'transactions.*.tags' => 'min:0|max:255|nullable', - 'transactions.*.tags.*' => 'min:0|max:255', - - // meta info fields - 'transactions.*.internal_reference' => 'min:1|max:255|nullable', - 'transactions.*.external_id' => 'min:1|max:255|nullable', - 'transactions.*.recurrence_id' => 'min:1|max:255|nullable', - 'transactions.*.bunq_payment_id' => 'min:1|max:255|nullable', - 'transactions.*.external_url' => sprintf('min:1|max:255|nullable|url:%s', $validProtocols), - - // SEPA fields: - 'transactions.*.sepa_cc' => 'min:1|max:255|nullable', - 'transactions.*.sepa_ct_op' => 'min:1|max:255|nullable', - 'transactions.*.sepa_ct_id' => 'min:1|max:255|nullable', - 'transactions.*.sepa_db' => 'min:1|max:255|nullable', - 'transactions.*.sepa_country' => 'min:1|max:255|nullable', - 'transactions.*.sepa_ep' => 'min:1|max:255|nullable', - 'transactions.*.sepa_ci' => 'min:1|max:255|nullable', - 'transactions.*.sepa_batch_id' => 'min:1|max:255|nullable', - - // dates - 'transactions.*.interest_date' => 'date|nullable', - 'transactions.*.book_date' => 'date|nullable', - 'transactions.*.process_date' => 'date|nullable', - 'transactions.*.due_date' => 'date|nullable', - 'transactions.*.payment_date' => 'date|nullable', - 'transactions.*.invoice_date' => 'date|nullable', - ]; - } - - /** - * Configure the validator instance. - */ - #[Override] - public function withValidator(Validator $validator): void - { - Log::debug('Now in withValidator'); - - /** @var TransactionGroup $transactionGroup */ - $transactionGroup = $this->route()->parameter('userGroupTransaction'); - $validator->after( - function (Validator $validator) use ($transactionGroup): void { - // if more than one, verify that there are journal ID's present. - $this->validateJournalIds($validator, $transactionGroup); - - // all transaction types must be equal: - $this->validateTransactionTypesForUpdate($validator); - - // user wants to update a reconciled transaction. - // source, destination, amount + foreign_amount cannot be changed - // and must be omitted from the request. - $this->preventUpdateReconciled($validator, $transactionGroup); - - // validate source/destination is equal, depending on the transaction journal type. - $this->validateEqualAccountsForUpdate($validator, $transactionGroup); - - // see method: - // $this->preventNoAccountInfo($validator, ); - - // validate that the currency fits the source and/or destination account. - // validate all account info - $this->validateAccountInformationUpdate($validator, $transactionGroup); - } - ); - if ($validator->fails()) { - Log::channel('audit')->error(sprintf('Validation errors in %s', self::class), $validator->errors()->toArray()); - } - } -} diff --git a/app/Api/V2/Request/Model/TransactionCurrency/IndexRequest.php b/app/Api/V2/Request/Model/TransactionCurrency/IndexRequest.php deleted file mode 100644 index 426ccdb415..0000000000 --- a/app/Api/V2/Request/Model/TransactionCurrency/IndexRequest.php +++ /dev/null @@ -1,64 +0,0 @@ - $this->convertBoolean($this->get('enabled')), - ]; - } - - /** - * The rules that the incoming request must be matched against. - */ - public function rules(): array - { - return [ - 'enabled' => 'nullable|boolean', - ]; - - } -} diff --git a/app/Api/V2/Request/UserGroup/StoreRequest.php b/app/Api/V2/Request/UserGroup/StoreRequest.php deleted file mode 100644 index d7196387a2..0000000000 --- a/app/Api/V2/Request/UserGroup/StoreRequest.php +++ /dev/null @@ -1,66 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Request\UserGroup; - -use FireflyIII\Enums\UserRoleEnum; -use FireflyIII\Support\Request\ChecksLogin; -use FireflyIII\Support\Request\ConvertsDataTypes; -use Illuminate\Foundation\Http\FormRequest; - -/** - * Class StoreRequest - */ -class StoreRequest extends FormRequest -{ - use ChecksLogin; - use ConvertsDataTypes; - - protected array $acceptedRoles = [UserRoleEnum::OWNER, UserRoleEnum::FULL]; - - public function getAll(): array - { - return [ - 'title' => $this->convertString('title'), - ]; - } - - public function rules(): array - { - $roles = []; - foreach (UserRoleEnum::cases() as $role) { - $roles[] = $role->value; - } - $string = implode(',', $roles); - - return [ - 'title' => 'unique:user_groups,title|required|min:1|max:255', - 'members' => 'required|min:1', - 'members.*.user_email' => 'email|missing_with:members.*.user_id', - 'members.*.user_id' => 'integer|exists:users,id|missing_with:members.*.user_email', - 'members.*.roles' => 'required|array|min:1', - 'members.*.roles.*' => sprintf('required|in:%s', $string), - ]; - } -} diff --git a/app/Api/V2/Request/UserGroup/UpdateMembershipRequest.php b/app/Api/V2/Request/UserGroup/UpdateMembershipRequest.php deleted file mode 100644 index c4a2fa9b81..0000000000 --- a/app/Api/V2/Request/UserGroup/UpdateMembershipRequest.php +++ /dev/null @@ -1,64 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Request\UserGroup; - -use FireflyIII\Enums\UserRoleEnum; -use FireflyIII\Support\Request\ChecksLogin; -use FireflyIII\Support\Request\ConvertsDataTypes; -use Illuminate\Foundation\Http\FormRequest; - -/** - * Class StoreRequest - */ -class UpdateMembershipRequest extends FormRequest -{ - use ChecksLogin; - use ConvertsDataTypes; - - protected array $acceptedRoles = [UserRoleEnum::OWNER, UserRoleEnum::FULL]; - - public function getAll(): array - { - return [ - 'id' => $this->convertInteger('id'), - 'email' => $this->convertString('email'), - 'roles' => $this->get('roles') ?? [], - ]; - } - - public function rules(): array - { - $validRoles = []; - foreach (UserRoleEnum::cases() as $role) { - $validRoles[] = $role->value; - } - - return [ - 'id' => 'exists:users,id|required_without:email', - 'email' => 'exists:users,email|required_without:id', - 'roles.*' => 'required|in:'.implode(',', $validRoles), - ]; - } -} diff --git a/app/Api/V2/Request/UserGroup/UpdateRequest.php b/app/Api/V2/Request/UserGroup/UpdateRequest.php deleted file mode 100644 index 3b02c60937..0000000000 --- a/app/Api/V2/Request/UserGroup/UpdateRequest.php +++ /dev/null @@ -1,60 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Request\UserGroup; - -use FireflyIII\Enums\UserRoleEnum; -use FireflyIII\Models\UserGroup; -use FireflyIII\Rules\IsDefaultUserGroupName; -use FireflyIII\Support\Request\ChecksLogin; -use FireflyIII\Support\Request\ConvertsDataTypes; -use Illuminate\Foundation\Http\FormRequest; - -/** - * Class StoreRequest - */ -class UpdateRequest extends FormRequest -{ - use ChecksLogin; - use ConvertsDataTypes; - - protected array $acceptedRoles = [UserRoleEnum::OWNER, UserRoleEnum::FULL]; - - public function getAll(): array - { - return [ - 'title' => $this->convertString('title'), - ]; - } - - public function rules(): array - { - /** @var UserGroup $userGroup */ - $userGroup = $this->route()->parameter('userGroup'); - - return [ - 'title' => ['required', 'min:1', 'max:255', sprintf('unique:user_groups,title,%d', $userGroup->id), new IsDefaultUserGroupName($userGroup)], - ]; - } -} diff --git a/app/Api/V2/Response/Sum/AutoSum.php b/app/Api/V2/Response/Sum/AutoSum.php deleted file mode 100644 index 0f1d601f7c..0000000000 --- a/app/Api/V2/Response/Sum/AutoSum.php +++ /dev/null @@ -1,71 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Api\V2\Response\Sum; - -use Closure; -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\TransactionCurrency; -use Illuminate\Database\Eloquent\Model; -use Illuminate\Support\Collection; - -/** - * Class AutoSum - * - * @deprecated - */ -class AutoSum -{ - /** - * @throws FireflyException - */ - public function autoSum(Collection $objects, Closure $getCurrency, Closure $getSum): array - { - $return = []; - - /** @var Model $object */ - foreach ($objects as $object) { - /** @var TransactionCurrency $currency */ - $currency = $getCurrency($object); - - /** @var string $amount */ - $amount = $getSum($object); - - $return[$currency->id] ??= [ - 'id' => (string) $currency->id, - 'name' => $currency->name, - 'symbol' => $currency->symbol, - 'code' => $currency->code, - 'decimal_places' => $currency->decimal_places, - 'sum' => '0', - ]; - - $return[$currency->id]['sum'] = bcadd($return[$currency->id]['sum'], $amount); - } - - var_dump(array_values($return)); - - throw new FireflyException('Not implemented'); - } -} diff --git a/app/Console/Commands/Correction/CorrectsAmounts.php b/app/Console/Commands/Correction/CorrectsAmounts.php index 5616908377..9bcf3d478a 100644 --- a/app/Console/Commands/Correction/CorrectsAmounts.php +++ b/app/Console/Commands/Correction/CorrectsAmounts.php @@ -86,7 +86,7 @@ class CorrectsAmounts extends Command /** @var TransactionJournal $journal */ foreach ($journals as $journal) { $repository->setUser($journal->user); - $native = Amount::getNativeCurrencyByUserGroup($journal->userGroup); + $primary = Amount::getPrimaryCurrencyByUserGroup($journal->userGroup); /** @var null|Transaction $source */ $source = $journal->transactions()->where('amount', '<', 0)->first(); @@ -104,8 +104,8 @@ class CorrectsAmounts extends Command if (null === $sourceAccount || null === $destAccount) { continue; } - $sourceCurrency = $repository->getAccountCurrency($sourceAccount) ?? $native; - $destCurrency = $repository->getAccountCurrency($destAccount) ?? $native; + $sourceCurrency = $repository->getAccountCurrency($sourceAccount) ?? $primary; + $destCurrency = $repository->getAccountCurrency($destAccount) ?? $primary; if ($sourceCurrency->id === $destCurrency->id) { Log::debug('Both accounts have the same currency. Removing foreign currency info.'); diff --git a/app/Console/Commands/Correction/CorrectsCurrencies.php b/app/Console/Commands/Correction/CorrectsCurrencies.php index e96a15523d..f62314179e 100644 --- a/app/Console/Commands/Correction/CorrectsCurrencies.php +++ b/app/Console/Commands/Correction/CorrectsCurrencies.php @@ -63,7 +63,7 @@ class CorrectsCurrencies extends Command $repos = app(CurrencyRepositoryInterface::class); // first check if the user has any default currency (not necessarily the case, so can be forced). - $defaultCurrency = app('amount')->getNativeCurrencyByUserGroup($userGroup); + $defaultCurrency = app('amount')->getPrimaryCurrencyByUserGroup($userGroup); Log::debug(sprintf('Now correcting currencies for user group #%d', $userGroup->id)); $found = [$defaultCurrency->id]; diff --git a/app/Console/Commands/Correction/CorrectsDatabase.php b/app/Console/Commands/Correction/CorrectsDatabase.php index 974d4a19c0..5850619f61 100644 --- a/app/Console/Commands/Correction/CorrectsDatabase.php +++ b/app/Console/Commands/Correction/CorrectsDatabase.php @@ -75,7 +75,7 @@ class CorrectsDatabase extends Command 'correction:recalculates-liabilities', 'correction:preferences', // 'correction:transaction-types', // resource heavy, disabled. - 'correction:recalculate-native-amounts', // not necessary, disabled. + 'correction:recalculate-pc-amounts', // not necessary, disabled. 'firefly-iii:report-integrity', ]; foreach ($commands as $command) { diff --git a/app/Console/Commands/Correction/CorrectsOpeningBalanceCurrencies.php b/app/Console/Commands/Correction/CorrectsOpeningBalanceCurrencies.php index 713f54d8c6..0383e72785 100644 --- a/app/Console/Commands/Correction/CorrectsOpeningBalanceCurrencies.php +++ b/app/Console/Commands/Correction/CorrectsOpeningBalanceCurrencies.php @@ -132,6 +132,6 @@ class CorrectsOpeningBalanceCurrencies extends Command $repos = app(AccountRepositoryInterface::class); $repos->setUser($account->user); - return $repos->getAccountCurrency($account) ?? app('amount')->getNativeCurrencyByUserGroup($account->userGroup); + return $repos->getAccountCurrency($account) ?? app('amount')->getPrimaryCurrencyByUserGroup($account->userGroup); } } diff --git a/app/Console/Commands/Correction/CorrectsNativeAmounts.php b/app/Console/Commands/Correction/CorrectsPrimaryCurrencyAmounts.php similarity index 94% rename from app/Console/Commands/Correction/CorrectsNativeAmounts.php rename to app/Console/Commands/Correction/CorrectsPrimaryCurrencyAmounts.php index 87d84abe66..f4544f8aa8 100644 --- a/app/Console/Commands/Correction/CorrectsNativeAmounts.php +++ b/app/Console/Commands/Correction/CorrectsPrimaryCurrencyAmounts.php @@ -2,7 +2,7 @@ /* - * CorrectsNativeAmounts.php + * CorrectsPrimaryCurrencyAmounts.php * Copyright (c) 2025 james@firefly-iii.org. * * This file is part of Firefly III (https://github.com/firefly-iii). @@ -48,13 +48,13 @@ use Illuminate\Database\Query\Builder as DatabaseBuilder; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; -class CorrectsNativeAmounts extends Command +class CorrectsPrimaryCurrencyAmounts extends Command { use ShowsFriendlyMessages; - protected $description = 'Recalculate native amounts for all objects.'; + protected $description = 'Recalculate primary currency amounts for all objects.'; - protected $signature = 'correction:recalculate-native-amounts'; + protected $signature = 'correction:recalculate-pc-amounts'; /** * Execute the console command. @@ -66,8 +66,8 @@ class CorrectsNativeAmounts extends Command return 0; } - Log::debug('Will update all native amounts. This may take some time.'); - $this->friendlyWarning('Recalculating native amounts for all objects. This may take some time!'); + Log::debug('Will update all primary currency amounts. This may take some time.'); + $this->friendlyWarning('Recalculating primary currency amounts for all objects. This may take some time!'); /** @var UserGroupRepositoryInterface $repository */ $repository = app(UserGroupRepositoryInterface::class); @@ -76,7 +76,7 @@ class CorrectsNativeAmounts extends Command foreach ($repository->getAll() as $userGroup) { $this->recalculateForGroup($userGroup); } - $this->friendlyInfo('Recalculated all native amounts.'); + $this->friendlyInfo('Recalculated all primary currency amounts.'); return 0; } @@ -88,7 +88,7 @@ class CorrectsNativeAmounts extends Command // do a check with the group's currency so we can skip some stuff. Preferences::mark(); - $currency = app('amount')->getNativeCurrencyByUserGroup($userGroup); + $currency = app('amount')->getPrimaryCurrencyByUserGroup($userGroup); $this->recalculatePiggyBanks($userGroup, $currency); $this->recalculateBudgets($userGroup, $currency); diff --git a/app/Console/Commands/Upgrade/UpgradesAccountCurrencies.php b/app/Console/Commands/Upgrade/UpgradesAccountCurrencies.php index 94c5643feb..3c4e62003f 100644 --- a/app/Console/Commands/Upgrade/UpgradesAccountCurrencies.php +++ b/app/Console/Commands/Upgrade/UpgradesAccountCurrencies.php @@ -108,7 +108,7 @@ class UpgradesAccountCurrencies extends Command $accounts = $this->accountRepos->getAccountsByType([AccountTypeEnum::DEFAULT->value, AccountTypeEnum::ASSET->value]); // get user's currency preference: - $defaultCurrency = app('amount')->getNativeCurrencyByUserGroup($user->userGroup); + $defaultCurrency = app('amount')->getPrimaryCurrencyByUserGroup($user->userGroup); /** @var Account $account */ foreach ($accounts as $account) { diff --git a/app/Console/Commands/Upgrade/UpgradesBudgetLimits.php b/app/Console/Commands/Upgrade/UpgradesBudgetLimits.php index a1bbe571ed..473247de6f 100644 --- a/app/Console/Commands/Upgrade/UpgradesBudgetLimits.php +++ b/app/Console/Commands/Upgrade/UpgradesBudgetLimits.php @@ -66,7 +66,7 @@ class UpgradesBudgetLimits extends Command /** @var null|User $user */ $user = $budget->user; if (null !== $user) { - $currency = app('amount')->getNativeCurrencyByUserGroup($user->userGroup); + $currency = app('amount')->getPrimaryCurrencyByUserGroup($user->userGroup); $budgetLimit->transaction_currency_id = $currency->id; $budgetLimit->save(); $this->friendlyInfo( diff --git a/app/Console/Commands/Upgrade/UpgradesDatabase.php b/app/Console/Commands/Upgrade/UpgradesDatabase.php index 13d7db7832..a98ff922d8 100644 --- a/app/Console/Commands/Upgrade/UpgradesDatabase.php +++ b/app/Console/Commands/Upgrade/UpgradesDatabase.php @@ -74,7 +74,7 @@ class UpgradesDatabase extends Command 'upgrade:610-currency-preferences', 'upgrade:610-currency-preferences', 'upgrade:620-piggy-banks', - 'upgrade:620-native-amounts', + 'upgrade:620-pc-amounts', 'firefly-iii:correct-database', ]; $args = []; diff --git a/app/Console/Commands/Upgrade/UpgradesMultiPiggyBanks.php b/app/Console/Commands/Upgrade/UpgradesMultiPiggyBanks.php index 7affe2abc0..d155510181 100644 --- a/app/Console/Commands/Upgrade/UpgradesMultiPiggyBanks.php +++ b/app/Console/Commands/Upgrade/UpgradesMultiPiggyBanks.php @@ -96,7 +96,7 @@ class UpgradesMultiPiggyBanks extends Command $this->repository->setUser($piggyBank->account->user); $this->accountRepository->setUser($piggyBank->account->user); $repetition = $this->repository->getRepetition($piggyBank, true); - $currency = $this->accountRepository->getAccountCurrency($piggyBank->account) ?? app('amount')->getNativeCurrencyByUserGroup($piggyBank->account->user->userGroup); + $currency = $this->accountRepository->getAccountCurrency($piggyBank->account) ?? app('amount')->getPrimaryCurrencyByUserGroup($piggyBank->account->user->userGroup); // update piggy bank to have a currency. $piggyBank->transaction_currency_id = $currency->id; diff --git a/app/Console/Commands/Upgrade/UpgradesNativeAmounts.php b/app/Console/Commands/Upgrade/UpgradesPrimaryCurrencyAmounts.php similarity index 80% rename from app/Console/Commands/Upgrade/UpgradesNativeAmounts.php rename to app/Console/Commands/Upgrade/UpgradesPrimaryCurrencyAmounts.php index 648237b33c..9cb26669ee 100644 --- a/app/Console/Commands/Upgrade/UpgradesNativeAmounts.php +++ b/app/Console/Commands/Upgrade/UpgradesPrimaryCurrencyAmounts.php @@ -2,7 +2,7 @@ /* - * UpgradesNativeAmounts.php + * UpgradesPrimaryCurrencyAmounts.php * Copyright (c) 2025 james@firefly-iii.org. * * This file is part of Firefly III (https://github.com/firefly-iii). @@ -29,15 +29,15 @@ use FireflyIII\Console\Commands\ShowsFriendlyMessages; use Illuminate\Console\Command; use Illuminate\Support\Facades\Artisan; -class UpgradesNativeAmounts extends Command +class UpgradesPrimaryCurrencyAmounts extends Command { use ShowsFriendlyMessages; - public const string CONFIG_NAME = '620_native_amounts'; + public const string CONFIG_NAME = '620_pc_amounts'; - protected $description = 'Runs the native amounts calculations.'; + protected $description = 'Runs the primary currency amounts calculations.'; - protected $signature = 'upgrade:620-native-amounts {--F|force : Force the execution of this command.}'; + protected $signature = 'upgrade:620-pc-amounts {--F|force : Force the execution of this command.}'; /** * Execute the console command. @@ -50,7 +50,7 @@ class UpgradesNativeAmounts extends Command return 0; } - Artisan::call('correction:recalculate-native-amounts'); + Artisan::call('correction:recalculate-pc-amounts'); $this->markAsExecuted(); diff --git a/app/Factory/BillFactory.php b/app/Factory/BillFactory.php index 7a6babf654..1fe4567134 100644 --- a/app/Factory/BillFactory.php +++ b/app/Factory/BillFactory.php @@ -50,7 +50,7 @@ class BillFactory app('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)) - ?? app('amount')->getNativeCurrencyByUserGroup($this->user->userGroup); + ?? app('amount')->getPrimaryCurrencyByUserGroup($this->user->userGroup); try { $skip = array_key_exists('skip', $data) ? $data['skip'] : 0; diff --git a/app/Factory/PiggyBankFactory.php b/app/Factory/PiggyBankFactory.php index eefd1436e5..933f870d0b 100644 --- a/app/Factory/PiggyBankFactory.php +++ b/app/Factory/PiggyBankFactory.php @@ -126,7 +126,7 @@ class PiggyBankFactory private function getCurrency(array $data): TransactionCurrency { // currency: - $defaultCurrency = app('amount')->getNativeCurrency(); + $defaultCurrency = app('amount')->getPrimaryCurrency(); $currency = null; if (array_key_exists('transaction_currency_code', $data)) { $currency = $this->currencyRepository->findByCode((string)($data['transaction_currency_code'] ?? '')); diff --git a/app/Factory/TransactionJournalFactory.php b/app/Factory/TransactionJournalFactory.php index bf1a755e9e..070f71fa26 100644 --- a/app/Factory/TransactionJournalFactory.php +++ b/app/Factory/TransactionJournalFactory.php @@ -297,7 +297,7 @@ class TransactionJournalFactory $transactionFactory->setForeignCurrency($currency); $amount = (string) $row['foreign_amount']; $foreignAmount = (string) $row['amount']; - Log::debug('Swap native/foreign amounts in transfer for new save method.'); + Log::debug('Swap primary/foreign amounts in transfer for new save method.'); } try { @@ -488,7 +488,7 @@ class TransactionJournalFactory $preference = $this->accountRepository->getAccountCurrency($account); if (null === $preference && !$currency instanceof TransactionCurrency) { // return user's default: - return app('amount')->getNativeCurrencyByUserGroup($this->user->userGroup); + return app('amount')->getPrimaryCurrencyByUserGroup($this->user->userGroup); } $result = $preference ?? $currency; Log::debug(sprintf('Currency is now #%d (%s) because of account #%d (%s)', $result->id, $result->code, $account->id, $account->name)); diff --git a/app/Generator/Report/Audit/MonthReportGenerator.php b/app/Generator/Report/Audit/MonthReportGenerator.php index a8bbca3b18..b54e1c9042 100644 --- a/app/Generator/Report/Audit/MonthReportGenerator.php +++ b/app/Generator/Report/Audit/MonthReportGenerator.php @@ -141,7 +141,7 @@ class MonthReportGenerator implements ReportGeneratorInterface Log::debug(sprintf('getAuditReport: Call finalAccountBalance with date/time "%s"', $date->toIso8601String())); $dayBeforeBalance = Steam::finalAccountBalance($account, $date); $startBalance = $dayBeforeBalance['balance']; - $defaultCurrency = app('amount')->getNativeCurrencyByUserGroup($account->user->userGroup); + $defaultCurrency = app('amount')->getPrimaryCurrencyByUserGroup($account->user->userGroup); $currency = $accountRepository->getAccountCurrency($account) ?? $defaultCurrency; foreach ($journals as $index => $journal) { diff --git a/app/Generator/Webhook/StandardMessageGenerator.php b/app/Generator/Webhook/StandardMessageGenerator.php index dbb3516dfc..5ea7fa002b 100644 --- a/app/Generator/Webhook/StandardMessageGenerator.php +++ b/app/Generator/Webhook/StandardMessageGenerator.php @@ -177,7 +177,7 @@ class StandardMessageGenerator implements MessageGeneratorInterface $accounts = $this->collectAccounts($model); $enrichment = new AccountEnrichment(); $enrichment->setUser($model->user); - $enrichment->setNative(Amount::getNativeCurrencyByUserGroup($model->userGroup)); + $enrichment->setPrimary(Amount::getPrimaryCurrencyByUserGroup($model->userGroup)); $accounts = $enrichment->enrich($accounts); foreach ($accounts as $account) { $transformer = new AccountTransformer(); diff --git a/app/Handlers/Events/PreferencesEventHandler.php b/app/Handlers/Events/PreferencesEventHandler.php index 91bbb9a9bd..6296d07437 100644 --- a/app/Handlers/Events/PreferencesEventHandler.php +++ b/app/Handlers/Events/PreferencesEventHandler.php @@ -38,17 +38,16 @@ use Illuminate\Support\Facades\Log; class PreferencesEventHandler { - public function resetNativeAmounts(UserGroupChangedDefaultCurrency $event): void + public function resetPrimaryCurrencyAmounts(UserGroupChangedDefaultCurrency $event): void { - // Reset the native amounts for all objects that have it. - Log::debug('Resetting native amounts for all objects.'); + // Reset the primary currency amounts for all objects that have it. + Log::debug('Resetting primary currency amounts for all objects.'); $tables = [ // !!! this array is also in the migration 'accounts' => ['native_virtual_balance'], 'available_budgets' => ['native_amount'], 'bills' => ['native_amount_min', 'native_amount_max'], - // 'transactions' => ['native_amount', 'native_foreign_amount'] ]; foreach ($tables as $table => $columns) { foreach ($columns as $column) { @@ -60,13 +59,13 @@ class PreferencesEventHandler $this->resetBudgets($event->userGroup); $this->resetTransactions($event->userGroup); // fire laravel command to recalculate them all. - if (Amount::convertToNative()) { - Log::debug('Will now convert to native.'); - Artisan::call('correction:recalculate-native-amounts'); + if (Amount::convertToPrimary()) { + Log::debug('Will now convert to primary currency.'); + Artisan::call('correction:recalculate-pc-amounts'); return; } - Log::debug('Will NOT convert to native.'); + Log::debug('Will NOT convert to primary currency.'); } private function resetPiggyBanks(UserGroup $userGroup): void diff --git a/app/Handlers/Observer/AccountObserver.php b/app/Handlers/Observer/AccountObserver.php index b5f5c32443..b29983ada5 100644 --- a/app/Handlers/Observer/AccountObserver.php +++ b/app/Handlers/Observer/AccountObserver.php @@ -44,15 +44,15 @@ class AccountObserver public function created(Account $account): void { // Log::debug('Observe "created" of an account.'); - $this->updateNativeAmount($account); + $this->updatePrimaryCurrencyAmount($account); } - private function updateNativeAmount(Account $account): void + private function updatePrimaryCurrencyAmount(Account $account): void { - if (!Amount::convertToNative($account->user)) { + if (!Amount::convertToPrimary($account->user)) { return; } - $userCurrency = app('amount')->getNativeCurrencyByUserGroup($account->user->userGroup); + $userCurrency = app('amount')->getPrimaryCurrencyByUserGroup($account->user->userGroup); $repository = app(AccountRepositoryInterface::class); $currency = $repository->getAccountCurrency($account); if (null !== $currency && $currency->id !== $userCurrency->id && '' !== (string) $account->virtual_balance && 0 !== bccomp($account->virtual_balance, '0')) { @@ -67,7 +67,7 @@ class AccountObserver $account->native_virtual_balance = null; } $account->saveQuietly(); - // Log::debug('Account native virtual balance is updated.'); + // Log::debug('Account primary currency virtual balance is updated.'); } /** @@ -108,6 +108,6 @@ class AccountObserver public function updated(Account $account): void { // Log::debug('Observe "updated" of an account.'); - $this->updateNativeAmount($account); + $this->updatePrimaryCurrencyAmount($account); } } diff --git a/app/Handlers/Observer/AutoBudgetObserver.php b/app/Handlers/Observer/AutoBudgetObserver.php index 8ff4ff8e1f..ca030ba70e 100644 --- a/app/Handlers/Observer/AutoBudgetObserver.php +++ b/app/Handlers/Observer/AutoBudgetObserver.php @@ -34,15 +34,15 @@ class AutoBudgetObserver public function created(AutoBudget $autoBudget): void { Log::debug('Observe "created" of an auto budget.'); - $this->updateNativeAmount($autoBudget); + $this->updatePrimaryCurrencyAmount($autoBudget); } - private function updateNativeAmount(AutoBudget $autoBudget): void + private function updatePrimaryCurrencyAmount(AutoBudget $autoBudget): void { - if (!Amount::convertToNative($autoBudget->budget->user)) { + if (!Amount::convertToPrimary($autoBudget->budget->user)) { return; } - $userCurrency = app('amount')->getNativeCurrencyByUserGroup($autoBudget->budget->user->userGroup); + $userCurrency = app('amount')->getPrimaryCurrencyByUserGroup($autoBudget->budget->user->userGroup); $autoBudget->native_amount = null; if ($autoBudget->transactionCurrency->id !== $userCurrency->id) { $converter = new ExchangeRateConverter(); @@ -51,12 +51,12 @@ class AutoBudgetObserver $autoBudget->native_amount = $converter->convert($autoBudget->transactionCurrency, $userCurrency, today(), $autoBudget->amount); } $autoBudget->saveQuietly(); - Log::debug('Auto budget native amount is updated.'); + Log::debug('Auto budget primary currency amount is updated.'); } public function updated(AutoBudget $autoBudget): void { Log::debug('Observe "updated" of an auto budget.'); - $this->updateNativeAmount($autoBudget); + $this->updatePrimaryCurrencyAmount($autoBudget); } } diff --git a/app/Handlers/Observer/AvailableBudgetObserver.php b/app/Handlers/Observer/AvailableBudgetObserver.php index 5e1e3ef890..02fc32d0b1 100644 --- a/app/Handlers/Observer/AvailableBudgetObserver.php +++ b/app/Handlers/Observer/AvailableBudgetObserver.php @@ -34,17 +34,17 @@ class AvailableBudgetObserver public function created(AvailableBudget $availableBudget): void { // Log::debug('Observe "created" of an available budget.'); - $this->updateNativeAmount($availableBudget); + $this->updatePrimaryCurrencyAmount($availableBudget); } - private function updateNativeAmount(AvailableBudget $availableBudget): void + private function updatePrimaryCurrencyAmount(AvailableBudget $availableBudget): void { - if (!Amount::convertToNative($availableBudget->user)) { - // Log::debug('Do not update native available amount of the available budget.'); + if (!Amount::convertToPrimary($availableBudget->user)) { + // Log::debug('Do not update primary currency available amount of the available budget.'); return; } - $userCurrency = app('amount')->getNativeCurrencyByUserGroup($availableBudget->user->userGroup); + $userCurrency = app('amount')->getPrimaryCurrencyByUserGroup($availableBudget->user->userGroup); $availableBudget->native_amount = null; if ($availableBudget->transactionCurrency->id !== $userCurrency->id) { $converter = new ExchangeRateConverter(); @@ -53,12 +53,12 @@ class AvailableBudgetObserver $availableBudget->native_amount = $converter->convert($availableBudget->transactionCurrency, $userCurrency, today(), $availableBudget->amount); } $availableBudget->saveQuietly(); - Log::debug('Available budget native amount is updated.'); + Log::debug('Available budget primary currency amount is updated.'); } public function updated(AvailableBudget $availableBudget): void { // Log::debug('Observe "updated" of an available budget.'); - $this->updateNativeAmount($availableBudget); + $this->updatePrimaryCurrencyAmount($availableBudget); } } diff --git a/app/Handlers/Observer/BillObserver.php b/app/Handlers/Observer/BillObserver.php index 5ab6549a77..9d7d5f9672 100644 --- a/app/Handlers/Observer/BillObserver.php +++ b/app/Handlers/Observer/BillObserver.php @@ -38,15 +38,15 @@ class BillObserver public function created(Bill $bill): void { // Log::debug('Observe "created" of a bill.'); - $this->updateNativeAmount($bill); + $this->updatePrimaryCurrencyAmount($bill); } - private function updateNativeAmount(Bill $bill): void + private function updatePrimaryCurrencyAmount(Bill $bill): void { - if (!Amount::convertToNative($bill->user)) { + if (!Amount::convertToPrimary($bill->user)) { return; } - $userCurrency = app('amount')->getNativeCurrencyByUserGroup($bill->user->userGroup); + $userCurrency = app('amount')->getPrimaryCurrencyByUserGroup($bill->user->userGroup); $bill->native_amount_min = null; $bill->native_amount_max = null; if ($bill->transactionCurrency->id !== $userCurrency->id) { @@ -57,7 +57,7 @@ class BillObserver $bill->native_amount_max = $converter->convert($bill->transactionCurrency, $userCurrency, today(), $bill->amount_max); } $bill->saveQuietly(); - Log::debug('Bill native amounts are updated.'); + Log::debug('Bill primary currency amounts are updated.'); } public function deleting(Bill $bill): void @@ -76,6 +76,6 @@ class BillObserver public function updated(Bill $bill): void { // Log::debug('Observe "updated" of a bill.'); - $this->updateNativeAmount($bill); + $this->updatePrimaryCurrencyAmount($bill); } } diff --git a/app/Handlers/Observer/BudgetLimitObserver.php b/app/Handlers/Observer/BudgetLimitObserver.php index f67e6a37e9..fcc4b405a8 100644 --- a/app/Handlers/Observer/BudgetLimitObserver.php +++ b/app/Handlers/Observer/BudgetLimitObserver.php @@ -34,17 +34,17 @@ class BudgetLimitObserver public function created(BudgetLimit $budgetLimit): void { Log::debug('Observe "created" of a budget limit.'); - $this->updateNativeAmount($budgetLimit); + $this->updatePrimaryCurrencyAmount($budgetLimit); } - private function updateNativeAmount(BudgetLimit $budgetLimit): void + private function updatePrimaryCurrencyAmount(BudgetLimit $budgetLimit): void { - if (!Amount::convertToNative($budgetLimit->budget->user)) { - // Log::debug('Do not update native amount of the budget limit.'); + if (!Amount::convertToPrimary($budgetLimit->budget->user)) { + // Log::debug('Do not update primary currency amount of the budget limit.'); return; } - $userCurrency = app('amount')->getNativeCurrencyByUserGroup($budgetLimit->budget->user->userGroup); + $userCurrency = app('amount')->getPrimaryCurrencyByUserGroup($budgetLimit->budget->user->userGroup); $budgetLimit->native_amount = null; if ($budgetLimit->transactionCurrency->id !== $userCurrency->id) { $converter = new ExchangeRateConverter(); @@ -53,12 +53,12 @@ class BudgetLimitObserver $budgetLimit->native_amount = $converter->convert($budgetLimit->transactionCurrency, $userCurrency, today(), $budgetLimit->amount); } $budgetLimit->saveQuietly(); - Log::debug('Budget limit native amounts are updated.'); + Log::debug('Budget limit primary currency amounts are updated.'); } public function updated(BudgetLimit $budgetLimit): void { Log::debug('Observe "updated" of a budget limit.'); - $this->updateNativeAmount($budgetLimit); + $this->updatePrimaryCurrencyAmount($budgetLimit); } } diff --git a/app/Handlers/Observer/PiggyBankEventObserver.php b/app/Handlers/Observer/PiggyBankEventObserver.php index 0f62454063..acd8656727 100644 --- a/app/Handlers/Observer/PiggyBankEventObserver.php +++ b/app/Handlers/Observer/PiggyBankEventObserver.php @@ -34,10 +34,10 @@ class PiggyBankEventObserver public function created(PiggyBankEvent $event): void { Log::debug('Observe "created" of a piggy bank event.'); - $this->updateNativeAmount($event); + $this->updatePrimaryCurrencyAmount($event); } - private function updateNativeAmount(PiggyBankEvent $event): void + private function updatePrimaryCurrencyAmount(PiggyBankEvent $event): void { $user = $event->piggyBank->accounts()->first()?->user; if (null === $user) { @@ -45,10 +45,10 @@ class PiggyBankEventObserver return; } - if (!Amount::convertToNative($user)) { + if (!Amount::convertToPrimary($user)) { return; } - $userCurrency = app('amount')->getNativeCurrencyByUserGroup($event->piggyBank->accounts()->first()->user->userGroup); + $userCurrency = app('amount')->getPrimaryCurrencyByUserGroup($event->piggyBank->accounts()->first()->user->userGroup); $event->native_amount = null; if ($event->piggyBank->transactionCurrency->id !== $userCurrency->id) { $converter = new ExchangeRateConverter(); @@ -57,12 +57,12 @@ class PiggyBankEventObserver $event->native_amount = $converter->convert($event->piggyBank->transactionCurrency, $userCurrency, today(), $event->amount); } $event->saveQuietly(); - Log::debug('Piggy bank event native amount is updated.'); + Log::debug('Piggy bank event primary currency amount is updated.'); } public function updated(PiggyBankEvent $event): void { Log::debug('Observe "updated" of a piggy bank event.'); - $this->updateNativeAmount($event); + $this->updatePrimaryCurrencyAmount($event); } } diff --git a/app/Handlers/Observer/PiggyBankObserver.php b/app/Handlers/Observer/PiggyBankObserver.php index 47f2052a84..8c8364f01f 100644 --- a/app/Handlers/Observer/PiggyBankObserver.php +++ b/app/Handlers/Observer/PiggyBankObserver.php @@ -38,10 +38,10 @@ class PiggyBankObserver public function created(PiggyBank $piggyBank): void { Log::debug('Observe "created" of a piggy bank.'); - $this->updateNativeAmount($piggyBank); + $this->updatePrimaryCurrencyAmount($piggyBank); } - private function updateNativeAmount(PiggyBank $piggyBank): void + private function updatePrimaryCurrencyAmount(PiggyBank $piggyBank): void { $group = $piggyBank->accounts()->first()?->user->userGroup; if (null === $group) { @@ -49,7 +49,7 @@ class PiggyBankObserver return; } - $userCurrency = app('amount')->getNativeCurrencyByUserGroup($group); + $userCurrency = app('amount')->getPrimaryCurrencyByUserGroup($group); $piggyBank->native_target_amount = null; if ($piggyBank->transactionCurrency->id !== $userCurrency->id) { $converter = new ExchangeRateConverter(); @@ -58,7 +58,7 @@ class PiggyBankObserver $piggyBank->native_target_amount = $converter->convert($piggyBank->transactionCurrency, $userCurrency, today(), $piggyBank->target_amount); } $piggyBank->saveQuietly(); - Log::debug('Piggy bank native target amount is updated.'); + Log::debug('Piggy bank primary currency target amount is updated.'); } /** @@ -85,6 +85,6 @@ class PiggyBankObserver public function updated(PiggyBank $piggyBank): void { Log::debug('Observe "updated" of a piggy bank.'); - $this->updateNativeAmount($piggyBank); + $this->updatePrimaryCurrencyAmount($piggyBank); } } diff --git a/app/Handlers/Observer/TransactionObserver.php b/app/Handlers/Observer/TransactionObserver.php index 9869b45dd3..a5c5fefd73 100644 --- a/app/Handlers/Observer/TransactionObserver.php +++ b/app/Handlers/Observer/TransactionObserver.php @@ -45,15 +45,15 @@ class TransactionObserver AccountBalanceCalculator::recalculateForJournal($transaction->transactionJournal); } } - $this->updateNativeAmount($transaction); + $this->updatePrimaryCurrencyAmount($transaction); } - private function updateNativeAmount(Transaction $transaction): void + private function updatePrimaryCurrencyAmount(Transaction $transaction): void { - if (!Amount::convertToNative($transaction->transactionJournal->user)) { + if (!Amount::convertToPrimary($transaction->transactionJournal->user)) { return; } - $userCurrency = app('amount')->getNativeCurrencyByUserGroup($transaction->transactionJournal->user->userGroup); + $userCurrency = app('amount')->getPrimaryCurrencyByUserGroup($transaction->transactionJournal->user->userGroup); $transaction->native_amount = null; $transaction->native_foreign_amount = null; // first normal amount @@ -72,7 +72,7 @@ class TransactionObserver } $transaction->saveQuietly(); - Log::debug('Transaction native amounts are updated.'); + Log::debug('Transaction primary currency amounts are updated.'); } public function deleting(?Transaction $transaction): void @@ -90,6 +90,6 @@ class TransactionObserver AccountBalanceCalculator::recalculateForJournal($transaction->transactionJournal); } } - $this->updateNativeAmount($transaction); + $this->updatePrimaryCurrencyAmount($transaction); } } diff --git a/app/Helpers/Collector/GroupCollector.php b/app/Helpers/Collector/GroupCollector.php index 73c4414227..270318ba3b 100644 --- a/app/Helpers/Collector/GroupCollector.php +++ b/app/Helpers/Collector/GroupCollector.php @@ -105,7 +105,7 @@ class GroupCollector implements GroupCollectorInterface 'category_id', 'budget_id', ]; - $this->stringFields = ['amount', 'foreign_amount', 'native_amount', 'native_foreign_amount', 'source_balance_after', 'destination_balance_after']; + $this->stringFields = ['amount', 'foreign_amount', 'pc_amount', 'pc_foreign_amount', 'source_balance_after', 'destination_balance_after']; $this->total = 0; $this->fields = [ // group @@ -138,7 +138,7 @@ class GroupCollector implements GroupCollectorInterface 'source.amount as amount', 'source.balance_after as source_balance_after', 'source.balance_dirty as source_balance_dirty', - 'source.native_amount as native_amount', + 'source.native_amount as pc_amount', 'source.transaction_currency_id as currency_id', 'currency.code as currency_code', 'currency.name as currency_name', @@ -147,7 +147,7 @@ class GroupCollector implements GroupCollectorInterface // foreign currency info 'source.foreign_amount as foreign_amount', - 'source.native_foreign_amount as native_foreign_amount', + 'source.native_foreign_amount as pc_foreign_amount', 'source.foreign_currency_id as foreign_currency_id', 'foreign_currency.code as foreign_currency_code', 'foreign_currency.name as foreign_currency_name', @@ -735,8 +735,8 @@ class GroupCollector implements GroupCollectorInterface if (null === $transaction['amount']) { throw new FireflyException(sprintf('Amount is NULL for a transaction in group #%d, please investigate.', $groudId)); } - $nativeAmount = (string) ('' === $transaction['native_amount'] ? '0' : $transaction['native_amount']); - $nativeForeignAmount = (string) ('' === $transaction['native_foreign_amount'] ? '0' : $transaction['native_foreign_amount']); + $pcAmount = (string) ('' === $transaction['pc_amount'] ? '0' : $transaction['pc_amount']); + $pcForeignAmount = (string) ('' === $transaction['pc_foreign_amount'] ? '0' : $transaction['pc_foreign_amount']); $foreignAmount = (string) ('' === $transaction['foreign_amount'] ? '0' : $transaction['foreign_amount']); // set default: @@ -746,10 +746,10 @@ class GroupCollector implements GroupCollectorInterface $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]['native_amount'] = '0'; + $groups[$groudId]['sums'][$currencyId]['pc_amount'] = '0'; } $groups[$groudId]['sums'][$currencyId]['amount'] = bcadd((string) $groups[$groudId]['sums'][$currencyId]['amount'], $transaction['amount']); - $groups[$groudId]['sums'][$currencyId]['native_amount'] = bcadd((string) $groups[$groudId]['sums'][$currencyId]['native_amount'], $nativeAmount); + $groups[$groudId]['sums'][$currencyId]['pc_amount'] = bcadd((string) $groups[$groudId]['sums'][$currencyId]['pc_amount'], $pcAmount); if (null !== $transaction['foreign_amount'] && null !== $transaction['foreign_currency_id']) { $currencyId = (int) $transaction['foreign_currency_id']; @@ -761,10 +761,10 @@ class GroupCollector implements GroupCollectorInterface $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]['native_amount'] = '0'; + $groups[$groudId]['sums'][$currencyId]['pc_amount'] = '0'; } $groups[$groudId]['sums'][$currencyId]['amount'] = bcadd((string) $groups[$groudId]['sums'][$currencyId]['amount'], $foreignAmount); - $groups[$groudId]['sums'][$currencyId]['native_amount'] = bcadd($groups[$groudId]['sums'][$currencyId]['amount'], $nativeForeignAmount); + $groups[$groudId]['sums'][$currencyId]['pc_amount'] = bcadd($groups[$groudId]['sums'][$currencyId]['amount'], $pcForeignAmount); } } } diff --git a/app/Helpers/Report/NetWorth.php b/app/Helpers/Report/NetWorth.php index 2fca6d115a..ce1be496dd 100644 --- a/app/Helpers/Report/NetWorth.php +++ b/app/Helpers/Report/NetWorth.php @@ -55,7 +55,7 @@ class NetWorth implements NetWorthInterface /** * This method collects the user's net worth in ALL the user's currencies - * (1, 4 and 8) and also in the 'native' currency for ease of use. + * (1, 4 and 8) and also in the 'primary' currency for ease of use. * * The set of accounts has to be fed to it. * @@ -64,18 +64,18 @@ class NetWorth implements NetWorthInterface public function byAccounts(Collection $accounts, Carbon $date): array { // start in the past, end in the future? use $date - $convertToNative = Amount::convertToNative(); + $convertToPrimary = Amount::convertToPrimary(); $ids = implode(',', $accounts->pluck('id')->toArray()); $cache = new CacheProperties(); $cache->addProperty($date); - $cache->addProperty($convertToNative); + $cache->addProperty($convertToPrimary); $cache->addProperty('net-worth-by-accounts'); $cache->addProperty($ids); if ($cache->has()) { return $cache->get(); } Log::debug(sprintf('Now in byAccounts("%s", "%s")', $ids, $date->format('Y-m-d H:i:s'))); - $default = Amount::getNativeCurrency(); + $default = Amount::getPrimaryCurrency(); $netWorth = []; Log::debug(sprintf('NetWorth: finalAccountsBalance("%s")', $date->format('Y-m-d H:i:s'))); $balances = Steam::finalAccountsBalance($accounts, $date); @@ -84,20 +84,20 @@ class NetWorth implements NetWorthInterface foreach ($accounts as $account) { // Log::debug(sprintf('Now at account #%d ("%s")', $account->id, $account->name)); $currency = $this->accountRepository->getAccountCurrency($account) ?? $default; - $useNative = $convertToNative && $default->id !== $currency->id; - $currency = $useNative ? $default : $currency; + $usePrimary = $convertToPrimary && $default->id !== $currency->id; + $currency = $usePrimary ? $default : $currency; $currencyCode = $currency->code; $balance = '0'; - $nativeBalance = '0'; + $primaryBalance = '0'; if (array_key_exists($account->id, $balances)) { $balance = $balances[$account->id]['balance'] ?? '0'; - $nativeBalance = $balances[$account->id]['native_balance'] ?? '0'; + $primaryBalance = $balances[$account->id]['pc_balance'] ?? '0'; } - // Log::debug(sprintf('Balance is %s, native balance is %s', $balance, $nativeBalance)); + // Log::debug(sprintf('Balance is %s, primary balance is %s', $balance, $primaryBalance)); // always subtract virtual balance again. $balance = '' !== (string) $account->virtual_balance ? bcsub($balance, (string) $account->virtual_balance) : $balance; - $nativeBalance = '' !== (string) $account->native_virtual_balance ? bcsub($nativeBalance, (string) $account->native_virtual_balance) : $nativeBalance; - $amountToUse = $useNative ? $nativeBalance : $balance; + $primaryBalance = '' !== (string) $account->native_virtual_balance ? bcsub($primaryBalance, (string) $account->native_virtual_balance) : $primaryBalance; + $amountToUse = $usePrimary ? $primaryBalance : $balance; // Log::debug(sprintf('Will use %s %s', $currencyCode, $amountToUse)); $netWorth[$currencyCode] ??= [ diff --git a/app/Helpers/Report/NetWorthInterface.php b/app/Helpers/Report/NetWorthInterface.php index 6891b57c82..a73cd53b4d 100644 --- a/app/Helpers/Report/NetWorthInterface.php +++ b/app/Helpers/Report/NetWorthInterface.php @@ -40,9 +40,9 @@ interface NetWorthInterface * Collect net worth based on the given set of accounts. * * Returns X arrays with the net worth in each given currency, and the net worth in - * of that amount in the native currency. + * of that amount in the primary currency. * - * Includes extra array with the total(!) net worth in the native currency. + * Includes extra array with the total(!) net worth in the primary currency. */ public function byAccounts(Collection $accounts, Carbon $date): array; diff --git a/app/Http/Controllers/Account/CreateController.php b/app/Http/Controllers/Account/CreateController.php index 8f0904f859..9098c4e2fa 100644 --- a/app/Http/Controllers/Account/CreateController.php +++ b/app/Http/Controllers/Account/CreateController.php @@ -105,7 +105,7 @@ class CreateController extends Controller $request->session()->flash( 'preFilled', [ - 'currency_id' => $this->defaultCurrency->id, + 'currency_id' => $this->primaryCurrency->id, 'include_net_worth' => $hasOldInput ? (bool) $request->old('include_net_worth') : true, ] ); diff --git a/app/Http/Controllers/Account/EditController.php b/app/Http/Controllers/Account/EditController.php index 7b0115a32c..7d172bead1 100644 --- a/app/Http/Controllers/Account/EditController.php +++ b/app/Http/Controllers/Account/EditController.php @@ -125,7 +125,7 @@ class EditController extends Controller $openingBalanceAmount = ''; } $openingBalanceDate = $repository->getOpeningBalanceDate($account); - $currency = $this->repository->getAccountCurrency($account) ?? $this->defaultCurrency; + $currency = $this->repository->getAccountCurrency($account) ?? $this->primaryCurrency; // include this account in net-worth charts? $includeNetWorth = $repository->getMetaValue($account, 'include_net_worth'); diff --git a/app/Http/Controllers/Account/IndexController.php b/app/Http/Controllers/Account/IndexController.php index 92bd62e491..31ec4d033b 100644 --- a/app/Http/Controllers/Account/IndexController.php +++ b/app/Http/Controllers/Account/IndexController.php @@ -104,14 +104,14 @@ class IndexController extends Controller function (Account $account) use ($activities, $startBalances, $endBalances): void { $currency = $this->repository->getAccountCurrency($account); $account->lastActivityDate = $this->isInArrayDate($activities, $account->id); - $account->startBalances = Steam::filterAccountBalance($startBalances[$account->id] ?? [], $account, $this->convertToNative, $currency); - $account->endBalances = Steam::filterAccountBalance($endBalances[$account->id] ?? [], $account, $this->convertToNative, $currency); + $account->startBalances = Steam::filterAccountBalance($startBalances[$account->id] ?? [], $account, $this->convertToPrimary, $currency); + $account->endBalances = Steam::filterAccountBalance($endBalances[$account->id] ?? [], $account, $this->convertToPrimary, $currency); $account->differences = $this->subtract($account->startBalances, $account->endBalances); $account->interest = Steam::bcround($this->repository->getMetaValue($account, 'interest'), 4); $account->interestPeriod = (string) trans(sprintf('firefly.interest_calc_%s', $this->repository->getMetaValue($account, 'interest_period'))); $account->accountTypeString = (string) trans(sprintf('firefly.account_type_%s', $account->accountType->type)); $account->current_debt = '0'; - $account->currency = $currency ?? $this->defaultCurrency; + $account->currency = $currency ?? $this->primaryCurrency; $account->iban = implode(' ', str_split((string) $account->iban, 4)); } ); @@ -183,8 +183,8 @@ class IndexController extends Controller $interest = '' === $interest ? '0' : $interest; $currency = $this->repository->getAccountCurrency($account); - $account->startBalances = Steam::filterAccountBalance($startBalances[$account->id] ?? [], $account, $this->convertToNative, $currency); - $account->endBalances = Steam::filterAccountBalance($endBalances[$account->id] ?? [], $account, $this->convertToNative, $currency); + $account->startBalances = Steam::filterAccountBalance($startBalances[$account->id] ?? [], $account, $this->convertToPrimary, $currency); + $account->endBalances = Steam::filterAccountBalance($endBalances[$account->id] ?? [], $account, $this->convertToPrimary, $currency); $account->differences = $this->subtract($account->startBalances, $account->endBalances); $account->lastActivityDate = $this->isInArrayDate($activities, $account->id); $account->interest = Steam::bcround($interest, 4); @@ -195,7 +195,7 @@ class IndexController extends Controller $account->location = $this->repository->getLocation($account); $account->liability_direction = $this->repository->getMetaValue($account, 'liability_direction'); $account->current_debt = $this->repository->getMetaValue($account, 'current_debt') ?? '-'; - $account->currency = $currency ?? $this->defaultCurrency; + $account->currency = $currency ?? $this->primaryCurrency; $account->iban = implode(' ', str_split((string) $account->iban, 4)); diff --git a/app/Http/Controllers/Account/ReconcileController.php b/app/Http/Controllers/Account/ReconcileController.php index bbad4248a9..cee8c1c158 100644 --- a/app/Http/Controllers/Account/ReconcileController.php +++ b/app/Http/Controllers/Account/ReconcileController.php @@ -87,7 +87,7 @@ class ReconcileController extends Controller return redirect(route('accounts.index', [config(sprintf('firefly.shortNamesByFullName.%s', $account->accountType->type))])); } - $currency = $this->accountRepos->getAccountCurrency($account) ?? $this->defaultCurrency; + $currency = $this->accountRepos->getAccountCurrency($account) ?? $this->primaryCurrency; // no start or end: $range = app('navigation')->getViewRange(false); @@ -204,7 +204,7 @@ class ReconcileController extends Controller } $reconciliation = $this->accountRepos->getReconciliation($account); - $currency = $this->accountRepos->getAccountCurrency($account) ?? $this->defaultCurrency; + $currency = $this->accountRepos->getAccountCurrency($account) ?? $this->primaryCurrency; $source = $reconciliation; $destination = $account; if (1 === bccomp($difference, '0')) { diff --git a/app/Http/Controllers/Account/ShowController.php b/app/Http/Controllers/Account/ShowController.php index b798d1a0be..f231c8f704 100644 --- a/app/Http/Controllers/Account/ShowController.php +++ b/app/Http/Controllers/Account/ShowController.php @@ -108,7 +108,7 @@ class ShowController extends Controller $page = (int) $request->get('page'); $pageSize = (int) app('preferences')->get('listPageSize', 50)->data; $accountCurrency = $this->repository->getAccountCurrency($account); - $currency = $accountCurrency ?? $this->defaultCurrency; + $currency = $accountCurrency ?? $this->primaryCurrency; $fStart = $start->isoFormat($this->monthAndDayFormat); $fEnd = $end->isoFormat($this->monthAndDayFormat); $subTitle = (string) trans('firefly.journals_in_period_for_account', ['name' => $account->name, 'start' => $fStart, 'end' => $fEnd]); @@ -165,7 +165,7 @@ class ShowController extends Controller } Log::debug(sprintf('show: Call finalAccountBalance with date/time "%s"', $now->toIso8601String())); - $balances = Steam::filterAccountBalance(Steam::finalAccountBalance($account, $now), $account, $this->convertToNative, $accountCurrency); + $balances = Steam::filterAccountBalance(Steam::finalAccountBalance($account, $now), $account, $this->convertToPrimary, $accountCurrency); return view( 'accounts.show', @@ -212,7 +212,7 @@ class ShowController extends Controller $subTitleIcon = config('firefly.subIconsByIdentifier.'.$account->accountType->type); $page = (int) $request->get('page'); $pageSize = (int) app('preferences')->get('listPageSize', 50)->data; - $currency = $this->repository->getAccountCurrency($account) ?? $this->defaultCurrency; + $currency = $this->repository->getAccountCurrency($account) ?? $this->primaryCurrency; $subTitle = (string) trans('firefly.all_journals_for_account', ['name' => $account->name]); $periods = new Collection(); @@ -232,7 +232,7 @@ class ShowController extends Controller $showAll = true; // correct Log::debug(sprintf('showAll: Call finalAccountBalance with date/time "%s"', $end->toIso8601String())); - $balances = Steam::filterAccountBalance(Steam::finalAccountBalance($account, $end), $account, $this->convertToNative, $accountCurrency); + $balances = Steam::filterAccountBalance(Steam::finalAccountBalance($account, $end), $account, $this->convertToPrimary, $accountCurrency); return view( 'accounts.show', diff --git a/app/Http/Controllers/Bill/CreateController.php b/app/Http/Controllers/Bill/CreateController.php index 664f7d8689..4bc0536a31 100644 --- a/app/Http/Controllers/Bill/CreateController.php +++ b/app/Http/Controllers/Bill/CreateController.php @@ -77,7 +77,7 @@ class CreateController extends Controller $periods[$current] = (string) trans('firefly.repeat_freq_'.$current); } $subTitle = (string) trans('firefly.create_new_bill'); - $defaultCurrency = $this->defaultCurrency; + $defaultCurrency = $this->primaryCurrency; // put previous url in session if not redirect from store (not "create another"). if (true !== session('bills.create.fromStore')) { diff --git a/app/Http/Controllers/Bill/EditController.php b/app/Http/Controllers/Bill/EditController.php index c3f7b24969..e744444798 100644 --- a/app/Http/Controllers/Bill/EditController.php +++ b/app/Http/Controllers/Bill/EditController.php @@ -88,7 +88,7 @@ class EditController extends Controller $bill->amount_min = app('steam')->bcround($bill->amount_min, $bill->transactionCurrency->decimal_places); $bill->amount_max = app('steam')->bcround($bill->amount_max, $bill->transactionCurrency->decimal_places); $rules = $this->repository->getRulesForBill($bill); - $defaultCurrency = $this->defaultCurrency; + $defaultCurrency = $this->primaryCurrency; // code to handle active-checkboxes $hasOldInput = null !== $request->old('_token'); diff --git a/app/Http/Controllers/Bill/IndexController.php b/app/Http/Controllers/Bill/IndexController.php index bd89b64edc..d45fd1a733 100644 --- a/app/Http/Controllers/Bill/IndexController.php +++ b/app/Http/Controllers/Bill/IndexController.php @@ -91,8 +91,8 @@ class IndexController extends Controller $admin = auth()->user(); $enrichment = new SubscriptionEnrichment(); $enrichment->setUser($admin); - $enrichment->setConvertToNative($this->convertToNative); - $enrichment->setNative($this->defaultCurrency); + $enrichment->setConvertToPrimary($this->convertToPrimary); + $enrichment->setPrimary($this->primaryCurrency); $enrichment->setStart($tempStart); $enrichment->setEnd($end); $collection = $enrichment->enrich($collection); @@ -100,8 +100,8 @@ class IndexController extends Controller $parameters->set('start', $tempStart); $parameters->set('end', $end); - $parameters->set('convertToNative', $this->convertToNative); - $parameters->set('defaultCurrency', $this->defaultCurrency); + $parameters->set('convertToPrimary', $this->convertToPrimary); + $parameters->set('defaultCurrency', $this->primaryCurrency); /** @var BillTransformer $transformer */ $transformer = app(BillTransformer::class); @@ -130,7 +130,7 @@ class IndexController extends Controller 'bills' => [], ]; - $currency = $bill->transactionCurrency ?? $this->defaultCurrency; + $currency = $bill->transactionCurrency ?? $this->primaryCurrency; $array['currency_id'] = $currency->id; $array['currency_name'] = $currency->name; $array['currency_symbol'] = $currency->symbol; diff --git a/app/Http/Controllers/Bill/ShowController.php b/app/Http/Controllers/Bill/ShowController.php index bf5306b791..8408546605 100644 --- a/app/Http/Controllers/Bill/ShowController.php +++ b/app/Http/Controllers/Bill/ShowController.php @@ -149,8 +149,8 @@ class ShowController extends Controller $admin = auth()->user(); $enrichment = new SubscriptionEnrichment(); $enrichment->setUser($admin); - $enrichment->setConvertToNative($this->convertToNative); - $enrichment->setNative($this->defaultCurrency); + $enrichment->setConvertToPrimary($this->convertToPrimary); + $enrichment->setPrimary($this->primaryCurrency); $enrichment->setStart($start); $enrichment->setEnd($end); $bill = $enrichment->enrichSingle($bill); diff --git a/app/Http/Controllers/Budget/CreateController.php b/app/Http/Controllers/Budget/CreateController.php index 602d797e59..45f05ad897 100644 --- a/app/Http/Controllers/Budget/CreateController.php +++ b/app/Http/Controllers/Budget/CreateController.php @@ -89,7 +89,7 @@ class CreateController extends Controller $preFilled = [ 'auto_budget_period' => $hasOldInput ? (bool) $request->old('auto_budget_period') : 'monthly', - 'auto_budget_currency_id' => $hasOldInput ? (int) $request->old('auto_budget_currency_id') : $this->defaultCurrency->id, + 'auto_budget_currency_id' => $hasOldInput ? (int) $request->old('auto_budget_currency_id') : $this->primaryCurrency->id, ]; $request->session()->flash('preFilled', $preFilled); diff --git a/app/Http/Controllers/Budget/EditController.php b/app/Http/Controllers/Budget/EditController.php index 7f9aeb8504..d030cc8f52 100644 --- a/app/Http/Controllers/Budget/EditController.php +++ b/app/Http/Controllers/Budget/EditController.php @@ -94,7 +94,7 @@ class EditController extends Controller $hasOldInput = null !== $request->old('_token'); $preFilled = [ 'active' => $hasOldInput ? (bool) $request->old('active') : $budget->active, - 'auto_budget_currency_id' => $hasOldInput ? (int) $request->old('auto_budget_currency_id') : $this->defaultCurrency->id, + 'auto_budget_currency_id' => $hasOldInput ? (int) $request->old('auto_budget_currency_id') : $this->primaryCurrency->id, ]; if ($autoBudget instanceof AutoBudget) { $amount = $hasOldInput ? $request->old('auto_budget_amount') : $autoBudget->amount; diff --git a/app/Http/Controllers/Budget/IndexController.php b/app/Http/Controllers/Budget/IndexController.php index 22e1cb382a..afb957312a 100644 --- a/app/Http/Controllers/Budget/IndexController.php +++ b/app/Http/Controllers/Budget/IndexController.php @@ -119,14 +119,14 @@ class IndexController extends Controller // get all available budgets: $availableBudgets = $this->getAllAvailableBudgets($start, $end); // get all active budgets: - $budgets = $this->getAllBudgets($start, $end, $currencies, $this->defaultCurrency); + $budgets = $this->getAllBudgets($start, $end, $currencies, $this->primaryCurrency); $sums = $this->getSums($budgets); // get budgeted for default currency: if (0 === count($availableBudgets)) { - $budgeted = $this->blRepository->budgeted($start, $end, $this->defaultCurrency); - $spentArr = $this->opsRepository->sumExpenses($start, $end, null, null, $this->defaultCurrency); - $spent = $spentArr[$this->defaultCurrency->id]['sum'] ?? '0'; + $budgeted = $this->blRepository->budgeted($start, $end, $this->primaryCurrency); + $spentArr = $this->opsRepository->sumExpenses($start, $end, null, null, $this->primaryCurrency); + $spent = $spentArr[$this->primaryCurrency->id]['sum'] ?? '0'; unset($spentArr); } @@ -136,7 +136,7 @@ class IndexController extends Controller // get all inactive budgets, and simply list them: $inactive = $this->repository->getInactiveBudgets(); - $defaultCurrency = $this->defaultCurrency; + $defaultCurrency = $this->primaryCurrency; return view( 'budgets.index', @@ -179,11 +179,11 @@ class IndexController extends Controller // spent in period: $spentArr = $this->opsRepository->sumExpenses($entry->start_date, $entry->end_date, null, null, $entry->transactionCurrency, false); $array['spent'] = $spentArr[$entry->transaction_currency_id]['sum'] ?? '0'; - $array['native_spent'] = $this->convertToNative && $entry->transaction_currency_id !== $this->defaultCurrency->id ? $converter->convert($entry->transactionCurrency, $this->defaultCurrency, $entry->start_date, $array['spent']) : null; + $array['pc_spent'] = $this->convertToPrimary && $entry->transaction_currency_id !== $this->primaryCurrency->id ? $converter->convert($entry->transactionCurrency, $this->primaryCurrency, $entry->start_date, $array['spent']) : null; // budgeted in period: $budgeted = $this->blRepository->budgeted($entry->start_date, $entry->end_date, $entry->transactionCurrency); $array['budgeted'] = $budgeted; - $array['native_budgeted'] = $this->convertToNative && $entry->transaction_currency_id !== $this->defaultCurrency->id ? $converter->convert($entry->transactionCurrency, $this->defaultCurrency, $entry->start_date, $budgeted) : null; + $array['pc_budgeted'] = $this->convertToPrimary && $entry->transaction_currency_id !== $this->primaryCurrency->id ? $converter->convert($entry->transactionCurrency, $this->primaryCurrency, $entry->start_date, $budgeted) : null; // this time, because of complex sums, use the currency converter. diff --git a/app/Http/Controllers/Budget/ShowController.php b/app/Http/Controllers/Budget/ShowController.php index 9c90829c77..36815436a4 100644 --- a/app/Http/Controllers/Budget/ShowController.php +++ b/app/Http/Controllers/Budget/ShowController.php @@ -188,8 +188,8 @@ class ShowController extends Controller 'currency' => $budgetLimit->transactionCurrency->name, ] ); - if ($this->convertToNative) { - $currencySymbol = $this->defaultCurrency->symbol; + if ($this->convertToPrimary) { + $currencySymbol = $this->primaryCurrency->symbol; } // collector: diff --git a/app/Http/Controllers/Chart/AccountController.php b/app/Http/Controllers/Chart/AccountController.php index 486530a8a1..2a24db8cee 100644 --- a/app/Http/Controllers/Chart/AccountController.php +++ b/app/Http/Controllers/Chart/AccountController.php @@ -96,7 +96,7 @@ class AccountController extends Controller $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); - $cache->addProperty($this->convertToNative); + $cache->addProperty($this->convertToPrimary); $cache->addProperty('chart.account.expense-accounts'); if ($cache->has()) { return response()->json($cache->get()); @@ -132,19 +132,19 @@ class AccountController extends Controller * @var string $endBalance */ foreach ($expenses as $key => $endBalance) { - if (!$this->convertToNative && 'native_balance' === $key) { + if (!$this->convertToPrimary && 'pc_balance' === $key) { // Log::debug(sprintf('[a] Will skip expense array "%s"', $key)); continue; } - if ($this->convertToNative && 'native_balance' !== $key) { + if ($this->convertToPrimary && 'pc_balance' !== $key) { // Log::debug(sprintf('[b] Will skip expense array "%s"', $key)); continue; } // Log::debug(sprintf('Will process expense array "%s" with amount %s', $key, $endBalance)); - $searchCode = $this->convertToNative ? $this->defaultCurrency->code : $key; - $searchCode = 'balance' === $searchCode || 'native_balance' === $searchCode ? $this->defaultCurrency->code : $searchCode; + $searchCode = $this->convertToPrimary ? $this->primaryCurrency->code : $key; + $searchCode = 'balance' === $searchCode || 'pc_balance' === $searchCode ? $this->primaryCurrency->code : $searchCode; // Log::debug(sprintf('Search code is %s', $searchCode)); // see if there is an accompanying start amount. // grab the difference and find the currency. @@ -433,7 +433,7 @@ class AccountController extends Controller $cache->addProperty('chart.account.period'); $cache->addProperty($start); $cache->addProperty($end); - $cache->addProperty($this->convertToNative); + $cache->addProperty($this->convertToPrimary); $cache->addProperty($account->id); if ($cache->has()) { return response()->json($cache->get()); @@ -453,8 +453,8 @@ class AccountController extends Controller $format = (string) trans('config.month_and_day_js', [], $locale); $accountCurrency = $this->accountRepository->getAccountCurrency($account); - $range = Steam::finalAccountBalanceInRange($account, $start, $end, $this->convertToNative); - $range = Steam::filterAccountBalances($range, $account, $this->convertToNative, $accountCurrency); + $range = Steam::finalAccountBalanceInRange($account, $start, $end, $this->convertToPrimary); + $range = Steam::filterAccountBalances($range, $account, $this->convertToPrimary, $accountCurrency); // temp, get end balance. Log::debug(sprintf('period: Call finalAccountBalance with date/time "%s"', $end->toIso8601String())); @@ -462,7 +462,7 @@ class AccountController extends Controller Log::debug('END temp get end balance done'); $previous = array_values($range)[0]; - $accountCurrency ??= $this->defaultCurrency; // do this AFTER getting the balances. + $accountCurrency ??= $this->primaryCurrency; // do this AFTER getting the balances. Log::debug('Start chart loop.'); $newRange = []; @@ -510,7 +510,7 @@ class AccountController extends Controller $chartData = []; foreach ($return as $key => $info) { - if ('balance' !== $key && 'native_balance' !== $key) { + if ('balance' !== $key && 'pc_balance' !== $key) { // assume it's a currency: $setCurrency = $this->currencyRepository->findByCode((string) $key); $info['currency_symbol'] = $setCurrency->symbol; @@ -522,10 +522,10 @@ class AccountController extends Controller $info['currency_code'] = $accountCurrency->code; $info['label'] = sprintf('%s (%s)', $account->name, $accountCurrency->symbol); } - if ('native_balance' === $key) { - $info['currency_symbol'] = $this->defaultCurrency->symbol; - $info['currency_code'] = $this->defaultCurrency->code; - $info['label'] = sprintf('%s (%s) (%s)', $account->name, (string) trans('firefly.sum'), $this->defaultCurrency->symbol); + if ('pc_balance' === $key) { + $info['currency_symbol'] = $this->primaryCurrency->symbol; + $info['currency_code'] = $this->primaryCurrency->code; + $info['label'] = sprintf('%s (%s) (%s)', $account->name, (string) trans('firefly.sum'), $this->primaryCurrency->symbol); } $chartData[] = $info; } @@ -578,7 +578,7 @@ class AccountController extends Controller $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); - $cache->addProperty($this->convertToNative); + $cache->addProperty($this->convertToPrimary); $cache->addProperty('chart.account.revenue-accounts'); if ($cache->has()) { return response()->json($cache->get()); @@ -615,19 +615,19 @@ class AccountController extends Controller * @var string $endBalance */ foreach ($expenses as $key => $endBalance) { - if (!$this->convertToNative && 'native_balance' === $key) { + if (!$this->convertToPrimary && 'pc_balance' === $key) { // Log::debug(sprintf('[a] Will skip expense array "%s"', $key)); continue; } - if ($this->convertToNative && 'native_balance' !== $key) { + if ($this->convertToPrimary && 'pc_balance' !== $key) { // Log::debug(sprintf('[b] Will skip expense array "%s"', $key)); continue; } // Log::debug(sprintf('Will process expense array "%s" with amount %s', $key, $endBalance)); - $searchCode = $this->convertToNative ? $this->defaultCurrency->code : $key; - $searchCode = 'balance' === $searchCode || 'native_balance' === $searchCode ? $this->defaultCurrency->code : $searchCode; + $searchCode = $this->convertToPrimary ? $this->primaryCurrency->code : $key; + $searchCode = 'balance' === $searchCode || 'pc_balance' === $searchCode ? $this->primaryCurrency->code : $searchCode; // Log::debug(sprintf('Search code is %s', $searchCode)); // see if there is an accompanying start amount. // grab the difference and find the currency. diff --git a/app/Http/Controllers/Chart/BillController.php b/app/Http/Controllers/Chart/BillController.php index 1d60113c62..ceb02a444b 100644 --- a/app/Http/Controllers/Chart/BillController.php +++ b/app/Http/Controllers/Chart/BillController.php @@ -109,7 +109,7 @@ class BillController extends Controller $cache = new CacheProperties(); $cache->addProperty('chart.bill.single'); $cache->addProperty($bill->id); - $cache->addProperty($this->convertToNative); + $cache->addProperty($this->convertToPrimary); if ($cache->has()) { return response()->json($cache->get()); } @@ -134,8 +134,8 @@ class BillController extends Controller } ); $currency = $bill->transactionCurrency; - if ($this->convertToNative) { - $currency = $this->defaultCurrency; + if ($this->convertToPrimary) { + $currency = $this->primaryCurrency; } $chartData = [ @@ -164,7 +164,7 @@ class BillController extends Controller $currencyId = $bill->transaction_currency_id; $amountMin = $bill->amount_min; $amountMax = $bill->amount_max; - if ($this->convertToNative && $currencyId !== $this->defaultCurrency->id) { + if ($this->convertToPrimary && $currencyId !== $this->primaryCurrency->id) { $amountMin = $bill->native_amount_min; $amountMax = $bill->native_amount_max; } @@ -178,11 +178,11 @@ class BillController extends Controller $chartData[2]['entries'][$date] = '0'; } $amount = bcmul((string) $journal['amount'], '-1'); - if ($this->convertToNative && $currencyId !== $journal['currency_id']) { - $amount = bcmul($journal['native_amount'] ?? '0', '-1'); + if ($this->convertToPrimary && $currencyId !== $journal['currency_id']) { + $amount = bcmul($journal['pc_amount'] ?? '0', '-1'); } - if ($this->convertToNative && $currencyId === $journal['foreign_currency_id']) { - $amount = bcmul((string) $journal['foreign_amount'], '-1'); + if ($this->convertToPrimary && $currencyId === $journal['foreign_currency_id']) { + $amount = bcmul((string) $journal['pc_amount'], '-1'); } $chartData[2]['entries'][$date] = bcadd($chartData[2]['entries'][$date], $amount); // amount of journal diff --git a/app/Http/Controllers/Chart/BudgetController.php b/app/Http/Controllers/Chart/BudgetController.php index 0865b5270b..ae9124068a 100644 --- a/app/Http/Controllers/Chart/BudgetController.php +++ b/app/Http/Controllers/Chart/BudgetController.php @@ -91,7 +91,7 @@ class BudgetController extends Controller $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); - $cache->addProperty($this->convertToNative); + $cache->addProperty($this->convertToPrimary); $cache->addProperty('chart.budget.budget'); $cache->addProperty($budget->id); @@ -108,7 +108,7 @@ class BudgetController extends Controller while ($end >= $loopStart) { /** @var Carbon $loopEnd */ $loopEnd = app('navigation')->endOfPeriod($loopStart, $step); - $spent = $this->opsRepository->sumExpenses($loopStart, $loopEnd, null, $collection); // this method already converts to native. + $spent = $this->opsRepository->sumExpenses($loopStart, $loopEnd, null, $collection); // this method already converts to primary currency. $label = trim((string) app('navigation')->periodShow($loopStart, $step)); foreach ($spent as $row) { @@ -157,7 +157,7 @@ class BudgetController extends Controller $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); - $cache->addProperty($this->convertToNative); + $cache->addProperty($this->convertToPrimary); $cache->addProperty('chart.budget.budget.limit'); $cache->addProperty($budgetLimit->id); $cache->addProperty($budget->id); @@ -170,14 +170,14 @@ class BudgetController extends Controller $amount = $budgetLimit->amount ?? '0'; $budgetCollection = new Collection([$budget]); $currency = $budgetLimit->transactionCurrency; - if ($this->convertToNative) { + if ($this->convertToPrimary) { $amount = $budgetLimit->native_amount ?? $amount; - $currency = $this->defaultCurrency; + $currency = $this->primaryCurrency; } while ($start <= $end) { $current = clone $start; - $expenses = $this->opsRepository->sumExpenses($current, $current, null, $budgetCollection, $budgetLimit->transactionCurrency, $this->convertToNative); + $expenses = $this->opsRepository->sumExpenses($current, $current, null, $budgetCollection, $budgetLimit->transactionCurrency, $this->convertToPrimary); $spent = $expenses[$currency->id]['sum'] ?? '0'; $amount = bcadd((string) $amount, $spent); $format = $start->isoFormat((string) trans('config.month_and_day_js', [], $locale)); @@ -205,7 +205,7 @@ class BudgetController extends Controller $budgetLimitId = $budgetLimit instanceof BudgetLimit ? $budgetLimit->id : 0; $cache = new CacheProperties(); $cache->addProperty($budget->id); - $cache->addProperty($this->convertToNative); + $cache->addProperty($this->convertToPrimary); $cache->addProperty($budgetLimitId); $cache->addProperty('chart.budget.expense-asset'); $start = session('first', today(config('app.timezone'))->startOfYear()); @@ -237,16 +237,16 @@ class BudgetController extends Controller $code = $journal['currency_code']; $name = $journal['currency_name']; - // if convert to native, use the native things, unless it's the foreign amount which is in the native currency. - if ($this->convertToNative && $journal['currency_id'] !== $this->defaultCurrency->id) { - $key = sprintf('%d-%d', $journal['source_account_id'], $this->defaultCurrency->id); - $symbol = $this->defaultCurrency->symbol; - $code = $this->defaultCurrency->code; - $name = $this->defaultCurrency->name; - $amount = $journal['native_amount']; + // if convert to primary, use the primary things, unless it's the foreign amount which is in the primary currency. + if ($this->convertToPrimary && $journal['currency_id'] !== $this->primaryCurrency->id) { + $key = sprintf('%d-%d', $journal['source_account_id'], $this->primaryCurrency->id); + $symbol = $this->primaryCurrency->symbol; + $code = $this->primaryCurrency->code; + $name = $this->primaryCurrency->name; + $amount = $journal['pc_amount']; } - if ($journal['foreign_currency_id'] === $this->defaultCurrency->id) { + if ($journal['foreign_currency_id'] === $this->primaryCurrency->id) { $amount = $journal['foreign_amount']; } @@ -288,7 +288,7 @@ class BudgetController extends Controller $budgetLimitId = $budgetLimit instanceof BudgetLimit ? $budgetLimit->id : 0; $cache = new CacheProperties(); $cache->addProperty($budget->id); - $cache->addProperty($this->convertToNative); + $cache->addProperty($this->convertToPrimary); $cache->addProperty($budgetLimitId); $cache->addProperty('chart.budget.expense-category'); $start = session('first', today(config('app.timezone'))->startOfYear()); @@ -315,22 +315,22 @@ class BudgetController extends Controller $code = $journal['currency_code']; $name = $journal['currency_name']; $amount = $journal['amount']; - // if convert to native, use the native things, unless it's the foreign amount which is in the native currency. - if ($this->convertToNative && $journal['currency_id'] !== $this->defaultCurrency->id && $journal['foreign_currency_id'] !== $this->defaultCurrency->id + // if convert to primary, use the primary things, unless it's the foreign amount which is in the primary currency. + if ($this->convertToPrimary && $journal['currency_id'] !== $this->primaryCurrency->id && $journal['foreign_currency_id'] !== $this->primaryCurrency->id ) { - $key = sprintf('%d-%d', $journal['category_id'], $this->defaultCurrency->id); - $symbol = $this->defaultCurrency->symbol; - $code = $this->defaultCurrency->code; - $name = $this->defaultCurrency->name; - $amount = $journal['native_amount']; + $key = sprintf('%d-%d', $journal['category_id'], $this->primaryCurrency->id); + $symbol = $this->primaryCurrency->symbol; + $code = $this->primaryCurrency->code; + $name = $this->primaryCurrency->name; + $amount = $journal['pc_amount']; } - if ($this->convertToNative && $journal['currency_id'] !== $this->defaultCurrency->id && $journal['foreign_currency_id'] === $this->defaultCurrency->id + if ($this->convertToPrimary && $journal['currency_id'] !== $this->primaryCurrency->id && $journal['foreign_currency_id'] === $this->primaryCurrency->id ) { - $key = sprintf('%d-%d', $journal['category_id'], $this->defaultCurrency->id); - $symbol = $this->defaultCurrency->symbol; - $code = $this->defaultCurrency->code; - $name = $this->defaultCurrency->name; + $key = sprintf('%d-%d', $journal['category_id'], $this->primaryCurrency->id); + $symbol = $this->primaryCurrency->symbol; + $code = $this->primaryCurrency->code; + $name = $this->primaryCurrency->name; $amount = $journal['foreign_amount']; } @@ -371,7 +371,7 @@ class BudgetController extends Controller $cache = new CacheProperties(); $cache->addProperty($budget->id); $cache->addProperty($budgetLimitId); - $cache->addProperty($this->convertToNative); + $cache->addProperty($this->convertToPrimary); $cache->addProperty('chart.budget.expense-expense'); $start = session('first', today(config('app.timezone'))->startOfYear()); $end = today(); @@ -400,20 +400,20 @@ class BudgetController extends Controller $code = $journal['currency_code']; $name = $journal['currency_name']; - // if convert to native, use the native things, unless it's the foreign amount which is in the native currency. - if ($this->convertToNative && $journal['currency_id'] !== $this->defaultCurrency->id && $journal['foreign_currency_id'] !== $this->defaultCurrency->id) { - $key = sprintf('%d-%d', $journal['destination_account_id'], $this->defaultCurrency->id); - $symbol = $this->defaultCurrency->symbol; - $code = $this->defaultCurrency->code; - $name = $this->defaultCurrency->name; - $amount = $journal['native_amount']; + // if convert to primary, use the primary things, unless it's the foreign amount which is in the primary currency. + if ($this->convertToPrimary && $journal['currency_id'] !== $this->primaryCurrency->id && $journal['foreign_currency_id'] !== $this->primaryCurrency->id) { + $key = sprintf('%d-%d', $journal['destination_account_id'], $this->primaryCurrency->id); + $symbol = $this->primaryCurrency->symbol; + $code = $this->primaryCurrency->code; + $name = $this->primaryCurrency->name; + $amount = $journal['pc_amount']; } - if ($this->convertToNative && $journal['currency_id'] !== $this->defaultCurrency->id && $journal['foreign_currency_id'] === $this->defaultCurrency->id) { - $key = sprintf('%d-%d', $journal['destination_account_id'], $this->defaultCurrency->id); - $symbol = $this->defaultCurrency->symbol; - $code = $this->defaultCurrency->code; - $name = $this->defaultCurrency->name; + if ($this->convertToPrimary && $journal['currency_id'] !== $this->primaryCurrency->id && $journal['foreign_currency_id'] === $this->primaryCurrency->id) { + $key = sprintf('%d-%d', $journal['destination_account_id'], $this->primaryCurrency->id); + $symbol = $this->primaryCurrency->symbol; + $code = $this->primaryCurrency->code; + $name = $this->primaryCurrency->name; $amount = $journal['foreign_amount']; } @@ -456,7 +456,7 @@ class BudgetController extends Controller $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); - $cache->addProperty($this->convertToNative); + $cache->addProperty($this->convertToPrimary); $cache->addProperty('chart.budget.frontpage'); if ($cache->has()) { return response()->json($cache->get()); @@ -466,8 +466,8 @@ class BudgetController extends Controller $chartGenerator->setUser(auth()->user()); $chartGenerator->setStart($start); $chartGenerator->setEnd($end); - $chartGenerator->convertToNative = $this->convertToNative; - $chartGenerator->default = $this->defaultCurrency; + $chartGenerator->convertToPrimary = $this->convertToPrimary; + $chartGenerator->default = $this->primaryCurrency; $chartData = $chartGenerator->generate(); $data = $this->generator->multiSet($chartData); diff --git a/app/Http/Controllers/Chart/CategoryController.php b/app/Http/Controllers/Chart/CategoryController.php index c9e243844f..c6324ca042 100644 --- a/app/Http/Controllers/Chart/CategoryController.php +++ b/app/Http/Controllers/Chart/CategoryController.php @@ -73,7 +73,7 @@ class CategoryController extends Controller $cache = new CacheProperties(); $cache->addProperty('chart.category.all'); $cache->addProperty($category->id); - $cache->addProperty($this->convertToNative); + $cache->addProperty($this->convertToPrimary); if ($cache->has()) { return response()->json($cache->get()); } @@ -87,7 +87,7 @@ class CategoryController extends Controller /** @var WholePeriodChartGenerator $chartGenerator */ $chartGenerator = app(WholePeriodChartGenerator::class); - $chartGenerator->convertToNative = $this->convertToNative; + $chartGenerator->convertToPrimary = $this->convertToPrimary; $chartData = $chartGenerator->generate($category, $start, $end); $data = $this->generator->multiSet($chartData); @@ -113,7 +113,7 @@ class CategoryController extends Controller $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); - $cache->addProperty($this->convertToNative); + $cache->addProperty($this->convertToPrimary); $cache->addProperty('chart.category.frontpage'); if ($cache->has()) { return response()->json($cache->get()); @@ -139,7 +139,7 @@ class CategoryController extends Controller $cache->addProperty('chart.category.period'); $cache->addProperty($accounts->pluck('id')->toArray()); $cache->addProperty($category); - $cache->addProperty($this->convertToNative); + $cache->addProperty($this->convertToPrimary); if ($cache->has()) { return response()->json($cache->get()); } diff --git a/app/Http/Controllers/Chart/ReportController.php b/app/Http/Controllers/Chart/ReportController.php index 40bccc3727..6dbb91ac9a 100644 --- a/app/Http/Controllers/Chart/ReportController.php +++ b/app/Http/Controllers/Chart/ReportController.php @@ -108,7 +108,7 @@ class ReportController extends Controller // loop result, add to array. /** @var array $netWorthItem */ foreach ($result as $key => $netWorthItem) { - if ('native' === $key) { + if ('primary' === $key) { continue; } $currencyId = $netWorthItem['currency_id']; diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php index daa9da7db8..b3175e9e8d 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -55,9 +55,9 @@ abstract class Controller extends BaseController // fails on PHP < 8.4 public protected(set) string $name; - protected bool $convertToNative = false; + protected bool $convertToPrimary = false; protected string $dateTimeFormat; - protected ?TransactionCurrency $defaultCurrency; + protected ?TransactionCurrency $primaryCurrency; protected string $monthAndDayFormat; protected string $monthFormat; protected string $redirectUrl = '/'; @@ -125,19 +125,19 @@ abstract class Controller extends BaseController $this->monthAndDayFormat = (string) trans('config.month_and_day_js', [], $locale); $this->dateTimeFormat = (string) trans('config.date_time_js', [], $locale); $darkMode = 'browser'; - $this->defaultCurrency = null; + $this->primaryCurrency = null; // get shown-intro-preference: if (auth()->check()) { - $this->defaultCurrency = Amount::getNativeCurrency(); + $this->primaryCurrency = Amount::getPrimaryCurrency(); $language = Steam::getLanguage(); $locale = Steam::getLocale(); $darkMode = app('preferences')->get('darkMode', 'browser')->data; - $this->convertToNative = Amount::convertToNative(); + $this->convertToPrimary = Amount::convertToPrimary(); $page = $this->getPageName(); $shownDemo = $this->hasSeenDemo(); View::share('language', $language); View::share('locale', $locale); - View::share('convertToNative', $this->convertToNative); + View::share('convertToPrimary', $this->convertToPrimary); View::share('shownDemo', $shownDemo); View::share('current_route_name', $page); View::share('original_route_name', Route::currentRouteName()); diff --git a/app/Http/Controllers/DebugController.php b/app/Http/Controllers/DebugController.php index 71f7b7dc27..a5c427b6a4 100644 --- a/app/Http/Controllers/DebugController.php +++ b/app/Http/Controllers/DebugController.php @@ -285,8 +285,8 @@ class DebugController extends Controller 'user_count' => User::count(), 'user_flags' => $userFlags, 'user_agent' => $userAgent, - 'native' => Amount::getNativeCurrency(), - 'convert_to_native' => Amount::convertToNative(), + 'primary' => Amount::getPrimaryCurrency(), + 'convert_to_primary' => Amount::convertToPrimary(), 'locale_attempts' => $localeAttempts, 'locale' => Steam::getLocale(), 'language' => Steam::getLanguage(), diff --git a/app/Http/Controllers/JavascriptController.php b/app/Http/Controllers/JavascriptController.php index ea062700d4..bccff306d9 100644 --- a/app/Http/Controllers/JavascriptController.php +++ b/app/Http/Controllers/JavascriptController.php @@ -55,7 +55,7 @@ class JavascriptController extends Controller foreach ($accounts as $account) { $accountId = $account->id; $currency = (int) $repository->getMetaValue($account, 'currency_id'); - $currency = 0 === $currency ? $this->defaultCurrency->id : $currency; + $currency = 0 === $currency ? $this->primaryCurrency->id : $currency; $entry = ['preferredCurrency' => $currency, 'name' => $account->name]; $data['accounts'][$accountId] = $entry; } @@ -95,9 +95,9 @@ class JavascriptController extends Controller public function variables(Request $request, AccountRepositoryInterface $repository): Response { $account = $repository->find((int) $request->get('account')); - $currency = $this->defaultCurrency; + $currency = $this->primaryCurrency; if ($account instanceof Account) { - $currency = $repository->getAccountCurrency($account) ?? $this->defaultCurrency; + $currency = $repository->getAccountCurrency($account) ?? $this->primaryCurrency; } $locale = app('steam')->getLocale(); $accounting = app('amount')->getJsConfig(); diff --git a/app/Http/Controllers/Json/BoxController.php b/app/Http/Controllers/Json/BoxController.php index c54b30ec64..ff3f5e8c83 100644 --- a/app/Http/Controllers/Json/BoxController.php +++ b/app/Http/Controllers/Json/BoxController.php @@ -68,7 +68,7 @@ class BoxController extends Controller $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); - $cache->addProperty($this->convertToNative); + $cache->addProperty($this->convertToPrimary); $cache->addProperty('box-balance'); if ($cache->has()) { return response()->json($cache->get()); @@ -77,7 +77,7 @@ class BoxController extends Controller $incomes = []; $expenses = []; $sums = []; - $currency = $this->defaultCurrency; + $currency = $this->primaryCurrency; // collect income of user: /** @var GroupCollectorInterface $collector */ @@ -89,7 +89,7 @@ class BoxController extends Controller /** @var array $journal */ foreach ($set as $journal) { - $currencyId = $this->convertToNative && $this->defaultCurrency->id !== (int) $journal['currency_id'] ? $this->defaultCurrency->id : (int) $journal['currency_id']; + $currencyId = $this->convertToPrimary && $this->primaryCurrency->id !== (int) $journal['currency_id'] ? $this->primaryCurrency->id : (int) $journal['currency_id']; $amount = Amount::getAmountFromJournal($journal); $incomes[$currencyId] ??= '0'; $incomes[$currencyId] = bcadd($incomes[$currencyId], (string) app('steam')->positive($amount)); @@ -107,7 +107,7 @@ class BoxController extends Controller /** @var array $journal */ foreach ($set as $journal) { - $currencyId = $this->convertToNative ? $this->defaultCurrency->id : (int) $journal['currency_id']; + $currencyId = $this->convertToPrimary ? $this->primaryCurrency->id : (int) $journal['currency_id']; $amount = Amount::getAmountFromJournal($journal); $expenses[$currencyId] ??= '0'; $expenses[$currencyId] = bcadd($expenses[$currencyId], $amount); @@ -124,10 +124,10 @@ class BoxController extends Controller $expenses[$currencyId] = app('amount')->formatAnything($currency, $expenses[$currencyId] ?? '0', false); } if (0 === count($sums)) { - $currency = $this->defaultCurrency; - $sums[$this->defaultCurrency->id] = app('amount')->formatAnything($this->defaultCurrency, '0', false); - $incomes[$this->defaultCurrency->id] = app('amount')->formatAnything($this->defaultCurrency, '0', false); - $expenses[$this->defaultCurrency->id] = app('amount')->formatAnything($this->defaultCurrency, '0', false); + $currency = $this->primaryCurrency; + $sums[$this->primaryCurrency->id] = app('amount')->formatAnything($this->primaryCurrency, '0', false); + $incomes[$this->primaryCurrency->id] = app('amount')->formatAnything($this->primaryCurrency, '0', false); + $expenses[$this->primaryCurrency->id] = app('amount')->formatAnything($this->primaryCurrency, '0', false); } $response = [ @@ -182,7 +182,7 @@ class BoxController extends Controller $netWorthSet = $netWorthHelper->byAccounts($filtered, $date); $return = []; foreach ($netWorthSet as $key => $data) { - if ('native' === $key) { + if ('primary' === $key) { continue; } $return[$data['currency_id']] = app('amount')->formatFlat($data['currency_symbol'], $data['currency_decimal_places'], $data['balance'], false); diff --git a/app/Http/Controllers/Json/FrontpageController.php b/app/Http/Controllers/Json/FrontpageController.php index f508c66763..f67ac10359 100644 --- a/app/Http/Controllers/Json/FrontpageController.php +++ b/app/Http/Controllers/Json/FrontpageController.php @@ -45,14 +45,12 @@ class FrontpageController extends Controller { $set = $repository->getPiggyBanks(); $info = []; - $native = Amount::getNativeCurrency(); - $convertToNative = Amount::convertToNative(); /** @var PiggyBank $piggyBank */ foreach ($set as $piggyBank) { $amount = $repository->getCurrentAmount($piggyBank); - $nativeAmount = $repository->getCurrentNativeAmount($piggyBank); + $pcAmount = $repository->getCurrentPrimaryCurrencyAmount($piggyBank); if (1 === bccomp($amount, '0')) { // percentage! $pct = 0; @@ -64,15 +62,15 @@ class FrontpageController extends Controller 'id' => $piggyBank->id, 'name' => $piggyBank->name, 'amount' => $amount, - 'native_amount' => $nativeAmount, + 'pc_amount' => $pcAmount, 'target' => $piggyBank->target_amount, - 'native_target' => $piggyBank->native_target_amount, + 'pc_target' => $piggyBank->native_target_amount, 'percentage' => $pct, // currency: 'currency_symbol' => $piggyBank->transactionCurrency->symbol, 'currency_decimal_places' => $piggyBank->transactionCurrency->decimal_places, - 'native_currency_symbol' => $native->symbol, - 'native_currency_decimal_places' => $native->decimal_places, + 'primary_currency_symbol' => $this->primaryCurrency->symbol, + 'primary_currency_decimal_places' => $this->primaryCurrency->decimal_places, ]; @@ -89,7 +87,9 @@ class FrontpageController extends Controller $html = ''; if (0 !== count($info)) { try { - $html = view('json.piggy-banks', compact('info', 'convertToNative', 'native'))->render(); + $convertToPrimary = $this->convertToPrimary; + $primary = $this->primaryCurrency; + $html = view('json.piggy-banks', compact('info', 'convertToPrimary', 'primary'))->render(); } catch (Throwable $e) { app('log')->error(sprintf('Cannot render json.piggy-banks: %s', $e->getMessage())); app('log')->error($e->getTraceAsString()); diff --git a/app/Http/Controllers/Json/ReconcileController.php b/app/Http/Controllers/Json/ReconcileController.php index db7642cfe8..44a4d0cdf9 100644 --- a/app/Http/Controllers/Json/ReconcileController.php +++ b/app/Http/Controllers/Json/ReconcileController.php @@ -74,7 +74,7 @@ class ReconcileController extends Controller { $startBalance = $request->get('startBalance'); $endBalance = $request->get('endBalance'); - $accountCurrency = $this->accountRepos->getAccountCurrency($account) ?? $this->defaultCurrency; + $accountCurrency = $this->accountRepos->getAccountCurrency($account) ?? $this->primaryCurrency; $amount = '0'; $clearedAmount = '0'; @@ -195,7 +195,7 @@ class ReconcileController extends Controller $startDate = clone $start; $startDate->subDay(); - $currency = $this->accountRepos->getAccountCurrency($account) ?? $this->defaultCurrency; + $currency = $this->accountRepos->getAccountCurrency($account) ?? $this->primaryCurrency; // correct Log::debug(sprintf('transactions: Call finalAccountBalance with date/time "%s"', $startDate->toIso8601String())); Log::debug(sprintf('transactions2: Call finalAccountBalance with date/time "%s"', $end->toIso8601String())); diff --git a/app/Http/Controllers/PiggyBank/IndexController.php b/app/Http/Controllers/PiggyBank/IndexController.php index b6379e859c..e27f0878d5 100644 --- a/app/Http/Controllers/PiggyBank/IndexController.php +++ b/app/Http/Controllers/PiggyBank/IndexController.php @@ -148,7 +148,7 @@ class IndexController extends Controller // enrich each account. $enrichment = new AccountEnrichment(); $enrichment->setUser(auth()->user()); - $enrichment->setNative($this->defaultCurrency); + $enrichment->setPrimary($this->primaryCurrency); $return = []; /** @var PiggyBank $piggy */ diff --git a/app/Http/Controllers/PreferencesController.php b/app/Http/Controllers/PreferencesController.php index 3031037624..ab0cd9717a 100644 --- a/app/Http/Controllers/PreferencesController.php +++ b/app/Http/Controllers/PreferencesController.php @@ -112,7 +112,7 @@ class PreferencesController extends Controller $darkMode = Preferences::get('darkMode', 'browser')->data; $customFiscalYear = Preferences::get('customFiscalYear', 0)->data; $fiscalYearStartStr = Preferences::get('fiscalYearStart', '01-01')->data; - $convertToNative = $this->convertToNative; + $convertToPrimary = $this->convertToPrimary; if (is_array($fiscalYearStartStr)) { $fiscalYearStartStr = '01-01'; } @@ -198,7 +198,7 @@ class PreferencesController extends Controller 'darkMode', 'availableDarkModes', 'notifications', - 'convertToNative', + 'convertToPrimary', 'slackUrl', 'locales', 'locale', @@ -265,15 +265,15 @@ class PreferencesController extends Controller Preferences::set('ntfy_auth', $all['ntfy_auth'] ?? false); } - // convert native - $convertToNative = 1 === (int) $request->get('convertToNative'); - if ($convertToNative && !$this->convertToNative) { + // convert primary + $convertToPrimary = 1 === (int) $request->get('convertToPrimary'); + if ($convertToPrimary && !$this->convertToPrimary) { // set to true! - Log::debug('User sets convertToNative to true.'); - Preferences::set('convert_to_native', $convertToNative); + Log::debug('User sets convertToPrimary to true.'); + Preferences::set('convert_to_primary', $convertToPrimary); event(new UserGroupChangedDefaultCurrency(auth()->user()->userGroup)); } - Preferences::set('convert_to_native', $convertToNative); + Preferences::set('convert_to_primary', $convertToPrimary); // custom fiscal year $customFiscalYear = 1 === (int) $request->get('customFiscalYear'); diff --git a/app/Http/Controllers/Recurring/CreateController.php b/app/Http/Controllers/Recurring/CreateController.php index 35f4e25a8f..9e2c70e99b 100644 --- a/app/Http/Controllers/Recurring/CreateController.php +++ b/app/Http/Controllers/Recurring/CreateController.php @@ -84,7 +84,7 @@ class CreateController extends Controller { $budgets = app('expandedform')->makeSelectListWithEmpty($this->budgetRepos->getActiveBudgets()); $bills = app('expandedform')->makeSelectListWithEmpty($this->billRepository->getActiveBills()); - $defaultCurrency = $this->defaultCurrency; + $defaultCurrency = $this->primaryCurrency; $tomorrow = today(config('app.timezone')); $oldRepetitionType = $request->old('repetition_type'); $tomorrow->addDay(); @@ -129,7 +129,7 @@ class CreateController extends Controller { $budgets = app('expandedform')->makeSelectListWithEmpty($this->budgetRepos->getActiveBudgets()); $bills = app('expandedform')->makeSelectListWithEmpty($this->billRepository->getActiveBills()); - $defaultCurrency = $this->defaultCurrency; + $defaultCurrency = $this->primaryCurrency; $tomorrow = today(config('app.timezone')); $oldRepetitionType = $request->old('repetition_type'); $tomorrow->addDay(); diff --git a/app/Http/Controllers/Transaction/ConvertController.php b/app/Http/Controllers/Transaction/ConvertController.php index 5a524db619..8f24176f59 100644 --- a/app/Http/Controllers/Transaction/ConvertController.php +++ b/app/Http/Controllers/Transaction/ConvertController.php @@ -228,7 +228,7 @@ class ConvertController extends Controller $date = today()->endOfDay(); Log::debug(sprintf('getLiabilities: Call finalAccountBalance with date/time "%s"', $date->toIso8601String())); $balance = Steam::finalAccountBalance($account, $date)['balance']; - $currency = $this->accountRepository->getAccountCurrency($account) ?? $this->defaultCurrency; + $currency = $this->accountRepository->getAccountCurrency($account) ?? $this->primaryCurrency; $role = 'l_'.$account->accountType->type; $key = (string) trans('firefly.opt_group_'.$role); $grouped[$key][$account->id] = $account->name.' ('.app('amount')->formatAnything($currency, $balance, false).')'; @@ -252,7 +252,7 @@ class ConvertController extends Controller $date = today()->endOfDay(); Log::debug(sprintf('getAssetAccounts: Call finalAccountBalance with date/time "%s"', $date->toIso8601String())); $balance = Steam::finalAccountBalance($account, $date)['balance']; - $currency = $this->accountRepository->getAccountCurrency($account) ?? $this->defaultCurrency; + $currency = $this->accountRepository->getAccountCurrency($account) ?? $this->primaryCurrency; $role = (string) $this->accountRepository->getMetaValue($account, 'account_role'); if ('' === $role) { $role = 'no_account_type'; diff --git a/app/Http/Controllers/Transaction/CreateController.php b/app/Http/Controllers/Transaction/CreateController.php index 8fdaf2e2a4..6eab9a121c 100644 --- a/app/Http/Controllers/Transaction/CreateController.php +++ b/app/Http/Controllers/Transaction/CreateController.php @@ -117,7 +117,7 @@ class CreateController extends Controller $optionalFields = app('preferences')->get('transaction_journal_optional_fields', [])->data; $allowedOpposingTypes = config('firefly.allowed_opposing_types'); $accountToTypes = config('firefly.account_to_transaction'); - $defaultCurrency = $this->defaultCurrency; + $defaultCurrency = $this->primaryCurrency; $previousUrl = $this->rememberPreviousUrl('transactions.create.url'); $parts = parse_url((string) $previousUrl); $search = sprintf('?%s', $parts['query'] ?? ''); diff --git a/app/Http/Controllers/Transaction/EditController.php b/app/Http/Controllers/Transaction/EditController.php index ee8a9897a4..14b1614ee0 100644 --- a/app/Http/Controllers/Transaction/EditController.php +++ b/app/Http/Controllers/Transaction/EditController.php @@ -84,7 +84,7 @@ class EditController extends Controller $title = $transactionGroup->transactionJournals()->count() > 1 ? $transactionGroup->title : $transactionGroup->transactionJournals()->first()->description; $subTitle = (string) trans('firefly.edit_transaction_title', ['description' => $title]); $subTitleIcon = 'fa-plus'; - $defaultCurrency = $this->defaultCurrency; + $defaultCurrency = $this->primaryCurrency; $cash = $repository->getCashAccount(); $previousUrl = $this->rememberPreviousUrl('transactions.edit.url'); $parts = parse_url((string) $previousUrl); diff --git a/app/Http/Controllers/TransactionCurrency/IndexController.php b/app/Http/Controllers/TransactionCurrency/IndexController.php index e57cc16384..e6fe7edde4 100644 --- a/app/Http/Controllers/TransactionCurrency/IndexController.php +++ b/app/Http/Controllers/TransactionCurrency/IndexController.php @@ -74,10 +74,10 @@ class IndexController extends Controller // order so default and enabled are on top: $collection = $collection->sortBy( static function (TransactionCurrency $currency) { - $native = true === $currency->userGroupNative ? 0 : 1; + $primary = true === $currency->userGroupNative ? 0 : 1; $enabled = true === $currency->userGroupEnabled ? 0 : 1; - return sprintf('%s-%s-%s', $native, $enabled, $currency->code); + return sprintf('%s-%s-%s', $primary, $enabled, $currency->code); } ); $total = $collection->count(); diff --git a/app/Http/Middleware/Range.php b/app/Http/Middleware/Range.php index 4699a454c0..31933b924a 100644 --- a/app/Http/Middleware/Range.php +++ b/app/Http/Middleware/Range.php @@ -120,7 +120,7 @@ class Range // save some formats: $monthAndDayFormat = (string) trans('config.month_and_day_js', [], $locale); $dateTimeFormat = (string) trans('config.date_time_js', [], $locale); - $defaultCurrency = Amount::getNativeCurrency(); + $defaultCurrency = Amount::getPrimaryCurrency(); // also format for moment JS: $madMomentJS = (string) trans('config.month_and_day_moment_js', [], $locale); diff --git a/app/Http/Requests/PiggyBankStoreRequest.php b/app/Http/Requests/PiggyBankStoreRequest.php index 61ba326821..d7a9058100 100644 --- a/app/Http/Requests/PiggyBankStoreRequest.php +++ b/app/Http/Requests/PiggyBankStoreRequest.php @@ -126,7 +126,7 @@ class PiggyBankStoreRequest extends FormRequest $currencyId = (int) ($data['transaction_currency_id'] ?? 0); $currency = TransactionCurrency::find($currencyId); if (null === $currency) { - return Amount::getNativeCurrency(); + return Amount::getPrimaryCurrency(); } return $currency; diff --git a/app/Http/Requests/PiggyBankUpdateRequest.php b/app/Http/Requests/PiggyBankUpdateRequest.php index d6facfb7de..37c895cde4 100644 --- a/app/Http/Requests/PiggyBankUpdateRequest.php +++ b/app/Http/Requests/PiggyBankUpdateRequest.php @@ -131,7 +131,7 @@ class PiggyBankUpdateRequest extends FormRequest $currencyId = (int) ($data['transaction_currency_id'] ?? 0); $currency = TransactionCurrency::find($currencyId); if (null === $currency) { - return Amount::getNativeCurrency(); + return Amount::getPrimaryCurrency(); } return $currency; diff --git a/app/Models/TransactionCurrency.php b/app/Models/TransactionCurrency.php index 4f93717955..83dfd6bfe0 100644 --- a/app/Models/TransactionCurrency.php +++ b/app/Models/TransactionCurrency.php @@ -65,7 +65,7 @@ class TransactionCurrency extends Model public function refreshForUser(User $user): void { $current = $user->userGroup->currencies()->where('transaction_currencies.id', $this->id)->first(); - $native = app('amount')->getNativeCurrencyByUserGroup($user->userGroup); + $native = app('amount')->getPrimaryCurrencyByUserGroup($user->userGroup); $this->userGroupNative = $native->id === $this->id; $this->userGroupEnabled = null !== $current; } diff --git a/app/Providers/EventServiceProvider.php b/app/Providers/EventServiceProvider.php index 3776b71f10..4a78b01823 100644 --- a/app/Providers/EventServiceProvider.php +++ b/app/Providers/EventServiceProvider.php @@ -258,7 +258,7 @@ class EventServiceProvider extends ServiceProvider ], // preferences UserGroupChangedDefaultCurrency::class => [ - 'FireflyIII\Handlers\Events\PreferencesEventHandler@resetNativeAmounts', + 'FireflyIII\Handlers\Events\PreferencesEventHandler@resetPrimaryCurrencyAmounts', ], ]; diff --git a/app/Repositories/Account/AccountRepository.php b/app/Repositories/Account/AccountRepository.php index 47cae859bc..d67213d74e 100644 --- a/app/Repositories/Account/AccountRepository.php +++ b/app/Repositories/Account/AccountRepository.php @@ -295,7 +295,7 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac /** * Returns the amount of the opening balance for this account. */ - public function getOpeningBalanceAmount(Account $account, bool $convertToNative): ?string + public function getOpeningBalanceAmount(Account $account, bool $convertToPrimary): ?string { $journal = TransactionJournal::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->where('transactions.account_id', $account->id) @@ -309,7 +309,7 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac if (null === $transaction) { return null; } - if ($convertToNative) { + if ($convertToPrimary) { return $transaction->native_amount ?? '0'; } @@ -357,7 +357,7 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac if (AccountTypeEnum::ASSET->value !== $account->accountType->type) { throw new FireflyException(sprintf('%s is not an asset account.', $account->name)); } - $currency = $this->getAccountCurrency($account) ?? app('amount')->getNativeCurrency(); + $currency = $this->getAccountCurrency($account) ?? app('amount')->getPrimaryCurrency(); $name = trans('firefly.reconciliation_account_name', ['name' => $account->name, 'currency' => $currency->code]); /** @var AccountType $type */ diff --git a/app/Repositories/Account/AccountRepositoryInterface.php b/app/Repositories/Account/AccountRepositoryInterface.php index 8f54067bc5..3a16896695 100644 --- a/app/Repositories/Account/AccountRepositoryInterface.php +++ b/app/Repositories/Account/AccountRepositoryInterface.php @@ -117,7 +117,7 @@ interface AccountRepositoryInterface /** * Returns the amount of the opening balance for this account. */ - public function getOpeningBalanceAmount(Account $account, bool $convertToNative): ?string; + public function getOpeningBalanceAmount(Account $account, bool $convertToPrimary): ?string; /** * Return date of opening balance as string or null. diff --git a/app/Repositories/Account/AccountTasker.php b/app/Repositories/Account/AccountTasker.php index 031794595e..a8fda5196c 100644 --- a/app/Repositories/Account/AccountTasker.php +++ b/app/Repositories/Account/AccountTasker.php @@ -58,7 +58,7 @@ class AccountTasker implements AccountTaskerInterface, UserGroupInterface /** @var AccountRepositoryInterface $repository */ $repository = app(AccountRepositoryInterface::class); - $defaultCurrency = app('amount')->getNativeCurrencyByUserGroup($this->user->userGroup); + $primaryCurrency = app('amount')->getPrimaryCurrencyByUserGroup($this->user->userGroup); $return = [ 'accounts' => [], @@ -68,7 +68,7 @@ class AccountTasker implements AccountTaskerInterface, UserGroupInterface /** @var Account $account */ foreach ($accounts as $account) { $id = $account->id; - $currency = $repository->getAccountCurrency($account) ?? $defaultCurrency; + $currency = $repository->getAccountCurrency($account) ?? $primaryCurrency; $return['sums'][$currency->id] ??= [ 'start' => '0', 'end' => '0', @@ -148,11 +148,11 @@ class AccountTasker implements AccountTaskerInterface, UserGroupInterface */ private function groupExpenseByDestination(array $array): array { - $defaultCurrency = app('amount')->getNativeCurrencyByUserGroup($this->user->userGroup); + $primaryCurrency = app('amount')->getPrimaryCurrencyByUserGroup($this->user->userGroup); /** @var CurrencyRepositoryInterface $currencyRepos */ $currencyRepos = app(CurrencyRepositoryInterface::class); - $currencies = [$defaultCurrency->id => $defaultCurrency]; + $currencies = [$primaryCurrency->id => $primaryCurrency]; $report = [ 'accounts' => [], 'sums' => [], @@ -236,11 +236,11 @@ class AccountTasker implements AccountTaskerInterface, UserGroupInterface */ private function groupIncomeBySource(array $array): array { - $defaultCurrency = app('amount')->getNativeCurrencyByUserGroup($this->user->userGroup); + $primaryCurrency = app('amount')->getPrimaryCurrencyByUserGroup($this->user->userGroup); /** @var CurrencyRepositoryInterface $currencyRepos */ $currencyRepos = app(CurrencyRepositoryInterface::class); - $currencies = [$defaultCurrency->id => $defaultCurrency]; + $currencies = [$primaryCurrency->id => $primaryCurrency]; $report = [ 'accounts' => [], 'sums' => [], diff --git a/app/Repositories/Bill/BillRepository.php b/app/Repositories/Bill/BillRepository.php index 48bd57711b..62da96a65b 100644 --- a/app/Repositories/Bill/BillRepository.php +++ b/app/Repositories/Bill/BillRepository.php @@ -264,19 +264,19 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface $currency = $journal->transactionCurrency; $result[$currencyId] ??= [ 'sum' => '0', - 'native_sum' => '0', + 'pc_sum' => '0', 'count' => 0, 'avg' => '0', - 'native_avg' => '0', + 'pc_avg' => '0', 'currency_id' => $currency->id, 'currency_code' => $currency->code, 'currency_symbol' => $currency->symbol, 'currency_decimal_places' => $currency->decimal_places, ]; $result[$currencyId]['sum'] = bcadd($result[$currencyId]['sum'], (string) $transaction->amount); - $result[$currencyId]['native_sum'] = bcadd($result[$currencyId]['native_sum'], $transaction->native_amount ?? '0'); - if ($journal->foreign_currency_id === Amount::getNativeCurrency()->id) { - $result[$currencyId]['native_sum'] = bcadd($result[$currencyId]['native_sum'], (string) $transaction->amount); + $result[$currencyId]['pc_sum'] = bcadd($result[$currencyId]['pc_sum'], $transaction->native_amount ?? '0'); + if ($journal->foreign_currency_id === Amount::getPrimaryCurrency()->id) { + $result[$currencyId]['pc_sum'] = bcadd($result[$currencyId]['pc_sum'], (string) $transaction->amount); } ++$result[$currencyId]['count']; } @@ -288,7 +288,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface */ foreach ($result as $currencyId => $arr) { $result[$currencyId]['avg'] = bcdiv((string) $arr['sum'], (string) $arr['count']); - $result[$currencyId]['native_avg'] = bcdiv((string) $arr['native_sum'], (string) $arr['count']); + $result[$currencyId]['pc_avg'] = bcdiv((string) $arr['pc_sum'], (string) $arr['count']); } return $result; @@ -401,7 +401,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface $currency = $journal->transactionCurrency; $result[$currencyId] ??= [ 'sum' => '0', - 'native_sum' => '0', + 'pc_sum' => '0', 'count' => 0, 'avg' => '0', 'currency_id' => $currency->id, @@ -410,9 +410,9 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface 'currency_decimal_places' => $currency->decimal_places, ]; $result[$currencyId]['sum'] = bcadd($result[$currencyId]['sum'], (string) $transaction->amount); - $result[$currencyId]['native_sum'] = bcadd($result[$currencyId]['native_sum'], $transaction->native_amount ?? '0'); - if ($journal->foreign_currency_id === Amount::getNativeCurrency()->id) { - $result[$currencyId]['native_sum'] = bcadd($result[$currencyId]['native_sum'], (string) $transaction->amount); + $result[$currencyId]['pc_sum'] = bcadd($result[$currencyId]['pc_sum'], $transaction->native_amount ?? '0'); + if ($journal->foreign_currency_id === Amount::getPrimaryCurrency()->id) { + $result[$currencyId]['pc_sum'] = bcadd($result[$currencyId]['pc_sum'], (string) $transaction->amount); } ++$result[$currencyId]['count']; } @@ -424,7 +424,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface */ foreach ($result as $currencyId => $arr) { $result[$currencyId]['avg'] = bcdiv((string) $arr['sum'], (string) $arr['count']); - $result[$currencyId]['native_avg'] = bcdiv((string) $arr['native_sum'], (string) $arr['count']); + $result[$currencyId]['pc_avg'] = bcdiv((string) $arr['pc_sum'], (string) $arr['count']); } return $result; @@ -534,15 +534,15 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface Log::debug(sprintf('sumPaidInRange from %s to %s', $start->toW3cString(), $end->toW3cString())); $bills = $this->getActiveBills(); $return = []; - $convertToNative = Amount::convertToNative($this->user); - $default = app('amount')->getNativeCurrency(); + $convertToPrimary = Amount::convertToPrimary($this->user); + $primary = app('amount')->getPrimaryCurrency(); /** @var Bill $bill */ foreach ($bills as $bill) { /** @var Collection $set */ $set = $bill->transactionJournals()->after($start)->before($end)->get(['transaction_journals.*']); - $currency = $convertToNative && $bill->transactionCurrency->id !== $default->id ? $default : $bill->transactionCurrency; + $currency = $convertToPrimary && $bill->transactionCurrency->id !== $primary->id ? $primary : $bill->transactionCurrency; $return[(int) $currency->id] ??= [ 'id' => (string) $currency->id, 'name' => $currency->name, @@ -600,8 +600,8 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface app('log')->debug(sprintf('Now in sumUnpaidInRange("%s", "%s")', $start->format('Y-m-d'), $end->format('Y-m-d'))); $bills = $this->getActiveBills(); $return = []; - $convertToNative = Amount::convertToNative($this->user); - $default = app('amount')->getNativeCurrency(); + $convertToPrimary = Amount::convertToPrimary($this->user); + $primary = app('amount')->getPrimaryCurrency(); /** @var Bill $bill */ foreach ($bills as $bill) { @@ -612,12 +612,12 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface // app('log')->debug(sprintf('Pay dates: %d, count: %d, left: %d', $dates->count(), $count, $total)); // app('log')->debug('dates', $dates->toArray()); - $minField = $convertToNative && $bill->transactionCurrency->id !== $default->id ? 'native_amount_min' : 'amount_min'; - $maxField = $convertToNative && $bill->transactionCurrency->id !== $default->id ? 'native_amount_max' : 'amount_max'; + $minField = $convertToPrimary && $bill->transactionCurrency->id !== $primary->id ? 'native_amount_min' : 'amount_min'; + $maxField = $convertToPrimary && $bill->transactionCurrency->id !== $primary->id ? 'native_amount_max' : 'amount_max'; // Log::debug(sprintf('min field is %s, max field is %s', $minField, $maxField)); if ($total > 0) { - $currency = $convertToNative && $bill->transactionCurrency->id !== $default->id ? $default : $bill->transactionCurrency; + $currency = $convertToPrimary && $bill->transactionCurrency->id !== $primary->id ? $primary : $bill->transactionCurrency; $average = bcdiv(bcadd($bill->{$maxField} ?? '0', $bill->{$minField} ?? '0'), '2'); Log::debug(sprintf('Amount to pay is %s %s (%d times)', $currency->code, $average, $total)); $return[$currency->id] ??= [ diff --git a/app/Repositories/Budget/AvailableBudgetRepository.php b/app/Repositories/Budget/AvailableBudgetRepository.php index 2ec270541f..641e5e7157 100644 --- a/app/Repositories/Budget/AvailableBudgetRepository.php +++ b/app/Repositories/Budget/AvailableBudgetRepository.php @@ -141,14 +141,14 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U Log::debug(sprintf('Found %d available budgets (already converted)', $availableBudgets->count())); - // use native amount if necessary? - $convertToNative = Amount::convertToNative($this->user); - $default = Amount::getNativeCurrency(); + // use primary amount if necessary? + $convertToPrimary = Amount::convertToPrimary($this->user); + $primary = Amount::getPrimaryCurrency(); /** @var AvailableBudget $availableBudget */ foreach ($availableBudgets as $availableBudget) { - $currencyId = $convertToNative && $availableBudget->transaction_currency_id !== $default->id ? $default->id : $availableBudget->transaction_currency_id; - $field = $convertToNative && $availableBudget->transaction_currency_id !== $default->id ? 'native_amount' : 'amount'; + $currencyId = $convertToPrimary && $availableBudget->transaction_currency_id !== $primary->id ? $primary->id : $availableBudget->transaction_currency_id; + $field = $convertToPrimary && $availableBudget->transaction_currency_id !== $primary->id ? 'native_amount' : 'amount'; $return[$currencyId] ??= '0'; $amount = '' === (string) $availableBudget->{$field} ? '0' : (string) $availableBudget->{$field}; $return[$currencyId] = bcadd($return[$currencyId], $amount); diff --git a/app/Repositories/Budget/BudgetLimitRepository.php b/app/Repositories/Budget/BudgetLimitRepository.php index 87a18dde34..8974613364 100644 --- a/app/Repositories/Budget/BudgetLimitRepository.php +++ b/app/Repositories/Budget/BudgetLimitRepository.php @@ -271,7 +271,7 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup $factory = app(TransactionCurrencyFactory::class); $currency = $factory->find($data['currency_id'] ?? null, $data['currency_code'] ?? null); if (null === $currency) { - $currency = app('amount')->getNativeCurrencyByUserGroup($this->user->userGroup); + $currency = app('amount')->getPrimaryCurrencyByUserGroup($this->user->userGroup); } $currency->enabled = true; $currency->save(); @@ -369,7 +369,7 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup } // catch unexpected null: if (null === $currency) { - $currency = $budgetLimit->transactionCurrency ?? app('amount')->getNativeCurrencyByUserGroup($this->user->userGroup); + $currency = $budgetLimit->transactionCurrency ?? app('amount')->getPrimaryCurrencyByUserGroup($this->user->userGroup); } $currency->enabled = true; $currency->save(); diff --git a/app/Repositories/Budget/BudgetRepository.php b/app/Repositories/Budget/BudgetRepository.php index 6c7cf80784..def70b71d5 100644 --- a/app/Repositories/Budget/BudgetRepository.php +++ b/app/Repositories/Budget/BudgetRepository.php @@ -91,7 +91,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface $limitRepository = app(BudgetLimitRepository::class); $limitRepository->setUser($this->user); $budgets = $this->getActiveBudgets(); - $defaultCurrency = app('amount')->getNativeCurrency(); + $primaryCurrency = app('amount')->getPrimaryCurrency(); $converter = new ExchangeRateConverter(); /** @var Budget $budget */ @@ -103,7 +103,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface foreach ($limits as $limit) { app('log')->debug(sprintf('Budget limit #%d', $limit->id)); $currency = $limit->transactionCurrency; - $rate = $converter->getCurrencyRate($currency, $defaultCurrency, $end); + $rate = $converter->getCurrencyRate($currency, $primaryCurrency, $end); $currencyCode = $currency->code; $return[$currencyCode] ??= [ 'currency_id' => (string) $currency->id, @@ -111,18 +111,18 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface 'currency_symbol' => $currency->symbol, 'currency_code' => $currency->code, 'currency_decimal_places' => $currency->decimal_places, - 'native_currency_id' => (string) $defaultCurrency->id, - 'native_currency_name' => $defaultCurrency->name, - 'native_currency_symbol' => $defaultCurrency->symbol, - 'native_currency_code' => $defaultCurrency->code, - 'native_currency_decimal_places' => $defaultCurrency->decimal_places, + 'primary_currency_id' => (string) $primaryCurrency->id, + 'primary_currency_name' => $primaryCurrency->name, + 'primary_currency_symbol' => $primaryCurrency->symbol, + 'primary_currency_code' => $primaryCurrency->code, + 'primary_currency_decimal_places' => $primaryCurrency->decimal_places, 'sum' => '0', - 'native_sum' => '0', + 'pc_sum' => '0', ]; // same period if ($limit->start_date->isSameDay($start) && $limit->end_date->isSameDay($end)) { $return[$currencyCode]['sum'] = bcadd($return[$currencyCode]['sum'], (string) $limit->amount); - $return[$currencyCode]['native_sum'] = bcmul($rate, $return[$currencyCode]['sum']); + $return[$currencyCode]['pc_sum'] = bcmul($rate, $return[$currencyCode]['sum']); app('log')->debug(sprintf('Add full amount [1]: %s', $limit->amount)); continue; @@ -130,7 +130,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface // limit is inside of date range if ($start->lte($limit->start_date) && $end->gte($limit->end_date)) { $return[$currencyCode]['sum'] = bcadd($return[$currencyCode]['sum'], (string) $limit->amount); - $return[$currencyCode]['native_sum'] = bcmul($rate, $return[$currencyCode]['sum']); + $return[$currencyCode]['pc_sum'] = bcmul($rate, $return[$currencyCode]['sum']); app('log')->debug(sprintf('Add full amount [2]: %s', $limit->amount)); continue; @@ -139,7 +139,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface $days = $this->daysInOverlap($limit, $start, $end); $amount = bcmul(bcdiv((string) $limit->amount, (string) $total), (string) $days); $return[$currencyCode]['sum'] = bcadd($return[$currencyCode]['sum'], $amount); - $return[$currencyCode]['native_sum'] = bcmul($rate, $return[$currencyCode]['sum']); + $return[$currencyCode]['pc_sum'] = bcmul($rate, $return[$currencyCode]['sum']); app('log')->debug( sprintf( 'Amount per day: %s (%s over %d days). Total amount for %d days: %s', @@ -391,7 +391,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface $autoBudget = $this->getAutoBudget($budget); // grab default currency: - $currency = app('amount')->getNativeCurrencyByUserGroup($this->user->userGroup); + $currency = app('amount')->getPrimaryCurrencyByUserGroup($this->user->userGroup); if (!$autoBudget instanceof AutoBudget) { // at this point it's a blind assumption auto_budget_type is 1 or 2. @@ -776,7 +776,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface $currency = $repos->findByCode((string) $data['currency_code']); } if (null === $currency) { - $currency = app('amount')->getNativeCurrencyByUserGroup($this->user->userGroup); + $currency = app('amount')->getPrimaryCurrencyByUserGroup($this->user->userGroup); } $autoBudget = new AutoBudget(); diff --git a/app/Repositories/Budget/OperationsRepository.php b/app/Repositories/Budget/OperationsRepository.php index cc4f5b654b..e7a787c361 100644 --- a/app/Repositories/Budget/OperationsRepository.php +++ b/app/Repositories/Budget/OperationsRepository.php @@ -141,32 +141,32 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $journals = $collector->getExtractedJournals(); $array = []; - // if needs conversion to native. - $convertToNative = Amount::convertToNative($this->user); - $nativeCurrency = Amount::getNativeCurrencyByUserGroup($this->userGroup); - $currencyId = (int) $nativeCurrency->id; - $currencyCode = $nativeCurrency->code; - $currencyName = $nativeCurrency->name; - $currencySymbol = $nativeCurrency->symbol; - $currencyDecimalPlaces = $nativeCurrency->decimal_places; + // if needs conversion to primary. + $convertToPrimary = Amount::convertToPrimary($this->user); + $primaryCurrency = Amount::getPrimaryCurrencyByUserGroup($this->userGroup); + $currencyId = (int) $primaryCurrency->id; + $currencyCode = $primaryCurrency->code; + $currencyName = $primaryCurrency->name; + $currencySymbol = $primaryCurrency->symbol; + $currencyDecimalPlaces = $primaryCurrency->decimal_places; $converter = new ExchangeRateConverter(); $currencies = [ - $currencyId => $nativeCurrency, + $currencyId => $primaryCurrency, ]; foreach ($journals as $journal) { $amount = app('steam')->negative($journal['amount']); $journalCurrencyId = (int)$journal['currency_id']; - if (false === $convertToNative) { + if (false === $convertToPrimary) { $currencyId = $journalCurrencyId; $currencyName = $journal['currency_name']; $currencySymbol = $journal['currency_symbol']; $currencyCode = $journal['currency_code']; $currencyDecimalPlaces = $journal['currency_decimal_places']; } - if (true === $convertToNative && $journalCurrencyId !== $currencyId) { + if (true === $convertToPrimary && $journalCurrencyId !== $currencyId) { $currencies[$journalCurrencyId] ??= TransactionCurrency::find($journalCurrencyId); - $amount = $converter->convert($currencies[$journalCurrencyId], $nativeCurrency, $journal['date'], $amount); + $amount = $converter->convert($currencies[$journalCurrencyId], $primaryCurrency, $journal['date'], $amount); } $budgetId = (int)$journal['budget_id']; @@ -230,9 +230,9 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn ?Collection $accounts = null, ?Collection $budgets = null, ?TransactionCurrency $currency = null, - bool $convertToNative = false + bool $convertToPrimary = false ): array { - Log::debug(sprintf('Start of %s(date, date, array, array, "%s", %s).', __METHOD__, $currency?->code, var_export($convertToNative, true))); + Log::debug(sprintf('Start of %s(date, date, array, array, "%s", %s).', __METHOD__, $currency?->code, var_export($convertToPrimary, true))); // this collector excludes all transfers TO liabilities (which are also withdrawals) // because those expenses only become expenses once they move from the liability to the friend. // 2024-12-24 disable the exclusion for now. @@ -277,8 +277,8 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn Log::debug('STOP looking for transactions in the foreign currency.'); } $summarizer = new TransactionSummarizer($this->user); - // 2025-04-21 overrule "convertToNative" because in this particular view, we never want to do this. - $summarizer->setConvertToNative($convertToNative); + // 2025-04-21 overrule "convertToPrimary" because in this particular view, we never want to do this. + $summarizer->setConvertToPrimary($convertToPrimary); return $summarizer->groupByCurrencyId($journals, 'negative', false); } diff --git a/app/Repositories/Budget/OperationsRepositoryInterface.php b/app/Repositories/Budget/OperationsRepositoryInterface.php index e4348e2821..2329e4142a 100644 --- a/app/Repositories/Budget/OperationsRepositoryInterface.php +++ b/app/Repositories/Budget/OperationsRepositoryInterface.php @@ -71,6 +71,6 @@ interface OperationsRepositoryInterface ?Collection $accounts = null, ?Collection $budgets = null, ?TransactionCurrency $currency = null, - bool $convertToNative = false + bool $convertToPrimary = false ): array; } diff --git a/app/Repositories/Category/OperationsRepository.php b/app/Repositories/Category/OperationsRepository.php index 051769c563..ca07010926 100644 --- a/app/Repositories/Category/OperationsRepository.php +++ b/app/Repositories/Category/OperationsRepository.php @@ -358,8 +358,8 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn } $collector->setCategories($categories); $journals = $collector->getExtractedJournals(); - $convertToNative = Amount::convertToNative($this->user); - $default = Amount::getNativeCurrency(); + $convertToPrimary = Amount::convertToPrimary($this->user); + $primary = Amount::getPrimaryCurrency(); $array = []; foreach ($journals as $journal) { @@ -370,16 +370,16 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn $currencySymbol = $journal['currency_symbol']; $currencyCode = $journal['currency_code']; $currencyDecimalPlaces = $journal['currency_decimal_places']; - if ($convertToNative) { + if ($convertToPrimary) { $amount = Amount::getAmountFromJournal($journal); - if ($default->id !== (int) $journal['currency_id'] && $default->id !== (int) $journal['foreign_currency_id']) { - $currencyId = $default->id; - $currencyName = $default->name; - $currencySymbol = $default->symbol; - $currencyCode = $default->code; - $currencyDecimalPlaces = $default->decimal_places; + if ($primary->id !== (int) $journal['currency_id'] && $primary->id !== (int) $journal['foreign_currency_id']) { + $currencyId = $primary->id; + $currencyName = $primary->name; + $currencySymbol = $primary->symbol; + $currencyCode = $primary->code; + $currencyDecimalPlaces = $primary->decimal_places; } - if ($default->id !== (int) $journal['currency_id'] && $default->id === (int) $journal['foreign_currency_id']) { + if ($primary->id !== (int) $journal['currency_id'] && $primary->id === (int) $journal['foreign_currency_id']) { $currencyId = $journal['foreign_currency_id']; $currencyName = $journal['foreign_currency_name']; $currencySymbol = $journal['foreign_currency_symbol']; @@ -388,7 +388,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn } Log::debug(sprintf('[a] Add amount %s %s', $currencyCode, $amount)); } - if (!$convertToNative) { + if (!$convertToPrimary) { // ignore the amount in foreign currency. Log::debug(sprintf('[b] Add amount %s %s', $currencyCode, $journal['amount'])); $amount = $journal['amount']; diff --git a/app/Repositories/Currency/CurrencyRepository.php b/app/Repositories/Currency/CurrencyRepository.php index 2716d2e21e..ec797744f0 100644 --- a/app/Repositories/Currency/CurrencyRepository.php +++ b/app/Repositories/Currency/CurrencyRepository.php @@ -183,9 +183,9 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf return $all->map(static function (TransactionCurrency $current) use ($local) { $hasId = $local->contains(static fn (TransactionCurrency $entry) => $entry->id === $current->id); - $isNative = $local->contains(static fn (TransactionCurrency $entry) => 1 === (int) $entry->pivot->group_default && $entry->id === $current->id); + $isPrimary = $local->contains(static fn (TransactionCurrency $entry) => 1 === (int) $entry->pivot->group_default && $entry->id === $current->id); $current->userGroupEnabled = $hasId; - $current->userGroupNative = $isNative; + $current->userGroupNative = $isPrimary; return $current; }); @@ -243,7 +243,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf Log::debug('Grabbing default currency for this user...'); /** @var null|TransactionCurrency $result */ - $result = app('amount')->getNativeCurrencyByUserGroup($this->user->userGroup); + $result = app('amount')->getPrimaryCurrencyByUserGroup($this->user->userGroup); } Log::debug(sprintf('Final result: %s', $result->code)); @@ -428,7 +428,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf public function makeDefault(TransactionCurrency $currency): void { - $current = app('amount')->getNativeCurrencyByUserGroup($this->userGroup); + $current = app('amount')->getPrimaryCurrencyByUserGroup($this->userGroup); Log::debug(sprintf('Enabled + made default currency %s for user #%d', $currency->code, $this->userGroup->id)); $this->userGroup->currencies()->detach($currency->id); foreach ($this->userGroup->currencies()->get() as $item) { @@ -437,7 +437,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf $this->userGroup->currencies()->syncWithoutDetaching([$currency->id => ['group_default' => true]]); if ($current->id !== $currency->id) { Log::debug('Trigger on a different default currency.'); - // clear all native amounts through an event. + // clear all primary currency amounts through an event. event(new UserGroupChangedDefaultCurrency($this->userGroup)); } } diff --git a/app/Repositories/PiggyBank/ModifiesPiggyBanks.php b/app/Repositories/PiggyBank/ModifiesPiggyBanks.php index 3da904540d..658ca6e1c8 100644 --- a/app/Repositories/PiggyBank/ModifiesPiggyBanks.php +++ b/app/Repositories/PiggyBank/ModifiesPiggyBanks.php @@ -71,7 +71,7 @@ trait ModifiesPiggyBanks $pivot->native_current_amount = null; // also update native_current_amount. - $userCurrency = app('amount')->getNativeCurrencyByUserGroup($this->user->userGroup); + $userCurrency = app('amount')->getPrimaryCurrencyByUserGroup($this->user->userGroup); if ($userCurrency->id !== $piggyBank->transaction_currency_id) { $converter = new ExchangeRateConverter(); $converter->setIgnoreSettings(true); @@ -94,7 +94,7 @@ trait ModifiesPiggyBanks $pivot->native_current_amount = null; // also update native_current_amount. - $userCurrency = app('amount')->getNativeCurrencyByUserGroup($this->user->userGroup); + $userCurrency = app('amount')->getPrimaryCurrencyByUserGroup($this->user->userGroup); if ($userCurrency->id !== $piggyBank->transaction_currency_id) { $converter = new ExchangeRateConverter(); $converter->setIgnoreSettings(true); diff --git a/app/Repositories/PiggyBank/PiggyBankRepository.php b/app/Repositories/PiggyBank/PiggyBankRepository.php index f84266febd..9d93f01edc 100644 --- a/app/Repositories/PiggyBank/PiggyBankRepository.php +++ b/app/Repositories/PiggyBank/PiggyBankRepository.php @@ -131,7 +131,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte /** * Get current amount saved in piggy bank. */ - public function getCurrentNativeAmount(PiggyBank $piggyBank, ?Account $account = null): string + public function getCurrentPrimaryAmount(PiggyBank $piggyBank, ?Account $account = null): string { $sum = '0'; foreach ($piggyBank->accounts as $current) { @@ -171,7 +171,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte $accountRepos = app(AccountRepositoryInterface::class); $accountRepos->setUser($this->user); - $defaultCurrency = app('amount')->getNativeCurrencyByUserGroup($this->user->userGroup); + $primaryCurrency = app('amount')->getPrimaryCurrencyByUserGroup($this->user->userGroup); app('log')->debug(sprintf('Piggy bank #%d currency is %s', $piggyBank->id, $piggyBank->transactionCurrency->code)); @@ -186,14 +186,14 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte // matches source, which means amount will be removed from piggy: if ($account->id === $source->account_id) { $operator = 'negative'; - $currency = $accountRepos->getAccountCurrency($source->account) ?? $defaultCurrency; + $currency = $accountRepos->getAccountCurrency($source->account) ?? $primaryCurrency; app('log')->debug(sprintf('Currency will draw money out of piggy bank. Source currency is %s', $currency->code)); ++$hits; } // matches destination, which means amount will be added to piggy. if ($account->id === $destination->account_id) { $operator = 'positive'; - $currency = $accountRepos->getAccountCurrency($destination->account) ?? $defaultCurrency; + $currency = $accountRepos->getAccountCurrency($destination->account) ?? $primaryCurrency; app('log')->debug(sprintf('Currency will add money to piggy bank. Destination currency is %s', $currency->code)); ++$hits; } diff --git a/app/Repositories/PiggyBank/PiggyBankRepositoryInterface.php b/app/Repositories/PiggyBank/PiggyBankRepositoryInterface.php index 2ac344069c..2a952ae45c 100644 --- a/app/Repositories/PiggyBank/PiggyBankRepositoryInterface.php +++ b/app/Repositories/PiggyBank/PiggyBankRepositoryInterface.php @@ -80,7 +80,7 @@ interface PiggyBankRepositoryInterface */ public function getCurrentAmount(PiggyBank $piggyBank, ?Account $account = null): string; - public function getCurrentNativeAmount(PiggyBank $piggyBank, ?Account $account = null): string; + public function getCurrentPrimaryAmount(PiggyBank $piggyBank, ?Account $account = null): string; /** * Get all events. diff --git a/app/Repositories/Tag/TagRepository.php b/app/Repositories/Tag/TagRepository.php index 4210f5cdd4..11edb3a29d 100644 --- a/app/Repositories/Tag/TagRepository.php +++ b/app/Repositories/Tag/TagRepository.php @@ -140,7 +140,7 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface } if (null !== $year) { - $year = min(2038,max(1970, $year)); + $year = min(2038, max(1970, $year)); app('log')->debug(sprintf('Get tags with year %s.', $year)); $tagQuery->where('tags.date', '>=', sprintf('%d-01-01 00:00:00', $year))->where('tags.date', '<=', sprintf('%d-12-31 23:59:59', $year)); } diff --git a/app/Repositories/TransactionGroup/TransactionGroupRepository.php b/app/Repositories/TransactionGroup/TransactionGroupRepository.php index 97e4c6ef09..6fce8e43db 100644 --- a/app/Repositories/TransactionGroup/TransactionGroupRepository.php +++ b/app/Repositories/TransactionGroup/TransactionGroupRepository.php @@ -340,7 +340,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface, { $return = []; $journals = $group->transactionJournals->pluck('id')->toArray(); - $currency = app('amount')->getNativeCurrencyByUserGroup($this->user->userGroup); + $currency = app('amount')->getPrimaryCurrencyByUserGroup($this->user->userGroup); $data = PiggyBankEvent::whereIn('transaction_journal_id', $journals) ->with('piggyBank', 'piggyBank.account') ->get(['piggy_bank_events.*']) diff --git a/app/Repositories/UserGroup/UserGroupRepository.php b/app/Repositories/UserGroup/UserGroupRepository.php index f30033dea3..5301b87f9f 100644 --- a/app/Repositories/UserGroup/UserGroupRepository.php +++ b/app/Repositories/UserGroup/UserGroupRepository.php @@ -199,14 +199,14 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte /** @var CurrencyRepositoryInterface $repository */ $repository = app(CurrencyRepositoryInterface::class); - if (array_key_exists('native_currency_code', $data)) { + if (array_key_exists('primary_currency_code', $data)) { $repository->setUser($this->user); - $currency = $repository->findByCode($data['native_currency_code']); + $currency = $repository->findByCode($data['primary_currency_code']); } - if (array_key_exists('native_currency_id', $data) && null === $currency) { + if (array_key_exists('primary_currency_id', $data) && null === $currency) { $repository->setUser($this->user); - $currency = $repository->find((int) $data['native_currency_id']); + $currency = $repository->find((int) $data['primary_currency_id']); } if (null !== $currency) { $repository->makeDefault($currency); diff --git a/app/Repositories/UserGroups/Bill/BillRepository.php b/app/Repositories/UserGroups/Bill/BillRepository.php index df61518b1c..f992e095f5 100644 --- a/app/Repositories/UserGroups/Bill/BillRepository.php +++ b/app/Repositories/UserGroups/Bill/BillRepository.php @@ -71,7 +71,7 @@ class BillRepository implements BillRepositoryInterface { Log::debug(sprintf('Created new ExchangeRateConverter in %s', __METHOD__)); $bills = $this->getActiveBills(); - $default = app('amount')->getNativeCurrency(); + $primary = app('amount')->getPrimaryCurrency(); $return = []; $converter = new ExchangeRateConverter(); @@ -88,13 +88,13 @@ class BillRepository implements BillRepositoryInterface 'currency_symbol' => $currency->symbol, 'currency_code' => $currency->code, 'currency_decimal_places' => $currency->decimal_places, - 'native_currency_id' => (string) $default->id, - 'native_currency_name' => $default->name, - 'native_currency_symbol' => $default->symbol, - 'native_currency_code' => $default->code, - 'native_currency_decimal_places' => $default->decimal_places, + 'primary_currency_id' => (string) $primary->id, + 'primary_currency_name' => $primary->name, + 'primary_currency_symbol' => $primary->symbol, + 'primary_currency_code' => $primary->code, + 'primary_currency_decimal_places' => $primary->decimal_places, 'sum' => '0', - 'native_sum' => '0', + 'pc_sum' => '0', ]; /** @var TransactionJournal $transactionJournal */ @@ -107,18 +107,18 @@ class BillRepository implements BillRepositoryInterface // use foreign amount instead! $amount = (string) $sourceTransaction->foreign_amount; } - // convert to native currency - $nativeAmount = $amount; - if ($currencyId !== $default->id) { + // convert to primary currency + $pcAmount = $amount; + if ($currencyId !== $primary->id) { // get rate and convert. - $nativeAmount = $converter->convert($currency, $default, $transactionJournal->date, $amount); + $pcAmount = $converter->convert($currency, $primary, $transactionJournal->date, $amount); } - if ((int) $sourceTransaction->foreign_currency_id === $default->id) { + if ((int) $sourceTransaction->foreign_currency_id === $primary->id) { // ignore conversion, use foreign amount - $nativeAmount = (string) $sourceTransaction->foreign_amount; + $pcAmount = (string) $sourceTransaction->foreign_amount; } $return[$currencyId]['sum'] = bcadd($return[$currencyId]['sum'], (string) $amount); - $return[$currencyId]['native_sum'] = bcadd($return[$currencyId]['native_sum'], (string) $nativeAmount); + $return[$currencyId]['pc_sum'] = bcadd($return[$currencyId]['pc_sum'], (string) $pcAmount); } } } @@ -141,7 +141,7 @@ class BillRepository implements BillRepositoryInterface Log::debug(sprintf('Created new ExchangeRateConverter in %s', __METHOD__)); $bills = $this->getActiveBills(); $return = []; - $default = app('amount')->getNativeCurrency(); + $primary = app('amount')->getPrimaryCurrency(); $converter = new ExchangeRateConverter(); /** @var Bill $bill */ @@ -154,23 +154,23 @@ class BillRepository implements BillRepositoryInterface $currency = $bill->transactionCurrency; $currencyId = $bill->transaction_currency_id; $average = bcdiv(bcadd((string) $bill->amount_max, (string) $bill->amount_min), '2'); - $nativeAverage = $converter->convert($currency, $default, $start, $average); + $pcAverage = $converter->convert($currency, $primary, $start, $average); $return[$currencyId] ??= [ 'currency_id' => (string) $currency->id, 'currency_name' => $currency->name, 'currency_symbol' => $currency->symbol, 'currency_code' => $currency->code, 'currency_decimal_places' => $currency->decimal_places, - 'native_currency_id' => (string) $default->id, - 'native_currency_name' => $default->name, - 'native_currency_symbol' => $default->symbol, - 'native_currency_code' => $default->code, - 'native_currency_decimal_places' => $default->decimal_places, + 'primary_currency_id' => (string) $primary->id, + 'primary_currency_name' => $primary->name, + 'primary_currency_symbol' => $primary->symbol, + 'primary_currency_code' => $primary->code, + 'primary_currency_decimal_places' => $primary->decimal_places, 'sum' => '0', - 'native_sum' => '0', + 'pc_sum' => '0', ]; $return[$currencyId]['sum'] = bcadd($return[$currencyId]['sum'], bcmul($average, (string) $total)); - $return[$currencyId]['native_sum'] = bcadd($return[$currencyId]['native_sum'], bcmul($nativeAverage, (string) $total)); + $return[$currencyId]['pc_sum'] = bcadd($return[$currencyId]['pc_sum'], bcmul($pcAverage, (string) $total)); } } $converter->summarize(); diff --git a/app/Repositories/UserGroups/Budget/AvailableBudgetRepository.php b/app/Repositories/UserGroups/Budget/AvailableBudgetRepository.php index 277832c924..ef9cf5b6a9 100644 --- a/app/Repositories/UserGroups/Budget/AvailableBudgetRepository.php +++ b/app/Repositories/UserGroups/Budget/AvailableBudgetRepository.php @@ -44,7 +44,7 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface Log::debug(sprintf('Created new ExchangeRateConverter in %s', __METHOD__)); $return = []; $converter = new ExchangeRateConverter(); - $default = app('amount')->getNativeCurrency(); + $primary = app('amount')->getPrimaryCurrency(); $availableBudgets = $this->userGroup->availableBudgets() ->where('start_date', $start->format('Y-m-d')) ->where('end_date', $end->format('Y-m-d'))->get() @@ -59,17 +59,17 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface 'currency_symbol' => $availableBudget->transactionCurrency->symbol, 'currency_name' => $availableBudget->transactionCurrency->name, 'currency_decimal_places' => $availableBudget->transactionCurrency->decimal_places, - 'native_currency_id' => $default->id, - 'native_currency_code' => $default->code, - 'native_currency_symbol' => $default->symbol, - 'native_currency_name' => $default->name, - 'native_currency_decimal_places' => $default->decimal_places, + 'primary_currency_id' => $primary->id, + 'primary_currency_code' => $primary->code, + 'primary_currency_symbol' => $primary->symbol, + 'primary_currency_name' => $primary->name, + 'primary_currency_decimal_places' => $primary->decimal_places, 'amount' => '0', - 'native_amount' => '0', + 'pc_amount' => '0', ]; - $nativeAmount = $converter->convert($availableBudget->transactionCurrency, $default, $availableBudget->start_date, $availableBudget->amount); + $pcAmount = $converter->convert($availableBudget->transactionCurrency, $primary, $availableBudget->start_date, $availableBudget->amount); $return[$currencyId]['amount'] = bcadd($return[$currencyId]['amount'], (string) $availableBudget->amount); - $return[$currencyId]['native_amount'] = bcadd($return[$currencyId]['native_amount'], $nativeAmount); + $return[$currencyId]['pc_amount'] = bcadd($return[$currencyId]['pc_amount'], $pcAmount); } $converter->summarize(); diff --git a/app/Repositories/UserGroups/Currency/CurrencyRepository.php b/app/Repositories/UserGroups/Currency/CurrencyRepository.php index eddd408446..3e02cb4d0c 100644 --- a/app/Repositories/UserGroups/Currency/CurrencyRepository.php +++ b/app/Repositories/UserGroups/Currency/CurrencyRepository.php @@ -182,9 +182,9 @@ class CurrencyRepository implements CurrencyRepositoryInterface return $all->map(static function (TransactionCurrency $current) use ($local) { $hasId = $local->contains(static fn (TransactionCurrency $entry) => $entry->id === $current->id); - $isNative = $local->contains(static fn (TransactionCurrency $entry) => 1 === (int) $entry->pivot->group_default && $entry->id === $current->id); + $isPrimary = $local->contains(static fn (TransactionCurrency $entry) => 1 === (int) $entry->pivot->group_default && $entry->id === $current->id); $current->userGroupEnabled = $hasId; - $current->userGroupNative = $isNative; + $current->userGroupNative = $isPrimary; return $current; }); @@ -245,7 +245,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface Log::debug('Grabbing default currency for this user...'); /** @var null|TransactionCurrency $result */ - $result = app('amount')->getNativeCurrencyByUserGroup($this->user->userGroup); + $result = app('amount')->getPrimaryCurrencyByUserGroup($this->user->userGroup); } Log::debug(sprintf('Final result: %s', $result->code)); @@ -376,7 +376,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface public function makeDefault(TransactionCurrency $currency): void { - $current = app('amount')->getNativeCurrencyByUserGroup($this->userGroup); + $current = app('amount')->getPrimaryCurrencyByUserGroup($this->userGroup); Log::debug(sprintf('Enabled + made default currency %s for user #%d', $currency->code, $this->userGroup->id)); $this->userGroup->currencies()->detach($currency->id); foreach ($this->userGroup->currencies()->get() as $item) { @@ -385,7 +385,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface $this->userGroup->currencies()->syncWithoutDetaching([$currency->id => ['group_default' => true]]); if ($current->id !== $currency->id) { Log::debug('Trigger on a different default currency.'); - // clear all native amounts through an event. + // clear all primary currency amounts through an event. event(new UserGroupChangedDefaultCurrency($this->userGroup)); } } diff --git a/app/Services/Internal/Support/AccountServiceTrait.php b/app/Services/Internal/Support/AccountServiceTrait.php index 95471d1032..f3225155c7 100644 --- a/app/Services/Internal/Support/AccountServiceTrait.php +++ b/app/Services/Internal/Support/AccountServiceTrait.php @@ -235,7 +235,7 @@ trait AccountServiceTrait // get or grab currency: $currency = $this->accountRepository->getAccountCurrency($account); if (null === $currency) { - $currency = app('amount')->getNativeCurrencyByUserGroup($account->user->userGroup); + $currency = app('amount')->getPrimaryCurrencyByUserGroup($account->user->userGroup); } // submit to factory: @@ -355,7 +355,7 @@ trait AccountServiceTrait if (null === $currency) { // use default currency: - $currency = app('amount')->getNativeCurrencyByUserGroup($this->user->userGroup); + $currency = app('amount')->getPrimaryCurrencyByUserGroup($this->user->userGroup); } $currency->enabled = true; $currency->save(); @@ -395,7 +395,7 @@ trait AccountServiceTrait // if exists, update: $currency = $this->accountRepository->getAccountCurrency($account); if (null === $currency) { - $currency = app('amount')->getNativeCurrencyByUserGroup($account->user->userGroup); + $currency = app('amount')->getPrimaryCurrencyByUserGroup($account->user->userGroup); } // simply grab the first journal and change it: @@ -461,7 +461,7 @@ trait AccountServiceTrait // get or grab currency: $currency = $this->accountRepository->getAccountCurrency($account); if (null === $currency) { - $currency = app('amount')->getNativeCurrencyByUserGroup($account->user->userGroup); + $currency = app('amount')->getPrimaryCurrencyByUserGroup($account->user->userGroup); } // submit to factory: $submission = [ @@ -578,7 +578,7 @@ trait AccountServiceTrait // if exists, update: $currency = $this->accountRepository->getAccountCurrency($account); if (null === $currency) { - $currency = app('amount')->getNativeCurrencyByUserGroup($account->user->userGroup); + $currency = app('amount')->getPrimaryCurrencyByUserGroup($account->user->userGroup); } // simply grab the first journal and change it: @@ -659,7 +659,7 @@ trait AccountServiceTrait // get or grab currency: $currency = $this->accountRepository->getAccountCurrency($account); if (null === $currency) { - $currency = app('amount')->getNativeCurrencyByUserGroup($account->user->userGroup); + $currency = app('amount')->getPrimaryCurrencyByUserGroup($account->user->userGroup); } // submit to factory: diff --git a/app/Services/Internal/Support/RecurringTransactionTrait.php b/app/Services/Internal/Support/RecurringTransactionTrait.php index 84771766cf..6ac399f6e5 100644 --- a/app/Services/Internal/Support/RecurringTransactionTrait.php +++ b/app/Services/Internal/Support/RecurringTransactionTrait.php @@ -109,7 +109,7 @@ trait RecurringTransactionTrait $currency = $factory->find($array['currency_id'] ?? null, $array['currency_code'] ?? null); $foreignCurrency = $factory->find($array['foreign_currency_id'] ?? null, $array['foreign_currency_code'] ?? null); if (null === $currency) { - $currency = app('amount')->getNativeCurrencyByUserGroup($recurrence->user->userGroup); + $currency = app('amount')->getPrimaryCurrencyByUserGroup($recurrence->user->userGroup); } app('log')->debug( diff --git a/app/Services/Internal/Update/BillUpdateService.php b/app/Services/Internal/Update/BillUpdateService.php index 8726cd7ebc..a4aca38ce4 100644 --- a/app/Services/Internal/Update/BillUpdateService.php +++ b/app/Services/Internal/Update/BillUpdateService.php @@ -56,7 +56,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) - ?? app('amount')->getNativeCurrencyByUserGroup($bill->user->userGroup); + ?? app('amount')->getPrimaryCurrencyByUserGroup($bill->user->userGroup); // enable the currency if it isn't. $currency->enabled = true; diff --git a/app/Support/Amount.php b/app/Support/Amount.php index adaea875a6..e09c7447d4 100644 --- a/app/Support/Amount.php +++ b/app/Support/Amount.php @@ -101,13 +101,13 @@ class Amount */ public function getAmountFromJournal(array $journal): string { - $convertToNative = $this->convertToNative(); - $currency = $this->getNativeCurrency(); - $field = $convertToNative && $currency->id !== $journal['currency_id'] ? 'native_amount' : 'amount'; + $convertToPrimary = $this->convertToPrimary(); + $currency = $this->getPrimaryCurrency(); + $field = $convertToPrimary && $currency->id !== $journal['currency_id'] ? 'native_amount' : 'amount'; $amount = $journal[$field] ?? '0'; // Log::debug(sprintf('Field is %s, amount is %s', $field, $amount)); // fallback, the transaction has a foreign amount in $currency. - if ($convertToNative && null !== $journal['foreign_amount'] && $currency->id === (int)$journal['foreign_currency_id']) { + if ($convertToPrimary && null !== $journal['foreign_amount'] && $currency->id === (int)$journal['foreign_currency_id']) { $amount = $journal['foreign_amount']; // Log::debug(sprintf('Overruled, amount is now %s', $amount)); } @@ -115,7 +115,7 @@ class Amount return (string)$amount; } - public function convertToNative(?User $user = null): bool + public function convertToPrimary(?User $user = null): bool { if (!$user instanceof User) { return true === Preferences::get('convert_to_native', false)->data && true === config('cer.enabled'); @@ -124,38 +124,38 @@ class Amount return true === Preferences::getForUser($user, 'convert_to_native', false)->data && true === config('cer.enabled'); } - public function getNativeCurrency(): TransactionCurrency + public function getPrimaryCurrency(): TransactionCurrency { if (auth()->check()) { /** @var User $user */ $user = auth()->user(); if (null !== $user->userGroup) { - return $this->getNativeCurrencyByUserGroup($user->userGroup); + return $this->getPrimaryCurrencyByUserGroup($user->userGroup); } } return $this->getSystemCurrency(); } - public function getNativeCurrencyByUserGroup(UserGroup $userGroup): TransactionCurrency + public function getPrimaryCurrencyByUserGroup(UserGroup $userGroup): TransactionCurrency { $cache = new CacheProperties(); - $cache->addProperty('getNativeCurrencyByGroup'); + $cache->addProperty('getPrimaryCurrencyByGroup'); $cache->addProperty($userGroup->id); if ($cache->has()) { return $cache->get(); } - /** @var null|TransactionCurrency $native */ - $native = $userGroup->currencies()->where('group_default', true)->first(); - if (null === $native) { - $native = $this->getSystemCurrency(); + /** @var null|TransactionCurrency $primary */ + $primary = $userGroup->currencies()->where('group_default', true)->first(); + if (null === $primary) { + $primary = $this->getSystemCurrency(); // could be the user group has no default right now. - $userGroup->currencies()->sync([$native->id => ['group_default' => true]]); + $userGroup->currencies()->sync([$primary->id => ['group_default' => true]]); } - $cache->store($native); + $cache->store($primary); - return $native; + return $primary; } public function getSystemCurrency(): TransactionCurrency @@ -169,9 +169,9 @@ class Amount */ public function getAmountFromJournalObject(TransactionJournal $journal): string { - $convertToNative = $this->convertToNative(); - $currency = $this->getNativeCurrency(); - $field = $convertToNative && $currency->id !== $journal->transaction_currency_id ? 'native_amount' : 'amount'; + $convertToPrimary = $this->convertToPrimary(); + $currency = $this->getPrimaryCurrency(); + $field = $convertToPrimary && $currency->id !== $journal->transaction_currency_id ? 'native_amount' : 'amount'; /** @var null|Transaction $sourceTransaction */ $sourceTransaction = $journal->transactions()->where('amount', '<', 0)->first(); @@ -195,24 +195,6 @@ class Amount return $user->currencies()->orderBy('code', 'ASC')->get(); } - #[Deprecated] - public function getDefaultCurrency(): TransactionCurrency - { - return $this->getNativeCurrency(); - } - - #[Deprecated(message: 'use getDefaultCurrencyByUserGroup instead')] - public function getDefaultCurrencyByUser(User $user): TransactionCurrency - { - return $this->getDefaultCurrencyByUserGroup($user->userGroup); - } - - #[Deprecated] - public function getDefaultCurrencyByUserGroup(UserGroup $userGroup): TransactionCurrency - { - return $this->getNativeCurrencyByUserGroup($userGroup); - } - /** * This method returns the correct format rules required by accounting.js, * the library used to format amounts in charts. diff --git a/app/Support/Export/ExportDataGenerator.php b/app/Support/Export/ExportDataGenerator.php index 78145d74e9..1364eec115 100644 --- a/app/Support/Export/ExportDataGenerator.php +++ b/app/Support/Export/ExportDataGenerator.php @@ -738,7 +738,7 @@ class ExportDataGenerator $metaFields = config('firefly.journal_meta_fields'); $header = array_merge($header, $metaFields); - $default = Amount::getNativeCurrency(); + $default = Amount::getPrimaryCurrency(); $collector = app(GroupCollectorInterface::class); $collector->setUser($this->user); diff --git a/app/Support/Form/CurrencyForm.php b/app/Support/Form/CurrencyForm.php index 0ac0b07f62..c947e7b192 100644 --- a/app/Support/Form/CurrencyForm.php +++ b/app/Support/Form/CurrencyForm.php @@ -61,7 +61,7 @@ class CurrencyForm $classes = $this->getHolderClasses($name); $value = $this->fillFieldValue($name, $value); $options['step'] = 'any'; - $defaultCurrency = $options['currency'] ?? app('amount')->getNativeCurrency(); + $defaultCurrency = $options['currency'] ?? app('amount')->getPrimaryCurrency(); /** @var Collection $currencies */ $currencies = app('amount')->getCurrencies(); @@ -129,7 +129,7 @@ class CurrencyForm $classes = $this->getHolderClasses($name); $value = $this->fillFieldValue($name, $value); $options['step'] = 'any'; - $defaultCurrency = $options['currency'] ?? app('amount')->getNativeCurrency(); + $defaultCurrency = $options['currency'] ?? app('amount')->getPrimaryCurrency(); /** @var Collection $currencies */ $currencies = app('amount')->getAllCurrencies(); diff --git a/app/Support/Http/Controllers/ChartGeneration.php b/app/Support/Http/Controllers/ChartGeneration.php index 1680a3ec5b..689e03de6a 100644 --- a/app/Support/Http/Controllers/ChartGeneration.php +++ b/app/Support/Http/Controllers/ChartGeneration.php @@ -48,7 +48,7 @@ trait ChartGeneration protected function accountBalanceChart(Collection $accounts, Carbon $start, Carbon $end): array // chart helper method. { // chart properties for cache: - $convertToNative = Amount::convertToNative(); + $convertToNative = Amount::convertToPrimary(); $cache = new CacheProperties(); $cache->addProperty($start); $cache->addProperty($end); @@ -67,7 +67,7 @@ trait ChartGeneration /** @var AccountRepositoryInterface $accountRepos */ $accountRepos = app(AccountRepositoryInterface::class); - $default = app('amount')->getNativeCurrency(); + $default = app('amount')->getPrimaryCurrency(); $chartData = []; Log::debug(sprintf('Start of accountBalanceChart(list, %s, %s)', $start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s'))); diff --git a/app/Support/JsonApi/Enrichments/SubscriptionEnrichment.php b/app/Support/JsonApi/Enrichments/SubscriptionEnrichment.php index eff7439eb3..994d345d2e 100644 --- a/app/Support/JsonApi/Enrichments/SubscriptionEnrichment.php +++ b/app/Support/JsonApi/Enrichments/SubscriptionEnrichment.php @@ -40,6 +40,7 @@ class SubscriptionEnrichment implements EnrichmentInterface public function enrich(Collection $collection): Collection { + Log::debug(sprintf('%s(%s item(s))', __METHOD__, $collection->count())); $this->calculator = app(BillDateCalculator::class); $this->collection = $collection; $this->collectSubscriptionIds(); @@ -89,6 +90,7 @@ class SubscriptionEnrichment implements EnrichmentInterface // Convert amounts to native currency if needed if ($this->convertToNative && $item->currency_id !== $this->nativeCurrency->id) { + Log::debug('Convert to native currency'); $converter = new ExchangeRateConverter(); $amounts = [ 'amount_min' => Steam::bcround($converter->convert($item->transactionCurrency, $this->nativeCurrency, today(), $item->amount_min), $this->nativeCurrency->decimal_places), @@ -185,6 +187,7 @@ class SubscriptionEnrichment implements EnrichmentInterface Log::debug('Now in collectPaidDates for bills'); if (null === $this->start || null === $this->end) { Log::debug('Parameters are NULL, set empty array'); + return; } @@ -192,23 +195,22 @@ class SubscriptionEnrichment implements EnrichmentInterface // 2023-07-18 this particular date is used to search for the last paid date. // 2023-07-18 the cloned $searchDate is used to grab the correct transactions. /** @var Carbon $start */ - $start = clone $this->start; - $searchStart = clone $start; + $start = clone $this->start; + $searchStart = clone $start; $start->subDay(); /** @var Carbon $end */ - $end = clone $this->end; - $searchEnd = clone $end; + $end = clone $this->end; + $searchEnd = clone $end; // move the search dates to the start of the day. $searchStart->startOfDay(); $searchEnd->endOfDay(); - Log::debug(sprintf('Parameters are start: %s, end: %s', $start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s'))); Log::debug(sprintf('Search parameters are: start: %s, end: %s', $searchStart->format('Y-m-d H:i:s'), $searchEnd->format('Y-m-d H:i:s'))); // Get from database when bills were paid. - $set = $this->user->transactionJournals() + $set = $this->user->transactionJournals() ->whereIn('bill_id', $this->subscriptionIds) ->leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id') ->leftJoin('transaction_currencies AS currency', 'currency.id', '=', 'transactions.transaction_currency_id') @@ -234,22 +236,26 @@ class SubscriptionEnrichment implements EnrichmentInterface Log::debug(sprintf('Count %d entries in set', $set->count())); // for each bill, do a loop. + $converter = new ExchangeRateConverter(); /** @var Bill $subscription */ foreach ($this->collection as $subscription) { // Grab from array the most recent payment. If none exist, fall back to the start date and pretend *that* was the last paid date. Log::debug(sprintf('Grab last paid date from function, return %s if it comes up with nothing.', $start->format('Y-m-d'))); - $lastPaidDate = $this->lastPaidDate($subscription, $set, $start); + $lastPaidDate = $this->lastPaidDate($subscription, $set, $start); Log::debug(sprintf('Result of lastPaidDate is %s', $lastPaidDate->format('Y-m-d'))); // At this point the "next match" is exactly after the last time the bill was paid. - $result = []; - foreach ($set as $entry) { + $result = []; + $filtered = $set->filter(function (TransactionJournal $journal) use ($subscription) { + return (int) $journal->bill_id === (int) $subscription->id; + }); + foreach ($filtered as $entry) { $array = [ 'transaction_group_id' => (string)$entry->transaction_group_id, 'transaction_journal_id' => (string)$entry->id, 'date' => $entry->date->toAtomString(), 'date_object' => $entry->date, - 'bill_id' => $entry->bill_id, + 'bill_id' => $entry->bill_id, 'currency_id' => $entry->transaction_currency_id, 'currency_code' => $entry->transaction_currency_code, 'currency_decimal_places' => $entry->transaction_currency_decimal_places, @@ -261,6 +267,13 @@ class SubscriptionEnrichment implements EnrichmentInterface $array['foreign_currency_decimal_places'] = $entry->foreign_currency_decimal_places; $array['foreign_amount'] = Steam::bcround($entry->foreign_amount, $entry->foreign_currency_decimal_places); } + if($this->convertToNative) { + $array['amount'] = $converter->convert($entry->transactionCurrency, $this->nativeCurrency, $entry->date, $entry->amount); + $array['currency_id'] = $this->nativeCurrency->id; + $array['currency_code'] = $this->nativeCurrency->code; + $array['currency_decimal_places'] = $this->nativeCurrency->decimal_places; + + } $result[] = $array; } @@ -287,6 +300,7 @@ class SubscriptionEnrichment implements EnrichmentInterface $filtered = $dates->filter(function (TransactionJournal $journal) use ($subscription) { return (int) $journal->bill_id === (int) $subscription->id; }); + Log::debug(sprintf('Filtered down from %d to %d entries for bill #%d.', $dates->count(), $filtered->count(), $subscription->id)); if (0 === $filtered->count()) { return $default; } @@ -329,6 +343,10 @@ class SubscriptionEnrichment implements EnrichmentInterface private function collectPayDates(): void { + if(null === $this->start || null === $this->end) { + Log::debug('Parameters are NULL, set empty array'); + return; + } /** @var Bill $subscription */ foreach ($this->collection as $subscription) { $id = (int)$subscription->id; diff --git a/app/Support/JsonApi/Enrichments/TransactionGroupEnrichment.php b/app/Support/JsonApi/Enrichments/TransactionGroupEnrichment.php index 41567cf529..3d4f373c68 100644 --- a/app/Support/JsonApi/Enrichments/TransactionGroupEnrichment.php +++ b/app/Support/JsonApi/Enrichments/TransactionGroupEnrichment.php @@ -54,7 +54,7 @@ class TransactionGroupEnrichment implements EnrichmentInterface private array $notes; // @phpstan-ignore-line private array $tags; private User $user; - private readonly TransactionCurrency $nativeCurrency; + private readonly TransactionCurrency $primaryCurrency; private UserGroup $userGroup; public function __construct() @@ -66,7 +66,7 @@ class TransactionGroupEnrichment implements EnrichmentInterface $this->locations = []; $this->attachmentCount = []; $this->dateFields = ['interest_date', 'book_date', 'process_date', 'due_date', 'payment_date', 'invoice_date']; - $this->nativeCurrency = Amount::getNativeCurrency(); + $this->primaryCurrency = Amount::getPrimaryCurrency(); } #[Override] @@ -198,9 +198,9 @@ class TransactionGroupEnrichment implements EnrichmentInterface $metaData = $this->metaData; $locations = $this->locations; $attachmentCount = $this->attachmentCount; - $nativeCurrency = $this->nativeCurrency; + $primaryCurrency = $this->primaryCurrency; - $this->collection = $this->collection->map(function (array $item) use ($nativeCurrency, $notes, $tags, $metaData, $locations, $attachmentCount) { + $this->collection = $this->collection->map(function (array $item) use ($primaryCurrency, $notes, $tags, $metaData, $locations, $attachmentCount) { foreach ($item['transactions'] as $index => $transaction) { $journalId = (int) $transaction['transaction_journal_id']; @@ -220,13 +220,13 @@ class TransactionGroupEnrichment implements EnrichmentInterface 'zoom_level' => null, ]; - // native currency - $item['transactions'][$index]['native_currency'] = [ - 'id' => (string) $nativeCurrency->id, - 'code' => $nativeCurrency->code, - 'name' => $nativeCurrency->name, - 'symbol' => $nativeCurrency->symbol, - 'decimal_places' => $nativeCurrency->decimal_places, + // primary currency + $item['transactions'][$index]['primary_currency'] = [ + 'id' => (string) $primaryCurrency->id, + 'code' => $primaryCurrency->code, + 'name' => $primaryCurrency->name, + 'symbol' => $primaryCurrency->symbol, + 'decimal_places' => $primaryCurrency->decimal_places, ]; // append meta data diff --git a/app/Support/Report/Budget/BudgetReportGenerator.php b/app/Support/Report/Budget/BudgetReportGenerator.php index d8516bbc7b..3014e97dc4 100644 --- a/app/Support/Report/Budget/BudgetReportGenerator.php +++ b/app/Support/Report/Budget/BudgetReportGenerator.php @@ -347,6 +347,6 @@ class BudgetReportGenerator $this->blRepository->setUser($user); $this->opsRepository->setUser($user); $this->nbRepository->setUser($user); - $this->currency = app('amount')->getNativeCurrencyByUserGroup($user->userGroup); + $this->currency = app('amount')->getPrimaryCurrencyByUserGroup($user->userGroup); } } diff --git a/app/Support/Report/Summarizer/TransactionSummarizer.php b/app/Support/Report/Summarizer/TransactionSummarizer.php index 59a0f1e223..1306a491ba 100644 --- a/app/Support/Report/Summarizer/TransactionSummarizer.php +++ b/app/Support/Report/Summarizer/TransactionSummarizer.php @@ -45,8 +45,8 @@ class TransactionSummarizer public function setUser(User $user): void { $this->user = $user; - $this->default = Amount::getNativeCurrencyByUserGroup($user->userGroup); - $this->convertToNative = Amount::convertToNative($user); + $this->default = Amount::getPrimaryCurrencyByUserGroup($user->userGroup); + $this->convertToNative = Amount::convertToPrimary($user); } public function groupByCurrencyId(array $journals, string $method = 'negative', bool $includeForeign = true): array @@ -159,8 +159,8 @@ class TransactionSummarizer $array = []; $idKey = sprintf('%s_account_id', $direction); $nameKey = sprintf('%s_account_name', $direction); - $convertToNative = Amount::convertToNative($this->user); - $default = Amount::getNativeCurrencyByUserGroup($this->user->userGroup); + $convertToNative = Amount::convertToPrimary($this->user); + $default = Amount::getPrimaryCurrencyByUserGroup($this->user->userGroup); Log::debug(sprintf('groupByDirection(array, %s, %s).', $direction, $method)); diff --git a/app/Support/Steam.php b/app/Support/Steam.php index a8cde113cf..d4b301e9e1 100644 --- a/app/Support/Steam.php +++ b/app/Support/Steam.php @@ -93,7 +93,7 @@ class Steam return []; } - $defaultCurrency = Amount::getNativeCurrency(); + $defaultCurrency = Amount::getPrimaryCurrency(); if ($convertToNative) { if ($defaultCurrency->id === $currency?->id) { Log::debug(sprintf('Unset [%s] for account #%d (no longer unset "native_balance")', $defaultCurrency->code, $account->id)); @@ -224,7 +224,7 @@ class Steam $request->subDay()->endOfDay(); Log::debug(sprintf('finalAccountBalanceInRange: Call finalAccountBalance with date/time "%s"', $request->toIso8601String())); $startBalance = $this->finalAccountBalance($account, $request); - $nativeCurrency = Amount::getNativeCurrencyByUserGroup($account->user->userGroup); + $nativeCurrency = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup); $accountCurrency = $this->getAccountCurrency($account); $hasCurrency = $accountCurrency instanceof TransactionCurrency; $currency = $accountCurrency ?? $nativeCurrency; @@ -344,10 +344,10 @@ class Steam } // Log::debug(sprintf('finalAccountBalance(#%d, %s)', $account->id, $date->format('Y-m-d H:i:s'))); if (null === $convertToNative) { - $convertToNative = Amount::convertToNative($account->user); + $convertToNative = Amount::convertToPrimary($account->user); } if (!$native instanceof TransactionCurrency) { - $native = Amount::getNativeCurrencyByUserGroup($account->user->userGroup); + $native = Amount::getPrimaryCurrencyByUserGroup($account->user->userGroup); } // account balance thing. $currencyPresent = isset($account->meta) && array_key_exists('currency', $account->meta) && null !== $account->meta['currency']; diff --git a/app/Support/Twig/AmountFormat.php b/app/Support/Twig/AmountFormat.php index 70581d32a9..97bf5ff0c3 100644 --- a/app/Support/Twig/AmountFormat.php +++ b/app/Support/Twig/AmountFormat.php @@ -52,7 +52,7 @@ class AmountFormat extends AbstractExtension return new TwigFilter( 'formatAmount', static function (string $string): string { - $currency = app('amount')->getNativeCurrency(); + $currency = app('amount')->getPrimaryCurrency(); return app('amount')->formatAnything($currency, $string, true); }, @@ -65,7 +65,7 @@ class AmountFormat extends AbstractExtension return new TwigFilter( 'formatAmountPlain', static function (string $string): string { - $currency = app('amount')->getNativeCurrency(); + $currency = app('amount')->getPrimaryCurrency(); return app('amount')->formatAnything($currency, $string, false); }, @@ -98,7 +98,7 @@ class AmountFormat extends AbstractExtension /** @var AccountRepositoryInterface $accountRepos */ $accountRepos = app(AccountRepositoryInterface::class); - $currency = $accountRepos->getAccountCurrency($account) ?? app('amount')->getNativeCurrency(); + $currency = $accountRepos->getAccountCurrency($account) ?? app('amount')->getPrimaryCurrency(); return app('amount')->formatAnything($currency, $amount, $coloured); }, @@ -157,7 +157,7 @@ class AmountFormat extends AbstractExtension $currency = TransactionCurrency::whereCode($code)->first(); if (null === $currency) { Log::error(sprintf('Could not find currency with code "%s". Fallback to native currency.', $code)); - $currency = Amount::getNativeCurrency(); + $currency = Amount::getPrimaryCurrency(); Log::error(sprintf('Fallback currency is "%s".', $currency->code)); } diff --git a/app/Support/Twig/General.php b/app/Support/Twig/General.php index 61cbd5eba4..9f0a145b35 100644 --- a/app/Support/Twig/General.php +++ b/app/Support/Twig/General.php @@ -75,8 +75,8 @@ class General extends AbstractExtension Log::debug(sprintf('twig balance: Call finalAccountBalance with date/time "%s"', $date->toIso8601String())); $info = Steam::finalAccountBalance($account, $date); $currency = Steam::getAccountCurrency($account); - $default = Amount::getNativeCurrency(); - $convertToNative = Amount::convertToNative(); + $default = Amount::getPrimaryCurrency(); + $convertToNative = Amount::convertToPrimary(); $useNative = $convertToNative && $default->id !== $currency->id; $currency ??= $default; $strings = []; diff --git a/app/Transformers/AccountTransformer.php b/app/Transformers/AccountTransformer.php index f995606de1..aa528a3a59 100644 --- a/app/Transformers/AccountTransformer.php +++ b/app/Transformers/AccountTransformer.php @@ -40,8 +40,8 @@ use Symfony\Component\HttpFoundation\ParameterBag; */ class AccountTransformer extends AbstractTransformer { - protected bool $convertToNative; - protected TransactionCurrency $native; + protected bool $convertToPrimary; + protected TransactionCurrency $primary; protected AccountRepositoryInterface $repository; /** @@ -51,8 +51,8 @@ class AccountTransformer extends AbstractTransformer { $this->parameters = new ParameterBag(); $this->repository = app(AccountRepositoryInterface::class); - $this->convertToNative = Amount::convertToNative(); - $this->native = Amount::getNativeCurrency(); + $this->convertToPrimary = Amount::convertToPrimary(); + $this->primary = Amount::getPrimaryCurrency(); } /** @@ -80,13 +80,13 @@ class AccountTransformer extends AbstractTransformer $date->endOfDay(); [$creditCardType, $monthlyPaymentDate] = $this->getCCInfo($account, $accountRole, $accountType); - [$openingBalance, $nativeOpeningBalance, $openingBalanceDate] = $this->getOpeningBalance($account, $accountType); + [$openingBalance, $pcOpeningBalance, $openingBalanceDate] = $this->getOpeningBalance($account, $accountType); [$interest, $interestPeriod] = $this->getInterest($account, $accountType); - $native = $this->native; - if (!$this->convertToNative) { - // reset native currency to NULL, not interesting. - $native = null; + $primary = $this->primary; + if (!$this->convertToPrimary) { + // reset primary currency to NULL, not interesting. + $primary = null; } $decimalPlaces = (int)$account->meta['currency']?->decimal_places; @@ -102,15 +102,14 @@ class AccountTransformer extends AbstractTransformer if (!in_array(strtolower($accountType), ['liability', 'liabilities', 'asset'], true)) { $order = null; } - // balance, native balance, virtual balance, native virtual balance? Log::debug(sprintf('transform: Call finalAccountBalance with date/time "%s"', $date->toIso8601String())); - $finalBalance = Steam::finalAccountBalance($account, $date, $this->native, $this->convertToNative); - if ($this->convertToNative) { + $finalBalance = Steam::finalAccountBalance($account, $date, $this->primary, $this->convertToPrimary); + if ($this->convertToPrimary) { $finalBalance['balance'] = $finalBalance[$account->meta['currency']?->code] ?? '0'; } $currentBalance = Steam::bcround($finalBalance['balance'] ?? '0', $decimalPlaces); - $nativeCurrentBalance = $this->convertToNative ? Steam::bcround($finalBalance['native_balance'] ?? '0', $native->decimal_places) : null; + $pcCurrentBalance = $this->convertToPrimary ? Steam::bcround($finalBalance['pc_balance'] ?? '0', $primary->decimal_places) : null; // set up balances array: $balances = []; @@ -124,14 +123,14 @@ class AccountTransformer extends AbstractTransformer 'currency_decimal_places' => $account->meta['currency']?->decimal_places, 'date' => $date->toAtomString(), ]; - if (null !== $nativeCurrentBalance) { + if (null !== $pcCurrentBalance) { $balances[] = [ - 'type' => 'native_current', - 'amount' => $nativeCurrentBalance, - 'currency_id' => $native instanceof TransactionCurrency ? (string)$native->id : null, - 'currency_code' => $native?->code, - 'currency_symbol' => $native?->symbol, - 'ccurrency_decimal_places' => $native?->decimal_places, + 'type' => 'pc_current', + 'amount' => $pcCurrentBalance, + 'currency_id' => $primary instanceof TransactionCurrency ? (string)$primary->id : null, + 'currency_code' => $primary?->code, + 'currency_symbol' => $primary?->symbol, + 'ccurrency_decimal_places' => $primary?->decimal_places, 'date' => $date->toAtomString(), ]; @@ -172,12 +171,12 @@ class AccountTransformer extends AbstractTransformer 'currency_code' => $account->meta['currency']?->code, 'currency_symbol' => $account->meta['currency']?->symbol, 'currency_decimal_places' => $account->meta['currency']?->decimal_places, - 'native_currency_id' => $native instanceof TransactionCurrency ? (string)$native->id : null, - 'native_currency_code' => $native?->code, - 'native_currency_symbol' => $native?->symbol, - 'native_currency_decimal_places' => $native?->decimal_places, + 'primary_currency_id' => $primary instanceof TransactionCurrency ? (string)$primary->id : null, + 'primary_currency_code' => $primary?->code, + 'primary_currency_symbol' => $primary?->symbol, + 'primary_currency_decimal_places' => $primary?->decimal_places, 'current_balance' => $currentBalance, - 'native_current_balance' => $nativeCurrentBalance, + 'pc_current_balance' => $pcCurrentBalance, 'current_balance_date' => $date->toAtomString(), 'notes' => $account->meta['notes'] ?? null, 'monthly_payment_date' => $monthlyPaymentDate, @@ -186,9 +185,9 @@ class AccountTransformer extends AbstractTransformer 'iban' => '' === $account->iban ? null : $account->iban, 'bic' => $account->meta['BIC'] ?? null, 'virtual_balance' => Steam::bcround($account->virtual_balance, $decimalPlaces), - 'native_virtual_balance' => $this->convertToNative ? Steam::bcround($account->native_virtual_balance, $native->decimal_places) : null, + 'pc_virtual_balance' => $this->convertToPrimary ? Steam::bcround($account->native_virtual_balance, $primary->decimal_places) : null, 'opening_balance' => $openingBalanceRounded, - 'native_opening_balance' => $nativeOpeningBalance, + 'pc_opening_balance' => $pcOpeningBalance, 'opening_balance_date' => $openingBalanceDate, 'liability_type' => $liabilityType, 'liability_direction' => $liabilityDirection, @@ -261,11 +260,11 @@ class AccountTransformer extends AbstractTransformer { $openingBalance = null; $openingBalanceDate = null; - $nativeOpeningBalance = null; + $pcOpeningBalance = null; if (in_array($accountType, ['asset', 'liabilities'], true)) { // grab from meta. $openingBalance = $account->meta['opening_balance_amount'] ?? null; - $nativeOpeningBalance = null; + $pcOpeningBalance = null; $openingBalanceDate = $account->meta['opening_balance_date'] ?? null; } if (null !== $openingBalanceDate) { @@ -276,14 +275,14 @@ class AccountTransformer extends AbstractTransformer $openingBalanceDate = $object->toAtomString(); // NOW do conversion. - if ($this->convertToNative && null !== $account->meta['currency']) { + if ($this->convertToPrimary && null !== $account->meta['currency']) { $converter = new ExchangeRateConverter(); - $nativeOpeningBalance = $converter->convert($account->meta['currency'], $this->native, $object, $openingBalance); + $pcOpeningBalance = $converter->convert($account->meta['currency'], $this->primary, $object, $openingBalance); } } - return [$openingBalance, $nativeOpeningBalance, $openingBalanceDate]; + return [$openingBalance, $pcOpeningBalance, $openingBalanceDate]; } private function getInterest(Account $account, string $accountType): array diff --git a/app/Transformers/AvailableBudgetTransformer.php b/app/Transformers/AvailableBudgetTransformer.php index fb34c8c9b1..3988057214 100644 --- a/app/Transformers/AvailableBudgetTransformer.php +++ b/app/Transformers/AvailableBudgetTransformer.php @@ -36,8 +36,8 @@ use FireflyIII\Support\Facades\Amount; */ class AvailableBudgetTransformer extends AbstractTransformer { - private readonly bool $convertToNative; - private readonly TransactionCurrency $default; + private readonly bool $convertToPrimary; + private readonly TransactionCurrency $primary; private readonly NoBudgetRepositoryInterface $noBudgetRepository; private readonly OperationsRepositoryInterface $opsRepository; private readonly BudgetRepositoryInterface $repository; @@ -50,8 +50,8 @@ class AvailableBudgetTransformer extends AbstractTransformer $this->repository = app(BudgetRepositoryInterface::class); $this->opsRepository = app(OperationsRepositoryInterface::class); $this->noBudgetRepository = app(NoBudgetRepositoryInterface::class); - $this->default = Amount::getNativeCurrency(); - $this->convertToNative = Amount::convertToNative(); + $this->primary = Amount::getPrimaryCurrency(); + $this->convertToPrimary = Amount::convertToPrimary(); } /** @@ -62,37 +62,37 @@ class AvailableBudgetTransformer extends AbstractTransformer $this->repository->setUser($availableBudget->user); $currency = $availableBudget->transactionCurrency; - $default = $this->default; - if (!$this->convertToNative) { - $default = null; + $primary = $this->primary; + if (!$this->convertToPrimary) { + $primary = null; } - $data = [ - 'id' => (string) $availableBudget->id, - 'created_at' => $availableBudget->created_at->toAtomString(), - 'updated_at' => $availableBudget->updated_at->toAtomString(), - 'currency_id' => (string) $currency->id, - 'currency_code' => $currency->code, - 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => $currency->decimal_places, - 'native_currency_id' => $default instanceof TransactionCurrency ? (string) $default->id : null, - 'native_currency_code' => $default?->code, - 'native_currency_symbol' => $default?->symbol, - 'native_currency_decimal_places' => $default?->decimal_places, - 'amount' => app('steam')->bcround($availableBudget->amount, $currency->decimal_places), - 'native_amount' => $this->convertToNative ? app('steam')->bcround($availableBudget->native_amount, $currency->decimal_places) : null, - 'start' => $availableBudget->start_date->toAtomString(), - 'end' => $availableBudget->end_date->endOfDay()->toAtomString(), - 'spent_in_budgets' => [], - 'spent_no_budget' => [], - 'links' => [ + $data = [ + 'id' => (string)$availableBudget->id, + 'created_at' => $availableBudget->created_at->toAtomString(), + 'updated_at' => $availableBudget->updated_at->toAtomString(), + 'currency_id' => (string)$currency->id, + 'currency_code' => $currency->code, + 'currency_symbol' => $currency->symbol, + 'currency_decimal_places' => $currency->decimal_places, + 'primary_currency_id' => $primary instanceof TransactionCurrency ? (string)$primary->id : null, + 'primary_currency_code' => $primary?->code, + 'primary_currency_symbol' => $primary?->symbol, + 'primary_currency_decimal_places' => $primary?->decimal_places, + 'amount' => app('steam')->bcround($availableBudget->amount, $currency->decimal_places), + 'pc_amount' => $this->convertToPrimary ? app('steam')->bcround($availableBudget->native_amount, $currency->decimal_places) : null, + 'start' => $availableBudget->start_date->toAtomString(), + 'end' => $availableBudget->end_date->endOfDay()->toAtomString(), + 'spent_in_budgets' => [], + 'spent_no_budget' => [], + 'links' => [ [ 'rel' => 'self', - 'uri' => '/available_budgets/'.$availableBudget->id, + 'uri' => '/available_budgets/' . $availableBudget->id, ], ], ]; - $start = $this->parameters->get('start'); - $end = $this->parameters->get('end'); + $start = $this->parameters->get('start'); + $end = $this->parameters->get('end'); if (null !== $start && null !== $end) { $data['spent_in_budgets'] = $this->getSpentInBudgets(); $data['spent_no_budget'] = $this->spentOutsideBudgets(); diff --git a/app/Transformers/BillTransformer.php b/app/Transformers/BillTransformer.php index 5318d08533..a06d6c10b0 100644 --- a/app/Transformers/BillTransformer.php +++ b/app/Transformers/BillTransformer.php @@ -33,14 +33,14 @@ use FireflyIII\Support\Facades\Amount; */ class BillTransformer extends AbstractTransformer { - private readonly TransactionCurrency $native; + private readonly TransactionCurrency $primary; /** * BillTransformer constructor. */ public function __construct() { - $this->native = Amount::getNativeCurrency(); + $this->primary = Amount::getPrimaryCurrency(); } /** @@ -60,10 +60,10 @@ class BillTransformer extends AbstractTransformer 'currency_symbol' => $currency->symbol, 'currency_decimal_places' => $currency->decimal_places, - 'native_currency_id' => (string)$this->native->id, - 'native_currency_code' => $this->native->code, - 'native_currency_symbol' => $this->native->symbol, - 'native_currency_decimal_places' => $this->native->decimal_places, + 'primary_currency_id' => (string)$this->primary->id, + 'primary_currency_code' => $this->primary->code, + 'primary_currency_symbol' => $this->primary->symbol, + 'primary_currency_decimal_places' => $this->primary->decimal_places, 'name' => $bill->name, 'amount_min' => $bill->amounts['amount_min'], diff --git a/app/Transformers/BudgetLimitTransformer.php b/app/Transformers/BudgetLimitTransformer.php index bc43a51f9e..19f105affe 100644 --- a/app/Transformers/BudgetLimitTransformer.php +++ b/app/Transformers/BudgetLimitTransformer.php @@ -37,17 +37,17 @@ use League\Fractal\Resource\Item; */ class BudgetLimitTransformer extends AbstractTransformer { - protected array $availableIncludes + protected array $availableIncludes = [ 'budget', ]; - protected bool $convertToNative; - protected TransactionCurrency $default; + protected bool $convertToPrimary; + protected TransactionCurrency $primary; public function __construct() { - $this->default = Amount::getNativeCurrency(); - $this->convertToNative = Amount::convertToNative(); + $this->primary = Amount::getPrimaryCurrency(); + $this->convertToPrimary = Amount::convertToPrimary(); } /** @@ -65,8 +65,8 @@ class BudgetLimitTransformer extends AbstractTransformer */ public function transform(BudgetLimit $budgetLimit): array { - $repository = app(OperationsRepository::class); - $limitRepos = app(BudgetLimitRepositoryInterface::class); + $repository = app(OperationsRepository::class); + $limitRepos = app(BudgetLimitRepositoryInterface::class); $repository->setUser($budgetLimit->budget->user); $limitRepos->setUser($budgetLimit->budget->user); $expenses = $repository->sumExpenses( @@ -92,38 +92,38 @@ class BudgetLimitTransformer extends AbstractTransformer $currencySymbol = $currency->symbol; $currencyDecimalPlaces = $currency->decimal_places; } - $amount = app('steam')->bcround($amount, $currencyDecimalPlaces); - $default = $this->default; - if (!$this->convertToNative) { - $default = null; + $amount = app('steam')->bcround($amount, $currencyDecimalPlaces); + $primary = $this->primary; + if (!$this->convertToPrimary) { + $primary = null; } return [ - 'id' => (string) $budgetLimit->id, - 'created_at' => $budgetLimit->created_at->toAtomString(), - 'updated_at' => $budgetLimit->updated_at->toAtomString(), - 'start' => $budgetLimit->start_date->toAtomString(), - 'end' => $budgetLimit->end_date->endOfDay()->toAtomString(), - 'budget_id' => (string) $budgetLimit->budget_id, - 'currency_id' => (string) $currencyId, - 'currency_code' => $currencyCode, - 'currency_name' => $currencyName, - 'currency_decimal_places' => $currencyDecimalPlaces, - 'currency_symbol' => $currencySymbol, - 'native_currency_id' => $default instanceof TransactionCurrency ? (string) $default->id : null, - 'native_currency_code' => $default?->code, - 'native_currency_symbol' => $default?->symbol, - 'native_currency_decimal_places' => $default?->decimal_places, - 'amount' => $amount, - 'native_amount' => $this->convertToNative ? app('steam')->bcround($budgetLimit->native_amount, $default->decimal_places) : null, - 'period' => $budgetLimit->period, - 'spent' => $expenses[$currencyId]['sum'] ?? '0', // will be in native if convertToNative. - 'notes' => '' === $notes ? null : $notes, - 'links' => [ + '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, + 'currency_code' => $currencyCode, + 'currency_name' => $currencyName, + 'currency_decimal_places' => $currencyDecimalPlaces, + 'currency_symbol' => $currencySymbol, + 'primary_currency_id' => $primary instanceof TransactionCurrency ? (string)$primary->id : null, + 'primary_currency_code' => $primary?->code, + 'primary_currency_symbol' => $primary?->symbol, + 'primary_currency_decimal_places' => $primary?->decimal_places, + 'amount' => $amount, + 'pc_amount' => $this->convertToPrimary ? app('steam')->bcround($budgetLimit->native_amount, $primary->decimal_places) : null, + 'period' => $budgetLimit->period, + 'spent' => $expenses[$currencyId]['sum'] ?? '0', // will be in native if convertToNative. + 'notes' => '' === $notes ? null : $notes, + 'links' => [ [ 'rel' => 'self', - 'uri' => '/budgets/limits/'.$budgetLimit->id, + 'uri' => '/budgets/limits/' . $budgetLimit->id, ], ], ]; diff --git a/app/Transformers/BudgetTransformer.php b/app/Transformers/BudgetTransformer.php index d028143c41..eec4aeeaae 100644 --- a/app/Transformers/BudgetTransformer.php +++ b/app/Transformers/BudgetTransformer.php @@ -38,8 +38,8 @@ use Symfony\Component\HttpFoundation\ParameterBag; */ class BudgetTransformer extends AbstractTransformer { - private readonly bool $convertToNative; - private readonly TransactionCurrency $default; + private readonly bool $convertToPrimary; + private readonly TransactionCurrency $primary; private readonly OperationsRepositoryInterface $opsRepository; private readonly BudgetRepositoryInterface $repository; @@ -51,8 +51,8 @@ class BudgetTransformer extends AbstractTransformer $this->opsRepository = app(OperationsRepositoryInterface::class); $this->repository = app(BudgetRepositoryInterface::class); $this->parameters = new ParameterBag(); - $this->default = Amount::getNativeCurrency(); - $this->convertToNative = Amount::convertToNative(); + $this->primary = Amount::getPrimaryCurrency(); + $this->convertToPrimary = Amount::convertToPrimary(); } /** @@ -72,7 +72,7 @@ class BudgetTransformer extends AbstractTransformer // info for auto budget. $abType = null; $abAmount = null; - $abNative = null; + $abPrimary = null; $abPeriod = null; $notes = $this->repository->getNoteText($budget); @@ -82,17 +82,17 @@ class BudgetTransformer extends AbstractTransformer AutoBudgetType::AUTO_BUDGET_ADJUSTED->value => 'adjusted', ]; $currency = $autoBudget?->transactionCurrency; - $default = $this->default; - if (!$this->convertToNative) { - $default = null; + $primary = $this->primary; + if (!$this->convertToPrimary) { + $primary = null; } if (null === $autoBudget) { - $currency = $default; + $currency = $primary; } if (null !== $autoBudget) { $abType = $types[$autoBudget->auto_budget_type]; $abAmount = app('steam')->bcround($autoBudget->amount, $currency->decimal_places); - $abNative = $this->convertToNative ? app('steam')->bcround($autoBudget->native_amount, $default->decimal_places) : null; + $abPrimary = $this->convertToPrimary ? app('steam')->bcround($autoBudget->native_amount, $primary->decimal_places) : null; $abPeriod = $autoBudget->period; } @@ -113,16 +113,16 @@ class BudgetTransformer extends AbstractTransformer 'currency_decimal_places' => $autoBudget?->transactionCurrency->decimal_places, 'currency_symbol' => $autoBudget?->transactionCurrency->symbol, - 'native_currency_id' => $default instanceof TransactionCurrency ? (string) $default->id : null, - 'native_currency_code' => $default?->code, - 'native_currency_symbol' => $default?->symbol, - 'native_currency_decimal_places' => $default?->decimal_places, + 'primary_currency_id' => $primary instanceof TransactionCurrency ? (string) $primary->id : null, + 'primary_currency_code' => $primary?->code, + 'primary_currency_symbol' => $primary?->symbol, + 'primary_currency_decimal_places' => $primary?->decimal_places, - // amount and native amount if present. + // amount and primary currency amount if present. 'auto_budget_amount' => $abAmount, - 'native_auto_budget_amount' => $abNative, - 'spent' => $spent, // always in native. + 'pc_auto_budget_amount' => $abPrimary, + 'spent' => $spent, // always in primary currency. 'links' => [ [ 'rel' => 'self', diff --git a/app/Transformers/CategoryTransformer.php b/app/Transformers/CategoryTransformer.php index f7090cec3b..cad3bdb15f 100644 --- a/app/Transformers/CategoryTransformer.php +++ b/app/Transformers/CategoryTransformer.php @@ -37,7 +37,7 @@ use Illuminate\Support\Collection; class CategoryTransformer extends AbstractTransformer { private readonly bool $convertToNative; - private readonly TransactionCurrency $default; + private readonly TransactionCurrency $primary; private readonly OperationsRepositoryInterface $opsRepository; private readonly CategoryRepositoryInterface $repository; @@ -48,8 +48,8 @@ class CategoryTransformer extends AbstractTransformer { $this->opsRepository = app(OperationsRepositoryInterface::class); $this->repository = app(CategoryRepositoryInterface::class); - $this->default = Amount::getNativeCurrency(); - $this->convertToNative = Amount::convertToNative(); + $this->primary = Amount::getPrimaryCurrency(); + $this->convertToNative = Amount::convertToPrimary(); } /** @@ -60,36 +60,36 @@ class CategoryTransformer extends AbstractTransformer $this->opsRepository->setUser($category->user); $this->repository->setUser($category->user); - $spent = []; - $earned = []; - $start = $this->parameters->get('start'); - $end = $this->parameters->get('end'); + $spent = []; + $earned = []; + $start = $this->parameters->get('start'); + $end = $this->parameters->get('end'); if (null !== $start && null !== $end) { $earned = $this->beautify($this->opsRepository->sumIncome($start, $end, null, new Collection([$category]))); $spent = $this->beautify($this->opsRepository->sumExpenses($start, $end, null, new Collection([$category]))); } - $default = $this->default; + $primary = $this->primary; if (!$this->convertToNative) { - $default = null; + $primary = null; } - $notes = $this->repository->getNoteText($category); + $notes = $this->repository->getNoteText($category); return [ - 'id' => $category->id, - 'created_at' => $category->created_at->toAtomString(), - 'updated_at' => $category->updated_at->toAtomString(), - 'name' => $category->name, - 'notes' => $notes, - 'native_currency_id' => $default instanceof TransactionCurrency ? (string) $default->id : null, - 'native_currency_code' => $default?->code, - 'native_currency_symbol' => $default?->symbol, - 'native_currency_decimal_places' => $default?->decimal_places, - 'spent' => $spent, - 'earned' => $earned, - 'links' => [ + 'id' => $category->id, + 'created_at' => $category->created_at->toAtomString(), + 'updated_at' => $category->updated_at->toAtomString(), + 'name' => $category->name, + 'notes' => $notes, + 'primary_currency_id' => $primary instanceof TransactionCurrency ? (string)$primary->id : null, + 'primary_currency_code' => $primary?->code, + 'primary_currency_symbol' => $primary?->symbol, + 'primary_currency_decimal_places' => $primary?->decimal_places, + 'spent' => $spent, + 'earned' => $earned, + 'links' => [ [ 'rel' => 'self', - 'uri' => '/categories/'.$category->id, + 'uri' => '/categories/' . $category->id, ], ], ]; @@ -99,7 +99,7 @@ class CategoryTransformer extends AbstractTransformer { $return = []; foreach ($array as $data) { - $data['sum'] = app('steam')->bcround($data['sum'], (int) $data['currency_decimal_places']); + $data['sum'] = app('steam')->bcround($data['sum'], (int)$data['currency_decimal_places']); $return[] = $data; } diff --git a/app/Transformers/PiggyBankEventTransformer.php b/app/Transformers/PiggyBankEventTransformer.php index 07202d4d97..70f8122189 100644 --- a/app/Transformers/PiggyBankEventTransformer.php +++ b/app/Transformers/PiggyBankEventTransformer.php @@ -61,7 +61,7 @@ class PiggyBankEventTransformer extends AbstractTransformer $this->piggyRepos->setUser($account->user); // get associated currency or fall back to the default: - $currency = $this->repository->getAccountCurrency($account) ?? app('amount')->getNativeCurrencyByUserGroup($account->user->userGroup); + $currency = $this->repository->getAccountCurrency($account) ?? app('amount')->getPrimaryCurrencyByUserGroup($account->user->userGroup); // get associated journal and transaction, if any: $journalId = $event->transaction_journal_id; diff --git a/app/Transformers/PiggyBankTransformer.php b/app/Transformers/PiggyBankTransformer.php index 924ccbe43f..ece95aeb6e 100644 --- a/app/Transformers/PiggyBankTransformer.php +++ b/app/Transformers/PiggyBankTransformer.php @@ -135,7 +135,7 @@ class PiggyBankTransformer extends AbstractTransformer 'id' => (string) $account->id, 'name' => $account->name, 'current_amount' => (string) $account->pivot->current_amount, - 'native_current_amount' => (string) $account->pivot->native_current_amount, + 'pc_current_amount' => (string) $account->pivot->native_current_amount, // TODO add balance, add left to save. ]; } diff --git a/app/Transformers/TransactionGroupTransformer.php b/app/Transformers/TransactionGroupTransformer.php index ccf4c6c0ab..ea3b57c713 100644 --- a/app/Transformers/TransactionGroupTransformer.php +++ b/app/Transformers/TransactionGroupTransformer.php @@ -122,13 +122,13 @@ class TransactionGroupTransformer extends AbstractTransformer $foreignAmount = app('steam')->positive($transaction['foreign_amount']); } - // set native amount to the normal amount if the currency matches. - if ($transaction['native_currency']['id'] ?? null === $transaction['currency_id']) { - $transaction['native_amount'] = $amount; + // set primary amount to the normal amount if the currency matches. + if ($transaction['primary_currency']['id'] ?? null === $transaction['currency_id']) { + $transaction['pc_amount'] = $amount; } - if (array_key_exists('native_amount', $transaction) && null !== $transaction['native_amount']) { - $transaction['native_amount'] = app('steam')->positive($transaction['native_amount']); + if (array_key_exists('pc_amount', $transaction) && null !== $transaction['pc_amount']) { + $transaction['pc_amount'] = app('steam')->positive($transaction['pc_amount']); } $type = $this->stringFromArray($transaction, 'transaction_type_type', TransactionTypeEnum::WITHDRAWAL->value); @@ -160,15 +160,15 @@ class TransactionGroupTransformer extends AbstractTransformer 'amount' => $amount, 'foreign_amount' => $foreignAmount, - // native amount, defaults to NULL when convertToNative is false. - 'native_amount' => $transaction['native_amount'] ?? null, + // primary currency amount, defaults to NULL when convertToPrimary is false. + 'pc_amount' => $transaction['pc_amount'] ?? null, - // native currency, always present. - 'native_currency_id' => $transaction['native_currency']['id'] ?? null, - 'native_currency_code' => $transaction['native_currency']['code'] ?? null, - 'native_currency_name' => $transaction['native_currency']['name'] ?? null, - 'native_currency_symbol' => $transaction['native_currency']['symbol'] ?? null, - 'native_currency_decimal_places' => $transaction['native_currency']['decimal_places'] ?? null, + // primary currency, always present. + 'primary_currency_id' => $transaction['primary_currency']['id'] ?? null, + 'primary_currency_code' => $transaction['primary_currency']['code'] ?? null, + 'primary_currency_name' => $transaction['primary_currency']['name'] ?? null, + 'primary_currency_symbol' => $transaction['primary_currency']['symbol'] ?? null, + 'primary_currency_decimal_places' => $transaction['primary_currency']['decimal_places'] ?? null, // source balance after 'source_balance_after' => $transaction['source_balance_after'] ?? null, diff --git a/app/Transformers/UserGroupTransformer.php b/app/Transformers/UserGroupTransformer.php index 8ba47228ba..98e495f6ef 100644 --- a/app/Transformers/UserGroupTransformer.php +++ b/app/Transformers/UserGroupTransformer.php @@ -105,7 +105,7 @@ class UserGroupTransformer extends AbstractTransformer */ public function transform(UserGroup $userGroup): array { - $currency = Amount::getNativeCurrencyByUserGroup($userGroup); + $currency = Amount::getPrimaryCurrencyByUserGroup($userGroup); return [ 'id' => $userGroup->id, @@ -114,11 +114,11 @@ class UserGroupTransformer extends AbstractTransformer 'in_use' => $this->inUse[$userGroup->id] ?? false, 'can_see_members' => $this->membershipsVisible[$userGroup->id] ?? false, 'title' => $userGroup->title, - 'native_currency_id' => (string) $currency->id, - 'native_currency_name' => $currency->name, - 'native_currency_code' => $currency->code, - 'native_currency_symbol' => $currency->symbol, - 'native_currency_decimal_places' => $currency->decimal_places, + 'primary_currency_id' => (string) $currency->id, + 'primary_currency_name' => $currency->name, + 'primary_currency_code' => $currency->code, + 'primary_currency_symbol' => $currency->symbol, + 'primary_currency_decimal_places' => $currency->decimal_places, 'members' => array_values($this->memberships[$userGroup->id] ?? []), ]; // if the user has a specific role in this group, then collect the memberships. diff --git a/app/Transformers/V2/AbstractTransformer.php b/app/Transformers/V2/AbstractTransformer.php deleted file mode 100644 index 84c2a3e255..0000000000 --- a/app/Transformers/V2/AbstractTransformer.php +++ /dev/null @@ -1,54 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Transformers\V2; - -use Illuminate\Support\Collection; -use League\Fractal\TransformerAbstract; -use Symfony\Component\HttpFoundation\ParameterBag; - -/** - * Class AbstractTransformer - * - * @deprecated - */ -abstract class AbstractTransformer extends TransformerAbstract -{ - protected ParameterBag $parameters; - - /** - * This method is called exactly ONCE from FireflyIII\Api\V2\Controllers\Controller::jsonApiList - */ - abstract public function collectMetaData(Collection $objects): Collection; - - final public function getParameters(): ParameterBag - { - return $this->parameters; - } - - final public function setParameters(ParameterBag $parameters): void - { - $this->parameters = $parameters; - } -} diff --git a/app/Transformers/V2/AccountTransformer.php b/app/Transformers/V2/AccountTransformer.php deleted file mode 100644 index 4b7e9f58bc..0000000000 --- a/app/Transformers/V2/AccountTransformer.php +++ /dev/null @@ -1,440 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Transformers\V2; - -use Carbon\Carbon; -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\Account; -use FireflyIII\Models\AccountType; -use FireflyIII\Models\TransactionCurrency; -use FireflyIII\Repositories\Account\AccountRepositoryInterface; -use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; -use Illuminate\Support\Collection; -use Illuminate\Support\Facades\Log; - -/** - * Class AccountTransformer - * - * @deprecated - */ -class AccountTransformer extends AbstractTransformer -{ - private array $accountMeta; - private array $accountTypes; - private array $balanceDifferences; - private array $balances; - private array $convertedBalances; - private array $currencies; - private TransactionCurrency $default; - private array $fullTypes; - private array $lastActivity; - private array $objectGroups; - - /** - * This method collects meta-data for one or all accounts in the transformer's collection. - */ - public function collectMetaData(Collection $objects): Collection - { - $this->currencies = []; - $this->balances = []; - $this->accountMeta = []; - $this->accountTypes = []; - $this->fullTypes = []; - $this->lastActivity = []; - $this->objectGroups = []; - $this->convertedBalances = []; - $this->balanceDifferences = []; - - Log::debug(sprintf('collectMetaData on %d object(s)', $objects->count())); - - // first collect all the "heavy" stuff that relies on ALL data to be present. - // get last activity: - $this->getLastActivity($objects); - - // get balances of all accounts - $this->getMetaBalances($objects); - - // get default currency: - $this->getDefaultCurrency(); - - // collect currency and other meta-data: - $this->collectAccountMetaData($objects); - - // get account types: - $this->collectAccountTypes($objects); - - // add balance difference - if (null !== $this->parameters->get('start') && null !== $this->parameters->get('end')) { - $this->getBalanceDifference($objects, $this->parameters->get('start'), $this->parameters->get('end')); - } - - // get object groups - $this->getObjectGroups($objects); - - // sort: - $objects = $this->sortAccounts($objects); - - // if pagination is disabled, do it now: - if (true === $this->parameters->get('disablePagination')) { - $page = (int) $this->parameters->get('page'); - $size = (int) $this->parameters->get('pageSize'); - $objects = $objects->slice(($page - 1) * $size, $size); - } - - return $objects; - } - - private function getLastActivity(Collection $accounts): void - { - /** @var AccountRepositoryInterface $accountRepository */ - $accountRepository = app(AccountRepositoryInterface::class); - $lastActivity = $accountRepository->getLastActivity($accounts); - foreach ($lastActivity as $row) { - $this->lastActivity[(int) $row['account_id']] = Carbon::parse($row['date_max'], config('app.timezone')); - } - } - - private function getMetaBalances(Collection $accounts): void - { - try { - $this->convertedBalances = app('steam')->finalAccountsBalance($accounts, $this->getDate()); - } catch (FireflyException $e) { - Log::error($e->getMessage()); - } - } - - private function getDate(): Carbon - { - if (null !== $this->parameters->get('date')) { - return $this->parameters->get('date'); - } - - return today(config('app.timezone')); - } - - private function getDefaultCurrency(): void - { - $this->default = app('amount')->getNativeCurrency(); - } - - private function collectAccountMetaData(Collection $accounts): void - { - /** @var CurrencyRepositoryInterface $repository */ - $repository = app(CurrencyRepositoryInterface::class); - - /** @var AccountRepositoryInterface $accountRepository */ - $accountRepository = app(AccountRepositoryInterface::class); - $metaFields = $accountRepository->getMetaValues($accounts, ['currency_id', 'account_role', 'account_number', 'liability_direction', 'interest', 'interest_period', 'current_debt']); - $currencyIds = $metaFields->where('name', 'currency_id')->pluck('data')->toArray(); - - $currencies = $repository->getByIds($currencyIds); - foreach ($currencies as $currency) { - $id = $currency->id; - $this->currencies[$id] = $currency; - } - foreach ($metaFields as $entry) { - $id = $entry->account_id; - $this->accountMeta[$id][$entry->name] = $entry->data; - } - } - - private function collectAccountTypes(Collection $accounts): void - { - /** @var AccountRepositoryInterface $accountRepository */ - $accountRepository = app(AccountRepositoryInterface::class); - $accountTypes = $accountRepository->getAccountTypes($accounts); - - /** @var AccountType $row */ - foreach ($accountTypes as $row) { - $this->accountTypes[$row->id] = (string) config(sprintf('firefly.shortNamesByFullName.%s', $row->type)); - $this->fullTypes[$row->id] = $row->type; - } - } - - private function getBalanceDifference(Collection $accounts, Carbon $start, Carbon $end): void - { - if ('en_US' === config('app.fallback_locale')) { - throw new FireflyException('Used deprecated method, rethink this.'); - } - // collect balances, start and end for both native and converted. - // yes the b is usually used for boolean by idiots but here it's for balance. - $bStart = []; - $bEnd = []; - - try { - Log::debug(sprintf('v2 transformer: finalAccountsBalance("%s")', $start->format('Y-m-d H:i:s'))); - Log::debug(sprintf('v2 transformer: finalAccountsBalance("%s")', $end->format('Y-m-d H:i:s'))); - $bStart = app('steam')->finalAccountsBalance($accounts, $start); - $bEnd = app('steam')->finalAccountsBalance($accounts, $end); - } catch (FireflyException $e) { - Log::error($e->getMessage()); - } - - /** @var Account $account */ - foreach ($accounts as $account) { - $id = $account->id; - if (array_key_exists($id, $bStart) && array_key_exists($id, $bEnd)) { - $this->balanceDifferences[$id] = [ - 'balance' => bcsub((string) $bEnd[$id]['balance'], (string) $bStart[$id]['balance']), - 'native_balance' => bcsub((string) $bEnd[$id]['native_balance'], (string) $bStart[$id]['native_balance']), - ]; - } - } - } - - private function getObjectGroups(Collection $accounts): void - { - /** @var AccountRepositoryInterface $accountRepository */ - $accountRepository = app(AccountRepositoryInterface::class); - $this->objectGroups = $accountRepository->getObjectGroups($accounts); - } - - private function sortAccounts(Collection $accounts): Collection - { - /** @var null|array $sort */ - $sort = $this->parameters->get('sort'); - - if (null === $sort || 0 === count($sort)) { - return $accounts; - } - - /** - * @var string $column - * @var string $direction - */ - foreach ($sort as $column => $direction) { - // account_number + iban - if ('iban' === $column) { - $accounts = $this->sortByIban($accounts, $direction); - } - if ('balance' === $column) { - $accounts = $this->sortByBalance($accounts, $direction); - } - if ('last_activity' === $column) { - $accounts = $this->sortByLastActivity($accounts, $direction); - } - if ('balance_difference' === $column) { - $accounts = $this->sortByBalanceDifference($accounts, $direction); - } - if ('current_debt' === $column) { - $accounts = $this->sortByCurrentDebt($accounts, $direction); - } - } - - return $accounts; - } - - private function sortByIban(Collection $accounts, string $direction): Collection - { - $meta = $this->accountMeta; - - return $accounts->sort(function (Account $left, Account $right) use ($meta, $direction) { - $leftIban = trim(sprintf('%s%s', $left->iban, $meta[$left->id]['account_number'] ?? '')); - $rightIban = trim(sprintf('%s%s', $right->iban, $meta[$right->id]['account_number'] ?? '')); - if ('asc' === $direction) { - return strcasecmp($leftIban, $rightIban); - } - - return strcasecmp($rightIban, $leftIban); - }); - } - - private function sortByBalance(Collection $accounts, string $direction): Collection - { - $balances = $this->convertedBalances; - - return $accounts->sort(function (Account $left, Account $right) use ($balances, $direction) { - $leftBalance = (float) ($balances[$left->id]['native_balance'] ?? 0); - $rightBalance = (float) ($balances[$right->id]['native_balance'] ?? 0); - if ('asc' === $direction) { - return $leftBalance <=> $rightBalance; - } - - return $rightBalance <=> $leftBalance; - }); - } - - private function sortByLastActivity(Collection $accounts, string $direction): Collection - { - $dates = $this->lastActivity; - - return $accounts->sort(function (Account $left, Account $right) use ($dates, $direction) { - $leftDate = $dates[$left->id] ?? Carbon::create(1900, 1, 1, 0, 0, 0); - $rightDate = $dates[$right->id] ?? Carbon::create(1900, 1, 1, 0, 0, 0); - if ('asc' === $direction) { - return $leftDate->gt($rightDate) ? 1 : -1; - } - - return $rightDate->gt($leftDate) ? 1 : -1; - }); - } - - private function sortByBalanceDifference(Collection $accounts, string $direction): Collection - { - $balances = $this->balanceDifferences; - - return $accounts->sort(function (Account $left, Account $right) use ($balances, $direction) { - $leftBalance = (float) ($balances[$left->id]['native_balance'] ?? 0); - $rightBalance = (float) ($balances[$right->id]['native_balance'] ?? 0); - if ('asc' === $direction) { - return $leftBalance <=> $rightBalance; - } - - return $rightBalance <=> $leftBalance; - }); - } - - private function sortByCurrentDebt(Collection $accounts, string $direction): Collection - { - $amounts = $this->accountMeta; - - return $accounts->sort(function (Account $left, Account $right) use ($amounts, $direction) { - $leftCurrent = (float) ($amounts[$left->id]['current_debt'] ?? 0); - $rightCurrent = (float) ($amounts[$right->id]['current_debt'] ?? 0); - if ('asc' === $direction) { - return $leftCurrent <=> $rightCurrent; - } - - return $rightCurrent <=> $leftCurrent; - }); - } - - /** - * Transform the account. - */ - public function transform(Account $account): array - { - $id = $account->id; - - // various meta - $accountRole = $this->accountMeta[$id]['account_role'] ?? null; - $accountType = $this->accountTypes[$id]; - $order = $account->order; - - // liability type - $liabilityType = 'liabilities' === $accountType ? $this->fullTypes[$id] : null; - $liabilityDirection = $this->accountMeta[$id]['liability_direction'] ?? null; - $interest = $this->accountMeta[$id]['interest'] ?? null; - $interestPeriod = $this->accountMeta[$id]['interest_period'] ?? null; - $currentDebt = $this->accountMeta[$id]['current_debt'] ?? null; - - // no currency? use default - $currency = $this->default; - if (array_key_exists($id, $this->accountMeta) && 0 !== (int) ($this->accountMeta[$id]['currency_id'] ?? 0)) { - $currency = $this->currencies[(int) $this->accountMeta[$id]['currency_id']]; - } - // amounts and calculation. - $balance = $this->balances[$id]['balance'] ?? null; - $nativeBalance = $this->convertedBalances[$id]['native_balance'] ?? null; - - // no order for some accounts: - if (!in_array(strtolower((string) $accountType), ['liability', 'liabilities', 'asset'], true)) { - $order = null; - } - - // object group - $objectGroupId = $this->objectGroups[$id]['id'] ?? null; - $objectGroupOrder = $this->objectGroups[$id]['order'] ?? null; - $objectGroupTitle = $this->objectGroups[$id]['title'] ?? null; - - // balance difference - $diffStart = null; - $diffEnd = null; - $balanceDiff = null; - $nativeBalanceDiff = null; - if (null !== $this->parameters->get('start') && null !== $this->parameters->get('end')) { - $diffStart = $this->parameters->get('start')->toAtomString(); - $diffEnd = $this->parameters->get('end')->toAtomString(); - $balanceDiff = $this->balanceDifferences[$id]['balance'] ?? null; - $nativeBalanceDiff = $this->balanceDifferences[$id]['native_balance'] ?? null; - } - - return [ - 'id' => (string) $account->id, - 'created_at' => $account->created_at->toAtomString(), - 'updated_at' => $account->updated_at->toAtomString(), - 'active' => $account->active, - 'order' => $order, - 'name' => $account->name, - 'iban' => '' === (string) $account->iban ? null : $account->iban, - 'account_number' => $this->accountMeta[$id]['account_number'] ?? null, - 'type' => strtolower((string) $accountType), - 'account_role' => $accountRole, - 'currency_id' => (string) $currency->id, - 'currency_code' => $currency->code, - 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => $currency->decimal_places, - - 'native_currency_id' => (string) $this->default->id, - 'native_currency_code' => $this->default->code, - 'native_currency_symbol' => $this->default->symbol, - 'native_currency_decimal_places' => $this->default->decimal_places, - - // balance: - 'current_balance' => $balance, - 'native_current_balance' => $nativeBalance, - 'current_balance_date' => $this->getDate()->endOfDay()->toAtomString(), - - // balance difference - 'balance_difference' => $balanceDiff, - 'native_balance_difference' => $nativeBalanceDiff, - 'balance_difference_start' => $diffStart, - 'balance_difference_end' => $diffEnd, - - // more meta - 'last_activity' => array_key_exists($id, $this->lastActivity) ? $this->lastActivity[$id]->toAtomString() : null, - - // liability stuff - 'liability_type' => $liabilityType, - 'liability_direction' => $liabilityDirection, - 'interest' => $interest, - 'interest_period' => $interestPeriod, - 'current_debt' => $currentDebt, - - // object group - 'object_group_id' => null !== $objectGroupId ? (string) $objectGroupId : null, - 'object_group_order' => $objectGroupOrder, - 'object_group_title' => $objectGroupTitle, - - // 'notes' => $this->repository->getNoteText($account), - // 'monthly_payment_date' => $monthlyPaymentDate, - // 'credit_card_type' => $creditCardType, - // 'bic' => $this->repository->getMetaValue($account, 'BIC'), - // 'virtual_balance' => number_format((float) $account->virtual_balance, $decimalPlaces, '.', ''), - // 'opening_balance' => $openingBalance, - // 'opening_balance_date' => $openingBalanceDate, - // 'include_net_worth' => $includeNetWorth, - // 'longitude' => $longitude, - // 'latitude' => $latitude, - // 'zoom_level' => $zoomLevel, - 'links' => [ - [ - 'rel' => 'self', - 'uri' => '/accounts/'.$account->id, - ], - ], - ]; - } -} diff --git a/app/Transformers/V2/BillTransformer.php b/app/Transformers/V2/BillTransformer.php deleted file mode 100644 index 79d18c671a..0000000000 --- a/app/Transformers/V2/BillTransformer.php +++ /dev/null @@ -1,367 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Transformers\V2; - -use Carbon\Carbon; -use Carbon\CarbonInterface; -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\Bill; -use FireflyIII\Models\Note; -use FireflyIII\Models\ObjectGroup; -use FireflyIII\Models\Transaction; -use FireflyIII\Models\TransactionCurrency; -use FireflyIII\Models\TransactionJournal; -use FireflyIII\Support\Http\Api\ExchangeRateConverter; -use Illuminate\Support\Collection; -use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Log; - -/** - * Class BillTransformer - * - * @deprecated - */ -class BillTransformer extends AbstractTransformer -{ - private ExchangeRateConverter $converter; - private array $currencies; - private TransactionCurrency $default; - private array $groups; - private array $notes; - private array $paidDates; - - /** - * @throws FireflyException - * - * @SuppressWarnings("PHPMD.ExcessiveMethodLength") - */ - public function collectMetaData(Collection $objects): Collection - { - /** @var array $currencies */ - $currencies = []; - $bills = []; - $this->notes = []; - $this->groups = []; - $this->paidDates = []; - - /** @var Bill $object */ - foreach ($objects as $object) { - $id = $object->transaction_currency_id; - $bills[] = $object->id; - $currencies[$id] ??= TransactionCurrency::find($id); - } - $this->currencies = $currencies; - $notes = Note::whereNoteableType(Bill::class)->whereIn('noteable_id', array_keys($bills))->get(); - - /** @var Note $note */ - foreach ($notes as $note) { - $id = $note->noteable_id; - $this->notes[$id] = $note; - } - // grab object groups: - $set = DB::table('object_groupables') - ->leftJoin('object_groups', 'object_groups.id', '=', 'object_groupables.object_group_id') - ->where('object_groupables.object_groupable_type', Bill::class) - ->get(['object_groupables.*', 'object_groups.title', 'object_groups.order']) - ; - - /** @var ObjectGroup $entry */ - foreach ($set as $entry) { - $billId = (int) $entry->object_groupable_id; - $id = (int) $entry->object_group_id; - $order = $entry->order; - $this->groups[$billId] = [ - 'object_group_id' => $id, - 'object_group_title' => $entry->title, - 'object_group_order' => $order, - ]; - } - Log::debug(sprintf('Created new ExchangeRateConverter in %s', __METHOD__)); - $this->default = app('amount')->getNativeCurrency(); - $this->converter = new ExchangeRateConverter(); - - // grab all paid dates: - if (null !== $this->parameters->get('start') && null !== $this->parameters->get('end')) { - $journals = TransactionJournal::whereIn('bill_id', $bills) - ->where('date', '>=', $this->parameters->get('start')) - ->where('date', '<=', $this->parameters->get('end')) - ->get(['transaction_journals.id', 'transaction_journals.transaction_group_id', 'transaction_journals.date', 'transaction_journals.bill_id']) - ; - $journalIds = $journals->pluck('id')->toArray(); - - // grab transactions for amount: - $set = Transaction::whereIn('transaction_journal_id', $journalIds) - ->where('transactions.amount', '<', 0) - ->get(['transactions.id', 'transactions.transaction_journal_id', 'transactions.amount', 'transactions.foreign_amount', 'transactions.transaction_currency_id', 'transactions.foreign_currency_id']) - ; - $transactions = []; - - /** @var Transaction $transaction */ - foreach ($set as $transaction) { - $journalId = $transaction->transaction_journal_id; - $transactions[$journalId] = $transaction->toArray(); - } - - /** @var TransactionJournal $journal */ - foreach ($journals as $journal) { - app('log')->debug(sprintf('Processing journal #%d', $journal->id)); - $transaction = $transactions[$journal->id] ?? []; - $billId = (int) $journal->bill_id; - $currencyId = (int) ($transaction['transaction_currency_id'] ?? 0); - $currencies[$currencyId] ??= TransactionCurrency::find($currencyId); - - // foreign currency - $foreignCurrencyId = null; - $foreignCurrencyCode = null; - $foreignCurrencyName = null; - $foreignCurrencySymbol = null; - $foreignCurrencyDp = null; - app('log')->debug('Foreign currency is NULL'); - if (null !== $transaction['foreign_currency_id']) { - app('log')->debug(sprintf('Foreign currency is #%d', $transaction['foreign_currency_id'])); - $foreignCurrencyId = (int) $transaction['foreign_currency_id']; - $currencies[$foreignCurrencyId] ??= TransactionCurrency::find($foreignCurrencyId); - $foreignCurrencyCode = $currencies[$foreignCurrencyId]->code; // @phpstan-ignore property.notFound - $foreignCurrencyName = $currencies[$foreignCurrencyId]->name; // @phpstan-ignore property.notFound - $foreignCurrencySymbol = $currencies[$foreignCurrencyId]->symbol; // @phpstan-ignore property.notFound - $foreignCurrencyDp = $currencies[$foreignCurrencyId]->decimal_places; // @phpstan-ignore property.notFound - } - - $this->paidDates[$billId][] = [ - 'transaction_group_id' => (string) $journal->id, - 'transaction_journal_id' => (string) $journal->transaction_group_id, - 'date' => $journal->date->toAtomString(), - 'currency_id' => $currencies[$currencyId]->id, // @phpstan-ignore property.notFound - 'currency_code' => $currencies[$currencyId]->code, // @phpstan-ignore property.notFound - 'currency_name' => $currencies[$currencyId]->name, // @phpstan-ignore property.notFound - 'currency_symbol' => $currencies[$currencyId]->symbol, // @phpstan-ignore property.notFound - 'currency_decimal_places' => $currencies[$currencyId]->decimal_places, // @phpstan-ignore property.notFound - 'native_currency_id' => $currencies[$currencyId]->id, // @phpstan-ignore property.notFound - 'native_currency_code' => $currencies[$currencyId]->code, // @phpstan-ignore property.notFound - 'native_currency_symbol' => $currencies[$currencyId]->symbol, // @phpstan-ignore property.notFound - 'native_currency_decimal_places' => $currencies[$currencyId]->decimal_places, // @phpstan-ignore property.notFound - 'foreign_currency_id' => $foreignCurrencyId, - 'foreign_currency_code' => $foreignCurrencyCode, - 'foreign_currency_name' => $foreignCurrencyName, - 'foreign_currency_symbol' => $foreignCurrencySymbol, - 'foreign_currency_decimal_places' => $foreignCurrencyDp, - 'amount' => $transaction['amount'], - 'foreign_amount' => $transaction['foreign_amount'], - 'native_amount' => null, - 'foreign_native_amount' => null, - ]; - } - } - - return $objects; - } - - /** - * Transform the bill. - */ - public function transform(Bill $bill): array - { - $paidData = $this->paidDates[$bill->id] ?? []; - $nextExpectedMatch = $this->nextExpectedMatch($bill, $this->paidDates[$bill->id] ?? []); - $payDates = $this->payDates($bill); - $currency = $this->currencies[$bill->transaction_currency_id]; - $group = $this->groups[$bill->id] ?? null; - - // date for currency conversion - /** @var null|Carbon $startParam */ - $startParam = $this->parameters->get('start'); - - /** @var null|Carbon $date */ - $date = null === $startParam ? today() : clone $startParam; - - $nextExpectedMatchDiff = $this->getNextExpectedMatchDiff($nextExpectedMatch, $payDates); - $this->converter->summarize(); - - return [ - 'id' => $bill->id, - 'created_at' => $bill->created_at->toAtomString(), - 'updated_at' => $bill->updated_at->toAtomString(), - 'name' => $bill->name, - 'amount_min' => app('steam')->bcround($bill->amount_min, $currency->decimal_places), - 'amount_max' => app('steam')->bcround($bill->amount_max, $currency->decimal_places), - 'native_amount_min' => $this->converter->convert($currency, $this->default, $date, $bill->amount_min), - 'native_amount_max' => $this->converter->convert($currency, $this->default, $date, $bill->amount_max), - 'currency_id' => (string) $bill->transaction_currency_id, - 'currency_code' => $currency->code, - 'currency_name' => $currency->name, - 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => $currency->decimal_places, - 'native_currency_id' => $this->default->id, - 'native_currency_code' => $this->default->code, - 'native_currency_name' => $this->default->name, - 'native_currency_symbol' => $this->default->symbol, - 'native_currency_decimal_places' => $this->default->decimal_places, - 'date' => $bill->date->toAtomString(), - 'end_date' => $bill->end_date?->toAtomString(), - 'extension_date' => $bill->extension_date?->toAtomString(), - 'repeat_freq' => $bill->repeat_freq, - 'skip' => $bill->skip, - 'active' => $bill->active, - 'order' => $bill->order, - 'notes' => $this->notes[$bill->id] ?? null, - 'object_group_id' => $group ? $group['object_group_id'] : null, - 'object_group_order' => $group ? $group['object_group_order'] : null, - 'object_group_title' => $group ? $group['object_group_title'] : null, - 'next_expected_match' => $nextExpectedMatch->toAtomString(), - 'next_expected_match_diff' => $nextExpectedMatchDiff, - 'pay_dates' => $payDates, - 'paid_dates' => $paidData, - 'links' => [ - [ - 'rel' => 'self', - 'uri' => sprintf('/bills/%d', $bill->id), - ], - ], - ]; - } - - /** - * Get the data the bill was paid and predict the next expected match. - */ - protected function nextExpectedMatch(Bill $bill, array $dates): Carbon - { - // 2023-07-1 sub one day from the start date to fix a possible bug (see #7704) - // 2023-07-18 this particular date is used to search for the last paid date. - // 2023-07-18 the cloned $searchDate is used to grab the correct transactions. - - /** @var null|Carbon $startParam */ - $startParam = $this->parameters->get('start'); - - /** @var null|Carbon $start */ - $start = null === $startParam ? today() : clone $startParam; - $start->subDay(); - - $lastPaidDate = $this->lastPaidDate($dates, $start); - $nextMatch = clone $bill->date; - while ($nextMatch < $lastPaidDate) { - /* - * As long as this date is smaller than the last time the bill was paid, keep jumping ahead. - * For example: 1 jan, 1 feb, etc. - */ - $nextMatch = app('navigation')->addPeriod($nextMatch, $bill->repeat_freq, $bill->skip); - } - if ($nextMatch->isSameDay($lastPaidDate)) { - // Add another period because it's the same day as the last paid date. - return app('navigation')->addPeriod($nextMatch, $bill->repeat_freq, $bill->skip); - } - - return $nextMatch; - } - - /** - * Returns the latest date in the set, or start when set is empty. - */ - protected function lastPaidDate(array $dates, Carbon $default): Carbon - { - if (0 === count($dates)) { - return $default; - } - $latest = $dates[0]['date']; - - /** @var array $row */ - foreach ($dates as $row) { - $carbon = new Carbon($row['date']); - if ($carbon->gte($latest)) { - $latest = $row['date']; - } - } - - return new Carbon($latest); - } - - protected function payDates(Bill $bill): array - { - // app('log')->debug(sprintf('Now in payDates() for bill #%d', $bill->id)); - if (null === $this->parameters->get('start') || null === $this->parameters->get('end')) { - // app('log')->debug('No start or end date, give empty array.'); - - return []; - } - $set = new Collection(); - $currentStart = clone $this->parameters->get('start'); - // 2023-06-23 subDay to fix 7655 - $currentStart->subDay(); - $loop = 0; - while ($currentStart <= $this->parameters->get('end')) { - $nextExpectedMatch = $this->nextDateMatch($bill, $currentStart); - // If nextExpectedMatch is after end, we continue: - if ($nextExpectedMatch > $this->parameters->get('end')) { - break; - } - // add to set - $set->push(clone $nextExpectedMatch); - $nextExpectedMatch->addDay(); - $currentStart = clone $nextExpectedMatch; - ++$loop; - if ($loop > 4) { - break; - } - } - $simple = $set->map( // @phpstan-ignore-line - static fn (Carbon $date) => $date->toAtomString() - ); - - return $simple->toArray(); - } - - /** - * 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. - * - * TODO this method is bad compared to the v1 one. - */ - protected function nextDateMatch(Bill $bill, Carbon $date): Carbon - { - // app('log')->debug(sprintf('Now in nextDateMatch(%d, %s)', $bill->id, $date->format('Y-m-d'))); - $start = clone $bill->date; - // app('log')->debug(sprintf('Bill start date is %s', $start->format('Y-m-d'))); - while ($start < $date) { - $start = app('navigation')->addPeriod($start, $bill->repeat_freq, $bill->skip); - } - - // app('log')->debug(sprintf('End of loop, bill start date is now %s', $start->format('Y-m-d'))); - - return $start; - } - - private function getNextExpectedMatchDiff(Carbon $next, array $dates): string - { - if ($next->isToday()) { - return trans('firefly.today'); - } - $current = $dates[0] ?? null; - if (null === $current) { - return trans('firefly.not_expected_period'); - } - $carbon = new Carbon($current); - - return $carbon->diffForHumans(today(config('app.timezone')), CarbonInterface::DIFF_RELATIVE_TO_NOW); - } -} diff --git a/app/Transformers/V2/BudgetLimitTransformer.php b/app/Transformers/V2/BudgetLimitTransformer.php deleted file mode 100644 index a1a82d166a..0000000000 --- a/app/Transformers/V2/BudgetLimitTransformer.php +++ /dev/null @@ -1,109 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Transformers\V2; - -use FireflyIII\Models\BudgetLimit; -use Illuminate\Support\Collection; -use League\Fractal\Resource\Item; - -/** - * Class BudgetLimitTransformer - * - * @deprecated - */ -class BudgetLimitTransformer extends AbstractTransformer -{ - protected array $availableIncludes - = [ - 'budget', - ]; - - public function collectMetaData(Collection $objects): Collection - { - // TODO: Implement collectMetaData() method. - return $objects; - } - - /** - * Include Budget - * - * @return Item - */ - public function includeBudget(BudgetLimit $limit) - { - return $this->item($limit->budget, new BudgetTransformer(), 'budgets'); - } - - /** - * Transform the note. - */ - public function transform(BudgetLimit $budgetLimit): array - { - // $repository = app(OperationsRepository::class); - // $repository->setUser($budgetLimit->budget->user); - // $expenses = $repository->sumExpenses( - // $budgetLimit->start_date, $budgetLimit->end_date, null, new Collection([$budgetLimit->budget]), $budgetLimit->transactionCurrency - // ); - $currency = $budgetLimit->transactionCurrency; - $amount = $budgetLimit->amount; - $currencyDecimalPlaces = 2; - $currencyId = null; - $currencyName = null; - $currencyCode = null; - $currencySymbol = null; - if (null !== $currency) { - $amount = $budgetLimit->amount; - $currencyId = $currency->id; - $currencyName = $currency->name; - $currencyCode = $currency->code; - $currencySymbol = $currency->symbol; - $currencyDecimalPlaces = $currency->decimal_places; - } - $amount = number_format((float) $amount, $currencyDecimalPlaces, '.', ''); - - return [ - 'id' => (string) $budgetLimit->id, - 'created_at' => $budgetLimit->created_at->toAtomString(), - 'updated_at' => $budgetLimit->updated_at->toAtomString(), - 'start' => $budgetLimit->start_date->toAtomString(), - 'end' => $budgetLimit->end_date->endOfDay()->toAtomString(), - 'budget_id' => (string) $budgetLimit->budget_id, - 'currency_id' => (string) $currencyId, - 'currency_code' => $currencyCode, - 'currency_name' => $currencyName, - 'currency_decimal_places' => $currencyDecimalPlaces, - 'currency_symbol' => $currencySymbol, - 'amount' => $amount, - 'period' => $budgetLimit->period, - // 'spent' => $expenses[$currencyId]['sum'] ?? '0', - 'links' => [ - [ - 'rel' => 'self', - 'uri' => sprintf('/budget-limits/%d', $budgetLimit->id), - ], - ], - ]; - } -} diff --git a/app/Transformers/V2/BudgetTransformer.php b/app/Transformers/V2/BudgetTransformer.php deleted file mode 100644 index b1e048130c..0000000000 --- a/app/Transformers/V2/BudgetTransformer.php +++ /dev/null @@ -1,113 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Transformers\V2; - -use FireflyIII\Models\Budget; -use Illuminate\Support\Collection; -use Symfony\Component\HttpFoundation\ParameterBag; - -/** - * Class BudgetTransformer - * - * @deprecated - */ -class BudgetTransformer extends AbstractTransformer -{ - // private OperationsRepositoryInterface $opsRepository; - // private BudgetRepositoryInterface $repository; - - /** - * BudgetTransformer constructor. - */ - public function __construct() - { - // $this->opsRepository = app(OperationsRepositoryInterface::class); - // $this->repository = app(BudgetRepositoryInterface::class); - $this->parameters = new ParameterBag(); - } - - public function collectMetaData(Collection $objects): Collection - { - // TODO: Implement collectMetaData() method. - return $objects; - } - - /** - * Transform a budget. - */ - public function transform(Budget $budget): array - { - // $this->opsRepository->setUser($budget->user); - // $start = $this->parameters->get('start'); - // $end = $this->parameters->get('end'); - // $autoBudget = $this->repository->getAutoBudget($budget); - // $spent = []; - // if (null !== $start && null !== $end) { - // $spent = $this->beautify($this->opsRepository->sumExpenses($start, $end, null, new Collection([$budget]))); - // } - - // $abCurrencyId = null; - // $abCurrencyCode = null; - // $abType = null; - // $abAmount = null; - // $abPeriod = null; - // $notes = $this->repository->getNoteText($budget); - // - // $types = [ - // AutoBudget::AUTO_BUDGET_RESET => 'reset', - // AutoBudget::AUTO_BUDGET_ROLLOVER => 'rollover', - // ]; - // - // if (null !== $autoBudget) { - // $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, '.', ''); - // $abPeriod = $autoBudget->period; - // } - - return [ - 'id' => (string) $budget->id, - 'created_at' => $budget->created_at->toAtomString(), - 'updated_at' => $budget->updated_at->toAtomString(), - 'name' => $budget->name, - 'active' => $budget->active, - 'order' => $budget->order, - // 'notes' => $notes, - // 'auto_budget_type' => $abType, - // 'auto_budget_period' => $abPeriod, - // 'auto_budget_currency_id' => $abCurrencyId, - // 'auto_budget_currency_code' => $abCurrencyCode, - // 'auto_budget_amount' => $abAmount, - // 'spent' => $spent, - 'links' => [ - [ - 'rel' => 'self', - 'uri' => sprintf('/budgets/%d', $budget->id), - ], - ], - ]; - } -} diff --git a/app/Transformers/V2/CurrencyTransformer.php b/app/Transformers/V2/CurrencyTransformer.php deleted file mode 100644 index 53352d0843..0000000000 --- a/app/Transformers/V2/CurrencyTransformer.php +++ /dev/null @@ -1,66 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Transformers\V2; - -use FireflyIII\Models\TransactionCurrency; -use Illuminate\Support\Collection; - -/** - * Class CurrencyTransformer - * - * @deprecated - */ -class CurrencyTransformer extends AbstractTransformer -{ - public function collectMetaData(Collection $objects): Collection - { - return $objects; - } - - /** - * Transform the currency. - */ - public function transform(TransactionCurrency $currency): array - { - return [ - 'id' => $currency->id, - 'created_at' => $currency->created_at->toAtomString(), - 'updated_at' => $currency->updated_at->toAtomString(), - 'native' => $currency->userGroupNative, - 'default' => $currency->userGroupNative, - 'enabled' => $currency->userGroupEnabled, - 'name' => $currency->name, - 'code' => $currency->code, - 'symbol' => $currency->symbol, - 'decimal_places' => $currency->decimal_places, - 'links' => [ - [ - 'rel' => 'self', - 'uri' => '/currencies/'.$currency->id, - ], - ], - ]; - } -} diff --git a/app/Transformers/V2/ExchangeRateTransformer.php b/app/Transformers/V2/ExchangeRateTransformer.php deleted file mode 100644 index 7abed13832..0000000000 --- a/app/Transformers/V2/ExchangeRateTransformer.php +++ /dev/null @@ -1,75 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Transformers\V2; - -use FireflyIII\Models\CurrencyExchangeRate; -use Illuminate\Support\Collection; - -/** - * Class AccountTransformer - * - * @deprecated - */ -class ExchangeRateTransformer extends AbstractTransformer -{ - /** - * This method collects meta-data for one or all accounts in the transformer's collection. - */ - public function collectMetaData(Collection $objects): Collection - { - return $objects; - } - - /** - * Transform the account. - */ - public function transform(CurrencyExchangeRate $rate): array - { - return [ - 'id' => (string) $rate->id, - 'created_at' => $rate->created_at->toAtomString(), - 'updated_at' => $rate->updated_at->toAtomString(), - - 'from_currency_id' => (string) $rate->fromCurrency->id, - 'from_currency_code' => $rate->fromCurrency->code, - 'from_currency_symbol' => $rate->fromCurrency->symbol, - 'from_currency_decimal_places' => $rate->fromCurrency->decimal_places, - - 'to_currency_id' => (string) $rate->toCurrency->id, - 'to_currency_code' => $rate->toCurrency->code, - 'to_currency_symbol' => $rate->toCurrency->symbol, - 'to_currency_decimal_places' => $rate->toCurrency->decimal_places, - - 'rate' => $rate->rate, - 'date' => $rate->date->toAtomString(), - 'links' => [ - [ - 'rel' => 'self', - 'uri' => sprintf('/exchange-rates/%s', $rate->id), - ], - ], - ]; - } -} diff --git a/app/Transformers/V2/PiggyBankTransformer.php b/app/Transformers/V2/PiggyBankTransformer.php deleted file mode 100644 index 26e927b0d4..0000000000 --- a/app/Transformers/V2/PiggyBankTransformer.php +++ /dev/null @@ -1,273 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Transformers\V2; - -use Carbon\Carbon; -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\Account; -use FireflyIII\Models\AccountMeta; -use FireflyIII\Models\Note; -use FireflyIII\Models\ObjectGroup; -use FireflyIII\Models\PiggyBank; -use FireflyIII\Models\PiggyBankRepetition; -use FireflyIII\Models\TransactionCurrency; -use FireflyIII\Models\TransactionJournal; -use FireflyIII\Support\Http\Api\ExchangeRateConverter; -use Illuminate\Support\Collection; -use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Log; - -/** - * Class PiggyBankTransformer - * - * @deprecated - */ -class PiggyBankTransformer extends AbstractTransformer -{ - // private AccountRepositoryInterface $accountRepos; - // private CurrencyRepositoryInterface $currencyRepos; - // private PiggyBankRepositoryInterface $piggyRepos; - private array $accounts; - private ExchangeRateConverter $converter; - private array $currencies; - private TransactionCurrency $default; - private array $groups; - private array $notes; - private array $repetitions; - - /** - * PiggyBankTransformer constructor. - */ - public function __construct() - { - $this->notes = []; - $this->accounts = []; - $this->groups = []; - $this->currencies = []; - $this->repetitions = []; - // $this-> - // $this->currencyRepos = app(CurrencyRepositoryInterface::class); - // $this->piggyRepos = app(PiggyBankRepositoryInterface::class); - } - - public function collectMetaData(Collection $objects): Collection - { - // TODO move to repository (does not exist yet) - $piggyBanks = $objects->pluck('id')->toArray(); - $accountInfo = Account::whereIn('id', $objects->pluck('account_id')->toArray())->get(); - $currencyPreferences = AccountMeta::where('name', '"currency_id"')->whereIn('account_id', $objects->pluck('account_id')->toArray())->get(); - $currencies = []; - - /** @var Account $account */ - foreach ($accountInfo as $account) { - $id = $account->id; - $this->accounts[$id] = [ - 'name' => $account->name, - ]; - } - - /** @var AccountMeta $preference */ - foreach ($currencyPreferences as $preference) { - $currencyId = (int) $preference->data; - $accountId = $preference->account_id; - $currencies[$currencyId] ??= TransactionJournal::find($currencyId); - $this->currencies[$accountId] = $currencies[$currencyId]; - } - - // grab object groups: - $set = DB::table('object_groupables') - ->leftJoin('object_groups', 'object_groups.id', '=', 'object_groupables.object_group_id') - ->where('object_groupables.object_groupable_type', PiggyBank::class) - ->get(['object_groupables.*', 'object_groups.title', 'object_groups.order']) - ; - - /** @var ObjectGroup $entry */ - foreach ($set as $entry) { - $piggyBankId = (int) $entry->object_groupable_id; - $id = (int) $entry->object_group_id; - $order = $entry->order; - $this->groups[$piggyBankId] = [ - 'object_group_id' => (string) $id, - 'object_group_title' => $entry->title, - 'object_group_order' => $order, - ]; - } - - // grab repetitions (for current amount): - $repetitions = PiggyBankRepetition::whereIn('piggy_bank_id', $piggyBanks)->get(); - if ('en_US' === config('app.fallback_locale')) { - throw new FireflyException('[d] Piggy bank repetitions are EOL.'); - } - - /** @var PiggyBankRepetition $repetition */ - foreach ($repetitions as $repetition) { - $this->repetitions[$repetition->piggy_bank_id] = [ - 'amount' => $repetition->current_amount, - ]; - } - - // grab notes - // continue with notes - $notes = Note::whereNoteableType(PiggyBank::class)->whereIn('noteable_id', array_keys($piggyBanks))->get(); - - /** @var Note $note */ - foreach ($notes as $note) { - $id = $note->noteable_id; - $this->notes[$id] = $note; - } - - Log::debug(sprintf('Created new ExchangeRateConverter in %s', __METHOD__)); - $this->default = app('amount')->getNativeCurrencyByUserGroup(auth()->user()->userGroup); - $this->converter = new ExchangeRateConverter(); - - return $objects; - } - - /** - * Transform the piggy bank. - * - * @throws FireflyException - */ - public function transform(PiggyBank $piggyBank): array - { - // $account = $piggyBank->account; - // $this->accountRepos->setUser($account->user); - // $this->currencyRepos->setUser($account->user); - // $this->piggyRepos->setUser($account->user); - - // get currency from account, or use default. - // $currency = $this->accountRepos->getAccountCurrency($account) ?? app('amount')->getNativeCurrencyByUser($account->user); - - // note - // $notes = $this->piggyRepos->getNoteText($piggyBank); - // $notes = '' === $notes ? null : $notes; - - // $objectGroupId = null; - // $objectGroupOrder = null; - // $objectGroupTitle = null; - // /** @var ObjectGroup $objectGroup */ - // $objectGroup = $piggyBank->objectGroups->first(); - // if (null !== $objectGroup) { - // $objectGroupId = (int)$objectGroup->id; - // $objectGroupOrder = (int)$objectGroup->order; - // $objectGroupTitle = $objectGroup->title; - // } - - // get currently saved amount: - // $currentAmount = app('steam')->bcround($this->piggyRepos->getCurrentAmount($piggyBank), $currency->decimal_places); - - $percentage = null; - $leftToSave = null; - $nativeLeftToSave = null; - $savePerMonth = null; - $nativeSavePerMonth = null; - $startDate = $piggyBank->start_date?->format('Y-m-d'); - $targetDate = $piggyBank->target_date?->format('Y-m-d'); - $accountId = $piggyBank->account_id; - $accountName = $this->accounts[$accountId]['name'] ?? null; - $currency = $this->currencies[$accountId] ?? $this->default; - $currentAmount = app('steam')->bcround($this->repetitions[$piggyBank->id]['amount'] ?? '0', $currency->decimal_places); - $nativeCurrentAmount = $this->converter->convert($this->default, $currency, today(), $currentAmount); - $targetAmount = $piggyBank->target_amount; - $nativeTargetAmount = $this->converter->convert($this->default, $currency, today(), $targetAmount); - $note = $this->notes[$piggyBank->id] ?? null; - $group = $this->groups[$piggyBank->id] ?? null; - - if (0 !== bccomp($targetAmount, '0')) { // target amount is not 0.00 - $leftToSave = bcsub($targetAmount, (string) $currentAmount); - $nativeLeftToSave = $this->converter->convert($this->default, $currency, today(), $leftToSave); - $percentage = (int) bcmul(bcdiv((string) $currentAmount, $targetAmount), '100'); - $savePerMonth = $this->getSuggestedMonthlyAmount($currentAmount, $targetAmount, $piggyBank->start_date, $piggyBank->target_date); - $nativeSavePerMonth = $this->converter->convert($this->default, $currency, today(), $savePerMonth); - } - $this->converter->summarize(); - - return [ - 'id' => (string) $piggyBank->id, - 'created_at' => $piggyBank->created_at->toAtomString(), - 'updated_at' => $piggyBank->updated_at->toAtomString(), - 'account_id' => (string) $piggyBank->account_id, - 'account_name' => $accountName, - 'name' => $piggyBank->name, - 'currency_id' => (string) $currency->id, - 'currency_code' => $currency->code, - 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => $currency->decimal_places, - 'native_currency_id' => (string) $this->default->id, - 'native_currency_code' => $this->default->code, - 'native_currency_symbol' => $this->default->symbol, - 'native_currency_decimal_places' => $this->default->decimal_places, - 'current_amount' => $currentAmount, - 'native_current_amount' => $nativeCurrentAmount, - 'target_amount' => $targetAmount, - 'native_target_amount' => $nativeTargetAmount, - 'percentage' => $percentage, - 'left_to_save' => $leftToSave, - 'native_left_to_save' => $nativeLeftToSave, - 'save_per_month' => $savePerMonth, - 'native_save_per_month' => $nativeSavePerMonth, - 'start_date' => $startDate, - 'target_date' => $targetDate, - 'order' => $piggyBank->order, - 'active' => $piggyBank->active, - 'notes' => $note, - 'object_group_id' => $group ? $group['object_group_id'] : null, - 'object_group_order' => $group ? $group['object_group_order'] : null, - 'object_group_title' => $group ? $group['object_group_title'] : null, - 'links' => [ - [ - 'rel' => 'self', - 'uri' => '/piggy_banks/'.$piggyBank->id, - ], - ], - ]; - } - - private function getSuggestedMonthlyAmount(string $currentAmount, string $targetAmount, ?Carbon $startDate, ?Carbon $targetDate): string - { - $savePerMonth = '0'; - if (!$targetDate instanceof Carbon) { - return '0'; - } - if (bccomp($currentAmount, $targetAmount) < 1) { - $now = today(config('app.timezone')); - $startDate = $startDate instanceof Carbon && $startDate->gte($now) ? $startDate : $now; - $diffInMonths = (int) $startDate->diffInMonths($targetDate); - $remainingAmount = bcsub($targetAmount, $currentAmount); - - // more than 1 month to go and still need money to save: - if ($diffInMonths > 0 && 1 === bccomp($remainingAmount, '0')) { - $savePerMonth = bcdiv($remainingAmount, (string) $diffInMonths); - } - - // less than 1 month to go but still need money to save: - if (0 === $diffInMonths && 1 === bccomp($remainingAmount, '0')) { - $savePerMonth = $remainingAmount; - } - } - - return $savePerMonth; - } -} diff --git a/app/Transformers/V2/PreferenceTransformer.php b/app/Transformers/V2/PreferenceTransformer.php deleted file mode 100644 index a93c7e1aec..0000000000 --- a/app/Transformers/V2/PreferenceTransformer.php +++ /dev/null @@ -1,56 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Transformers\V2; - -use FireflyIII\Models\Preference; -use Illuminate\Support\Collection; - -/** - * Class PreferenceTransformer - * - * @deprecated - */ -class PreferenceTransformer extends AbstractTransformer -{ - public function collectMetaData(Collection $objects): Collection - { - // TODO: Implement collectMetaData() method. - return $objects; - } - - /** - * Transform the preference - */ - public function transform(Preference $preference): array - { - return [ - 'id' => $preference->id, - 'created_at' => $preference->created_at->toAtomString(), - 'updated_at' => $preference->updated_at->toAtomString(), - 'name' => $preference->name, - 'data' => $preference->data, - ]; - } -} diff --git a/app/Transformers/V2/TransactionGroupTransformer.php b/app/Transformers/V2/TransactionGroupTransformer.php deleted file mode 100644 index e9f3b12128..0000000000 --- a/app/Transformers/V2/TransactionGroupTransformer.php +++ /dev/null @@ -1,625 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Transformers\V2; - -use Carbon\Carbon; -use FireflyIII\Enums\TransactionTypeEnum; -use FireflyIII\Exceptions\FireflyException; -use FireflyIII\Models\Budget; -use FireflyIII\Models\Category; -use FireflyIII\Models\Location; -use FireflyIII\Models\Note; -use FireflyIII\Models\Transaction; -use FireflyIII\Models\TransactionCurrency; -use FireflyIII\Models\TransactionGroup; -use FireflyIII\Models\TransactionJournal; -use FireflyIII\Models\TransactionJournalMeta; -use FireflyIII\Support\Http\Api\ExchangeRateConverter; -use FireflyIII\Support\NullArrayObject; -use Illuminate\Support\Collection; -use Illuminate\Support\Facades\DB; -use stdClass; - -/** - * Class TransactionGroupTransformer - * - * @deprecated - */ -class TransactionGroupTransformer extends AbstractTransformer -{ - private array $accountTypes = []; // account types collection. - private ExchangeRateConverter $converter; // collection of all journals and some important meta-data. - private array $currencies = []; - private TransactionCurrency $default; // collection of all currencies for this transformer. - private array $journals = []; - private array $meta = []; - - // private array $currencies = []; - // private array $transactionTypes = []; - private array $notes = []; - private array $objects = []; - // private array $locations = []; - private array $tags = []; - // private array $amounts = []; - // private array $foreignAmounts = []; - // private array $journalCurrencies = []; - // private array $foreignCurrencies = []; - - public function collectMetaData(Collection $objects): Collection - { - $collectForObjects = false; - - /** @var array|TransactionGroup $object */ - foreach ($objects as $object) { - if (is_array($object)) { - $this->collectForArray($object); - } - if ($object instanceof TransactionGroup) { - $this->collectForObject($object); - $collectForObjects = true; - } - } - - $this->default = app('amount')->getNativeCurrency(); - $this->converter = new ExchangeRateConverter(); - - $this->collectAllMetaData(); - $this->collectAllNotes(); - $this->collectAllLocations(); - $this->collectAllTags(); - if ($collectForObjects) { - $this->collectAllCurrencies(); - // $this->collectAllAmounts(); - // $this->collectTransactionTypes(); - // $this->collectAccounts(); - // source accounts - // destination accounts - } - - return $objects; - } - - private function collectForArray(array $object): void - { - foreach ($object['sums'] as $sum) { - $this->currencies[(int) $sum['currency_id']] ??= TransactionCurrency::find($sum['currency_id']); - } - - /** @var array $transaction */ - foreach ($object['transactions'] as $transaction) { - $this->journals[(int) $transaction['transaction_journal_id']] = []; - } - } - - private function collectForObject(TransactionGroup $object): void - { - foreach ($object->transactionJournals as $journal) { - $this->journals[$journal->id] = []; - $this->objects[] = $journal; - } - } - - private function collectAllMetaData(): void - { - $meta = TransactionJournalMeta::whereIn('transaction_journal_id', array_keys($this->journals))->get(); - - /** @var TransactionJournalMeta $entry */ - foreach ($meta as $entry) { - $id = $entry->transaction_journal_id; - $this->journals[$id]['meta'] ??= []; - $this->journals[$id]['meta'][$entry->name] = $entry->data; - } - } - - private function collectAllNotes(): void - { - // grab all notes for all journals: - $notes = Note::whereNoteableType(TransactionJournal::class)->whereIn('noteable_id', array_keys($this->journals))->get(); - - /** @var Note $note */ - foreach ($notes as $note) { - $id = $note->noteable_id; - $this->journals[$id]['notes'] = $note->text; - } - } - - private function collectAllLocations(): void - { - // grab all locations for all journals: - $locations = Location::whereLocatableType(TransactionJournal::class)->whereIn('locatable_id', array_keys($this->journals))->get(); - - /** @var Location $location */ - foreach ($locations as $location) { - $id = $location->locatable_id; - $this->journals[$id]['location'] = [ - 'latitude' => $location->latitude, - 'longitude' => $location->longitude, - 'zoom_level' => $location->zoom_level, - ]; - } - } - - private function collectAllTags(): void - { - // grab all tags for all journals: - $tags = DB::table('tag_transaction_journal') - ->leftJoin('tags', 'tags.id', 'tag_transaction_journal.tag_id') - ->whereIn('tag_transaction_journal.transaction_journal_id', array_keys($this->journals)) - ->get(['tag_transaction_journal.transaction_journal_id', 'tags.tag']) - ; - - /** @var stdClass $tag */ - foreach ($tags as $tag) { - $id = (int) $tag->transaction_journal_id; - $this->journals[$id]['tags'][] = $tag->tag; - } - } - - private function collectAllCurrencies(): void - { - /** @var TransactionJournal $journal */ - foreach ($this->objects as $journal) { - $id = $journal->id; - $this->journals[$id]['reconciled'] = false; - $this->journals[$id]['foreign_amount'] = null; - $this->journals[$id]['foreign_currency_id'] = null; - $this->journals[$id]['amount'] = null; - $this->journals[$id]['currency_id'] = null; - $this->journals[$id]['type'] = $journal->transactionType->type; - $this->journals[$id]['budget_id'] = null; - $this->journals[$id]['budget_name'] = null; - $this->journals[$id]['category_id'] = null; - $this->journals[$id]['category_name'] = null; - $this->journals[$id]['bill_id'] = null; - $this->journals[$id]['bill_name'] = null; - - // collect budget: - /** @var null|Budget $budget */ - $budget = $journal->budgets()->first(); - if (null !== $budget) { - $this->journals[$id]['budget_id'] = (string) $budget->id; - $this->journals[$id]['budget_name'] = $budget->name; - } - - // collect category: - /** @var null|Category $category */ - $category = $journal->categories()->first(); - if (null !== $category) { - $this->journals[$id]['category_id'] = (string) $category->id; - $this->journals[$id]['category_name'] = $category->name; - } - - // collect bill: - if (null !== $journal->bill_id) { - $bill = $journal->bill; - $this->journals[$id]['bill_id'] = (string) $bill->id; - $this->journals[$id]['bill_name'] = $bill->name; - } - - /** @var Transaction $transaction */ - foreach ($journal->transactions as $transaction) { - if (-1 === bccomp((string) $transaction->amount, '0')) { - // only collect source account info - $account = $transaction->account; - $this->accountTypes[$account->account_type_id] ??= $account->accountType->type; - $this->journals[$id]['source_account_name'] = $account->name; - $this->journals[$id]['source_account_iban'] = $account->iban; - $this->journals[$id]['source_account_type'] = $this->accountTypes[$account->account_type_id]; - $this->journals[$id]['source_account_id'] = $transaction->account_id; - $this->journals[$id]['reconciled'] = $transaction->reconciled; - - continue; - } - - // add account - $account = $transaction->account; - $this->accountTypes[$account->account_type_id] ??= $account->accountType->type; - $this->journals[$id]['destination_account_name'] = $account->name; - $this->journals[$id]['destination_account_iban'] = $account->iban; - $this->journals[$id]['destination_account_type'] = $this->accountTypes[$account->account_type_id]; - $this->journals[$id]['destination_account_id'] = $transaction->account_id; - - // find and set currency - $currencyId = $transaction->transaction_currency_id; - $this->currencies[$currencyId] ??= $transaction->transactionCurrency; - $this->journals[$id]['currency_id'] = $currencyId; - $this->journals[$id]['amount'] = $transaction->amount; - // find and set foreign currency - if (null !== $transaction->foreign_currency_id) { - $foreignCurrencyId = $transaction->foreign_currency_id; - $this->currencies[$foreignCurrencyId] ??= $transaction->foreignCurrency; - $this->journals[$id]['foreign_currency_id'] = $foreignCurrencyId; - $this->journals[$id]['foreign_amount'] = $transaction->foreign_amount; - } - - // find and set destination account info. - } - } - } - - public function transform(array|TransactionGroup $group): array - { - if (is_array($group)) { - $first = reset($group['transactions']); - - return [ - 'id' => (string) $group['id'], - 'created_at' => $group['created_at']->toAtomString(), - 'updated_at' => $group['updated_at']->toAtomString(), - 'user' => (string) $first['user_id'], - 'user_group' => (string) $first['user_group_id'], - 'group_title' => $group['title'] ?? null, - 'transactions' => $this->transformTransactions($group['transactions'] ?? []), - 'links' => [ - [ - 'rel' => 'self', - 'uri' => sprintf('/transactions/%d', $group['id']), - ], - ], - ]; - } - - return [ - 'id' => (string) $group->id, - 'created_at' => $group->created_at->toAtomString(), - 'updated_at' => $group->created_at->toAtomString(), - 'user' => (string) $group->user_id, - 'user_group' => (string) $group->user_group_id, - 'group_title' => $group->title ?? null, - 'transactions' => $this->transformJournals($group), - 'links' => [ - [ - 'rel' => 'self', - 'uri' => sprintf('/transactions/%d', $group->id), - ], - ], - ]; - } - - private function transformTransactions(array $transactions): array - { - $return = []; - - /** @var array $transaction */ - foreach ($transactions as $transaction) { - $return[] = $this->transformTransaction($transaction); - } - - return $return; - } - - /** - * @throws FireflyException - * - * @SuppressWarnings("PHPMD.ExcessiveMethodLength") - */ - private function transformTransaction(array $transaction): array - { - $transaction = new NullArrayObject($transaction); - $type = $this->stringFromArray($transaction, 'transaction_type_type', TransactionTypeEnum::WITHDRAWAL->value); - $journalId = (int) $transaction['transaction_journal_id']; - $meta = new NullArrayObject($this->meta[$journalId] ?? []); - - /** - * Convert and use amount: - */ - $amount = app('steam')->positive((string) ($transaction['amount'] ?? '0')); - $currencyId = (int) $transaction['currency_id']; - $nativeAmount = $this->converter->convert($this->default, $this->currencies[$currencyId], $transaction['date'], $amount); - $foreignAmount = null; - $nativeForeignAmount = null; - if (null !== $transaction['foreign_amount']) { - $foreignCurrencyId = (int) $transaction['foreign_currency_id']; - $foreignAmount = app('steam')->positive($transaction['foreign_amount']); - $nativeForeignAmount = $this->converter->convert($this->default, $this->currencies[$foreignCurrencyId], $transaction['date'], $foreignAmount); - } - $this->converter->summarize(); - - $longitude = null; - $latitude = null; - $zoomLevel = null; - if (array_key_exists('location', $this->journals[$journalId])) { - $latitude = (string) $this->journals[$journalId]['location']['latitude']; - $longitude = (string) $this->journals[$journalId]['location']['longitude']; - $zoomLevel = $this->journals[$journalId]['location']['zoom_level']; - } - - return [ - 'user' => (string) $transaction['user_id'], - 'user_group' => (string) $transaction['user_group_id'], - 'transaction_journal_id' => (string) $transaction['transaction_journal_id'], - 'type' => strtolower((string) $type), - 'date' => $transaction['date']->toAtomString(), - 'order' => $transaction['order'], - 'amount' => $amount, - 'native_amount' => $nativeAmount, - 'foreign_amount' => $foreignAmount, - 'native_foreign_amount' => $nativeForeignAmount, - 'currency_id' => (string) $transaction['currency_id'], - 'currency_code' => $transaction['currency_code'], - 'currency_name' => $transaction['currency_name'], - 'currency_symbol' => $transaction['currency_symbol'], - 'currency_decimal_places' => (int) $transaction['currency_decimal_places'], - - // converted to native currency - 'native_currency_id' => (string) $this->default->id, - 'native_currency_code' => $this->default->code, - 'native_currency_name' => $this->default->name, - 'native_currency_symbol' => $this->default->symbol, - 'native_currency_decimal_places' => $this->default->decimal_places, - - // foreign currency amount: - 'foreign_currency_id' => $this->stringFromArray($transaction, 'foreign_currency_id', null), - 'foreign_currency_code' => $transaction['foreign_currency_code'], - 'foreign_currency_name' => $transaction['foreign_currency_name'], - 'foreign_currency_symbol' => $transaction['foreign_currency_symbol'], - 'foreign_currency_decimal_places' => $transaction['foreign_currency_decimal_places'], - - // foreign converted to native: - 'description' => $transaction['description'], - 'source_id' => (string) $transaction['source_account_id'], - 'source_name' => $transaction['source_account_name'], - 'source_iban' => $transaction['source_account_iban'], - 'source_type' => $transaction['source_account_type'], - 'destination_id' => (string) $transaction['destination_account_id'], - 'destination_name' => $transaction['destination_account_name'], - 'destination_iban' => $transaction['destination_account_iban'], - 'destination_type' => $transaction['destination_account_type'], - 'budget_id' => $this->stringFromArray($transaction, 'budget_id', null), - 'budget_name' => $transaction['budget_name'], - 'category_id' => $this->stringFromArray($transaction, 'category_id', null), - 'category_name' => $transaction['category_name'], - 'bill_id' => $this->stringFromArray($transaction, 'bill_id', null), - 'bill_name' => $transaction['bill_name'], - 'reconciled' => $transaction['reconciled'], - 'notes' => $this->notes[$journalId] ?? null, - 'tags' => $this->tags[$journalId] ?? [], - 'internal_reference' => $meta['internal_reference'], - 'external_id' => $meta['external_id'], - 'original_source' => $meta['original_source'], - 'recurrence_id' => $meta['recurrence_id'], - 'recurrence_total' => $meta['recurrence_total'], - 'recurrence_count' => $meta['recurrence_count'], - 'external_url' => $meta['external_url'], - 'import_hash_v2' => $meta['import_hash_v2'], - 'sepa_cc' => $meta['sepa_cc'], - 'sepa_ct_op' => $meta['sepa_ct_op'], - 'sepa_ct_id' => $meta['sepa_ct_id'], - 'sepa_db' => $meta['sepa_db'], - 'sepa_country' => $meta['sepa_country'], - 'sepa_ep' => $meta['sepa_ep'], - 'sepa_ci' => $meta['sepa_ci'], - 'sepa_batch_id' => $meta['sepa_batch_id'], - 'interest_date' => $this->date($meta['interest_date']), - 'book_date' => $this->date($meta['book_date']), - 'process_date' => $this->date($meta['process_date']), - 'due_date' => $this->date($meta['due_date']), - 'payment_date' => $this->date($meta['payment_date']), - 'invoice_date' => $this->date($meta['invoice_date']), - - // location data - 'longitude' => $longitude, - 'latitude' => $latitude, - 'zoom_level' => $zoomLevel, - // - // 'has_attachments' => $this->hasAttachments((int) $row['transaction_journal_id']), - ]; - } - - /** - * TODO also in the old transformer. - * - * Used to extract a value from the given array, and fall back on a sensible default or NULL - * if it can't be helped. - */ - private function stringFromArray(NullArrayObject $array, string $key, ?string $default): ?string - { - // app('log')->debug(sprintf('%s: %s', $key, var_export($array[$key], true))); - if (null === $array[$key] && null === $default) { - return null; - } - if (0 === $array[$key]) { - return $default; - } - if ('0' === $array[$key]) { - return $default; - } - if (null !== $array[$key]) { - return (string) $array[$key]; - } - - if (null !== $default) { - return $default; - } - - return null; - } - - private function date(?string $string): ?Carbon - { - if (null === $string) { - return null; - } - // app('log')->debug(sprintf('Now in date("%s")', $string)); - if (10 === strlen($string)) { - $res = Carbon::createFromFormat('Y-m-d', $string, config('app.timezone')); - if (!$res instanceof Carbon) { - return null; - } - - return $res; - } - if (25 === strlen($string)) { - return Carbon::parse($string, config('app.timezone')); - } - if (19 === strlen($string) && str_contains($string, 'T')) { - $res = Carbon::createFromFormat('Y-m-d\TH:i:s', substr($string, 0, 19), config('app.timezone')); - if (!$res instanceof Carbon) { - return null; - } - - return $res; - } - - // 2022-01-01 01:01:01 - $res = Carbon::createFromFormat('Y-m-d H:i:s', substr($string, 0, 19), config('app.timezone')); - if (!$res instanceof Carbon) { - return null; - } - - return $res; - } - - private function transformJournals(TransactionGroup $group): array - { - $return = []; - - /** @var TransactionJournal $journal */ - foreach ($group->transactionJournals as $journal) { - $return[] = $this->transformJournal($journal); - } - - return $return; - } - - /** - * @throws FireflyException - * - * @SuppressWarnings("PHPMD.ExcessiveMethodLength") - */ - private function transformJournal(TransactionJournal $journal): array - { - $id = $journal->id; - - /** @var null|TransactionCurrency $foreignCurrency */ - $foreignCurrency = null; - - /** @var TransactionCurrency $currency */ - $currency = $this->currencies[$this->journals[$id]['currency_id']]; - $nativeForeignAmount = null; - $amount = $this->journals[$journal->id]['amount']; - $foreignAmount = $this->journals[$journal->id]['foreign_amount']; - $meta = new NullArrayObject($this->meta[$id] ?? []); - - // has foreign amount? - if (null !== $foreignAmount) { - $foreignCurrency = $this->currencies[$this->journals[$id]['foreign_currency_id']]; - $nativeForeignAmount = $this->converter->convert($this->default, $foreignCurrency, $journal->date, $foreignAmount); - } - - $nativeAmount = $this->converter->convert($this->default, $currency, $journal->date, $amount); - - $longitude = null; - $latitude = null; - $zoomLevel = null; - if (array_key_exists('location', $this->journals[$id])) { - $latitude = (string) $this->journals[$id]['location']['latitude']; - $longitude = (string) $this->journals[$id]['location']['longitude']; - $zoomLevel = $this->journals[$id]['location']['zoom_level']; - } - - return [ - 'user' => (string) $journal->user_id, - 'user_group' => (string) $journal->user_group_id, - 'transaction_journal_id' => (string) $journal->id, - 'type' => $this->journals[$journal->id]['type'], - 'date' => $journal->date->toAtomString(), - 'order' => $journal->order, - 'amount' => $amount, - 'native_amount' => $nativeAmount, - 'foreign_amount' => $foreignAmount, - 'native_foreign_amount' => $nativeForeignAmount, - 'currency_id' => (string) $currency->id, - 'currency_code' => $currency->code, - 'currency_name' => $currency->name, - 'currency_symbol' => $currency->symbol, - 'currency_decimal_places' => $currency->decimal_places, - - // converted to native currency - 'native_currency_id' => (string) $this->default->id, - 'native_currency_code' => $this->default->code, - 'native_currency_name' => $this->default->name, - 'native_currency_symbol' => $this->default->symbol, - 'native_currency_decimal_places' => $this->default->decimal_places, - - // foreign currency amount: - 'foreign_currency_id' => $foreignCurrency?->id, - 'foreign_currency_code' => $foreignCurrency?->code, - 'foreign_currency_name' => $foreignCurrency?->name, - 'foreign_currency_symbol' => $foreignCurrency?->symbol, - 'foreign_currency_decimal_places' => $foreignCurrency?->decimal_places, - - 'description' => $journal->description, - 'source_id' => (string) $this->journals[$id]['source_account_id'], - 'source_name' => $this->journals[$id]['source_account_name'], - 'source_iban' => $this->journals[$id]['source_account_iban'], - 'source_type' => $this->journals[$id]['source_account_type'], - - 'destination_id' => (string) $this->journals[$id]['destination_account_id'], - 'destination_name' => $this->journals[$id]['destination_account_name'], - 'destination_iban' => $this->journals[$id]['destination_account_iban'], - 'destination_type' => $this->journals[$id]['destination_account_type'], - - 'budget_id' => $this->journals[$id]['budget_id'], - 'budget_name' => $this->journals[$id]['budget_name'], - 'category_id' => $this->journals[$id]['category_id'], - 'category_name' => $this->journals[$id]['category_name'], - 'bill_id' => $this->journals[$id]['bill_id'], - 'bill_name' => $this->journals[$id]['bill_name'], - 'reconciled' => $this->journals[$id]['reconciled'], - 'notes' => $this->journals[$id]['notes'] ?? null, - 'tags' => $this->journals[$id]['tags'] ?? [], - 'internal_reference' => $meta['internal_reference'], - 'external_id' => $meta['external_id'], - 'original_source' => $meta['original_source'], - 'recurrence_id' => $meta['recurrence_id'], - 'recurrence_total' => $meta['recurrence_total'], - 'recurrence_count' => $meta['recurrence_count'], - 'external_url' => $meta['external_url'], - 'import_hash_v2' => $meta['import_hash_v2'], - 'sepa_cc' => $meta['sepa_cc'], - 'sepa_ct_op' => $meta['sepa_ct_op'], - 'sepa_ct_id' => $meta['sepa_ct_id'], - 'sepa_db' => $meta['sepa_db'], - 'sepa_country' => $meta['sepa_country'], - 'sepa_ep' => $meta['sepa_ep'], - 'sepa_ci' => $meta['sepa_ci'], - 'sepa_batch_id' => $meta['sepa_batch_id'], - 'interest_date' => $this->date($meta['interest_date']), - 'book_date' => $this->date($meta['book_date']), - 'process_date' => $this->date($meta['process_date']), - 'due_date' => $this->date($meta['due_date']), - 'payment_date' => $this->date($meta['payment_date']), - 'invoice_date' => $this->date($meta['invoice_date']), - - // location data - 'longitude' => $longitude, - 'latitude' => $latitude, - 'zoom_level' => $zoomLevel, - // - // 'has_attachments' => $this->hasAttachments((int) $row['transaction_journal_id']), - ]; - } -} diff --git a/app/Transformers/V2/UserGroupTransformer.php b/app/Transformers/V2/UserGroupTransformer.php deleted file mode 100644 index 5aba3042a9..0000000000 --- a/app/Transformers/V2/UserGroupTransformer.php +++ /dev/null @@ -1,120 +0,0 @@ -. - */ - -declare(strict_types=1); - -namespace FireflyIII\Transformers\V2; - -use FireflyIII\Enums\UserRoleEnum; -use FireflyIII\Models\GroupMembership; -use FireflyIII\Models\UserGroup; -use FireflyIII\User; -use Illuminate\Support\Collection; - -/** - * Class UserGroupTransformer - * - * @deprecated - */ -class UserGroupTransformer extends AbstractTransformer -{ - private array $inUse; - private array $memberships; - private array $membershipsVisible; - - public function __construct() - { - $this->memberships = []; - $this->membershipsVisible = []; - $this->inUse = []; - } - - public function collectMetaData(Collection $objects): Collection - { - if (auth()->check()) { - // collect memberships so they can be listed in the group. - /** @var User $user */ - $user = auth()->user(); - - /** @var UserGroup $userGroup */ - foreach ($objects as $userGroup) { - $userGroupId = $userGroup->id; - $this->inUse[$userGroupId] = $user->user_group_id === $userGroupId; - $access = $user->hasRoleInGroupOrOwner($userGroup, UserRoleEnum::VIEW_MEMBERSHIPS) || $user->hasRole('owner'); - $this->membershipsVisible[$userGroupId] = $access; - if ($access) { - $groupMemberships = $userGroup->groupMemberships()->get(); - - /** @var GroupMembership $groupMembership */ - foreach ($groupMemberships as $groupMembership) { - $this->memberships[$userGroupId][] = [ - 'user_id' => (string) $groupMembership->user_id, - 'user_email' => $groupMembership->user->email, - 'role' => $groupMembership->userRole->title, - 'you' => $groupMembership->user_id === $user->id, - ]; - } - } - } - $this->mergeMemberships(); - } - - return $objects; - } - - private function mergeMemberships(): void - { - $new = []; - foreach ($this->memberships as $groupId => $members) { - $new[$groupId] ??= []; - - foreach ($members as $member) { - $mail = $member['user_email']; - $new[$groupId][$mail] ??= [ - 'user_id' => $member['user_id'], - 'user_email' => $member['user_email'], - 'you' => $member['you'], - 'roles' => [], - ]; - $new[$groupId][$mail]['roles'][] = $member['role']; - } - } - $this->memberships = $new; - } - - /** - * Transform the user group. - */ - public function transform(UserGroup $userGroup): array - { - return [ - 'id' => $userGroup->id, - 'created_at' => $userGroup->created_at->toAtomString(), - 'updated_at' => $userGroup->updated_at->toAtomString(), - 'in_use' => $this->inUse[$userGroup->id] ?? false, - 'title' => $userGroup->title, - 'can_see_members' => $this->membershipsVisible[$userGroup->id] ?? false, - 'members' => array_values($this->memberships[$userGroup->id] ?? []), - ]; - // if the user has a specific role in this group, then collect the memberships. - } -} diff --git a/app/Validation/TransactionValidation.php b/app/Validation/TransactionValidation.php index c56c976c16..5352c0e9c1 100644 --- a/app/Validation/TransactionValidation.php +++ b/app/Validation/TransactionValidation.php @@ -224,7 +224,7 @@ trait TransactionValidation /** @var AccountRepository $accountRepository */ $accountRepository = app(AccountRepositoryInterface::class); - $defaultCurrency = app('amount')->getNativeCurrency(); + $defaultCurrency = app('amount')->getPrimaryCurrency(); $sourceCurrency = $accountRepository->getAccountCurrency($source) ?? $defaultCurrency; $destinationCurrency = $accountRepository->getAccountCurrency($destination) ?? $defaultCurrency; // if both accounts have the same currency, continue. diff --git a/composer.lock b/composer.lock index 25e763c963..28064be042 100644 --- a/composer.lock +++ b/composer.lock @@ -6407,16 +6407,16 @@ }, { "name": "symfony/cache", - "version": "v7.3.1", + "version": "v7.3.2", "source": { "type": "git", "url": "https://github.com/symfony/cache.git", - "reference": "a7c6caa9d6113cebfb3020b427bcb021ebfdfc9e" + "reference": "6621a2bee5373e3e972b2ae5dbedd5ac899d8cb6" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/cache/zipball/a7c6caa9d6113cebfb3020b427bcb021ebfdfc9e", - "reference": "a7c6caa9d6113cebfb3020b427bcb021ebfdfc9e", + "url": "https://api.github.com/repos/symfony/cache/zipball/6621a2bee5373e3e972b2ae5dbedd5ac899d8cb6", + "reference": "6621a2bee5373e3e972b2ae5dbedd5ac899d8cb6", "shasum": "" }, "require": { @@ -6485,7 +6485,7 @@ "psr6" ], "support": { - "source": "https://github.com/symfony/cache/tree/v7.3.1" + "source": "https://github.com/symfony/cache/tree/v7.3.2" }, "funding": [ { @@ -6496,12 +6496,16 @@ "url": "https://github.com/fabpot", "type": "github" }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, { "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "type": "tidelift" } ], - "time": "2025-06-27T19:55:54+00:00" + "time": "2025-07-30T17:13:41+00:00" }, { "name": "symfony/cache-contracts", @@ -6655,16 +6659,16 @@ }, { "name": "symfony/console", - "version": "v7.3.1", + "version": "v7.3.2", "source": { "type": "git", "url": "https://github.com/symfony/console.git", - "reference": "9e27aecde8f506ba0fd1d9989620c04a87697101" + "reference": "5f360ebc65c55265a74d23d7fe27f957870158a1" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/console/zipball/9e27aecde8f506ba0fd1d9989620c04a87697101", - "reference": "9e27aecde8f506ba0fd1d9989620c04a87697101", + "url": "https://api.github.com/repos/symfony/console/zipball/5f360ebc65c55265a74d23d7fe27f957870158a1", + "reference": "5f360ebc65c55265a74d23d7fe27f957870158a1", "shasum": "" }, "require": { @@ -6729,7 +6733,7 @@ "terminal" ], "support": { - "source": "https://github.com/symfony/console/tree/v7.3.1" + "source": "https://github.com/symfony/console/tree/v7.3.2" }, "funding": [ { @@ -6740,12 +6744,16 @@ "url": "https://github.com/fabpot", "type": "github" }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, { "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "type": "tidelift" } ], - "time": "2025-06-27T19:55:54+00:00" + "time": "2025-07-30T17:13:41+00:00" }, { "name": "symfony/css-selector", @@ -6881,16 +6889,16 @@ }, { "name": "symfony/error-handler", - "version": "v7.3.1", + "version": "v7.3.2", "source": { "type": "git", "url": "https://github.com/symfony/error-handler.git", - "reference": "35b55b166f6752d6aaf21aa042fc5ed280fce235" + "reference": "0b31a944fcd8759ae294da4d2808cbc53aebd0c3" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/error-handler/zipball/35b55b166f6752d6aaf21aa042fc5ed280fce235", - "reference": "35b55b166f6752d6aaf21aa042fc5ed280fce235", + "url": "https://api.github.com/repos/symfony/error-handler/zipball/0b31a944fcd8759ae294da4d2808cbc53aebd0c3", + "reference": "0b31a944fcd8759ae294da4d2808cbc53aebd0c3", "shasum": "" }, "require": { @@ -6938,7 +6946,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/v7.3.1" + "source": "https://github.com/symfony/error-handler/tree/v7.3.2" }, "funding": [ { @@ -6949,12 +6957,16 @@ "url": "https://github.com/fabpot", "type": "github" }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, { "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "type": "tidelift" } ], - "time": "2025-06-13T07:48:40+00:00" + "time": "2025-07-07T08:17:57+00:00" }, { "name": "symfony/event-dispatcher", @@ -7114,16 +7126,16 @@ }, { "name": "symfony/expression-language", - "version": "v7.3.0", + "version": "v7.3.2", "source": { "type": "git", "url": "https://github.com/symfony/expression-language.git", - "reference": "26f4884a455e755e630a5fc372df124a3578da2e" + "reference": "32d2d19c62e58767e6552166c32fb259975d2b23" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/expression-language/zipball/26f4884a455e755e630a5fc372df124a3578da2e", - "reference": "26f4884a455e755e630a5fc372df124a3578da2e", + "url": "https://api.github.com/repos/symfony/expression-language/zipball/32d2d19c62e58767e6552166c32fb259975d2b23", + "reference": "32d2d19c62e58767e6552166c32fb259975d2b23", "shasum": "" }, "require": { @@ -7158,7 +7170,7 @@ "description": "Provides an engine that can compile and evaluate expressions", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/expression-language/tree/v7.3.0" + "source": "https://github.com/symfony/expression-language/tree/v7.3.2" }, "funding": [ { @@ -7169,25 +7181,29 @@ "url": "https://github.com/fabpot", "type": "github" }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, { "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "type": "tidelift" } ], - "time": "2024-10-15T11:52:45+00:00" + "time": "2025-07-10T08:29:33+00:00" }, { "name": "symfony/finder", - "version": "v7.3.0", + "version": "v7.3.2", "source": { "type": "git", "url": "https://github.com/symfony/finder.git", - "reference": "ec2344cf77a48253bbca6939aa3d2477773ea63d" + "reference": "2a6614966ba1074fa93dae0bc804227422df4dfe" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/finder/zipball/ec2344cf77a48253bbca6939aa3d2477773ea63d", - "reference": "ec2344cf77a48253bbca6939aa3d2477773ea63d", + "url": "https://api.github.com/repos/symfony/finder/zipball/2a6614966ba1074fa93dae0bc804227422df4dfe", + "reference": "2a6614966ba1074fa93dae0bc804227422df4dfe", "shasum": "" }, "require": { @@ -7222,7 +7238,7 @@ "description": "Finds files and directories via an intuitive fluent interface", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/finder/tree/v7.3.0" + "source": "https://github.com/symfony/finder/tree/v7.3.2" }, "funding": [ { @@ -7233,25 +7249,29 @@ "url": "https://github.com/fabpot", "type": "github" }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, { "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "type": "tidelift" } ], - "time": "2024-12-30T19:00:26+00:00" + "time": "2025-07-15T13:41:35+00:00" }, { "name": "symfony/http-client", - "version": "v7.3.1", + "version": "v7.3.2", "source": { "type": "git", "url": "https://github.com/symfony/http-client.git", - "reference": "4403d87a2c16f33345dca93407a8714ee8c05a64" + "reference": "1c064a0c67749923483216b081066642751cc2c7" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/http-client/zipball/4403d87a2c16f33345dca93407a8714ee8c05a64", - "reference": "4403d87a2c16f33345dca93407a8714ee8c05a64", + "url": "https://api.github.com/repos/symfony/http-client/zipball/1c064a0c67749923483216b081066642751cc2c7", + "reference": "1c064a0c67749923483216b081066642751cc2c7", "shasum": "" }, "require": { @@ -7317,7 +7337,7 @@ "http" ], "support": { - "source": "https://github.com/symfony/http-client/tree/v7.3.1" + "source": "https://github.com/symfony/http-client/tree/v7.3.2" }, "funding": [ { @@ -7328,12 +7348,16 @@ "url": "https://github.com/fabpot", "type": "github" }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, { "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "type": "tidelift" } ], - "time": "2025-06-28T07:58:39+00:00" + "time": "2025-07-15T11:36:08+00:00" }, { "name": "symfony/http-client-contracts", @@ -7415,16 +7439,16 @@ }, { "name": "symfony/http-foundation", - "version": "v7.3.1", + "version": "v7.3.2", "source": { "type": "git", "url": "https://github.com/symfony/http-foundation.git", - "reference": "23dd60256610c86a3414575b70c596e5deff6ed9" + "reference": "6877c122b3a6cc3695849622720054f6e6fa5fa6" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/http-foundation/zipball/23dd60256610c86a3414575b70c596e5deff6ed9", - "reference": "23dd60256610c86a3414575b70c596e5deff6ed9", + "url": "https://api.github.com/repos/symfony/http-foundation/zipball/6877c122b3a6cc3695849622720054f6e6fa5fa6", + "reference": "6877c122b3a6cc3695849622720054f6e6fa5fa6", "shasum": "" }, "require": { @@ -7474,7 +7498,7 @@ "description": "Defines an object-oriented layer for the HTTP specification", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/http-foundation/tree/v7.3.1" + "source": "https://github.com/symfony/http-foundation/tree/v7.3.2" }, "funding": [ { @@ -7485,25 +7509,29 @@ "url": "https://github.com/fabpot", "type": "github" }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, { "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "type": "tidelift" } ], - "time": "2025-06-23T15:07:14+00:00" + "time": "2025-07-10T08:47:49+00:00" }, { "name": "symfony/http-kernel", - "version": "v7.3.1", + "version": "v7.3.2", "source": { "type": "git", "url": "https://github.com/symfony/http-kernel.git", - "reference": "1644879a66e4aa29c36fe33dfa6c54b450ce1831" + "reference": "6ecc895559ec0097e221ed2fd5eb44d5fede083c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/http-kernel/zipball/1644879a66e4aa29c36fe33dfa6c54b450ce1831", - "reference": "1644879a66e4aa29c36fe33dfa6c54b450ce1831", + "url": "https://api.github.com/repos/symfony/http-kernel/zipball/6ecc895559ec0097e221ed2fd5eb44d5fede083c", + "reference": "6ecc895559ec0097e221ed2fd5eb44d5fede083c", "shasum": "" }, "require": { @@ -7588,7 +7616,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/v7.3.1" + "source": "https://github.com/symfony/http-kernel/tree/v7.3.2" }, "funding": [ { @@ -7599,25 +7627,29 @@ "url": "https://github.com/fabpot", "type": "github" }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, { "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "type": "tidelift" } ], - "time": "2025-06-28T08:24:55+00:00" + "time": "2025-07-31T10:45:04+00:00" }, { "name": "symfony/mailer", - "version": "v7.3.1", + "version": "v7.3.2", "source": { "type": "git", "url": "https://github.com/symfony/mailer.git", - "reference": "b5db5105b290bdbea5ab27b89c69effcf1cb3368" + "reference": "d43e84d9522345f96ad6283d5dfccc8c1cfc299b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/mailer/zipball/b5db5105b290bdbea5ab27b89c69effcf1cb3368", - "reference": "b5db5105b290bdbea5ab27b89c69effcf1cb3368", + "url": "https://api.github.com/repos/symfony/mailer/zipball/d43e84d9522345f96ad6283d5dfccc8c1cfc299b", + "reference": "d43e84d9522345f96ad6283d5dfccc8c1cfc299b", "shasum": "" }, "require": { @@ -7668,7 +7700,7 @@ "description": "Helps sending emails", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/mailer/tree/v7.3.1" + "source": "https://github.com/symfony/mailer/tree/v7.3.2" }, "funding": [ { @@ -7679,12 +7711,16 @@ "url": "https://github.com/fabpot", "type": "github" }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, { "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "type": "tidelift" } ], - "time": "2025-06-27T19:55:54+00:00" + "time": "2025-07-15T11:36:08+00:00" }, { "name": "symfony/mailgun-mailer", @@ -7757,16 +7793,16 @@ }, { "name": "symfony/mime", - "version": "v7.3.0", + "version": "v7.3.2", "source": { "type": "git", "url": "https://github.com/symfony/mime.git", - "reference": "0e7b19b2f399c31df0cdbe5d8cbf53f02f6cfcd9" + "reference": "e0a0f859148daf1edf6c60b398eb40bfc96697d1" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/mime/zipball/0e7b19b2f399c31df0cdbe5d8cbf53f02f6cfcd9", - "reference": "0e7b19b2f399c31df0cdbe5d8cbf53f02f6cfcd9", + "url": "https://api.github.com/repos/symfony/mime/zipball/e0a0f859148daf1edf6c60b398eb40bfc96697d1", + "reference": "e0a0f859148daf1edf6c60b398eb40bfc96697d1", "shasum": "" }, "require": { @@ -7821,7 +7857,7 @@ "mime-type" ], "support": { - "source": "https://github.com/symfony/mime/tree/v7.3.0" + "source": "https://github.com/symfony/mime/tree/v7.3.2" }, "funding": [ { @@ -7832,25 +7868,29 @@ "url": "https://github.com/fabpot", "type": "github" }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, { "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "type": "tidelift" } ], - "time": "2025-02-19T08:51:26+00:00" + "time": "2025-07-15T13:41:35+00:00" }, { "name": "symfony/options-resolver", - "version": "v7.3.0", + "version": "v7.3.2", "source": { "type": "git", "url": "https://github.com/symfony/options-resolver.git", - "reference": "afb9a8038025e5dbc657378bfab9198d75f10fca" + "reference": "119bcf13e67dbd188e5dbc74228b1686f66acd37" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/options-resolver/zipball/afb9a8038025e5dbc657378bfab9198d75f10fca", - "reference": "afb9a8038025e5dbc657378bfab9198d75f10fca", + "url": "https://api.github.com/repos/symfony/options-resolver/zipball/119bcf13e67dbd188e5dbc74228b1686f66acd37", + "reference": "119bcf13e67dbd188e5dbc74228b1686f66acd37", "shasum": "" }, "require": { @@ -7888,7 +7928,7 @@ "options" ], "support": { - "source": "https://github.com/symfony/options-resolver/tree/v7.3.0" + "source": "https://github.com/symfony/options-resolver/tree/v7.3.2" }, "funding": [ { @@ -7899,12 +7939,16 @@ "url": "https://github.com/fabpot", "type": "github" }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, { "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "type": "tidelift" } ], - "time": "2025-04-04T13:12:05+00:00" + "time": "2025-07-15T11:36:08+00:00" }, { "name": "symfony/polyfill-ctype", @@ -8689,16 +8733,16 @@ }, { "name": "symfony/routing", - "version": "v7.3.0", + "version": "v7.3.2", "source": { "type": "git", "url": "https://github.com/symfony/routing.git", - "reference": "8e213820c5fea844ecea29203d2a308019007c15" + "reference": "7614b8ca5fa89b9cd233e21b627bfc5774f586e4" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/routing/zipball/8e213820c5fea844ecea29203d2a308019007c15", - "reference": "8e213820c5fea844ecea29203d2a308019007c15", + "url": "https://api.github.com/repos/symfony/routing/zipball/7614b8ca5fa89b9cd233e21b627bfc5774f586e4", + "reference": "7614b8ca5fa89b9cd233e21b627bfc5774f586e4", "shasum": "" }, "require": { @@ -8750,7 +8794,7 @@ "url" ], "support": { - "source": "https://github.com/symfony/routing/tree/v7.3.0" + "source": "https://github.com/symfony/routing/tree/v7.3.2" }, "funding": [ { @@ -8761,12 +8805,16 @@ "url": "https://github.com/fabpot", "type": "github" }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, { "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "type": "tidelift" } ], - "time": "2025-05-24T20:43:28+00:00" + "time": "2025-07-15T11:36:08+00:00" }, { "name": "symfony/service-contracts", @@ -8853,16 +8901,16 @@ }, { "name": "symfony/string", - "version": "v7.3.0", + "version": "v7.3.2", "source": { "type": "git", "url": "https://github.com/symfony/string.git", - "reference": "f3570b8c61ca887a9e2938e85cb6458515d2b125" + "reference": "42f505aff654e62ac7ac2ce21033818297ca89ca" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/string/zipball/f3570b8c61ca887a9e2938e85cb6458515d2b125", - "reference": "f3570b8c61ca887a9e2938e85cb6458515d2b125", + "url": "https://api.github.com/repos/symfony/string/zipball/42f505aff654e62ac7ac2ce21033818297ca89ca", + "reference": "42f505aff654e62ac7ac2ce21033818297ca89ca", "shasum": "" }, "require": { @@ -8920,7 +8968,7 @@ "utf8" ], "support": { - "source": "https://github.com/symfony/string/tree/v7.3.0" + "source": "https://github.com/symfony/string/tree/v7.3.2" }, "funding": [ { @@ -8931,25 +8979,29 @@ "url": "https://github.com/fabpot", "type": "github" }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, { "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "type": "tidelift" } ], - "time": "2025-04-20T20:19:01+00:00" + "time": "2025-07-10T08:47:49+00:00" }, { "name": "symfony/translation", - "version": "v7.3.1", + "version": "v7.3.2", "source": { "type": "git", "url": "https://github.com/symfony/translation.git", - "reference": "241d5ac4910d256660238a7ecf250deba4c73063" + "reference": "81b48f4daa96272efcce9c7a6c4b58e629df3c90" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/translation/zipball/241d5ac4910d256660238a7ecf250deba4c73063", - "reference": "241d5ac4910d256660238a7ecf250deba4c73063", + "url": "https://api.github.com/repos/symfony/translation/zipball/81b48f4daa96272efcce9c7a6c4b58e629df3c90", + "reference": "81b48f4daa96272efcce9c7a6c4b58e629df3c90", "shasum": "" }, "require": { @@ -9016,7 +9068,7 @@ "description": "Provides tools to internationalize your application", "homepage": "https://symfony.com", "support": { - "source": "https://github.com/symfony/translation/tree/v7.3.1" + "source": "https://github.com/symfony/translation/tree/v7.3.2" }, "funding": [ { @@ -9027,12 +9079,16 @@ "url": "https://github.com/fabpot", "type": "github" }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, { "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "type": "tidelift" } ], - "time": "2025-06-27T19:55:54+00:00" + "time": "2025-07-30T17:31:46+00:00" }, { "name": "symfony/translation-contracts", @@ -9188,16 +9244,16 @@ }, { "name": "symfony/var-dumper", - "version": "v7.3.1", + "version": "v7.3.2", "source": { "type": "git", "url": "https://github.com/symfony/var-dumper.git", - "reference": "6e209fbe5f5a7b6043baba46fe5735a4b85d0d42" + "reference": "53205bea27450dc5c65377518b3275e126d45e75" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/var-dumper/zipball/6e209fbe5f5a7b6043baba46fe5735a4b85d0d42", - "reference": "6e209fbe5f5a7b6043baba46fe5735a4b85d0d42", + "url": "https://api.github.com/repos/symfony/var-dumper/zipball/53205bea27450dc5c65377518b3275e126d45e75", + "reference": "53205bea27450dc5c65377518b3275e126d45e75", "shasum": "" }, "require": { @@ -9209,7 +9265,6 @@ "symfony/console": "<6.4" }, "require-dev": { - "ext-iconv": "*", "symfony/console": "^6.4|^7.0", "symfony/http-kernel": "^6.4|^7.0", "symfony/process": "^6.4|^7.0", @@ -9252,7 +9307,7 @@ "dump" ], "support": { - "source": "https://github.com/symfony/var-dumper/tree/v7.3.1" + "source": "https://github.com/symfony/var-dumper/tree/v7.3.2" }, "funding": [ { @@ -9263,25 +9318,29 @@ "url": "https://github.com/fabpot", "type": "github" }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, { "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "type": "tidelift" } ], - "time": "2025-06-27T19:55:54+00:00" + "time": "2025-07-29T20:02:46+00:00" }, { "name": "symfony/var-exporter", - "version": "v7.3.0", + "version": "v7.3.2", "source": { "type": "git", "url": "https://github.com/symfony/var-exporter.git", - "reference": "c9a1168891b5aaadfd6332ef44393330b3498c4c" + "reference": "05b3e90654c097817325d6abd284f7938b05f467" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/var-exporter/zipball/c9a1168891b5aaadfd6332ef44393330b3498c4c", - "reference": "c9a1168891b5aaadfd6332ef44393330b3498c4c", + "url": "https://api.github.com/repos/symfony/var-exporter/zipball/05b3e90654c097817325d6abd284f7938b05f467", + "reference": "05b3e90654c097817325d6abd284f7938b05f467", "shasum": "" }, "require": { @@ -9329,7 +9388,7 @@ "serialize" ], "support": { - "source": "https://github.com/symfony/var-exporter/tree/v7.3.0" + "source": "https://github.com/symfony/var-exporter/tree/v7.3.2" }, "funding": [ { @@ -9340,12 +9399,16 @@ "url": "https://github.com/fabpot", "type": "github" }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, { "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", "type": "tidelift" } ], - "time": "2025-05-15T09:04:05+00:00" + "time": "2025-07-10T08:47:49+00:00" }, { "name": "thecodingmachine/safe", diff --git a/config/firefly.php b/config/firefly.php index edd77d6eec..6dcf9f082f 100644 --- a/config/firefly.php +++ b/config/firefly.php @@ -79,7 +79,7 @@ return [ // see cer.php for exchange rates feature flag. ], 'version' => 'develop/2025-07-31', - 'build_time' => 1753950885, + 'build_time' => 1753977228, 'api_version' => '2.1.0', // field is no longer used. 'db_version' => 26, diff --git a/package-lock.json b/package-lock.json index 2cc9829e9a..05fdfe9278 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6360,9 +6360,9 @@ } }, "node_modules/follow-redirects": { - "version": "1.15.10", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.10.tgz", - "integrity": "sha512-V7O/fFKM539IC2bweloFWuoiJ9OtI3W2uIqJPWM8IT5xxNyt73QtvVqmSpcDmk07ivmmlKB+rRY0vpQjIYNtKw==", + "version": "1.15.11", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz", + "integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==", "dev": true, "funding": [ { diff --git a/resources/assets/v2/src/pages/dashboard/subscriptions.js b/resources/assets/v2/src/pages/dashboard/subscriptions.js index 20fab2772a..3053e56a54 100644 --- a/resources/assets/v2/src/pages/dashboard/subscriptions.js +++ b/resources/assets/v2/src/pages/dashboard/subscriptions.js @@ -30,6 +30,7 @@ import i18next from "i18next"; let afterPromises = false; let apiData = []; let subscriptionData = {}; +let convertToNative = false; function addObjectGroupInfo(data) { let objectGroupId = parseInt(data.object_group_id); @@ -70,6 +71,11 @@ function parseBillInfo(data) { pay_dates: parsePayDates(data.attributes.pay_dates), paid: data.attributes.paid_dates.length > 0, }; + if(convertToNative) { + result.currency_code = data.attributes.native_currency_code; + } + + // set variables result.expected_amount = formatMoney(result.amount, result.currency_code); result.expected_times = i18next.t('firefly.subscr_expected_x_times', { @@ -214,6 +220,7 @@ export default () => ({ ['@convert-to-native.window'](event){ console.log('I heard that! (dashboard/subscriptions)'); this.convertToNative = event.detail; + convertToNative = event.detail; this.startSubscriptions(); } }, @@ -308,6 +315,7 @@ export default () => ({ init() { Promise.all([getVariable('convert_to_native', false)]).then((values) => { this.convertToNative = values[0]; + convertToNative = values[0]; afterPromises = true; if (false === this.loading) {