firefly-iii/app/Handlers/Events/ConnectJournalToPiggyBank.php

75 lines
1.9 KiB
PHP
Raw Normal View History

2015-03-02 13:05:28 -06:00
<?php namespace FireflyIII\Handlers\Events;
use Auth;
use FireflyIII\Events\JournalCreated;
use FireflyIII\Models\PiggyBank;
use FireflyIII\Models\PiggyBankEvent;
use FireflyIII\Models\Transaction;
use FireflyIII\Models\TransactionJournal;
/**
* Class ConnectJournalToPiggyBank
*
* @package FireflyIII\Handlers\Events
*/
class ConnectJournalToPiggyBank
{
/**
* Create the event handler.
*
*/
public function __construct()
{
//
}
/**
* Handle the event when journal is saved.
*
2015-05-17 03:30:18 -05:00
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*
2015-03-02 13:05:28 -06:00
* @param JournalCreated $event
*
2015-05-11 14:45:31 -05:00
* @return boolean
2015-03-02 13:05:28 -06:00
*/
public function handle(JournalCreated $event)
{
/** @var TransactionJournal $journal */
$journal = $event->journal;
$piggyBankId = $event->piggyBankId;
/** @var PiggyBank $piggyBank */
$piggyBank = Auth::user()->piggybanks()->where('piggy_banks.id', $piggyBankId)->first(['piggy_banks.*']);
2015-05-17 03:30:18 -05:00
if (is_null($piggyBank)) {
2015-05-11 14:45:31 -05:00
return false;
2015-03-02 13:05:28 -06:00
}
// update piggy bank rep for date of transaction journal.
$repetition = $piggyBank->piggyBankRepetitions()->relevantOnDate($journal->date)->first();
if (is_null($repetition)) {
2015-05-11 14:45:31 -05:00
return false;
2015-03-02 13:05:28 -06:00
}
2015-05-17 03:30:18 -05:00
$amount = $journal->amount;
/** @var Transaction $transaction */
foreach ($journal->transactions()->get() as $transaction) {
if ($transaction->account_id == $piggyBank->account_id) {
if ($transaction->amount < 0) {
2015-05-17 03:30:18 -05:00
$amount = $transaction->amount * -1;
}
}
}
2015-03-02 13:05:28 -06:00
$repetition->currentamount += $amount;
$repetition->save();
2015-05-17 03:30:18 -05:00
PiggyBankEvent::create(['piggy_bank_id' => $piggyBank->id, 'transaction_journal_id' => $journal->id, 'date' => $journal->date, 'amount' => $amount]);
2015-05-14 02:51:54 -05:00
2015-05-11 14:45:31 -05:00
return true;
2015-03-02 13:05:28 -06:00
}
}