mirror of
https://github.com/firefly-iii/firefly-iii.git
synced 2025-02-25 18:45:27 -06:00
Is now capable of updating transactions over the API.
This commit is contained in:
@@ -24,16 +24,17 @@ declare(strict_types=1);
|
||||
namespace FireflyIII\Services\Internal\Support;
|
||||
|
||||
use Exception;
|
||||
use FireflyIII\Factory\BillFactory;
|
||||
use FireflyIII\Factory\BudgetFactory;
|
||||
use FireflyIII\Factory\CategoryFactory;
|
||||
use FireflyIII\Exceptions\FireflyException;
|
||||
use FireflyIII\Factory\TagFactory;
|
||||
use FireflyIII\Factory\TransactionJournalMetaFactory;
|
||||
use FireflyIII\Models\Bill;
|
||||
use FireflyIII\Models\Budget;
|
||||
use FireflyIII\Models\Category;
|
||||
use FireflyIII\Models\Account;
|
||||
use FireflyIII\Models\AccountType;
|
||||
use FireflyIII\Models\Note;
|
||||
use FireflyIII\Models\TransactionJournal;
|
||||
use FireflyIII\Models\TransactionType;
|
||||
use FireflyIII\Repositories\Account\AccountRepositoryInterface;
|
||||
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
|
||||
use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
|
||||
use FireflyIII\Support\NullArrayObject;
|
||||
use Log;
|
||||
|
||||
/**
|
||||
@@ -42,26 +43,229 @@ use Log;
|
||||
*/
|
||||
trait JournalServiceTrait
|
||||
{
|
||||
/** @var AccountRepositoryInterface */
|
||||
private $accountRepository;
|
||||
/** @var BudgetRepositoryInterface */
|
||||
private $budgetRepository;
|
||||
/** @var CategoryRepositoryInterface */
|
||||
private $categoryRepository;
|
||||
/** @var TagFactory */
|
||||
private $tagFactory;
|
||||
|
||||
|
||||
/**
|
||||
* @param string|null $amount
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function getForeignAmount(?string $amount): ?string
|
||||
{
|
||||
$result = null;
|
||||
if (null === $amount) {
|
||||
Log::debug('No foreign amount info in array. Return NULL');
|
||||
|
||||
return null;
|
||||
}
|
||||
if ('' === $amount) {
|
||||
Log::debug('Foreign amount is empty string, return NULL.');
|
||||
|
||||
return null;
|
||||
}
|
||||
if (0 === bccomp('0', $amount)) {
|
||||
Log::debug('Foreign amount is 0.0, return NULL.');
|
||||
|
||||
return null;
|
||||
}
|
||||
Log::debug(sprintf('Foreign amount is %s', $amount));
|
||||
|
||||
return $amount;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $transactionType
|
||||
* @param string $direction
|
||||
* @param int|null $accountId
|
||||
* @param string|null $accountName
|
||||
*
|
||||
* @return Account
|
||||
* @throws FireflyException
|
||||
*/
|
||||
protected function getAccount(string $transactionType, string $direction, ?int $accountId, ?string $accountName): Account
|
||||
{
|
||||
// some debug logging:
|
||||
Log::debug(sprintf('Now in getAccount(%s, %d, %s)', $direction, $accountId, $accountName));
|
||||
|
||||
// final result:
|
||||
$result = null;
|
||||
|
||||
// expected type of source account, in order of preference
|
||||
/** @var array $array */
|
||||
$array = config('firefly.expected_source_types');
|
||||
$expectedTypes = $array[$direction];
|
||||
unset($array);
|
||||
|
||||
// and now try to find it, based on the type of transaction.
|
||||
$message = 'Based on the fact that the transaction is a %s, the %s account should be in: %s';
|
||||
Log::debug(sprintf($message, $transactionType, $direction, implode(', ', $expectedTypes[$transactionType])));
|
||||
|
||||
// first attempt, find by ID.
|
||||
if (null !== $accountId) {
|
||||
$search = $this->accountRepository->findNull($accountId);
|
||||
if (null !== $search && in_array($search->accountType->type, $expectedTypes[$transactionType], true)) {
|
||||
Log::debug(
|
||||
sprintf('Found "account_id" object for %s: #%d, "%s" of type %s', $direction, $search->id, $search->name, $search->accountType->type)
|
||||
);
|
||||
$result = $search;
|
||||
}
|
||||
}
|
||||
|
||||
// second attempt, find by name.
|
||||
if (null === $result && null !== $accountName) {
|
||||
Log::debug('Found nothing by account ID.');
|
||||
// find by preferred type.
|
||||
$source = $this->accountRepository->findByName($accountName, [$expectedTypes[$transactionType][0]]);
|
||||
// or any expected type.
|
||||
$source = $source ?? $this->accountRepository->findByName($accountName, $expectedTypes[$transactionType]);
|
||||
|
||||
if (null !== $source) {
|
||||
Log::debug(sprintf('Found "account_name" object for %s: #%d, %s', $direction, $source->id, $source->name));
|
||||
|
||||
$result = $source;
|
||||
}
|
||||
}
|
||||
|
||||
// return cash account.
|
||||
if (null === $result && null === $accountName
|
||||
&& in_array(AccountType::CASH, $expectedTypes[$transactionType], true)) {
|
||||
$result = $this->accountRepository->getCashAccount();
|
||||
}
|
||||
|
||||
// return new account.
|
||||
if (null === $result) {
|
||||
$accountName = $accountName ?? '(no name)';
|
||||
// final attempt, create it.
|
||||
$preferredType = $expectedTypes[$transactionType][0];
|
||||
if (AccountType::ASSET === $preferredType) {
|
||||
throw new FireflyException(sprintf('TransactionFactory: Cannot create asset account with ID #%d or name "%s".', $accountId, $accountName));
|
||||
}
|
||||
|
||||
$result = $this->accountRepository->store(
|
||||
[
|
||||
'account_type_id' => null,
|
||||
'accountType' => $preferredType,
|
||||
'name' => $accountName,
|
||||
'active' => true,
|
||||
'iban' => null,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $amount
|
||||
*
|
||||
* @return string
|
||||
* @throws FireflyException
|
||||
*/
|
||||
protected function getAmount(string $amount): string
|
||||
{
|
||||
if ('' === $amount) {
|
||||
throw new FireflyException(sprintf('The amount cannot be an empty string: "%s"', $amount));
|
||||
}
|
||||
if (0 === bccomp('0', $amount)) {
|
||||
throw new FireflyException(sprintf('The amount seems to be zero: "%s"', $amount));
|
||||
}
|
||||
|
||||
return $amount;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param TransactionJournal $journal
|
||||
* @param NullArrayObject $data
|
||||
*/
|
||||
protected function storeBudget(TransactionJournal $journal, NullArrayObject $data): void
|
||||
{
|
||||
if (TransactionType::WITHDRAWAL !== $journal->transactionType->type) {
|
||||
$journal->budgets()->sync([]);
|
||||
|
||||
return;
|
||||
}
|
||||
$budget = $this->budgetRepository->findBudget($data['budget_id'], $data['budget_name']);
|
||||
if (null !== $budget) {
|
||||
Log::debug(sprintf('Link budget #%d to journal #%d', $budget->id, $journal->id));
|
||||
$journal->budgets()->sync([$budget->id]);
|
||||
|
||||
return;
|
||||
}
|
||||
// if the budget is NULL, sync empty.
|
||||
$journal->budgets()->sync([]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param TransactionJournal $journal
|
||||
* @param NullArrayObject $data
|
||||
*/
|
||||
protected function storeCategory(TransactionJournal $journal, NullArrayObject $data): void
|
||||
{
|
||||
$category = $this->categoryRepository->findCategory($data['category_id'], $data['category_name']);
|
||||
if (null !== $category) {
|
||||
Log::debug(sprintf('Link category #%d to journal #%d', $category->id, $journal->id));
|
||||
$journal->categories()->sync([$category->id]);
|
||||
|
||||
return;
|
||||
}
|
||||
// if the category is NULL, sync empty.
|
||||
$journal->categories()->sync([]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param TransactionJournal $journal
|
||||
* @param string $notes
|
||||
*/
|
||||
protected function storeNotes(TransactionJournal $journal, ?string $notes): void
|
||||
{
|
||||
$notes = (string)$notes;
|
||||
$note = $journal->notes()->first();
|
||||
if ('' !== $notes) {
|
||||
if (null === $note) {
|
||||
$note = new Note;
|
||||
$note->noteable()->associate($journal);
|
||||
}
|
||||
$note->text = $notes;
|
||||
$note->save();
|
||||
Log::debug(sprintf('Stored notes for journal #%d', $journal->id));
|
||||
|
||||
return;
|
||||
}
|
||||
if ('' === $notes && null !== $note) {
|
||||
// try to delete existing notes.
|
||||
try {
|
||||
$note->delete();
|
||||
} catch (Exception $e) {
|
||||
Log::debug(sprintf('Could not delete journal notes: %s', $e->getMessage()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Link tags to journal.
|
||||
*
|
||||
* @param TransactionJournal $journal
|
||||
* @param array $data
|
||||
* @param array $tags
|
||||
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
|
||||
*/
|
||||
public function connectTags(TransactionJournal $journal, array $data): void
|
||||
protected function storeTags(TransactionJournal $journal, ?array $tags): void
|
||||
{
|
||||
/** @var TagFactory $factory */
|
||||
$factory = app(TagFactory::class);
|
||||
$factory->setUser($journal->user);
|
||||
$this->tagFactory->setUser($journal->user);
|
||||
$set = [];
|
||||
if (!\is_array($data['tags'])) {
|
||||
return; // @codeCoverageIgnore
|
||||
if (!is_array($tags)) {
|
||||
return;
|
||||
}
|
||||
foreach ($data['tags'] as $string) {
|
||||
foreach ($tags as $string) {
|
||||
if ('' !== $string) {
|
||||
$tag = $factory->findOrCreate($string);
|
||||
$tag = $this->tagFactory->findOrCreate($string);
|
||||
if (null !== $tag) {
|
||||
$set[] = $tag->id;
|
||||
}
|
||||
@@ -71,117 +275,147 @@ trait JournalServiceTrait
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param int|null $budgetId
|
||||
* @param null|string $budgetName
|
||||
*
|
||||
* @return Budget|null
|
||||
*/
|
||||
protected function findBudget(?int $budgetId, ?string $budgetName): ?Budget
|
||||
{
|
||||
/** @var BudgetFactory $factory */
|
||||
$factory = app(BudgetFactory::class);
|
||||
$factory->setUser($this->user);
|
||||
|
||||
return $factory->find($budgetId, $budgetName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int|null $categoryId
|
||||
* @param null|string $categoryName
|
||||
*
|
||||
* @return Category|null
|
||||
*/
|
||||
protected function findCategory(?int $categoryId, ?string $categoryName): ?Category
|
||||
{
|
||||
Log::debug(sprintf('Going to find or create category #%d, with name "%s"', $categoryId, $categoryName));
|
||||
/** @var CategoryFactory $factory */
|
||||
$factory = app(CategoryFactory::class);
|
||||
$factory->setUser($this->user);
|
||||
|
||||
return $factory->findOrCreate($categoryId, $categoryName);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param TransactionJournal $journal
|
||||
* @param Budget|null $budget
|
||||
*/
|
||||
protected function setBudget(TransactionJournal $journal, ?Budget $budget): void
|
||||
{
|
||||
if (null === $budget) {
|
||||
$journal->budgets()->sync([]);
|
||||
|
||||
return;
|
||||
}
|
||||
$journal->budgets()->sync([$budget->id]);
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param TransactionJournal $journal
|
||||
* @param Category|null $category
|
||||
*/
|
||||
protected function setCategory(TransactionJournal $journal, ?Category $category): void
|
||||
{
|
||||
if (null === $category) {
|
||||
$journal->categories()->sync([]);
|
||||
|
||||
return;
|
||||
}
|
||||
$journal->categories()->sync([$category->id]);
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param TransactionJournal $journal
|
||||
* @param array $data
|
||||
* @param string $field
|
||||
*/
|
||||
protected function storeMeta(TransactionJournal $journal, array $data, string $field): void
|
||||
{
|
||||
$set = [
|
||||
'journal' => $journal,
|
||||
'name' => $field,
|
||||
'data' => (string)($data[$field] ?? ''),
|
||||
];
|
||||
|
||||
Log::debug(sprintf('Going to store meta-field "%s", with value "%s".', $set['name'], $set['data']));
|
||||
|
||||
/** @var TransactionJournalMetaFactory $factory */
|
||||
$factory = app(TransactionJournalMetaFactory::class);
|
||||
$factory->updateOrCreate($set);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param TransactionJournal $journal
|
||||
* @param string $notes
|
||||
*/
|
||||
protected function storeNote(TransactionJournal $journal, ?string $notes): void
|
||||
{
|
||||
$notes = (string)$notes;
|
||||
if ('' !== $notes) {
|
||||
$note = $journal->notes()->first();
|
||||
if (null === $note) {
|
||||
$note = new Note;
|
||||
$note->noteable()->associate($journal);
|
||||
}
|
||||
$note->text = $notes;
|
||||
$note->save();
|
||||
|
||||
return;
|
||||
}
|
||||
$note = $journal->notes()->first();
|
||||
if (null !== $note) {
|
||||
try {
|
||||
$note->delete();
|
||||
} catch (Exception $e) {
|
||||
Log::debug(sprintf('Journal service trait could not delete note: %s', $e->getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
//
|
||||
// /**
|
||||
// * Link tags to journal.
|
||||
// *
|
||||
// * @param TransactionJournal $journal
|
||||
// * @param array $data
|
||||
// * @SuppressWarnings(PHPMD.CyclomaticComplexity)
|
||||
// */
|
||||
// public function connectTags(TransactionJournal $journal, array $data): void
|
||||
// {
|
||||
// /** @var TagFactory $factory */
|
||||
// $factory = app(TagFactory::class);
|
||||
// $factory->setUser($journal->user);
|
||||
// $set = [];
|
||||
// if (!\is_array($data['tags'])) {
|
||||
// return; // @codeCoverageIgnore
|
||||
// }
|
||||
// foreach ($data['tags'] as $string) {
|
||||
// if ('' !== $string) {
|
||||
// $tag = $factory->findOrCreate($string);
|
||||
// if (null !== $tag) {
|
||||
// $set[] = $tag->id;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// $journal->tags()->sync($set);
|
||||
// }
|
||||
//
|
||||
//
|
||||
// /**
|
||||
// * @param int|null $budgetId
|
||||
// * @param null|string $budgetName
|
||||
// *
|
||||
// * @return Budget|null
|
||||
// */
|
||||
// protected function findBudget(?int $budgetId, ?string $budgetName): ?Budget
|
||||
// {
|
||||
// /** @var BudgetFactory $factory */
|
||||
// $factory = app(BudgetFactory::class);
|
||||
// $factory->setUser($this->user);
|
||||
//
|
||||
// return $factory->find($budgetId, $budgetName);
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * @param int|null $categoryId
|
||||
// * @param null|string $categoryName
|
||||
// *
|
||||
// * @return Category|null
|
||||
// */
|
||||
// protected function findCategory(?int $categoryId, ?string $categoryName): ?Category
|
||||
// {
|
||||
// Log::debug(sprintf('Going to find or create category #%d, with name "%s"', $categoryId, $categoryName));
|
||||
// /** @var CategoryFactory $factory */
|
||||
// $factory = app(CategoryFactory::class);
|
||||
// $factory->setUser($this->user);
|
||||
//
|
||||
// return $factory->findOrCreate($categoryId, $categoryName);
|
||||
// }
|
||||
//
|
||||
//
|
||||
// /**
|
||||
// * @param TransactionJournal $journal
|
||||
// * @param Budget|null $budget
|
||||
// */
|
||||
// protected function setBudget(TransactionJournal $journal, ?Budget $budget): void
|
||||
// {
|
||||
// if (null === $budget) {
|
||||
// $journal->budgets()->sync([]);
|
||||
//
|
||||
// return;
|
||||
// }
|
||||
// $journal->budgets()->sync([$budget->id]);
|
||||
//
|
||||
// }
|
||||
//
|
||||
//
|
||||
// /**
|
||||
// * @param TransactionJournal $journal
|
||||
// * @param Category|null $category
|
||||
// */
|
||||
// protected function setCategory(TransactionJournal $journal, ?Category $category): void
|
||||
// {
|
||||
// if (null === $category) {
|
||||
// $journal->categories()->sync([]);
|
||||
//
|
||||
// return;
|
||||
// }
|
||||
// $journal->categories()->sync([$category->id]);
|
||||
//
|
||||
// }
|
||||
//
|
||||
//
|
||||
// /**
|
||||
// * @param TransactionJournal $journal
|
||||
// * @param array $data
|
||||
// * @param string $field
|
||||
// */
|
||||
// protected function storeMeta(TransactionJournal $journal, array $data, string $field): void
|
||||
// {
|
||||
// $set = [
|
||||
// 'journal' => $journal,
|
||||
// 'name' => $field,
|
||||
// 'data' => (string)($data[$field] ?? ''),
|
||||
// ];
|
||||
//
|
||||
// Log::debug(sprintf('Going to store meta-field "%s", with value "%s".', $set['name'], $set['data']));
|
||||
//
|
||||
// /** @var TransactionJournalMetaFactory $factory */
|
||||
// $factory = app(TransactionJournalMetaFactory::class);
|
||||
// $factory->updateOrCreate($set);
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * @param TransactionJournal $journal
|
||||
// * @param string $notes
|
||||
// */
|
||||
// protected function storeNote(TransactionJournal $journal, ?string $notes): void
|
||||
// {
|
||||
// $notes = (string)$notes;
|
||||
// if ('' !== $notes) {
|
||||
// $note = $journal->notes()->first();
|
||||
// if (null === $note) {
|
||||
// $note = new Note;
|
||||
// $note->noteable()->associate($journal);
|
||||
// }
|
||||
// $note->text = $notes;
|
||||
// $note->save();
|
||||
//
|
||||
// return;
|
||||
// }
|
||||
// $note = $journal->notes()->first();
|
||||
// if (null !== $note) {
|
||||
// try {
|
||||
// $note->delete();
|
||||
// } catch (Exception $e) {
|
||||
// Log::debug(sprintf('Journal service trait could not delete note: %s', $e->getMessage()));
|
||||
// }
|
||||
// }
|
||||
//
|
||||
//
|
||||
// }
|
||||
}
|
||||
|
||||
84
app/Services/Internal/Update/GroupUpdateService.php
Normal file
84
app/Services/Internal/Update/GroupUpdateService.php
Normal file
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
/**
|
||||
* GroupUpdateService.php
|
||||
* Copyright (c) 2019 thegrumpydictator@gmail.com
|
||||
*
|
||||
* This file is part of Firefly III.
|
||||
*
|
||||
* Firefly III is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* Firefly III is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with Firefly III. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace FireflyIII\Services\Internal\Update;
|
||||
|
||||
use FireflyIII\Models\TransactionGroup;
|
||||
use FireflyIII\Models\TransactionJournal;
|
||||
use Log;
|
||||
|
||||
/**
|
||||
* Class GroupUpdateService
|
||||
*/
|
||||
class GroupUpdateService
|
||||
{
|
||||
/**
|
||||
* Update a transaction group.
|
||||
*
|
||||
* @param TransactionGroup $transactionGroup
|
||||
* @param array $data
|
||||
*
|
||||
* @return TransactionGroup
|
||||
*/
|
||||
public function update(TransactionGroup $transactionGroup, array $data): TransactionGroup
|
||||
{
|
||||
Log::debug('Now in group update service');
|
||||
$transactions = $data['transactions'] ?? [];
|
||||
// update group name.
|
||||
if (array_key_exists('group_title', $data)) {
|
||||
Log::debug(sprintf('Update transaction group #%d title.', $transactionGroup->id));
|
||||
$transactionGroup->title = $data['group_title'];
|
||||
$transactionGroup->save();
|
||||
}
|
||||
if (1 === count($transactions) && 1 === $transactionGroup->transactionJournals()->count()) {
|
||||
/** @var TransactionJournal $first */
|
||||
$first = $transactionGroup->transactionJournals()->first();
|
||||
Log::debug(sprintf('Will now update journal #%d (only journal in group #%d)', $first->id, $transactionGroup->id));
|
||||
$this->updateTransactionJournal($transactionGroup, $first, reset($transactions));
|
||||
$transactionGroup->refresh();
|
||||
|
||||
return $transactionGroup;
|
||||
}
|
||||
die('cannot update split');
|
||||
|
||||
app('preferences')->mark();
|
||||
}
|
||||
|
||||
/**
|
||||
* Update single journal.
|
||||
*
|
||||
* @param TransactionGroup $transactionGroup
|
||||
* @param TransactionJournal $journal
|
||||
* @param array $data
|
||||
*/
|
||||
private function updateTransactionJournal(TransactionGroup $transactionGroup, TransactionJournal $journal, array $data): void
|
||||
{
|
||||
/** @var JournalUpdateService $updateService */
|
||||
$updateService = app(JournalUpdateService::class);
|
||||
$updateService->setTransactionGroup($transactionGroup);
|
||||
$updateService->setTransactionJournal($journal);
|
||||
$updateService->setData($data);
|
||||
$updateService->update();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -23,12 +23,25 @@ declare(strict_types=1);
|
||||
|
||||
namespace FireflyIII\Services\Internal\Update;
|
||||
|
||||
use FireflyIII\Factory\TransactionFactory;
|
||||
use Carbon\Carbon;
|
||||
use Exception;
|
||||
use FireflyIII\Exceptions\FireflyException;
|
||||
use FireflyIII\Factory\TagFactory;
|
||||
use FireflyIII\Factory\TransactionJournalMetaFactory;
|
||||
use FireflyIII\Factory\TransactionTypeFactory;
|
||||
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 FireflyIII\Repositories\Bill\BillRepositoryInterface;
|
||||
use FireflyIII\Repositories\Budget\BudgetRepositoryInterface;
|
||||
use FireflyIII\Repositories\Category\CategoryRepositoryInterface;
|
||||
use FireflyIII\Repositories\Currency\CurrencyRepositoryInterface;
|
||||
use FireflyIII\Services\Internal\Support\JournalServiceTrait;
|
||||
use Illuminate\Support\Collection;
|
||||
use FireflyIII\Support\NullArrayObject;
|
||||
use FireflyIII\Validation\AccountValidator;
|
||||
use Log;
|
||||
|
||||
/**
|
||||
@@ -40,163 +53,618 @@ class JournalUpdateService
|
||||
{
|
||||
use JournalServiceTrait;
|
||||
|
||||
/** @var BillRepositoryInterface */
|
||||
private $billRepository;
|
||||
/** @var CurrencyRepositoryInterface */
|
||||
private $currencyRepository;
|
||||
/** @var array The data to update the journal with. */
|
||||
private $data;
|
||||
/** @var Account The destination account. */
|
||||
private $destinationAccount;
|
||||
/** @var Transaction */
|
||||
private $destinationTransaction;
|
||||
/** @var array All meta values that are dates. */
|
||||
private $metaDate;
|
||||
/** @var array All meta values that are strings. */
|
||||
private $metaString;
|
||||
/** @var Account Source account of the journal */
|
||||
private $sourceAccount;
|
||||
/** @var Transaction Source transaction of the journal. */
|
||||
private $sourceTransaction;
|
||||
/** @var TransactionGroup The parent group. */
|
||||
private $transactionGroup;
|
||||
/** @var TransactionJournal The journal to update. */
|
||||
private $transactionJournal;
|
||||
/** @var Account If new account info is submitted, this array will hold the valid destination. */
|
||||
private $validDestination;
|
||||
/** @var Account If new account info is submitted, this array will hold the valid source. */
|
||||
private $validSource;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
* JournalUpdateService constructor.
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
if ('testing' === config('app.env')) {
|
||||
Log::warning(sprintf('%s should not be instantiated in the TEST environment!', \get_class($this)));
|
||||
$this->billRepository = app(BillRepositoryInterface::class);
|
||||
$this->categoryRepository = app(CategoryRepositoryInterface::class);
|
||||
$this->budgetRepository = app(BudgetRepositoryInterface::class);
|
||||
$this->tagFactory = app(TagFactory::class);
|
||||
$this->accountRepository = app(AccountRepositoryInterface::class);
|
||||
$this->currencyRepository = app(CurrencyRepositoryInterface::class);
|
||||
$this->metaString = ['sepa_cc', 'sepa_ct_op', 'sepa_ct_id', 'sepa_db', 'sepa_country', 'sepa_ep', 'sepa_ci', 'sepa_batch_id', 'recurrence_id',
|
||||
'internal_reference', 'bunq_payment_id', 'external_id',];
|
||||
$this->metaDate = ['interest_date', 'book_date', 'process_date', 'due_date', 'payment_date', 'invoice_date',];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
*/
|
||||
public function setData(array $data): void
|
||||
{
|
||||
$this->data = $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param TransactionGroup $transactionGroup
|
||||
*/
|
||||
public function setTransactionGroup(TransactionGroup $transactionGroup): void
|
||||
{
|
||||
$this->transactionGroup = $transactionGroup;
|
||||
$this->billRepository->setUser($transactionGroup->user);
|
||||
$this->categoryRepository->setUser($transactionGroup->user);
|
||||
$this->budgetRepository->setUser($transactionGroup->user);
|
||||
$this->tagFactory->setUser($transactionGroup->user);
|
||||
$this->accountRepository->setUser($transactionGroup->user);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param TransactionJournal $transactionJournal
|
||||
*/
|
||||
public function setTransactionJournal(TransactionJournal $transactionJournal): void
|
||||
{
|
||||
$this->transactionJournal = $transactionJournal;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public function update(): void
|
||||
{
|
||||
Log::debug(sprintf('Now in JournalUpdateService for journal #%d.', $this->transactionJournal->id));
|
||||
|
||||
// can we update account data using the new type?
|
||||
if ($this->hasValidAccounts()) {
|
||||
Log::info('-- account info is valid, now update.');
|
||||
// update accounts:
|
||||
$this->updateAccounts();
|
||||
|
||||
// then also update transaction journal type ID:
|
||||
$this->updateType();
|
||||
$this->transactionJournal->refresh();
|
||||
}
|
||||
|
||||
// find and update bill, if possible.
|
||||
$this->updateBill();
|
||||
|
||||
// update journal fields.
|
||||
$this->updateField('description');
|
||||
$this->updateField('date');
|
||||
$this->updateField('order');
|
||||
|
||||
$this->transactionJournal->save();
|
||||
$this->transactionJournal->refresh();
|
||||
|
||||
// update category
|
||||
if ($this->hasFields(['category_id', 'category_name'])) {
|
||||
Log::debug('Will update category.');
|
||||
|
||||
$this->storeCategory($this->transactionJournal, new NullArrayObject($this->data));
|
||||
}
|
||||
// update budget
|
||||
if ($this->hasFields(['budget_id', 'budget_name'])) {
|
||||
Log::debug('Will update budget.');
|
||||
$this->storeBudget($this->transactionJournal, new NullArrayObject($this->data));
|
||||
}
|
||||
// update tags
|
||||
if ($this->hasFields(['tags'])) {
|
||||
Log::debug('Will update tags.');
|
||||
$tags = $this->data['tags'] ?? null;
|
||||
$this->storeTags($this->transactionJournal, $tags);
|
||||
}
|
||||
|
||||
// update notes.
|
||||
if ($this->hasFields(['notes'])) {
|
||||
$notes = '' === (string)$this->data['notes'] ? null : $this->data['notes'];
|
||||
$this->storeNotes($this->transactionJournal, $notes);
|
||||
}
|
||||
// update meta fields.
|
||||
// first string
|
||||
if ($this->hasFields($this->metaString)) {
|
||||
Log::debug('Meta string fields are present.');
|
||||
$this->updateMetaFields();
|
||||
}
|
||||
|
||||
// then date fields.
|
||||
if ($this->hasFields($this->metaDate)) {
|
||||
Log::debug('Meta date fields are present.');
|
||||
$this->updateMetaDateFields();
|
||||
}
|
||||
|
||||
|
||||
// update transactions.
|
||||
if ($this->hasFields(['currency_id', 'currency_code'])) {
|
||||
$this->updateCurrency();
|
||||
}
|
||||
if ($this->hasFields(['amount'])) {
|
||||
$this->updateAmount();
|
||||
}
|
||||
|
||||
// amount, foreign currency.
|
||||
if ($this->hasFields(['foreign_currency_id', 'foreign_currency_code', 'foreign_amount'])) {
|
||||
$this->updateForeignAmount();
|
||||
}
|
||||
|
||||
// TODO update hash
|
||||
|
||||
app('preferences')->mark();
|
||||
|
||||
$this->transactionJournal->refresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get destination transaction.
|
||||
*
|
||||
* @return Transaction
|
||||
*/
|
||||
private function getDestinationTransaction(): Transaction
|
||||
{
|
||||
if (null === $this->destinationTransaction) {
|
||||
$this->destinationTransaction = $this->transactionJournal->transactions()->where('amount', '>', 0)->first();
|
||||
}
|
||||
|
||||
return $this->destinationTransaction;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method returns the current or expected type of the journal (in case of a change) based on the data in the array.
|
||||
*
|
||||
* If the array contains key 'type' and the value is correct, this is returned. Otherwise, the original type is returned.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function getExpectedType(): string
|
||||
{
|
||||
Log::debug('Now in getExpectedType()');
|
||||
if ($this->hasFields(['type'])) {
|
||||
return ucfirst('opening-balance' === $this->data['type'] ? 'opening balance' : $this->data['type']);
|
||||
}
|
||||
|
||||
return $this->transactionJournal->transactionType->type;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Account
|
||||
*/
|
||||
private function getOriginalDestinationAccount(): Account
|
||||
{
|
||||
if (null === $this->destinationAccount) {
|
||||
$destination = $this->getSourceTransaction();
|
||||
$this->destinationAccount = $destination->account;
|
||||
}
|
||||
|
||||
return $this->destinationAccount;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Account
|
||||
*/
|
||||
private function getOriginalSourceAccount(): Account
|
||||
{
|
||||
if (null === $this->sourceAccount) {
|
||||
$source = $this->getSourceTransaction();
|
||||
$this->sourceAccount = $source->account;
|
||||
}
|
||||
|
||||
return $this->sourceAccount;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Transaction
|
||||
*/
|
||||
private function getSourceTransaction(): Transaction
|
||||
{
|
||||
if (null === $this->sourceTransaction) {
|
||||
$this->sourceTransaction = $this->transactionJournal->transactions()->with(['account'])->where('amount', '<', 0)->first();
|
||||
}
|
||||
|
||||
return $this->sourceTransaction;
|
||||
}
|
||||
|
||||
/**
|
||||
* Does a validation and returns the destination account. This method will break if the dest isn't really valid.
|
||||
*
|
||||
* @return Account
|
||||
*/
|
||||
private function getValidDestinationAccount(): Account
|
||||
{
|
||||
Log::debug('Now in getValidDestinationAccount().');
|
||||
|
||||
if (!$this->hasFields(['destination_id', 'destination_name'])) {
|
||||
return $this->getOriginalDestinationAccount();
|
||||
}
|
||||
|
||||
$destId = $this->data['destination_id'] ?? null;
|
||||
$destName = $this->data['destination_name'] ?? null;
|
||||
|
||||
// make new account validator.
|
||||
$expectedType = $this->getExpectedType();
|
||||
Log::debug(sprintf('Expected type (new or unchanged) is %s', $expectedType));
|
||||
try {
|
||||
$result = $this->getAccount($expectedType, 'destination', $destId, $destName);
|
||||
} catch (FireflyException $e) {
|
||||
Log::error(sprintf('getValidDestinationAccount() threw unexpected error: %s', $e->getMessage()));
|
||||
$result = $this->getOriginalDestinationAccount();
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Does a validation and returns the source account. This method will break if the source isn't really valid.
|
||||
*
|
||||
* @return Account
|
||||
*/
|
||||
private function getValidSourceAccount(): Account
|
||||
{
|
||||
Log::debug('Now in getValidSourceAccount().');
|
||||
$sourceId = $this->data['source_id'] ?? null;
|
||||
$sourceName = $this->data['source_name'] ?? null;
|
||||
|
||||
if (!$this->hasFields(['source_id', 'source_name'])) {
|
||||
return $this->getOriginalSourceAccount();
|
||||
}
|
||||
|
||||
$expectedType = $this->getExpectedType();
|
||||
try {
|
||||
$result = $this->getAccount($expectedType, 'source', $sourceId, $sourceName);
|
||||
} catch (FireflyException $e) {
|
||||
Log::error(sprintf('Cant get the valid source account: %s', $e->getMessage()));
|
||||
|
||||
$result = $this->getOriginalSourceAccount();
|
||||
}
|
||||
|
||||
Log::debug(sprintf('getValidSourceAccount() will return #%d ("%s")', $result->id, $result->name));
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $fields
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function hasFields(array $fields): bool
|
||||
{
|
||||
foreach ($fields as $field) {
|
||||
if (array_key_exists($field, $this->data)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
private function hasValidAccounts(): bool
|
||||
{
|
||||
return $this->hasValidSourceAccount() && $this->hasValidDestinationAccount();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
private function hasValidDestinationAccount(): bool
|
||||
{
|
||||
Log::debug('Now in hasValidDestinationAccount().');
|
||||
$destId = $this->data['destination_id'] ?? null;
|
||||
$destName = $this->data['destination_name'] ?? null;
|
||||
|
||||
if (!$this->hasFields(['destination_id', 'destination_name'])) {
|
||||
$destination = $this->getOriginalDestinationAccount();
|
||||
$destId = $destination->id;
|
||||
$destName = $destination->name;
|
||||
}
|
||||
|
||||
// make new account validator.
|
||||
$expectedType = $this->getExpectedType();
|
||||
Log::debug(sprintf('Expected type (new or unchanged) is %s', $expectedType));
|
||||
|
||||
// make a new validator.
|
||||
/** @var AccountValidator $validator */
|
||||
$validator = app(AccountValidator::class);
|
||||
$validator->setTransactionType($expectedType);
|
||||
$validator->setUser($this->transactionJournal->user);
|
||||
$validator->source = $this->getValidSourceAccount();
|
||||
|
||||
|
||||
$result = $validator->validateDestination($destId, $destName);
|
||||
Log::debug(sprintf('hasValidDestinationAccount(%d, "%s") will return %s', $destId, $destName, var_export($result, true)));
|
||||
|
||||
// validate submitted info:
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
private function hasValidSourceAccount(): bool
|
||||
{
|
||||
Log::debug('Now in hasValidSourceAccount().');
|
||||
$sourceId = $this->data['source_id'] ?? null;
|
||||
$sourceName = $this->data['source_name'] ?? null;
|
||||
|
||||
if (!$this->hasFields(['source_id', 'source_name'])) {
|
||||
$sourceAccount = $this->getOriginalSourceAccount();
|
||||
$sourceId = $sourceAccount->id;
|
||||
$sourceName = $sourceAccount->name;
|
||||
}
|
||||
|
||||
// make new account validator.
|
||||
$expectedType = $this->getExpectedType();
|
||||
Log::debug(sprintf('Expected type (new or unchanged) is %s', $expectedType));
|
||||
|
||||
// make a new validator.
|
||||
/** @var AccountValidator $validator */
|
||||
$validator = app(AccountValidator::class);
|
||||
$validator->setTransactionType($expectedType);
|
||||
$validator->setUser($this->transactionJournal->user);
|
||||
|
||||
$result = $validator->validateSource($sourceId, $sourceName);
|
||||
Log::debug(sprintf('hasValidSourceAccount(%d, "%s") will return %s', $sourceId, $sourceName, var_export($result, true)));
|
||||
|
||||
// validate submitted info:
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Will update the source and destination accounts of this journal. Assumes they are valid.
|
||||
*/
|
||||
private function updateAccounts(): void
|
||||
{
|
||||
$source = $this->getValidSourceAccount();
|
||||
$destination = $this->getValidDestinationAccount();
|
||||
|
||||
// cowardly refuse to update if both accounts are the same.
|
||||
if ($source->id === $destination->id) {
|
||||
Log::error(sprintf('Source + dest accounts are equal (%d, "%s")', $source->id, $source->name));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$sourceTransaction = $this->getSourceTransaction();
|
||||
$sourceTransaction->account()->associate($source);
|
||||
$sourceTransaction->save();
|
||||
|
||||
$destinationTransaction = $this->getDestinationTransaction();
|
||||
$destinationTransaction->account()->associate($destination);
|
||||
$destinationTransaction->save();
|
||||
|
||||
Log::debug(sprintf('Will set source to #%d ("%s")', $source->id, $source->name));
|
||||
Log::debug(sprintf('Will set dest to #%d ("%s")', $destination->id, $destination->name));
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private function updateAmount(): void
|
||||
{
|
||||
$value = $this->data['amount'] ?? '';
|
||||
try {
|
||||
$amount = $this->getAmount($value);
|
||||
} catch (FireflyException $e) {
|
||||
Log::debug(sprintf('getAmount("%s") returns error: %s', $value, $e->getMessage()));
|
||||
|
||||
return;
|
||||
}
|
||||
Log::debug(sprintf('Updated amount to %s', $amount));
|
||||
$sourceTransaction = $this->getSourceTransaction();
|
||||
$sourceTransaction->amount = app('steam')->negative($value);
|
||||
$sourceTransaction->save();
|
||||
|
||||
$destinationTransaction = $this->getDestinationTransaction();
|
||||
$destinationTransaction->amount = app('steam')->positive($value);
|
||||
$destinationTransaction->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Update journal bill information.
|
||||
*/
|
||||
private function updateBill(): void
|
||||
{
|
||||
$type = $this->transactionJournal->transactionType->type;
|
||||
if ((
|
||||
array_key_exists('bill_id', $this->data)
|
||||
|| array_key_exists('bill_name', $this->data)
|
||||
)
|
||||
&& TransactionType::WITHDRAWAL === $type
|
||||
) {
|
||||
$billId = (int)($this->data['bill_id'] ?? 0);
|
||||
$billName = (string)($this->data['bill_name'] ?? '');
|
||||
$bill = $this->billRepository->findBill($billId, $billName);
|
||||
$this->transactionJournal->bill_id = null === $bill ? null : $bill->id;
|
||||
Log::debug('Updated bill ID');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private function updateCurrency(): void
|
||||
{
|
||||
$currencyId = $this->data['currency_id'] ?? null;
|
||||
$currencyCode = $this->data['currency_code'] ?? null;
|
||||
$currency = $this->currencyRepository->findCurrency($currencyId, $currencyCode);
|
||||
if (null !== $currency) {
|
||||
// update currency everywhere.
|
||||
$this->transactionJournal->transaction_currency_id = $currency->id;
|
||||
$this->transactionJournal->save();
|
||||
|
||||
$source = $this->getSourceTransaction();
|
||||
$source->transaction_currency_id = $currency->id;
|
||||
$source->save();
|
||||
|
||||
$dest = $this->getDestinationTransaction();
|
||||
$dest->transaction_currency_id = $currency->id;
|
||||
$dest->save();
|
||||
Log::debug(sprintf('Updated currency to #%d (%s)', $currency->id, $currency->code));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update journal generic field. Cannot be set to NULL.
|
||||
*
|
||||
* @param $fieldName
|
||||
*/
|
||||
private function updateField($fieldName): void
|
||||
{
|
||||
if (array_key_exists($fieldName, $this->data) && '' !== (string)$this->data[$fieldName]) {
|
||||
$this->transactionJournal->$fieldName = $this->data[$fieldName];
|
||||
Log::debug(sprintf('Updated %s', $fieldName));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param TransactionJournal $journal
|
||||
* @param array $data
|
||||
*
|
||||
* @return TransactionJournal
|
||||
* @throws \FireflyIII\Exceptions\FireflyException
|
||||
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
|
||||
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
|
||||
*/
|
||||
public function update(TransactionJournal $journal, array $data): TransactionJournal
|
||||
private function updateForeignAmount(): void
|
||||
{
|
||||
// update journal:
|
||||
$journal->description = $data['description'];
|
||||
$journal->date = $data['date'];
|
||||
$journal->save();
|
||||
$amount = $this->data['foreign_amount'] ?? null;
|
||||
$foreignAmount = $this->getForeignAmount($amount);
|
||||
$source = $this->getSourceTransaction();
|
||||
$dest = $this->getDestinationTransaction();
|
||||
$foreignCurrency = $source->foreignCurrency;
|
||||
|
||||
// update transactions:
|
||||
/** @var TransactionUpdateService $service */
|
||||
$service = app(TransactionUpdateService::class);
|
||||
$service->setUser($journal->user);
|
||||
// find currency in data array
|
||||
$newForeignId = $this->data['foreign_currency_id'] ?? null;
|
||||
$newForeignCode = $this->data['foreign_currency_code'] ?? null;
|
||||
$foreignCurrency = $this->currencyRepository->findCurrencyNull($newForeignId, $newForeignCode) ?? $foreignCurrency;
|
||||
|
||||
// create transactions:
|
||||
/** @var TransactionFactory $factory */
|
||||
$factory = app(TransactionFactory::class);
|
||||
$factory->setUser($journal->user);
|
||||
// not the same as normal currency
|
||||
if (null !== $foreignCurrency && $foreignCurrency->id === $this->transactionJournal->transaction_currency_id) {
|
||||
Log::error(sprintf('Foreign currency is equal to normal currency (%s)', $foreignCurrency->code));
|
||||
|
||||
Log::debug(sprintf('Found %d rows in array (should result in %d transactions', \count($data['transactions']), \count($data['transactions']) * 2));
|
||||
|
||||
/**
|
||||
* @var int $identifier
|
||||
* @var array $trData
|
||||
*/
|
||||
foreach ($data['transactions'] as $identifier => $trData) {
|
||||
// exists transaction(s) with this identifier? update!
|
||||
/** @var Collection $existing */
|
||||
$existing = $journal->transactions()->where('identifier', $identifier)->get();
|
||||
Log::debug(sprintf('Found %d transactions with identifier %d', $existing->count(), $identifier));
|
||||
if ($existing->count() > 0) {
|
||||
$existing->each(
|
||||
function (Transaction $transaction) use ($service, $trData) {
|
||||
Log::debug(sprintf('Update transaction #%d (identifier %d)', $transaction->id, $trData['identifier']));
|
||||
$service->update($transaction, $trData);
|
||||
}
|
||||
);
|
||||
continue;
|
||||
}
|
||||
Log::debug('Found none, so create a pair.');
|
||||
// otherwise, create!
|
||||
$factory->createPair($journal, $trData);
|
||||
return;
|
||||
}
|
||||
// could be that journal has more transactions than submitted (remove split)
|
||||
$transactions = $journal->transactions()->where('amount', '>', 0)->get();
|
||||
Log::debug(sprintf('Journal #%d has %d transactions', $journal->id, $transactions->count()));
|
||||
/** @var Transaction $transaction */
|
||||
foreach ($transactions as $transaction) {
|
||||
Log::debug(sprintf('Now at transaction %d with identifier %d', $transaction->id, $transaction->identifier));
|
||||
if (!isset($data['transactions'][$transaction->identifier])) {
|
||||
Log::debug('No such entry in array, delete this set of transactions.');
|
||||
$journal->transactions()->where('identifier', $transaction->identifier)->delete();
|
||||
}
|
||||
|
||||
// add foreign currency info to source and destination if possible.
|
||||
if (null !== $foreignCurrency && null !== $foreignAmount) {
|
||||
$source->foreign_currency_id = $foreignCurrency->id;
|
||||
$source->foreign_amount = app('steam')->negative($foreignAmount);
|
||||
$source->save();
|
||||
|
||||
|
||||
$dest->foreign_currency_id = $foreignCurrency->id;
|
||||
$dest->foreign_amount = app('steam')->positive($foreignAmount);
|
||||
$dest->save();
|
||||
|
||||
Log::debug(sprintf('Update foreign info to %s (#%d) %s', $foreignCurrency->code, $foreignCurrency->id, $foreignAmount));
|
||||
|
||||
return;
|
||||
}
|
||||
Log::debug(sprintf('New count is %d, transactions array held %d items', $journal->transactions()->count(), \count($data['transactions'])));
|
||||
if ('0' === $amount) {
|
||||
$source->foreign_currency_id = null;
|
||||
$source->foreign_amount = null;
|
||||
$source->save();
|
||||
|
||||
// connect bill:
|
||||
$this->connectBill($journal, $data);
|
||||
|
||||
// connect tags:
|
||||
$this->connectTags($journal, $data);
|
||||
|
||||
// remove category from journal:
|
||||
$journal->categories()->sync([]);
|
||||
|
||||
// remove budgets from journal:
|
||||
$journal->budgets()->sync([]);
|
||||
|
||||
// update or create custom fields:
|
||||
// store date meta fields (if present):
|
||||
$this->storeMeta($journal, $data, 'interest_date');
|
||||
$this->storeMeta($journal, $data, 'book_date');
|
||||
$this->storeMeta($journal, $data, 'process_date');
|
||||
$this->storeMeta($journal, $data, 'due_date');
|
||||
$this->storeMeta($journal, $data, 'payment_date');
|
||||
$this->storeMeta($journal, $data, 'invoice_date');
|
||||
$this->storeMeta($journal, $data, 'internal_reference');
|
||||
|
||||
// store note:
|
||||
$this->storeNote($journal, $data['notes']);
|
||||
|
||||
|
||||
return $journal;
|
||||
$dest->foreign_currency_id = null;
|
||||
$dest->foreign_amount = null;
|
||||
$dest->save();
|
||||
Log::debug(sprintf('Foreign amount is "%s" so remove foreign amount info.', $amount));
|
||||
}
|
||||
Log::info('Not enough info to update foreign currency info.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Update budget for a journal.
|
||||
*
|
||||
* @param TransactionJournal $journal
|
||||
* @param int $budgetId
|
||||
*
|
||||
* @return TransactionJournal
|
||||
*/
|
||||
public function updateBudget(TransactionJournal $journal, int $budgetId): TransactionJournal
|
||||
private function updateMetaDateFields(): void
|
||||
{
|
||||
/** @var TransactionUpdateService $service */
|
||||
$service = app(TransactionUpdateService::class);
|
||||
$service->setUser($journal->user);
|
||||
if (TransactionType::WITHDRAWAL === $journal->transactionType->type) {
|
||||
/** @var Transaction $transaction */
|
||||
foreach ($journal->transactions as $transaction) {
|
||||
$service->updateBudget($transaction, $budgetId);
|
||||
/** @var TransactionJournalMetaFactory $factory */
|
||||
$factory = app(TransactionJournalMetaFactory::class);
|
||||
|
||||
foreach ($this->metaDate as $field) {
|
||||
if ($this->hasFields([$field])) {
|
||||
try {
|
||||
$value = '' === $this->data[$field] ? null : new Carbon($this->data[$field]);
|
||||
} catch (Exception $e) {
|
||||
Log::debug(sprintf('%s is not a valid date value: %s', $this->data[$field], $e->getMessage()));
|
||||
|
||||
return;
|
||||
}
|
||||
Log::debug(sprintf('Field "%s" is present ("%s"), try to update it.', $field, $value));
|
||||
$set = [
|
||||
'journal' => $this->transactionJournal,
|
||||
'name' => $field,
|
||||
'data' => $value,
|
||||
];
|
||||
$factory->updateOrCreate($set);
|
||||
}
|
||||
|
||||
return $journal;
|
||||
}
|
||||
// clear budget.
|
||||
/** @var Transaction $transaction */
|
||||
foreach ($journal->transactions as $transaction) {
|
||||
$transaction->budgets()->sync([]);
|
||||
}
|
||||
// remove budgets from journal:
|
||||
$journal->budgets()->sync([]);
|
||||
|
||||
return $journal;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update category for a journal.
|
||||
*
|
||||
* @param TransactionJournal $journal
|
||||
* @param string $category
|
||||
*
|
||||
* @return TransactionJournal
|
||||
*/
|
||||
public function updateCategory(TransactionJournal $journal, string $category): TransactionJournal
|
||||
private function updateMetaFields(): void
|
||||
{
|
||||
/** @var TransactionUpdateService $service */
|
||||
$service = app(TransactionUpdateService::class);
|
||||
$service->setUser($journal->user);
|
||||
/** @var TransactionJournalMetaFactory $factory */
|
||||
$factory = app(TransactionJournalMetaFactory::class);
|
||||
|
||||
/** @var Transaction $transaction */
|
||||
foreach ($journal->transactions as $transaction) {
|
||||
$service->updateCategory($transaction, $category);
|
||||
foreach ($this->metaString as $field) {
|
||||
if ($this->hasFields([$field])) {
|
||||
$value = '' === $this->data[$field] ? null : $this->data[$field];
|
||||
Log::debug(sprintf('Field "%s" is present ("%s"), try to update it.', $field, $value));
|
||||
$set = [
|
||||
'journal' => $this->transactionJournal,
|
||||
'name' => $field,
|
||||
'data' => $value,
|
||||
];
|
||||
$factory->updateOrCreate($set);
|
||||
}
|
||||
}
|
||||
// make journal empty:
|
||||
$journal->categories()->sync([]);
|
||||
|
||||
return $journal;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates journal transaction type.
|
||||
*/
|
||||
private function updateType(): void
|
||||
{
|
||||
Log::debug('Now in updateType()');
|
||||
if ($this->hasFields(['type'])) {
|
||||
$type = 'opening-balance' === $this->data['type'] ? 'opening balance' : $this->data['type'];
|
||||
Log::debug(
|
||||
sprintf(
|
||||
'Trying to change journal #%d from a %s to a %s.',
|
||||
$this->transactionJournal->id, $this->transactionJournal->transactionType->type, $type
|
||||
)
|
||||
);
|
||||
|
||||
/** @var TransactionTypeFactory $typeFactory */
|
||||
$typeFactory = app(TransactionTypeFactory::class);
|
||||
$result = $typeFactory->find($this->data['type']);
|
||||
if (null !== $result) {
|
||||
Log::debug('Changed transaction type!');
|
||||
$this->transactionJournal->transaction_type_id = $result->id;
|
||||
$this->transactionJournal->save();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
Log::debug('No type field present.');
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user