grantprograms.php 46.4 KB
Newer Older
1
<?php
2
require_once 'grantprograms.civix.php';
3 4
require_once 'grantprograms_data_define.php';

5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/**
 * 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
25 26 27
  _grantprograms_civix_civicrm_install();
  $smarty = CRM_Core_Smarty::singleton();
  $config = CRM_Core_Config::singleton();
28
  grantprograms_define($config->extensionsDir);
Mayur Jadhav's avatar
Mayur Jadhav committed
29
  $data = $smarty->fetch($config->extensionsDir . DIRECTORY_SEPARATOR . 'biz.jmaconsulting.grantprograms/sql/civicrm_msg_template.tpl');
Pradeep Nayak's avatar
Pradeep Nayak committed
30 31
  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
32
  grantprograms_addRemoveMenu(TRUE);
Pradeep Nayak's avatar
Pradeep Nayak committed
33
  return TRUE;
34 35 36 37 38 39
}

/**
 * Implementation of hook_civicrm_uninstall
 */
function grantprograms_civicrm_uninstall() {
Mayur Jadhav's avatar
Mayur Jadhav committed
40
  $config = CRM_Core_Config::singleton();
41 42 43
  $file = fopen($config->extensionsDir .'biz.jmaconsulting.grantprograms/grantprograms_data_define.php', 'w'); 
  fwrite($file, "<?php\n// placeholder which ensures custom group and custom fields and custom tables.\n?>");
  fclose($file);
44 45 46 47 48 49 50
  return _grantprograms_civix_civicrm_uninstall();
}

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

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

90 91 92 93 94 95
/*
 * hook_civicrm_grantAssessment
 *
 * @param array $params to alter
 *
 */
Pradeep Nayak's avatar
Pradeep Nayak committed
96
function grantprograms_civicrm_grantAssessment(&$params) {
Mayur Jadhav's avatar
Mayur Jadhav committed
97 98 99 100 101 102 103 104
  $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;
105
      } 
Mayur Jadhav's avatar
Mayur Jadhav committed
106 107
      elseif ($sumAmountGranted > 0) {
        $priority = 0;
108
      }
Mayur Jadhav's avatar
Mayur Jadhav committed
109 110 111 112
    } 
    else {
      $priority = -10;
    }
Mayur Jadhav's avatar
Mayur Jadhav committed
113
    if (array_key_exists('assessment', $params) && $params['adjustment_value']) {
Mayur Jadhav's avatar
Mayur Jadhav committed
114 115
      if ($params['assessment'] != 0) {
        $params['assessment'] = $params['assessment'] - $priority;
116 117 118
      }
    }
  }
Mayur Jadhav's avatar
Mayur Jadhav committed
119
   
120 121 122 123
  $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
124
  $grantStatuses = CRM_Core_OptionGroup::values('grant_status', TRUE);
Mayur Jadhav's avatar
Mayur Jadhav committed
125
  if ($algoType == 'immediate' && !CRM_Utils_Array::value('manualEdit', $params) && $params['status_id'] == $grantStatuses['Eligible']) {
126 127 128 129 130 131
    $params['amount_granted'] = quickAllocate($grantProgram, $params);
    if (empty($params['amount_granted'])) {
      unset($params['amount_granted']);
    }
  } 
}
Pradeep Nayak's avatar
Pradeep Nayak committed
132 133 134 135 136 137

/**
 * Algorithm for quick allocation
 *
 */
function quickAllocate($grantProgram, $value) {
138
  $grantThresholds = CRM_Core_OptionGroup::values('grant_thresholds', TRUE);
Mayur Jadhav's avatar
Mayur Jadhav committed
139
  $amountGranted = NULL;
140
  $grant_id = NULL;
141
  if (CRM_Utils_Array::value('assessment', $value)) {
Mayur Jadhav's avatar
Mayur Jadhav committed
142 143
    $userparams['contact_id'] = $value['contact_id'];
    $userparams['grant_program_id'] = $grantProgram->id;
144 145 146 147
    if (!empty($value['id'])) {
      $grant_id = $value['id'];
    }
    $userAmountGranted = CRM_Grant_BAO_GrantProgram::getUserAllocatedAmount($userparams, $grant_id);
Mayur Jadhav's avatar
Mayur Jadhav committed
148
    $defalutGrantedAmount = CRM_Grant_BAO_GrantProgram::getCurrentGrantAmount($grant_id);
Mayur Jadhav's avatar
Mayur Jadhav committed
149
    $amountEligible = $grantThresholds['Maximum Grant'] - $userAmountGranted;
Mayur Jadhav's avatar
Mayur Jadhav committed
150 151 152
    if ($amountEligible > $grantProgram->remainder_amount) {
      $amountEligible = $grantProgram->remainder_amount;
    }
153
    $value['amount_total'] = str_replace(',', '', $value['amount_total']);
154
    $requestedAmount = CRM_Utils_Money::format((($value['assessment']/100) * $value['amount_total'] * ($grantThresholds['Funding factor'] / 100)), NULL, NULL, TRUE);
155 156 157 158
    // Don't grant more money than originally requested
    if ($requestedAmount > $value['amount_total']) {
    	$requestedAmount = $value['amount_total'];
    }
Mayur Jadhav's avatar
Mayur Jadhav committed
159 160
    if ($requestedAmount > $amountEligible) {
      $requestedAmount = $amountEligible;
161
    }
Mayur Jadhav's avatar
Mayur Jadhav committed
162 163
    if ($requestedAmount > 0) {
      $remainderDifference = $requestedAmount - $defalutGrantedAmount;
Mayur Jadhav's avatar
Mayur Jadhav committed
164 165 166
      if ($remainderDifference < $grantProgram->remainder_amount) {
        $amountGranted = $requestedAmount;
      }
Pradeep Nayak's avatar
Pradeep Nayak committed
167 168
    }
  }
Mayur Jadhav's avatar
Mayur Jadhav committed
169
   
Pradeep Nayak's avatar
Pradeep Nayak committed
170
  //Update grant program
Mayur Jadhav's avatar
Mayur Jadhav committed
171
  if ($amountGranted > 0) {
Mayur Jadhav's avatar
Mayur Jadhav committed
172
    $grantProgramParams['remainder_amount'] = $grantProgram->remainder_amount - $remainderDifference;
Mayur Jadhav's avatar
Mayur Jadhav committed
173 174 175 176
    $grantProgramParams['id'] =  $grantProgram->id;
    $ids['grant_program']     =  $grantProgram->id;
    CRM_Grant_BAO_GrantProgram::create($grantProgramParams, $ids);
  }
Pradeep Nayak's avatar
Pradeep Nayak committed
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
  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',
      'title' => ts('View Grant Program') 
    ),
    CRM_Core_Action::UPDATE  => array(
      'name'  => ts('Edit'),
      'url'   => 'civicrm/grant_program',
      'qs'    => 'action=update&id=%%id%%&reset=1',
      'title' => ts('Edit Grant Program') 
    ),
    CRM_Core_Action::DELETE  => array(
      'name'  => ts('Delete'),
      'url'   => 'civicrm/grant_program',
      'qs'    => 'action=delete&id=%%id%%&reset=1',
      'title' => ts('Delete') 
    ),
    CRM_Core_Action::ADD  => array(
      'name'  => ts('Allocate Approved (Trial)'),
      'url'   => 'civicrm/grant_program',
      'qs'    => '#',
      'extra'   => 'id=allocation',
      'title' => ts('Allocate Approved (Trial)') 
    ),
    CRM_Core_Action::BROWSE  => array(
      'name'  => ts('Finalize Approved Allocations'),
      'url'   => 'civicrm/grant_program',
      'qs'    => '#',
      'extra'   => 'id=finalize',
      'title' => ts('Finalize Approved Allocations') 
    ),
    CRM_Core_Action::MAP  => array(
Mayur Jadhav's avatar
Mayur Jadhav committed
220
      'name'  => ts('Mark remaining unapproved Grants as Ineligible'),
Pradeep Nayak's avatar
Pradeep Nayak committed
221 222 223
      'url'   => 'civicrm/grant_program',
      'qs'    => '#',
      'extra'   => 'id=reject',
Mayur Jadhav's avatar
Mayur Jadhav committed
224
      'title' => ts('Mark remaining unapproved Grants as Ineligible') 
Pradeep Nayak's avatar
Pradeep Nayak committed
225 226 227
    ),
  );
  return $_links;
228 229
}

Edselopez's avatar
Edselopez committed
230
function grantprograms_civicrm_permission(&$permissions) {
Pradeep Nayak's avatar
Pradeep Nayak committed
231 232
  $prefix = ts('CiviCRM Grant Program') . ': '; // name of extension or module
  $permissions['edit grant finance'] = $prefix . ts('edit grant finance');
233
  $permissions['edit grant program'] = $prefix . ts('edit grant programs in CiviGrant');
234 235 236
  $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
237
}
238 239 240 241 242 243 244 245
/*
 * hook_civicrm_buildForm civicrm hook
 * 
 * @param string $formName form name
 * @param object $form form object
 *
*/
function grantprograms_civicrm_buildForm($formName, &$form) {
246 247 248 249 250 251 252 253 254 255 256 257

  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;
    }
    $grantUrl = CRM_Utils_System::url('civicrm/contact/view/grant', 
      'reset=1&action=view&id=' . $activityValues['source_record_id'] . '&cid=' . current($activityValues['assignee_contact']));
    $form->assign('grantUrl', $grantUrl);
  }
Mayur Jadhav's avatar
Mayur Jadhav committed
258
  
Mayur Jadhav's avatar
Mayur Jadhav committed
259
  if ($formName == 'CRM_Grant_Form_Grant' && ($form->getVar('_action') != CRM_Core_Action::DELETE)) {
Mayur Jadhav's avatar
Mayur Jadhav committed
260 261 262
    $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
263 264
    $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
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
    if (CRM_Utils_Request::retrieve('context', 'String', $form) == 'search' && isset($form->_next)) {
      $form->addButtons(array( 
        array ('type' => 'upload',
          'name' => ts('Save'), 
          'isDefault' => true),
        array ('type' => 'submit',
          'name' => ts('Save and Next'),
          'subName' => 'savenext'),   
        array ('type' => 'upload',
          'name' => ts('Save and New'), 
          'js' => array('onclick' => "return verify();"),
          'subName' => 'new' ),
        array ('type' => 'cancel', 
          'name' => ts('Cancel')),
        ) 
      );
    }
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
    $empId = $genId = $ccId = '-1';
    if ($form->getVar('_id')) {
      $tableName1 = CRM_Core_DAO::getFieldValue('CRM_Core_BAO_CustomGroup', NEI_EMPLOYMENT, 'table_name', 'name');
      $query1 = "SELECT id FROM {$tableName1} WHERE entity_id = {$form->getVar('_id')}";
      $empId = CRM_Core_DAO::singleValueQuery($query1);
      $tableName2 = CRM_Core_DAO::getFieldValue('CRM_Core_BAO_CustomGroup', NEI_GENERAL, 'table_name', 'name');
      $query2 = "SELECT id FROM {$tableName2} WHERE entity_id = {$form->getVar('_id')}";
      $genId = CRM_Core_DAO::singleValueQuery($query2);
      $tableName3 = CRM_Core_DAO::getFieldValue('CRM_Core_BAO_CustomGroup', NEI_CONFERENCE, 'table_name', 'name');
      $query3 = "SELECT id FROM {$tableName3} WHERE entity_id = {$form->getVar('_id')}";
      $ccId = CRM_Core_DAO::singleValueQuery($query3);
    }
    
      $form->assign('employment', 'custom_'.EMPLOYED_INDICATE.'_'.$empId);
      $form->assign('employment_other', 'custom_'.EMPLOYMENT_OTHER.'_'.$empId);
      $form->assign('position', 'custom_'.POSITION.'_'.$empId);
      $form->assign('position_other', 'custom_'.POSITION_OTHER.'_'.$empId);
      $form->assign('employment_setting', 'custom_'.EMPLOYMENT_SETTING.'_'.$empId);
      $form->assign('employment_setting_other', 'custom_'.EMPLOYMENT_SETTING_OTHER.'_'.$empId);
      $form->assign('init', 'custom_'.NEI_HEAR_ABOUT.'_'.$genId);
      $form->assign('init_other', 'custom_'.INITIATIVE_OTHER.'_'.$genId);
      $form->assign('course', 'custom_'.COURSE_CONFERENCE_TYPE.'_'.$ccId);
      $form->assign('course_other', 'custom_'.COURSE_CONFERENCE_TYPE_OTHER.'_'.$ccId);
      CRM_Core_Region::instance('page-body')->add(array(
        'template' => 'CRM/Grant/Form/GrantExtra.tpl',
      ));
308 309 310 311 312 313 314
    $form->_reasonGrantRejected = CRM_Core_OptionGroup::values('reason_grant_ineligible');
    $form->add('select', 
      'grant_rejected_reason_id', 
      ts('Reason Grant Ineligible'),
      array('' => ts('- select -')) + $form->_reasonGrantRejected, 
      FALSE
    );
315

316 317 318 319 320 321 322 323
    $form->_reasonGrantIncomplete = CRM_Core_OptionGroup::values('reason_grant_incomplete');
    $form->add('select', 
      'grant_incomplete_reason_id', 
      ts('Reason Grant Incomplete'),
      array('' => ts('- select -')) + $form->_reasonGrantIncomplete, 
      FALSE
    );

324 325 326 327 328 329 330
    $form->_grantPrograms = CRM_Grant_BAO_GrantProgram::getGrantPrograms();
    $form->add('select', 
      'grant_program_id', 
      ts('Grant Programs'),
      array('' => ts('- select -')) + $form->_grantPrograms,
      TRUE
    );
331
         
332 333 334 335 336 337 338 339 340 341
    //Financial Type RG-125
    $financialType = CRM_Contribute_PseudoConstant::financialType();
    if (count($financialType)) {
      $form->assign('financialType', $financialType);
    }
    $form->add('select', 'financial_type_id', 
      ts('Financial Type'), 
      array('' => ts('- Select Financial Type -')) + $financialType,
      FALSE 
    );      
Pradeep Nayak's avatar
Pradeep Nayak committed
342 343 344 345 346 347 348 349 350 351
    $showFields = FALSE;
    if ($form->getVar('_id')) {
      if (CRM_Core_Permission::check('administer CiviGrant')) {
        $form->add('text', 'assessment', ts('Assessment'));
      }
    
      // 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();
352 353 354 355 356 357 358 359 360
        }
        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
361 362 363 364 365 366
        }
        CRM_Core_Region::instance('page-body')->add(array(
          'template' => 'CRM/Grant/Form/Freeze.tpl',
        ));
      }
      $showFields = TRUE;
367
    }
Pradeep Nayak's avatar
Pradeep Nayak committed
368
    $form->assign('showFields', $showFields);
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
  }
  if ($formName == "CRM_Grant_Form_Search") {
    $grantPrograms = CRM_Grant_BAO_GrantProgram::getGrantPrograms();
    $form->add('select', 
      'grant_program_id',  
      ts('Grant Programs'),
      array('' => ts('- select -')) + $grantPrograms
    );
    $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).', 
Edselopez's avatar
Edselopez committed
384
        array(1 => CRM_Utils_Money::format('9.99', ' '))), 
385 386 387 388 389 390 391 392 393
      'money'
    );
    $form->add('text', 
      'grant_amount_total_high', 
      ts('To'), 
      array('size' => 8, 'maxlength' => 8)
    ); 
    $form->addRule('grant_amount_total_high', 
      ts('Please enter a valid money value (e.g. %1).', 
Edselopez's avatar
Edselopez committed
394
        array(1 => CRM_Utils_Money::format('99.99', ' '))), 
395 396 397 398 399 400 401
      'money'
    );
    $form->add('text', 
      'grant_assessment_low', 
      ts('From'), 
      array('size' => 9, 'maxlength' => 9)
    );
402
        
403 404 405 406 407 408 409 410 411 412 413 414
    $form->add('text', 
      'grant_assessment_high', 
      ts('To'), 
      array('size' => 9, 'maxlength' => 9)
    );
    $form->add('text', 
      'grant_amount_low', 
      ts('From'), 
      array('size' => 8, 'maxlength' => 8)
    ); 
    $form->addRule('grant_amount_low', 
      ts('Please enter a valid money value (e.g. %1).', 
Pradeep Nayak's avatar
Pradeep Nayak committed
415
        array(1 => CRM_Utils_Money::format('9.99', ' '))), 
416 417
      'money'
    );
Pradeep Nayak's avatar
Pradeep Nayak committed
418

419 420 421 422 423 424 425
    $form->add('text', 
      'grant_amount_high', 
      ts('To'), 
      array('size' => 8, 'maxlength' => 8)
    );
    $form->addRule('grant_amount_high', 
      ts('Please enter a valid money value (e.g. %1).', 
Pradeep Nayak's avatar
Pradeep Nayak committed
426
        array(1 => CRM_Utils_Money::format('99.99', ' '))), 
427 428
      'money'
    );
429
  }
430

431 432 433
  
  if ($formName == 'CRM_Custom_Form_Field') {
    
434 435 436
    for ($i = 1; $i <= $formName::NUM_OPTION; $i++) {
      $form->add('text', 
        'option_description['. $i .']', 
Mayur Jadhav's avatar
Mayur Jadhav committed
437
        'Mark', 
438 439
        array('id' => 'marks') 
      );
440
    } 
Edselopez's avatar
Edselopez committed
441 442 443 444
    $form->assign('edit_form', 1);
    CRM_Core_Region::instance('page-body')->add(array(
      'template' => 'CRM/Grant/Form/CustomFields.tpl',
    ));
445
  }
446 447 448
  if ($formName == 'CRM_Custom_Form_Option') {
    $form->add('text', 
      'description', 
Mayur Jadhav's avatar
Mayur Jadhav committed
449
      'Mark', 
450 451
      array('id' => 'marks')
    );
Edselopez's avatar
Edselopez committed
452 453 454
    CRM_Core_Region::instance('page-body')->add(array(
      'template' => 'CRM/Grant/Form/CustomFields.tpl',
    ));
455
  }
Mayur Jadhav's avatar
Mayur Jadhav committed
456
  
Edselopez's avatar
Edselopez committed
457
  if ($formName == 'CRM_Grant_Form_Search' && $form->get('context') == 'dashboard') {
Pradeep Nayak's avatar
Pradeep Nayak committed
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
    //Version of grant program listings
    $grantProgram = array();
    require_once 'CRM/Grant/DAO/GrantProgram.php';
    $dao = new CRM_Grant_DAO_GrantProgram();
      
    $dao->orderBy('label');
    $dao->find();
      
    while ($dao->fetch()) {
      $grantProgram[$dao->id] = array();
      CRM_Core_DAO::storeValues( $dao, $grantProgram[$dao->id]);
      $action = array_sum(array_keys(links()));
      $grantProgram[$dao->id]['action'] = CRM_Core_Action::formLink(links(), $action, 
                                          array('id' => $dao->id));
    }
473
    $grantType   = CRM_Core_OptionGroup::values('grant_type');
474
    $grantStatus = CRM_Grant_BAO_GrantProgram::grantProgramStatus( );
Pradeep Nayak's avatar
Pradeep Nayak committed
475
    foreach ( $grantProgram as $key => $value ) {
Edselopez's avatar
Edselopez committed
476
      $grantProgram[$key]['grant_type_id'] = $grantType[$grantProgram[$key]['grant_type_id']];
Pradeep Nayak's avatar
Pradeep Nayak committed
477 478 479 480 481 482
      $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
483 484
  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
485
    $form->assign('hideAttachments', 1);
486 487 488
    $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));
489 490
    //Freeze Prior Year's Assessment field
    $form->_elements[$form->_elementIndex['prev_assessment']]->freeze();
Edselopez's avatar
Edselopez committed
491
    // Filter out grant being edited from search results
492
    $form->assign('grant_id', $form->getVar('_id'));
Pradeep Nayak's avatar
Pradeep Nayak committed
493
 }
494 495
}

Edselopez's avatar
Edselopez committed
496
function grantprograms_civicrm_pageRun( &$page ) {
497 498 499 500 501 502
  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
503
    $smarty = CRM_Core_Smarty::singleton();
504
    if ($smarty->_tpl_vars['action'] & CRM_Core_Action::VIEW) {
Mayur Jadhav's avatar
Mayur Jadhav committed
505
      $smarty->_tpl_vars['assessment'] = CRM_Core_DAO::getFieldValue('CRM_Grant_DAO_Grant', $smarty->_tpl_vars['id'], 'assessment', 'id');
506 507
      $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
508 509 510 511
      CRM_Core_Region::instance('page-body')->add(array(
        'template' => 'CRM/Grant/Page/GrantExtra.tpl',
      ));
    }
512 513
  }
  
Mayur Jadhav's avatar
Mayur Jadhav committed
514 515 516
  if ($page->getVar('_name') == "CRM_Custom_Page_Option") { 
    $params['id'] = $page->getVar('_fid');
    $params['custom_group_id'] = $page->getVar('_gid');
Mayur Jadhav's avatar
Mayur Jadhav committed
517
    CRM_Core_BAO_CustomField::retrieve($params, $defaults);
Mayur Jadhav's avatar
Mayur Jadhav committed
518 519 520 521 522 523 524
    $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
525 526
    $page->assign('view_form', 1);
    CRM_Core_Region::instance('page-body')->add(array(
Mayur Jadhav's avatar
Mayur Jadhav committed
527
      'template' => 'CRM/Grant/Form/CustomFieldsView.tpl',
Edselopez's avatar
Edselopez committed
528 529 530
    ));
  }
}
531 532 533 534 535 536 537 538 539 540 541
/*
 * 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;
542 543
  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
544 545 546 547
    $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) {
548
      $errors[''] = ts('Error');
Mayur Jadhav's avatar
Mayur Jadhav committed
549 550 551 552 553 554 555
      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");
556 557
    }
  }
Mayur Jadhav's avatar
Mayur Jadhav committed
558
  if ($formName == 'CRM_Grant_Form_Grant' && ($form->getVar('_action') != CRM_Core_Action::DELETE)) {
559
    $defaults = array();
560
    $params['id'] = $form->_submitValues['grant_program_id'];
561
    CRM_Grant_BAO_GrantProgram::retrieve($params, $defaults);
Pradeep Nayak's avatar
Pradeep Nayak committed
562
    if (array_key_exists('amount_granted', $form->_submitValues) && CRM_Utils_Array::value('remainder_amount', $defaults) < $form->_submitValues['amount_granted']) {
563
      $errors['amount_granted'] = ts('You need to increase the Grant Program Total Amount');
564
    }
565 566 567 568
    
    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');
    }
569
  }
Pradeep Nayak's avatar
Pradeep Nayak committed
570
  if ($formName == 'CRM_Grant_Form_Search') {
571
    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
572 573 574
      foreach ($fields as $fieldKey => $fieldValue) {
        if (strstr($fieldKey, 'mark_x_')) {
          $grantID = ltrim( $fieldKey, 'mark_x_' );
Mayur Jadhav's avatar
Mayur Jadhav committed
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
          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
590 591 592 593 594
          }
        }
      }
    }
  } 
595
  return empty($errors) ? TRUE : $errors;
Pradeep Nayak's avatar
Pradeep Nayak committed
596 597
}

Pradeep Nayak's avatar
Pradeep Nayak committed
598 599
function grantprograms_civicrm_pre($op, $objectName, $id, &$params) {
  if ($objectName == 'Grant' && ($op == 'edit' || $op == 'create')) { 
Pradeep Nayak's avatar
Pradeep Nayak committed
600
    $grantStatus = CRM_Core_OptionGroup::values('grant_status');
Pradeep Nayak's avatar
Pradeep Nayak committed
601
    $assessmentAmount = 0;
Mayur Jadhav's avatar
Mayur Jadhav committed
602
    $calculateAssessment = FALSE;
Mayur Jadhav's avatar
Mayur Jadhav committed
603
    $params['adjustment_value'] = TRUE;
Pradeep Nayak's avatar
Pradeep Nayak committed
604
    $previousGrant = NULL;
605 606
    $smarty = CRM_Core_Smarty::singleton();
    $sendMail = TRUE;
Mayur Jadhav's avatar
Mayur Jadhav committed
607 608 609
    if ($objectName == 'Grant' && $op == "edit") {
      $grantParams = array('id' => $id);
      $previousGrant = CRM_Grant_BAO_Grant::retrieve($grantParams, CRM_Core_DAO::$_nullArray);
610 611 612
      if ($params['status_id'] == $previousGrant->status_id) {
        $sendMail = FALSE;
      }
Mayur Jadhav's avatar
Mayur Jadhav committed
613
      if ((CRM_Utils_Array::value('assessment', $params) == $previousGrant->assessment)) {
Mayur Jadhav's avatar
Mayur Jadhav committed
614 615 616
        $calculateAssessment = TRUE;
      }
    }
617
    $smarty->assign('sendMail', $sendMail);
Pradeep Nayak's avatar
Pradeep Nayak committed
618
    $grantStatusApproved = array_search('Approved for Payment', $grantStatus);
Pradeep Nayak's avatar
Pradeep Nayak committed
619 620 621
    if ($grantStatusApproved == $params['status_id']  && empty($params['decision_date']) && 
      ($op == 'create') || ($previousGrant && !$previousGrant->decision_date && 
      $previousGrant->status_id != $params['status_id'])) {
Pradeep Nayak's avatar
Pradeep Nayak committed
622 623
      $params['decision_date'] = date('Ymd');
    }
Mayur Jadhav's avatar
Mayur Jadhav committed
624
    if ((empty($params['assessment']) || $calculateAssessment) && ($op == 'create' || $op == 'edit')) {
625 626 627 628 629 630 631 632 633 634 635
      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());
            if (!empty($customFields)) { 
              $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
636 637 638 639 640 641 642
            }
          }
        }
      }
    }
    if(!empty($assessmentAmount)) {
      $params['assessment'] = $assessmentAmount;
Mayur Jadhav's avatar
Mayur Jadhav committed
643 644 645
    } 
    elseif ($objectName == 'Grant' && $op == "edit") {
      $params['adjustment_value'] = FALSE;
Pradeep Nayak's avatar
Pradeep Nayak committed
646
    }
Mayur Jadhav's avatar
Mayur Jadhav committed
647 648
    
    if ($objectName == 'Grant' && $op == "edit") {
649
      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
650 651 652 653 654 655 656
        $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);
657 658 659
        $params['manualEdit'] = TRUE;
      }
    }
Mayur Jadhav's avatar
Mayur Jadhav committed
660 661 662
    elseif ($objectName == 'Grant' && $op == "create" && CRM_Utils_Array::value('amount_granted', $params)) {
      $params['manualEdit'] = TRUE;
    }
Mayur Jadhav's avatar
Mayur Jadhav committed
663
    
664 665 666
    if (!empty($id)) {
      $params['id'] = $id;
    }
667
    CRM_Utils_Hook::grantAssessment($params);
Pradeep Nayak's avatar
Pradeep Nayak committed
668 669 670 671
    if ($op == 'edit') {
      $smarty = CRM_Core_Smarty::singleton();
      $smarty->assign('previousGrant', $previousGrant);
    }
Mayur Jadhav's avatar
Mayur Jadhav committed
672 673
    $config = CRM_Core_Config::singleton();
    $config->_params = $params;
Pradeep Nayak's avatar
Pradeep Nayak committed
674 675 676 677 678 679 680 681
  }
}

/*
 * hook_civicrm_post
 *
 */
function grantprograms_civicrm_post($op, $objectName, $objectId, &$objectRef) {
Mayur Jadhav's avatar
Mayur Jadhav committed
682
  //send mail after grant save
Mayur Jadhav's avatar
Mayur Jadhav committed
683
  $config = CRM_Core_Config::singleton();
Mayur Jadhav's avatar
Mayur Jadhav committed
684
  if ($objectName == 'Grant' && isset($config->_params) && !isset($config->_params['restrictEmail'])) {
Mayur Jadhav's avatar
Mayur Jadhav committed
685 686 687 688 689 690 691 692 693 694 695 696 697 698
    $params = $config->_params;
    // added by JMA fixme in module
    $grantProgram  = new CRM_Grant_DAO_GrantProgram();
    $grantProgram->id = $params['grant_program_id'];
    $page = new CRM_Core_Page();
    if ($grantProgram->find(TRUE)) {
      $params['is_auto_email'] = $grantProgram->is_auto_email;
    }
     
    if ($params['is_auto_email'] == 1) {
      // FIXME: for grant profiles
      $customData = array();
      if (!CRM_Utils_Array::value('custom', $params)) {
        $params['custom'] = array();
699 700
        $entityValues = CRM_Core_BAO_CustomValueTable::getEntityValues($objectId, 'Grant');
        getCustomFields(array_filter($entityValues), $customData);
Mayur Jadhav's avatar
Mayur Jadhav committed
701
      }
Mayur Jadhav's avatar
Mayur Jadhav committed
702
      foreach ($params['custom'] as $key => $value) {
Mayur Jadhav's avatar
Mayur Jadhav committed
703
        foreach ($value as $index => $field) {
Mayur Jadhav's avatar
Mayur Jadhav committed
704
          if (!empty($field['value'])) {
Mayur Jadhav's avatar
Mayur Jadhav committed
705 706 707 708 709 710 711 712 713 714
            $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'];
            }
          }
        }
      }
715
      $customGroup = $customField = array();
Mayur Jadhav's avatar
Mayur Jadhav committed
716 717
      if (!empty( $customData)) {
        foreach ($customData as $dataKey => $dataValue) {
Mayur Jadhav's avatar
Mayur Jadhav committed
718
          $customGroupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',$dataKey,'title');
Mayur Jadhav's avatar
Mayur Jadhav committed
719 720 721
          $customGroup[$customGroupName] = $customGroupName;
          $count = 0;
          foreach ($dataValue  as $dataValueKey => $dataValueValue) {
Mayur Jadhav's avatar
Mayur Jadhav committed
722
            $customField[$customGroupName]['custom_'.$dataValueKey]['label'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $dataValueKey, 'label');
Mayur Jadhav's avatar
Mayur Jadhav committed
723
            $customFieldData = grantprograms_getCustomFieldData($dataValueKey);
Mayur Jadhav's avatar
Mayur Jadhav committed
724
            if (CRM_Utils_Array::value('html_type', $customFieldData) == 'Select') {
Mayur Jadhav's avatar
Mayur Jadhav committed
725
              $customField[$customGroupName]['custom_'.$dataValueKey]['value'] = grantprograms_getOptionValueLabel($customFieldData['option_group_id'],$dataValueValue);
Mayur Jadhav's avatar
Mayur Jadhav committed
726
            } 
Mayur Jadhav's avatar
Mayur Jadhav committed
727
            elseif (CRM_Utils_Array::value('html_type', $customFieldData) == 'Select Date') {
Mayur Jadhav's avatar
Mayur Jadhav committed
728
              $customField[$customGroupName]['custom_'.$dataValueKey]['value'] = date('Y-m-d', strtotime($dataValueValue));
Mayur Jadhav's avatar
Mayur Jadhav committed
729 730
            } 
            else {
Mayur Jadhav's avatar
Mayur Jadhav committed
731
              $customField[$customGroupName]['custom_'.$dataValueKey]['value'] = $dataValueValue;
Mayur Jadhav's avatar
Mayur Jadhav committed
732
            }
Mayur Jadhav's avatar
Mayur Jadhav committed
733 734 735 736
            $count++;
          }
        }
      }
737 738
      $page->assign('customGroup', $customGroup);
      $page->assign('customField', $customField);
Mayur Jadhav's avatar
Mayur Jadhav committed
739
      
Pradeep Nayak's avatar
Pradeep Nayak committed
740
      $grantStatuses = $grantStatus = CRM_Core_OptionGroup::values('grant_status');
Mayur Jadhav's avatar
Mayur Jadhav committed
741 742 743 744 745
      $grantPrograms = CRM_Grant_BAO_GrantProgram::getGrantPrograms();
      $grantTypes = CRM_Core_OptionGroup::values('grant_type');
      $grantProgram = $grantPrograms[$params['grant_program_id']];
      $grantType = $grantTypes[$params['grant_type_id']];
      $grantStatus = $grantStatus[$params['status_id']];
746
      $grantIneligibleReasons = CRM_Core_OptionGroup::values('reason_grant_ineligible');
747
      $grantIncompleteReasons = CRM_Core_OptionGroup::values('reason_grant_incomplete');
Mayur Jadhav's avatar
Mayur Jadhav committed
748 749 750 751
      
      $page->assign('grant_type', $grantType);
      $page->assign('grant_programs', $grantProgram);
      $page->assign('grant_status', $grantStatus);
752 753 754 755 756 757
      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']];
      }
758
      $page->assign('grant', $params);
759 760 761
      $smarty = CRM_Core_Smarty::singleton();
      $sendMail = $smarty->get_template_vars('sendMail');
      if ($sendMail) {
Pradeep Nayak's avatar
Pradeep Nayak committed
762 763
        $previousGrant = $smarty->get_template_vars('previousGrant');
        $previousStatus = '';
Pradeep Nayak's avatar
Pradeep Nayak committed
764
        if ($previousGrant && property_exists($previousGrant, 'status_id')) {
Pradeep Nayak's avatar
Pradeep Nayak committed
765 766 767
          $previousStatus = $grantStatuses[$previousGrant->status_id];
        }
        CRM_Grant_BAO_GrantProgram::sendMail($params['contact_id'], $params, $grantStatus, $objectId, $previousStatus);
768
      }
Mayur Jadhav's avatar
Mayur Jadhav committed
769
    }
770
    
771
    $grantStatus = CRM_Core_OptionGroup::values('grant_status', TRUE);
772
    if (isset($endDate)) {
Pradeep Nayak's avatar
Pradeep Nayak committed
773 774
      $infoTooLate = key(CRM_Core_PseudoConstant::accountOptionValues('grant_info_too_late'));
      $days = ' +' . $infoTooLate . ' days';
Pradeep Nayak's avatar
Pradeep Nayak committed
775
      $newDate = date('Y-m-d', strtotime($endDate . $days));
776 777 778 779 780
      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
781 782
        $ids['grant_id'] = $objectId;
        $result = CRM_Grant_BAO_Grant::create($params, $ids);
783
      }
Mayur Jadhav's avatar
Mayur Jadhav committed
784 785
    }
  }
Mayur Jadhav's avatar
Mayur Jadhav committed
786 787 788 789 790 791 792 793
  //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;
    }
794
    $status = CRM_Core_OptionGroup::values('grant_status');
Mayur Jadhav's avatar
Mayur Jadhav committed
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
    $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
    $financialItemStatus = CRM_Core_PseudoConstant::accountOptionValues('financial_item_status');
    $amount = $objectRef->amount_granted;
    $params = array();
    if ($objectRef->status_id == array_search('Approved for Payment', $status)) {
      $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Payable Account is' "));
      $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($objectRef->financial_type_id, $relationTypeId);
      $financialItemStatusID = array_search('Unpaid', $financialItemStatus);
      $statusID = array_search('Pending', $contributionStatuses);
    }
    elseif ($objectRef->status_id == array_search('Paid', $status)) {
      $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Asset Account is' "));
      $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($objectRef->financial_type_id, $relationTypeId);
      $statusID = array_search('Completed', $contributionStatuses);
      $createItem = FALSE;
    }
Pradeep Nayak's avatar
Pradeep Nayak committed
811 812
    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
813 814
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
815 816
ORDER BY cft.id DESC LIMIT 1");
      $statusID = array_search('Cancelled', $contributionStatuses);
Pradeep Nayak's avatar
Pradeep Nayak committed
817
      $financialItemStatusID = array_search('Unpaid', $financialItemStatus);
Pradeep Nayak's avatar
Pradeep Nayak committed
818 819
      $amount = -$amount;
    }
Mayur Jadhav's avatar
Mayur Jadhav committed
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
    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,
      );
      $trxnEntityTable = array(
        '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)) {
        $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Accounts Payable Account is' "));
        $trxnParams['from_financial_account_id'] = CRM_Contribute_PseudoConstant::financialAccountType($objectRef->financial_type_id, $relationTypeId);
      }
      $trxnId = CRM_Core_BAO_FinancialTrxn::create($trxnParams, $trxnEntityTable);
      if ($createItem) {
        $relationTypeId = key(CRM_Core_PseudoConstant::accountOptionValues('account_relationship', NULL, " AND v.name LIKE 'Expense Account is' "));
        $financialAccountId = CRM_Contribute_PseudoConstant::financialAccountType($objectRef->financial_type_id, $relationTypeId);
        $itemParams = array(
          'transaction_date' => date('YmdHis'),
          'contact_id' => $objectRef->contact_id, 
          'currency' => $objectRef->currency,
          'amount' => $amount,
          'description' => NULL, 
          '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
857 858 859 860 861 862 863 864 865 866
}

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

Mayur Jadhav's avatar
Mayur Jadhav committed
868 869 870 871
  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
872 873 874 875 876 877 878
        $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
879 880 881 882
      }
    }
  }
  
Edselopez's avatar
Edselopez committed
883 884
  if ($formName == "CRM_Custom_Form_Option") {
    $params = array(
Mayur Jadhav's avatar
Mayur Jadhav committed
885
      'id' => $form->_submitValues['optionId'],
Edselopez's avatar
Edselopez committed
886
      'description' => $form->_submitValues['description'],
Mayur Jadhav's avatar
Mayur Jadhav committed
887
      'option_group_id' => $form->getVar('_optionGroupID'),
Edselopez's avatar
Edselopez committed
888
    );
Mayur Jadhav's avatar
Mayur Jadhav committed
889
    CRM_Core_BAO_OptionValue::create($params);
Edselopez's avatar
Edselopez committed
890 891
  }

Mayur Jadhav's avatar
Mayur Jadhav committed
892
  if ($formName == 'CRM_Grant_Form_Grant' && ($form->getVar('_action') != CRM_Core_Action::DELETE)) {
893
   
Pradeep Nayak's avatar
Pradeep Nayak committed
894
    // FIXME: cookies error
Mayur Jadhav's avatar
Mayur Jadhav committed
895
    if ($form->getVar('_context') == 'search') {
Mayur Jadhav's avatar
Mayur Jadhav committed
896 897 898
      $array['contact_id'] = $form->_ncid;
      $searchGrants = explode(',', $form->_searchGrants);
      $grants = array_flip($searchGrants);
Pradeep Nayak's avatar
Pradeep Nayak committed
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
      $foundit = FALSE;
      foreach ($grants as $gKey => $gVal) {
        if ($foundit) {
          $next = $gKey; 
          break;
        }
        if ($gKey == $form->_next) { 
          $next = $gKey; 
          if($gVal == end($grants)) {
            reset($grants);
            $next = key($grants);
          }
          $foundit = TRUE;
        }
      }
Mayur Jadhav's avatar
Mayur Jadhav committed
914 915
      $grantParams['id'] = $next;
      $result = CRM_Grant_BAO_GrantProgram::getGrants($grantParams);
Pradeep Nayak's avatar
Pradeep Nayak committed
916
      if (CRM_Utils_Array::value($form->getButtonName('submit', 'savenext'), $_POST)) {
Mayur Jadhav's avatar
Mayur Jadhav committed
917
        if ($form->getVar('_id') != $form->_prev) {
Pradeep Nayak's avatar
Pradeep Nayak committed
918
          CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/grant', 
Mayur Jadhav's avatar
Mayur Jadhav committed
919
            "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}"));
Pradeep Nayak's avatar
Pradeep Nayak committed
920 921 922 923 924 925 926 927 928
        } 
        else {
          CRM_Core_Session::setStatus( ts('The next record in the Search no longer exists. Select another record to edit if desired.'));
          CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/grant/search', 
            "force=1&qfKey={$form->_key}"));
        }
      } 
      elseif (CRM_Utils_Array::value( $form->getButtonName('upload', 'new'), $_POST)) {
        CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/grant', 
Mayur Jadhav's avatar
Mayur Jadhav committed
929
          "reset=1&action=add&context=grant&cid={$array['contact_id']}"));
Pradeep Nayak's avatar
Pradeep Nayak committed
930 931 932 933 934 935 936
      } 
      else {
        CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/grant/search', 
          "force=1&qfKey={$form->_key}"));
      }
    }
  }
Pradeep Nayak's avatar
Pradeep Nayak committed
937 938 939 940 941 942 943 944 945 946
}

/*
 * hook_civicrm_searchTasks
 *
 * @param string $objectName form name
 * @param array $tasks search task
 *
 */
function grantprograms_civicrm_searchTasks($objectName, &$tasks) {
Mayur Jadhav's avatar
Mayur Jadhav committed
947 948
  if ($objectName == 'grant' && !strstr($_GET['q'], 'payment/search') 
    && CRM_Core_Permission::check('create payments in CiviGrant')) {
Pradeep Nayak's avatar
Pradeep Nayak committed
949 950 951 952 953 954 955 956
    $tasks[PAY_GRANTS] = array( 
      'title' => ts('Pay Grants'),
      'class' => array('CRM_Grant_Form_Task_Pay',
        'CRM_Grant_Form_Task_GrantPayment' 
      ),
      'result' => FALSE,
    );
  }
Mayur Jadhav's avatar
Mayur Jadhav committed
957
}
Mayur Jadhav's avatar
Mayur Jadhav committed
958 959

function grantprograms_getOptionValueLabel($optioGroupID, $value) {
960
  $value = CRM_Core_DAO::escapeString($value);
Mayur Jadhav's avatar
Mayur Jadhav committed
961 962 963
  $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
964

Mayur Jadhav's avatar
Mayur Jadhav committed
965 966 967 968 969 970 971 972 973
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
974
}
Mayur Jadhav's avatar
Mayur Jadhav committed
975

976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
function grantprograms_define($extensionsDir) {
  $file  = fopen($extensionsDir .'biz.jmaconsulting.grantprograms/grantprograms_data_define.php', 'w'); 
  fwrite($file, "<?php\n\n//define custom table Names.\ndefine('COURSE_CONFERENCE_DETAILS', 'civicrm_value_nei_course_conference_details');\ndefine('EMPLOYMENT_INFORMATION', 'civicrm_value_nei_employment_information');\ndefine('GENERAL_INFORMATION', 'civicrm_value_nei_general_information');\ndefine('NEI_ID_TABLE', 'civicrm_value_nei_id');\n\n");

  fwrite($file, "//define custom group Names.\ndefine('NEI_EMPLOYMENT', 'NEI_Employment_Information');\ndefine('NEI_GENERAL', 'NEI_General_information');\ndefine('NEI_CONFERENCE', 'NEI_Course_conference_details');\n\n");

  fwrite($file, "//define custom groups Ids.\n");
  $tables = array(
    'civicrm_value_nei_employment_information' => 'COURSE_CONFERENCE_DETAILS_ID',
    'civicrm_value_nei_general_information' => 'EMPLOYMENT_INFORMATION_ID',
    'civicrm_value_nei_course_conference_details' => 'GENERAL_INFORMATION_ID',
    'civicrm_value_nei_id' => 'NEI_ID',
  );
  foreach ($tables as $tableKey => $tableValue) {
    fwrite($file, "define('".$tableValue."', '".CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup', $tableKey, 'id' ,'table_name')."');\n");
  }
  
  fwrite($file, "\n//define custom field Ids and Columns.\n");
  $customFields = array(
    'predominant_clinical_area_of_pra' => 'NEI_PRACTICE_AREA',
    'nei_employment_status' => 'NEI_EMPLOYMENT_STATUS',
    'if_you_are_not_employed_indicate' => 'EMPLOYED_INDICATE',
    'other' => 'EMPLOYMENT_OTHER',
    'employer_name' => 'EMPLOYER_NAME',
    'province_of_employment' => 'PROVINCES_OF_EMPLOYMENT',
    'position' => 'POSITION',
    'select_or_other' => 'POSITION_OTHER',
    'employment_setting' => 'EMPLOYMENT_SETTING',
    'employment_setting_other' => 'EMPLOYMENT_SETTING_OTHER',
    'work_phone' => 'WORK_PHONE',
    'work_phone_extension' => 'WORK_PHONE_EXTENSION',
    'how_did_you_hear_about_this_init' => 'NEI_HEAR_ABOUT',
    'other_initiative' => 'INITIATIVE_OTHER',
    'course_conference_type' => 'COURSE_CONFERENCE_TYPE',
    'course_conference_type_other' => 'COURSE_CONFERENCE_TYPE_OTHER',
    'course_conference_code' => 'COURSE_CONFERENCE_CODE',
    'course_conference_name' => 'COURSE_CONFERENCE_NAME',
    'course_conference_provider' => 'COURSE_CONFERENCE_PROVDER',
    'how_will_this_course_enhance_the' => 'NEI_COURSE_ENHANCEMENT',
    'proof_of_completion' => 'PROOF_OF_COMPELTION',
    'proof_of_payment' => 'PROOF_OF_PAYMENT',
    'type_of_course_provider' => 'COURSE_PROVIDER_TYPE',
    'start_date' => 'START_DATE',
    'end_date' => 'END_DATE',
    'college_of_nurses_of_ontario_reg' => 'NEI_CNO_REGISTRATION_ID',
    'social_insurance_number' => 'NEI_CIN',
  );
  
  foreach ($customFields as $tableKey => $tableValue) {
    fwrite($file, "define('".$tableValue."', '".CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $tableKey, 'id' ,'column_name')."');\n");
    fwrite($file, "define('".$tableValue."_COLUMN', '".$tableKey."');\n");
  } 
  fwrite($file, "\ndefine('PAY_GRANTS', 5);\ndefine('DELETE_GRANTS', 1);\n\n?>");
  fclose($file);
  return;
}

Mayur Jadhav's avatar
Mayur Jadhav committed
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
function grantprograms_addRemoveMenu($enable) {
  $config_backend = unserialize(CRM_Core_DAO::singleValueQuery('SELECT config_backend FROM civicrm_domain WHERE id = 1'));
  $params['enableComponents'] = $config_backend['enableComponents'];
  $params['enableComponentIDs'] = $config_backend['enableComponentIDs'];
  if ($enable) {
    $params['enableComponents'][] = 'CiviGrant';
    $params['enableComponentIDs'][] = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_component WHERE name = 'CiviGrant'");
  }
  else {
    foreach (array_keys($params['enableComponents'], 'CiviGrant', TRUE) as $key) {
      unset($params['enableComponents'][$key]);
    }
    foreach (array_keys($params['enableComponentIDs'], (int)CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_component WHERE name = 'CiviGrant'"), TRUE) as $key) {
      unset($params['enableComponentIDs'][$key]);
    }
  }
  CRM_Core_BAO_ConfigSetting::create($params);
  return;
}
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
 
function getCustomFields($params, &$values) {
  static $_customGroup = array();
  if (empty($_customGroup)) {
    $query = "SELECT ccf.id, ccg.id custom_group FROM civicrm_custom_group ccg
LEFT JOIN civicrm_custom_field ccf ON ccf.custom_group_id = ccg.id
WHERE ccg.name LIKE 'NEI_%' ORDER BY ccg.id";
    $dao = CRM_Core_DAO::executeQuery($query);
    while ($dao->fetch()) {
      $_customGroup[$dao->custom_group][$dao->id] = $dao->id;
    }
  }
  foreach ($_customGroup as $key => $val) {
    $values[$key] = array_intersect_key($params, $val);
  }
}
Pradeep Nayak's avatar
Pradeep Nayak committed
1068 1069 1070 1071 1072 1073 1074 1075 1076

/**
 * 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']);
  }
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
}

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
      $links[] = array( 'url'   => 'grant_program?reset=1&action=browse',
                 'title' => ts('Grant Program'),
                 'ref'   => 'new-grant program');
    }
Pradeep Nayak's avatar
Pradeep Nayak committed
1087
}