firefly-iii/app/Http/Controllers/CurrencyController.php
2023-02-22 18:03:31 +01:00

434 lines
16 KiB
PHP

<?php
/**
* CurrencyController.php
* Copyright (c) 2019 james@firefly-iii.org
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace FireflyIII\Http\Controllers;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Http\Requests\CurrencyFormRequest;
use FireflyIII\Models\TransactionCurrency;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\User;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Routing\Redirector;
use Illuminate\View\View;
use Log;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
/**
* Class CurrencyController.
*/
class CurrencyController extends Controller
{
protected CurrencyRepositoryInterface $repository;
protected UserRepositoryInterface $userRepository;
/**
* CurrencyController constructor.
*
*/
public function __construct()
{
parent::__construct();
$this->middleware(
function ($request, $next) {
app('view')->share('title', (string)trans('firefly.currencies'));
app('view')->share('mainTitleIcon', 'fa-usd');
$this->repository = app(CurrencyRepositoryInterface::class);
$this->userRepository = app(UserRepositoryInterface::class);
return $next($request);
}
);
}
/**
* Create a currency.
*
* @param Request $request
*
* @return Factory|RedirectResponse|Redirector|View
*/
public function create(Request $request)
{
/** @var User $user */
$user = auth()->user();
if (!$this->userRepository->hasRole($user, 'owner')) {
$request->session()->flash('error', (string)trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))]));
return redirect(route('currencies.index'));
}
$subTitleIcon = 'fa-plus';
$subTitle = (string)trans('firefly.create_currency');
// put previous url in session if not redirect from store (not "create another").
if (true !== session('currencies.create.fromStore')) {
$this->rememberPreviousUrl('currencies.create.url');
}
$request->session()->forget('currencies.create.fromStore');
Log::channel('audit')->info('Create new currency.');
return view('currencies.create', compact('subTitleIcon', 'subTitle'));
}
/**
* Make currency the default currency.
*
* @param Request $request
*
* @return RedirectResponse|Redirector
* @throws FireflyException
*/
public function defaultCurrency(Request $request)
{
$currencyId = (int)$request->get('id');
if ($currencyId > 0) {
// valid currency?
$currency = $this->repository->find($currencyId);
if (null !== $currency) {
app('preferences')->set('currencyPreference', $currency->code);
app('preferences')->mark();
Log::channel('audit')->info(sprintf('Make %s the default currency.', $currency->code));
$this->repository->enable($currency);
$request->session()->flash('success', (string)trans('firefly.new_default_currency', ['name' => $currency->name]));
return redirect(route('currencies.index'));
}
}
return redirect(route('currencies.index'));
}
/**
* Deletes a currency.
*
* @param Request $request
* @param TransactionCurrency $currency
*
* @return Factory|RedirectResponse|Redirector|View
*/
public function delete(Request $request, TransactionCurrency $currency)
{
/** @var User $user */
$user = auth()->user();
if (!$this->userRepository->hasRole($user, 'owner')) {
$request->session()->flash('error', (string)trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))]));
Log::channel('audit')->info(sprintf('Tried to visit page to delete currency %s but is not site owner.', $currency->code));
return redirect(route('currencies.index'));
}
if ($this->repository->currencyInUse($currency)) {
$location = $this->repository->currencyInUseAt($currency);
$message = (string)trans(sprintf('firefly.cannot_disable_currency_%s', $location), ['name' => e($currency->name)]);
$request->session()->flash('error', $message);
Log::channel('audit')->info(sprintf('Tried to visit page to delete currency %s but currency is in use.', $currency->code));
return redirect(route('currencies.index'));
}
// put previous url in session
$this->rememberPreviousUrl('currencies.delete.url');
$subTitle = (string)trans('form.delete_currency', ['name' => $currency->name]);
Log::channel('audit')->info(sprintf('Visit page to delete currency %s.', $currency->code));
return view('currencies.delete', compact('currency', 'subTitle'));
}
/**
* Destroys a currency.
*
* @param Request $request
* @param TransactionCurrency $currency
*
* @return RedirectResponse|Redirector
*/
public function destroy(Request $request, TransactionCurrency $currency)
{
/** @var User $user */
$user = auth()->user();
if (!$this->userRepository->hasRole($user, 'owner')) {
$request->session()->flash('error', (string)trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))]));
Log::channel('audit')->info(sprintf('Tried to delete currency %s but is not site owner.', $currency->code));
return redirect(route('currencies.index'));
}
if ($this->repository->currencyInUse($currency)) {
$request->session()->flash('error', (string)trans('firefly.cannot_delete_currency', ['name' => e($currency->name)]));
Log::channel('audit')->info(sprintf('Tried to delete currency %s but is in use.', $currency->code));
return redirect(route('currencies.index'));
}
if ($this->repository->isFallbackCurrency($currency)) {
$request->session()->flash('error', (string)trans('firefly.cannot_delete_fallback_currency', ['name' => e($currency->name)]));
Log::channel('audit')->info(sprintf('Tried to delete currency %s but is FALLBACK.', $currency->code));
return redirect(route('currencies.index'));
}
Log::channel('audit')->info(sprintf('Deleted currency %s.', $currency->code));
$this->repository->destroy($currency);
$request->session()->flash('success', (string)trans('firefly.deleted_currency', ['name' => $currency->name]));
return redirect($this->getPreviousUrl('currencies.delete.url'));
}
/**
* @param Request $request
* @return JsonResponse
* @throws FireflyException
*/
public function disableCurrency(Request $request): JsonResponse
{
$currencyId = (int)$request->get('id');
$currency = $this->repository->find($currencyId);
// valid currency?
if (null === $currency) {
return response()->json([]);
}
app('preferences')->mark();
// user must be "owner"
/** @var User $user */
$user = auth()->user();
if (!$this->userRepository->hasRole($user, 'owner')) {
$request->session()->flash('error', (string)trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))]));
Log::channel('audit')->info(sprintf('Tried to disable currency %s but is not site owner.', $currency->code));
return response()->json([]);
}
// currency cannot be in use.
if ($this->repository->currencyInUse($currency)) {
$location = $this->repository->currencyInUseAt($currency);
$message = (string)trans(sprintf('firefly.cannot_disable_currency_%s', $location), ['name' => e($currency->name)]);
$request->session()->flash('error', $message);
Log::channel('audit')->info(sprintf('Tried to disable currency %s but is in use.', $currency->code));
return response()->json([]);
}
// currency disabled!
$this->repository->disable($currency);
Log::channel('audit')->info(sprintf('Disabled currency %s.', $currency->code));
$this->repository->ensureMinimalEnabledCurrencies();
// extra warning
if ('EUR' === $currency->code) {
session()->flash('warning', (string)trans('firefly.disable_EUR_side_effects'));
}
session()->flash('success', (string)trans('firefly.currency_is_now_disabled', ['name' => $currency->name]));
return response()->json([]);
}
/**
* Edit a currency.
*
* @param Request $request
* @param TransactionCurrency $currency
*
* @return Factory|RedirectResponse|Redirector|View
*/
public function edit(Request $request, TransactionCurrency $currency)
{
/** @var User $user */
$user = auth()->user();
if (!$this->userRepository->hasRole($user, 'owner')) {
$request->session()->flash('error', (string)trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))]));
Log::channel('audit')->info(sprintf('Tried to edit currency %s but is not owner.', $currency->code));
return redirect(route('currencies.index'));
}
$subTitleIcon = 'fa-pencil';
$subTitle = (string)trans('breadcrumbs.edit_currency', ['name' => $currency->name]);
$currency->symbol = htmlentities($currency->symbol);
// code to handle active-checkboxes
$hasOldInput = null !== $request->old('_token');
$preFilled = [
'enabled' => $hasOldInput ? (bool)$request->old('enabled') : $currency->enabled,
];
$request->session()->flash('preFilled', $preFilled);
Log::channel('audit')->info('Edit currency.', $currency->toArray());
// put previous url in session if not redirect from store (not "return_to_edit").
if (true !== session('currencies.edit.fromUpdate')) {
$this->rememberPreviousUrl('currencies.edit.url');
}
$request->session()->forget('currencies.edit.fromUpdate');
return view('currencies.edit', compact('currency', 'subTitle', 'subTitleIcon'));
}
/**
* @param Request $request
* @return JsonResponse
*/
public function enableCurrency(Request $request): JsonResponse
{
$currencyId = (int)$request->get('id');
if ($currencyId > 0) {
// valid currency?
$currency = $this->repository->find($currencyId);
if (null !== $currency) {
app('preferences')->mark();
$this->repository->enable($currency);
session()->flash('success', (string)trans('firefly.currency_is_now_enabled', ['name' => $currency->name]));
Log::channel('audit')->info(sprintf('Enabled currency %s.', $currency->code));
}
}
return response()->json([]);
}
/**
* Show overview of currencies.
*
* @param Request $request
*
* @return Factory|View
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function index(Request $request)
{
/** @var User $user */
$user = auth()->user();
$page = 0 === (int)$request->get('page') ? 1 : (int)$request->get('page');
$pageSize = (int)app('preferences')->get('listPageSize', 50)->data;
$collection = $this->repository->getAll();
$total = $collection->count();
$collection = $collection->slice(($page - 1) * $pageSize, $pageSize);
$currencies = new LengthAwarePaginator($collection, $total, $pageSize, $page);
$currencies->setPath(route('currencies.index'));
$defaultCurrency = $this->repository->getCurrencyByPreference(app('preferences')->get('currencyPreference', config('firefly.default_currency', 'EUR')));
$isOwner = true;
if (!$this->userRepository->hasRole($user, 'owner')) {
$request->session()->flash('info', (string)trans('firefly.ask_site_owner', ['owner' => config('firefly.site_owner')]));
$isOwner = false;
}
return view('currencies.index', compact('currencies', 'defaultCurrency', 'isOwner'));
}
/**
* Store new currency.
*
* @param CurrencyFormRequest $request
*
* @return $this|RedirectResponse|Redirector
*/
public function store(CurrencyFormRequest $request)
{
/** @var User $user */
$user = auth()->user();
$data = $request->getCurrencyData();
if (!$this->userRepository->hasRole($user, 'owner')) {
Log::error('User '.auth()->user()->id.' is not admin, but tried to store a currency.');
Log::channel('audit')->info('Tried to create (POST) currency without admin rights.', $data);
return redirect($this->getPreviousUrl('currencies.create.url'));
}
$data['enabled'] = true;
try {
$currency = $this->repository->store($data);
} catch (FireflyException $e) {
Log::error($e->getMessage());
Log::channel('audit')->info('Could not store (POST) currency without admin rights.', $data);
$request->session()->flash('error', (string)trans('firefly.could_not_store_currency'));
$currency = null;
}
$redirect = redirect($this->getPreviousUrl('currencies.create.url'));
if (null !== $currency) {
$request->session()->flash('success', (string)trans('firefly.created_currency', ['name' => $currency->name]));
Log::channel('audit')->info('Created (POST) currency.', $data);
if (1 === (int)$request->get('create_another')) {
$request->session()->put('currencies.create.fromStore', true);
$redirect = redirect(route('currencies.create'))->withInput();
}
}
return $redirect;
}
/**
* Updates a currency.
*
* @param CurrencyFormRequest $request
* @param TransactionCurrency $currency
*
* @return RedirectResponse|Redirector
*/
public function update(CurrencyFormRequest $request, TransactionCurrency $currency)
{
/** @var User $user */
$user = auth()->user();
$data = $request->getCurrencyData();
if (false === $data['enabled'] && $this->repository->currencyInUse($currency)) {
$data['enabled'] = true;
}
if (!$this->userRepository->hasRole($user, 'owner')) {
$request->session()->flash('error', (string)trans('firefly.ask_site_owner', ['owner' => e(config('firefly.site_owner'))]));
Log::channel('audit')->info('Tried to update (POST) currency without admin rights.', $data);
return redirect(route('currencies.index'));
}
$currency = $this->repository->update($currency, $data);
Log::channel('audit')->info('Updated (POST) currency.', $data);
$request->session()->flash('success', (string)trans('firefly.updated_currency', ['name' => $currency->name]));
app('preferences')->mark();
if (1 === (int)$request->get('return_to_edit')) {
$request->session()->put('currencies.edit.fromUpdate', true);
return redirect(route('currencies.edit', [$currency->id]));
}
return redirect($this->getPreviousUrl('currencies.edit.url'));
}
}