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

610 lines
21 KiB
PHP
Raw Normal View History

2015-02-09 00:23:39 -06:00
<?php
2016-02-05 05:08:25 -06:00
declare(strict_types = 1);
2015-02-09 00:23:39 -06:00
namespace FireflyIII\Repositories\Journal;
use Carbon\Carbon;
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;
2016-05-15 05:08:41 -05:00
use FireflyIII\Models\PiggyBankEvent;
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;
2016-05-01 02:52:58 -05:00
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\JoinClause;
use Illuminate\Pagination\LengthAwarePaginator;
2015-02-25 14:19:06 -06:00
use Illuminate\Support\Collection;
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;
/**
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
2016-05-13 02:55:06 -05:00
/**
* Returns the amount in the account before the specified transaction took place.
*
* @param Transaction $transaction
*
* @return string
*/
public function balanceBeforeTransaction(Transaction $transaction): string
{
// some dates from journal
$journal = $transaction->transactionJournal;
$query = Transaction::
leftJoin('transaction_journals', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')
->where('transactions.account_id', $transaction->account_id)
->where('transaction_journals.user_id', $this->user->id)
->where(
function (Builder $q) use ($journal) {
$q->where('transaction_journals.date', '<', $journal->date->format('Y-m-d'));
$q->orWhere(
function (Builder $qq) use ($journal) {
$qq->where('transaction_journals.date', '=', $journal->date->format('Y-m-d'));
$qq->where('transaction_journals.order', '>', $journal->order);
}
);
}
)
->where('transactions.id', '!=', $transaction->id)
->whereNull('transactions.deleted_at')
->whereNull('transaction_journals.deleted_at')
->orderBy('transaction_journals.date', 'DESC')
->orderBy('transaction_journals.order', 'ASC')
->orderBy('transaction_journals.id', 'DESC');
$sum = $query->sum('transactions.amount');
return strval($sum);
}
/**
* @param TransactionJournal $journal
*
* @return bool
*/
2016-04-06 02:27:45 -05:00
public function delete(TransactionJournal $journal): bool
{
2016-05-01 02:42:08 -05:00
/** @var Transaction $transaction */
foreach ($journal->transactions()->get() as $transaction) {
$transaction->delete();
}
$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();
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
}
/**
* @param array $types
* @param int $page
2016-04-21 03:34:16 -05:00
* @param int $pageSize
2016-02-17 14:14:32 -06:00
*
* @return LengthAwarePaginator
*/
2016-05-01 02:42:08 -05:00
public function getJournals(array $types, int $page, int $pageSize = 50): LengthAwarePaginator
{
2016-04-21 03:34:16 -05:00
$offset = ($page - 1) * $pageSize;
2016-05-11 01:10:05 -05:00
$query = $this->user->transactionJournals()->expanded()->sortCorrectly();
2016-05-01 02:42:08 -05:00
if (count($types) > 0) {
$query->transactionTypes($types);
}
2016-05-15 08:39:22 -05:00
$count = $this->user->transactionJournals()->transactionTypes($types)->count();
$set = $query->take($pageSize)->offset($offset)->get(TransactionJournal::queryFields());
2016-04-21 03:34:16 -05:00
$journals = new LengthAwarePaginator($set, $count, $pageSize, $page);
return $journals;
}
2016-05-01 02:52:58 -05:00
/**
* Returns a collection of ALL journals, given a specific account and a date range.
*
* @param Collection $accounts
* @param Carbon $start
* @param Carbon $end
*
* @return Collection
*/
public function getJournalsInRange(Collection $accounts, Carbon $start, Carbon $end): Collection
{
2016-05-11 01:10:05 -05:00
$query = $this->user->transactionJournals()->expanded()->sortCorrectly();
2016-05-01 02:52:58 -05:00
$query->before($end);
$query->after($start);
if ($accounts->count() > 0) {
$ids = $accounts->pluck('id')->toArray();
// join source and destination:
$query->leftJoin(
'transactions as source', function (JoinClause $join) {
$join->on('source.transaction_journal_id', '=', 'transaction_journals.id')->where('source.amount', '<', 0);
}
);
$query->leftJoin(
'transactions as destination', function (JoinClause $join) {
$join->on('destination.transaction_journal_id', '=', 'transaction_journals.id')->where('destination.amount', '>', 0);
}
);
2016-05-01 02:52:58 -05:00
$query->where(
function (Builder $q) use ($ids) {
$q->whereIn('destination.account_id', $ids);
$q->orWhereIn('source.account_id', $ids);
}
);
}
$set = $query->get(TransactionJournal::queryFields());
return $set;
}
2016-05-15 05:08:41 -05:00
/**
* @param TransactionJournal $journal
*
* @return Collection
*/
public function getPiggyBankEvents(TransactionJournal $journal): Collection
{
/** @var Collection $set */
$events = $journal->piggyBankEvents()->get();
$events->each(
function (PiggyBankEvent $event) {
$event->piggyBank = $event->piggyBank()->withTrashed()->first();
}
);
return $events;
}
/**
* @param TransactionJournal $journal
*
* @return Collection
*/
public function getTransactions(TransactionJournal $journal): Collection
{
2016-05-20 01:00:35 -05:00
$transactions = new Collection;
2016-05-15 05:08:41 -05:00
switch ($journal->transactionType->type) {
case TransactionType::DEPOSIT:
/** @var Collection $transactions */
$transactions = $journal->transactions()
->groupBy('transactions.account_id')
->where('amount', '<', 0)
->groupBy('transactions.id')
->orderBy('amount', 'ASC')->get(
['transactions.*', DB::raw('SUM(`transactions`.`amount`) as `sum`')]
);
$final = $journal->transactions()
->groupBy('transactions.account_id')
->where('amount', '>', 0)
->orderBy('amount', 'ASC')->first(
['transactions.*', DB::raw('SUM(`transactions`.`amount`) as `sum`')]
);
$transactions->push($final);
break;
case TransactionType::TRANSFER:
/** @var Collection $transactions */
$transactions = $journal->transactions()
2016-05-15 08:39:22 -05:00
->groupBy('transactions.id')
->orderBy('transactions.id')->get(
2016-05-15 05:08:41 -05:00
['transactions.*', DB::raw('SUM(`transactions`.`amount`) as `sum`')]
);
break;
case TransactionType::WITHDRAWAL:
/** @var Collection $transactions */
$transactions = $journal->transactions()
->where('amount', '>', 0)
->groupBy('transactions.id')
->orderBy('amount', 'ASC')->get(
['transactions.*', DB::raw('SUM(`transactions`.`amount`) as `sum`')]
);
$final = $journal->transactions()
->where('amount', '<', 0)
->groupBy('transactions.account_id')
->orderBy('amount', 'ASC')->first(
['transactions.*', DB::raw('SUM(`transactions`.`amount`) as `sum`')]
);
$transactions->push($final);
break;
}
// foreach do balance thing
$transactions->each(
function (Transaction $t) {
$t->before = $this->balanceBeforeTransaction($t);
}
);
return $transactions;
}
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();
// 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'],
'interest_date' => $data['interest_date'],
'book_date' => $data['book_date'],
'process_date' => $data['process_date'],
2015-02-24 15:53:38 -06:00
]
);
$journal->save();
// store or get category
if (strlen($data['category']) > 0) {
$category = Category::firstOrCreateEncrypted(['name' => $data['category'], 'user_id' => $data['user']]);
2015-02-24 15:53:38 -06:00
$journal->categories()->save($category);
}
// store or get budget
if (intval($data['budget_id']) > 0) {
2015-05-05 03:23:01 -05:00
/** @var \FireflyIII\Models\Budget $budget */
2015-02-24 15:53:38 -06:00
$budget = Budget::find($data['budget_id']);
$journal->budgets()->save($budget);
}
// store accounts (depends on type)
2016-04-29 10:29:13 -05:00
list($sourceAccount, $destinationAccount) = $this->storeAccounts($transactionType, $data);
2015-02-24 15:53:38 -06:00
// store accompanying transactions.
Transaction::create( // first transaction.
[
2016-04-29 10:29:13 -05:00
'account_id' => $sourceAccount->id,
2015-02-24 15:53:38 -06:00
'transaction_journal_id' => $journal->id,
2016-01-15 16:12:52 -06:00
'amount' => $data['amount'] * -1,
2015-02-24 15:53:38 -06:00
]
);
2015-04-03 15:54:21 -05:00
Transaction::create( // second transaction.
2015-02-24 15:53:38 -06:00
[
2016-04-29 10:29:13 -05:00
'account_id' => $destinationAccount->id,
2015-02-24 15:53:38 -06:00
'transaction_journal_id' => $journal->id,
2016-01-15 16:12:52 -06:00
'amount' => $data['amount'],
2015-02-24 15:53:38 -06:00
]
);
2015-02-27 07:27:04 -06:00
$journal->completed = 1;
$journal->save();
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']);
}
2015-02-24 15:53:38 -06:00
return $journal;
}
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'],
'interest_date' => $data['interest_date'],
'book_date' => $data['book_date'],
'process_date' => $data['process_date'],
]
);
$journal->save();
return $journal;
}
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['amount_currency_id_amount'];
2015-02-27 07:27:04 -06:00
$journal->description = $data['description'];
$journal->date = $data['date'];
$journal->interest_date = $data['interest_date'];
$journal->book_date = $data['book_date'];
$journal->process_date = $data['process_date'];
2015-02-27 07:27:04 -06:00
// unlink all categories, recreate them:
$journal->categories()->detach();
if (strlen($data['category']) > 0) {
$category = Category::firstOrCreateEncrypted(['name' => $data['category'], 'user_id' => $data['user']]);
2015-02-27 07:27:04 -06:00
$journal->categories()->save($category);
}
// unlink all budgets and recreate them:
$journal->budgets()->detach();
if (intval($data['budget_id']) > 0) {
2015-05-05 03:23:01 -05:00
/** @var \FireflyIII\Models\Budget $budget */
2016-04-30 05:46:21 -05:00
$budget = Budget::where('user_id', $this->user->id)->where('id', $data['budget_id'])->first();
2015-02-27 07:27:04 -06:00
$journal->budgets()->save($budget);
}
// store accounts (depends on type)
2015-07-06 11:57:15 -05:00
list($fromAccount, $toAccount) = $this->storeAccounts($journal->transactionType, $data);
2015-03-29 05:32:00 -05:00
// update the from and to transaction.
/** @var Transaction $transaction */
foreach ($journal->transactions()->get() as $transaction) {
if ($transaction->amount < 0) {
2015-03-29 05:32:00 -05:00
// this is the from transaction, negative amount:
$transaction->amount = $data['amount'] * -1;
2015-07-06 11:57:15 -05:00
$transaction->account_id = $fromAccount->id;
2015-03-29 05:32:00 -05:00
$transaction->save();
}
if ($transaction->amount > 0) {
2015-03-29 05:32:00 -05:00
$transaction->amount = $data['amount'];
2015-07-06 11:57:15 -05:00
$transaction->account_id = $toAccount->id;
2015-03-29 05:32:00 -05:00
$transaction->save();
}
}
$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']);
}
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
{
2016-04-29 10:29:13 -05:00
$sourceAccount = null;
$destinationAccount = null;
2015-03-29 05:32:00 -05:00
switch ($type->type) {
case TransactionType::WITHDRAWAL:
2016-04-29 10:29:13 -05:00
list($sourceAccount, $destinationAccount) = $this->storeWithdrawalAccounts($data);
2015-02-27 07:27:04 -06:00
break;
case TransactionType::DEPOSIT:
2016-04-29 10:29:13 -05:00
list($sourceAccount, $destinationAccount) = $this->storeDepositAccounts($data);
2015-02-27 07:27:04 -06:00
break;
case TransactionType::TRANSFER:
2016-04-30 05:46:21 -05:00
$sourceAccount = Account::where('user_id', $this->user->id)->where('id', $data['source_account_id'])->first();
$destinationAccount = 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('Did not recognise transaction type.');
2015-02-27 07:27:04 -06:00
}
2015-05-17 05:49:09 -05:00
2016-04-29 10:29:13 -05:00
if (is_null($destinationAccount)) {
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
2016-04-29 10:29:13 -05:00
if (is_null($sourceAccount)) {
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
2016-04-29 10:29:13 -05:00
return [$sourceAccount, $destinationAccount];
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) {
2016-01-20 08:23:36 -06:00
$fromType = AccountType::where('type', 'Revenue account')->first();
$fromAccount = Account::firstOrCreateEncrypted(
2016-04-29 10:29:13 -05:00
['user_id' => $data['user'], 'account_type_id' => $fromType->id, 'name' => $data['source_account_name'], 'active' => 1]
2015-05-17 05:49:09 -05:00
);
2016-04-29 10:29:13 -05:00
return [$fromAccount, $destinationAccount];
2015-05-17 05:49:09 -05:00
} else {
$fromType = AccountType::where('type', 'Cash account')->first();
2016-01-20 08:23:36 -06:00
$fromAccount = Account::firstOrCreateEncrypted(
2016-04-29 10:29:13 -05:00
['user_id' => $data['user'], 'account_type_id' => $fromType->id, 'name' => 'Cash account', 'active' => 1]
2015-05-17 05:49:09 -05:00
);
}
2016-04-29 10:29:13 -05:00
return [$fromAccount, $destinationAccount];
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 [$sourceAccount, $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 [$sourceAccount, $destinationAccount];
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;
}
}