chore: code cleanup.

This commit is contained in:
James Cole
2023-05-29 13:56:55 +02:00
parent 7f7644c92f
commit 1b52147a05
295 changed files with 12418 additions and 12324 deletions

View File

@@ -34,8 +34,8 @@ use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\View\View;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

View File

@@ -32,9 +32,9 @@ use FireflyIII\Support\Http\Controllers\BasicDataSupport;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
use JsonException;
use Illuminate\Support\Facades\Log;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

View File

@@ -38,9 +38,9 @@ use FireflyIII\User;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
use JsonException;
use Illuminate\Support\Facades\Log;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

View File

@@ -29,8 +29,8 @@ use FireflyIII\Http\Middleware\IsDemoUser;
use FireflyIII\Http\Requests\ConfigurationRequest;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

View File

@@ -33,8 +33,8 @@ use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\View\View;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

View File

@@ -32,8 +32,8 @@ use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\View\View;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
/**
* Class LinkController.

View File

@@ -36,8 +36,8 @@ use Illuminate\Contracts\View\Factory;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Routing\Redirector;
use Illuminate\View\View;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

View File

@@ -31,8 +31,8 @@ use Illuminate\Contracts\View\Factory;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

View File

@@ -38,8 +38,8 @@ use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Redirector;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
@@ -128,37 +128,6 @@ class LoginController extends Controller
$this->sendFailedLoginResponse($request);
}
/**
* Get the login username to be used by the controller.
*
* @return string
*/
public function username()
{
return $this->username;
}
/**
* Get the failed login response instance.
*
* @param Request $request
*
* @return void
*
* @throws ValidationException
*/
protected function sendFailedLoginResponse(Request $request)
{
$exception = ValidationException::withMessages(
[
$this->username() => [trans('auth.failed')],
]
);
$exception->redirectTo = route('login');
throw $exception;
}
/**
* Log the user out of the application.
*
@@ -244,4 +213,35 @@ class LoginController extends Controller
return view('auth.login', compact('allowRegistration', 'email', 'remember', 'allowReset', 'title', 'usernameField'));
}
/**
* Get the login username to be used by the controller.
*
* @return string
*/
public function username()
{
return $this->username;
}
/**
* Get the failed login response instance.
*
* @param Request $request
*
* @return void
*
* @throws ValidationException
*/
protected function sendFailedLoginResponse(Request $request)
{
$exception = ValidationException::withMessages(
[
$this->username() => [trans('auth.failed')],
]
);
$exception->redirectTo = route('login');
throw $exception;
}
}

View File

@@ -35,9 +35,9 @@ use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;
use Illuminate\Support\Facades\Log;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
@@ -117,30 +117,6 @@ class RegisterController extends Controller
return redirect($this->redirectPath());
}
/**
* @return bool
* @throws FireflyException
*/
protected function allowedToRegister(): bool
{
// is allowed to register?
$allowRegistration = true;
try {
$singleUserMode = app('fireflyconfig')->get('single_user_mode', config('firefly.configuration.single_user_mode'))->data;
} catch (ContainerExceptionInterface|NotFoundExceptionInterface $e) {
$singleUserMode = true;
}
$userCount = User::count();
$guard = config('auth.defaults.guard');
if (true === $singleUserMode && $userCount > 0 && 'web' === $guard) {
$allowRegistration = false;
}
if ('web' !== $guard) {
$allowRegistration = false;
}
return $allowRegistration;
}
/**
* Show the application registration form if the invitation code is valid.
*
@@ -201,4 +177,28 @@ class RegisterController extends Controller
return view('auth.register', compact('isDemoSite', 'email', 'pageTitle'));
}
/**
* @return bool
* @throws FireflyException
*/
protected function allowedToRegister(): bool
{
// is allowed to register?
$allowRegistration = true;
try {
$singleUserMode = app('fireflyconfig')->get('single_user_mode', config('firefly.configuration.single_user_mode'))->data;
} catch (ContainerExceptionInterface|NotFoundExceptionInterface $e) {
$singleUserMode = true;
}
$userCount = User::count();
$guard = config('auth.defaults.guard');
if (true === $singleUserMode && $userCount > 0 && 'web' === $guard) {
$allowRegistration = false;
}
if ('web' !== $guard) {
$allowRegistration = false;
}
return $allowRegistration;
}
}

View File

@@ -99,26 +99,20 @@ class TwoFactorController extends Controller
}
/**
* Each MFA history has a timestamp and a code, saving the MFA entries for 5 minutes. So if the
* submitted MFA code has been submitted in the last 5 minutes, it won't work despite being valid.
*
* @param string $mfaCode
* @param array $mfaHistory
*
* @return bool
*/
private function inMFAHistory(string $mfaCode, array $mfaHistory): bool
private function addToMFAHistory(string $mfaCode): void
{
$now = time();
foreach ($mfaHistory as $entry) {
$time = $entry['time'];
$code = $entry['code'];
if ($code === $mfaCode && $now - $time <= 300) {
return true;
}
}
/** @var array $mfaHistory */
$mfaHistory = Preferences::get('mfa_history', [])->data;
$entry = [
'time' => time(),
'code' => $mfaCode,
];
$mfaHistory[] = $entry;
return false;
Preferences::set('mfa_history', $mfaHistory);
$this->filterMFAHistory();
}
/**
@@ -144,20 +138,26 @@ class TwoFactorController extends Controller
}
/**
* Each MFA history has a timestamp and a code, saving the MFA entries for 5 minutes. So if the
* submitted MFA code has been submitted in the last 5 minutes, it won't work despite being valid.
*
* @param string $mfaCode
* @param array $mfaHistory
*
* @return bool
*/
private function addToMFAHistory(string $mfaCode): void
private function inMFAHistory(string $mfaCode, array $mfaHistory): bool
{
/** @var array $mfaHistory */
$mfaHistory = Preferences::get('mfa_history', [])->data;
$entry = [
'time' => time(),
'code' => $mfaCode,
];
$mfaHistory[] = $entry;
$now = time();
foreach ($mfaHistory as $entry) {
$time = $entry['time'];
$code = $entry['code'];
if ($code === $mfaCode && $now - $time <= 300) {
return true;
}
}
Preferences::set('mfa_history', $mfaHistory);
$this->filterMFAHistory();
return false;
}
/**

View File

@@ -135,49 +135,26 @@ class IndexController extends Controller
}
/**
* @param array $bills
* Set the order of a bill.
*
* @return array
* @throws FireflyException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
* @param Request $request
* @param Bill $bill
*
* @return JsonResponse
*/
private function getSums(array $bills): array
public function setOrder(Request $request, Bill $bill): JsonResponse
{
$sums = [];
$range = app('navigation')->getViewRange(false);
/** @var array $group */
foreach ($bills as $groupOrder => $group) {
/** @var array $bill */
foreach ($group['bills'] as $bill) {
if (false === $bill['active']) {
continue;
}
$currencyId = $bill['currency_id'];
$sums[$groupOrder][$currencyId] = $sums[$groupOrder][$currencyId] ?? [
'currency_id' => $currencyId,
'currency_code' => $bill['currency_code'],
'currency_name' => $bill['currency_name'],
'currency_symbol' => $bill['currency_symbol'],
'currency_decimal_places' => $bill['currency_decimal_places'],
'avg' => '0',
'period' => $range,
'per_period' => '0',
];
// only fill in avg when bill is active.
if (count($bill['pay_dates']) > 0) {
$avg = bcdiv(bcadd((string)$bill['amount_min'], (string)$bill['amount_max']), '2');
$avg = bcmul($avg, (string)count($bill['pay_dates']));
$sums[$groupOrder][$currencyId]['avg'] = bcadd($sums[$groupOrder][$currencyId]['avg'], $avg);
}
// fill in per period regardless:
$sums[$groupOrder][$currencyId]['per_period'] = bcadd($sums[$groupOrder][$currencyId]['per_period'], $this->amountPerPeriod($bill, $range));
}
$objectGroupTitle = (string)$request->get('objectGroupTitle');
$newOrder = (int)$request->get('order');
$this->repository->setOrder($bill, $newOrder);
if ('' !== $objectGroupTitle) {
$this->repository->setObjectGroup($bill, $objectGroupTitle);
}
if ('' === $objectGroupTitle) {
$this->repository->removeObjectGroup($bill);
}
return $sums;
return response()->json(['data' => 'OK']);
}
/**
@@ -227,6 +204,52 @@ class IndexController extends Controller
return $perPeriod;
}
/**
* @param array $bills
*
* @return array
* @throws FireflyException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
private function getSums(array $bills): array
{
$sums = [];
$range = app('navigation')->getViewRange(false);
/** @var array $group */
foreach ($bills as $groupOrder => $group) {
/** @var array $bill */
foreach ($group['bills'] as $bill) {
if (false === $bill['active']) {
continue;
}
$currencyId = $bill['currency_id'];
$sums[$groupOrder][$currencyId] = $sums[$groupOrder][$currencyId] ?? [
'currency_id' => $currencyId,
'currency_code' => $bill['currency_code'],
'currency_name' => $bill['currency_name'],
'currency_symbol' => $bill['currency_symbol'],
'currency_decimal_places' => $bill['currency_decimal_places'],
'avg' => '0',
'period' => $range,
'per_period' => '0',
];
// only fill in avg when bill is active.
if (count($bill['pay_dates']) > 0) {
$avg = bcdiv(bcadd((string)$bill['amount_min'], (string)$bill['amount_max']), '2');
$avg = bcmul($avg, (string)count($bill['pay_dates']));
$sums[$groupOrder][$currencyId]['avg'] = bcadd($sums[$groupOrder][$currencyId]['avg'], $avg);
}
// fill in per period regardless:
$sums[$groupOrder][$currencyId]['per_period'] = bcadd($sums[$groupOrder][$currencyId]['per_period'], $this->amountPerPeriod($bill, $range));
}
}
return $sums;
}
/**
* @param array $sums
*
@@ -264,27 +287,4 @@ class IndexController extends Controller
return $totals;
}
/**
* Set the order of a bill.
*
* @param Request $request
* @param Bill $bill
*
* @return JsonResponse
*/
public function setOrder(Request $request, Bill $bill): JsonResponse
{
$objectGroupTitle = (string)$request->get('objectGroupTitle');
$newOrder = (int)$request->get('order');
$this->repository->setOrder($bill, $newOrder);
if ('' !== $objectGroupTitle) {
$this->repository->setObjectGroup($bill, $objectGroupTitle);
}
if ('' === $objectGroupTitle) {
$this->repository->removeObjectGroup($bill);
}
return response()->json(['data' => 'OK']);
}
}

View File

@@ -26,7 +26,6 @@ namespace FireflyIII\Http\Controllers\Budget;
use Carbon\Carbon;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Models\AvailableBudget;
use FireflyIII\Models\Budget;
use FireflyIII\Models\BudgetLimit;
use FireflyIII\Models\TransactionCurrency;
@@ -41,8 +40,8 @@ use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Collection;
use Illuminate\View\View;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
/**
*

View File

@@ -173,6 +173,29 @@ class IndexController extends Controller
);
}
/**
* @param Request $request
* @param BudgetRepositoryInterface $repository
*
* @return JsonResponse
*/
public function reorder(Request $request, BudgetRepositoryInterface $repository): JsonResponse
{
$budgetIds = $request->get('budgetIds');
foreach ($budgetIds as $index => $budgetId) {
$budgetId = (int)$budgetId;
$budget = $repository->find($budgetId);
if (null !== $budget) {
Log::debug(sprintf('Set budget #%d ("%s") to position %d', $budget->id, $budget->name, $index + 1));
$repository->setBudgetOrder($budget, $index + 1);
}
}
app('preferences')->mark();
return response()->json(['OK']);
}
/**
* @param Carbon $start
* @param Carbon $end
@@ -328,27 +351,4 @@ class IndexController extends Controller
return $sums;
}
/**
* @param Request $request
* @param BudgetRepositoryInterface $repository
*
* @return JsonResponse
*/
public function reorder(Request $request, BudgetRepositoryInterface $repository): JsonResponse
{
$budgetIds = $request->get('budgetIds');
foreach ($budgetIds as $index => $budgetId) {
$budgetId = (int)$budgetId;
$budget = $repository->find($budgetId);
if (null !== $budget) {
Log::debug(sprintf('Set budget #%d ("%s") to position %d', $budget->id, $budget->name, $index + 1));
$repository->setBudgetOrder($budget, $index + 1);
}
}
app('preferences')->mark();
return response()->json(['OK']);
}
}

View File

@@ -33,9 +33,9 @@ use FireflyIII\Support\Http\Controllers\PeriodOverview;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
use JsonException;
use Illuminate\Support\Facades\Log;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

View File

@@ -40,8 +40,8 @@ use FireflyIII\Support\Http\Controllers\ChartGeneration;
use FireflyIII\Support\Http\Controllers\DateCalculation;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Collection;
use JsonException;
use Illuminate\Support\Facades\Log;
use JsonException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
@@ -173,22 +173,6 @@ class AccountController extends Controller
return response()->json($data);
}
/**
* Expenses per budget for all time, as shown on account overview.
*
* @param AccountRepositoryInterface $repository
* @param Account $account
*
* @return JsonResponse
*/
public function expenseBudgetAll(AccountRepositoryInterface $repository, Account $account): JsonResponse
{
$start = $repository->oldestJournalDate($account) ?? today(config('app.timezone'))->startOfMonth();
$end = today(config('app.timezone'));
return $this->expenseBudget($account, $start, $end);
}
/**
* Expenses per budget, as shown on account overview.
*
@@ -248,19 +232,19 @@ class AccountController extends Controller
}
/**
* Expenses grouped by category for account.
* Expenses per budget for all time, as shown on account overview.
*
* @param AccountRepositoryInterface $repository
* @param Account $account
*
* @return JsonResponse
*/
public function expenseCategoryAll(AccountRepositoryInterface $repository, Account $account): JsonResponse
public function expenseBudgetAll(AccountRepositoryInterface $repository, Account $account): JsonResponse
{
$start = $repository->oldestJournalDate($account) ?? today(config('app.timezone'))->startOfMonth();
$end = today(config('app.timezone'));
return $this->expenseCategory($account, $start, $end);
return $this->expenseBudget($account, $start, $end);
}
/**
@@ -319,6 +303,22 @@ class AccountController extends Controller
return response()->json($data);
}
/**
* Expenses grouped by category for account.
*
* @param AccountRepositoryInterface $repository
* @param Account $account
*
* @return JsonResponse
*/
public function expenseCategoryAll(AccountRepositoryInterface $repository, Account $account): JsonResponse
{
$start = $repository->oldestJournalDate($account) ?? today(config('app.timezone'))->startOfMonth();
$end = today(config('app.timezone'));
return $this->expenseCategory($account, $start, $end);
}
/**
* Shows the balances for all the user's frontpage accounts.
*
@@ -347,22 +347,6 @@ class AccountController extends Controller
return response()->json($this->accountBalanceChart($accounts, $start, $end));
}
/**
* Shows the income grouped by category for an account, in all time.
*
* @param AccountRepositoryInterface $repository
* @param Account $account
*
* @return JsonResponse
*/
public function incomeCategoryAll(AccountRepositoryInterface $repository, Account $account): JsonResponse
{
$start = $repository->oldestJournalDate($account) ?? today(config('app.timezone'))->startOfMonth();
$end = today(config('app.timezone'));
return $this->incomeCategory($account, $start, $end);
}
/**
* Shows all income per account for each category.
*
@@ -419,6 +403,22 @@ class AccountController extends Controller
return response()->json($data);
}
/**
* Shows the income grouped by category for an account, in all time.
*
* @param AccountRepositoryInterface $repository
* @param Account $account
*
* @return JsonResponse
*/
public function incomeCategoryAll(AccountRepositoryInterface $repository, Account $account): JsonResponse
{
$start = $repository->oldestJournalDate($account) ?? today(config('app.timezone'))->startOfMonth();
$end = today(config('app.timezone'));
return $this->incomeCategory($account, $start, $end);
}
/**
* Shows overview of account during a single period.
*
@@ -460,54 +460,6 @@ class AccountController extends Controller
return response()->json($data);
}
/**
* @param Carbon $start
* @param Carbon $end
* @param Account $account
* @param TransactionCurrency $currency
*
* @return array
* @throws FireflyException
* @throws JsonException
*/
private function periodByCurrency(Carbon $start, Carbon $end, Account $account, TransactionCurrency $currency): array
{
$locale = app('steam')->getLocale();
$step = $this->calculateStep($start, $end);
$result = [
'label' => sprintf('%s (%s)', $account->name, $currency->symbol),
'currency_symbol' => $currency->symbol,
'currency_code' => $currency->code,
];
$entries = [];
$current = clone $start;
if ('1D' === $step) {
// per day the entire period, balance for every day.
$format = (string)trans('config.month_and_day_js', [], $locale);
$range = app('steam')->balanceInRange($account, $start, $end, $currency);
$previous = array_values($range)[0];
while ($end >= $current) {
$theDate = $current->format('Y-m-d');
$balance = $range[$theDate] ?? $previous;
$label = $current->isoFormat($format);
$entries[$label] = (float)$balance;
$previous = $balance;
$current->addDay();
}
}
if ('1W' === $step || '1M' === $step || '1Y' === $step) {
while ($end >= $current) {
$balance = (float)app('steam')->balance($account, $current, $currency);
$label = app('navigation')->periodShow($current, $step);
$entries[$label] = $balance;
$current = app('navigation')->addPeriod($current, $step, 0);
}
}
$result['entries'] = $entries;
return $result;
}
/**
* Shows the balances for a given set of dates and accounts.
*
@@ -619,4 +571,52 @@ class AccountController extends Controller
return response()->json($data);
}
/**
* @param Carbon $start
* @param Carbon $end
* @param Account $account
* @param TransactionCurrency $currency
*
* @return array
* @throws FireflyException
* @throws JsonException
*/
private function periodByCurrency(Carbon $start, Carbon $end, Account $account, TransactionCurrency $currency): array
{
$locale = app('steam')->getLocale();
$step = $this->calculateStep($start, $end);
$result = [
'label' => sprintf('%s (%s)', $account->name, $currency->symbol),
'currency_symbol' => $currency->symbol,
'currency_code' => $currency->code,
];
$entries = [];
$current = clone $start;
if ('1D' === $step) {
// per day the entire period, balance for every day.
$format = (string)trans('config.month_and_day_js', [], $locale);
$range = app('steam')->balanceInRange($account, $start, $end, $currency);
$previous = array_values($range)[0];
while ($end >= $current) {
$theDate = $current->format('Y-m-d');
$balance = $range[$theDate] ?? $previous;
$label = $current->isoFormat($format);
$entries[$label] = (float)$balance;
$previous = $balance;
$current->addDay();
}
}
if ('1W' === $step || '1M' === $step || '1Y' === $step) {
while ($end >= $current) {
$balance = (float)app('steam')->balance($account, $current, $currency);
$label = app('navigation')->periodShow($current, $step);
$entries[$label] = $balance;
$current = app('navigation')->addPeriod($current, $step, 0);
}
}
$result['entries'] = $entries;
return $result;
}
}

View File

@@ -226,29 +226,6 @@ class BudgetReportController extends Controller
return response()->json($data);
}
/**
* @param Carbon $start
* @param Carbon $end
*
* @return array
*/
private function makeEntries(Carbon $start, Carbon $end): array
{
$return = [];
$format = app('navigation')->preferredCarbonLocalizedFormat($start, $end);
$preferredRange = app('navigation')->preferredRangeFormat($start, $end);
$currentStart = clone $start;
while ($currentStart <= $end) {
$currentEnd = app('navigation')->endOfPeriod($currentStart, $preferredRange);
$key = $currentStart->isoFormat($format);
$return[$key] = '0';
$currentStart = clone $currentEnd;
$currentStart->addDay()->startOfDay();
}
return $return;
}
/**
* Chart that groups expenses by the account.
*
@@ -285,4 +262,27 @@ class BudgetReportController extends Controller
return response()->json($data);
}
/**
* @param Carbon $start
* @param Carbon $end
*
* @return array
*/
private function makeEntries(Carbon $start, Carbon $end): array
{
$return = [];
$format = app('navigation')->preferredCarbonLocalizedFormat($start, $end);
$preferredRange = app('navigation')->preferredRangeFormat($start, $end);
$currentStart = clone $start;
while ($currentStart <= $end) {
$currentEnd = app('navigation')->endOfPeriod($currentStart, $preferredRange);
$key = $currentStart->isoFormat($format);
$return[$key] = '0';
$currentStart = clone $currentEnd;
$currentStart->addDay()->startOfDay();
}
return $return;
}
}

View File

@@ -102,14 +102,6 @@ class CategoryController extends Controller
return response()->json($data);
}
/**
* @return Carbon
*/
private function getDate(): Carbon
{
return today(config('app.timezone'));
}
/**
* Shows the category chart on the front page.
* TODO test method for category refactor.
@@ -166,6 +158,81 @@ class CategoryController extends Controller
return response()->json($data);
}
/**
* Chart for period for transactions without a category.
* TODO test me.
*
* @param Collection $accounts
* @param Carbon $start
* @param Carbon $end
*
* @return JsonResponse
*/
public function reportPeriodNoCategory(Collection $accounts, Carbon $start, Carbon $end): JsonResponse
{
$cache = new CacheProperties();
$cache->addProperty($start);
$cache->addProperty($end);
$cache->addProperty('chart.category.period.no-cat');
$cache->addProperty($accounts->pluck('id')->toArray());
if ($cache->has()) {
return response()->json($cache->get());
}
$data = $this->reportPeriodChart($accounts, $start, $end, null);
$cache->store($data);
return response()->json($data);
}
/**
* Chart for a specific period.
* TODO test me, for category refactor.
*
* @param Category $category
* @param Carbon $date
*
* @return JsonResponse
* @throws FireflyException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function specificPeriod(Category $category, Carbon $date): JsonResponse
{
$range = app('navigation')->getViewRange(false);
$start = app('navigation')->startOfPeriod($date, $range);
$end = session()->get('end');
if ($end < $start) {
[$end, $start] = [$start, $end];
}
$cache = new CacheProperties();
$cache->addProperty($start);
$cache->addProperty($end);
$cache->addProperty($category->id);
$cache->addProperty('chart.category.period-chart');
if ($cache->has()) {
return response()->json($cache->get());
}
/** @var WholePeriodChartGenerator $chartGenerator */
$chartGenerator = app(WholePeriodChartGenerator::class);
$chartData = $chartGenerator->generate($category, $start, $end);
$data = $this->generator->multiSet($chartData);
$cache->store($data);
return response()->json($data);
}
/**
* @return Carbon
*/
private function getDate(): Carbon
{
return today(config('app.timezone'));
}
/**
* Generate report chart for either with or without category.
*
@@ -251,71 +318,4 @@ class CategoryController extends Controller
return $this->generator->multiSet($chartData);
}
/**
* Chart for period for transactions without a category.
* TODO test me.
*
* @param Collection $accounts
* @param Carbon $start
* @param Carbon $end
*
* @return JsonResponse
*/
public function reportPeriodNoCategory(Collection $accounts, Carbon $start, Carbon $end): JsonResponse
{
$cache = new CacheProperties();
$cache->addProperty($start);
$cache->addProperty($end);
$cache->addProperty('chart.category.period.no-cat');
$cache->addProperty($accounts->pluck('id')->toArray());
if ($cache->has()) {
return response()->json($cache->get());
}
$data = $this->reportPeriodChart($accounts, $start, $end, null);
$cache->store($data);
return response()->json($data);
}
/**
* Chart for a specific period.
* TODO test me, for category refactor.
*
* @param Category $category
* @param Carbon $date
*
* @return JsonResponse
* @throws FireflyException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function specificPeriod(Category $category, Carbon $date): JsonResponse
{
$range = app('navigation')->getViewRange(false);
$start = app('navigation')->startOfPeriod($date, $range);
$end = session()->get('end');
if ($end < $start) {
[$end, $start] = [$start, $end];
}
$cache = new CacheProperties();
$cache->addProperty($start);
$cache->addProperty($end);
$cache->addProperty($category->id);
$cache->addProperty('chart.category.period-chart');
if ($cache->has()) {
return response()->json($cache->get());
}
/** @var WholePeriodChartGenerator $chartGenerator */
$chartGenerator = app(WholePeriodChartGenerator::class);
$chartData = $chartGenerator->generate($category, $start, $end);
$data = $this->generator->multiSet($chartData);
$cache->store($data);
return response()->json($data);
}
}

View File

@@ -319,31 +319,6 @@ class CategoryReportController extends Controller
return response()->json($data);
}
/**
* TODO duplicate function
*
* @param Carbon $start
* @param Carbon $end
*
* @return array
*/
private function makeEntries(Carbon $start, Carbon $end): array
{
$return = [];
$format = app('navigation')->preferredCarbonLocalizedFormat($start, $end);
$preferredRange = app('navigation')->preferredRangeFormat($start, $end);
$currentStart = clone $start;
while ($currentStart <= $end) {
$currentEnd = app('navigation')->endOfPeriod($currentStart, $preferredRange);
$key = $currentStart->isoFormat($format);
$return[$key] = '0';
$currentStart = clone $currentEnd;
$currentStart->addDay()->startOfDay();
}
return $return;
}
/**
* @param Collection $accounts
* @param Collection $categories
@@ -415,4 +390,29 @@ class CategoryReportController extends Controller
return response()->json($data);
}
/**
* TODO duplicate function
*
* @param Carbon $start
* @param Carbon $end
*
* @return array
*/
private function makeEntries(Carbon $start, Carbon $end): array
{
$return = [];
$format = app('navigation')->preferredCarbonLocalizedFormat($start, $end);
$preferredRange = app('navigation')->preferredRangeFormat($start, $end);
$currentStart = clone $start;
while ($currentStart <= $end) {
$currentEnd = app('navigation')->endOfPeriod($currentStart, $preferredRange);
$key = $currentStart->isoFormat($format);
$return[$key] = '0';
$currentStart = clone $currentEnd;
$currentStart->addDay()->startOfDay();
}
return $return;
}
}

View File

@@ -247,56 +247,6 @@ class DoubleReportController extends Controller
return response()->json($data);
}
/**
* TODO duplicate function
*
* @param Collection $accounts
* @param int $id
* @param string $name
* @param null|string $iban
*
* @return string
*/
private function getCounterpartName(Collection $accounts, int $id, string $name, ?string $iban): string
{
/** @var Account $account */
foreach ($accounts as $account) {
if ($account->name === $name && $account->id !== $id) {
return $account->name;
}
if (null !== $account->iban && $account->iban === $iban && $account->id !== $id) {
return $account->iban;
}
}
return $name;
}
/**
* TODO duplicate function
*
* @param Carbon $start
* @param Carbon $end
*
* @return array
*/
private function makeEntries(Carbon $start, Carbon $end): array
{
$return = [];
$format = app('navigation')->preferredCarbonLocalizedFormat($start, $end);
$preferredRange = app('navigation')->preferredRangeFormat($start, $end);
$currentStart = clone $start;
while ($currentStart <= $end) {
$currentEnd = app('navigation')->endOfPeriod($currentStart, $preferredRange);
$key = $currentStart->isoFormat($format);
$return[$key] = '0';
$currentStart = clone $currentEnd;
$currentStart->addDay()->startOfDay();
}
return $return;
}
/**
* @param Collection $accounts
* @param Collection $others
@@ -416,4 +366,54 @@ class DoubleReportController extends Controller
return response()->json($data);
}
/**
* TODO duplicate function
*
* @param Collection $accounts
* @param int $id
* @param string $name
* @param null|string $iban
*
* @return string
*/
private function getCounterpartName(Collection $accounts, int $id, string $name, ?string $iban): string
{
/** @var Account $account */
foreach ($accounts as $account) {
if ($account->name === $name && $account->id !== $id) {
return $account->name;
}
if (null !== $account->iban && $account->iban === $iban && $account->id !== $id) {
return $account->iban;
}
}
return $name;
}
/**
* TODO duplicate function
*
* @param Carbon $start
* @param Carbon $end
*
* @return array
*/
private function makeEntries(Carbon $start, Carbon $end): array
{
$return = [];
$format = app('navigation')->preferredCarbonLocalizedFormat($start, $end);
$preferredRange = app('navigation')->preferredRangeFormat($start, $end);
$currentStart = clone $start;
while ($currentStart <= $end) {
$currentEnd = app('navigation')->endOfPeriod($currentStart, $preferredRange);
$key = $currentStart->isoFormat($format);
$return[$key] = '0';
$currentStart = clone $currentEnd;
$currentStart->addDay()->startOfDay();
}
return $return;
}
}

View File

@@ -37,8 +37,8 @@ use FireflyIII\Support\Http\Controllers\BasicDataSupport;
use FireflyIII\Support\Http\Controllers\ChartGeneration;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Collection;
use JsonException;
use Illuminate\Support\Facades\Log;
use JsonException;
/**
* Class ReportController.

View File

@@ -324,31 +324,6 @@ class TagReportController extends Controller
return response()->json($data);
}
/**
* TODO duplicate function
*
* @param Carbon $start
* @param Carbon $end
*
* @return array
*/
private function makeEntries(Carbon $start, Carbon $end): array
{
$return = [];
$format = app('navigation')->preferredCarbonLocalizedFormat($start, $end);
$preferredRange = app('navigation')->preferredRangeFormat($start, $end);
$currentStart = clone $start;
while ($currentStart <= $end) {
$currentEnd = app('navigation')->endOfPeriod($currentStart, $preferredRange);
$key = $currentStart->isoFormat($format);
$return[$key] = '0';
$currentStart = clone $currentEnd;
$currentStart->addDay()->startOfDay();
}
return $return;
}
/**
* @param Collection $accounts
* @param Collection $tags
@@ -488,4 +463,29 @@ class TagReportController extends Controller
return response()->json($data);
}
/**
* TODO duplicate function
*
* @param Carbon $start
* @param Carbon $end
*
* @return array
*/
private function makeEntries(Carbon $start, Carbon $end): array
{
$return = [];
$format = app('navigation')->preferredCarbonLocalizedFormat($start, $end);
$preferredRange = app('navigation')->preferredRangeFormat($start, $end);
$currentStart = clone $start;
while ($currentStart <= $end) {
$currentEnd = app('navigation')->endOfPeriod($currentStart, $preferredRange);
$key = $currentStart->isoFormat($format);
$return[$key] = '0';
$currentStart = clone $currentEnd;
$currentStart->addDay()->startOfDay();
}
return $return;
}
}

View File

@@ -35,8 +35,8 @@ use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Routing\Redirector;
use Illuminate\View\View;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

View File

@@ -69,14 +69,14 @@ class HomeController extends Controller
{
try {
$stringStart = e((string)$request->get('start'));
$start = Carbon::createFromFormat('Y-m-d', $stringStart);
$start = Carbon::createFromFormat('Y-m-d', $stringStart);
} catch (InvalidFormatException $e) {
Log::error(sprintf('Start: could not parse date string "%s" so ignore it.', $stringStart));
$start = Carbon::now()->startOfMonth();
}
try {
$stringEnd = e((string)$request->get('end'));
$end = Carbon::createFromFormat('Y-m-d', $stringEnd);
$end = Carbon::createFromFormat('Y-m-d', $stringEnd);
} catch (InvalidFormatException $e) {
Log::error(sprintf('End could not parse date string "%s" so ignore it.', $stringEnd));
$end = Carbon::now()->endOfMonth();

View File

@@ -34,8 +34,8 @@ use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use JsonException;
use Illuminate\Support\Facades\Log;
use JsonException;
use Throwable;
/**
@@ -169,46 +169,6 @@ class ReconcileController extends Controller
return response()->json($return);
}
/**
* @param Account $account
* @param TransactionCurrency $currency
* @param array $journal
* @param string $amount
*
* @return string
*/
private function processJournal(Account $account, TransactionCurrency $currency, array $journal, string $amount): string
{
$toAdd = '0';
Log::debug(sprintf('User submitted %s #%d: "%s"', $journal['transaction_type_type'], $journal['transaction_journal_id'], $journal['description']));
// not much magic below we need to cover using tests.
if ($account->id === $journal['source_account_id']) {
if ($currency->id === $journal['currency_id']) {
$toAdd = $journal['amount'];
}
if (null !== $journal['foreign_currency_id'] && $journal['foreign_currency_id'] === $currency->id) {
$toAdd = $journal['foreign_amount'];
}
}
if ($account->id === $journal['destination_account_id']) {
if ($currency->id === $journal['currency_id']) {
$toAdd = bcmul($journal['amount'], '-1');
}
if (null !== $journal['foreign_currency_id'] && $journal['foreign_currency_id'] === $currency->id) {
$toAdd = bcmul($journal['foreign_amount'], '-1');
}
}
Log::debug(sprintf('Going to add %s to %s', $toAdd, $amount));
$amount = bcadd($amount, $toAdd);
Log::debug(sprintf('Result is %s', $amount));
return $amount;
}
/**
* Returns a list of transactions in a modal.
*
@@ -265,6 +225,46 @@ class ReconcileController extends Controller
return response()->json(['html' => $html, 'startBalance' => $startBalance, 'endBalance' => $endBalance]);
}
/**
* @param Account $account
* @param TransactionCurrency $currency
* @param array $journal
* @param string $amount
*
* @return string
*/
private function processJournal(Account $account, TransactionCurrency $currency, array $journal, string $amount): string
{
$toAdd = '0';
Log::debug(sprintf('User submitted %s #%d: "%s"', $journal['transaction_type_type'], $journal['transaction_journal_id'], $journal['description']));
// not much magic below we need to cover using tests.
if ($account->id === $journal['source_account_id']) {
if ($currency->id === $journal['currency_id']) {
$toAdd = $journal['amount'];
}
if (null !== $journal['foreign_currency_id'] && $journal['foreign_currency_id'] === $currency->id) {
$toAdd = $journal['foreign_amount'];
}
}
if ($account->id === $journal['destination_account_id']) {
if ($currency->id === $journal['currency_id']) {
$toAdd = bcmul($journal['amount'], '-1');
}
if (null !== $journal['foreign_currency_id'] && $journal['foreign_currency_id'] === $currency->id) {
$toAdd = bcmul($journal['foreign_amount'], '-1');
}
}
Log::debug(sprintf('Going to add %s to %s', $toAdd, $amount));
$amount = bcadd($amount, $toAdd);
Log::debug(sprintf('Result is %s', $amount));
return $amount;
}
/**
* "fix" amounts to make it easier on the reconciliation overview:
*

View File

@@ -32,8 +32,8 @@ use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
/**
* Class AmountController

View File

@@ -144,6 +144,29 @@ class IndexController extends Controller
return view('piggy-banks.index', compact('piggyBanks', 'accounts'));
}
/**
* Set the order of a piggy bank.
*
* @param Request $request
* @param PiggyBank $piggyBank
*
* @return JsonResponse
*/
public function setOrder(Request $request, PiggyBank $piggyBank): JsonResponse
{
$objectGroupTitle = (string)$request->get('objectGroupTitle');
$newOrder = (int)$request->get('order');
$this->piggyRepos->setOrder($piggyBank, $newOrder);
if ('' !== $objectGroupTitle) {
$this->piggyRepos->setObjectGroup($piggyBank, $objectGroupTitle);
}
if ('' === $objectGroupTitle) {
$this->piggyRepos->removeObjectGroup($piggyBank);
}
return response()->json(['data' => 'OK']);
}
/**
* @param array $piggyBanks
*
@@ -183,27 +206,4 @@ class IndexController extends Controller
return $piggyBanks;
}
/**
* Set the order of a piggy bank.
*
* @param Request $request
* @param PiggyBank $piggyBank
*
* @return JsonResponse
*/
public function setOrder(Request $request, PiggyBank $piggyBank): JsonResponse
{
$objectGroupTitle = (string)$request->get('objectGroupTitle');
$newOrder = (int)$request->get('order');
$this->piggyRepos->setOrder($piggyBank, $newOrder);
if ('' !== $objectGroupTitle) {
$this->piggyRepos->setObjectGroup($piggyBank, $objectGroupTitle);
}
if ('' === $objectGroupTitle) {
$this->piggyRepos->removeObjectGroup($piggyBank);
}
return response()->json(['data' => 'OK']);
}
}

View File

@@ -262,7 +262,7 @@ class PreferencesController extends Controller
// dark mode
$darkMode = $request->get('darkMode') ?? 'browser';
if(in_array($darkMode, config('firefly.available_dark_modes'), true)) {
if (in_array($darkMode, config('firefly.available_dark_modes'), true)) {
app('preferences')->set('darkMode', $darkMode);
}

View File

@@ -49,9 +49,9 @@ use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
use Laravel\Passport\ClientRepository;
use Illuminate\Support\Facades\Log;
use PragmaRX\Google2FA\Exceptions\IncompatibleWithGoogleAuthenticatorException;
use PragmaRX\Google2FA\Exceptions\InvalidCharactersException;
use PragmaRX\Google2FA\Exceptions\SecretKeyTooShortException;
@@ -98,6 +98,51 @@ class ProfileController extends Controller
$this->middleware(IsDemoUser::class)->except(['index']);
}
/**
* Change your email address.
*
* @param Request $request
*
* @return Factory|RedirectResponse|View
*/
public function changeEmail(Request $request): Factory|RedirectResponse|View
{
if (!$this->internalAuth || !$this->internalIdentity) {
$request->session()->flash('error', trans('firefly.external_user_mgt_disabled'));
return redirect(route('profile.index'));
}
$title = auth()->user()->email;
$email = auth()->user()->email;
$subTitle = (string)trans('firefly.change_your_email');
$subTitleIcon = 'fa-envelope';
return view('profile.change-email', compact('title', 'subTitle', 'subTitleIcon', 'email'));
}
/**
* Change your password.
*
* @param Request $request
*
* @return Factory|RedirectResponse|Redirector|View
*/
public function changePassword(Request $request)
{
if (!$this->internalAuth || !$this->internalIdentity) {
$request->session()->flash('error', trans('firefly.external_user_mgt_disabled'));
return redirect(route('profile.index'));
}
$title = auth()->user()->email;
$subTitle = (string)trans('firefly.change_your_password');
$subTitleIcon = 'fa-key';
return view('profile.change-password', compact('title', 'subTitle', 'subTitleIcon'));
}
/**
* View that generates a 2FA code for the user.
*
@@ -401,29 +446,6 @@ class ProfileController extends Controller
return redirect(route('index'));
}
/**
* Change your email address.
*
* @param Request $request
*
* @return Factory|RedirectResponse|View
*/
public function changeEmail(Request $request): Factory|RedirectResponse|View
{
if (!$this->internalAuth || !$this->internalIdentity) {
$request->session()->flash('error', trans('firefly.external_user_mgt_disabled'));
return redirect(route('profile.index'));
}
$title = auth()->user()->email;
$email = auth()->user()->email;
$subTitle = (string)trans('firefly.change_your_email');
$subTitleIcon = 'fa-envelope';
return view('profile.change-email', compact('title', 'subTitle', 'subTitleIcon', 'email'));
}
/**
* Submit change password form.
*
@@ -459,28 +481,6 @@ class ProfileController extends Controller
return redirect(route('profile.index'));
}
/**
* Change your password.
*
* @param Request $request
*
* @return Factory|RedirectResponse|Redirector|View
*/
public function changePassword(Request $request)
{
if (!$this->internalAuth || !$this->internalIdentity) {
$request->session()->flash('error', trans('firefly.external_user_mgt_disabled'));
return redirect(route('profile.index'));
}
$title = auth()->user()->email;
$subTitle = (string)trans('firefly.change_your_password');
$subTitleIcon = 'fa-key';
return view('profile.change-password', compact('title', 'subTitle', 'subTitleIcon'));
}
/**
* Submit 2FA for the first time.
*
@@ -531,51 +531,6 @@ class ProfileController extends Controller
return redirect(route('profile.index'));
}
/**
* TODO duplicate code.
*
* @param string $mfaCode
*
* @throws FireflyException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
private function addToMFAHistory(string $mfaCode): void
{
/** @var array $mfaHistory */
$mfaHistory = app('preferences')->get('mfa_history', [])->data;
$entry = [
'time' => time(),
'code' => $mfaCode,
];
$mfaHistory[] = $entry;
app('preferences')->set('mfa_history', $mfaHistory);
$this->filterMFAHistory();
}
/**
* Remove old entries from the preferences array.
*/
private function filterMFAHistory(): void
{
/** @var array $mfaHistory */
$mfaHistory = app('preferences')->get('mfa_history', [])->data;
$newHistory = [];
$now = time();
foreach ($mfaHistory as $entry) {
$time = $entry['time'];
$code = $entry['code'];
if ($now - $time <= 300) {
$newHistory[] = [
'time' => $time,
'code' => $code,
];
}
}
app('preferences')->set('mfa_history', $newHistory);
}
/**
* Submit delete account.
*
@@ -715,4 +670,49 @@ class ProfileController extends Controller
return redirect(route('login'));
}
/**
* TODO duplicate code.
*
* @param string $mfaCode
*
* @throws FireflyException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
private function addToMFAHistory(string $mfaCode): void
{
/** @var array $mfaHistory */
$mfaHistory = app('preferences')->get('mfa_history', [])->data;
$entry = [
'time' => time(),
'code' => $mfaCode,
];
$mfaHistory[] = $entry;
app('preferences')->set('mfa_history', $mfaHistory);
$this->filterMFAHistory();
}
/**
* Remove old entries from the preferences array.
*/
private function filterMFAHistory(): void
{
/** @var array $mfaHistory */
$mfaHistory = app('preferences')->get('mfa_history', [])->data;
$newHistory = [];
$now = time();
foreach ($mfaHistory as $entry) {
$time = $entry['time'];
$code = $entry['code'];
if ($now - $time <= 300) {
$newHistory[] = [
'time' => $time,
'code' => $code,
];
}
}
app('preferences')->set('mfa_history', $newHistory);
}
}

View File

@@ -34,9 +34,9 @@ use FireflyIII\Support\Http\Controllers\BasicDataSupport;
use FireflyIII\Support\Report\Budget\BudgetReportGenerator;
use Illuminate\Contracts\View\Factory;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
use JsonException;
use Illuminate\Support\Facades\Log;
use Throwable;
/**

View File

@@ -35,8 +35,8 @@ use FireflyIII\Support\Http\Controllers\BasicDataSupport;
use FireflyIII\Support\Report\Category\CategoryReportGenerator;
use Illuminate\Contracts\View\Factory;
use Illuminate\Support\Collection;
use Illuminate\View\View;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
use Throwable;
/**

View File

@@ -32,8 +32,8 @@ use FireflyIII\Repositories\Account\OperationsRepositoryInterface;
use FireflyIII\Support\Http\Controllers\AugumentData;
use Illuminate\Contracts\View\Factory;
use Illuminate\Support\Collection;
use Illuminate\View\View;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
use Throwable;
/**
@@ -295,31 +295,6 @@ class DoubleController extends Controller
return view('reports.double.partials.accounts', compact('sums', 'report'));
}
/**
* TODO this method is duplicated.
*
* @param Collection $accounts
* @param int $id
* @param string $name
* @param string|null $iban
*
* @return string
*/
private function getCounterpartName(Collection $accounts, int $id, string $name, ?string $iban): string
{
/** @var Account $account */
foreach ($accounts as $account) {
if ($account->name === $name && $account->id !== $id) {
return $account->name;
}
if (null !== $account->iban && $account->iban === $iban && $account->id !== $id) {
return $account->iban;
}
}
return $name;
}
/**
* @param Collection $accounts
* @param Collection $double
@@ -521,4 +496,29 @@ class DoubleController extends Controller
return $result;
}
/**
* TODO this method is duplicated.
*
* @param Collection $accounts
* @param int $id
* @param string $name
* @param string|null $iban
*
* @return string
*/
private function getCounterpartName(Collection $accounts, int $id, string $name, ?string $iban): string
{
/** @var Account $account */
foreach ($accounts as $account) {
if ($account->name === $name && $account->id !== $id) {
return $account->name;
}
if (null !== $account->iban && $account->iban === $iban && $account->id !== $id) {
return $account->iban;
}
}
return $name;
}
}

View File

@@ -31,8 +31,8 @@ use FireflyIII\Models\Tag;
use FireflyIII\Repositories\Tag\OperationsRepositoryInterface;
use Illuminate\Contracts\View\Factory;
use Illuminate\Support\Collection;
use Illuminate\View\View;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
use Throwable;
/**

View File

@@ -38,8 +38,8 @@ use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Collection;
use Illuminate\View\View;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

View File

@@ -36,8 +36,8 @@ use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\View\View;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
use Throwable;
/**
@@ -139,6 +139,32 @@ class EditController extends Controller
return view('rules.rule.edit', compact('rule', 'subTitle', 'primaryTrigger', 'oldTriggers', 'oldActions', 'triggerCount', 'actionCount'));
}
/**
* Update the rule.
*
* @param RuleFormRequest $request
* @param Rule $rule
*
* @return RedirectResponse|Redirector
*/
public function update(RuleFormRequest $request, Rule $rule)
{
$data = $request->getRuleData();
$this->ruleRepos->update($rule, $data);
session()->flash('success', (string)trans('firefly.updated_rule', ['title' => $rule->title]));
app('preferences')->mark();
$redirect = redirect($this->getPreviousUrl('rules.edit.url'));
if (1 === (int)$request->get('return_to_edit')) {
session()->put('rules.edit.fromUpdate', true);
$redirect = redirect(route('rules.edit', [$rule->id]))->withInput(['return_to_edit' => 1]);
}
return $redirect;
}
/**
* @param array $submittedOperators
*
@@ -182,30 +208,4 @@ class EditController extends Controller
return $renderedEntries;
}
/**
* Update the rule.
*
* @param RuleFormRequest $request
* @param Rule $rule
*
* @return RedirectResponse|Redirector
*/
public function update(RuleFormRequest $request, Rule $rule)
{
$data = $request->getRuleData();
$this->ruleRepos->update($rule, $data);
session()->flash('success', (string)trans('firefly.updated_rule', ['title' => $rule->title]));
app('preferences')->mark();
$redirect = redirect($this->getPreviousUrl('rules.edit.url'));
if (1 === (int)$request->get('return_to_edit')) {
session()->put('rules.edit.fromUpdate', true);
$redirect = redirect(route('rules.edit', [$rule->id]))->withInput(['return_to_edit' => 1]);
}
return $redirect;
}
}

View File

@@ -29,8 +29,8 @@ use FireflyIII\Support\Search\SearchInterface;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
use Throwable;
/**

View File

@@ -23,8 +23,8 @@ declare(strict_types=1);
namespace FireflyIII\Http\Controllers\System;
use FireflyIII\User;
use FireflyIII\Http\Controllers\Controller;
use FireflyIII\User;
use Illuminate\Http\Response;
/**

View File

@@ -91,6 +91,30 @@ class InstallController extends Controller
return view('install.index');
}
/**
* Create specific RSA keys.
*/
public function keys(): void
{
// switch on PHP version.
$keys = [];
// switch on class existence.
Log::info('Will run PHP8 code.');
$keys = RSA::createKey(4096);
[$publicKey, $privateKey] = [
Passport::keyPath('oauth-public.key'),
Passport::keyPath('oauth-private.key'),
];
if (file_exists($publicKey) || file_exists($privateKey)) {
return;
}
file_put_contents($publicKey, $keys['publickey']);
file_put_contents($privateKey, $keys['privatekey']);
}
/**
* @param Request $request
*
@@ -161,28 +185,4 @@ class InstallController extends Controller
return true;
}
/**
* Create specific RSA keys.
*/
public function keys(): void
{
// switch on PHP version.
$keys = [];
// switch on class existence.
Log::info('Will run PHP8 code.');
$keys = RSA::createKey(4096);
[$publicKey, $privateKey] = [
Passport::keyPath('oauth-public.key'),
Passport::keyPath('oauth-private.key'),
];
if (file_exists($publicKey) || file_exists($privateKey)) {
return;
}
file_put_contents($publicKey, $keys['publickey']);
file_put_contents($privateKey, $keys['privatekey']);
}
}

View File

@@ -34,8 +34,8 @@ use FireflyIII\Support\Http\Controllers\PeriodOverview;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
@@ -117,6 +117,24 @@ class TagController extends Controller
return view('tags.delete', compact('tag', 'subTitle'));
}
/**
* Destroy a tag.
*
* @param Tag $tag
*
* @return RedirectResponse
*/
public function destroy(Tag $tag): RedirectResponse
{
$tagName = $tag->tag;
$this->repository->destroy($tag);
session()->flash('success', (string)trans('firefly.deleted_tag', ['tag' => $tagName]));
app('preferences')->mark();
return redirect($this->getPreviousUrl('tags.delete.url'));
}
/**
* Edit a tag.
*
@@ -205,24 +223,6 @@ class TagController extends Controller
return redirect(route('tags.index'));
}
/**
* Destroy a tag.
*
* @param Tag $tag
*
* @return RedirectResponse
*/
public function destroy(Tag $tag): RedirectResponse
{
$tagName = $tag->tag;
$this->repository->destroy($tag);
session()->flash('success', (string)trans('firefly.deleted_tag', ['tag' => $tagName]));
app('preferences')->mark();
return redirect($this->getPreviousUrl('tags.delete.url'));
}
/**
* Show a single tag.
*

View File

@@ -34,8 +34,8 @@ use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Collection;
use Illuminate\View\View;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
/**
* Class BulkController
@@ -152,6 +152,24 @@ class BulkController extends Controller
return true;
}
/**
* @param TransactionJournal $journal
* @param bool $ignoreUpdate
* @param string $category
*
* @return bool
*/
private function updateJournalCategory(TransactionJournal $journal, bool $ignoreUpdate, string $category): bool
{
if (true === $ignoreUpdate) {
return false;
}
Log::debug(sprintf('Set budget to %s', $category));
$this->repository->updateCategory($journal, $category);
return true;
}
/**
* @param TransactionJournal $journal
* @param string $action
@@ -173,22 +191,4 @@ class BulkController extends Controller
return true;
}
/**
* @param TransactionJournal $journal
* @param bool $ignoreUpdate
* @param string $category
*
* @return bool
*/
private function updateJournalCategory(TransactionJournal $journal, bool $ignoreUpdate, string $category): bool
{
if (true === $ignoreUpdate) {
return false;
}
Log::debug(sprintf('Set budget to %s', $category));
$this->repository->updateCategory($journal, $category);
return true;
}
}

View File

@@ -42,8 +42,8 @@ use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\View\View;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
/**
* Class ConvertController.
@@ -144,133 +144,6 @@ class ConvertController extends Controller
);
}
/**
* @return array
*/
private function getValidDepositSources(): array
{
// make repositories
$liabilityTypes = [AccountType::MORTGAGE, AccountType::DEBT, AccountType::CREDITCARD, AccountType::LOAN];
$accountList = $this->accountRepository
->getActiveAccountsByType([AccountType::REVENUE, AccountType::CASH, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]);
$grouped = [];
// group accounts:
/** @var Account $account */
foreach ($accountList as $account) {
$role = (string)$this->accountRepository->getMetaValue($account, 'account_role');
$name = $account->name;
if ('' === $role) {
$role = 'no_account_type';
}
// maybe it's a liability thing:
if (in_array($account->accountType->type, $liabilityTypes, true)) {
$role = 'l_'.$account->accountType->type;
}
if (AccountType::CASH === $account->accountType->type) {
$role = 'cash_account';
$name = sprintf('(%s)', trans('firefly.cash'));
}
if (AccountType::REVENUE === $account->accountType->type) {
$role = 'revenue_account';
}
$key = (string)trans('firefly.opt_group_'.$role);
$grouped[$key][$account->id] = $name;
}
return $grouped;
}
/**
* @return array
*/
private function getValidWithdrawalDests(): array
{
// make repositories
$liabilityTypes = [AccountType::MORTGAGE, AccountType::DEBT, AccountType::CREDITCARD, AccountType::LOAN];
$accountList = $this->accountRepository->getActiveAccountsByType(
[AccountType::EXPENSE, AccountType::CASH, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]
);
$grouped = [];
// group accounts:
/** @var Account $account */
foreach ($accountList as $account) {
$role = (string)$this->accountRepository->getMetaValue($account, 'account_role');
$name = $account->name;
if ('' === $role) {
$role = 'no_account_type';
}
// maybe it's a liability thing:
if (in_array($account->accountType->type, $liabilityTypes, true)) {
$role = 'l_'.$account->accountType->type;
}
if (AccountType::CASH === $account->accountType->type) {
$role = 'cash_account';
$name = sprintf('(%s)', trans('firefly.cash'));
}
if (AccountType::EXPENSE === $account->accountType->type) {
$role = 'expense_account';
}
$key = (string)trans('firefly.opt_group_'.$role);
$grouped[$key][$account->id] = $name;
}
return $grouped;
}
/**
* @return array
* @throws Exception
*/
private function getLiabilities(): array
{
// make repositories
$accountList = $this->accountRepository->getActiveAccountsByType([AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]);
$defaultCurrency = app('amount')->getDefaultCurrency();
$grouped = [];
// group accounts:
/** @var Account $account */
foreach ($accountList as $account) {
$balance = app('steam')->balance($account, today());
$currency = $this->accountRepository->getAccountCurrency($account) ?? $defaultCurrency;
$role = 'l_'.$account->accountType->type;
$key = (string)trans('firefly.opt_group_'.$role);
$grouped[$key][$account->id] = $account->name.' ('.app('amount')->formatAnything($currency, $balance, false).')';
}
return $grouped;
}
/**
* @return array
* @throws Exception
*/
private function getAssetAccounts(): array
{
// make repositories
$accountList = $this->accountRepository->getActiveAccountsByType([AccountType::ASSET]);
$defaultCurrency = app('amount')->getDefaultCurrency();
$grouped = [];
// group accounts:
/** @var Account $account */
foreach ($accountList as $account) {
$balance = app('steam')->balance($account, today());
$currency = $this->accountRepository->getAccountCurrency($account) ?? $defaultCurrency;
$role = (string)$this->accountRepository->getMetaValue($account, 'account_role');
if ('' === $role) {
$role = 'no_account_type';
}
$key = (string)trans('firefly.opt_group_'.$role);
$grouped[$key][$account->id] = $account->name.' ('.app('amount')->formatAnything($currency, $balance, false).')';
}
return $grouped;
}
/**
* Do the conversion.
*
@@ -361,4 +234,131 @@ class ConvertController extends Controller
return $journal;
}
/**
* @return array
* @throws Exception
*/
private function getAssetAccounts(): array
{
// make repositories
$accountList = $this->accountRepository->getActiveAccountsByType([AccountType::ASSET]);
$defaultCurrency = app('amount')->getDefaultCurrency();
$grouped = [];
// group accounts:
/** @var Account $account */
foreach ($accountList as $account) {
$balance = app('steam')->balance($account, today());
$currency = $this->accountRepository->getAccountCurrency($account) ?? $defaultCurrency;
$role = (string)$this->accountRepository->getMetaValue($account, 'account_role');
if ('' === $role) {
$role = 'no_account_type';
}
$key = (string)trans('firefly.opt_group_'.$role);
$grouped[$key][$account->id] = $account->name.' ('.app('amount')->formatAnything($currency, $balance, false).')';
}
return $grouped;
}
/**
* @return array
* @throws Exception
*/
private function getLiabilities(): array
{
// make repositories
$accountList = $this->accountRepository->getActiveAccountsByType([AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]);
$defaultCurrency = app('amount')->getDefaultCurrency();
$grouped = [];
// group accounts:
/** @var Account $account */
foreach ($accountList as $account) {
$balance = app('steam')->balance($account, today());
$currency = $this->accountRepository->getAccountCurrency($account) ?? $defaultCurrency;
$role = 'l_'.$account->accountType->type;
$key = (string)trans('firefly.opt_group_'.$role);
$grouped[$key][$account->id] = $account->name.' ('.app('amount')->formatAnything($currency, $balance, false).')';
}
return $grouped;
}
/**
* @return array
*/
private function getValidDepositSources(): array
{
// make repositories
$liabilityTypes = [AccountType::MORTGAGE, AccountType::DEBT, AccountType::CREDITCARD, AccountType::LOAN];
$accountList = $this->accountRepository
->getActiveAccountsByType([AccountType::REVENUE, AccountType::CASH, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]);
$grouped = [];
// group accounts:
/** @var Account $account */
foreach ($accountList as $account) {
$role = (string)$this->accountRepository->getMetaValue($account, 'account_role');
$name = $account->name;
if ('' === $role) {
$role = 'no_account_type';
}
// maybe it's a liability thing:
if (in_array($account->accountType->type, $liabilityTypes, true)) {
$role = 'l_'.$account->accountType->type;
}
if (AccountType::CASH === $account->accountType->type) {
$role = 'cash_account';
$name = sprintf('(%s)', trans('firefly.cash'));
}
if (AccountType::REVENUE === $account->accountType->type) {
$role = 'revenue_account';
}
$key = (string)trans('firefly.opt_group_'.$role);
$grouped[$key][$account->id] = $name;
}
return $grouped;
}
/**
* @return array
*/
private function getValidWithdrawalDests(): array
{
// make repositories
$liabilityTypes = [AccountType::MORTGAGE, AccountType::DEBT, AccountType::CREDITCARD, AccountType::LOAN];
$accountList = $this->accountRepository->getActiveAccountsByType(
[AccountType::EXPENSE, AccountType::CASH, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE]
);
$grouped = [];
// group accounts:
/** @var Account $account */
foreach ($accountList as $account) {
$role = (string)$this->accountRepository->getMetaValue($account, 'account_role');
$name = $account->name;
if ('' === $role) {
$role = 'no_account_type';
}
// maybe it's a liability thing:
if (in_array($account->accountType->type, $liabilityTypes, true)) {
$role = 'l_'.$account->accountType->type;
}
if (AccountType::CASH === $account->accountType->type) {
$role = 'cash_account';
$name = sprintf('(%s)', trans('firefly.cash'));
}
if (AccountType::EXPENSE === $account->accountType->type) {
$role = 'expense_account';
}
$key = (string)trans('firefly.opt_group_'.$role);
$grouped[$key][$account->id] = $name;
}
return $grouped;
}
}

View File

@@ -33,8 +33,8 @@ use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\View\View;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View;
/**
* Class LinkController.

View File

@@ -39,9 +39,9 @@ use FireflyIII\Services\Internal\Update\JournalUpdateService;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Http\RedirectResponse;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Facades\Log;
use Illuminate\View\View as IlluminateView;
use InvalidArgumentException;
use Illuminate\Support\Facades\Log;
/**
* Class MassController.
@@ -196,6 +196,73 @@ class MassController extends Controller
return redirect($this->getPreviousUrl('transactions.mass-edit.url'));
}
/**
* @param MassEditJournalRequest $request
* @param int $journalId
* @param string $key
*
* @return Carbon|null
*/
private function getDateFromRequest(MassEditJournalRequest $request, int $journalId, string $key): ?Carbon
{
$value = $request->get($key);
if (!is_array($value)) {
return null;
}
if (!array_key_exists($journalId, $value)) {
return null;
}
try {
$carbon = Carbon::parse($value[$journalId]);
} catch (InvalidArgumentException $e) {
$e->getMessage();
return null;
}
return $carbon;
}
/**
* @param MassEditJournalRequest $request
* @param int $journalId
* @param string $string
*
* @return int|null
*/
private function getIntFromRequest(MassEditJournalRequest $request, int $journalId, string $string): ?int
{
$value = $request->get($string);
if (!is_array($value)) {
return null;
}
if (!array_key_exists($journalId, $value)) {
return null;
}
return (int)$value[$journalId];
}
/**
* @param MassEditJournalRequest $request
* @param int $journalId
* @param string $string
*
* @return string|null
*/
private function getStringFromRequest(MassEditJournalRequest $request, int $journalId, string $string): ?string
{
$value = $request->get($string);
if (!is_array($value)) {
return null;
}
if (!array_key_exists($journalId, $value)) {
return null;
}
return (string)$value[$journalId];
}
/**
* @param int $journalId
* @param MassEditJournalRequest $request
@@ -232,71 +299,4 @@ class MassController extends Controller
// trigger rules
event(new UpdatedTransactionGroup($journal->transactionGroup, true, true));
}
/**
* @param MassEditJournalRequest $request
* @param int $journalId
* @param string $key
*
* @return Carbon|null
*/
private function getDateFromRequest(MassEditJournalRequest $request, int $journalId, string $key): ?Carbon
{
$value = $request->get($key);
if (!is_array($value)) {
return null;
}
if (!array_key_exists($journalId, $value)) {
return null;
}
try {
$carbon = Carbon::parse($value[$journalId]);
} catch (InvalidArgumentException $e) {
$e->getMessage();
return null;
}
return $carbon;
}
/**
* @param MassEditJournalRequest $request
* @param int $journalId
* @param string $string
*
* @return string|null
*/
private function getStringFromRequest(MassEditJournalRequest $request, int $journalId, string $string): ?string
{
$value = $request->get($string);
if (!is_array($value)) {
return null;
}
if (!array_key_exists($journalId, $value)) {
return null;
}
return (string)$value[$journalId];
}
/**
* @param MassEditJournalRequest $request
* @param int $journalId
* @param string $string
*
* @return int|null
*/
private function getIntFromRequest(MassEditJournalRequest $request, int $journalId, string $string): ?int
{
$value = $request->get($string);
if (!is_array($value)) {
return null;
}
if (!array_key_exists($journalId, $value)) {
return null;
}
return (int)$value[$journalId];
}
}

View File

@@ -139,6 +139,36 @@ class ShowController extends Controller
);
}
/**
* @param array $group
*
* @return array
*/
private function getAccounts(array $group): array
{
$accounts = [];
foreach ($group['transactions'] as $transaction) {
$accounts['source'][] = [
'type' => $transaction['source_type'],
'id' => $transaction['source_id'],
'name' => $transaction['source_name'],
'iban' => $transaction['source_iban'],
];
$accounts['destination'][] = [
'type' => $transaction['destination_type'],
'id' => $transaction['destination_id'],
'name' => $transaction['destination_name'],
'iban' => $transaction['destination_iban'],
];
}
$accounts['source'] = array_unique($accounts['source'], SORT_REGULAR);
$accounts['destination'] = array_unique($accounts['destination'], SORT_REGULAR);
return $accounts;
}
/**
* @param array $group
*
@@ -173,34 +203,4 @@ class ShowController extends Controller
return $amounts;
}
/**
* @param array $group
*
* @return array
*/
private function getAccounts(array $group): array
{
$accounts = [];
foreach ($group['transactions'] as $transaction) {
$accounts['source'][] = [
'type' => $transaction['source_type'],
'id' => $transaction['source_id'],
'name' => $transaction['source_name'],
'iban' => $transaction['source_iban'],
];
$accounts['destination'][] = [
'type' => $transaction['destination_type'],
'id' => $transaction['destination_id'],
'name' => $transaction['destination_name'],
'iban' => $transaction['destination_iban'],
];
}
$accounts['source'] = array_unique($accounts['source'], SORT_REGULAR);
$accounts['destination'] = array_unique($accounts['destination'], SORT_REGULAR);
return $accounts;
}
}