$journal->id, 'credit' => $credit ? $credit->getAmount():null, 'debit' => $debit ? $debit->getAmount():null, 'currency_code' => config('phpvms.currency'), 'memo' => $memo, 'post_date' => $post_date ?: Carbon::now(), 'transaction_group' => $transaction_group, ]; if($reference !== null) { $attrs['ref_class'] = \get_class($reference); $attrs['ref_class_id'] = $reference->id; } try { $transaction = $this->create($attrs); } catch (ValidatorException $e) { throw $e; } # Adjust the balance on the journal $balance = new Money($journal->balance); if($credit) { $balance = $balance->add($credit); } if($debit) { $balance = $balance->subtract($debit); } $journal->balance = $balance->getAmount(); $journal->save(); return $transaction; } /** * @param Journal $journal * @param Carbon|null $date * @return Money * @throws \UnexpectedValueException * @throws \InvalidArgumentException */ public function getBalance(Journal $journal, Carbon $date=null) { if(!$date) { $date = Carbon::now(); } $credit = $this->getCreditBalanceOn($journal, $date); $debit = $this->getDebitBalanceOn($journal, $date); return $credit->subtract($debit); } /** * Get the credit only balance of the journal based on a given date. * @param Journal $journal * @param Carbon $date * @return Money * @throws \UnexpectedValueException * @throws \InvalidArgumentException */ public function getCreditBalanceOn(Journal $journal, Carbon $date) { $balance = $this->findWhere([ 'journal_id' => $journal->id, ['post_date', '<=', $date] ], ['id', 'credit'])->sum('credit') ?: 0; return new Money($balance); } /** * @param Journal $journal * @param Carbon $date * @return Money * @throws \UnexpectedValueException * @throws \InvalidArgumentException */ public function getDebitBalanceOn(Journal $journal, Carbon $date): Money { $balance = $this->findWhere([ 'journal_id' => $journal->id, ['post_date', '<=', $date] ], ['id', 'debit'])->sum('debit') ?: 0; return new Money($balance); } }