- Will now return 0 when nothing to save or when target date is in the past.

- Will calculate correctly when date difference with target date is more than a year.
- Will always return a string
- Will do calculations using bcmath module.
This commit is contained in:
James Cole
2017-02-25 13:05:33 +01:00
parent c58745b6ce
commit 4f50689d0e

View File

@@ -108,17 +108,29 @@ class PiggyBank extends Model
return $value; return $value;
} }
public function getSuggestedMonthlyAmount() /**
* @return string
*/
public function getSuggestedMonthlyAmount(): string
{ {
$savePerMonth = '0';
if ($this->targetdate && $this->currentRelevantRep()->currentamount < $this->targetamount) { if ($this->targetdate && $this->currentRelevantRep()->currentamount < $this->targetamount) {
$thisMonth = Carbon::now()->month; $now = Carbon::now();
$targetMonth = $this->targetdate->month; $diffInMonths = $now->diffInMonths($this->targetdate, false);
$remainingAmount = $this->targetamount - $this->currentRelevantRep()->currentamount; $remainingAmount = bcsub($this->targetamount, $this->currentRelevantRep()->currentamount);
return $thisMonth < $targetMonth ? $remainingAmount / ($targetMonth - $thisMonth) : $remainingAmount; // more than 1 month to go and still need money to save:
if ($diffInMonths > 0 && bccomp($remainingAmount, '0') === 1) {
$savePerMonth = bcdiv($remainingAmount, strval($diffInMonths));
} }
return 0; // less than 1 month to go but still need money to save:
if ($diffInMonths === 0 && bccomp($remainingAmount, '0') === 1) {
$savePerMonth = $remainingAmount;
}
}
return $savePerMonth;
} }
/** /**