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