grantprograms.php 45.2 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);
}

Pradeep Nayak's avatar
Pradeep Nayak committed
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');
Edselopez's avatar
Edselopez committed
233 234 235
  $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
236
}
Pradeep Nayak's avatar
Pradeep Nayak committed
237 238 239 240 241 242 243 244
/*
 * hook_civicrm_buildForm civicrm hook
 * 
 * @param string $formName form name
 * @param object $form form object
 *
*/
function grantprograms_civicrm_buildForm($formName, &$form) {
Mayur Jadhav's avatar
Mayur Jadhav committed
245
  
Mayur Jadhav's avatar
Mayur Jadhav committed
246
  if ($formName == 'CRM_Grant_Form_Grant' && ($form->getVar('_action') != CRM_Core_Action::DELETE)) {
Mayur Jadhav's avatar
Mayur Jadhav committed
247 248 249
    $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
250 251
    $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
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
    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')),
        ) 
      );
    }
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
    $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',
      ));
295 296 297 298 299 300 301
    $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
    );
302

303 304 305 306 307 308 309 310
    $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
    );

311 312 313 314 315 316 317
    $form->_grantPrograms = CRM_Grant_BAO_GrantProgram::getGrantPrograms();
    $form->add('select', 
      'grant_program_id', 
      ts('Grant Programs'),
      array('' => ts('- select -')) + $form->_grantPrograms,
      TRUE
    );
318
         
319 320 321 322 323 324 325 326 327 328
    //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
329 330 331 332 333 334 335 336 337 338
    $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();
339 340 341 342 343 344 345 346 347
        }
        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
348 349 350 351 352 353
        }
        CRM_Core_Region::instance('page-body')->add(array(
          'template' => 'CRM/Grant/Form/Freeze.tpl',
        ));
      }
      $showFields = TRUE;
354
    }
Pradeep Nayak's avatar
Pradeep Nayak committed
355
    $form->assign('showFields', $showFields);
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
  }
  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
371
        array(1 => CRM_Utils_Money::format('9.99', ' '))), 
372 373 374 375 376 377 378 379 380
      '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
381
        array(1 => CRM_Utils_Money::format('99.99', ' '))), 
382 383 384 385 386 387 388
      'money'
    );
    $form->add('text', 
      'grant_assessment_low', 
      ts('From'), 
      array('size' => 9, 'maxlength' => 9)
    );
389
        
390 391 392 393 394 395 396 397 398 399 400 401
    $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
402
        array(1 => CRM_Utils_Money::format('9.99', ' '))), 
403 404
      'money'
    );
Pradeep Nayak's avatar
Pradeep Nayak committed
405

406 407 408 409 410 411 412
    $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
413
        array(1 => CRM_Utils_Money::format('99.99', ' '))), 
414 415
      'money'
    );
416
  }
417

418 419 420
  
  if ($formName == 'CRM_Custom_Form_Field') {
    
Pradeep Nayak's avatar
Pradeep Nayak committed
421 422 423
    for ($i = 1; $i <= $formName::NUM_OPTION; $i++) {
      $form->add('text', 
        'option_description['. $i .']', 
Mayur Jadhav's avatar
Mayur Jadhav committed
424
        'Mark', 
Pradeep Nayak's avatar
Pradeep Nayak committed
425 426
        array('id' => 'marks') 
      );
427
    } 
Edselopez's avatar
Edselopez committed
428 429 430 431
    $form->assign('edit_form', 1);
    CRM_Core_Region::instance('page-body')->add(array(
      'template' => 'CRM/Grant/Form/CustomFields.tpl',
    ));
432
  }
Pradeep Nayak's avatar
Pradeep Nayak committed
433 434 435
  if ($formName == 'CRM_Custom_Form_Option') {
    $form->add('text', 
      'description', 
Mayur Jadhav's avatar
Mayur Jadhav committed
436
      'Mark', 
Pradeep Nayak's avatar
Pradeep Nayak committed
437 438
      array('id' => 'marks')
    );
Edselopez's avatar
Edselopez committed
439 440 441
    CRM_Core_Region::instance('page-body')->add(array(
      'template' => 'CRM/Grant/Form/CustomFields.tpl',
    ));
442
  }
Mayur Jadhav's avatar
Mayur Jadhav committed
443
  
Edselopez's avatar
Edselopez committed
444
  if ($formName == 'CRM_Grant_Form_Search' && $form->get('context') == 'dashboard') {
Pradeep Nayak's avatar
Pradeep Nayak committed
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
    //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));
    }
    $grantType   = CRM_Grant_PseudoConstant::grantType( );
461
    $grantStatus = CRM_Grant_BAO_GrantProgram::grantProgramStatus( );
Pradeep Nayak's avatar
Pradeep Nayak committed
462
    foreach ( $grantProgram as $key => $value ) {
Edselopez's avatar
Edselopez committed
463
      $grantProgram[$key]['grant_type_id'] = $grantType[$grantProgram[$key]['grant_type_id']];
Pradeep Nayak's avatar
Pradeep Nayak committed
464 465 466 467 468 469
      $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
470 471
  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
472
    $form->assign('hideAttachments', 1);
473 474 475
    $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));
476 477
    //Freeze Prior Year's Assessment field
    $form->_elements[$form->_elementIndex['prev_assessment']]->freeze();
Edselopez's avatar
Edselopez committed
478
    // Filter out grant being edited from search results
479
    $form->assign('grant_id', $form->getVar('_id'));
Pradeep Nayak's avatar
Pradeep Nayak committed
480
 }
481 482
}

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

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

/*
 * hook_civicrm_post
 *
 */
function grantprograms_civicrm_post($op, $objectName, $objectId, &$objectRef) {
Mayur Jadhav's avatar
Mayur Jadhav committed
669
  //send mail after grant save
Mayur Jadhav's avatar
Mayur Jadhav committed
670
  $config = CRM_Core_Config::singleton();
Mayur Jadhav's avatar
Mayur Jadhav committed
671
  if ($objectName == 'Grant' && isset($config->_params) && !isset($config->_params['restrictEmail'])) {
Mayur Jadhav's avatar
Mayur Jadhav committed
672 673 674 675 676 677 678 679 680 681 682 683 684 685
    $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();
686 687
        $entityValues = CRM_Core_BAO_CustomValueTable::getEntityValues($objectId, 'Grant');
        getCustomFields(array_filter($entityValues), $customData);
Mayur Jadhav's avatar
Mayur Jadhav committed
688
      }
Mayur Jadhav's avatar
Mayur Jadhav committed
689
      foreach ($params['custom'] as $key => $value) {
Mayur Jadhav's avatar
Mayur Jadhav committed
690
        foreach ($value as $index => $field) {
Mayur Jadhav's avatar
Mayur Jadhav committed
691
          if (!empty($field['value'])) {
Mayur Jadhav's avatar
Mayur Jadhav committed
692 693 694 695 696 697 698 699 700 701
            $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'];
            }
          }
        }
      }
702
      $customGroup = $customField = array();
Mayur Jadhav's avatar
Mayur Jadhav committed
703 704
      if (!empty( $customData)) {
        foreach ($customData as $dataKey => $dataValue) {
Mayur Jadhav's avatar
Mayur Jadhav committed
705
          $customGroupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',$dataKey,'title');
Mayur Jadhav's avatar
Mayur Jadhav committed
706 707 708
          $customGroup[$customGroupName] = $customGroupName;
          $count = 0;
          foreach ($dataValue  as $dataValueKey => $dataValueValue) {
Mayur Jadhav's avatar
Mayur Jadhav committed
709
            $customField[$customGroupName]['custom_'.$dataValueKey]['label'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $dataValueKey, 'label');
Mayur Jadhav's avatar
Mayur Jadhav committed
710
            $customFieldData = grantprograms_getCustomFieldData($dataValueKey);
Mayur Jadhav's avatar
Mayur Jadhav committed
711
            if (CRM_Utils_Array::value('html_type', $customFieldData) == 'Select') {
Mayur Jadhav's avatar
Mayur Jadhav committed
712
              $customField[$customGroupName]['custom_'.$dataValueKey]['value'] = grantprograms_getOptionValueLabel($customFieldData['option_group_id'],$dataValueValue);
Mayur Jadhav's avatar
Mayur Jadhav committed
713
            } 
Mayur Jadhav's avatar
Mayur Jadhav committed
714
            elseif (CRM_Utils_Array::value('html_type', $customFieldData) == 'Select Date') {
Mayur Jadhav's avatar
Mayur Jadhav committed
715
              $customField[$customGroupName]['custom_'.$dataValueKey]['value'] = date('Y-m-d', strtotime($dataValueValue));
Mayur Jadhav's avatar
Mayur Jadhav committed
716 717
            } 
            else {
Mayur Jadhav's avatar
Mayur Jadhav committed
718
              $customField[$customGroupName]['custom_'.$dataValueKey]['value'] = $dataValueValue;
Mayur Jadhav's avatar
Mayur Jadhav committed
719
            }
Mayur Jadhav's avatar
Mayur Jadhav committed
720 721 722 723
            $count++;
          }
        }
      }
724 725
      $page->assign('customGroup', $customGroup);
      $page->assign('customField', $customField);
Mayur Jadhav's avatar
Mayur Jadhav committed
726
      
Pradeep Nayak's avatar
Pradeep Nayak committed
727
      $grantStatuses = $grantStatus = CRM_Core_OptionGroup::values('grant_status');
Mayur Jadhav's avatar
Mayur Jadhav committed
728 729 730 731 732
      $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']];
733
      $grantIneligibleReasons = CRM_Core_OptionGroup::values('reason_grant_ineligible');
734
      $grantIncompleteReasons = CRM_Core_OptionGroup::values('reason_grant_incomplete');
Mayur Jadhav's avatar
Mayur Jadhav committed
735 736 737 738
      
      $page->assign('grant_type', $grantType);
      $page->assign('grant_programs', $grantProgram);
      $page->assign('grant_status', $grantStatus);
739 740 741 742 743 744
      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']];
      }
745
      $page->assign('grant', $params);
746 747 748
      $smarty = CRM_Core_Smarty::singleton();
      $sendMail = $smarty->get_template_vars('sendMail');
      if ($sendMail) {
Pradeep Nayak's avatar
Pradeep Nayak committed
749 750
        $previousGrant = $smarty->get_template_vars('previousGrant');
        $previousStatus = '';
Pradeep Nayak's avatar
Pradeep Nayak committed
751
        if ($previousGrant && property_exists($previousGrant, 'status_id')) {
Pradeep Nayak's avatar
Pradeep Nayak committed
752 753 754
          $previousStatus = $grantStatuses[$previousGrant->status_id];
        }
        CRM_Grant_BAO_GrantProgram::sendMail($params['contact_id'], $params, $grantStatus, $objectId, $previousStatus);
755
      }
Mayur Jadhav's avatar
Mayur Jadhav committed
756
    }
757
    
758
    $grantStatus = CRM_Core_OptionGroup::values('grant_status', TRUE);
759
    if (isset($endDate)) {
Pradeep Nayak's avatar
Pradeep Nayak committed
760 761
      $infoTooLate = key(CRM_Core_PseudoConstant::accountOptionValues('grant_info_too_late'));
      $days = ' +' . $infoTooLate . ' days';
Pradeep Nayak's avatar
Pradeep Nayak committed
762
      $newDate = date('Y-m-d', strtotime($endDate . $days));
763 764 765 766 767
      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
768 769
        $ids['grant_id'] = $objectId;
        $result = CRM_Grant_BAO_Grant::create($params, $ids);
770
      }
Mayur Jadhav's avatar
Mayur Jadhav committed
771 772
    }
  }
Mayur Jadhav's avatar
Mayur Jadhav committed
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
  //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;
    }
    $status = CRM_Grant_PseudoConstant::grantStatus();
    $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
798 799
    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
800 801
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
802 803
ORDER BY cft.id DESC LIMIT 1");
      $statusID = array_search('Cancelled', $contributionStatuses);
Pradeep Nayak's avatar
Pradeep Nayak committed
804
      $financialItemStatusID = array_search('Unpaid', $financialItemStatus);
Pradeep Nayak's avatar
Pradeep Nayak committed
805 806
      $amount = -$amount;
    }
Mayur Jadhav's avatar
Mayur Jadhav committed
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
    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
844 845 846 847 848 849 850 851 852 853
}

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

Mayur Jadhav's avatar
Mayur Jadhav committed
855 856 857 858
  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
859 860 861 862 863 864 865
        $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
866 867 868 869
      }
    }
  }
  
Edselopez's avatar
Edselopez committed
870 871
  if ($formName == "CRM_Custom_Form_Option") {
    $params = array(
Mayur Jadhav's avatar
Mayur Jadhav committed
872
      'id' => $form->_submitValues['optionId'],
Edselopez's avatar
Edselopez committed
873
      'description' => $form->_submitValues['description'],
Mayur Jadhav's avatar
Mayur Jadhav committed
874
      'option_group_id' => $form->getVar('_optionGroupID'),
Edselopez's avatar
Edselopez committed
875
    );
Mayur Jadhav's avatar
Mayur Jadhav committed
876
    CRM_Core_BAO_OptionValue::create($params);
Edselopez's avatar
Edselopez committed
877 878
  }

Mayur Jadhav's avatar
Mayur Jadhav committed
879
  if ($formName == 'CRM_Grant_Form_Grant' && ($form->getVar('_action') != CRM_Core_Action::DELETE)) {
880
   
Pradeep Nayak's avatar
Pradeep Nayak committed
881
    // FIXME: cookies error
Mayur Jadhav's avatar
Mayur Jadhav committed
882
    if ($form->getVar('_context') == 'search') {
Mayur Jadhav's avatar
Mayur Jadhav committed
883 884 885
      $array['contact_id'] = $form->_ncid;
      $searchGrants = explode(',', $form->_searchGrants);
      $grants = array_flip($searchGrants);
Pradeep Nayak's avatar
Pradeep Nayak committed
886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
      $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
901 902
      $grantParams['id'] = $next;
      $result = CRM_Grant_BAO_GrantProgram::getGrants($grantParams);
Pradeep Nayak's avatar
Pradeep Nayak committed
903
      if (CRM_Utils_Array::value($form->getButtonName('submit', 'savenext'), $_POST)) {
Mayur Jadhav's avatar
Mayur Jadhav committed
904
        if ($form->getVar('_id') != $form->_prev) {
Pradeep Nayak's avatar
Pradeep Nayak committed
905
          CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view/grant', 
Mayur Jadhav's avatar
Mayur Jadhav committed
906
            "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
907 908 909 910 911 912 913 914 915
        } 
        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
916
          "reset=1&action=add&context=grant&cid={$array['contact_id']}"));
Pradeep Nayak's avatar
Pradeep Nayak committed
917 918 919 920 921 922 923
      } 
      else {
        CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/grant/search', 
          "force=1&qfKey={$form->_key}"));
      }
    }
  }
Pradeep Nayak's avatar
Pradeep Nayak committed
924 925 926 927 928 929 930 931 932 933
}

/*
 * 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
934 935
  if ($objectName == 'grant' && !strstr($_GET['q'], 'payment/search') 
    && CRM_Core_Permission::check('create payments in CiviGrant')) {
Pradeep Nayak's avatar
Pradeep Nayak committed
936 937 938 939 940 941 942 943
    $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
944
}
Mayur Jadhav's avatar
Mayur Jadhav committed
945 946 947 948 949

function grantprograms_getOptionValueLabel($optioGroupID, $value) {
  $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
950

Mayur Jadhav's avatar
Mayur Jadhav committed
951 952 953 954 955 956 957 958 959
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
960
}
Mayur Jadhav's avatar
Mayur Jadhav committed
961

962 963 964 965 966 967 968 969 970 971 972 973 974 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
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
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
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;
}
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
 
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
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063

/**
 * 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']);
  }
}