Merge pull request #48 from dpradeep/merge-forward
[civicrm-core.git] / CRM / Report / Form / Grant / Statistics.php
CommitLineData
6a488035 1<?php
6a488035
TO
2
3/*
4 +--------------------------------------------------------------------+
06b69b18 5 | CiviCRM version 4.5 |
6a488035 6 +--------------------------------------------------------------------+
06b69b18 7 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
8 +--------------------------------------------------------------------+
9 | This file is a part of CiviCRM. |
10 | |
11 | CiviCRM is free software; you can copy, modify, and distribute it |
12 | under the terms of the GNU Affero General Public License |
13 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | |
15 | CiviCRM is distributed in the hope that it will be useful, but |
16 | WITHOUT ANY WARRANTY; without even the implied warranty of |
17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
18 | See the GNU Affero General Public License for more details. |
19 | |
20 | You should have received a copy of the GNU Affero General Public |
21 | License and the CiviCRM Licensing Exception along |
22 | with this program; if not, contact CiviCRM LLC |
23 | at info[AT]civicrm[DOT]org. If you have questions about the |
24 | GNU Affero General Public License or the licensing of CiviCRM, |
25 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
26 +--------------------------------------------------------------------+
27*/
28
29/**
30 *
31 * @package CRM
06b69b18 32 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
33 * $Id$
34 *
35 */
36class CRM_Report_Form_Grant_Statistics extends CRM_Report_Form {
37
38 protected $_addressField = FALSE;
39
40 protected $_customGroupExtends = array('Grant');
41
42 protected $_add2groupSupported = FALSE;
74cf4551
EM
43
44 /**
45 *
46 */
47 /**
48 *
49 */
6a488035
TO
50 function __construct() {
51 $this->_columns = array(
52 'civicrm_grant' =>
53 array(
54 'dao' => 'CRM_Grant_DAO_Grant',
55 'fields' =>
56 array(
57 'summary_statistics' =>
58 array(
59 'name' => 'id',
60 'title' => ts('Summary Statistics'),
61 'required' => TRUE,
62 ),
63 'grant_type_id' =>
64 array(
65 'name' => 'grant_type_id',
66 'title' => ts('By Grant Type'),
67 ),
6a488035
TO
68 'status_id' =>
69 array(
70 'no_display' => TRUE,
71 'required' => TRUE,
72 ),
73 'amount_total' =>
74 array(
75 'no_display' => TRUE,
76 'required' => TRUE,
77 ),
78 'grant_report_received' =>
79 array(
80 'no_display' => TRUE,
81 'required' => TRUE,
82 ),
83 'currency' =>
84 array(
85 'no_display' => TRUE,
86 'required' => TRUE,
87 ),
88 ),
89 'filters' =>
90 array(
91 'application_received_date' =>
92 array(
93 'name' => 'application_received_date',
94 'title' => ts('Application Received'),
95 'operatorType' => CRM_Report_Form::OP_DATE,
96 'type' => CRM_Utils_Type::T_DATE,
97 ),
98 'decision_date' =>
99 array(
100 'name' => 'decision_date',
101 'title' => ts('Grant Decision'),
102 'operatorType' => CRM_Report_Form::OP_DATE,
103 'type' => CRM_Utils_Type::T_DATE,
104 ),
105 'money_transfer_date' =>
106 array(
107 'name' => 'money_transfer_date',
108 'title' => ts('Money Transferred'),
109 'operatorType' => CRM_Report_Form::OP_DATE,
110 'type' => CRM_Utils_Type::T_DATE,
111 ),
112 'grant_due_date' =>
113 array(
114 'name' => 'grant_due_date',
115 'title' => ts('Grant Report Due'),
116 'operatorType' => CRM_Report_Form::OP_DATE,
117 'type' => CRM_Utils_Type::T_DATE,
118 ),
119 'grant_type' =>
120 array(
121 'name' => 'grant_type_id',
122 'title' => ts('Grant Type'),
123 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
fb1fd730 124 'options' => CRM_Core_PseudoConstant::get('CRM_Grant_DAO_Grant', 'grant_type_id'),
6a488035
TO
125 ),
126 'status_id' =>
127 array(
128 'name' => 'status_id',
129 'title' => ts('Grant Status'),
130 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
fb1fd730 131 'options' => CRM_Core_PseudoConstant::get('CRM_Grant_DAO_Grant', 'status_id'),
6a488035
TO
132 ),
133 'amount_requested' =>
134 array(
135 'name' => 'amount_requested',
136 'title' => ts('Amount Requested'),
137 'type' => CRM_Utils_Type::T_MONEY,
138 ),
139 'amount_granted' =>
140 array(
141 'name' => 'amount_granted',
142 'title' => ts('Amount Granted'),
143 ),
144 'grant_report_received' =>
145 array(
146 'name' => 'grant_report_received',
147 'title' => ts('Report Received'),
148 'operatorType' => CRM_Report_Form::OP_SELECT,
149 'options' => array('' => ts('- select -'),
150 0 => ts('No'),
151 1 => ts('Yes'),
152 ),
153 ),
154 ),
155 ),
156 'civicrm_contact' =>
157 array(
158 'dao' => 'CRM_Contact_DAO_Contact',
159 'fields' =>
160 array(
161 'id' =>
162 array(
163 'required' => TRUE,
164 'no_display' => TRUE,
165 ),
166 'gender_id' =>
167 array(
168 'name' => 'gender_id',
169 'title' => ts('By Gender'),
170 ),
171 'contact_type' =>
172 array(
173 'name' => 'contact_type',
174 'title' => ts('By Contact Type'),
175 ),
176 ),
177 'filters' =>
178 array(
179 'gender_id' =>
180 array(
181 'name' => 'gender_id',
182 'title' => ts('Gender'),
183 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
26cf88b5 184 'options' => CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'),
6a488035
TO
185 ),
186 'contact_type' =>
187 array(
188 'name' => 'contact_type',
189 'title' => ts('Contact Type'),
190 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
191 'options' => CRM_Contact_BAO_ContactType::basicTypePairs(),
192 ),
193 ),
194 'grouping' => 'contact-fields',
195 ),
196 'civicrm_world_region' =>
197 array(
198 'dao' => 'CRM_Core_DAO_Worldregion',
199 'fields' =>
200 array(
201 'id' =>
202 array(
203 'no_display' => TRUE,
204 ),
205 'name' =>
206 array(
207 'name' => 'name',
208 'title' => ts('By World Region'),
209 ),
210 ),
211 'filters' =>
212 array(
213 'region_id' =>
214 array(
215 'name' => 'id',
216 'title' => ts('World Region'),
217 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
218 'options' => CRM_Core_PseudoConstant::worldRegion(),
219 ),
220 ),
221 ),
222 'civicrm_address' =>
223 array(
224 'dao' => 'CRM_Core_DAO_Address',
225 'fields' =>
226 array(
227 'country_id' =>
228 array(
229 'name' => 'country_id',
230 'title' => ts('By Country'),
231 ),
232 ),
233 'filters' =>
234 array(
235 'country_id' =>
236 array('title' => ts('Country'),
237 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
238 'options' => CRM_Core_PseudoConstant::country(),
239 ),
240 ),
241 ),
242 );
243 parent::__construct();
244 }
245
246 function select() {
247 $select = array();
248
249 $this->_columnHeaders = array();
250 foreach ($this->_columns as $tableName => $table) {
251 if (in_array($tableName, array(
252 'civicrm_address', 'civicrm_world_region'))) {
253 $this->_addressField = TRUE;
254 }
255
256 if (array_key_exists('fields', $table)) {
257 foreach ($table['fields'] as $fieldName => $field) {
8cc574cf 258 if (!empty($field['required']) || !empty($this->_params['fields'][$fieldName])) {
6a488035
TO
259
260 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
261
262 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array::value('title', $field);
263 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
264 }
265 }
266 }
267 }
268
269 $this->_select = "SELECT " . implode(', ', $select) . " ";
270 }
271
272 function from() {
273 $this->_from = "
274 FROM civicrm_grant {$this->_aliases['civicrm_grant']}
39eb89f4 275 LEFT JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
6a488035
TO
276 ON ({$this->_aliases['civicrm_grant']}.contact_id = {$this->_aliases['civicrm_contact']}.id ) ";
277 if ($this->_addressField) {
278 $this->_from .= "
39eb89f4
DL
279 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
280 ON {$this->_aliases['civicrm_contact']}.id =
281 {$this->_aliases['civicrm_address']}.contact_id AND
6a488035
TO
282 {$this->_aliases['civicrm_address']}.is_primary = 1\n
283 LEFT JOIN civicrm_country country
39eb89f4 284 ON {$this->_aliases['civicrm_address']}.country_id =
6a488035
TO
285 country.id
286 LEFT JOIN civicrm_worldregion {$this->_aliases['civicrm_world_region']}
39eb89f4 287 ON country.region_id =
6a488035
TO
288 {$this->_aliases['civicrm_world_region']}.id";
289 }
290 }
291
292 function where() {
39eb89f4
DL
293 $whereClause = "
294WHERE {$this->_aliases['civicrm_grant']}.amount_total IS NOT NULL
6a488035 295 AND {$this->_aliases['civicrm_grant']}.amount_total > 0";
7bed22fc 296 $this->_where = $whereClause;
6a488035
TO
297
298 foreach ($this->_columns as $tableName => $table) {
299 if (array_key_exists('filters', $table)) {
300 foreach ($table['filters'] as $fieldName => $field) {
301
302 $clause = NULL;
303 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
304 $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
305 $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
306 $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
307
308 if ($relative || $from || $to) {
309 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
310 }
311 }
312 else {
313 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
314 if (($fieldName == 'grant_report_received') &&
315 (CRM_Utils_Array::value("{$fieldName}_value", $this->_params) === 0)
316 ) {
317 $op = 'nll';
318 $this->_params["{$fieldName}_value"] = NULL;
319 }
320 if ($op) {
321 $clause = $this->whereClause($field,
322 $op,
323 CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
324 CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
325 CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
326 );
327 }
328 }
329 if (!empty($clause)) {
330 $clauses[] = $clause;
331 $this->_where .= " AND " . implode(' AND ', $clauses);
332 $this->_whereClause = $whereClause . " AND " . implode(' AND ', $clauses);
333 }
334 }
335 }
336 }
337 }
338
339 function groupBy() {
340 $this->_groupBy = '';
341
a7488080 342 if (!empty($this->_params['fields']) &&
6a488035
TO
343 is_array($this->_params['fields']) &&
344 !empty($this->_params['fields'])
345 ) {
346 foreach ($this->_columns as $tableName => $table) {
347 if (array_key_exists('fields', $table)) {
348 foreach ($table['fields'] as $fieldName => $field) {
a7488080 349 if (!empty($this->_params['fields'][$fieldName])) {
6a488035
TO
350 $this->_groupBy[] = $field['dbAlias'];
351 }
352 }
353 }
354 }
355 }
356 if (!empty($this->_groupBy)) {
357 $this->_groupBy = " GROUP BY " . implode(', ', $this->_groupBy);
358 }
359 }
360
361 function postProcess() {
362 // get ready with post process params
363 $this->beginPostProcess();
364
365 // build query, do not apply limit
366 $sql = $this->buildQuery(FALSE);
367
368 // build array of result based on column headers. This method also allows
369 // modifying column headers before using it to build result set i.e $rows.
370 $this->buildRows($sql, $rows);
371
372 // format result set.
373 $this->formatDisplay($rows);
374
375 // assign variables to templates
376 $this->doTemplateAssignment($rows);
377
378 // do print / pdf / instance stuff if needed
379 $this->endPostProcess($rows);
380 }
381
74cf4551
EM
382 /**
383 * @param $rows
384 */
6a488035
TO
385 function alterDisplay(&$rows) {
386 $totalStatistics = $grantStatistics = array();
387 $totalStatistics = parent::statistics($rows);
388 $awardedGrantsAmount = $grantsReceived = $totalAmount = $awardedGrants = $grantReportsReceived = 0;
389 $grantStatistics = array();
390
fb1fd730 391 $grantTypes = CRM_Core_PseudoConstant::get('CRM_Grant_DAO_Grant', 'grant_type_id');
6a488035 392 $countries = CRM_Core_PseudoConstant::country();
26cf88b5 393 $gender = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id');
6a488035
TO
394
395 $grantAmountTotal = "
39eb89f4
DL
396SELECT COUNT({$this->_aliases['civicrm_grant']}.id) as count ,
397 SUM({$this->_aliases['civicrm_grant']}.amount_total) as totalAmount
6a488035
TO
398 {$this->_from} ";
399
400 if (!empty($this->_whereClause)) {
401 $grantAmountTotal .= " {$this->_whereClause}";
402 }
403
404 $result = CRM_Core_DAO::executeQuery($grantAmountTotal);
405 while ($result->fetch()) {
406 $grantsReceived = $result->count;
407 $totalAmount = $result->totalAmount;
408 }
409
410 if (!$grantsReceived) {
411 return;
412 }
413
414 $grantAmountAwarded = "
39eb89f4 415SELECT COUNT({$this->_aliases['civicrm_grant']}.id) as count ,
6a488035
TO
416 SUM({$this->_aliases['civicrm_grant']}.amount_granted) as grantedAmount,
417 SUM({$this->_aliases['civicrm_grant']}.amount_total) as totalAmount
418 {$this->_from} ";
419
420 if (!empty($this->_where)) {
421 $grantAmountAwarded .= " {$this->_where}";
422 }
423 $values = CRM_Core_DAO::executeQuery($grantAmountAwarded);
424 while ($values->fetch()) {
425 $awardedGrants = $values->count;
426 $awardedGrantsAmount = $values->totalAmount;
427 $amountGranted = $values->grantedAmount;
428 }
429
430 foreach ($rows as $key => $values) {
a7488080 431 if (!empty($values['civicrm_grant_grant_report_received'])) {
6a488035
TO
432 $grantReportsReceived++;
433 }
434
a7488080 435 if (!empty($values['civicrm_grant_grant_type_id'])) {
6a488035
TO
436 $grantType = CRM_Utils_Array::value($values['civicrm_grant_grant_type_id'], $grantTypes);
437 $grantStatistics['civicrm_grant_grant_type_id']['title'] = ts('By Grant Type');
438 self::getStatistics($grantStatistics['civicrm_grant_grant_type_id'], $grantType, $values,
439 $awardedGrants, $awardedGrantsAmount
440 );
441 }
442
6a488035
TO
443 if (array_key_exists('civicrm_world_region_name', $values)) {
444 $region = CRM_Utils_Array::value('civicrm_world_region_name', $values);
445 $region = ($region) ? $region : 'Unassigned';
446 $grantStatistics['civicrm_world_region_name']['title'] = ts('By Region');
447 self::getStatistics($grantStatistics['civicrm_world_region_name'], $region, $values,
448 $awardedGrants, $awardedGrantsAmount
449 );
450 }
451
452 if (array_key_exists('civicrm_address_country_id', $values)) {
453 $country = CRM_Utils_Array::value($values['civicrm_address_country_id'], $countries);
454 $country = ($country) ? $country : 'Unassigned';
455 $grantStatistics['civicrm_address_country_id']['title'] = ts('By Country');
456 self::getStatistics($grantStatistics['civicrm_address_country_id'], $country, $values,
457 $awardedGrants, $awardedGrantsAmount
458 );
459 }
460
461 if ($type = CRM_Utils_Array::value('civicrm_contact_contact_type', $values)) {
462 $grantStatistics['civicrm_contact_contact_type']['title'] = ts('By Contact Type');
463 $title = "Total Number of {$type}(s)";
464 self::getStatistics($grantStatistics['civicrm_contact_contact_type'], $title, $values,
465 $awardedGrants, $awardedGrantsAmount
466 );
467 }
468
469 if (array_key_exists('civicrm_contact_gender_id', $values)) {
470 $genderLabel = CRM_Utils_Array::value($values['civicrm_contact_gender_id'], $gender);
471 $genderLabel = ($genderLabel) ? $genderLabel : 'Unassigned';
472 $grantStatistics['civicrm_contact_gender_id']['title'] = ts('By Gender');
473 self::getStatistics($grantStatistics['civicrm_contact_gender_id'], $genderLabel, $values,
474 $awardedGrants, $awardedGrantsAmount
475 );
476 }
477
478 foreach ($values as $customField => $customValue) {
479 if (strstr($customField, 'civicrm_value_')) {
480 $customFieldTitle = CRM_Utils_Array::value('title', $this->_columnHeaders[$customField]);
481 $customGroupTitle = explode('_custom', strstr($customField, 'civicrm_value_'));
482 $customGroupTitle = $this->_columns[$customGroupTitle[0]]['group_title'];
483 $grantStatistics[$customGroupTitle]['title'] = ts('By %1', array(1 => $customGroupTitle));
484
485 $customData = ($customValue) ? FALSE : TRUE;
486 self::getStatistics($grantStatistics[$customGroupTitle], $customFieldTitle, $values,
487 $awardedGrants, $awardedGrantsAmount, $customData
488 );
489 }
490 }
491 }
492
493 $totalStatistics['total_statistics'] = array('grants_received' => array('title' => ts('Grant Requests Received'),
494 'count' => $grantsReceived,
495 'amount' => $totalAmount,
496 ),
497 'grants_awarded' => array('title' => ts('Grants Awarded'),
498 'count' => $awardedGrants,
499 'amount' => $amountGranted,
500 ),
501 'grants_report_received' => array('title' => ts('Grant Reports Received'),
502 'count' => $grantReportsReceived,
503 ),
504 );
505
506 $this->assign('totalStatistics', $totalStatistics);
507 $this->assign('grantStatistics', $grantStatistics);
508
509 if ($this->_outputMode == 'csv' ||
510 $this->_outputMode == 'pdf'
511 ) {
512 $row = array();
513 $this->_columnHeaders = array('civicrm_grant_total_grants' => array('title' => ts('Summary')),
514 'civicrm_grant_count' => array('title' => ts('Count')),
515 'civicrm_grant_amount' => array('title' => ts('Amount')),
516 );
517 foreach ($totalStatistics['total_statistics'] as $title => $value) {
518 $row[] = array(
519 'civicrm_grant_total_grants' => $value['title'],
520 'civicrm_grant_count' => $value['count'],
521 'civicrm_grant_amount' => $value['amount'],
522 );
523 }
524
525 if (!empty($grantStatistics)) {
526 foreach ($grantStatistics as $key => $value) {
527 $row[] = array(
528 'civicrm_grant_total_grants' => $value['title'],
529 'civicrm_grant_count' => ts('Number of Grants') . ' (%)',
530 'civicrm_grant_amount' => ts('Total Amount') . ' (%)',
531 );
532
533 foreach ($value['value'] as $field => $values) {
534 foreach ($values['currency'] as $currency => $amount) {
535 $totalAmount[$currency] = $currency . $amount['value'] . "({$values['percentage']}%)";
536 }
537 $totalAmt = implode(', ', $totalAmount);
538 $count = (boolean)CRM_Utils_Array::value('count', $values, 0) ? $values['count'] . " ({$values['percentage']}%)" : '';
539 $row[] = array(
540 'civicrm_grant_total_grants' => $field,
541 'civicrm_grant_count' => $count,
542 'civicrm_grant_amount' => $totalAmt,
543 );
544 }
545 }
546 }
547 $rows = $row;
548 }
549 }
550
74cf4551
EM
551 /**
552 * @param $grantStatistics
553 * @param $fieldValue
554 * @param $values
555 * @param $awardedGrants
556 * @param $awardedGrantsAmount
557 * @param bool $customData
558 */
6a488035
TO
559 static function getStatistics(&$grantStatistics, $fieldValue, $values,
560 $awardedGrants, $awardedGrantsAmount, $customData = FALSE
561 ) {
562 if (!$awardedGrantsAmount) {
563 return;
564 }
565
cba74230 566 $currencies = CRM_Core_PseudoConstant::get('CRM_Grant_DAO_Grant', 'currency', array('labelColumn' => 'symbol'));
6a488035
TO
567 $currency = $currencies[$values['civicrm_grant_currency']];
568
7bed22fc 569
6a488035 570 if (!$customData) {
74cf4551 571 if (!isset($grantStatistics['value'][$fieldValue]['currency'][$currency])
7bed22fc
PN
572 || !isset($grantStatistics['value'][$fieldValue]['currency'][$currency]['value'])) {
573 $grantStatistics['value'][$fieldValue]['currency'][$currency]['value'] = 0;
574 }
6a488035
TO
575 $grantStatistics['value'][$fieldValue]['currency'][$currency]['value'] += $values['civicrm_grant_amount_total'];
576 $grantStatistics['value'][$fieldValue]['currency'][$currency]['percentage'] = round(($grantStatistics['value'][$fieldValue]['currency'][$currency]['value'] / $awardedGrantsAmount) * 100);
7bed22fc
PN
577 if (!isset($grantStatistics['value'][$fieldValue]['count'])) {
578 $grantStatistics['value'][$fieldValue]['count'] = 0;
579 }
6a488035
TO
580 $grantStatistics['value'][$fieldValue]['count']++;
581 $grantStatistics['value'][$fieldValue]['percentage'] = round(($grantStatistics['value'][$fieldValue]['count'] / $awardedGrants) * 100);
582 }
583 else {
74cf4551 584 if (!isset($grantStatistics['value'][$fieldValue]['unassigned_currency'][$currency])
7bed22fc
PN
585 || !isset($grantStatistics['value'][$fieldValue]['unassigned_currency'][$currency]['value'])) {
586 $grantStatistics['value'][$fieldValue]['unassigned_currency'][$currency]['value'] = 0;
74cf4551 587 }
6a488035
TO
588 $grantStatistics['value'][$fieldValue]['unassigned_currency'][$currency]['value'] += $values['civicrm_grant_amount_total'];
589 $grantStatistics['value'][$fieldValue]['unassigned_currency'][$currency]['percentage'] = round(($grantStatistics['value'][$fieldValue]['unassigned_currency'][$currency]['value'] / $awardedGrantsAmount) * 100);
590 $grantStatistics['value'][$fieldValue]['unassigned_count']++;
591 $grantStatistics['value'][$fieldValue]['unassigned_percentage'] = round(($grantStatistics['value'][$fieldValue]['unassigned_count'] / $awardedGrants) * 100);
592 }
593 }
594}
595