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

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

View File

@@ -1,4 +1,5 @@
<?php
/*
* NotificationController.php
* Copyright (c) 2024 james@firefly-iii.org.
@@ -36,25 +37,25 @@ class NotificationController extends Controller
public function index()
{
Log::channel('audit')->info('User visits notifications index.');
$title = (string) trans('firefly.administration');
$mainTitleIcon = 'fa-hand-spock-o';
$subTitle = (string) trans('firefly.title_owner_notifications');
$subTitleIcon = 'envelope-o';
$title = (string) trans('firefly.administration');
$mainTitleIcon = 'fa-hand-spock-o';
$subTitle = (string) trans('firefly.title_owner_notifications');
$subTitleIcon = 'envelope-o';
// notification settings:
$slackUrl = app('fireflyconfig')->getEncrypted('slack_webhook_url', '')->data;
$pushoverAppToken = app('fireflyconfig')->getEncrypted('pushover_app_token', '')->data;
$pushoverUserToken = app('fireflyconfig')->getEncrypted('pushover_user_token', '')->data;
$ntfyServer = app('fireflyconfig')->getEncrypted('ntfy_server', 'https://ntfy.sh')->data;
$ntfyTopic = app('fireflyconfig')->getEncrypted('ntfy_topic', '')->data;
$ntfyAuth = app('fireflyconfig')->get('ntfy_auth', false)->data;
$ntfyUser = app('fireflyconfig')->getEncrypted('ntfy_user', '')->data;
$ntfyPass = app('fireflyconfig')->getEncrypted('ntfy_pass', '')->data;
$channels = config('notifications.channels');
$forcedAvailability = [];
$slackUrl = app('fireflyconfig')->getEncrypted('slack_webhook_url', '')->data;
$pushoverAppToken = app('fireflyconfig')->getEncrypted('pushover_app_token', '')->data;
$pushoverUserToken = app('fireflyconfig')->getEncrypted('pushover_user_token', '')->data;
$ntfyServer = app('fireflyconfig')->getEncrypted('ntfy_server', 'https://ntfy.sh')->data;
$ntfyTopic = app('fireflyconfig')->getEncrypted('ntfy_topic', '')->data;
$ntfyAuth = app('fireflyconfig')->get('ntfy_auth', false)->data;
$ntfyUser = app('fireflyconfig')->getEncrypted('ntfy_user', '')->data;
$ntfyPass = app('fireflyconfig')->getEncrypted('ntfy_pass', '')->data;
$channels = config('notifications.channels');
$forcedAvailability = [];
// admin notification settings:
$notifications = [];
$notifications = [];
foreach (config('notifications.notifications.owner') as $key => $info) {
if ($info['enabled']) {
$notifications[$key] = app('fireflyconfig')->get(sprintf('notification_%s', $key), true)->data;
@@ -68,18 +69,31 @@ class NotificationController extends Controller
$forcedAvailability['ntfy'] = '' !== $ntfyTopic;
$forcedAvailability['pushover'] = '' !== $pushoverAppToken && '' !== $pushoverUserToken;
return view('admin.notifications.index',
compact(
'title', 'subTitle', 'forcedAvailability', 'mainTitleIcon', 'subTitleIcon', 'channels',
'slackUrl', 'notifications',
'pushoverAppToken', 'pushoverUserToken',
'ntfyServer', 'ntfyTopic', 'ntfyAuth', 'ntfyUser', 'ntfyPass'
));
return view(
'admin.notifications.index',
compact(
'title',
'subTitle',
'forcedAvailability',
'mainTitleIcon',
'subTitleIcon',
'channels',
'slackUrl',
'notifications',
'pushoverAppToken',
'pushoverUserToken',
'ntfyServer',
'ntfyTopic',
'ntfyAuth',
'ntfyUser',
'ntfyPass'
)
);
}
public function postIndex(NotificationRequest $request): RedirectResponse
{
$all = $request->getAll();
$all = $request->getAll();
foreach (config('notifications.notifications.owner') as $key => $info) {
if (array_key_exists($key, $all)) {
@@ -112,7 +126,9 @@ class NotificationController extends Controller
switch ($channel) {
default:
session()->flash('error', (string) trans('firefly.notification_test_failed', ['channel' => $channel]));
break;
case 'email':
case 'slack':
case 'pushover':

View File

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

View File

@@ -95,7 +95,7 @@ class RegisterController extends Controller
$this->validator($request->all())->validate();
$user = $this->createUser($request->all());
app('log')->info(sprintf('Registered new user %s', $user->email));
$owner = new OwnerNotifiable();
$owner = new OwnerNotifiable();
event(new RegisteredUser($owner, $user));
$this->guard()->login($user);

View File

@@ -84,7 +84,7 @@ class BudgetLimitController extends Controller
$budgetLimits = $this->blRepository->getBudgetLimits($budget, $start, $end);
// remove already budgeted currencies with the same date range
$currencies = $collection->filter(
$currencies = $collection->filter(
static function (TransactionCurrency $currency) use ($budgetLimits, $start, $end) {
/** @var BudgetLimit $limit */
foreach ($budgetLimits as $limit) {
@@ -107,6 +107,7 @@ class BudgetLimitController extends Controller
public function show(BudgetLimit $budgetLimit)
{
$notes = $this->blRepository->getNoteText($budgetLimit);
return view('budgets.budget-limits.show', compact('budgetLimit', 'notes'));
}
@@ -116,6 +117,7 @@ class BudgetLimitController extends Controller
public function edit(BudgetLimit $budgetLimit)
{
$notes = $this->blRepository->getNoteText($budgetLimit);
return view('budgets.budget-limits.edit', compact('budgetLimit', 'notes'));
}
@@ -135,7 +137,7 @@ class BudgetLimitController extends Controller
*
* @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());
// first search for existing one and update it if necessary.
@@ -144,14 +146,14 @@ class BudgetLimitController extends Controller
if (null === $currency || null === $budget) {
throw new FireflyException('No valid currency or budget.');
}
$start = Carbon::createFromFormat('Y-m-d', $request->get('start'));
$end = Carbon::createFromFormat('Y-m-d', $request->get('end'));
$start = Carbon::createFromFormat('Y-m-d', $request->get('start'));
$end = Carbon::createFromFormat('Y-m-d', $request->get('end'));
if (null === $start || null === $end) {
return response()->json([]);
}
$amount = (string) $request->get('amount');
$amount = (string) $request->get('amount');
$start->startOfDay();
$end->startOfDay();
@@ -161,7 +163,7 @@ class BudgetLimitController extends Controller
app('log')->debug(sprintf('Start: %s, end: %s', $start->format('Y-m-d'), $end->format('Y-m-d')));
$limit = $this->blRepository->find($budget, $currency, $start, $end);
$limit = $this->blRepository->find($budget, $currency, $start, $end);
// sanity check on amount:
if (0 === bccomp($amount, '0')) {
@@ -195,25 +197,25 @@ class BudgetLimitController extends Controller
);
}
// parse notes, if any.
$notes = (string) $request->get('notes');
$notes = (string) $request->get('notes');
$this->blRepository->setNoteText($limit, $notes);
if ($request->expectsJson()) {
$array = $limit->toArray();
$array = $limit->toArray();
// add some extra metadata:
$spentArr = $this->opsRepository->sumExpenses($limit->start_date, $limit->end_date, null, new Collection([$budget]), $currency);
$array['spent'] = $spentArr[$currency->id]['sum'] ?? '0';
$array['left_formatted'] = app('amount')->formatAnything($limit->transactionCurrency, bcadd($array['spent'], $array['amount']));
$array['amount_formatted'] = app('amount')->formatAnything($limit->transactionCurrency, $limit['amount']);
$array['days_left'] = (string) $this->activeDaysLeft($start, $end);
$spentArr = $this->opsRepository->sumExpenses($limit->start_date, $limit->end_date, null, new Collection([$budget]), $currency);
$array['spent'] = $spentArr[$currency->id]['sum'] ?? '0';
$array['left_formatted'] = app('amount')->formatAnything($limit->transactionCurrency, bcadd($array['spent'], $array['amount']));
$array['amount_formatted'] = app('amount')->formatAnything($limit->transactionCurrency, $limit['amount']);
$array['days_left'] = (string) $this->activeDaysLeft($start, $end);
// left per day:
$array['left_per_day'] = 0 === bccomp('0', $array['days_left']) ? bcadd($array['spent'], $array['amount']) : bcdiv(bcadd($array['spent'], $array['amount']), $array['days_left']);
$array['left_per_day'] = 0 === bccomp('0', $array['days_left']) ? bcadd($array['spent'], $array['amount']) : bcdiv(bcadd($array['spent'], $array['amount']), $array['days_left']);
// left per day formatted.
$array['left_per_day_formatted'] = app('amount')->formatAnything($limit->transactionCurrency, $array['left_per_day']);
// notes:
$array['notes'] = $this->blRepository->getNoteText($limit);
$array['notes'] = $this->blRepository->getNoteText($limit);
return response()->json($array);
}
@@ -223,7 +225,7 @@ class BudgetLimitController extends Controller
public function update(Request $request, BudgetLimit $budgetLimit): JsonResponse|RedirectResponse
{
$amount = (string) $request->get('amount');
$amount = (string) $request->get('amount');
if ('' === $amount) {
$amount = '0';
}
@@ -235,7 +237,7 @@ class BudgetLimitController extends Controller
$budgetId = $budgetLimit->budget_id;
$currency = $budgetLimit->transactionCurrency;
$this->blRepository->destroyBudgetLimit($budgetLimit);
$array = [
$array = [
'budget_id' => $budgetId,
'left_formatted' => app('amount')->formatAnything($currency, '0'),
'left_per_day_formatted' => app('amount')->formatAnything($currency, '0'),
@@ -248,29 +250,29 @@ class BudgetLimitController extends Controller
if (-1 === bccomp($amount, '0')) {
$amount = bcmul($amount, '-1');
}
$notes = (string)$request->get('notes');
if(strlen($notes) > 32768) {
$notes = (string)$request->get('notes');
if (strlen($notes) > 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();
$array = $limit->toArray();
$array = $limit->toArray();
$spentArr = $this->opsRepository->sumExpenses(
$spentArr = $this->opsRepository->sumExpenses(
$limit->start_date,
$limit->end_date,
null,
new Collection([$budgetLimit->budget]),
$budgetLimit->transactionCurrency
);
$daysLeft = $this->activeDaysLeft($limit->start_date, $limit->end_date);
$array['spent'] = $spentArr[$budgetLimit->transactionCurrency->id]['sum'] ?? '0';
$array['left_formatted'] = app('amount')->formatAnything($limit->transactionCurrency, bcadd($array['spent'], $array['amount']));
$array['amount_formatted'] = app('amount')->formatAnything($limit->transactionCurrency, $limit['amount']);
$array['days_left'] = (string) $daysLeft;
$array['left_per_day'] = 0 === $daysLeft ? bcadd($array['spent'], $array['amount']) : bcdiv(bcadd($array['spent'], $array['amount']), $array['days_left']);
$daysLeft = $this->activeDaysLeft($limit->start_date, $limit->end_date);
$array['spent'] = $spentArr[$budgetLimit->transactionCurrency->id]['sum'] ?? '0';
$array['left_formatted'] = app('amount')->formatAnything($limit->transactionCurrency, bcadd($array['spent'], $array['amount']));
$array['amount_formatted'] = app('amount')->formatAnything($limit->transactionCurrency, $limit['amount']);
$array['days_left'] = (string) $daysLeft;
$array['left_per_day'] = 0 === $daysLeft ? bcadd($array['spent'], $array['amount']) : bcdiv(bcadd($array['spent'], $array['amount']), $array['days_left']);
// left per day formatted.
$array['amount'] = app('steam')->bcround($limit['amount'], $limit->transactionCurrency->decimal_places);
@@ -278,6 +280,7 @@ class BudgetLimitController extends Controller
if ('true' === $request->get('redirect')) {
return redirect(route('budgets.index'));
}
return response()->json($array);
}
}

View File

@@ -213,7 +213,7 @@ class IndexController extends Controller
$array['budgeted'][] = [
'id' => $limit->id,
'amount' => $amount,
'notes' => $this->blRepository->getNoteText($limit),
'notes' => $this->blRepository->getNoteText($limit),
'start_date' => $limit->start_date->isoFormat($this->monthAndDayFormat),
'end_date' => $limit->end_date->isoFormat($this->monthAndDayFormat),
'in_range' => $limit->start_date->isSameDay($start) && $limit->end_date->isSameDay($end),

View File

@@ -43,7 +43,6 @@ use Illuminate\Support\Facades\Log;
*/
class HomeController extends Controller
{
/**
* HomeController constructor.
*/
@@ -62,8 +61,8 @@ class HomeController extends Controller
*/
public function dateRange(Request $request): JsonResponse
{
$stringStart = '';
$stringEnd = '';
$stringStart = '';
$stringEnd = '';
try {
$stringStart = e((string) $request->get('start'));
@@ -98,7 +97,7 @@ class HomeController extends Controller
app('log')->debug('Range is now marked as "custom".');
}
$diff = $start->diffInDays($end, true) + 1;
$diff = $start->diffInDays($end, true) + 1;
if ($diff > 366) {
$request->session()->flash('warning', (string) trans('firefly.warning_much_data', ['days' => (int) $diff]));
@@ -153,13 +152,13 @@ class HomeController extends Controller
}
/** @var Carbon $start */
$start = session('start', today(config('app.timezone'))->startOfMonth());
$start = session('start', today(config('app.timezone'))->startOfMonth());
/** @var Carbon $end */
$end = session('end', today(config('app.timezone'))->endOfMonth());
$accounts = $repository->getAccountsById($frontpageArray);
$today = today(config('app.timezone'));
$accounts = $accounts->sortBy('order'); // sort frontpage accounts by order
$end = session('end', today(config('app.timezone'))->endOfMonth());
$accounts = $repository->getAccountsById($frontpageArray);
$today = today(config('app.timezone'));
$accounts = $accounts->sortBy('order'); // sort frontpage accounts by order
app('log')->debug('Frontpage accounts are ', $frontpageArray);
@@ -169,14 +168,14 @@ class HomeController extends Controller
// collect groups for each transaction.
foreach ($accounts as $account) {
/** @var GroupCollectorInterface $collector */
$collector = app(GroupCollectorInterface::class);
$collector = app(GroupCollectorInterface::class);
$collector->setAccounts(new Collection([$account]))->withAccountInformation()->setRange($start, $end)->setLimit(10)->setPage(1);
$set = $collector->getExtractedJournals();
$transactions[] = ['transactions' => $set, 'account' => $account];
}
/** @var User $user */
$user = auth()->user();
$user = auth()->user();
event(new RequestedVersionCheckStatus($user));
return view('index', compact('count', 'subTitle', 'transactions', 'billCount', 'start', 'end', 'today', 'pageTitle'));
@@ -187,11 +186,11 @@ class HomeController extends Controller
$subTitle = (string) trans('firefly.welcome_back');
$pageTitle = (string) trans('firefly.main_dashboard_page_title');
$start = session('start', today(config('app.timezone'))->startOfMonth());
$end = session('end', today(config('app.timezone'))->endOfMonth());
$start = session('start', today(config('app.timezone'))->startOfMonth());
$end = session('end', today(config('app.timezone'))->endOfMonth());
/** @var User $user */
$user = auth()->user();
$user = auth()->user();
event(new RequestedVersionCheckStatus($user));
return view('index', compact('subTitle', 'start', 'end', 'pageTitle'));

View File

@@ -94,7 +94,7 @@ class CreateController extends Controller
*/
public function store(PiggyBankStoreRequest $request)
{
$data = $request->getPiggyBankData();
$data = $request->getPiggyBankData();
if (null === $data['start_date']) {
$data['start_date'] = today(config('app.timezone'));
@@ -107,7 +107,7 @@ class CreateController extends Controller
// store attachment(s):
/** @var null|array $files */
$files = $request->hasFile('attachments') ? $request->file('attachments') : null;
$files = $request->hasFile('attachments') ? $request->file('attachments') : null;
if (null !== $files && !auth()->user()->hasRole('demo')) {
$this->attachments->saveAttachmentsForModel($piggyBank, $files);
}
@@ -119,7 +119,7 @@ class CreateController extends Controller
if (count($this->attachments->getMessages()->get('attachments')) > 0) {
$request->session()->flash('info', $this->attachments->getMessages()->get('attachments'));
}
$redirect = redirect($this->getPreviousUrl('piggy-banks.create.url'));
$redirect = redirect($this->getPreviousUrl('piggy-banks.create.url'));
if (1 === (int) $request->get('create_another')) {
session()->put('piggy-banks.create.fromStore', true);

View File

@@ -81,13 +81,13 @@ class IndexController extends Controller
{
$this->cleanupObjectGroups();
$this->piggyRepos->resetOrder();
$collection = $this->piggyRepos->getPiggyBanks();
$collection = $this->piggyRepos->getPiggyBanks();
/** @var Carbon $end */
$end = session('end', today(config('app.timezone'))->endOfMonth());
$end = session('end', today(config('app.timezone'))->endOfMonth());
// transform piggies using the transformer:
$parameters = new ParameterBag();
$parameters = new ParameterBag();
$parameters->set('end', $end);
@@ -96,10 +96,10 @@ class IndexController extends Controller
$accountTransformer->setParameters($parameters);
// data
$piggyBanks = $this->groupPiggyBanks($collection);
$accounts = $this->collectAccounts($collection);
$accounts = $this->mergeAccountsAndPiggies($piggyBanks, $accounts);
$piggyBanks = $this->makeSums($piggyBanks);
$piggyBanks = $this->groupPiggyBanks($collection);
$accounts = $this->collectAccounts($collection);
$accounts = $this->mergeAccountsAndPiggies($piggyBanks, $accounts);
$piggyBanks = $this->makeSums($piggyBanks);
ksort($piggyBanks);
@@ -112,7 +112,7 @@ class IndexController extends Controller
foreach ($piggyBanks as $groupOrder => $group) {
$groupId = $group['object_group_id'];
foreach ($group['piggy_banks'] as $piggy) {
$currencyId = $piggy['currency_id'];
$currencyId = $piggy['currency_id'];
$sums[$groupId][$currencyId] ??= [
'target' => '0',
'saved' => '0',
@@ -164,47 +164,51 @@ class IndexController extends Controller
/** @var PiggyBankTransformer $transformer */
$transformer = app(PiggyBankTransformer::class);
$transformer->setParameters(new ParameterBag());
$piggyBanks = [];
$piggyBanks = [];
/** @var PiggyBank $piggy */
foreach ($collection as $piggy) {
$array = $transformer->transform($piggy);
$groupOrder = (int) $array['object_group_order'];
$array = $transformer->transform($piggy);
$groupOrder = (int) $array['object_group_order'];
$piggyBanks[$groupOrder] ??= [
'object_group_id' => $array['object_group_id'] ?? 0,
'object_group_title' => $array['object_group_title'] ?? trans('firefly.default_group_title_name'),
'piggy_banks' => [],
];
$array['attachments'] = $this->piggyRepos->getAttachments($piggy);
$array['attachments'] = $this->piggyRepos->getAttachments($piggy);
// sum the total amount for the index.
$piggyBanks[$groupOrder]['piggy_banks'][] = $array;
}
return $piggyBanks;
}
private function collectAccounts(Collection $collection): array
{
/** @var Carbon $end */
$end = session('end', today(config('app.timezone'))->endOfMonth());
$end = session('end', today(config('app.timezone'))->endOfMonth());
// transform piggies using the transformer:
$parameters = new ParameterBag();
$parameters = new ParameterBag();
$parameters->set('end', $end);
/** @var AccountTransformer $accountTransformer */
$accountTransformer = app(AccountTransformer::class);
$accountTransformer->setParameters($parameters);
$return = [];
$return = [];
/** @var PiggyBank $piggy */
foreach ($collection as $piggy) {
$accounts = $piggy->accounts;
/** @var Account $account */
foreach ($accounts as $account) {
$array = $accountTransformer->transform($account);
$accountId = (int) $array['id'];
if (!array_key_exists($accountId, $return)) {
$return[$accountId] = $array;
$return[$accountId] = $array;
// add some interesting details:
$return[$accountId]['left'] = $return[$accountId]['current_balance'];
@@ -214,20 +218,21 @@ class IndexController extends Controller
}
// calculate new interesting fields:
// $return[$accountId]['left'] -= $array['current_amount'];
// $return[$accountId]['saved'] += $array['current_amount'];
// $return[$accountId]['target'] += $array['target_amount'];
// $return[$accountId]['to_save'] += ($array['target_amount'] - $array['current_amount']);
// $return['account_name'] = $account['name'];
// $return[$accountId]['left'] -= $array['current_amount'];
// $return[$accountId]['saved'] += $array['current_amount'];
// $return[$accountId]['target'] += $array['target_amount'];
// $return[$accountId]['to_save'] += ($array['target_amount'] - $array['current_amount']);
// $return['account_name'] = $account['name'];
}
}
return $return;
}
private function mergeAccountsAndPiggies(array $piggyBanks, array $accounts): array
{
/** @var array $piggyBank */
// @var array $piggyBank
foreach ($piggyBanks as $group) {
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.
@@ -243,6 +248,7 @@ class IndexController extends Controller
}
}
}
return $accounts;
}
}

View File

@@ -66,14 +66,14 @@ class PreferencesController extends Controller
*/
public function index(AccountRepositoryInterface $repository)
{
$accounts = $repository->getAccountsByType([AccountType::DEFAULT, AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]);
$isDocker = env('IS_DOCKER', false);
$groupedAccounts = [];
$accounts = $repository->getAccountsByType([AccountType::DEFAULT, AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]);
$isDocker = env('IS_DOCKER', false);
$groupedAccounts = [];
/** @var Account $account */
foreach ($accounts as $account) {
$type = $account->accountType->type;
$role = sprintf('opt_group_%s', $repository->getMetaValue($account, 'account_role'));
$type = $account->accountType->type;
$role = sprintf('opt_group_%s', $repository->getMetaValue($account, 'account_role'));
if (in_array($type, [AccountType::MORTGAGE, AccountType::DEBT, AccountType::LOAN], true)) {
$role = sprintf('opt_group_l_%s', $type);
@@ -94,42 +94,49 @@ class PreferencesController extends Controller
if (!is_array($frontpageAccounts)) {
$frontpageAccounts = $accountIds;
}
$language = app('steam')->getLanguage();
$languages = config('firefly.languages');
$locale = app('preferences')->get('locale', config('firefly.default_locale', 'equal'))->data;
$listPageSize = app('preferences')->get('listPageSize', 50)->data;
$darkMode = app('preferences')->get('darkMode', 'browser')->data;
$customFiscalYear = app('preferences')->get('customFiscalYear', 0)->data;
$fiscalYearStartStr = app('preferences')->get('fiscalYearStart', '01-01')->data;
$language = app('steam')->getLanguage();
$languages = config('firefly.languages');
$locale = app('preferences')->get('locale', config('firefly.default_locale', 'equal'))->data;
$listPageSize = app('preferences')->get('listPageSize', 50)->data;
$darkMode = app('preferences')->get('darkMode', 'browser')->data;
$customFiscalYear = app('preferences')->get('customFiscalYear', 0)->data;
$fiscalYearStartStr = app('preferences')->get('fiscalYearStart', '01-01')->data;
if (is_array($fiscalYearStartStr)) {
$fiscalYearStartStr = '01-01';
}
$fiscalYearStart = sprintf('%s-%s', date('Y'), (string) $fiscalYearStartStr);
$tjOptionalFields = app('preferences')->get('transaction_journal_optional_fields', [])->data;
$availableDarkModes = config('firefly.available_dark_modes');
$fiscalYearStart = sprintf('%s-%s', date('Y'), (string) $fiscalYearStartStr);
$tjOptionalFields = app('preferences')->get('transaction_journal_optional_fields', [])->data;
$availableDarkModes = config('firefly.available_dark_modes');
// notifications settings
$slackUrl = app('preferences')->getEncrypted('slack_webhook_url', '')->data;
$pushoverAppToken = app('preferences')->getEncrypted('pushover_app_token', '')->data;
$pushoverUserToken = app('preferences')->getEncrypted('pushover_user_token', '')->data;
$ntfyServer = app('preferences')->getEncrypted('ntfy_server', 'https://ntfy.sh')->data;
$ntfyTopic = app('preferences')->getEncrypted('ntfy_topic', '')->data;
$ntfyAuth = app('preferences')->get('ntfy_auth', false)->data;
$ntfyUser = app('preferences')->getEncrypted('ntfy_user', '')->data;
$ntfyPass = app('preferences')->getEncrypted('ntfy_pass', '')->data;
$slackUrl = app('preferences')->getEncrypted('slack_webhook_url', '')->data;
$pushoverAppToken = app('preferences')->getEncrypted('pushover_app_token', '')->data;
$pushoverUserToken = app('preferences')->getEncrypted('pushover_user_token', '')->data;
$ntfyServer = app('preferences')->getEncrypted('ntfy_server', 'https://ntfy.sh')->data;
$ntfyTopic = app('preferences')->getEncrypted('ntfy_topic', '')->data;
$ntfyAuth = app('preferences')->get('ntfy_auth', false)->data;
$ntfyUser = app('preferences')->getEncrypted('ntfy_user', '')->data;
$ntfyPass = app('preferences')->getEncrypted('ntfy_pass', '')->data;
$channels = config('notifications.channels');
$forcedAvailability = [];
// notification preferences (single value for each):
$notifications = [];
// notification preferences
$notifications = [];
foreach (config('notifications.notifications.user') as $key => $info) {
if ($info['enabled']) {
$notifications[$key]
= [
'enabled' => app('preferences')->get(sprintf('notification_%s', $key), true)->data,
'configurable' => $info['configurable'],
];
'enabled' => app('preferences')->get(sprintf('notification_%s', $key), true)->data,
'configurable' => $info['configurable'],
];
}
}
// 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);
@@ -141,7 +148,7 @@ class PreferencesController extends Controller
app('log')->error($e->getMessage());
$locales = [];
}
$locales = ['equal' => (string) trans('firefly.equal_to_language')] + $locales;
$locales = ['equal' => (string) trans('firefly.equal_to_language')] + $locales;
// an important fallback is that the frontPageAccount array gets refilled automatically
// when it turns up empty.
if (0 === count($frontpageAccounts)) {
@@ -151,7 +158,7 @@ class PreferencesController extends Controller
// for the demo user, the notification settings are automatically emptied.
// this isn't really secure, but it means that the demo site has semi-secret notification settings.
if (auth()->user()->hasRole('demo')) {
$slackUrl = '';
$slackUrl = '';
$pushoverAppToken = '';
$pushoverUserToken = '';
$ntfyServer = '';
@@ -161,9 +168,32 @@ class PreferencesController extends Controller
$ntfyPass = '';
}
return view('preferences.index', compact('language', 'pushoverAppToken', 'pushoverUserToken',
'ntfyServer', 'ntfyTopic', 'ntfyAuth', 'ntfyUser', 'ntfyPass',
'groupedAccounts', 'isDocker', 'frontpageAccounts', 'languages', 'darkMode', 'availableDarkModes', 'notifications', 'slackUrl', 'locales', 'locale', 'tjOptionalFields', 'viewRange', 'customFiscalYear', 'listPageSize', 'fiscalYearStart'));
return view('preferences.index', compact(
'language',
'pushoverAppToken',
'pushoverUserToken',
'ntfyServer',
'ntfyTopic',
'ntfyAuth',
'ntfyUser',
'forcedAvailability',
'ntfyPass',
'groupedAccounts',
'isDocker',
'frontpageAccounts',
'languages',
'darkMode',
'availableDarkModes',
'notifications',
'slackUrl',
'locales',
'locale',
'tjOptionalFields',
'viewRange',
'customFiscalYear',
'listPageSize',
'fiscalYearStart'
));
}
/**
@@ -188,8 +218,9 @@ class PreferencesController extends Controller
}
// extract notifications:
$all = $request->all();
die('fix the reference to the available notifications.');
$all = $request->all();
exit('fix the reference to the available notifications.');
foreach (config('firefly.available_notifications') as $option) {
$key = sprintf('notification_%s', $option);
if (array_key_exists($key, $all)) {
@@ -219,8 +250,8 @@ class PreferencesController extends Controller
}
// custom fiscal year
$customFiscalYear = 1 === (int) $request->get('customFiscalYear');
$string = strtotime((string) $request->get('fiscalYearStart'));
$customFiscalYear = 1 === (int) $request->get('customFiscalYear');
$string = strtotime((string) $request->get('fiscalYearStart'));
if (false !== $string) {
$fiscalYearStart = date('m-d', $string);
app('preferences')->set('customFiscalYear', $customFiscalYear);
@@ -229,15 +260,15 @@ class PreferencesController extends Controller
// save page size:
app('preferences')->set('listPageSize', 50);
$listPageSize = (int) $request->get('listPageSize');
$listPageSize = (int) $request->get('listPageSize');
if ($listPageSize > 0 && $listPageSize < 1337) {
app('preferences')->set('listPageSize', $listPageSize);
}
// language:
/** @var Preference $currentLang */
$currentLang = app('preferences')->get('language', 'en_US');
$lang = $request->get('language');
$currentLang = app('preferences')->get('language', 'en_US');
$lang = $request->get('language');
if (array_key_exists($lang, config('firefly.languages'))) {
app('preferences')->set('language', $lang);
}
@@ -254,8 +285,8 @@ class PreferencesController extends Controller
}
// optional fields for transactions:
$setOptions = $request->get('tj') ?? [];
$optionalTj = [
$setOptions = $request->get('tj') ?? [];
$optionalTj = [
'interest_date' => array_key_exists('interest_date', $setOptions),
'book_date' => array_key_exists('book_date', $setOptions),
'process_date' => array_key_exists('process_date', $setOptions),
@@ -272,7 +303,7 @@ class PreferencesController extends Controller
app('preferences')->set('transaction_journal_optional_fields', $optionalTj);
// dark mode
$darkMode = $request->get('darkMode') ?? 'browser';
$darkMode = $request->get('darkMode') ?? 'browser';
if (in_array($darkMode, config('firefly.available_dark_modes'), true)) {
app('preferences')->set('darkMode', $darkMode);
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* NotificationRequest.php
* Copyright (c) 2024 james@firefly-iii.org.
@@ -35,24 +36,25 @@ class NotificationRequest extends FormRequest
public function getAll(): array
{
$return = [];
$return = [];
foreach (config('notifications.notifications.owner') as $key => $info) {
$value = false;
$value = false;
if ($this->has(sprintf('notification_%s', $key))) {
$value = true;
}
$return[$key] = $value;
}
$return['slack_webhook_url'] = $this->convertString('slack_webhook_url');
$return['slack_webhook_url'] = $this->convertString('slack_webhook_url');
$return['pushover_app_token'] = $this->convertString('pushover_app_token');
$return['pushover_user_token'] = $this->convertString('pushover_user_token');
$return['ntfy_server'] = $this->convertString('ntfy_server');
$return['ntfy_topic'] = $this->convertString('ntfy_topic');
$return['ntfy_auth'] = $this->convertBoolean($this->get('ntfy_auth'));
$return['ntfy_user'] = $this->convertString('ntfy_user');
$return['ntfy_pass'] = $this->convertString('ntfy_pass');
$return['ntfy_server'] = $this->convertString('ntfy_server');
$return['ntfy_topic'] = $this->convertString('ntfy_topic');
$return['ntfy_auth'] = $this->convertBoolean($this->get('ntfy_auth'));
$return['ntfy_user'] = $this->convertString('ntfy_user');
$return['ntfy_pass'] = $this->convertString('ntfy_pass');
return $return;
}
@@ -63,14 +65,14 @@ class NotificationRequest extends FormRequest
{
$rules = [
'slack_webhook_url' => ['nullable', 'url', 'min:1', new IsValidSlackOrDiscordUrl()],
'ntfy_server' => ['nullable', 'url', 'min:1'],
'ntfy_user' => ['required_with:ntfy_pass,ntfy_auth', 'nullable', 'string', 'min:1'],
'ntfy_pass' => ['required_with:ntfy_user,ntfy_auth', 'nullable', 'string', 'min:1'],
'ntfy_server' => ['nullable', 'url', 'min:1'],
'ntfy_user' => ['required_with:ntfy_pass,ntfy_auth', 'nullable', 'string', 'min:1'],
'ntfy_pass' => ['required_with:ntfy_user,ntfy_auth', 'nullable', 'string', 'min:1'],
];
foreach (config('notifications.notifications.owner') as $key => $info) {
$rules[sprintf('notification_%s', $key)] = 'in:0,1';
}
return $rules;
}
}

View File

@@ -59,7 +59,7 @@ class PiggyBankStoreRequest extends FormRequest
$accounts = [];
}
foreach ($accounts as $item) {
$data['accounts'][] = ['account_id' => (int) ($item)];
$data['accounts'][] = ['account_id' => (int) $item];
}
return $data;
@@ -105,7 +105,7 @@ class PiggyBankStoreRequest extends FormRequest
if ($accountCurrency->id !== $currency->id && 'true' !== $isMultiCurrency) {
$validator->errors()->add('accounts', trans('validation.invalid_account_currency'));
}
$type = $account->accountType->type;
$type = $account->accountType->type;
if (!in_array($type, $types, true)) {
$validator->errors()->add('accounts', trans('validation.invalid_account_type'));
}
@@ -127,6 +127,7 @@ class PiggyBankStoreRequest extends FormRequest
if (null === $currency) {
return app('amount')->getDefaultCurrency();
}
return $currency;
}
}