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

624 lines
20 KiB
PHP
Raw Normal View History

2015-02-09 00:23:39 -06:00
<?php
/**
* JournalRepository.php
2017-10-21 01:40:00 -05:00
* Copyright (c) 2017 thegrumpydictator@gmail.com
*
2017-10-21 01:40:00 -05:00
* This file is part of Firefly III.
*
2017-10-21 01:40:00 -05:00
* 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
2017-12-17 07:44:05 -06:00
* along with Firefly III. If not, see <http://www.gnu.org/licenses/>.
*/
2017-03-24 09:01:53 -05:00
declare(strict_types=1);
2015-02-09 00:23:39 -06:00
namespace FireflyIII\Repositories\Journal;
use Carbon\Carbon;
2017-12-30 07:25:11 -06:00
use DB;
2015-02-24 15:53:38 -06:00
use FireflyIII\Models\Account;
use FireflyIII\Models\AccountType;
2017-12-23 10:42:07 -06:00
use FireflyIII\Models\Note;
use FireflyIII\Models\Tag;
use FireflyIII\Models\Transaction;
2015-02-24 15:53:38 -06:00
use FireflyIII\Models\TransactionJournal;
use FireflyIII\Models\TransactionType;
2017-12-30 07:25:11 -06:00
use FireflyIII\Repositories\Tag\TagRepositoryInterface;
use FireflyIII\User;
2016-10-21 14:41:31 -05:00
use Illuminate\Support\Collection;
2016-10-30 00:14:07 -05:00
use Illuminate\Support\MessageBag;
2015-04-03 15:54:21 -05:00
use Log;
2016-10-30 00:14:07 -05:00
use Preferences;
2015-02-24 15:53:38 -06:00
2015-02-11 00:35:10 -06:00
/**
2017-11-15 05:25:49 -06:00
* Class JournalRepository.
2015-02-11 00:35:10 -06:00
*/
class JournalRepository implements JournalRepositoryInterface
{
2017-06-07 01:18:42 -05:00
use CreateJournalsTrait, UpdateJournalsTrait, SupportJournalsTrait;
/** @var User */
private $user;
/** @var array */
2017-10-03 03:30:56 -05:00
private $validMetaFields = ['interest_date', 'book_date', 'process_date', 'due_date', 'payment_date', 'invoice_date', 'internal_reference'];
2016-10-30 00:14:07 -05:00
/**
* @param TransactionJournal $journal
* @param TransactionType $type
* @param Account $source
* @param Account $destination
*
* @return MessageBag
*/
public function convert(TransactionJournal $journal, TransactionType $type, Account $source, Account $destination): MessageBag
{
// default message bag that shows errors for everything.
$messages = new MessageBag;
$messages->add('source_account_revenue', trans('firefly.invalid_convert_selection'));
$messages->add('destination_account_asset', trans('firefly.invalid_convert_selection'));
$messages->add('destination_account_expense', trans('firefly.invalid_convert_selection'));
$messages->add('source_account_asset', trans('firefly.invalid_convert_selection'));
2017-11-15 05:25:49 -06:00
if ($source->id === $destination->id || null === $source->id || null === $destination->id) {
2016-10-30 00:14:07 -05:00
return $messages;
}
$sourceTransaction = $journal->transactions()->where('amount', '<', 0)->first();
$destinationTransaction = $journal->transactions()->where('amount', '>', 0)->first();
$sourceTransaction->account_id = $source->id;
$sourceTransaction->save();
$destinationTransaction->account_id = $destination->id;
$destinationTransaction->save();
$journal->transaction_type_id = $type->id;
$journal->save();
// if journal is a transfer now, remove budget:
2017-11-15 05:25:49 -06:00
if (TransactionType::TRANSFER === $type->type) {
$journal->budgets()->detach();
}
2016-10-30 00:14:07 -05:00
Preferences::mark();
return new MessageBag;
2016-10-30 00:14:07 -05:00
}
2017-07-04 09:31:16 -05:00
/**
* @param TransactionJournal $journal
*
* @return int
*/
public function countTransactions(TransactionJournal $journal): int
{
return $journal->transactions()->count();
}
/**
* @param TransactionJournal $journal
*
* @return bool
2017-12-22 11:32:43 -06:00
*
2017-12-17 07:30:53 -06:00
* @throws \Exception
*/
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
2016-04-23 02:33:54 -05:00
{
$journal = $this->user->transactionJournals()->where('id', $journalId)->first();
2017-11-15 05:25:49 -06:00
if (null === $journal) {
2016-04-23 02:33:54 -05:00
return new TransactionJournal;
}
return $journal;
}
/**
* @param Transaction $transaction
*
* @return Transaction|null
*/
public function findOpposingTransaction(Transaction $transaction): ?Transaction
{
$opposing = Transaction::leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->where('transaction_journals.user_id', $this->user->id)
->where('transactions.transaction_journal_id', $transaction->transaction_journal_id)
->where('transactions.identifier', $transaction->identifier)
->where('amount', bcmul($transaction->amount, '-1'))
->first(['transactions.*']);
return $opposing;
}
/**
* @param int $transactionid
*
* @return Transaction|null
*/
public function findTransaction(int $transactionid): ?Transaction
{
$transaction = Transaction::leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->where('transaction_journals.user_id', $this->user->id)
->where('transactions.id', $transactionid)
->first(['transactions.*']);
return $transaction;
}
2015-04-03 15:54:21 -05:00
/**
2017-11-15 05:25:49 -06:00
* Get users first transaction journal.
2015-04-03 15:54:21 -05:00
*
* @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.*']);
2017-11-15 05:25:49 -06:00
if (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
}
/**
* @param TransactionJournal $journal
*
* @return Transaction|null
*/
public function getAssetTransaction(TransactionJournal $journal): ?Transaction
{
/** @var Transaction $transaction */
foreach ($journal->transactions as $transaction) {
2017-12-22 11:32:43 -06:00
if (AccountType::ASSET === $transaction->account->accountType->type) {
return $transaction;
}
}
return null;
}
2017-12-23 10:42:07 -06:00
/**
* @param TransactionJournal $journal
*
* @return Note|null
*/
public function getNote(TransactionJournal $journal): ?Note
{
return $journal->notes()->first();
}
/**
* @return Collection
*/
public function getTransactionTypes(): Collection
{
return TransactionType::orderBy('type', 'ASC')->get();
}
2017-11-22 09:54:49 -06:00
/**
* @param array $transactionIds
*
* @return Collection
*/
public function getTransactionsById(array $transactionIds): Collection
{
$set = Transaction::leftJoin('transaction_journals', 'transaction_journals.id', '=', 'transactions.transaction_journal_id')
->whereIn('transactions.id', $transactionIds)
->where('transaction_journals.user_id', $this->user->id)
->whereNull('transaction_journals.deleted_at')
->whereNull('transactions.deleted_at')
2017-11-22 14:12:27 -06:00
->get(['transactions.*']);
2017-11-22 09:54:49 -06:00
return $set;
}
2017-04-28 00:51:09 -05:00
/**
* @param TransactionJournal $journal
*
* @return bool
*/
public function isTransfer(TransactionJournal $journal): bool
{
2017-11-15 05:25:49 -06:00
return TransactionType::TRANSFER === $journal->transactionType->type;
2017-04-28 00:51:09 -05:00
}
/**
* Mark journal as completed and return it.
*
* @param TransactionJournal $journal
*
* @return TransactionJournal
*/
public function markCompleted(TransactionJournal $journal): TransactionJournal
{
$journal->completed = true;
$journal->save();
return $journal;
}
/**
* @param Transaction $transaction
*
* @return bool
*/
public function reconcile(Transaction $transaction): bool
{
Log::debug(sprintf('Going to reconcile transaction #%d', $transaction->id));
$opposing = $this->findOpposingTransaction($transaction);
2017-11-15 05:25:49 -06:00
if (null === $opposing) {
Log::debug('Opposing transaction is NULL. Cannot reconcile.');
return false;
}
Log::debug(sprintf('Opposing transaction ID is #%d', $opposing->id));
$transaction->reconciled = true;
$opposing->reconciled = true;
$transaction->save();
$opposing->save();
return true;
}
2017-03-24 09:01:53 -05:00
/**
* @param TransactionJournal $journal
* @param int $order
*
* @return bool
*/
public function setOrder(TransactionJournal $journal, int $order): bool
{
$journal->order = $order;
$journal->save();
return true;
}
2017-02-16 23:42:36 -06:00
/**
* @param User $user
*/
public function setUser(User $user)
{
$this->user = $user;
}
2015-02-24 15:53:38 -06:00
/**
* @param array $data
*
* @return TransactionJournal
2017-12-22 11:32:43 -06:00
*
2017-12-17 07:30:53 -06:00
* @throws \FireflyIII\Exceptions\FireflyException
* @throws \FireflyIII\Exceptions\FireflyException
2015-02-24 15:53:38 -06:00
*/
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.
/** @var TransactionType $transactionType */
2015-02-24 15:53:38 -06:00
$transactionType = TransactionType::where('type', ucfirst($data['what']))->first();
2017-06-07 01:18:42 -05:00
$accounts = $this->storeAccounts($this->user, $transactionType, $data);
$data = $this->verifyNativeAmount($data, $accounts);
$amount = strval($data['amount']);
$dateString = $data['date'];
if ($data['date'] instanceof Carbon) {
$dateString = $data['date']->format('Y-m-d 00:00:00');
}
$journal = new TransactionJournal(
2015-02-24 15:53:38 -06:00
[
2016-10-23 05:19:32 -05:00
'user_id' => $this->user->id,
'transaction_type_id' => $transactionType->id,
'transaction_currency_id' => $data['currency_id'], // no longer used.
'description' => $data['description'],
'completed' => 0,
'date' => $dateString,
2015-02-24 15:53:38 -06:00
]
);
$journal->save();
// store stuff:
2017-09-20 01:35:20 -05:00
$this->storeCategoryWithJournal($journal, strval($data['category']));
2017-06-07 01:18:42 -05:00
$this->storeBudgetWithJournal($journal, $data['budget_id']);
// store two transactions:
2017-11-17 22:46:19 -06:00
$one = [
'journal' => $journal,
'account' => $accounts['source'],
'amount' => bcmul($amount, '-1'),
'transaction_currency_id' => $data['currency_id'],
2017-11-15 05:25:49 -06:00
'foreign_amount' => null === $data['foreign_amount'] ? null : bcmul(strval($data['foreign_amount']), '-1'),
'foreign_currency_id' => $data['foreign_currency_id'],
'description' => null,
'category' => null,
'budget' => null,
'identifier' => 0,
];
2017-06-07 01:18:42 -05:00
$this->storeTransaction($one);
$two = [
'journal' => $journal,
'account' => $accounts['destination'],
'amount' => $amount,
'transaction_currency_id' => $data['currency_id'],
'foreign_amount' => $data['foreign_amount'],
'foreign_currency_id' => $data['foreign_currency_id'],
'description' => null,
'category' => null,
'budget' => null,
'identifier' => 0,
];
2017-06-07 01:18:42 -05:00
$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']);
}
2017-10-03 03:30:56 -05:00
// update note:
2017-10-05 23:36:00 -05:00
if (isset($data['notes'])) {
$this->updateNote($journal, $data['notes']);
}
2017-10-03 03:30:56 -05:00
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
2018-02-16 09:45:03 -06:00
/**
* Store a new transaction journal based on the values given.
*
* @param array $values
*
* @return TransactionJournal
*/
public function storeBasic(array $values): TransactionJournal
{
return TransactionJournal::create($values);
}
/**
* Store a new transaction based on the values given.
*
* @param array $values
*
* @return Transaction
*/
public function storeBasicTransaction(array $values): Transaction
{
return Transaction::create($values);
}
2015-04-28 03:36:13 -05:00
/**
2017-06-07 01:18:42 -05:00
* @param TransactionJournal $journal
* @param array $data
2016-05-01 02:42:08 -05:00
*
2017-06-07 01:18:42 -05:00
* @return TransactionJournal
2017-12-22 11:32:43 -06:00
*
2017-12-17 07:30:53 -06:00
* @throws \FireflyIII\Exceptions\FireflyException
* @throws \FireflyIII\Exceptions\FireflyException
* @throws \FireflyIII\Exceptions\FireflyException
* @throws \FireflyIII\Exceptions\FireflyException
2017-06-07 01:18:42 -05:00
*/
public function update(TransactionJournal $journal, array $data): TransactionJournal
{
// update actual journal:
$journal->description = $data['description'];
$journal->date = $data['date'];
$accounts = $this->storeAccounts($this->user, $journal->transactionType, $data);
$data = $this->verifyNativeAmount($data, $accounts);
$data['amount'] = strval($data['amount']);
2017-11-15 05:25:49 -06:00
$data['foreign_amount'] = null === $data['foreign_amount'] ? null : strval($data['foreign_amount']);
2017-06-07 01:18:42 -05:00
// unlink all categories, recreate them:
$journal->categories()->detach();
$journal->budgets()->detach();
2017-09-20 01:35:20 -05:00
$this->storeCategoryWithJournal($journal, strval($data['category']));
2017-06-07 01:18:42 -05:00
$this->storeBudgetWithJournal($journal, $data['budget_id']);
// negative because source loses money.
$this->updateSourceTransaction($journal, $accounts['source'], $data);
// positive because destination gets money.
$this->updateDestinationTransaction($journal, $accounts['destination'], $data);
$journal->save();
// update tags:
if (isset($data['tags']) && is_array($data['tags'])) {
$this->updateTags($journal, $data['tags']);
}
2017-10-03 03:30:56 -05:00
// update note:
2017-11-15 05:25:49 -06:00
if (isset($data['notes']) && null !== $data['notes']) {
2017-10-20 00:51:53 -05:00
$this->updateNote($journal, strval($data['notes']));
2017-10-05 23:36:00 -05:00
}
2017-10-03 03:30:56 -05:00
2017-06-07 01:18:42 -05:00
// 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;
}
return $journal;
}
/**
2017-12-30 07:25:11 -06:00
* @param TransactionJournal $journal
* @param int $budgetId
*
2017-12-30 07:25:11 -06:00
* @return TransactionJournal
*/
2017-12-30 07:25:11 -06:00
public function updateBudget(TransactionJournal $journal, int $budgetId): TransactionJournal
{
2017-12-30 07:25:11 -06:00
if ($budgetId === 0) {
$journal->budgets()->detach();
$journal->save();
2017-12-30 07:25:11 -06:00
return $journal;
}
$this->storeBudgetWithJournal($journal, $budgetId);
2017-12-30 07:25:11 -06:00
return $journal;
}
/**
* @param TransactionJournal $journal
* @param string $category
*
* @return TransactionJournal
*/
public function updateCategory(TransactionJournal $journal, string $category): TransactionJournal
{
Log::debug(sprintf('In updateCategory("%s")', $category));
$journal->categories()->detach();
if (strlen($category) === 0) {
return $journal;
}
2017-12-30 07:25:11 -06:00
$this->storeCategoryWithJournal($journal, $category);
2017-12-30 07:25:11 -06:00
return $journal;
}
2017-06-07 01:18:42 -05:00
/**
* Same as above but for transaction journal with multiple transactions.
2016-05-01 02:42:08 -05:00
*
2015-04-28 03:36:13 -05:00
* @param TransactionJournal $journal
2017-06-07 01:18:42 -05:00
* @param array $data
2015-04-28 03:36:13 -05:00
*
2017-06-07 01:18:42 -05:00
* @return TransactionJournal
2015-04-28 03:36:13 -05:00
*/
2017-06-07 01:18:42 -05:00
public function updateSplitJournal(TransactionJournal $journal, array $data): TransactionJournal
2015-04-28 03:36:13 -05:00
{
2017-06-07 01:18:42 -05:00
// update actual journal:
$journal->description = $data['journal_description'];
$journal->date = $data['date'];
$journal->save();
Log::debug(sprintf('Updated split journal #%d', $journal->id));
// unlink all categories:
$journal->categories()->detach();
$journal->budgets()->detach();
2017-10-03 03:30:56 -05:00
// update note:
2017-11-15 05:25:49 -06:00
if (isset($data['notes']) && null !== $data['notes']) {
2017-10-20 00:51:53 -05:00
$this->updateNote($journal, strval($data['notes']));
}
2017-06-07 01:18:42 -05:00
// update meta fields:
$result = $journal->save();
if ($result) {
foreach ($data as $key => $value) {
if (in_array($key, $this->validMetaFields)) {
$journal->setMeta($key, $value);
continue;
2016-05-01 02:42:08 -05:00
}
2017-06-07 01:18:42 -05:00
Log::debug(sprintf('Could not store meta field "%s" with value "%s" for journal #%d', json_encode($key), json_encode($value), $journal->id));
2015-04-28 14:01:54 -05:00
}
2015-04-28 03:36:13 -05:00
}
2017-06-07 01:18:42 -05:00
// update tags:
if (isset($data['tags']) && is_array($data['tags'])) {
$this->updateTags($journal, $data['tags']);
}
// delete original transactions, and recreate them.
$journal->transactions()->delete();
// store each transaction.
$identifier = 0;
Log::debug(sprintf('Count %d transactions in updateSplitJournal()', count($data['transactions'])));
foreach ($data['transactions'] as $transaction) {
Log::debug(sprintf('Split journal update split transaction %d', $identifier));
$transaction = $this->appendTransactionData($transaction, $data);
$this->storeSplitTransaction($journal, $transaction, $identifier);
2017-11-15 05:25:49 -06:00
++$identifier;
2017-06-07 01:18:42 -05:00
}
$journal->save();
return $journal;
2015-04-28 03:36:13 -05:00
}
2017-12-30 07:25:11 -06:00
/**
* Update tags.
*
* @param TransactionJournal $journal
* @param array $array
*
* @return bool
*/
public function updateTags(TransactionJournal $journal, array $array): bool
{
// create tag repository
/** @var TagRepositoryInterface $tagRepository */
$tagRepository = app(TagRepositoryInterface::class);
// 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 (0 === count($ids)) {
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) {
Log::debug(sprintf('Will try to connect tag #%d to journal #%d.', $tag->id, $journal->id));
$tagRepository->connect($journal, $tag);
}
return true;
}
}