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

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

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

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

/**
 * Implementation of hook_civicrm_enable
 */
function grantprograms_civicrm_enable() {
Mayur Jadhav's avatar
Mayur Jadhav committed
50 51
  $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
52
  grantprograms_addRemoveMenu(TRUE);
53 54 55 56 57 58 59
  return _grantprograms_civix_civicrm_enable();
}

/**
 * Implementation of hook_civicrm_disable
 */
function grantprograms_civicrm_disable() {
Mayur Jadhav's avatar
Mayur Jadhav committed
60 61
  $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
62
  grantprograms_addRemoveMenu(FALSE);
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
  return _grantprograms_civix_civicrm_disable();
}

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

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

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

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

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

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

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

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

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

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

}
270 271
/*
 * hook_civicrm_buildForm civicrm hook
272
 *
273 274 275 276 277
 * @param string $formName form name
 * @param object $form form object
 *
*/
function grantprograms_civicrm_buildForm($formName, &$form) {
278 279 280 281 282 283 284 285

  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;
    }
286
    $grantUrl = CRM_Utils_System::url('civicrm/contact/view/grant',
287 288 289
      'reset=1&action=view&id=' . $activityValues['source_record_id'] . '&cid=' . current($activityValues['assignee_contact']));
    $form->assign('grantUrl', $grantUrl);
  }
290

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

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

333
    $form->_grantPrograms = CRM_Grant_BAO_GrantProgram::getGrantPrograms();
334 335
    $form->add('select',
      'grant_program_id',
336 337 338 339
      ts('Grant Programs'),
      array('' => ts('- select -')) + $form->_grantPrograms,
      TRUE
    );
340

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

Pradeep Nayak's avatar
Pradeep Nayak committed
353 354 355 356 357 358 359 360 361 362 363 364
    if ( $form->getVar('_action') == CRM_Core_Action::UPDATE && $form->getVar('_id')) {
      $grantStatuses = CRM_Core_OptionGroup::values('grant_status');
      $grantWeight = CRM_Core_OptionGroup::values('grant_status', FALSE, FALSE, FALSE, NULL, 'weight');
      $currentStatus = $form->_defaultValues['status_id'];
      $coreStatus = array(
        array_search('Eligible', $grantStatuses),
        array_search('Awaiting Information', $grantStatuses) => array('Eligible', '', ''),
        array_search('Withdrawn', $grantStatuses),
      );

        $currentStatusWeight = $grantWeight[$currentStatus] + 1;
        foreach ($grantStatuses as $statusId => $statusName) {
365
          if ((($grantWeight[$currentStatus] >= 7 && $statusId == array_search('Ineligible', $grantStatuses))
Pradeep Nayak's avatar
Pradeep Nayak committed
366 367 368 369 370 371 372 373 374 375
               || ($grantWeight[$currentStatus] >= 1 && $grantWeight[$currentStatus] <= 7 && $grantWeight[$statusId] > 7 && $statusId != array_search('Ineligible', $grantStatuses))
              || $grantWeight[$currentStatus] > 7
              || $grantWeight[$statusId] < $grantWeight[$currentStatus])
              && $statusId != $currentStatus
              && $statusId != array_search('Withdrawn', $grantStatuses)
              && $currentStatusWeight != $grantWeight[$statusId]) {
            unset($grantStatuses[$statusId]);
          }
        }
      $form->removeElement('status_id');
376

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

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

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

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

473

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

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

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

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

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

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

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

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

  if ($page->getVar('_name') == "CRM_Custom_Page_Option") {
Mayur Jadhav's avatar
Mayur Jadhav committed
567 568
    $params['id'] = $page->getVar('_fid');
    $params['custom_group_id'] = $page->getVar('_gid');
569
    CRM_Core_BAO_CustomField::retrieve($params, $defaults);
Mayur Jadhav's avatar
Mayur Jadhav committed
570 571 572 573 574 575 576
    $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'];
      }
    }
Edsel's avatar
Edsel committed
577 578
    $page->assign('view_form', 1);
    CRM_Core_Region::instance('page-body')->add(array(
Mayur Jadhav's avatar
Mayur Jadhav committed
579
      'template' => 'CRM/Grant/Form/CustomFieldsView.tpl',
Edsel's avatar
Edsel committed
580 581 582
    ));
  }
}
583 584 585 586 587 588 589 590 591 592 593
/*
 * 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;
594 595
  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
596 597 598 599
    $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) {
600
      $errors[''] = ts('Error');
Mayur Jadhav's avatar
Mayur Jadhav committed
601 602 603 604 605 606 607
      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");
608 609
    }
  }
Mayur Jadhav's avatar
Mayur Jadhav committed
610
  if ($formName == 'CRM_Grant_Form_Grant' && ($form->getVar('_action') != CRM_Core_Action::DELETE)) {
611
    $defaults = array();
612
    $params['id'] = $form->_submitValues['grant_program_id'];
613
    CRM_Grant_BAO_GrantProgram::retrieve($params, $defaults);
Pradeep Nayak's avatar
Pradeep Nayak committed
614
    if (array_key_exists('amount_granted', $form->_submitValues) && CRM_Utils_Array::value('remainder_amount', $defaults) < $form->_submitValues['amount_granted']) {
Edsel's avatar
Edsel committed
615
      $errors['amount_granted'] = ts('You need to increase the Grant Program Remainder Amount');
616
    }
617

618 619 620
    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');
    }
621
  }
Pradeep Nayak's avatar
Pradeep Nayak committed
622
  if ($formName == 'CRM_Grant_Form_Search') {
623
    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
624 625 626
      foreach ($fields as $fieldKey => $fieldValue) {
        if (strstr($fieldKey, 'mark_x_')) {
          $grantID = ltrim( $fieldKey, 'mark_x_' );
Mayur Jadhav's avatar
Mayur Jadhav committed
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
          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
642 643 644 645
          }
        }
      }
    }
646
  }
647
  return empty($errors) ? TRUE : $errors;
Pradeep Nayak's avatar
Pradeep Nayak committed
648 649
}

Pradeep Nayak's avatar
Pradeep Nayak committed
650
function grantprograms_civicrm_pre($op, $objectName, $id, &$params) {
651
  if ($objectName == 'Grant' && ($op == 'edit' || $op == 'create')) {
Pradeep Nayak's avatar
Pradeep Nayak committed
652
    $grantStatus = CRM_Core_OptionGroup::values('grant_status');
Pradeep Nayak's avatar
Pradeep Nayak committed
653
    $assessmentAmount = 0;
Mayur Jadhav's avatar
Mayur Jadhav committed
654
    $calculateAssessment = FALSE;
Mayur Jadhav's avatar
Mayur Jadhav committed
655
    $params['adjustment_value'] = TRUE;
Pradeep Nayak's avatar
Pradeep Nayak committed
656
    $previousGrant = NULL;
657 658
    $smarty = CRM_Core_Smarty::singleton();
    $sendMail = TRUE;
Mayur Jadhav's avatar
Mayur Jadhav committed
659 660 661
    if ($objectName == 'Grant' && $op == "edit") {
      $grantParams = array('id' => $id);
      $previousGrant = CRM_Grant_BAO_Grant::retrieve($grantParams, CRM_Core_DAO::$_nullArray);
662
      if (isset($params['status_id']) && $params['status_id'] == $previousGrant->status_id) {
663 664
        $sendMail = FALSE;
      }
Mayur Jadhav's avatar
Mayur Jadhav committed
665
      if ((CRM_Utils_Array::value('assessment', $params) == $previousGrant->assessment)) {
Mayur Jadhav's avatar
Mayur Jadhav committed
666 667 668
        $calculateAssessment = TRUE;
      }
    }
669
    $smarty->assign('sendMail', $sendMail);
Pradeep Nayak's avatar
Pradeep Nayak committed
670
    $grantStatusApproved = array_search('Approved for Payment', $grantStatus);
671 672 673 674 675
    if ((isset($params['status_id']) && $grantStatusApproved == $params['status_id'] &&
        empty($params['decision_date']) && $op == 'create') ||
      ($previousGrant && !$previousGrant->decision_date && isset($params['status_id']) &&
        $previousGrant->status_id != $params['status_id'])
    ) {
Pradeep Nayak's avatar
Pradeep Nayak committed
676 677
      $params['decision_date'] = date('Ymd');
    }
Mayur Jadhav's avatar
Mayur Jadhav committed
678
    if ((empty($params['assessment']) || $calculateAssessment) && ($op == 'create' || $op == 'edit')) {
679 680 681 682 683
      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());
684
            if (!empty($customFields)) {
685 686 687 688 689
              $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
690 691 692 693 694
            }
          }
        }
      }
    }
695

Pradeep Nayak's avatar
Pradeep Nayak committed
696 697
    if(!empty($assessmentAmount)) {
      $params['assessment'] = $assessmentAmount;
698
    }
Mayur Jadhav's avatar
Mayur Jadhav committed
699 700
    elseif ($objectName == 'Grant' && $op == "edit") {
      $params['adjustment_value'] = FALSE;
Pradeep Nayak's avatar
Pradeep Nayak committed
701
    }
Mayur Jadhav's avatar
Mayur Jadhav committed
702
    if ($objectName == 'Grant' && $op == "edit") {
703
      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
704 705 706 707 708 709 710
        $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);
711 712 713
        $params['manualEdit'] = TRUE;
      }
    }
Mayur Jadhav's avatar
Mayur Jadhav committed
714 715 716
    elseif ($objectName == 'Grant' && $op == "create" && CRM_Utils_Array::value('amount_granted', $params)) {
      $params['manualEdit'] = TRUE;
    }
717

718 719 720
    if (!empty($id)) {
      $params['id'] = $id;
    }
721
    CRM_Grantprograms_Hook::grantAssessment($params);
Pradeep Nayak's avatar
Pradeep Nayak committed
722 723 724 725
    if ($op == 'edit') {
      $smarty = CRM_Core_Smarty::singleton();
      $smarty->assign('previousGrant', $previousGrant);
    }
726 727 728

    $session = CRM_Core_Session::singleton();
    $session->set('grant-params', $params);
Pradeep Nayak's avatar
Pradeep Nayak committed
729 730 731 732 733 734 735 736
  }
}

/*
 * hook_civicrm_post
 *
 */
function grantprograms_civicrm_post($op, $objectName, $objectId, &$objectRef) {
Mayur Jadhav's avatar
Mayur Jadhav committed
737
  //send mail after grant save
738 739 740
  $config = CRM_Core_Session::singleton();
  $params = $config->get('grant-params');
  if ($objectName == 'Grant' && isset($params) && !isset($params['restrictEmail'])) {
Mayur Jadhav's avatar
Mayur Jadhav committed
741 742
    // added by JMA fixme in module
    $grantProgram  = new CRM_Grant_DAO_GrantProgram();
743
    $grantProgram->id = isset($params['grant_program_id']) ? $params['grant_program_id'] : NULL;
Mayur Jadhav's avatar
Mayur Jadhav committed
744 745 746 747
    $page = new CRM_Core_Page();
    if ($grantProgram->find(TRUE)) {
      $params['is_auto_email'] = $grantProgram->is_auto_email;
    }
748

Mayur Jadhav's avatar
Mayur Jadhav committed
749 750 751 752 753
    if ($params['is_auto_email'] == 1) {
      // FIXME: for grant profiles
      $customData = array();
      if (!CRM_Utils_Array::value('custom', $params)) {
        $params['custom'] = array();
754 755
        $entityValues = CRM_Core_BAO_CustomValueTable::getEntityValues($objectId, 'Grant');
        getCustomFields(array_filter($entityValues), $customData);
Mayur Jadhav's avatar
Mayur Jadhav committed
756
      }
Mayur Jadhav's avatar
Mayur Jadhav committed
757
      foreach ($params['custom'] as $key => $value) {
Mayur Jadhav's avatar
Mayur Jadhav committed
758
        foreach ($value as $index => $field) {
Mayur Jadhav's avatar
Mayur Jadhav committed
759
          if (!empty($field['value'])) {
Mayur Jadhav's avatar
Mayur Jadhav committed
760 761 762 763 764 765 766 767 768 769
            $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'];
            }
          }
        }
      }
770
      $customGroup = $customField = array();
Mayur Jadhav's avatar
Mayur Jadhav committed
771 772
      if (!empty( $customData)) {
        foreach ($customData as $dataKey => $dataValue) {
Mayur Jadhav's avatar
Mayur Jadhav committed
773
          $customGroupName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomGroup',$dataKey,'title');
Mayur Jadhav's avatar
Mayur Jadhav committed
774 775 776
          $customGroup[$customGroupName] = $customGroupName;
          $count = 0;
          foreach ($dataValue  as $dataValueKey => $dataValueValue) {
Mayur Jadhav's avatar
Mayur Jadhav committed
777
            $customField[$customGroupName]['custom_'.$dataValueKey]['label'] = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $dataValueKey, 'label');
Mayur Jadhav's avatar
Mayur Jadhav committed
778
            $customFieldData = grantprograms_getCustomFieldData($dataValueKey);
Mayur Jadhav's avatar
Mayur Jadhav committed
779
            if (CRM_Utils_Array::value('html_type', $customFieldData) == 'Select') {
Mayur Jadhav's avatar
Mayur Jadhav committed
780
              $customField[$customGroupName]['custom_'.$dataValueKey]['value'] = grantprograms_getOptionValueLabel($customFieldData['option_group_id'],$dataValueValue);
781
            }
Mayur Jadhav's avatar
Mayur Jadhav committed
782
            elseif (CRM_Utils_Array::value('html_type', $customFieldData) == 'Select Date') {
Mayur Jadhav's avatar
Mayur Jadhav committed
783
              $customField[$customGroupName]['custom_'.$dataValueKey]['value'] = date('Y-m-d', strtotime($dataValueValue));
784
            }
Mayur Jadhav's avatar
Mayur Jadhav committed
785
            else {
Mayur Jadhav's avatar
Mayur Jadhav committed
786
              $customField[$customGroupName]['custom_'.$dataValueKey]['value'] = $dataValueValue;
Mayur Jadhav's avatar
Mayur Jadhav committed
787
            }
Mayur Jadhav's avatar
Mayur Jadhav committed
788 789 790 791
            $count++;
          }
        }
      }
792 793
      $page->assign('customGroup', $customGroup);
      $page->assign('customField', $customField);
794

Pradeep Nayak's avatar
Pradeep Nayak committed
795
      $grantStatuses = $grantStatus = CRM_Core_OptionGroup::values('grant_status');
Mayur Jadhav's avatar
Mayur Jadhav committed
796 797
      $grantPrograms = CRM_Grant_BAO_GrantProgram::getGrantPrograms();
      $grantTypes = CRM_Core_OptionGroup::values('grant_type');
798 799 800 801 802 803
      if (CRM_Utils_Array::value('grant_program_id', $params)) {
        $grantProgram = $grantPrograms[$params['grant_program_id']];
      }
      else {
        $grantProgram = '';
      }
Mayur Jadhav's avatar
Mayur Jadhav committed
804 805
      $grantType = $grantTypes[$params['grant_type_id']];
      $grantStatus = $grantStatus[$params['status_id']];
806
      $grantIneligibleReasons = CRM_Core_OptionGroup::values('reason_grant_ineligible');
807
      $grantIncompleteReasons = CRM_Core_OptionGroup::values('reason_grant_incomplete');
808

Mayur Jadhav's avatar
Mayur Jadhav committed
809 810 811
      $page->assign('grant_type', $grantType);
      $page->assign('grant_programs', $grantProgram);
      $page->assign('grant_status', $grantStatus);
812 813 814 815 816 817
      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']];
      }
818
      $page->assign('grant', $params);
819 820 821
      $smarty = CRM_Core_Smarty::singleton();
      $sendMail = $smarty->get_template_vars('sendMail');
      if ($sendMail) {
Pradeep Nayak's avatar
Pradeep Nayak committed
822 823
        $previousGrant = $smarty->get_template_vars('previousGrant');
        $previousStatus = '';
Pradeep Nayak's avatar
Pradeep Nayak committed
824
        if ($previousGrant && property_exists($previousGrant, 'status_id')) {
Pradeep Nayak's avatar
Pradeep Nayak committed
825 826 827
          $previousStatus = $grantStatuses[$previousGrant->status_id];
        }
        CRM_Grant_BAO_GrantProgram::sendMail($params['contact_id'], $params, $grantStatus, $objectId, $previousStatus);
828
      }
Mayur Jadhav's avatar
Mayur Jadhav committed
829
    }
Pradeep Nayak's avatar
Pradeep Nayak committed
830 831 832 833 834
    else {
      $smarty = CRM_Core_Smarty::singleton();
      $previousGrant = $smarty->get_template_vars('previousGrant');
      if ($previousGrant && property_exists($previousGrant, 'status_id')) {
        $grantStatuses = CRM_Core_OptionGroup::values('grant_status');
835
        CRM_Grant_BAO_GrantProgram::createStatusChangeActivity($params['contact_id'],
Pradeep Nayak's avatar
Pradeep Nayak committed
836 837 838
        $grantStatuses[$params['status_id']], $grantStatuses[$previousGrant->status_id], $params['contact_id']);
      }
    }
839

840
    $grantStatus = CRM_Core_OptionGroup::values('grant_status', TRUE);
841
    if (isset($endDate)) {
Pradeep Nayak's avatar
Pradeep Nayak committed
842 843
      $infoTooLate = key(CRM_Core_PseudoConstant::accountOptionValues('grant_info_too_late'));
      $days = ' +' . $infoTooLate . ' days';
Pradeep Nayak's avatar
Pradeep Nayak committed
844
      $newDate = date('Y-m-d', strtotime($endDate . $days));
845 846 847 848 849
      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
850 851
        $ids['grant_id'] = $objectId;
        $result = CRM_Grant_BAO_Grant::create($params, $ids);
852
      }
Mayur Jadhav's avatar
Mayur Jadhav committed
853 854
    }
  }
Mayur Jadhav's avatar
Mayur Jadhav committed
855 856 857 858 859 860 861 862
  //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;
    }
863
    $status = CRM_Core_OptionGroup::values('grant_status');
Mayur Jadhav's avatar
Mayur Jadhav committed
864 865
    $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
    $financialItemStatus = CRM_Core_PseudoConstant::accountOptionValues('financial_item_status');
Monish Deb's avatar
Monish Deb committed
866
    $amount = $objectRef->amount_total;
Mayur Jadhav's avatar
Mayur Jadhav committed
867 868
    $params = array();
    if ($objectRef->status_id == array_search('Approved for Payment', $status)) {
Monish Deb's avatar
Monish Deb committed
869
      $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($objectRef->financial_type_id, 'Accounts Receivable Account is');
Mayur Jadhav's avatar
Mayur Jadhav committed
870 871 872 873
      $financialItemStatusID = array_search('Unpaid', $financialItemStatus);
      $statusID = array_search('Pending', $contributionStatuses);
    }
    elseif ($objectRef->status_id == array_search('Paid', $status)) {
Monish Deb's avatar
Monish Deb committed
874
      $params['to_financial_account_id'] = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($objectRef->financial_type_id, 'Asset Account is');
Mayur Jadhav's avatar
Mayur Jadhav committed
875 876 877
      $statusID = array_search('Completed', $contributionStatuses);
      $createItem = FALSE;
    }
Pradeep Nayak's avatar
Pradeep Nayak committed
878 879
    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
880 881
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
882 883
ORDER BY cft.id DESC LIMIT 1");
      $statusID = array_search('Cancelled', $contributionStatuses);
Pradeep Nayak's avatar
Pradeep Nayak committed
884
      $financialItemStatusID = array_search('Unpaid', $financialItemStatus);
Pradeep Nayak's avatar
Pradeep Nayak committed
885 886
      $amount = -$amount;
    }
Mayur Jadhav's avatar
Mayur Jadhav committed
887 888 889 890 891 892 893 894 895 896 897 898
    if (CRM_Utils_Array::value('to_financial_account_id', $params)) {
      //build financial transaction params
      $trxnParams = array(
        'to_financial_account_id' => $params['to_financial_account_id'],
        'trxn_date' => date('YmdHis'),
        'total_amount' => $amount,
        'currency' => $objectRef->currency,
        'status_id' => $statusID,
        'entity_table' => 'civicrm_grant',
        'entity_id' => $objectId,
      );
      if ($previousGrant && $previousGrant->status_id == array_search('Approved for Payment', $status) && $objectRef->status_id == array_search('Paid', $status)) {
Monish Deb's avatar
Monish Deb committed
899
        $trxnParams['from_financial_account_id'] = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($objectRef->financial_type_id, 'Accounts Receivable Account is');
Mayur Jadhav's avatar
Mayur Jadhav committed
900
      }
Monish Deb's avatar
Monish Deb committed
901
      $trxnId = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
Mayur Jadhav's avatar
Mayur Jadhav committed
902
      if ($createItem) {
Monish Deb's avatar
Monish Deb committed
903
        $financialAccountId = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($objectRef->financial_type_id, 'Accounts Receivable Account is');
Mayur Jadhav's avatar
Mayur Jadhav committed
904 905
        $itemParams = array(
          'transaction_date' => date('YmdHis'),
906
          'contact_id' => $objectRef->contact_id,
Mayur Jadhav's avatar
Mayur Jadhav committed
907 908
          'currency' => $objectRef->currency,
          'amount' => $amount,
909
          'description' => NULL,
Mayur Jadhav's avatar
Mayur Jadhav committed
910 911 912 913 914 915 916 917 918 919
          '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
920 921 922 923 924 925 926 927 928 929
}

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

Mayur Jadhav's avatar
Mayur Jadhav committed
931 932 933 934
  if ($formName == "CRM_Custom_Form_Field") {
    $customGroupID = CRM_Core_DAO::getFieldValue( 'CRM_Core_DAO_OptionGroup', $form->_submitValues['label'], 'id', 'title');
    foreach ($form->_submitValues['option_label'] as $key => $value) {
      if (!empty($value)) {
Edsel's avatar
Edsel committed
935 936 937 938 939 940 941
        $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
942 943 944
      }
    }
  }
945

Edsel's avatar
Edsel committed
946 947
  if ($formName == "CRM_Custom_Form_Option") {
    $params = array(
Mayur Jadhav's avatar
Mayur Jadhav committed
948
      'id' => $form->_submitValues['optionId'],
Edsel's avatar
Edsel committed
949
      'description' => $form->_submitValues['description'],
Mayur Jadhav's avatar
Mayur Jadhav committed
950
      'option_group_id' => $form->getVar('_optionGroupID'),
Edsel's avatar
Edsel committed
951
    );
Mayur Jadhav's avatar
Mayur Jadhav committed
952
    CRM_Core_BAO_OptionValue::create($params);
Edsel's avatar
Edsel committed
953 954
  }

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

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

/*
 * hook_civicrm_searchTasks
 *
 * @param string $objectName form name
 * @param array $tasks search task
 *
 */
function grantprograms_civicrm_searchTasks($objectName, &$tasks) {
1010
  if ($objectName == 'grant' && !strstr($_GET['q'], 'payment/search')
Mayur Jadhav's avatar
Mayur Jadhav committed
1011
    && CRM_Core_Permission::check('create payments in CiviGrant')) {
1012
    $tasks[PAY_GRANTS] = array(
Pradeep Nayak's avatar
Pradeep Nayak committed
1013 1014
      'title' => ts('Pay Grants'),
      'class' => array('CRM_Grant_Form_Task_Pay',
1015
        'CRM_Grant_Form_Task_GrantPayment'
Pradeep Nayak's avatar
Pradeep Nayak committed
1016 1017 1018 1019
      ),
      'result' => FALSE,
    );
  }
Mayur Jadhav's avatar
Mayur Jadhav committed
1020
}
Mayur Jadhav's avatar
Mayur Jadhav committed
1021 1022

function grantprograms_getOptionValueLabel($optioGroupID, $value) {
1023
  $value = CRM_Core_DAO::escapeString($value);
Mayur Jadhav's avatar
Mayur Jadhav committed
1024 1025 1026
  $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
1027

Mayur Jadhav's avatar
Mayur Jadhav committed
1028 1029 1030 1031 1032 1033 1034 1035 1036
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
1037
}
Mayur Jadhav's avatar
Mayur Jadhav committed
1038

Mayur Jadhav's avatar
Mayur Jadhav committed
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
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;
}
1058

1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
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
1074 1075 1076 1077 1078 1079 1080 1081 1082

/**
 * 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']);
  }
1083 1084 1085 1086 1087 1088
}

function grantprograms_civicrm_links( $op, $objectName, $objectId, &$links ) {
      if ($op == 'create.new.shorcuts' && (CRM_Core_Permission::check('access CiviGrant') &&
      CRM_Core_Permission::check('edit grant program')) ) {
      // add link to create new profile
Edsel's avatar
Edsel committed
1089
      $links[] = array( 'url'   => CRM_Utils_System::url('civicrm/grant_program', 'reset=1&action=browse', FALSE),
1090 1091 1092
                 'title' => ts('Grant Program'),
                 'ref'   => 'new-grant program');
    }
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
}

/**
 * Implements hook_civicrm_merge().
 * Move grant payments to new contact.
 *
 * @param $type
 * @param $data
 * @param null $mainId
 * @param null $otherId
 * @param null $tables
 */
function grantprograms_civicrm_merge($type, &$data, $mainId = NULL, $otherId = NULL, $tables = NULL) {
  if ($type == 'cidRefs') {
    global $db_url;
    if (!empty($db_url)) {
      $db_default = is_array($db_url) ? $db_url['default'] : $db_url;
      $db_default = ltrim(parse_url($db_default, PHP_URL_PATH), '/');
    } else {
      $db_default = '';
    }
1114

1115 1116 1117
    $data[$db_default . 'civicrm_payment'] = array('contact_id');
  }
}