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