From 4f50689d0e96b85771f194277e5fba757c7c5981 Mon Sep 17 00:00:00 2001 From: James Cole Date: Sat, 25 Feb 2017 13:05:33 +0100 Subject: [PATCH] - 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. --- app/Models/PiggyBank.php | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/app/Models/PiggyBank.php b/app/Models/PiggyBank.php index b9113a8dbb..2bdbc32791 100644 --- a/app/Models/PiggyBank.php +++ b/app/Models/PiggyBank.php @@ -108,17 +108,29 @@ class PiggyBank extends Model return $value; } - public function getSuggestedMonthlyAmount() + /** + * @return string + */ + public function getSuggestedMonthlyAmount(): string { + $savePerMonth = '0'; if ($this->targetdate && $this->currentRelevantRep()->currentamount < $this->targetamount) { - $thisMonth = Carbon::now()->month; - $targetMonth = $this->targetdate->month; - $remainingAmount = $this->targetamount - $this->currentRelevantRep()->currentamount; + $now = Carbon::now(); + $diffInMonths = $now->diffInMonths($this->targetdate, false); + $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)); + } + + // less than 1 month to go but still need money to save: + if ($diffInMonths === 0 && bccomp($remainingAmount, '0') === 1) { + $savePerMonth = $remainingAmount; + } } - return 0; + return $savePerMonth; } /**