Rearrange some code.

This commit is contained in:
James Cole
2025-09-26 05:33:35 +02:00
parent 66d09450d3
commit 08879d31ba
19 changed files with 407 additions and 416 deletions

View File

@@ -44,10 +44,10 @@ class AccountBalanceGrouped
private readonly ExchangeRateConverter $converter; private readonly ExchangeRateConverter $converter;
private array $currencies = []; private array $currencies = [];
private array $data = []; private array $data = [];
private TransactionCurrency $primary;
private Carbon $end; private Carbon $end;
private array $journals = []; private array $journals = [];
private string $preferredRange; private string $preferredRange;
private TransactionCurrency $primary;
private Carbon $start; private Carbon $start;
public function __construct() public function __construct()
@@ -259,6 +259,22 @@ class AccountBalanceGrouped
$this->accountIds = $accounts->pluck('id')->toArray(); $this->accountIds = $accounts->pluck('id')->toArray();
} }
public function setEnd(Carbon $end): void
{
$this->end = $end;
}
public function setJournals(array $journals): void
{
$this->journals = $journals;
}
public function setPreferredRange(string $preferredRange): void
{
$this->preferredRange = $preferredRange;
$this->carbonFormat = Navigation::preferredCarbonFormatByPeriod($preferredRange);
}
public function setPrimary(TransactionCurrency $primary): void public function setPrimary(TransactionCurrency $primary): void
{ {
$this->primary = $primary; $this->primary = $primary;
@@ -278,22 +294,6 @@ class AccountBalanceGrouped
]; ];
} }
public function setEnd(Carbon $end): void
{
$this->end = $end;
}
public function setJournals(array $journals): void
{
$this->journals = $journals;
}
public function setPreferredRange(string $preferredRange): void
{
$this->preferredRange = $preferredRange;
$this->carbonFormat = Navigation::preferredCarbonFormatByPeriod($preferredRange);
}
public function setStart(Carbon $start): void public function setStart(Carbon $start): void
{ {
$this->start = $start; $this->start = $start;

View File

@@ -39,7 +39,7 @@ trait CollectsAccountsFromFilter
// always collect from the query parameter, even when it's empty. // always collect from the query parameter, even when it's empty.
if (null !== $queryParameters['accounts']) { if (null !== $queryParameters['accounts']) {
foreach ($queryParameters['accounts'] as $accountId) { foreach ($queryParameters['accounts'] as $accountId) {
$account = $this->repository->find((int) $accountId); $account = $this->repository->find((int)$accountId);
if (null !== $account) { if (null !== $account) {
$collection->push($account); $collection->push($account);
} }

View File

@@ -187,10 +187,9 @@ class ExchangeRateConverter
->where('to_currency_id', $to) ->where('to_currency_id', $to)
->where('date', '<=', $date) ->where('date', '<=', $date)
->orderBy('date', 'DESC') ->orderBy('date', 'DESC')
->first() ->first();
;
++$this->queryCount; ++$this->queryCount;
$rate = (string) $result?->rate; $rate = (string)$result?->rate;
if ('' === $rate) { if ('' === $rate) {
app('log')->debug(sprintf('ExchangeRateConverter: Found no rate for #%d->#%d (%s) in the DB.', $from, $to, $date)); app('log')->debug(sprintf('ExchangeRateConverter: Found no rate for #%d->#%d (%s) in the DB.', $from, $to, $date));
@@ -245,7 +244,7 @@ class ExchangeRateConverter
// grab backup values from config file: // grab backup values from config file:
$backup = config(sprintf('cer.rates.%s', $currency->code)); $backup = config(sprintf('cer.rates.%s', $currency->code));
if (null !== $backup) { if (null !== $backup) {
return bcdiv('1', (string) $backup); return bcdiv('1', (string)$backup);
// app('log')->debug(sprintf('Backup rate for %s to EUR is %s.', $currency->code, $backup)); // app('log')->debug(sprintf('Backup rate for %s to EUR is %s.', $currency->code, $backup));
// return $backup; // return $backup;
} }
@@ -263,7 +262,7 @@ class ExchangeRateConverter
$cache = new CacheProperties(); $cache = new CacheProperties();
$cache->addProperty('cer-euro-id'); $cache->addProperty('cer-euro-id');
if ($cache->has()) { if ($cache->has()) {
return (int) $cache->get(); return (int)$cache->get();
} }
$euro = Amount::getTransactionCurrencyByCode('EUR'); $euro = Amount::getTransactionCurrencyByCode('EUR');
++$this->queryCount; ++$this->queryCount;

View File

@@ -60,7 +60,7 @@ class SummaryBalanceGrouped
$return[] = [ $return[] = [
'key' => sprintf('%s-in-pc', $title), 'key' => sprintf('%s-in-pc', $title),
'value' => $this->amounts[$key]['primary'] ?? '0', 'value' => $this->amounts[$key]['primary'] ?? '0',
'currency_id' => (string) $this->default->id, 'currency_id' => (string)$this->default->id,
'currency_code' => $this->default->code, 'currency_code' => $this->default->code,
'currency_symbol' => $this->default->symbol, 'currency_symbol' => $this->default->symbol,
'currency_decimal_places' => $this->default->decimal_places, 'currency_decimal_places' => $this->default->decimal_places,
@@ -73,7 +73,7 @@ class SummaryBalanceGrouped
// skip primary entries. // skip primary entries.
continue; continue;
} }
$currencyId = (int) $currencyId; $currencyId = (int)$currencyId;
$currency = $this->currencies[$currencyId] ?? $this->currencyRepository->find($currencyId); $currency = $this->currencies[$currencyId] ?? $this->currencyRepository->find($currencyId);
$this->currencies[$currencyId] = $currency; $this->currencies[$currencyId] = $currency;
// create objects for big array. // create objects for big array.
@@ -87,7 +87,7 @@ class SummaryBalanceGrouped
$return[] = [ $return[] = [
'key' => sprintf('%s-in-%s', $title, $currency->code), 'key' => sprintf('%s-in-%s', $title, $currency->code),
'value' => $this->amounts[$key][$currencyId] ?? '0', 'value' => $this->amounts[$key][$currencyId] ?? '0',
'currency_id' => (string) $currency->id, 'currency_id' => (string)$currency->id,
'currency_code' => $currency->code, 'currency_code' => $currency->code,
'currency_symbol' => $currency->symbol, 'currency_symbol' => $currency->symbol,
'currency_decimal_places' => $currency->decimal_places, 'currency_decimal_places' => $currency->decimal_places,
@@ -109,12 +109,12 @@ class SummaryBalanceGrouped
/** @var array $journal */ /** @var array $journal */
foreach ($journals as $journal) { foreach ($journals as $journal) {
// transaction info: // transaction info:
$currencyId = (int) $journal['currency_id']; $currencyId = (int)$journal['currency_id'];
$amount = bcmul((string) $journal['amount'], $multiplier); $amount = bcmul((string)$journal['amount'], $multiplier);
$currency = $this->currencies[$currencyId] ?? Amount::getTransactionCurrencyById($currencyId); $currency = $this->currencies[$currencyId] ?? Amount::getTransactionCurrencyById($currencyId);
$this->currencies[$currencyId] = $currency; $this->currencies[$currencyId] = $currency;
$pcAmount = $converter->convert($currency, $this->default, $journal['date'], $amount); $pcAmount = $converter->convert($currency, $this->default, $journal['date'], $amount);
if ((int) $journal['foreign_currency_id'] === $this->default->id) { if ((int)$journal['foreign_currency_id'] === $this->default->id) {
// use foreign amount instead // use foreign amount instead
$pcAmount = $journal['foreign_amount']; $pcAmount = $journal['foreign_amount'];
} }
@@ -126,10 +126,10 @@ class SummaryBalanceGrouped
$this->amounts[self::SUM]['primary'] ??= '0'; $this->amounts[self::SUM]['primary'] ??= '0';
// add values: // add values:
$this->amounts[$key][$currencyId] = bcadd((string) $this->amounts[$key][$currencyId], $amount); $this->amounts[$key][$currencyId] = bcadd((string)$this->amounts[$key][$currencyId], $amount);
$this->amounts[self::SUM][$currencyId] = bcadd((string) $this->amounts[self::SUM][$currencyId], $amount); $this->amounts[self::SUM][$currencyId] = bcadd((string)$this->amounts[self::SUM][$currencyId], $amount);
$this->amounts[$key]['primary'] = bcadd((string) $this->amounts[$key]['primary'], (string) $pcAmount); $this->amounts[$key]['primary'] = bcadd((string)$this->amounts[$key]['primary'], (string)$pcAmount);
$this->amounts[self::SUM]['primary'] = bcadd((string) $this->amounts[self::SUM]['primary'], (string) $pcAmount); $this->amounts[self::SUM]['primary'] = bcadd((string)$this->amounts[self::SUM]['primary'], (string)$pcAmount);
} }
$converter->summarize(); $converter->summarize();
} }

View File

@@ -38,8 +38,8 @@ use Illuminate\Support\Facades\Log;
*/ */
trait ValidatesUserGroupTrait trait ValidatesUserGroupTrait
{ {
protected UserGroup $userGroup;
protected User $user; protected User $user;
protected UserGroup $userGroup;
/** /**
* An "undocumented" filter * An "undocumented" filter
@@ -62,11 +62,11 @@ trait ValidatesUserGroupTrait
$user = auth()->user(); $user = auth()->user();
$groupId = 0; $groupId = 0;
if (!$request->has('user_group_id')) { if (!$request->has('user_group_id')) {
$groupId = (int) $user->user_group_id; $groupId = (int)$user->user_group_id;
Log::debug(sprintf('validateUserGroup: no user group submitted, use default group #%d.', $groupId)); Log::debug(sprintf('validateUserGroup: no user group submitted, use default group #%d.', $groupId));
} }
if ($request->has('user_group_id')) { if ($request->has('user_group_id')) {
$groupId = (int) $request->get('user_group_id'); $groupId = (int)$request->get('user_group_id');
Log::debug(sprintf('validateUserGroup: user group submitted, search for memberships in group #%d.', $groupId)); Log::debug(sprintf('validateUserGroup: user group submitted, search for memberships in group #%d.', $groupId));
} }
@@ -78,7 +78,7 @@ trait ValidatesUserGroupTrait
if (0 === $memberships->count()) { if (0 === $memberships->count()) {
Log::debug(sprintf('validateUserGroup: user has no access to group #%d.', $groupId)); Log::debug(sprintf('validateUserGroup: user has no access to group #%d.', $groupId));
throw new AuthorizationException((string) trans('validation.no_access_group')); throw new AuthorizationException((string)trans('validation.no_access_group'));
} }
// need to get the group from the membership: // need to get the group from the membership:
@@ -86,14 +86,14 @@ trait ValidatesUserGroupTrait
if (null === $group) { if (null === $group) {
Log::debug(sprintf('validateUserGroup: group #%d does not exist.', $groupId)); Log::debug(sprintf('validateUserGroup: group #%d does not exist.', $groupId));
throw new AuthorizationException((string) trans('validation.belongs_user_or_user_group')); throw new AuthorizationException((string)trans('validation.belongs_user_or_user_group'));
} }
Log::debug(sprintf('validateUserGroup: validate access of user to group #%d ("%s").', $groupId, $group->title)); Log::debug(sprintf('validateUserGroup: validate access of user to group #%d ("%s").', $groupId, $group->title));
$roles = property_exists($this, 'acceptedRoles') ? $this->acceptedRoles : []; // @phpstan-ignore-line $roles = property_exists($this, 'acceptedRoles') ? $this->acceptedRoles : []; // @phpstan-ignore-line
if (0 === count($roles)) { if (0 === count($roles)) {
Log::debug('validateUserGroup: no roles defined, so no access.'); Log::debug('validateUserGroup: no roles defined, so no access.');
throw new AuthorizationException((string) trans('validation.no_accepted_roles_defined')); throw new AuthorizationException((string)trans('validation.no_accepted_roles_defined'));
} }
Log::debug(sprintf('validateUserGroup: have %d roles to check.', count($roles)), $roles); Log::debug(sprintf('validateUserGroup: have %d roles to check.', count($roles)), $roles);
@@ -111,6 +111,6 @@ trait ValidatesUserGroupTrait
Log::debug('validateUserGroup: User does NOT have enough rights to access endpoint.'); Log::debug('validateUserGroup: User does NOT have enough rights to access endpoint.');
throw new AuthorizationException((string) trans('validation.belongs_user_or_user_group')); throw new AuthorizationException((string)trans('validation.belongs_user_or_user_group'));
} }
} }

View File

@@ -110,8 +110,8 @@ trait AugumentData
$grouped = $accounts->groupBy('id')->toArray(); $grouped = $accounts->groupBy('id')->toArray();
$return = []; $return = [];
foreach ($accountIds as $combinedId) { foreach ($accountIds as $combinedId) {
$parts = explode('-', (string) $combinedId); $parts = explode('-', (string)$combinedId);
$accountId = (int) $parts[0]; $accountId = (int)$parts[0];
if (array_key_exists($accountId, $grouped)) { if (array_key_exists($accountId, $grouped)) {
$return[$accountId] = $grouped[$accountId][0]['name']; $return[$accountId] = $grouped[$accountId][0]['name'];
} }
@@ -136,7 +136,7 @@ trait AugumentData
$return[$budgetId] = $grouped[$budgetId][0]['name']; $return[$budgetId] = $grouped[$budgetId][0]['name'];
} }
} }
$return[0] = (string) trans('firefly.no_budget'); $return[0] = (string)trans('firefly.no_budget');
return $return; return $return;
} }
@@ -152,13 +152,13 @@ trait AugumentData
$grouped = $categories->groupBy('id')->toArray(); $grouped = $categories->groupBy('id')->toArray();
$return = []; $return = [];
foreach ($categoryIds as $combinedId) { foreach ($categoryIds as $combinedId) {
$parts = explode('-', (string) $combinedId); $parts = explode('-', (string)$combinedId);
$categoryId = (int) $parts[0]; $categoryId = (int)$parts[0];
if (array_key_exists($categoryId, $grouped)) { if (array_key_exists($categoryId, $grouped)) {
$return[$categoryId] = $grouped[$categoryId][0]['name']; $return[$categoryId] = $grouped[$categoryId][0]['name'];
} }
} }
$return[0] = (string) trans('firefly.no_category'); $return[0] = (string)trans('firefly.no_category');
return $return; return $return;
} }
@@ -249,7 +249,7 @@ trait AugumentData
} }
$grouped[$name] ??= '0'; $grouped[$name] ??= '0';
$grouped[$name] = bcadd((string) $journal['amount'], $grouped[$name]); $grouped[$name] = bcadd((string)$journal['amount'], $grouped[$name]);
} }
return $grouped; return $grouped;
@@ -272,7 +272,7 @@ trait AugumentData
]; ];
// loop to support multi currency // loop to support multi currency
foreach ($journals as $journal) { foreach ($journals as $journal) {
$currencyId = (int) $journal['currency_id']; $currencyId = (int)$journal['currency_id'];
// if not set, set to zero: // if not set, set to zero:
if (!array_key_exists($currencyId, $sum['per_currency'])) { if (!array_key_exists($currencyId, $sum['per_currency'])) {
@@ -287,8 +287,8 @@ trait AugumentData
} }
// add amount // add amount
$sum['per_currency'][$currencyId]['sum'] = bcadd($sum['per_currency'][$currencyId]['sum'], (string) $journal['amount']); $sum['per_currency'][$currencyId]['sum'] = bcadd($sum['per_currency'][$currencyId]['sum'], (string)$journal['amount']);
$sum['grand_sum'] = bcadd($sum['grand_sum'], (string) $journal['amount']); $sum['grand_sum'] = bcadd($sum['grand_sum'], (string)$journal['amount']);
} }
return $sum; return $sum;

View File

@@ -92,7 +92,7 @@ trait ChartGeneration
Log::debug(sprintf('Start balance for account #%d ("%s) is', $account->id, $account->name), $previous); Log::debug(sprintf('Start balance for account #%d ("%s) is', $account->id, $account->name), $previous);
while ($currentStart <= $end) { while ($currentStart <= $end) {
$format = $currentStart->format('Y-m-d'); $format = $currentStart->format('Y-m-d');
$label = trim($currentStart->isoFormat((string) trans('config.month_and_day_js', [], $locale))); $label = trim($currentStart->isoFormat((string)trans('config.month_and_day_js', [], $locale)));
$balance = $range[$format] ?? $previous; $balance = $range[$format] ?? $previous;
$previous = $balance; $previous = $balance;
$currentStart->addDay(); $currentStart->addDay();

View File

@@ -32,7 +32,6 @@ use FireflyIII\User;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
use Laravel\Passport\Passport; use Laravel\Passport\Passport;
use phpseclib3\Crypt\RSA; use phpseclib3\Crypt\RSA;
use function Safe\file_put_contents; use function Safe\file_put_contents;
/** /**
@@ -73,7 +72,7 @@ trait CreateStuff
/** @var AccountRepositoryInterface $repository */ /** @var AccountRepositoryInterface $repository */
$repository = app(AccountRepositoryInterface::class); $repository = app(AccountRepositoryInterface::class);
$assetAccount = [ $assetAccount = [
'name' => (string) trans('firefly.cash_wallet', [], $language), 'name' => (string)trans('firefly.cash_wallet', [], $language),
'iban' => null, 'iban' => null,
'account_type_name' => 'asset', 'account_type_name' => 'asset',
'virtual_balance' => 0, 'virtual_balance' => 0,
@@ -108,7 +107,7 @@ trait CreateStuff
Log::alert('NO OAuth keys were found. They have been created.'); Log::alert('NO OAuth keys were found. They have been created.');
file_put_contents($publicKey, (string) $key->getPublicKey()); file_put_contents($publicKey, (string)$key->getPublicKey());
file_put_contents($privateKey, $key->toString('PKCS1')); file_put_contents($privateKey, $key->toString('PKCS1'));
} }
@@ -120,7 +119,7 @@ trait CreateStuff
/** @var AccountRepositoryInterface $repository */ /** @var AccountRepositoryInterface $repository */
$repository = app(AccountRepositoryInterface::class); $repository = app(AccountRepositoryInterface::class);
$savingsAccount = [ $savingsAccount = [
'name' => (string) trans('firefly.new_savings_account', ['bank_name' => $request->get('bank_name')], $language), 'name' => (string)trans('firefly.new_savings_account', ['bank_name' => $request->get('bank_name')], $language),
'iban' => null, 'iban' => null,
'account_type_name' => 'asset', 'account_type_name' => 'asset',
'account_type_id' => null, 'account_type_id' => null,

View File

@@ -63,32 +63,6 @@ trait CronRunner
]; ];
} }
protected function webhookCronJob(bool $force, Carbon $date): array
{
/** @var WebhookCronjob $webhook */
$webhook = app(WebhookCronjob::class);
$webhook->setForce($force);
$webhook->setDate($date);
try {
$webhook->fire();
} catch (FireflyException $e) {
return [
'job_fired' => false,
'job_succeeded' => false,
'job_errored' => true,
'message' => $e->getMessage(),
];
}
return [
'job_fired' => $webhook->jobFired,
'job_succeeded' => $webhook->jobSucceeded,
'job_errored' => $webhook->jobErrored,
'message' => $webhook->message,
];
}
protected function exchangeRatesCronJob(bool $force, Carbon $date): array protected function exchangeRatesCronJob(bool $force, Carbon $date): array
{ {
/** @var ExchangeRatesCronjob $exchangeRates */ /** @var ExchangeRatesCronjob $exchangeRates */
@@ -166,4 +140,30 @@ trait CronRunner
'message' => $recurring->message, 'message' => $recurring->message,
]; ];
} }
protected function webhookCronJob(bool $force, Carbon $date): array
{
/** @var WebhookCronjob $webhook */
$webhook = app(WebhookCronjob::class);
$webhook->setForce($force);
$webhook->setDate($date);
try {
$webhook->fire();
} catch (FireflyException $e) {
return [
'job_fired' => false,
'job_succeeded' => false,
'job_errored' => true,
'message' => $e->getMessage(),
];
}
return [
'job_fired' => $webhook->jobFired,
'job_succeeded' => $webhook->jobSucceeded,
'job_errored' => $webhook->jobErrored,
'message' => $webhook->message,
];
}
} }

View File

@@ -40,13 +40,13 @@ trait DateCalculation
*/ */
public function activeDaysLeft(Carbon $start, Carbon $end): int public function activeDaysLeft(Carbon $start, Carbon $end): int
{ {
$difference = (int) ($start->diffInDays($end, true) + 1); $difference = (int)($start->diffInDays($end, true) + 1);
$today = today(config('app.timezone'))->startOfDay(); $today = today(config('app.timezone'))->startOfDay();
if ($start->lte($today) && $end->gte($today)) { if ($start->lte($today) && $end->gte($today)) {
$difference = $today->diffInDays($end) + 1; $difference = $today->diffInDays($end) + 1;
} }
return (int) (0 === $difference ? 1 : $difference); return (int)(0 === $difference ? 1 : $difference);
} }
/** /**
@@ -63,7 +63,7 @@ trait DateCalculation
$difference = $start->diffInDays($today, true) + 1; $difference = $start->diffInDays($today, true) + 1;
} }
return (int) $difference; return (int)$difference;
} }
protected function calculateStep(Carbon $start, Carbon $end): string protected function calculateStep(Carbon $start, Carbon $end): string

View File

@@ -48,7 +48,7 @@ trait GetConfigurationData
E_COMPILE_ERROR | E_RECOVERABLE_ERROR | E_ERROR | E_CORE_ERROR => 'E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR', E_COMPILE_ERROR | E_RECOVERABLE_ERROR | E_ERROR | E_CORE_ERROR => 'E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR',
]; ];
return $array[$value] ?? (string) $value; return $array[$value] ?? (string)$value;
} }
/** /**
@@ -64,7 +64,7 @@ trait GetConfigurationData
$currentStep = $options; $currentStep = $options;
// get the text: // get the text:
$currentStep['intro'] = (string) trans('intro.'.$route.'_'.$key); $currentStep['intro'] = (string)trans('intro.' . $route . '_' . $key);
// save in array: // save in array:
$steps[] = $currentStep; $steps[] = $currentStep;
@@ -133,41 +133,41 @@ trait GetConfigurationData
$todayEnd = app('navigation')->endOfPeriod($todayStart, $viewRange); $todayEnd = app('navigation')->endOfPeriod($todayStart, $viewRange);
if ($todayStart->ne($start) || $todayEnd->ne($end)) { if ($todayStart->ne($start) || $todayEnd->ne($end)) {
$ranges[ucfirst((string) trans('firefly.today'))] = [$todayStart, $todayEnd]; $ranges[ucfirst((string)trans('firefly.today'))] = [$todayStart, $todayEnd];
} }
// last seven days: // last seven days:
$seven = today(config('app.timezone'))->subDays(7); $seven = today(config('app.timezone'))->subDays(7);
$index = (string) trans('firefly.last_seven_days'); $index = (string)trans('firefly.last_seven_days');
$ranges[$index] = [$seven, new Carbon()]; $ranges[$index] = [$seven, new Carbon()];
// last 30 days: // last 30 days:
$thirty = today(config('app.timezone'))->subDays(30); $thirty = today(config('app.timezone'))->subDays(30);
$index = (string) trans('firefly.last_thirty_days'); $index = (string)trans('firefly.last_thirty_days');
$ranges[$index] = [$thirty, new Carbon()]; $ranges[$index] = [$thirty, new Carbon()];
// month to date: // month to date:
$monthBegin = today(config('app.timezone'))->startOfMonth(); $monthBegin = today(config('app.timezone'))->startOfMonth();
$index = (string) trans('firefly.month_to_date'); $index = (string)trans('firefly.month_to_date');
$ranges[$index] = [$monthBegin, new Carbon()]; $ranges[$index] = [$monthBegin, new Carbon()];
// year to date: // year to date:
$yearBegin = today(config('app.timezone'))->startOfYear(); $yearBegin = today(config('app.timezone'))->startOfYear();
$index = (string) trans('firefly.year_to_date'); $index = (string)trans('firefly.year_to_date');
$ranges[$index] = [$yearBegin, new Carbon()]; $ranges[$index] = [$yearBegin, new Carbon()];
// everything // everything
$index = (string) trans('firefly.everything'); $index = (string)trans('firefly.everything');
$ranges[$index] = [$first, new Carbon()]; $ranges[$index] = [$first, new Carbon()];
return [ return [
'title' => $title, 'title' => $title,
'configuration' => [ 'configuration' => [
'apply' => (string) trans('firefly.apply'), 'apply' => (string)trans('firefly.apply'),
'cancel' => (string) trans('firefly.cancel'), 'cancel' => (string)trans('firefly.cancel'),
'from' => (string) trans('firefly.from'), 'from' => (string)trans('firefly.from'),
'to' => (string) trans('firefly.to'), 'to' => (string)trans('firefly.to'),
'customRange' => (string) trans('firefly.customRange'), 'customRange' => (string)trans('firefly.customRange'),
'start' => $start->format('Y-m-d'), 'start' => $start->format('Y-m-d'),
'end' => $end->format('Y-m-d'), 'end' => $end->format('Y-m-d'),
'ranges' => $ranges, 'ranges' => $ranges,
@@ -186,13 +186,13 @@ trait GetConfigurationData
// user is on page with specific instructions: // user is on page with specific instructions:
if ('' !== $specificPage) { if ('' !== $specificPage) {
$routeKey = str_replace('.', '_', $route); $routeKey = str_replace('.', '_', $route);
$elements = config(sprintf('intro.%s', $routeKey.'_'.$specificPage)); $elements = config(sprintf('intro.%s', $routeKey . '_' . $specificPage));
if (is_array($elements) && count($elements) > 0) { if (is_array($elements) && count($elements) > 0) {
foreach ($elements as $key => $options) { foreach ($elements as $key => $options) {
$currentStep = $options; $currentStep = $options;
// get the text: // get the text:
$currentStep['intro'] = (string) trans('intro.'.$route.'_'.$specificPage.'_'.$key); $currentStep['intro'] = (string)trans('intro.' . $route . '_' . $specificPage . '_' . $key);
// save in array: // save in array:
$steps[] = $currentStep; $steps[] = $currentStep;
@@ -207,7 +207,7 @@ trait GetConfigurationData
protected function verifyRecurringCronJob(): void protected function verifyRecurringCronJob(): void
{ {
$config = FireflyConfig::get('last_rt_job', 0); $config = FireflyConfig::get('last_rt_job', 0);
$lastTime = (int) $config?->data; $lastTime = (int)$config?->data;
$now = Carbon::now()->getTimestamp(); $now = Carbon::now()->getTimestamp();
app('log')->debug(sprintf('verifyRecurringCronJob: last time is %d ("%s"), now is %d', $lastTime, $config?->data, $now)); app('log')->debug(sprintf('verifyRecurringCronJob: last time is %d ("%s"), now is %d', $lastTime, $config?->data, $now));
if (0 === $lastTime) { if (0 === $lastTime) {

View File

@@ -87,9 +87,9 @@ trait ModelInformation
/** @var AccountType $mortgage */ /** @var AccountType $mortgage */
$mortgage = $repository->getAccountTypeByType(AccountTypeEnum::MORTGAGE->value); $mortgage = $repository->getAccountTypeByType(AccountTypeEnum::MORTGAGE->value);
$liabilityTypes = [ $liabilityTypes = [
$debt->id => (string) trans(sprintf('firefly.account_type_%s', AccountTypeEnum::DEBT->value)), $debt->id => (string)trans(sprintf('firefly.account_type_%s', AccountTypeEnum::DEBT->value)),
$loan->id => (string) trans(sprintf('firefly.account_type_%s', AccountTypeEnum::LOAN->value)), $loan->id => (string)trans(sprintf('firefly.account_type_%s', AccountTypeEnum::LOAN->value)),
$mortgage->id => (string) trans(sprintf('firefly.account_type_%s', AccountTypeEnum::MORTGAGE->value)), $mortgage->id => (string)trans(sprintf('firefly.account_type_%s', AccountTypeEnum::MORTGAGE->value)),
]; ];
asort($liabilityTypes); asort($liabilityTypes);
@@ -100,7 +100,7 @@ trait ModelInformation
{ {
$roles = []; $roles = [];
foreach (config('firefly.accountRoles') as $role) { foreach (config('firefly.accountRoles') as $role) {
$roles[$role] = (string) trans(sprintf('firefly.account_role_%s', $role)); $roles[$role] = (string)trans(sprintf('firefly.account_role_%s', $role));
} }
return $roles; return $roles;
@@ -118,7 +118,7 @@ trait ModelInformation
$triggers = []; $triggers = [];
foreach ($operators as $key => $operator) { foreach ($operators as $key => $operator) {
if ('user_action' !== $key && false === $operator['alias']) { if ('user_action' !== $key && false === $operator['alias']) {
$triggers[$key] = (string) trans(sprintf('firefly.rule_trigger_%s_choice', $key)); $triggers[$key] = (string)trans(sprintf('firefly.rule_trigger_%s_choice', $key));
} }
} }
asort($triggers); asort($triggers);
@@ -169,7 +169,7 @@ trait ModelInformation
$triggers = []; $triggers = [];
foreach ($operators as $key => $operator) { foreach ($operators as $key => $operator) {
if ('user_action' !== $key && false === $operator['alias']) { if ('user_action' !== $key && false === $operator['alias']) {
$triggers[$key] = (string) trans(sprintf('firefly.rule_trigger_%s_choice', $key)); $triggers[$key] = (string)trans(sprintf('firefly.rule_trigger_%s_choice', $key));
} }
} }
asort($triggers); asort($triggers);

View File

@@ -166,31 +166,23 @@ trait PeriodOverview
/** @var PeriodStatistic $statistic */ /** @var PeriodStatistic $statistic */
foreach ($statistics as $statistic) { foreach ($statistics as $statistic) {
$id = (int) $statistic->transaction_currency_id; $id = (int)$statistic->transaction_currency_id;
$currency = Amount::getTransactionCurrencyById($id); $currency = Amount::getTransactionCurrencyById($id);
$grouped[$id] = [ $grouped[$id] = [
'amount' => (string) $statistic->amount, 'amount' => (string)$statistic->amount,
'count' => (int) $statistic->count, 'count' => (int)$statistic->count,
'currency_id' => $currency->id, 'currency_id' => $currency->id,
'currency_name' => $currency->name, 'currency_name' => $currency->name,
'currency_code' => $currency->code, 'currency_code' => $currency->code,
'currency_symbol' => $currency->symbol, 'currency_symbol' => $currency->symbol,
'currency_decimal_places' => $currency->decimal_places, 'currency_decimal_places' => $currency->decimal_places,
]; ];
$grouped['count'] += (int) $statistic->count; $grouped['count'] += (int)$statistic->count;
} }
return $grouped; return $grouped;
} }
protected function saveGroupedAsStatistics(Account $account, Carbon $start, Carbon $end, string $type, array $array): void
{
unset($array['count']);
foreach ($array as $entry) {
$this->periodStatisticRepo->saveStatistic($account, $entry['currency_id'], $start, $end, $type, $entry['count'], $entry['amount']);
}
}
private function filterTransactionsByType(TransactionTypeEnum $type, array $transactions, Carbon $start, Carbon $end): array private function filterTransactionsByType(TransactionTypeEnum $type, array $transactions, Carbon $start, Carbon $end): array
{ {
$result = []; $result = [];
@@ -298,6 +290,14 @@ trait PeriodOverview
return $return; return $return;
} }
protected function saveGroupedAsStatistics(Account $account, Carbon $start, Carbon $end, string $type, array $array): void
{
unset($array['count']);
foreach ($array as $entry) {
$this->periodStatisticRepo->saveStatistic($account, $entry['currency_id'], $start, $end, $type, $entry['count'], $entry['amount']);
}
}
/** /**
* Overview for single category. Has been refactored recently. * Overview for single category. Has been refactored recently.
* *

View File

@@ -56,10 +56,10 @@ trait RenderPartialViews
/** @var BudgetRepositoryInterface $budgetRepository */ /** @var BudgetRepositoryInterface $budgetRepository */
$budgetRepository = app(BudgetRepositoryInterface::class); $budgetRepository = app(BudgetRepositoryInterface::class);
$budget = $budgetRepository->find((int) $attributes['budgetId']); $budget = $budgetRepository->find((int)$attributes['budgetId']);
$accountRepos = app(AccountRepositoryInterface::class); $accountRepos = app(AccountRepositoryInterface::class);
$account = $accountRepos->find((int) $attributes['accountId']); $account = $accountRepos->find((int)$attributes['accountId']);
if (null === $budget || null === $account) { if (null === $budget || null === $account) {
throw new FireflyException('Could not render popup.report.balance-amount because budget or account is null.'); throw new FireflyException('Could not render popup.report.balance-amount because budget or account is null.');
@@ -115,7 +115,7 @@ trait RenderPartialViews
/** @var PopupReportInterface $popupHelper */ /** @var PopupReportInterface $popupHelper */
$popupHelper = app(PopupReportInterface::class); $popupHelper = app(PopupReportInterface::class);
$budget = $budgetRepository->find((int) $attributes['budgetId']); $budget = $budgetRepository->find((int)$attributes['budgetId']);
if (null === $budget) { if (null === $budget) {
// transactions without a budget. // transactions without a budget.
$budget = new Budget(); $budget = new Budget();
@@ -146,7 +146,7 @@ trait RenderPartialViews
/** @var CategoryRepositoryInterface $categoryRepository */ /** @var CategoryRepositoryInterface $categoryRepository */
$categoryRepository = app(CategoryRepositoryInterface::class); $categoryRepository = app(CategoryRepositoryInterface::class);
$category = $categoryRepository->find((int) $attributes['categoryId']); $category = $categoryRepository->find((int)$attributes['categoryId']);
$journals = $popupHelper->byCategory($category, $attributes); $journals = $popupHelper->byCategory($category, $attributes);
try { try {
@@ -239,7 +239,7 @@ trait RenderPartialViews
/** @var PopupReportInterface $popupHelper */ /** @var PopupReportInterface $popupHelper */
$popupHelper = app(PopupReportInterface::class); $popupHelper = app(PopupReportInterface::class);
$account = $accountRepository->find((int) $attributes['accountId']); $account = $accountRepository->find((int)$attributes['accountId']);
if (null === $account) { if (null === $account) {
return 'This is an unknown account. Apologies.'; return 'This is an unknown account. Apologies.';
@@ -310,7 +310,7 @@ trait RenderPartialViews
$triggers = []; $triggers = [];
foreach ($operators as $key => $operator) { foreach ($operators as $key => $operator) {
if ('user_action' !== $key && false === $operator['alias']) { if ('user_action' !== $key && false === $operator['alias']) {
$triggers[$key] = (string) trans(sprintf('firefly.rule_trigger_%s_choice', $key)); $triggers[$key] = (string)trans(sprintf('firefly.rule_trigger_%s_choice', $key));
} }
} }
asort($triggers); asort($triggers);
@@ -325,7 +325,7 @@ trait RenderPartialViews
$count = ($index + 1); $count = ($index + 1);
try { try {
$rootOperator = OperatorQuerySearch::getRootOperator((string) $entry->trigger_type); $rootOperator = OperatorQuerySearch::getRootOperator((string)$entry->trigger_type);
if (str_starts_with($rootOperator, '-')) { if (str_starts_with($rootOperator, '-')) {
$rootOperator = substr($rootOperator, 1); $rootOperator = substr($rootOperator, 1);
} }
@@ -335,7 +335,7 @@ trait RenderPartialViews
'oldTrigger' => $rootOperator, 'oldTrigger' => $rootOperator,
'oldValue' => $entry->trigger_value, 'oldValue' => $entry->trigger_value,
'oldChecked' => $entry->stop_processing, 'oldChecked' => $entry->stop_processing,
'oldProhibited' => str_starts_with((string) $entry->trigger_type, '-'), 'oldProhibited' => str_starts_with((string)$entry->trigger_type, '-'),
'count' => $count, 'count' => $count,
'triggers' => $triggers, 'triggers' => $triggers,
] ]
@@ -366,7 +366,7 @@ trait RenderPartialViews
/** @var PopupReportInterface $popupHelper */ /** @var PopupReportInterface $popupHelper */
$popupHelper = app(PopupReportInterface::class); $popupHelper = app(PopupReportInterface::class);
$account = $accountRepository->find((int) $attributes['accountId']); $account = $accountRepository->find((int)$attributes['accountId']);
if (null === $account) { if (null === $account) {
return 'This is an unknown category. Apologies.'; return 'This is an unknown category. Apologies.';

View File

@@ -32,10 +32,9 @@ use FireflyIII\Support\Binder\AccountList;
use FireflyIII\User; use FireflyIII\User;
use Illuminate\Contracts\Validation\Validator as ValidatorContract; use Illuminate\Contracts\Validation\Validator as ValidatorContract;
use Illuminate\Routing\Route; use Illuminate\Routing\Route;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Route as RouteFacade;
use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Route as RouteFacade;
use Illuminate\Support\Facades\Validator;
use function Safe\parse_url; use function Safe\parse_url;
/** /**
@@ -67,7 +66,7 @@ trait RequestInformation
'type' => $triggerInfo['type'] ?? '', 'type' => $triggerInfo['type'] ?? '',
'value' => $triggerInfo['value'] ?? '', 'value' => $triggerInfo['value'] ?? '',
'prohibited' => $triggerInfo['prohibited'] ?? false, 'prohibited' => $triggerInfo['prohibited'] ?? false,
'stop_processing' => 1 === (int) ($triggerInfo['stop_processing'] ?? '0'), 'stop_processing' => 1 === (int)($triggerInfo['stop_processing'] ?? '0'),
]; ];
$current = RuleFormRequest::replaceAmountTrigger($current); $current = RuleFormRequest::replaceAmountTrigger($current);
$triggers[] = $current; $triggers[] = $current;
@@ -172,11 +171,11 @@ trait RequestInformation
final protected function validatePassword(User $user, string $current, string $new): bool // get request info final protected function validatePassword(User $user, string $current, string $new): bool // get request info
{ {
if (!Hash::check($current, $user->password)) { if (!Hash::check($current, $user->password)) {
throw new ValidationException((string) trans('firefly.invalid_current_password')); throw new ValidationException((string)trans('firefly.invalid_current_password'));
} }
if ($current === $new) { if ($current === $new) {
throw new ValidationException((string) trans('firefly.should_change')); throw new ValidationException((string)trans('firefly.should_change'));
} }
return true; return true;

View File

@@ -51,7 +51,7 @@ trait RuleManagement
[ [
'oldAction' => $oldAction['type'], 'oldAction' => $oldAction['type'],
'oldValue' => $oldAction['value'] ?? '', 'oldValue' => $oldAction['value'] ?? '',
'oldChecked' => 1 === (int) ($oldAction['stop_processing'] ?? '0'), 'oldChecked' => 1 === (int)($oldAction['stop_processing'] ?? '0'),
'count' => $index + 1, 'count' => $index + 1,
] ]
)->render(); )->render();
@@ -78,7 +78,7 @@ trait RuleManagement
$triggers = []; $triggers = [];
foreach ($operators as $key => $operator) { foreach ($operators as $key => $operator) {
if ('user_action' !== $key && false === $operator['alias']) { if ('user_action' !== $key && false === $operator['alias']) {
$triggers[$key] = (string) trans(sprintf('firefly.rule_trigger_%s_choice', $key)); $triggers[$key] = (string)trans(sprintf('firefly.rule_trigger_%s_choice', $key));
} }
} }
asort($triggers); asort($triggers);
@@ -94,8 +94,8 @@ trait RuleManagement
[ [
'oldTrigger' => OperatorQuerySearch::getRootOperator($oldTrigger['type']), 'oldTrigger' => OperatorQuerySearch::getRootOperator($oldTrigger['type']),
'oldValue' => $oldTrigger['value'] ?? '', 'oldValue' => $oldTrigger['value'] ?? '',
'oldChecked' => 1 === (int) ($oldTrigger['stop_processing'] ?? '0'), 'oldChecked' => 1 === (int)($oldTrigger['stop_processing'] ?? '0'),
'oldProhibited' => 1 === (int) ($oldTrigger['prohibited'] ?? '0'), 'oldProhibited' => 1 === (int)($oldTrigger['prohibited'] ?? '0'),
'count' => $index + 1, 'count' => $index + 1,
'triggers' => $triggers, 'triggers' => $triggers,
] ]
@@ -124,7 +124,7 @@ trait RuleManagement
$triggers = []; $triggers = [];
foreach ($operators as $key => $operator) { foreach ($operators as $key => $operator) {
if ('user_action' !== $key && false === $operator['alias']) { if ('user_action' !== $key && false === $operator['alias']) {
$triggers[$key] = (string) trans(sprintf('firefly.rule_trigger_%s_choice', $key)); $triggers[$key] = (string)trans(sprintf('firefly.rule_trigger_%s_choice', $key));
} }
} }
asort($triggers); asort($triggers);
@@ -132,7 +132,7 @@ trait RuleManagement
$index = 0; $index = 0;
foreach ($submittedOperators as $operator) { foreach ($submittedOperators as $operator) {
$rootOperator = OperatorQuerySearch::getRootOperator($operator['type']); $rootOperator = OperatorQuerySearch::getRootOperator($operator['type']);
$needsContext = (bool) config(sprintf('search.operators.%s.needs_context', $rootOperator)); $needsContext = (bool)config(sprintf('search.operators.%s.needs_context', $rootOperator));
try { try {
$renderedEntries[] = view( $renderedEntries[] = view(
@@ -164,8 +164,8 @@ trait RuleManagement
$repository = app(RuleGroupRepositoryInterface::class); $repository = app(RuleGroupRepositoryInterface::class);
if (0 === $repository->count()) { if (0 === $repository->count()) {
$data = [ $data = [
'title' => (string) trans('firefly.default_rule_group_name'), 'title' => (string)trans('firefly.default_rule_group_name'),
'description' => (string) trans('firefly.default_rule_group_description'), 'description' => (string)trans('firefly.default_rule_group_description'),
'active' => true, 'active' => true,
]; ];

View File

@@ -46,8 +46,7 @@ trait TransactionCalculation
$collector->setAccounts($total) $collector->setAccounts($total)
->setRange($start, $end) ->setRange($start, $end)
->withAccountInformation() ->withAccountInformation()
->setTypes([TransactionTypeEnum::WITHDRAWAL->value]) ->setTypes([TransactionTypeEnum::WITHDRAWAL->value]);
;
return $collector->getExtractedJournals(); return $collector->getExtractedJournals();
} }
@@ -61,8 +60,7 @@ trait TransactionCalculation
$collector = app(GroupCollectorInterface::class); $collector = app(GroupCollectorInterface::class);
$collector->setAccounts($accounts)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::TRANSFER->value]) $collector->setAccounts($accounts)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::TRANSFER->value])
->setTags($tags)->withAccountInformation() ->setTags($tags)->withAccountInformation();
;
return $collector->getExtractedJournals(); return $collector->getExtractedJournals();
} }
@@ -75,8 +73,7 @@ trait TransactionCalculation
/** @var GroupCollectorInterface $collector */ /** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class); $collector = app(GroupCollectorInterface::class);
$collector->setAccounts($accounts)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::TRANSFER->value]) $collector->setAccounts($accounts)->setRange($start, $end)->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::TRANSFER->value])
->setBudgets($budgets)->withAccountInformation() ->setBudgets($budgets)->withAccountInformation();
;
return $collector->getExtractedJournals(); return $collector->getExtractedJournals();
} }
@@ -93,8 +90,7 @@ trait TransactionCalculation
->setRange($start, $end) ->setRange($start, $end)
->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::TRANSFER->value]) ->setTypes([TransactionTypeEnum::WITHDRAWAL->value, TransactionTypeEnum::TRANSFER->value])
->setCategories($categories) ->setCategories($categories)
->withAccountInformation() ->withAccountInformation();
;
return $collector->getExtractedJournals(); return $collector->getExtractedJournals();
} }
@@ -107,8 +103,7 @@ trait TransactionCalculation
/** @var GroupCollectorInterface $collector */ /** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class); $collector = app(GroupCollectorInterface::class);
$collector->setAccounts($accounts)->setRange($start, $end)->setTypes([TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value]) $collector->setAccounts($accounts)->setRange($start, $end)->setTypes([TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value])
->setCategories($categories)->withAccountInformation() ->setCategories($categories)->withAccountInformation();
;
return $collector->getExtractedJournals(); return $collector->getExtractedJournals();
} }
@@ -135,8 +130,7 @@ trait TransactionCalculation
/** @var GroupCollectorInterface $collector */ /** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class); $collector = app(GroupCollectorInterface::class);
$collector->setAccounts($accounts)->setRange($start, $end)->setTypes([TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value]) $collector->setAccounts($accounts)->setRange($start, $end)->setTypes([TransactionTypeEnum::DEPOSIT->value, TransactionTypeEnum::TRANSFER->value])
->setTags($tags)->withAccountInformation() ->setTags($tags)->withAccountInformation();
;
return $collector->getExtractedJournals(); return $collector->getExtractedJournals();
} }

View File

@@ -49,7 +49,7 @@ trait UserNavigation
final protected function getPreviousUrl(string $identifier): string final protected function getPreviousUrl(string $identifier): string
{ {
app('log')->debug(sprintf('Trying to retrieve URL stored under "%s"', $identifier)); app('log')->debug(sprintf('Trying to retrieve URL stored under "%s"', $identifier));
$url = (string) session($identifier); $url = (string)session($identifier);
app('log')->debug(sprintf('The URL is %s', $url)); app('log')->debug(sprintf('The URL is %s', $url));
return app('steam')->getSafeUrl($url, route('index')); return app('steam')->getSafeUrl($url, route('index'));