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

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

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

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

/**
 * Implementation of hook_civicrm_enable
 */
function grantprograms_civicrm_enable() {
Mayur Jadhav's avatar
Mayur Jadhav committed
50
  $config = CRM_Core_Config::singleton();
51
  CRM_Utils_File::sourceSQLFile(CIVICRM_DSN, $config->extensionsDir . 'biz.jmaconsulting.grantprograms/sql/grantprograms_enable.sql');
Mayur Jadhav's avatar
Mayur Jadhav committed
52
  grantprograms_addRemoveMenu(TRUE);
Monish Deb's avatar
Monish Deb committed
53
  manageNavigationLinks('enable');
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
  $config = CRM_Core_Config::singleton();
62
  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);
Monish Deb's avatar
Monish Deb committed
64
  manageNavigationLinks('disable');
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
90
  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
91
92
93
94
95
96
/*
 * hook_civicrm_grantAssessment
 *
 * @param array $params to alter
 *
 */
Pradeep Nayak's avatar
Pradeep Nayak committed
97
function grantprograms_civicrm_grantAssessment(&$params) {
98
99
100
  if (!CRM_Utils_Array::value('grant_program_id', $params)) {
    return;
  }
101

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

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

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

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

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

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

Monish Deb's avatar
Monish Deb committed
272
273
274
275
276
277
278
279
280
281
282
283
284
285
function _setDefaultFinancialEntries($grantID) {
  $sql = "SELECT ft.check_number, ft.trxn_date, ft.trxn_id, b.id as contribution_batch_id, fi.description
    FROM civicrm_entity_financial_trxn eft
    INNER JOIN civicrm_financial_trxn ft ON eft.financial_trxn_id = ft.id AND eft.entity_table = 'civicrm_grant' AND eft.entity_id = $grantID
    LEFT JOIN civicrm_entity_financial_trxn eft1 ON eft1.financial_trxn_id = ft.id AND eft1.entity_table = 'civicrm_financial_item'
    LEFT JOIN civicrm_financial_item fi ON eft1.entity_id = fi.id
    LEFT JOIN civicrm_entity_batch eb ON eb.entity_table ='civicrm_financial_trxn' AND eb.entity_id = ft.id
    LEFT JOIN civicrm_batch b ON b.id = eb.batch_id
    ORDER BY eft.id DESC
    LIMIT 1
  ";
  return CRM_Utils_Array::value(0, CRM_Core_DAO::executeQuery($sql)->fetchAll(), []);
}

Pradeep Nayak's avatar
Pradeep Nayak committed
286
287
/*
 * hook_civicrm_buildForm civicrm hook
288
 *
Pradeep Nayak's avatar
Pradeep Nayak committed
289
290
291
292
293
 * @param string $formName form name
 * @param object $form form object
 *
*/
function grantprograms_civicrm_buildForm($formName, &$form) {
294
295
296
297
298
299
300
  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;
    }
301
    $grantUrl = CRM_Utils_System::url('civicrm/contact/view/grant',
302
303
304
      'reset=1&action=view&id=' . $activityValues['source_record_id'] . '&cid=' . current($activityValues['assignee_contact']));
    $form->assign('grantUrl', $grantUrl);
  }
305

306

Mayur Jadhav's avatar
Mayur Jadhav committed
307
  if ($formName == 'CRM_Grant_Form_Grant' && ($form->getVar('_action') != CRM_Core_Action::DELETE)) {
Mayur Jadhav's avatar
Mayur Jadhav committed
308
309
310
    $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
311
312
    $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
313
    if (CRM_Utils_Request::retrieve('context', 'String', $form) == 'search' && isset($form->_next)) {
314
      $form->addButtons(array(
Mayur Jadhav's avatar
Mayur Jadhav committed
315
        array ('type' => 'upload',
316
          'name' => ts('Save'),
Mayur Jadhav's avatar
Mayur Jadhav committed
317
318
319
          'isDefault' => true),
        array ('type' => 'submit',
          'name' => ts('Save and Next'),
320
          'subName' => 'savenext'),
Mayur Jadhav's avatar
Mayur Jadhav committed
321
        array ('type' => 'upload',
322
          'name' => ts('Save and New'),
Mayur Jadhav's avatar
Mayur Jadhav committed
323
324
          'js' => array('onclick' => "return verify();"),
          'subName' => 'new' ),
325
        array ('type' => 'cancel',
Mayur Jadhav's avatar
Mayur Jadhav committed
326
          'name' => ts('Cancel')),
327
        )
Mayur Jadhav's avatar
Mayur Jadhav committed
328
329
      );
    }
330
331
332
      CRM_Core_Region::instance('page-body')->add(array(
        'template' => 'CRM/Grant/Form/GrantExtra.tpl',
      ));
333
    $form->_reasonGrantRejected = CRM_Core_OptionGroup::values('reason_grant_ineligible');
334
335
    $form->add('select',
      'grant_rejected_reason_id',
336
      ts('Reason Grant Ineligible'),
337
      array('' => ts('- select -')) + $form->_reasonGrantRejected,
338
339
      FALSE
    );
340

341
    $form->_reasonGrantIncomplete = CRM_Core_OptionGroup::values('reason_grant_incomplete');
342
343
    $form->add('select',
      'grant_incomplete_reason_id',
344
      ts('Reason Grant Incomplete'),
345
      array('' => ts('- select -')) + $form->_reasonGrantIncomplete,
346
347
348
      FALSE
    );

349
350
    $form->add('select',
      'grant_program_id',
351
      ts('Grant Programs'),
Monish Deb's avatar
Monish Deb committed
352
      array('' => ts('- select -')) + CRM_Grant_BAO_GrantProgram::getGrantPrograms(),
353
354
      TRUE
    );
355

356
357
    //Financial Type RG-125
    $financialType = CRM_Contribute_PseudoConstant::financialType();
Monish Deb's avatar
Monish Deb committed
358
359
360
361
362
    foreach ($financialType as $id => $dontCare) {
      if (!CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($id, 'Expense Account is')) {
        unset($financialType[$id]);
      }
    }
363
364
365
    if (count($financialType)) {
      $form->assign('financialType', $financialType);
    }
366
367
    $form->add('select', 'financial_type_id',
      ts('Financial Type'),
Monish Deb's avatar
Monish Deb committed
368
      array('' => ts('- select -')) + $financialType,
369
370
      FALSE
    );
Pradeep Nayak's avatar
Pradeep Nayak committed
371
    $showFields = FALSE;
372

Pradeep Nayak's avatar
Pradeep Nayak committed
373
374
375
376
377
378
379
380
381
    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),
      );
Monish Deb's avatar
Monish Deb committed
382
383
384
      if ($currentStatus == array_search('Paid', $grantStatuses)) {
        $form->setDefaults(_setDefaultFinancialEntries($form->getVar('_id')));
      }
Pradeep Nayak's avatar
Pradeep Nayak committed
385
386
387

        $currentStatusWeight = $grantWeight[$currentStatus] + 1;
        foreach ($grantStatuses as $statusId => $statusName) {
388
          if ((($grantWeight[$currentStatus] >= 7 && $statusId == array_search('Ineligible', $grantStatuses))
Pradeep Nayak's avatar
Pradeep Nayak committed
389
390
391
392
393
394
395
396
397
398
               || ($grantWeight[$currentStatus] >= 1 && $grantWeight[$currentStatus] <= 7 && $grantWeight[$statusId] > 7 && $statusId != array_search('Ineligible', $grantStatuses))
              || $grantWeight[$currentStatus] > 7
              || $grantWeight[$statusId] < $grantWeight[$currentStatus])
              && $statusId != $currentStatus
              && $statusId != array_search('Withdrawn', $grantStatuses)
              && $currentStatusWeight != $grantWeight[$statusId]) {
            unset($grantStatuses[$statusId]);
          }
        }
      $form->removeElement('status_id');
Monish Deb's avatar
Monish Deb committed
399
400
401
402
403
404
      if ($grantStatuses[$currentStatus] == 'Paid') {
        $approvedStatusID = array_search('Approved for Payment', $grantStatuses);
        if (!empty($grantStatuses[$approvedStatusID])) {
          unset($grantStatuses[$approvedStatusID]);
        }
      }
405

Pradeep Nayak's avatar
Pradeep Nayak committed
406
407
408
409
410
411
      $element = $form->add('select', 'status_id', ts('Grant Status'),
        $grantStatuses,
        TRUE
      );
      if ($grantStatuses[$currentStatus] == 'Withdrawn') {
        $element->freeze();
412
      }
Pradeep Nayak's avatar
Pradeep Nayak committed
413
    }
Monish Deb's avatar
Monish Deb committed
414
415
416
417
418
419
    elseif ($form->getVar('_action') == CRM_Core_Action::ADD) {
      $grantStatuses = CRM_Core_OptionGroup::values('grant_status');
      unset($grantStatuses[array_search('Withdrawn', $grantStatuses)]);
      $form->add('select', 'status_id', ts('Grant Status'), $grantStatuses, TRUE);
    }

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

Pradeep Nayak's avatar
Pradeep Nayak committed
422
423
424
425
    if ($form->getVar('_id')) {
      if (CRM_Core_Permission::check('administer CiviGrant')) {
        $form->add('text', 'assessment', ts('Assessment'));
      }
426

Pradeep Nayak's avatar
Pradeep Nayak committed
427
428
429
430
      // 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();
431
432
433
434
435
436
437
438
439
        }
        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
440
441
442
443
444
445
        }
        CRM_Core_Region::instance('page-body')->add(array(
          'template' => 'CRM/Grant/Form/Freeze.tpl',
        ));
      }
      $showFields = TRUE;
446
    }
Pradeep Nayak's avatar
Pradeep Nayak committed
447
    $form->assign('showFields', $showFields);
448
449
450
  }
  if ($formName == "CRM_Grant_Form_Search") {
    $grantPrograms = CRM_Grant_BAO_GrantProgram::getGrantPrograms();
451
452
    $form->add('select',
      'grant_program_id',
453
454
455
      ts('Grant Programs'),
      array('' => ts('- select -')) + $grantPrograms
    );
456
457
458
459
460
461
462
463
    $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', ' '))),
464
465
      'money'
    );
466
467
468
    $form->add('text',
      'grant_amount_total_high',
      ts('To'),
469
      array('size' => 8, 'maxlength' => 8)
470
471
472
473
    );
    $form->addRule('grant_amount_total_high',
      ts('Please enter a valid money value (e.g. %1).',
        array(1 => CRM_Utils_Money::format('99.99', ' '))),
474
475
      'money'
    );
476
477
478
    $form->add('text',
      'grant_assessment_low',
      ts('From'),
479
480
      array('size' => 9, 'maxlength' => 9)
    );
481
482
483
484

    $form->add('text',
      'grant_assessment_high',
      ts('To'),
485
486
      array('size' => 9, 'maxlength' => 9)
    );
487
488
489
    $form->add('text',
      'grant_amount_low',
      ts('From'),
490
      array('size' => 8, 'maxlength' => 8)
491
492
493
494
    );
    $form->addRule('grant_amount_low',
      ts('Please enter a valid money value (e.g. %1).',
        array(1 => CRM_Utils_Money::format('9.99', ' '))),
495
496
      'money'
    );
Pradeep Nayak's avatar
Pradeep Nayak committed
497

498
499
500
    $form->add('text',
      'grant_amount_high',
      ts('To'),
501
502
      array('size' => 8, 'maxlength' => 8)
    );
503
504
505
    $form->addRule('grant_amount_high',
      ts('Please enter a valid money value (e.g. %1).',
        array(1 => CRM_Utils_Money::format('99.99', ' '))),
506
507
      'money'
    );
508
  }
509

510

511
  if ($formName == 'CRM_Custom_Form_Field') {
Pradeep Nayak's avatar
Pradeep Nayak committed
512
    for ($i = 1; $i <= $formName::NUM_OPTION; $i++) {
513
514
515
516
      $form->add('text',
        'option_description['. $i .']',
        'Mark',
        array('id' => 'marks')
Pradeep Nayak's avatar
Pradeep Nayak committed
517
      );
518
    }
Edselopez's avatar
Edselopez committed
519
520
521
522
    $form->assign('edit_form', 1);
    CRM_Core_Region::instance('page-body')->add(array(
      'template' => 'CRM/Grant/Form/CustomFields.tpl',
    ));
523
  }
Pradeep Nayak's avatar
Pradeep Nayak committed
524
  if ($formName == 'CRM_Custom_Form_Option') {
525
526
527
    $form->add('text',
      'description',
      'Mark',
Pradeep Nayak's avatar
Pradeep Nayak committed
528
529
      array('id' => 'marks')
    );
Edselopez's avatar
Edselopez committed
530
531
532
    CRM_Core_Region::instance('page-body')->add(array(
      'template' => 'CRM/Grant/Form/CustomFields.tpl',
    ));
533
  }
534

Edselopez's avatar
Edselopez committed
535
  if ($formName == 'CRM_Grant_Form_Search' && $form->get('context') == 'dashboard') {
Pradeep Nayak's avatar
Pradeep Nayak committed
536
537
538
539
    //Version of grant program listings
    $grantProgram = array();
    require_once 'CRM/Grant/DAO/GrantProgram.php';
    $dao = new CRM_Grant_DAO_GrantProgram();
540

Pradeep Nayak's avatar
Pradeep Nayak committed
541
542
    $dao->orderBy('label');
    $dao->find();
543

Pradeep Nayak's avatar
Pradeep Nayak committed
544
545
546
547
    while ($dao->fetch()) {
      $grantProgram[$dao->id] = array();
      CRM_Core_DAO::storeValues( $dao, $grantProgram[$dao->id]);
      $action = array_sum(array_keys(links()));
548
      $grantProgram[$dao->id]['action'] = CRM_Core_Action::formLink(links(), $action,
Pradeep Nayak's avatar
Pradeep Nayak committed
549
550
                                          array('id' => $dao->id));
    }
551
    $grantType   = CRM_Core_OptionGroup::values('grant_type');
552
    $grantStatus = CRM_Grant_BAO_GrantProgram::grantProgramStatus( );
Pradeep Nayak's avatar
Pradeep Nayak committed
553
    foreach ( $grantProgram as $key => $value ) {
Edselopez's avatar
Edselopez committed
554
      $grantProgram[$key]['grant_type_id'] = $grantType[$grantProgram[$key]['grant_type_id']];
Pradeep Nayak's avatar
Pradeep Nayak committed
555
556
557
558
559
560
      $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
561
562
  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
563
    $form->assign('hideAttachments', 1);
564
565
566
    $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));
567
568
    //Freeze Prior Year's Assessment field
    $form->_elements[$form->_elementIndex['prev_assessment']]->freeze();
Edselopez's avatar
Edselopez committed
569
    // Filter out grant being edited from search results
570
    $form->assign('grant_id', $form->getVar('_id'));
571
572
573
574
575
576
577
578
579
580
581
  }

  // 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
    );
  }
582
583
}

Edselopez's avatar
Edselopez committed
584
function grantprograms_civicrm_pageRun( &$page ) {
585
586
587
588
589
590
  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
591
    $smarty = CRM_Core_Smarty::singleton();
592
    if ($smarty->_tpl_vars['action'] & CRM_Core_Action::VIEW) {
Mayur Jadhav's avatar
Mayur Jadhav committed
593
      $smarty->_tpl_vars['assessment'] = CRM_Core_DAO::getFieldValue('CRM_Grant_DAO_Grant', $smarty->_tpl_vars['id'], 'assessment', 'id');
594
595
      $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
596
597
598
599
      CRM_Core_Region::instance('page-body')->add(array(
        'template' => 'CRM/Grant/Page/GrantExtra.tpl',
      ));
    }
600
  }
601
602

  if ($page->getVar('_name') == "CRM_Custom_Page_Option") {
Mayur Jadhav's avatar
Mayur Jadhav committed
603
604
    $params['id'] = $page->getVar('_fid');
    $params['custom_group_id'] = $page->getVar('_gid');
Mayur Jadhav's avatar
Mayur Jadhav committed
605
    CRM_Core_BAO_CustomField::retrieve($params, $defaults);
Mayur Jadhav's avatar
Mayur Jadhav committed
606
607
608
609
610
611
612
    $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
613
614
    $page->assign('view_form', 1);
    CRM_Core_Region::instance('page-body')->add(array(
Mayur Jadhav's avatar
Mayur Jadhav committed
615
      'template' => 'CRM/Grant/Form/CustomFieldsView.tpl',
Edselopez's avatar
Edselopez committed
616
617
    ));
  }
618
619
620
621
622
623
624
625

  if ($page->getVar('_name') == "CRM_Grant_Page_DashBoard") {
    $page->assign('grantSummary', CRM_Grant_BAO_GrantPayment::getGrantSummary(CRM_Core_Permission::check('administer CiviCRM')));
  }
}

function grantprograms_civicrm_alterTemplateFile($formName, &$form, $context, &$tplName) {
  if ($tplName == 'CRM/Grant/Page/DashBoard.tpl') {
Monish Deb's avatar
Monish Deb committed
626
    $tplName = 'CRM/Grant/Page/DashboardExtra.tpl';
627
628
629
630
631
632
633
  }
}

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

Pradeep Nayak's avatar
Pradeep Nayak committed
636
637
638
639
640
641
642
643
644
/*
 * hook_civicrm_validate
 *
 * @param string $formName form name
 * @param array $fields form submitted values
 * @param array $files file properties as sent by PHP POST protocol
 * @param object $form form object
 *
 */
Monish Deb's avatar
Monish Deb committed
645
function grantprograms_civicrm_validateForm($formName, &$fields, &$files, &$form, &$errors) {
646
647
  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
648
649
650
651
    $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) {
652
      $errors[''] = ts('Error');
Mayur Jadhav's avatar
Mayur Jadhav committed
653
654
655
656
657
658
659
      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");
660
661
    }
  }
Monish Deb's avatar
Monish Deb committed
662
  if ($formName == 'CRM_Grant_Form_Grant') {
Pradeep Nayak's avatar
Pradeep Nayak committed
663
    $defaults = array();
664
    $params['id'] = $form->_submitValues['grant_program_id'];
Pradeep Nayak's avatar
Pradeep Nayak committed
665
    CRM_Grant_BAO_GrantProgram::retrieve($params, $defaults);
Pradeep Nayak's avatar
Pradeep Nayak committed
666
    if (array_key_exists('amount_granted', $form->_submitValues) && CRM_Utils_Array::value('remainder_amount', $defaults) < $form->_submitValues['amount_granted']) {
Edselopez's avatar
Edselopez committed
667
      $errors['amount_granted'] = ts('You need to increase the Grant Program Remainder Amount');
668
    }
669

670
671
672
    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');
    }
Monish Deb's avatar
Monish Deb committed
673
674
    if (!empty($fields['status_id'])) {
      $grantStatuses = CRM_Core_OptionGroup::values('grant_status');
Monish Deb's avatar
Monish Deb committed
675
      if (in_array($grantStatuses[$fields['status_id']], ['Paid', 'Withdrawn', 'Approved for Payment', 'Eligible']) && empty($fields['financial_type_id'])) {
Monish Deb's avatar
Monish Deb committed
676
677
678
        $errors['financial_type_id'] = ts('Financial Type is a required field');
      }
      if ($grantStatuses[$fields['status_id']] == 'Paid') {
Monish Deb's avatar
Monish Deb committed
679
680
        if (empty($fields['contribution_batch_id'])) {
          $errors['contribution_batch_id'] = ts('Batch is a required field');
Monish Deb's avatar
Monish Deb committed
681
682
683
        }
      }
    }
684
  }
Pradeep Nayak's avatar
Pradeep Nayak committed
685
  if ($formName == 'CRM_Grant_Form_Search') {
686
    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
687
688
689
      foreach ($fields as $fieldKey => $fieldValue) {
        if (strstr($fieldKey, 'mark_x_')) {
          $grantID = ltrim( $fieldKey, 'mark_x_' );
Mayur Jadhav's avatar
Mayur Jadhav committed
690
          if ($fields['task'] == PAY_GRANTS) {
Monish Deb's avatar
Monish Deb committed
691
            $grantDetails = civicrm_api3('Grant', 'get', ['id' => $grantID])['values'];
Mayur Jadhav's avatar
Mayur Jadhav committed
692
693
694
695
696
697
698
699
700
701
702
703
704
            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
705
706
707
708
          }
        }
      }
    }
709
  }
Pradeep Nayak's avatar
Pradeep Nayak committed
710
  return empty($errors) ? TRUE : $errors;
Pradeep Nayak's avatar
Pradeep Nayak committed
711
712
}

Pradeep Nayak's avatar
Pradeep Nayak committed
713
function grantprograms_civicrm_pre($op, $objectName, $id, &$params) {
Monish Deb's avatar
Monish Deb committed
714
715
716
  if ($objectName == 'Grant' && in_array($op, ['edit', 'create'])) {
    $grantStatuses = CRM_Core_OptionGroup::values('grant_status');
    $grantStatusApproved = array_search('Approved for Payment', $grantStatuses);
Mayur Jadhav's avatar
Mayur Jadhav committed
717
    $calculateAssessment = FALSE;
Monish Deb's avatar
Monish Deb committed
718
719
720
721
722
723
    $previousGrant = [];
    if ($op == 'edit') {
      $previousGrant = civicrm_api3('Grant', 'getsingle', ['id' => $id]);
      $sendMail = (CRM_Utils_Array::value('status_id', $params) !== $previousGrant['status_id']);
      $calculateAssessment = (CRM_Utils_Array::value('assessment', $params) == $previousGrant['assessment']);
      $params['id'] = $id;
Mayur Jadhav's avatar
Mayur Jadhav committed
724
    }
Monish Deb's avatar
Monish Deb committed
725
    if (($grantStatusApproved == CRM_Utils_Array::value('status_id', $params) && empty($params['decision_date'])) ||
726
      (empty($previousGrant['decision_date']) && CRM_Utils_Array::value('status_id', $previousGrant) != CRM_Utils_Array::value('status_id', $params))
727
    ) {
Pradeep Nayak's avatar
Pradeep Nayak committed
728
729
      $params['decision_date'] = date('Ymd');
    }
Monish Deb's avatar
Monish Deb committed
730
731
732

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

Monish Deb's avatar
Monish Deb committed
735
736
737
738
739
740
741
    if ($op == 'edit') {
      if (!CRM_Utils_Array::value('allocation', $params) &&
        !empty($previousGrant['amount_granted']) &&
        CRM_Utils_Array::value('amount_granted', $params) != $previousGrant['amount_granted'] &&
        !empty($previousGrant['grant_program_id'])
      ) {
        $programParams = ['id' => $previousGrant['grant_program_id']];
Mayur Jadhav's avatar
Mayur Jadhav committed
742
        $grantProgram = CRM_Grant_BAO_GrantProgram::retrieve($programParams, CRM_Core_DAO::$_nullArray);
Monish Deb's avatar
Monish Deb committed
743
744
        $grantProgram->remainder_amount -= CRM_Utils_Rule::cleanMoney($params['amount_granted']) - $previousGrant['amount_granted'];
        $grantProgram->save();
745
746
        $params['manualEdit'] = TRUE;
      }
Monish Deb's avatar
Monish Deb committed
747
      CRM_Core_Smarty::singleton()->assign('previousGrant', $previousGrant);
748
    }
Monish Deb's avatar
Monish Deb committed
749
    elseif (!empty($params['amount_granted'])) {
Mayur Jadhav's avatar
Mayur Jadhav committed
750
751
      $params['manualEdit'] = TRUE;
    }
Monish Deb's avatar
Monish Deb committed
752
    CRM_Core_BAO_Cache::setItem($params, 'grant params', __FUNCTION__);
Pradeep Nayak's avatar
Pradeep Nayak committed
753
754
755
  }
}

Monish Deb's avatar
Monish Deb committed
756

Pradeep Nayak's avatar
Pradeep Nayak committed
757
function grantprograms_civicrm_post($op, $objectName, $objectId, &$objectRef) {
Monish Deb's avatar
Monish Deb committed
758
  if ($objectName == 'Grant' && in_array($op, ['edit', 'create'])) {
Monish Deb's avatar
Monish Deb committed
759
    $params = CRM_Core_BAO_Cache::getItem("grant params", 'grantprograms_civicrm_pre');
Monish Deb's avatar
Monish Deb committed
760
761
762
763
764
    $smarty = CRM_Core_Smarty::singleton();
    $previousGrant = $smarty->get_template_vars('previousGrant');
    // core bug $op always return 'create'
    $op = ($op == 'create' && !empty($previousGrant)) ? 'edit' : $op;
    $grantStatuses = CRM_Core_OptionGroup::values('grant_status');
Mayur Jadhav's avatar
Mayur Jadhav committed
765
    $grantProgram  = new CRM_Grant_DAO_GrantProgram();
Monish Deb's avatar
Monish Deb committed
766
767
768
769
770
771
772
773
774
775
    if ($grantProgram->id = CRM_Utils_Array::value('grant_program_id', $params)) {
      $grantProgram->find(TRUE);
      $isAutoEmail = (!empty($grantProgram->is_auto_email));
      if ($isAutoEmail) {
        $params['is_auto_email'] = TRUE;
        $params['tplParams'] = [];
        // FIXME: for grant profiles
        $grantStatuses = CRM_Core_OptionGroup::values('grant_status');
        if (CRM_Utils_Array::value('grant_program_id', $params)) {
          $params['tplParams']['grant_programs'] = CRM_Utils_Array::value($params['grant_program_id'], CRM_Grant_BAO_GrantProgram::getGrantPrograms(), '');
Mayur Jadhav's avatar
Mayur Jadhav committed
776
        }
Monish Deb's avatar
Monish Deb committed
777
778
779
780
781
        $params['tplParams']['grant_type'] = CRM_Utils_Array::value($params['grant_type_id'], CRM_Core_OptionGroup::values('grant_type'));
        $params['tplParams']['grant_status'] = CRM_Utils_Array::value($params['status_id'], $grantStatuses);

        if (CRM_Utils_Array::value('grant_rejected_reason_id', $params)) {
          $params['tplParams']['grant_rejected_reason'] = CRM_Utils_Array::value($params['grant_rejected_reason_id'], CRM_Core_OptionGroup::values('reason_grant_ineligible'));
Mayur Jadhav's avatar
Mayur Jadhav committed
782
        }
Monish Deb's avatar
Monish Deb committed
783
784
        if (CRM_Utils_Array::value('grant_incomplete_reason_id', $params)) {
          $params['tplParams']['grant_incomplete_reason'] = CRM_Utils_Array::value($params['grant_incomplete_reason_id'], CRM_Core_OptionGroup::values('reason_grant_incomplete'));
Pradeep Nayak's avatar
Pradeep Nayak committed
785
        }
Monish Deb's avatar
Monish Deb committed
786
        $params['tplParams']['grant'] = $params;
Pradeep Nayak's avatar
Pradeep Nayak committed
787
      }
788

Monish Deb's avatar
Monish Deb committed
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
      $previousStatus = '';
      if ($previousGrant && !empty($previousGrant['status_id'])) {
        $previousGrantStatus = CRM_Utils_Array::value($previousGrant['status_id'], $grantStatuses, '');
        $currentGrantStatus = CRM_Utils_Array::value($params['status_id'], $grantStatuses, '');
        if ($isAutoEmail) {
          CRM_Grant_BAO_GrantProgram::sendMail($params['contact_id'], $params, $currentGrantStatus, $objectId, $previousGrantStatus);
        }
        else {
          CRM_Grant_BAO_GrantProgram::createStatusChangeActivity(
            $params['contact_id'],
            $currentGrantStatus,
            $previousGrantStatus,
            $params['contact_id']
          );
        }
804
      }
Mayur Jadhav's avatar
Mayur Jadhav committed
805
    }
Monish Deb's avatar
Monish Deb committed
806
807
808
809

    // record financial record only on 'New Grant' form or on edit when grant status is changed
    $recordFinancialRecords = ($op == 'create' || (!empty($previousGrant['status_id']) && $previousGrant['status_id'] != $objectRef->status_id));
    if (!empty($objectRef->financial_type_id) && $recordFinancialRecords) {
Monish Deb's avatar
Monish Deb committed
810
811
812
813
814
815
816
817
818
819
820
      $grantParams = (array) $objectRef;
      _createFinancialEntries($previousGrant['status_id'], $grantParams, $params);
    }
  }
  elseif ($objectName == 'Grant' && $op == 'delete') {
    CRM_Grant_BAO_GrantPayment::deleteGrantFinancialEntries($objectId);
  }
}

function _createFinancialEntries($previousStatusID, $grantParams, $params) {
  $grantStatuses = CRM_Core_OptionGroup::values('grant_status');
Monish Deb's avatar
Monish Deb committed
821
  $multiEntries = _processMultiFundEntries($_POST);
Monish Deb's avatar
Monish Deb committed
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
  $amount = $grantParams['amount_total'];
  $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
  $financialItemStatus = CRM_Core_PseudoConstant::accountOptionValues('financial_item_status');
  $currentStatusID = $grantParams['status_id'];
  $createItem = TRUE;
  $trxnParams = [];
  $financialItemStatusID = array_search('Paid', $financialItemStatus);
  if ($currentStatusID == array_search('Approved for Payment', $grantStatuses)) {
    $trxnParams['to_financial_account_id'] = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($grantParams['financial_type_id'], 'Accounts Receivable Account is');
    $financialItemStatusID = array_search('Unpaid', $financialItemStatus);
    $trxnParams['status_id'] = array_search('Pending', $contributionStatuses);
  }
  elseif ($currentStatusID == array_search('Paid', $grantStatuses)) {
    $trxnParams['to_financial_account_id'] = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($grantParams['financial_type_id'], 'Asset Account is') ?: CRM_Grant_BAO_GrantProgram::getAssetFinancialAccountID();
    $trxnParams['status_id'] = array_search('Completed', $contributionStatuses);
    $createItem = empty($previousStatusID);
  }
  elseif ($currentStatusID == array_search('Withdrawn', $grantStatuses)) {
    $trxnParams['to_financial_account_id'] = CRM_Grant_BAO_GrantProgram::getAssetFinancialAccountID();
    $trxnParams['from_financial_account_id'] = CRM_Core_DAO::singleValueQuery("
    SELECT to_financial_account_id FROM civicrm_financial_trxn  cft
      INNER JOIN civicrm_entity_financial_trxn ecft ON ecft.financial_trxn_id = cft.id
    WHERE  ecft.entity_id = " . $grantParams['id'] . " and ecft.entity_table = 'civicrm_grant'
    ORDER BY cft.id DESC LIMIT 1");
    $trxnParams['status_id'] = array_search('Cancelled', $contributionStatuses);
    $financialItemStatusID = array_search('Unpaid', $financialItemStatus);
    $amount = -$amount;
  }
Monish Deb's avatar
Monish Deb committed
850

Monish Deb's avatar
Monish Deb committed
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
  //build financial transaction params
  $trxnParams = array_merge($trxnParams, array(
    'trxn_date' => date('YmdHis'),
    'currency' => $grantParams['currency'],
    'entity_table' => 'civicrm_grant',
    'entity_id' => $grantParams['id'],
  ));

  if (empty($multiEntries)) {
    if ($previousStatusID == array_search('Approved for Payment', $grantStatuses) &&
      $currentStatusID == array_search('Paid', $grantStatuses)
    ) {
      $multiEntries[] = [
        'from_financial_account_id' => CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($grantParams['financial_type_id'], 'Accounts Receivable Account is'),
        'total_amount' => $amount,
      ];
    }
    else {
      $multiEntries[] = [
        'from_financial_account_id' => CRM_Utils_Array::value('from_financial_account_id', $trxnParams),
        'total_amount' => $amount,
      ];
    }
  }

  $financialItemID = NULL;
  foreach ($multiEntries as $key => $entry) {
    $trxnParams = array_merge($trxnParams, $entry);
    $trxnId = CRM_Core_BAO_FinancialTrxn::create($trxnParams);

    if ($currentStatusID == array_search('Paid', $grantStatuses)) {
      CRM_Grant_Form_Task_GrantPayment::processPaymentDetails([
Monish Deb's avatar
Monish Deb committed
883
884
        'trxn_id' => $params['trxn_id'],
        'financial_trxn_id' => $trxnId->id,
Monish Deb's avatar
Monish Deb committed
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
        'batch_id' => $params['contribution_batch_id'],
        'check_number' => $params['check_number'],
        'description' => CRM_Utils_Array::value('description', $params),
      ]);
    }

    if ($createItem) {
      $financialAccountId = CRM_Contribute_PseudoConstant::getRelationalFinancialAccount($grantParams['financial_type_id'], 'Accounts Receivable Account is');
      if ($financialItemID) {
        civicrm_api3('EntityFinancialTrxn', 'create', [
          'entity_table' => 'civicrm_financial_item',
          'entity_id' => $financialItemID,
          'financial_trxn_id' => $trxnId->id,
          'amount' => $entry['total_amount'],
        ]);
      }
      else {
        $itemParams = array(
          'transaction_date' => date('YmdHis'),
          'contact_id' => $grantParams['contact_id'],
          'currency' => $grantParams['currency'],
          'amount' => $entry['total_amount'],
          'description' => CRM_Utils_Array::value('description', $params),
          'status_id' => $financialItemStatusID,
          'financial_account_id' => $financialAccountId,
Mayur Jadhav's avatar
Mayur Jadhav committed
910
          'entity_table' => 'civicrm_grant',
Monish Deb's avatar
Monish Deb committed
911
          'entity_id' => $grantParams['id'],
Mayur Jadhav's avatar
Mayur Jadhav committed
912
        );
Monish Deb's avatar
Monish Deb committed
913
914
        $trxnIds['id'] = $trxnId->id;
        $financialItemID = CRM_Financial_BAO_FinancialItem::create($itemParams, NULL, $trxnIds)->id;
Mayur Jadhav's avatar
Mayur Jadhav committed
915
916
917
      }
    }
  }
Pradeep Nayak's avatar
Pradeep Nayak committed
918
919
920
921
922
923
924
925
926
927
}

/*
 * hook_civicrm_postProcess
 *
 * @param string $formName form name
 * @param object $form form object
 *
 */
function grantprograms_civicrm_postProcess($formName, &$form) {
Mayur Jadhav's avatar
Mayur Jadhav committed
928
929
930
931
  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
932
933
934
935
936
937
938
        $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
939
940
941
      }
    }
  }
942

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

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

Monish Deb's avatar
Monish Deb committed
998
999
1000
function _processMultiFundEntries($values) {
  $multifundEntries = [];
  if (empty($values['multifund_amount'])) {
For faster browsing, not all history is shown. View entire blame