From dc48335ed9cefde546973d4eae4e17f1f018ec57 Mon Sep 17 00:00:00 2001 From: James Cole Date: Sun, 15 Oct 2017 14:38:12 +0200 Subject: [PATCH] Remove double budget limits. --- app/Repositories/Budget/BudgetRepository.php | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/app/Repositories/Budget/BudgetRepository.php b/app/Repositories/Budget/BudgetRepository.php index 4961d8987d..c83d7eba73 100644 --- a/app/Repositories/Budget/BudgetRepository.php +++ b/app/Repositories/Budget/BudgetRepository.php @@ -588,6 +588,11 @@ class BudgetRepository implements BudgetRepositoryInterface */ public function updateLimitAmount(Budget $budget, Carbon $start, Carbon $end, int $amount): BudgetLimit { + // count the limits: + $limits = $budget->budgetlimits() + ->where('budget_limits.start_date', $start->format('Y-m-d')) + ->where('budget_limits.end_date', $end->format('Y-m-d')) + ->get(['budget_limits.*'])->count(); // there might be a budget limit for these dates: /** @var BudgetLimit $limit */ $limit = $budget->budgetlimits() @@ -595,6 +600,14 @@ class BudgetRepository implements BudgetRepositoryInterface ->where('budget_limits.end_date', $end->format('Y-m-d')) ->first(['budget_limits.*']); + // if more than 1 limit found, delete the others: + if ($limits > 1 && !is_null($limit)) { + $budget->budgetlimits() + ->where('budget_limits.start_date', $start->format('Y-m-d')) + ->where('budget_limits.end_date', $end->format('Y-m-d')) + ->where('budget_limits.id', '!=', $limit->id)->delete(); + } + // delete if amount is zero. if (!is_null($limit) && $amount <= 0.0) { $limit->delete();