Code cleanup.

This commit is contained in:
James Cole
2023-12-20 19:35:52 +01:00
parent c4f6366642
commit 64ec0cf62e
997 changed files with 12908 additions and 28136 deletions

View File

@@ -46,12 +46,11 @@ class AccountBalanceGrouped
/**
* Convert the given input to a chart compatible array.
*
* @return array
*/
public function convertToChartData(): array
{
$chartData = [];
// loop2: loop this data, make chart bars for each currency:
/** @var array $currency */
foreach ($this->data as $currency) {
@@ -87,7 +86,6 @@ class AccountBalanceGrouped
'period' => $this->preferredRange,
'entries' => [],
'native_entries' => [],
];
// loop all possible periods between $start and $end, and add them to the correct dataset.
$currentStart = clone $this->start;
@@ -95,12 +93,12 @@ class AccountBalanceGrouped
$key = $currentStart->format($this->carbonFormat);
$label = $currentStart->toAtomString();
// normal entries
$income['entries'][$label] = app('steam')->bcround(($currency[$key]['earned'] ?? '0'), $currency['currency_decimal_places']);
$expense['entries'][$label] = app('steam')->bcround(($currency[$key]['spent'] ?? '0'), $currency['currency_decimal_places']);
$income['entries'][$label] = app('steam')->bcround($currency[$key]['earned'] ?? '0', $currency['currency_decimal_places']);
$expense['entries'][$label] = app('steam')->bcround($currency[$key]['spent'] ?? '0', $currency['currency_decimal_places']);
// converted entries
$income['native_entries'][$label] = app('steam')->bcround(($currency[$key]['native_earned'] ?? '0'), $currency['native_decimal_places']);
$expense['native_entries'][$label] = app('steam')->bcround(($currency[$key]['native_spent'] ?? '0'), $currency['native_decimal_places']);
$income['native_entries'][$label] = app('steam')->bcround($currency[$key]['native_earned'] ?? '0', $currency['native_decimal_places']);
$expense['native_entries'][$label] = app('steam')->bcround($currency[$key]['native_spent'] ?? '0', $currency['native_decimal_places']);
// next loop
$currentStart = app('navigation')->addPeriod($currentStart, $this->preferredRange, 0);
@@ -109,18 +107,18 @@ class AccountBalanceGrouped
$chartData[] = $income;
$chartData[] = $expense;
}
return $chartData;
}
/**
* Group the given journals by currency and then by period.
* If they are part of a set of accounts this basically means it's balance chart.
*
* @return void
*/
public function groupByCurrencyAndPeriod(): void
{
$converter = new ExchangeRateConverter();
// loop. group by currency and by period.
/** @var array $journal */
foreach ($this->journals as $journal) {
@@ -159,9 +157,8 @@ class AccountBalanceGrouped
// transfer or reconcile or opening balance, and these accounts are the destination.
if (
TransactionType::DEPOSIT === $journal['transaction_type_type']
||
(
|| (
(
TransactionType::TRANSFER === $journal['transaction_type_type']
|| TransactionType::RECONCILIATION === $journal['transaction_type_type']
@@ -173,6 +170,7 @@ class AccountBalanceGrouped
$key = 'earned';
$amount = app('steam')->positive($journal['amount']);
}
// get conversion rate
try {
$rate = $converter->getCurrencyRate($currency, $this->default, $journal['date']);
@@ -195,29 +193,18 @@ class AccountBalanceGrouped
$convertedKey = sprintf('native_%s', $key);
$this->data[$currencyId][$period][$convertedKey] = bcadd($this->data[$currencyId][$period][$convertedKey], $amountConverted);
}
}
/**
* @param Collection $accounts
*
* @return void
*/
public function setAccounts(Collection $accounts): void
{
$this->accountIds = $accounts->pluck('id')->toArray();
}
/**
* @param TransactionCurrency $default
*
* @return void
*/
public function setDefault(TransactionCurrency $default): void
{
$this->default = $default;
$defaultCurrencyId = $default->id;
$this->currencies = [$default->id => $default,]; // currency cache
$this->currencies = [$default->id => $default]; // currency cache
$this->data[$defaultCurrencyId] = [
'currency_id' => (string)$defaultCurrencyId,
'currency_symbol' => $default->symbol,
@@ -232,47 +219,24 @@ class AccountBalanceGrouped
];
}
/**
* @param Carbon $end
*
* @return void
*/
public function setEnd(Carbon $end): void
{
$this->end = $end;
}
/**
* @param array $journals
*
* @return void
*/
public function setJournals(array $journals): void
{
$this->journals = $journals;
}
/**
* @param string $preferredRange
*
* @return void
*/
public function setPreferredRange(string $preferredRange): void
{
$this->preferredRange = $preferredRange;
$this->carbonFormat = app('navigation')->preferredCarbonFormatByPeriod($preferredRange);
}
/**
* @param Carbon $start
*
* @return void
*/
public function setStart(Carbon $start): void
{
$this->start = $start;
}
}

View File

@@ -27,17 +27,11 @@ use FireflyIII\Models\AccountType;
/**
* Trait AccountFilter
*
*/
trait AccountFilter
{
/**
* All the available types.
*
* @param string $type
*
* @return array
*/
protected function mapAccountTypes(string $type): array
{
@@ -56,11 +50,11 @@ trait AccountFilter
AccountType::DEBT,
AccountType::MORTGAGE,
],
'asset' => [AccountType::DEFAULT, AccountType::ASSET,],
'cash' => [AccountType::CASH,],
'expense' => [AccountType::EXPENSE, AccountType::BENEFICIARY,],
'revenue' => [AccountType::REVENUE,],
'special' => [AccountType::CASH, AccountType::INITIAL_BALANCE, AccountType::IMPORT, AccountType::RECONCILIATION,],
'asset' => [AccountType::DEFAULT, AccountType::ASSET],
'cash' => [AccountType::CASH],
'expense' => [AccountType::EXPENSE, AccountType::BENEFICIARY],
'revenue' => [AccountType::REVENUE],
'special' => [AccountType::CASH, AccountType::INITIAL_BALANCE, AccountType::IMPORT, AccountType::RECONCILIATION],
'hidden' => [AccountType::INITIAL_BALANCE, AccountType::IMPORT, AccountType::RECONCILIATION],
'liability' => [AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE, AccountType::CREDITCARD],
'liabilities' => [AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE, AccountType::CREDITCARD],

View File

@@ -28,17 +28,11 @@ use Illuminate\Support\Collection;
/**
* Trait ApiSupport
*
*/
trait ApiSupport
{
/**
* Small helper function for the revenue and expense account charts.
*
* @param array $names
*
* @return array
*/
protected function expandNames(array $names): array
{
@@ -52,14 +46,11 @@ trait ApiSupport
/**
* Small helper function for the revenue and expense account charts.
*
* @param Collection $accounts
*
* @return array
*/
protected function extractNames(Collection $accounts): array
{
$return = [];
/** @var Account $account */
foreach ($accounts as $account) {
$return[$account->id] = $account->name;

View File

@@ -1,6 +1,5 @@
<?php
/*
* CleansChartData.php
* Copyright (c) 2023 james@firefly-iii.org
@@ -37,14 +36,12 @@ trait CleansChartData
* "main" entry used in the V2 API chart endpoints. This loop makes sure
* IDs are strings and other values are present (or missing).
*
* @param array $data
*
* @return array
* @throws FireflyException
*/
private function clean(array $data): array
{
$return = [];
/**
* @var mixed $index
* @var array $array
@@ -67,7 +64,7 @@ trait CleansChartData
}
$return[] = $array;
}
return $return;
}
}

View File

@@ -25,7 +25,6 @@ declare(strict_types=1);
namespace FireflyIII\Support\Http\Api;
use Carbon\Carbon;
use DateTimeInterface;
use FireflyIII\Models\TransactionCurrency;
/**
@@ -36,9 +35,6 @@ trait ConvertsExchangeRates
private ?bool $enabled = null;
/**
* @param array $set
*
* @return array
* @deprecated
*/
public function cerChartSet(array $set): array
@@ -52,10 +48,12 @@ trait ConvertsExchangeRates
$this->enabled = false;
if (false === $this->enabled) {
$set['converted'] = false;
return $set;
}
$set['converted'] = true;
/** @var TransactionCurrency $native */
$native = app('amount')->getDefaultCurrency();
$currency = $this->getCurrency((int)$set['currency_id']);
@@ -64,50 +62,24 @@ trait ConvertsExchangeRates
$set['native_code'] = $currency->code;
$set['native_symbol'] = $currency->symbol;
$set['native_decimal_places'] = $currency->decimal_places;
return $set;
}
foreach ($set['entries'] as $date => $entry) {
$carbon = Carbon::createFromFormat(DateTimeInterface::ATOM, $date);
$carbon = Carbon::createFromFormat(\DateTimeInterface::ATOM, $date);
$rate = $this->getRate($currency, $native, $carbon);
$rate = '0' === $rate ? '1' : $rate;
app('log')->debug(sprintf('bcmul("%s", "%s")', (string)$entry, $rate));
$set['entries'][$date] = (float)bcmul((string)$entry, $rate);
}
return $set;
}
/**
* @return void
* @deprecated
*/
private function getPreference(): void
{
$this->enabled = config('cer.currency_conversion');
}
/**
* @param int $currencyId
*
* @return TransactionCurrency
* @deprecated
*/
private function getCurrency(int $currencyId): TransactionCurrency
{
$result = TransactionCurrency::find($currencyId);
if (null === $result) {
return app('amount')->getDefaultCurrency();
}
return $result;
}
/**
* For a sum of entries, get the exchange rate to the native currency of
* the user.
*
* @param array $entries
*
* @return array
* @deprecated
*/
public function cerSum(array $entries): array
@@ -119,18 +91,20 @@ trait ConvertsExchangeRates
// if false, return the same array without conversion info
if (false === $this->enabled) {
$return = [];
/** @var array $entry */
foreach ($entries as $entry) {
$entry['converted'] = false;
$return[] = $entry;
}
return $return;
}
/** @var TransactionCurrency $native */
$native = app('amount')->getDefaultCurrency();
$return = [];
/** @var array $entry */
foreach ($entries as $entry) {
$currency = $this->getCurrency((int)$entry['id']);
@@ -155,17 +129,32 @@ trait ConvertsExchangeRates
}
$return[] = $entry;
}
return $return;
}
/**
* @param string $amount
* @param TransactionCurrency $from
* @param TransactionCurrency $to
* @param Carbon|null $date
*
* @return string
*
* @deprecated
*/
private function getPreference(): void
{
$this->enabled = config('cer.currency_conversion');
}
/**
* @deprecated
*/
private function getCurrency(int $currencyId): TransactionCurrency
{
$result = TransactionCurrency::find($currencyId);
if (null === $result) {
return app('amount')->getDefaultCurrency();
}
return $result;
}
/**
* @deprecated
*/
private function convertAmount(string $amount, TransactionCurrency $from, TransactionCurrency $to, ?Carbon $date = null): string

View File

@@ -1,6 +1,5 @@
<?php
/*
* ExchangeRateConverter.php
* Copyright (c) 2023 james@firefly-iii.org
@@ -36,43 +35,29 @@ use FireflyIII\Support\CacheProperties;
*/
class ExchangeRateConverter
{
//use ConvertsExchangeRates;
// use ConvertsExchangeRates;
/**
* @param TransactionCurrency $from
* @param TransactionCurrency $to
* @param Carbon $date
* @param string $amount
*
* @return string
* @throws FireflyException
*/
public function convert(TransactionCurrency $from, TransactionCurrency $to, Carbon $date, string $amount): string
{
$rate = $this->getCurrencyRate($from, $to, $date);
return bcmul($amount, $rate);
}
/**
* @param TransactionCurrency $from
* @param TransactionCurrency $to
* @param Carbon $date
*
* @return string
* @throws FireflyException
*/
public function getCurrencyRate(TransactionCurrency $from, TransactionCurrency $to, Carbon $date): string
{
$rate = $this->getRate($from, $to, $date);
return '0' === $rate ? '1' : $rate;
}
/**
* @param TransactionCurrency $from
* @param TransactionCurrency $to
* @param Carbon $date
*
* @return string
* @throws FireflyException
*/
private function getRate(TransactionCurrency $from, TransactionCurrency $to, Carbon $date): string
@@ -98,16 +83,10 @@ class ExchangeRateConverter
}
$second = bcdiv('1', $second);
return bcmul($first, $second);
}
/**
* @param int $from
* @param int $to
* @param string $date
*
* @return string|null
*/
private function getFromDB(int $from, int $to, string $date): ?string
{
$key = sprintf('cer-%d-%d-%s', $from, $to, $date);
@@ -119,34 +98,31 @@ class ExchangeRateConverter
if ('' === $rate) {
return null;
}
return $rate;
}
app('log')->debug(sprintf('Going to get rate #%d->#%d (%s) from DB.', $from, $to, $date));
/** @var CurrencyExchangeRate|null $result */
/** @var null|CurrencyExchangeRate $result */
$result = auth()->user()
->currencyExchangeRates()
->where('from_currency_id', $from)
->where('to_currency_id', $to)
->where('date', '<=', $date)
->orderBy('date', 'DESC')
->first();
->currencyExchangeRates()
->where('from_currency_id', $from)
->where('to_currency_id', $to)
->where('date', '<=', $date)
->orderBy('date', 'DESC')
->first()
;
$rate = (string)$result?->rate;
$cache->store($rate);
if ('' === $rate) {
return null;
}
return $rate;
}
/**
* @param TransactionCurrency $currency
* @param Carbon $date
*
* @return string
* @throws FireflyException
*
*/
private function getEuroRate(TransactionCurrency $currency, Carbon $date): string
{
@@ -164,23 +140,21 @@ class ExchangeRateConverter
if (null !== $rate) {
return bcdiv('1', $rate);
// app('log')->debug(sprintf('Inverted rate for %s to EUR is %s.', $currency->code, $rate));
//return $rate;
// return $rate;
}
// grab backup values from config file:
$backup = config(sprintf('cer.rates.%s', $currency->code));
if (null !== $backup) {
return bcdiv('1', (string)$backup);
// app('log')->debug(sprintf('Backup rate for %s to EUR is %s.', $currency->code, $backup));
//return $backup;
// return $backup;
}
// app('log')->debug(sprintf('No rate for %s to EUR.', $currency->code));
return '0';
}
/**
* @return int
* @throws FireflyException
*/
private function getEuroId(): int
@@ -195,6 +169,7 @@ class ExchangeRateConverter
throw new FireflyException('Cannot find EUR in system, cannot do currency conversion.');
}
$cache->store($euro->id);
return $euro->id;
}
}

View File

@@ -25,15 +25,14 @@ namespace FireflyIII\Support\Http\Api;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Repositories\UserGroups\Currency\CurrencyRepositoryInterface;
use Log;
class SummaryBalanceGrouped
{
private const string SUM = 'sum';
private TransactionCurrency $default;
private array $amounts = [];
private array $keys;
private array $currencies;
private const string SUM = 'sum';
private CurrencyRepositoryInterface $currencyRepository;
public function __construct()
@@ -45,14 +44,10 @@ class SummaryBalanceGrouped
/**
* TODO remember to do -1 for deposits.
*
* @param array $journals
*
* @return void
*/
public function groupTransactions(string $key, array $journals): void
{
Log::debug(sprintf('Now in groupTransactions with key "%s" and %d journal(s)', $key, count($journals)));
\Log::debug(sprintf('Now in groupTransactions with key "%s" and %d journal(s)', $key, count($journals)));
$converter = new ExchangeRateConverter();
$this->keys[] = $key;
$multiplier = 'income' === $key ? '-1' : '1';
@@ -81,18 +76,14 @@ class SummaryBalanceGrouped
$this->amounts[self::SUM][$currencyId] = bcadd($this->amounts[self::SUM][$currencyId], $amount);
$this->amounts[$key]['native'] = bcadd($this->amounts[$key]['native'], $nativeAmount);
$this->amounts[self::SUM]['native'] = bcadd($this->amounts[self::SUM]['native'], $nativeAmount);
}
app('log')->debug(sprintf('this->amounts[%s][native] is now %s', $key, $this->amounts[$key]['native']));
app('log')->debug(sprintf('this->amounts[%s][native] is now %s', self::SUM, $this->amounts[$key]['native']));
}
/**
* @return array
*/
public function groupData(): array
{
Log::debug('Now going to group data.');
\Log::debug('Now going to group data.');
$return = [];
foreach ($this->keys as $key) {
$title = match ($key) {
@@ -138,6 +129,7 @@ class SummaryBalanceGrouped
];
}
}
return $return;
}
@@ -145,6 +137,4 @@ class SummaryBalanceGrouped
{
$this->default = $default;
}
}

View File

@@ -27,17 +27,11 @@ use FireflyIII\Models\TransactionType;
/**
* Trait TransactionFilter
*
*/
trait TransactionFilter
{
/**
* All the types you can request.
*
* @param string $type
*
* @return array
*/
protected function mapTransactionTypes(string $type): array
{
@@ -49,27 +43,28 @@ trait TransactionFilter
TransactionType::OPENING_BALANCE,
TransactionType::RECONCILIATION,
],
'withdrawal' => [TransactionType::WITHDRAWAL,],
'withdrawals' => [TransactionType::WITHDRAWAL,],
'expense' => [TransactionType::WITHDRAWAL,],
'expenses' => [TransactionType::WITHDRAWAL,],
'income' => [TransactionType::DEPOSIT,],
'deposit' => [TransactionType::DEPOSIT,],
'deposits' => [TransactionType::DEPOSIT,],
'transfer' => [TransactionType::TRANSFER,],
'transfers' => [TransactionType::TRANSFER,],
'opening_balance' => [TransactionType::OPENING_BALANCE,],
'reconciliation' => [TransactionType::RECONCILIATION,],
'reconciliations' => [TransactionType::RECONCILIATION,],
'special' => [TransactionType::OPENING_BALANCE, TransactionType::RECONCILIATION,],
'specials' => [TransactionType::OPENING_BALANCE, TransactionType::RECONCILIATION,],
'default' => [TransactionType::WITHDRAWAL, TransactionType::DEPOSIT, TransactionType::TRANSFER,],
'withdrawal' => [TransactionType::WITHDRAWAL],
'withdrawals' => [TransactionType::WITHDRAWAL],
'expense' => [TransactionType::WITHDRAWAL],
'expenses' => [TransactionType::WITHDRAWAL],
'income' => [TransactionType::DEPOSIT],
'deposit' => [TransactionType::DEPOSIT],
'deposits' => [TransactionType::DEPOSIT],
'transfer' => [TransactionType::TRANSFER],
'transfers' => [TransactionType::TRANSFER],
'opening_balance' => [TransactionType::OPENING_BALANCE],
'reconciliation' => [TransactionType::RECONCILIATION],
'reconciliations' => [TransactionType::RECONCILIATION],
'special' => [TransactionType::OPENING_BALANCE, TransactionType::RECONCILIATION],
'specials' => [TransactionType::OPENING_BALANCE, TransactionType::RECONCILIATION],
'default' => [TransactionType::WITHDRAWAL, TransactionType::DEPOSIT, TransactionType::TRANSFER],
];
$return = [];
$parts = explode(',', $type);
foreach ($parts as $part) {
$return = array_merge($return, $types[$part] ?? $types['default']);
}
return array_unique($return);
}
}

View File

@@ -37,32 +37,35 @@ trait ValidatesUserGroupTrait
/**
* This check does not validate which rights the user has, that comes later.
*
* @param Request $request
*
* @return UserGroup|null
* @throws FireflyException
*/
protected function validateUserGroup(Request $request): ?UserGroup
{
if (!auth()->check()) {
app('log')->debug('validateUserGroup: user is not logged in, return NULL.');
return null;
}
/** @var User $user */
$user = auth()->user();
if (!$request->has('user_group_id')) {
$group = $user->userGroup;
app('log')->debug(sprintf('validateUserGroup: no user group submitted, return default group #%d.', $group?->id));
return $group;
}
$groupId = (int)$request->get('user_group_id');
/** @var GroupMembership|null $membership */
/** @var null|GroupMembership $membership */
$membership = $user->groupMemberships()->where('user_group_id', $groupId)->first();
if (null === $membership) {
app('log')->debug('validateUserGroup: user has no access to this group.');
throw new FireflyException((string)trans('validation.belongs_user_or_user_group'));
}
app('log')->debug(sprintf('validateUserGroup: user has role "%s" in group #%d.', $membership->userRole->title, $membership->userGroup->id));
return $membership->userGroup;
}
}