Some code cleanup for #1272

This commit is contained in:
James Cole
2018-04-22 17:10:11 +02:00
parent f7d3d4a010
commit 8032684ad0
24 changed files with 339 additions and 269 deletions

View File

@@ -100,7 +100,7 @@ class ReconcileController extends Controller
'amount' => $pTransaction->amount, 'amount' => $pTransaction->amount,
]; ];
Session::flash('preFilled', $preFilled); session()->flash('preFilled', $preFilled);
// put previous url in session if not redirect from store (not "return_to_edit"). // put previous url in session if not redirect from store (not "return_to_edit").
if (true !== session('reconcile.edit.fromUpdate')) { if (true !== session('reconcile.edit.fromUpdate')) {
@@ -184,7 +184,7 @@ class ReconcileController extends Controller
return $this->redirectToOriginalAccount($account); return $this->redirectToOriginalAccount($account);
} }
if (AccountType::ASSET !== $account->accountType->type) { if (AccountType::ASSET !== $account->accountType->type) {
Session::flash('error', trans('firefly.must_be_asset_account')); session()->flash('error', trans('firefly.must_be_asset_account'));
return redirect(route('accounts.index', [config('firefly.shortNamesByFullName.' . $account->accountType->type)])); return redirect(route('accounts.index', [config('firefly.shortNamesByFullName.' . $account->accountType->type)]));
} }
@@ -326,7 +326,7 @@ class ReconcileController extends Controller
Preferences::mark(); Preferences::mark();
Session::flash('success', trans('firefly.reconciliation_stored')); session()->flash('success', trans('firefly.reconciliation_stored'));
return redirect(route('accounts.show', [$account->id])); return redirect(route('accounts.show', [$account->id]));
} }
@@ -387,7 +387,7 @@ class ReconcileController extends Controller
return redirect(route('transactions.show', [$journal->id])); return redirect(route('transactions.show', [$journal->id]));
} }
if (0 === bccomp('0', $request->get('amount'))) { if (0 === bccomp('0', $request->get('amount'))) {
Session::flash('error', trans('firefly.amount_cannot_be_zero')); session()->flash('error', trans('firefly.amount_cannot_be_zero'));
return redirect(route('accounts.reconcile.edit', [$journal->id]))->withInput(); return redirect(route('accounts.reconcile.edit', [$journal->id]))->withInput();
} }

View File

@@ -91,7 +91,7 @@ class ConfigurationController extends Controller
FireflyConfig::set('is_demo_site', $data['is_demo_site']); FireflyConfig::set('is_demo_site', $data['is_demo_site']);
// flash message // flash message
Session::flash('success', (string)trans('firefly.configuration_updated')); session()->flash('success', (string)trans('firefly.configuration_updated'));
Preferences::mark(); Preferences::mark();
return Redirect::route('admin.configuration.index'); return Redirect::route('admin.configuration.index');

View File

@@ -66,7 +66,7 @@ class HomeController extends Controller
$ipAddress = $request->ip(); $ipAddress = $request->ip();
Log::debug(sprintf('Now in testMessage() controller. IP is %s', $ipAddress)); Log::debug(sprintf('Now in testMessage() controller. IP is %s', $ipAddress));
event(new AdminRequestedTestMessage(auth()->user(), $ipAddress)); event(new AdminRequestedTestMessage(auth()->user(), $ipAddress));
Session::flash('info', (string)trans('firefly.send_test_triggered')); session()->flash('info', (string)trans('firefly.send_test_triggered'));
return redirect(route('admin.index')); return redirect(route('admin.index'));
} }

View File

@@ -90,7 +90,7 @@ class UpdateController extends Controller
$checkForUpdates = (int)$request->get('check_for_updates'); $checkForUpdates = (int)$request->get('check_for_updates');
FireflyConfig::set('permission_update_check', $checkForUpdates); FireflyConfig::set('permission_update_check', $checkForUpdates);
FireflyConfig::set('last_update_check', time()); FireflyConfig::set('last_update_check', time());
Session::flash('success', (string)trans('firefly.configuration_updated')); session()->flash('success', (string)trans('firefly.configuration_updated'));
return redirect(route('admin.update-check')); return redirect(route('admin.update-check'));
} }

View File

@@ -78,7 +78,7 @@ class UserController extends Controller
public function destroy(User $user, UserRepositoryInterface $repository) public function destroy(User $user, UserRepositoryInterface $repository)
{ {
$repository->destroy($user); $repository->destroy($user);
Session::flash('success', (string)trans('firefly.user_deleted')); session()->flash('success', (string)trans('firefly.user_deleted'));
return redirect(route('admin.users')); return redirect(route('admin.users'));
} }
@@ -182,7 +182,7 @@ class UserController extends Controller
$repository->changeStatus($user, $data['blocked'], $data['blocked_code']); $repository->changeStatus($user, $data['blocked'], $data['blocked_code']);
$repository->updateEmail($user, $data['email']); $repository->updateEmail($user, $data['email']);
Session::flash('success', (string)trans('firefly.updated_user', ['email' => $user->email])); session()->flash('success', (string)trans('firefly.updated_user', ['email' => $user->email]));
Preferences::mark(); Preferences::mark();
if (1 === (int)$request->get('return_to_edit')) { if (1 === (int)$request->get('return_to_edit')) {

View File

@@ -83,7 +83,7 @@ class RegisterController extends Controller
$this->guard()->login($user); $this->guard()->login($user);
Session::flash('success', (string)trans('firefly.registered')); session()->flash('success', (string)trans('firefly.registered'));
return $this->registered($request, $user) return $this->registered($request, $user)
?: redirect($this->redirectPath()); ?: redirect($this->redirectPath());

View File

@@ -163,7 +163,7 @@ class Controller extends BaseController
} }
} }
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
Session::flash('error', (string)trans('firefly.cannot_redirect_to_account')); session()->flash('error', (string)trans('firefly.cannot_redirect_to_account'));
return redirect(route('index')); return redirect(route('index'));
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd

View File

@@ -126,7 +126,7 @@ class NewUserController extends Controller
]; ];
Preferences::set('transaction_journal_optional_fields', $visibleFields); Preferences::set('transaction_journal_optional_fields', $visibleFields);
Session::flash('success', (string)trans('firefly.stored_new_accounts_new_user')); session()->flash('success', (string)trans('firefly.stored_new_accounts_new_user'));
Preferences::mark(); Preferences::mark();
return redirect(route('index')); return redirect(route('index'));

View File

@@ -164,7 +164,7 @@ class PiggyBankController extends Controller
*/ */
public function destroy(PiggyBank $piggyBank) public function destroy(PiggyBank $piggyBank)
{ {
Session::flash('success', (string)trans('firefly.deleted_piggy_bank', ['name' => $piggyBank->name])); session()->flash('success', (string)trans('firefly.deleted_piggy_bank', ['name' => $piggyBank->name]));
Preferences::mark(); Preferences::mark();
$this->piggyRepos->destroy($piggyBank); $this->piggyRepos->destroy($piggyBank);
@@ -198,7 +198,7 @@ class PiggyBankController extends Controller
'startdate' => $startDate, 'startdate' => $startDate,
'note' => null === $note ? '' : $note->text, 'note' => null === $note ? '' : $note->text,
]; ];
Session::flash('preFilled', $preFilled); session()->flash('preFilled', $preFilled);
// put previous url in session if not redirect from store (not "return_to_edit"). // put previous url in session if not redirect from store (not "return_to_edit").
if (true !== session('piggy-banks.edit.fromUpdate')) { if (true !== session('piggy-banks.edit.fromUpdate')) {
@@ -299,7 +299,7 @@ class PiggyBankController extends Controller
} }
if ($this->piggyRepos->canAddAmount($piggyBank, $amount)) { if ($this->piggyRepos->canAddAmount($piggyBank, $amount)) {
$this->piggyRepos->addAmount($piggyBank, $amount); $this->piggyRepos->addAmount($piggyBank, $amount);
Session::flash( session()->flash(
'success', 'success',
(string)trans( (string)trans(
'firefly.added_amount_to_piggy', 'firefly.added_amount_to_piggy',
@@ -312,7 +312,7 @@ class PiggyBankController extends Controller
} }
Log::error('Cannot add ' . $amount . ' because canAddAmount returned false.'); Log::error('Cannot add ' . $amount . ' because canAddAmount returned false.');
Session::flash( session()->flash(
'error', 'error',
(string)trans( (string)trans(
'firefly.cannot_add_amount_piggy', 'firefly.cannot_add_amount_piggy',
@@ -339,7 +339,7 @@ class PiggyBankController extends Controller
} }
if ($this->piggyRepos->canRemoveAmount($piggyBank, $amount)) { if ($this->piggyRepos->canRemoveAmount($piggyBank, $amount)) {
$this->piggyRepos->removeAmount($piggyBank, $amount); $this->piggyRepos->removeAmount($piggyBank, $amount);
Session::flash( session()->flash(
'success', 'success',
(string)trans( (string)trans(
'firefly.removed_amount_from_piggy', 'firefly.removed_amount_from_piggy',
@@ -353,7 +353,7 @@ class PiggyBankController extends Controller
$amount = (string)round($request->get('amount'), 12); $amount = (string)round($request->get('amount'), 12);
Session::flash( session()->flash(
'error', 'error',
(string)trans( (string)trans(
'firefly.cannot_remove_from_piggy', 'firefly.cannot_remove_from_piggy',
@@ -430,7 +430,7 @@ class PiggyBankController extends Controller
} }
$piggyBank = $this->piggyRepos->store($data); $piggyBank = $this->piggyRepos->store($data);
Session::flash('success', (string)trans('firefly.stored_piggy_bank', ['name' => $piggyBank->name])); session()->flash('success', (string)trans('firefly.stored_piggy_bank', ['name' => $piggyBank->name]));
Preferences::mark(); Preferences::mark();
if (1 === (int)$request->get('create_another')) { if (1 === (int)$request->get('create_another')) {
@@ -455,7 +455,7 @@ class PiggyBankController extends Controller
$data = $request->getPiggyBankData(); $data = $request->getPiggyBankData();
$piggyBank = $this->piggyRepos->update($piggyBank, $data); $piggyBank = $this->piggyRepos->update($piggyBank, $data);
Session::flash('success', (string)trans('firefly.updated_piggy_bank', ['name' => $piggyBank->name])); session()->flash('success', (string)trans('firefly.updated_piggy_bank', ['name' => $piggyBank->name]));
Preferences::mark(); Preferences::mark();
if (1 === (int)$request->get('return_to_edit')) { if (1 === (int)$request->get('return_to_edit')) {

View File

@@ -143,7 +143,7 @@ class PreferencesController extends Controller
]; ];
Preferences::set('transaction_journal_optional_fields', $optionalTj); Preferences::set('transaction_journal_optional_fields', $optionalTj);
Session::flash('success', (string)trans('firefly.saved_preferences')); session()->flash('success', (string)trans('firefly.saved_preferences'));
Preferences::mark(); Preferences::mark();
return redirect(route('preferences.index')); return redirect(route('preferences.index'));

View File

@@ -107,7 +107,7 @@ class ProfileController extends Controller
{ {
$domain = $this->getDomain(); $domain = $this->getDomain();
$secret = Google2FA::generateSecretKey(); $secret = Google2FA::generateSecretKey();
Session::flash('two-factor-secret', $secret); session()->flash('two-factor-secret', $secret);
$image = Google2FA::getQRCodeInline($domain, auth()->user()->email, $secret, 200); $image = Google2FA::getQRCodeInline($domain, auth()->user()->email, $secret, 200);
return view('profile.code', compact('image')); return view('profile.code', compact('image'));
@@ -143,7 +143,7 @@ class ProfileController extends Controller
$repository->unblockUser($user); $repository->unblockUser($user);
// return to login. // return to login.
Session::flash('success', (string)trans('firefly.login_with_new_email')); session()->flash('success', (string)trans('firefly.login_with_new_email'));
return redirect(route('login')); return redirect(route('login'));
} }
@@ -167,8 +167,8 @@ class ProfileController extends Controller
{ {
Preferences::delete('twoFactorAuthEnabled'); Preferences::delete('twoFactorAuthEnabled');
Preferences::delete('twoFactorAuthSecret'); Preferences::delete('twoFactorAuthSecret');
Session::flash('success', (string)trans('firefly.pref_two_factor_auth_disabled')); session()->flash('success', (string)trans('firefly.pref_two_factor_auth_disabled'));
Session::flash('info', (string)trans('firefly.pref_two_factor_auth_remove_it')); session()->flash('info', (string)trans('firefly.pref_two_factor_auth_remove_it'));
return redirect(route('profile.index')); return redirect(route('profile.index'));
} }
@@ -242,7 +242,7 @@ class ProfileController extends Controller
$newEmail = $request->string('email'); $newEmail = $request->string('email');
$oldEmail = $user->email; $oldEmail = $user->email;
if ($newEmail === $user->email) { if ($newEmail === $user->email) {
Session::flash('error', (string)trans('firefly.email_not_changed')); session()->flash('error', (string)trans('firefly.email_not_changed'));
return redirect(route('profile.change-email'))->withInput(); return redirect(route('profile.change-email'))->withInput();
} }
@@ -252,7 +252,7 @@ class ProfileController extends Controller
Auth::guard()->logout(); Auth::guard()->logout();
$request->session()->invalidate(); $request->session()->invalidate();
Session::flash('success', (string)trans('firefly.email_changed')); session()->flash('success', (string)trans('firefly.email_changed'));
return redirect(route('index')); return redirect(route('index'));
} }
@@ -267,7 +267,7 @@ class ProfileController extends Controller
// force user logout. // force user logout.
Auth::guard()->logout(); Auth::guard()->logout();
$request->session()->invalidate(); $request->session()->invalidate();
Session::flash('success', (string)trans('firefly.email_changed')); session()->flash('success', (string)trans('firefly.email_changed'));
return redirect(route('index')); return redirect(route('index'));
} }
@@ -287,13 +287,13 @@ class ProfileController extends Controller
try { try {
$this->validatePassword(auth()->user(), $current, $new); $this->validatePassword(auth()->user(), $current, $new);
} catch (ValidationException $e) { } catch (ValidationException $e) {
Session::flash('error', $e->getMessage()); session()->flash('error', $e->getMessage());
return redirect(route('profile.change-password')); return redirect(route('profile.change-password'));
} }
$repository->changePassword(auth()->user(), $request->get('new_password')); $repository->changePassword(auth()->user(), $request->get('new_password'));
Session::flash('success', (string)trans('firefly.password_changed')); session()->flash('success', (string)trans('firefly.password_changed'));
return redirect(route('profile.index')); return redirect(route('profile.index'));
} }
@@ -309,7 +309,7 @@ class ProfileController extends Controller
Preferences::set('twoFactorAuthEnabled', 1); Preferences::set('twoFactorAuthEnabled', 1);
Preferences::set('twoFactorAuthSecret', Session::get('two-factor-secret')); Preferences::set('twoFactorAuthSecret', Session::get('two-factor-secret'));
Session::flash('success', (string)trans('firefly.saved_preferences')); session()->flash('success', (string)trans('firefly.saved_preferences'));
Preferences::mark(); Preferences::mark();
return redirect(route('profile.index')); return redirect(route('profile.index'));
@@ -324,7 +324,7 @@ class ProfileController extends Controller
public function postDeleteAccount(UserRepositoryInterface $repository, DeleteAccountFormRequest $request) public function postDeleteAccount(UserRepositoryInterface $repository, DeleteAccountFormRequest $request)
{ {
if (!Hash::check($request->get('password'), auth()->user()->password)) { if (!Hash::check($request->get('password'), auth()->user()->password)) {
Session::flash('error', (string)trans('firefly.invalid_password')); session()->flash('error', (string)trans('firefly.invalid_password'));
return redirect(route('profile.delete-account')); return redirect(route('profile.delete-account'));
} }
@@ -345,7 +345,7 @@ class ProfileController extends Controller
{ {
$token = auth()->user()->generateAccessToken(); $token = auth()->user()->generateAccessToken();
Preferences::set('access_token', $token); Preferences::set('access_token', $token);
Session::flash('success', (string)trans('firefly.token_regenerated')); session()->flash('success', (string)trans('firefly.token_regenerated'));
return redirect(route('profile.index')); return redirect(route('profile.index'));
} }
@@ -395,7 +395,7 @@ class ProfileController extends Controller
$repository->unblockUser($user); $repository->unblockUser($user);
// return to login. // return to login.
Session::flash('success', (string)trans('firefly.login_with_old_email')); session()->flash('success', (string)trans('firefly.login_with_old_email'));
return redirect(route('login')); return redirect(route('login'));
} }

View File

@@ -325,25 +325,25 @@ class ReportController extends Controller
if (0 === $request->getAccountList()->count()) { if (0 === $request->getAccountList()->count()) {
Log::debug('Account count is zero'); Log::debug('Account count is zero');
Session::flash('error', trans('firefly.select_more_than_one_account')); session()->flash('error', trans('firefly.select_more_than_one_account'));
return redirect(route('reports.index')); return redirect(route('reports.index'));
} }
if (0 === $request->getCategoryList()->count() && 'category' === $reportType) { if (0 === $request->getCategoryList()->count() && 'category' === $reportType) {
Session::flash('error', trans('firefly.select_more_than_one_category')); session()->flash('error', trans('firefly.select_more_than_one_category'));
return redirect(route('reports.index')); return redirect(route('reports.index'));
} }
if (0 === $request->getBudgetList()->count() && 'budget' === $reportType) { if (0 === $request->getBudgetList()->count() && 'budget' === $reportType) {
Session::flash('error', trans('firefly.select_more_than_one_budget')); session()->flash('error', trans('firefly.select_more_than_one_budget'));
return redirect(route('reports.index')); return redirect(route('reports.index'));
} }
if (0 === $request->getTagList()->count() && 'tag' === $reportType) { if (0 === $request->getTagList()->count() && 'tag' === $reportType) {
Session::flash('error', trans('firefly.select_more_than_one_tag')); session()->flash('error', trans('firefly.select_more_than_one_tag'));
return redirect(route('reports.index')); return redirect(route('reports.index'));
} }

View File

@@ -24,6 +24,7 @@ namespace FireflyIII\Http\Controllers;
use Carbon\Carbon; use Carbon\Carbon;
use ExpandedForm; use ExpandedForm;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Http\Requests\RuleFormRequest; use FireflyIII\Http\Requests\RuleFormRequest;
use FireflyIII\Http\Requests\SelectTransactionsRequest; use FireflyIII\Http\Requests\SelectTransactionsRequest;
use FireflyIII\Http\Requests\TestRuleFormRequest; use FireflyIII\Http\Requests\TestRuleFormRequest;
@@ -39,7 +40,9 @@ use FireflyIII\Repositories\Bill\BillRepositoryInterface;
use FireflyIII\Repositories\Rule\RuleRepositoryInterface; use FireflyIII\Repositories\Rule\RuleRepositoryInterface;
use FireflyIII\Repositories\RuleGroup\RuleGroupRepositoryInterface; use FireflyIII\Repositories\RuleGroup\RuleGroupRepositoryInterface;
use FireflyIII\TransactionRules\TransactionMatcher; use FireflyIII\TransactionRules\TransactionMatcher;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Log; use Log;
use Preferences; use Preferences;
use Session; use Session;
@@ -51,6 +54,15 @@ use View;
*/ */
class RuleController extends Controller class RuleController extends Controller
{ {
/** @var AccountRepositoryInterface */
private $accountRepos;
/** @var BillRepositoryInterface */
private $billRepos;
/** @var RuleGroupRepositoryInterface */
private $ruleGroupRepos;
/** @var RuleRepositoryInterface */
private $ruleRepos;
/** /**
* RuleController constructor. * RuleController constructor.
*/ */
@@ -63,6 +75,11 @@ class RuleController extends Controller
app('view')->share('title', trans('firefly.rules')); app('view')->share('title', trans('firefly.rules'));
app('view')->share('mainTitleIcon', 'fa-random'); app('view')->share('mainTitleIcon', 'fa-random');
$this->accountRepos = app(AccountRepositoryInterface::class);
$this->billRepos = app(BillRepositoryInterface::class);
$this->ruleGroupRepos = app(RuleGroupRepositoryInterface::class);
$this->ruleRepos = app(RuleRepositoryInterface::class);
return $next($request); return $next($request);
} }
); );
@@ -77,7 +94,7 @@ class RuleController extends Controller
* @return View * @return View
* *
*/ */
public function create(Request $request, RuleGroupRepositoryInterface $ruleGroupRepository, BillRepositoryInterface $billRepository, RuleGroup $ruleGroup) public function create(Request $request, RuleGroup $ruleGroup)
{ {
$this->createDefaultRuleGroup(); $this->createDefaultRuleGroup();
$this->createDefaultRule(); $this->createDefaultRule();
@@ -86,7 +103,7 @@ class RuleController extends Controller
$preFilled = [ $preFilled = [
'strict' => true, 'strict' => true,
]; ];
$groups = ExpandedForm::makeSelectList($ruleGroupRepository->get()); $groups = ExpandedForm::makeSelectList($this->ruleGroupRepos->get());
$oldTriggers = []; $oldTriggers = [];
$oldActions = []; $oldActions = [];
$returnToBill = false; $returnToBill = false;
@@ -97,7 +114,7 @@ class RuleController extends Controller
// has bill? // has bill?
if ($billId > 0) { if ($billId > 0) {
$bill = $billRepository->find($billId); $bill = $this->billRepos->find($billId);
} }
// has old input? // has old input?
@@ -160,74 +177,65 @@ class RuleController extends Controller
/** /**
* Actually destroy the given rule. * Actually destroy the given rule.
* *
* @param Rule $rule * @param Rule $rule
* @param RuleRepositoryInterface $repository
* *
* @return \Illuminate\Http\RedirectResponse * @return \Illuminate\Http\RedirectResponse
*/ */
public function destroy(RuleRepositoryInterface $repository, Rule $rule) public function destroy(Rule $rule)
{ {
$title = $rule->title; $title = $rule->title;
$repository->destroy($rule); $this->ruleRepos->destroy($rule);
Session::flash('success', trans('firefly.deleted_rule', ['title' => $title])); session()->flash('success', trans('firefly.deleted_rule', ['title' => $title]));
Preferences::mark(); Preferences::mark();
return redirect($this->getPreviousUri('rules.delete.uri')); return redirect($this->getPreviousUri('rules.delete.uri'));
} }
/** /**
* @param RuleRepositoryInterface $repository * @param Rule $rule
* @param Rule $rule
* *
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/ */
public function down(RuleRepositoryInterface $repository, Rule $rule) public function down(Rule $rule)
{ {
$repository->moveDown($rule); $this->ruleRepos->moveDown($rule);
return redirect(route('rules.index')); return redirect(route('rules.index'));
} }
/** /**
* @param Request $request * @param Request $request
* @param RuleRepositoryInterface $repository * @param Rule $rule
* @param Rule $rule
* *
* @return View * @return View
* *
*/ */
public function edit(Request $request, RuleRepositoryInterface $repository, Rule $rule) public function edit(Request $request, Rule $rule)
{ {
/** @var RuleGroupRepositoryInterface $ruleGroupRepository */ $ruleGroups = ExpandedForm::makeSelectList($this->ruleGroupRepos->get());
$ruleGroupRepository = app(RuleGroupRepositoryInterface::class); $triggerCount = 0;
$ruleGroups = ExpandedForm::makeSelectList($ruleGroupRepository->get()); $actionCount = 0;
$triggerCount = 0; $oldActions = [];
$actionCount = 0; $oldTriggers = [];
$oldActions = [];
$oldTriggers = [];
// has old input? // has old input?
if (count($request->old()) > 0) { if (\count($request->old()) > 0) {
$oldTriggers = $this->getPreviousTriggers($request); $oldTriggers = $this->getPreviousTriggers($request);
$triggerCount = count($oldTriggers); $triggerCount = \count($oldTriggers);
$oldActions = $this->getPreviousActions($request); $oldActions = $this->getPreviousActions($request);
$actionCount = count($oldActions); $actionCount = \count($oldActions);
} }
// overrule old input when it as no rule data: // overrule old input when it as no rule data:
if (0 === $triggerCount && 0 === $actionCount) { if (0 === $triggerCount && 0 === $actionCount) {
$oldTriggers = $this->getCurrentTriggers($rule); $oldTriggers = $this->getCurrentTriggers($rule);
$triggerCount = count($oldTriggers); $triggerCount = \count($oldTriggers);
$oldActions = $this->getCurrentActions($rule); $oldActions = $this->getCurrentActions($rule);
$actionCount = count($oldActions); $actionCount = \count($oldActions);
} }
// get rule trigger for update / store-journal: // get rule trigger for update / store-journal:
$primaryTrigger = $repository->getPrimaryTrigger($rule); $primaryTrigger = $this->ruleRepos->getPrimaryTrigger($rule);
$subTitle = trans('firefly.edit_rule', ['title' => $rule->title]); $subTitle = trans('firefly.edit_rule', ['title' => $rule->title]);
// put previous url in session if not redirect from store (not "return_to_edit"). // put previous url in session if not redirect from store (not "return_to_edit").
@@ -236,36 +244,23 @@ class RuleController extends Controller
} }
Session::forget('rules.edit.fromUpdate'); Session::forget('rules.edit.fromUpdate');
return view( return view('rules.rule.edit', compact('rule', 'subTitle', 'primaryTrigger', 'oldTriggers', 'oldActions', 'triggerCount', 'actionCount', 'ruleGroups'));
'rules.rule.edit',
compact(
'rule',
'subTitle',
'primaryTrigger',
'oldTriggers',
'oldActions',
'triggerCount',
'actionCount',
'ruleGroups'
)
);
} }
/** /**
* Execute the given rule on a set of existing transactions. * Execute the given rule on a set of existing transactions.
* *
* @param SelectTransactionsRequest $request * @param SelectTransactionsRequest $request
* @param AccountRepositoryInterface $repository * @param Rule $rule
* @param Rule $rule
* *
* @return \Illuminate\Http\RedirectResponse * @return \Illuminate\Http\RedirectResponse
* *
* @internal param RuleGroup $ruleGroup * @internal param RuleGroup $ruleGroup
*/ */
public function execute(SelectTransactionsRequest $request, AccountRepositoryInterface $repository, Rule $rule) public function execute(SelectTransactionsRequest $request, Rule $rule)
{ {
// Get parameters specified by the user // Get parameters specified by the user
$accounts = $repository->getAccountsById($request->get('accounts')); $accounts = $this->accountRepos->getAccountsById($request->get('accounts'));
$startDate = new Carbon($request->get('start_date')); $startDate = new Carbon($request->get('start_date'));
$endDate = new Carbon($request->get('end_date')); $endDate = new Carbon($request->get('end_date'));
@@ -282,37 +277,34 @@ class RuleController extends Controller
$this->dispatch($job); $this->dispatch($job);
// Tell the user that the job is queued // Tell the user that the job is queued
Session::flash('success', (string)trans('firefly.applied_rule_selection', ['title' => $rule->title])); session()->flash('success', (string)trans('firefly.applied_rule_selection', ['title' => $rule->title]));
return redirect()->route('rules.index'); return redirect()->route('rules.index');
} }
/** /**
* @param RuleGroupRepositoryInterface $repository
*
* @return View * @return View
*/ */
public function index(RuleGroupRepositoryInterface $repository) public function index()
{ {
$this->createDefaultRuleGroup(); $this->createDefaultRuleGroup();
$this->createDefaultRule(); $this->createDefaultRule();
$ruleGroups = $repository->getRuleGroupsWithRules(auth()->user()); $ruleGroups = $this->ruleGroupRepos->getRuleGroupsWithRules(auth()->user());
return view('rules.index', compact('ruleGroups')); return view('rules.index', compact('ruleGroups'));
} }
/** /**
* @param Request $request * @param Request $request
* @param RuleRepositoryInterface $repository * @param Rule $rule
* @param Rule $rule
* *
* @return \Illuminate\Http\JsonResponse * @return JsonResponse
*/ */
public function reorderRuleActions(Request $request, RuleRepositoryInterface $repository, Rule $rule) public function reorderRuleActions(Request $request, Rule $rule): JsonResponse
{ {
$ids = $request->get('actions'); $ids = $request->get('actions');
if (is_array($ids)) { if (\is_array($ids)) {
$repository->reorderRuleActions($rule, $ids); $this->ruleGroupRepos->reorderRuleActions($rule, $ids);
} }
return response()->json('true'); return response()->json('true');
@@ -323,28 +315,27 @@ class RuleController extends Controller
* @param RuleRepositoryInterface $repository * @param RuleRepositoryInterface $repository
* @param Rule $rule * @param Rule $rule
* *
* @return \Illuminate\Http\JsonResponse * @return JsonResponse
*/ */
public function reorderRuleTriggers(Request $request, RuleRepositoryInterface $repository, Rule $rule) public function reorderRuleTriggers(Request $request, Rule $rule): JsonResponse
{ {
$ids = $request->get('triggers'); $ids = $request->get('triggers');
if (is_array($ids)) { if (\is_array($ids)) {
$repository->reorderRuleTriggers($rule, $ids); $this->ruleGroupRepos->reorderRuleTriggers($rule, $ids);
} }
return response()->json('true'); return response()->json('true');
} }
/** /**
* @param AccountRepositoryInterface $repository * @param Rule $rule
* @param Rule $rule
* *
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/ */
public function selectTransactions(AccountRepositoryInterface $repository, Rule $rule) public function selectTransactions(Rule $rule)
{ {
// does the user have shared accounts? // does the user have shared accounts?
$accounts = $repository->getAccountsByType([AccountType::ASSET]); $accounts = $this->accountRepos->getAccountsByType([AccountType::ASSET]);
$accountList = ExpandedForm::makeSelectList($accounts); $accountList = ExpandedForm::makeSelectList($accounts);
$checkedAccounts = array_keys($accountList); $checkedAccounts = array_keys($accountList);
$first = session('first')->format('Y-m-d'); $first = session('first')->format('Y-m-d');
@@ -355,15 +346,14 @@ class RuleController extends Controller
} }
/** /**
* @param RuleFormRequest $request * @param RuleFormRequest $request
* @param RuleRepositoryInterface $repository
* *
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/ */
public function store(RuleFormRequest $request, RuleRepositoryInterface $repository) public function store(RuleFormRequest $request)
{ {
$data = $request->getRuleData(); $data = $request->getRuleData();
$rule = $repository->store($data); $rule = $this->ruleRepos->store($data);
session()->flash('success', trans('firefly.stored_new_rule', ['title' => $rule->title])); session()->flash('success', trans('firefly.stored_new_rule', ['title' => $rule->title]));
Preferences::mark(); Preferences::mark();
@@ -399,39 +389,50 @@ class RuleController extends Controller
* *
* @param TestRuleFormRequest $request * @param TestRuleFormRequest $request
* *
* @return \Illuminate\Http\JsonResponse * @return JsonResponse
*
*/ */
public function testTriggers(TestRuleFormRequest $request) public function testTriggers(TestRuleFormRequest $request): JsonResponse
{ {
// build trigger array from response // build trigger array from response
$triggers = $this->getValidTriggerList($request); $triggers = $this->getValidTriggerList($request);
if (0 === count($triggers)) { if (0 === \count($triggers)) {
return response()->json(['html' => '', 'warning' => trans('firefly.warning_no_valid_triggers')]); // @codeCoverageIgnore return response()->json(['html' => '', 'warning' => trans('firefly.warning_no_valid_triggers')]); // @codeCoverageIgnore
} }
$limit = (int)config('firefly.test-triggers.limit'); $limit = (int)config('firefly.test-triggers.limit');
$range = (int)config('firefly.test-triggers.range'); $range = (int)config('firefly.test-triggers.range');
$matchingTransactions = new Collection;
/** @var TransactionMatcher $matcher */ /** @var TransactionMatcher $matcher */
$matcher = app(TransactionMatcher::class); $matcher = app(TransactionMatcher::class);
$matcher->setLimit($limit); $matcher->setLimit($limit);
$matcher->setRange($range); $matcher->setRange($range);
$matcher->setTriggers($triggers); $matcher->setTriggers($triggers);
$matchingTransactions = $matcher->findTransactionsByTriggers(); try {
$matchingTransactions = $matcher->findTransactionsByTriggers();
} catch (FireflyException $exception) {
Log::error(sprintf('Could not grab transactions in testTriggers(): %s', $exception->getMessage()));
Log::error($exception->getTraceAsString());
}
// Warn the user if only a subset of transactions is returned // Warn the user if only a subset of transactions is returned
$warning = ''; $warning = '';
if (count($matchingTransactions) === $limit) { if ($matchingTransactions->count() === $limit) {
$warning = trans('firefly.warning_transaction_subset', ['max_num_transactions' => $limit]); // @codeCoverageIgnore $warning = trans('firefly.warning_transaction_subset', ['max_num_transactions' => $limit]); // @codeCoverageIgnore
} }
if (0 === count($matchingTransactions)) { if (0 === $matchingTransactions->count()) {
$warning = trans('firefly.warning_no_matching_transactions', ['num_transactions' => $range]); // @codeCoverageIgnore $warning = trans('firefly.warning_no_matching_transactions', ['num_transactions' => $range]); // @codeCoverageIgnore
} }
// Return json response // Return json response
$view = view('list.journals-tiny', ['transactions' => $matchingTransactions])->render(); $view = 'ERROR, see logs.';
try {
$view = view('list.journals-tiny', ['transactions' => $matchingTransactions])->render();
} catch (Throwable $exception) {
Log::error(sprintf('Could not render view in testTriggers(): %s', $exception->getMessage()));
Log::error($exception->getTraceAsString());
}
return response()->json(['html' => $view, 'warning' => $warning]); return response()->json(['html' => $view, 'warning' => $warning]);
} }
@@ -444,14 +445,11 @@ class RuleController extends Controller
* to find transaction journals matching the users input. A maximum range of transactions to try (range) and * to find transaction journals matching the users input. A maximum range of transactions to try (range) and
* a maximum number of transactions to return (limit) are set as well. * a maximum number of transactions to return (limit) are set as well.
* *
*
* @param Rule $rule * @param Rule $rule
* *
* @return \Illuminate\Http\JsonResponse * @return JsonResponse
* @throws Throwable
* @throws \FireflyIII\Exceptions\FireflyException
*/ */
public function testTriggersByRule(Rule $rule) public function testTriggersByRule(Rule $rule): JsonResponse
{ {
$triggers = $rule->ruleTriggers; $triggers = $rule->ruleTriggers;
@@ -459,57 +457,67 @@ class RuleController extends Controller
return response()->json(['html' => '', 'warning' => trans('firefly.warning_no_valid_triggers')]); // @codeCoverageIgnore return response()->json(['html' => '', 'warning' => trans('firefly.warning_no_valid_triggers')]); // @codeCoverageIgnore
} }
$limit = (int)config('firefly.test-triggers.limit'); $limit = (int)config('firefly.test-triggers.limit');
$range = (int)config('firefly.test-triggers.range'); $range = (int)config('firefly.test-triggers.range');
$matchingTransactions = new Collection;
/** @var TransactionMatcher $matcher */ /** @var TransactionMatcher $matcher */
$matcher = app(TransactionMatcher::class); $matcher = app(TransactionMatcher::class);
$matcher->setLimit($limit); $matcher->setLimit($limit);
$matcher->setRange($range); $matcher->setRange($range);
$matcher->setRule($rule); $matcher->setRule($rule);
$matchingTransactions = $matcher->findTransactionsByRule(); try {
$matchingTransactions = $matcher->findTransactionsByRule();
} catch (FireflyException $exception) {
Log::error(sprintf('Could not grab transactions in testTriggersByRule(): %s', $exception->getMessage()));
Log::error($exception->getTraceAsString());
}
// Warn the user if only a subset of transactions is returned // Warn the user if only a subset of transactions is returned
$warning = ''; $warning = '';
if (\count($matchingTransactions) === $limit) { if ($matchingTransactions->count() === $limit) {
$warning = trans('firefly.warning_transaction_subset', ['max_num_transactions' => $limit]); // @codeCoverageIgnore $warning = trans('firefly.warning_transaction_subset', ['max_num_transactions' => $limit]); // @codeCoverageIgnore
} }
if (0 === \count($matchingTransactions)) { if (0 === $matchingTransactions->count()) {
$warning = trans('firefly.warning_no_matching_transactions', ['num_transactions' => $range]); // @codeCoverageIgnore $warning = trans('firefly.warning_no_matching_transactions', ['num_transactions' => $range]); // @codeCoverageIgnore
} }
// Return json response // Return json response
$view = view('list.journals-tiny', ['transactions' => $matchingTransactions])->render(); $view = 'ERROR, see logs.';
try {
$view = view('list.journals-tiny', ['transactions' => $matchingTransactions])->render();
} catch (Throwable $exception) {
Log::error(sprintf('Could not render view in testTriggersByRule(): %s', $exception->getMessage()));
Log::error($exception->getTraceAsString());
}
return response()->json(['html' => $view, 'warning' => $warning]); return response()->json(['html' => $view, 'warning' => $warning]);
} }
/** /**
* @param RuleRepositoryInterface $repository * @param Rule $rule
* @param Rule $rule
* *
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/ */
public function up(RuleRepositoryInterface $repository, Rule $rule) public function up(Rule $rule)
{ {
$repository->moveUp($rule); $this->ruleRepos->moveUp($rule);
return redirect(route('rules.index')); return redirect(route('rules.index'));
} }
/** /**
* @param RuleRepositoryInterface $repository * @param RuleFormRequest $request
* @param RuleFormRequest $request * @param Rule $rule
* @param Rule $rule
* *
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/ */
public function update(RuleRepositoryInterface $repository, RuleFormRequest $request, Rule $rule) public function update(RuleFormRequest $request, Rule $rule)
{ {
$data = $request->getRuleData(); $data = $request->getRuleData();
$repository->update($rule, $data); $this->ruleRepos->update($rule, $data);
Session::flash('success', trans('firefly.updated_rule', ['title' => $rule->title])); session()->flash('success', trans('firefly.updated_rule', ['title' => $rule->title]));
Preferences::mark(); Preferences::mark();
if (1 === (int)$request->get('return_to_edit')) { if (1 === (int)$request->get('return_to_edit')) {
@@ -523,14 +531,14 @@ class RuleController extends Controller
return redirect($this->getPreviousUri('rules.edit.uri')); return redirect($this->getPreviousUri('rules.edit.uri'));
} }
private function createDefaultRule() /**
*
*/
private function createDefaultRule(): void
{ {
/** @var RuleRepositoryInterface $repository */ if (0 === $this->ruleRepos->count()) {
$repository = app(RuleRepositoryInterface::class);
if (0 === $repository->count()) {
$data = [ $data = [
'rule_group_id' => $repository->getFirstRuleGroup()->id, 'rule_group_id' => $this->ruleRepos->getFirstRuleGroup()->id,
'stop_processing' => 0, 'stop_processing' => 0,
'title' => trans('firefly.default_rule_name'), 'title' => trans('firefly.default_rule_name'),
'description' => trans('firefly.default_rule_description'), 'description' => trans('firefly.default_rule_description'),
@@ -548,25 +556,22 @@ class RuleController extends Controller
'rule-actions' => ['prepend_description', 'set_category'], 'rule-actions' => ['prepend_description', 'set_category'],
]; ];
$repository->store($data); $this->ruleRepos->store($data);
} }
} }
/** /**
* *
*/ */
private function createDefaultRuleGroup() private function createDefaultRuleGroup(): void
{ {
/** @var RuleGroupRepositoryInterface $repository */ if (0 === $this->ruleGroupRepos->count()) {
$repository = app(RuleGroupRepositoryInterface::class);
if (0 === $repository->count()) {
$data = [ $data = [
'title' => trans('firefly.default_rule_group_name'), 'title' => trans('firefly.default_rule_group_name'),
'description' => trans('firefly.default_rule_group_description'), 'description' => trans('firefly.default_rule_group_description'),
]; ];
$repository->store($data); $this->ruleGroupRepos->store($data);
} }
} }
@@ -589,7 +594,8 @@ class RuleController extends Controller
] ]
)->render(); )->render();
} catch (Throwable $e) { } catch (Throwable $e) {
Log::debug(sprintf('Throwable was thrown in getActionsForBill(): %s', $e->getMessage())); Log::error(sprintf('Throwable was thrown in getActionsForBill(): %s', $e->getMessage()));
Log::error($e->getTraceAsString());
} }
return $actions; return $actions;
@@ -602,7 +608,7 @@ class RuleController extends Controller
* *
*/ */
private function getCurrentActions(Rule $rule) private function getCurrentActions(Rule $rule): array
{ {
$index = 0; $index = 0;
$actions = []; $actions = [];
@@ -622,6 +628,7 @@ class RuleController extends Controller
)->render(); )->render();
} catch (Throwable $e) { } catch (Throwable $e) {
Log::debug(sprintf('Throwable was thrown in getCurrentActions(): %s', $e->getMessage())); Log::debug(sprintf('Throwable was thrown in getCurrentActions(): %s', $e->getMessage()));
Log::error($e->getTraceAsString());
} }
++$index; ++$index;
} }
@@ -634,9 +641,8 @@ class RuleController extends Controller
* *
* @return array * @return array
* *
*/ */
private function getCurrentTriggers(Rule $rule) private function getCurrentTriggers(Rule $rule): array
{ {
$index = 0; $index = 0;
$triggers = []; $triggers = [];
@@ -657,6 +663,7 @@ class RuleController extends Controller
)->render(); )->render();
} catch (Throwable $e) { } catch (Throwable $e) {
Log::debug(sprintf('Throwable was thrown in getCurrentTriggers(): %s', $e->getMessage())); Log::debug(sprintf('Throwable was thrown in getCurrentTriggers(): %s', $e->getMessage()));
Log::error($e->getTraceAsString());
} }
++$index; ++$index;
} }
@@ -670,9 +677,8 @@ class RuleController extends Controller
* *
* @return array * @return array
* *
*/ */
private function getPreviousActions(Request $request) private function getPreviousActions(Request $request): array
{ {
$newIndex = 0; $newIndex = 0;
$actions = []; $actions = [];
@@ -693,6 +699,7 @@ class RuleController extends Controller
)->render(); )->render();
} catch (Throwable $e) { } catch (Throwable $e) {
Log::debug(sprintf('Throwable was thrown in getPreviousActions(): %s', $e->getMessage())); Log::debug(sprintf('Throwable was thrown in getPreviousActions(): %s', $e->getMessage()));
Log::error($e->getTraceAsString());
} }
++$newIndex; ++$newIndex;
} }
@@ -707,7 +714,7 @@ class RuleController extends Controller
* *
*/ */
private function getPreviousTriggers(Request $request) private function getPreviousTriggers(Request $request): array
{ {
$newIndex = 0; $newIndex = 0;
$triggers = []; $triggers = [];
@@ -728,6 +735,7 @@ class RuleController extends Controller
)->render(); )->render();
} catch (Throwable $e) { } catch (Throwable $e) {
Log::debug(sprintf('Throwable was thrown in getPreviousTriggers(): %s', $e->getMessage())); Log::debug(sprintf('Throwable was thrown in getPreviousTriggers(): %s', $e->getMessage()));
Log::error($e->getTraceAsString());
} }
++$newIndex; ++$newIndex;
} }

View File

@@ -108,7 +108,7 @@ class RuleGroupController extends Controller
$repository->destroy($ruleGroup, $moveTo); $repository->destroy($ruleGroup, $moveTo);
Session::flash('success', (string)trans('firefly.deleted_rule_group', ['title' => $title])); session()->flash('success', (string)trans('firefly.deleted_rule_group', ['title' => $title]));
Preferences::mark(); Preferences::mark();
return redirect($this->getPreviousUri('rule-groups.delete.uri')); return redirect($this->getPreviousUri('rule-groups.delete.uri'));
@@ -174,7 +174,7 @@ class RuleGroupController extends Controller
$this->dispatch($job); $this->dispatch($job);
// Tell the user that the job is queued // Tell the user that the job is queued
Session::flash('success', (string)trans('firefly.applied_rule_group_selection', ['title' => $ruleGroup->title])); session()->flash('success', (string)trans('firefly.applied_rule_group_selection', ['title' => $ruleGroup->title]));
return redirect()->route('rules.index'); return redirect()->route('rules.index');
} }
@@ -209,7 +209,7 @@ class RuleGroupController extends Controller
$data = $request->getRuleGroupData(); $data = $request->getRuleGroupData();
$ruleGroup = $repository->store($data); $ruleGroup = $repository->store($data);
Session::flash('success', (string)trans('firefly.created_new_rule_group', ['title' => $ruleGroup->title])); session()->flash('success', (string)trans('firefly.created_new_rule_group', ['title' => $ruleGroup->title]));
Preferences::mark(); Preferences::mark();
if (1 === (int)$request->get('create_another')) { if (1 === (int)$request->get('create_another')) {
@@ -253,7 +253,7 @@ class RuleGroupController extends Controller
$repository->update($ruleGroup, $data); $repository->update($ruleGroup, $data);
Session::flash('success', (string)trans('firefly.updated_rule_group', ['title' => $ruleGroup->title])); session()->flash('success', (string)trans('firefly.updated_rule_group', ['title' => $ruleGroup->title]));
Preferences::mark(); Preferences::mark();
if (1 === (int)$request->get('return_to_edit')) { if (1 === (int)$request->get('return_to_edit')) {

View File

@@ -118,7 +118,7 @@ class TagController extends Controller
$tagName = $tag->tag; $tagName = $tag->tag;
$this->repository->destroy($tag); $this->repository->destroy($tag);
Session::flash('success', (string)trans('firefly.deleted_tag', ['tag' => $tagName])); session()->flash('success', (string)trans('firefly.deleted_tag', ['tag' => $tagName]));
Preferences::mark(); Preferences::mark();
return redirect($this->getPreviousUri('tags.delete.uri')); return redirect($this->getPreviousUri('tags.delete.uri'));
@@ -261,7 +261,7 @@ class TagController extends Controller
$data = $request->collectTagData(); $data = $request->collectTagData();
$this->repository->store($data); $this->repository->store($data);
Session::flash('success', (string)trans('firefly.created_tag', ['tag' => $data['tag']])); session()->flash('success', (string)trans('firefly.created_tag', ['tag' => $data['tag']]));
Preferences::mark(); Preferences::mark();
if (1 === (int)$request->get('create_another')) { if (1 === (int)$request->get('create_another')) {
@@ -286,7 +286,7 @@ class TagController extends Controller
$data = $request->collectTagData(); $data = $request->collectTagData();
$this->repository->update($tag, $data); $this->repository->update($tag, $data);
Session::flash('success', (string)trans('firefly.updated_tag', ['tag' => $data['tag']])); session()->flash('success', (string)trans('firefly.updated_tag', ['tag' => $data['tag']]));
Preferences::mark(); Preferences::mark();
if (1 === (int)$request->get('return_to_edit')) { if (1 === (int)$request->get('return_to_edit')) {

View File

@@ -28,7 +28,6 @@ use ExpandedForm;
use FireflyIII\Http\Controllers\Controller; use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Http\Requests\BulkEditJournalRequest; use FireflyIII\Http\Requests\BulkEditJournalRequest;
use FireflyIII\Models\TransactionJournal; use FireflyIII\Models\TransactionJournal;
use FireflyIII\Models\TransactionType;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface; use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface; use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use FireflyIII\Services\Internal\Update\JournalUpdateService; use FireflyIII\Services\Internal\Update\JournalUpdateService;
@@ -66,70 +65,25 @@ class BulkController extends Controller
} }
/** /**
* @param Request $request
* @param Collection $journals * @param Collection $journals
* *
* @return View * @return View
*/ */
public function edit(Request $request, Collection $journals) public function edit(Collection $journals)
{ {
$subTitle = trans('firefly.mass_bulk_journals'); $subTitle = trans('firefly.mass_bulk_journals');
// skip transactions that have multiple destinations, multiple sources or are an opening balance.
$filtered = new Collection;
$messages = [];
/** @var TransactionJournal $journal */
foreach ($journals as $journal) {
$sources = $this->repository->getJournalSourceAccounts($journal);
$destinations = $this->repository->getJournalDestinationAccounts($journal);
if ($sources->count() > 1) {
$messages[] = trans('firefly.cannot_edit_multiple_source', ['description' => $journal->description, 'id' => $journal->id]);
continue;
}
if ($destinations->count() > 1) {
$messages[] = trans('firefly.cannot_edit_multiple_dest', ['description' => $journal->description, 'id' => $journal->id]);
continue;
}
if (TransactionType::OPENING_BALANCE === $this->repository->getTransactionType($journal)) {
$messages[] = trans('firefly.cannot_edit_opening_balance');
continue;
}
// cannot edit reconciled transactions / journals:
if ($this->repository->isJournalReconciled($journal)) {
$messages[] = trans('firefly.cannot_edit_reconciled', ['description' => $journal->description, 'id' => $journal->id]);
continue;
}
$filtered->push($journal);
}
if (count($messages) > 0) {
$request->session()->flash('info', $messages);
}
// put previous url in session
$this->rememberPreviousUri('transactions.bulk-edit.uri');
// get list of budgets: // get list of budgets:
/** @var BudgetRepositoryInterface $repository */ /** @var BudgetRepositoryInterface $repository */
$repository = app(BudgetRepositoryInterface::class); $repository = app(BudgetRepositoryInterface::class);
$budgetList = ExpandedForm::makeSelectListWithEmpty($repository->getActiveBudgets()); $budgetList = ExpandedForm::makeSelectListWithEmpty($repository->getActiveBudgets());
// collect some useful meta data for the mass edit: // collect some useful meta data for the mass edit:
$filtered->each( $journals->each(
function (TransactionJournal $journal) { function (TransactionJournal $journal) {
$journal->transaction_count = $journal->transactions()->count(); $journal->transaction_count = $journal->transactions()->count();
} }
); );
if (0 === $filtered->count()) {
$request->session()->flash('error', trans('firefly.no_edit_multiple_left'));
}
$journals = $filtered;
return view('transactions.bulk.edit', compact('journals', 'subTitle', 'budgetList')); return view('transactions.bulk.edit', compact('journals', 'subTitle', 'budgetList'));
} }
@@ -142,36 +96,32 @@ class BulkController extends Controller
*/ */
public function update(BulkEditJournalRequest $request, JournalRepositoryInterface $repository) public function update(BulkEditJournalRequest $request, JournalRepositoryInterface $repository)
{ {
/** @var JournalUpdateService $service */
$service = app(JournalUpdateService::class);
$journalIds = $request->get('journals'); $journalIds = $request->get('journals');
$ignoreCategory = (int)$request->get('ignore_category') === 1; $ignoreCategory = (int)$request->get('ignore_category') === 1;
$ignoreBudget = (int)$request->get('ignore_budget') === 1; $ignoreBudget = (int)$request->get('ignore_budget') === 1;
$ignoreTags = (int)$request->get('ignore_tags') === 1; $ignoreTags = (int)$request->get('ignore_tags') === 1;
$count = 0; $count = 0;
if (is_array($journalIds)) { if (\is_array($journalIds)) {
foreach ($journalIds as $journalId) { foreach ($journalIds as $journalId) {
$journal = $repository->find((int)$journalId); $journal = $repository->find((int)$journalId);
if (null !== $journal) { $count++;
$count++; Log::debug(sprintf('Found journal #%d', $journal->id));
Log::debug(sprintf('Found journal #%d', $journal->id));
// update category if not told to ignore
if ($ignoreCategory === false) {
Log::debug(sprintf('Set category to %s', $request->string('category')));
$repository->updateCategory($journal, $request->string('category')); // update category if not told to ignore
} if ($ignoreCategory === false) {
// update budget if not told to ignore (and is withdrawal) Log::debug(sprintf('Set category to %s', $request->string('category')));
if ($ignoreBudget === false) {
Log::debug(sprintf('Set budget to %d', $request->integer('budget_id'))); $repository->updateCategory($journal, $request->string('category'));
$repository->updateBudget($journal, $request->integer('budget_id')); }
} // update budget if not told to ignore (and is withdrawal)
if ($ignoreTags === false) { if ($ignoreBudget === false) {
Log::debug(sprintf('Set tags to %s', $request->string('budget_id'))); Log::debug(sprintf('Set budget to %d', $request->integer('budget_id')));
$repository->updateTags($journal, ['tags' => explode(',', $request->string('tags'))]); $repository->updateBudget($journal, $request->integer('budget_id'));
} }
// update tags if not told to ignore (and is withdrawal) if ($ignoreTags === false) {
Log::debug(sprintf('Set tags to %s', $request->string('budget_id')));
$repository->updateTags($journal, ['tags' => explode(',', $request->string('tags'))]);
} }
} }
} }

View File

@@ -81,14 +81,14 @@ class ConvertController extends Controller
// cannot convert to its own type. // cannot convert to its own type.
if ($sourceType->type === $destinationType->type) { if ($sourceType->type === $destinationType->type) {
Session::flash('info', trans('firefly.convert_is_already_type_' . $destinationType->type)); session()->flash('info', trans('firefly.convert_is_already_type_' . $destinationType->type));
return redirect(route('transactions.show', [$journal->id])); return redirect(route('transactions.show', [$journal->id]));
} }
// cannot convert split. // cannot convert split.
if ($journal->transactions()->count() > 2) { if ($journal->transactions()->count() > 2) {
Session::flash('error', trans('firefly.cannot_convert_split_journal')); session()->flash('error', trans('firefly.cannot_convert_split_journal'));
return redirect(route('transactions.show', [$journal->id])); return redirect(route('transactions.show', [$journal->id]));
} }
@@ -138,13 +138,13 @@ class ConvertController extends Controller
$data = $request->all(); $data = $request->all();
if ($journal->transactionType->type === $destinationType->type) { if ($journal->transactionType->type === $destinationType->type) {
Session::flash('error', trans('firefly.convert_is_already_type_' . $destinationType->type)); session()->flash('error', trans('firefly.convert_is_already_type_' . $destinationType->type));
return redirect(route('transactions.show', [$journal->id])); return redirect(route('transactions.show', [$journal->id]));
} }
if ($journal->transactions()->count() > 2) { if ($journal->transactions()->count() > 2) {
Session::flash('error', trans('firefly.cannot_convert_split_journal')); session()->flash('error', trans('firefly.cannot_convert_split_journal'));
return redirect(route('transactions.show', [$journal->id])); return redirect(route('transactions.show', [$journal->id]));
} }
@@ -160,7 +160,7 @@ class ConvertController extends Controller
return redirect(route('transactions.convert.index', [strtolower($destinationType->type), $journal->id]))->withErrors($errors)->withInput(); return redirect(route('transactions.convert.index', [strtolower($destinationType->type), $journal->id]))->withErrors($errors)->withInput();
} }
Session::flash('success', trans('firefly.converted_to_' . $destinationType->type)); session()->flash('success', trans('firefly.converted_to_' . $destinationType->type));
return redirect(route('transactions.show', [$journal->id])); return redirect(route('transactions.show', [$journal->id]));
} }

View File

@@ -86,7 +86,7 @@ class LinkController extends Controller
{ {
$this->repository->destroyLink($link); $this->repository->destroyLink($link);
Session::flash('success', (string)trans('firefly.deleted_link')); session()->flash('success', (string)trans('firefly.deleted_link'));
Preferences::mark(); Preferences::mark();
return redirect((string)session('journal_links.delete.uri')); return redirect((string)session('journal_links.delete.uri'));
@@ -104,7 +104,7 @@ class LinkController extends Controller
Log::debug('We are here (store)'); Log::debug('We are here (store)');
$linkInfo = $request->getLinkInfo(); $linkInfo = $request->getLinkInfo();
if (0 === $linkInfo['transaction_journal_id']) { if (0 === $linkInfo['transaction_journal_id']) {
Session::flash('error', trans('firefly.invalid_link_selection')); session()->flash('error', trans('firefly.invalid_link_selection'));
return redirect(route('transactions.show', [$journal->id])); return redirect(route('transactions.show', [$journal->id]));
} }
@@ -112,19 +112,19 @@ class LinkController extends Controller
$alreadyLinked = $this->repository->findLink($journal, $other); $alreadyLinked = $this->repository->findLink($journal, $other);
if ($other->id === $journal->id) { if ($other->id === $journal->id) {
Session::flash('error', trans('firefly.journals_link_to_self')); session()->flash('error', trans('firefly.journals_link_to_self'));
return redirect(route('transactions.show', [$journal->id])); return redirect(route('transactions.show', [$journal->id]));
} }
if ($alreadyLinked) { if ($alreadyLinked) {
Session::flash('error', trans('firefly.journals_error_linked')); session()->flash('error', trans('firefly.journals_error_linked'));
return redirect(route('transactions.show', [$journal->id])); return redirect(route('transactions.show', [$journal->id]));
} }
Log::debug(sprintf('Journal is %d, opposing is %d', $journal->id, $other->id)); Log::debug(sprintf('Journal is %d, opposing is %d', $journal->id, $other->id));
$this->repository->storeLink($linkInfo, $other, $journal); $this->repository->storeLink($linkInfo, $other, $journal);
Session::flash('success', trans('firefly.journals_linked')); session()->flash('success', trans('firefly.journals_linked'));
return redirect(route('transactions.show', [$journal->id])); return redirect(route('transactions.show', [$journal->id]));
} }

View File

@@ -108,7 +108,7 @@ class MassController extends Controller
} }
Preferences::mark(); Preferences::mark();
Session::flash('success', trans('firefly.mass_deleted_transactions_success', ['amount' => $count])); session()->flash('success', trans('firefly.mass_deleted_transactions_success', ['amount' => $count]));
// redirect to previous URL: // redirect to previous URL:
return redirect($this->getPreviousUri('transactions.mass-delete.uri')); return redirect($this->getPreviousUri('transactions.mass-delete.uri'));
@@ -163,7 +163,7 @@ class MassController extends Controller
} }
if (count($messages) > 0) { if (count($messages) > 0) {
Session::flash('info', $messages); session()->flash('info', $messages);
} }
// put previous url in session // put previous url in session
@@ -196,7 +196,7 @@ class MassController extends Controller
); );
if (0 === $filtered->count()) { if (0 === $filtered->count()) {
Session::flash('error', trans('firefly.no_edit_multiple_left')); session()->flash('error', trans('firefly.no_edit_multiple_left'));
} }
$journals = $filtered; $journals = $filtered;
@@ -281,7 +281,7 @@ class MassController extends Controller
} }
} }
Preferences::mark(); Preferences::mark();
Session::flash('success', trans('firefly.mass_edited_transactions_success', ['amount' => $count])); session()->flash('success', trans('firefly.mass_edited_transactions_success', ['amount' => $count]));
// redirect to previous URL: // redirect to previous URL:
return redirect($this->getPreviousUri('transactions.mass-edit.uri')); return redirect($this->getPreviousUri('transactions.mass-edit.uri'));

View File

@@ -140,7 +140,7 @@ class SingleController extends Controller
$preFilled['notes'] = $note->text; $preFilled['notes'] = $note->text;
} }
Session::flash('preFilled', $preFilled); session()->flash('preFilled', $preFilled);
return redirect(route('transactions.create', [strtolower($journal->transactionType->type)])); return redirect(route('transactions.create', [strtolower($journal->transactionType->type)]));
} }
@@ -227,7 +227,7 @@ class SingleController extends Controller
} }
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
$type = $transactionJournal->transactionTypeStr(); $type = $transactionJournal->transactionTypeStr();
Session::flash('success', (string)trans('firefly.deleted_' . strtolower($type), ['description' => $transactionJournal->description])); session()->flash('success', (string)trans('firefly.deleted_' . strtolower($type), ['description' => $transactionJournal->description]));
$this->repository->destroy($transactionJournal); $this->repository->destroy($transactionJournal);
@@ -312,7 +312,7 @@ class SingleController extends Controller
$preFilled['currency'] = $pTransaction->foreignCurrency; $preFilled['currency'] = $pTransaction->foreignCurrency;
} }
Session::flash('preFilled', $preFilled); session()->flash('preFilled', $preFilled);
// put previous url in session if not redirect from store (not "return_to_edit"). // put previous url in session if not redirect from store (not "return_to_edit").
if (true !== session('transactions.edit.fromUpdate')) { if (true !== session('transactions.edit.fromUpdate')) {
@@ -343,7 +343,7 @@ class SingleController extends Controller
if (null === $journal->id) { if (null === $journal->id) {
// error! // error!
Log::error('Could not store transaction journal.'); Log::error('Could not store transaction journal.');
Session::flash('error', (string)trans('firefly.unknown_journal_error')); session()->flash('error', (string)trans('firefly.unknown_journal_error'));
return redirect(route('transactions.create', [$request->input('what')]))->withInput(); return redirect(route('transactions.create', [$request->input('what')]))->withInput();
} }
@@ -355,16 +355,16 @@ class SingleController extends Controller
// store the journal only, flash the rest. // store the journal only, flash the rest.
Log::debug(sprintf('Count of error messages is %d', $this->attachments->getErrors()->count())); Log::debug(sprintf('Count of error messages is %d', $this->attachments->getErrors()->count()));
if (\count($this->attachments->getErrors()->get('attachments')) > 0) { if (\count($this->attachments->getErrors()->get('attachments')) > 0) {
Session::flash('error', $this->attachments->getErrors()->get('attachments')); session()->flash('error', $this->attachments->getErrors()->get('attachments'));
} }
// flash messages // flash messages
if (\count($this->attachments->getMessages()->get('attachments')) > 0) { if (\count($this->attachments->getMessages()->get('attachments')) > 0) {
Session::flash('info', $this->attachments->getMessages()->get('attachments')); session()->flash('info', $this->attachments->getMessages()->get('attachments'));
} }
event(new StoredTransactionJournal($journal, $data['piggy_bank_id'])); event(new StoredTransactionJournal($journal, $data['piggy_bank_id']));
Session::flash('success', (string)trans('firefly.stored_journal', ['description' => $journal->description])); session()->flash('success', (string)trans('firefly.stored_journal', ['description' => $journal->description]));
Preferences::mark(); Preferences::mark();
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
@@ -410,10 +410,10 @@ class SingleController extends Controller
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
if (count($this->attachments->getErrors()->get('attachments')) > 0) { if (count($this->attachments->getErrors()->get('attachments')) > 0) {
Session::flash('error', $this->attachments->getErrors()->get('attachments')); session()->flash('error', $this->attachments->getErrors()->get('attachments'));
} }
if (count($this->attachments->getMessages()->get('attachments')) > 0) { if (count($this->attachments->getMessages()->get('attachments')) > 0) {
Session::flash('info', $this->attachments->getMessages()->get('attachments')); session()->flash('info', $this->attachments->getMessages()->get('attachments'));
} }
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
@@ -421,7 +421,7 @@ class SingleController extends Controller
// update, get events by date and sort DESC // update, get events by date and sort DESC
$type = strtolower($this->repository->getTransactionType($journal)); $type = strtolower($this->repository->getTransactionType($journal));
Session::flash('success', (string)trans('firefly.updated_' . $type, ['description' => $data['description']])); session()->flash('success', (string)trans('firefly.updated_' . $type, ['description' => $data['description']]));
Preferences::mark(); Preferences::mark();
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart

View File

@@ -159,12 +159,12 @@ class SplitController extends Controller
// flash messages // flash messages
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
if (count($this->attachments->getMessages()->get('attachments')) > 0) { if (count($this->attachments->getMessages()->get('attachments')) > 0) {
Session::flash('info', $this->attachments->getMessages()->get('attachments')); session()->flash('info', $this->attachments->getMessages()->get('attachments'));
} }
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
$type = strtolower($this->repository->getTransactionType($journal)); $type = strtolower($this->repository->getTransactionType($journal));
Session::flash('success', (string)trans('firefly.updated_' . $type, ['description' => $journal->description])); session()->flash('success', (string)trans('firefly.updated_' . $type, ['description' => $journal->description]));
Preferences::mark(); Preferences::mark();
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart

View File

@@ -0,0 +1,111 @@
<?php
/**
* SimpleJournalList.php
* Copyright (c) 2018 thegrumpydictator@gmail.com
*
* This file is part of Firefly III.
*
* Firefly III is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Firefly III 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Firefly III. If not, see <http://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace FireflyIII\Support\Binder;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Models\TransactionType;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use Illuminate\Routing\Route;
use Illuminate\Support\Collection;
use Session;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* Class SimpleJournalList
*/
class SimpleJournalList implements BinderInterface
{
/**
* @param string $value
* @param Route $route
*
* @return mixed
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public static function routeBinder(string $value, Route $route): Collection
{
if (auth()->check()) {
$list = [];
$incoming = explode(',', $value);
foreach ($incoming as $entry) {
$list[] = (int)$entry;
}
$list = array_unique($list);
if (\count($list) === 0) {
throw new NotFoundHttpException; // @codeCoverageIgnore
}
// prep some vars
$messages = [];
$final = new Collection;
/** @var JournalRepositoryInterface $repository */
$repository = app(JournalRepositoryInterface::class);
// get all journals:
/** @var \Illuminate\Support\Collection $collection */
$collection = auth()->user()->transactionJournals()
->whereIn('transaction_journals.id', $list)
->where('transaction_journals.completed', 1)
->get(['transaction_journals.*']);
// filter the list! Yay!
/** @var TransactionJournal $journal */
foreach ($collection as $journal) {
$sources = $repository->getJournalSourceAccounts($journal);
$destinations = $repository->getJournalDestinationAccounts($journal);
if ($sources->count() > 1) {
$messages[] = trans('firefly.cannot_edit_multiple_source', ['description' => $journal->description, 'id' => $journal->id]);
continue;
}
if ($destinations->count() > 1) {
$messages[] = trans('firefly.cannot_edit_multiple_dest', ['description' => $journal->description, 'id' => $journal->id]);
continue;
}
if (TransactionType::OPENING_BALANCE === $repository->getTransactionType($journal)) {
$messages[] = trans('firefly.cannot_edit_opening_balance');
continue;
}
// cannot edit reconciled transactions / journals:
if ($repository->isJournalReconciled($journal)) {
$messages[] = trans('firefly.cannot_edit_reconciled', ['description' => $journal->description, 'id' => $journal->id]);
continue;
}
$final->push($journal);
}
if ($final->count() > 0) {
if (\count($messages) > 0) {
session()->flash('info', $messages);
}
return $final;
}
}
throw new NotFoundHttpException;
}
}

View File

@@ -165,7 +165,7 @@ return [
'default_export_format' => 'csv', 'default_export_format' => 'csv',
'default_import_format' => 'csv', 'default_import_format' => 'csv',
'bill_periods' => ['weekly', 'monthly', 'quarterly', 'half-year', 'yearly'], 'bill_periods' => ['weekly', 'monthly', 'quarterly', 'half-year', 'yearly'],
'accountRoles' => ['defaultAsset', 'sharedAsset', 'savingAsset', 'ccAsset','cashWalletAsset'], 'accountRoles' => ['defaultAsset', 'sharedAsset', 'savingAsset', 'ccAsset', 'cashWalletAsset'],
'ccTypes' => [ 'ccTypes' => [
'monthlyFull' => 'Full payment every month', 'monthlyFull' => 'Full payment every month',
], ],
@@ -296,6 +296,7 @@ return [
'journalList' => \FireflyIII\Support\Binder\JournalList::class, 'journalList' => \FireflyIII\Support\Binder\JournalList::class,
'categoryList' => \FireflyIII\Support\Binder\CategoryList::class, 'categoryList' => \FireflyIII\Support\Binder\CategoryList::class,
'tagList' => \FireflyIII\Support\Binder\TagList::class, 'tagList' => \FireflyIII\Support\Binder\TagList::class,
'simpleJournalList' => \FireflyIII\Support\Binder\SimpleJournalList::class,
// others // others
'fromCurrencyCode' => \FireflyIII\Support\Binder\CurrencyCode::class, 'fromCurrencyCode' => \FireflyIII\Support\Binder\CurrencyCode::class,

View File

@@ -835,7 +835,7 @@ Route::group(
Route::group( Route::group(
['middleware' => 'user-full-auth', 'namespace' => 'FireflyIII\Http\Controllers\Transaction', 'prefix' => 'transactions/bulk', 'as' => 'transactions.bulk.'], ['middleware' => 'user-full-auth', 'namespace' => 'FireflyIII\Http\Controllers\Transaction', 'prefix' => 'transactions/bulk', 'as' => 'transactions.bulk.'],
function () { function () {
Route::get('edit/{journalList}', ['uses' => 'BulkController@edit', 'as' => 'edit']); Route::get('edit/{simpleJournalList}', ['uses' => 'BulkController@edit', 'as' => 'edit']);
Route::post('update', ['uses' => 'BulkController@update', 'as' => 'update']); Route::post('update', ['uses' => 'BulkController@update', 'as' => 'update']);
} }
); );