Lots of new code for recurring transactions. #1469

This commit is contained in:
James Cole
2018-06-16 21:47:51 +02:00
parent 968abd26e8
commit 1cf91c78f8
19 changed files with 769 additions and 79 deletions

View File

@@ -26,7 +26,9 @@ namespace FireflyIII\Http\Controllers\Recurring;
use Carbon\Carbon;
use FireflyIII\Http\Controllers\Controller;
use FireflyIII\Http\Requests\RecurrenceFormRequest;
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
use FireflyIII\Repositories\Recurring\RecurringRepositoryInterface;
use Illuminate\Http\Request;
@@ -38,6 +40,8 @@ class CreateController extends Controller
{
/** @var BudgetRepositoryInterface */
private $budgets;
/** @var PiggyBankRepositoryInterface */
private $piggyBanks;
/** @var RecurringRepositoryInterface */
private $recurring;
@@ -55,8 +59,9 @@ class CreateController extends Controller
app('view')->share('title', trans('firefly.recurrences'));
app('view')->share('subTitle', trans('firefly.create_new_recurrence'));
$this->recurring = app(RecurringRepositoryInterface::class);
$this->budgets = app(BudgetRepositoryInterface::class);
$this->recurring = app(RecurringRepositoryInterface::class);
$this->budgets = app(BudgetRepositoryInterface::class);
$this->piggyBanks = app(PiggyBankRepositoryInterface::class);
return $next($request);
}
@@ -64,6 +69,8 @@ class CreateController extends Controller
}
/**
* @param Request $request
*
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function create(Request $request)
@@ -71,6 +78,8 @@ class CreateController extends Controller
// todo refactor to expandedform method.
$budgets = app('expandedform')->makeSelectListWithEmpty($this->budgets->getActiveBudgets());
$defaultCurrency = app('amount')->getDefaultCurrency();
$piggyBanks = $this->piggyBanks->getPiggyBanksWithAmount();
$piggies = app('expandedform')->makeSelectListWithEmpty($piggyBanks);
$tomorrow = new Carbon;
$tomorrow->addDay();
@@ -90,7 +99,18 @@ class CreateController extends Controller
];
$request->session()->flash('preFilled', $preFilled);
return view('recurring.create', compact('tomorrow', 'preFilled','typesOfRepetitions', 'defaultCurrency', 'budgets'));
return view('recurring.create', compact('tomorrow', 'preFilled', 'piggies', 'typesOfRepetitions', 'defaultCurrency', 'budgets'));
}
/**
* @param RecurrenceFormRequest $request
*/
public function store(RecurrenceFormRequest $request)
{
$data = $request->getAll();
$this->recurring->store($data);
var_dump($data);
exit;
}
}

View File

@@ -76,9 +76,20 @@ class IndexController extends Controller
$return = [];
$start = Carbon::createFromFormat('Y-m-d', $request->get('start'));
$end = Carbon::createFromFormat('Y-m-d', $request->get('end'));
$firstDate = Carbon::createFromFormat('Y-m-d', $request->get('first_date'));
$endDate = '' !== (string)$request->get('end_date') ? Carbon::createFromFormat('Y-m-d', $request->get('end_date')) : null;
$endsAt = (string)$request->get('ends');
$repetitionType = explode(',', $request->get('type'))[0];
$repetitions = (int)$request->get('reps');
$repetitionMoment = '';
$start->startOfDay();
// if $firstDate is beyond $end, simply return an empty array.
if ($firstDate->gt($end)) {
return Response::json([]);
}
// if $firstDate is beyond start, use that one:
$actualStart = clone $firstDate;
switch ($repetitionType) {
default:
@@ -90,32 +101,51 @@ class IndexController extends Controller
$repetitionMoment = explode(',', $request->get('type'))[1] ?? '1';
break;
case 'ndom':
$repetitionMoment = explode(',', $request->get('type'))[1] ?? '1,1';
$repetitionMoment = str_ireplace('ndom,', '', $request->get('type'));
break;
case 'yearly':
$repetitionMoment = explode(',', $request->get('type'))[1] ?? '2018-01-01';
break;
}
$repetition = new RecurrenceRepetition;
$repetition->repetition_type = $repetitionType;
$repetition->repetition_moment = $repetitionMoment;
$repetition->repetition_skip = (int)$request->get('skip');
var_dump($repository->getXOccurrences($repetition, $start, 5));
exit;
// calculate events in range, depending on type:
$actualEnd = clone $end;
switch ($endsAt) {
default:
throw new FireflyException(sprintf('Cannot generate events for "%s"', $endsAt));
throw new FireflyException(sprintf('Cannot generate events for type that ends at "%s".', $endsAt));
case 'forever':
// simply generate up until $end. No change from default behavior.
$occurrences = $repository->getOccurrencesInRange($repetition, $actualStart, $actualEnd);
break;
case 'until_date':
$actualEnd = $endDate ?? clone $end;
$occurrences = $repository->getOccurrencesInRange($repetition, $actualStart, $actualEnd);
break;
case 'times':
$occurrences = $repository->getXOccurrences($repetition, $actualStart, $repetitions);
break;
}
/** @var Carbon $current */
foreach ($occurrences as $current) {
if ($current->gte($start)) {
$event = [
'id' => $repetitionType . $firstDate->format('Ymd'),
'title' => 'X',
'allDay' => true,
'start' => $current->format('Y-m-d'),
'end' => $current->format('Y-m-d'),
'editable' => false,
'rendering' => 'background',
];
$return[] = $event;
}
}
return Response::json($return);
}

View File

@@ -37,6 +37,7 @@ use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
use FireflyIII\Repositories\Journal\JournalRepositoryInterface;
use FireflyIII\Repositories\PiggyBank\PiggyBankRepositoryInterface;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Log;
use Preferences;
@@ -218,7 +219,7 @@ class SingleController extends Controller
*
* @internal param JournalRepositoryInterface $repository
*/
public function destroy(TransactionJournal $transactionJournal)
public function destroy(TransactionJournal $transactionJournal): RedirectResponse
{
// @codeCoverageIgnoreStart
if ($this->isOpeningBalance($transactionJournal)) {
@@ -329,9 +330,10 @@ class SingleController extends Controller
* @param JournalFormRequest $request
* @param JournalRepositoryInterface $repository
*
* @return \Illuminate\Http\RedirectResponse
* @return RedirectResponse
* @throws \FireflyIII\Exceptions\FireflyException
*/
public function store(JournalFormRequest $request, JournalRepositoryInterface $repository)
public function store(JournalFormRequest $request, JournalRepositoryInterface $repository): RedirectResponse
{
$doSplit = 1 === (int)$request->get('split_journal');
$createAnother = 1 === (int)$request->get('create_another');

View File

@@ -0,0 +1,189 @@
<?php
/**
* RecurrenceFormRequest.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\Http\Requests;
use Carbon\Carbon;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\TransactionType;
use FireflyIII\Rules\ValidRecurrenceRepetitionType;
/**
* Class RecurrenceFormRequest
*/
class RecurrenceFormRequest extends Request
{
/**
* @return bool
*/
public function authorize(): bool
{
// Only allow logged in users
return auth()->check();
}
/**
* @return array
* @throws FireflyException
*/
public function getAll(): array
{
$data = $this->all();
$return = [
'recurrence' => [
'type' => $this->string('transaction_type'),
'title' => $this->string('title'),
'description' => $this->string('recurring_description'),
'first_date' => $this->date('first_date'),
'repeat_until' => $this->date('repeat_until'),
'repetitions' => $this->integer('repetitions'),
'apply_rules' => $this->boolean('apply_rules'),
'active' => $this->boolean('active'),
],
'transactions' => [
[
'transaction_currency_id' => $this->integer('transaction_currency_id'),
'type' => $this->string('transaction_type'),
'description' => $this->string('transaction_description'),
'amount' => $this->string('amount'),
'foreign_amount' => null,
'foreign_currency_id' => null,
'budget_id' => $this->integer('budget_id'),
'category_name' => $this->string('category'),
],
],
'meta' => [
// tags and piggy bank ID.
'tags' => explode(',', $this->string('tags')),
'piggy_bank_id' => $this->integer('piggy_bank_id'),
],
'repetitions' => [
[
'skip' => $this->integer('skip'),
],
],
];
// fill in foreign currency data
if (null !== $this->float('foreign_amount')) {
$return['transactions'][0]['foreign_amount'] = $this->string('foreign_amount');
$return['transactions'][0]['foreign_currency_id'] = $this->integer('foreign_currency_id');
}
// fill in source and destination account data
switch ($this->string('transaction_type')) {
default:
throw new FireflyException(sprintf('Cannot handle transaction type "%s"', $this->string('transaction_type')));
case 'withdrawal':
$return['transactions'][0]['source_account_id'] = $this->integer('source_account_id');
$return['transactions'][0]['destination_account_name'] = $this->string('destination_account_name');
break;
}
return $return;
}
/**
* @return array
* @throws FireflyException
*/
public function rules(): array
{
$today = new Carbon;
$tomorrow = clone $today;
$tomorrow->addDay();
$rules = [
// mandatory info for recurrence.
//'title' => 'required|between:1,255|uniqueObjectForUser:recurrences,title',
'title' => 'required|between:1,255',
'first_date' => 'required|date|after:' . $today->format('Y-m-d'),
'repetition_type' => ['required', new ValidRecurrenceRepetitionType, 'between:1,20'],
'skip' => 'required|numeric|between:0,31',
// optional for recurrence:
'recurring_description' => 'between:0,65000',
'active' => 'numeric|between:0,1',
'apply_rules' => 'numeric|between:0,1',
// mandatory for transaction:
'transaction_description' => 'required|between:1,255',
'transaction_type' => 'required|in:withdrawal,deposit,transfer',
'transaction_currency_id' => 'required|exists:transaction_currencies,id',
'amount' => 'numeric|required|more:0',
// mandatory account info:
'source_account_id' => 'numeric|belongsToUser:accounts,id|nullable',
'source_account_name' => 'between:1,255|nullable',
'destination_account_id' => 'numeric|belongsToUser:accounts,id|nullable',
'destination_account_name' => 'between:1,255|nullable',
// foreign amount data:
'foreign_currency_id' => 'exists:transaction_currencies,id',
'foreign_amount' => 'nullable|more:0',
// optional fields:
'budget_id' => 'mustExist:budgets,id|belongsToUser:budgets,id|nullable',
'category' => 'between:1,255|nullable',
'tags' => 'between:1,255|nullable',
];
// if ends after X repetitions, set another rule
if ($this->string('repetition_end') === 'times') {
$rules['repetitions'] = 'required|numeric|between:0,254';
}
// if foreign amount, currency must be different.
if ($this->float('foreign_amount') !== 0.0) {
$rules['foreign_currency_id'] = 'exists:transaction_currencies,id|different:transaction_currency_id';
}
// if ends at date X, set another rule.
if ($this->string('repetition_end') === 'until_date') {
$rules['repeat_until'] = 'required|date|after:' . $tomorrow->format('Y-m-d');
}
// switchc on type to expand rules for source and destination accounts:
switch ($this->string('transaction_type')) {
case strtolower(TransactionType::WITHDRAWAL):
$rules['source_account_id'] = 'required|exists:accounts,id|belongsToUser:accounts';
$rules['destination_account_name'] = 'between:1,255|nullable';
break;
case strtolower(TransactionType::DEPOSIT):
$rules['source_account_name'] = 'between:1,255|nullable';
$rules['destination_account_id'] = 'required|exists:accounts,id|belongsToUser:accounts';
break;
case strtolower(TransactionType::TRANSFER):
// this may not work:
$rules['source_account_id'] = 'required|exists:accounts,id|belongsToUser:accounts|different:destination_account_id';
$rules['destination_account_id'] = 'required|exists:accounts,id|belongsToUser:accounts|different:source_account_id';
break;
default:
throw new FireflyException(sprintf('Cannot handle transaction type of type "%s"', $this->string('transaction_type'))); // @codeCoverageIgnore
}
return $rules;
}
}

View File

@@ -47,6 +47,16 @@ class Request extends FormRequest
return 1 === (int)$this->input($field);
}
/**
* @param string $field
*
* @return float
*/
public function float(string $field): float
{
return (float)$this->get($field);
}
/**
* @param string $field
*