Files
firefly-iii/app/Services/Internal/Update/AccountUpdateService.php

316 lines
12 KiB
PHP
Raw Normal View History

2018-02-21 20:34:24 +01:00
<?php
/**
* AccountUpdateService.php
2020-02-16 13:56:35 +01:00
* Copyright (c) 2019 james@firefly-iii.org
2018-02-21 20:34:24 +01:00
*
* This file is part of Firefly III (https://github.com/firefly-iii).
2018-02-21 20:34:24 +01:00
*
* 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.
2018-02-21 20:34:24 +01:00
*
* This program is distributed in the hope that it will be useful,
2018-02-21 20:34:24 +01:00
* 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.
2018-02-21 20:34:24 +01:00
*
* 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/>.
2018-02-21 20:34:24 +01:00
*/
declare(strict_types=1);
namespace FireflyIII\Services\Internal\Update;
use FireflyIII\Events\UpdatedAccount;
use FireflyIII\Exceptions\FireflyException;
2018-02-21 20:34:24 +01:00
use FireflyIII\Models\Account;
2019-06-22 10:25:34 +02:00
use FireflyIII\Models\AccountType;
use FireflyIII\Models\Location;
2019-06-22 10:25:34 +02:00
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
2018-02-21 20:34:24 +01:00
use FireflyIII\Services\Internal\Support\AccountServiceTrait;
2019-07-31 16:53:09 +02:00
use FireflyIII\User;
2018-02-21 20:34:24 +01:00
/**
* Class AccountUpdateService
2022-10-30 11:43:17 +01:00
* TODO this service is messy and convoluted.
2018-02-21 20:34:24 +01:00
*/
class AccountUpdateService
{
use AccountServiceTrait;
2018-12-21 16:38:10 +01:00
protected AccountRepositoryInterface $accountRepository;
protected array $validAssetFields;
protected array $validCCFields;
protected array $validFields;
private array $canHaveOpeningBalance;
private User $user;
/**
* Constructor.
*/
public function __construct()
{
$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);
}
2018-02-21 20:34:24 +01:00
/**
* Update account data.
*
2021-05-24 08:54:58 +02:00
* @throws FireflyException
2023-12-22 20:12:38 +01:00
*/
2018-02-21 20:34:24 +01:00
public function update(Account $account, array $data): Account
{
2023-10-29 06:33:43 +01:00
app('log')->debug(sprintf('Now in %s', __METHOD__));
2019-06-22 10:25:34 +02:00
$this->accountRepository->setUser($account->user);
2019-07-31 16:53:09 +02:00
$this->user = $account->user;
2020-03-17 14:46:17 +01:00
$account = $this->updateAccount($account, $data);
$account = $this->updateAccountOrder($account, $data);
2019-06-22 10:25:34 +02:00
// find currency, or use default currency instead.
if (array_key_exists('currency_id', $data) || array_key_exists('currency_code', $data)) {
$currency = $this->getCurrency((int)($data['currency_id'] ?? null), (string)($data['currency_code'] ?? null));
unset($data['currency_code'], $data['currency_id']);
$data['currency_id'] = $currency->id;
}
2018-02-21 20:34:24 +01:00
// update all meta data:
$this->updateMetaData($account, $data);
// update, delete or create location:
2020-10-23 18:26:18 +02:00
$this->updateLocation($account, $data);
// update opening balance.
$this->updateOpeningBalance($account, $data);
2023-01-08 07:43:16 +01:00
// Since 5.8.0, delete liability credit transactions, if any:
$this->deleteCreditTransaction($account);
2020-10-23 18:26:18 +02:00
// update note:
2021-04-06 17:00:16 +02:00
if (array_key_exists('notes', $data) && null !== $data['notes']) {
2022-12-29 19:42:26 +01:00
$this->updateNote($account, (string)$data['notes']);
2020-10-23 18:26:18 +02:00
}
// update preferences if inactive:
2021-04-04 07:25:52 +02:00
$this->updatePreferences($account);
2020-10-23 18:26:18 +02:00
event(new UpdatedAccount($account));
2020-10-23 18:26:18 +02:00
return $account;
}
2023-06-21 12:34:58 +02:00
public function setUser(User $user): void
{
$this->user = $user;
}
private function updateAccount(Account $account, array $data): Account
{
// update the account itself:
if (array_key_exists('name', $data)) {
$account->name = $data['name'];
}
if (array_key_exists('active', $data)) {
$account->active = $data['active'];
}
if (array_key_exists('iban', $data)) {
$account->iban = app('steam')->filterSpaces((string)$data['iban']);
}
// set liability, but account must already be a liability.
2023-12-20 19:35:52 +01:00
// $liabilityType = $data['liability_type'] ?? '';
2023-06-21 12:34:58 +02:00
if ($this->isLiability($account) && array_key_exists('liability_type', $data)) {
$type = $this->getAccountType($data['liability_type']);
$account->account_type_id = $type->id;
}
// set liability, alternative method used in v1 layout:
if ($this->isLiability($account) && array_key_exists('account_type_id', $data)) {
$type = AccountType::find((int)$data['account_type_id']);
if (null !== $type && in_array($type->type, config('firefly.valid_liabilities'), true)) {
$account->account_type_id = $type->id;
}
}
// update virtual balance (could be set to zero if empty string).
if (array_key_exists('virtual_balance', $data) && null !== $data['virtual_balance']) {
$account->virtual_balance = '' === trim($data['virtual_balance']) ? '0' : $data['virtual_balance'];
}
$account->save();
return $account;
}
private function isLiability(Account $account): bool
{
$type = $account->accountType->type;
return in_array($type, [AccountType::DEBT, AccountType::LOAN, AccountType::MORTGAGE], true);
}
private function getAccountType(string $type): AccountType
{
return AccountType::whereType(ucfirst($type))->first();
}
public function updateAccountOrder(Account $account, array $data): Account
{
// skip if no order info
if (!array_key_exists('order', $data) || $data['order'] === $account->order) {
app('log')->debug(sprintf('Account order will not be touched because its not set or already at %d.', $account->order));
return $account;
}
// skip if not of orderable type.
$type = $account->accountType->type;
if (!in_array($type, [AccountType::ASSET, AccountType::MORTGAGE, AccountType::LOAN, AccountType::DEBT], true)) {
app('log')->debug('Will not change order of this account.');
return $account;
}
// get account type ID's because a join and an update is hard:
$oldOrder = $account->order;
$newOrder = $data['order'];
app('log')->debug(sprintf('Order is set to be updated from %s to %s', $oldOrder, $newOrder));
$list = $this->getTypeIds([AccountType::MORTGAGE, AccountType::LOAN, AccountType::DEBT]);
if (AccountType::ASSET === $type) {
$list = $this->getTypeIds([AccountType::ASSET]);
}
if ($newOrder > $oldOrder) {
$this->user->accounts()->where('accounts.order', '<=', $newOrder)->where('accounts.order', '>', $oldOrder)
->where('accounts.id', '!=', $account->id)
->whereIn('accounts.account_type_id', $list)
->decrement('order')
;
$account->order = $newOrder;
app('log')->debug(sprintf('Order of account #%d ("%s") is now %d', $account->id, $account->name, $newOrder));
$account->save();
return $account;
}
$this->user->accounts()->where('accounts.order', '>=', $newOrder)->where('accounts.order', '<', $oldOrder)
->where('accounts.id', '!=', $account->id)
->whereIn('accounts.account_type_id', $list)
->increment('order')
;
$account->order = $newOrder;
app('log')->debug(sprintf('Order of account #%d ("%s") is now %d', $account->id, $account->name, $newOrder));
$account->save();
return $account;
}
2021-03-12 18:31:19 +01:00
private function getTypeIds(array $array): array
{
$return = [];
2023-12-20 19:35:52 +01:00
2021-03-12 18:31:19 +01:00
/** @var string $type */
foreach ($array as $type) {
/** @var AccountType $type */
$type = AccountType::whereType($type)->first();
2023-11-05 19:41:37 +01:00
$return[] = $type->id;
2021-03-12 18:31:19 +01:00
}
return $return;
}
private function updateLocation(Account $account, array $data): void
{
2021-03-12 18:31:19 +01:00
$updateLocation = $data['update_location'] ?? false;
// location must be updated?
if (true === $updateLocation) {
// if all set to NULL, delete
if (null === $data['latitude'] && null === $data['longitude'] && null === $data['zoom_level']) {
$account->locations()->delete();
}
// otherwise, update or create.
if (!(null === $data['latitude'] && null === $data['longitude'] && null === $data['zoom_level'])) {
$location = $this->accountRepository->getLocation($account);
2021-03-12 18:31:19 +01:00
if (null === $location) {
2022-10-30 14:24:37 +01:00
$location = new Location();
2021-03-12 18:31:19 +01:00
$location->locatable()->associate($account);
}
2021-03-12 18:31:19 +01:00
$location->latitude = $data['latitude'] ?? config('firefly.default_location.latitude');
$location->longitude = $data['longitude'] ?? config('firefly.default_location.longitude');
$location->zoom_level = $data['zoom_level'] ?? config('firefly.default_location.zoom_level');
$location->save();
}
}
}
2020-10-23 18:26:18 +02:00
/**
* @throws FireflyException
2020-10-23 18:26:18 +02:00
*/
private function updateOpeningBalance(Account $account, array $data): void
{
// has valid initial balance (IB) data?
$type = $account->accountType;
if (in_array($type->type, $this->canHaveOpeningBalance, true)) {
// check if is submitted as empty, that makes it valid:
2023-05-17 07:02:08 +02:00
if ($this->validOBData($data) && !$this->isEmptyOBData($data)) {
$openingBalance = $data['opening_balance'];
$openingBalanceDate = $data['opening_balance_date'];
2020-10-23 18:26:18 +02:00
// if liability, make sure the amount is positive for a credit, and negative for a debit.
2023-01-15 15:47:25 +01:00
if ($this->isLiability($account)) {
2023-02-22 18:14:14 +01:00
$openingBalance = 'credit' === $data['liability_direction'] ? app('steam')->positive($openingBalance) : app('steam')->negative(
$openingBalance
);
}
$this->updateOBGroupV2($account, $openingBalance, $openingBalanceDate);
}
if (!$this->validOBData($data) && $this->isEmptyOBData($data)) {
$this->deleteOBGroup($account);
}
}
2023-01-08 07:43:16 +01:00
// if cannot have an opening balance, delete it.
2023-01-15 15:47:25 +01:00
if (!in_array($type->type, $this->canHaveOpeningBalance, true)) {
2023-01-08 07:43:16 +01:00
$this->deleteOBGroup($account);
}
}
2020-10-23 18:26:18 +02:00
2023-02-22 18:14:14 +01:00
/**
* @throws FireflyException
*/
private function updatePreferences(Account $account): void
{
$account->refresh();
if (true === $account->active) {
return;
}
$preference = app('preferences')->getForUser($account->user, 'frontpageAccounts');
2023-02-22 18:14:14 +01:00
if (null === $preference) {
return;
}
$array = $preference->data;
2023-12-10 06:51:59 +01:00
if (!is_array($array)) {
2023-11-28 05:05:42 +01:00
$array = [$array];
}
2023-10-29 06:33:43 +01:00
app('log')->debug('Old array is: ', $array);
app('log')->debug(sprintf('Must remove : %d', $account->id));
2023-11-05 19:41:37 +01:00
$removeAccountId = $account->id;
2023-02-22 18:14:14 +01:00
$new = [];
foreach ($array as $value) {
if ((int)$value !== $removeAccountId) {
2023-10-29 06:33:43 +01:00
app('log')->debug(sprintf('Will include: %d', $value));
2023-02-22 18:14:14 +01:00
$new[] = (int)$value;
}
}
2023-10-29 06:33:43 +01:00
app('log')->debug('Final new array is', $new);
2023-02-22 18:14:14 +01:00
app('preferences')->setForUser($account->user, 'frontpageAccounts', $new);
}
2018-03-05 19:35:58 +01:00
}