diff --git a/annualgrantbudgets.php b/annualgrantbudgets.php index 7d7c1a1..d543b77 100644 --- a/annualgrantbudgets.php +++ b/annualgrantbudgets.php @@ -213,3 +213,42 @@ function annualgrantbudgets_civicrm_apiWrappers(&$wrappers, $apiRequest) { $wrappers[] = new CRM_AnnualGrantBudgets_APIWrapper(); } } + +/** + * Implements hook_civicrm_validateForm(). + * + * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_validateForm + * + */ +function annualgrantbudgets_civicrm_validateForm($formName, &$fields, &$files, &$form, &$errors) { + if ($formName == 'CRM_Grant_Form_Grant' && !($form->_action & CRM_Core_Action::DELETE)) { + if (empty($fields['financial_type_id']) + || empty($fields['status_id']) + || empty($fields['decision_date']) + || empty($fields['amount_granted']) + ) { + return; + } + $paidStatusID = CRM_Core_PseudoConstant::getKey( + 'CRM_Grant_DAO_Grant', + 'status_id', + 'Paid' + ); + if ($paidStatusID != $fields['status_id']) { + return; + } + $year = date('Y', strtotime($fields['decision_date'])); + $grantBudget = civicrm_api3('GrantBudget', 'getbudget', [ + 'financial_type_id' => $fields['financial_type_id'], + 'fiscal_year' => $year, + ]); + $grantBudget = reset($grantBudget['values']); + if ($grantBudget && !empty($grantBudget['id'])) { + $balanceAmount = CRM_Utils_Rule::cleanMoney($grantBudget['balance_amount']); + $amountGranted = CRM_Utils_Rule::cleanMoney($fields['amount_granted']); + if ($balanceAmount < $amountGranted) { + $errors['amount_granted'] = ts("The annual budget for this grant is {$grantBudget['budget']}. Grants totaling {$grantBudget['total_amount_granted']} have been made. {$grantBudget['balance_amount']} remains."); + } + } + } +}