Merge pull request #10171 from seamuslee001/CRM-20427
[civicrm-core.git] / CRM / Report / Form / Contribute / Summary.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
0f03f337 6 | Copyright CiviCRM LLC (c) 2004-2017 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
0f03f337 31 * @copyright CiviCRM LLC (c) 2004-2017
6a488035
TO
32 */
33class CRM_Report_Form_Contribute_Summary extends CRM_Report_Form {
34 protected $_addressField = FALSE;
35
36 protected $_charts = array(
37 '' => 'Tabular',
38 'barChart' => 'Bar Chart',
39 'pieChart' => 'Pie Chart',
40 );
41 protected $_customGroupExtends = array('Contribution');
f813f78e 42 protected $_customGroupGroupBy = TRUE;
6a488035
TO
43
44 public $_drilldownReport = array('contribute/detail' => 'Link to Detail Report');
45
35dd1d26 46 /**
47 * To what frequency group-by a date column
48 *
49 * @var array
50 */
51 protected $_groupByDateFreq = array(
52 'MONTH' => 'Month',
53 'YEARWEEK' => 'Week',
c5e4cf0e 54 'DATE' => 'Day',
35dd1d26 55 'QUARTER' => 'Quarter',
56 'YEAR' => 'Year',
57 'FISCALYEAR' => 'Fiscal Year',
58 );
59
43c1fa19 60 /**
61 * This report has been optimised for group filtering.
62 *
63 * CRM-19170
64 *
65 * @var bool
66 */
67 protected $groupFilterNotOptimised = FALSE;
68
74cf4551 69 /**
ae6f7290 70 * Class constructor.
74cf4551 71 */
00be9182 72 public function __construct() {
f813f78e 73
9d72cede
EM
74 // Check if CiviCampaign is a) enabled and b) has active campaigns
75 $config = CRM_Core_Config::singleton();
6a488035
TO
76 $campaignEnabled = in_array("CiviCampaign", $config->enableComponents);
77 if ($campaignEnabled) {
78 $getCampaigns = CRM_Campaign_BAO_Campaign::getPermissionedCampaigns(NULL, NULL, TRUE, FALSE, TRUE);
79 $this->activeCampaigns = $getCampaigns['campaigns'];
80 asort($this->activeCampaigns);
81 }
f813f78e 82
6a488035 83 $this->_columns = array(
a1a2a83d
TO
84 'civicrm_contact' => array(
85 'dao' => 'CRM_Contact_DAO_Contact',
3da9fd47 86 'fields' => array_merge(
87 $this->getBasicContactFields(),
88 array(
89 'sort_name' => array(
90 'title' => ts('Contact Name'),
91 'no_repeat' => TRUE,
ac58d438 92 ),
3da9fd47 93 )
94 ),
a1a2a83d
TO
95 'grouping' => 'contact-fields',
96 'group_bys' => array(
97 'id' => array('title' => ts('Contact ID')),
98 'sort_name' => array(
99 'title' => ts('Contact Name'),
6a488035
TO
100 ),
101 ),
a1a2a83d
TO
102 ),
103 'civicrm_email' => array(
104 'dao' => 'CRM_Core_DAO_Email',
105 'fields' => array(
106 'email' => array(
107 'title' => ts('Email'),
108 'no_repeat' => TRUE,
6a488035
TO
109 ),
110 ),
a1a2a83d
TO
111 'grouping' => 'contact-fields',
112 ),
1f76c4cd
E
113 'civicrm_line_item' => array(
114 'dao' => 'CRM_Price_DAO_LineItem',
115 ),
a1a2a83d
TO
116 'civicrm_phone' => array(
117 'dao' => 'CRM_Core_DAO_Phone',
118 'fields' => array(
119 'phone' => array(
120 'title' => ts('Phone'),
121 'no_repeat' => TRUE,
6a488035
TO
122 ),
123 ),
a1a2a83d
TO
124 'grouping' => 'contact-fields',
125 ),
126 'civicrm_financial_type' => array(
127 'dao' => 'CRM_Financial_DAO_FinancialType',
128 'fields' => array('financial_type' => NULL),
129 'grouping' => 'contri-fields',
130 'group_bys' => array(
131 'financial_type' => array('title' => ts('Financial Type')),
132 ),
133 ),
134 'civicrm_contribution' => array(
135 'dao' => 'CRM_Contribute_DAO_Contribution',
9d72cede 136 //'bao' => 'CRM_Contribute_BAO_Contribution',
a1a2a83d 137 'fields' => array(
3b654372 138 'contribution_status_id' => array(
8a347ca5
RO
139 'title' => ts('Contribution Status'),
140 ),
a1a2a83d
TO
141 'contribution_source' => array('title' => ts('Source')),
142 'currency' => array(
143 'required' => TRUE,
144 'no_display' => TRUE,
6a488035 145 ),
a1a2a83d
TO
146 'total_amount' => array(
147 'title' => ts('Contribution Amount Stats'),
148 'default' => TRUE,
149 'statistics' => array(
a1a2a83d 150 'count' => ts('Contributions'),
8a347ca5 151 'sum' => ts('Contribution Aggregate'),
a1a2a83d 152 'avg' => ts('Contribution Avg'),
9d72cede 153 ),
6a488035 154 ),
5afce5ad 155 'non_deductible_amount' => array(
156 'title' => ts('Non-deductible Amount'),
157 ),
a1a2a83d
TO
158 ),
159 'grouping' => 'contri-fields',
160 'filters' => array(
161 'receive_date' => array('operatorType' => CRM_Report_Form::OP_DATE),
162 'contribution_status_id' => array(
163 'title' => ts('Contribution Status'),
164 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
165 'options' => CRM_Contribute_PseudoConstant::contributionStatus(),
166 'default' => array(1),
167 'type' => CRM_Utils_Type::T_INT,
168 ),
169 'currency' => array(
fd6a6828 170 'title' => ts('Currency'),
a1a2a83d
TO
171 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
172 'options' => CRM_Core_OptionGroup::values('currencies_enabled'),
173 'default' => NULL,
174 'type' => CRM_Utils_Type::T_STRING,
175 ),
176 'financial_type_id' => array(
177 'title' => ts('Financial Type'),
178 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
803e39be 179 'options' => CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes(),
a1a2a83d
TO
180 'type' => CRM_Utils_Type::T_INT,
181 ),
182 'contribution_page_id' => array(
183 'title' => ts('Contribution Page'),
184 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
185 'options' => CRM_Contribute_PseudoConstant::contributionPage(),
186 'type' => CRM_Utils_Type::T_INT,
187 ),
188 'total_amount' => array(
189 'title' => ts('Contribution Amount'),
190 ),
5afce5ad 191 'non_deductible_amount' => array(
192 'title' => ts('Non-deductible Amount'),
193 ),
a1a2a83d
TO
194 'total_sum' => array(
195 'title' => ts('Contribution Aggregate'),
196 'type' => CRM_Report_Form::OP_INT,
197 'dbAlias' => 'civicrm_contribution_total_amount_sum',
198 'having' => TRUE,
199 ),
200 'total_count' => array(
201 'title' => ts('Contribution Count'),
202 'type' => CRM_Report_Form::OP_INT,
203 'dbAlias' => 'civicrm_contribution_total_amount_count',
204 'having' => TRUE,
205 ),
206 'total_avg' => array(
207 'title' => ts('Contribution Avg'),
208 'type' => CRM_Report_Form::OP_INT,
209 'dbAlias' => 'civicrm_contribution_total_amount_avg',
210 'having' => TRUE,
9b0380d9
DS
211 ),
212 ),
a1a2a83d
TO
213 'group_bys' => array(
214 'receive_date' => array(
215 'frequency' => TRUE,
216 'default' => TRUE,
217 'chart' => TRUE,
9b0380d9 218 ),
a1a2a83d 219 'contribution_source' => NULL,
8a347ca5
RO
220 'contribution_status_id' => array(
221 'title' => ts('Contribution Status'),
222 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
223 'options' => CRM_Contribute_PseudoConstant::contributionStatus(),
224 'default' => array(1),
225 'type' => CRM_Utils_Type::T_INT,
226 ),
a1a2a83d
TO
227 ),
228 ),
fa5fb88c
E
229 'civicrm_financial_trxn' => array(
230 'dao' => 'CRM_Financial_DAO_FinancialTrxn',
231 'fields' => array(
5e0343e8 232 'card_type_id' => array(
d72b084a 233 'title' => ts('Credit Card Type'),
5e0343e8 234 'dbAlias' => 'GROUP_CONCAT(financial_trxn_civireport.card_type_id SEPARATOR ",")',
fa5fb88c
E
235 ),
236 ),
237 'filters' => array(
5e0343e8 238 'card_type_id' => array(
fa5fb88c
E
239 'title' => ts('Credit Card Type'),
240 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
d72b084a 241 'options' => CRM_Financial_DAO_FinancialTrxn::buildOptions('card_type_id'),
fa5fb88c
E
242 'default' => NULL,
243 'type' => CRM_Utils_Type::T_STRING,
244 ),
245 ),
246 ),
433465bc
PN
247 'civicrm_batch' => array(
248 'dao' => 'CRM_Batch_DAO_EntityBatch',
249 'grouping' => 'contri-fields',
8d2ca6b8
E
250 'fields' => array(
251 'batch_id' => array(
252 'name' => 'batch_id',
253 'title' => ts('Batch Title'),
c76af7c4
E
254 'dbAlias' => 'GROUP_CONCAT(DISTINCT batch_civireport.batch_id
255 ORDER BY batch_civireport.batch_id SEPARATOR ",")',
8d2ca6b8
E
256 ),
257 ),
433465bc
PN
258 'filters' => array(
259 'batch_id' => array(
260 'title' => ts('Batch Title'),
261 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
262 'options' => CRM_Batch_BAO_Batch::getBatches(),
263 'type' => CRM_Utils_Type::T_INT,
264 ),
265 ),
8d2ca6b8 266 'group_bys' => array(
236e4b41 267 'batch_id' => array('title' => ts('Batch Title')),
8d2ca6b8 268 ),
433465bc 269 ),
a1a2a83d
TO
270 'civicrm_contribution_soft' => array(
271 'dao' => 'CRM_Contribute_DAO_ContributionSoft',
272 'fields' => array(
273 'soft_amount' => array(
274 'title' => ts('Soft Credit Amount Stats'),
275 'name' => 'amount',
276 'statistics' => array(
a1a2a83d 277 'count' => ts('Soft Credits'),
8a347ca5 278 'sum' => ts('Soft Credit Aggregate'),
a1a2a83d 279 'avg' => ts('Soft Credit Avg'),
9d72cede 280 ),
9b0380d9
DS
281 ),
282 ),
a1a2a83d
TO
283 'grouping' => 'contri-fields',
284 'filters' => array(
285 'amount' => array(
286 'title' => ts('Soft Credit Amount'),
287 ),
288 'soft_credit_type_id' => array(
fd6a6828 289 'title' => ts('Soft Credit Type'),
a1a2a83d
TO
290 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
291 'options' => CRM_Core_OptionGroup::values('soft_credit_type'),
292 'default' => NULL,
293 'type' => CRM_Utils_Type::T_STRING,
294 ),
295 'soft_sum' => array(
296 'title' => ts('Soft Credit Aggregate'),
297 'type' => CRM_Report_Form::OP_INT,
298 'dbAlias' => 'civicrm_contribution_soft_soft_amount_sum',
299 'having' => TRUE,
300 ),
301 'soft_count' => array(
302 'title' => ts('Soft Credits Count'),
303 'type' => CRM_Report_Form::OP_INT,
304 'dbAlias' => 'civicrm_contribution_soft_soft_amount_count',
305 'having' => TRUE,
306 ),
307 'soft_avg' => array(
308 'title' => ts('Soft Credit Avg'),
309 'type' => CRM_Report_Form::OP_INT,
310 'dbAlias' => 'civicrm_contribution_soft_soft_amount_avg',
311 'having' => TRUE,
312 ),
313 ),
314 ),
315 ) + $this->addAddressFields();
6a488035 316
a7dbbc5d 317 // If we have a campaign, build out the relevant elements
6a488035
TO
318 if ($campaignEnabled && !empty($this->activeCampaigns)) {
319 $this->_columns['civicrm_contribution']['fields']['campaign_id'] = array(
fd6a6828 320 'title' => ts('Campaign'),
6a488035
TO
321 'default' => 'false',
322 );
9d72cede
EM
323 $this->_columns['civicrm_contribution']['filters']['campaign_id'] = array(
324 'title' => ts('Campaign'),
09b5cdcf 325 'type' => CRM_Utils_Type::T_INT,
6a488035
TO
326 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
327 'options' => $this->activeCampaigns,
328 );
6a488035
TO
329 $this->_columns['civicrm_contribution']['group_bys']['campaign_id'] = array('title' => ts('Campaign'));
330 }
35d8497b 331
16e2e80c
CW
332 $this->_tagFilter = TRUE;
333 $this->_groupFilter = TRUE;
35d8497b 334 $this->_currencyColumn = 'civicrm_contribution_currency';
6a488035
TO
335 parent::__construct();
336 }
337
74cf4551 338 /**
ae6f7290 339 * Set select clause.
74cf4551 340 */
00be9182 341 public function select() {
6a488035
TO
342 $select = array();
343 $this->_columnHeaders = array();
344 foreach ($this->_columns as $tableName => $table) {
345 if (array_key_exists('group_bys', $table)) {
346 foreach ($table['group_bys'] as $fieldName => $field) {
347 if ($tableName == 'civicrm_address') {
348 $this->_addressField = TRUE;
349 }
a7488080 350 if (!empty($this->_params['group_bys'][$fieldName])) {
6a488035
TO
351 switch (CRM_Utils_Array::value($fieldName, $this->_params['group_bys_freq'])) {
352 case 'YEARWEEK':
9d72cede
EM
353 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
354 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
355 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
c5e4cf0e 356 $field['title'] = ts('Week Beginning');
6a488035
TO
357 break;
358
359 case 'YEAR':
9d72cede
EM
360 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
361 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
362 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
c5e4cf0e 363 $field['title'] = ts('Year Beginning');
6a488035
TO
364 break;
365
35dd1d26 366 case 'FISCALYEAR':
367 $config = CRM_Core_Config::singleton();
368 $fy = $config->fiscalYearStart;
369 $fiscal = self::fiscalYearOffset($field['dbAlias']);
370
371 $select[] = "DATE_ADD(MAKEDATE({$fiscal}, 1), INTERVAL ({$fy{'M'}})-1 MONTH) AS {$tableName}_{$fieldName}_start";
372 $select[] = "{$fiscal} AS {$tableName}_{$fieldName}_subtotal";
373 $select[] = "{$fiscal} AS {$tableName}_{$fieldName}_interval";
c5e4cf0e 374 $field['title'] = ts('Fiscal Year Beginning');
35dd1d26 375 break;
376
6a488035 377 case 'MONTH':
9d72cede
EM
378 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
379 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
380 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
c5e4cf0e 381 $field['title'] = ts('Month Beginning');
382 break;
383
384 case 'DATE':
385 $select[] = "DATE({$field['dbAlias']}) as {$tableName}_{$fieldName}_start";
386 $field['title'] = ts('Date');
6a488035
TO
387 break;
388
389 case 'QUARTER':
9d72cede
EM
390 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
391 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
392 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
6a488035
TO
393 $field['title'] = 'Quarter';
394 break;
395 }
a7488080 396 if (!empty($this->_params['group_bys_freq'][$fieldName])) {
891a34b4 397 $this->_interval = $this->_params['group_bys_freq'][$fieldName];
c5e4cf0e 398 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['title'] = $field['title'];
6a488035
TO
399 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
400 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params['group_bys_freq'][$fieldName];
401
b44e3f84 402 // just to make sure these values are transferred to rows.
6a488035
TO
403 // since we need that for calculation purpose,
404 // e.g making subtotals look nicer or graphs
405 $this->_columnHeaders["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
406 $this->_columnHeaders["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
407 }
408 }
409 }
410 }
411
412 if (array_key_exists('fields', $table)) {
413 foreach ($table['fields'] as $fieldName => $field) {
414 if ($tableName == 'civicrm_address') {
415 $this->_addressField = TRUE;
416 }
9d72cede
EM
417 if (!empty($field['required']) ||
418 !empty($this->_params['fields'][$fieldName])
419 ) {
6a488035 420 // only include statistics columns if set
a7488080 421 if (!empty($field['statistics'])) {
6a488035 422 foreach ($field['statistics'] as $stat => $label) {
030eb4f9 423 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
424 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
425 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
6a488035
TO
426 switch (strtolower($stat)) {
427 case 'sum':
428 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
6a488035
TO
429 break;
430
431 case 'count':
432 $select[] = "COUNT({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
433 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT;
6a488035
TO
434 break;
435
436 case 'avg':
437 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as {$tableName}_{$fieldName}_{$stat}";
6a488035
TO
438 break;
439 }
440 }
441 }
442 else {
443 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
444 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
445 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array::value('title', $field);
446 }
447 }
448 }
449 }
450 }
451
d1641c51 452 $this->_selectClauses = $select;
6a488035
TO
453 $this->_select = "SELECT " . implode(', ', $select) . " ";
454 }
455
74cf4551 456 /**
ae6f7290 457 * Set form rules.
458 *
459 * @param array $fields
460 * @param array $files
461 * @param CRM_Report_Form_Contribute_Summary $self
74cf4551
EM
462 *
463 * @return array
464 */
00be9182 465 public static function formRule($fields, $files, $self) {
ae6f7290 466 // Check for searching combination of display columns and
467 // grouping criteria
6a488035
TO
468 $ignoreFields = array('total_amount', 'sort_name');
469 $errors = $self->customDataFormRule($fields, $ignoreFields);
470
a7488080 471 if (empty($fields['fields']['total_amount'])) {
6a488035 472 foreach (array(
9d72cede
EM
473 'total_count_value',
474 'total_sum_value',
21dfd5f5 475 'total_avg_value',
9d72cede 476 ) as $val) {
a7488080 477 if (!empty($fields[$val])) {
6a488035
TO
478 $errors[$val] = ts("Please select the Amount Statistics");
479 }
480 }
481 }
482
483 return $errors;
484 }
485
ae6f7290 486 /**
487 * Set from clause.
488 *
489 * @param string $entity
73b448bf 490 *
491 * @todo fix function signature to match parent. Remove hacky passing of $entity
492 * to acheive unclear results.
ae6f7290 493 */
030eb4f9 494 public function from($entity = NULL) {
495 $softCreditJoinType = "LEFT";
9d72cede
EM
496 if (!empty($this->_params['fields']['soft_amount']) &&
497 empty($this->_params['fields']['total_amount'])
498 ) {
9b0380d9 499 // if its only soft credit stats, use inner join
030eb4f9 500 $softCreditJoinType = "INNER";
501 }
502
503 $softCreditJoin = "{$softCreditJoinType} JOIN civicrm_contribution_soft {$this->_aliases['civicrm_contribution_soft']}
504 ON {$this->_aliases['civicrm_contribution_soft']}.contribution_id = {$this->_aliases['civicrm_contribution']}.id";
505 if ($entity == 'contribution' || empty($this->_params['fields']['soft_amount'])) {
506 $softCreditJoin .= " AND {$this->_aliases['civicrm_contribution_soft']}.id = (SELECT MIN(id) FROM civicrm_contribution_soft cs WHERE cs.contribution_id = {$this->_aliases['civicrm_contribution']}.id) ";
9b0380d9
DS
507 }
508
43c1fa19 509 $this->setFromBase('civicrm_contact');
510
511 $this->_from .= "
f813f78e 512 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
6a488035
TO
513 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND
514 {$this->_aliases['civicrm_contribution']}.is_test = 0
030eb4f9 515 {$softCreditJoin}
f813f78e 516 LEFT JOIN civicrm_financial_type {$this->_aliases['civicrm_financial_type']}
6a488035 517 ON {$this->_aliases['civicrm_contribution']}.financial_type_id ={$this->_aliases['civicrm_financial_type']}.id
f813f78e 518 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
519 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
520 {$this->_aliases['civicrm_email']}.is_primary = 1)
521
522 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
523 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
6a488035
TO
524 {$this->_aliases['civicrm_phone']}.is_primary = 1)";
525
8b7f2513 526 $this->addAddressFromClause();
8d2ca6b8
E
527 //for contribution batches
528 if ($this->isTableSelected('civicrm_batch')) {
433465bc 529 $this->_from .= "
8d2ca6b8
E
530 LEFT JOIN civicrm_entity_financial_trxn eft
531 ON eft.entity_id = {$this->_aliases['civicrm_contribution']}.id AND
532 eft.entity_table = 'civicrm_contribution'
533 LEFT JOIN civicrm_entity_batch {$this->_aliases['civicrm_batch']}
534 ON ({$this->_aliases['civicrm_batch']}.entity_id = eft.financial_trxn_id
535 AND {$this->_aliases['civicrm_batch']}.entity_table = 'civicrm_financial_trxn')";
433465bc 536 }
fa5fb88c
E
537
538 // for credit card type
539 if ($this->isTableSelected('civicrm_financial_trxn')) {
ea00b887
E
540 $this->_from .= "
541 LEFT JOIN civicrm_entity_financial_trxn eftcc
542 ON ({$this->_aliases['civicrm_contribution']}.id = eftcc.entity_id AND
543 eftcc.entity_table = 'civicrm_contribution')
544 LEFT JOIN civicrm_financial_trxn {$this->_aliases['civicrm_financial_trxn']}
545 ON {$this->_aliases['civicrm_financial_trxn']}.id = eftcc.financial_trxn_id";
fa5fb88c 546 }
6a488035
TO
547 }
548
ae6f7290 549 /**
550 * Set group by clause.
551 */
00be9182 552 public function groupBy() {
6a488035
TO
553 $this->_groupBy = "";
554 $append = FALSE;
34c3a72b 555 if (!empty($this->_params['group_bys']) &&
556 is_array($this->_params['group_bys'])
6a488035
TO
557 ) {
558 foreach ($this->_columns as $tableName => $table) {
559 if (array_key_exists('group_bys', $table)) {
560 foreach ($table['group_bys'] as $fieldName => $field) {
a7488080
CW
561 if (!empty($this->_params['group_bys'][$fieldName])) {
562 if (!empty($field['chart'])) {
6a488035
TO
563 $this->assign('chartSupported', TRUE);
564 }
565
9d72cede
EM
566 if (!empty($table['group_bys'][$fieldName]['frequency']) &&
567 !empty($this->_params['group_bys_freq'][$fieldName])
568 ) {
6a488035 569
bad98dd5 570 $append = "YEAR({$field['dbAlias']});;";
6a488035 571 if (in_array(strtolower($this->_params['group_bys_freq'][$fieldName]),
9d72cede
EM
572 array('year')
573 )) {
6a488035
TO
574 $append = '';
575 }
35dd1d26 576 if ($this->_params['group_bys_freq'][$fieldName] == 'FISCALYEAR') {
577 $this->_groupBy[] = self::fiscalYearOffset($field['dbAlias']);
578 }
579 else {
580 $this->_groupBy[] = "$append {$this->_params['group_bys_freq'][$fieldName]}({$field['dbAlias']})";
581 }
6a488035
TO
582 $append = TRUE;
583 }
584 else {
585 $this->_groupBy[] = $field['dbAlias'];
586 }
587 }
588 }
589 }
590 }
591
592 if (!empty($this->_statFields) &&
9d72cede
EM
593 (($append && count($this->_groupBy) <= 1) || (!$append)) &&
594 !$this->_having
6a488035
TO
595 ) {
596 $this->_rollup = " WITH ROLLUP";
597 }
bad98dd5 598 $groupBy = array();
599 foreach ($this->_groupBy as $key => $val) {
dc852c7b 600 if (strpos($val, ';;') !== FALSE) {
bad98dd5 601 $groupBy = array_merge($groupBy, explode(';;', $val));
602 }
603 else {
604 $groupBy[] = $this->_groupBy[$key];
605 }
606 }
607 $this->_groupBy = "GROUP BY " . implode(', ', $groupBy);
6a488035
TO
608 }
609 else {
d1641c51 610 $groupBy = "{$this->_aliases['civicrm_contact']}.id";
6a488035
TO
611 $this->_groupBy = "GROUP BY {$this->_aliases['civicrm_contact']}.id";
612 }
d1641c51 613 $this->_groupBy .= $this->_rollup;
bad98dd5 614 // append select with ANY_VALUE() keyword
36d2f4d5 615 $this->_select = CRM_Contact_BAO_Query::appendAnyValueToSelect($this->_selectClauses, $groupBy);
6a488035
TO
616 }
617
ae6f7290 618 /**
619 * Store having clauses as an array.
620 */
00be9182 621 public function storeWhereHavingClauseArray() {
51fa20cb 622 parent::storeWhereHavingClauseArray();
9d72cede
EM
623 if (empty($this->_params['fields']['soft_amount']) &&
624 !empty($this->_havingClauses)
625 ) {
51fa20cb 626 foreach ($this->_havingClauses as $key => $havingClause) {
9d72cede 627 if (stristr($havingClause, 'soft_soft')) {
51fa20cb 628 unset($this->_havingClauses[$key]);
629 }
630 }
0d668154 631 }
51fa20cb 632 }
633
74cf4551 634 /**
ae6f7290 635 * Set statistics.
636 *
637 * @param array $rows
74cf4551
EM
638 *
639 * @return array
640 */
00be9182 641 public function statistics(&$rows) {
6a488035
TO
642 $statistics = parent::statistics($rows);
643
9b0380d9 644 $softCredit = CRM_Utils_Array::value('soft_amount', $this->_params['fields']);
ae6f7290 645 $onlySoftCredit = $softCredit && !CRM_Utils_Array::value('total_amount', $this->_params['fields']);
030eb4f9 646 $group = "\nGROUP BY {$this->_aliases['civicrm_contribution']}.currency";
35d8497b 647
030eb4f9 648 $this->from('contribution');
c90bacf9 649 $this->customDataFrom();
6dd5c484 650
c5b8382f 651 $contriQuery = "
9b0380d9
DS
652COUNT({$this->_aliases['civicrm_contribution']}.total_amount ) as civicrm_contribution_total_amount_count,
653SUM({$this->_aliases['civicrm_contribution']}.total_amount ) as civicrm_contribution_total_amount_sum,
654ROUND(AVG({$this->_aliases['civicrm_contribution']}.total_amount), 2) as civicrm_contribution_total_amount_avg,
030eb4f9 655{$this->_aliases['civicrm_contribution']}.currency as currency
35dd1d26 656{$this->_from} {$this->_where}";
9b0380d9
DS
657
658 if ($softCredit) {
030eb4f9 659 $this->from();
3b413375 660 $select = "
9b0380d9
DS
661COUNT({$this->_aliases['civicrm_contribution_soft']}.amount ) as civicrm_contribution_soft_soft_amount_count,
662SUM({$this->_aliases['civicrm_contribution_soft']}.amount ) as civicrm_contribution_soft_soft_amount_sum,
3b413375 663ROUND(AVG({$this->_aliases['civicrm_contribution_soft']}.amount), 2) as civicrm_contribution_soft_soft_amount_avg";
664 $contriQuery = "{$select}, {$contriQuery}";
665 $softSQL = "SELECT {$select}, {$this->_aliases['civicrm_contribution']}.currency as currency
666 {$this->_from} {$this->_where} {$group} {$this->_having}";
9b0380d9 667 }
c93f6d83 668
35dd1d26 669 $contriSQL = "SELECT {$contriQuery} {$group} {$this->_having}";
030eb4f9 670 $contriDAO = CRM_Core_DAO::executeQuery($contriSQL);
671
35dd1d26 672 $totalAmount = $average = $mode = $median = $softTotalAmount = $softAverage = array();
ae6884ce 673 $count = $softCount = 0;
030eb4f9 674 while ($contriDAO->fetch()) {
6c552737 675 $totalAmount[]
030eb4f9 676 = CRM_Utils_Money::format($contriDAO->civicrm_contribution_total_amount_sum, $contriDAO->currency) .
677 " (" . $contriDAO->civicrm_contribution_total_amount_count . ")";
678 $average[] = CRM_Utils_Money::format($contriDAO->civicrm_contribution_total_amount_avg, $contriDAO->currency);
679 $count += $contriDAO->civicrm_contribution_total_amount_count;
680 }
c93f6d83 681
35dd1d26 682 $groupBy = "\n{$group}, {$this->_aliases['civicrm_contribution']}.total_amount";
683 $orderBy = "\nORDER BY civicrm_contribution_total_amount_count DESC";
d1641c51 684 $modeSQL = "SELECT MAX(civicrm_contribution_total_amount_count) as civicrm_contribution_total_amount_count,
685 SUBSTRING_INDEX(GROUP_CONCAT(amount ORDER BY mode.civicrm_contribution_total_amount_count DESC SEPARATOR ';'), ';', 1) as amount,
686 currency
687 FROM (SELECT {$this->_aliases['civicrm_contribution']}.total_amount as amount,
35dd1d26 688 {$contriQuery} {$groupBy} {$orderBy}) as mode GROUP BY currency";
689
ae6884ce 690 $mode = CRM_Contribute_BAO_Contribution::computeStats('mode', $modeSQL);
35dd1d26 691
ae6884ce 692 $medianSQL = "{$this->_from} {$this->_where}";
693 $median = CRM_Contribute_BAO_Contribution::computeStats('median', $medianSQL, $this->_aliases['civicrm_contribution']);
35dd1d26 694
030eb4f9 695 if ($softCredit) {
696 $softDAO = CRM_Core_DAO::executeQuery($softSQL);
697 while ($softDAO->fetch()) {
6c552737 698 $softTotalAmount[]
030eb4f9 699 = CRM_Utils_Money::format($softDAO->civicrm_contribution_soft_soft_amount_sum, $softDAO->currency) .
700 " (" . $softDAO->civicrm_contribution_soft_soft_amount_count . ")";
701 $softAverage[] = CRM_Utils_Money::format($softDAO->civicrm_contribution_soft_soft_amount_avg, $softDAO->currency);
702 $softCount += $softDAO->civicrm_contribution_soft_soft_amount_count;
9b0380d9
DS
703 }
704 }
c93f6d83 705
9b0380d9 706 if (!$onlySoftCredit) {
35d8497b 707 $statistics['counts']['amount'] = array(
708 'title' => ts('Total Amount'),
709 'value' => implode(', ', $totalAmount),
710 'type' => CRM_Utils_Type::T_STRING,
711 );
712 $statistics['counts']['count'] = array(
be205937 713 'title' => ts('Total Contributions'),
35d8497b 714 'value' => $count,
715 );
716 $statistics['counts']['avg'] = array(
717 'title' => ts('Average'),
718 'value' => implode(', ', $average),
719 'type' => CRM_Utils_Type::T_STRING,
720 );
35dd1d26 721 $statistics['counts']['mode'] = array(
722 'title' => ts('Mode'),
723 'value' => implode(', ', $mode),
724 'type' => CRM_Utils_Type::T_STRING,
725 );
726 $statistics['counts']['median'] = array(
727 'title' => ts('Median'),
728 'value' => implode(', ', $median),
729 'type' => CRM_Utils_Type::T_STRING,
730 );
9b0380d9
DS
731 }
732 if ($softCredit) {
733 $statistics['counts']['soft_amount'] = array(
734 'title' => ts('Total Soft Credit Amount'),
735 'value' => implode(', ', $softTotalAmount),
736 'type' => CRM_Utils_Type::T_STRING,
737 );
738 $statistics['counts']['soft_count'] = array(
739 'title' => ts('Total Soft Credits'),
740 'value' => $softCount,
741 );
742 $statistics['counts']['soft_avg'] = array(
743 'title' => ts('Average Soft Credit'),
744 'value' => implode(', ', $softAverage),
745 'type' => CRM_Utils_Type::T_STRING,
746 );
6a488035
TO
747 }
748 return $statistics;
749 }
750
ae6f7290 751 /**
752 * Post process function.
753 */
00be9182 754 public function postProcess() {
0c00c2f2 755 $this->buildACLClause($this->_aliases['civicrm_contact']);
6a488035
TO
756 parent::postProcess();
757 }
758
ae6f7290 759 /**
760 * Build table rows for output.
761 *
762 * @param string $sql
763 * @param array $rows
764 */
030eb4f9 765 public function buildRows($sql, &$rows) {
766 $dao = CRM_Core_DAO::executeQuery($sql);
767 if (!is_array($rows)) {
768 $rows = array();
769 }
770
771 // use this method to modify $this->_columnHeaders
772 $this->modifyColumnHeaders();
ae6f7290 773 $contriRows = array();
030eb4f9 774 $unselectedSectionColumns = $this->unselectedSectionColumns();
775
776 //CRM-16338 if both soft-credit and contribution are enabled then process the contribution's
777 //total amount's average, count and sum separately and add it to the respective result list
778 $softCredit = (!empty($this->_params['fields']['soft_amount']) && !empty($this->_params['fields']['total_amount'])) ? TRUE : FALSE;
779 if ($softCredit) {
780 $this->from('contribution');
781 $contriSQL = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
782 $contriDAO = CRM_Core_DAO::executeQuery($contriSQL);
783 $contriFields = array(
784 'civicrm_contribution_total_amount_sum',
785 'civicrm_contribution_total_amount_avg',
786 'civicrm_contribution_total_amount_count');
787 $contriRows = array();
788 while ($contriDAO->fetch()) {
789 $contriRow = array();
790 foreach ($contriFields as $column) {
791 $contriRow[$column] = $contriDAO->$column;
792 }
793 $contriRows[] = $contriRow;
794 }
795 }
796
797 $count = 0;
798 while ($dao->fetch()) {
799 $row = array();
800 foreach ($this->_columnHeaders as $key => $value) {
801 if ($softCredit && array_key_exists($key, $contriRows[$count])) {
802 $row[$key] = $contriRows[$count][$key];
803 }
804 elseif (property_exists($dao, $key)) {
805 $row[$key] = $dao->$key;
806 }
807 }
808
809 // section headers not selected for display need to be added to row
810 foreach ($unselectedSectionColumns as $key => $values) {
811 if (property_exists($dao, $key)) {
812 $row[$key] = $dao->$key;
813 }
814 }
815
816 $count++;
817 $rows[] = $row;
818 }
819
820 }
821
74cf4551 822 /**
ae6f7290 823 * Build chart.
824 *
825 * @param array $rows
74cf4551 826 */
00be9182 827 public function buildChart(&$rows) {
6a488035 828 $graphRows = array();
6a488035 829
a7488080
CW
830 if (!empty($this->_params['charts'])) {
831 if (!empty($this->_params['group_bys']['receive_date'])) {
0c98098b 832
0d8afee2
CW
833 $contrib = !empty($this->_params['fields']['total_amount']) ? TRUE : FALSE;
834 $softContrib = !empty($this->_params['fields']['soft_amount']) ? TRUE : FALSE;
0c98098b
DS
835
836 foreach ($rows as $key => $row) {
837 if ($row['civicrm_contribution_receive_date_subtotal']) {
838 $graphRows['receive_date'][] = $row['civicrm_contribution_receive_date_start'];
839 $graphRows[$this->_interval][] = $row['civicrm_contribution_receive_date_interval'];
840 if ($softContrib && $contrib) {
841 // both contri & soft contri stats are present
842 $graphRows['multiValue'][0][] = $row['civicrm_contribution_total_amount_sum'];
843 $graphRows['multiValue'][1][] = $row['civicrm_contribution_soft_soft_amount_sum'];
9d72cede 844 }
4c9b6178 845 elseif ($softContrib) {
0c98098b
DS
846 // only soft contributions
847 $graphRows['multiValue'][0][] = $row['civicrm_contribution_soft_soft_amount_sum'];
9d72cede
EM
848 }
849 else {
0c98098b
DS
850 // only contributions
851 $graphRows['multiValue'][0][] = $row['civicrm_contribution_total_amount_sum'];
852 }
853 }
6a488035 854 }
6a488035 855
0c98098b
DS
856 if ($softContrib && $contrib) {
857 $graphRows['barKeys'][0] = ts('Contributions');
858 $graphRows['barKeys'][1] = ts('Soft Credits');
859 $graphRows['legend'] = ts('Contributions and Soft Credits');
9d72cede 860 }
4c9b6178 861 elseif ($softContrib) {
0c98098b
DS
862 $graphRows['legend'] = ts('Soft Credits');
863 }
6a488035
TO
864
865 // build the chart.
9d72cede 866 $config = CRM_Core_Config::Singleton();
6a488035
TO
867 $graphRows['xname'] = $this->_interval;
868 $graphRows['yname'] = "Amount ({$config->defaultCurrency})";
869 CRM_Utils_OpenFlashChart::chart($graphRows, $this->_params['charts'], $this->_interval);
870 $this->assign('chartType', $this->_params['charts']);
871 }
872 }
873 }
874
74cf4551 875 /**
ced9bfed
EM
876 * Alter display of rows.
877 *
878 * Iterate through the rows retrieved via SQL and make changes for display purposes,
879 * such as rendering contacts as links.
880 *
881 * @param array $rows
882 * Rows generated by SQL, with an array for each row.
74cf4551 883 */
00be9182 884 public function alterDisplay(&$rows) {
6a488035 885 $entryFound = FALSE;
8a347ca5 886 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
6a488035
TO
887
888 foreach ($rows as $rowNum => $row) {
889 // make count columns point to detail report
9d72cede
EM
890 if (!empty($this->_params['group_bys']['receive_date']) &&
891 !empty($row['civicrm_contribution_receive_date_start']) &&
892 CRM_Utils_Array::value('civicrm_contribution_receive_date_start', $row) &&
893 !empty($row['civicrm_contribution_receive_date_subtotal'])
894 ) {
6a488035
TO
895
896 $dateStart = CRM_Utils_Date::customFormat($row['civicrm_contribution_receive_date_start'], '%Y%m%d');
9d72cede
EM
897 $endDate = new DateTime($dateStart);
898 $dateEnd = array();
6a488035
TO
899
900 list($dateEnd['Y'], $dateEnd['M'], $dateEnd['d']) = explode(':', $endDate->format('Y:m:d'));
901
902 switch (strtolower($this->_params['group_bys_freq']['receive_date'])) {
903 case 'month':
904 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] + 1,
9d72cede
EM
905 $dateEnd['d'] - 1, $dateEnd['Y']
906 ));
6a488035
TO
907 break;
908
909 case 'year':
910 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
9d72cede
EM
911 $dateEnd['d'] - 1, $dateEnd['Y'] + 1
912 ));
6a488035
TO
913 break;
914
35dd1d26 915 case 'fiscalyear':
916 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
917 $dateEnd['d'] - 1, $dateEnd['Y'] + 1
918 ));
919 break;
920
6a488035
TO
921 case 'yearweek':
922 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
9d72cede
EM
923 $dateEnd['d'] + 6, $dateEnd['Y']
924 ));
6a488035
TO
925 break;
926
927 case 'quarter':
928 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] + 3,
9d72cede
EM
929 $dateEnd['d'] - 1, $dateEnd['Y']
930 ));
6a488035
TO
931 break;
932 }
933 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
9d72cede
EM
934 "reset=1&force=1&receive_date_from={$dateStart}&receive_date_to={$dateEnd}",
935 $this->_absoluteUrl,
936 $this->_id,
937 $this->_drilldownReport
938 );
6a488035
TO
939 $rows[$rowNum]['civicrm_contribution_receive_date_start_link'] = $url;
940 $rows[$rowNum]['civicrm_contribution_receive_date_start_hover'] = ts('List all contribution(s) for this date unit.');
941 $entryFound = TRUE;
942 }
943
944 // make subtotals look nicer
945 if (array_key_exists('civicrm_contribution_receive_date_subtotal', $row) &&
946 !$row['civicrm_contribution_receive_date_subtotal']
947 ) {
948 $this->fixSubTotalDisplay($rows[$rowNum], $this->_statFields);
949 $entryFound = TRUE;
950 }
951
952 // convert display name to links
953 if (array_key_exists('civicrm_contact_sort_name', $row) &&
954 array_key_exists('civicrm_contact_id', $row)
955 ) {
956 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
957 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'],
958 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
959 );
960 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
961 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("Lists detailed contribution(s) for this record.");
962 $entryFound = TRUE;
963 }
964
8a347ca5
RO
965 // convert contribution status id to status name
966 if ($value = CRM_Utils_Array::value('civicrm_contribution_contribution_status_id', $row)) {
967 $rows[$rowNum]['civicrm_contribution_contribution_status_id'] = $contributionStatus[$value];
968 $entryFound = TRUE;
969 }
970
5e0343e8 971 if (!empty($row['civicrm_financial_trxn_card_type_id'])) {
972 $rows[$rowNum]['civicrm_financial_trxn_card_type_id'] = $this->getLabels($row['civicrm_financial_trxn_card_type_id'], 'CRM_Financial_DAO_FinancialTrxn', 'card_type_id');
fa5fb88c
E
973 $entryFound = TRUE;
974 }
975
a7dbbc5d 976 // If using campaigns, convert campaign_id to campaign title
6a488035
TO
977 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
978 if ($value = $row['civicrm_contribution_campaign_id']) {
979 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns[$value];
980 }
981 $entryFound = TRUE;
982 }
2ebf49a4 983
8d2ca6b8 984 // convert batch id to batch title
c76af7c4
E
985 if (!empty($row['civicrm_batch_batch_id']) && !in_array('Subtotal', $rows[$rowNum])) {
986 $rows[$rowNum]['civicrm_batch_batch_id'] = $this->getLabels($row['civicrm_batch_batch_id'], 'CRM_Batch_BAO_EntityBatch', 'batch_id');
8d2ca6b8
E
987 $entryFound = TRUE;
988 }
989
6a488035 990 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s) for this ') ? TRUE : $entryFound;
7a4192f7 991 $entryFound = $this->alterDisplayContactFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s) for this ') ? TRUE : $entryFound;
6a488035 992
6a488035
TO
993 // skip looking further in rows, if first row itself doesn't
994 // have the column we need
995 if (!$entryFound) {
996 break;
997 }
998 }
999 }
96025800 1000
6a488035 1001}