Esempio n. 1
0
 /**
  * Shows all bills and whether or not theyve been paid this month (pie chart).
  *
  * @param BillRepositoryInterface    $repository
  * @param AccountRepositoryInterface $accounts
  *
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function frontpage(BillRepositoryInterface $repository, AccountRepositoryInterface $accounts)
 {
     $start = Session::get('start', Carbon::now()->startOfMonth());
     $end = Session::get('end', Carbon::now()->endOfMonth());
     // chart properties for cache:
     $cache = new CacheProperties();
     $cache->addProperty($start);
     $cache->addProperty($end);
     $cache->addProperty('bills');
     $cache->addProperty('frontpage');
     if ($cache->has()) {
         return Response::json($cache->get());
         // @codeCoverageIgnore
     }
     $bills = $repository->getActiveBills();
     $paid = new Collection();
     // journals.
     $unpaid = new Collection();
     // bills
     /** @var Bill $bill */
     foreach ($bills as $bill) {
         $ranges = $repository->getRanges($bill, $start, $end);
         foreach ($ranges as $range) {
             // paid a bill in this range?
             $journals = $repository->getJournalsInRange($bill, $range['start'], $range['end']);
             if ($journals->count() == 0) {
                 $unpaid->push([$bill, $range['start']]);
             } else {
                 $paid = $paid->merge($journals);
             }
         }
     }
     $creditCards = $accounts->getCreditCards();
     foreach ($creditCards as $creditCard) {
         $balance = Steam::balance($creditCard, $end, true);
         $date = new Carbon($creditCard->getMeta('ccMonthlyPaymentDate'));
         if ($balance < 0) {
             // unpaid! create a fake bill that matches the amount.
             $description = $creditCard->name;
             $amount = $balance * -1;
             $fakeBill = $repository->createFakeBill($description, $date, $amount);
             unset($description, $amount);
             $unpaid->push([$fakeBill, $date]);
         }
         if ($balance == 0) {
             // find transfer(s) TO the credit card which should account for
             // anything paid. If not, the CC is not yet used.
             $journals = $accounts->getTransfersInRange($creditCard, $start, $end);
             $paid = $paid->merge($journals);
         }
     }
     // build chart:
     $data = $this->generator->frontpage($paid, $unpaid);
     $cache->store($data);
     return Response::json($data);
 }
 /**
  * @param AccountRepositoryInterface $repository
  *
  * @return $this|\Illuminate\View\View
  */
 public function index(AccountRepositoryInterface $repository)
 {
     $accounts = $repository->getAccounts(['Default account', 'Asset account']);
     $viewRangePref = Preferences::get('viewRange', '1M');
     $viewRange = $viewRangePref->data;
     $frontPageAccounts = Preferences::get('frontPageAccounts', []);
     $budgetMax = Preferences::get('budgetMaximum', 1000);
     $language = Preferences::get('language', 'en')->data;
     $budgetMaximum = $budgetMax->data;
     return view('preferences.index', compact('budgetMaximum', 'language', 'accounts', 'frontPageAccounts', 'viewRange'));
 }
 /**
  * @param ARI $repository
  *
  * @@return View
  */
 public function index(ARI $repository)
 {
     View::share('title', trans('firefly.welcome'));
     View::share('mainTitleIcon', 'fa-fire');
     $types = config('firefly.accountTypesByIdentifier.asset');
     $count = $repository->countAccounts($types);
     if ($count > 0) {
         return redirect(route('index'));
     }
     return view('new-user.index');
 }
 /**
  * @param ARI $repository
  *
  * @return $this|\Illuminate\View\View
  */
 public function index(ARI $repository)
 {
     $accounts = $repository->getAccounts(['Default account', 'Asset account']);
     $viewRangePref = Preferences::get('viewRange', '1M');
     $viewRange = $viewRangePref->data;
     $frontPageAccounts = Preferences::get('frontPageAccounts', []);
     $budgetMax = Preferences::get('budgetMaximum', 1000);
     $language = Preferences::get('language', env('DEFAULT_LANGUAGE', 'en_US'))->data;
     $budgetMaximum = $budgetMax->data;
     $showIncomplete = env('SHOW_INCOMPLETE_TRANSLATIONS', 'false') == 'true';
     return view('preferences.index', compact('budgetMaximum', 'language', 'accounts', 'frontPageAccounts', 'viewRange', 'showIncomplete'));
 }
Esempio n. 5
0
 /**
  * @param AccountRepositoryInterface $repository
  *
  * @return View
  * @internal param ReportHelperInterface $helper
  */
 public function index(AccountRepositoryInterface $repository)
 {
     $start = Session::get('first');
     $months = $this->helper->listOfMonths($start);
     // does the user have shared accounts?
     $accounts = $repository->getAccounts(['Default account', 'Asset account']);
     $hasShared = false;
     /** @var Account $account */
     foreach ($accounts as $account) {
         if ($account->getMeta('accountRole') == 'sharedAsset') {
             $hasShared = true;
         }
     }
     return view('reports.index', compact('months', 'hasShared'));
 }
Esempio n. 6
0
 /**
  * @param AccountRepositoryInterface $repository
  *
  * @return \Illuminate\Http\RedirectResponse|\Illuminate\View\View
  */
 public function index(AccountRepositoryInterface $repository)
 {
     $types = Config::get('firefly.accountTypesByIdentifier.asset');
     $count = $repository->countAccounts($types);
     bcscale(2);
     if ($count == 0) {
         return redirect(route('new-user.index'));
     }
     $title = 'Firefly';
     $subTitle = trans('firefly.welcomeBack');
     $mainTitleIcon = 'fa-fire';
     $transactions = [];
     $frontPage = Preferences::get('frontPageAccounts', []);
     $start = Session::get('start', Carbon::now()->startOfMonth());
     $end = Session::get('end', Carbon::now()->endOfMonth());
     $showTour = Preferences::get('tour', true)->data;
     $accounts = $repository->getFrontpageAccounts($frontPage);
     $savings = $repository->getSavingsAccounts();
     $piggyBankAccounts = $repository->getPiggyBankAccounts();
     $savingsTotal = 0;
     foreach ($savings as $savingAccount) {
         $savingsTotal = bcadd($savingsTotal, Steam::balance($savingAccount, $end));
     }
     $sum = $repository->sumOfEverything();
     if ($sum != 0) {
         Session::flash('error', 'Your transactions are unbalanced. This means a' . ' withdrawal, deposit or transfer was not stored properly. ' . 'Please check your accounts and transactions for errors.');
     }
     foreach ($accounts as $account) {
         $set = $repository->getFrontpageTransactions($account, $start, $end);
         if (count($set) > 0) {
             $transactions[] = [$set, $account];
         }
     }
     return view('index', compact('count', 'showTour', 'title', 'savings', 'subTitle', 'mainTitleIcon', 'transactions', 'savingsTotal', 'piggyBankAccounts'));
 }
Esempio n. 7
0
 /**
  * Shows the balances for all the user's frontpage accounts.
  *
  * @param AccountRepositoryInterface $repository
  *
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function frontpage(AccountRepositoryInterface $repository)
 {
     $frontPage = Preferences::get('frontPageAccounts', []);
     $start = clone Session::get('start', Carbon::now()->startOfMonth());
     $end = clone Session::get('end', Carbon::now()->endOfMonth());
     $accounts = $repository->getFrontpageAccounts($frontPage);
     // chart properties for cache:
     $cache = new CacheProperties();
     $cache->addProperty($start);
     $cache->addProperty($end);
     $cache->addProperty('frontpage');
     $cache->addProperty('accounts');
     if ($cache->has()) {
         return Response::json($cache->get());
         // @codeCoverageIgnore
     }
     $data = $this->generator->frontpage($accounts, $start, $end);
     $cache->store($data);
     return Response::json($data);
 }
Esempio n. 8
0
 /**
  * @param NewUserFormRequest         $request
  * @param AccountRepositoryInterface $repository
  *
  * @return \Illuminate\Http\RedirectResponse
  */
 public function submit(NewUserFormRequest $request, AccountRepositoryInterface $repository)
 {
     // create normal asset account:
     $assetAccount = ['name' => $request->get('bank_name'), 'iban' => null, 'accountType' => 'asset', 'virtualBalance' => 0, 'active' => true, 'user' => Auth::user()->id, 'accountRole' => 'defaultAsset', 'openingBalance' => round($request->input('bank_balance'), 2), 'openingBalanceDate' => new Carbon(), 'openingBalanceCurrency' => intval($request->input('balance_currency_id'))];
     $repository->store($assetAccount);
     // create savings account
     if (strlen($request->get('savings_balance') > 0)) {
         $savingsAccount = ['name' => $request->get('bank_name') . ' savings account', 'iban' => null, 'accountType' => 'asset', 'virtualBalance' => 0, 'active' => true, 'user' => Auth::user()->id, 'accountRole' => 'savingAsset', 'openingBalance' => round($request->input('savings_balance'), 2), 'openingBalanceDate' => new Carbon(), 'openingBalanceCurrency' => intval($request->input('balance_currency_id'))];
         $repository->store($savingsAccount);
     }
     // create credit card.
     if (strlen($request->get('credit_card_limit') > 0)) {
         $creditAccount = ['name' => 'Credit card', 'iban' => null, 'accountType' => 'asset', 'virtualBalance' => round($request->get('credit_card_limit'), 2), 'active' => true, 'user' => Auth::user()->id, 'accountRole' => 'ccAsset', 'openingBalance' => null, 'openingBalanceDate' => null, 'openingBalanceCurrency' => intval($request->input('balance_currency_id'))];
         $creditCard = $repository->store($creditAccount);
         // store meta for CC:
         AccountMeta::create(['name' => 'ccType', 'data' => 'monthlyFull', 'account_id' => $creditCard->id]);
         AccountMeta::create(['name' => 'ccMonthlyPaymentDate', 'data' => Carbon::now()->year . '-01-01', 'account_id' => $creditCard->id]);
     }
     Session::flash('success', 'New account(s) created!');
     Preferences::mark();
     return redirect(route('index'));
 }
 /**
  * @param ARI $repository
  *
  * @return View
  * @internal param ReportHelperInterface $helper
  */
 public function index(ARI $repository)
 {
     $start = Session::get('first');
     $months = $this->helper->listOfMonths($start);
     $startOfMonth = clone Session::get('start');
     $endOfMonth = clone Session::get('start');
     $startOfYear = clone Session::get('start');
     $endOfYear = clone Session::get('start');
     $startOfMonth->startOfMonth();
     $endOfMonth->endOfMonth();
     $startOfYear->startOfYear();
     $endOfYear->endOfYear();
     // does the user have shared accounts?
     $accounts = $repository->getAccounts(['Default account', 'Asset account']);
     // get id's for quick links:
     $accountIds = [];
     /** @var Account $account */
     foreach ($accounts as $account) {
         $accountIds[] = $account->id;
     }
     $accountList = join(',', $accountIds);
     return view('reports.index', compact('months', 'accounts', 'start', 'accountList', 'startOfMonth', 'endOfMonth', 'startOfYear', 'endOfYear'));
 }
 /**
  * @param AccountFormRequest $request
  * @param ARI                $repository
  * @param Account            $account
  *
  * @return \Illuminate\Http\RedirectResponse
  */
 public function update(AccountFormRequest $request, ARI $repository, Account $account)
 {
     $accountData = ['name' => $request->input('name'), 'active' => $request->input('active'), 'user' => Auth::user()->id, 'iban' => $request->input('iban'), 'accountRole' => $request->input('accountRole'), 'virtualBalance' => round($request->input('virtualBalance'), 2), 'openingBalance' => round($request->input('openingBalance'), 2), 'openingBalanceDate' => new Carbon((string) $request->input('openingBalanceDate')), 'openingBalanceCurrency' => intval($request->input('balance_currency_id')), 'ccType' => $request->input('ccType'), 'ccMonthlyPaymentDate' => $request->input('ccMonthlyPaymentDate')];
     $repository->update($account, $accountData);
     Session::flash('success', 'Account "' . $account->name . '" updated.');
     Preferences::mark();
     if (intval(Input::get('return_to_edit')) === 1) {
         // set value so edit routine will not overwrite URL:
         Session::put('accounts.edit.fromUpdate', true);
         return redirect(route('accounts.edit', [$account->id]))->withInput(['return_to_edit' => 1]);
     }
     // redirect to previous URL.
     return redirect(Session::get('accounts.edit.url'));
 }
Esempio n. 11
0
 /**
  * Shows the view to edit a transaction.
  *
  * @param ARI                $repository
  * @param TransactionJournal $journal
  *
  * @return $this
  */
 public function edit(ARI $repository, TransactionJournal $journal)
 {
     // cannot edit opening balance
     if ($journal->isOpeningBalance()) {
         return view('error')->with('message', 'Cannot edit this transaction. Edit the account instead!');
     }
     $maxFileSize = Steam::phpBytes(ini_get('upload_max_filesize'));
     $maxPostSize = Steam::phpBytes(ini_get('post_max_size'));
     $uploadSize = min($maxFileSize, $maxPostSize);
     $what = strtolower($journal->getTransactionType());
     $accounts = ExpandedForm::makeSelectList($repository->getAccounts(['Default account', 'Asset account']));
     $budgets = ExpandedForm::makeSelectList(Auth::user()->budgets()->get());
     $budgets[0] = trans('form.noBudget');
     $piggies = ExpandedForm::makeSelectList(Auth::user()->piggyBanks()->get());
     $piggies[0] = trans('form.noPiggybank');
     $subTitle = trans('breadcrumbs.edit_journal', ['description' => $journal->description]);
     $preFilled = ['date' => $journal->date->format('Y-m-d'), 'category' => '', 'budget_id' => 0, 'piggy_bank_id' => 0];
     // get tags:
     $preFilled['tags'] = join(',', $journal->tags->pluck('tag')->toArray());
     $category = $journal->categories()->first();
     if (!is_null($category)) {
         $preFilled['category'] = $category->name;
     }
     $budget = $journal->budgets()->first();
     if (!is_null($budget)) {
         $preFilled['budget_id'] = $budget->id;
     }
     if ($journal->piggyBankEvents()->count() > 0) {
         $preFilled['piggy_bank_id'] = $journal->piggyBankEvents()->orderBy('date', 'DESC')->first()->piggy_bank_id;
     }
     $preFilled['amount'] = $journal->amount_positive;
     if ($journal->isWithdrawal()) {
         $preFilled['account_id'] = $journal->source_account->id;
         $preFilled['expense_account'] = $journal->destination_account->name_for_editform;
     } else {
         $preFilled['account_id'] = $journal->destination_account->id;
         $preFilled['revenue_account'] = $journal->source_account->name_for_editform;
     }
     $preFilled['account_from_id'] = $journal->source_account->id;
     $preFilled['account_to_id'] = $journal->destination_account->id;
     Session::flash('preFilled', $preFilled);
     Session::flash('gaEventCategory', 'transactions');
     Session::flash('gaEventAction', 'edit-' . $what);
     // put previous url in session if not redirect from store (not "return_to_edit").
     if (Session::get('transactions.edit.fromUpdate') !== true) {
         Session::put('transactions.edit.url', URL::previous());
     }
     Session::forget('transactions.edit.fromUpdate');
     return view('transactions.edit', compact('journal', 'uploadSize', 'accounts', 'what', 'budgets', 'piggies', 'subTitle'))->with('data', $preFilled);
 }
Esempio n. 12
0
 /**
  * @param PiggyBankRepositoryInterface $repository
  * @param ARI                          $accounts
  * @param PiggyBank                    $piggyBank
  *
  * @return \Illuminate\Http\RedirectResponse
  */
 public function postAdd(PiggyBankRepositoryInterface $repository, ARI $accounts, PiggyBank $piggyBank)
 {
     bcscale(2);
     $amount = round(Input::get('amount'), 2);
     $date = Session::get('end', Carbon::now()->endOfMonth());
     $leftOnAccount = $accounts->leftOnAccount($piggyBank->account, $date);
     $savedSoFar = $piggyBank->currentRelevantRep()->currentamount;
     $leftToSave = bcsub($piggyBank->targetamount, $savedSoFar);
     $maxAmount = round(min($leftOnAccount, $leftToSave), 2);
     if ($amount <= $maxAmount) {
         $repetition = $piggyBank->currentRelevantRep();
         $repetition->currentamount = bcadd($repetition->currentamount, $amount);
         $repetition->save();
         // create event
         $repository->createEvent($piggyBank, $amount);
         Session::flash('success', 'Added ' . Amount::format($amount, false) . ' to "' . e($piggyBank->name) . '".');
         Preferences::mark();
     } else {
         Log::error('Cannot add ' . $amount . ' because max amount is ' . $maxAmount . ' (left on account is ' . $leftOnAccount . ')');
         Session::flash('error', 'Could not add ' . Amount::format($amount, false) . ' to "' . e($piggyBank->name) . '".');
     }
     return redirect(route('piggy-banks.index'));
 }
Esempio n. 13
0
 /**
  * @param PiggyBankRepositoryInterface $repository
  * @param AccountRepositoryInterface   $accounts
  * @param PiggyBank                    $piggyBank
  *
  * @return \Illuminate\Http\RedirectResponse
  */
 public function postAdd(PiggyBankRepositoryInterface $repository, AccountRepositoryInterface $accounts, PiggyBank $piggyBank)
 {
     $amount = round(floatval(Input::get('amount')), 2);
     $date = Session::get('end', Carbon::now()->endOfMonth());
     $leftOnAccount = $accounts->leftOnAccount($piggyBank->account, $date);
     $savedSoFar = $piggyBank->currentRelevantRep()->currentamount;
     $leftToSave = $piggyBank->targetamount - $savedSoFar;
     $maxAmount = round(min($leftOnAccount, $leftToSave), 2);
     if ($amount <= $maxAmount) {
         $repetition = $piggyBank->currentRelevantRep();
         $repetition->currentamount += $amount;
         $repetition->save();
         // create event
         $repository->createEvent($piggyBank, $amount);
         Session::flash('success', 'Added ' . Amount::format($amount, false) . ' to "' . e($piggyBank->name) . '".');
         Preferences::mark();
     } else {
         Session::flash('error', 'Could not add ' . Amount::format($amount, false) . ' to "' . e($piggyBank->name) . '".');
     }
     return Redirect::route('piggy-banks.index');
 }
 /**
  * @param ARI     $repository
  * @param Account $account
  * @param string  $date
  *
  * @return View
  */
 public function showWithDate(ARI $repository, Account $account, string $date)
 {
     $carbon = new Carbon($date);
     $range = Preferences::get('viewRange', '1M')->data;
     $start = Navigation::startOfPeriod($carbon, $range);
     $end = Navigation::endOfPeriod($carbon, $range);
     $subTitle = $account->name . ' (' . Navigation::periodShow($start, $range) . ')';
     $page = intval(Input::get('page'));
     $page = $page === 0 ? 1 : $page;
     $pageSize = Preferences::get('transactionPageSize', 50)->data;
     $offset = ($page - 1) * $pageSize;
     $set = $repository->journalsInPeriod(new Collection([$account]), [], $start, $end);
     $count = $set->count();
     $subSet = $set->splice($offset, $pageSize);
     $journals = new LengthAwarePaginator($subSet, $count, $pageSize, $page);
     $journals->setPath('accounts/show/' . $account->id . '/' . $date);
     return view('accounts.show_with_date', compact('category', 'date', 'account', 'journals', 'subTitle', 'carbon'));
 }
Esempio n. 15
0
 /**
  * @param BudgetRepositoryInterface $repository
  *
  * @param ARI                       $accountRepository
  *
  * @return \Illuminate\View\View
  */
 public function index(BudgetRepositoryInterface $repository, ARI $accountRepository)
 {
     $budgets = $repository->getActiveBudgets();
     $inactive = $repository->getInactiveBudgets();
     $spent = '0';
     $budgeted = '0';
     $range = Preferences::get('viewRange', '1M')->data;
     $start = Navigation::startOfPeriod(Session::get('start', new Carbon()), $range);
     $end = Navigation::endOfPeriod($start, $range);
     $key = 'budgetIncomeTotal' . $start->format('Ymd') . $end->format('Ymd');
     $budgetIncomeTotal = Preferences::get($key, 1000)->data;
     $period = Navigation::periodShow($start, $range);
     $accounts = $accountRepository->getAccounts(['Default account', 'Asset account', 'Cash account']);
     bcscale(2);
     /**
      * Do some cleanup:
      */
     $repository->cleanupBudgets();
     // loop the budgets:
     /** @var Budget $budget */
     foreach ($budgets as $budget) {
         $budget->spent = $repository->balanceInPeriod($budget, $start, $end, $accounts);
         $budget->currentRep = $repository->getCurrentRepetition($budget, $start, $end);
         if ($budget->currentRep) {
             $budgeted = bcadd($budgeted, $budget->currentRep->amount);
         }
         $spent = bcadd($spent, $budget->spent);
     }
     $budgetMaximum = Preferences::get('budgetMaximum', 1000)->data;
     $defaultCurrency = Amount::getDefaultCurrency();
     return view('budgets.index', compact('budgetMaximum', 'period', 'range', 'budgetIncomeTotal', 'defaultCurrency', 'inactive', 'budgets', 'spent', 'budgeted'));
 }
 /**
  * @param ARI                  $repository
  * @param AccountCrudInterface $crud
  *
  * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
  */
 public function index(ARI $repository, AccountCrudInterface $crud)
 {
     $types = config('firefly.accountTypesByIdentifier.asset');
     $count = $repository->countAccounts($types);
     if ($count == 0) {
         return redirect(route('new-user.index'));
     }
     $title = 'Firefly';
     $subTitle = trans('firefly.welcomeBack');
     $mainTitleIcon = 'fa-fire';
     $transactions = [];
     $frontPage = Preferences::get('frontPageAccounts', $crud->getAccountsByType([AccountType::DEFAULT, AccountType::ASSET])->pluck('id')->toArray());
     /** @var Carbon $start */
     $start = session('start', Carbon::now()->startOfMonth());
     /** @var Carbon $end */
     $end = session('end', Carbon::now()->endOfMonth());
     $showTour = Preferences::get('tour', true)->data;
     $accounts = $crud->getAccountsById($frontPage->data);
     $savings = $repository->getSavingsAccounts($start, $end);
     $piggyBankAccounts = $repository->getPiggyBankAccounts($start, $end);
     $savingsTotal = '0';
     foreach ($savings as $savingAccount) {
         $savingsTotal = bcadd($savingsTotal, Steam::balance($savingAccount, $end));
     }
     foreach ($accounts as $account) {
         $set = $repository->journalsInPeriod(new Collection([$account]), [], $start, $end);
         $set = $set->splice(0, 10);
         if (count($set) > 0) {
             $transactions[] = [$set, $account];
         }
     }
     return view('index', compact('count', 'showTour', 'title', 'savings', 'subTitle', 'mainTitleIcon', 'transactions', 'savingsTotal', 'piggyBankAccounts'));
 }
Esempio n. 17
0
 /**
  * This method shows the initial upload form.
  *
  * STEP ONE
  *
  * @return \Illuminate\View\View
  */
 public function index(AccountRepositoryInterface $repository)
 {
     $subTitle = trans('firefly.csv_import');
     Session::forget('csv-date-format');
     Session::forget('csv-has-headers');
     Session::forget('csv-file');
     Session::forget('csv-import-account');
     Session::forget('csv-map');
     Session::forget('csv-roles');
     Session::forget('csv-mapped');
     Session::forget('csv-specifix');
     // get list of supported specifix
     $specifix = [];
     foreach (Config::get('csv.specifix') as $entry) {
         $specifix[$entry] = trans('firefly.csv_specifix_' . $entry);
     }
     // get a list of asset accounts:
     $accounts = ExpandedForm::makeSelectList($repository->getAccounts(['Asset account', 'Default account']));
     // can actually upload?
     $uploadPossible = is_writable(storage_path('upload'));
     $path = storage_path('upload');
     return view('csv.index', compact('subTitle', 'uploadPossible', 'path', 'specifix', 'accounts'));
 }
Esempio n. 18
0
 /**
  * @param AccountRepositoryInterface $accountRepository
  *
  * @return \Illuminate\Http\JsonResponse
  */
 public function revenueAccounts(AccountRepositoryInterface $accountRepository)
 {
     $list = $accountRepository->getAccounts(['Revenue account']);
     $return = [];
     foreach ($list as $entry) {
         $return[] = $entry->name;
     }
     return Response::json($return);
 }
 /**
  * @param PiggyBankRepositoryInterface $repository
  * @param ARI                          $accounts
  * @param PiggyBank                    $piggyBank
  *
  * @return \Illuminate\Http\RedirectResponse
  */
 public function postAdd(PiggyBankRepositoryInterface $repository, ARI $accounts, PiggyBank $piggyBank)
 {
     $amount = strval(round(Input::get('amount'), 2));
     /** @var Carbon $date */
     $date = session('end', Carbon::now()->endOfMonth());
     $leftOnAccount = $accounts->leftOnAccount($piggyBank->account, $date);
     $savedSoFar = strval($piggyBank->currentRelevantRep()->currentamount);
     $leftToSave = bcsub($piggyBank->targetamount, $savedSoFar);
     $maxAmount = round(min($leftOnAccount, $leftToSave), 2);
     if ($amount <= $maxAmount) {
         $repetition = $piggyBank->currentRelevantRep();
         $currentAmount = $repetition->currentamount ?? '0';
         $repetition->currentamount = bcadd($currentAmount, $amount);
         $repetition->save();
         // create event
         $repository->createEvent($piggyBank, $amount);
         Session::flash('success', strval(trans('firefly.added_amount_to_piggy', ['amount' => Amount::format($amount, false), 'name' => e($piggyBank->name)])));
         Preferences::mark();
         return redirect(route('piggy-banks.index'));
     }
     Log::error('Cannot add ' . $amount . ' because max amount is ' . $maxAmount . ' (left on account is ' . $leftOnAccount . ')');
     Session::flash('error', strval(trans('firefly.cannot_add_amount_piggy', ['amount' => Amount::format($amount, false), 'name' => e($piggyBank->name)])));
     return redirect(route('piggy-banks.index'));
 }
 /**
  * @param ARI                  $accountRepository
  * @param AccountCrudInterface $crud
  *
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function boxOut(ARI $accountRepository, AccountCrudInterface $crud)
 {
     $start = session('start', Carbon::now()->startOfMonth());
     $end = session('end', Carbon::now()->endOfMonth());
     // works for json too!
     $cache = new CacheProperties();
     $cache->addProperty($start);
     $cache->addProperty($end);
     $cache->addProperty('box-out');
     if ($cache->has()) {
         return Response::json($cache->get());
     }
     $accounts = $crud->getAccountsByType([AccountType::DEFAULT, AccountType::ASSET, AccountType::CASH]);
     $amount = $accountRepository->spentInPeriod($accounts, $start, $end);
     $data = ['box' => 'out', 'amount' => Amount::format($amount, false), 'amount_raw' => $amount];
     $cache->store($data);
     return Response::json($data);
 }
Esempio n. 21
0
 /**
  * Shows a budget list with spent/left/overspent.
  *
  * @param BudgetRepositoryInterface $repository
  *
  * @param ARI                       $accountRepository
  *
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function frontpage(BudgetRepositoryInterface $repository, ARI $accountRepository)
 {
     $start = Session::get('start', Carbon::now()->startOfMonth());
     $end = Session::get('end', Carbon::now()->endOfMonth());
     // chart properties for cache:
     $cache = new CacheProperties();
     $cache->addProperty($start);
     $cache->addProperty($end);
     $cache->addProperty('budget');
     $cache->addProperty('all');
     if ($cache->has()) {
         return Response::json($cache->get());
         // @codeCoverageIgnore
     }
     $budgets = $repository->getBudgetsAndLimitsInRange($start, $end);
     $allEntries = new Collection();
     $accounts = $accountRepository->getAccounts(['Default account', 'Asset account', 'Cash account']);
     bcscale(2);
     /** @var Budget $budget */
     foreach ($budgets as $budget) {
         // we already have amount, startdate and enddate.
         // if this "is" a limit repetition (as opposed to a budget without one entirely)
         // depends on whether startdate and enddate are null.
         $name = $budget->name;
         if (is_null($budget->startdate) && is_null($budget->enddate)) {
             $currentStart = clone $start;
             $currentEnd = clone $end;
             $expenses = $repository->balanceInPeriod($budget, $currentStart, $currentEnd, $accounts);
             $amount = 0;
             $left = 0;
             $spent = $expenses;
             $overspent = 0;
         } else {
             $currentStart = clone $budget->startdate;
             $currentEnd = clone $budget->enddate;
             $expenses = $repository->balanceInPeriod($budget, $currentStart, $currentEnd, $accounts);
             $amount = $budget->amount;
             // smaller than 1 means spent MORE than budget allows.
             $left = bccomp(bcadd($budget->amount, $expenses), '0') < 1 ? 0 : bcadd($budget->amount, $expenses);
             $spent = bccomp(bcadd($budget->amount, $expenses), '0') < 1 ? $amount * -1 : $expenses;
             $overspent = bccomp(bcadd($budget->amount, $expenses), '0') < 1 ? bcadd($budget->amount, $expenses) : 0;
         }
         $allEntries->push([$name, $left, $spent, $overspent, $amount, $expenses]);
     }
     $noBudgetExpenses = $repository->getWithoutBudgetSum($start, $end);
     $allEntries->push([trans('firefly.noBudget'), 0, 0, $noBudgetExpenses, 0, 0]);
     $data = $this->generator->frontpage($allEntries);
     $cache->store($data);
     return Response::json($data);
 }
 /**
  * @param AccountRepositoryInterface $repository
  * @param string                     $reportType
  * @param Carbon                     $start
  * @param Carbon                     $end
  * @param Collection                 $accounts
  *
  * @return \Illuminate\Http\JsonResponse
  */
 public function yearInOutSummarized(AccountRepositoryInterface $repository, string $reportType, Carbon $start, Carbon $end, Collection $accounts)
 {
     // chart properties for cache:
     $cache = new CacheProperties();
     $cache->addProperty('yearInOutSummarized');
     $cache->addProperty($start);
     $cache->addProperty($end);
     $cache->addProperty($reportType);
     $cache->addProperty($accounts);
     if ($cache->has()) {
         return Response::json($cache->get());
     }
     // always per month.
     $currentStart = clone $start;
     $spentArray = [];
     $earnedArray = [];
     while ($currentStart <= $end) {
         $currentEnd = Navigation::endOfPeriod($currentStart, '1M');
         $date = $currentStart->format('Y-m');
         $spent = $repository->spentInPeriod($accounts, $currentStart, $currentEnd);
         $earned = $repository->earnedInPeriod($accounts, $currentStart, $currentEnd);
         $spentArray[$date] = bcmul($spent, '-1');
         $earnedArray[$date] = $earned;
         $currentStart = Navigation::addPeriod($currentStart, '1M', 0);
     }
     if ($start->diffInMonths($end) > 12) {
         // per year
         $data = $this->multiYearInOutSummarized($earnedArray, $spentArray, $start, $end);
         $cache->store($data);
         return Response::json($data);
     }
     // per month!
     $data = $this->singleYearInOutSummarized($earnedArray, $spentArray, $start, $end);
     $cache->store($data);
     return Response::json($data);
 }
 /**
  * @param ExportFormRequest $request
  * @param ARI               $repository
  *
  * @param EJRI              $jobs
  *
  * @return string
  * @throws \FireflyIII\Exceptions\FireflyException
  */
 public function postIndex(ExportFormRequest $request, ARI $repository, EJRI $jobs)
 {
     set_time_limit(0);
     $job = $jobs->findByKey($request->get('job'));
     $settings = ['accounts' => $repository->get($request->get('accounts')), 'startDate' => new Carbon($request->get('export_start_range')), 'endDate' => new Carbon($request->get('export_end_range')), 'exportFormat' => $request->get('exportFormat'), 'includeAttachments' => intval($request->get('include_attachments')) === 1, 'includeConfig' => intval($request->get('include_config')) === 1, 'includeOldUploads' => intval($request->get('include_old_uploads')) === 1, 'job' => $job];
     $job->change('export_status_make_exporter');
     $processor = new Processor($settings);
     /*
      * Collect journals:
      */
     $job->change('export_status_collecting_journals');
     $processor->collectJournals();
     $job->change('export_status_collected_journals');
     /*
      * Transform to exportable entries:
      */
     $job->change('export_status_converting_to_export_format');
     $processor->convertJournals();
     $job->change('export_status_converted_to_export_format');
     /*
      * Transform to (temporary) file:
      */
     $job->change('export_status_creating_journal_file');
     $processor->exportJournals();
     $job->change('export_status_created_journal_file');
     /*
      *  Collect attachments, if applicable.
      */
     if ($settings['includeAttachments']) {
         $job->change('export_status_collecting_attachments');
         $processor->collectAttachments();
         $job->change('export_status_collected_attachments');
     }
     /*
      * Collect old uploads
      */
     if ($settings['includeOldUploads']) {
         $job->change('export_status_collecting_old_uploads');
         $processor->collectOldUploads();
         $job->change('export_status_collected_old_uploads');
     }
     /*
      * Generate / collect config file.
      */
     if ($settings['includeConfig']) {
         $job->change('export_status_creating_config_file');
         $processor->createConfigFile();
         $job->change('export_status_created_config_file');
     }
     /*
      * Create ZIP file:
      */
     $job->change('export_status_creating_zip_file');
     $processor->createZipFile();
     $job->change('export_status_created_zip_file');
     $job->change('export_status_finished');
     return Response::json('ok');
 }
 /**
  * Execute the given rulegroup on a set of existing transactions
  *
  * @param SelectTransactionsRequest  $request
  * @param AccountRepositoryInterface $repository
  * @param RuleGroup                  $ruleGroup
  *
  * @return \Illuminate\Http\RedirectResponse
  */
 public function execute(SelectTransactionsRequest $request, AccountRepositoryInterface $repository, RuleGroup $ruleGroup)
 {
     // Get parameters specified by the user
     $accounts = $repository->get($request->get('accounts'));
     $startDate = new Carbon($request->get('start_date'));
     $endDate = new Carbon($request->get('end_date'));
     // Create a job to do the work asynchronously
     $job = new ExecuteRuleGroupOnExistingTransactions($ruleGroup);
     // Apply parameters to the job
     $job->setUser(auth()->user());
     $job->setAccounts($accounts);
     $job->setStartDate($startDate);
     $job->setEndDate($endDate);
     // Dispatch a new job to execute it in a queue
     $this->dispatch($job);
     // Tell the user that the job is queued
     Session::flash('success', strval(trans('firefly.executed_group_on_existing_transactions', ['title' => $ruleGroup->title])));
     return redirect()->route('rules.index');
 }
Esempio n. 25
0
 /**
  * Shows the view to edit a transaction.
  *
  * @param AccountRepositoryInterface $repository
  * @param TransactionJournal         $journal
  *
  * @return $this
  */
 public function edit(AccountRepositoryInterface $repository, TransactionJournal $journal)
 {
     $what = strtolower($journal->transactionType->type);
     $accounts = ExpandedForm::makeSelectList($repository->getAccounts(['Default account', 'Asset account']));
     $budgets = ExpandedForm::makeSelectList(Auth::user()->budgets()->get());
     $budgets[0] = trans('form.noBudget');
     $piggies = ExpandedForm::makeSelectList(Auth::user()->piggyBanks()->get());
     $piggies[0] = trans('form.noPiggybank');
     $subTitle = trans('breadcrumbs.edit_journal', ['description' => $journal->description]);
     $preFilled = ['date' => $journal->date->format('Y-m-d'), 'category' => '', 'budget_id' => 0, 'piggy_bank_id' => 0];
     // get tags:
     $tags = [];
     foreach ($journal->tags as $tag) {
         $tags[] = $tag->tag;
     }
     $preFilled['tags'] = join(',', $tags);
     $category = $journal->categories()->first();
     if (!is_null($category)) {
         $preFilled['category'] = $category->name;
     }
     $budget = $journal->budgets()->first();
     if (!is_null($budget)) {
         $preFilled['budget_id'] = $budget->id;
     }
     if ($journal->piggyBankEvents()->count() > 0) {
         $preFilled['piggy_bank_id'] = $journal->piggyBankEvents()->orderBy('date', 'DESC')->first()->piggy_bank_id;
     }
     $preFilled['amount'] = $journal->actual_amount;
     if ($journal->transactionType->type == 'Withdrawal') {
         $preFilled['account_id'] = $journal->source_account->id;
         $preFilled['expense_account'] = $journal->destination_account->name_for_editform;
     } else {
         $preFilled['account_id'] = $journal->destination_account->id;
         $preFilled['revenue_account'] = $journal->source_account->name_for_editform;
     }
     $preFilled['account_from_id'] = $journal->source_account->id;
     $preFilled['account_to_id'] = $journal->destination_account->id;
     Session::flash('preFilled', $preFilled);
     Session::flash('gaEventCategory', 'transactions');
     Session::flash('gaEventAction', 'edit-' . $what);
     // put previous url in session if not redirect from store (not "return_to_edit").
     if (Session::get('transactions.edit.fromUpdate') !== true) {
         Session::put('transactions.edit.url', URL::previous());
     }
     Session::forget('transactions.edit.fromUpdate');
     return View::make('transactions.edit', compact('journal', 'accounts', 'what', 'budgets', 'piggies', 'subTitle'))->with('data', $preFilled);
 }