Clean up some code.

This commit is contained in:
James Cole
2024-12-14 05:45:54 +01:00
parent b930ad4da7
commit 7d8d773f8f
78 changed files with 2760 additions and 2674 deletions

View File

@@ -67,14 +67,14 @@ class PurgeController extends Controller
$repository = app(PiggyBankRepositoryInterface::class); $repository = app(PiggyBankRepositoryInterface::class);
$repository->setUser($user); $repository->setUser($user);
$repository->purgeAll(); $repository->purgeAll();
// $set = PiggyBank::leftJoin('accounts', 'accounts.id', 'piggy_banks.account_id') // $set = PiggyBank::leftJoin('accounts', 'accounts.id', 'piggy_banks.account_id')
// ->where('accounts.user_id', $user->id)->onlyTrashed()->get(['piggy_banks.*']) // ->where('accounts.user_id', $user->id)->onlyTrashed()->get(['piggy_banks.*'])
// ; // ;
// //
// /** @var PiggyBank $piggy */ // /** @var PiggyBank $piggy */
// foreach ($set as $piggy) { // foreach ($set as $piggy) {
// $piggy->forceDelete(); // $piggy->forceDelete();
// } // }
// rule group // rule group
RuleGroup::whereUserId($user->id)->onlyTrashed()->forceDelete(); RuleGroup::whereUserId($user->id)->onlyTrashed()->forceDelete();

View File

@@ -28,7 +28,6 @@ use FireflyIII\Api\V1\Controllers\Controller;
use FireflyIII\Api\V1\Requests\Insight\GenericRequest; use FireflyIII\Api\V1\Requests\Insight\GenericRequest;
use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Enums\TransactionTypeEnum;
use FireflyIII\Helpers\Collector\GroupCollectorInterface; use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Models\TransactionType;
use FireflyIII\Repositories\Bill\BillRepositoryInterface; use FireflyIII\Repositories\Bill\BillRepositoryInterface;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;

View File

@@ -28,7 +28,6 @@ use FireflyIII\Api\V1\Controllers\Controller;
use FireflyIII\Api\V1\Requests\Insight\GenericRequest; use FireflyIII\Api\V1\Requests\Insight\GenericRequest;
use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Enums\TransactionTypeEnum;
use FireflyIII\Helpers\Collector\GroupCollectorInterface; use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Models\TransactionType;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
/** /**

View File

@@ -28,7 +28,6 @@ use FireflyIII\Api\V1\Controllers\Controller;
use FireflyIII\Api\V1\Requests\Insight\GenericRequest; use FireflyIII\Api\V1\Requests\Insight\GenericRequest;
use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Enums\TransactionTypeEnum;
use FireflyIII\Helpers\Collector\GroupCollectorInterface; use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Models\TransactionType;
use FireflyIII\Repositories\Tag\TagRepositoryInterface; use FireflyIII\Repositories\Tag\TagRepositoryInterface;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;

View File

@@ -28,7 +28,6 @@ use FireflyIII\Api\V1\Controllers\Controller;
use FireflyIII\Api\V1\Requests\Insight\GenericRequest; use FireflyIII\Api\V1\Requests\Insight\GenericRequest;
use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Enums\TransactionTypeEnum;
use FireflyIII\Helpers\Collector\GroupCollectorInterface; use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Models\TransactionType;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
/** /**

View File

@@ -28,7 +28,6 @@ use FireflyIII\Api\V1\Controllers\Controller;
use FireflyIII\Api\V1\Requests\Insight\GenericRequest; use FireflyIII\Api\V1\Requests\Insight\GenericRequest;
use FireflyIII\Enums\TransactionTypeEnum; use FireflyIII\Enums\TransactionTypeEnum;
use FireflyIII\Helpers\Collector\GroupCollectorInterface; use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Models\TransactionType;
use FireflyIII\Repositories\Tag\TagRepositoryInterface; use FireflyIII\Repositories\Tag\TagRepositoryInterface;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;

View File

@@ -32,7 +32,6 @@ use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Helpers\Report\NetWorthInterface; use FireflyIII\Helpers\Report\NetWorthInterface;
use FireflyIII\Models\Account; use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType; use FireflyIII\Models\AccountType;
use FireflyIII\Models\TransactionType;
use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\Bill\BillRepositoryInterface; use FireflyIII\Repositories\Bill\BillRepositoryInterface;
use FireflyIII\Repositories\Budget\AvailableBudgetRepositoryInterface; use FireflyIII\Repositories\Budget\AvailableBudgetRepositoryInterface;

View File

@@ -53,10 +53,11 @@ class UpdateRequest extends FormRequest
'currency_code' => ['currency_code', 'convertString'], 'currency_code' => ['currency_code', 'convertString'],
'notes' => ['notes', 'stringWithNewlines'], 'notes' => ['notes', 'stringWithNewlines'],
]; ];
if(false === $this->has('notes')) { if (false === $this->has('notes')) {
// ignore notes, not submitted. // ignore notes, not submitted.
unset($fields['notes']); unset($fields['notes']);
} }
return $this->getAllData($fields); return $this->getAllData($fields);
} }

View File

@@ -27,7 +27,6 @@ namespace FireflyIII\Api\V1\Requests\Models\PiggyBank;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\TransactionCurrency; use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Repositories\Account\AccountRepositoryInterface; use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Rules\IsValidPositiveAmount;
use FireflyIII\Rules\IsValidZeroOrMoreAmount; use FireflyIII\Rules\IsValidZeroOrMoreAmount;
use FireflyIII\Support\Request\ChecksLogin; use FireflyIII\Support\Request\ChecksLogin;
use FireflyIII\Support\Request\ConvertsDataTypes; use FireflyIII\Support\Request\ConvertsDataTypes;
@@ -121,7 +120,7 @@ class StoreRequest extends FormRequest
} }
} }
} }
if(bccomp($targetAmount, $currentAmount) === -1 && bccomp($targetAmount, '0') === 1) { if (-1 === bccomp($targetAmount, $currentAmount) && 1 === bccomp($targetAmount, '0')) {
$validator->errors()->add('target_amount', trans('validation.current_amount_too_much')); $validator->errors()->add('target_amount', trans('validation.current_amount_too_much'));
} }
} }
@@ -146,6 +145,7 @@ class StoreRequest extends FormRequest
'current_amount' => $this->clearString((string) ($entry['current_amount'] ?? '0')), 'current_amount' => $this->clearString((string) ($entry['current_amount'] ?? '0')),
]; ];
} }
return $return; return $return;
} }
@@ -163,6 +163,7 @@ class StoreRequest extends FormRequest
return $currency; return $currency;
} }
} }
throw new FireflyException('Unexpected empty currency.'); throw new FireflyException('Unexpected empty currency.');
} }
} }

View File

@@ -30,7 +30,6 @@ use FireflyIII\Enums\TransactionTypeEnum;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Helpers\Collector\GroupCollectorInterface; use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Models\TransactionCurrency; use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Models\TransactionType;
use FireflyIII\Repositories\UserGroups\Account\AccountRepositoryInterface; use FireflyIII\Repositories\UserGroups\Account\AccountRepositoryInterface;
use FireflyIII\Support\Chart\ChartData; use FireflyIII\Support\Chart\ChartData;
use FireflyIII\Support\Http\Api\AccountBalanceGrouped; use FireflyIII\Support\Http\Api\AccountBalanceGrouped;

View File

@@ -31,7 +31,6 @@ use FireflyIII\Enums\TransactionTypeEnum;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Helpers\Collector\GroupCollectorInterface; use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Models\AccountType; use FireflyIII\Models\AccountType;
use FireflyIII\Models\TransactionType;
use FireflyIII\Repositories\UserGroups\Account\AccountRepositoryInterface; use FireflyIII\Repositories\UserGroups\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\UserGroups\Currency\CurrencyRepositoryInterface; use FireflyIII\Repositories\UserGroups\Currency\CurrencyRepositoryInterface;
use FireflyIII\Support\Http\Api\CleansChartData; use FireflyIII\Support\Http\Api\CleansChartData;

View File

@@ -33,7 +33,6 @@ use FireflyIII\Helpers\Collector\GroupCollectorInterface;
use FireflyIII\Helpers\Report\NetWorthInterface; use FireflyIII\Helpers\Report\NetWorthInterface;
use FireflyIII\Models\Account; use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType; use FireflyIII\Models\AccountType;
use FireflyIII\Models\TransactionType;
use FireflyIII\Models\UserGroup; use FireflyIII\Models\UserGroup;
use FireflyIII\Repositories\UserGroups\Account\AccountRepositoryInterface; use FireflyIII\Repositories\UserGroups\Account\AccountRepositoryInterface;
use FireflyIII\Repositories\UserGroups\Bill\BillRepositoryInterface; use FireflyIII\Repositories\UserGroups\Bill\BillRepositoryInterface;

View File

@@ -1,4 +1,6 @@
<?php <?php
declare(strict_types=1);
/* /*
* UpgradeMultiPiggyBanks.php * UpgradeMultiPiggyBanks.php
* Copyright (c) 2024 james@firefly-iii.org. * Copyright (c) 2024 james@firefly-iii.org.
@@ -43,8 +45,6 @@ class UpgradeMultiPiggyBanks extends Command
/** /**
* Execute the console command. * Execute the console command.
*
* @return int
*/ */
public function handle(): int public function handle(): int
{ {
@@ -61,9 +61,6 @@ class UpgradeMultiPiggyBanks extends Command
return 0; return 0;
} }
/**
* @return bool
*/
private function isExecuted(): bool private function isExecuted(): bool
{ {
$configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false); $configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false);
@@ -74,10 +71,6 @@ class UpgradeMultiPiggyBanks extends Command
return false; return false;
} }
/**
*
*/
private function markAsExecuted(): void private function markAsExecuted(): void
{ {
app('fireflyconfig')->set(self::CONFIG_NAME, true); app('fireflyconfig')->set(self::CONFIG_NAME, true);
@@ -89,6 +82,7 @@ class UpgradeMultiPiggyBanks extends Command
$this->accountRepository = app(AccountRepositoryInterface::class); $this->accountRepository = app(AccountRepositoryInterface::class);
$set = PiggyBank::whereNotNull('account_id')->get(); $set = PiggyBank::whereNotNull('account_id')->get();
Log::debug(sprintf('Will update %d piggy banks(s).', $set->count())); Log::debug(sprintf('Will update %d piggy banks(s).', $set->count()));
/** @var PiggyBank $piggyBank */ /** @var PiggyBank $piggyBank */
foreach ($set as $piggyBank) { foreach ($set as $piggyBank) {
$this->upgradePiggyBank($piggyBank); $this->upgradePiggyBank($piggyBank);

View File

@@ -1,4 +1,5 @@
<?php <?php
/* /*
* UnknownUserAttemptedLogin.php * UnknownUserAttemptedLogin.php
* Copyright (c) 2024 james@firefly-iii.org. * Copyright (c) 2024 james@firefly-iii.org.
@@ -24,7 +25,6 @@ declare(strict_types=1);
namespace FireflyIII\Events\Security; namespace FireflyIII\Events\Security;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
class UnknownUserAttemptedLogin class UnknownUserAttemptedLogin
{ {

View File

@@ -1,4 +1,5 @@
<?php <?php
/* /*
* TestEmailChannel.php * TestEmailChannel.php
* Copyright (c) 2024 james@firefly-iii.org. * Copyright (c) 2024 james@firefly-iii.org.

View File

@@ -43,7 +43,8 @@ use Illuminate\Support\Facades\Notification;
*/ */
class AdminEventHandler class AdminEventHandler
{ {
public function sendLoginAttemptNotification(UnknownUserAttemptedLogin $event): void { public function sendLoginAttemptNotification(UnknownUserAttemptedLogin $event): void
{
try { try {
$owner = new OwnerNotifiable(); $owner = new OwnerNotifiable();
Notification::send($owner, new UnknownUserLoginAttempt($event->address)); Notification::send($owner, new UnknownUserLoginAttempt($event->address));
@@ -64,13 +65,13 @@ class AdminEventHandler
} }
} }
public function sendInvitationNotification(InvitationCreated $event): void public function sendInvitationNotification(InvitationCreated $event): void
{ {
$sendMail = app('fireflyconfig')->get('notification_invite_created', true)->data; $sendMail = app('fireflyconfig')->get('notification_invite_created', true)->data;
if (false === $sendMail) { if (false === $sendMail) {
return; return;
} }
try { try {
$owner = new OwnerNotifiable(); $owner = new OwnerNotifiable();
Notification::send($owner, new UserInvitation($owner, $event->invitee)); Notification::send($owner, new UserInvitation($owner, $event->invitee));
@@ -131,18 +132,27 @@ class AdminEventHandler
switch ($event->channel) { switch ($event->channel) {
case 'email': case 'email':
$class = TestNotificationEmail::class; $class = TestNotificationEmail::class;
break; break;
case 'slack': case 'slack':
$class = TestNotificationSlack::class; $class = TestNotificationSlack::class;
break; break;
case 'ntfy': case 'ntfy':
$class = TestNotificationNtfy::class; $class = TestNotificationNtfy::class;
break; break;
case 'pushover': case 'pushover':
$class = TestNotificationPushover::class; $class = TestNotificationPushover::class;
break; break;
default: default:
app('log')->error(sprintf('Unknown channel "%s" in sendTestNotification method.', $event->channel)); app('log')->error(sprintf('Unknown channel "%s" in sendTestNotification method.', $event->channel));
return; return;
} }
Log::debug(sprintf('Will send %s as a notification.', $class)); Log::debug(sprintf('Will send %s as a notification.', $class));

View File

@@ -223,6 +223,7 @@ class UserEventHandler
$sendMail = (bool) app('fireflyconfig')->get('notification_admin_new_reg', true)->data; $sendMail = (bool) app('fireflyconfig')->get('notification_admin_new_reg', true)->data;
if ($sendMail) { if ($sendMail) {
$owner = $event->owner; $owner = $event->owner;
try { try {
Notification::send($owner, new AdminRegistrationNotification($event->owner, $event->user)); Notification::send($owner, new AdminRegistrationNotification($event->owner, $event->user));
} catch (\Exception $e) { // @phpstan-ignore-line } catch (\Exception $e) { // @phpstan-ignore-line

View File

@@ -36,14 +36,14 @@ class PiggyBankObserver
{ {
app('log')->debug('Observe "created" of a piggy bank. DO NOTHING.'); app('log')->debug('Observe "created" of a piggy bank. DO NOTHING.');
// $repetition = new PiggyBankRepetition(); // $repetition = new PiggyBankRepetition();
// $repetition->piggyBank()->associate($piggyBank); // $repetition->piggyBank()->associate($piggyBank);
// $repetition->start_date = $piggyBank->start_date; // $repetition->start_date = $piggyBank->start_date;
// $repetition->start_date_tz = $piggyBank->start_date->format('e'); // $repetition->start_date_tz = $piggyBank->start_date->format('e');
// $repetition->target_date = $piggyBank->target_date; // $repetition->target_date = $piggyBank->target_date;
// $repetition->target_date_tz = $piggyBank->target_date?->format('e'); // $repetition->target_date_tz = $piggyBank->target_date?->format('e');
// $repetition->current_amount = '0'; // $repetition->current_amount = '0';
// $repetition->save(); // $repetition->save();
} }
/** /**

View File

@@ -23,15 +23,9 @@ declare(strict_types=1);
namespace FireflyIII\Http\Controllers\Admin; namespace FireflyIII\Http\Controllers\Admin;
use FireflyIII\Events\AdminRequestedTestMessage;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Http\Middleware\IsDemoUser; use FireflyIII\Http\Middleware\IsDemoUser;
use FireflyIII\Support\Notifications\UrlValidator;
use FireflyIII\User;
use Illuminate\Contracts\View\Factory; use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
use Illuminate\View\View; use Illuminate\View\View;

View File

@@ -1,4 +1,5 @@
<?php <?php
/* /*
* NotificationController.php * NotificationController.php
* Copyright (c) 2024 james@firefly-iii.org. * Copyright (c) 2024 james@firefly-iii.org.
@@ -68,13 +69,26 @@ class NotificationController extends Controller
$forcedAvailability['ntfy'] = '' !== $ntfyTopic; $forcedAvailability['ntfy'] = '' !== $ntfyTopic;
$forcedAvailability['pushover'] = '' !== $pushoverAppToken && '' !== $pushoverUserToken; $forcedAvailability['pushover'] = '' !== $pushoverAppToken && '' !== $pushoverUserToken;
return view('admin.notifications.index', return view(
'admin.notifications.index',
compact( compact(
'title', 'subTitle', 'forcedAvailability', 'mainTitleIcon', 'subTitleIcon', 'channels', 'title',
'slackUrl', 'notifications', 'subTitle',
'pushoverAppToken', 'pushoverUserToken', 'forcedAvailability',
'ntfyServer', 'ntfyTopic', 'ntfyAuth', 'ntfyUser', 'ntfyPass' 'mainTitleIcon',
)); 'subTitleIcon',
'channels',
'slackUrl',
'notifications',
'pushoverAppToken',
'pushoverUserToken',
'ntfyServer',
'ntfyTopic',
'ntfyAuth',
'ntfyUser',
'ntfyPass'
)
);
} }
public function postIndex(NotificationRequest $request): RedirectResponse public function postIndex(NotificationRequest $request): RedirectResponse
@@ -112,7 +126,9 @@ class NotificationController extends Controller
switch ($channel) { switch ($channel) {
default: default:
session()->flash('error', (string) trans('firefly.notification_test_failed', ['channel' => $channel])); session()->flash('error', (string) trans('firefly.notification_test_failed', ['channel' => $channel]));
break; break;
case 'email': case 'email':
case 'slack': case 'slack':
case 'pushover': case 'pushover':

View File

@@ -28,7 +28,6 @@ use FireflyIII\Events\ActuallyLoggedIn;
use FireflyIII\Events\Security\UnknownUserAttemptedLogin; use FireflyIII\Events\Security\UnknownUserAttemptedLogin;
use FireflyIII\Exceptions\FireflyException; use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Notifications\Notifiables\OwnerNotifiable;
use FireflyIII\Providers\RouteServiceProvider; use FireflyIII\Providers\RouteServiceProvider;
use FireflyIII\Repositories\User\UserRepositoryInterface; use FireflyIII\Repositories\User\UserRepositoryInterface;
use Illuminate\Contracts\Foundation\Application; use Illuminate\Contracts\Foundation\Application;
@@ -128,7 +127,7 @@ class LoginController extends Controller
} }
app('log')->warning('Login attempt failed.'); app('log')->warning('Login attempt failed.');
$username = (string) $request->get($this->username()); $username = (string) $request->get($this->username());
if(null === $this->repository->findByEmail($username)) { if (null === $this->repository->findByEmail($username)) {
// send event to owner. // send event to owner.
event(new UnknownUserAttemptedLogin($username)); event(new UnknownUserAttemptedLogin($username));
} }

View File

@@ -107,6 +107,7 @@ class BudgetLimitController extends Controller
public function show(BudgetLimit $budgetLimit) public function show(BudgetLimit $budgetLimit)
{ {
$notes = $this->blRepository->getNoteText($budgetLimit); $notes = $this->blRepository->getNoteText($budgetLimit);
return view('budgets.budget-limits.show', compact('budgetLimit', 'notes')); return view('budgets.budget-limits.show', compact('budgetLimit', 'notes'));
} }
@@ -116,6 +117,7 @@ class BudgetLimitController extends Controller
public function edit(BudgetLimit $budgetLimit) public function edit(BudgetLimit $budgetLimit)
{ {
$notes = $this->blRepository->getNoteText($budgetLimit); $notes = $this->blRepository->getNoteText($budgetLimit);
return view('budgets.budget-limits.edit', compact('budgetLimit', 'notes')); return view('budgets.budget-limits.edit', compact('budgetLimit', 'notes'));
} }
@@ -135,7 +137,7 @@ class BudgetLimitController extends Controller
* *
* @throws FireflyException * @throws FireflyException
*/ */
public function store(Request $request): JsonResponse | RedirectResponse public function store(Request $request): JsonResponse|RedirectResponse
{ {
app('log')->debug('Going to store new budget-limit.', $request->all()); app('log')->debug('Going to store new budget-limit.', $request->all());
// first search for existing one and update it if necessary. // first search for existing one and update it if necessary.
@@ -249,12 +251,12 @@ class BudgetLimitController extends Controller
$amount = bcmul($amount, '-1'); $amount = bcmul($amount, '-1');
} }
$notes = (string)$request->get('notes'); $notes = (string)$request->get('notes');
if(strlen($notes) > 32768) { if (strlen($notes) > 32768) {
$notes = substr($notes, 0, 32768); $notes = substr($notes, 0, 32768);
} }
$limit = $this->blRepository->update($budgetLimit, ['amount' => $amount,'notes' => $notes]); $limit = $this->blRepository->update($budgetLimit, ['amount' => $amount, 'notes' => $notes]);
app('preferences')->mark(); app('preferences')->mark();
$array = $limit->toArray(); $array = $limit->toArray();
@@ -278,6 +280,7 @@ class BudgetLimitController extends Controller
if ('true' === $request->get('redirect')) { if ('true' === $request->get('redirect')) {
return redirect(route('budgets.index')); return redirect(route('budgets.index'));
} }
return response()->json($array); return response()->json($array);
} }
} }

View File

@@ -43,7 +43,6 @@ use Illuminate\Support\Facades\Log;
*/ */
class HomeController extends Controller class HomeController extends Controller
{ {
/** /**
* HomeController constructor. * HomeController constructor.
*/ */

View File

@@ -165,6 +165,7 @@ class IndexController extends Controller
$transformer = app(PiggyBankTransformer::class); $transformer = app(PiggyBankTransformer::class);
$transformer->setParameters(new ParameterBag()); $transformer->setParameters(new ParameterBag());
$piggyBanks = []; $piggyBanks = [];
/** @var PiggyBank $piggy */ /** @var PiggyBank $piggy */
foreach ($collection as $piggy) { foreach ($collection as $piggy) {
$array = $transformer->transform($piggy); $array = $transformer->transform($piggy);
@@ -179,6 +180,7 @@ class IndexController extends Controller
// sum the total amount for the index. // sum the total amount for the index.
$piggyBanks[$groupOrder]['piggy_banks'][] = $array; $piggyBanks[$groupOrder]['piggy_banks'][] = $array;
} }
return $piggyBanks; return $piggyBanks;
} }
@@ -196,9 +198,11 @@ class IndexController extends Controller
$accountTransformer->setParameters($parameters); $accountTransformer->setParameters($parameters);
$return = []; $return = [];
/** @var PiggyBank $piggy */ /** @var PiggyBank $piggy */
foreach ($collection as $piggy) { foreach ($collection as $piggy) {
$accounts = $piggy->accounts; $accounts = $piggy->accounts;
/** @var Account $account */ /** @var Account $account */
foreach ($accounts as $account) { foreach ($accounts as $account) {
$array = $accountTransformer->transform($account); $array = $accountTransformer->transform($account);
@@ -214,20 +218,21 @@ class IndexController extends Controller
} }
// calculate new interesting fields: // calculate new interesting fields:
// $return[$accountId]['left'] -= $array['current_amount']; // $return[$accountId]['left'] -= $array['current_amount'];
// $return[$accountId]['saved'] += $array['current_amount']; // $return[$accountId]['saved'] += $array['current_amount'];
// $return[$accountId]['target'] += $array['target_amount']; // $return[$accountId]['target'] += $array['target_amount'];
// $return[$accountId]['to_save'] += ($array['target_amount'] - $array['current_amount']); // $return[$accountId]['to_save'] += ($array['target_amount'] - $array['current_amount']);
// $return['account_name'] = $account['name']; // $return['account_name'] = $account['name'];
} }
} }
return $return; return $return;
} }
private function mergeAccountsAndPiggies(array $piggyBanks, array $accounts): array private function mergeAccountsAndPiggies(array $piggyBanks, array $accounts): array
{ {
/** @var array $piggyBank */ // @var array $piggyBank
foreach ($piggyBanks as $group) { foreach ($piggyBanks as $group) {
foreach ($group['piggy_banks'] as $piggyBank) { foreach ($group['piggy_banks'] as $piggyBank) {
// loop all accounts in this piggy bank subtract the current amount from "left to save" in the $accounts array. // loop all accounts in this piggy bank subtract the current amount from "left to save" in the $accounts array.
@@ -243,6 +248,7 @@ class IndexController extends Controller
} }
} }
} }
return $accounts; return $accounts;
} }
} }

View File

@@ -117,9 +117,10 @@ class PreferencesController extends Controller
$ntfyAuth = app('preferences')->get('ntfy_auth', false)->data; $ntfyAuth = app('preferences')->get('ntfy_auth', false)->data;
$ntfyUser = app('preferences')->getEncrypted('ntfy_user', '')->data; $ntfyUser = app('preferences')->getEncrypted('ntfy_user', '')->data;
$ntfyPass = app('preferences')->getEncrypted('ntfy_pass', '')->data; $ntfyPass = app('preferences')->getEncrypted('ntfy_pass', '')->data;
$channels = config('notifications.channels');
$forcedAvailability = [];
// notification preferences
// notification preferences (single value for each):
$notifications = []; $notifications = [];
foreach (config('notifications.notifications.user') as $key => $info) { foreach (config('notifications.notifications.user') as $key => $info) {
if ($info['enabled']) { if ($info['enabled']) {
@@ -130,6 +131,12 @@ class PreferencesController extends Controller
]; ];
} }
} }
// loop all channels to see if they are available.
foreach ($channels as $channel => $info) {
$forcedAvailability[$channel] = true;
}
$forcedAvailability['ntfy'] = '' !== $ntfyTopic;
$forcedAvailability['pushover'] = '' !== $pushoverAppToken && '' !== $pushoverUserToken;
ksort($languages); ksort($languages);
@@ -161,9 +168,32 @@ class PreferencesController extends Controller
$ntfyPass = ''; $ntfyPass = '';
} }
return view('preferences.index', compact('language', 'pushoverAppToken', 'pushoverUserToken', return view('preferences.index', compact(
'ntfyServer', 'ntfyTopic', 'ntfyAuth', 'ntfyUser', 'ntfyPass', 'language',
'groupedAccounts', 'isDocker', 'frontpageAccounts', 'languages', 'darkMode', 'availableDarkModes', 'notifications', 'slackUrl', 'locales', 'locale', 'tjOptionalFields', 'viewRange', 'customFiscalYear', 'listPageSize', 'fiscalYearStart')); 'pushoverAppToken',
'pushoverUserToken',
'ntfyServer',
'ntfyTopic',
'ntfyAuth',
'ntfyUser',
'forcedAvailability',
'ntfyPass',
'groupedAccounts',
'isDocker',
'frontpageAccounts',
'languages',
'darkMode',
'availableDarkModes',
'notifications',
'slackUrl',
'locales',
'locale',
'tjOptionalFields',
'viewRange',
'customFiscalYear',
'listPageSize',
'fiscalYearStart'
));
} }
/** /**
@@ -189,7 +219,8 @@ class PreferencesController extends Controller
// extract notifications: // extract notifications:
$all = $request->all(); $all = $request->all();
die('fix the reference to the available notifications.');
exit('fix the reference to the available notifications.');
foreach (config('firefly.available_notifications') as $option) { foreach (config('firefly.available_notifications') as $option) {
$key = sprintf('notification_%s', $option); $key = sprintf('notification_%s', $option);
if (array_key_exists($key, $all)) { if (array_key_exists($key, $all)) {

View File

@@ -1,4 +1,5 @@
<?php <?php
/* /*
* NotificationRequest.php * NotificationRequest.php
* Copyright (c) 2024 james@firefly-iii.org. * Copyright (c) 2024 james@firefly-iii.org.
@@ -53,6 +54,7 @@ class NotificationRequest extends FormRequest
$return['ntfy_auth'] = $this->convertBoolean($this->get('ntfy_auth')); $return['ntfy_auth'] = $this->convertBoolean($this->get('ntfy_auth'));
$return['ntfy_user'] = $this->convertString('ntfy_user'); $return['ntfy_user'] = $this->convertString('ntfy_user');
$return['ntfy_pass'] = $this->convertString('ntfy_pass'); $return['ntfy_pass'] = $this->convertString('ntfy_pass');
return $return; return $return;
} }
@@ -70,7 +72,7 @@ class NotificationRequest extends FormRequest
foreach (config('notifications.notifications.owner') as $key => $info) { foreach (config('notifications.notifications.owner') as $key => $info) {
$rules[sprintf('notification_%s', $key)] = 'in:0,1'; $rules[sprintf('notification_%s', $key)] = 'in:0,1';
} }
return $rules; return $rules;
} }
} }

View File

@@ -59,7 +59,7 @@ class PiggyBankStoreRequest extends FormRequest
$accounts = []; $accounts = [];
} }
foreach ($accounts as $item) { foreach ($accounts as $item) {
$data['accounts'][] = ['account_id' => (int) ($item)]; $data['accounts'][] = ['account_id' => (int) $item];
} }
return $data; return $data;
@@ -127,6 +127,7 @@ class PiggyBankStoreRequest extends FormRequest
if (null === $currency) { if (null === $currency) {
return app('amount')->getDefaultCurrency(); return app('amount')->getDefaultCurrency();
} }
return $currency; return $currency;
} }
} }

View File

@@ -55,7 +55,7 @@ class PiggyBank extends Model
'target_amount' => 'string', 'target_amount' => 'string',
]; ];
protected $fillable = ['name', 'account_id', 'order', 'target_amount', 'start_date', 'start_date_tz', 'target_date', 'target_date_tz', 'active','transaction_currency_id']; protected $fillable = ['name', 'account_id', 'order', 'target_amount', 'start_date', 'start_date_tz', 'target_date', 'target_date_tz', 'active', 'transaction_currency_id'];
/** /**
* Route binder. Converts the key in the URL to the specified object (or throw 404). * Route binder. Converts the key in the URL to the specified object (or throw 404).
@@ -67,9 +67,10 @@ class PiggyBank extends Model
if (auth()->check()) { if (auth()->check()) {
$piggyBankId = (int)$value; $piggyBankId = (int)$value;
$piggyBank = self::where('piggy_banks.id', $piggyBankId) $piggyBank = self::where('piggy_banks.id', $piggyBankId)
->leftJoin('account_piggy_bank','account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id') ->leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id')
->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id') ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id')
->where('accounts.user_id', auth()->user()->id)->first(['piggy_banks.*']); ->where('accounts.user_id', auth()->user()->id)->first(['piggy_banks.*'])
;
if (null !== $piggyBank) { if (null !== $piggyBank) {
return $piggyBank; return $piggyBank;
} }

View File

@@ -38,7 +38,6 @@ use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany; use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/** /**

View File

@@ -1,4 +1,5 @@
<?php <?php
/* /*
* UnknownUserLoginAttempt.php * UnknownUserLoginAttempt.php
* Copyright (c) 2024 james@firefly-iii.org. * Copyright (c) 2024 james@firefly-iii.org.
@@ -64,15 +65,14 @@ class UnknownUserLoginAttempt extends Notification
/** /**
* Get the mail representation of the notification. * Get the mail representation of the notification.
* *
* @return MailMessage
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter) * @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/ */
public function toMail(OwnerNotifiable $notifiable): MailMessage public function toMail(OwnerNotifiable $notifiable): MailMessage
{ {
return new MailMessage() return new MailMessage()
->markdown('emails.owner.unknown-user', ['address' => $this->address]) ->markdown('emails.owner.unknown-user', ['address' => $this->address])
->subject((string) trans('email.unknown_user_subject')); ->subject((string) trans('email.unknown_user_subject'))
;
} }
/** /**
@@ -90,7 +90,8 @@ class UnknownUserLoginAttempt extends Notification
public function toPushover(OwnerNotifiable $notifiable): PushoverMessage public function toPushover(OwnerNotifiable $notifiable): PushoverMessage
{ {
return PushoverMessage::create((string) trans('email.unknown_user_message', ['address' => $this->address])) return PushoverMessage::create((string) trans('email.unknown_user_message', ['address' => $this->address]))
->title((string) trans('email.unknown_user_subject')); ->title((string) trans('email.unknown_user_subject'))
;
} }
public function toNtfy(OwnerNotifiable $notifiable): Message public function toNtfy(OwnerNotifiable $notifiable): Message

View File

@@ -83,7 +83,8 @@ class UserInvitation extends Notification
{ {
return (new MailMessage()) return (new MailMessage())
->markdown('emails.invitation-created', ['email' => $this->invitee->user->email, 'invitee' => $this->invitee->email]) ->markdown('emails.invitation-created', ['email' => $this->invitee->user->email, 'invitee' => $this->invitee->email])
->subject((string) trans('email.invitation_created_subject')); ->subject((string) trans('email.invitation_created_subject'))
;
} }
/** /**
@@ -107,7 +108,8 @@ class UserInvitation extends Notification
Log::debug('Now in toPushover() for UserInvitation'); Log::debug('Now in toPushover() for UserInvitation');
return PushoverMessage::create((string) trans('email.invitation_created_body', ['email' => $this->invitee->user->email, 'invitee' => $this->invitee->email])) return PushoverMessage::create((string) trans('email.invitation_created_body', ['email' => $this->invitee->user->email, 'invitee' => $this->invitee->email]))
->title((string) trans('email.invitation_created_subject')); ->title((string) trans('email.invitation_created_subject'))
;
} }
public function toNtfy(OwnerNotifiable $notifiable): Message public function toNtfy(OwnerNotifiable $notifiable): Message

View File

@@ -79,7 +79,8 @@ class UserRegistration extends Notification
{ {
return (new MailMessage()) return (new MailMessage())
->markdown('emails.registered-admin', ['email' => $this->user->email, 'id' => $this->user->id]) ->markdown('emails.registered-admin', ['email' => $this->user->email, 'id' => $this->user->id])
->subject((string) trans('email.registered_subject_admin')); ->subject((string) trans('email.registered_subject_admin'))
;
} }
/** /**
@@ -101,7 +102,8 @@ class UserRegistration extends Notification
Log::debug('Now in toPushover() for UserRegistration'); Log::debug('Now in toPushover() for UserRegistration');
return PushoverMessage::create((string) trans('email.admin_new_user_registered', ['email' => $this->user->email, 'invitee' => $this->user->email])) return PushoverMessage::create((string) trans('email.admin_new_user_registered', ['email' => $this->user->email, 'invitee' => $this->user->email]))
->title((string) trans('email.registered_subject_admin')); ->title((string) trans('email.registered_subject_admin'))
;
} }
public function toNtfy(OwnerNotifiable $notifiable): Message public function toNtfy(OwnerNotifiable $notifiable): Message
@@ -123,7 +125,7 @@ class UserRegistration extends Notification
$message = new Message(); $message = new Message();
$message->topic($settings['ntfy_topic']); $message->topic($settings['ntfy_topic']);
$message->title((string) trans('email.registered_subject_admin')); $message->title((string) trans('email.registered_subject_admin'));
$message->body((string) trans('email.admin_new_user_registered', ['email' => $this->user->email, 'invitee' => $this->user->email]) ); $message->body((string) trans('email.admin_new_user_registered', ['email' => $this->user->email, 'invitee' => $this->user->email]));
return $message; return $message;
} }

View File

@@ -27,7 +27,6 @@ namespace FireflyIII\Notifications\Admin;
use FireflyIII\Notifications\Notifiables\OwnerNotifiable; use FireflyIII\Notifications\Notifiables\OwnerNotifiable;
use FireflyIII\Notifications\ReturnsAvailableChannels; use FireflyIII\Notifications\ReturnsAvailableChannels;
use FireflyIII\Notifications\ReturnsSettings; use FireflyIII\Notifications\ReturnsSettings;
use FireflyIII\Support\Notifications\UrlValidator;
use Illuminate\Bus\Queueable; use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\SlackMessage; use Illuminate\Notifications\Messages\SlackMessage;
@@ -108,7 +107,8 @@ class VersionCheckResult extends Notification
Log::debug('Now in toPushover() for VersionCheckResult'); Log::debug('Now in toPushover() for VersionCheckResult');
return PushoverMessage::create($this->message) return PushoverMessage::create($this->message)
->title((string) trans('email.new_version_email_subject')); ->title((string) trans('email.new_version_email_subject'))
;
} }
public function toNtfy(OwnerNotifiable $notifiable): Message public function toNtfy(OwnerNotifiable $notifiable): Message

View File

@@ -1,4 +1,5 @@
<?php <?php
/* /*
* AdminNotifiable.php * AdminNotifiable.php
* Copyright (c) 2024 james@firefly-iii.org. * Copyright (c) 2024 james@firefly-iii.org.
@@ -30,13 +31,13 @@ use NotificationChannels\Pushover\PushoverReceiver;
class OwnerNotifiable class OwnerNotifiable
{ {
public function routeNotificationForSlack(): string public function routeNotificationForSlack(): string
{ {
$res = app('fireflyconfig')->getEncrypted('slack_webhook_url', '')->data; $res = app('fireflyconfig')->getEncrypted('slack_webhook_url', '')->data;
if (is_array($res)) { if (is_array($res)) {
$res = ''; $res = '';
} }
return (string) $res; return (string) $res;
} }
@@ -45,8 +46,10 @@ class OwnerNotifiable
Log::debug('Return settings for routeNotificationForPushover'); Log::debug('Return settings for routeNotificationForPushover');
$pushoverAppToken = (string) app('fireflyconfig')->getEncrypted('pushover_app_token', '')->data; $pushoverAppToken = (string) app('fireflyconfig')->getEncrypted('pushover_app_token', '')->data;
$pushoverUserToken = (string) app('fireflyconfig')->getEncrypted('pushover_user_token', '')->data; $pushoverUserToken = (string) app('fireflyconfig')->getEncrypted('pushover_user_token', '')->data;
return PushoverReceiver::withUserKey($pushoverUserToken) return PushoverReceiver::withUserKey($pushoverUserToken)
->withApplicationToken($pushoverAppToken); ->withApplicationToken($pushoverAppToken)
;
} }
/** /**
@@ -59,9 +62,10 @@ class OwnerNotifiable
*/ */
public function routeNotificationFor($driver, $notification = null) public function routeNotificationFor($driver, $notification = null)
{ {
$method = 'routeNotificationFor' . Str::studly($driver); $method = 'routeNotificationFor'.Str::studly($driver);
if (method_exists($this, $method)) { if (method_exists($this, $method)) {
Log::debug(sprintf('Redirect for settings to "%s".', $method)); Log::debug(sprintf('Redirect for settings to "%s".', $method));
return $this->{$method}($notification); // @phpstan-ignore-line return $this->{$method}($notification); // @phpstan-ignore-line
} }
Log::debug(sprintf('No method "%s" found, return generic settings.', $method)); Log::debug(sprintf('No method "%s" found, return generic settings.', $method));

View File

@@ -1,4 +1,5 @@
<?php <?php
/* /*
* ReturnsAvailableChannels.php * ReturnsAvailableChannels.php
* Copyright (c) 2024 james@firefly-iii.org. * Copyright (c) 2024 james@firefly-iii.org.
@@ -73,8 +74,8 @@ class ReturnsAvailableChannels
} }
Log::debug(sprintf('Final channel set in ReturnsAvailableChannels: %s ', implode(', ', $channels))); Log::debug(sprintf('Final channel set in ReturnsAvailableChannels: %s ', implode(', ', $channels)));
// only the owner can get notifications over // only the owner can get notifications over
return $channels; return $channels;
} }
} }

View File

@@ -1,4 +1,5 @@
<?php <?php
/* /*
* ReturnsSettings.php * ReturnsSettings.php
* Copyright (c) 2024 james@firefly-iii.org. * Copyright (c) 2024 james@firefly-iii.org.
@@ -34,6 +35,7 @@ class ReturnsSettings
if ('ntfy' === $channel) { if ('ntfy' === $channel) {
return self::getNtfySettings($type, $user); return self::getNtfySettings($type, $user);
} }
throw new FireflyException(sprintf('Cannot handle channel "%s"', $channel)); throw new FireflyException(sprintf('Cannot handle channel "%s"', $channel));
} }
@@ -54,7 +56,7 @@ class ReturnsSettings
$settings['ntfy_user'] = FireflyConfig::getEncrypted('ntfy_user', '')->data; $settings['ntfy_user'] = FireflyConfig::getEncrypted('ntfy_user', '')->data;
$settings['ntfy_pass'] = FireflyConfig::getEncrypted('ntfy_pass', '')->data; $settings['ntfy_pass'] = FireflyConfig::getEncrypted('ntfy_pass', '')->data;
} }
return $settings; return $settings;
} }
} }

View File

@@ -49,8 +49,6 @@ class TestNotificationEmail extends Notification
/** /**
* Get the array representation of the notification. * Get the array representation of the notification.
* *
* @param OwnerNotifiable $notifiable
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter) * @SuppressWarnings(PHPMD.UnusedFormalParameter)
* *
* @return array * @return array
@@ -73,9 +71,11 @@ class TestNotificationEmail extends Notification
public function toMail(OwnerNotifiable $notifiable) public function toMail(OwnerNotifiable $notifiable)
{ {
$address = (string) config('firefly.site_owner'); $address = (string) config('firefly.site_owner');
return (new MailMessage()) return (new MailMessage())
->markdown('emails.admin-test', ['email' => $address]) ->markdown('emails.admin-test', ['email' => $address])
->subject((string) trans('email.admin_test_subject')); ->subject((string) trans('email.admin_test_subject'))
;
} }
/** /**

View File

@@ -26,13 +26,12 @@ namespace FireflyIII\Notifications\Test;
use FireflyIII\Notifications\Notifiables\OwnerNotifiable; use FireflyIII\Notifications\Notifiables\OwnerNotifiable;
use FireflyIII\Notifications\ReturnsSettings; use FireflyIII\Notifications\ReturnsSettings;
use FireflyIII\User;
use Illuminate\Bus\Queueable; use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification; use Illuminate\Notifications\Notification;
use Ntfy\Message; use Ntfy\Message;
use Wijourdil\NtfyNotificationChannel\Channels\NtfyChannel; use Wijourdil\NtfyNotificationChannel\Channels\NtfyChannel;
//use Illuminate\Notifications\Slack\SlackMessage; // use Illuminate\Notifications\Slack\SlackMessage;
/** /**
* Class TestNotification * Class TestNotification
@@ -66,7 +65,6 @@ class TestNotificationNtfy extends Notification
]; ];
} }
public function toNtfy(OwnerNotifiable $notifiable): Message public function toNtfy(OwnerNotifiable $notifiable): Message
{ {
$settings = ReturnsSettings::getSettings('ntfy', 'owner', null); $settings = ReturnsSettings::getSettings('ntfy', 'owner', null);

View File

@@ -25,17 +25,13 @@ declare(strict_types=1);
namespace FireflyIII\Notifications\Test; namespace FireflyIII\Notifications\Test;
use FireflyIII\Notifications\Notifiables\OwnerNotifiable; use FireflyIII\Notifications\Notifiables\OwnerNotifiable;
use FireflyIII\User;
use Illuminate\Bus\Queueable; use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification; use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
use NotificationChannels\Pushover\PushoverChannel; use NotificationChannels\Pushover\PushoverChannel;
use NotificationChannels\Pushover\PushoverMessage; use NotificationChannels\Pushover\PushoverMessage;
use Ntfy\Message;
use Wijourdil\NtfyNotificationChannel\Channels\NtfyChannel;
//use Illuminate\Notifications\Slack\SlackMessage; // use Illuminate\Notifications\Slack\SlackMessage;
/** /**
* Class TestNotification * Class TestNotification
@@ -57,8 +53,6 @@ class TestNotificationPushover extends Notification
/** /**
* Get the array representation of the notification. * Get the array representation of the notification.
* *
* @param OwnerNotifiable $notifiable
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter) * @SuppressWarnings(PHPMD.UnusedFormalParameter)
* *
* @return array * @return array
@@ -69,16 +63,15 @@ class TestNotificationPushover extends Notification
]; ];
} }
public function toPushover(OwnerNotifiable $notifiable): PushoverMessage public function toPushover(OwnerNotifiable $notifiable): PushoverMessage
{ {
Log::debug('Now in toPushover()'); Log::debug('Now in toPushover()');
return PushoverMessage::create((string)trans('email.admin_test_message', ['channel' => 'Pushover'])) return PushoverMessage::create((string)trans('email.admin_test_message', ['channel' => 'Pushover']))
->title((string)trans('email.admin_test_subject')); ->title((string)trans('email.admin_test_subject'))
;
} }
/** /**
* @SuppressWarnings(PHPMD.UnusedFormalParameter) * @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/ */

View File

@@ -29,7 +29,7 @@ use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\SlackMessage; use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification; use Illuminate\Notifications\Notification;
//use Illuminate\Notifications\Slack\SlackMessage; // use Illuminate\Notifications\Slack\SlackMessage;
/** /**
* Class TestNotification * Class TestNotification
@@ -51,8 +51,6 @@ class TestNotificationSlack extends Notification
/** /**
* Get the array representation of the notification. * Get the array representation of the notification.
* *
* @param OwnerNotifiable $notifiable
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter) * @SuppressWarnings(PHPMD.UnusedFormalParameter)
* *
* @return array * @return array
@@ -66,15 +64,12 @@ class TestNotificationSlack extends Notification
/** /**
* Get the Slack representation of the notification. * Get the Slack representation of the notification.
* *
* @param OwnerNotifiable $notifiable
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter) * @SuppressWarnings(PHPMD.UnusedFormalParameter)
*
*/ */
public function toSlack(OwnerNotifiable $notifiable) public function toSlack(OwnerNotifiable $notifiable)
{ {
return new SlackMessage()->content((string) trans('email.admin_test_subject')); return new SlackMessage()->content((string) trans('email.admin_test_subject'));
//return new SlackMessage()->text((string) trans('email.admin_test_subject'))->to($url); // return new SlackMessage()->text((string) trans('email.admin_test_subject'))->to($url);
} }
/** /**
@@ -82,8 +77,6 @@ class TestNotificationSlack extends Notification
* *
* @SuppressWarnings(PHPMD.UnusedFormalParameter) * @SuppressWarnings(PHPMD.UnusedFormalParameter)
* *
* @param OwnerNotifiable $notifiable
*
* @return array * @return array
*/ */
public function via(OwnerNotifiable $notifiable) public function via(OwnerNotifiable $notifiable)

View File

@@ -25,7 +25,6 @@ namespace FireflyIII\Providers;
use FireflyIII\Events\ActuallyLoggedIn; use FireflyIII\Events\ActuallyLoggedIn;
use FireflyIII\Events\Admin\InvitationCreated; use FireflyIII\Events\Admin\InvitationCreated;
use FireflyIII\Events\AdminRequestedTestMessage;
use FireflyIII\Events\DestroyedTransactionGroup; use FireflyIII\Events\DestroyedTransactionGroup;
use FireflyIII\Events\DetectedNewIPAddress; use FireflyIII\Events\DetectedNewIPAddress;
use FireflyIII\Events\Model\BudgetLimit\Created; use FireflyIII\Events\Model\BudgetLimit\Created;

View File

@@ -68,7 +68,8 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface
$q3->where('budget_limits.start_date', '>=', $start->format('Y-m-d')); $q3->where('budget_limits.start_date', '>=', $start->format('Y-m-d'));
$q3->where('budget_limits.start_date', '<=', $end->format('Y-m-d')); $q3->where('budget_limits.start_date', '<=', $end->format('Y-m-d'));
} }
); )
;
} }
) )
->orWhere( ->orWhere(
@@ -77,13 +78,15 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface
$q4->where('budget_limits.start_date', '<=', $start->format('Y-m-d')); $q4->where('budget_limits.start_date', '<=', $start->format('Y-m-d'));
$q4->where('budget_limits.end_date', '>=', $end->format('Y-m-d')); $q4->where('budget_limits.end_date', '>=', $end->format('Y-m-d'));
} }
); )
;
} }
) )
->where('budget_limits.transaction_currency_id', $currency->id) ->where('budget_limits.transaction_currency_id', $currency->id)
->whereNull('budgets.deleted_at') ->whereNull('budgets.deleted_at')
->where('budgets.active', true) ->where('budgets.active', true)
->where('budgets.user_id', $this->user->id); ->where('budgets.user_id', $this->user->id)
;
if (null !== $budgets && $budgets->count() > 0) { if (null !== $budgets && $budgets->count() > 0) {
$query->whereIn('budget_limits.budget_id', $budgets->pluck('id')->toArray()); $query->whereIn('budget_limits.budget_id', $budgets->pluck('id')->toArray());
} }
@@ -138,14 +141,16 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface
->with(['budget']) ->with(['budget'])
->where('budgets.user_id', $this->user->id) ->where('budgets.user_id', $this->user->id)
->whereNull('budgets.deleted_at') ->whereNull('budgets.deleted_at')
->get(['budget_limits.*']); ->get(['budget_limits.*'])
;
} }
// one of the two is NULL. // one of the two is NULL.
if (null === $start xor null === $end) { if (null === $start xor null === $end) {
$query = BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id') $query = BudgetLimit::leftJoin('budgets', 'budgets.id', '=', 'budget_limits.budget_id')
->with(['budget']) ->with(['budget'])
->whereNull('budgets.deleted_at') ->whereNull('budgets.deleted_at')
->where('budgets.user_id', $this->user->id); ->where('budgets.user_id', $this->user->id)
;
if (null !== $end) { if (null !== $end) {
// end date must be before $end. // end date must be before $end.
$query->where('end_date', '<=', $end->format('Y-m-d 00:00:00')); $query->where('end_date', '<=', $end->format('Y-m-d 00:00:00'));
@@ -178,7 +183,8 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface
$q3->where('budget_limits.start_date', '>=', $start->format('Y-m-d')); $q3->where('budget_limits.start_date', '>=', $start->format('Y-m-d'));
$q3->where('budget_limits.start_date', '<=', $end->format('Y-m-d')); $q3->where('budget_limits.start_date', '<=', $end->format('Y-m-d'));
} }
); )
;
} }
) )
->orWhere( ->orWhere(
@@ -187,9 +193,11 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface
$q4->where('budget_limits.start_date', '<=', $start->format('Y-m-d')); $q4->where('budget_limits.start_date', '<=', $start->format('Y-m-d'));
$q4->where('budget_limits.end_date', '>=', $end->format('Y-m-d')); $q4->where('budget_limits.end_date', '>=', $end->format('Y-m-d'));
} }
); )
;
} }
)->get(['budget_limits.*']); )->get(['budget_limits.*'])
;
} }
public function getBudgetLimits(Budget $budget, ?Carbon $start = null, ?Carbon $end = null): Collection public function getBudgetLimits(Budget $budget, ?Carbon $start = null, ?Carbon $end = null): Collection
@@ -231,7 +239,8 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface
$q3->where('budget_limits.start_date', '>=', $start->format('Y-m-d 00:00:00')); $q3->where('budget_limits.start_date', '>=', $start->format('Y-m-d 00:00:00'));
$q3->where('budget_limits.start_date', '<=', $end->format('Y-m-d 23:59:59')); $q3->where('budget_limits.start_date', '<=', $end->format('Y-m-d 23:59:59'));
} }
); )
;
} }
) )
->orWhere( ->orWhere(
@@ -240,12 +249,14 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface
$q4->where('budget_limits.start_date', '<=', $start->format('Y-m-d 23:59:59')); $q4->where('budget_limits.start_date', '<=', $start->format('Y-m-d 23:59:59'));
$q4->where('budget_limits.end_date', '>=', $end->format('Y-m-d 00:00:00')); $q4->where('budget_limits.end_date', '>=', $end->format('Y-m-d 00:00:00'));
} }
); )
;
} }
)->orderBy('budget_limits.start_date', 'DESC')->get(['budget_limits.*']); )->orderBy('budget_limits.start_date', 'DESC')->get(['budget_limits.*'])
;
} }
public function setUser(null | Authenticatable | User $user): void public function setUser(null|Authenticatable|User $user): void
{ {
if ($user instanceof User) { if ($user instanceof User) {
$this->user = $user; $this->user = $user;
@@ -278,7 +289,8 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface
->where('budget_limits.start_date', $data['start_date']->format('Y-m-d')) ->where('budget_limits.start_date', $data['start_date']->format('Y-m-d'))
->where('budget_limits.end_date', $data['end_date']->format('Y-m-d')) ->where('budget_limits.end_date', $data['end_date']->format('Y-m-d'))
->where('budget_limits.transaction_currency_id', $currency->id) ->where('budget_limits.transaction_currency_id', $currency->id)
->first(['budget_limits.*']); ->first(['budget_limits.*'])
;
if (null !== $limit) { if (null !== $limit) {
throw new FireflyException('200027: Budget limit already exists.'); throw new FireflyException('200027: Budget limit already exists.');
} }
@@ -303,13 +315,13 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface
return $limit; return $limit;
} }
public function find(Budget $budget, TransactionCurrency $currency, Carbon $start, Carbon $end): ?BudgetLimit public function find(Budget $budget, TransactionCurrency $currency, Carbon $start, Carbon $end): ?BudgetLimit
{ {
return $budget->budgetlimits() return $budget->budgetlimits()
->where('transaction_currency_id', $currency->id) ->where('transaction_currency_id', $currency->id)
->where('start_date', $start->format('Y-m-d')) ->where('start_date', $start->format('Y-m-d'))
->where('end_date', $end->format('Y-m-d'))->first(); ->where('end_date', $end->format('Y-m-d'))->first()
;
} }
/** /**
@@ -349,7 +361,7 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface
$budgetLimit->save(); $budgetLimit->save();
// update notes if they exist. // update notes if they exist.
if(array_key_exists('notes', $data)) { if (array_key_exists('notes', $data)) {
$this->setNoteText($budgetLimit, (string)$data['notes']); $this->setNoteText($budgetLimit, (string)$data['notes']);
} }
@@ -362,7 +374,8 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface
$limits = $budget->budgetlimits() $limits = $budget->budgetlimits()
->where('budget_limits.start_date', $start->format('Y-m-d 00:00:00')) ->where('budget_limits.start_date', $start->format('Y-m-d 00:00:00'))
->where('budget_limits.end_date', $end->format('Y-m-d 00:00:00')) ->where('budget_limits.end_date', $end->format('Y-m-d 00:00:00'))
->count('budget_limits.*'); ->count('budget_limits.*')
;
app('log')->debug(sprintf('Found %d budget limits.', $limits)); app('log')->debug(sprintf('Found %d budget limits.', $limits));
// there might be a budget limit for these dates: // there might be a budget limit for these dates:
@@ -370,7 +383,8 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface
$limit = $budget->budgetlimits() $limit = $budget->budgetlimits()
->where('budget_limits.start_date', $start->format('Y-m-d 00:00:00')) ->where('budget_limits.start_date', $start->format('Y-m-d 00:00:00'))
->where('budget_limits.end_date', $end->format('Y-m-d 00:00:00')) ->where('budget_limits.end_date', $end->format('Y-m-d 00:00:00'))
->first(['budget_limits.*']); ->first(['budget_limits.*'])
;
// if more than 1 limit found, delete the others: // if more than 1 limit found, delete the others:
if ($limits > 1 && null !== $limit) { if ($limits > 1 && null !== $limit) {
@@ -378,7 +392,8 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface
$budget->budgetlimits() $budget->budgetlimits()
->where('budget_limits.start_date', $start->format('Y-m-d 00:00:00')) ->where('budget_limits.start_date', $start->format('Y-m-d 00:00:00'))
->where('budget_limits.end_date', $end->format('Y-m-d 00:00:00')) ->where('budget_limits.end_date', $end->format('Y-m-d 00:00:00'))
->where('budget_limits.id', '!=', $limit->id)->delete(); ->where('budget_limits.id', '!=', $limit->id)->delete()
;
} }
// delete if amount is zero. // delete if amount is zero.
@@ -413,12 +428,14 @@ class BudgetLimitRepository implements BudgetLimitRepositoryInterface
return $limit; return $limit;
} }
#[\Override] public function getNoteText(BudgetLimit $budgetLimit): string #[\Override]
public function getNoteText(BudgetLimit $budgetLimit): string
{ {
return (string) $budgetLimit->notes()->first()?->text; return (string) $budgetLimit->notes()->first()?->text;
} }
#[\Override] public function setNoteText(BudgetLimit $budgetLimit, string $text): void #[\Override]
public function setNoteText(BudgetLimit $budgetLimit, string $text): void
{ {
$dbNote = $budgetLimit->notes()->first(); $dbNote = $budgetLimit->notes()->first();
if ('' !== $text) { if ('' !== $text) {

View File

@@ -49,6 +49,7 @@ interface BudgetLimitRepositoryInterface
public function destroyAll(): void; public function destroyAll(): void;
public function getNoteText(BudgetLimit $budgetLimit): string; public function getNoteText(BudgetLimit $budgetLimit): string;
public function setNoteText(BudgetLimit $budgetLimit, string $text): void; public function setNoteText(BudgetLimit $budgetLimit, string $text): void;
/** /**

View File

@@ -106,7 +106,8 @@ class CurrencyRepository implements CurrencyRepositoryInterface
} }
} }
#[\Override] public function find(int $currencyId): ?TransactionCurrency #[\Override]
public function find(int $currencyId): ?TransactionCurrency
{ {
return TransactionCurrency::find($currencyId); return TransactionCurrency::find($currencyId);
} }

View File

@@ -30,11 +30,9 @@ use FireflyIII\Factory\PiggyBankFactory;
use FireflyIII\Models\Note; use FireflyIII\Models\Note;
use FireflyIII\Models\PiggyBank; use FireflyIII\Models\PiggyBank;
use FireflyIII\Models\PiggyBankRepetition; use FireflyIII\Models\PiggyBankRepetition;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\ObjectGroup\CreatesObjectGroups; use FireflyIII\Repositories\ObjectGroup\CreatesObjectGroups;
use FireflyIII\Support\Facades\Amount; use FireflyIII\Support\Facades\Amount;
use Illuminate\Database\QueryException;
/** /**
* Trait ModifiesPiggyBanks * Trait ModifiesPiggyBanks
@@ -184,10 +182,10 @@ trait ModifiesPiggyBanks
{ {
$factory = new PiggyBankFactory(); $factory = new PiggyBankFactory();
$factory->user = $this->user; $factory->user = $this->user;
return $factory->store($data); return $factory->store($data);
} }
public function setOrder(PiggyBank $piggyBank, int $newOrder): bool public function setOrder(PiggyBank $piggyBank, int $newOrder): bool
{ {
$oldOrder = $piggyBank->order; $oldOrder = $piggyBank->order;
@@ -220,7 +218,8 @@ trait ModifiesPiggyBanks
if ('' === $note) { if ('' === $note) {
$dbNote = $piggyBank->notes()->first(); $dbNote = $piggyBank->notes()->first();
$dbNote?->delete(); $dbNote?->delete();
return ;
return;
} }
$dbNote = $piggyBank->notes()->first(); $dbNote = $piggyBank->notes()->first();
if (null === $dbNote) { if (null === $dbNote) {

View File

@@ -122,12 +122,14 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
$amount = '' === $amount ? '0' : $amount; $amount = '' === $amount ? '0' : $amount;
$sum = bcadd($sum, $amount); $sum = bcadd($sum, $amount);
} }
return $sum; return $sum;
} }
public function getRepetition(PiggyBank $piggyBank): ?PiggyBankRepetition public function getRepetition(PiggyBank $piggyBank): ?PiggyBankRepetition
{ {
throw new FireflyException('[b] Piggy bank repetitions are EOL.'); throw new FireflyException('[b] Piggy bank repetitions are EOL.');
return $piggyBank->piggyBankRepetitions()->first(); return $piggyBank->piggyBankRepetitions()->first();
} }
@@ -237,14 +239,13 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
return (string) $amount; return (string) $amount;
} }
public function setUser(null | Authenticatable | User $user): void public function setUser(null|Authenticatable|User $user): void
{ {
if ($user instanceof User) { if ($user instanceof User) {
$this->user = $user; $this->user = $user;
} }
} }
/** /**
* Return note for piggy bank. * Return note for piggy bank.
*/ */
@@ -268,7 +269,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
/** @var PiggyBank $piggy */ /** @var PiggyBank $piggy */
foreach ($set as $piggy) { foreach ($set as $piggy) {
$currentAmount = $this->getRepetition($piggy)->current_amount ?? '0'; $currentAmount = $this->getRepetition($piggy)->current_amount ?? '0';
$piggy->name = $piggy->name . ' (' . app('amount')->formatAnything($currency, $currentAmount, false) . ')'; $piggy->name = $piggy->name.' ('.app('amount')->formatAnything($currency, $currentAmount, false).')';
} }
return $set; return $set;
@@ -276,8 +277,7 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
public function getPiggyBanks(): Collection public function getPiggyBanks(): Collection
{ {
return PiggyBank return PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id')
::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id')
->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id') ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id')
->where('accounts.user_id', auth()->user()->id) ->where('accounts.user_id', auth()->user()->id)
->with( ->with(
@@ -286,7 +286,8 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
'objectGroups', 'objectGroups',
] ]
) )
->orderBy('piggy_banks.order', 'ASC')->get(['piggy_banks.*']); ->orderBy('piggy_banks.order', 'ASC')->get(['piggy_banks.*'])
;
} }
/** /**
@@ -344,17 +345,20 @@ class PiggyBankRepository implements PiggyBankRepositoryInterface
$search->whereLike('piggy_banks.name', sprintf('%%%s%%', $query)); $search->whereLike('piggy_banks.name', sprintf('%%%s%%', $query));
} }
$search->orderBy('piggy_banks.order', 'ASC') $search->orderBy('piggy_banks.order', 'ASC')
->orderBy('piggy_banks.name', 'ASC'); ->orderBy('piggy_banks.name', 'ASC')
;
return $search->take($limit)->get(); return $search->take($limit)->get();
} }
#[\Override] public function purgeAll(): void #[\Override]
public function purgeAll(): void
{ {
throw new FireflyException('TODO Not implemented'); throw new FireflyException('TODO Not implemented');
} }
#[\Override] public function resetOrder(): void #[\Override]
public function resetOrder(): void
{ {
$factory = new PiggyBankFactory(); $factory = new PiggyBankFactory();
$factory->user = $this->user; $factory->user = $this->user;

View File

@@ -129,7 +129,7 @@ interface PiggyBankRepositoryInterface
*/ */
public function setOrder(PiggyBank $piggyBank, int $newOrder): bool; public function setOrder(PiggyBank $piggyBank, int $newOrder): bool;
public function setUser(null | Authenticatable | User $user): void; public function setUser(null|Authenticatable|User $user): void;
/** /**
* Store new piggy bank. * Store new piggy bank.

View File

@@ -18,11 +18,11 @@ class IsValidDiscordUrl implements ValidationRule
public function validate(string $attribute, mixed $value, \Closure $fail): void public function validate(string $attribute, mixed $value, \Closure $fail): void
{ {
$value = (string)$value; $value = (string)$value;
if('' === $value) { if ('' === $value) {
return; return;
} }
if(!str_starts_with($value, 'https://discord.com/api/webhooks/')) { if (!str_starts_with($value, 'https://discord.com/api/webhooks/')) {
$fail('validation.active_url')->translate(); $fail('validation.active_url')->translate();
$message = sprintf('IsValidDiscordUrl: "%s" is not a discord URL.', substr($value, 0, 255)); $message = sprintf('IsValidDiscordUrl: "%s" is not a discord URL.', substr($value, 0, 255));
Log::debug($message); Log::debug($message);

View File

@@ -18,11 +18,11 @@ class IsValidSlackOrDiscordUrl implements ValidationRule
public function validate(string $attribute, mixed $value, \Closure $fail): void public function validate(string $attribute, mixed $value, \Closure $fail): void
{ {
$value = (string)$value; $value = (string)$value;
if('' === $value) { if ('' === $value) {
return; return;
} }
if(!str_starts_with($value, 'https://hooks.slack.com/services/') && !str_starts_with($value, 'https://discord.com/api/webhooks/')) { if (!str_starts_with($value, 'https://hooks.slack.com/services/') && !str_starts_with($value, 'https://discord.com/api/webhooks/')) {
$fail('validation.active_url')->translate(); $fail('validation.active_url')->translate();
$message = sprintf('IsValidSlackUrl: "%s" is not a discord or slack URL.', substr($value, 0, 255)); $message = sprintf('IsValidSlackUrl: "%s" is not a discord or slack URL.', substr($value, 0, 255));
Log::debug($message); Log::debug($message);

View File

@@ -18,11 +18,11 @@ class IsValidSlackUrl implements ValidationRule
public function validate(string $attribute, mixed $value, \Closure $fail): void public function validate(string $attribute, mixed $value, \Closure $fail): void
{ {
$value = (string)$value; $value = (string)$value;
if('' === $value) { if ('' === $value) {
return; return;
} }
if(!str_starts_with($value, 'https://hooks.slack.com/services/')) { if (!str_starts_with($value, 'https://hooks.slack.com/services/')) {
$fail('validation.active_url')->translate(); $fail('validation.active_url')->translate();
$message = sprintf('IsValidSlackUrl: "%s" is not a slack URL.', substr($value, 0, 255)); $message = sprintf('IsValidSlackUrl: "%s" is not a slack URL.', substr($value, 0, 255));
Log::debug($message); Log::debug($message);

View File

@@ -289,6 +289,7 @@ class ExpandedForm
return $html; return $html;
} }
/** /**
* @throws FireflyException * @throws FireflyException
*/ */
@@ -299,7 +300,7 @@ 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', compact('classes', 'value', 'name', 'label', 'options'))->render();
} catch (\Throwable $e) { } catch (\Throwable $e) {
app('log')->debug(sprintf('Could not render passwordWithValue(): %s', $e->getMessage())); app('log')->debug(sprintf('Could not render passwordWithValue(): %s', $e->getMessage()));
$html = 'Could not render passwordWithValue.'; $html = 'Could not render passwordWithValue.';

View File

@@ -37,7 +37,7 @@ class FireflyConfig
{ {
public function delete(string $name): void public function delete(string $name): void
{ {
$fullName = 'ff-config-' . $name; $fullName = 'ff-config-'.$name;
if (\Cache::has($fullName)) { if (\Cache::has($fullName)) {
\Cache::forget($fullName); \Cache::forget($fullName);
} }
@@ -57,14 +57,18 @@ class FireflyConfig
} }
if ('' === $result->data) { if ('' === $result->data) {
Log::warning(sprintf('Empty encrypted configuration value found: "%s"', $name)); Log::warning(sprintf('Empty encrypted configuration value found: "%s"', $name));
return $result; return $result;
} }
try { try {
$result->data = decrypt($result->data); $result->data = decrypt($result->data);
} catch (DecryptException $e) { } catch (DecryptException $e) {
Log::error(sprintf('Could not decrypt configuration value "%s": %s', $name, $e->getMessage())); Log::error(sprintf('Could not decrypt configuration value "%s": %s', $name, $e->getMessage()));
return $result; return $result;
} }
return $result; return $result;
} }
@@ -75,7 +79,7 @@ class FireflyConfig
*/ */
public function get(string $name, $default = null): ?Configuration public function get(string $name, $default = null): ?Configuration
{ {
$fullName = 'ff-config-' . $name; $fullName = 'ff-config-'.$name;
if (\Cache::has($fullName)) { if (\Cache::has($fullName)) {
return \Cache::get($fullName); return \Cache::get($fullName);
} }
@@ -83,7 +87,7 @@ class FireflyConfig
try { try {
/** @var null|Configuration $config */ /** @var null|Configuration $config */
$config = Configuration::where('name', $name)->first(['id', 'name', 'data']); $config = Configuration::where('name', $name)->first(['id', 'name', 'data']);
} catch (\Exception | QueryException $e) { } catch (\Exception|QueryException $e) {
throw new FireflyException(sprintf('Could not poll the database: %s', $e->getMessage()), 0, $e); throw new FireflyException(sprintf('Could not poll the database: %s', $e->getMessage()), 0, $e);
} }
@@ -106,8 +110,10 @@ class FireflyConfig
$encrypted = encrypt($value); $encrypted = encrypt($value);
} catch (EncryptException $e) { } catch (EncryptException $e) {
Log::error(sprintf('Could not encrypt configuration value "%s": %s', $name, $e->getMessage())); Log::error(sprintf('Could not encrypt configuration value "%s": %s', $name, $e->getMessage()));
throw new FireflyException(sprintf('Could not encrypt configuration value "%s". Cowardly refuse to continue.', $name)); throw new FireflyException(sprintf('Could not encrypt configuration value "%s". Cowardly refuse to continue.', $name));
} }
return $this->set($name, $encrypted); return $this->set($name, $encrypted);
} }
@@ -129,13 +135,13 @@ class FireflyConfig
$item->name = $name; $item->name = $name;
$item->data = $value; $item->data = $value;
$item->save(); $item->save();
\Cache::forget('ff-config-' . $name); \Cache::forget('ff-config-'.$name);
return $item; return $item;
} }
$config->data = $value; $config->data = $value;
$config->save(); $config->save();
\Cache::forget('ff-config-' . $name); \Cache::forget('ff-config-'.$name);
return $config; return $config;
} }

View File

@@ -155,8 +155,9 @@ class AccountForm
*/ */
public function assetLiabilityMultiAccountList(string $name, $value = null, ?array $options = null): string public function assetLiabilityMultiAccountList(string $name, $value = null, ?array $options = null): string
{ {
$types = [AccountTypeEnum::ASSET->value, AccountTypeEnum::DEFAULT->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::DEBT->value,AccountTypeEnum::LOAN->value]; $types = [AccountTypeEnum::ASSET->value, AccountTypeEnum::DEFAULT->value, AccountTypeEnum::MORTGAGE->value, AccountTypeEnum::DEBT->value, AccountTypeEnum::LOAN->value];
$grouped = $this->getAccountsGrouped($types); $grouped = $this->getAccountsGrouped($types);
return $this->multiSelect($name, $grouped, $value, $options); return $this->multiSelect($name, $grouped, $value, $options);
} }

View File

@@ -64,14 +64,18 @@ class Preferences
} }
if ('' === $result->data) { if ('' === $result->data) {
Log::warning(sprintf('Empty encrypted preference found: "%s"', $name)); Log::warning(sprintf('Empty encrypted preference found: "%s"', $name));
return $result; return $result;
} }
try { try {
$result->data = decrypt($result->data); $result->data = decrypt($result->data);
} catch (DecryptException $e) { } catch (DecryptException $e) {
Log::error(sprintf('Could not decrypt preference "%s": %s', $name, $e->getMessage())); Log::error(sprintf('Could not decrypt preference "%s": %s', $name, $e->getMessage()));
return $result; return $result;
} }
return $result; return $result;
} }
@@ -81,12 +85,13 @@ class Preferences
$encrypted = encrypt($value); $encrypted = encrypt($value);
} catch (EncryptException $e) { } catch (EncryptException $e) {
Log::error(sprintf('Could not encrypt preference "%s": %s', $name, $e->getMessage())); Log::error(sprintf('Could not encrypt preference "%s": %s', $name, $e->getMessage()));
throw new FireflyException(sprintf('Could not encrypt preference "%s". Cowardly refuse to continue.', $name)); throw new FireflyException(sprintf('Could not encrypt preference "%s". Cowardly refuse to continue.', $name));
} }
return $this->set($name, $encrypted); return $this->set($name, $encrypted);
} }
public function get(string $name, null|array|bool|int|string $default = null): ?Preference public function get(string $name, null|array|bool|int|string $default = null): ?Preference
{ {
/** @var null|User $user */ /** @var null|User $user */

View File

@@ -103,7 +103,7 @@ class BudgetLimitTransformer extends AbstractTransformer
'links' => [ 'links' => [
[ [
'rel' => 'self', 'rel' => 'self',
'uri' => '/budgets/limits/' . $budgetLimit->id, 'uri' => '/budgets/limits/'.$budgetLimit->id,
], ],
], ],
]; ];

View File

@@ -100,8 +100,8 @@ class PiggyBankTransformer extends AbstractTransformer
'created_at' => $piggyBank->created_at->toAtomString(), 'created_at' => $piggyBank->created_at->toAtomString(),
'updated_at' => $piggyBank->updated_at->toAtomString(), 'updated_at' => $piggyBank->updated_at->toAtomString(),
'accounts' => $this->renderAccounts($piggyBank), 'accounts' => $this->renderAccounts($piggyBank),
//'account_id' => (string)$piggyBank->account_id, // 'account_id' => (string)$piggyBank->account_id,
//'account_name' => $piggyBank->account->name, // 'account_name' => $piggyBank->account->name,
'name' => $piggyBank->name, 'name' => $piggyBank->name,
'currency_id' => (string) $currency->id, 'currency_id' => (string) $currency->id,
'currency_code' => $currency->code, 'currency_code' => $currency->code,
@@ -123,7 +123,7 @@ class PiggyBankTransformer extends AbstractTransformer
'links' => [ 'links' => [
[ [
'rel' => 'self', 'rel' => 'self',
'uri' => '/piggy_banks/' . $piggyBank->id, 'uri' => '/piggy_banks/'.$piggyBank->id,
], ],
], ],
]; ];
@@ -140,6 +140,7 @@ class PiggyBankTransformer extends AbstractTransformer
// TODO add balance, add left to save. // TODO add balance, add left to save.
]; ];
} }
return $return; return $return;
} }
} }

View File

@@ -115,6 +115,7 @@ class PiggyBankTransformer extends AbstractTransformer
// grab repetitions (for current amount): // grab repetitions (for current amount):
$repetitions = PiggyBankRepetition::whereIn('piggy_bank_id', $piggyBanks)->get(); $repetitions = PiggyBankRepetition::whereIn('piggy_bank_id', $piggyBanks)->get();
throw new FireflyException('[d] Piggy bank repetitions are EOL.'); throw new FireflyException('[d] Piggy bank repetitions are EOL.');
/** @var PiggyBankRepetition $repetition */ /** @var PiggyBankRepetition $repetition */

View File

@@ -49,10 +49,8 @@ use FireflyIII\Models\TransactionJournal;
use FireflyIII\Models\UserGroup; use FireflyIII\Models\UserGroup;
use FireflyIII\Models\UserRole; use FireflyIII\Models\UserRole;
use FireflyIII\Models\Webhook; use FireflyIII\Models\Webhook;
use FireflyIII\Notifications\Admin\UserInvitation;
use FireflyIII\Notifications\Admin\UserRegistration; use FireflyIII\Notifications\Admin\UserRegistration;
use FireflyIII\Notifications\Admin\VersionCheckResult; use FireflyIII\Notifications\Admin\VersionCheckResult;
use FireflyIII\Notifications\Test\TestNotificationDiscord;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasMany;
@@ -357,7 +355,7 @@ class User extends Authenticatable
*/ */
public function routeNotificationFor($driver, $notification = null) public function routeNotificationFor($driver, $notification = null)
{ {
$method = 'routeNotificationFor' . Str::studly($driver); $method = 'routeNotificationFor'.Str::studly($driver);
if (method_exists($this, $method)) { if (method_exists($this, $method)) {
return $this->{$method}($notification); // @phpstan-ignore-line return $this->{$method}($notification); // @phpstan-ignore-line
} }
@@ -400,18 +398,18 @@ class User extends Authenticatable
$appToken = (string) app('fireflyconfig')->getEncrypted('pushover_app_token', '')->data; $appToken = (string) app('fireflyconfig')->getEncrypted('pushover_app_token', '')->data;
$userToken = (string) app('fireflyconfig')->getEncrypted('pushover_user_token', '')->data; $userToken = (string) app('fireflyconfig')->getEncrypted('pushover_user_token', '')->data;
if (property_exists($notification, 'type') && $notification->type === 'owner') { if (property_exists($notification, 'type') && 'owner' === $notification->type) {
return PushoverReceiver::withUserKey($userToken) return PushoverReceiver::withUserKey($userToken)
->withApplicationToken($appToken); ->withApplicationToken($appToken)
;
} }
throw new FireflyException('No pushover token found.'); throw new FireflyException('No pushover token found.');
// return PushoverReceiver::withUserKey((string) config('services.pushover.user_token')) // return PushoverReceiver::withUserKey((string) config('services.pushover.user_token'))
// ->withApplicationToken((string) config('services.pushover.token')); // ->withApplicationToken((string) config('services.pushover.token'));
//return (string) config('services.pushover.token'); // return (string) config('services.pushover.token');
} }
/** /**
* Route notifications for the Slack channel. * Route notifications for the Slack channel.
*/ */
@@ -424,7 +422,7 @@ class User extends Authenticatable
} }
$res = (string) $res; $res = (string) $res;
if (property_exists($notification, 'type') && $notification->type === 'owner') { if (property_exists($notification, 'type') && 'owner' === $notification->type) {
return $res; return $res;
} }

View File

@@ -813,14 +813,15 @@ class FireflyValidator extends Validator
public function validateUniquePiggyBankForUser($attribute, $value, $parameters): bool public function validateUniquePiggyBankForUser($attribute, $value, $parameters): bool
{ {
$exclude = $parameters[0] ?? null; $exclude = $parameters[0] ?? null;
$query = PiggyBank $query = PiggyBank::leftJoin('account_piggy_bank', 'account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id')
::leftJoin('account_piggy_bank','account_piggy_bank.piggy_bank_id', '=', 'piggy_banks.id')
->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id') ->leftJoin('accounts', 'accounts.id', '=', 'account_piggy_bank.account_id')
->where('accounts.user_id', auth()->user()->id); ->where('accounts.user_id', auth()->user()->id)
;
if (null !== $exclude) { if (null !== $exclude) {
$query->where('piggy_banks.id', '!=', (int) $exclude); $query->where('piggy_banks.id', '!=', (int) $exclude);
} }
$query->where('piggy_banks.name', $value); $query->where('piggy_banks.name', $value);
return 0 === $query->get(['piggy_banks.*'])->count(); return 0 === $query->get(['piggy_banks.*'])->count();
} }

View File

@@ -1,4 +1,5 @@
<?php <?php
/* /*
* notifications.php * notifications.php
* Copyright (c) 2024 james@firefly-iii.org. * Copyright (c) 2024 james@firefly-iii.org.
@@ -20,14 +21,15 @@
*/ */
declare(strict_types=1); declare(strict_types=1);
return [ return [
'channels' => [ 'channels' => [
'email' => ['enabled' => true, 'ui_configurable' => 0,], 'email' => ['enabled' => true, 'ui_configurable' => 0],
'slack' => ['enabled' => true, 'ui_configurable' => 1,], 'slack' => ['enabled' => true, 'ui_configurable' => 1],
'ntfy' => ['enabled' => true, 'ui_configurable' => 1,], 'ntfy' => ['enabled' => true, 'ui_configurable' => 1],
'pushover' => ['enabled' => true, 'ui_configurable' => 1,], 'pushover' => ['enabled' => true, 'ui_configurable' => 1],
'gotify' => ['enabled' => false, 'ui_configurable' => 0,], 'gotify' => ['enabled' => false, 'ui_configurable' => 0],
'pushbullet' => ['enabled' => false, 'ui_configurable' => 0,], 'pushbullet' => ['enabled' => false, 'ui_configurable' => 0],
], ],
'notifications' => [ 'notifications' => [
'user' => [ 'user' => [
@@ -49,7 +51,7 @@ return [
'new_backup_codes' => ['enabled' => true, 'configurable' => false], 'new_backup_codes' => ['enabled' => true, 'configurable' => false],
], ],
'owner' => [ 'owner' => [
//'invitation_created' => ['enabled' => true], // 'invitation_created' => ['enabled' => true],
// 'some_notification' => ['enabled' => true], // 'some_notification' => ['enabled' => true],
'admin_new_reg' => ['enabled' => true], 'admin_new_reg' => ['enabled' => true],
'user_new_reg' => ['enabled' => true], 'user_new_reg' => ['enabled' => true],

View File

@@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
// config for Wijourdil/NtfyNotificationChannel // config for Wijourdil/NtfyNotificationChannel
return [ return [

View File

@@ -1,31 +1,32 @@
<?php <?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Schema;
return new class extends Migration return new class () extends Migration {
{
/** /**
* Run the migrations. * Run the migrations.
*/ */
public function up(): void public function up(): void
{ {
// make account_id nullable and the relation also nullable. // make account_id nullable and the relation also nullable.
Schema::table('piggy_banks', static function (Blueprint $table) { Schema::table('piggy_banks', static function (Blueprint $table): void {
// 1. drop index // 1. drop index
$table->dropForeign('piggy_banks_account_id_foreign'); $table->dropForeign('piggy_banks_account_id_foreign');
}); });
Schema::table('piggy_banks', static function (Blueprint $table) { Schema::table('piggy_banks', static function (Blueprint $table): void {
// 2. make column nullable. // 2. make column nullable.
$table->unsignedInteger('account_id')->nullable()->change(); $table->unsignedInteger('account_id')->nullable()->change();
}); });
Schema::table('piggy_banks', static function (Blueprint $table) { Schema::table('piggy_banks', static function (Blueprint $table): void {
// 3. add currency // 3. add currency
$table->integer('transaction_currency_id', false, true)->after('account_id'); $table->integer('transaction_currency_id', false, true)->after('account_id');
$table->foreign('transaction_currency_id','unique_currency')->references('id')->on('transaction_currencies')->onDelete('cascade'); $table->foreign('transaction_currency_id', 'unique_currency')->references('id')->on('transaction_currencies')->onDelete('cascade');
}); });
Schema::table('piggy_banks', static function (Blueprint $table) { Schema::table('piggy_banks', static function (Blueprint $table): void {
// 4. rename columns // 4. rename columns
$table->renameColumn('targetamount', 'target_amount'); $table->renameColumn('targetamount', 'target_amount');
$table->renameColumn('startdate', 'start_date'); $table->renameColumn('startdate', 'start_date');
@@ -33,13 +34,13 @@ return new class extends Migration
$table->renameColumn('startdate_tz', 'start_date_tz'); $table->renameColumn('startdate_tz', 'start_date_tz');
$table->renameColumn('targetdate_tz', 'target_date_tz'); $table->renameColumn('targetdate_tz', 'target_date_tz');
}); });
Schema::table('piggy_banks', static function (Blueprint $table) { Schema::table('piggy_banks', static function (Blueprint $table): void {
// 5. add new index // 5. add new index
$table->foreign('account_id')->references('id')->on('accounts')->onDelete('set null'); $table->foreign('account_id')->references('id')->on('accounts')->onDelete('set null');
}); });
// rename some fields in piggy bank reps. // rename some fields in piggy bank reps.
Schema::table('piggy_bank_repetitions', static function (Blueprint $table) { Schema::table('piggy_bank_repetitions', static function (Blueprint $table): void {
// 6. rename columns // 6. rename columns
$table->renameColumn('currentamount', 'current_amount'); $table->renameColumn('currentamount', 'current_amount');
$table->renameColumn('startdate', 'start_date'); $table->renameColumn('startdate', 'start_date');
@@ -49,14 +50,14 @@ return new class extends Migration
}); });
// create table account_piggy_bank // create table account_piggy_bank
Schema::create('account_piggy_bank', static function (Blueprint $table) { Schema::create('account_piggy_bank', static function (Blueprint $table): void {
$table->id(); $table->id();
$table->integer('account_id', false, true); $table->integer('account_id', false, true);
$table->integer('piggy_bank_id',false, true); $table->integer('piggy_bank_id', false, true);
$table->decimal('current_amount', 32, 12)->default('0'); $table->decimal('current_amount', 32, 12)->default('0');
$table->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade'); $table->foreign('account_id')->references('id')->on('accounts')->onDelete('cascade');
$table->foreign('piggy_bank_id')->references('id')->on('piggy_banks')->onDelete('cascade'); $table->foreign('piggy_bank_id')->references('id')->on('piggy_banks')->onDelete('cascade');
$table->unique(['account_id', 'piggy_bank_id'],'unique_piggy_save'); $table->unique(['account_id', 'piggy_bank_id'], 'unique_piggy_save');
}); });
} }
@@ -66,7 +67,7 @@ return new class extends Migration
*/ */
public function down(): void public function down(): void
{ {
Schema::table('piggy_banks', static function (Blueprint $table) { Schema::table('piggy_banks', static function (Blueprint $table): void {
// 1. drop account index again. // 1. drop account index again.
$table->dropForeign('piggy_banks_account_id_foreign'); $table->dropForeign('piggy_banks_account_id_foreign');
@@ -89,7 +90,7 @@ return new class extends Migration
}); });
// rename some fields in piggy bank reps. // rename some fields in piggy bank reps.
Schema::table('piggy_bank_repetitions', static function (Blueprint $table) { Schema::table('piggy_bank_repetitions', static function (Blueprint $table): void {
// 6. rename columns // 6. rename columns
$table->renameColumn('current_amount', 'currentamount'); $table->renameColumn('current_amount', 'currentamount');
$table->renameColumn('start_date', 'startdate'); $table->renameColumn('start_date', 'startdate');