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

65 lines
1.8 KiB
PHP
Raw Normal View History

2016-02-05 05:08:25 -06:00
<?php
declare(strict_types = 1);
namespace FireflyIII\Handlers\Events;
2015-03-02 13:05:28 -06:00
use Auth;
2016-01-12 14:38:05 -06:00
use FireflyIII\Events\TransactionJournalStored;
2015-03-02 13:05:28 -06:00
use FireflyIII\Models\PiggyBank;
use FireflyIII\Models\PiggyBankEvent;
use FireflyIII\Models\TransactionJournal;
/**
* Class ConnectJournalToPiggyBank
*
* @package FireflyIII\Handlers\Events
*/
class ConnectJournalToPiggyBank
{
/**
2016-01-12 14:38:05 -06:00
* Connect a new transaction journal to any related piggy banks.
2015-03-02 13:05:28 -06:00
*
2016-01-12 14:38:05 -06:00
* @param TransactionJournalStored $event
2015-03-02 13:05:28 -06:00
*
2016-02-18 00:21:48 -06:00
* @return bool
2015-03-02 13:05:28 -06:00
*/
2016-02-18 00:21:48 -06:00
public function handle(TransactionJournalStored $event): bool
2015-03-02 13:05:28 -06:00
{
/** @var TransactionJournal $journal */
$journal = $event->journal;
$piggyBankId = $event->piggyBankId;
bcscale(2);
2015-03-02 13:05:28 -06:00
/** @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)) {
2016-01-13 00:16:29 -06:00
return true;
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)) {
2016-01-13 00:16:29 -06:00
return true;
2015-03-02 13:05:28 -06:00
}
2015-06-02 15:22:47 -05:00
bcscale(2);
$amount = TransactionJournal::amountPositive($journal);
// if piggy account matches source account, the amount is positive
if ($piggyBank->account_id == TransactionJournal::sourceAccount($journal)->id) {
2016-02-05 08:41:40 -06:00
$amount = bcmul($amount, '-1');
}
2015-06-02 15:22:47 -05:00
$repetition->currentamount = bcadd($repetition->currentamount, $amount);
2015-03-02 13:05:28 -06:00
$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
}
}