grantprograms.php 34.8 KB
Newer Older
1
<?php
2
require_once 'grantprograms.civix.php';
3 4
define('PAY_GRANTS', 5);
define('DELETE_GRANTS', 1);
5 6 7
define('PANEL_REVIEW_EVALUATION', 'civicrm_value_panel_review_evaluation_19');
define('GRANT_COMMITTEE_REVIEW', 'civicrm_value_grant_committee_review_20');
define('FULL_BOARD_REVIEW', 'civicrm_value_full_board_review_21');
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
/**
 * Implementation of hook_civicrm_config
 */
function grantprograms_civicrm_config(&$config) {
  _grantprograms_civix_civicrm_config($config);
}

/**
 * Implementation of hook_civicrm_xmlMenu
 *
 * @param $files array(string)
 */
function grantprograms_civicrm_xmlMenu(&$files) {
  _grantprograms_civix_civicrm_xmlMenu($files);
}

/**
 * Implementation of hook_civicrm_install
 */
function grantprograms_civicrm_install() {
Pradeep Nayak's avatar
Pradeep Nayak committed
28 29 30
  _grantprograms_civix_civicrm_install();
  $smarty = CRM_Core_Smarty::singleton();
  $config = CRM_Core_Config::singleton();
Mayur Jadhav's avatar
Mayur Jadhav committed
31
  $data = $smarty->fetch($config->extensionsDir . DIRECTORY_SEPARATOR . 'biz.jmaconsulting.grantprograms/sql/civicrm_msg_template.tpl');
Pradeep Nayak's avatar
Pradeep Nayak committed
32 33 34
  file_put_contents($config->uploadDir . "civicrm_data.sql", $data);
  CRM_Utils_File::sourceSQLFile(CIVICRM_DSN, $config->uploadDir . "civicrm_data.sql");
  return TRUE;
35 36 37 38 39 40
}

/**
 * Implementation of hook_civicrm_uninstall
 */
function grantprograms_civicrm_uninstall() {
Monish Deb's avatar
Monish Deb committed
41
  manageNavigationLinks('delete');
42 43 44 45 46 47 48
  return _grantprograms_civix_civicrm_uninstall();
}

/**
 * Implementation of hook_civicrm_enable
 */
function grantprograms_civicrm_enable() {
Mayur Jadhav's avatar
Mayur Jadhav committed
49
  $config = CRM_Core_Config::singleton();
50
  CRM_Utils_File::sourceSQLFile(CIVICRM_DSN, $config->extensionsDir . 'biz.jmaconsulting.grantprograms/sql/grantprograms_enable.sql');
Monish Deb's avatar
Monish Deb committed
51
  manageNavigationLinks('enable');
52 53 54 55 56 57 58
  return _grantprograms_civix_civicrm_enable();
}

/**
 * Implementation of hook_civicrm_disable
 */
function grantprograms_civicrm_disable() {
Mayur Jadhav's avatar
Mayur Jadhav committed
59
  $config = CRM_Core_Config::singleton();
60
  CRM_Utils_File::sourceSQLFile(CIVICRM_DSN, $config->extensionsDir . 'biz.jmaconsulting.grantprograms/sql/grantprograms_disable.sql');
Monish Deb's avatar
Monish Deb committed
61
  manageNavigationLinks('disable');
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
  return _grantprograms_civix_civicrm_disable();
}

/**
 * Implementation of hook_civicrm_upgrade
 *
 * @param $op string, the type of operation being performed; 'check' or 'enqueue'
 * @param $queue CRM_Queue_Queue, (for 'enqueue') the modifiable list of pending up upgrade tasks
 *
 * @return mixed  based on op. for 'check', returns array(boolean) (TRUE if upgrades are pending)
 *                for 'enqueue', returns void
 */
function grantprograms_civicrm_upgrade($op, CRM_Queue_Queue $queue = NULL) {
  return _grantprograms_civix_civicrm_upgrade($op, $queue);
}

/**
 * Implementation of hook_civicrm_managed
 *
 * Generate a list of entities to create/deactivate/delete when this module
 * is installed, disabled, uninstalled.
 */
function grantprograms_civicrm_managed(&$entities) {
  return _grantprograms_civix_civicrm_managed($entities);
}

88 89 90 91 92 93
/*
 * hook_civicrm_grantAssessment
 *
 * @param array $params to alter
 *
 */
Pradeep Nayak's avatar
Pradeep Nayak committed
94
function grantprograms_civicrm_grantAssessment(&$params) {
95 96 97
  if (!CRM_Utils_Array::value('grant_program_id', $params)) {
    return;
  }
98

Pradeep Nayak's avatar
Pradeep Nayak committed
99 100 101 102
  if (CRM_Utils_Array::value('custom', $params)) {
    $assessmentAmount = 0;
    foreach ($params['custom'] as $key => $value) {
      foreach($value as $fieldKey => $fieldValue) {
103
        if (in_array($fieldValue['table_name'], array(PANEL_REVIEW_EVALUATION, GRANT_COMMITTEE_REVIEW, FULL_BOARD_REVIEW))
Pradeep Nayak's avatar
Pradeep Nayak committed
104
          && CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $fieldValue['custom_field_id'], 'html_type') == 'Select') {
105 106 107
          if (is_nan((float)$fieldValue['value']) === FALSE) {
            $assessmentAmount += $fieldValue['value'];
          }
Pradeep Nayak's avatar
Pradeep Nayak committed
108 109 110 111 112 113 114
        }
      }
    }
    if ($assessmentAmount) {
      $params['assessment'] = $assessmentAmount;
    }
  }
Mayur Jadhav's avatar
Mayur Jadhav committed
115 116 117 118 119 120 121 122
  $grantProgramParams['id'] = $params['grant_program_id'];
  $grantProgram = CRM_Grant_BAO_GrantProgram::retrieve($grantProgramParams, CRM_Core_DAO::$_nullArray);
  if (!empty($grantProgram->grant_program_id)) {
    $sumAmountGranted = CRM_Core_DAO::singleValueQuery("SELECT SUM(amount_granted) as sum_amount_granted  FROM civicrm_grant WHERE status_id = " . CRM_Core_OptionGroup::getValue('grant_status', 'Paid', 'name') . " AND grant_program_id = {$grantProgram->grant_program_id} AND contact_id = {$params['contact_id']}");
    $grantThresholds = CRM_Core_OptionGroup::values('grant_thresholds', TRUE);
    if (!empty($sumAmountGranted)) {
      if ($sumAmountGranted >= $grantThresholds['Maximum Grant']) {
        $priority = 10;
123
      }
Mayur Jadhav's avatar
Mayur Jadhav committed
124 125
      elseif ($sumAmountGranted > 0) {
        $priority = 0;
126
      }
127
    }
Mayur Jadhav's avatar
Mayur Jadhav committed
128 129 130
    else {
      $priority = -10;
    }
Mayur Jadhav's avatar
Mayur Jadhav committed
131
    if (array_key_exists('assessment', $params) && $params['adjustment_value']) {
Mayur Jadhav's avatar
Mayur Jadhav committed
132 133
      if ($params['assessment'] != 0) {
        $params['assessment'] = $params['assessment'] - $priority;
134 135 136
      }
    }
  }
137

138 139 140 141
  $defaults = array();
  $programParams = array('id' => $params['grant_program_id']);
  $grantProgram = CRM_Grant_BAO_GrantProgram::retrieve($programParams, $defaults);
  $algoType = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $grantProgram->allocation_algorithm, 'grouping');
Mayur Jadhav's avatar
Mayur Jadhav committed
142
  $grantStatuses = CRM_Core_OptionGroup::values('grant_status', TRUE);
Pradeep Nayak's avatar
Pradeep Nayak committed
143
  if ($algoType == 'immediate' && !CRM_Utils_Array::value('manualEdit', $params) && $params['status_id'] == CRM_Utils_Array::value('Eligible', $grantStatuses)) {
144 145 146 147
    $params['amount_granted'] = quickAllocate($grantProgram, $params);
    if (empty($params['amount_granted'])) {
      unset($params['amount_granted']);
    }
148
  }
149
}
Pradeep Nayak's avatar
Pradeep Nayak committed
150 151 152 153 154 155

/**
 * Algorithm for quick allocation
 *
 */
function quickAllocate($grantProgram, $value) {
156
  $grantThresholds = CRM_Core_OptionGroup::values('grant_thresholds', TRUE);
Mayur Jadhav's avatar
Mayur Jadhav committed
157
  $amountGranted = NULL;
158
  $grant_id = NULL;
159
  if (CRM_Utils_Array::value('assessment', $value)) {
Mayur Jadhav's avatar
Mayur Jadhav committed
160 161
    $userparams['contact_id'] = $value['contact_id'];
    $userparams['grant_program_id'] = $grantProgram->id;
162 163 164 165
    if (!empty($value['id'])) {
      $grant_id = $value['id'];
    }
    $userAmountGranted = CRM_Grant_BAO_GrantProgram::getUserAllocatedAmount($userparams, $grant_id);
Mayur Jadhav's avatar
Mayur Jadhav committed
166
    $defalutGrantedAmount = CRM_Grant_BAO_GrantProgram::getCurrentGrantAmount($grant_id);
Mayur Jadhav's avatar
Mayur Jadhav committed
167
    $amountEligible = $grantThresholds['Maximum Grant'] - $userAmountGranted;
Mayur Jadhav's avatar
Mayur Jadhav committed
168 169 170
    if ($amountEligible > $grantProgram->remainder_amount) {
      $amountEligible = $grantProgram->remainder_amount;
    }
171
    $value['amount_total'] = str_replace(',', '', $value['amount_total']);
172
    $requestedAmount = CRM_Utils_Money::format((($value['assessment']/100) * $value['amount_total'] * ($grantThresholds['Funding factor'] / 100)), NULL, NULL, TRUE);
173 174 175 176
    // Don't grant more money than originally requested
    if ($requestedAmount > $value['amount_total']) {
    	$requestedAmount = $value['amount_total'];
    }
Mayur Jadhav's avatar
Mayur Jadhav committed
177 178
    if ($requestedAmount > $amountEligible) {
      $requestedAmount = $amountEligible;
179
    }
Mayur Jadhav's avatar
Mayur Jadhav committed
180 181
    if ($requestedAmount > 0) {
      $remainderDifference = $requestedAmount - $defalutGrantedAmount;
Mayur Jadhav's avatar
Mayur Jadhav committed
182 183 184
      if ($remainderDifference < $grantProgram->remainder_amount) {
        $amountGranted = $requestedAmount;
      }
Pradeep Nayak's avatar
Pradeep Nayak committed
185 186
    }
  }
187

Pradeep Nayak's avatar
Pradeep Nayak committed
188
  //Update grant program
Mayur Jadhav's avatar
Mayur Jadhav committed
189
  if ($amountGranted > 0) {
Mayur Jadhav's avatar
Mayur Jadhav committed
190
    $grantProgramParams['remainder_amount'] = $grantProgram->remainder_amount - $remainderDifference;
Mayur Jadhav's avatar
Mayur Jadhav committed
191 192 193 194
    $grantProgramParams['id'] =  $grantProgram->id;
    $ids['grant_program']     =  $grantProgram->id;
    CRM_Grant_BAO_GrantProgram::create($grantProgramParams, $ids);
  }
Pradeep Nayak's avatar
Pradeep Nayak committed
195 196 197 198 199 200 201 202 203 204 205 206 207 208
  return $amountGranted;
}

/**
 * Get action Links
 *
 * @return array (reference) of action links
 */
function &links() {
  $_links = array(
    CRM_Core_Action::VIEW  => array(
      'name'  => ts('View'),
      'url'   => 'civicrm/grant_program',
      'qs'    => 'action=view&id=%%id%%&reset=1',
209
      'title' => ts('View Grant Program')
Pradeep Nayak's avatar
Pradeep Nayak committed
210 211 212 213 214
    ),
    CRM_Core_Action::UPDATE  => array(
      'name'  => ts('Edit'),
      'url'   => 'civicrm/grant_program',
      'qs'    => 'action=update&id=%%id%%&reset=1',
215
      'title' => ts('Edit Grant Program')
Pradeep Nayak's avatar
Pradeep Nayak committed
216 217 218 219 220
    ),
    CRM_Core_Action::DELETE  => array(
      'name'  => ts('Delete'),
      'url'   => 'civicrm/grant_program',
      'qs'    => 'action=delete&id=%%id%%&reset=1',
221
      'title' => ts('Delete')
Pradeep Nayak's avatar
Pradeep Nayak committed
222 223 224 225
    ),
    CRM_Core_Action::ADD  => array(
      'name'  => ts('Allocate Approved (Trial)'),
      'url'   => 'civicrm/grant_program',
Monish Deb's avatar
Monish Deb committed
226
      'qs'    => 'id=allocation',
227
      'extra' => 'onclick="actionTask(\'allocation\', %%id%%); return false;"',
228
      'title' => ts('Allocate Approved (Trial)')
Pradeep Nayak's avatar
Pradeep Nayak committed
229 230 231 232 233
    ),
    CRM_Core_Action::BROWSE  => array(
      'name'  => ts('Finalize Approved Allocations'),
      'url'   => 'civicrm/grant_program',
      'qs'    => '#',
234
      'extra' => 'onclick="actionTask(\'finalize\', %%id%%); return false;"',
235
      'title' => ts('Finalize Approved Allocations')
Pradeep Nayak's avatar
Pradeep Nayak committed
236 237
    ),
    CRM_Core_Action::MAP  => array(
Mayur Jadhav's avatar
Mayur Jadhav committed
238
      'name'  => ts('Mark remaining unapproved Grants as Ineligible'),
Pradeep Nayak's avatar
Pradeep Nayak committed
239 240
      'url'   => 'civicrm/grant_program',
      'qs'    => '#',
241
      'extra' => 'onclick="actionTask(\'reject\', %%id%%); return false;"',
242
      'title' => ts('Mark remaining unapproved Grants as Ineligible')
Pradeep Nayak's avatar
Pradeep Nayak committed
243 244 245
    ),
  );
  return $_links;
246 247
}

Edsel's avatar
Edsel committed
248
function grantprograms_civicrm_permission(&$permissions) {
Pradeep Nayak's avatar
Pradeep Nayak committed
249 250
  $prefix = ts('CiviCRM Grant Program') . ': '; // name of extension or module
  $permissions['edit grant finance'] = $prefix . ts('edit grant finance');
251
  $permissions['edit grant program'] = $prefix . ts('edit grant programs in CiviGrant');
252 253 254
  $permissions['cancel payments in CiviGrant'] = $prefix . ts('cancel payments in CiviGrant');
  $permissions['edit payments in CiviGrant'] = $prefix . ts('edit payments in CiviGrant');
  $permissions['create payments in CiviGrant'] = $prefix . ts('create payments in CiviGrant');
Pradeep Nayak's avatar
Pradeep Nayak committed
255
}
256 257 258 259 260 261 262 263 264 265 266 267

function grantprograms_civicrm_preProcess($formName, &$form) {
  if ($formName == 'CRM_Grant_Form_Search') {
    $programID = CRM_Utils_Request::retrieve('pid', 'String',
      CRM_Core_DAO::$_nullObject
    );
    if ($programID) {
      $form->_formValues['grant_program_id'] = $programID;
      $form->defaults['grant_program_id'] = $programID;
    }
  }
}
268

269 270
/*
 * hook_civicrm_buildForm civicrm hook
271
 *
272 273 274 275 276
 * @param string $formName form name
 * @param object $form form object
 *
*/
function grantprograms_civicrm_buildForm($formName, &$form) {
277 278 279 280 281 282 283
  if ($formName == 'CRM_Activity_Form_Activity'
    && ($form->getVar('_action') == CRM_Core_Action::UPDATE || $form->getVar('_action') == CRM_Core_Action::VIEW)) {
    $activityType = CRM_Core_PseudoConstant::activityType();
    $activityValues = $form->getVar('_values');
    if (array_search('Grant Status Change', $activityType) != $activityValues['activity_type_id']) {
      return FALSE;
    }
284
    $grantUrl = CRM_Utils_System::url('civicrm/contact/view/grant',
285 286 287
      'reset=1&action=view&id=' . $activityValues['source_record_id'] . '&cid=' . current($activityValues['assignee_contact']));
    $form->assign('grantUrl', $grantUrl);
  }
288

289

Mayur Jadhav's avatar
Mayur Jadhav committed
290
  if ($formName == 'CRM_Grant_Form_Grant' && ($form->getVar('_action') != CRM_Core_Action::DELETE)) {
Mayur Jadhav's avatar
Mayur Jadhav committed
291 292 293
    $form->_key = CRM_Utils_Request::retrieve('key', 'String', $form);
    $form->_next = CRM_Utils_Request::retrieve('next', 'Positive', $form);
    $form->_prev = CRM_Utils_Request::retrieve('prev', 'Positive', $form);
Mayur Jadhav's avatar
Mayur Jadhav committed
294 295
    $form->_searchGrants = CRM_Utils_Request::retrieve('searchGrants', 'String', $form);
    $form->_ncid = CRM_Utils_Request::retrieve('ncid', 'String', $form);
Mayur Jadhav's avatar
Mayur Jadhav committed
296
    if (CRM_Utils_Request::retrieve('context', 'String', $form) == 'search' && isset($form->_next)) {
297
      $form->addButtons(array(
Mayur Jadhav's avatar
Mayur Jadhav committed
298
        array ('type' => 'upload',
299
          'name' => ts('Save'),
Mayur Jadhav's avatar
Mayur Jadhav committed
300 301 302
          'isDefault' => true),
        array ('type' => 'submit',
          'name' => ts('Save and Next'),
303
          'subName' => 'savenext'),
Mayur Jadhav's avatar
Mayur Jadhav committed
304
        array ('type' => 'upload',
305
          'name' => ts('Save and New'),
Mayur Jadhav's avatar
Mayur Jadhav committed
306 307
          'js' => array('onclick' => "return verify();"),
          'subName' => 'new' ),
308
        array ('type' => 'cancel',
Mayur Jadhav's avatar
Mayur Jadhav committed
309
          'name' => ts('Cancel')),
310
        )
Mayur Jadhav's avatar
Mayur Jadhav committed
311 312
      );
    }
313 314 315
      CRM_Core_Region::instance('page-body')->add(array(
        'template' => 'CRM/Grant/Form/GrantExtra.tpl',
      ));
316
    $form->_reasonGrantRejected = CRM_Core_OptionGroup::values('reason_grant_ineligible');
317 318
    $form->add('select',
      'grant_rejected_reason_id',
319
      ts('Reason Grant Ineligible'),
320
      array('' => ts('- select -')) + $form->_reasonGrantRejected,
321 322
      FALSE
    );
323

324
    $form->_reasonGrantIncomplete = CRM_Core_OptionGroup::values('reason_grant_incomplete');
325 326
    $form->add('select',
      'grant_incomplete_reason_id',
327
      ts('Reason Grant Incomplete'),
328
      array('' => ts('- select -')) + $form->_reasonGrantIncomplete,
329 330 331
      FALSE
    );

332 333
    $form->add('select',
      'grant_program_id',
334
      ts('Grant Programs'),
Monish Deb's avatar
Monish Deb committed
335
      array('' => ts('- select -')) + CRM_Grant_BAO_GrantProgram::getGrantPrograms(),
336 337
      TRUE
    );
338

Pradeep Nayak's avatar
Pradeep Nayak committed
339
    $showFields = FALSE;
340

Pradeep Nayak's avatar
Pradeep Nayak committed
341 342 343 344 345 346 347 348 349 350 351 352
    if ( $form->getVar('_action') == CRM_Core_Action::UPDATE && $form->getVar('_id')) {
      $grantStatuses = CRM_Core_OptionGroup::values('grant_status');
      $grantWeight = CRM_Core_OptionGroup::values('grant_status', FALSE, FALSE, FALSE, NULL, 'weight');
      $currentStatus = $form->_defaultValues['status_id'];
      $coreStatus = array(
        array_search('Eligible', $grantStatuses),
        array_search('Awaiting Information', $grantStatuses) => array('Eligible', '', ''),
        array_search('Withdrawn', $grantStatuses),
      );

        $currentStatusWeight = $grantWeight[$currentStatus] + 1;
        foreach ($grantStatuses as $statusId => $statusName) {
353
          if ((($grantWeight[$currentStatus] >= 7 && $statusId == array_search('Ineligible', $grantStatuses))
Pradeep Nayak's avatar
Pradeep Nayak committed
354 355 356 357 358 359 360 361 362 363
               || ($grantWeight[$currentStatus] >= 1 && $grantWeight[$currentStatus] <= 7 && $grantWeight[$statusId] > 7 && $statusId != array_search('Ineligible', $grantStatuses))
              || $grantWeight[$currentStatus] > 7
              || $grantWeight[$statusId] < $grantWeight[$currentStatus])
              && $statusId != $currentStatus
              && $statusId != array_search('Withdrawn', $grantStatuses)
              && $currentStatusWeight != $grantWeight[$statusId]) {
            unset($grantStatuses[$statusId]);
          }
        }
      $form->removeElement('status_id');
Monish Deb's avatar
Monish Deb committed
364 365 366 367 368 369
      if ($grantStatuses[$currentStatus] == 'Paid') {
        $approvedStatusID = array_search('Approved for Payment', $grantStatuses);
        if (!empty($grantStatuses[$approvedStatusID])) {
          unset($grantStatuses[$approvedStatusID]);
        }
      }
370

Pradeep Nayak's avatar
Pradeep Nayak committed
371 372 373 374 375 376
      $element = $form->add('select', 'status_id', ts('Grant Status'),
        $grantStatuses,
        TRUE
      );
      if ($grantStatuses[$currentStatus] == 'Withdrawn') {
        $element->freeze();
377
      }
Pradeep Nayak's avatar
Pradeep Nayak committed
378
    }
Monish Deb's avatar
Monish Deb committed
379 380 381 382 383 384
    elseif ($form->getVar('_action') == CRM_Core_Action::ADD) {
      $grantStatuses = CRM_Core_OptionGroup::values('grant_status');
      unset($grantStatuses[array_search('Withdrawn', $grantStatuses)]);
      $form->add('select', 'status_id', ts('Grant Status'), $grantStatuses, TRUE);
    }

Monish Deb's avatar
Monish Deb committed
385 386
    CRM_Grant_Form_Task_GrantPayment::buildPaymentBlock($form, FALSE);

Pradeep Nayak's avatar
Pradeep Nayak committed
387 388 389 390
    if ($form->getVar('_id')) {
      if (CRM_Core_Permission::check('administer CiviGrant')) {
        $form->add('text', 'assessment', ts('Assessment'));
      }
391

Pradeep Nayak's avatar
Pradeep Nayak committed
392 393 394 395
      // freeze fields based on permissions
      if (CRM_Core_Permission::check('edit grants') && !CRM_Core_Permission::check('edit grant finance')) {
        if (CRM_Utils_Array::value('amount_granted', $form->_elementIndex)) {
          $form->_elements[$form->_elementIndex['amount_granted']]->freeze();
396 397 398 399 400 401 402 403 404
        }
        if (CRM_Utils_Array::value('assessment', $form->_elementIndex)) {
          $form->_elements[$form->_elementIndex['assessment']]->freeze();
        }
        if (CRM_Utils_Array::value('amount_total', $form->_elementIndex)) {
          $form->_elements[$form->_elementIndex['amount_total']]->freeze();
        }
        if (CRM_Utils_Array::value('amount_requested', $form->_elementIndex)) {
          $form->_elements[$form->_elementIndex['amount_requested']]->freeze();
Pradeep Nayak's avatar
Pradeep Nayak committed
405 406 407 408 409 410
        }
        CRM_Core_Region::instance('page-body')->add(array(
          'template' => 'CRM/Grant/Form/Freeze.tpl',
        ));
      }
      $showFields = TRUE;
411
    }
Pradeep Nayak's avatar
Pradeep Nayak committed
412
    $form->assign('showFields', $showFields);
413
  }
Monish Deb's avatar
Monish Deb committed
414
  if ($formName == "CRM_Grant_Form_Search" || $formName == 'CRM_Contact_Form_Search_Advanced') {
415
    $grantPrograms = CRM_Grant_BAO_GrantProgram::getGrantPrograms();
416 417
    $form->add('select',
      'grant_program_id',
418 419 420
      ts('Grant Programs'),
      array('' => ts('- select -')) + $grantPrograms
    );
421 422 423 424 425 426 427 428
    $form->add('text',
      'grant_amount_total_low',
      ts('From'),
      array('size' => 8, 'maxlength' => 8)
    );
    $form->addRule('grant_amount_total_low',
      ts('Please enter a valid money value (e.g. %1).',
        array(1 => CRM_Utils_Money::format('9.99', ' '))),
429 430
      'money'
    );
431 432 433
    $form->add('text',
      'grant_amount_total_high',
      ts('To'),
434
      array('size' => 8, 'maxlength' => 8)
435 436 437 438
    );
    $form->addRule('grant_amount_total_high',
      ts('Please enter a valid money value (e.g. %1).',
        array(1 => CRM_Utils_Money::format('99.99', ' '))),
439 440
      'money'
    );
441 442 443
    $form->add('text',
      'grant_assessment_low',
      ts('From'),
444 445
      array('size' => 9, 'maxlength' => 9)
    );
446 447 448 449

    $form->add('text',
      'grant_assessment_high',
      ts('To'),
450 451
      array('size' => 9, 'maxlength' => 9)
    );
452 453 454
    $form->add('text',
      'grant_amount_low',
      ts('From'),
455
      array('size' => 8, 'maxlength' => 8)
456 457 458 459
    );
    $form->addRule('grant_amount_low',
      ts('Please enter a valid money value (e.g. %1).',
        array(1 => CRM_Utils_Money::format('9.99', ' '))),
460 461
      'money'
    );
Pradeep Nayak's avatar
Pradeep Nayak committed
462

463 464 465
    $form->add('text',
      'grant_amount_high',
      ts('To'),
466 467
      array('size' => 8, 'maxlength' => 8)
    );
468 469 470
    $form->addRule('grant_amount_high',
      ts('Please enter a valid money value (e.g. %1).',
        array(1 => CRM_Utils_Money::format('99.99', ' '))),
471 472
      'money'
    );
473
  }
474

Edsel's avatar
Edsel committed
475
  if ($formName == 'CRM_Grant_Form_Search' && $form->get('context') == 'dashboard') {
Pradeep Nayak's avatar
Pradeep Nayak committed
476 477 478 479
    //Version of grant program listings
    $grantProgram = array();
    require_once 'CRM/Grant/DAO/GrantProgram.php';
    $dao = new CRM_Grant_DAO_GrantProgram();
480

Pradeep Nayak's avatar
Pradeep Nayak committed
481 482
    $dao->orderBy('label');
    $dao->find();
483

Pradeep Nayak's avatar
Pradeep Nayak committed
484 485 486 487
    while ($dao->fetch()) {
      $grantProgram[$dao->id] = array();
      CRM_Core_DAO::storeValues( $dao, $grantProgram[$dao->id]);
      $action = array_sum(array_keys(links()));
488
      $grantProgram[$dao->id]['action'] = CRM_Core_Action::formLink(links(), $action,
Pradeep Nayak's avatar
Pradeep Nayak committed
489 490
                                          array('id' => $dao->id));
    }
491
    $grantType   = CRM_Core_OptionGroup::values('grant_type');
492
    $grantStatus = CRM_Grant_BAO_GrantProgram::grantProgramStatus( );
Pradeep Nayak's avatar
Pradeep Nayak committed
493
    foreach ( $grantProgram as $key => $value ) {
Edsel's avatar
Edsel committed
494
      $grantProgram[$key]['grant_type_id'] = $grantType[$grantProgram[$key]['grant_type_id']];
Pradeep Nayak's avatar
Pradeep Nayak committed
495 496 497 498 499 500
      $grantProgram[$key]['status_id'] = $grantStatus[CRM_Grant_BAO_GrantProgram::getOptionValue($grantProgram[$key]['status_id'])];
    }
    $form->assign('programs',$grantProgram );
    $form->assign('context', 'dashboard');
  }

Edsel's avatar
Edsel committed
501 502
  if ($formName == 'CRM_Grant_Form_Grant' && ($form->getVar('_action') & CRM_Core_Action::UPDATE) && $form->getVar('_id') && $form->getVar('_name') == 'Grant') {
    // RG-116 Hide attachments on edit
503
    $form->assign('hideAttachments', 1);
504 505 506
    $form->add('text', 'prev_assessment', ts('Prior Year\'s Assessment'));
    $priority = CRM_Grant_BAO_GrantProgram::getPriorities($form->_defaultValues['grant_program_id'], $form->getVar('_contactID'));
    $form->setDefaults(array('prev_assessment' => $priority));
507 508
    //Freeze Prior Year's Assessment field
    $form->_elements[$form->_elementIndex['prev_assessment']]->freeze();
Edsel's avatar
Edsel committed
509
    // Filter out grant being edited from search results
510
    $form->assign('grant_id', $form->getVar('_id'));
511 512 513 514 515 516 517 518 519 520 521
  }

  // Expose value field for option value edit
  if ($formName == 'CRM_Admin_Form_Options') {
    $form->add('text',
      'value',
      ts('Value'),
      CRM_Core_DAO::getAttribute('CRM_Core_DAO_OptionValue', 'value'),
      true
    );
  }
522 523
}

Edsel's avatar
Edsel committed
524
function grantprograms_civicrm_pageRun( &$page ) {
525 526 527 528 529 530
  if ($page->getVar('_name') == "CRM_Grant_Page_Tab") {
    $contactId = $page->getVar('_contactId');
    if ($contactId) {
      $name = CRM_Contact_BAO_Contact::getDisplayAndImage($contactId);
      CRM_Utils_System::setTitle('Grant - '.$name[0] );
    }
Mayur Jadhav's avatar
Mayur Jadhav committed
531
    $smarty = CRM_Core_Smarty::singleton();
532
    if ($smarty->_tpl_vars['action'] & CRM_Core_Action::VIEW) {
Mayur Jadhav's avatar
Mayur Jadhav committed
533
      $smarty->_tpl_vars['assessment'] = CRM_Core_DAO::getFieldValue('CRM_Grant_DAO_Grant', $smarty->_tpl_vars['id'], 'assessment', 'id');
534 535
      $grantProgram = CRM_Core_DAO::getFieldValue('CRM_Grant_DAO_Grant', $smarty->_tpl_vars['id'], 'grant_program_id', 'id');
      $smarty->_tpl_vars['prev_assessment'] = CRM_Grant_BAO_GrantProgram::getPriorities($grantProgram, $smarty->_tpl_vars['contactId']);
Mayur Jadhav's avatar
Mayur Jadhav committed
536 537 538 539
      CRM_Core_Region::instance('page-body')->add(array(
        'template' => 'CRM/Grant/Page/GrantExtra.tpl',
      ));
    }
540
  }
541

542 543 544 545 546 547 548
  if ($page->getVar('_name') == "CRM_Grant_Page_DashBoard") {
    $page->assign('grantSummary', CRM_Grant_BAO_GrantPayment::getGrantSummary(CRM_Core_Permission::check('administer CiviCRM')));
  }
}

function grantprograms_civicrm_alterTemplateFile($formName, &$form, $context, &$tplName) {
  if ($tplName == 'CRM/Grant/Page/DashBoard.tpl') {
Monish Deb's avatar
Monish Deb committed
549
    $tplName = 'CRM/Grant/Page/DashboardExtra.tpl';
550 551 552 553 554 555 556
  }
}

function grantprograms_civicrm_queryObjects(&$queryObjects, $type) {
  if ($type == 'Contact') {
     $queryObjects[] = new CRM_Grantprograms_Query();
   }
Edsel's avatar
Edsel committed
557
}
558

559 560 561 562 563 564 565 566 567
/*
 * hook_civicrm_validate
 *
 * @param string $formName form name
 * @param array $fields form submitted values
 * @param array $files file properties as sent by PHP POST protocol
 * @param object $form form object
 *
 */
Monish Deb's avatar
Monish Deb committed
568
function grantprograms_civicrm_validateForm($formName, &$fields, &$files, &$form, &$errors) {
569 570
  if ($formName == "CRM_Admin_Form_Options" && ($form->getVar('_action') & CRM_Core_Action::DELETE) && $form->getVar('_gName') == "grant_type") {
    $defaults = array();
Mayur Jadhav's avatar
Mayur Jadhav committed
571 572 573 574
    $valId = $form->getVar('_values');
    $isGrantPresent = CRM_Core_DAO::getFieldValue('CRM_Grant_DAO_Grant', $valId['value'], 'id', 'grant_type_id');
    $isProgramPresent = CRM_Core_DAO::getFieldValue('CRM_Grant_DAO_GrantProgram', $form->getVar('_id'), 'id', 'grant_type_id');
    if ($isGrantPresent || $isProgramPresent) {
575
      $errors[''] = ts('Error');
Mayur Jadhav's avatar
Mayur Jadhav committed
576 577 578 579 580 581 582
      if ($isGrantPresent) {
        $error[] = l('Grant(s)', 'civicrm/grant?reset=1');
      }
      if ($isProgramPresent) {
        $error[] = l('Grant Program(s)', 'civicrm/grant_program?reset=1');
      }
      CRM_Core_Session::setStatus(ts('You cannot delete this Grant Type because '. implode(' and ', $error ) .' are currently using it.'), ts("Sorry"), "error");
583 584
    }
  }
Monish Deb's avatar
Monish Deb committed
585
  if ($formName == 'CRM_Grant_Form_Grant') {
586
    $defaults = array();
587
    $params['id'] = $form->_submitValues['grant_program_id'];
588
    CRM_Grant_BAO_GrantProgram::retrieve($params, $defaults);
Pradeep Nayak's avatar
Pradeep Nayak committed
589
    if (array_key_exists('amount_granted', $form->_submitValues) && CRM_Utils_Array::value('remainder_amount', $defaults) < $form->_submitValues['amount_granted']) {
Edsel's avatar
Edsel committed
590
      $errors['amount_granted'] = ts('You need to increase the Grant Program Remainder Amount');
591
    }
592

593 594 595
    if (CRM_Utils_Array::value('amount_granted', $fields) && $fields['amount_granted'] > 0 && !CRM_Utils_Array::value('financial_type_id', $fields) && CRM_Utils_Array::value('money_transfer_date', $fields)) {
      $errors['financial_type_id'] = ts('Financial Type is a required field if Amount is Granted');
    }
596
  }
Pradeep Nayak's avatar
Pradeep Nayak committed
597
  if ($formName == 'CRM_Grant_Form_Search') {
598
    if (isset($fields['task']) && CRM_Utils_Array::value('task', $fields) == PAY_GRANTS || CRM_Utils_Array::value('task', $fields) == DELETE_GRANTS) {
Pradeep Nayak's avatar
Pradeep Nayak committed
599 600 601
      foreach ($fields as $fieldKey => $fieldValue) {
        if (strstr($fieldKey, 'mark_x_')) {
          $grantID = ltrim( $fieldKey, 'mark_x_' );
Mayur Jadhav's avatar
Mayur Jadhav committed
602
          if ($fields['task'] == PAY_GRANTS) {
Monish Deb's avatar
Monish Deb committed
603
            $grantDetails = civicrm_api3('Grant', 'get', ['id' => $grantID])['values'];
Mayur Jadhav's avatar
Mayur Jadhav committed
604 605 606 607 608 609 610 611 612 613 614 615 616
            if (!$grantDetails[$grantID]['amount_granted']) {
              $errors['task'] = ts('Payments are only possible when there is an amount owing.');
              break;
            }
          }
          elseif ($fields['task'] == DELETE_GRANTS) {
            $params['entity_table'] = 'civicrm_grant';
            $params['entity_id'] = $grantID;
            $grantPayment = CRM_Grant_BAO_EntityPayment::retrieve($params, $defaults = CRM_Core_DAO::$_nullArray);
            if ($grantPayment) {
              $errors['task'] = ts('You cannot delete grant because grant payment is currently using it.');
              break;
            }
Pradeep Nayak's avatar
Pradeep Nayak committed
617 618 619 620
          }
        }
      }
    }
621
  }
622
  return empty($errors) ? TRUE : $errors;
Pradeep Nayak's avatar
Pradeep Nayak committed
623 624
}

Pradeep Nayak's avatar
Pradeep Nayak committed
625
function grantprograms_civicrm_pre($op, $objectName, $id, &$params) {
Monish Deb's avatar
Monish Deb committed
626 627 628
  if ($objectName == 'Grant' && in_array($op, ['edit', 'create'])) {
    $grantStatuses = CRM_Core_OptionGroup::values('grant_status');
    $grantStatusApproved = array_search('Approved for Payment', $grantStatuses);
Mayur Jadhav's avatar
Mayur Jadhav committed
629
    $calculateAssessment = FALSE;
Monish Deb's avatar
Monish Deb committed
630 631 632 633 634 635
    $previousGrant = [];
    if ($op == 'edit') {
      $previousGrant = civicrm_api3('Grant', 'getsingle', ['id' => $id]);
      $sendMail = (CRM_Utils_Array::value('status_id', $params) !== $previousGrant['status_id']);
      $calculateAssessment = (CRM_Utils_Array::value('assessment', $params) == $previousGrant['assessment']);
      $params['id'] = $id;
Mayur Jadhav's avatar
Mayur Jadhav committed
636
    }
Monish Deb's avatar
Monish Deb committed
637
    if (($grantStatusApproved == CRM_Utils_Array::value('status_id', $params) && empty($params['decision_date'])) ||
638
      (empty($previousGrant['decision_date']) && CRM_Utils_Array::value('status_id', $previousGrant) != CRM_Utils_Array::value('status_id', $params))
639
    ) {
Pradeep Nayak's avatar
Pradeep Nayak committed
640 641
      $params['decision_date'] = date('Ymd');
    }
Monish Deb's avatar
Monish Deb committed
642 643 644

    if ((empty($params['assessment']) || $calculateAssessment)) {
      $params['assessment'] = $params['amount_total'];
Pradeep Nayak's avatar
Pradeep Nayak committed
645
    }
646

Monish Deb's avatar
Monish Deb committed
647 648 649 650 651 652 653
    if ($op == 'edit') {
      if (!CRM_Utils_Array::value('allocation', $params) &&
        !empty($previousGrant['amount_granted']) &&
        CRM_Utils_Array::value('amount_granted', $params) != $previousGrant['amount_granted'] &&
        !empty($previousGrant['grant_program_id'])
      ) {
        $programParams = ['id' => $previousGrant['grant_program_id']];
Mayur Jadhav's avatar
Mayur Jadhav committed
654
        $grantProgram = CRM_Grant_BAO_GrantProgram::retrieve($programParams, CRM_Core_DAO::$_nullArray);
Monish Deb's avatar
Monish Deb committed
655 656
        $grantProgram->remainder_amount -= CRM_Utils_Rule::cleanMoney($params['amount_granted']) - $previousGrant['amount_granted'];
        $grantProgram->save();
657 658
        $params['manualEdit'] = TRUE;
      }
Monish Deb's avatar
Monish Deb committed
659
      CRM_Core_Smarty::singleton()->assign('previousGrant', $previousGrant);
660
    }
Monish Deb's avatar
Monish Deb committed
661
    elseif (!empty($params['amount_granted'])) {
Mayur Jadhav's avatar
Mayur Jadhav committed
662 663
      $params['manualEdit'] = TRUE;
    }
Monish Deb's avatar
Monish Deb committed
664
    CRM_Core_BAO_Cache::setItem($params, 'grant params', __FUNCTION__);
Pradeep Nayak's avatar
Pradeep Nayak committed
665 666 667
  }
}

Monish Deb's avatar
Monish Deb committed
668

Pradeep Nayak's avatar
Pradeep Nayak committed
669
function grantprograms_civicrm_post($op, $objectName, $objectId, &$objectRef) {
Monish Deb's avatar
Monish Deb committed
670
  if ($objectName == 'Grant' && in_array($op, ['edit', 'create'])) {
Monish Deb's avatar
Monish Deb committed
671
    $params = CRM_Core_BAO_Cache::getItem("grant params", 'grantprograms_civicrm_pre');
Monish Deb's avatar
Monish Deb committed
672 673 674 675 676
    $smarty = CRM_Core_Smarty::singleton();
    $previousGrant = $smarty->get_template_vars('previousGrant');
    // core bug $op always return 'create'
    $op = ($op == 'create' && !empty($previousGrant)) ? 'edit' : $op;
    $grantStatuses = CRM_Core_OptionGroup::values('grant_status');
Mayur Jadhav's avatar
Mayur Jadhav committed
677
    $grantProgram  = new CRM_Grant_DAO_GrantProgram();
Monish Deb's avatar
Monish Deb committed
678 679 680 681 682 683 684 685 686 687
    if ($grantProgram->id = CRM_Utils_Array::value('grant_program_id', $params)) {
      $grantProgram->find(TRUE);
      $isAutoEmail = (!empty($grantProgram->is_auto_email));
      if ($isAutoEmail) {
        $params['is_auto_email'] = TRUE;
        $params['tplParams'] = [];
        // FIXME: for grant profiles
        $grantStatuses = CRM_Core_OptionGroup::values('grant_status');
        if (CRM_Utils_Array::value('grant_program_id', $params)) {
          $params['tplParams']['grant_programs'] = CRM_Utils_Array::value($params['grant_program_id'], CRM_Grant_BAO_GrantProgram::getGrantPrograms(), '');
Mayur Jadhav's avatar
Mayur Jadhav committed
688
        }
Monish Deb's avatar
Monish Deb committed
689 690 691 692 693
        $params['tplParams']['grant_type'] = CRM_Utils_Array::value($params['grant_type_id'], CRM_Core_OptionGroup::values('grant_type'));
        $params['tplParams']['grant_status'] = CRM_Utils_Array::value($params['status_id'], $grantStatuses);

        if (CRM_Utils_Array::value('grant_rejected_reason_id', $params)) {
          $params['tplParams']['grant_rejected_reason'] = CRM_Utils_Array::value($params['grant_rejected_reason_id'], CRM_Core_OptionGroup::values('reason_grant_ineligible'));
Mayur Jadhav's avatar
Mayur Jadhav committed
694
        }
Monish Deb's avatar
Monish Deb committed
695 696
        if (CRM_Utils_Array::value('grant_incomplete_reason_id', $params)) {
          $params['tplParams']['grant_incomplete_reason'] = CRM_Utils_Array::value($params['grant_incomplete_reason_id'], CRM_Core_OptionGroup::values('reason_grant_incomplete'));
Pradeep Nayak's avatar
Pradeep Nayak committed
697
        }
Monish Deb's avatar
Monish Deb committed
698
        $params['tplParams']['grant'] = $params;
Pradeep Nayak's avatar
Pradeep Nayak committed
699
      }
700

Monish Deb's avatar
Monish Deb committed
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
      $previousStatus = '';
      if ($previousGrant && !empty($previousGrant['status_id'])) {
        $previousGrantStatus = CRM_Utils_Array::value($previousGrant['status_id'], $grantStatuses, '');
        $currentGrantStatus = CRM_Utils_Array::value($params['status_id'], $grantStatuses, '');
        if ($isAutoEmail) {
          CRM_Grant_BAO_GrantProgram::sendMail($params['contact_id'], $params, $currentGrantStatus, $objectId, $previousGrantStatus);
        }
        else {
          CRM_Grant_BAO_GrantProgram::createStatusChangeActivity(
            $params['contact_id'],
            $currentGrantStatus,
            $previousGrantStatus,
            $params['contact_id']
          );
        }
716
      }
Mayur Jadhav's avatar
Mayur Jadhav committed
717
    }
Mayur Jadhav's avatar
Mayur Jadhav committed
718
  }
Pradeep Nayak's avatar
Pradeep Nayak committed
719 720 721 722 723 724 725 726 727 728
}

/*
 * hook_civicrm_postProcess
 *
 * @param string $formName form name
 * @param object $form form object
 *
 */
function grantprograms_civicrm_postProcess($formName, &$form) {
Mayur Jadhav's avatar
Mayur Jadhav committed
729 730 731 732
  if ($formName == "CRM_Custom_Form_Field") {
    $customGroupID = CRM_Core_DAO::getFieldValue( 'CRM_Core_DAO_OptionGroup', $form->_submitValues['label'], 'id', 'title');
    foreach ($form->_submitValues['option_label'] as $key => $value) {
      if (!empty($value)) {
Edsel's avatar
Edsel committed
733 734 735 736 737 738 739
        $sql = "UPDATE civicrm_option_value SET description = %1 WHERE option_group_id = %2 AND label = %3";
        $params = array(
          1 => array($form->_submitValues['option_description'][$key], 'String'),
          2 => array($customGroupID, 'Integer'),
          3 => array($value, 'String'),
        );
        CRM_Core_DAO::executeQuery($sql, $params);
Mayur Jadhav's avatar
Mayur Jadhav committed
740 741 742
      }
    }
  }
743

Edsel's avatar
Edsel committed
744 745
  if ($formName == "CRM_Custom_Form_Option") {
    $params = array(
Mayur Jadhav's avatar
Mayur Jadhav committed
746
      'id' => $form->_submitValues['optionId'],
Edsel's avatar
Edsel committed
747
      'description' => $form->_submitValues['description'],
Mayur Jadhav's avatar
Mayur Jadhav committed
748
      'option_group_id' => $form->getVar('_optionGroupID'),
Edsel's avatar
Edsel committed
749
    );
Mayur Jadhav's avatar
Mayur Jadhav committed
750
    CRM_Core_BAO_OptionValue::create($params);
Edsel's avatar
Edsel committed
751 752
  }

Mayur Jadhav's avatar
Mayur Jadhav committed
753
  if ($formName == 'CRM_Grant_Form_Grant' && ($form->getVar('_action') != CRM_Core_Action::DELETE)) {
Pradeep Nayak's avatar
Pradeep Nayak committed
754
    // FIXME: cookies error
Mayur Jadhav's avatar
Mayur Jadhav committed
755
    if ($form->getVar('_context') == 'search') {
Mayur Jadhav's avatar
Mayur Jadhav committed
756 757 758
      $array['contact_id'] = $form->_ncid;
      $searchGrants = explode(',', $form->_searchGrants);
      $grants = array_flip($searchGrants);
Pradeep Nayak's avatar
Pradeep Nayak committed
759 760 761
      $foundit = FALSE;
      foreach ($grants as $gKey => $gVal) {
        if ($foundit) {
762
          $next = $gKey;
Pradeep Nayak's avatar
Pradeep Nayak committed
763 764
          break;
        }
765 766
        if ($gKey == $form->_next) {
          $next = $gKey;
Pradeep Nayak's avatar
Pradeep Nayak committed
767 768 769 770 771 772 773
          if($gVal == end($grants)) {
            reset($grants);
            $next = key($grants);
          }
          $foundit = TRUE;
        }
      }
Mayur Jadhav's avatar
Mayur Jadhav committed
774
      $grantParams['id'] = $next;
Monish Deb's avatar
Monish Deb committed
775
      $result = civicrm_api3('Grant', 'get', ['id' => $next])['values'];
Pradeep Nayak's avatar
Pradeep Nayak committed
776
      if (CRM_Utils_Array::value($form->getButtonName('submit', 'savenext'), $_POST)) {
Mayur Jadhav's avatar
Mayur Jadhav committed
777
        if ($form->getVar('_id') != $form->_prev) {
778
          CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/grant',
Mayur Jadhav's avatar
Mayur Jadhav committed
779
            "reset=1&action=update&id={$form->_next}&cid={$array['contact_id']}&context=search&next={$next}&prev={$form->_prev}&key={$form->_key}&ncid={$result[$next]['contact_id']}&searchGrants={$form->_searchGrants}"));
780
        }
Pradeep Nayak's avatar
Pradeep Nayak committed
781 782
        else {
          CRM_Core_Session::setStatus( ts('The next record in the Search no longer exists. Select another record to edit if desired.'));
783
          CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/grant/search',
Pradeep Nayak's avatar
Pradeep Nayak committed
784 785
            "force=1&qfKey={$form->_key}"));
        }
786
      }
Pradeep Nayak's avatar
Pradeep Nayak committed
787
      elseif (CRM_Utils_Array::value( $form->getButtonName('upload', 'new'), $_POST)) {
788
        CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/grant',
Mayur Jadhav's avatar
Mayur Jadhav committed
789
          "reset=1&action=add&context=grant&cid={$array['contact_id']}"));
790
      }
Pradeep Nayak's avatar
Pradeep Nayak committed
791
      else {
792
        CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/grant/search',
Pradeep Nayak's avatar
Pradeep Nayak committed
793 794 795 796
          "force=1&qfKey={$form->_key}"));
      }
    }
  }
Pradeep Nayak's avatar
Pradeep Nayak committed
797 798 799 800 801 802 803 804 805 806
}

/*
 * hook_civicrm_searchTasks
 *
 * @param string $objectName form name
 * @param array $tasks search task
 *
 */
function grantprograms_civicrm_searchTasks($objectName, &$tasks) {
807
  if ($objectName == 'grant' && !strstr($_GET['q'], 'payment/search')
Mayur Jadhav's avatar
Mayur Jadhav committed
808
    && CRM_Core_Permission::check('create payments in CiviGrant')) {
809
    $tasks[PAY_GRANTS] = array(
Pradeep Nayak's avatar
Pradeep Nayak committed
810 811
      'title' => ts('Pay Grants'),
      'class' => array('CRM_Grant_Form_Task_Pay',
812
        'CRM_Grant_Form_Task_GrantPayment'
Pradeep Nayak's avatar
Pradeep Nayak committed
813 814 815 816
      ),
      'result' => FALSE,
    );
  }
Mayur Jadhav's avatar
Mayur Jadhav committed
817
}
Mayur Jadhav's avatar
Mayur Jadhav committed
818 819

function grantprograms_getOptionValueLabel($optioGroupID, $value) {
820
  $value = CRM_Core_DAO::escapeString($value);
Mayur Jadhav's avatar
Mayur Jadhav committed
821 822 823
  $query = "SELECT label FROM civicrm_option_value WHERE  option_group_id = {$optioGroupID} AND value = '{$value}' ";
  return CRM_Core_DAO::singleValueQuery($query);
}
Mayur Jadhav's avatar
Mayur Jadhav committed
824

Mayur Jadhav's avatar
Mayur Jadhav committed
825 826 827 828 829 830 831 832 833
function grantprograms_getCustomFieldData($id) {
  $customFieldData = array();
  $query = "SELECT html_type, option_group_id FROM civicrm_custom_field WHERE id = {$id} ";
  $DAO = CRM_Core_DAO::executeQuery($query);
  while ($DAO->fetch()) {
    $customFieldData['html_type'] = $DAO->html_type;
    $customFieldData['option_group_id'] = $DAO->option_group_id;
  }
  return $customFieldData;
Pradeep Nayak's avatar
Pradeep Nayak committed
834
}
Mayur Jadhav's avatar
Mayur Jadhav committed
835

Monish Deb's avatar
Monish Deb committed
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
function manageNavigationLinks($action) {
  $menus = [
    'Grant Programs',
    'Grant Payment',
    'Find Grant Payments',
    'Grant Payment Reprint',
  ];
  foreach ($menus as $menu) {
    $navs = CRM_Utils_Array::collect('id', civicrm_api3('Navigation', 'get', ['name' => $menu, 'sequential' => 1])['values']);
    foreach ($navs as $id) {
      if ($action == 'disable') {
        civicrm_api3('Navigation', 'create', ['id' => $id, 'is_active' => FALSE]);
      }
      elseif ($action == 'enable') {
        civicrm_api3('Navigation', 'create', ['id' => $id, 'is_active' => TRUE]);
      }
      elseif ($action == 'delete') {
        civicrm_api3('Navigation', 'delete', ['id' => $id]);
      }
    }
  }
}

Pradeep Nayak's avatar
Pradeep Nayak committed
859 860 861 862 863 864 865 866
/**
 * Hook implementation when an email is about to be sent by CiviCRM.
 *
 */
function grantprograms_civicrm_alterMailParams(&$params) {
  if (substr($params['valueName'], 0, 6) == 'grant_') {
    CRM_Core_Smarty::singleton()->assign('messageBody', $params['html']);
  }
867 868 869 870 871 872
}

function grantprograms_civicrm_links( $op, $objectName, $objectId, &$links ) {
      if ($op == 'create.new.shorcuts' && (CRM_Core_Permission::check('access CiviGrant') &&
      CRM_Core_Permission::check('edit grant program')) ) {
      // add link to create new profile
Edsel's avatar
Edsel committed
873
      $links[] = array( 'url'   => CRM_Utils_System::url('civicrm/grant_program', 'reset=1&action=browse', FALSE),
874 875 876
                 'title' => ts('Grant Program'),
                 'ref'   => 'new-grant program');
    }
877
}