2015-03-02 13:05:28 -06:00
|
|
|
<?php namespace FireflyIII\Handlers\Events;
|
|
|
|
|
|
|
|
use FireflyIII\Events\JournalSaved;
|
|
|
|
use FireflyIII\Models\PiggyBankEvent;
|
|
|
|
use FireflyIII\Models\Transaction;
|
|
|
|
|
2015-03-29 00:51:56 -05:00
|
|
|
/**
|
|
|
|
* Class UpdateJournalConnection
|
|
|
|
*
|
|
|
|
* @package FireflyIII\Handlers\Events
|
|
|
|
*/
|
2015-03-02 13:05:28 -06:00
|
|
|
class UpdateJournalConnection
|
|
|
|
{
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Create the event handler.
|
|
|
|
*
|
|
|
|
* @return void
|
|
|
|
*/
|
|
|
|
public function __construct()
|
|
|
|
{
|
|
|
|
//
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Handle the event.
|
|
|
|
*
|
|
|
|
* @param JournalSaved $event
|
|
|
|
*
|
|
|
|
* @return void
|
|
|
|
*/
|
|
|
|
public function handle(JournalSaved $event)
|
|
|
|
{
|
|
|
|
$journal = $event->journal;
|
|
|
|
|
|
|
|
// get the event connected to this journal:
|
|
|
|
/** @var PiggyBankEvent $event */
|
2015-03-29 14:27:51 -05:00
|
|
|
$event = PiggyBankEvent::where('transaction_journal_id', $journal->id)->first();
|
|
|
|
if (is_null($event)) {
|
2015-03-03 01:46:14 -06:00
|
|
|
return;
|
|
|
|
}
|
2015-03-02 13:05:28 -06:00
|
|
|
$piggyBank = $event->piggyBank()->first();
|
|
|
|
$repetition = $piggyBank->piggyBankRepetitions()->relevantOnDate($journal->date)->first();
|
|
|
|
|
|
|
|
if (is_null($repetition)) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
$amount = 0;
|
|
|
|
/** @var Transaction $transaction */
|
|
|
|
foreach ($journal->transactions()->get() as $transaction) {
|
|
|
|
if ($transaction->account_id === $piggyBank->account_id) {
|
|
|
|
// this transaction is the relevant one.
|
|
|
|
$amount = floatval($transaction->amount);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// update current repetition:
|
|
|
|
$diff = $amount - $event->amount;
|
|
|
|
|
|
|
|
$repetition->currentamount += $diff;
|
|
|
|
$repetition->save();
|
|
|
|
|
|
|
|
|
|
|
|
$event->amount = $amount;
|
|
|
|
$event->save();
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|