public function close($id) { try { $user = User::find(Session::uid()); if (!$user->getId()) { throw new Exception('You have to be logged in to access user info!'); } $budget_id = (int) $id; $budget = new Budget(); if (!$budget->loadById($budget_id)) { throw new Exception('Invalid budget id'); } if ($budget->active != 1) { throw new Exception('This budget is already closed.'); } if ($user->getId() != $budget->receiver_id && $budget->giver_id != $user->getId()) { throw new Exception('Not enough rights'); } $budgetGiver = new User(); if (!$budgetGiver->findUserById($budget->giver_id)) { throw new Exception('Invalid giver id.'); } $budgetReceiver = new User(); if (!$budgetReceiver->findUserById($budget->receiver_id)) { throw new Exception('Invalid receiver id.'); } // all the child budgets are closed ? $childrenNotClosed = $budget->getChildrenNotClosed($budget->id); if ($childrenNotClosed != 0) { throw new Exception("This budget has one or more sub-allocated budget that are still active. " . "You may not close out this budget until the other budgets are closed out."); } // all the budgeted jobs are paid ? $feeAmountNotPaid = $this->getSumOfFeeNotPaidByBudget($budget->id); if ($feeAmountNotPaid !== null) { throw new Exception('Some fees are not paid.'); } $remainingFunds = $budget->getRemainingFunds(); if ($remainingFunds >= 0) { $budget->original_amount = $budget->amount; $budget->amount = $budget->original_amount - $remainingFunds; $budget->active = 0; $budgetReceiver->updateBudget(-$remainingFunds, $budget->id, false); $this->closeOutBudgetSource($remainingFunds, $budget, $budgetReceiver, $budgetGiver); if (!$budget->save('id')) { throw new Exception('Error in update budget.'); } } else { if ($user->getId() == $budget->receiver_id) { throw new Exception('Your budget is spent. Please contact the grantor (' . $budgetGiver->getNickname() . ') for additional funds.'); } $budget->original_amount = $budget->amount; $budget->amount = $budget->original_amount - $remainingFunds; $budget->active = 0; $budgetReceiver->updateBudget(-$remainingFunds, $budget->id, false); $this->closeOutBudgetSource($remainingFunds, $budget, $budgetReceiver, $budgetGiver); if (!$budget->save('id')) { throw new Exception('Error in update budget.'); } } $this->setOutput(array('success' => true, 'message' => 'Budget closed')); } catch (Exception $e) { return $this->setOutput(array('success' => false, 'message' => $e->getMessage())); } }