firefly-iii/app/Repositories/Journal/JournalRepository.php

537 lines
17 KiB
PHP
Raw Normal View History

2015-02-09 00:23:39 -06:00
<?php
/**
* JournalRepository.php
* Copyright (C) 2016 thegrumpydictator@gmail.com
*
* This software may be modified and distributed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International License.
*
* See the LICENSE file for details.
*/
2016-02-05 05:08:25 -06:00
declare(strict_types = 1);
2015-02-09 00:23:39 -06:00
namespace FireflyIII\Repositories\Journal;
2015-04-28 03:36:13 -05:00
use DB;
2016-02-17 08:52:46 -06:00
use FireflyIII\Exceptions\FireflyException;
2015-02-24 15:53:38 -06:00
use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType;
use FireflyIII\Models\Budget;
use FireflyIII\Models\Category;
2015-04-28 03:36:13 -05:00
use FireflyIII\Models\Tag;
2015-02-24 15:53:38 -06:00
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Models\TransactionType;
2016-05-02 13:49:19 -05:00
use FireflyIII\Repositories\Tag\TagRepositoryInterface;
use FireflyIII\User;
2015-04-03 15:54:21 -05:00
use Log;
2015-02-24 15:53:38 -06:00
2015-02-11 00:35:10 -06:00
/**
* Class JournalRepository
*
* @package FireflyIII\Repositories\Journal
*/
class JournalRepository implements JournalRepositoryInterface
{
/** @var User */
private $user;
/** @var array */
private $validMetaFields = ['interest_date', 'book_date', 'process_date', 'due_date', 'payment_date', 'invoice_date', 'internal_reference', 'notes'];
/**
2016-04-26 02:21:57 -05:00
* JournalRepository constructor.
*
* @param User $user
*/
public function __construct(User $user)
{
$this->user = $user;
}
2015-02-09 00:23:39 -06:00
/**
* @param TransactionJournal $journal
*
* @return bool
*/
2016-04-06 02:27:45 -05:00
public function delete(TransactionJournal $journal): bool
{
$journal->delete();
return true;
}
2016-04-23 02:33:54 -05:00
/**
* @param int $journalId
*
* @return TransactionJournal
*/
public function find(int $journalId) : TransactionJournal
{
$journal = $this->user->transactionJournals()->where('id', $journalId)->first();
2016-04-23 02:33:54 -05:00
if (is_null($journal)) {
return new TransactionJournal;
}
return $journal;
}
2015-04-03 15:54:21 -05:00
/**
* Get users first transaction journal
*
* @return TransactionJournal
*/
2016-04-06 02:27:45 -05:00
public function first(): TransactionJournal
2015-04-03 15:54:21 -05:00
{
$entry = $this->user->transactionJournals()->orderBy('date', 'ASC')->first(['transaction_journals.*']);
2016-04-10 14:31:00 -05:00
if (is_null($entry)) {
2016-04-10 14:31:00 -05:00
return new TransactionJournal;
}
2015-12-25 10:11:55 -06:00
return $entry;
2015-04-03 15:54:21 -05:00
}
2016-05-15 05:08:41 -05:00
2015-02-24 15:53:38 -06:00
/**
* @param array $data
*
* @return TransactionJournal
*/
2016-04-06 02:27:45 -05:00
public function store(array $data): TransactionJournal
2015-02-24 15:53:38 -06:00
{
// find transaction type.
$transactionType = TransactionType::where('type', ucfirst($data['what']))->first();
$journal = new TransactionJournal(
2015-02-24 15:53:38 -06:00
[
'user_id' => $data['user'],
'transaction_type_id' => $transactionType->id,
'transaction_currency_id' => $data['currency_id'],
'description' => $data['description'],
'completed' => 0,
'date' => $data['date'],
2015-02-24 15:53:38 -06:00
]
);
$journal->save();
// store stuff:
$this->storeCategoryWithJournal($journal, $data['category']);
$this->storeBudgetWithJournal($journal, $data['budget_id']);
$accounts = $this->storeAccounts($transactionType, $data);
// store two transactions:
$one = [
'journal' => $journal,
'account' => $accounts['source'],
'amount' => bcmul(strval($data['amount']), '-1'),
'description' => null,
'category' => null,
'budget' => null,
'identifier' => 0,
];
$this->storeTransaction($one);
$two = [
'journal' => $journal,
'account' => $accounts['destination'],
'amount' => $data['amount'],
'description' => null,
'category' => null,
'budget' => null,
'identifier' => 0,
];
$this->storeTransaction($two);
2015-02-24 15:53:38 -06:00
2015-04-28 07:08:58 -05:00
// store tags
if (isset($data['tags']) && is_array($data['tags'])) {
$this->saveTags($journal, $data['tags']);
}
foreach ($data as $key => $value) {
if (in_array($key, $this->validMetaFields)) {
$journal->setMeta($key, $value);
continue;
}
Log::debug(sprintf('Could not store meta field "%s" with value "%s" for journal #%d', json_encode($key), json_encode($value), $journal->id));
}
2015-02-24 15:53:38 -06:00
$journal->completed = 1;
$journal->save();
return $journal;
2015-02-24 15:53:38 -06:00
}
2015-02-27 07:27:04 -06:00
2016-05-15 05:08:41 -05:00
/**
* Store journal only, uncompleted, with attachments if necessary.
*
* @param array $data
*
* @return TransactionJournal
*/
public function storeJournal(array $data): TransactionJournal
{
// find transaction type.
$transactionType = TransactionType::where('type', ucfirst($data['what']))->first();
// store actual journal.
$journal = new TransactionJournal(
[
'user_id' => $data['user'],
'transaction_type_id' => $transactionType->id,
'transaction_currency_id' => $data['amount_currency_id_amount'],
'description' => $data['description'],
'completed' => 0,
'date' => $data['date'],
]
);
$result = $journal->save();
if ($result) {
return $journal;
}
return new TransactionJournal();
2016-05-15 05:08:41 -05:00
}
2015-02-27 07:27:04 -06:00
/**
* @param TransactionJournal $journal
* @param array $data
*
* @return TransactionJournal
2015-02-27 07:27:04 -06:00
*/
2016-04-06 02:27:45 -05:00
public function update(TransactionJournal $journal, array $data): TransactionJournal
2015-02-27 07:27:04 -06:00
{
// update actual journal:
$journal->transaction_currency_id = $data['currency_id'];
2015-02-27 07:27:04 -06:00
$journal->description = $data['description'];
$journal->date = $data['date'];
// unlink all categories, recreate them:
$journal->categories()->detach();
$journal->budgets()->detach();
$this->storeCategoryWithJournal($journal, $data['category']);
$this->storeBudgetWithJournal($journal, $data['budget_id']);
$accounts = $this->storeAccounts($journal->transactionType, $data);
2015-03-29 05:32:00 -05:00
$sourceAmount = bcmul(strval($data['amount']), '-1');
$this->updateSourceTransaction($journal, $accounts['source'], $sourceAmount); // negative because source loses money.
2015-03-29 05:32:00 -05:00
$amount = strval($data['amount']);
$this->updateDestinationTransaction($journal, $accounts['destination'], $amount); // positive because destination gets money.
2015-03-29 05:32:00 -05:00
$journal->save();
2015-04-28 03:36:13 -05:00
// update tags:
if (isset($data['tags']) && is_array($data['tags'])) {
$this->updateTags($journal, $data['tags']);
}
// update meta fields:
$result = $journal->save();
if ($result) {
foreach ($data as $key => $value) {
if (in_array($key, $this->validMetaFields)) {
$journal->setMeta($key, $value);
continue;
}
Log::debug(sprintf('Could not store meta field "%s" with value "%s" for journal #%d', json_encode($key), json_encode($value), $journal->id));
}
return $journal;
}
2015-03-29 05:32:00 -05:00
return $journal;
}
2015-04-28 03:36:13 -05:00
/**
2016-05-01 02:42:08 -05:00
*
* * Remember: a balancingAct takes at most one expense and one transfer.
* an advancePayment takes at most one expense, infinite deposits and NO transfers.
*
2015-04-28 03:36:13 -05:00
* @param TransactionJournal $journal
* @param array $array
*
2016-04-06 02:27:45 -05:00
* @return bool
2015-04-28 03:36:13 -05:00
*/
2016-05-01 02:42:08 -05:00
private function saveTags(TransactionJournal $journal, array $array): bool
2015-04-28 03:36:13 -05:00
{
2016-05-02 13:49:19 -05:00
/** @var TagRepositoryInterface $tagRepository */
$tagRepository = app(TagRepositoryInterface::class);
2015-04-28 10:10:52 -05:00
2015-04-28 03:36:13 -05:00
foreach ($array as $name) {
2015-04-28 14:01:54 -05:00
if (strlen(trim($name)) > 0) {
2016-05-01 02:42:08 -05:00
$tag = Tag::firstOrCreateEncrypted(['tag' => $name, 'user_id' => $journal->user_id]);
if (!is_null($tag)) {
$tagRepository->connect($journal, $tag);
}
2015-04-28 14:01:54 -05:00
}
2015-04-28 03:36:13 -05:00
}
2016-04-06 02:27:45 -05:00
return true;
2015-04-28 03:36:13 -05:00
}
2015-03-29 05:32:00 -05:00
/**
* @param TransactionType $type
* @param array $data
*
* @return array
2016-02-17 14:14:32 -06:00
* @throws FireflyException
2015-03-29 05:32:00 -05:00
*/
2016-05-01 02:42:08 -05:00
private function storeAccounts(TransactionType $type, array $data): array
2015-03-29 05:32:00 -05:00
{
$accounts = [
'source' => null,
'destination' => null,
];
2015-03-29 05:32:00 -05:00
switch ($type->type) {
case TransactionType::WITHDRAWAL:
$accounts = $this->storeWithdrawalAccounts($data);
2015-02-27 07:27:04 -06:00
break;
case TransactionType::DEPOSIT:
$accounts = $this->storeDepositAccounts($data);
2015-02-27 07:27:04 -06:00
break;
case TransactionType::TRANSFER:
$accounts['source'] = Account::where('user_id', $this->user->id)->where('id', $data['source_account_id'])->first();
$accounts['destination'] = Account::where('user_id', $this->user->id)->where('id', $data['destination_account_id'])->first();
2015-02-27 07:27:04 -06:00
break;
2016-04-24 00:18:39 -05:00
default:
throw new FireflyException(sprintf('Did not recognise transaction type "%s".', $type->type));
2015-02-27 07:27:04 -06:00
}
2015-05-17 05:49:09 -05:00
if (is_null($accounts['source'])) {
Log::error('"destination"-account is null, so we cannot continue!', ['data' => $data]);
throw new FireflyException('"destination"-account is null, so we cannot continue!');
2015-04-03 15:54:21 -05:00
}
2015-05-09 11:30:58 -05:00
if (is_null($accounts['destination'])) {
Log::error('"source"-account is null, so we cannot continue!', ['data' => $data]);
throw new FireflyException('"source"-account is null, so we cannot continue!');
2015-07-07 12:09:45 -05:00
2015-04-03 15:54:21 -05:00
}
2015-05-14 02:51:54 -05:00
2015-02-27 07:27:04 -06:00
return $accounts;
}
/**
* @param TransactionJournal $journal
* @param int $budgetId
*/
private function storeBudgetWithJournal(TransactionJournal $journal, int $budgetId)
{
if (intval($budgetId) > 0 && $journal->transactionType->type !== TransactionType::TRANSFER) {
/** @var \FireflyIII\Models\Budget $budget */
$budget = Budget::find($budgetId);
$journal->budgets()->save($budget);
}
}
/**
* @param TransactionJournal $journal
* @param string $category
*/
private function storeCategoryWithJournal(TransactionJournal $journal, string $category)
{
if (strlen($category) > 0) {
$category = Category::firstOrCreateEncrypted(['name' => $category, 'user_id' => $journal->user_id]);
$journal->categories()->save($category);
}
2015-05-17 05:49:09 -05:00
}
/**
* @param array $data
*
* @return array
*/
2016-05-01 02:42:08 -05:00
private function storeDepositAccounts(array $data): array
2015-05-17 05:49:09 -05:00
{
$destinationAccount = Account::where('user_id', $this->user->id)->where('id', $data['destination_account_id'])->first(['accounts.*']);
2015-05-17 05:49:09 -05:00
2016-04-29 10:29:13 -05:00
if (strlen($data['source_account_name']) > 0) {
$sourceType = AccountType::where('type', 'Revenue account')->first();
$sourceAccount = Account::firstOrCreateEncrypted(
['user_id' => $data['user'], 'account_type_id' => $sourceType->id, 'name' => $data['source_account_name'], 'active' => 1]
2015-05-17 05:49:09 -05:00
);
return [
'source' => $sourceAccount,
'destination' => $destinationAccount,
];
2015-05-17 05:49:09 -05:00
}
$sourceType = AccountType::where('type', 'Cash account')->first();
$sourceAccount = Account::firstOrCreateEncrypted(
['user_id' => $data['user'], 'account_type_id' => $sourceType->id, 'name' => 'Cash account', 'active' => 1]
);
return [
'source' => $sourceAccount,
'destination' => $destinationAccount,
];
}
private function storeTransaction(array $data): Transaction
{
/** @var Transaction $transaction */
$transaction = Transaction::create(
[
'transaction_journal_id' => $data['journal']->id,
'account_id' => $data['account']->id,
'amount' => $data['amount'],
'description' => $data['description'],
'identifier' => $data['identifier'],
]
);
if (!is_null($data['category'])) {
$transaction->categories()->save($data['category']);
}
if (!is_null($data['budget'])) {
$transaction->categories()->save($data['budget']);
}
return $transaction;
2015-05-17 05:49:09 -05:00
}
/**
* @param array $data
*
* @return array
*/
2016-05-01 02:42:08 -05:00
private function storeWithdrawalAccounts(array $data): array
2015-05-17 05:49:09 -05:00
{
2016-04-29 10:29:13 -05:00
$sourceAccount = Account::where('user_id', $this->user->id)->where('id', $data['source_account_id'])->first(['accounts.*']);
if (strlen($data['destination_account_name']) > 0) {
$destinationType = AccountType::where('type', 'Expense account')->first();
$destinationAccount = Account::firstOrCreateEncrypted(
[
'user_id' => $data['user'],
'account_type_id' => $destinationType->id,
'name' => $data['destination_account_name'],
'active' => 1,
]
2015-05-17 05:49:09 -05:00
);
2016-04-29 10:29:13 -05:00
return [
'source' => $sourceAccount,
'destination' => $destinationAccount,
];
2015-05-17 05:49:09 -05:00
}
2016-04-29 10:29:13 -05:00
$destinationType = AccountType::where('type', 'Cash account')->first();
$destinationAccount = Account::firstOrCreateEncrypted(
['user_id' => $data['user'], 'account_type_id' => $destinationType->id, 'name' => 'Cash account', 'active' => 1]
);
return [
'source' => $sourceAccount,
'destination' => $destinationAccount,
];
}
/**
* @param TransactionJournal $journal
* @param Account $account
* @param string $amount
*
* @throws FireflyException
*/
private function updateDestinationTransaction(TransactionJournal $journal, Account $account, string $amount)
{
// should be one:
$set = $journal->transactions()->where('amount', '>', 0)->get();
if ($set->count() != 1) {
throw new FireflyException(
sprintf('Journal #%d has an unexpected (%d) amount of transactions with an amount more than zero.', $journal->id, $set->count())
);
}
/** @var Transaction $transaction */
$transaction = $set->first();
$transaction->amount = $amount;
$transaction->account_id = $account->id;
$transaction->save();
}
/**
* @param TransactionJournal $journal
* @param Account $account
* @param string $amount
*
* @throws FireflyException
*/
private function updateSourceTransaction(TransactionJournal $journal, Account $account, string $amount)
{
// should be one:
$set = $journal->transactions()->where('amount', '<', 0)->get();
if ($set->count() != 1) {
throw new FireflyException(
sprintf('Journal #%d has an unexpected (%d) amount of transactions with an amount less than zero.', $journal->id, $set->count())
);
}
/** @var Transaction $transaction */
$transaction = $set->first();
$transaction->amount = $amount;
$transaction->account_id = $account->id;
$transaction->save();
2016-04-29 10:29:13 -05:00
2015-05-17 05:49:09 -05:00
2015-02-27 07:27:04 -06:00
}
2016-05-01 02:42:08 -05:00
/**
* @param TransactionJournal $journal
* @param array $array
*
* @return bool
*/
private function updateTags(TransactionJournal $journal, array $array): bool
{
// create tag repository
2016-05-02 13:49:19 -05:00
/** @var TagRepositoryInterface $tagRepository */
$tagRepository = app(TagRepositoryInterface::class);
2016-05-01 02:42:08 -05:00
// find or create all tags:
$tags = [];
$ids = [];
foreach ($array as $name) {
if (strlen(trim($name)) > 0) {
$tag = Tag::firstOrCreateEncrypted(['tag' => $name, 'user_id' => $journal->user_id]);
$tags[] = $tag;
$ids[] = $tag->id;
}
}
// delete all tags connected to journal not in this array:
if (count($ids) > 0) {
DB::table('tag_transaction_journal')->where('transaction_journal_id', $journal->id)->whereNotIn('tag_id', $ids)->delete();
}
// if count is zero, delete them all:
if (count($ids) == 0) {
DB::table('tag_transaction_journal')->where('transaction_journal_id', $journal->id)->delete();
}
// connect each tag to journal (if not yet connected):
/** @var Tag $tag */
foreach ($tags as $tag) {
$tagRepository->connect($journal, $tag);
}
return true;
}
}