grantprograms.php 45.4 KB
Newer Older
1
<?php
2
require_once 'grantprograms.civix.php';
3 4
define('PAY_GRANTS', 5);
define('DELETE_GRANTS', 1);
Edselopez's avatar
Edselopez committed
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
  file_put_contents($config->uploadDir . "civicrm_data.sql", $data);
  CRM_Utils_File::sourceSQLFile(CIVICRM_DSN, $config->uploadDir . "civicrm_data.sql");
Mayur Jadhav's avatar
Mayur Jadhav committed
34
  grantprograms_addRemoveMenu(TRUE);
Pradeep Nayak's avatar
Pradeep Nayak committed
35
  return TRUE;
36 37 38 39 40 41
}

/**
 * Implementation of hook_civicrm_uninstall
 */
function grantprograms_civicrm_uninstall() {
Mayur Jadhav's avatar
Mayur Jadhav committed
42
  $config = CRM_Core_Config::singleton();
43 44 45 46 47 48 49
  return _grantprograms_civix_civicrm_uninstall();
}

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

/**
 * Implementation of hook_civicrm_disable
 */
function grantprograms_civicrm_disable() {
Mayur Jadhav's avatar
Mayur Jadhav committed
60
  $config = CRM_Core_Config::singleton();
61
  CRM_Utils_File::sourceSQLFile(CIVICRM_DSN, $config->extensionsDir . 'biz.jmaconsulting.grantprograms/sql/grantprograms_disable.sql');
Mayur Jadhav's avatar
Mayur Jadhav committed
62
  grantprograms_addRemoveMenu(FALSE);
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 88
  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);
}

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

Pradeep Nayak's avatar
Pradeep Nayak committed
100 101 102 103
  if (CRM_Utils_Array::value('custom', $params)) {
    $assessmentAmount = 0;
    foreach ($params['custom'] as $key => $value) {
      foreach($value as $fieldKey => $fieldValue) {
104
        if (in_array($fieldValue['table_name'], array(PANEL_REVIEW_EVALUATION, GRANT_COMMITTEE_REVIEW, FULL_BOARD_REVIEW))
Pradeep Nayak's avatar
Pradeep Nayak committed
105
          && CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $fieldValue['custom_field_id'], 'html_type') == 'Select') {
106 107 108
          if (is_nan((float)$fieldValue['value']) === FALSE) {
            $assessmentAmount += $fieldValue['value'];
          }
Pradeep Nayak's avatar
Pradeep Nayak committed
109 110 111 112 113 114 115
        }
      }
    }
    if ($assessmentAmount) {
      $params['assessment'] = $assessmentAmount;
    }
  }
Mayur Jadhav's avatar
Mayur Jadhav committed
116 117 118 119 120 121 122 123
  $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;
124
      }
Mayur Jadhav's avatar
Mayur Jadhav committed
125 126
      elseif ($sumAmountGranted > 0) {
        $priority = 0;
127
      }
128
    }
Mayur Jadhav's avatar
Mayur Jadhav committed
129 130 131
    else {
      $priority = -10;
    }
Mayur Jadhav's avatar
Mayur Jadhav committed
132
    if (array_key_exists('assessment', $params) && $params['adjustment_value']) {
Mayur Jadhav's avatar
Mayur Jadhav committed
133 134
      if ($params['assessment'] != 0) {
        $params['assessment'] = $params['assessment'] - $priority;
135 136 137
      }
    }
  }
138

139 140 141 142
  $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
143
  $grantStatuses = CRM_Core_OptionGroup::values('grant_status', TRUE);
Pradeep Nayak's avatar
Pradeep Nayak committed
144
  if ($algoType == 'immediate' && !CRM_Utils_Array::value('manualEdit', $params) && $params['status_id'] == CRM_Utils_Array::value('Eligible', $grantStatuses)) {
145 146 147 148
    $params['amount_granted'] = quickAllocate($grantProgram, $params);
    if (empty($params['amount_granted'])) {
      unset($params['amount_granted']);
    }
149
  }
150
}
Pradeep Nayak's avatar
Pradeep Nayak committed
151 152 153 154 155 156

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

Pradeep Nayak's avatar
Pradeep Nayak committed
189
  //Update grant program
Mayur Jadhav's avatar
Mayur Jadhav committed
190
  if ($amountGranted > 0) {
Mayur Jadhav's avatar
Mayur Jadhav committed
191
    $grantProgramParams['remainder_amount'] = $grantProgram->remainder_amount - $remainderDifference;
Mayur Jadhav's avatar
Mayur Jadhav committed
192 193 194 195
    $grantProgramParams['id'] =  $grantProgram->id;
    $ids['grant_program']     =  $grantProgram->id;
    CRM_Grant_BAO_GrantProgram::create($grantProgramParams, $ids);
  }
Pradeep Nayak's avatar
Pradeep Nayak committed
196 197 198 199 200 201 202 203 204 205 206 207 208 209
  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',
210
      'title' => ts('View Grant Program')
Pradeep Nayak's avatar
Pradeep Nayak committed
211 212 213 214 215
    ),
    CRM_Core_Action::UPDATE  => array(
      'name'  => ts('Edit'),
      'url'   => 'civicrm/grant_program',
      'qs'    => 'action=update&id=%%id%%&reset=1',
216
      'title' => ts('Edit Grant Program')
Pradeep Nayak's avatar
Pradeep Nayak committed
217 218 219 220 221
    ),
    CRM_Core_Action::DELETE  => array(
      'name'  => ts('Delete'),
      'url'   => 'civicrm/grant_program',
      'qs'    => 'action=delete&id=%%id%%&reset=1',
222
      'title' => ts('Delete')
Pradeep Nayak's avatar
Pradeep Nayak committed
223 224 225 226
    ),
    CRM_Core_Action::ADD  => array(
      'name'  => ts('Allocate Approved (Trial)'),
      'url'   => 'civicrm/grant_program',
Monish Deb's avatar
Monish Deb committed
227
      'qs'    => 'id=allocation',
Pradeep Nayak's avatar
Pradeep Nayak committed
228
      'extra'   => 'id=allocation',
229
      'title' => ts('Allocate Approved (Trial)')
Pradeep Nayak's avatar
Pradeep Nayak committed
230 231 232 233 234 235
    ),
    CRM_Core_Action::BROWSE  => array(
      'name'  => ts('Finalize Approved Allocations'),
      'url'   => 'civicrm/grant_program',
      'qs'    => '#',
      'extra'   => 'id=finalize',
236
      'title' => ts('Finalize Approved Allocations')
Pradeep Nayak's avatar
Pradeep Nayak committed
237 238
    ),
    CRM_Core_Action::MAP  => array(
Mayur Jadhav's avatar
Mayur Jadhav committed
239
      'name'  => ts('Mark remaining unapproved Grants as Ineligible'),
Pradeep Nayak's avatar
Pradeep Nayak committed
240 241 242
      'url'   => 'civicrm/grant_program',
      'qs'    => '#',
      'extra'   => 'id=reject',
243
      'title' => ts('Mark remaining unapproved Grants as Ineligible')
Pradeep Nayak's avatar
Pradeep Nayak committed
244 245 246
    ),
  );
  return $_links;
247 248
}

Edselopez's avatar
Edselopez committed
249
function grantprograms_civicrm_permission(&$permissions) {
Pradeep Nayak's avatar
Pradeep Nayak committed
250 251
  $prefix = ts('CiviCRM Grant Program') . ': '; // name of extension or module
  $permissions['edit grant finance'] = $prefix . ts('edit grant finance');
252
  $permissions['edit grant program'] = $prefix . ts('edit grant programs in CiviGrant');
Edselopez's avatar
Edselopez committed
253 254 255
  $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
256
}
257 258 259 260 261 262 263 264 265 266 267 268

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;
    }
  }
}
269

Pradeep Nayak's avatar
Pradeep Nayak committed
270 271
/*
 * hook_civicrm_buildForm civicrm hook
272
 *
Pradeep Nayak's avatar
Pradeep Nayak committed
273 274 275 276 277
 * @param string $formName form name
 * @param object $form form object
 *
*/
function grantprograms_civicrm_buildForm($formName, &$form) {
278 279 280 281 282 283 284
  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;
    }
285
    $grantUrl = CRM_Utils_System::url('civicrm/contact/view/grant',
286 287 288
      'reset=1&action=view&id=' . $activityValues['source_record_id'] . '&cid=' . current($activityValues['assignee_contact']));
    $form->assign('grantUrl', $grantUrl);
  }
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
    $form->_grantPrograms = CRM_Grant_BAO_GrantProgram::getGrantPrograms();
333 334
    $form->add('select',
      'grant_program_id',
335 336 337 338
      ts('Grant Programs'),
      array('' => ts('- select -')) + $form->_grantPrograms,
      TRUE
    );
339

340 341 342 343 344
    //Financial Type RG-125
    $financialType = CRM_Contribute_PseudoConstant::financialType();
    if (count($financialType)) {
      $form->assign('financialType', $financialType);
    }
345 346
    $form->add('select', 'financial_type_id',
      ts('Financial Type'),
347
      array('' => ts('- Select Financial Type -')) + $financialType,
348 349
      FALSE
    );
Pradeep Nayak's avatar
Pradeep Nayak committed
350
    $showFields = FALSE;
351

Pradeep Nayak's avatar
Pradeep Nayak committed
352 353 354 355 356 357 358 359 360 361 362 363
    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) {
364
          if ((($grantWeight[$currentStatus] >= 7 && $statusId == array_search('Ineligible', $grantStatuses))
Pradeep Nayak's avatar
Pradeep Nayak committed
365 366 367 368 369 370 371 372 373 374
               || ($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');
375

Pradeep Nayak's avatar
Pradeep Nayak committed
376 377 378 379 380 381
      $element = $form->add('select', 'status_id', ts('Grant Status'),
        $grantStatuses,
        TRUE
      );
      if ($grantStatuses[$currentStatus] == 'Withdrawn') {
        $element->freeze();
382
      }
Pradeep Nayak's avatar
Pradeep Nayak committed
383
    }
Pradeep Nayak's avatar
Pradeep Nayak committed
384 385 386 387
    if ($form->getVar('_id')) {
      if (CRM_Core_Permission::check('administer CiviGrant')) {
        $form->add('text', 'assessment', ts('Assessment'));
      }
388

Pradeep Nayak's avatar
Pradeep Nayak committed
389 390 391 392
      // 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();
393 394 395 396 397 398 399 400 401
        }
        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
402 403 404 405 406 407
        }
        CRM_Core_Region::instance('page-body')->add(array(
          'template' => 'CRM/Grant/Form/Freeze.tpl',
        ));
      }
      $showFields = TRUE;
408
    }
Pradeep Nayak's avatar
Pradeep Nayak committed
409
    $form->assign('showFields', $showFields);
410 411 412
  }
  if ($formName == "CRM_Grant_Form_Search") {
    $grantPrograms = CRM_Grant_BAO_GrantProgram::getGrantPrograms();
413 414
    $form->add('select',
      'grant_program_id',
415 416 417
      ts('Grant Programs'),
      array('' => ts('- select -')) + $grantPrograms
    );
418 419 420 421 422 423 424 425
    $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', ' '))),
426 427
      'money'
    );
428 429 430
    $form->add('text',
      'grant_amount_total_high',
      ts('To'),
431
      array('size' => 8, 'maxlength' => 8)
432 433 434 435
    );
    $form->addRule('grant_amount_total_high',
      ts('Please enter a valid money value (e.g. %1).',
        array(1 => CRM_Utils_Money::format('99.99', ' '))),
436 437
      'money'
    );
438 439 440
    $form->add('text',
      'grant_assessment_low',
      ts('From'),
441 442
      array('size' => 9, 'maxlength' => 9)
    );
443 444 445 446

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

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

472

473
  if ($formName == 'CRM_Custom_Form_Field') {
474

Pradeep Nayak's avatar
Pradeep Nayak committed
475
    for ($i = 1; $i <= $formName::NUM_OPTION; $i++) {
476 477 478 479
      $form->add('text',
        'option_description['. $i .']',
        'Mark',
        array('id' => 'marks')
Pradeep Nayak's avatar
Pradeep Nayak committed
480
      );
481
    }
Edselopez's avatar
Edselopez committed
482 483 484 485
    $form->assign('edit_form', 1);
    CRM_Core_Region::instance('page-body')->add(array(
      'template' => 'CRM/Grant/Form/CustomFields.tpl',
    ));
486
  }
Pradeep Nayak's avatar
Pradeep Nayak committed
487
  if ($formName == 'CRM_Custom_Form_Option') {
488 489 490
    $form->add('text',
      'description',
      'Mark',
Pradeep Nayak's avatar
Pradeep Nayak committed
491 492
      array('id' => 'marks')
    );
Edselopez's avatar
Edselopez committed
493 494 495
    CRM_Core_Region::instance('page-body')->add(array(
      'template' => 'CRM/Grant/Form/CustomFields.tpl',
    ));
496
  }
497

Edselopez's avatar
Edselopez committed
498
  if ($formName == 'CRM_Grant_Form_Search' && $form->get('context') == 'dashboard') {
Pradeep Nayak's avatar
Pradeep Nayak committed
499 500 501 502
    //Version of grant program listings
    $grantProgram = array();
    require_once 'CRM/Grant/DAO/GrantProgram.php';
    $dao = new CRM_Grant_DAO_GrantProgram();
503

Pradeep Nayak's avatar
Pradeep Nayak committed
504 505
    $dao->orderBy('label');
    $dao->find();
506

Pradeep Nayak's avatar
Pradeep Nayak committed
507 508 509 510
    while ($dao->fetch()) {
      $grantProgram[$dao->id] = array();
      CRM_Core_DAO::storeValues( $dao, $grantProgram[$dao->id]);
      $action = array_sum(array_keys(links()));
511
      $grantProgram[$dao->id]['action'] = CRM_Core_Action::formLink(links(), $action,
Pradeep Nayak's avatar
Pradeep Nayak committed
512 513
                                          array('id' => $dao->id));
    }
514
    $grantType   = CRM_Core_OptionGroup::values('grant_type');
515
    $grantStatus = CRM_Grant_BAO_GrantProgram::grantProgramStatus( );
Pradeep Nayak's avatar
Pradeep Nayak committed
516
    foreach ( $grantProgram as $key => $value ) {
Edselopez's avatar
Edselopez committed
517
      $grantProgram[$key]['grant_type_id'] = $grantType[$grantProgram[$key]['grant_type_id']];
Pradeep Nayak's avatar
Pradeep Nayak committed
518 519 520 521 522 523
      $grantProgram[$key]['status_id'] = $grantStatus[CRM_Grant_BAO_GrantProgram::getOptionValue($grantProgram[$key]['status_id'])];
    }
    $form->assign('programs',$grantProgram );
    $form->assign('context', 'dashboard');
  }

Edselopez's avatar
Edselopez committed
524 525
  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
526
    $form->assign('hideAttachments', 1);
527 528 529
    $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));
530 531
    //Freeze Prior Year's Assessment field
    $form->_elements[$form->_elementIndex['prev_assessment']]->freeze();
Edselopez's avatar
Edselopez committed
532
    // Filter out grant being edited from search results
533
    $form->assign('grant_id', $form->getVar('_id'));
534 535 536 537 538 539 540 541 542 543 544
  }

  // 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
    );
  }
545 546
}

Edselopez's avatar
Edselopez committed
547
function grantprograms_civicrm_pageRun( &$page ) {
548 549 550 551 552 553
  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
554
    $smarty = CRM_Core_Smarty::singleton();
555
    if ($smarty->_tpl_vars['action'] & CRM_Core_Action::VIEW) {
Mayur Jadhav's avatar
Mayur Jadhav committed
556
      $smarty->_tpl_vars['assessment'] = CRM_Core_DAO::getFieldValue('CRM_Grant_DAO_Grant', $smarty->_tpl_vars['id'], 'assessment', 'id');
557 558
      $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
559 560 561 562
      CRM_Core_Region::instance('page-body')->add(array(
        'template' => 'CRM/Grant/Page/GrantExtra.tpl',
      ));
    }
563
  }
564 565

  if ($page->getVar('_name') == "CRM_Custom_Page_Option") {
Mayur Jadhav's avatar
Mayur Jadhav committed
566 567
    $params['id'] = $page->getVar('_fid');
    $params['custom_group_id'] = $page->getVar('_gid');
Mayur Jadhav's avatar
Mayur Jadhav committed
568
    CRM_Core_BAO_CustomField::retrieve($params, $defaults);
Mayur Jadhav's avatar
Mayur Jadhav committed
569 570 571 572 573 574 575
    $optionValues = CRM_Core_BAO_OptionValue::getOptionValuesArray($defaults['option_group_id']);
    $smarty = CRM_Core_Smarty::singleton();
    foreach ($optionValues as $key => $value) {
      if (!empty($value['description'])) {
        $smarty->_tpl_vars['customOption'][$key]['description'] = $value['description'];
      }
    }
Edselopez's avatar
Edselopez committed
576 577
    $page->assign('view_form', 1);
    CRM_Core_Region::instance('page-body')->add(array(
Mayur Jadhav's avatar
Mayur Jadhav committed
578
      'template' => 'CRM/Grant/Form/CustomFieldsView.tpl',
Edselopez's avatar
Edselopez committed
579 580
    ));
  }
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596

  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') {
    $tplName = 'CRM/Grant/Page/DashBoardExtra.tpl';
  }
}

function grantprograms_civicrm_queryObjects(&$queryObjects, $type) {
  if ($type == 'Contact') {
     $queryObjects[] = new CRM_Grantprograms_Query();
   }
Edselopez's avatar
Edselopez committed
597
}
598

Pradeep Nayak's avatar
Pradeep Nayak committed
599 600 601 602 603 604 605 606 607 608 609
/*
 * 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
 *
 */
function grantprograms_civicrm_validate($formName, &$fields, &$files, &$form) {
  $errors = NULL;
610 611
  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
612 613 614 615
    $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) {
616
      $errors[''] = ts('Error');
Mayur Jadhav's avatar
Mayur Jadhav committed
617 618 619 620 621 622 623
      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");
624 625
    }
  }
Mayur Jadhav's avatar
Mayur Jadhav committed
626
  if ($formName == 'CRM_Grant_Form_Grant' && ($form->getVar('_action') != CRM_Core_Action::DELETE)) {
Pradeep Nayak's avatar
Pradeep Nayak committed
627
    $defaults = array();
628
    $params['id'] = $form->_submitValues['grant_program_id'];
Pradeep Nayak's avatar
Pradeep Nayak committed
629
    CRM_Grant_BAO_GrantProgram::retrieve($params, $defaults);
Pradeep Nayak's avatar
Pradeep Nayak committed
630
    if (array_key_exists('amount_granted', $form->_submitValues) && CRM_Utils_Array::value('remainder_amount', $defaults) < $form->_submitValues['amount_granted']) {
Edselopez's avatar
Edselopez committed
631
      $errors['amount_granted'] = ts('You need to increase the Grant Program Remainder Amount');
632
    }
633

634 635 636
    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');
    }
637
  }
Pradeep Nayak's avatar
Pradeep Nayak committed
638
  if ($formName == 'CRM_Grant_Form_Search') {
639
    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
640 641 642
      foreach ($fields as $fieldKey => $fieldValue) {
        if (strstr($fieldKey, 'mark_x_')) {
          $grantID = ltrim( $fieldKey, 'mark_x_' );
Mayur Jadhav's avatar
Mayur Jadhav committed
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
          if ($fields['task'] == PAY_GRANTS) {
            $grantDetails = CRM_Grant_BAO_GrantProgram::getGrants(array('id' => $grantID));
            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
658 659 660 661
          }
        }
      }
    }
662
  }
Pradeep Nayak's avatar
Pradeep Nayak committed
663
  return empty($errors) ? TRUE : $errors;
Pradeep Nayak's avatar
Pradeep Nayak committed
664 665
}

Pradeep Nayak's avatar
Pradeep Nayak committed
666
function grantprograms_civicrm_pre($op, $objectName, $id, &$params) {
667
  if ($objectName == 'Grant' && ($op == 'edit' || $op == 'create')) {
Pradeep Nayak's avatar
Pradeep Nayak committed
668
    $grantStatus = CRM_Core_OptionGroup::values('grant_status');
Pradeep Nayak's avatar
Pradeep Nayak committed
669
    $assessmentAmount = 0;
Mayur Jadhav's avatar
Mayur Jadhav committed
670
    $calculateAssessment = FALSE;
Mayur Jadhav's avatar
Mayur Jadhav committed
671
    $params['adjustment_value'] = TRUE;
Pradeep Nayak's avatar
Pradeep Nayak committed
672
    $previousGrant = NULL;
673 674
    $smarty = CRM_Core_Smarty::singleton();
    $sendMail = TRUE;
Mayur Jadhav's avatar
Mayur Jadhav committed
675 676 677
    if ($objectName == 'Grant' && $op == "edit") {
      $grantParams = array('id' => $id);
      $previousGrant = CRM_Grant_BAO_Grant::retrieve($grantParams, CRM_Core_DAO::$_nullArray);
678
      if (isset($params['status_id']) && $params['status_id'] == $previousGrant->status_id) {
679 680
        $sendMail = FALSE;
      }
Mayur Jadhav's avatar
Mayur Jadhav committed
681
      if ((CRM_Utils_Array::value('assessment', $params) == $previousGrant->assessment)) {
Mayur Jadhav's avatar
Mayur Jadhav committed
682 683 684
        $calculateAssessment = TRUE;
      }
    }
685
    $smarty->assign('sendMail', $sendMail);
Pradeep Nayak's avatar
Pradeep Nayak committed
686
    $grantStatusApproved = array_search('Approved for Payment', $grantStatus);
687 688 689 690 691
    if ((isset($params['status_id']) && $grantStatusApproved == $params['status_id'] &&
        empty($params['decision_date']) && $op == 'create') ||
      ($previousGrant && !$previousGrant->decision_date && isset($params['status_id']) &&
        $previousGrant->status_id != $params['status_id'])
    ) {
Pradeep Nayak's avatar
Pradeep Nayak committed
692 693
      $params['decision_date'] = date('Ymd');
    }
Mayur Jadhav's avatar
Mayur Jadhav committed
694
    if ((empty($params['assessment']) || $calculateAssessment) && ($op == 'create' || $op == 'edit')) {
695 696 697 698 699
      if (CRM_Utils_Array::value('custom', $params)) {
        foreach ($params['custom'] as $key => $value) {
          foreach($value as $fieldKey => $fieldValue) {
            $customParams = array('id' => $key, 'is_active' => 1, 'html_type' => 'Select');
            $customFields = CRM_Core_BAO_CustomField::retrieve($customParams, $default = array());
700
            if (!empty($customFields)) {
701 702 703 704 705
              $optionValueParams = array('option_group_id' => $customFields->option_group_id, 'value' => $fieldValue['value'], 'is_active' => 1);
              $optionValues = CRM_Core_BAO_OptionValue::retrieve($optionValueParams,  $default = array());
              if(!empty($optionValues->description)) {
                $assessmentAmount += $optionValues->description;
              }
Pradeep Nayak's avatar
Pradeep Nayak committed
706 707 708 709 710
            }
          }
        }
      }
    }
711

Pradeep Nayak's avatar
Pradeep Nayak committed
712 713
    if(!empty($assessmentAmount)) {
      $params['assessment'] = $assessmentAmount;
714
    }
Mayur Jadhav's avatar
Mayur Jadhav committed
715 716
    elseif ($objectName == 'Grant' && $op == "edit") {
      $params['adjustment_value'] = FALSE;
Pradeep Nayak's avatar
Pradeep Nayak committed
717
    }
Mayur Jadhav's avatar
Mayur Jadhav committed
718
    if ($objectName == 'Grant' && $op == "edit") {
719
      if (!empty($previousGrant->amount_granted) && array_key_exists('amount_granted', $params) && CRM_Utils_Money::format($previousGrant->amount_granted) != CRM_Utils_Money::format($params['amount_granted']) && !CRM_Utils_Array::value('allocation', $params)) {
Mayur Jadhav's avatar
Mayur Jadhav committed
720 721 722 723 724 725 726
        $programParams = array('id' => $previousGrant->grant_program_id);
        $grantProgram = CRM_Grant_BAO_GrantProgram::retrieve($programParams, CRM_Core_DAO::$_nullArray);
        $remainderDifference = CRM_Utils_Rule::cleanMoney($params['amount_granted']) - $previousGrant->amount_granted;
        $grantProgramParams['remainder_amount'] = $grantProgram->remainder_amount - $remainderDifference;
        $grantProgramParams['id'] =  $grantProgram->id;
        $ids['grant_program'] =  $grantProgram->id;
        CRM_Grant_BAO_GrantProgram::create($grantProgramParams, $ids);
727 728 729
        $params['manualEdit'] = TRUE;
      }
    }
Mayur Jadhav's avatar
Mayur Jadhav committed
730 731 732
    elseif ($objectName == 'Grant' && $op == "create" && CRM_Utils_Array::value('amount_granted', $params)) {
      $params['manualEdit'] = TRUE;
    }
733

734 735 736
    if (!empty($id)) {
      $params['id'] = $id;
    }
737
    CRM_Grantprograms_Hook::grantAssessment($params);
Pradeep Nayak's avatar
Pradeep Nayak committed
738 739 740 741
    if ($op == 'edit') {
      $smarty = CRM_Core_Smarty::singleton();
      $smarty->assign('previousGrant', $previousGrant);
    }
742 743 744

    $session = CRM_Core_Session::singleton();
    $session->set('grant-params', $params);
Pradeep Nayak's avatar
Pradeep Nayak committed
745 746 747 748 749 750 751 752
  }
}

/*
 * hook_civicrm_post
 *
 */
function grantprograms_civicrm_post($op, $objectName, $objectId, &$objectRef) {
Mayur Jadhav's avatar
Mayur Jadhav committed
753
  //send mail after grant save
754 755 756
  $config = CRM_Core_Session::singleton();
  $params = $config->get('grant-params');
  if ($objectName == 'Grant' && isset($params) && !isset($params['restrictEmail'])) {
Mayur Jadhav's avatar
Mayur Jadhav committed
757 758
    // added by JMA fixme in module
    $grantProgram  = new CRM_Grant_DAO_GrantProgram();
759
    $grantProgram->id = isset($params['grant_program_id']) ? $params['grant_program_id'] : NULL;
Mayur Jadhav's avatar
Mayur Jadhav committed
760 761 762 763
    $page = new CRM_Core_Page();
    if ($grantProgram->find(TRUE)) {
      $params['is_auto_email'] = $grantProgram->is_auto_email;
    }
764

Mayur Jadhav's avatar
Mayur Jadhav committed
765 766 767 768 769
    if ($params['is_auto_email'] == 1) {
      // FIXME: for grant profiles
      $customData = array();
      if (!CRM_Utils_Array::value('custom', $params)) {
        $params['custom'] = array();
770 771
        $entityValues = CRM_Core_BAO_CustomValueTable::getEntityValues($objectId, 'Grant');
        getCustomFields(array_filter($entityValues), $customData);
Mayur Jadhav's avatar
Mayur Jadhav committed
772
      }
Mayur Jadhav's avatar
Mayur Jadhav committed
773
      foreach ($params['custom'] as $key => $value) {
Mayur Jadhav's avatar
Mayur Jadhav committed
774
        foreach ($value as $index => $field) {
Mayur Jadhav's avatar
Mayur Jadhav committed
775
          if (!empty($field['value'])) {
Mayur Jadhav's avatar
Mayur Jadhav committed
776 777 778 779 780 781 782 783 784 785
            $customData[$field['custom_group_id']][$field['custom_field_id']] = $field['value'];
            if (strstr($field['column_name'], 'start_date')) {
              $startDate = $field['value'];
            }
            if (strstr($field['column_name'], 'end_date')) {
              $endDate = $field['value'];
            }
          }
        }
      }
786
      $customGroup = $customField = array();
Mayur Jadhav's avatar
Mayur Jadhav committed
787 788
      if (!empty( $customData)) {
        foreach ($customData as $dataKey => $dataValue) {
Mayur Jadhav's avatar
Mayur Jadhav committed
789
          $customGroupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',$dataKey,'title');
Mayur Jadhav's avatar
Mayur Jadhav committed
790 791 792
          $customGroup[$customGroupName] = $customGroupName;
          $count = 0;
          foreach ($dataValue  as $dataValueKey => $dataValueValue) {
Mayur Jadhav's avatar
Mayur Jadhav committed
793
            $customField[$customGroupName]['custom_'.$dataValueKey]['label'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $dataValueKey, 'label');
Mayur Jadhav's avatar
Mayur Jadhav committed
794
            $customFieldData = grantprograms_getCustomFieldData($dataValueKey);
Mayur Jadhav's avatar
Mayur Jadhav committed
795
            if (CRM_Utils_Array::value('html_type', $customFieldData) == 'Select') {
Mayur Jadhav's avatar
Mayur Jadhav committed
796
              $customField[$customGroupName]['custom_'.$dataValueKey]['value'] = grantprograms_getOptionValueLabel($customFieldData['option_group_id'],$dataValueValue);
797
            }
Mayur Jadhav's avatar
Mayur Jadhav committed
798
            elseif (CRM_Utils_Array::value('html_type', $customFieldData) == 'Select Date') {
Mayur Jadhav's avatar
Mayur Jadhav committed
799
              $customField[$customGroupName]['custom_'.$dataValueKey]['value'] = date('Y-m-d', strtotime($dataValueValue));
800
            }
Mayur Jadhav's avatar
Mayur Jadhav committed
801
            else {
Mayur Jadhav's avatar
Mayur Jadhav committed
802
              $customField[$customGroupName]['custom_'.$dataValueKey]['value'] = $dataValueValue;
Mayur Jadhav's avatar
Mayur Jadhav committed
803
            }
Mayur Jadhav's avatar
Mayur Jadhav committed
804 805 806 807
            $count++;
          }
        }
      }
808 809
      $page->assign('customGroup', $customGroup);
      $page->assign('customField', $customField);
810

Pradeep Nayak's avatar
Pradeep Nayak committed
811
      $grantStatuses = $grantStatus = CRM_Core_OptionGroup::values('grant_status');
Mayur Jadhav's avatar
Mayur Jadhav committed
812 813
      $grantPrograms = CRM_Grant_BAO_GrantProgram::getGrantPrograms();
      $grantTypes = CRM_Core_OptionGroup::values('grant_type');
814 815 816 817 818 819
      if (CRM_Utils_Array::value('grant_program_id', $params)) {
        $grantProgram = $grantPrograms[$params['grant_program_id']];
      }
      else {
        $grantProgram = '';
      }
Mayur Jadhav's avatar
Mayur Jadhav committed
820 821
      $grantType = $grantTypes[$params['grant_type_id']];
      $grantStatus = $grantStatus[$params['status_id']];
822
      $grantIneligibleReasons = CRM_Core_OptionGroup::values('reason_grant_ineligible');
823
      $grantIncompleteReasons = CRM_Core_OptionGroup::values('reason_grant_incomplete');
824

Mayur Jadhav's avatar
Mayur Jadhav committed
825 826 827
      $page->assign('grant_type', $grantType);
      $page->assign('grant_programs', $grantProgram);
      $page->assign('grant_status', $grantStatus);
828 829 830 831 832 833
      if (CRM_Utils_Array::value('grant_rejected_reason_id', $params)) {
        $params['grant_rejected_reason'] = $grantIneligibleReasons[$params['grant_rejected_reason_id']];
      }
      if (CRM_Utils_Array::value('grant_incomplete_reason_id', $params)) {
        $params['grant_incomplete_reason'] = $grantIncompleteReasons[$params['grant_incomplete_reason_id']];
      }
834
      $page->assign('grant', $params);
835 836 837
      $smarty = CRM_Core_Smarty::singleton();
      $sendMail = $smarty->get_template_vars('sendMail');
      if ($sendMail) {
Pradeep Nayak's avatar
Pradeep Nayak committed
838 839
        $previousGrant = $smarty->get_template_vars('previousGrant');
        $previousStatus = '';
Pradeep Nayak's avatar
Pradeep Nayak committed
840
        if ($previousGrant && property_exists($previousGrant, 'status_id')) {
Pradeep Nayak's avatar
Pradeep Nayak committed
841 842 843
          $previousStatus = $grantStatuses[$previousGrant->status_id];
        }
        CRM_Grant_BAO_GrantProgram::sendMail($params['contact_id'], $params, $grantStatus, $objectId, $previousStatus);
844
      }
Mayur Jadhav's avatar
Mayur Jadhav committed
845
    }
Pradeep Nayak's avatar
Pradeep Nayak committed
846 847 848 849 850
    else {
      $smarty = CRM_Core_Smarty::singleton();
      $previousGrant = $smarty->get_template_vars('previousGrant');
      if ($previousGrant && property_exists($previousGrant, 'status_id')) {
        $grantStatuses = CRM_Core_OptionGroup::values('grant_status');
851
        CRM_Grant_BAO_GrantProgram::createStatusChangeActivity($params['contact_id'],
Pradeep Nayak's avatar
Pradeep Nayak committed
852 853 854
        $grantStatuses[$params['status_id']], $grantStatuses[$previousGrant->status_id], $params['contact_id']);
      }
    }
855

856
    $grantStatus = CRM_Core_OptionGroup::values('grant_status', TRUE);
857
    if (isset($endDate)) {
Pradeep Nayak's avatar
Pradeep Nayak committed
858 859
      $infoTooLate = key(CRM_Core_PseudoConstant::accountOptionValues('grant_info_too_late'));
      $days = ' +' . $infoTooLate . ' days';
Pradeep Nayak's avatar
Pradeep Nayak committed
860
      $newDate = date('Y-m-d', strtotime($endDate . $days));
861 862 863 864 865
      if (($newDate <= date('Y-m-d') || date('Y') < date('Y',strtotime($endDate))) && $params['status_id'] == $grantStatus['Submitted']) {
        $reasonGranItneligible = CRM_Core_OptionGroup::values('reason_grant_ineligible');
        $reasonGranItneligible = array_flip($reasonGranItneligible);
        $params['status_id'] = $grantStatus['Ineligible'];
        $params['grant_rejected_reason_id'] = $reasonGranItneligible['Outside dates'];
Pradeep Nayak's avatar
Pradeep Nayak committed
866 867
        $ids['grant_id'] = $objectId;
        $result = CRM_Grant_BAO_Grant::create($params, $ids);
868
      }
Mayur Jadhav's avatar
Mayur Jadhav committed
869 870
    }
  }
Mayur Jadhav's avatar
Mayur Jadhav committed
871 872 873 874 875 876 877 878
  //create financial account entry on grant create
  if ($objectName == 'Grant' && ($op == 'edit' || $op == 'create') && $objectRef->financial_type_id) {
    $smarty = CRM_Core_Smarty::singleton();
    $createItem = TRUE;
    $previousGrant = $smarty->get_template_vars('previousGrant');
    if ($previousGrant && $previousGrant->status_id == $objectRef->status_id) {
      return FALSE;
    }
879
    $status = CRM_Core_OptionGroup::values('grant_status');
Mayur Jadhav's avatar
Mayur Jadhav committed
880 881
    $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
    $financialItemStatus = CRM_Core_PseudoConstant::accountOptionValues('financial_item_status');
Monish Deb's avatar
Monish Deb committed
882
    $amount = $objectRef->amount_total;
Mayur Jadhav's avatar
Mayur Jadhav committed
883 884
    $params = array();
    if ($objectRef->status_id == array_search('Approved for Payment', $status)) {
Monish Deb's avatar
Monish Deb committed
885
      $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($objectRef->financial_type_id, 'Accounts Receivable Account is');
Mayur Jadhav's avatar
Mayur Jadhav committed
886 887 888 889
      $financialItemStatusID = array_search('Unpaid', $financialItemStatus);
      $statusID = array_search('Pending', $contributionStatuses);
    }
    elseif ($objectRef->status_id == array_search('Paid', $status)) {
Monish Deb's avatar
Monish Deb committed
890
      $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($objectRef->financial_type_id, 'Asset Account is');
Mayur Jadhav's avatar
Mayur Jadhav committed
891 892 893
      $statusID = array_search('Completed', $contributionStatuses);
      $createItem = FALSE;
    }
Pradeep Nayak's avatar
Pradeep Nayak committed
894 895
    elseif ($objectRef->status_id == array_search('Withdrawn', $status)) {
      $params['to_financial_account_id'] = CRM_Core_DAO::singleValueQuery("SELECT to_financial_account_id FROM civicrm_financial_trxn  cft
Pradeep Nayak's avatar
Pradeep Nayak committed
896 897
INNER JOIN civicrm_entity_financial_trxn ecft ON ecft.financial_trxn_id = cft.id
WHERE  ecft.entity_id = {$objectRef->id} and ecft.entity_table = 'civicrm_grant'
Pradeep Nayak's avatar
Pradeep Nayak committed
898 899
ORDER BY cft.id DESC LIMIT 1");
      $statusID = array_search('Cancelled', $contributionStatuses);
Pradeep Nayak's avatar
Pradeep Nayak committed
900
      $financialItemStatusID = array_search('Unpaid', $financialItemStatus);
Pradeep Nayak's avatar
Pradeep Nayak committed
901 902
      $amount = -$amount;
    }
Mayur Jadhav's avatar
Mayur Jadhav committed
903 904 905 906 907 908 909 910 911 912 913 914
    if (CRM_Utils_Array::value('to_financial_account_id', $params)) {
      //build financial transaction params
      $trxnParams = array(
        'to_financial_account_id' => $params['to_financial_account_id'],
        'trxn_date' => date('YmdHis'),
        'total_amount' => $amount,
        'currency' => $objectRef->currency,
        'status_id' => $statusID,
        'entity_table' => 'civicrm_grant',
        'entity_id' => $objectId,
      );
      if ($previousGrant && $previousGrant->status_id == array_search('Approved for Payment', $status) && $objectRef->status_id == array_search('Paid', $status)) {
Monish Deb's avatar
Monish Deb committed
915
        $trxnParams['from_financial_account_id'] = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($objectRef->financial_type_id, 'Accounts Receivable Account is');
Mayur Jadhav's avatar
Mayur Jadhav committed
916
      }
Monish Deb's avatar
Monish Deb committed
917
      $trxnId = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
Mayur Jadhav's avatar
Mayur Jadhav committed
918
      if ($createItem) {
Monish Deb's avatar
Monish Deb committed
919
        $financialAccountId = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($objectRef->financial_type_id, 'Accounts Receivable Account is');
Mayur Jadhav's avatar
Mayur Jadhav committed
920 921
        $itemParams = array(
          'transaction_date' => date('YmdHis'),
922
          'contact_id' => $objectRef->contact_id,
Mayur Jadhav's avatar
Mayur Jadhav committed
923 924
          'currency' => $objectRef->currency,
          'amount' => $amount,
925
          'description' => NULL,
Mayur Jadhav's avatar
Mayur Jadhav committed
926 927 928 929 930 931 932 933 934 935
          'status_id' => $financialItemStatusID,
          'financial_account_id' => $financialAccountId,
          'entity_table' => 'civicrm_grant',
          'entity_id' => $objectId
        );
        $trxnIds['id'] = $trxnId->id;
        CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds);
      }
    }
  }
Pradeep Nayak's avatar
Pradeep Nayak committed
936 937 938 939 940 941 942 943 944 945
}

/*
 * hook_civicrm_postProcess
 *
 * @param string $formName form name
 * @param object $form form object
 *
 */
function grantprograms_civicrm_postProcess($formName, &$form) {
Edselopez's avatar
Edselopez committed
946

Mayur Jadhav's avatar
Mayur Jadhav committed
947 948 949 950
  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)) {
Edselopez's avatar
Edselopez committed
951 952 953 954 955 956 957
        $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
958 959 960
      }
    }
  }
961

Edselopez's avatar
Edselopez committed
962 963
  if ($formName == "CRM_Custom_Form_Option") {
    $params = array(
Mayur Jadhav's avatar
Mayur Jadhav committed
964
      'id' => $form->_submitValues['optionId'],
Edselopez's avatar
Edselopez committed
965
      'description' => $form->_submitValues['description'],
Mayur Jadhav's avatar
Mayur Jadhav committed
966
      'option_group_id' => $form->getVar('_optionGroupID'),
Edselopez's avatar
Edselopez committed
967
    );
Mayur Jadhav's avatar
Mayur Jadhav committed
968
    CRM_Core_BAO_OptionValue::create($params);
Edselopez's avatar
Edselopez committed
969 970
  }

Mayur Jadhav's avatar
Mayur Jadhav committed
971
  if ($formName == 'CRM_Grant_Form_Grant' && ($form->getVar('_action') != CRM_Core_Action::DELETE)) {
972

Pradeep Nayak's avatar
Pradeep Nayak committed
973
    // FIXME: cookies error
Mayur Jadhav's avatar
Mayur Jadhav committed
974
    if ($form->getVar('_context') == 'search') {
Mayur Jadhav's avatar
Mayur Jadhav committed
975 976 977
      $array['contact_id'] = $form->_ncid;
      $searchGrants = explode(',', $form->_searchGrants);
      $grants = array_flip($searchGrants);
Pradeep Nayak's avatar
Pradeep Nayak committed
978 979 980
      $foundit = FALSE;
      foreach ($grants as $gKey => $gVal) {
        if ($foundit) {
981
          $next = $gKey;
Pradeep Nayak's avatar
Pradeep Nayak committed
982 983
          break;
        }
984 985
        if ($gKey == $form->_next) {
          $next = $gKey;
Pradeep Nayak's avatar
Pradeep Nayak committed
986 987 988 989 990 991 992
          if($gVal == end($grants)) {
            reset($grants);
            $next = key($grants);
          }
          $foundit = TRUE;
        }
      }
Mayur Jadhav's avatar
Mayur Jadhav committed
993 994
      $grantParams['id'] = $next;
      $result = CRM_Grant_BAO_GrantProgram::getGrants($grantParams);
Pradeep Nayak's avatar
Pradeep Nayak committed
995
      if (CRM_Utils_Array::value($form->getButtonName('submit', 'savenext'), $_POST)) {
Mayur Jadhav's avatar
Mayur Jadhav committed
996
        if ($form->getVar('_id') != $form->_prev) {
997
          CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/grant',
Mayur Jadhav's avatar
Mayur Jadhav committed
998
            "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}"));
999
        }
Pradeep Nayak's avatar
Pradeep Nayak committed
1000 1001
        else {
          CRM_Core_Session::setStatus( ts('The next record in the Search no longer exists. Select another record to edit if desired.'));
1002
          CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/grant/search',
Pradeep Nayak's avatar
Pradeep Nayak committed
1003 1004
            "force=1&qfKey={$form->_key}"));
        }
1005
      }
Pradeep Nayak's avatar
Pradeep Nayak committed
1006
      elseif (CRM_Utils_Array::value( $form->getButtonName('upload', 'new'), $_POST)) {
1007
        CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/grant',
Mayur Jadhav's avatar
Mayur Jadhav committed
1008
          "reset=1&action=add&context=grant&cid={$array['contact_id']}"));
1009
      }
Pradeep Nayak's avatar
Pradeep Nayak committed
1010
      else {
1011
        CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/grant/search',
Pradeep Nayak's avatar
Pradeep Nayak committed
1012 1013 1014 1015
          "force=1&qfKey={$form->_key}"));
      }
    }
  }
Pradeep Nayak's avatar
Pradeep Nayak committed
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
}

/*
 * hook_civicrm_searchTasks
 *
 * @param string $objectName form name
 * @param array $tasks search task
 *
 */
function grantprograms_civicrm_searchTasks($objectName, &$tasks) {
1026
  if ($objectName == 'grant' && !strstr($_GET['q'], 'payment/search')
Mayur Jadhav's avatar
Mayur Jadhav committed
1027
    && CRM_Core_Permission::check('create payments in CiviGrant')) {
1028
    $tasks[PAY_GRANTS] = array(
Pradeep Nayak's avatar
Pradeep Nayak committed
1029 1030
      'title' => ts('Pay Grants'),
      'class' => array('CRM_Grant_Form_Task_Pay',
1031
        'CRM_Grant_Form_Task_GrantPayment'
Pradeep Nayak's avatar
Pradeep Nayak committed
1032 1033 1034 1035
      ),
      'result' => FALSE,
    );
  }
Mayur Jadhav's avatar
Mayur Jadhav committed
1036
}
Mayur Jadhav's avatar
Mayur Jadhav committed
1037 1038

function grantprograms_getOptionValueLabel($optioGroupID, $value) {
1039
  $value = CRM_Core_DAO::escapeString($value);
Mayur Jadhav's avatar
Mayur Jadhav committed
1040 1041 1042
  $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
1043

Mayur Jadhav's avatar
Mayur Jadhav committed
1044 1045 1046 1047 1048 1049 1050 1051 1052
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