Merge branch 'feature/credit_calc' into develop

This commit is contained in:
James Cole
2021-05-13 05:35:07 +02:00
46 changed files with 1651 additions and 235 deletions

View File

@@ -31,6 +31,7 @@ use FireflyIII\Transformers\AccountTransformer;
use Illuminate\Http\JsonResponse;
use League\Fractal\Resource\Item;
use Log;
use Preferences;
/**
* Class UpdateController
@@ -75,6 +76,7 @@ class UpdateController extends Controller
$account = $this->repository->update($account, $data);
$manager = $this->getManager();
$account->refresh();
Preferences::mark();
/** @var AccountTransformer $transformer */
$transformer = app(AccountTransformer::class);

View File

@@ -77,13 +77,14 @@ class StoreRequest extends FormRequest
'interest' => $this->string('interest'),
'interest_period' => $this->string('interest_period'),
];
// append Location information.
// append location information.
$data = $this->appendLocationData($data, null);
if ('liability' === $data['account_type_name'] || 'liabilities' === $data['account_type_name']) {
$data['opening_balance'] = bcmul($this->string('liability_amount'), '-1');
$data['opening_balance'] = app('steam')->negative($this->string('liability_amount'));
$data['opening_balance_date'] = $this->date('liability_start_date');
$data['account_type_name'] = $this->string('liability_type');
$data['account_type_name'] = $this->string('liability_type');
$data['liability_direction'] = $this->string('liability_direction');
$data['account_type_id'] = null;
}
@@ -118,11 +119,12 @@ class StoreRequest extends FormRequest
'account_role' => sprintf('in:%s|required_if:type,asset', $accountRoles),
'credit_card_type' => sprintf('in:%s|required_if:account_role,ccAsset', $ccPaymentTypes),
'monthly_payment_date' => 'date' . '|required_if:account_role,ccAsset|required_if:credit_card_type,monthlyFull',
'liability_type' => 'required_if:type,liability|in:loan,debt,mortgage',
'liability_amount' => 'required_if:type,liability|min:0|numeric',
'liability_start_date' => 'required_if:type,liability|date',
'interest' => 'required_if:type,liability|between:0,100|numeric',
'interest_period' => 'required_if:type,liability|in:daily,monthly,yearly',
'liability_type' => 'required_if:type,liability|required_if:type,liabilities|in:loan,debt,mortgage',
'liability_amount' => 'required_with:liability_start_date|min:0|numeric',
'liability_start_date' => 'required_with:liability_amount|date',
'liability_direction' => 'required_if:type,liability|required_if:type,liabilities|in:credit,debit',
'interest' => 'between:0,100|numeric',
'interest_period' => sprintf('in:%s', join(',', config('firefly.interest_periods'))),
'notes' => 'min:0|max:65536',
];

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Api\V1\Requests\Models\Account;
use FireflyIII\Models\Account;
use FireflyIII\Models\Location;
use FireflyIII\Rules\IsBoolean;
use FireflyIII\Rules\UniqueAccountNumber;
@@ -32,6 +33,7 @@ use FireflyIII\Support\Request\AppendsLocationData;
use FireflyIII\Support\Request\ChecksLogin;
use FireflyIII\Support\Request\ConvertsDataTypes;
use Illuminate\Foundation\Http\FormRequest;
use Log;
/**
* Class UpdateRequest
@@ -68,15 +70,23 @@ class UpdateRequest extends FormRequest
'order' => ['order', 'integer'],
'currency_id' => ['currency_id', 'integer'],
'currency_code' => ['currency_code', 'string'],
'liability_direction' => ['liability_direction', 'string'],
'liability_amount' => ['liability_amount', 'string'],
'liability_start_date' => ['liability_start_date', 'date'],
];
$data = $this->getAllData($fields);
$data = $this->appendLocationData($data, null);
/** @var Account $account */
$account = $this->route()->parameter('account');
$data = $this->getAllData($fields);
$data = $this->appendLocationData($data, null);
$valid = config('firefly.valid_liabilities');
if (array_key_exists('liability_amount', $data) && in_array($account->accountType->type, $valid, true)) {
$data['opening_balance'] = app('steam')->negative($data['liability_amount']);
Log::debug(sprintf('Opening balance for liability is "%s".', $data['opening_balance']));
}
if (array_key_exists('account_type_name', $data) && 'liability' === $data['account_type_name']) {
$data['opening_balance'] = bcmul($this->string('liability_amount'), '-1');
$data['opening_balance_date'] = $this->date('liability_start_date');
$data['account_type_name'] = $this->string('liability_type');
$data['account_type_id'] = null;
if (array_key_exists('liability_start_date', $data) && in_array($account->accountType->type, $valid, true)) {
$data['opening_balance_date'] = $data['liability_start_date'];
Log::debug(sprintf('Opening balance date for liability is "%s".', $data['opening_balance_date']));
}
return $data;
@@ -112,6 +122,7 @@ class UpdateRequest extends FormRequest
'credit_card_type' => sprintf('in:%s|nullable|required_if:account_role,ccAsset', $ccPaymentTypes),
'monthly_payment_date' => 'date' . '|nullable|required_if:account_role,ccAsset|required_if:credit_card_type,monthlyFull',
'liability_type' => 'required_if:type,liability|in:loan,debt,mortgage',
'liability_direction' => 'required_if:type,liability|in:credit,debit',
'interest' => 'required_if:type,liability|between:0,100|numeric',
'interest_period' => 'required_if:type,liability|in:daily,monthly,yearly',
'notes' => 'min:0|max:65536',

View File

@@ -74,6 +74,7 @@ class UpgradeDatabase extends Command
'firefly-iii:migrate-recurrence-meta',
'firefly-iii:migrate-tag-locations',
'firefly-iii:migrate-recurrence-type',
'firefly-iii:upgrade-liabilities',
// there are 16 verify commands.
'firefly-iii:fix-piggies',

View File

@@ -0,0 +1,178 @@
<?php
namespace FireflyIII\Console\Commands\Upgrade;
use FireflyIII\Factory\AccountMetaFactory;
use FireflyIII\Models\Account;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Services\Internal\Support\CreditRecalculateService;
use FireflyIII\User;
use Illuminate\Console\Command;
use Log;
/**
* Class UpgradeLiabilities
*/
class UpgradeLiabilities extends Command
{
public const CONFIG_NAME = '560_upgrade_liabilities';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Upgrade liabilities to new 5.6.0 structure.';
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'firefly-iii:upgrade-liabilities {--F|force : Force the execution of this command.}';
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
$start = microtime(true);
if ($this->isExecuted() && true !== $this->option('force')) {
$this->warn('This command has already been executed.');
return 0;
}
$this->upgradeLiabilities();
$this->markAsExecuted();
$end = round(microtime(true) - $start, 2);
$this->info(sprintf('Upgraded liabilities in %s seconds.', $end));
return 0;
}
/**
* @return bool
*/
private function isExecuted(): bool
{
$configVar = app('fireflyconfig')->get(self::CONFIG_NAME, false);
if (null !== $configVar) {
return (bool)$configVar->data;
}
return false;
}
/**
* @param Account $account
* @param TransactionJournal $openingBalance
*/
private function correctOpeningBalance(Account $account, TransactionJournal $openingBalance): void
{
$source = $this->getSourceTransaction($openingBalance);
$destination = $this->getDestinationTransaction($openingBalance);
if (null === $source || null === $destination) {
return;
}
// source MUST be the liability.
if ((int)$destination->account_id === (int)$account->id) {
Log::debug(sprintf('Must switch around, because account #%d is the destination.', $destination->account_id));
// so if not, switch things around:
$sourceAccountId = (int)$source->account_id;
$source->account_id = $destination->account_id;
$destination->account_id = $sourceAccountId;
$source->save();
$destination->save();
Log::debug(sprintf('Source transaction #%d now has account #%d', $source->id, $source->account_id));
Log::debug(sprintf('Dest transaction #%d now has account #%d', $destination->id, $destination->account_id));
}
}
/**
* @param TransactionJournal $journal
*
* @return Transaction
*/
private function getSourceTransaction(TransactionJournal $journal): ?Transaction
{
return $journal->transactions()->where('amount', '<', 0)->first();
}
/**
* @param TransactionJournal $journal
*
* @return Transaction
*/
private function getDestinationTransaction(TransactionJournal $journal): ?Transaction
{
return $journal->transactions()->where('amount', '>', 0)->first();
}
/**
*
*/
private function markAsExecuted(): void
{
app('fireflyconfig')->set(self::CONFIG_NAME, true);
}
/**
*
*/
private function upgradeLiabilities(): void
{
Log::debug('Upgrading liabilities.');
$users = User::get();
/** @var User $user */
foreach ($users as $user) {
$this->upgradeForUser($user);
}
}
/**
* @param User $user
*/
private function upgradeForUser(User $user): void
{
Log::debug(sprintf('Upgrading liabilities for user #%d', $user->id));
$accounts = $user->accounts()
->leftJoin('account_types', 'account_types.id', '=', 'accounts.account_type_id')
->whereIn('account_types.type', config('firefly.valid_liabilities'))
->get(['accounts.*']);
/** @var Account $account */
foreach ($accounts as $account) {
$this->upgradeLiability($account);
$service = app(CreditRecalculateService::class);
$service->setAccount($account);
$service->recalculate();
}
}
/**
* @param Account $account
*/
private function upgradeLiability(Account $account): void
{
/** @var AccountRepositoryInterface $repository */
$repository = app(AccountRepositoryInterface::class);
$repository->setUser($account->user);
Log::debug(sprintf('Upgrade liability #%d', $account->id));
// get opening balance, and correct if necessary.
$openingBalance = $repository->getOpeningBalance($account);
if (null !== $openingBalance) {
// correct if necessary
$this->correctOpeningBalance($account, $openingBalance);
}
// add liability direction property
/** @var AccountMetaFactory $factory */
$factory = app(AccountMetaFactory::class);
$factory->crud($account, 'liability_direction', 'debit');
}
}

View File

@@ -0,0 +1,46 @@
<?php
/*
* StoredAccount.php
* Copyright (c) 2021 james@firefly-iii.org
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
namespace FireflyIII\Events;
use FireflyIII\Models\Account;
use Illuminate\Queue\SerializesModels;
/**
* Class StoredAccount
*/
class StoredAccount extends Event
{
use SerializesModels;
public Account $account;
/**
* Create a new event instance.
*
* @param Account $account
*/
public function __construct(Account $account)
{
$this->account = $account;
}
}

View File

@@ -0,0 +1,46 @@
<?php
/*
* StoredAccount.php
* Copyright (c) 2021 james@firefly-iii.org
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
namespace FireflyIII\Events;
use FireflyIII\Models\Account;
use Illuminate\Queue\SerializesModels;
/**
* Class UpdatedAccount
*/
class UpdatedAccount extends Event
{
use SerializesModels;
public Account $account;
/**
* Create a new event instance.
*
* @param Account $account
*/
public function __construct(Account $account)
{
$this->account = $account;
}
}

View File

@@ -24,6 +24,7 @@ declare(strict_types=1);
namespace FireflyIII\Factory;
use FireflyIII\Events\StoredAccount;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType;
@@ -48,6 +49,7 @@ class AccountFactory
protected array $validCCFields;
protected array $validFields;
private array $canHaveVirtual;
private array $canHaveOpeningBalance;
private User $user;
/**
@@ -57,11 +59,12 @@ class AccountFactory
*/
public function __construct()
{
$this->accountRepository = app(AccountRepositoryInterface::class);
$this->canHaveVirtual = config('firefly.can_have_virtual_amounts');
$this->validAssetFields = config('firefly.valid_asset_fields');
$this->validCCFields = config('firefly.valid_cc_fields');
$this->validFields = config('firefly.valid_account_fields');
$this->accountRepository = app(AccountRepositoryInterface::class);
$this->canHaveVirtual = config('firefly.can_have_virtual_amounts');
$this->canHaveOpeningBalance = config('firefly.can_have_opening_balance');
$this->validAssetFields = config('firefly.valid_asset_fields');
$this->validCCFields = config('firefly.valid_cc_fields');
$this->validFields = config('firefly.valid_account_fields');
}
/**
@@ -113,10 +116,14 @@ class AccountFactory
// account may exist already:
$return = $this->find($data['name'], $type->type);
if (null === $return) {
$return = $this->createAccount($type, $data);
if (null !== $return) {
return $return;
}
$return = $this->createAccount($type, $data);
event(new StoredAccount($return));
return $return;
}
@@ -203,7 +210,18 @@ class AccountFactory
$this->storeMetaData($account, $data);
// create opening balance
$this->storeOpeningBalance($account, $data);
try {
$this->storeOpeningBalance($account, $data);
} catch (FireflyException $e) {
Log::error($e->getMessage());
}
// create credit liability data (if relevant)
try {
$this->storeCreditLiability($account, $data);
} catch (FireflyException $e) {
Log::error($e->getMessage());
}
// create notes
$notes = array_key_exists('notes', $data) ? $data['notes'] : '';
@@ -238,7 +256,10 @@ class AccountFactory
if ($account->accountType->type !== AccountType::ASSET) {
$accountRole = '';
}
// only liability may have direction:
if (array_key_exists('liability_direction', $data) && !in_array($account->accountType->type, config('firefly.valid_liabilities'), true)) {
$data['liability_direction'] = null;
}
$data['account_role'] = $accountRole;
$data['currency_id'] = $currency->id;
@@ -257,7 +278,7 @@ class AccountFactory
$fields = $this->validAssetFields;
}
if ($account->accountType->type === AccountType::ASSET && 'ccAsset' === $data['account_role']) {
$fields = $this->validCCFields;
$fields = $this->validCCFields;
}
/** @var AccountMetaFactory $factory */
@@ -269,10 +290,10 @@ class AccountFactory
// convert boolean value:
if (is_bool($data[$field]) && false === $data[$field]) {
$data[$field] = 0;
$data[$field] = 0;
}
if (is_bool($data[$field]) && true === $data[$field]) {
$data[$field] = 1;
$data[$field] = 1;
}
$factory->crud($account, $field, (string)$data[$field]);
@@ -283,15 +304,18 @@ class AccountFactory
/**
* @param Account $account
* @param array $data
*
* @throws FireflyException
*/
private function storeOpeningBalance(Account $account, array $data)
{
$accountType = $account->accountType->type;
// if it can have a virtual balance, it can also have an opening balance.
if (in_array($accountType, $this->canHaveVirtual, true)) {
if (in_array($accountType, $this->canHaveOpeningBalance, true)) {
if ($this->validOBData($data)) {
$this->updateOBGroup($account, $data);
$openingBalance = $data['opening_balance'];
$openingBalanceDate = $data['opening_balance_date'];
$this->updateOBGroupV2($account, $openingBalance, $openingBalanceDate);
}
if (!$this->validOBData($data)) {
$this->deleteOBGroup($account);
@@ -299,6 +323,34 @@ class AccountFactory
}
}
/**
* @param Account $account
* @param array $data
*
* @throws FireflyException
*/
private function storeCreditLiability(Account $account, array $data)
{
Log::debug('storeCreditLiability');
$account->refresh();
$accountType = $account->accountType->type;
$direction = $this->accountRepository->getMetaValue($account, 'liability_direction');
$valid = config('firefly.valid_liabilities');
if (in_array($accountType, $valid, true) && 'credit' === $direction) {
Log::debug('Is a liability with credit direction.');
if ($this->validOBData($data)) {
Log::debug('Has valid CL data.');
$openingBalance = $data['opening_balance'];
$openingBalanceDate = $data['opening_balance_date'];
$this->updateCreditTransaction($account, $openingBalance, $openingBalanceDate);
}
if (!$this->validOBData($data)) {
Log::debug('Has NOT valid CL data.');
$this->deleteCreditTransaction($account);
}
}
}
/**
* @param Account $account
* @param array $data

View File

@@ -46,7 +46,7 @@ class TransactionJournalMetaFactory
/** @var TransactionJournalMeta $entry */
$entry = $data['journal']->transactionJournalMeta()->where('name', $data['name'])->first();
if (null === $value && null !== $entry) {
Log::debug('Value is empty, delete meta value.');
//Log::debug('Value is empty, delete meta value.');
try {
$entry->delete();
} catch (Exception $e) { // @phpstan-ignore-line
@@ -57,7 +57,7 @@ class TransactionJournalMetaFactory
}
if ($data['data'] instanceof Carbon) {
Log::debug('Is a carbon object.');
//Log::debug('Is a carbon object.');
$value = $data['data']->toW3cString();
}
if ('' === (string)$value) {
@@ -76,7 +76,7 @@ class TransactionJournalMetaFactory
}
if (null === $entry) {
Log::debug('Will create new object.');
//Log::debug('Will create new object.');
Log::debug(sprintf('Going to create new meta-data entry to store "%s".', $data['name']));
$entry = new TransactionJournalMeta();
$entry->transactionJournal()->associate($data['journal']);

View File

@@ -0,0 +1,44 @@
<?php
/*
* StoredAccountEventHandler.php
* Copyright (c) 2021 james@firefly-iii.org
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
namespace FireflyIII\Handlers\Events;
use FireflyIII\Events\StoredAccount;
use FireflyIII\Services\Internal\Support\CreditRecalculateService;
/**
* Class StoredAccountEventHandler
*/
class StoredAccountEventHandler
{
/**
* @param StoredAccount $event
*/
public function recalculateCredit(StoredAccount $event): void
{
$account = $event->account;
/** @var CreditRecalculateService $object */
$object = app(CreditRecalculateService::class);
$object->setAccount($account);
$object->recalculate();
}
}

View File

@@ -28,6 +28,7 @@ use FireflyIII\Generator\Webhook\MessageGeneratorInterface;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Models\Webhook;
use FireflyIII\Repositories\RuleGroup\RuleGroupRepositoryInterface;
use FireflyIII\Services\Internal\Support\CreditRecalculateService;
use FireflyIII\TransactionRules\Engine\RuleEngineInterface;
use Illuminate\Support\Collection;
use Log;
@@ -101,4 +102,16 @@ class StoredGroupEventHandler
event(new RequestedSendWebhookMessages);
}
/**
* @param StoredTransactionGroup $event
*/
public function recalculateCredit(StoredTransactionGroup $event): void
{
$group = $event->transactionGroup;
/** @var CreditRecalculateService $object */
$object = app(CreditRecalculateService::class);
$object->setGroup($group);
$object->recalculate();
}
}

View File

@@ -0,0 +1,45 @@
<?php
/*
* UpdatedAccountEventHandler.php
* Copyright (c) 2021 james@firefly-iii.org
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
namespace FireflyIII\Handlers\Events;
use FireflyIII\Events\StoredAccount;
use FireflyIII\Events\UpdatedAccount;
use FireflyIII\Services\Internal\Support\CreditRecalculateService;
/**
* Class UpdatedAccountEventHandler
*/
class UpdatedAccountEventHandler
{
/**
* @param UpdatedAccount $event
*/
public function recalculateCredit(UpdatedAccount $event): void
{
$account = $event->account;
/** @var CreditRecalculateService $object */
$object = app(CreditRecalculateService::class);
$object->setAccount($account);
$object->recalculate();
}
}

View File

@@ -31,6 +31,7 @@ use FireflyIII\Models\TransactionJournal;
use FireflyIII\Models\TransactionType;
use FireflyIII\Models\Webhook;
use FireflyIII\Repositories\RuleGroup\RuleGroupRepositoryInterface;
use FireflyIII\Services\Internal\Support\CreditRecalculateService;
use FireflyIII\TransactionRules\Engine\RuleEngineInterface;
use Illuminate\Support\Collection;
use Log;
@@ -94,6 +95,18 @@ class UpdatedGroupEventHandler
event(new RequestedSendWebhookMessages);
}
/**
* @param UpdatedTransactionGroup $event
*/
public function recalculateCredit(UpdatedTransactionGroup $event): void
{
$group = $event->transactionGroup;
/** @var CreditRecalculateService $object */
$object = app(CreditRecalculateService::class);
$object->setGroup($group);
$object->recalculate();
}
/**
* This method will make sure all source / destination accounts are the same.
*

View File

@@ -80,14 +80,14 @@ class CreateController extends Controller
*/
public function create(Request $request, string $objectType = null)
{
$objectType = $objectType ?? 'asset';
$defaultCurrency = app('amount')->getDefaultCurrency();
$subTitleIcon = config(sprintf('firefly.subIconsByIdentifier.%s', $objectType));
$subTitle = (string)trans(sprintf('firefly.make_new_%s_account', $objectType));
$roles = $this->getRoles();
$liabilityTypes = $this->getLiabilityTypes();
$hasOldInput = null !== $request->old('_token');
$locations = [
$objectType = $objectType ?? 'asset';
$defaultCurrency = app('amount')->getDefaultCurrency();
$subTitleIcon = config(sprintf('firefly.subIconsByIdentifier.%s', $objectType));
$subTitle = (string)trans(sprintf('firefly.make_new_%s_account', $objectType));
$roles = $this->getRoles();
$liabilityTypes = $this->getLiabilityTypes();
$hasOldInput = null !== $request->old('_token');
$locations = [
'location' => [
'latitude' => $hasOldInput ? old('location_latitude') : config('firefly.default_location.latitude'),
'longitude' => $hasOldInput ? old('location_longitude') : config('firefly.default_location.longitude'),
@@ -95,6 +95,10 @@ class CreateController extends Controller
'has_location' => $hasOldInput ? 'true' === old('location_has_location') : false,
],
];
$liabilityDirections = [
'debit' => trans('firefly.liability_direction_debit'),
'credit' => trans('firefly.liability_direction_credit'),
];
// interest calculation periods:
$interestPeriods = [
@@ -119,7 +123,10 @@ class CreateController extends Controller
$request->session()->forget('accounts.create.fromStore');
Log::channel('audit')->info('Creating new account.');
return prefixView('accounts.create', compact('subTitleIcon', 'locations', 'objectType', 'interestPeriods', 'subTitle', 'roles', 'liabilityTypes'));
return prefixView(
'accounts.create',
compact('subTitleIcon', 'liabilityDirections', 'locations', 'objectType', 'interestPeriods', 'subTitle', 'roles', 'liabilityTypes')
);
}
/**
@@ -156,7 +163,7 @@ class CreateController extends Controller
}
if (count($this->attachments->getMessages()->get('attachments')) > 0) {
$request->session()->flash('info', $this->attachments->getMessages()->get('attachments'));
$request->session()->flash('info', $this->attachments->getMessages()->get('attachments'));
}
// redirect to previous URL.

View File

@@ -45,10 +45,8 @@ class EditController extends Controller
use ModelInformation;
private AttachmentHelperInterface $attachments;
/** @var CurrencyRepositoryInterface The currency repository */
private $currencyRepos;
/** @var AccountRepositoryInterface The account repository */
private $repository;
private CurrencyRepositoryInterface $currencyRepos;
private AccountRepositoryInterface $repository;
/**
* EditController constructor.
@@ -106,6 +104,11 @@ class EditController extends Controller
],
];
$liabilityDirections = [
'debit' => trans('firefly.liability_direction_debit'),
'credit' => trans('firefly.liability_direction_credit'),
];
// interest calculation periods:
$interestPeriods = [
'daily' => (string)trans('firefly.interest_calc_daily'),
@@ -119,7 +122,10 @@ class EditController extends Controller
}
$request->session()->forget('accounts.edit.fromUpdate');
$openingBalanceAmount = (string)$repository->getOpeningBalanceAmount($account);
$openingBalanceAmount = app('steam')->positive((string)$repository->getOpeningBalanceAmount($account));
if('0' === $openingBalanceAmount) {
$openingBalanceAmount = '';
}
$openingBalanceDate = $repository->getOpeningBalanceDate($account);
$currency = $this->repository->getAccountCurrency($account) ?? app('amount')->getDefaultCurrency();
@@ -138,6 +144,7 @@ class EditController extends Controller
'opening_balance_date' => $openingBalanceDate,
'liability_type_id' => $account->account_type_id,
'opening_balance' => $openingBalanceAmount,
'liability_direction' => $this->repository->getMetaValue($account, 'liability_direction'),
'virtual_balance' => $account->virtual_balance,
'currency_id' => $currency->id,
'include_net_worth' => $includeNetWorth,
@@ -157,6 +164,7 @@ class EditController extends Controller
'subTitle',
'subTitleIcon',
'locations',
'liabilityDirections',
'objectType',
'roles',
'preFilled',

View File

@@ -103,7 +103,7 @@ class IndexController extends Controller
$account->startBalance = $this->isInArray($startBalances, $account->id);
$account->endBalance = $this->isInArray($endBalances, $account->id);
$account->difference = bcsub($account->endBalance, $account->startBalance);
$account->interest = number_format((float)$this->repository->getMetaValue($account, 'interest'), 6, '.', '');
$account->interest = number_format((float)$this->repository->getMetaValue($account, 'interest'), 4, '.', '');
$account->interestPeriod = (string)trans(sprintf('firefly.interest_calc_%s', $this->repository->getMetaValue($account, 'interest_period')));
$account->accountTypeString = (string)trans(sprintf('firefly.account_type_%s', $account->accountType->type));
}
@@ -160,14 +160,16 @@ class IndexController extends Controller
$accounts->each(
function (Account $account) use ($activities, $startBalances, $endBalances) {
// TODO lots of queries executed in this block.
$account->lastActivityDate = $this->isInArray($activities, $account->id);
$account->startBalance = $this->isInArray($startBalances, $account->id);
$account->endBalance = $this->isInArray($endBalances, $account->id);
$account->difference = bcsub($account->endBalance, $account->startBalance);
$account->interest = number_format((float)$this->repository->getMetaValue($account, 'interest'), 6, '.', '');
$account->interestPeriod = (string)trans(sprintf('firefly.interest_calc_%s', $this->repository->getMetaValue($account, 'interest_period')));
$account->accountTypeString = (string)trans(sprintf('firefly.account_type_%s', $account->accountType->type));
$account->location = $this->repository->getLocation($account);
$account->lastActivityDate = $this->isInArray($activities, $account->id);
$account->startBalance = $this->isInArray($startBalances, $account->id);
$account->endBalance = $this->isInArray($endBalances, $account->id);
$account->difference = bcsub($account->endBalance, $account->startBalance);
$account->interest = number_format((float)$this->repository->getMetaValue($account, 'interest'), 4, '.', '');
$account->interestPeriod = (string)trans(sprintf('firefly.interest_calc_%s', $this->repository->getMetaValue($account, 'interest_period')));
$account->accountTypeString = (string)trans(sprintf('firefly.account_type_%s', $account->accountType->type));
$account->location = $this->repository->getLocation($account);
$account->liability_direction = $this->repository->getMetaValue($account, 'liability_direction');
$account->current_debt = $this->repository->getMetaValue($account, 'current_debt') ?? '-';
}
);
// make paginator:

View File

@@ -85,6 +85,7 @@ class InstallController extends Controller
'firefly-iii:migrate-recurrence-meta' => [],
'firefly-iii:migrate-tag-locations' => [],
'firefly-iii:migrate-recurrence-type' => [],
'firefly-iii:upgrade-liabilities' => [],
// verify commands
'firefly-iii:fix-piggies' => [],

View File

@@ -62,6 +62,7 @@ class AccountFormRequest extends FormRequest
'interest' => $this->string('interest'),
'interest_period' => $this->string('interest_period'),
'include_net_worth' => '1',
'liability_direction' => $this->string('liability_direction'),
];
$data = $this->appendLocationData($data, 'location');
@@ -74,6 +75,9 @@ class AccountFormRequest extends FormRequest
if ('liabilities' === $data['account_type_name']) {
$data['account_type_name'] = null;
$data['account_type_id'] = $this->integer('liability_type_id');
if ('' !== $data['opening_balance']) {
$data['opening_balance'] = app('steam')->negative($data['opening_balance']);
}
}
return $data;
@@ -108,11 +112,6 @@ class AccountFormRequest extends FormRequest
];
$rules = Location::requestRules($rules);
if ('liabilities' === $this->get('objectType')) {
$rules['opening_balance'] = ['numeric', 'required', 'max:1000000000'];
$rules['opening_balance_date'] = 'date|required';
}
/** @var Account $account */
$account = $this->route()->parameter('account');
if (null !== $account) {

View File

@@ -88,7 +88,16 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
* @method static Builder|Account withTrashed()
* @method static Builder|Account withoutTrashed()
* @mixin Eloquent
* @property Carbon $lastActivityDate
* @property Carbon $lastActivityDate
* @property string $startBalance
* @property string $endBalance
* @property string $difference
* @property string $interest
* @property string $interestPeriod
* @property string $accountTypeString
* @property string $location
* @property string $liability_direction
* @property string $current_debt
*/
class Account extends Model
{

View File

@@ -74,6 +74,8 @@ class AccountType extends Model
public const MORTGAGE = 'Mortgage';
/** @var string */
public const CREDITCARD = 'Credit card';
/** @var string */
public const LIABILITY_CREDIT = 'Liability credit account';
/**
* The attributes that should be casted to native types.
*

View File

@@ -34,13 +34,13 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* FireflyIII\Models\TransactionType
*
* @property int $id
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property Carbon|null $deleted_at
* @property string $type
* @property int $id
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
* @property Carbon|null $deleted_at
* @property string $type
* @property-read Collection|\FireflyIII\Models\TransactionJournal[] $transactionJournals
* @property-read int|null $transaction_journals_count
* @property-read int|null $transaction_journals_count
* @method static \Illuminate\Database\Eloquent\Builder|TransactionType newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|TransactionType newQuery()
* @method static Builder|TransactionType onlyTrashed()
@@ -57,12 +57,21 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class TransactionType extends Model
{
use SoftDeletes;
/** @var string */
public const WITHDRAWAL = 'Withdrawal';
/** @var string */
public const DEPOSIT = 'Deposit';
/** @var string */
public const TRANSFER = 'Transfer';
/** @var string */
public const OPENING_BALANCE = 'Opening balance';
/** @var string */
public const RECONCILIATION = 'Reconciliation';
/** @var string */
public const INVALID = 'Invalid';
/** @var string */
public const LIABILITY_CREDIT = 'Liability credit';
/** @var string[] */
protected $casts
= [
@@ -70,7 +79,7 @@ class TransactionType extends Model
'updated_at' => 'datetime',
'deleted_at' => 'datetime',
];
/** @var string[] */
/** @var string[] */
protected $fillable = ['type'];
/**
@@ -78,8 +87,8 @@ class TransactionType extends Model
*
* @param string $type
*
* @throws NotFoundHttpException
* @return TransactionType
* @throws NotFoundHttpException
*/
public static function routeBinder(string $type): TransactionType
{

View File

@@ -31,7 +31,9 @@ use FireflyIII\Events\RequestedNewPassword;
use FireflyIII\Events\RequestedReportOnJournals;
use FireflyIII\Events\RequestedSendWebhookMessages;
use FireflyIII\Events\RequestedVersionCheckStatus;
use FireflyIII\Events\StoredAccount;
use FireflyIII\Events\StoredTransactionGroup;
use FireflyIII\Events\UpdatedAccount;
use FireflyIII\Events\UpdatedTransactionGroup;
use FireflyIII\Events\UserChangedEmail;
use FireflyIII\Mail\OAuthTokenCreatedMail;
@@ -98,12 +100,14 @@ class EventServiceProvider extends ServiceProvider
// is a Transaction Journal related event.
StoredTransactionGroup::class => [
'FireflyIII\Handlers\Events\StoredGroupEventHandler@processRules',
'FireflyIII\Handlers\Events\StoredGroupEventHandler@recalculateCredit',
'FireflyIII\Handlers\Events\StoredGroupEventHandler@triggerWebhooks',
],
// is a Transaction Journal related event.
UpdatedTransactionGroup::class => [
'FireflyIII\Handlers\Events\UpdatedGroupEventHandler@unifyAccounts',
'FireflyIII\Handlers\Events\UpdatedGroupEventHandler@processRules',
'FireflyIII\Handlers\Events\UpdatedGroupEventHandler@recalculateCredit',
'FireflyIII\Handlers\Events\UpdatedGroupEventHandler@triggerWebhooks',
],
DestroyedTransactionGroup::class => [
@@ -118,6 +122,14 @@ class EventServiceProvider extends ServiceProvider
RequestedSendWebhookMessages::class => [
'FireflyIII\Handlers\Events\WebhookEventHandler@sendWebhookMessages',
],
// account related events:
StoredAccount::class => [
'FireflyIII\Handlers\Events\StoredAccountEventHandler@recalculateCredit',
],
UpdatedAccount::class => [
'FireflyIII\Handlers\Events\UpdatedAccountEventHandler@recalculateCredit',
],
];
/**

View File

@@ -123,14 +123,24 @@ class AccountRepository implements AccountRepositoryInterface
*/
public function findByIbanNull(string $iban, array $types): ?Account
{
$query = $this->user->accounts()->where('accounts.iban', $iban);
$query = $this->user->accounts()->where('iban', '!=', '')->whereNotNull('iban');
if (0 !== count($types)) {
$query->leftJoin('account_types', 'accounts.account_type_id', '=', 'account_types.id');
$query->whereIn('account_types.type', $types);
}
return $query->first(['accounts.*']);
// TODO a loop like this is no longer necessary
$accounts = $query->get(['accounts.*']);
/** @var Account $account */
foreach ($accounts as $account) {
if ($account->iban === $iban) {
return $account;
}
}
return null;
}
/**
@@ -738,6 +748,23 @@ class AccountRepository implements AccountRepositoryInterface
return $service->update($account, $data);
}
/**
* @inheritDoc
*/
public function getCreditTransactionGroup(Account $account): ?TransactionGroup
{
$journal = TransactionJournal
::leftJoin('transactions', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
->where('transactions.account_id', $account->id)
->transactionTypes([TransactionType::LIABILITY_CREDIT])
->first(['transaction_journals.*']);
if (null === $journal) {
return null;
}
return $journal->transactionGroup;
}
/**
* @inheritDoc
*/
@@ -762,4 +789,5 @@ class AccountRepository implements AccountRepositoryInterface
return $dbQuery->first(['accounts.*']);
}
}

View File

@@ -207,6 +207,13 @@ interface AccountRepositoryInterface
*/
public function getOpeningBalanceDate(Account $account): ?string;
/**
* @param Account $account
*
* @return TransactionGroup|null
*/
public function getCreditTransactionGroup(Account $account): ?TransactionGroup;
/**
* @param Account $account
*

View File

@@ -23,7 +23,9 @@ declare(strict_types=1);
namespace FireflyIII\Services\Internal\Support;
use Carbon\Carbon;
use Exception;
use FireflyIII\Exceptions\DuplicateTransactionException;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Factory\AccountMetaFactory;
use FireflyIII\Factory\TransactionCurrencyFactory;
@@ -37,6 +39,7 @@ use FireflyIII\Models\TransactionGroup;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use FireflyIII\Services\Internal\Destroy\TransactionGroupDestroyService;
use JsonException;
use Log;
use Validator;
@@ -126,7 +129,7 @@ trait AccountServiceTrait
}
if ($account->accountType->type === AccountType::ASSET && array_key_exists('account_role', $data) && 'ccAsset' === $data['account_role']) {
$fields = $this->validCCFields;
$fields = $this->validCCFields;
}
/** @var AccountMetaFactory $factory */
$factory = app(AccountMetaFactory::class);
@@ -137,10 +140,10 @@ trait AccountServiceTrait
// convert boolean value:
if (is_bool($data[$field]) && false === $data[$field]) {
$data[$field] = 0;
$data[$field] = 0;
}
if (is_bool($data[$field]) && true === $data[$field]) {
$data[$field] = 1;
$data[$field] = 1;
}
$factory->crud($account, $field, (string)$data[$field]);
@@ -191,9 +194,10 @@ trait AccountServiceTrait
{
$data['opening_balance'] = (string)($data['opening_balance'] ?? '');
if ('' !== $data['opening_balance'] && 0 === bccomp($data['opening_balance'], '0')) {
$data['opening_balance'] = '';
$data['opening_balance'] = '';
}
if ('' !== $data['opening_balance'] && array_key_exists('opening_balance_date', $data) && '' !== $data['opening_balance_date']) {
if ('' !== $data['opening_balance'] && array_key_exists('opening_balance_date', $data) && '' !== $data['opening_balance_date']
&& $data['opening_balance_date'] instanceof Carbon) {
Log::debug('Array has valid opening balance data.');
return true;
@@ -222,6 +226,24 @@ trait AccountServiceTrait
}
}
/**
* Delete TransactionGroup with liability credit in it.
*
* @param Account $account
*/
protected function deleteCreditTransaction(Account $account): void
{
Log::debug(sprintf('deleteCreditTransaction() for account #%d', $account->id));
$creditGroup = $this->getCreditTransaction($account);
if (null !== $creditGroup) {
Log::debug('Credit journal found, delete journal.');
/** @var TransactionGroupDestroyService $service */
$service = app(TransactionGroupDestroyService::class);
$service->destroy($creditGroup);
}
}
/**
* Returns the opening balance group, or NULL if it does not exist.
*
@@ -234,11 +256,26 @@ trait AccountServiceTrait
return $this->accountRepository->getOpeningBalanceGroup($account);
}
/**
* Returns the credit transaction group, or NULL if it does not exist.
*
* @param Account $account
*
* @return TransactionGroup|null
*/
protected function getCreditTransaction(Account $account): ?TransactionGroup
{
Log::debug(sprintf('Now at %s', __METHOD__));
return $this->accountRepository->getCreditTransactionGroup($account);
}
/**
* @param int $currencyId
* @param string $currencyCode
*
* @return TransactionCurrency
* @throws JsonException
*/
protected function getCurrency(int $currencyId, string $currencyCode): TransactionCurrency
{
@@ -259,59 +296,57 @@ trait AccountServiceTrait
}
/**
* Update or create the opening balance group. Assumes valid data in $data.
*
* Returns null if this fails.
* Update or create the opening balance group.
* Since opening balance and date can still be empty strings, it may fail.
*
* @param Account $account
* @param array $data
* @param string $openingBalance
* @param Carbon $openingBalanceDate
*
* @return TransactionGroup|null
* @return TransactionGroup
* @throws FireflyException
*/
protected function updateOBGroup(Account $account, array $data): ?TransactionGroup
protected function updateOBGroupV2(Account $account, string $openingBalance, Carbon $openingBalanceDate): TransactionGroup
{
Log::debug(sprintf('Now in %s', __METHOD__));
// create if not exists:
$obGroup = $this->getOBGroup($account);
if (null === $obGroup) {
return $this->createOBGroup($account, $data);
return $this->createOBGroupV2($account, $openingBalance, $openingBalanceDate);
}
// $data['currency_id'] is empty so creating a new journal may break.
if (!array_key_exists('currency_id', $data)) {
$currency = $this->accountRepository->getAccountCurrency($account);
if (null === $currency) {
$currency = app('default')->getDefaultCurrencyByUser($account->user);
}
$data['currency_id'] = $currency->id;
// if exists, update:
$currency = $this->accountRepository->getAccountCurrency($account);
if (null === $currency) {
$currency = app('default')->getDefaultCurrencyByUser($account->user);
}
/** @var TransactionJournal $journal */
$journal = $obGroup->transactionJournals()->first();
$journal->date = $data['opening_balance_date'] ?? $journal->date;
$journal->transaction_currency_id = $data['currency_id'];
// simply grab the first journal and change it:
$journal = $this->getObJournal($obGroup);
$obTransaction = $this->getOBTransaction($journal, $account);
$accountTransaction = $this->getNotOBTransaction($journal, $account);
$journal->date = $openingBalanceDate;
$journal->transactionCurrency()->associate($currency);
/** @var Transaction $obTransaction */
$obTransaction = $journal->transactions()->where('account_id', '!=', $account->id)->first();
/** @var Transaction $accountTransaction */
$accountTransaction = $journal->transactions()->where('account_id', $account->id)->first();
// if amount is negative:
if (1 === bccomp('0', $data['opening_balance'])) {
if (1 === bccomp('0', $openingBalance)) {
// account transaction loses money:
$accountTransaction->amount = app('steam')->negative($data['opening_balance']);
$accountTransaction->transaction_currency_id = $data['currency_id'];
$accountTransaction->amount = app('steam')->negative($openingBalance);
$accountTransaction->transaction_currency_id = $currency->id;
// OB account transaction gains money
$obTransaction->amount = app('steam')->positive($data['opening_balance']);
$obTransaction->transaction_currency_id = $data['currency_id'];
$obTransaction->amount = app('steam')->positive($openingBalance);
$obTransaction->transaction_currency_id = $currency->id;
}
if (-1 === bccomp('0', $data['opening_balance'])) {
if (-1 === bccomp('0', $openingBalance)) {
// account gains money:
$accountTransaction->amount = app('steam')->positive($data['opening_balance']);
$accountTransaction->transaction_currency_id = $data['currency_id'];
$accountTransaction->amount = app('steam')->positive($openingBalance);
$accountTransaction->transaction_currency_id = $currency->id;
// OB account loses money:
$obTransaction->amount = app('steam')->negative($data['opening_balance']);
$obTransaction->transaction_currency_id = $data['currency_id'];
$obTransaction->amount = app('steam')->negative($openingBalance);
$obTransaction->transaction_currency_id = $currency->id;
}
// save both
$accountTransaction->save();
@@ -323,12 +358,105 @@ trait AccountServiceTrait
}
/**
* @param Account $account
* @param array $data
* Create the opposing "credit liability" transaction for credit liabilities.
*
* @return TransactionGroup|null
* @param Account $account
* @param string $openingBalance
* @param Carbon $openingBalanceDate
*
* @return TransactionGroup
* @throws FireflyException
*/
protected function createOBGroup(Account $account, array $data): ?TransactionGroup
protected function updateCreditTransaction(Account $account, string $openingBalance, Carbon $openingBalanceDate): TransactionGroup
{
Log::debug(sprintf('Now in %s', __METHOD__));
if (0 === bccomp($openingBalance, '0')) {
Log::debug('Amount is zero, so will not update liability credit group.');
throw new FireflyException('Amount for update liability credit was unexpectedly 0.');
}
// create if not exists:
$clGroup = $this->getCreditTransaction($account);
if (null === $clGroup) {
return $this->createCreditTransaction($account, $openingBalance, $openingBalanceDate);
}
// if exists, update:
$currency = $this->accountRepository->getAccountCurrency($account);
if (null === $currency) {
$currency = app('default')->getDefaultCurrencyByUser($account->user);
}
// simply grab the first journal and change it:
$journal = $this->getObJournal($clGroup);
$clTransaction = $this->getOBTransaction($journal, $account);
$accountTransaction = $this->getNotOBTransaction($journal, $account);
$journal->date = $openingBalanceDate;
$journal->transactionCurrency()->associate($currency);
// account always gains money:
$accountTransaction->amount = app('steam')->positive($openingBalance);
$accountTransaction->transaction_currency_id = $currency->id;
// CL account always loses money:
$clTransaction->amount = app('steam')->negative($openingBalance);
$clTransaction->transaction_currency_id = $currency->id;
// save both
$accountTransaction->save();
$clTransaction->save();
$journal->save();
$clGroup->refresh();
return $clGroup;
}
/**
* TODO rename to "getOpposingTransaction"
*
* @param TransactionJournal $journal
* @param Account $account
*
* @return Transaction
* @throws FireflyException
*/
private function getOBTransaction(TransactionJournal $journal, Account $account): Transaction
{
/** @var Transaction $transaction */
$transaction = $journal->transactions()->where('account_id', '!=', $account->id)->first();
if (null === $transaction) {
throw new FireflyException(sprintf('Could not get OB transaction for journal #%d', $journal->id));
}
return $transaction;
}
/**
* @param TransactionJournal $journal
* @param Account $account
*
* @return Transaction
* @throws FireflyException
*/
private function getNotOBTransaction(TransactionJournal $journal, Account $account): Transaction
{
/** @var Transaction $transaction */
$transaction = $journal->transactions()->where('account_id', $account->id)->first();
if (null === $transaction) {
throw new FireflyException(sprintf('Could not get non-OB transaction for journal #%d', $journal->id));
}
return $transaction;
}
/**
* @param Account $account
* @param string $openingBalance
* @param Carbon $openingBalanceDate
*
* @return TransactionGroup
* @throws FireflyException
*/
protected function createOBGroupV2(Account $account, string $openingBalance, Carbon $openingBalanceDate): TransactionGroup
{
Log::debug('Now going to create an OB group.');
$language = app('preferences')->getForUser($account->user, 'language', 'en_US')->data;
@@ -336,48 +464,48 @@ trait AccountServiceTrait
$sourceName = null;
$destId = null;
$destName = null;
$amount = $data['opening_balance'];
if (1 === bccomp($amount, '0')) {
Log::debug(sprintf('Amount is %s, which is positive. Source is a new IB account, destination is #%d', $amount, $account->id));
// amount is positive.
// amount is positive.
if (1 === bccomp($openingBalance, '0')) {
Log::debug(sprintf('Amount is %s, which is positive. Source is a new IB account, destination is #%d', $openingBalance, $account->id));
$sourceName = trans('firefly.initial_balance_description', ['account' => $account->name], $language);
$destId = $account->id;
}
if (-1 === bccomp($amount, '0')) {
Log::debug(sprintf('Amount is %s, which is negative. Destination is a new IB account, source is #%d', $amount, $account->id));
// amount is not positive
// amount is not positive
if (-1 === bccomp($openingBalance, '0')) {
Log::debug(sprintf('Amount is %s, which is negative. Destination is a new IB account, source is #%d', $openingBalance, $account->id));
$destName = trans('firefly.initial_balance_account', ['account' => $account->name], $language);
$sourceId = $account->id;
}
if (0 === bccomp($amount, '0')) {
// amount is 0
if (0 === bccomp($openingBalance, '0')) {
Log::debug('Amount is zero, so will not make an OB group.');
return null;
}
$amount = app('steam')->positive($amount);
if (!array_key_exists('currency_id', $data)) {
$currency = $this->accountRepository->getAccountCurrency($account);
if (null === $currency) {
$currency = app('default')->getDefaultCurrencyByUser($account->user);
}
$data['currency_id'] = $currency->id;
throw new FireflyException('Amount for new opening balance was unexpectedly 0.');
}
// make amount positive, regardless:
$amount = app('steam')->positive($openingBalance);
// get or grab currency:
$currency = $this->accountRepository->getAccountCurrency($account);
if (null === $currency) {
$currency = app('default')->getDefaultCurrencyByUser($account->user);
}
// submit to factory:
$submission = [
'group_title' => null,
'user' => $account->user_id,
'transactions' => [
[
'type' => 'Opening balance',
'date' => $data['opening_balance_date'],
'date' => $openingBalanceDate,
'source_id' => $sourceId,
'source_name' => $sourceName,
'destination_id' => $destId,
'destination_name' => $destName,
'user' => $account->user_id,
'currency_id' => $data['currency_id'],
'currency_id' => $currency->id,
'order' => 0,
'amount' => $amount,
'foreign_amount' => null,
@@ -395,18 +523,204 @@ trait AccountServiceTrait
],
];
Log::debug('Going for submission', $submission);
$group = null;
/** @var TransactionGroupFactory $factory */
$factory = app(TransactionGroupFactory::class);
$factory->setUser($account->user);
try {
$group = $factory->create($submission);
} catch (FireflyException $e) {
} catch (DuplicateTransactionException $e) {
Log::error($e->getMessage());
Log::error($e->getTraceAsString());
throw new FireflyException($e->getMessage(), 0, $e);
}
return $group;
}
/**
* @param Account $account
* @param string $openingBalance
* @param Carbon $openingBalanceDate
*
* @return TransactionGroup
* @throws FireflyException
*/
protected function createCreditTransaction(Account $account, string $openingBalance, Carbon $openingBalanceDate): TransactionGroup
{
Log::debug('Now going to create an createCreditTransaction.');
if (0 === bccomp($openingBalance, '0')) {
Log::debug('Amount is zero, so will not make an liability credit group.');
throw new FireflyException('Amount for new liability credit was unexpectedly 0.');
}
$language = app('preferences')->getForUser($account->user, 'language', 'en_US')->data;
$amount = app('steam')->positive($openingBalance);
// get or grab currency:
$currency = $this->accountRepository->getAccountCurrency($account);
if (null === $currency) {
$currency = app('default')->getDefaultCurrencyByUser($account->user);
}
// submit to factory:
$submission = [
'group_title' => null,
'user' => $account->user_id,
'transactions' => [
[
'type' => 'Liability credit',
'date' => $openingBalanceDate,
'source_id' => null,
'source_name' => trans('firefly.liability_credit_description', ['account' => $account->name], $language),
'destination_id' => $account->id,
'destination_name' => null,
'user' => $account->user_id,
'currency_id' => $currency->id,
'order' => 0,
'amount' => $amount,
'foreign_amount' => null,
'description' => trans('firefly.liability_credit_description', ['account' => $account->name]),
'budget_id' => null,
'budget_name' => null,
'category_id' => null,
'category_name' => null,
'piggy_bank_id' => null,
'piggy_bank_name' => null,
'reconciled' => false,
'notes' => null,
'tags' => [],
],
],
];
Log::debug('Going for submission', $submission);
/** @var TransactionGroupFactory $factory */
$factory = app(TransactionGroupFactory::class);
$factory->setUser($account->user);
try {
$group = $factory->create($submission);
} catch (DuplicateTransactionException $e) {
Log::error($e->getMessage());
Log::error($e->getTraceAsString());
throw new FireflyException($e->getMessage(), 0, $e);
}
return $group;
}
/**
* @param Account $account
* @param array $data
*
* @return TransactionGroup
* @throws FireflyException
* @deprecated
*/
protected function createOBGroup(Account $account, array $data): TransactionGroup
{
Log::debug('Now going to create an OB group.');
$language = app('preferences')->getForUser($account->user, 'language', 'en_US')->data;
$sourceId = null;
$sourceName = null;
$destId = null;
$destName = null;
$amount = array_key_exists('opening_balance', $data) ? $data['opening_balance'] : '0';
// amount is positive.
if (1 === bccomp($amount, '0')) {
Log::debug(sprintf('Amount is %s, which is positive. Source is a new IB account, destination is #%d', $amount, $account->id));
$sourceName = trans('firefly.initial_balance_description', ['account' => $account->name], $language);
$destId = $account->id;
}
// amount is not positive
if (-1 === bccomp($amount, '0')) {
Log::debug(sprintf('Amount is %s, which is negative. Destination is a new IB account, source is #%d', $amount, $account->id));
$destName = trans('firefly.initial_balance_account', ['account' => $account->name], $language);
$sourceId = $account->id;
}
// amount is 0
if (0 === bccomp($amount, '0')) {
Log::debug('Amount is zero, so will not make an OB group.');
throw new FireflyException('Amount for new opening balance was unexpectedly 0.');
}
// make amount positive, regardless:
$amount = app('steam')->positive($amount);
// get or grab currency:
$currency = $this->accountRepository->getAccountCurrency($account);
if (null === $currency) {
$currency = app('default')->getDefaultCurrencyByUser($account->user);
}
// submit to factory:
$submission = [
'group_title' => null,
'user' => $account->user_id,
'transactions' => [
[
'type' => 'Opening balance',
'date' => $data['opening_balance_date'],
'source_id' => $sourceId,
'source_name' => $sourceName,
'destination_id' => $destId,
'destination_name' => $destName,
'user' => $account->user_id,
'currency_id' => $currency->id,
'order' => 0,
'amount' => $amount,
'foreign_amount' => null,
'description' => trans('firefly.initial_balance_description', ['account' => $account->name]),
'budget_id' => null,
'budget_name' => null,
'category_id' => null,
'category_name' => null,
'piggy_bank_id' => null,
'piggy_bank_name' => null,
'reconciled' => false,
'notes' => null,
'tags' => [],
],
],
];
Log::debug('Going for submission', $submission);
/** @var TransactionGroupFactory $factory */
$factory = app(TransactionGroupFactory::class);
$factory->setUser($account->user);
try {
$group = $factory->create($submission);
} catch (DuplicateTransactionException $e) {
Log::error($e->getMessage());
Log::error($e->getTraceAsString());
throw new FireflyException($e->getMessage(), 0, $e);
}
return $group;
}
/**
* TODO Refactor to "getFirstJournal"
*
* @param TransactionGroup $group
*
* @return TransactionJournal
* @throws FireflyException
*/
private function getObJournal(TransactionGroup $group): TransactionJournal
{
/** @var TransactionJournal $journal */
$journal = $group->transactionJournals()->first();
if (null === $journal) {
throw new FireflyException(sprintf('Group #%d has no OB journal', $group->id));
}
return $journal;
}
}

View File

@@ -0,0 +1,269 @@
<?php
/*
* CreditRecalculateService.php
* Copyright (c) 2021 james@firefly-iii.org
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
namespace FireflyIII\Services\Internal\Support;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Factory\AccountMetaFactory;
use FireflyIII\Models\Account;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionGroup;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Models\TransactionType;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
use Log;
class CreditRecalculateService
{
private ?Account $account;
private ?TransactionGroup $group;
private array $work;
private AccountRepositoryInterface $repository;
/**
* CreditRecalculateService constructor.
*/
public function __construct()
{
$this->group = null;
$this->account = null;
$this->work = [];
}
/**
*
*/
public function recalculate(): void
{
Log::debug(sprintf('Now in %s', __METHOD__));
if (true !== config('firefly.feature_flags.handle_debts')) {
Log::debug('handle_debts is disabled.');
return;
}
if (null !== $this->group && null === $this->account) {
$this->processGroup();
}
if (null !== $this->account && null === $this->group) {
// work based on account.
$this->processAccount();
}
if (0 === count($this->work)) {
Log::debug('No work accounts, do not do CreditRecalculationService');
return;
}
Log::debug('Will now do CreditRecalculationService');
$this->processWork();
}
/**
*
*/
private function processWork(): void
{
$this->repository = app(AccountRepositoryInterface::class);
Log::debug(sprintf('Now in %s', __METHOD__));
foreach ($this->work as $account) {
$this->processWorkAccount($account);
}
Log::debug(sprintf('Done with %s', __METHOD__));
}
/**
* @param Account $account
*/
private function processWorkAccount(Account $account): void
{
Log::debug(sprintf('Now in %s(#%d)', __METHOD__, $account->id));
// get opening balance (if present)
$this->repository->setUser($account->user);
$startOfDebt = $this->repository->getOpeningBalanceAmount($account) ?? '0';
$leftOfDebt = app('steam')->positive($startOfDebt);
/** @var AccountMetaFactory $factory */
$factory = app(AccountMetaFactory::class);
$factory->crud($account, 'start_of_debt', $startOfDebt);
// now loop all transactions (except opening balance and credit thing)
$transactions = $account->transactions()->get();
/** @var Transaction $transaction */
foreach ($transactions as $transaction) {
$leftOfDebt = $this->processTransaction($account, $transaction, $leftOfDebt);
}
$factory->crud($account, 'current_debt', $leftOfDebt);
Log::debug(sprintf('Done with %s(#%d)', __METHOD__, $account->id));
}
/**
*
*/
private function processGroup(): void
{
Log::debug(sprintf('Now in %s', __METHOD__));
/** @var TransactionJournal $journal */
foreach ($this->group->transactionJournals as $journal) {
if (0 === count($this->work)) {
try {
$this->findByJournal($journal);
} catch (FireflyException $e) {
Log::error($e->getTraceAsString());
Log::error(sprintf('Could not find work account for transaction group #%d.', $this->group->id));
}
}
}
Log::debug(sprintf('Done with %s', __METHOD__));
}
/**
* @param TransactionJournal $journal
*
* @throws FireflyException
*/
private function findByJournal(TransactionJournal $journal): void
{
Log::debug(sprintf('Now in %s', __METHOD__));
$source = $this->getSourceAccount($journal);
$destination = $this->getDestinationAccount($journal);
// destination or source must be liability.
$valid = config('firefly.valid_liabilities');
if (in_array($destination->accountType->type, $valid)) {
Log::debug(sprintf('Dest account type is "%s", include it.', $destination->accountType->type));
$this->work[] = $destination;
}
if (in_array($source->accountType->type, $valid)) {
Log::debug(sprintf('Src account type is "%s", include it.', $source->accountType->type));
$this->work[] = $source;
}
}
/**
* @param TransactionJournal $journal
*
* @return Account
* @throws FireflyException
*/
private function getSourceAccount(TransactionJournal $journal): Account
{
return $this->getAccountByDirection($journal, '<');
}
/**
* @param TransactionJournal $journal
* @param string $direction
*
* @return Account
* @throws FireflyException
*/
private function getAccountByDirection(TransactionJournal $journal, string $direction): Account
{
/** @var Transaction $transaction */
$transaction = $journal->transactions()->where('amount', $direction, '0')->first();
if (null === $transaction) {
throw new FireflyException(sprintf('Cannot find "%s"-transaction of journal #%d', $direction, $journal->id));
}
$account = $transaction->account;
if (null === $account) {
throw new FireflyException(sprintf('Cannot find "%s"-account of transaction #%d of journal #%d', $direction, $transaction->id, $journal->id));
}
return $account;
}
/**
* @param TransactionJournal $journal
*
* @return Account
* @throws FireflyException
*/
private function getDestinationAccount(TransactionJournal $journal): Account
{
return $this->getAccountByDirection($journal, '>');
}
/**
*
*/
private function processAccount(): void
{
Log::debug(sprintf('Now in %s', __METHOD__));
$valid = config('firefly.valid_liabilities');
if (in_array($this->account->accountType->type, $valid)) {
Log::debug(sprintf('Account type is "%s", include it.', $this->account->accountType->type));
$this->work[] = $this->account;
}
}
/**
* @param Account|null $account
*/
public function setAccount(?Account $account): void
{
$this->account = $account;
}
/**
* @param TransactionGroup $group
*/
public function setGroup(TransactionGroup $group): void
{
$this->group = $group;
}
/**
* @param Transaction $transaction
* @param string $amount
*
* @return string
*/
private function processTransaction(Account $account, Transaction $transaction, string $amount): string
{
Log::debug(sprintf('Now in %s(#%d, %s)', __METHOD__, $transaction->id, $amount));
$journal = $transaction->transactionJournal;
$type = $journal->transactionType->type;
Log::debug(sprintf('Type is "%s"', $type));
if (in_array($type, [TransactionType::WITHDRAWAL]) && (int)$account->id === (int)$transaction->account_id && 1 === bccomp($transaction->amount, '0')) {
Log::debug(sprintf('Transaction #%d is withdrawal into liability #%d, does not influence the amount left.', $account->id, $transaction->account_id));
return $amount;
}
if (in_array($type, [TransactionType::DEPOSIT]) && (int)$account->id === (int)$transaction->account_id && -1 === bccomp($transaction->amount, '0')) {
Log::debug(sprintf('Transaction #%d is deposit from liability #%d,does not influence the amount left.', $account->id, $transaction->account_id));
return $amount;
}
if (in_array($type, [TransactionType::WITHDRAWAL, TransactionType::DEPOSIT, TransactionType::TRANSFER], true)) {
$amount = bcadd($amount, bcmul($transaction->amount, '-1'));
}
Log::debug(sprintf('Amount is now %s', $amount));
return $amount;
}
}

View File

@@ -23,6 +23,8 @@ declare(strict_types=1);
namespace FireflyIII\Services\Internal\Update;
use FireflyIII\Events\UpdatedAccount;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType;
use FireflyIII\Models\Location;
@@ -44,6 +46,7 @@ class AccountUpdateService
protected array $validCCFields;
protected array $validFields;
private array $canHaveVirtual;
private array $canHaveOpeningBalance;
private User $user;
/**
@@ -51,11 +54,12 @@ class AccountUpdateService
*/
public function __construct()
{
$this->canHaveVirtual = config('firefly.can_have_virtual_amounts');
$this->validAssetFields = config('firefly.valid_asset_fields');
$this->validCCFields = config('firefly.valid_cc_fields');
$this->validFields = config('firefly.valid_account_fields');
$this->accountRepository = app(AccountRepositoryInterface::class);
$this->canHaveVirtual = config('firefly.can_have_virtual_amounts');
$this->canHaveOpeningBalance = config('firefly.can_have_opening_balance');
$this->validAssetFields = config('firefly.valid_asset_fields');
$this->validCCFields = config('firefly.valid_cc_fields');
$this->validFields = config('firefly.valid_account_fields');
$this->accountRepository = app(AccountRepositoryInterface::class);
}
/**
@@ -98,6 +102,9 @@ class AccountUpdateService
// update opening balance.
$this->updateOpeningBalance($account, $data);
// update opening balance.
$this->updateCreditLiability($account, $data);
// update note:
if (array_key_exists('notes', $data) && null !== $data['notes']) {
$this->updateNote($account, (string)$data['notes']);
@@ -106,6 +113,8 @@ class AccountUpdateService
// update preferences if inactive:
$this->updatePreferences($account);
event(new UpdatedAccount($account));
return $account;
}
@@ -275,19 +284,21 @@ class AccountUpdateService
/**
* @param Account $account
* @param array $data
*
* @throws FireflyException
*/
private function updateOpeningBalance(Account $account, array $data): void
{
// has valid initial balance (IB) data?
$type = $account->accountType;
// if it can have a virtual balance, it can also have an opening balance.
if (in_array($type->type, $this->canHaveVirtual, true)) {
if (in_array($type->type, $this->canHaveOpeningBalance, true)) {
// check if is submitted as empty, that makes it valid:
if ($this->validOBData($data) && !$this->isEmptyOBData($data)) {
$this->updateOBGroup($account, $data);
$openingBalance = $data['opening_balance'];
$openingBalanceDate = $data['opening_balance_date'];
$this->updateOBGroupV2($account, $openingBalance, $openingBalanceDate);
}
if (!$this->validOBData($data) && $this->isEmptyOBData($data)) {
@@ -296,6 +307,36 @@ class AccountUpdateService
}
}
/**
* @param Account $account
* @param array $data
*
* @throws FireflyException
*/
private function updateCreditLiability(Account $account, array $data): void
{
$type = $account->accountType;
$valid = config('firefly.valid_liabilities');
if (in_array($type->type, $valid, true)) {
$direction = array_key_exists('liability_direction', $data) ? $data['liability_direction'] : 'empty';
// check if is submitted as empty, that makes it valid:
if ($this->validOBData($data) && !$this->isEmptyOBData($data)) {
$openingBalance = $data['opening_balance'];
$openingBalanceDate = $data['opening_balance_date'];
if ('credit' === $data['liability_direction']) {
$this->updateCreditTransaction($account, $openingBalance, $openingBalanceDate);
}
}
if (!$this->validOBData($data) && $this->isEmptyOBData($data)) {
$this->deleteCreditTransaction($account);
}
if ($this->validOBData($data) && !$this->isEmptyOBData($data) && 'credit' !== $direction) {
$this->deleteCreditTransaction($account);
}
}
}
/**
* @param Account $account
*/

View File

@@ -110,7 +110,7 @@ trait UserNavigation
final protected function redirectAccountToAccount(Account $account)
{
$type = $account->accountType->type;
if (AccountType::RECONCILIATION === $type || AccountType::INITIAL_BALANCE === $type) {
if (AccountType::RECONCILIATION === $type || AccountType::INITIAL_BALANCE === $type || AccountType::LIABILITY_CREDIT === $type) {
// reconciliation must be stored somewhere in this account's transactions.
/** @var Transaction|null $transaction */

View File

@@ -22,6 +22,7 @@
declare(strict_types=1);
namespace FireflyIII\Transformers;
use Carbon\Carbon;
use FireflyIII\Models\Account;
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
@@ -56,10 +57,11 @@ class AccountTransformer extends AbstractTransformer
$this->repository->setUser($account->user);
// get account type:
$fullType = $account->accountType->type;
$accountType = (string)config(sprintf('firefly.shortNamesByFullName.%s', $fullType));
$liabilityType = (string)config(sprintf('firefly.shortLiabilityNameByFullName.%s', $fullType));
$liabilityType = '' === $liabilityType ? null : strtolower($liabilityType);
$fullType = $account->accountType->type;
$accountType = (string)config(sprintf('firefly.shortNamesByFullName.%s', $fullType));
$liabilityType = (string)config(sprintf('firefly.shortLiabilityNameByFullName.%s', $fullType));
$liabilityType = '' === $liabilityType ? null : strtolower($liabilityType);
$liabilityDirection = $this->repository->getMetaValue($account, 'liability_direction');
// get account role (will only work if the type is asset.
$accountRole = $this->getAccountRole($account, $accountType);
@@ -114,8 +116,10 @@ class AccountTransformer extends AbstractTransformer
'opening_balance' => $openingBalance,
'opening_balance_date' => $openingBalanceDate,
'liability_type' => $liabilityType,
'liability_direction' => $liabilityDirection,
'interest' => $interest,
'interest_period' => $interestPeriod,
'current_debt' => $this->repository->getMetaValue($account,'current_debt'),
'include_net_worth' => $includeNetWorth,
'longitude' => $longitude,
'latitude' => $latitude,
@@ -195,7 +199,7 @@ class AccountTransformer extends AbstractTransformer
$creditCardType = $this->repository->getMetaValue($account, 'cc_type');
$monthlyPaymentDate = $this->repository->getMetaValue($account, 'cc_monthly_payment_date');
}
if(null !== $monthlyPaymentDate) {
if (null !== $monthlyPaymentDate) {
$monthlyPaymentDate = Carbon::createFromFormat('!Y-m-d', $monthlyPaymentDate, config('app.timezone'))->toAtomString();
}
@@ -219,7 +223,7 @@ class AccountTransformer extends AbstractTransformer
$openingBalance = $amount;
$openingBalanceDate = $this->repository->getOpeningBalanceDate($account);
}
if(null !== $openingBalanceDate) {
if (null !== $openingBalanceDate) {
$openingBalanceDate = Carbon::createFromFormat('!Y-m-d', $openingBalanceDate, config('app.timezone'))->toAtomString();
}

View File

@@ -0,0 +1,96 @@
<?php
/*
* LiabilityValidation.php
* Copyright (c) 2021 james@firefly-iii.org
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
namespace FireflyIII\Validation\Account;
use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType;
use Log;
/**
* Trait LiabilityValidation
*/
trait LiabilityValidation
{
/**
* Source of an liability credit must be a liability.
*
* @param string|null $accountName
*
* @return bool
*/
protected function validateLCSource(?string $accountName): bool
{
$result = true;
Log::debug(sprintf('Now in validateLCDestination("%s")', $accountName));
if ('' === $accountName || null === $accountName) {
$result = false;
}
if (true === $result) {
// set the source to be a (dummy) revenue account.
$account = new Account;
$accountType = AccountType::whereType(AccountType::LIABILITY_CREDIT)->first();
$account->accountType = $accountType;
$this->source = $account;
}
return $result;
}
/**
* @param int|null $accountId
*
* @return bool
*/
protected function validateLCDestination(?int $accountId): bool
{
Log::debug(sprintf('Now in validateLCDestination(%d)', $accountId));
$result = null;
$validTypes = config('firefly.valid_liabilities');
if (null === $accountId) {
$this->sourceError = (string)trans('validation.lc_destination_need_data');
$result = false;
}
Log::debug('Destination ID is not null.');
$search = $this->accountRepository->findNull($accountId);
// the source resulted in an account, but it's not of a valid type.
if (null !== $search && !in_array($search->accountType->type, $validTypes, true)) {
$message = sprintf('User submitted only an ID (#%d), which is a "%s", so this is not a valid destination.', $accountId, $search->accountType->type);
Log::debug($message);
$this->sourceError = $message;
$result = false;
}
// the source resulted in an account, AND it's of a valid type.
if (null !== $search && in_array($search->accountType->type, $validTypes, true)) {
Log::debug(sprintf('Found account of correct type: #%d, "%s"', $search->id, $search->name));
$this->source = $search;
$result = true;
}
return $result ?? false;
}
}

View File

@@ -34,6 +34,7 @@ use FireflyIII\Validation\Account\OBValidation;
use FireflyIII\Validation\Account\ReconciliationValidation;
use FireflyIII\Validation\Account\TransferValidation;
use FireflyIII\Validation\Account\WithdrawalValidation;
use FireflyIII\Validation\Account\LiabilityValidation;
use Log;
/**
@@ -41,7 +42,7 @@ use Log;
*/
class AccountValidator
{
use AccountValidatorProperties, WithdrawalValidation, DepositValidation, TransferValidation, ReconciliationValidation, OBValidation;
use AccountValidatorProperties, WithdrawalValidation, DepositValidation, TransferValidation, ReconciliationValidation, OBValidation, LiabilityValidation;
public bool $createMode;
public string $destError;
@@ -129,6 +130,9 @@ class AccountValidator
case TransactionType::OPENING_BALANCE:
$result = $this->validateOBDestination($accountId, $accountName);
break;
case TransactionType::LIABILITY_CREDIT:
$result = $this->validateLCDestination($accountId);
break;
case TransactionType::RECONCILIATION:
$result = $this->validateReconciliationDestination($accountId);
break;
@@ -164,6 +168,10 @@ class AccountValidator
case TransactionType::OPENING_BALANCE:
$result = $this->validateOBSource($accountId, $accountName);
break;
case TransactionType::LIABILITY_CREDIT:
$result = $this->validateLCSource($accountName);
break;
case TransactionType::RECONCILIATION:
Log::debug('Calling validateReconciliationSource');
$result = $this->validateReconciliationSource($accountId);
@@ -201,7 +209,7 @@ class AccountValidator
*/
protected function canCreateType(string $accountType): bool
{
$canCreate = [AccountType::EXPENSE, AccountType::REVENUE, AccountType::INITIAL_BALANCE];
$canCreate = [AccountType::EXPENSE, AccountType::REVENUE, AccountType::INITIAL_BALANCE, AccountType::LIABILITY_CREDIT];
if (in_array($accountType, $canCreate, true)) {
return true;
}

View File

@@ -172,6 +172,7 @@
"@php artisan firefly-iii:migrate-recurrence-meta",
"@php artisan firefly-iii:migrate-tag-locations",
"@php artisan firefly-iii:migrate-recurrence-type",
"@php artisan firefly-iii:upgrade-liabilities",
"@php artisan firefly-iii:fix-piggies",
"@php artisan firefly-iii:create-link-types",

View File

@@ -637,7 +637,7 @@ return [
AccountType::MORTGAGE,],
TransactionTypeModel::RECONCILIATION => [AccountType::RECONCILIATION, AccountType::ASSET],
// in case no transaction type is known yet, it could be anything.
'none' => [
'none' => [
AccountType::ASSET,
AccountType::EXPENSE,
AccountType::REVENUE,
@@ -647,77 +647,82 @@ return [
],
],
'destination' => [
TransactionTypeModel::WITHDRAWAL => [AccountType::EXPENSE, AccountType::CASH, AccountType::LOAN, AccountType::DEBT,
AccountType::MORTGAGE,],
TransactionTypeModel::DEPOSIT => [AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE],
TransactionTypeModel::TRANSFER => [AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE],
TransactionTypeModel::OPENING_BALANCE => [AccountType::INITIAL_BALANCE, AccountType::ASSET, AccountType::LOAN, AccountType::DEBT,
AccountType::MORTGAGE,],
TransactionTypeModel::RECONCILIATION => [AccountType::RECONCILIATION, AccountType::ASSET],
TransactionTypeModel::WITHDRAWAL => [AccountType::EXPENSE, AccountType::CASH, AccountType::LOAN, AccountType::DEBT,
AccountType::MORTGAGE,],
TransactionTypeModel::DEPOSIT => [AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE],
TransactionTypeModel::TRANSFER => [AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE],
TransactionTypeModel::OPENING_BALANCE => [AccountType::INITIAL_BALANCE, AccountType::ASSET, AccountType::LOAN, AccountType::DEBT,
AccountType::MORTGAGE,],
TransactionTypeModel::RECONCILIATION => [AccountType::RECONCILIATION, AccountType::ASSET],
TransactionTypeModel::LIABILITY_CREDIT => [AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE],
],
],
'allowed_opposing_types' => [
'source' => [
AccountType::ASSET => [AccountType::ASSET, AccountType::CASH, AccountType::DEBT, AccountType::EXPENSE, AccountType::INITIAL_BALANCE,
AccountType::LOAN, AccountType::RECONCILIATION, AccountType::MORTGAGE],
AccountType::CASH => [AccountType::ASSET],
AccountType::DEBT => [AccountType::ASSET, AccountType::DEBT, AccountType::EXPENSE, AccountType::INITIAL_BALANCE, AccountType::LOAN,
AccountType::MORTGAGE,],
AccountType::EXPENSE => [], // is not allowed as a source.
AccountType::INITIAL_BALANCE => [AccountType::ASSET, AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE],
AccountType::LOAN => [AccountType::ASSET, AccountType::DEBT, AccountType::EXPENSE, AccountType::INITIAL_BALANCE, AccountType::LOAN,
AccountType::MORTGAGE,],
AccountType::MORTGAGE => [AccountType::ASSET, AccountType::DEBT, AccountType::EXPENSE, AccountType::INITIAL_BALANCE, AccountType::LOAN,
AccountType::MORTGAGE,],
AccountType::RECONCILIATION => [AccountType::ASSET],
AccountType::REVENUE => [AccountType::ASSET, AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE],
AccountType::ASSET => [AccountType::ASSET, AccountType::CASH, AccountType::DEBT, AccountType::EXPENSE, AccountType::INITIAL_BALANCE,
AccountType::LOAN, AccountType::RECONCILIATION, AccountType::MORTGAGE],
AccountType::CASH => [AccountType::ASSET],
AccountType::DEBT => [AccountType::ASSET, AccountType::DEBT, AccountType::EXPENSE, AccountType::INITIAL_BALANCE, AccountType::LOAN,
AccountType::MORTGAGE, AccountType::LIABILITY_CREDIT],
AccountType::EXPENSE => [], // is not allowed as a source.
AccountType::INITIAL_BALANCE => [AccountType::ASSET, AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE],
AccountType::LOAN => [AccountType::ASSET, AccountType::DEBT, AccountType::EXPENSE, AccountType::INITIAL_BALANCE, AccountType::LOAN,
AccountType::MORTGAGE, AccountType::LIABILITY_CREDIT],
AccountType::MORTGAGE => [AccountType::ASSET, AccountType::DEBT, AccountType::EXPENSE, AccountType::INITIAL_BALANCE, AccountType::LOAN,
AccountType::MORTGAGE, AccountType::LIABILITY_CREDIT],
AccountType::RECONCILIATION => [AccountType::ASSET],
AccountType::REVENUE => [AccountType::ASSET, AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE],
AccountType::LIABILITY_CREDIT => [AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE],
],
'destination' => [
AccountType::ASSET => [AccountType::ASSET, AccountType::CASH, AccountType::DEBT, AccountType::INITIAL_BALANCE, AccountType::LOAN,
AccountType::MORTGAGE, AccountType::RECONCILIATION, AccountType::REVENUE,],
AccountType::CASH => [AccountType::ASSET],
AccountType::DEBT => [AccountType::ASSET, AccountType::DEBT, AccountType::INITIAL_BALANCE, AccountType::LOAN, AccountType::MORTGAGE,
AccountType::REVENUE,],
AccountType::EXPENSE => [AccountType::ASSET, AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE],
AccountType::INITIAL_BALANCE => [AccountType::ASSET, AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE],
AccountType::LOAN => [AccountType::ASSET, AccountType::DEBT, AccountType::INITIAL_BALANCE, AccountType::LOAN, AccountType::MORTGAGE,
AccountType::REVENUE,],
AccountType::MORTGAGE => [AccountType::ASSET, AccountType::DEBT, AccountType::INITIAL_BALANCE, AccountType::LOAN, AccountType::MORTGAGE,
AccountType::REVENUE,],
AccountType::RECONCILIATION => [AccountType::ASSET],
AccountType::REVENUE => [], // is not allowed as a destination
AccountType::ASSET => [AccountType::ASSET, AccountType::CASH, AccountType::DEBT, AccountType::INITIAL_BALANCE, AccountType::LOAN,
AccountType::MORTGAGE, AccountType::RECONCILIATION, AccountType::REVENUE,],
AccountType::CASH => [AccountType::ASSET],
AccountType::DEBT => [AccountType::ASSET, AccountType::DEBT, AccountType::INITIAL_BALANCE, AccountType::LOAN, AccountType::MORTGAGE,
AccountType::REVENUE,],
AccountType::EXPENSE => [AccountType::ASSET, AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE],
AccountType::INITIAL_BALANCE => [AccountType::ASSET, AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE],
AccountType::LOAN => [AccountType::ASSET, AccountType::DEBT, AccountType::INITIAL_BALANCE, AccountType::LOAN, AccountType::MORTGAGE,
AccountType::REVENUE,],
AccountType::MORTGAGE => [AccountType::ASSET, AccountType::DEBT, AccountType::INITIAL_BALANCE, AccountType::LOAN, AccountType::MORTGAGE,
AccountType::REVENUE,],
AccountType::RECONCILIATION => [AccountType::ASSET],
AccountType::REVENUE => [], // is not allowed as a destination
AccountType::LIABILITY_CREDIT => [],// is not allowed as a destination
],
],
// depending on the account type, return the allowed transaction types:
'allowed_transaction_types' => [
'source' => [
AccountType::ASSET => [TransactionTypeModel::WITHDRAWAL, TransactionTypeModel::TRANSFER, TransactionTypeModel::OPENING_BALANCE,
TransactionTypeModel::RECONCILIATION,],
AccountType::EXPENSE => [], // is not allowed as a source.
AccountType::REVENUE => [TransactionTypeModel::DEPOSIT],
AccountType::LOAN => [TransactionTypeModel::WITHDRAWAL, TransactionTypeModel::DEPOSIT, TransactionTypeModel::TRANSFER,
TransactionTypeModel::OPENING_BALANCE,],
AccountType::DEBT => [TransactionTypeModel::WITHDRAWAL, TransactionTypeModel::DEPOSIT, TransactionTypeModel::TRANSFER,
TransactionTypeModel::OPENING_BALANCE,],
AccountType::MORTGAGE => [TransactionTypeModel::WITHDRAWAL, TransactionTypeModel::DEPOSIT, TransactionTypeModel::TRANSFER,
TransactionTypeModel::OPENING_BALANCE,],
AccountType::INITIAL_BALANCE => [TransactionTypeModel::OPENING_BALANCE],
AccountType::RECONCILIATION => [TransactionTypeModel::RECONCILIATION],
AccountType::ASSET => [TransactionTypeModel::WITHDRAWAL, TransactionTypeModel::TRANSFER, TransactionTypeModel::OPENING_BALANCE,
TransactionTypeModel::RECONCILIATION,],
AccountType::EXPENSE => [], // is not allowed as a source.
AccountType::REVENUE => [TransactionTypeModel::DEPOSIT],
AccountType::LOAN => [TransactionTypeModel::WITHDRAWAL, TransactionTypeModel::DEPOSIT, TransactionTypeModel::TRANSFER,
TransactionTypeModel::OPENING_BALANCE, TransactionTypeModel::LIABILITY_CREDIT],
AccountType::DEBT => [TransactionTypeModel::WITHDRAWAL, TransactionTypeModel::DEPOSIT, TransactionTypeModel::TRANSFER,
TransactionTypeModel::OPENING_BALANCE, TransactionTypeModel::LIABILITY_CREDIT],
AccountType::MORTGAGE => [TransactionTypeModel::WITHDRAWAL, TransactionTypeModel::DEPOSIT, TransactionTypeModel::TRANSFER,
TransactionTypeModel::OPENING_BALANCE, TransactionTypeModel::LIABILITY_CREDIT],
AccountType::INITIAL_BALANCE => [TransactionTypeModel::OPENING_BALANCE],
AccountType::RECONCILIATION => [TransactionTypeModel::RECONCILIATION],
AccountType::LIABILITY_CREDIT => [TransactionTypeModel::LIABILITY_CREDIT],
],
'destination' => [
AccountType::ASSET => [TransactionTypeModel::DEPOSIT, TransactionTypeModel::TRANSFER, TransactionTypeModel::OPENING_BALANCE,
TransactionTypeModel::RECONCILIATION,],
AccountType::EXPENSE => [TransactionTypeModel::WITHDRAWAL],
AccountType::REVENUE => [], // is not allowed as destination.
AccountType::LOAN => [TransactionTypeModel::WITHDRAWAL, TransactionTypeModel::DEPOSIT, TransactionTypeModel::TRANSFER,
TransactionTypeModel::OPENING_BALANCE,],
AccountType::DEBT => [TransactionTypeModel::WITHDRAWAL, TransactionTypeModel::DEPOSIT, TransactionTypeModel::TRANSFER,
TransactionTypeModel::OPENING_BALANCE,],
AccountType::MORTGAGE => [TransactionTypeModel::WITHDRAWAL, TransactionTypeModel::DEPOSIT, TransactionTypeModel::TRANSFER,
TransactionTypeModel::OPENING_BALANCE,],
AccountType::INITIAL_BALANCE => [TransactionTypeModel::OPENING_BALANCE],
AccountType::RECONCILIATION => [TransactionTypeModel::RECONCILIATION],
AccountType::ASSET => [TransactionTypeModel::DEPOSIT, TransactionTypeModel::TRANSFER, TransactionTypeModel::OPENING_BALANCE,
TransactionTypeModel::RECONCILIATION,],
AccountType::EXPENSE => [TransactionTypeModel::WITHDRAWAL],
AccountType::REVENUE => [], // is not allowed as destination.
AccountType::LOAN => [TransactionTypeModel::WITHDRAWAL, TransactionTypeModel::DEPOSIT, TransactionTypeModel::TRANSFER,
TransactionTypeModel::OPENING_BALANCE,],
AccountType::DEBT => [TransactionTypeModel::WITHDRAWAL, TransactionTypeModel::DEPOSIT, TransactionTypeModel::TRANSFER,
TransactionTypeModel::OPENING_BALANCE,],
AccountType::MORTGAGE => [TransactionTypeModel::WITHDRAWAL, TransactionTypeModel::DEPOSIT, TransactionTypeModel::TRANSFER,
TransactionTypeModel::OPENING_BALANCE,],
AccountType::INITIAL_BALANCE => [TransactionTypeModel::OPENING_BALANCE],
AccountType::RECONCILIATION => [TransactionTypeModel::RECONCILIATION],
AccountType::LIABILITY_CREDIT => [], // is not allowed as a destination
],
],
@@ -776,40 +781,51 @@ return [
AccountType::LOAN => TransactionTypeModel::DEPOSIT,
AccountType::MORTGAGE => TransactionTypeModel::DEPOSIT,
],
AccountType::LIABILITY_CREDIT => [
AccountType::DEBT => TransactionTypeModel::LIABILITY_CREDIT,
AccountType::LOAN => TransactionTypeModel::LIABILITY_CREDIT,
AccountType::MORTGAGE => TransactionTypeModel::LIABILITY_CREDIT,
],
// AccountType::EXPENSE unlisted because it cant be a source
],
// allowed source -> destination accounts.
'source_dests' => [
TransactionTypeModel::WITHDRAWAL => [
TransactionTypeModel::WITHDRAWAL => [
AccountType::ASSET => [AccountType::EXPENSE, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE, AccountType::CASH],
AccountType::LOAN => [AccountType::EXPENSE, AccountType::CASH],
AccountType::DEBT => [AccountType::EXPENSE, AccountType::CASH],
AccountType::MORTGAGE => [AccountType::EXPENSE, AccountType::CASH],
],
TransactionTypeModel::DEPOSIT => [
TransactionTypeModel::DEPOSIT => [
AccountType::REVENUE => [AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE],
AccountType::CASH => [AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE],
AccountType::LOAN => [AccountType::ASSET],
AccountType::DEBT => [AccountType::ASSET],
AccountType::MORTGAGE => [AccountType::ASSET],
],
TransactionTypeModel::TRANSFER => [
TransactionTypeModel::TRANSFER => [
AccountType::ASSET => [AccountType::ASSET],
AccountType::LOAN => [AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE],
AccountType::DEBT => [AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE],
AccountType::MORTGAGE => [AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE],
],
TransactionTypeModel::OPENING_BALANCE => [
TransactionTypeModel::OPENING_BALANCE => [
AccountType::ASSET => [AccountType::INITIAL_BALANCE],
AccountType::LOAN => [AccountType::INITIAL_BALANCE],
AccountType::DEBT => [AccountType::INITIAL_BALANCE],
AccountType::MORTGAGE => [AccountType::INITIAL_BALANCE],
AccountType::INITIAL_BALANCE => [AccountType::ASSET, AccountType::LOAN, AccountType::DEBT, AccountType::MORTGAGE],
],
TransactionTypeModel::RECONCILIATION => [
TransactionTypeModel::RECONCILIATION => [
AccountType::RECONCILIATION => [AccountType::ASSET],
AccountType::ASSET => [AccountType::RECONCILIATION],
],
TransactionTypeModel::LIABILITY_CREDIT => [
AccountType::LOAN => [AccountType::LIABILITY_CREDIT],
AccountType::DEBT => [AccountType::LIABILITY_CREDIT],
AccountType::MORTGAGE => [AccountType::LIABILITY_CREDIT],
],
],
// if you add fields to this array, dont forget to update the export routine (ExportDataGenerator).
'journal_meta_fields' => [
@@ -845,7 +861,8 @@ return [
Webhook::DELIVERY_JSON => 'DELIVERY_JSON',
],
],
'can_have_virtual_amounts' => [AccountType::ASSET, AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE, AccountType::CREDITCARD],
'can_have_virtual_amounts' => [AccountType::ASSET],
'can_have_opening_balance' => [AccountType::ASSET, AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE, AccountType::CREDITCARD],
'valid_asset_fields' => ['account_role', 'account_number', 'currency_id', 'BIC', 'include_net_worth'],
'valid_cc_fields' => ['account_role', 'cc_monthly_payment_date', 'cc_type', 'account_number', 'currency_id', 'BIC', 'include_net_worth'],
'valid_account_fields' => ['account_number', 'currency_id', 'BIC', 'interest', 'interest_period', 'include_net_worth', 'liability_direction'],

View File

@@ -46,6 +46,7 @@ class AccountTypeSeeder extends Seeder
AccountType::RECONCILIATION,
AccountType::DEBT,
AccountType::MORTGAGE,
AccountType::LIABILITY_CREDIT
];
foreach ($types as $type) {
try {

View File

@@ -40,6 +40,7 @@ class TransactionTypeSeeder extends Seeder
TransactionType::OPENING_BALANCE,
TransactionType::RECONCILIATION,
TransactionType::INVALID,
TransactionType::LIABILITY_CREDIT
];
foreach ($types as $type) {

View File

@@ -238,7 +238,8 @@ export default {
axios.post(url, submission)
.then(response => {
// console.log('success!');
this.errors = lodashClonedeep(this.defaultErrors);
console.log('success!');
this.returnedId = parseInt(response.data.data.id);
this.returnedTitle = response.data.data.attributes.name;
this.successMessage = this.$t('firefly.stored_new_account_js', {ID: this.returnedId, name: this.returnedTitle});
@@ -281,6 +282,9 @@ export default {
if (errors.errors.hasOwnProperty(i)) {
this.errors[i] = errors.errors[i];
}
if('liability_start_date' === i) {
this.errors.opening_balance_date = errors.errors[i];
}
}
},
getSubmission: function () {
@@ -302,13 +306,18 @@ export default {
submission.liability_type = this.liability_type.toLowerCase();
submission.interest = this.interest;
submission.interest_period = this.interest_period;
submission.opening_balance = this.liability_amount;
submission.opening_balance_date = this.liability_date;
submission.liability_amount = this.liability_amount;
submission.liability_start_date = this.liability_date;
submission.liability_direction = this.liability_direction;
}
if (null !== this.opening_balance && null !== this.opening_balance_date && 'asset' === this.type) {
if ((null !== this.opening_balance || null !== this.opening_balance_date) && 'asset' === this.type) {
submission.opening_balance = this.opening_balance;
submission.opening_balance_date = this.opening_balance_date;
}
if('' === submission.opening_balance) {
delete submission.opening_balance;
}
if ('asset' === this.type && 'ccAsset' === this.account_role) {
submission.credit_card_type = 'monthlyFull';
submission.monthly_payment_date = '2021-01-01';

View File

@@ -54,6 +54,31 @@
<span v-if="null === data.item.iban && null !== data.item.account_number">{{ data.item.account_number }}</span>
<span v-if="null !== data.item.iban && null !== data.item.account_number">{{ data.item.iban }} ({{ data.item.account_number }})</span>
</template>
<template #cell(last_activity)="data">
<span v-if="'asset' === type && 'loading' === data.item.last_activity">
<i class="fas fa-spinner fa-spin"></i>
</span>
<span v-if="'asset' === type && 'none' === data.item.last_activity" class="text-muted">
{{ $t('firefly.never') }}
</span>
<span v-if="'asset' === type && 'loading' !== data.item.last_activity && 'none' !== data.item.last_activity">
{{ data.item.last_activity }}
</span>
</template>
<template #cell(amount_due)="data">
<span class="text-success" v-if="parseFloat(data.item.amount_due) > 0">
{{ Intl.NumberFormat('en-US', {style: 'currency', currency: data.item.currency_code}).format(data.item.amount_due) }}
</span>
<span class="text-danger" v-if="parseFloat(data.item.amount_due) < 0">
{{ Intl.NumberFormat('en-US', {style: 'currency', currency: data.item.currency_code}).format(data.item.amount_due) }}
</span>
<span class="text-muted" v-if="parseFloat(data.item.amount_due) === 0.0">
{{ Intl.NumberFormat('en-US', {style: 'currency', currency: data.item.currency_code}).format(data.item.amount_due) }}
</span>
</template>
<template #cell(current_balance)="data">
<span class="text-success" v-if="parseFloat(data.item.current_balance) > 0">
{{
@@ -102,6 +127,9 @@
}}</span>)
</span>
</template>
<template #cell(interest)="data">
{{ parseFloat(data.item.interest) }}% ({{ data.item.interest_period }})
</template>
<template #cell(menu)="data">
<div class="btn-group btn-group-sm">
<div class="dropdown">
@@ -249,14 +277,24 @@ export default {
updateFieldList: function () {
this.fields = [];
this.fields = [{key: 'title', label: this.$t('list.name'), sortable: !this.orderMode}];
if ('asset' === this.type) {
this.fields.push({key: 'role', label: this.$t('list.role'), sortable: !this.orderMode});
}
if ('liabilities' === this.type) {
this.fields.push({key: 'liability_type', label: this.$t('list.liability_type'), sortable: !this.orderMode});
this.fields.push({key: 'liability_direction', label: this.$t('list.liability_direction'), sortable: !this.orderMode});
this.fields.push({key: 'interest', label: this.$t('list.interest') + ' (' + this.$t('list.interest_period') + ')', sortable: !this.orderMode});
}
// add the rest
this.fields.push({key: 'number', label: this.$t('list.iban'), sortable: !this.orderMode});
this.fields.push({key: 'current_balance', label: this.$t('list.currentBalance'), sortable: !this.orderMode});
if ('liabilities' === this.type) {
this.fields.push({key: 'amount_due', label: this.$t('firefly.left_in_debt'), sortable: !this.orderMode});
}
if ('asset' === this.type || 'liabilities' === this.type) {
this.fields.push({key: 'last_activity', label: this.$t('list.lastActivity'), sortable: !this.orderMode});
}
this.fields.push({key: 'menu', label: ' ', sortable: false});
},
getAccountList: function () {
@@ -273,7 +311,6 @@ export default {
// console.log('Index ready, not loading and not downloaded.');
this.loading = true;
this.filterAccountList();
// TODO filter accounts.
}
},
downloadAccountList: function (page) {
@@ -344,19 +381,45 @@ export default {
acct.account_number = current.attributes.account_number;
acct.current_balance = current.attributes.current_balance;
acct.currency_code = current.attributes.currency_code;
if ('liabilities' === this.type) {
acct.liability_type = this.$t('firefly.account_type_' + current.attributes.liability_type);
acct.liability_direction = this.$t('firefly.liability_direction_' + current.attributes.liability_direction + '_short');
acct.interest = current.attributes.interest;
acct.interest_period = this.$t('firefly.interest_calc_' + current.attributes.interest_period);
acct.amount_due = current.attributes.current_debt;
}
acct.balance_diff = 'loading';
acct.last_activity = 'loading';
if (null !== current.attributes.iban) {
acct.iban = current.attributes.iban.match(/.{1,4}/g).join(' ');
}
if (null === current.attributes.iban) {
acct.iban = null;
}
this.allAccounts.push(acct);
if ('asset' === this.type) {
this.getAccountBalanceDifference(this.allAccounts.length - 1, current);
this.getAccountLastActivity(this.allAccounts.length - 1, current);
}
}
}
},
getAccountLastActivity: function (index, acct) {
// console.log('getAccountLastActivity(' + index + ')');
// get single transaction for account:
// /api/v1/accounts/1/transactions?limit=1
axios.get('./api/v1/accounts/' + acct.id + '/transactions?limit=1').then(response => {
if (0 === response.data.data.length) {
this.allAccounts[index].last_activity = 'none';
return;
}
let date = new Date(response.data.data[0].attributes.transactions[0].date);
this.allAccounts[index].last_activity = format(date, this.$t('config.month_and_day_fns'));
});
},
getAccountBalanceDifference: function (index, acct) {
// console.log('getAccountBalanceDifference(' + index + ')');
// get account on day 0

View File

@@ -28,6 +28,7 @@ return [
'month' => '%B %Y',
'month_and_day' => '%B %e, %Y',
'month_and_day_moment_js' => 'MMM D, YYYY',
'month_and_day_fns' => 'MMMM d, y',
'month_and_date_day' => '%A %B %e, %Y',
'month_and_day_no_year' => '%B %e',
'date_time' => '%B %e, %Y, @ %T',

View File

@@ -1130,6 +1130,7 @@ return [
'already_cleared_transactions' => 'Already cleared transactions (:count)',
'submitted_end_balance' => 'Submitted end balance',
'initial_balance_description' => 'Initial balance for ":account"',
'liability_credit_description' => 'Liability credit for ":account"',
'interest_calc_' => 'unknown',
'interest_calc_daily' => 'Per day',
'interest_calc_monthly' => 'Per month',
@@ -1317,9 +1318,16 @@ return [
'account_type_Debt' => 'Debt',
'account_type_Loan' => 'Loan',
'account_type_Mortgage' => 'Mortgage',
'account_type_debt' => 'Debt',
'account_type_loan' => 'Loan',
'account_type_mortgage' => 'Mortgage',
'account_type_Credit card' => 'Credit card',
'liability_direction_credit' => 'I am owed this debt',
'liability_direction_debit' => 'I owe this debt to somebody else',
'liability_direction_credit_short' => 'Owed this debt',
'liability_direction_debit_short' => 'Owe this debt',
'liability_direction__short' => 'Unknown',
'Liability credit' => 'Liability credit',
'budgets' => 'Budgets',
'tags' => 'Tags',
'reports' => 'Reports',
@@ -1390,6 +1398,7 @@ return [
'splitByAccount' => 'Split by account',
'coveredWithTags' => 'Covered with tags',
'leftInBudget' => 'Left in budget',
'left_in_debt' => 'Amount due',
'sumOfSums' => 'Sum of sums',
'noCategory' => '(no category)',
'notCharged' => 'Not charged (yet)',

View File

@@ -130,6 +130,7 @@ return [
'field' => 'Field',
'value' => 'Value',
'interest' => 'Interest',
'interest_period' => 'interest period',
'interest_period' => 'Interest period',
'liability_type' => 'Type of liability',
'liability_direction' => 'Liability in/out',
];

View File

@@ -200,6 +200,7 @@ return [
'need_id_in_edit' => 'Each split must have transaction_journal_id (either valid ID or 0).',
'ob_source_need_data' => 'Need to get a valid source account ID and/or valid source account name to continue.',
'lc_source_need_data' => 'Need to get a valid source account ID to continue.',
'ob_dest_need_data' => 'Need to get a valid destination account ID and/or valid destination account name to continue.',
'ob_dest_bad_data' => 'Could not find a valid destination account when searching for ID ":id" or name ":name".',

View File

@@ -27,7 +27,8 @@
{% endif %}
{% if objectType == 'liabilities' %}
{{ ExpandedForm.select('liability_type_id', liabilityTypes) }}
{{ ExpandedForm.amountNoCurrency('opening_balance', null, {label:'debt_start_amount'|_, helpText: 'debt_start_amount_help'|_}) }}
{{ ExpandedForm.amountNoCurrency('opening_balance', null, {label:'debt_start_amount'|_}) }}
{{ ExpandedForm.select('liability_direction', liabilityDirections) }}
{{ ExpandedForm.date('opening_balance_date', null, {label:'debt_start_date'|_}) }}
{{ ExpandedForm.percentage('interest') }}
{{ ExpandedForm.select('interest_period', interestPeriods, null, {helpText: 'interest_period_help'|_}) }}

View File

@@ -36,6 +36,7 @@
{% if objectType == 'liabilities' %}
{{ ExpandedForm.select('liability_type_id', liabilityTypes) }}
{{ ExpandedForm.amountNoCurrency('opening_balance', null, {label:'debt_start_amount'|_, helpText: 'debt_start_amount_help'|_}) }}
{{ ExpandedForm.select('liability_direction', liabilityDirections) }}
{{ ExpandedForm.date('opening_balance_date', null, {label:'debt_start_date'|_}) }}
{{ ExpandedForm.percentage('interest') }}
{{ ExpandedForm.select('interest_period', interestPeriods) }}

View File

@@ -11,10 +11,16 @@
{% endif %}
{% if objectType == 'liabilities' %}
<th>{{ trans('list.liability_type') }}</th>
<th>{{ trans('form.liability_direction') }}</th>
<th>{{ trans('list.interest') }} ({{ trans('list.interest_period') }})</th>
{% endif %}
<th class="hidden-sm hidden-xs">{{ trans('form.account_number') }}</th>
<th>{{ trans('list.currentBalance') }}</th>
<th style="text-align: right;">{{ trans('list.currentBalance') }}</th>
{% if objectType == 'liabilities' %}
<th style="text-align: right;">
{{ trans('firefly.left_in_debt') }}
</th>
{% endif %}
<th class="hidden-sm hidden-xs">{{ trans('list.active') }}</th>
{# hide last activity to make room for other stuff #}
{% if objectType != 'liabilities' %}
@@ -50,10 +56,9 @@
</td>
{% endif %}
{% if objectType == 'liabilities' %}
<td>{{ account.accountTypeString }}</td>
<td>
{{ account.interest }}% ({{ account.interestPeriod|lower }})
</td>
<td>{{ account.accountTypeString }}</td>
<td>{{ trans('firefly.liability_direction_'~account.liability_direction~'_short') }}</td>
<td>{{ account.interest }}% ({{ account.interestPeriod|lower }})</td>
{% endif %}
<td class="hidden-sm hidden-xs">{{ account.iban }}{% if account.iban == '' %}{{ accountGetMetaField(account, 'account_number') }}{% endif %}</td>
<td style="text-align: right;">
@@ -61,6 +66,13 @@
{{ formatAmountByAccount(account, account.endBalance) }}
</span>
</td>
{% if objectType == 'liabilities' %}
<td style="text-align: right;">
{% if '-' != account.current_debt %}
<span class="text-info">{{ formatAmountByAccount(account, account.current_debt, false) }}</span>
{% endif %}
</td>
{% endif %}
<td class="hidden-sm hidden-xs">
{% if account.active %}
<i class="fa fa-fw fa-check"></i>

View File

@@ -118,6 +118,9 @@
{% if transaction.transaction_type_type == 'Opening balance' %}
<i class="object-handle fa-fw fa fa-star-o" title="{{ trans('firefly.Opening balance') }}"></i>
{% endif %}
{% if transaction.transaction_type_type == 'Liability credit' %}
<i class="object-handle fa-fw fa fa-star-o" title="{{ trans('firefly.Liability credit') }}"></i>
{% endif %}
</td>
<td style=" {{ style|raw }}">
@@ -136,11 +139,13 @@
{% endif %}
</td>
<td style=" {{ style|raw }}">
{# deposit #}
{% if transaction.transaction_type_type == 'Deposit' %}
{{ formatAmountBySymbol(transaction.amount*-1, transaction.currency_symbol, transaction.currency_decimal_places) }}
{% if null != transaction.foreign_amount %}
({{ formatAmountBySymbol(transaction.foreign_amount*-1, transaction.foreign_currency_symbol, transaction.foreign_currency_decimal_places) }})
{% endif %}
{# transfer #}
{% elseif transaction.transaction_type_type == 'Transfer' %}
<span class="text-info">
{{ formatAmountBySymbol(transaction.amount*-1, transaction.currency_symbol, transaction.currency_decimal_places, false) }}
@@ -148,6 +153,7 @@
({{ formatAmountBySymbol(transaction.foreign_amount*-1, transaction.foreign_currency_symbol, transaction.foreign_currency_decimal_places, false) }})
{% endif %}
</span>
{# opening balance #}
{% elseif transaction.transaction_type_type == 'Opening balance' %}
{% if transaction.source_account_type == 'Initial balance account' %}
{{ formatAmountBySymbol(transaction.amount*-1, transaction.currency_symbol, transaction.currency_decimal_places) }}
@@ -160,6 +166,7 @@
({{ formatAmountBySymbol(transaction.foreign_amount, transaction.foreign_currency_symbol, transaction.foreign_currency_decimal_places) }})
{% endif %}
{% endif %}
{# reconciliation #}
{% elseif transaction.transaction_type_type == 'Reconciliation' %}
{% if transaction.source_account_type == 'Reconciliation account' %}
{{ formatAmountBySymbol(transaction.amount*-1, transaction.currency_symbol, transaction.currency_decimal_places) }}
@@ -172,6 +179,22 @@
({{ formatAmountBySymbol(transaction.foreign_amount, transaction.foreign_currency_symbol, transaction.foreign_currency_decimal_places) }})
{% endif %}
{% endif %}
{# liability credit #}
{% elseif transaction.transaction_type_type == 'Liability credit' %}
{% if transaction.source_account_type == 'Liability credit' %}
{{ formatAmountBySymbol(transaction.amount, transaction.currency_symbol, transaction.currency_decimal_places) }}
{% if null != transaction.foreign_amount %}
({{ formatAmountBySymbol(transaction.foreign_amount, transaction.foreign_currency_symbol, transaction.foreign_currency_decimal_places) }})
{% endif %}
{% else %}
{{ formatAmountBySymbol(transaction.amount*-1, transaction.currency_symbol, transaction.currency_decimal_places) }}
{% if null != transaction.foreign_amount %}
({{ formatAmountBySymbol(transaction.foreign_amount*-1, transaction.foreign_currency_symbol, transaction.foreign_currency_decimal_places) }})
{% endif %}
{% endif %}
{# THE REST #}
{% else %}
{{ formatAmountBySymbol(transaction.amount, transaction.currency_symbol, transaction.currency_decimal_places) }}
{% if null != transaction.foreign_amount %}

View File

@@ -39,6 +39,7 @@
<li role="separator" class="divider"></li>
<li><a href="{{ route('transactions.clone', [transactionGroup.id]) }}"><i class="fa fa-copy"></i> {{ 'clone'|_ }}</a></li>
{% endif %}
</ul>
</div>
</div>
@@ -231,12 +232,17 @@
<a href="{{ route('accounts.show', journal.source_id) }}"
title="{{ journal.source_iban|default(journal.source_name) }}">{{ journal.source_name }}</a> &rarr;
{% endif %}
{% if first.transactiontype.type == 'Withdrawal' or first.transactiontype.type == 'Deposit' %}
{{ formatAmountBySymbol(journal.amount*-1, journal.currency_symbol, journal.currency_decimal_places) }}
{% elseif first.transactiontype.type == 'Transfer' or first.transactiontype.type == 'Opening balance' %}
<span class="text-info">
{{ formatAmountBySymbol(journal.amount, journal.currency_symbol, journal.currency_decimal_places, false) }}
</span>
{% elseif first.transactiontype.type == 'Liability credit' %}
<span class="text-info">
{{ formatAmountBySymbol(journal.amount*-1, journal.currency_symbol, journal.currency_decimal_places, false) }}
</span>
{% endif %}
<!-- do foreign amount -->