Fix code quality with rector [skip ci]

This commit is contained in:
James Cole
2025-11-09 09:08:03 +01:00
parent d2610be790
commit 68183a0a0e
209 changed files with 1021 additions and 1248 deletions

View File

@@ -82,21 +82,21 @@ class RecurrenceRepetition extends Model
protected function recurrenceId(): Attribute protected function recurrenceId(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int)$value, get: static fn ($value): int => (int)$value,
); );
} }
protected function repetitionSkip(): Attribute protected function repetitionSkip(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int)$value, get: static fn ($value): int => (int)$value,
); );
} }
protected function weekend(): Attribute protected function weekend(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int)$value, get: static fn ($value): int => (int)$value,
); );
} }
} }

View File

@@ -91,7 +91,7 @@ class RecurrenceTransaction extends Model
protected function amount(): Attribute protected function amount(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (string)$value, get: static fn ($value): string => (string)$value,
); );
} }
@@ -110,42 +110,42 @@ class RecurrenceTransaction extends Model
protected function destinationId(): Attribute protected function destinationId(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int)$value, get: static fn ($value): int => (int)$value,
); );
} }
protected function foreignAmount(): Attribute protected function foreignAmount(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (string)$value, get: static fn ($value): string => (string)$value,
); );
} }
protected function recurrenceId(): Attribute protected function recurrenceId(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int)$value, get: static fn ($value): int => (int)$value,
); );
} }
protected function sourceId(): Attribute protected function sourceId(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int)$value, get: static fn ($value): int => (int)$value,
); );
} }
protected function transactionCurrencyId(): Attribute protected function transactionCurrencyId(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int)$value, get: static fn ($value): int => (int)$value,
); );
} }
protected function userId(): Attribute protected function userId(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int)$value, get: static fn ($value): int => (int)$value,
); );
} }
} }

View File

@@ -58,7 +58,7 @@ class RecurrenceTransactionMeta extends Model
protected function rtId(): Attribute protected function rtId(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int)$value, get: static fn ($value): int => (int)$value,
); );
} }
} }

View File

@@ -113,20 +113,20 @@ class Rule extends Model
protected function description(): Attribute protected function description(): Attribute
{ {
return Attribute::make(set: fn ($value) => ['description' => e($value)]); return Attribute::make(set: fn ($value): array => ['description' => e($value)]);
} }
protected function order(): Attribute protected function order(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int)$value, get: static fn ($value): int => (int)$value,
); );
} }
protected function ruleGroupId(): Attribute protected function ruleGroupId(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int)$value, get: static fn ($value): int => (int)$value,
); );
} }
} }

View File

@@ -80,14 +80,14 @@ class RuleAction extends Model
protected function order(): Attribute protected function order(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int)$value, get: static fn ($value): int => (int)$value,
); );
} }
protected function ruleId(): Attribute protected function ruleId(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int)$value, get: static fn ($value): int => (int)$value,
); );
} }
} }

View File

@@ -99,7 +99,7 @@ class RuleGroup extends Model
protected function order(): Attribute protected function order(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int)$value, get: static fn ($value): int => (int)$value,
); );
} }
} }

View File

@@ -53,14 +53,14 @@ class RuleTrigger extends Model
protected function order(): Attribute protected function order(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int)$value, get: static fn ($value): int => (int)$value,
); );
} }
protected function ruleId(): Attribute protected function ruleId(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int)$value, get: static fn ($value): int => (int)$value,
); );
} }
} }

View File

@@ -113,7 +113,7 @@ class Transaction extends Model
protected function accountId(): Attribute protected function accountId(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int)$value, get: static fn ($value): int => (int)$value,
); );
} }
@@ -151,14 +151,14 @@ class Transaction extends Model
protected function amount(): Attribute protected function amount(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (string)$value, get: static fn ($value): string => (string)$value,
); );
} }
protected function balanceDirty(): Attribute protected function balanceDirty(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => 1 === (int)$value, get: static fn ($value): bool => 1 === (int)$value,
); );
} }
@@ -201,14 +201,14 @@ class Transaction extends Model
protected function foreignAmount(): Attribute protected function foreignAmount(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (string)$value, get: static fn ($value): string => (string)$value,
); );
} }
protected function transactionJournalId(): Attribute protected function transactionJournalId(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int)$value, get: static fn ($value): int => (int)$value,
); );
} }

View File

@@ -115,7 +115,7 @@ class TransactionCurrency extends Model
protected function decimalPlaces(): Attribute protected function decimalPlaces(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int)$value, get: static fn ($value): int => (int)$value,
); );
} }
} }

View File

@@ -232,14 +232,14 @@ class TransactionJournal extends Model
protected function order(): Attribute protected function order(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int)$value, get: static fn ($value): int => (int)$value,
); );
} }
protected function transactionTypeId(): Attribute protected function transactionTypeId(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int)$value, get: static fn ($value): int => (int)$value,
); );
} }

View File

@@ -94,21 +94,21 @@ class TransactionJournalLink extends Model
protected function destinationId(): Attribute protected function destinationId(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int)$value, get: static fn ($value): int => (int)$value,
); );
} }
protected function linkTypeId(): Attribute protected function linkTypeId(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int)$value, get: static fn ($value): int => (int)$value,
); );
} }
protected function sourceId(): Attribute protected function sourceId(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int)$value, get: static fn ($value): int => (int)$value,
); );
} }
} }

View File

@@ -57,7 +57,7 @@ class TransactionJournalMeta extends Model
protected function data(): Attribute protected function data(): Attribute
{ {
return Attribute::make(get: fn ($value) => json_decode((string)$value, false), set: function ($value) { return Attribute::make(get: fn ($value): mixed => json_decode((string)$value, false), set: function ($value): array {
$data = json_encode($value); $data = json_encode($value);
return ['data' => $data, 'hash' => hash('sha256', $data)]; return ['data' => $data, 'hash' => hash('sha256', $data)];
@@ -67,7 +67,7 @@ class TransactionJournalMeta extends Model
protected function transactionJournalId(): Attribute protected function transactionJournalId(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int)$value, get: static fn ($value): int => (int)$value,
); );
} }
} }

View File

@@ -68,7 +68,7 @@ class WebhookAttempt extends Model
protected function webhookMessageId(): Attribute protected function webhookMessageId(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int)$value, get: static fn ($value): int => (int)$value,
); );
} }
} }

View File

@@ -41,7 +41,7 @@ class WebhookDelivery extends Model
protected function key(): Attribute protected function key(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int)$value, get: static fn ($value): int => (int)$value,
); );
} }
} }

View File

@@ -89,14 +89,14 @@ class WebhookMessage extends Model
protected function sent(): Attribute protected function sent(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (bool)$value, get: static fn ($value): bool => (bool)$value,
); );
} }
protected function webhookId(): Attribute protected function webhookId(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int)$value, get: static fn ($value): int => (int)$value,
); );
} }
} }

View File

@@ -41,7 +41,7 @@ class WebhookResponse extends Model
protected function key(): Attribute protected function key(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int)$value, get: static fn ($value): int => (int)$value,
); );
} }
} }

View File

@@ -41,7 +41,7 @@ class WebhookTrigger extends Model
protected function key(): Attribute protected function key(): Attribute
{ {
return Attribute::make( return Attribute::make(
get: static fn ($value) => (int)$value, get: static fn ($value): int => (int)$value,
); );
} }
} }

View File

@@ -42,8 +42,6 @@ class NewAccessToken extends Notification
{ {
use Queueable; use Queueable;
public function __construct() {}
public function toArray(User $notifiable): array public function toArray(User $notifiable): array
{ {
return [ return [

View File

@@ -36,8 +36,6 @@ class UserRegistration extends Notification
{ {
use Queueable; use Queueable;
public function __construct() {}
/** /**
* @SuppressWarnings("PHPMD.UnusedFormalParameter") * @SuppressWarnings("PHPMD.UnusedFormalParameter")
*/ */

View File

@@ -61,7 +61,7 @@ class AppServiceProvider extends ServiceProvider
}); });
// blade extension // blade extension
Blade::directive('activeXRoutePartial', function (string $route) { Blade::directive('activeXRoutePartial', function (string $route): string {
$name = Route::getCurrentRoute()->getName() ?? ''; $name = Route::getCurrentRoute()->getName() ?? '';
if (str_contains($name, $route)) { if (str_contains($name, $route)) {
return 'menu-open'; return 'menu-open';
@@ -69,7 +69,7 @@ class AppServiceProvider extends ServiceProvider
return ''; return '';
}); });
Blade::if('partialroute', function (string $route, string $firstParam = '') { Blade::if('partialroute', function (string $route, string $firstParam = ''): bool {
$name = Route::getCurrentRoute()->getName() ?? ''; $name = Route::getCurrentRoute()->getName() ?? '';
if ('' === $firstParam && str_contains($name, $route)) { if ('' === $firstParam && str_contains($name, $route)) {
return true; return true;
@@ -79,11 +79,7 @@ class AppServiceProvider extends ServiceProvider
$params = Route::getCurrentRoute()->parameters(); $params = Route::getCurrentRoute()->parameters();
$params ??= []; $params ??= [];
$objectType = $params['objectType'] ?? ''; $objectType = $params['objectType'] ?? '';
if ($objectType === $firstParam && str_contains($name, $route)) { return $objectType === $firstParam && str_contains($name, $route);
return true;
}
return false;
}); });
} }

View File

@@ -48,12 +48,12 @@ class AuthServiceProvider extends ServiceProvider
{ {
Auth::provider( Auth::provider(
'remote_user_provider', 'remote_user_provider',
static fn ($app, array $config) => new RemoteUserProvider() static fn ($app, array $config): RemoteUserProvider => new RemoteUserProvider()
); );
Auth::extend( Auth::extend(
'remote_user_guard', 'remote_user_guard',
static fn ($app, string $name, array $config) => new RemoteUserGuard(Auth::createUserProvider($config['provider']), $app) static fn ($app, string $name, array $config): RemoteUserGuard => new RemoteUserGuard(Auth::createUserProvider($config['provider']), $app)
); );
Passport::tokensExpireIn(now()->addDays(14)); Passport::tokensExpireIn(now()->addDays(14));

View File

@@ -51,7 +51,7 @@ class CurrencyServiceProvider extends ServiceProvider
$this->app->bind( $this->app->bind(
static function (Application $app): GroupCurrencyRepositoryInterface { static function (Application $app): GroupCurrencyRepositoryInterface {
/** @var CurrencyRepository $repository */ /** @var CurrencyRepository $repository */
$repository = app(CurrencyRepository::class); $repository = app(GroupCurrencyRepository::class);
// phpstan does not get the reference to auth // phpstan does not get the reference to auth
if ($app->auth->check()) { // @phpstan-ignore-line if ($app->auth->check()) { // @phpstan-ignore-line
$repository->setUser(auth()->user()); $repository->setUser(auth()->user());

View File

@@ -93,7 +93,7 @@ class FireflyServiceProvider extends ServiceProvider
public function boot(): void public function boot(): void
{ {
Validator::resolver( Validator::resolver(
static fn ($translator, $data, $rules, $messages) => new FireflyValidator($translator, $data, $rules, $messages) static fn ($translator, $data, $rules, $messages): FireflyValidator => new FireflyValidator($translator, $data, $rules, $messages)
); );
} }
@@ -107,52 +107,52 @@ class FireflyServiceProvider extends ServiceProvider
{ {
$this->app->bind( $this->app->bind(
'preferences', 'preferences',
static fn () => new Preferences() static fn (): Preferences => new Preferences()
); );
$this->app->bind( $this->app->bind(
'fireflyconfig', 'fireflyconfig',
static fn () => new FireflyConfig() static fn (): FireflyConfig => new FireflyConfig()
); );
$this->app->bind( $this->app->bind(
'navigation', 'navigation',
static fn () => new Navigation() static fn (): Navigation => new Navigation()
); );
$this->app->bind( $this->app->bind(
'amount', 'amount',
static fn () => new Amount() static fn (): Amount => new Amount()
); );
$this->app->bind( $this->app->bind(
'steam', 'steam',
static fn () => new Steam() static fn (): Steam => new Steam()
); );
$this->app->bind( $this->app->bind(
'balance', 'balance',
static fn () => new Balance() static fn (): Balance => new Balance()
); );
$this->app->bind( $this->app->bind(
'expandedform', 'expandedform',
static fn () => new ExpandedForm() static fn (): ExpandedForm => new ExpandedForm()
); );
$this->app->bind( $this->app->bind(
'accountform', 'accountform',
static fn () => new AccountForm() static fn (): AccountForm => new AccountForm()
); );
$this->app->bind( $this->app->bind(
'currencyform', 'currencyform',
static fn () => new CurrencyForm() static fn (): CurrencyForm => new CurrencyForm()
); );
$this->app->bind( $this->app->bind(
'piggybankform', 'piggybankform',
static fn () => new PiggyBankForm() static fn (): PiggyBankForm => new PiggyBankForm()
); );
$this->app->bind( $this->app->bind(
'ruleform', 'ruleform',
static fn () => new RuleForm() static fn (): RuleForm => new RuleForm()
); );
// chart generator: // chart generator:

View File

@@ -53,7 +53,7 @@ class FireflySessionProvider extends ServiceProvider
{ {
$this->app->singleton( $this->app->singleton(
'session', 'session',
static fn ($app) => new SessionManager($app) static fn ($app): SessionManager => new SessionManager($app)
); );
} }

View File

@@ -224,7 +224,7 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac
$disk = Storage::disk('upload'); $disk = Storage::disk('upload');
return $set->each( return $set->each(
static function (Attachment $attachment) use ($disk) { // @phpstan-ignore-line static function (Attachment $attachment) use ($disk): Attachment { // @phpstan-ignore-line
$notes = $attachment->notes()->first(); $notes = $attachment->notes()->first();
$attachment->file_exists = $disk->exists($attachment->fileName()); $attachment->file_exists = $disk->exists($attachment->fileName());
$attachment->notes_text = null !== $notes ? $notes->text : ''; $attachment->notes_text = null !== $notes ? $notes->text : '';
@@ -414,7 +414,7 @@ class AccountRepository implements AccountRepositoryInterface, UserGroupInterfac
public function getMetaValue(Account $account, string $field): ?string public function getMetaValue(Account $account, string $field): ?string
{ {
$result = $account->accountMeta->filter( $result = $account->accountMeta->filter(
static fn (AccountMeta $meta) => strtolower($meta->name) === strtolower($field) static fn (AccountMeta $meta): bool => strtolower($meta->name) === strtolower($field)
); );
if (0 === $result->count()) { if (0 === $result->count()) {
return null; return null;

View File

@@ -23,6 +23,7 @@ declare(strict_types=1);
namespace FireflyIII\Repositories\Attachment; namespace FireflyIII\Repositories\Attachment;
use Illuminate\Support\Facades\Log;
use Exception; use Exception;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Factory\AttachmentFactory; use FireflyIII\Factory\AttachmentFactory;
@@ -78,7 +79,7 @@ class AttachmentRepository implements AttachmentRepositoryInterface, UserGroupIn
try { try {
$unencryptedContent = Crypt::decrypt($encryptedContent); // verified $unencryptedContent = Crypt::decrypt($encryptedContent); // verified
} catch (DecryptException $e) { } catch (DecryptException $e) {
app('log')->debug(sprintf('Could not decrypt attachment #%d but this is fine: %s', $attachment->id, $e->getMessage())); Log::debug(sprintf('Could not decrypt attachment #%d but this is fine: %s', $attachment->id, $e->getMessage()));
$unencryptedContent = $encryptedContent; $unencryptedContent = $encryptedContent;
} }
} }
@@ -161,7 +162,7 @@ class AttachmentRepository implements AttachmentRepositoryInterface, UserGroupIn
try { try {
$dbNote->delete(); $dbNote->delete();
} catch (LogicException $e) { } catch (LogicException $e) {
app('log')->error($e->getMessage()); Log::error($e->getMessage());
} }
} }

View File

@@ -121,7 +121,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface
if (null !== $billId) { if (null !== $billId) {
$searchResult = $this->find($billId); $searchResult = $this->find($billId);
if ($searchResult instanceof Bill) { if ($searchResult instanceof Bill) {
app('log')->debug(sprintf('Found bill based on #%d, will return it.', $billId)); Log::debug(sprintf('Found bill based on #%d, will return it.', $billId));
return $searchResult; return $searchResult;
} }
@@ -129,12 +129,12 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface
if (null !== $billName) { if (null !== $billName) {
$searchResult = $this->findByName($billName); $searchResult = $this->findByName($billName);
if ($searchResult instanceof Bill) { if ($searchResult instanceof Bill) {
app('log')->debug(sprintf('Found bill based on "%s", will return it.', $billName)); Log::debug(sprintf('Found bill based on "%s", will return it.', $billName));
return $searchResult; return $searchResult;
} }
} }
app('log')->debug('Found no bill in findBill()'); Log::debug('Found no bill in findBill()');
return null; return null;
} }
@@ -166,7 +166,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface
$disk = Storage::disk('upload'); $disk = Storage::disk('upload');
return $set->each( return $set->each(
static function (Attachment $attachment) use ($disk) { // @phpstan-ignore-line static function (Attachment $attachment) use ($disk): Attachment { // @phpstan-ignore-line
$notes = $attachment->notes()->first(); $notes = $attachment->notes()->first();
$attachment->file_exists = $disk->exists($attachment->fileName()); $attachment->file_exists = $disk->exists($attachment->fileName());
$attachment->notes_text = null !== $notes ? $notes->text : ''; $attachment->notes_text = null !== $notes ? $notes->text : '';
@@ -307,7 +307,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface
*/ */
public function getPaidDatesInRange(Bill $bill, Carbon $start, Carbon $end): Collection public function getPaidDatesInRange(Bill $bill, Carbon $start, Carbon $end): Collection
{ {
// app('log')->debug('Now in getPaidDatesInRange()'); // \Illuminate\Support\Facades\Log::debug('Now in getPaidDatesInRange()');
Log::debug(sprintf('Search for linked journals between %s and %s', $start->toW3cString(), $end->toW3cString())); Log::debug(sprintf('Search for linked journals between %s and %s', $start->toW3cString(), $end->toW3cString()));
@@ -440,7 +440,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface
$journal = $bill->user->transactionJournals()->find((int) $transaction['transaction_journal_id']); $journal = $bill->user->transactionJournals()->find((int) $transaction['transaction_journal_id']);
$journal->bill_id = $bill->id; $journal->bill_id = $bill->id;
$journal->save(); $journal->save();
app('log')->debug(sprintf('Linked journal #%d to bill #%d', $journal->id, $bill->id)); Log::debug(sprintf('Linked journal #%d to bill #%d', $journal->id, $bill->id));
} }
} }
@@ -459,12 +459,12 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface
// find the most recent date for this bill NOT in the future. Cache this date: // find the most recent date for this bill NOT in the future. Cache this date:
$start = clone $bill->date; $start = clone $bill->date;
$start->startOfDay(); $start->startOfDay();
app('log')->debug('nextExpectedMatch: Start is '.$start->format('Y-m-d')); Log::debug('nextExpectedMatch: Start is '.$start->format('Y-m-d'));
while ($start < $date) { while ($start < $date) {
app('log')->debug(sprintf('$start (%s) < $date (%s)', $start->format('Y-m-d H:i:s'), $date->format('Y-m-d H:i:s'))); Log::debug(sprintf('$start (%s) < $date (%s)', $start->format('Y-m-d H:i:s'), $date->format('Y-m-d H:i:s')));
$start = app('navigation')->addPeriod($start, $bill->repeat_freq, $bill->skip); $start = app('navigation')->addPeriod($start, $bill->repeat_freq, $bill->skip);
app('log')->debug('Start is now '.$start->format('Y-m-d H:i:s')); Log::debug('Start is now '.$start->format('Y-m-d H:i:s'));
} }
$end = app('navigation')->addPeriod($start, $bill->repeat_freq, $bill->skip); $end = app('navigation')->addPeriod($start, $bill->repeat_freq, $bill->skip);
@@ -475,12 +475,12 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface
if ($journalCount > 0) { if ($journalCount > 0) {
// this period had in fact a bill. The new start is the current end, and we create a new end. // this period had in fact a bill. The new start is the current end, and we create a new end.
app('log')->debug(sprintf('Journal count is %d, so start becomes %s', $journalCount, $end->format('Y-m-d'))); Log::debug(sprintf('Journal count is %d, so start becomes %s', $journalCount, $end->format('Y-m-d')));
$start = clone $end; $start = clone $end;
$end = app('navigation')->addPeriod($start, $bill->repeat_freq, $bill->skip); $end = app('navigation')->addPeriod($start, $bill->repeat_freq, $bill->skip);
} }
app('log')->debug('nextExpectedMatch: Final start is '.$start->format('Y-m-d')); Log::debug('nextExpectedMatch: Final start is '.$start->format('Y-m-d'));
app('log')->debug('nextExpectedMatch: Matching end is '.$end->format('Y-m-d')); Log::debug('nextExpectedMatch: Matching end is '.$end->format('Y-m-d'));
$cache->store($start); $cache->store($start);
@@ -597,7 +597,7 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface
public function sumUnpaidInRange(Carbon $start, Carbon $end): array public function sumUnpaidInRange(Carbon $start, Carbon $end): array
{ {
app('log')->debug(sprintf('Now in sumUnpaidInRange("%s", "%s")', $start->format('Y-m-d'), $end->format('Y-m-d'))); Log::debug(sprintf('Now in sumUnpaidInRange("%s", "%s")', $start->format('Y-m-d'), $end->format('Y-m-d')));
$bills = $this->getActiveBills(); $bills = $this->getActiveBills();
$return = []; $return = [];
$convertToPrimary = Amount::convertToPrimary($this->user); $convertToPrimary = Amount::convertToPrimary($this->user);
@@ -605,12 +605,12 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface
/** @var Bill $bill */ /** @var Bill $bill */
foreach ($bills as $bill) { foreach ($bills as $bill) {
// app('log')->debug(sprintf('Processing bill #%d ("%s")', $bill->id, $bill->name)); // \Illuminate\Support\Facades\Log::debug(sprintf('Processing bill #%d ("%s")', $bill->id, $bill->name));
$dates = $this->getPayDatesInRange($bill, $start, $end); $dates = $this->getPayDatesInRange($bill, $start, $end);
$count = $bill->transactionJournals()->after($start)->before($end)->count(); $count = $bill->transactionJournals()->after($start)->before($end)->count();
$total = $dates->count() - $count; $total = $dates->count() - $count;
// app('log')->debug(sprintf('Pay dates: %d, count: %d, left: %d', $dates->count(), $count, $total)); // \Illuminate\Support\Facades\Log::debug(sprintf('Pay dates: %d, count: %d, left: %d', $dates->count(), $count, $total));
// app('log')->debug('dates', $dates->toArray()); // \Illuminate\Support\Facades\Log::debug('dates', $dates->toArray());
$minField = $convertToPrimary && $bill->transactionCurrency->id !== $primary->id ? 'native_amount_min' : 'amount_min'; $minField = $convertToPrimary && $bill->transactionCurrency->id !== $primary->id ? 'native_amount_min' : 'amount_min';
$maxField = $convertToPrimary && $bill->transactionCurrency->id !== $primary->id ? 'native_amount_max' : 'amount_max'; $maxField = $convertToPrimary && $bill->transactionCurrency->id !== $primary->id ? 'native_amount_max' : 'amount_max';
@@ -642,21 +642,21 @@ class BillRepository implements BillRepositoryInterface, UserGroupInterface
{ {
$set = new Collection(); $set = new Collection();
$currentStart = clone $start; $currentStart = clone $start;
// app('log')->debug(sprintf('Now at bill "%s" (%s)', $bill->name, $bill->repeat_freq)); // \Illuminate\Support\Facades\Log::debug(sprintf('Now at bill "%s" (%s)', $bill->name, $bill->repeat_freq));
// app('log')->debug(sprintf('First currentstart is %s', $currentStart->format('Y-m-d'))); // \Illuminate\Support\Facades\Log::debug(sprintf('First currentstart is %s', $currentStart->format('Y-m-d')));
while ($currentStart <= $end) { while ($currentStart <= $end) {
// app('log')->debug(sprintf('Currentstart is now %s.', $currentStart->format('Y-m-d'))); // \Illuminate\Support\Facades\Log::debug(sprintf('Currentstart is now %s.', $currentStart->format('Y-m-d')));
$nextExpectedMatch = $this->nextDateMatch($bill, $currentStart); $nextExpectedMatch = $this->nextDateMatch($bill, $currentStart);
// app('log')->debug(sprintf('Next Date match after %s is %s', $currentStart->format('Y-m-d'), $nextExpectedMatch->format('Y-m-d'))); // \Illuminate\Support\Facades\Log::debug(sprintf('Next Date match after %s is %s', $currentStart->format('Y-m-d'), $nextExpectedMatch->format('Y-m-d')));
if ($nextExpectedMatch > $end) {// If nextExpectedMatch is after end, we continue if ($nextExpectedMatch > $end) {// If nextExpectedMatch is after end, we continue
break; break;
} }
$set->push(clone $nextExpectedMatch); $set->push(clone $nextExpectedMatch);
// app('log')->debug(sprintf('Now %d dates in set.', $set->count())); // \Illuminate\Support\Facades\Log::debug(sprintf('Now %d dates in set.', $set->count()));
$nextExpectedMatch->addDay(); $nextExpectedMatch->addDay();
// app('log')->debug(sprintf('Currentstart (%s) has become %s.', $currentStart->format('Y-m-d'), $nextExpectedMatch->format('Y-m-d'))); // \Illuminate\Support\Facades\Log::debug(sprintf('Currentstart (%s) has become %s.', $currentStart->format('Y-m-d'), $nextExpectedMatch->format('Y-m-d')));
$currentStart = clone $nextExpectedMatch; $currentStart = clone $nextExpectedMatch;
} }

View File

@@ -53,7 +53,7 @@ class AvailableBudgetRepository implements AvailableBudgetRepositoryInterface, U
$end = $availableBudget->end_date->format('Y-m-d'); $end = $availableBudget->end_date->format('Y-m-d');
$key = sprintf('%s-%s-%s', $availableBudget->transaction_currency_id, $start, $end); $key = sprintf('%s-%s-%s', $availableBudget->transaction_currency_id, $start, $end);
if (array_key_exists($key, $exists)) { if (array_key_exists($key, $exists)) {
app('log')->debug(sprintf('Found duplicate AB: %s %s, %s-%s. Has been deleted', $availableBudget->transaction_currency_id, $availableBudget->amount, $start, $end)); Log::debug(sprintf('Found duplicate AB: %s %s, %s-%s. Has been deleted', $availableBudget->transaction_currency_id, $availableBudget->amount, $start, $end));
$availableBudget->delete(); $availableBudget->delete();
} }
$exists[$key] = true; $exists[$key] = true;

View File

@@ -130,7 +130,7 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface, UserGroup
public function getAllBudgetLimitsByCurrency(TransactionCurrency $currency, ?Carbon $start = null, ?Carbon $end = null): Collection public function getAllBudgetLimitsByCurrency(TransactionCurrency $currency, ?Carbon $start = null, ?Carbon $end = null): Collection
{ {
return $this->getAllBudgetLimits($start, $end)->filter( return $this->getAllBudgetLimits($start, $end)->filter(
static fn (BudgetLimit $budgetLimit) => $budgetLimit->transaction_currency_id === $currency->id static fn (BudgetLimit $budgetLimit): bool => $budgetLimit->transaction_currency_id === $currency->id
); );
} }

View File

@@ -307,7 +307,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface
$autoBudget = $this->getAutoBudget($budget); $autoBudget = $this->getAutoBudget($budget);
// first things first: delete when no longer required: // first things first: delete when no longer required:
$autoBudgetType = array_key_exists('auto_budget_type', $data) ? $data['auto_budget_type'] : null; $autoBudgetType = $data['auto_budget_type'] ?? null;
if (0 === $autoBudgetType && $autoBudget instanceof AutoBudget) { if (0 === $autoBudgetType && $autoBudget instanceof AutoBudget) {
// delete! // delete!
@@ -534,7 +534,7 @@ class BudgetRepository implements BudgetRepositoryInterface, UserGroupInterface
$disk = Storage::disk('upload'); $disk = Storage::disk('upload');
return $set->each( return $set->each(
static function (Attachment $attachment) use ($disk) { // @phpstan-ignore-line static function (Attachment $attachment) use ($disk): Attachment { // @phpstan-ignore-line
$notes = $attachment->notes()->first(); $notes = $attachment->notes()->first();
$attachment->file_exists = $disk->exists($attachment->fileName()); $attachment->file_exists = $disk->exists($attachment->fileName());
$attachment->notes_text = null !== $notes ? $notes->text : ''; $attachment->notes_text = null !== $notes ? $notes->text : '';

View File

@@ -54,7 +54,7 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn
*/ */
public function budgetedPerDay(Budget $budget): string public function budgetedPerDay(Budget $budget): string
{ {
app('log')->debug(sprintf('Now with budget #%d "%s"', $budget->id, $budget->name)); Log::debug(sprintf('Now with budget #%d "%s"', $budget->id, $budget->name));
$total = '0'; $total = '0';
$count = 0; $count = 0;
foreach ($budget->budgetlimits as $limit) { foreach ($budget->budgetlimits as $limit) {
@@ -64,13 +64,13 @@ class OperationsRepository implements OperationsRepositoryInterface, UserGroupIn
$perDay = bcdiv((string) $amount, (string) $diff); $perDay = bcdiv((string) $amount, (string) $diff);
$total = bcadd($total, $perDay); $total = bcadd($total, $perDay);
++$count; ++$count;
app('log')->debug(sprintf('Found %d budget limits. Per day is %s, total is %s', $count, $perDay, $total)); Log::debug(sprintf('Found %d budget limits. Per day is %s, total is %s', $count, $perDay, $total));
} }
$avg = $total; $avg = $total;
if ($count > 0) { if ($count > 0) {
$avg = bcdiv($total, (string) $count); $avg = bcdiv($total, (string) $count);
} }
app('log')->debug(sprintf('%s / %d = %s = average.', $total, $count, $avg)); Log::debug(sprintf('%s / %d = %s = average.', $total, $count, $avg));
return $avg; return $avg;
} }

View File

@@ -108,11 +108,11 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf
*/ */
public function findCategory(?int $categoryId, ?string $categoryName): ?Category public function findCategory(?int $categoryId, ?string $categoryName): ?Category
{ {
app('log')->debug('Now in findCategory()'); Log::debug('Now in findCategory()');
app('log')->debug(sprintf('Searching for category with ID #%d...', $categoryId)); Log::debug(sprintf('Searching for category with ID #%d...', $categoryId));
$result = $this->find((int) $categoryId); $result = $this->find((int) $categoryId);
if (!$result instanceof Category) { if (!$result instanceof Category) {
app('log')->debug(sprintf('Searching for category with name %s...', $categoryName)); Log::debug(sprintf('Searching for category with name %s...', $categoryName));
$result = $this->findByName((string) $categoryName); $result = $this->findByName((string) $categoryName);
if (!$result instanceof Category && '' !== (string) $categoryName) { if (!$result instanceof Category && '' !== (string) $categoryName) {
// create it! // create it!
@@ -120,9 +120,9 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf
} }
} }
if ($result instanceof Category) { if ($result instanceof Category) {
app('log')->debug(sprintf('Found category #%d: %s', $result->id, $result->name)); Log::debug(sprintf('Found category #%d: %s', $result->id, $result->name));
} }
app('log')->debug(sprintf('Found category result is null? %s', var_export(!$result instanceof Category, true))); Log::debug(sprintf('Found category result is null? %s', var_export(!$result instanceof Category, true)));
return $result; return $result;
} }
@@ -240,7 +240,7 @@ class CategoryRepository implements CategoryRepositoryInterface, UserGroupInterf
$disk = Storage::disk('upload'); $disk = Storage::disk('upload');
return $set->each( return $set->each(
static function (Attachment $attachment) use ($disk) { // @phpstan-ignore-line static function (Attachment $attachment) use ($disk): Attachment { // @phpstan-ignore-line
$notes = $attachment->notes()->first(); $notes = $attachment->notes()->first();
$attachment->file_exists = $disk->exists($attachment->fileName()); $attachment->file_exists = $disk->exists($attachment->fileName());
$attachment->notes_text = null !== $notes ? $notes->text : ''; $attachment->notes_text = null !== $notes ? $notes->text : '';

View File

@@ -183,9 +183,9 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf
$all = TransactionCurrency::orderBy('code', 'ASC')->get(); $all = TransactionCurrency::orderBy('code', 'ASC')->get();
$local = $this->get(); $local = $this->get();
return $all->map(static function (TransactionCurrency $current) use ($local) { return $all->map(static function (TransactionCurrency $current) use ($local): TransactionCurrency {
$hasId = $local->contains(static fn (TransactionCurrency $entry) => $entry->id === $current->id); $hasId = $local->contains(static fn (TransactionCurrency $entry): bool => $entry->id === $current->id);
$isPrimary = $local->contains(static fn (TransactionCurrency $entry) => 1 === (int)$entry->pivot->group_default && $entry->id === $current->id); $isPrimary = $local->contains(static fn (TransactionCurrency $entry): bool => 1 === (int)$entry->pivot->group_default && $entry->id === $current->id);
$current->userGroupEnabled = $hasId; $current->userGroupEnabled = $hasId;
$current->userGroupNative = $isPrimary; $current->userGroupNative = $isPrimary;
@@ -196,14 +196,13 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf
public function get(): Collection public function get(): Collection
{ {
$all = $this->userGroup->currencies()->orderBy('code', 'ASC')->withPivot(['group_default'])->get(); $all = $this->userGroup->currencies()->orderBy('code', 'ASC')->withPivot(['group_default'])->get();
$all->map(static function (TransactionCurrency $current) { // @phpstan-ignore-line $all->map(static function (TransactionCurrency $current): TransactionCurrency { // @phpstan-ignore-line
$current->userGroupEnabled = true; $current->userGroupEnabled = true;
$current->userGroupNative = 1 === (int)$current->pivot->group_default; $current->userGroupNative = 1 === (int)$current->pivot->group_default;
return $current; return $current;
}); });
/** @var Collection */
return $all; return $all;
} }
@@ -402,7 +401,7 @@ class CurrencyRepository implements CurrencyRepositoryInterface, UserGroupInterf
{ {
Log::debug('Now in update()'); Log::debug('Now in update()');
// can be true, false, null // can be true, false, null
$enabled = array_key_exists('enabled', $data) ? $data['enabled'] : null; $enabled = $data['enabled'] ?? null;
// can be true, false, but method only responds to "true". // can be true, false, but method only responds to "true".
$default = array_key_exists('default', $data) ? $data['default'] : false; $default = array_key_exists('default', $data) ? $data['default'] : false;

View File

@@ -65,7 +65,7 @@ class JournalAPIRepository implements JournalAPIRepositoryInterface, UserGroupIn
$disk = Storage::disk('upload'); $disk = Storage::disk('upload');
return $set->each( return $set->each(
static function (Attachment $attachment) use ($disk) { static function (Attachment $attachment) use ($disk): Attachment {
$notes = $attachment->notes()->first(); $notes = $attachment->notes()->first();
$attachment->file_exists = $disk->exists($attachment->fileName()); $attachment->file_exists = $disk->exists($attachment->fileName());
$attachment->notes_text = null !== $notes ? $notes->text : ''; // TODO should not set notes like this. $attachment->notes_text = null !== $notes ? $notes->text : ''; // TODO should not set notes like this.

View File

@@ -78,13 +78,9 @@ class JournalRepository implements JournalRepositoryInterface, UserGroupInterfac
{ {
/** @var null|TransactionJournal $entry */ /** @var null|TransactionJournal $entry */
$entry = $this->user->transactionJournals()->orderBy('date', 'ASC')->first(['transaction_journals.*']); $entry = $this->user->transactionJournals()->orderBy('date', 'ASC')->first(['transaction_journals.*']);
if (null !== $entry) {
return $entry; return $entry;
} }
return null;
}
public function getDestinationAccount(TransactionJournal $journal): Account public function getDestinationAccount(TransactionJournal $journal): Account
{ {
/** @var null|Transaction $transaction */ /** @var null|Transaction $transaction */
@@ -120,13 +116,9 @@ class JournalRepository implements JournalRepositoryInterface, UserGroupInterfac
{ {
/** @var null|TransactionJournal $entry */ /** @var null|TransactionJournal $entry */
$entry = $this->user->transactionJournals()->orderBy('date', 'DESC')->first(['transaction_journals.*']); $entry = $this->user->transactionJournals()->orderBy('date', 'DESC')->first(['transaction_journals.*']);
if (null !== $entry) {
return $entry; return $entry;
} }
return null;
}
public function getLinkNoteText(TransactionJournalLink $link): string public function getLinkNoteText(TransactionJournalLink $link): string
{ {
/** @var null|Note $note */ /** @var null|Note $note */

View File

@@ -23,6 +23,7 @@ declare(strict_types=1);
namespace FireflyIII\Repositories\LinkType; namespace FireflyIII\Repositories\LinkType;
use Illuminate\Support\Facades\Log;
use Exception; use Exception;
use FireflyIII\Models\LinkType; use FireflyIII\Models\LinkType;
use FireflyIII\Models\Note; use FireflyIII\Models\Note;
@@ -85,7 +86,7 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf
*/ */
public function findLink(TransactionJournal $one, TransactionJournal $two): bool public function findLink(TransactionJournal $one, TransactionJournal $two): bool
{ {
app('log')->debug(sprintf('Now in findLink(%d, %d)', $one->id, $two->id)); Log::debug(sprintf('Now in findLink(%d, %d)', $one->id, $two->id));
$count = TransactionJournalLink::whereDestinationId($one->id)->whereSourceId($two->id)->count(); $count = TransactionJournalLink::whereDestinationId($one->id)->whereSourceId($two->id)->count();
$opposingCount = TransactionJournalLink::whereDestinationId($two->id)->whereSourceId($one->id)->count(); $opposingCount = TransactionJournalLink::whereDestinationId($two->id)->whereSourceId($one->id)->count();
@@ -150,7 +151,7 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf
$merged = $outward->merge($inward); $merged = $outward->merge($inward);
return $merged->filter( return $merged->filter(
static fn (TransactionJournalLink $link) => null !== $link->source && null !== $link->destination static fn (TransactionJournalLink $link): bool => null !== $link->source && null !== $link->destination
); );
} }
@@ -192,13 +193,13 @@ class LinkTypeRepository implements LinkTypeRepositoryInterface, UserGroupInterf
$link = new TransactionJournalLink(); $link = new TransactionJournalLink();
$link->linkType()->associate($linkType); $link->linkType()->associate($linkType);
if ('inward' === $information['direction']) { if ('inward' === $information['direction']) {
app('log')->debug(sprintf('Link type is inwards ("%s"), so %d is source and %d is destination.', $linkType->inward, $inward->id, $outward->id)); Log::debug(sprintf('Link type is inwards ("%s"), so %d is source and %d is destination.', $linkType->inward, $inward->id, $outward->id));
$link->source()->associate($inward); $link->source()->associate($inward);
$link->destination()->associate($outward); $link->destination()->associate($outward);
} }
if ('outward' === $information['direction']) { if ('outward' === $information['direction']) {
app('log')->debug(sprintf('Link type is inwards ("%s"), so %d is source and %d is destination.', $linkType->outward, $outward->id, $inward->id)); Log::debug(sprintf('Link type is inwards ("%s"), so %d is source and %d is destination.', $linkType->outward, $outward->id, $inward->id));
$link->source()->associate($outward); $link->source()->associate($outward);
$link->destination()->associate($inward); $link->destination()->associate($inward);
} }

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Repositories\ObjectGroup; namespace FireflyIII\Repositories\ObjectGroup;
use Illuminate\Support\Facades\Log;
use FireflyIII\Models\ObjectGroup; use FireflyIII\Models\ObjectGroup;
use FireflyIII\Models\PiggyBank; use FireflyIII\Models\PiggyBank;
use FireflyIII\Support\Repositories\UserGroup\UserGroupInterface; use FireflyIII\Support\Repositories\UserGroup\UserGroupInterface;
@@ -96,14 +97,14 @@ class ObjectGroupRepository implements ObjectGroupRepositoryInterface, UserGroup
public function resetOrder(): void public function resetOrder(): void
{ {
app('log')->debug('Now in resetOrder'); Log::debug('Now in resetOrder');
$list = $this->get(); $list = $this->get();
$index = 1; $index = 1;
/** @var ObjectGroup $objectGroup */ /** @var ObjectGroup $objectGroup */
foreach ($list as $objectGroup) { foreach ($list as $objectGroup) {
if ($index !== $objectGroup->order) { if ($index !== $objectGroup->order) {
app('log')->debug( Log::debug(
sprintf('objectGroup #%d ("%s"): order should %d be but is %d.', $objectGroup->id, $objectGroup->title, $index, $objectGroup->order) sprintf('objectGroup #%d ("%s"): order should %d be but is %d.', $objectGroup->id, $objectGroup->title, $index, $objectGroup->order)
); );
$objectGroup->order = $index; $objectGroup->order = $index;
@@ -166,7 +167,7 @@ class ObjectGroupRepository implements ObjectGroupRepositoryInterface, UserGroup
$objectGroup->save(); $objectGroup->save();
} }
app('log')->debug(sprintf('Objectgroup #%d order is now %d', $objectGroup->id, $newOrder)); Log::debug(sprintf('Objectgroup #%d order is now %d', $objectGroup->id, $newOrder));
return $objectGroup; return $objectGroup;
} }

View File

@@ -118,7 +118,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface, UserGroupInte
$disk = Storage::disk('upload'); $disk = Storage::disk('upload');
return $set->each( return $set->each(
static function (Attachment $attachment) use ($disk) { // @phpstan-ignore-line static function (Attachment $attachment) use ($disk): Attachment { // @phpstan-ignore-line
$notes = $attachment->notes()->first(); $notes = $attachment->notes()->first();
$attachment->file_exists = $disk->exists($attachment->fileName()); $attachment->file_exists = $disk->exists($attachment->fileName());
$attachment->notes_text = null !== $notes ? $notes->text : ''; $attachment->notes_text = null !== $notes ? $notes->text : '';

View File

@@ -79,7 +79,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte
foreach ($set as $journalMeta) { foreach ($set as $journalMeta) {
$count = TransactionJournalMeta::where(static function (Builder $q2) use ($date): void { $count = TransactionJournalMeta::where(static function (Builder $q2) use ($date): void {
$string = (string) $date; $string = (string) $date;
app('log')->debug(sprintf('Search for date: %s', json_encode($string))); Log::debug(sprintf('Search for date: %s', json_encode($string)));
$q2->where('name', 'recurrence_date'); $q2->where('name', 'recurrence_date');
$q2->where('data', json_encode($string)); $q2->where('data', json_encode($string));
}) })
@@ -87,7 +87,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte
->count() ->count()
; ;
if ($count > 0) { if ($count > 0) {
app('log')->debug(sprintf('Looks like journal #%d was already created', $journalMeta->transaction_journal_id)); Log::debug(sprintf('Looks like journal #%d was already created', $journalMeta->transaction_journal_id));
return true; return true;
} }
@@ -373,7 +373,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte
*/ */
public function getXOccurrencesSince(RecurrenceRepetition $repetition, Carbon $date, Carbon $afterDate, int $count): array public function getXOccurrencesSince(RecurrenceRepetition $repetition, Carbon $date, Carbon $afterDate, int $count): array
{ {
app('log')->debug('Now in getXOccurrencesSince()'); Log::debug('Now in getXOccurrencesSince()');
$skipMod = $repetition->repetition_skip + 1; $skipMod = $repetition->repetition_skip + 1;
$occurrences = []; $occurrences = [];
@@ -433,7 +433,7 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte
*/ */
public function repetitionDescription(RecurrenceRepetition $repetition): string public function repetitionDescription(RecurrenceRepetition $repetition): string
{ {
app('log')->debug('Now in repetitionDescription()'); Log::debug('Now in repetitionDescription()');
/** @var Preference $pref */ /** @var Preference $pref */
$pref = app('preferences')->getForUser($this->user, 'language', config('firefly.default_language', 'en_US')); $pref = app('preferences')->getForUser($this->user, 'language', config('firefly.default_language', 'en_US'));
@@ -546,8 +546,8 @@ class RecurringRepository implements RecurringRepositoryInterface, UserGroupInte
$mutator = clone $start; $mutator = clone $start;
$mutator->startOfDay(); $mutator->startOfDay();
$skipMod = $repetition->repetition_skip + 1; $skipMod = $repetition->repetition_skip + 1;
app('log')->debug(sprintf('Calculating occurrences for rep type "%s"', $repetition->repetition_type)); Log::debug(sprintf('Calculating occurrences for rep type "%s"', $repetition->repetition_type));
app('log')->debug(sprintf('Mutator is now: %s', $mutator->format('Y-m-d'))); Log::debug(sprintf('Mutator is now: %s', $mutator->format('Y-m-d')));
if ('daily' === $repetition->repetition_type) { if ('daily' === $repetition->repetition_type) {
$occurrences = $this->getDailyInRange($mutator, $end, $skipMod); $occurrences = $this->getDailyInRange($mutator, $end, $skipMod);

View File

@@ -23,6 +23,7 @@ declare(strict_types=1);
namespace FireflyIII\Repositories\Rule; namespace FireflyIII\Repositories\Rule;
use Illuminate\Support\Facades\Log;
use Exception; use Exception;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Rule; use FireflyIII\Models\Rule;
@@ -261,9 +262,9 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface
// reset order: // reset order:
$this->resetRuleOrder($ruleGroup); $this->resetRuleOrder($ruleGroup);
app('log')->debug('Done with resetting.'); Log::debug('Done with resetting.');
if (array_key_exists('order', $data)) { if (array_key_exists('order', $data)) {
app('log')->debug(sprintf('User has submitted order %d', $data['order'])); Log::debug(sprintf('User has submitted order %d', $data['order']));
$this->setOrder($rule, $data['order']); $this->setOrder($rule, $data['order']);
} }
@@ -318,7 +319,7 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface
$groupId = $rule->rule_group_id; $groupId = $rule->rule_group_id;
$maxOrder = $this->maxOrder($rule->ruleGroup); $maxOrder = $this->maxOrder($rule->ruleGroup);
$newOrder = $newOrder > $maxOrder ? $maxOrder + 1 : $newOrder; $newOrder = $newOrder > $maxOrder ? $maxOrder + 1 : $newOrder;
app('log')->debug(sprintf('New order will be %d', $newOrder)); Log::debug(sprintf('New order will be %d', $newOrder));
if ($newOrder > $oldOrder) { if ($newOrder > $oldOrder) {
$this->user->rules() $this->user->rules()
@@ -329,7 +330,7 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface
->decrement('rules.order') ->decrement('rules.order')
; ;
$rule->order = $newOrder; $rule->order = $newOrder;
app('log')->debug(sprintf('Order of rule #%d ("%s") is now %d', $rule->id, $rule->title, $newOrder)); Log::debug(sprintf('Order of rule #%d ("%s") is now %d', $rule->id, $rule->title, $newOrder));
$rule->save(); $rule->save();
return; return;
@@ -343,7 +344,7 @@ class RuleRepository implements RuleRepositoryInterface, UserGroupInterface
->increment('rules.order') ->increment('rules.order')
; ;
$rule->order = $newOrder; $rule->order = $newOrder;
app('log')->debug(sprintf('Order of rule #%d ("%s") is now %d', $rule->id, $rule->title, $newOrder)); Log::debug(sprintf('Order of rule #%d ("%s") is now %d', $rule->id, $rule->title, $newOrder));
$rule->save(); $rule->save();
} }

View File

@@ -280,11 +280,11 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte
Log::debug(sprintf('Will filter getRuleGroupsWithRules on "%s".', $filter)); Log::debug(sprintf('Will filter getRuleGroupsWithRules on "%s".', $filter));
return $groups->map( return $groups->map(
static function (RuleGroup $group) use ($filter) { // @phpstan-ignore-line static function (RuleGroup $group) use ($filter): RuleGroup { // @phpstan-ignore-line
Log::debug(sprintf('Now filtering group #%d', $group->id)); Log::debug(sprintf('Now filtering group #%d', $group->id));
// filter the rules in the rule group: // filter the rules in the rule group:
$group->rules = $group->rules->filter( $group->rules = $group->rules->filter(
static function (Rule $rule) use ($filter, $group) { static function (Rule $rule) use ($filter, $group): bool {
Log::debug(sprintf('Now filtering rule #%d', $rule->id)); Log::debug(sprintf('Now filtering rule #%d', $rule->id));
foreach ($rule->ruleTriggers as $trigger) { foreach ($rule->ruleTriggers as $trigger) {
if ('user_action' === $trigger->trigger_type && $filter === $trigger->trigger_value) { if ('user_action' === $trigger->trigger_type && $filter === $trigger->trigger_value) {
@@ -337,11 +337,11 @@ class RuleGroupRepository implements RuleGroupRepositoryInterface, UserGroupInte
Log::debug(sprintf('Will filter getRuleGroupsWithRules on "%s".', $filter)); Log::debug(sprintf('Will filter getRuleGroupsWithRules on "%s".', $filter));
return $groups->map( return $groups->map(
static function (RuleGroup $group) use ($filter) { // @phpstan-ignore-line static function (RuleGroup $group) use ($filter): RuleGroup { // @phpstan-ignore-line
Log::debug(sprintf('Now filtering group #%d', $group->id)); Log::debug(sprintf('Now filtering group #%d', $group->id));
// filter the rules in the rule group: // filter the rules in the rule group:
$group->rules = $group->rules->filter( $group->rules = $group->rules->filter(
static function (Rule $rule) use ($filter, $group) { static function (Rule $rule) use ($filter, $group): bool {
Log::debug(sprintf('Now filtering rule #%d', $rule->id)); Log::debug(sprintf('Now filtering rule #%d', $rule->id));
foreach ($rule->ruleTriggers as $trigger) { foreach ($rule->ruleTriggers as $trigger) {
if ('user_action' === $trigger->trigger_type && $filter === $trigger->trigger_value) { if ('user_action' === $trigger->trigger_type && $filter === $trigger->trigger_value) {

View File

@@ -110,7 +110,6 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface
public function firstUseDate(Tag $tag): ?Carbon public function firstUseDate(Tag $tag): ?Carbon
{ {
/** @var null|Carbon */
return $tag->transactionJournals()->orderBy('date', 'ASC')->first()?->date; return $tag->transactionJournals()->orderBy('date', 'ASC')->first()?->date;
} }
@@ -137,13 +136,13 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface
// add date range (or not): // add date range (or not):
if (null === $year) { if (null === $year) {
app('log')->debug('Get tags without a date.'); Log::debug('Get tags without a date.');
$tagQuery->whereNull('tags.date'); $tagQuery->whereNull('tags.date');
} }
if (null !== $year) { 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)); 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)); $tagQuery->where('tags.date', '>=', sprintf('%d-01-01 00:00:00', $year))->where('tags.date', '<=', sprintf('%d-12-31 23:59:59', $year));
} }
$collection = $tagQuery->get(); $collection = $tagQuery->get();
@@ -177,7 +176,6 @@ class TagRepository implements TagRepositoryInterface, UserGroupInterface
public function lastUseDate(Tag $tag): ?Carbon public function lastUseDate(Tag $tag): ?Carbon
{ {
/** @var null|Carbon */
return $tag->transactionJournals()->orderBy('date', 'DESC')->first()?->date; return $tag->transactionJournals()->orderBy('date', 'DESC')->first()?->date;
} }

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Repositories\TransactionGroup; namespace FireflyIII\Repositories\TransactionGroup;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon; use Carbon\Carbon;
use Exception; use Exception;
use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Enums\TransactionTypeEnum;
@@ -78,7 +79,7 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface,
public function destroy(TransactionGroup $group): void public function destroy(TransactionGroup $group): void
{ {
app('log')->debug(sprintf('Now in %s', __METHOD__)); Log::debug(sprintf('Now in %s', __METHOD__));
$service = new TransactionGroupDestroyService(); $service = new TransactionGroupDestroyService();
$service->destroy($group); $service->destroy($group);
} }
@@ -406,13 +407,13 @@ class TransactionGroupRepository implements TransactionGroupRepositoryInterface,
try { try {
return $factory->create($data); return $factory->create($data);
} catch (DuplicateTransactionException $e) { } catch (DuplicateTransactionException $e) {
app('log')->warning('Group repository caught group factory with a duplicate exception!'); Log::warning('Group repository caught group factory with a duplicate exception!');
throw new DuplicateTransactionException($e->getMessage(), 0, $e); throw new DuplicateTransactionException($e->getMessage(), 0, $e);
} catch (FireflyException $e) { } catch (FireflyException $e) {
app('log')->warning('Group repository caught group factory with an exception!'); Log::warning('Group repository caught group factory with an exception!');
app('log')->error($e->getMessage()); Log::error($e->getMessage());
app('log')->error($e->getTraceAsString()); Log::error($e->getTraceAsString());
throw new FireflyException($e->getMessage(), 0, $e); throw new FireflyException($e->getMessage(), 0, $e);
} }

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Repositories\TransactionType; namespace FireflyIII\Repositories\TransactionType;
use Illuminate\Support\Facades\Log;
use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Enums\TransactionTypeEnum;
use FireflyIII\Models\TransactionType; use FireflyIII\Models\TransactionType;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
@@ -35,9 +36,9 @@ class TransactionTypeRepository implements TransactionTypeRepositoryInterface
{ {
public function findTransactionType(?TransactionType $type, ?string $typeString): TransactionType public function findTransactionType(?TransactionType $type, ?string $typeString): TransactionType
{ {
app('log')->debug('Now looking for a transaction type.'); Log::debug('Now looking for a transaction type.');
if ($type instanceof TransactionType) { if ($type instanceof TransactionType) {
app('log')->debug(sprintf('Found $type in parameters, its %s. Will return it.', $type->type)); Log::debug(sprintf('Found $type in parameters, its %s. Will return it.', $type->type));
return $type; return $type;
} }
@@ -46,7 +47,7 @@ class TransactionTypeRepository implements TransactionTypeRepositoryInterface
if (!$search instanceof TransactionType) { if (!$search instanceof TransactionType) {
$search = $this->findByType(TransactionTypeEnum::WITHDRAWAL->value); $search = $this->findByType(TransactionTypeEnum::WITHDRAWAL->value);
} }
app('log')->debug(sprintf('Tried to search for "%s", came up with "%s". Will return it.', $typeString, $search->type)); Log::debug(sprintf('Tried to search for "%s", came up with "%s". Will return it.', $typeString, $search->type));
return $search; return $search;
} }

View File

@@ -23,6 +23,7 @@ declare(strict_types=1);
namespace FireflyIII\Repositories\User; namespace FireflyIII\Repositories\User;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon; use Carbon\Carbon;
use Exception; use Exception;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
@@ -97,7 +98,7 @@ class UserRepository implements UserRepositoryInterface
public function deleteInvite(InvitedUser $invite): void public function deleteInvite(InvitedUser $invite): void
{ {
app('log')->debug(sprintf('Deleting invite #%d', $invite->id)); Log::debug(sprintf('Deleting invite #%d', $invite->id));
$invite->delete(); $invite->delete();
} }
@@ -106,7 +107,7 @@ class UserRepository implements UserRepositoryInterface
*/ */
public function destroy(User $user): bool public function destroy(User $user): bool
{ {
app('log')->debug(sprintf('Calling delete() on user %d', $user->id)); Log::debug(sprintf('Calling delete() on user %d', $user->id));
$user->groupMemberships()->delete(); $user->groupMemberships()->delete();
$user->delete(); $user->delete();
@@ -123,7 +124,7 @@ class UserRepository implements UserRepositoryInterface
foreach ($groups as $group) { foreach ($groups as $group) {
$count = $group->groupMemberships()->count(); $count = $group->groupMemberships()->count();
if (0 === $count) { if (0 === $count) {
app('log')->info(sprintf('Deleted empty group #%d ("%s")', $group->id, $group->title)); Log::info(sprintf('Deleted empty group #%d ("%s")', $group->id, $group->title));
$group->delete(); $group->delete();
} }
} }
@@ -198,33 +199,12 @@ class UserRepository implements UserRepositoryInterface
*/ */
public function getUserData(User $user): array public function getUserData(User $user): array
{ {
$return = []; return ['has_2fa' => null !== $user->mfa_secret, 'is_admin' => $this->hasRole($user, 'owner'), 'blocked' => 1 === (int) $user->blocked, 'blocked_code' => $user->blocked_code, 'accounts' => $user->accounts()->count(), 'journals' => $user->transactionJournals()->count(), 'transactions' => $user->transactions()->count(), 'attachments' => $user->attachments()->count(), 'attachments_size' => $user->attachments()->sum('size'), 'bills' => $user->bills()->count(), 'categories' => $user->categories()->count(), 'budgets' => $user->budgets()->count(), 'budgets_with_limits' => BudgetLimit::distinct()
// two factor:
$return['has_2fa'] = null !== $user->mfa_secret;
$return['is_admin'] = $this->hasRole($user, 'owner');
$return['blocked'] = 1 === (int) $user->blocked;
$return['blocked_code'] = $user->blocked_code;
$return['accounts'] = $user->accounts()->count();
$return['journals'] = $user->transactionJournals()->count();
$return['transactions'] = $user->transactions()->count();
$return['attachments'] = $user->attachments()->count();
$return['attachments_size'] = $user->attachments()->sum('size');
$return['bills'] = $user->bills()->count();
$return['categories'] = $user->categories()->count();
$return['budgets'] = $user->budgets()->count();
$return['budgets_with_limits'] = BudgetLimit::distinct()
->leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id') ->leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id')
->where('amount', '>', 0) ->where('amount', '>', 0)
->whereNull('budgets.deleted_at') ->whereNull('budgets.deleted_at')
->where('budgets.user_id', $user->id) ->where('budgets.user_id', $user->id)
->count('budget_limits.budget_id') ->count('budget_limits.budget_id'), 'rule_groups' => $user->ruleGroups()->count(), 'rules' => $user->rules()->count(), 'tags' => $user->tags()->count()];
;
$return['rule_groups'] = $user->ruleGroups()->count();
$return['rules'] = $user->rules()->count();
$return['tags'] = $user->tags()->count();
return $return;
} }
public function hasRole(Authenticatable|User|null $user, string $role): bool public function hasRole(Authenticatable|User|null $user, string $role): bool
@@ -327,7 +307,7 @@ class UserRepository implements UserRepositoryInterface
{ {
$roleObject = Role::where('name', $role)->first(); $roleObject = Role::where('name', $role)->first();
if (null === $roleObject) { if (null === $roleObject) {
app('log')->error(sprintf('Could not find role "%s" in attachRole()', $role)); Log::error(sprintf('Could not find role "%s" in attachRole()', $role));
return false; return false;
} }
@@ -336,7 +316,7 @@ class UserRepository implements UserRepositoryInterface
$user->roles()->attach($roleObject); $user->roles()->attach($roleObject);
} catch (QueryException $e) { } catch (QueryException $e) {
// don't care // don't care
app('log')->error(sprintf('Query exception when giving user a role: %s', $e->getMessage())); Log::error(sprintf('Query exception when giving user a role: %s', $e->getMessage()));
} }
return true; return true;

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Repositories\UserGroup; namespace FireflyIII\Repositories\UserGroup;
use Illuminate\Support\Facades\Log;
use FireflyIII\Enums\UserRoleEnum; use FireflyIII\Enums\UserRoleEnum;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Factory\UserGroupFactory; use FireflyIII\Factory\UserGroupFactory;
@@ -47,7 +48,7 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte
public function destroy(UserGroup $userGroup): void public function destroy(UserGroup $userGroup): void
{ {
app('log')->debug(sprintf('Going to destroy user group #%d ("%s").', $userGroup->id, $userGroup->title)); Log::debug(sprintf('Going to destroy user group #%d ("%s").', $userGroup->id, $userGroup->title));
$memberships = $userGroup->groupMemberships()->get(); $memberships = $userGroup->groupMemberships()->get();
/** @var GroupMembership $membership */ /** @var GroupMembership $membership */
@@ -57,19 +58,19 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte
if (null === $user) { if (null === $user) {
continue; continue;
} }
app('log')->debug(sprintf('Processing membership #%d (user #%d "%s")', $membership->id, $user->id, $user->email)); Log::debug(sprintf('Processing membership #%d (user #%d "%s")', $membership->id, $user->id, $user->email));
// user has memberships of other groups? // user has memberships of other groups?
$count = $user->groupMemberships()->where('user_group_id', '!=', $userGroup->id)->count(); $count = $user->groupMemberships()->where('user_group_id', '!=', $userGroup->id)->count();
if (0 === $count) { if (0 === $count) {
app('log')->debug('User has no other memberships and needs a new user group.'); Log::debug('User has no other memberships and needs a new user group.');
$newUserGroup = $this->createNewUserGroup($user); $newUserGroup = $this->createNewUserGroup($user);
$user->user_group_id = $newUserGroup->id; $user->user_group_id = $newUserGroup->id;
$user->save(); $user->save();
app('log')->debug(sprintf('Make new group #%d ("%s")', $newUserGroup->id, $newUserGroup->title)); Log::debug(sprintf('Make new group #%d ("%s")', $newUserGroup->id, $newUserGroup->title));
} }
// user has other memberships, select one at random and assign it to the user. // user has other memberships, select one at random and assign it to the user.
if ($count > 0) { if ($count > 0) {
app('log')->debug('User has other memberships and will be assigned a new administration.'); Log::debug('User has other memberships and will be assigned a new administration.');
/** @var GroupMembership $first */ /** @var GroupMembership $first */
$first = $user->groupMemberships()->where('user_group_id', '!=', $userGroup->id)->inRandomOrder()->first(); $first = $user->groupMemberships()->where('user_group_id', '!=', $userGroup->id)->inRandomOrder()->first();
@@ -91,7 +92,7 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte
} }
} }
$userGroup->delete(); $userGroup->delete();
app('log')->debug('Done!'); Log::debug('Done!');
} }
/** /**
@@ -216,23 +217,23 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte
public function updateMembership(UserGroup $userGroup, array $data): UserGroup public function updateMembership(UserGroup $userGroup, array $data): UserGroup
{ {
$owner = UserRole::whereTitle(UserRoleEnum::OWNER)->first(); $owner = UserRole::whereTitle(UserRoleEnum::OWNER)->first();
app('log')->debug('in update membership'); Log::debug('in update membership');
/** @var null|User $user */ /** @var null|User $user */
$user = null; $user = null;
if (array_key_exists('id', $data)) { if (array_key_exists('id', $data)) {
/** @var null|User $user */ /** @var null|User $user */
$user = User::find($data['id']); $user = User::find($data['id']);
app('log')->debug('Found user by ID'); Log::debug('Found user by ID');
} }
if (array_key_exists('email', $data) && '' !== (string)$data['email']) { if (array_key_exists('email', $data) && '' !== (string)$data['email']) {
/** @var null|User $user */ /** @var null|User $user */
$user = User::whereEmail($data['email'])->first(); $user = User::whereEmail($data['email'])->first();
app('log')->debug('Found user by email'); Log::debug('Found user by email');
} }
if (null === $user) { if (null === $user) {
// should throw error, but validator already catches this. // should throw error, but validator already catches this.
app('log')->debug('No user found'); Log::debug('No user found');
return $userGroup; return $userGroup;
} }
@@ -244,13 +245,13 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte
$lastUserId = $userGroup->groupMemberships()->distinct()->first(['group_memberships.user_id'])->user_id; $lastUserId = $userGroup->groupMemberships()->distinct()->first(['group_memberships.user_id'])->user_id;
// if this is also the user we're editing right now, and we remove all of their roles: // if this is also the user we're editing right now, and we remove all of their roles:
if ($lastUserId === (int)$user->id && 0 === count($data['roles'])) { if ($lastUserId === (int)$user->id && 0 === count($data['roles'])) {
app('log')->debug('User is last in this group, refuse to act'); Log::debug('User is last in this group, refuse to act');
throw new FireflyException('You cannot remove the last member from this user group. Delete the user group instead.'); throw new FireflyException('You cannot remove the last member from this user group. Delete the user group instead.');
} }
// if this is also the user we're editing right now, and do not grant them the owner role: // if this is also the user we're editing right now, and do not grant them the owner role:
if ($lastUserId === (int)$user->id && count($data['roles']) > 0 && !in_array(UserRoleEnum::OWNER->value, $data['roles'], true)) { if ($lastUserId === (int)$user->id && count($data['roles']) > 0 && !in_array(UserRoleEnum::OWNER->value, $data['roles'], true)) {
app('log')->debug('User needs to have owner role in this group, refuse to act'); Log::debug('User needs to have owner role in this group, refuse to act');
throw new FireflyException('The last member in this user group must get or keep the "owner" role.'); throw new FireflyException('The last member in this user group must get or keep the "owner" role.');
} }
@@ -267,7 +268,7 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte
&& (0 === count($data['roles']) && (0 === count($data['roles'])
|| (count($data['roles']) > 0 // @phpstan-ignore-line || (count($data['roles']) > 0 // @phpstan-ignore-line
&& !in_array(UserRoleEnum::OWNER->value, $data['roles'], true)))) { && !in_array(UserRoleEnum::OWNER->value, $data['roles'], true)))) {
app('log')->debug('User needs to keep owner role in this group, refuse to act'); Log::debug('User needs to keep owner role in this group, refuse to act');
throw new FireflyException('The last owner in this user group must keep the "owner" role.'); throw new FireflyException('The last owner in this user group must keep the "owner" role.');
} }
@@ -294,12 +295,12 @@ class UserGroupRepository implements UserGroupRepositoryInterface, UserGroupInte
private function simplifyListByName(array $roles): array private function simplifyListByName(array $roles): array
{ {
if (in_array(UserRoleEnum::OWNER->value, $roles, true)) { if (in_array(UserRoleEnum::OWNER->value, $roles, true)) {
app('log')->debug(sprintf('List of roles is [%1$s] but this includes "%2$s", so return [%2$s]', implode(',', $roles), UserRoleEnum::OWNER->value)); Log::debug(sprintf('List of roles is [%1$s] but this includes "%2$s", so return [%2$s]', implode(',', $roles), UserRoleEnum::OWNER->value));
return [UserRoleEnum::OWNER->value]; return [UserRoleEnum::OWNER->value];
} }
if (in_array(UserRoleEnum::FULL->value, $roles, true)) { if (in_array(UserRoleEnum::FULL->value, $roles, true)) {
app('log')->debug(sprintf('List of roles is [%1$s] but this includes "%2$s", so return [%2$s]', implode(',', $roles), UserRoleEnum::FULL->value)); Log::debug(sprintf('List of roles is [%1$s] but this includes "%2$s", so return [%2$s]', implode(',', $roles), UserRoleEnum::FULL->value));
return [UserRoleEnum::FULL->value]; return [UserRoleEnum::FULL->value];
} }

View File

@@ -92,7 +92,7 @@ class WebhookRepository implements WebhookRepositoryInterface, UserGroupInterfac
->where('webhook_messages.errored', 0) ->where('webhook_messages.errored', 0)
->get(['webhook_messages.*']) ->get(['webhook_messages.*'])
->filter( ->filter(
static fn (WebhookMessage $message) // @phpstan-ignore-line static fn (WebhookMessage $message): bool // @phpstan-ignore-line
=> $message->webhookAttempts()->count() <= 2 => $message->webhookAttempts()->count() <= 2
)->splice(0, 3) )->splice(0, 3)
; ;

View File

@@ -47,7 +47,6 @@ class IsValidAccountTypeList implements ValidationRule
} }
$keys = array_keys($this->types); $keys = array_keys($this->types);
foreach ($values as $entry) { foreach ($values as $entry) {
$entry = (string) $entry;
if (!in_array($entry, $keys, true)) { if (!in_array($entry, $keys, true)) {
$fail('validation.invalid_account_list')->translate(); $fail('validation.invalid_account_list')->translate();
} }

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Rules; namespace FireflyIII\Rules;
use Illuminate\Support\Facades\Log;
use Closure; use Closure;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Account; use FireflyIII\Models\Account;
@@ -47,7 +48,7 @@ class BelongsUser implements ValidationRule
return; return;
} }
app('log')->debug(sprintf('Going to validate %s', $attribute)); Log::debug(sprintf('Going to validate %s', $attribute));
$result = match ($attribute) { $result = match ($attribute) {
'piggy_bank_id' => $this->validatePiggyBankId((int) $value), 'piggy_bank_id' => $this->validatePiggyBankId((int) $value),
@@ -126,7 +127,7 @@ class BelongsUser implements ValidationRule
private function validateBillName(string $value): bool private function validateBillName(string $value): bool
{ {
$count = $this->countField(Bill::class, 'name', $value); $count = $this->countField(Bill::class, 'name', $value);
app('log')->debug(sprintf('Result of countField for bill name "%s" is %d', $value, $count)); Log::debug(sprintf('Result of countField for bill name "%s" is %d', $value, $count));
return 1 === $count; return 1 === $count;
} }
@@ -147,10 +148,10 @@ class BelongsUser implements ValidationRule
$count = 0; $count = 0;
foreach ($objects as $object) { foreach ($objects as $object) {
$objectValue = trim((string) $object->{$field}); // @phpstan-ignore-line $objectValue = trim((string) $object->{$field}); // @phpstan-ignore-line
app('log')->debug(sprintf('Comparing object "%s" with value "%s"', $objectValue, $value)); Log::debug(sprintf('Comparing object "%s" with value "%s"', $objectValue, $value));
if ($objectValue === $value) { if ($objectValue === $value) {
++$count; ++$count;
app('log')->debug(sprintf('Hit! Count is now %d', $count)); Log::debug(sprintf('Hit! Count is now %d', $count));
} }
} }

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Rules; namespace FireflyIII\Rules;
use Illuminate\Support\Facades\Log;
use Closure; use Closure;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Account; use FireflyIII\Models\Account;
@@ -56,7 +57,7 @@ class BelongsUserGroup implements ValidationRule
return; return;
} }
app('log')->debug(sprintf('Group: Going to validate "%s"', $attribute)); Log::debug(sprintf('Group: Going to validate "%s"', $attribute));
$result = match ($attribute) { $result = match ($attribute) {
'piggy_bank_id' => $this->validatePiggyBankId((int) $value), 'piggy_bank_id' => $this->validatePiggyBankId((int) $value),
@@ -121,10 +122,10 @@ class BelongsUserGroup implements ValidationRule
$count = 0; $count = 0;
foreach ($objects as $object) { foreach ($objects as $object) {
$objectValue = trim((string) $object->{$field}); // @phpstan-ignore-line $objectValue = trim((string) $object->{$field}); // @phpstan-ignore-line
app('log')->debug(sprintf('Comparing object "%s" with value "%s"', $objectValue, $value)); Log::debug(sprintf('Comparing object "%s" with value "%s"', $objectValue, $value));
if ($objectValue === $value) { if ($objectValue === $value) {
++$count; ++$count;
app('log')->debug(sprintf('Hit! Count is now %d', $count)); Log::debug(sprintf('Hit! Count is now %d', $count));
} }
} }
@@ -154,7 +155,7 @@ class BelongsUserGroup implements ValidationRule
private function validateBillName(string $value): bool private function validateBillName(string $value): bool
{ {
$count = $this->countField(Bill::class, 'name', $value); $count = $this->countField(Bill::class, 'name', $value);
app('log')->debug(sprintf('Result of countField for bill name "%s" is %d', $value, $count)); Log::debug(sprintf('Result of countField for bill name "%s" is %d', $value, $count));
return 1 === $count; return 1 === $count;
} }

View File

@@ -28,8 +28,6 @@ use Closure;
use FireflyIII\Enums\UserRoleEnum; use FireflyIII\Enums\UserRoleEnum;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Account; use FireflyIII\Models\Account;
use FireflyIII\Repositories\UserGroup\UserGroupRepositoryInterface;
use FireflyIII\User;
use Illuminate\Auth\Access\AuthorizationException; use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Contracts\Validation\ValidationRule; use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
@@ -37,14 +35,11 @@ use Override;
class IsAllowedGroupAction implements ValidationRule class IsAllowedGroupAction implements ValidationRule
{ {
private array $acceptedRoles; // you need these roles to do anything with any endpoint.
private readonly UserGroupRepositoryInterface $repository; private array $acceptedRoles = [UserRoleEnum::OWNER, UserRoleEnum::FULL];
public function __construct(private readonly string $className, private readonly string $methodName) public function __construct(private readonly string $className, private readonly string $methodName)
{ {
// you need these roles to do anything with any endpoint.
$this->acceptedRoles = [UserRoleEnum::OWNER, UserRoleEnum::FULL];
$this->repository = app(UserGroupRepositoryInterface::class);
} }
/** /**
@@ -69,68 +64,16 @@ class IsAllowedGroupAction implements ValidationRule
break; break;
} }
} }
$this->validateUserGroup((int)$value, $fail); $this->validateUserGroup();
} }
private function validateUserGroup(int $userGroupId, Closure $fail): void private function validateUserGroup(): void
{ {
try { try {
throw new FireflyException('Here we are'); throw new FireflyException('Here we are');
} catch (FireflyException $e) { } catch (FireflyException $e) {
Log::error($e->getTraceAsString()); Log::error($e->getTraceAsString());
} }
exit('here we are'); exit('here we are');
Log::debug(sprintf('validateUserGroup: %s', static::class));
if (!auth()->check()) {
Log::debug('validateUserGroup: user is not logged in, return NULL.');
$fail('validation.no_auth_user_group')->translate();
return;
}
/** @var User $user */
$user = auth()->user();
if (0 !== $userGroupId) {
Log::debug(sprintf('validateUserGroup: user group submitted, search for memberships in group #%d.', $userGroupId));
}
if (0 === $userGroupId) {
$userGroupId = $user->user_group_id;
Log::debug(sprintf('validateUserGroup: no user group submitted, use default group #%d.', $userGroupId));
}
$this->repository->setUser($user);
$memberships = $this->repository->getMembershipsFromGroupId($userGroupId);
if (0 === $memberships->count()) {
Log::debug(sprintf('validateUserGroup: user has no access to group #%d.', $userGroupId));
$fail('validation.no_access_user_group')->translate();
return;
}
// need to get the group from the membership:
$userGroup = $this->repository->getById($userGroupId);
if (null === $userGroup) {
Log::debug(sprintf('validateUserGroup: group #%d does not exist.', $userGroupId));
$fail('validation.belongs_user_or_user_group')->translate();
return;
}
Log::debug(sprintf('validateUserGroup: validate access of user to group #%d ("%s").', $userGroupId, $userGroup->title));
Log::debug(sprintf('validateUserGroup: have %d roles to check.', count($this->acceptedRoles)), $this->acceptedRoles);
/** @var UserRoleEnum $role */
foreach ($this->acceptedRoles as $role) {
if ($user->hasRoleInGroupOrOwner($userGroup, $role)) {
Log::debug(sprintf('validateUserGroup: User has role "%s" in group #%d, return.', $role->value, $userGroupId));
return;
}
Log::debug(sprintf('validateUserGroup: User does NOT have role "%s" in group #%d, continue searching.', $role->value, $userGroupId));
}
Log::debug('validateUserGroup: User does NOT have enough rights to access endpoint.');
$fail('validation.belongs_user_or_user_group')->translate();
} }
} }

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Rules; namespace FireflyIII\Rules;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon; use Carbon\Carbon;
use Carbon\Exceptions\InvalidDateException; use Carbon\Exceptions\InvalidDateException;
use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidFormatException;
@@ -51,13 +52,13 @@ class IsDateOrTime implements ValidationRule
try { try {
Carbon::createFromFormat('Y-m-d', $value); Carbon::createFromFormat('Y-m-d', $value);
} catch (InvalidDateException $e) { // @phpstan-ignore-line } catch (InvalidDateException $e) { // @phpstan-ignore-line
app('log')->error(sprintf('"%s" is not a valid date: %s', $value, $e->getMessage())); Log::error(sprintf('"%s" is not a valid date: %s', $value, $e->getMessage()));
$fail('validation.date_or_time')->translate(); $fail('validation.date_or_time')->translate();
return; return;
} catch (InvalidFormatException $e) { } catch (InvalidFormatException $e) {
app('log')->error(sprintf('"%s" is of an invalid format: %s', $value, $e->getMessage())); Log::error(sprintf('"%s" is of an invalid format: %s', $value, $e->getMessage()));
$fail('validation.date_or_time')->translate(); $fail('validation.date_or_time')->translate();
@@ -71,13 +72,13 @@ class IsDateOrTime implements ValidationRule
try { try {
Carbon::parse($value); Carbon::parse($value);
} catch (InvalidDateException $e) { // @phpstan-ignore-line } catch (InvalidDateException $e) { // @phpstan-ignore-line
app('log')->error(sprintf('"%s" is not a valid date or time: %s', $value, $e->getMessage())); Log::error(sprintf('"%s" is not a valid date or time: %s', $value, $e->getMessage()));
$fail('validation.date_or_time')->translate(); $fail('validation.date_or_time')->translate();
return; return;
} catch (InvalidFormatException $e) { } catch (InvalidFormatException $e) {
app('log')->error(sprintf('"%s" is of an invalid format: %s', $value, $e->getMessage())); Log::error(sprintf('"%s" is of an invalid format: %s', $value, $e->getMessage()));
$fail('validation.date_or_time')->translate(); $fail('validation.date_or_time')->translate();

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Rules; namespace FireflyIII\Rules;
use Illuminate\Support\Facades\Log;
use Closure; use Closure;
use FireflyIII\Models\UserGroup; use FireflyIII\Models\UserGroup;
use FireflyIII\Repositories\User\UserRepositoryInterface; use FireflyIII\Repositories\User\UserRepositoryInterface;
@@ -42,7 +43,7 @@ class IsDefaultUserGroupName implements ValidationRule
*/ */
public function validate(string $attribute, mixed $value, Closure $fail): void public function validate(string $attribute, mixed $value, Closure $fail): void
{ {
app('log')->debug(sprintf('Now in %s(%s)', __METHOD__, $value)); Log::debug(sprintf('Now in %s(%s)', __METHOD__, $value));
// are you owner of this group and the name is the same? fail. // are you owner of this group and the name is the same? fail.
/** @var User $user */ /** @var User $user */

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Rules; namespace FireflyIII\Rules;
use Illuminate\Support\Facades\Log;
use Closure; use Closure;
use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Enums\TransactionTypeEnum;
use FireflyIII\Validation\AccountValidator; use FireflyIII\Validation\AccountValidator;
@@ -39,7 +40,7 @@ class IsTransferAccount implements ValidationRule
*/ */
public function validate(string $attribute, mixed $value, Closure $fail): void public function validate(string $attribute, mixed $value, Closure $fail): void
{ {
app('log')->debug(sprintf('Now in %s(%s)', __METHOD__, $value)); Log::debug(sprintf('Now in %s(%s)', __METHOD__, $value));
/** @var AccountValidator $validator */ /** @var AccountValidator $validator */
$validator = app(AccountValidator::class); $validator = app(AccountValidator::class);
@@ -48,13 +49,13 @@ class IsTransferAccount implements ValidationRule
$validAccount = $validator->validateSource(['name' => (string) $value]); $validAccount = $validator->validateSource(['name' => (string) $value]);
if (true === $validAccount) { if (true === $validAccount) {
app('log')->debug('Found account based on name. Return true.'); Log::debug('Found account based on name. Return true.');
// found by name, use repos to return. // found by name, use repos to return.
return; return;
} }
$validAccount = $validator->validateSource(['id' => (int) $value]); $validAccount = $validator->validateSource(['id' => (int) $value]);
app('log')->debug(sprintf('Search by id (%d), result is %s.', (int) $value, var_export($validAccount, true))); Log::debug(sprintf('Search by id (%d), result is %s.', (int) $value, var_export($validAccount, true)));
if (false === $validAccount) { if (false === $validAccount) {
$fail('validation.not_transfer_account')->translate(); $fail('validation.not_transfer_account')->translate();

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Rules; namespace FireflyIII\Rules;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon; use Carbon\Carbon;
use Carbon\Exceptions\InvalidDateException; use Carbon\Exceptions\InvalidDateException;
use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidFormatException;
@@ -54,13 +55,13 @@ class IsValidDateRange implements ValidationRule
$left = Carbon::parse($value); $left = Carbon::parse($value);
$right = Carbon::parse($otherValue); $right = Carbon::parse($otherValue);
} catch (InvalidDateException $e) { // @phpstan-ignore-line } catch (InvalidDateException $e) { // @phpstan-ignore-line
app('log')->error(sprintf('"%s" or "%s" is not a valid date or time: %s', $value, $otherValue, $e->getMessage())); Log::error(sprintf('"%s" or "%s" is not a valid date or time: %s', $value, $otherValue, $e->getMessage()));
$fail('validation.date_or_time')->translate(); $fail('validation.date_or_time')->translate();
return; return;
} catch (InvalidFormatException $e) { } catch (InvalidFormatException $e) {
app('log')->error(sprintf('"%s" or "%s" is of an invalid format: %s', $value, $otherValue, $e->getMessage())); Log::error(sprintf('"%s" or "%s" is of an invalid format: %s', $value, $otherValue, $e->getMessage()));
$fail('validation.date_or_time')->translate(); $fail('validation.date_or_time')->translate();

View File

@@ -41,7 +41,7 @@ class IsValidZeroOrMoreAmount implements ValidationRule
*/ */
public function validate(string $attribute, mixed $value, Closure $fail): void public function validate(string $attribute, mixed $value, Closure $fail): void
{ {
if (true === $this->nullable && null === $value) { if ($this->nullable && null === $value) {
return; return;
} }
$value = (string) $value; $value = (string) $value;

View File

@@ -47,7 +47,6 @@ class IsValidTransactionTypeList implements ValidationRule
} }
$keys = array_keys($this->transactionTypes); $keys = array_keys($this->transactionTypes);
foreach ($values as $entry) { foreach ($values as $entry) {
$entry = (string)$entry;
if (!in_array($entry, $keys, true)) { if (!in_array($entry, $keys, true)) {
$fail('validation.invalid_transaction_type_list')->translate(); $fail('validation.invalid_transaction_type_list')->translate();
} }

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Rules; namespace FireflyIII\Rules;
use Illuminate\Support\Facades\Log;
use Closure; use Closure;
use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Enums\AccountTypeEnum;
use FireflyIII\Models\Account; use FireflyIII\Models\Account;
@@ -55,7 +56,7 @@ class UniqueAccountNumber implements ValidationRule
if ('asset' === $this->expectedType) { if ('asset' === $this->expectedType) {
$this->expectedType = AccountTypeEnum::ASSET->value; $this->expectedType = AccountTypeEnum::ASSET->value;
} }
app('log')->debug(sprintf('Expected type is "%s"', $this->expectedType)); Log::debug(sprintf('Expected type is "%s"', $this->expectedType));
} }
/** /**
@@ -87,9 +88,9 @@ class UniqueAccountNumber implements ValidationRule
foreach ($maxCounts as $type => $max) { foreach ($maxCounts as $type => $max) {
$count = $this->countHits($type, $value); $count = $this->countHits($type, $value);
app('log')->debug(sprintf('Count for "%s" and account number "%s" is %d', $type, $value, $count)); Log::debug(sprintf('Count for "%s" and account number "%s" is %d', $type, $value, $count));
if ($count > $max) { if ($count > $max) {
app('log')->debug( Log::debug(
sprintf( sprintf(
'account number "%s" is in use with %d account(s) of type "%s", which is too much for expected type "%s"', 'account number "%s" is in use with %d account(s) of type "%s", which is too much for expected type "%s"',
$value, $value,
@@ -104,7 +105,7 @@ class UniqueAccountNumber implements ValidationRule
return; return;
} }
} }
app('log')->debug('Account number is valid.'); Log::debug('Account number is valid.');
} }
private function getMaxOccurrences(): array private function getMaxOccurrences(): array

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Rules; namespace FireflyIII\Rules;
use Illuminate\Support\Facades\Log;
use Closure; use Closure;
use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Enums\AccountTypeEnum;
use FireflyIII\Models\Account; use FireflyIII\Models\Account;
@@ -35,14 +36,13 @@ use Illuminate\Contracts\Validation\ValidationRule;
*/ */
class UniqueIban implements ValidationRule class UniqueIban implements ValidationRule
{ {
private array $expectedTypes; private array $expectedTypes = [];
/** /**
* Create a new rule instance. * Create a new rule instance.
*/ */
public function __construct(private readonly ?Account $account, ?string $expectedType) public function __construct(private readonly ?Account $account, ?string $expectedType)
{ {
$this->expectedTypes = [];
if (null === $expectedType) { if (null === $expectedType) {
return; return;
} }
@@ -104,9 +104,9 @@ class UniqueIban implements ValidationRule
$value = Steam::filterSpaces($value); $value = Steam::filterSpaces($value);
$count = $this->countHits($type, $value); $count = $this->countHits($type, $value);
app('log')->debug(sprintf('Count for "%s" and IBAN "%s" is %d', $type, $value, $count)); Log::debug(sprintf('Count for "%s" and IBAN "%s" is %d', $type, $value, $count));
if ($count > $max) { if ($count > $max) {
app('log')->debug( Log::debug(
sprintf( sprintf(
'IBAN "%s" is in use with %d account(s) of type "%s", which is too much for expected types "%s"', 'IBAN "%s" is in use with %d account(s) of type "%s", which is too much for expected types "%s"',
$value, $value,

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Rules; namespace FireflyIII\Rules;
use Illuminate\Support\Facades\Log;
use Closure; use Closure;
use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionJournal;
use Illuminate\Contracts\Validation\ValidationRule; use Illuminate\Contracts\Validation\ValidationRule;
@@ -38,7 +39,7 @@ class ValidJournals implements ValidationRule
*/ */
public function validate(string $attribute, mixed $value, Closure $fail): void public function validate(string $attribute, mixed $value, Closure $fail): void
{ {
app('log')->debug('In ValidJournals::passes'); Log::debug('In ValidJournals::passes');
if (!is_array($value)) { if (!is_array($value)) {
return; return;
} }
@@ -46,13 +47,13 @@ class ValidJournals implements ValidationRule
foreach ($value as $journalId) { foreach ($value as $journalId) {
$count = TransactionJournal::where('id', $journalId)->where('user_id', $userId)->count(); $count = TransactionJournal::where('id', $journalId)->where('user_id', $userId)->count();
if (0 === $count) { if (0 === $count) {
app('log')->debug(sprintf('Count for transaction #%d and user #%d is zero! Return FALSE', $journalId, $userId)); Log::debug(sprintf('Count for transaction #%d and user #%d is zero! Return FALSE', $journalId, $userId));
$fail('validation.invalid_selection')->translate(); $fail('validation.invalid_selection')->translate();
return; return;
} }
} }
app('log')->debug('Return true!'); Log::debug('Return true!');
} }
} }

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Rules; namespace FireflyIII\Rules;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon; use Carbon\Carbon;
use Closure; use Closure;
use Illuminate\Contracts\Validation\ValidationRule; use Illuminate\Contracts\Validation\ValidationRule;
@@ -105,7 +106,7 @@ class ValidRecurrenceRepetitionValue implements ValidationRule
try { try {
Carbon::createFromFormat('Y-m-d', $dateString); Carbon::createFromFormat('Y-m-d', $dateString);
} catch (InvalidArgumentException $e) { } catch (InvalidArgumentException $e) {
app('log')->debug(sprintf('Could not parse date %s: %s', $dateString, $e->getMessage())); Log::debug(sprintf('Could not parse date %s: %s', $dateString, $e->getMessage()));
return false; return false;
} }

View File

@@ -149,7 +149,7 @@ class UpdateRequest implements UpdateRequestInterface
$latest = substr($latest, 1); $latest = substr($latest, 1);
} }
if (str_starts_with($current, 'develop')) { if (str_starts_with($current, 'develop')) {
return $this->parseResultDevelop($current, $latest, $information); return $this->parseResultDevelop($current, $latest);
} }
$compare = version_compare($latest, $current); $compare = version_compare($latest, $current);
@@ -183,7 +183,7 @@ class UpdateRequest implements UpdateRequestInterface
return $this->releasedNewVersion($current, $latest, $released); return $this->releasedNewVersion($current, $latest, $released);
} }
private function parseResultDevelop(string $current, string $latest, array $information): array private function parseResultDevelop(string $current, string $latest): array
{ {
Log::debug(sprintf('User is running develop version "%s"', $current)); Log::debug(sprintf('User is running develop version "%s"', $current));
$compare = $this->compareDevelopVersions($current, $latest); $compare = $this->compareDevelopVersions($current, $latest);

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Services\Internal\Destroy; namespace FireflyIII\Services\Internal\Destroy;
use Illuminate\Support\Facades\Log;
use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Enums\TransactionTypeEnum;
use FireflyIII\Models\Account; use FireflyIII\Models\Account;
use FireflyIII\Models\PiggyBank; use FireflyIII\Models\PiggyBank;
@@ -65,7 +66,7 @@ class AccountDestroyService
private function destroyOpeningBalance(Account $account): void private function destroyOpeningBalance(Account $account): void
{ {
app('log')->debug(sprintf('Searching for opening balance for account #%d "%s"', $account->id, $account->name)); Log::debug(sprintf('Searching for opening balance for account #%d "%s"', $account->id, $account->name));
$set = $account->transactions() $set = $account->transactions()
->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id') ->leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id') ->leftJoin('transaction_types', 'transaction_types.id', '=', 'transaction_journals.transaction_type_id')
@@ -74,7 +75,7 @@ class AccountDestroyService
; ;
if ($set->count() > 0) { if ($set->count() > 0) {
$journalId = $set->first()->transaction_journal_id; $journalId = $set->first()->transaction_journal_id;
app('log')->debug(sprintf('Found opening balance journal with ID #%d', $journalId)); Log::debug(sprintf('Found opening balance journal with ID #%d', $journalId));
// get transactions with this journal (should be just one): // get transactions with this journal (should be just one):
$transactions = Transaction::where('transaction_journal_id', $journalId) $transactions = Transaction::where('transaction_journal_id', $journalId)
@@ -84,9 +85,9 @@ class AccountDestroyService
/** @var Transaction $transaction */ /** @var Transaction $transaction */
foreach ($transactions as $transaction) { foreach ($transactions as $transaction) {
app('log')->debug(sprintf('Found transaction with ID #%d', $transaction->id)); Log::debug(sprintf('Found transaction with ID #%d', $transaction->id));
$ibAccount = $transaction->account; $ibAccount = $transaction->account;
app('log')->debug(sprintf('Connected to account #%d "%s"', $ibAccount->id, $ibAccount->name)); Log::debug(sprintf('Connected to account #%d "%s"', $ibAccount->id, $ibAccount->name));
$ibAccount->accountMeta()->delete(); $ibAccount->accountMeta()->delete();
$transaction->delete(); $transaction->delete();
@@ -105,7 +106,7 @@ class AccountDestroyService
public function moveTransactions(Account $account, Account $moveTo): void public function moveTransactions(Account $account, Account $moveTo): void
{ {
app('log')->debug(sprintf('Move from account #%d to #%d', $account->id, $moveTo->id)); Log::debug(sprintf('Move from account #%d to #%d', $account->id, $moveTo->id));
DB::table('transactions')->where('account_id', $account->id)->update(['account_id' => $moveTo->id]); DB::table('transactions')->where('account_id', $account->id)->update(['account_id' => $moveTo->id]);
$collection = Transaction::groupBy('transaction_journal_id', 'account_id')->where('account_id', $moveTo->id)->get(['transaction_journal_id', 'account_id', DB::raw('count(*) as the_count')]); $collection = Transaction::groupBy('transaction_journal_id', 'account_id')->where('account_id', $moveTo->id)->get(['transaction_journal_id', 'account_id', DB::raw('count(*) as the_count')]);
@@ -123,7 +124,7 @@ class AccountDestroyService
$journalId = $row->transaction_journal_id; $journalId = $row->transaction_journal_id;
$journal = $user->transactionJournals()->find($journalId); $journal = $user->transactionJournals()->find($journalId);
if (null !== $journal) { if (null !== $journal) {
app('log')->debug(sprintf('Deleted journal #%d because it has the same source as destination.', $journal->id)); Log::debug(sprintf('Deleted journal #%d because it has the same source as destination.', $journal->id));
$service->destroy($journal); $service->destroy($journal);
} }
} }

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Services\Internal\Destroy; namespace FireflyIII\Services\Internal\Destroy;
use Illuminate\Support\Facades\Log;
use FireflyIII\Models\Attachment; use FireflyIII\Models\Attachment;
use FireflyIII\Models\Transaction; use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionJournal;
@@ -38,18 +39,18 @@ class JournalDestroyService
{ {
public function destroy(TransactionJournal $journal): void public function destroy(TransactionJournal $journal): void
{ {
app('log')->debug(sprintf('Now in %s', __METHOD__)); Log::debug(sprintf('Now in %s', __METHOD__));
/** @var Transaction $transaction */ /** @var Transaction $transaction */
foreach ($journal->transactions()->get() as $transaction) { foreach ($journal->transactions()->get() as $transaction) {
app('log')->debug(sprintf('Will now delete transaction #%d', $transaction->id)); Log::debug(sprintf('Will now delete transaction #%d', $transaction->id));
$transaction->delete(); $transaction->delete();
} }
// also delete journal_meta entries. // also delete journal_meta entries.
/** @var TransactionJournalMeta $meta */ /** @var TransactionJournalMeta $meta */
foreach ($journal->transactionJournalMeta()->get() as $meta) { foreach ($journal->transactionJournalMeta()->get() as $meta) {
app('log')->debug(sprintf('Will now delete meta-entry #%d', $meta->id)); Log::debug(sprintf('Will now delete meta-entry #%d', $meta->id));
$meta->delete(); $meta->delete();
} }

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Services\Internal\Destroy; namespace FireflyIII\Services\Internal\Destroy;
use Illuminate\Support\Facades\Log;
use FireflyIII\Events\DestroyedTransactionGroup; use FireflyIII\Events\DestroyedTransactionGroup;
use FireflyIII\Models\TransactionGroup; use FireflyIII\Models\TransactionGroup;
@@ -34,7 +35,7 @@ class TransactionGroupDestroyService
{ {
public function destroy(TransactionGroup $transactionGroup): void public function destroy(TransactionGroup $transactionGroup): void
{ {
app('log')->debug(sprintf('Now in %s', __METHOD__)); Log::debug(sprintf('Now in %s', __METHOD__));
/** @var JournalDestroyService $service */ /** @var JournalDestroyService $service */
$service = app(JournalDestroyService::class); $service = app(JournalDestroyService::class);

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Services\Internal\Support; namespace FireflyIII\Services\Internal\Support;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon; use Carbon\Carbon;
use Deprecated; use Deprecated;
use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Enums\AccountTypeEnum;
@@ -58,7 +59,7 @@ trait AccountServiceTrait
$rules = ['iban' => 'required|iban']; $rules = ['iban' => 'required|iban'];
$validator = Validator::make($data, $rules); $validator = Validator::make($data, $rules);
if ($validator->fails()) { if ($validator->fails()) {
app('log')->info(sprintf('Detected invalid IBAN ("%s"). Return NULL instead.', $iban)); Log::info(sprintf('Detected invalid IBAN ("%s"). Return NULL instead.', $iban));
return null; return null;
} }
@@ -78,14 +79,8 @@ trait AccountServiceTrait
return false; return false;
} }
// if is set, but is empty: // if is set, but is empty:
if ( return (array_key_exists('opening_balance', $data) && '' === $data['opening_balance'])
(array_key_exists('opening_balance', $data) && '' === $data['opening_balance']) || (array_key_exists('opening_balance_date', $data) && '' === $data['opening_balance_date']);
|| (array_key_exists('opening_balance_date', $data) && '' === $data['opening_balance_date'])
) {
return true;
}
return false;
} }
/** /**
@@ -180,11 +175,11 @@ trait AccountServiceTrait
} }
if ('' !== $data['opening_balance'] && array_key_exists('opening_balance_date', $data) && '' !== $data['opening_balance_date'] if ('' !== $data['opening_balance'] && array_key_exists('opening_balance_date', $data) && '' !== $data['opening_balance_date']
&& $data['opening_balance_date'] instanceof Carbon) { && $data['opening_balance_date'] instanceof Carbon) {
app('log')->debug('Array has valid opening balance data.'); Log::debug('Array has valid opening balance data.');
return true; return true;
} }
app('log')->debug('Array does not have valid opening balance data.'); Log::debug('Array does not have valid opening balance data.');
return false; return false;
} }
@@ -196,7 +191,7 @@ trait AccountServiceTrait
#[Deprecated] #[Deprecated]
protected function createOBGroup(Account $account, array $data): TransactionGroup protected function createOBGroup(Account $account, array $data): TransactionGroup
{ {
app('log')->debug('Now going to create an OB group.'); Log::debug('Now going to create an OB group.');
$language = app('preferences')->getForUser($account->user, 'language', 'en_US')->data; $language = app('preferences')->getForUser($account->user, 'language', 'en_US')->data;
if (is_array($language)) { if (is_array($language)) {
$language = 'en_US'; $language = 'en_US';
@@ -210,19 +205,19 @@ trait AccountServiceTrait
// amount is positive. // amount is positive.
if (1 === bccomp((string) $amount, '0')) { if (1 === bccomp((string) $amount, '0')) {
app('log')->debug(sprintf('Amount is %s, which is positive. Source is a new IB account, destination is #%d', $amount, $account->id)); Log::debug(sprintf('Amount is %s, which is positive. Source is a new IB account, destination is #%d', $amount, $account->id));
$sourceName = trans('firefly.initial_balance_description', ['account' => $account->name], $language); $sourceName = trans('firefly.initial_balance_description', ['account' => $account->name], $language);
$destId = $account->id; $destId = $account->id;
} }
// amount is not positive // amount is not positive
if (-1 === bccomp((string) $amount, '0')) { if (-1 === bccomp((string) $amount, '0')) {
app('log')->debug(sprintf('Amount is %s, which is negative. Destination is a new IB account, source is #%d', $amount, $account->id)); Log::debug(sprintf('Amount is %s, which is negative. Destination is a new IB account, source is #%d', $amount, $account->id));
$destName = trans('firefly.initial_balance_account', ['account' => $account->name], $language); $destName = trans('firefly.initial_balance_account', ['account' => $account->name], $language);
$sourceId = $account->id; $sourceId = $account->id;
} }
// amount is 0 // amount is 0
if (0 === bccomp((string) $amount, '0')) { if (0 === bccomp((string) $amount, '0')) {
app('log')->debug('Amount is zero, so will not make an OB group.'); Log::debug('Amount is zero, so will not make an OB group.');
throw new FireflyException('Amount for new opening balance was unexpectedly 0.'); throw new FireflyException('Amount for new opening balance was unexpectedly 0.');
} }
@@ -268,7 +263,7 @@ trait AccountServiceTrait
], ],
], ],
]; ];
app('log')->debug('Going for submission in createOBGroup', $submission); Log::debug('Going for submission in createOBGroup', $submission);
/** @var TransactionGroupFactory $factory */ /** @var TransactionGroupFactory $factory */
$factory = app(TransactionGroupFactory::class); $factory = app(TransactionGroupFactory::class);
@@ -277,8 +272,8 @@ trait AccountServiceTrait
try { try {
$group = $factory->create($submission); $group = $factory->create($submission);
} catch (DuplicateTransactionException $e) { } catch (DuplicateTransactionException $e) {
app('log')->error($e->getMessage()); Log::error($e->getMessage());
app('log')->error($e->getTraceAsString()); Log::error($e->getTraceAsString());
throw new FireflyException($e->getMessage(), 0, $e); throw new FireflyException($e->getMessage(), 0, $e);
} }
@@ -291,11 +286,11 @@ trait AccountServiceTrait
*/ */
protected function deleteCreditTransaction(Account $account): void protected function deleteCreditTransaction(Account $account): void
{ {
app('log')->debug(sprintf('deleteCreditTransaction() for account #%d', $account->id)); Log::debug(sprintf('deleteCreditTransaction() for account #%d', $account->id));
$creditGroup = $this->getCreditTransaction($account); $creditGroup = $this->getCreditTransaction($account);
if (null !== $creditGroup) { if (null !== $creditGroup) {
app('log')->debug('Credit journal found, delete journal.'); Log::debug('Credit journal found, delete journal.');
/** @var TransactionGroupDestroyService $service */ /** @var TransactionGroupDestroyService $service */
$service = app(TransactionGroupDestroyService::class); $service = app(TransactionGroupDestroyService::class);
@@ -308,7 +303,7 @@ trait AccountServiceTrait
*/ */
protected function getCreditTransaction(Account $account): ?TransactionGroup protected function getCreditTransaction(Account $account): ?TransactionGroup
{ {
app('log')->debug(sprintf('Now at %s', __METHOD__)); Log::debug(sprintf('Now at %s', __METHOD__));
return $this->accountRepository->getCreditTransactionGroup($account); return $this->accountRepository->getCreditTransactionGroup($account);
} }
@@ -318,12 +313,12 @@ trait AccountServiceTrait
*/ */
protected function deleteOBGroup(Account $account): void protected function deleteOBGroup(Account $account): void
{ {
app('log')->debug(sprintf('deleteOB() for account #%d', $account->id)); Log::debug(sprintf('deleteOB() for account #%d', $account->id));
$openingBalanceGroup = $this->getOBGroup($account); $openingBalanceGroup = $this->getOBGroup($account);
// opening balance data? update it! // opening balance data? update it!
if (null !== $openingBalanceGroup) { if (null !== $openingBalanceGroup) {
app('log')->debug('Opening balance journal found, delete journal.'); Log::debug('Opening balance journal found, delete journal.');
/** @var TransactionGroupDestroyService $service */ /** @var TransactionGroupDestroyService $service */
$service = app(TransactionGroupDestroyService::class); $service = app(TransactionGroupDestroyService::class);
@@ -365,10 +360,10 @@ trait AccountServiceTrait
*/ */
protected function updateCreditTransaction(Account $account, string $direction, string $openingBalance, Carbon $openingBalanceDate): TransactionGroup protected function updateCreditTransaction(Account $account, string $direction, string $openingBalance, Carbon $openingBalanceDate): TransactionGroup
{ {
app('log')->debug(sprintf('Now in %s', __METHOD__)); Log::debug(sprintf('Now in %s', __METHOD__));
if (0 === bccomp($openingBalance, '0')) { if (0 === bccomp($openingBalance, '0')) {
app('log')->debug('Amount is zero, so will not update liability credit/debit group.'); Log::debug('Amount is zero, so will not update liability credit/debit group.');
throw new FireflyException('Amount for update liability credit/debit was unexpectedly 0.'); throw new FireflyException('Amount for update liability credit/debit was unexpectedly 0.');
} }
@@ -421,10 +416,10 @@ trait AccountServiceTrait
*/ */
protected function createCreditTransaction(Account $account, string $openingBalance, Carbon $openingBalanceDate): TransactionGroup protected function createCreditTransaction(Account $account, string $openingBalance, Carbon $openingBalanceDate): TransactionGroup
{ {
app('log')->debug('Now going to create an createCreditTransaction.'); Log::debug('Now going to create an createCreditTransaction.');
if (0 === bccomp($openingBalance, '0')) { if (0 === bccomp($openingBalance, '0')) {
app('log')->debug('Amount is zero, so will not make an liability credit group.'); Log::debug('Amount is zero, so will not make an liability credit group.');
throw new FireflyException('Amount for new liability credit was unexpectedly 0.'); throw new FireflyException('Amount for new liability credit was unexpectedly 0.');
} }
@@ -490,7 +485,7 @@ trait AccountServiceTrait
], ],
], ],
]; ];
app('log')->debug('Going for submission in createCreditTransaction', $submission); Log::debug('Going for submission in createCreditTransaction', $submission);
/** @var TransactionGroupFactory $factory */ /** @var TransactionGroupFactory $factory */
$factory = app(TransactionGroupFactory::class); $factory = app(TransactionGroupFactory::class);
@@ -499,8 +494,8 @@ trait AccountServiceTrait
try { try {
$group = $factory->create($submission); $group = $factory->create($submission);
} catch (DuplicateTransactionException $e) { } catch (DuplicateTransactionException $e) {
app('log')->error($e->getMessage()); Log::error($e->getMessage());
app('log')->error($e->getTraceAsString()); Log::error($e->getTraceAsString());
throw new FireflyException($e->getMessage(), 0, $e); throw new FireflyException($e->getMessage(), 0, $e);
} }
@@ -562,13 +557,13 @@ trait AccountServiceTrait
*/ */
protected function updateOBGroupV2(Account $account, string $openingBalance, Carbon $openingBalanceDate): TransactionGroup protected function updateOBGroupV2(Account $account, string $openingBalance, Carbon $openingBalanceDate): TransactionGroup
{ {
app('log')->debug(sprintf('Now in %s', __METHOD__)); Log::debug(sprintf('Now in %s', __METHOD__));
// create if not exists: // create if not exists:
$obGroup = $this->getOBGroup($account); $obGroup = $this->getOBGroup($account);
if (null === $obGroup) { if (null === $obGroup) {
return $this->createOBGroupV2($account, $openingBalance, $openingBalanceDate); return $this->createOBGroupV2($account, $openingBalance, $openingBalanceDate);
} }
app('log')->debug('Update OB group'); Log::debug('Update OB group');
// if exists, update: // if exists, update:
$currency = $this->accountRepository->getAccountCurrency($account); $currency = $this->accountRepository->getAccountCurrency($account);
@@ -585,7 +580,7 @@ trait AccountServiceTrait
// if amount is negative: // if amount is negative:
if (1 === bccomp('0', $openingBalance)) { if (1 === bccomp('0', $openingBalance)) {
app('log')->debug('Amount is negative.'); Log::debug('Amount is negative.');
// account transaction loses money: // account transaction loses money:
$accountTransaction->amount = app('steam')->negative($openingBalance); $accountTransaction->amount = app('steam')->negative($openingBalance);
$accountTransaction->transaction_currency_id = $currency->id; $accountTransaction->transaction_currency_id = $currency->id;
@@ -595,7 +590,7 @@ trait AccountServiceTrait
$obTransaction->transaction_currency_id = $currency->id; $obTransaction->transaction_currency_id = $currency->id;
} }
if (-1 === bccomp('0', $openingBalance)) { if (-1 === bccomp('0', $openingBalance)) {
app('log')->debug('Amount is positive.'); Log::debug('Amount is positive.');
// account gains money: // account gains money:
$accountTransaction->amount = app('steam')->positive($openingBalance); $accountTransaction->amount = app('steam')->positive($openingBalance);
$accountTransaction->transaction_currency_id = $currency->id; $accountTransaction->transaction_currency_id = $currency->id;
@@ -618,7 +613,7 @@ trait AccountServiceTrait
*/ */
protected function createOBGroupV2(Account $account, string $openingBalance, Carbon $openingBalanceDate): TransactionGroup protected function createOBGroupV2(Account $account, string $openingBalance, Carbon $openingBalanceDate): TransactionGroup
{ {
app('log')->debug('Now going to create an OB group.'); Log::debug('Now going to create an OB group.');
$language = app('preferences')->getForUser($account->user, 'language', 'en_US')->data; $language = app('preferences')->getForUser($account->user, 'language', 'en_US')->data;
if (is_array($language)) { if (is_array($language)) {
$language = 'en_US'; $language = 'en_US';
@@ -631,19 +626,19 @@ trait AccountServiceTrait
// amount is positive. // amount is positive.
if (1 === bccomp($openingBalance, '0')) { if (1 === bccomp($openingBalance, '0')) {
app('log')->debug(sprintf('Amount is %s, which is positive. Source is a new IB account, destination is #%d', $openingBalance, $account->id)); Log::debug(sprintf('Amount is %s, which is positive. Source is a new IB account, destination is #%d', $openingBalance, $account->id));
$sourceName = trans('firefly.initial_balance_description', ['account' => $account->name], $language); $sourceName = trans('firefly.initial_balance_description', ['account' => $account->name], $language);
$destId = $account->id; $destId = $account->id;
} }
// amount is not positive // amount is not positive
if (-1 === bccomp($openingBalance, '0')) { if (-1 === bccomp($openingBalance, '0')) {
app('log')->debug(sprintf('Amount is %s, which is negative. Destination is a new IB account, source is #%d', $openingBalance, $account->id)); Log::debug(sprintf('Amount is %s, which is negative. Destination is a new IB account, source is #%d', $openingBalance, $account->id));
$destName = trans('firefly.initial_balance_account', ['account' => $account->name], $language); $destName = trans('firefly.initial_balance_account', ['account' => $account->name], $language);
$sourceId = $account->id; $sourceId = $account->id;
} }
// amount is 0 // amount is 0
if (0 === bccomp($openingBalance, '0')) { if (0 === bccomp($openingBalance, '0')) {
app('log')->debug('Amount is zero, so will not make an OB group.'); Log::debug('Amount is zero, so will not make an OB group.');
throw new FireflyException('Amount for new opening balance was unexpectedly 0.'); throw new FireflyException('Amount for new opening balance was unexpectedly 0.');
} }
@@ -689,7 +684,7 @@ trait AccountServiceTrait
], ],
], ],
]; ];
app('log')->debug('Going for submission in createOBGroupV2', $submission); Log::debug('Going for submission in createOBGroupV2', $submission);
/** @var TransactionGroupFactory $factory */ /** @var TransactionGroupFactory $factory */
$factory = app(TransactionGroupFactory::class); $factory = app(TransactionGroupFactory::class);
@@ -698,8 +693,8 @@ trait AccountServiceTrait
try { try {
$group = $factory->create($submission); $group = $factory->create($submission);
} catch (DuplicateTransactionException $e) { } catch (DuplicateTransactionException $e) {
app('log')->error($e->getMessage()); Log::error($e->getMessage());
app('log')->error($e->getTraceAsString()); Log::error($e->getTraceAsString());
throw new FireflyException($e->getMessage(), 0, $e); throw new FireflyException($e->getMessage(), 0, $e);
} }

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Services\Internal\Support; namespace FireflyIII\Services\Internal\Support;
use Illuminate\Support\Facades\Log;
use FireflyIII\Models\Bill; use FireflyIII\Models\Bill;
use FireflyIII\Models\Note; use FireflyIII\Models\Note;
use FireflyIII\Models\RuleAction; use FireflyIII\Models\RuleAction;
@@ -46,7 +47,7 @@ trait BillServiceTrait
/** @var RuleAction $ruleAction */ /** @var RuleAction $ruleAction */
foreach ($set as $ruleAction) { foreach ($set as $ruleAction) {
app('log')->debug(sprintf('Updated rule action #%d to search for new bill name "%s"', $ruleAction->id, $newName)); Log::debug(sprintf('Updated rule action #%d to search for new bill name "%s"', $ruleAction->id, $newName));
$ruleAction->action_value = $newName; $ruleAction->action_value = $newName;
$ruleAction->save(); $ruleAction->save();
} }

View File

@@ -40,20 +40,10 @@ use Illuminate\Support\Facades\Log;
*/ */
class CreditRecalculateService class CreditRecalculateService
{ {
private ?Account $account; private ?Account $account = null;
private ?TransactionGroup $group; private ?TransactionGroup $group = null;
private AccountRepositoryInterface $repository; private AccountRepositoryInterface $repository;
private array $work; private array $work = [];
/**
* CreditRecalculateService constructor.
*/
public function __construct()
{
$this->group = null;
$this->account = null;
$this->work = [];
}
public function recalculate(): void public function recalculate(): void
{ {
@@ -163,13 +153,11 @@ class CreditRecalculateService
$this->repository->setUser($account->user); $this->repository->setUser($account->user);
$direction = (string) $this->repository->getMetaValue($account, 'liability_direction'); $direction = (string) $this->repository->getMetaValue($account, 'liability_direction');
$openingBalance = $this->repository->getOpeningBalance($account); $openingBalance = $this->repository->getOpeningBalance($account);
if ($openingBalance instanceof TransactionJournal) {
// Log::debug(sprintf('Found opening balance transaction journal #%d', $openingBalance->id)); // Log::debug(sprintf('Found opening balance transaction journal #%d', $openingBalance->id));
// if account direction is "debit" ("I owe this amount") the opening balance must always be AWAY from the account: // if account direction is "debit" ("I owe this amount") the opening balance must always be AWAY from the account:
if ('debit' === $direction) { if ($openingBalance instanceof TransactionJournal && 'debit' === $direction) {
$this->validateOpeningBalance($account, $openingBalance); $this->validateOpeningBalance($account, $openingBalance);
} }
}
$startOfDebt = $this->repository->getOpeningBalanceAmount($account, false) ?? '0'; $startOfDebt = $this->repository->getOpeningBalanceAmount($account, false) ?? '0';
$leftOfDebt = app('steam')->positive($startOfDebt); $leftOfDebt = app('steam')->positive($startOfDebt);
// Log::debug(sprintf('Start of debt is "%s", so initial left of debt is "%s"', app('steam')->bcround($startOfDebt, 2), app('steam')->bcround($leftOfDebt, 2))); // Log::debug(sprintf('Start of debt is "%s", so initial left of debt is "%s"', app('steam')->bcround($startOfDebt, 2), app('steam')->bcround($leftOfDebt, 2)));
@@ -188,7 +176,7 @@ class CreditRecalculateService
->orderBy('transaction_journals.date', 'ASC') ->orderBy('transaction_journals.date', 'ASC')
->get(['transactions.*']) ->get(['transactions.*'])
; ;
$total = $transactions->count(); $transactions->count();
// Log::debug(sprintf('Found %d transaction(s) to process.', $total)); // Log::debug(sprintf('Found %d transaction(s) to process.', $total));
/** @var Transaction $transaction */ /** @var Transaction $transaction */

View File

@@ -258,7 +258,7 @@ trait JournalServiceTrait
/** @var string $type */ /** @var string $type */
foreach ($types as $type) { foreach ($types as $type) {
if (true === in_array($type, $list, true)) { if (in_array($type, $list, true)) {
$result = $type; $result = $type;
break; break;

View File

@@ -94,9 +94,9 @@ trait RecurringTransactionTrait
*/ */
protected function createTransactions(Recurrence $recurrence, array $transactions): void protected function createTransactions(Recurrence $recurrence, array $transactions): void
{ {
app('log')->debug('Now in createTransactions()'); Log::debug('Now in createTransactions()');
foreach ($transactions as $index => $array) { foreach ($transactions as $index => $array) {
app('log')->debug(sprintf('Now at transaction #%d', $index)); Log::debug(sprintf('Now at transaction #%d', $index));
$sourceTypes = config(sprintf('firefly.expected_source_types.source.%s', $recurrence->transactionType->type)); $sourceTypes = config(sprintf('firefly.expected_source_types.source.%s', $recurrence->transactionType->type));
$destTypes = config(sprintf('firefly.expected_source_types.destination.%s', $recurrence->transactionType->type)); $destTypes = config(sprintf('firefly.expected_source_types.destination.%s', $recurrence->transactionType->type));
$source = $this->findAccount($sourceTypes, $array['source_id'], null); $source = $this->findAccount($sourceTypes, $array['source_id'], null);
@@ -110,7 +110,7 @@ trait RecurringTransactionTrait
$currency = app('amount')->getPrimaryCurrencyByUserGroup($recurrence->user->userGroup); $currency = app('amount')->getPrimaryCurrencyByUserGroup($recurrence->user->userGroup);
} }
app('log')->debug( Log::debug(
sprintf('Will set the validator type to %s based on the type of the recurrence (#%d).', $recurrence->transactionType->type, $recurrence->id) sprintf('Will set the validator type to %s based on the type of the recurrence (#%d).', $recurrence->transactionType->type, $recurrence->id)
); );
@@ -204,7 +204,7 @@ trait RecurringTransactionTrait
try { try {
$result = $factory->findOrCreate($accountName, $expectedType); $result = $factory->findOrCreate($accountName, $expectedType);
} catch (FireflyException $e) { } catch (FireflyException $e) {
app('log')->error($e->getMessage()); Log::error($e->getMessage());
} }
} }
} }
@@ -325,7 +325,7 @@ trait RecurringTransactionTrait
protected function deleteTransactions(Recurrence $recurrence): void protected function deleteTransactions(Recurrence $recurrence): void
{ {
app('log')->debug('deleteTransactions()'); Log::debug('deleteTransactions()');
/** @var RecurrenceTransaction $transaction */ /** @var RecurrenceTransaction $transaction */
foreach ($recurrence->recurrenceTransactions as $transaction) { foreach ($recurrence->recurrenceTransactions as $transaction) {

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Services\Internal\Support; namespace FireflyIII\Services\Internal\Support;
use Illuminate\Support\Facades\Log;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Factory\TransactionTypeFactory; use FireflyIII\Factory\TransactionTypeFactory;
use FireflyIII\Models\TransactionType; use FireflyIII\Models\TransactionType;
@@ -44,7 +45,7 @@ trait TransactionTypeTrait
$factory = app(TransactionTypeFactory::class); $factory = app(TransactionTypeFactory::class);
$transactionType = $factory->find($type); $transactionType = $factory->find($type);
if (null === $transactionType) { if (null === $transactionType) {
app('log')->error(sprintf('Could not find transaction type for "%s"', $type)); Log::error(sprintf('Could not find transaction type for "%s"', $type));
throw new FireflyException(sprintf('Could not find transaction type for "%s"', $type)); throw new FireflyException(sprintf('Could not find transaction type for "%s"', $type));
} }

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Services\Internal\Update; namespace FireflyIII\Services\Internal\Update;
use Illuminate\Support\Facades\Log;
use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Enums\AccountTypeEnum;
use FireflyIII\Events\UpdatedAccount; use FireflyIII\Events\UpdatedAccount;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
@@ -68,7 +69,7 @@ class AccountUpdateService
*/ */
public function update(Account $account, array $data): Account public function update(Account $account, array $data): Account
{ {
app('log')->debug(sprintf('Now in %s', __METHOD__)); Log::debug(sprintf('Now in %s', __METHOD__));
$this->accountRepository->setUser($account->user); $this->accountRepository->setUser($account->user);
$this->user = $account->user; $this->user = $account->user;
$account = $this->updateAccount($account, $data); $account = $this->updateAccount($account, $data);
@@ -166,21 +167,21 @@ class AccountUpdateService
{ {
// skip if no order info // skip if no order info
if (!array_key_exists('order', $data) || $data['order'] === $account->order) { if (!array_key_exists('order', $data) || $data['order'] === $account->order) {
app('log')->debug(sprintf('Account order will not be touched because its not set or already at %d.', $account->order)); Log::debug(sprintf('Account order will not be touched because its not set or already at %d.', $account->order));
return $account; return $account;
} }
// skip if not of orderable type. // skip if not of orderable type.
$type = $account->accountType->type; $type = $account->accountType->type;
if (!in_array($type, [AccountTypeEnum::ASSET->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value], true)) { if (!in_array($type, [AccountTypeEnum::ASSET->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value], true)) {
app('log')->debug('Will not change order of this account.'); Log::debug('Will not change order of this account.');
return $account; return $account;
} }
// get account type ID's because a join and an update is hard: // get account type ID's because a join and an update is hard:
$oldOrder = $account->order; $oldOrder = $account->order;
$newOrder = $data['order']; $newOrder = $data['order'];
app('log')->debug(sprintf('Order is set to be updated from %s to %s', $oldOrder, $newOrder)); Log::debug(sprintf('Order is set to be updated from %s to %s', $oldOrder, $newOrder));
$list = $this->getTypeIds([AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value]); $list = $this->getTypeIds([AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::LOAN->value, AccountTypeEnum::DEBT->value]);
if (AccountTypeEnum::ASSET->value === $type) { if (AccountTypeEnum::ASSET->value === $type) {
$list = $this->getTypeIds([AccountTypeEnum::ASSET->value]); $list = $this->getTypeIds([AccountTypeEnum::ASSET->value]);
@@ -193,7 +194,7 @@ class AccountUpdateService
->decrement('order') ->decrement('order')
; ;
$account->order = $newOrder; $account->order = $newOrder;
app('log')->debug(sprintf('Order of account #%d ("%s") is now %d', $account->id, $account->name, $newOrder)); Log::debug(sprintf('Order of account #%d ("%s") is now %d', $account->id, $account->name, $newOrder));
$account->save(); $account->save();
return $account; return $account;
@@ -205,7 +206,7 @@ class AccountUpdateService
->increment('order') ->increment('order')
; ;
$account->order = $newOrder; $account->order = $newOrder;
app('log')->debug(sprintf('Order of account #%d ("%s") is now %d', $account->id, $account->name, $newOrder)); Log::debug(sprintf('Order of account #%d ("%s") is now %d', $account->id, $account->name, $newOrder));
$account->save(); $account->save();
return $account; return $account;
@@ -298,17 +299,17 @@ class AccountUpdateService
if (!is_array($array)) { if (!is_array($array)) {
$array = [$array]; $array = [$array];
} }
app('log')->debug('Old array is: ', $array); Log::debug('Old array is: ', $array);
app('log')->debug(sprintf('Must remove : %d', $account->id)); Log::debug(sprintf('Must remove : %d', $account->id));
$removeAccountId = $account->id; $removeAccountId = $account->id;
$new = []; $new = [];
foreach ($array as $value) { foreach ($array as $value) {
if ((int) $value !== $removeAccountId) { if ((int) $value !== $removeAccountId) {
app('log')->debug(sprintf('Will include: %d', $value)); Log::debug(sprintf('Will include: %d', $value));
$new[] = (int) $value; $new[] = (int) $value;
} }
} }
app('log')->debug('Final new array is', $new); Log::debug('Final new array is', $new);
app('preferences')->setForUser($account->user, 'frontpageAccounts', $new); app('preferences')->setForUser($account->user, 'frontpageAccounts', $new);
} }
} }

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Services\Internal\Update; namespace FireflyIII\Services\Internal\Update;
use Illuminate\Support\Facades\Log;
use FireflyIII\Factory\TransactionCurrencyFactory; use FireflyIII\Factory\TransactionCurrencyFactory;
use FireflyIII\Models\Bill; use FireflyIII\Models\Bill;
use FireflyIII\Models\ObjectGroup; use FireflyIII\Models\ObjectGroup;
@@ -193,18 +194,18 @@ class BillUpdateService
private function updateBillTriggers(Bill $bill, array $oldData, array $newData): void private function updateBillTriggers(Bill $bill, array $oldData, array $newData): void
{ {
app('log')->debug(sprintf('Now in updateBillTriggers(%d, "%s")', $bill->id, $bill->name)); Log::debug(sprintf('Now in updateBillTriggers(%d, "%s")', $bill->id, $bill->name));
/** @var BillRepositoryInterface $repository */ /** @var BillRepositoryInterface $repository */
$repository = app(BillRepositoryInterface::class); $repository = app(BillRepositoryInterface::class);
$repository->setUser($bill->user); $repository->setUser($bill->user);
$rules = $repository->getRulesForBill($bill); $rules = $repository->getRulesForBill($bill);
if (0 === $rules->count()) { if (0 === $rules->count()) {
app('log')->debug('Found no rules.'); Log::debug('Found no rules.');
return; return;
} }
app('log')->debug(sprintf('Found %d rules', $rules->count())); Log::debug(sprintf('Found %d rules', $rules->count()));
$fields = [ $fields = [
'name' => 'description_contains', 'name' => 'description_contains',
'amount_min' => 'amount_more', 'amount_min' => 'amount_more',
@@ -216,7 +217,7 @@ class BillUpdateService
continue; continue;
} }
if ($oldData[$field] === $newData[$field]) { if ($oldData[$field] === $newData[$field]) {
app('log')->debug(sprintf('Field %s is unchanged ("%s"), continue.', $field, $oldData[$field])); Log::debug(sprintf('Field %s is unchanged ("%s"), continue.', $field, $oldData[$field]));
continue; continue;
} }
@@ -230,7 +231,7 @@ class BillUpdateService
foreach ($rules as $rule) { foreach ($rules as $rule) {
$trigger = $this->getRuleTrigger($rule, $key); $trigger = $this->getRuleTrigger($rule, $key);
if ($trigger instanceof RuleTrigger && $trigger->trigger_value === $oldValue) { if ($trigger instanceof RuleTrigger && $trigger->trigger_value === $oldValue) {
app('log')->debug(sprintf('Updated rule trigger #%d from value "%s" to value "%s"', $trigger->id, $oldValue, $newValue)); Log::debug(sprintf('Updated rule trigger #%d from value "%s" to value "%s"', $trigger->id, $oldValue, $newValue));
$trigger->trigger_value = $newValue; $trigger->trigger_value = $newValue;
$trigger->save(); $trigger->save();
@@ -238,7 +239,7 @@ class BillUpdateService
} }
if ($trigger instanceof RuleTrigger && $trigger->trigger_value !== $oldValue && in_array($key, ['amount_more', 'amount_less'], true) if ($trigger instanceof RuleTrigger && $trigger->trigger_value !== $oldValue && in_array($key, ['amount_more', 'amount_less'], true)
&& 0 === bccomp($trigger->trigger_value, $oldValue)) { && 0 === bccomp($trigger->trigger_value, $oldValue)) {
app('log')->debug(sprintf('Updated rule trigger #%d from value "%s" to value "%s"', $trigger->id, $oldValue, $newValue)); Log::debug(sprintf('Updated rule trigger #%d from value "%s" to value "%s"', $trigger->id, $oldValue, $newValue));
$trigger->trigger_value = $newValue; $trigger->trigger_value = $newValue;
$trigger->save(); $trigger->save();
} }

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Services\Internal\Update; namespace FireflyIII\Services\Internal\Update;
use Illuminate\Support\Facades\Log;
use Exception; use Exception;
use FireflyIII\Models\Category; use FireflyIII\Models\Category;
use FireflyIII\Models\Note; use FireflyIII\Models\Note;
@@ -54,7 +55,7 @@ class CategoryUpdateService
/** /**
* @param mixed $user * @param mixed $user
*/ */
public function setUser($user): void public function setUser(User $user): void
{ {
$this->user = $user; $this->user = $user;
} }
@@ -88,13 +89,13 @@ class CategoryUpdateService
->where('rule_triggers.trigger_value', $oldName) ->where('rule_triggers.trigger_value', $oldName)
->get(['rule_triggers.*']) ->get(['rule_triggers.*'])
; ;
app('log')->debug(sprintf('Found %d triggers to update.', $triggers->count())); Log::debug(sprintf('Found %d triggers to update.', $triggers->count()));
/** @var RuleTrigger $trigger */ /** @var RuleTrigger $trigger */
foreach ($triggers as $trigger) { foreach ($triggers as $trigger) {
$trigger->trigger_value = $newName; $trigger->trigger_value = $newName;
$trigger->save(); $trigger->save();
app('log')->debug(sprintf('Updated trigger %d: %s', $trigger->id, $trigger->trigger_value)); Log::debug(sprintf('Updated trigger %d: %s', $trigger->id, $trigger->trigger_value));
} }
} }
@@ -107,13 +108,13 @@ class CategoryUpdateService
->where('rule_actions.action_value', $oldName) ->where('rule_actions.action_value', $oldName)
->get(['rule_actions.*']) ->get(['rule_actions.*'])
; ;
app('log')->debug(sprintf('Found %d actions to update.', $actions->count())); Log::debug(sprintf('Found %d actions to update.', $actions->count()));
/** @var RuleAction $action */ /** @var RuleAction $action */
foreach ($actions as $action) { foreach ($actions as $action) {
$action->action_value = $newName; $action->action_value = $newName;
$action->save(); $action->save();
app('log')->debug(sprintf('Updated action %d: %s', $action->id, $action->action_value)); Log::debug(sprintf('Updated action %d: %s', $action->id, $action->action_value));
} }
} }
@@ -133,7 +134,7 @@ class CategoryUpdateService
*/ */
private function updateNotes(Category $category, array $data): void private function updateNotes(Category $category, array $data): void
{ {
$note = array_key_exists('notes', $data) ? $data['notes'] : null; $note = $data['notes'] ?? null;
if (null === $note) { if (null === $note) {
return; return;
} }

View File

@@ -105,7 +105,6 @@ class GroupUpdateService
$result = array_diff($existing, $updated); $result = array_diff($existing, $updated);
Log::debug('Result of DIFF: ', $result); Log::debug('Result of DIFF: ', $result);
if (count($result) > 0) {
/** @var string $deletedId */ /** @var string $deletedId */
foreach ($result as $deletedId) { foreach ($result as $deletedId) {
/** @var TransactionJournal $journal */ /** @var TransactionJournal $journal */
@@ -115,7 +114,6 @@ class GroupUpdateService
$service = app(JournalDestroyService::class); $service = app(JournalDestroyService::class);
$service->destroy($journal); $service->destroy($journal);
} }
}
app('preferences')->mark(); app('preferences')->mark();
$transactionGroup->touch(); $transactionGroup->touch();

View File

@@ -63,35 +63,11 @@ class JournalUpdateService
private CurrencyRepositoryInterface $currencyRepository; private CurrencyRepositoryInterface $currencyRepository;
private TransactionGroupRepositoryInterface $transactionGroupRepository; private TransactionGroupRepositoryInterface $transactionGroupRepository;
private array $data; private array $data;
private ?Account $destinationAccount; private ?Account $destinationAccount = null;
private ?Transaction $destinationTransaction; private ?Transaction $destinationTransaction = null;
private array $metaDate; private array $metaDate = ['interest_date', 'book_date', 'process_date', 'due_date', 'payment_date',
private array $metaString; 'invoice_date', ];
private ?Account $sourceAccount; private array $metaString = [
private ?Transaction $sourceTransaction;
private ?TransactionGroup $transactionGroup;
private ?TransactionJournal $transactionJournal;
private string $startCompareHash = '';
/**
* JournalUpdateService constructor.
*/
public function __construct()
{
$this->destinationAccount = null;
$this->destinationTransaction = null;
$this->sourceAccount = null;
$this->sourceTransaction = null;
$this->transactionGroup = null;
$this->transactionJournal = null;
$this->billRepository = app(BillRepositoryInterface::class);
$this->categoryRepository = app(CategoryRepositoryInterface::class);
$this->budgetRepository = app(BudgetRepositoryInterface::class);
$this->tagFactory = app(TagFactory::class);
$this->accountRepository = app(AccountRepositoryInterface::class);
$this->currencyRepository = app(CurrencyRepositoryInterface::class);
$this->transactionGroupRepository = app(TransactionGroupRepositoryInterface::class);
$this->metaString = [
'sepa_cc', 'sepa_cc',
'sepa_ct_op', 'sepa_ct_op',
'sepa_ct_id', 'sepa_ct_id',
@@ -106,8 +82,24 @@ class JournalUpdateService
'external_id', 'external_id',
'external_url', 'external_url',
]; ];
$this->metaDate = ['interest_date', 'book_date', 'process_date', 'due_date', 'payment_date', private ?Account $sourceAccount = null;
'invoice_date', ]; private ?Transaction $sourceTransaction = null;
private ?TransactionGroup $transactionGroup = null;
private ?TransactionJournal $transactionJournal = null;
private string $startCompareHash = '';
/**
* JournalUpdateService constructor.
*/
public function __construct()
{
$this->billRepository = app(BillRepositoryInterface::class);
$this->categoryRepository = app(CategoryRepositoryInterface::class);
$this->budgetRepository = app(BudgetRepositoryInterface::class);
$this->tagFactory = app(TagFactory::class);
$this->accountRepository = app(AccountRepositoryInterface::class);
$this->currencyRepository = app(CurrencyRepositoryInterface::class);
$this->transactionGroupRepository = app(TransactionGroupRepositoryInterface::class);
} }
public function setData(array $data): void public function setData(array $data): void
@@ -141,7 +133,7 @@ class JournalUpdateService
Log::debug(sprintf('Now in %s', __METHOD__)); Log::debug(sprintf('Now in %s', __METHOD__));
Log::debug(sprintf('Now in JournalUpdateService for journal #%d.', $this->transactionJournal->id)); Log::debug(sprintf('Now in JournalUpdateService for journal #%d.', $this->transactionJournal->id));
$this->data['reconciled'] = array_key_exists('reconciled', $this->data) ? $this->data['reconciled'] : null; $this->data['reconciled'] ??= null;
// can we update account data using the new type? // can we update account data using the new type?
if ($this->hasValidAccounts()) { if ($this->hasValidAccounts()) {
@@ -221,7 +213,7 @@ class JournalUpdateService
private function hasFields(array $fields): bool private function hasFields(array $fields): bool
{ {
return array_any($fields, fn ($field) => array_key_exists($field, $this->data)); return array_any($fields, fn ($field): bool => array_key_exists($field, $this->data));
} }
private function getOriginalSourceAccount(): Account private function getOriginalSourceAccount(): Account

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Services\Internal\Update; namespace FireflyIII\Services\Internal\Update;
use Illuminate\Support\Facades\Log;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Factory\TransactionCurrencyFactory; use FireflyIII\Factory\TransactionCurrencyFactory;
use FireflyIII\Models\Note; use FireflyIII\Models\Note;
@@ -94,7 +95,7 @@ class RecurrenceUpdateService
// update all repetitions // update all repetitions
if (array_key_exists('repetitions', $data)) { if (array_key_exists('repetitions', $data)) {
app('log')->debug('Will update repetitions array'); Log::debug('Will update repetitions array');
// update each repetition or throw error yay // update each repetition or throw error yay
$this->updateRepetitions($recurrence, $data['repetitions'] ?? []); $this->updateRepetitions($recurrence, $data['repetitions'] ?? []);
} }
@@ -135,14 +136,14 @@ class RecurrenceUpdateService
} }
// user added or removed repetitions, delete all and recreate: // user added or removed repetitions, delete all and recreate:
if ($originalCount !== count($repetitions)) { if ($originalCount !== count($repetitions)) {
app('log')->debug('Delete existing repetitions and create new ones.'); Log::debug('Delete existing repetitions and create new ones.');
$this->deleteRepetitions($recurrence); $this->deleteRepetitions($recurrence);
$this->createRepetitions($recurrence, $repetitions); $this->createRepetitions($recurrence, $repetitions);
return; return;
} }
// loop all and try to match them: // loop all and try to match them:
app('log')->debug('Loop and find'); Log::debug('Loop and find');
foreach ($repetitions as $current) { foreach ($repetitions as $current) {
$match = $this->matchRepetition($recurrence, $current); $match = $this->matchRepetition($recurrence, $current);
if (!$match instanceof RecurrenceRepetition) { if (!$match instanceof RecurrenceRepetition) {
@@ -167,7 +168,7 @@ class RecurrenceUpdateService
{ {
$originalCount = $recurrence->recurrenceRepetitions()->count(); $originalCount = $recurrence->recurrenceRepetitions()->count();
if (1 === $originalCount) { if (1 === $originalCount) {
app('log')->debug('Return the first one'); Log::debug('Return the first one');
/** @var null|RecurrenceRepetition */ /** @var null|RecurrenceRepetition */
return $recurrence->recurrenceRepetitions()->first(); return $recurrence->recurrenceRepetitions()->first();
@@ -198,12 +199,12 @@ class RecurrenceUpdateService
*/ */
private function updateTransactions(Recurrence $recurrence, array $transactions): void private function updateTransactions(Recurrence $recurrence, array $transactions): void
{ {
app('log')->debug('Now in updateTransactions()'); Log::debug('Now in updateTransactions()');
$originalCount = $recurrence->recurrenceTransactions()->count(); $originalCount = $recurrence->recurrenceTransactions()->count();
app('log')->debug(sprintf('Original count is %d', $originalCount)); Log::debug(sprintf('Original count is %d', $originalCount));
if (0 === count($transactions)) { if (0 === count($transactions)) {
// won't drop transactions, rather avoid. // won't drop transactions, rather avoid.
app('log')->warning('No transactions to update, too scared to continue!'); Log::warning('No transactions to update, too scared to continue!');
return; return;
} }
@@ -213,7 +214,7 @@ class RecurrenceUpdateService
foreach ($originalTransactions as $i => $originalTransaction) { foreach ($originalTransactions as $i => $originalTransaction) {
foreach ($transactions as $ii => $submittedTransaction) { foreach ($transactions as $ii => $submittedTransaction) {
if (array_key_exists('id', $submittedTransaction) && (int) $originalTransaction['id'] === (int) $submittedTransaction['id']) { if (array_key_exists('id', $submittedTransaction) && (int) $originalTransaction['id'] === (int) $submittedTransaction['id']) {
app('log')->debug(sprintf('Match original transaction #%d with an entry in the submitted array.', $originalTransaction['id'])); Log::debug(sprintf('Match original transaction #%d with an entry in the submitted array.', $originalTransaction['id']));
$combinations[] = [ $combinations[] = [
'original' => $originalTransaction, 'original' => $originalTransaction,
'submitted' => $submittedTransaction, 'submitted' => $submittedTransaction,
@@ -225,7 +226,7 @@ class RecurrenceUpdateService
// If one left of both we can match those as well and presto. // If one left of both we can match those as well and presto.
if (1 === count($originalTransactions) && 1 === count($transactions)) { if (1 === count($originalTransactions) && 1 === count($transactions)) {
$first = array_shift($originalTransactions); $first = array_shift($originalTransactions);
app('log')->debug(sprintf('One left of each, link them (ID is #%d)', $first['id'])); Log::debug(sprintf('One left of each, link them (ID is #%d)', $first['id']));
$combinations[] = [ $combinations[] = [
'original' => $first, 'original' => $first,
'submitted' => array_shift($transactions), 'submitted' => array_shift($transactions),
@@ -240,7 +241,7 @@ class RecurrenceUpdateService
} }
// anything left in the original transactions array can be deleted. // anything left in the original transactions array can be deleted.
foreach ($originalTransactions as $original) { foreach ($originalTransactions as $original) {
app('log')->debug(sprintf('Original transaction #%d is unmatched, delete it!', $original['id'])); Log::debug(sprintf('Original transaction #%d is unmatched, delete it!', $original['id']));
$this->deleteTransaction($recurrence, (int) $original['id']); $this->deleteTransaction($recurrence, (int) $original['id']);
} }
// anything left is new. // anything left is new.
@@ -261,7 +262,7 @@ class RecurrenceUpdateService
/** @var RecurrenceTransaction $transaction */ /** @var RecurrenceTransaction $transaction */
$transaction = $recurrence->recurrenceTransactions()->find($original['id']); $transaction = $recurrence->recurrenceTransactions()->find($original['id']);
app('log')->debug(sprintf('Now in updateCombination(#%d)', $original['id'])); Log::debug(sprintf('Now in updateCombination(#%d)', $original['id']));
// loop all and try to match them: // loop all and try to match them:
$currency = null; $currency = null;
@@ -269,7 +270,7 @@ class RecurrenceUpdateService
if (array_key_exists('currency_id', $submitted) || array_key_exists('currency_code', $submitted)) { if (array_key_exists('currency_id', $submitted) || array_key_exists('currency_code', $submitted)) {
$currency = $currencyFactory->find( $currency = $currencyFactory->find(
array_key_exists('currency_id', $submitted) ? (int) $submitted['currency_id'] : null, array_key_exists('currency_id', $submitted) ? (int) $submitted['currency_id'] : null,
array_key_exists('currency_code', $submitted) ? $submitted['currency_code'] : null $submitted['currency_code'] ?? null
); );
} }
if (null === $currency) { if (null === $currency) {
@@ -281,7 +282,7 @@ class RecurrenceUpdateService
if (array_key_exists('foreign_currency_id', $submitted) || array_key_exists('foreign_currency_code', $submitted)) { if (array_key_exists('foreign_currency_id', $submitted) || array_key_exists('foreign_currency_code', $submitted)) {
$foreignCurrency = $currencyFactory->find( $foreignCurrency = $currencyFactory->find(
array_key_exists('foreign_currency_id', $submitted) ? (int) $submitted['foreign_currency_id'] : null, array_key_exists('foreign_currency_id', $submitted) ? (int) $submitted['foreign_currency_id'] : null,
array_key_exists('foreign_currency_code', $submitted) ? $submitted['foreign_currency_code'] : null $submitted['foreign_currency_code'] ?? null
); );
} }
if (null === $foreignCurrency) { if (null === $foreignCurrency) {
@@ -317,13 +318,13 @@ class RecurrenceUpdateService
// reset category if name is set but empty: // reset category if name is set but empty:
// can be removed when v1 is retired. // can be removed when v1 is retired.
if (array_key_exists('category_name', $submitted) && '' === (string) $submitted['category_name']) { if (array_key_exists('category_name', $submitted) && '' === (string) $submitted['category_name']) {
app('log')->debug('Category name is submitted but is empty. Set category to be empty.'); Log::debug('Category name is submitted but is empty. Set category to be empty.');
$submitted['category_name'] = null; $submitted['category_name'] = null;
$submitted['category_id'] = 0; $submitted['category_id'] = 0;
} }
if (array_key_exists('category_id', $submitted)) { if (array_key_exists('category_id', $submitted)) {
app('log')->debug(sprintf('Category ID is submitted, set category to be %d.', (int) $submitted['category_id'])); Log::debug(sprintf('Category ID is submitted, set category to be %d.', (int) $submitted['category_id']));
$this->setCategory($transaction, (int) $submitted['category_id']); $this->setCategory($transaction, (int) $submitted['category_id']);
} }
@@ -337,7 +338,7 @@ class RecurrenceUpdateService
private function deleteTransaction(Recurrence $recurrence, int $transactionId): void private function deleteTransaction(Recurrence $recurrence, int $transactionId): void
{ {
app('log')->debug(sprintf('Will delete transaction #%d in recurrence #%d.', $transactionId, $recurrence->id)); Log::debug(sprintf('Will delete transaction #%d in recurrence #%d.', $transactionId, $recurrence->id));
$recurrence->recurrenceTransactions()->where('id', $transactionId)->delete(); $recurrence->recurrenceTransactions()->where('id', $transactionId)->delete();
} }
} }

View File

@@ -23,6 +23,7 @@ declare(strict_types=1);
namespace FireflyIII\Services\Password; namespace FireflyIII\Services\Password;
use Illuminate\Support\Facades\Log;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException; use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\RequestException; use GuzzleHttp\Exception\RequestException;
@@ -50,28 +51,28 @@ class PwndVerifierV2 implements Verifier
'timeout' => 3.1415, 'timeout' => 3.1415,
]; ];
app('log')->debug(sprintf('hash prefix is %s', $prefix)); Log::debug(sprintf('hash prefix is %s', $prefix));
app('log')->debug(sprintf('rest is %s', $rest)); Log::debug(sprintf('rest is %s', $rest));
try { try {
$client = new Client(); $client = new Client();
$res = $client->request('GET', $url, $opt); $res = $client->request('GET', $url, $opt);
} catch (GuzzleException|RequestException $e) { } catch (GuzzleException|RequestException $e) {
app('log')->error(sprintf('Could not verify password security: %s', $e->getMessage())); Log::error(sprintf('Could not verify password security: %s', $e->getMessage()));
return true; return true;
} }
app('log')->debug(sprintf('Status code returned is %d', $res->getStatusCode())); Log::debug(sprintf('Status code returned is %d', $res->getStatusCode()));
if (404 === $res->getStatusCode()) { if (404 === $res->getStatusCode()) {
return true; return true;
} }
$strpos = stripos($res->getBody()->getContents(), $rest); $strpos = stripos($res->getBody()->getContents(), $rest);
if (false === $strpos) { if (false === $strpos) {
app('log')->debug(sprintf('%s was not found in result body. Return true.', $rest)); Log::debug(sprintf('%s was not found in result body. Return true.', $rest));
return true; return true;
} }
app('log')->debug(sprintf('Found %s, return FALSE.', $rest)); Log::debug(sprintf('Found %s, return FALSE.', $rest));
return false; return false;
} }

View File

@@ -174,7 +174,7 @@ class Amount
$fmt->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $decimalPlaces); $fmt->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $decimalPlaces);
$result = (string)$fmt->format((float)$rounded); // intentional float $result = (string)$fmt->format((float)$rounded); // intentional float
if (true === $coloured) { if ($coloured) {
if (1 === bccomp($rounded, '0')) { if (1 === bccomp($rounded, '0')) {
return sprintf('<span class="text-success money-positive">%s</span>', $result); return sprintf('<span class="text-success money-positive">%s</span>', $result);
} }
@@ -355,7 +355,7 @@ class Amount
private function getLocaleField(array $info, string $field): bool private function getLocaleField(array $info, string $field): bool
{ {
return (is_bool($info[$field]) && true === $info[$field]) return (is_bool($info[$field]) && $info[$field])
|| (is_int($info[$field]) && 1 === $info[$field]); || (is_int($info[$field]) && 1 === $info[$field]);
} }

View File

@@ -40,18 +40,16 @@ use Illuminate\Support\Facades\Log;
class RemoteUserGuard implements Guard class RemoteUserGuard implements Guard
{ {
protected Application $application; protected Application $application;
protected ?User $user; protected ?User $user = null;
/** /**
* Create a new authentication guard. * Create a new authentication guard.
*/ */
public function __construct(protected UserProvider $provider, Application $app) public function __construct(protected UserProvider $provider, Application $app)
{ {
/** @var null|Request $request */ $app->get('request');
$request = $app->get('request');
// Log::debug(sprintf('Created RemoteUserGuard for %s "%s"', $request?->getMethod(), $request?->getRequestUri())); // Log::debug(sprintf('Created RemoteUserGuard for %s "%s"', $request?->getMethod(), $request?->getRequestUri()));
$this->application = $app; $this->application = $app;
$this->user = null;
} }
public function authenticate(): void public function authenticate(): void

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Support\Authentication; namespace FireflyIII\Support\Authentication;
use Illuminate\Support\Facades\Log;
use FireflyIII\Console\Commands\Correction\CreatesGroupMemberships; use FireflyIII\Console\Commands\Correction\CreatesGroupMemberships;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Role; use FireflyIII\Models\Role;
@@ -41,7 +42,7 @@ class RemoteUserProvider implements UserProvider
#[Override] #[Override]
public function rehashPasswordIfRequired(Authenticatable $user, array $credentials, bool $force = false): void public function rehashPasswordIfRequired(Authenticatable $user, array $credentials, bool $force = false): void
{ {
app('log')->debug(sprintf('Now at %s', __METHOD__)); Log::debug(sprintf('Now at %s', __METHOD__));
throw new FireflyException(sprintf('Did not implement %s', __METHOD__)); throw new FireflyException(sprintf('Did not implement %s', __METHOD__));
} }
@@ -53,7 +54,7 @@ class RemoteUserProvider implements UserProvider
*/ */
public function retrieveByCredentials(array $credentials): ?Authenticatable public function retrieveByCredentials(array $credentials): ?Authenticatable
{ {
app('log')->debug(sprintf('Now at %s', __METHOD__)); Log::debug(sprintf('Now at %s', __METHOD__));
throw new FireflyException(sprintf('Did not implement %s', __METHOD__)); throw new FireflyException(sprintf('Did not implement %s', __METHOD__));
} }
@@ -65,10 +66,10 @@ class RemoteUserProvider implements UserProvider
*/ */
public function retrieveById($identifier): User public function retrieveById($identifier): User
{ {
app('log')->debug(sprintf('Now at %s(%s)', __METHOD__, $identifier)); Log::debug(sprintf('Now at %s(%s)', __METHOD__, $identifier));
$user = User::where('email', $identifier)->first(); $user = User::where('email', $identifier)->first();
if (null === $user) { if (null === $user) {
app('log')->debug(sprintf('User with email "%s" not found. Will be created.', $identifier)); Log::debug(sprintf('User with email "%s" not found. Will be created.', $identifier));
$user = User::create( $user = User::create(
[ [
'blocked' => false, 'blocked' => false,
@@ -86,7 +87,7 @@ class RemoteUserProvider implements UserProvider
// make sure the user gets an administration as well. // make sure the user gets an administration as well.
CreatesGroupMemberships::createGroupMembership($user); CreatesGroupMemberships::createGroupMembership($user);
app('log')->debug(sprintf('Going to return user #%d (%s)', $user->id, $user->email)); Log::debug(sprintf('Going to return user #%d (%s)', $user->id, $user->email));
return $user; return $user;
} }
@@ -101,7 +102,7 @@ class RemoteUserProvider implements UserProvider
*/ */
public function retrieveByToken($identifier, $token): ?Authenticatable public function retrieveByToken($identifier, $token): ?Authenticatable
{ {
app('log')->debug(sprintf('Now at %s', __METHOD__)); Log::debug(sprintf('Now at %s', __METHOD__));
throw new FireflyException(sprintf('A) Did not implement %s', __METHOD__)); throw new FireflyException(sprintf('A) Did not implement %s', __METHOD__));
} }
@@ -115,7 +116,7 @@ class RemoteUserProvider implements UserProvider
*/ */
public function updateRememberToken(Authenticatable $user, $token): void public function updateRememberToken(Authenticatable $user, $token): void
{ {
app('log')->debug(sprintf('Now at %s', __METHOD__)); Log::debug(sprintf('Now at %s', __METHOD__));
throw new FireflyException(sprintf('B) Did not implement %s', __METHOD__)); throw new FireflyException(sprintf('B) Did not implement %s', __METHOD__));
} }
@@ -127,7 +128,7 @@ class RemoteUserProvider implements UserProvider
*/ */
public function validateCredentials(Authenticatable $user, array $credentials): bool public function validateCredentials(Authenticatable $user, array $credentials): bool
{ {
app('log')->debug(sprintf('Now at %s', __METHOD__)); Log::debug(sprintf('Now at %s', __METHOD__));
throw new FireflyException(sprintf('C) Did not implement %s', __METHOD__)); throw new FireflyException(sprintf('C) Did not implement %s', __METHOD__));
} }

View File

@@ -23,6 +23,7 @@ declare(strict_types=1);
namespace FireflyIII\Support\Binder; namespace FireflyIII\Support\Binder;
use Illuminate\Support\Facades\Log;
use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Enums\AccountTypeEnum;
use Illuminate\Routing\Route; use Illuminate\Routing\Route;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
@@ -50,7 +51,7 @@ class AccountList implements BinderInterface
; ;
} }
if ('allAssetAccounts' !== $value) { if ('allAssetAccounts' !== $value) {
$incoming = array_map('\intval', explode(',', $value)); $incoming = array_map(\intval(...), explode(',', $value));
$list = array_merge(array_unique($incoming), [0]); $list = array_merge(array_unique($incoming), [0]);
/** @var Collection $collection */ /** @var Collection $collection */
@@ -66,7 +67,7 @@ class AccountList implements BinderInterface
return $collection; return $collection;
} }
} }
app('log')->error(sprintf('Trying to show account list (%s), but user is not logged in or list is empty.', $route->uri)); Log::error(sprintf('Trying to show account list (%s), but user is not logged in or list is empty.', $route->uri));
throw new NotFoundHttpException(); throw new NotFoundHttpException();
} }

View File

@@ -23,6 +23,7 @@ declare(strict_types=1);
namespace FireflyIII\Support\Binder; namespace FireflyIII\Support\Binder;
use Illuminate\Support\Facades\Log;
use FireflyIII\Models\Budget; use FireflyIII\Models\Budget;
use Illuminate\Routing\Route; use Illuminate\Routing\Route;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
@@ -47,10 +48,10 @@ class BudgetList implements BinderInterface
; ;
} }
$list = array_unique(array_map('\intval', explode(',', $value))); $list = array_unique(array_map(\intval(...), explode(',', $value)));
if (0 === count($list)) { // @phpstan-ignore-line if (0 === count($list)) { // @phpstan-ignore-line
app('log')->warning('Budget list count is zero, return 404.'); Log::warning('Budget list count is zero, return 404.');
throw new NotFoundHttpException(); throw new NotFoundHttpException();
} }
@@ -71,7 +72,7 @@ class BudgetList implements BinderInterface
return $collection; return $collection;
} }
} }
app('log')->warning('BudgetList fallback to 404.'); Log::warning('BudgetList fallback to 404.');
throw new NotFoundHttpException(); throw new NotFoundHttpException();
} }

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Support\Binder; namespace FireflyIII\Support\Binder;
use Illuminate\Support\Facades\Log;
use FireflyIII\Repositories\User\UserRepositoryInterface; use FireflyIII\Repositories\User\UserRepositoryInterface;
use Illuminate\Routing\Route; use Illuminate\Routing\Route;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
@@ -33,10 +34,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
*/ */
class CLIToken implements BinderInterface class CLIToken implements BinderInterface
{ {
/** public static function routeBinder(string $value, Route $route): string
* @return mixed
*/
public static function routeBinder(string $value, Route $route)
{ {
/** @var UserRepositoryInterface $repository */ /** @var UserRepositoryInterface $repository */
$repository = app(UserRepositoryInterface::class); $repository = app(UserRepositoryInterface::class);
@@ -50,12 +48,12 @@ class CLIToken implements BinderInterface
foreach ($users as $user) { foreach ($users as $user) {
$accessToken = app('preferences')->getForUser($user, 'access_token'); $accessToken = app('preferences')->getForUser($user, 'access_token');
if (null !== $accessToken && $accessToken->data === $value) { if (null !== $accessToken && $accessToken->data === $value) {
app('log')->info(sprintf('Recognized user #%d (%s) from his access token.', $user->id, $user->email)); Log::info(sprintf('Recognized user #%d (%s) from his access token.', $user->id, $user->email));
return $value; return $value;
} }
} }
app('log')->error(sprintf('Recognized no users by access token "%s"', $value)); Log::error(sprintf('Recognized no users by access token "%s"', $value));
throw new NotFoundHttpException(); throw new NotFoundHttpException();
} }

View File

@@ -46,7 +46,7 @@ class CategoryList implements BinderInterface
; ;
} }
$list = array_unique(array_map('\intval', explode(',', $value))); $list = array_unique(array_map(\intval(...), explode(',', $value)));
if (0 === count($list)) { // @phpstan-ignore-line if (0 === count($list)) { // @phpstan-ignore-line
throw new NotFoundHttpException(); throw new NotFoundHttpException();
} }

View File

@@ -23,6 +23,7 @@ declare(strict_types=1);
namespace FireflyIII\Support\Binder; namespace FireflyIII\Support\Binder;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon; use Carbon\Carbon;
use Carbon\Exceptions\InvalidDateException; use Carbon\Exceptions\InvalidDateException;
use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidFormatException;
@@ -61,7 +62,7 @@ class Date implements BinderInterface
]; ];
if (array_key_exists($value, $magicWords)) { if (array_key_exists($value, $magicWords)) {
$return = $magicWords[$value]; $return = $magicWords[$value];
app('log')->debug(sprintf('User requests "%s", so will return "%s"', $value, $return)); Log::debug(sprintf('User requests "%s", so will return "%s"', $value, $return));
return $return; return $return;
} }
@@ -70,7 +71,7 @@ class Date implements BinderInterface
$result = new Carbon($value); $result = new Carbon($value);
} catch (InvalidDateException|InvalidFormatException $e) { // @phpstan-ignore-line } catch (InvalidDateException|InvalidFormatException $e) { // @phpstan-ignore-line
$message = sprintf('Could not parse date "%s" for user #%d: %s', $value, auth()->user()->id, $e->getMessage()); $message = sprintf('Could not parse date "%s" for user #%d: %s', $value, auth()->user()->id, $e->getMessage());
app('log')->error($message); Log::error($message);
throw new NotFoundHttpException('Could not parse value', $e); throw new NotFoundHttpException('Could not parse value', $e);
} }

View File

@@ -60,7 +60,7 @@ class JournalList implements BinderInterface
protected static function parseList(string $value): array protected static function parseList(string $value): array
{ {
$list = array_unique(array_map('\intval', explode(',', $value))); $list = array_unique(array_map(\intval(...), explode(',', $value)));
if (0 === count($list)) { // @phpstan-ignore-line if (0 === count($list)) { // @phpstan-ignore-line
throw new NotFoundHttpException(); throw new NotFoundHttpException();
} }

View File

@@ -47,11 +47,11 @@ class TagList implements BinderInterface
->get() ->get()
; ;
} }
$list = array_unique(array_map('\strtolower', explode(',', $value))); $list = array_unique(array_map(\strtolower(...), explode(',', $value)));
app('log')->debug('List of tags is', $list); Log::debug('List of tags is', $list);
if (0 === count($list)) { // @phpstan-ignore-line if (0 === count($list)) { // @phpstan-ignore-line
app('log')->error('Tag list is empty.'); Log::error('Tag list is empty.');
throw new NotFoundHttpException(); throw new NotFoundHttpException();
} }
@@ -62,7 +62,7 @@ class TagList implements BinderInterface
$allTags = $repository->get(); $allTags = $repository->get();
$collection = $allTags->filter( $collection = $allTags->filter(
static function (Tag $tag) use ($list) { static function (Tag $tag) use ($list): bool {
if (in_array(strtolower($tag->tag), $list, true)) { if (in_array(strtolower($tag->tag), $list, true)) {
Log::debug(sprintf('TagList: (string) found tag #%d ("%s") in list.', $tag->id, $tag->tag)); Log::debug(sprintf('TagList: (string) found tag #%d ("%s") in list.', $tag->id, $tag->tag));
@@ -82,7 +82,7 @@ class TagList implements BinderInterface
return $collection; return $collection;
} }
} }
app('log')->error('TagList: user is not logged in.'); Log::error('TagList: user is not logged in.');
throw new NotFoundHttpException(); throw new NotFoundHttpException();
} }

View File

@@ -23,6 +23,7 @@ declare(strict_types=1);
namespace FireflyIII\Support\Binder; namespace FireflyIII\Support\Binder;
use Illuminate\Support\Facades\Log;
use FireflyIII\Models\Tag; use FireflyIII\Models\Tag;
use FireflyIII\Repositories\Tag\TagRepositoryInterface; use FireflyIII\Repositories\Tag\TagRepositoryInterface;
use Illuminate\Routing\Route; use Illuminate\Routing\Route;
@@ -47,11 +48,11 @@ class TagOrId implements BinderInterface
if (null !== $result) { if (null !== $result) {
return $result; return $result;
} }
app('log')->error('TagOrId: tag not found.'); Log::error('TagOrId: tag not found.');
throw new NotFoundHttpException(); throw new NotFoundHttpException();
} }
app('log')->error('TagOrId: user is not logged in.'); Log::error('TagOrId: user is not logged in.');
throw new NotFoundHttpException(); throw new NotFoundHttpException();
} }

View File

@@ -37,12 +37,12 @@ class Calculator
private static ?SplObjectStorage $intervalMap = null; // @phpstan-ignore-line private static ?SplObjectStorage $intervalMap = null; // @phpstan-ignore-line
private static array $intervals = []; private static array $intervals = [];
private static function containsInterval(Periodicity $periodicity): bool private function containsInterval(Periodicity $periodicity): bool
{ {
return self::loadIntervalMap()->contains($periodicity); return $this->loadIntervalMap()->contains($periodicity);
} }
private static function loadIntervalMap(): SplObjectStorage private function loadIntervalMap(): SplObjectStorage
{ {
if (self::$intervalMap instanceof SplObjectStorage) { if (self::$intervalMap instanceof SplObjectStorage) {
return self::$intervalMap; return self::$intervalMap;
@@ -59,7 +59,7 @@ class Calculator
public function isAvailablePeriodicity(Periodicity $periodicity): bool public function isAvailablePeriodicity(Periodicity $periodicity): bool
{ {
return self::containsInterval($periodicity); return $this->containsInterval($periodicity);
} }
/** /**

View File

@@ -45,7 +45,7 @@ class FrontpageChartGenerator
private readonly BudgetLimitRepositoryInterface $blRepository; private readonly BudgetLimitRepositoryInterface $blRepository;
private readonly BudgetRepositoryInterface $budgetRepository; private readonly BudgetRepositoryInterface $budgetRepository;
private Carbon $end; private Carbon $end;
private string $monthAndDayFormat; private string $monthAndDayFormat = '';
private Carbon $start; private Carbon $start;
/** /**
@@ -56,7 +56,6 @@ class FrontpageChartGenerator
$this->budgetRepository = app(BudgetRepositoryInterface::class); $this->budgetRepository = app(BudgetRepositoryInterface::class);
$this->blRepository = app(BudgetLimitRepositoryInterface::class); $this->blRepository = app(BudgetLimitRepositoryInterface::class);
$this->opsRepository = app(OperationsRepositoryInterface::class); $this->opsRepository = app(OperationsRepositoryInterface::class);
$this->monthAndDayFormat = '';
} }
/** /**
@@ -192,7 +191,7 @@ class FrontpageChartGenerator
Log::debug(sprintf('Process spent row (%s)', $entry['currency_code'])); Log::debug(sprintf('Process spent row (%s)', $entry['currency_code']));
$data = $this->processRow($data, $budget, $limit, $entry); $data = $this->processRow($data, $budget, $limit, $entry);
} }
if (!($entry['currency_id'] === $limit->transaction_currency_id || $usePrimary)) { if ($entry['currency_id'] !== $limit->transaction_currency_id && !$usePrimary) {
Log::debug(sprintf('Skipping spent row (%s).', $entry['currency_code'])); Log::debug(sprintf('Skipping spent row (%s).', $entry['currency_code']));
} }
} }

View File

@@ -45,7 +45,7 @@ class FrontpageChartGenerator
public bool $convertToPrimary = false; public bool $convertToPrimary = false;
public TransactionCurrency $primaryCurrency; public TransactionCurrency $primaryCurrency;
private AccountRepositoryInterface $accountRepos; private AccountRepositoryInterface $accountRepos;
private array $currencies; private array $currencies = [];
private NoCategoryRepositoryInterface $noCatRepos; private NoCategoryRepositoryInterface $noCatRepos;
private OperationsRepositoryInterface $opsRepos; private OperationsRepositoryInterface $opsRepos;
private CategoryRepositoryInterface $repository; private CategoryRepositoryInterface $repository;
@@ -55,7 +55,6 @@ class FrontpageChartGenerator
*/ */
public function __construct(private Carbon $start, private Carbon $end) public function __construct(private Carbon $start, private Carbon $end)
{ {
$this->currencies = [];
$this->repository = app(CategoryRepositoryInterface::class); $this->repository = app(CategoryRepositoryInterface::class);
$this->accountRepos = app(AccountRepositoryInterface::class); $this->accountRepos = app(AccountRepositoryInterface::class);
$this->opsRepos = app(OperationsRepositoryInterface::class); $this->opsRepos = app(OperationsRepositoryInterface::class);

View File

@@ -31,12 +31,7 @@ use FireflyIII\Exceptions\FireflyException;
*/ */
class ChartData class ChartData
{ {
private array $series; private array $series = [];
public function __construct()
{
$this->series = [];
}
/** /**
* @throws FireflyException * @throws FireflyException

View File

@@ -31,25 +31,20 @@ use Carbon\Carbon;
*/ */
abstract class AbstractCronjob abstract class AbstractCronjob
{ {
public bool $jobErrored; public bool $jobErrored = false;
public bool $jobFired; public bool $jobFired = false;
public bool $jobSucceeded; public bool $jobSucceeded = false;
public ?string $message; public ?string $message = null;
public int $timeBetweenRuns = 43200; public int $timeBetweenRuns = 43200;
protected Carbon $date; protected Carbon $date;
protected bool $force; protected bool $force = false;
/** /**
* AbstractCronjob constructor. * AbstractCronjob constructor.
*/ */
public function __construct() public function __construct()
{ {
$this->force = false;
$this->date = today(config('app.timezone')); $this->date = today(config('app.timezone'));
$this->jobErrored = false;
$this->jobSucceeded = false;
$this->jobFired = false;
$this->message = null;
} }
abstract public function fire(): void; abstract public function fire(): void;

View File

@@ -23,6 +23,7 @@ declare(strict_types=1);
namespace FireflyIII\Support; namespace FireflyIII\Support;
use Illuminate\Support\Facades\Log;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Support\Form\FormSupport; use FireflyIII\Support\Form\FormSupport;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
@@ -56,9 +57,9 @@ class ExpandedForm
// $value = round((float)$value, 8); // $value = round((float)$value, 8);
// } // }
try { try {
$html = view('form.amount-no-currency', compact('classes', 'name', 'label', 'value', 'options'))->render(); $html = view('form.amount-no-currency', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render();
} catch (Throwable $e) { } catch (Throwable $e) {
app('log')->error(sprintf('Could not render amountNoCurrency(): %s', $e->getMessage())); Log::error(sprintf('Could not render amountNoCurrency(): %s', $e->getMessage()));
$html = 'Could not render amountNoCurrency.'; $html = 'Could not render amountNoCurrency.';
throw new FireflyException($html, 0, $e); throw new FireflyException($html, 0, $e);
@@ -91,9 +92,9 @@ class ExpandedForm
unset($options['placeholder'], $options['autocomplete'], $options['class']); unset($options['placeholder'], $options['autocomplete'], $options['class']);
try { try {
$html = view('form.checkbox', compact('classes', 'name', 'label', 'value', 'options'))->render(); $html = view('form.checkbox', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render();
} catch (Throwable $e) { } catch (Throwable $e) {
app('log')->debug(sprintf('Could not render checkbox(): %s', $e->getMessage())); Log::debug(sprintf('Could not render checkbox(): %s', $e->getMessage()));
$html = 'Could not render checkbox.'; $html = 'Could not render checkbox.';
throw new FireflyException($html, 0, $e); throw new FireflyException($html, 0, $e);
@@ -116,9 +117,9 @@ class ExpandedForm
unset($options['placeholder']); unset($options['placeholder']);
try { try {
$html = view('form.date', compact('classes', 'name', 'label', 'value', 'options'))->render(); $html = view('form.date', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render();
} catch (Throwable $e) { } catch (Throwable $e) {
app('log')->debug(sprintf('Could not render date(): %s', $e->getMessage())); Log::debug(sprintf('Could not render date(): %s', $e->getMessage()));
$html = 'Could not render date.'; $html = 'Could not render date.';
throw new FireflyException($html, 0, $e); throw new FireflyException($html, 0, $e);
@@ -138,9 +139,9 @@ class ExpandedForm
$classes = $this->getHolderClasses($name); $classes = $this->getHolderClasses($name);
try { try {
$html = view('form.file', compact('classes', 'name', 'label', 'options'))->render(); $html = view('form.file', ['classes' => $classes, 'name' => $name, 'label' => $label, 'options' => $options])->render();
} catch (Throwable $e) { } catch (Throwable $e) {
app('log')->debug(sprintf('Could not render file(): %s', $e->getMessage())); Log::debug(sprintf('Could not render file(): %s', $e->getMessage()));
$html = 'Could not render file.'; $html = 'Could not render file.';
throw new FireflyException($html, 0, $e); throw new FireflyException($html, 0, $e);
@@ -164,9 +165,9 @@ class ExpandedForm
$options['step'] ??= '1'; $options['step'] ??= '1';
try { try {
$html = view('form.integer', compact('classes', 'name', 'label', 'value', 'options'))->render(); $html = view('form.integer', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render();
} catch (Throwable $e) { } catch (Throwable $e) {
app('log')->debug(sprintf('Could not render integer(): %s', $e->getMessage())); Log::debug(sprintf('Could not render integer(): %s', $e->getMessage()));
$html = 'Could not render integer.'; $html = 'Could not render integer.';
throw new FireflyException($html, 0, $e); throw new FireflyException($html, 0, $e);
@@ -189,9 +190,9 @@ class ExpandedForm
$value = $this->fillFieldValue($name, $value); $value = $this->fillFieldValue($name, $value);
try { try {
$html = view('form.location', compact('classes', 'name', 'label', 'value', 'options'))->render(); $html = view('form.location', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render();
} catch (Throwable $e) { } catch (Throwable $e) {
app('log')->debug(sprintf('Could not render location(): %s', $e->getMessage())); Log::debug(sprintf('Could not render location(): %s', $e->getMessage()));
$html = 'Could not render location.'; $html = 'Could not render location.';
throw new FireflyException($html, 0, $e); throw new FireflyException($html, 0, $e);
@@ -224,8 +225,6 @@ class ExpandedForm
} }
/** /**
* @param null $value
*
* @throws FireflyException * @throws FireflyException
*/ */
public function objectGroup($value = null, ?array $options = null): string public function objectGroup($value = null, ?array $options = null): string
@@ -242,9 +241,9 @@ class ExpandedForm
} }
try { try {
$html = view('form.object_group', compact('classes', 'name', 'label', 'value', 'options'))->render(); $html = view('form.object_group', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render();
} catch (Throwable $e) { } catch (Throwable $e) {
app('log')->debug(sprintf('Could not render objectGroup(): %s', $e->getMessage())); Log::debug(sprintf('Could not render objectGroup(): %s', $e->getMessage()));
$html = 'Could not render objectGroup.'; $html = 'Could not render objectGroup.';
throw new FireflyException($html, 0, $e); throw new FireflyException($html, 0, $e);
@@ -259,9 +258,9 @@ class ExpandedForm
public function optionsList(string $type, string $name): string public function optionsList(string $type, string $name): string
{ {
try { try {
$html = view('form.options', compact('type', 'name'))->render(); $html = view('form.options', ['type' => $type, 'name' => $name])->render();
} catch (Throwable $e) { } catch (Throwable $e) {
app('log')->debug(sprintf('Could not render select(): %s', $e->getMessage())); Log::debug(sprintf('Could not render select(): %s', $e->getMessage()));
$html = 'Could not render optionsList.'; $html = 'Could not render optionsList.';
throw new FireflyException($html, 0, $e); throw new FireflyException($html, 0, $e);
@@ -280,9 +279,9 @@ class ExpandedForm
$classes = $this->getHolderClasses($name); $classes = $this->getHolderClasses($name);
try { try {
$html = view('form.password', compact('classes', 'name', 'label', 'options'))->render(); $html = view('form.password', ['classes' => $classes, 'name' => $name, 'label' => $label, 'options' => $options])->render();
} catch (Throwable $e) { } catch (Throwable $e) {
app('log')->debug(sprintf('Could not render password(): %s', $e->getMessage())); Log::debug(sprintf('Could not render password(): %s', $e->getMessage()));
$html = 'Could not render password.'; $html = 'Could not render password.';
throw new FireflyException($html, 0, $e); throw new FireflyException($html, 0, $e);
@@ -301,9 +300,9 @@ class ExpandedForm
$classes = $this->getHolderClasses($name); $classes = $this->getHolderClasses($name);
try { try {
$html = view('form.password', compact('classes', 'value', 'name', 'label', 'options'))->render(); $html = view('form.password', ['classes' => $classes, 'value' => $value, 'name' => $name, 'label' => $label, 'options' => $options])->render();
} catch (Throwable $e) { } catch (Throwable $e) {
app('log')->debug(sprintf('Could not render passwordWithValue(): %s', $e->getMessage())); Log::debug(sprintf('Could not render passwordWithValue(): %s', $e->getMessage()));
$html = 'Could not render passwordWithValue.'; $html = 'Could not render passwordWithValue.';
throw new FireflyException($html, 0, $e); throw new FireflyException($html, 0, $e);
@@ -329,9 +328,9 @@ class ExpandedForm
unset($options['placeholder']); unset($options['placeholder']);
try { try {
$html = view('form.percentage', compact('classes', 'name', 'label', 'value', 'options'))->render(); $html = view('form.percentage', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render();
} catch (Throwable $e) { } catch (Throwable $e) {
app('log')->debug(sprintf('Could not render percentage(): %s', $e->getMessage())); Log::debug(sprintf('Could not render percentage(): %s', $e->getMessage()));
$html = 'Could not render percentage.'; $html = 'Could not render percentage.';
throw new FireflyException($html, 0, $e); throw new FireflyException($html, 0, $e);
@@ -352,9 +351,9 @@ class ExpandedForm
$classes = $this->getHolderClasses($name); $classes = $this->getHolderClasses($name);
try { try {
$html = view('form.static', compact('classes', 'name', 'label', 'value', 'options'))->render(); $html = view('form.static', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render();
} catch (Throwable $e) { } catch (Throwable $e) {
app('log')->debug(sprintf('Could not render staticText(): %s', $e->getMessage())); Log::debug(sprintf('Could not render staticText(): %s', $e->getMessage()));
$html = 'Could not render staticText.'; $html = 'Could not render staticText.';
throw new FireflyException($html, 0, $e); throw new FireflyException($html, 0, $e);
@@ -376,9 +375,9 @@ class ExpandedForm
$value = $this->fillFieldValue($name, $value); $value = $this->fillFieldValue($name, $value);
try { try {
$html = view('form.text', compact('classes', 'name', 'label', 'value', 'options'))->render(); $html = view('form.text', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render();
} catch (Throwable $e) { } catch (Throwable $e) {
app('log')->debug(sprintf('Could not render text(): %s', $e->getMessage())); Log::debug(sprintf('Could not render text(): %s', $e->getMessage()));
$html = 'Could not render text.'; $html = 'Could not render text.';
throw new FireflyException($html, 0, $e); throw new FireflyException($html, 0, $e);
@@ -405,9 +404,9 @@ class ExpandedForm
} }
try { try {
$html = view('form.textarea', compact('classes', 'name', 'label', 'value', 'options'))->render(); $html = view('form.textarea', ['classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render();
} catch (Throwable $e) { } catch (Throwable $e) {
app('log')->debug(sprintf('Could not render textarea(): %s', $e->getMessage())); Log::debug(sprintf('Could not render textarea(): %s', $e->getMessage()));
$html = 'Could not render textarea.'; $html = 'Could not render textarea.';
throw new FireflyException($html, 0, $e); throw new FireflyException($html, 0, $e);

View File

@@ -76,15 +76,15 @@ class ExportDataGenerator
private const string EXPORT_ERR = 'Could not export to string: %s'; private const string EXPORT_ERR = 'Could not export to string: %s';
private Collection $accounts; private Collection $accounts;
private Carbon $end; private Carbon $end;
private bool $exportAccounts; private bool $exportAccounts = false;
private bool $exportBills; private bool $exportBills = false;
private bool $exportBudgets; private bool $exportBudgets = false;
private bool $exportCategories; private bool $exportCategories = false;
private bool $exportPiggies; private bool $exportPiggies = false;
private bool $exportRecurring; private bool $exportRecurring = false;
private bool $exportRules; private bool $exportRules = false;
private bool $exportTags; private bool $exportTags = false;
private bool $exportTransactions; private bool $exportTransactions = false;
private Carbon $start; private Carbon $start;
private User $user; private User $user;
private UserGroup $userGroup; // @phpstan-ignore-line private UserGroup $userGroup; // @phpstan-ignore-line
@@ -95,15 +95,6 @@ class ExportDataGenerator
$this->start = today(config('app.timezone')); $this->start = today(config('app.timezone'));
$this->start->subYear(); $this->start->subYear();
$this->end = today(config('app.timezone')); $this->end = today(config('app.timezone'));
$this->exportTransactions = false;
$this->exportAccounts = false;
$this->exportBudgets = false;
$this->exportCategories = false;
$this->exportTags = false;
$this->exportRecurring = false;
$this->exportRules = false;
$this->exportBills = false;
$this->exportPiggies = false;
} }
/** /**
@@ -306,7 +297,7 @@ class ExportDataGenerator
try { try {
$string = $csv->toString(); $string = $csv->toString();
} catch (Exception $e) { // intentional generic exception } catch (Exception $e) { // intentional generic exception
app('log')->error($e->getMessage()); Log::error($e->getMessage());
throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e); throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e);
} }
@@ -375,7 +366,7 @@ class ExportDataGenerator
try { try {
$string = $csv->toString(); $string = $csv->toString();
} catch (Exception $e) { // intentional generic exception } catch (Exception $e) { // intentional generic exception
app('log')->error($e->getMessage()); Log::error($e->getMessage());
throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e); throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e);
} }
@@ -444,7 +435,7 @@ class ExportDataGenerator
try { try {
$string = $csv->toString(); $string = $csv->toString();
} catch (Exception $e) { // intentional generic exception } catch (Exception $e) { // intentional generic exception
app('log')->error($e->getMessage()); Log::error($e->getMessage());
throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e); throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e);
} }
@@ -495,7 +486,7 @@ class ExportDataGenerator
try { try {
$string = $csv->toString(); $string = $csv->toString();
} catch (Exception $e) { // intentional generic exception } catch (Exception $e) { // intentional generic exception
app('log')->error($e->getMessage()); Log::error($e->getMessage());
throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e); throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e);
} }
@@ -575,7 +566,7 @@ class ExportDataGenerator
try { try {
$string = $csv->toString(); $string = $csv->toString();
} catch (Exception $e) { // intentional generic exception } catch (Exception $e) { // intentional generic exception
app('log')->error($e->getMessage()); Log::error($e->getMessage());
throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e); throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e);
} }
@@ -667,7 +658,7 @@ class ExportDataGenerator
try { try {
$string = $csv->toString(); $string = $csv->toString();
} catch (Exception $e) { // intentional generic exception } catch (Exception $e) { // intentional generic exception
app('log')->error($e->getMessage()); Log::error($e->getMessage());
throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e); throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e);
} }
@@ -744,7 +735,7 @@ class ExportDataGenerator
try { try {
$string = $csv->toString(); $string = $csv->toString();
} catch (Exception $e) { // intentional generic exception } catch (Exception $e) { // intentional generic exception
app('log')->error($e->getMessage()); Log::error($e->getMessage());
throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e); throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e);
} }
@@ -800,7 +791,7 @@ class ExportDataGenerator
try { try {
$string = $csv->toString(); $string = $csv->toString();
} catch (Exception $e) { // intentional generic exception } catch (Exception $e) { // intentional generic exception
app('log')->error($e->getMessage()); Log::error($e->getMessage());
throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e); throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e);
} }
@@ -901,7 +892,7 @@ class ExportDataGenerator
try { try {
$string = $csv->toString(); $string = $csv->toString();
} catch (Exception $e) { // intentional generic exception } catch (Exception $e) { // intentional generic exception
app('log')->error($e->getMessage()); Log::error($e->getMessage());
throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e); throw new FireflyException(sprintf(self::EXPORT_ERR, $e->getMessage()), 0, $e);
} }

View File

@@ -23,13 +23,14 @@ declare(strict_types=1);
namespace FireflyIII\Support\Facades; namespace FireflyIII\Support\Facades;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Facade; use Illuminate\Support\Facades\Facade;
class Preferences extends Facade class Preferences extends Facade
{ {
public function __construct() public function __construct()
{ {
app('log')->warning('Hi there'); Log::warning('Hi there');
} }
/** /**

View File

@@ -133,7 +133,7 @@ class FireflyConfig
try { try {
$config = Configuration::whereName($name)->whereNull('deleted_at')->first(); $config = Configuration::whereName($name)->whereNull('deleted_at')->first();
} catch (QueryException $e) { } catch (QueryException $e) {
app('log')->error($e->getMessage()); Log::error($e->getMessage());
$item = new Configuration(); $item = new Configuration();
$item->name = $name; $item->name = $name;
$item->data = $value; $item->data = $value;

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Support\Form; namespace FireflyIII\Support\Form;
use Illuminate\Support\Facades\Log;
use FireflyIII\Enums\AccountTypeEnum; use FireflyIII\Enums\AccountTypeEnum;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Account; use FireflyIII\Models\Account;
@@ -93,9 +94,9 @@ class AccountForm
unset($options['class']); unset($options['class']);
try { try {
$html = view('form.assetAccountCheckList', compact('classes', 'selected', 'name', 'label', 'options', 'grouped'))->render(); $html = view('form.assetAccountCheckList', ['classes' => $classes, 'selected' => $selected, 'name' => $name, 'label' => $label, 'options' => $options, 'grouped' => $grouped])->render();
} catch (Throwable $e) { } catch (Throwable $e) {
app('log')->debug(sprintf('Could not render assetAccountCheckList(): %s', $e->getMessage())); Log::debug(sprintf('Could not render assetAccountCheckList(): %s', $e->getMessage()));
$html = 'Could not render assetAccountCheckList.'; $html = 'Could not render assetAccountCheckList.';
throw new FireflyException($html, 0, $e); throw new FireflyException($html, 0, $e);

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Support\Form; namespace FireflyIII\Support\Form;
use Illuminate\Support\Facades\Log;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\TransactionCurrency; use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface; use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
@@ -135,13 +136,13 @@ class CurrencyForm
$key = 'amount_currency_id_'.$name; $key = 'amount_currency_id_'.$name;
$sentCurrencyId = array_key_exists($key, $preFilled) ? (int)$preFilled[$key] : $primaryCurrency->id; $sentCurrencyId = array_key_exists($key, $preFilled) ? (int)$preFilled[$key] : $primaryCurrency->id;
app('log')->debug(sprintf('Sent currency ID is %d', $sentCurrencyId)); Log::debug(sprintf('Sent currency ID is %d', $sentCurrencyId));
// find this currency in set of currencies: // find this currency in set of currencies:
foreach ($currencies as $currency) { foreach ($currencies as $currency) {
if ($currency->id === $sentCurrencyId) { if ($currency->id === $sentCurrencyId) {
$primaryCurrency = $currency; $primaryCurrency = $currency;
app('log')->debug(sprintf('default currency is now %s', $primaryCurrency->code)); Log::debug(sprintf('default currency is now %s', $primaryCurrency->code));
break; break;
} }
@@ -153,9 +154,9 @@ class CurrencyForm
} }
try { try {
$html = view('form.'.$view, compact('primaryCurrency', 'currencies', 'classes', 'name', 'label', 'value', 'options'))->render(); $html = view('form.'.$view, ['primaryCurrency' => $primaryCurrency, 'currencies' => $currencies, 'classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render();
} catch (Throwable $e) { } catch (Throwable $e) {
app('log')->debug(sprintf('Could not render currencyField(): %s', $e->getMessage())); Log::debug(sprintf('Could not render currencyField(): %s', $e->getMessage()));
$html = 'Could not render currencyField.'; $html = 'Could not render currencyField.';
throw new FireflyException($html, 0, $e); throw new FireflyException($html, 0, $e);
@@ -187,13 +188,13 @@ class CurrencyForm
$key = 'amount_currency_id_'.$name; $key = 'amount_currency_id_'.$name;
$sentCurrencyId = array_key_exists($key, $preFilled) ? (int)$preFilled[$key] : $primaryCurrency->id; $sentCurrencyId = array_key_exists($key, $preFilled) ? (int)$preFilled[$key] : $primaryCurrency->id;
app('log')->debug(sprintf('Sent currency ID is %d', $sentCurrencyId)); Log::debug(sprintf('Sent currency ID is %d', $sentCurrencyId));
// find this currency in set of currencies: // find this currency in set of currencies:
foreach ($currencies as $currency) { foreach ($currencies as $currency) {
if ($currency->id === $sentCurrencyId) { if ($currency->id === $sentCurrencyId) {
$primaryCurrency = $currency; $primaryCurrency = $currency;
app('log')->debug(sprintf('default currency is now %s', $primaryCurrency->code)); Log::debug(sprintf('default currency is now %s', $primaryCurrency->code));
break; break;
} }
@@ -205,9 +206,9 @@ class CurrencyForm
} }
try { try {
$html = view('form.'.$view, compact('primaryCurrency', 'currencies', 'classes', 'name', 'label', 'value', 'options'))->render(); $html = view('form.'.$view, ['primaryCurrency' => $primaryCurrency, 'currencies' => $currencies, 'classes' => $classes, 'name' => $name, 'label' => $label, 'value' => $value, 'options' => $options])->render();
} catch (Throwable $e) { } catch (Throwable $e) {
app('log')->debug(sprintf('Could not render currencyField(): %s', $e->getMessage())); Log::debug(sprintf('Could not render currencyField(): %s', $e->getMessage()));
$html = 'Could not render currencyField.'; $html = 'Could not render currencyField.';
throw new FireflyException($html, 0, $e); throw new FireflyException($html, 0, $e);

Some files were not shown because too many files have changed in this diff Show More