Merge pull request #9159 from liedekef/patch-1
[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 +--------------------------------------------------------------------+
fa938177 6 | Copyright CiviCRM LLC (c) 2004-2016 |
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
fa938177 31 * @copyright CiviCRM LLC (c) 2004-2016
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 ),
433465bc
PN
229 'civicrm_batch' => array(
230 'dao' => 'CRM_Batch_DAO_EntityBatch',
231 'grouping' => 'contri-fields',
232 'filters' => array(
233 'batch_id' => array(
234 'title' => ts('Batch Title'),
235 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
236 'options' => CRM_Batch_BAO_Batch::getBatches(),
237 'type' => CRM_Utils_Type::T_INT,
238 ),
239 ),
240 ),
a1a2a83d
TO
241 'civicrm_contribution_soft' => array(
242 'dao' => 'CRM_Contribute_DAO_ContributionSoft',
243 'fields' => array(
244 'soft_amount' => array(
245 'title' => ts('Soft Credit Amount Stats'),
246 'name' => 'amount',
247 'statistics' => array(
a1a2a83d 248 'count' => ts('Soft Credits'),
8a347ca5 249 'sum' => ts('Soft Credit Aggregate'),
a1a2a83d 250 'avg' => ts('Soft Credit Avg'),
9d72cede 251 ),
9b0380d9
DS
252 ),
253 ),
a1a2a83d
TO
254 'grouping' => 'contri-fields',
255 'filters' => array(
256 'amount' => array(
257 'title' => ts('Soft Credit Amount'),
258 ),
259 'soft_credit_type_id' => array(
fd6a6828 260 'title' => ts('Soft Credit Type'),
a1a2a83d
TO
261 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
262 'options' => CRM_Core_OptionGroup::values('soft_credit_type'),
263 'default' => NULL,
264 'type' => CRM_Utils_Type::T_STRING,
265 ),
266 'soft_sum' => array(
267 'title' => ts('Soft Credit Aggregate'),
268 'type' => CRM_Report_Form::OP_INT,
269 'dbAlias' => 'civicrm_contribution_soft_soft_amount_sum',
270 'having' => TRUE,
271 ),
272 'soft_count' => array(
273 'title' => ts('Soft Credits Count'),
274 'type' => CRM_Report_Form::OP_INT,
275 'dbAlias' => 'civicrm_contribution_soft_soft_amount_count',
276 'having' => TRUE,
277 ),
278 'soft_avg' => array(
279 'title' => ts('Soft Credit Avg'),
280 'type' => CRM_Report_Form::OP_INT,
281 'dbAlias' => 'civicrm_contribution_soft_soft_amount_avg',
282 'having' => TRUE,
283 ),
284 ),
285 ),
286 ) + $this->addAddressFields();
6a488035 287
a7dbbc5d 288 // If we have a campaign, build out the relevant elements
6a488035
TO
289 if ($campaignEnabled && !empty($this->activeCampaigns)) {
290 $this->_columns['civicrm_contribution']['fields']['campaign_id'] = array(
fd6a6828 291 'title' => ts('Campaign'),
6a488035
TO
292 'default' => 'false',
293 );
9d72cede
EM
294 $this->_columns['civicrm_contribution']['filters']['campaign_id'] = array(
295 'title' => ts('Campaign'),
09b5cdcf 296 'type' => CRM_Utils_Type::T_INT,
6a488035
TO
297 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
298 'options' => $this->activeCampaigns,
299 );
6a488035
TO
300 $this->_columns['civicrm_contribution']['group_bys']['campaign_id'] = array('title' => ts('Campaign'));
301 }
35d8497b 302
16e2e80c
CW
303 $this->_tagFilter = TRUE;
304 $this->_groupFilter = TRUE;
35d8497b 305 $this->_currencyColumn = 'civicrm_contribution_currency';
6a488035
TO
306 parent::__construct();
307 }
308
74cf4551 309 /**
ae6f7290 310 * Set select clause.
74cf4551 311 */
00be9182 312 public function select() {
6a488035
TO
313 $select = array();
314 $this->_columnHeaders = array();
315 foreach ($this->_columns as $tableName => $table) {
316 if (array_key_exists('group_bys', $table)) {
317 foreach ($table['group_bys'] as $fieldName => $field) {
318 if ($tableName == 'civicrm_address') {
319 $this->_addressField = TRUE;
320 }
a7488080 321 if (!empty($this->_params['group_bys'][$fieldName])) {
6a488035
TO
322 switch (CRM_Utils_Array::value($fieldName, $this->_params['group_bys_freq'])) {
323 case 'YEARWEEK':
9d72cede
EM
324 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
325 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
326 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
c5e4cf0e 327 $field['title'] = ts('Week Beginning');
6a488035
TO
328 break;
329
330 case 'YEAR':
9d72cede
EM
331 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
332 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
333 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
c5e4cf0e 334 $field['title'] = ts('Year Beginning');
6a488035
TO
335 break;
336
35dd1d26 337 case 'FISCALYEAR':
338 $config = CRM_Core_Config::singleton();
339 $fy = $config->fiscalYearStart;
340 $fiscal = self::fiscalYearOffset($field['dbAlias']);
341
342 $select[] = "DATE_ADD(MAKEDATE({$fiscal}, 1), INTERVAL ({$fy{'M'}})-1 MONTH) AS {$tableName}_{$fieldName}_start";
343 $select[] = "{$fiscal} AS {$tableName}_{$fieldName}_subtotal";
344 $select[] = "{$fiscal} AS {$tableName}_{$fieldName}_interval";
c5e4cf0e 345 $field['title'] = ts('Fiscal Year Beginning');
35dd1d26 346 break;
347
6a488035 348 case 'MONTH':
9d72cede
EM
349 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
350 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
351 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
c5e4cf0e 352 $field['title'] = ts('Month Beginning');
353 break;
354
355 case 'DATE':
356 $select[] = "DATE({$field['dbAlias']}) as {$tableName}_{$fieldName}_start";
357 $field['title'] = ts('Date');
6a488035
TO
358 break;
359
360 case 'QUARTER':
9d72cede
EM
361 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
362 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
363 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
6a488035
TO
364 $field['title'] = 'Quarter';
365 break;
366 }
a7488080 367 if (!empty($this->_params['group_bys_freq'][$fieldName])) {
891a34b4 368 $this->_interval = $this->_params['group_bys_freq'][$fieldName];
c5e4cf0e 369 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['title'] = $field['title'];
6a488035
TO
370 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
371 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params['group_bys_freq'][$fieldName];
372
b44e3f84 373 // just to make sure these values are transferred to rows.
6a488035
TO
374 // since we need that for calculation purpose,
375 // e.g making subtotals look nicer or graphs
376 $this->_columnHeaders["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
377 $this->_columnHeaders["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
378 }
379 }
380 }
381 }
382
383 if (array_key_exists('fields', $table)) {
384 foreach ($table['fields'] as $fieldName => $field) {
385 if ($tableName == 'civicrm_address') {
386 $this->_addressField = TRUE;
387 }
9d72cede
EM
388 if (!empty($field['required']) ||
389 !empty($this->_params['fields'][$fieldName])
390 ) {
6a488035 391 // only include statistics columns if set
a7488080 392 if (!empty($field['statistics'])) {
6a488035 393 foreach ($field['statistics'] as $stat => $label) {
030eb4f9 394 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
395 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
396 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
6a488035
TO
397 switch (strtolower($stat)) {
398 case 'sum':
399 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
6a488035
TO
400 break;
401
402 case 'count':
403 $select[] = "COUNT({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
404 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT;
6a488035
TO
405 break;
406
407 case 'avg':
408 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as {$tableName}_{$fieldName}_{$stat}";
6a488035
TO
409 break;
410 }
411 }
412 }
413 else {
414 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
415 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
416 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array::value('title', $field);
417 }
418 }
419 }
420 }
421 }
422
d1641c51 423 $this->_selectClauses = $select;
6a488035
TO
424 $this->_select = "SELECT " . implode(', ', $select) . " ";
425 }
426
74cf4551 427 /**
ae6f7290 428 * Set form rules.
429 *
430 * @param array $fields
431 * @param array $files
432 * @param CRM_Report_Form_Contribute_Summary $self
74cf4551
EM
433 *
434 * @return array
435 */
00be9182 436 public static function formRule($fields, $files, $self) {
ae6f7290 437 // Check for searching combination of display columns and
438 // grouping criteria
6a488035
TO
439 $ignoreFields = array('total_amount', 'sort_name');
440 $errors = $self->customDataFormRule($fields, $ignoreFields);
441
a7488080 442 if (empty($fields['fields']['total_amount'])) {
6a488035 443 foreach (array(
9d72cede
EM
444 'total_count_value',
445 'total_sum_value',
21dfd5f5 446 'total_avg_value',
9d72cede 447 ) as $val) {
a7488080 448 if (!empty($fields[$val])) {
6a488035
TO
449 $errors[$val] = ts("Please select the Amount Statistics");
450 }
451 }
452 }
453
454 return $errors;
455 }
456
ae6f7290 457 /**
458 * Set from clause.
459 *
460 * @param string $entity
73b448bf 461 *
462 * @todo fix function signature to match parent. Remove hacky passing of $entity
463 * to acheive unclear results.
ae6f7290 464 */
030eb4f9 465 public function from($entity = NULL) {
466 $softCreditJoinType = "LEFT";
9d72cede
EM
467 if (!empty($this->_params['fields']['soft_amount']) &&
468 empty($this->_params['fields']['total_amount'])
469 ) {
9b0380d9 470 // if its only soft credit stats, use inner join
030eb4f9 471 $softCreditJoinType = "INNER";
472 }
473
474 $softCreditJoin = "{$softCreditJoinType} JOIN civicrm_contribution_soft {$this->_aliases['civicrm_contribution_soft']}
475 ON {$this->_aliases['civicrm_contribution_soft']}.contribution_id = {$this->_aliases['civicrm_contribution']}.id";
476 if ($entity == 'contribution' || empty($this->_params['fields']['soft_amount'])) {
477 $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
478 }
479
43c1fa19 480 $this->setFromBase('civicrm_contact');
481
482 $this->_from .= "
f813f78e 483 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
6a488035
TO
484 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND
485 {$this->_aliases['civicrm_contribution']}.is_test = 0
030eb4f9 486 {$softCreditJoin}
f813f78e 487 LEFT JOIN civicrm_financial_type {$this->_aliases['civicrm_financial_type']}
6a488035 488 ON {$this->_aliases['civicrm_contribution']}.financial_type_id ={$this->_aliases['civicrm_financial_type']}.id
f813f78e 489 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
490 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
491 {$this->_aliases['civicrm_email']}.is_primary = 1)
492
493 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
494 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
6a488035
TO
495 {$this->_aliases['civicrm_phone']}.is_primary = 1)";
496
8b7f2513 497 $this->addAddressFromClause();
433465bc
PN
498 if (!empty($this->_params['batch_id_value'])) {
499 $this->_from .= "
500 LEFT JOIN civicrm_entity_financial_trxn eft
501 ON eft.entity_id = {$this->_aliases['civicrm_contribution']}.id AND
502 eft.entity_table = 'civicrm_contribution'
503 LEFT JOIN civicrm_entity_batch {$this->_aliases['civicrm_batch']}
504 ON {$this->_aliases['civicrm_batch']}.entity_id = eft.financial_trxn_id AND
505 {$this->_aliases['civicrm_batch']}.entity_table = 'civicrm_financial_trxn'\n";
506 }
6a488035
TO
507 }
508
ae6f7290 509 /**
510 * Set group by clause.
511 */
00be9182 512 public function groupBy() {
6a488035
TO
513 $this->_groupBy = "";
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') {
537 $this->_groupBy[] = self::fiscalYearOffset($field['dbAlias']);
538 }
539 else {
540 $this->_groupBy[] = "$append {$this->_params['group_bys_freq'][$fieldName]}({$field['dbAlias']})";
541 }
6a488035
TO
542 $append = TRUE;
543 }
544 else {
545 $this->_groupBy[] = $field['dbAlias'];
546 }
547 }
548 }
549 }
550 }
551
552 if (!empty($this->_statFields) &&
9d72cede
EM
553 (($append && count($this->_groupBy) <= 1) || (!$append)) &&
554 !$this->_having
6a488035
TO
555 ) {
556 $this->_rollup = " WITH ROLLUP";
557 }
bad98dd5 558 $groupBy = array();
559 foreach ($this->_groupBy as $key => $val) {
dc852c7b 560 if (strpos($val, ';;') !== FALSE) {
bad98dd5 561 $groupBy = array_merge($groupBy, explode(';;', $val));
562 }
563 else {
564 $groupBy[] = $this->_groupBy[$key];
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();
3b413375 620 $select = "
9b0380d9
DS
621COUNT({$this->_aliases['civicrm_contribution_soft']}.amount ) as civicrm_contribution_soft_soft_amount_count,
622SUM({$this->_aliases['civicrm_contribution_soft']}.amount ) as civicrm_contribution_soft_soft_amount_sum,
3b413375 623ROUND(AVG({$this->_aliases['civicrm_contribution_soft']}.amount), 2) as civicrm_contribution_soft_soft_amount_avg";
624 $contriQuery = "{$select}, {$contriQuery}";
625 $softSQL = "SELECT {$select}, {$this->_aliases['civicrm_contribution']}.currency as currency
626 {$this->_from} {$this->_where} {$group} {$this->_having}";
9b0380d9 627 }
c93f6d83 628
35dd1d26 629 $contriSQL = "SELECT {$contriQuery} {$group} {$this->_having}";
030eb4f9 630 $contriDAO = CRM_Core_DAO::executeQuery($contriSQL);
631
35dd1d26 632 $totalAmount = $average = $mode = $median = $softTotalAmount = $softAverage = array();
ae6884ce 633 $count = $softCount = 0;
030eb4f9 634 while ($contriDAO->fetch()) {
6c552737 635 $totalAmount[]
030eb4f9 636 = CRM_Utils_Money::format($contriDAO->civicrm_contribution_total_amount_sum, $contriDAO->currency) .
637 " (" . $contriDAO->civicrm_contribution_total_amount_count . ")";
638 $average[] = CRM_Utils_Money::format($contriDAO->civicrm_contribution_total_amount_avg, $contriDAO->currency);
639 $count += $contriDAO->civicrm_contribution_total_amount_count;
640 }
c93f6d83 641
35dd1d26 642 $groupBy = "\n{$group}, {$this->_aliases['civicrm_contribution']}.total_amount";
643 $orderBy = "\nORDER BY civicrm_contribution_total_amount_count DESC";
d1641c51 644 $modeSQL = "SELECT MAX(civicrm_contribution_total_amount_count) as civicrm_contribution_total_amount_count,
645 SUBSTRING_INDEX(GROUP_CONCAT(amount ORDER BY mode.civicrm_contribution_total_amount_count DESC SEPARATOR ';'), ';', 1) as amount,
646 currency
647 FROM (SELECT {$this->_aliases['civicrm_contribution']}.total_amount as amount,
35dd1d26 648 {$contriQuery} {$groupBy} {$orderBy}) as mode GROUP BY currency";
649
ae6884ce 650 $mode = CRM_Contribute_BAO_Contribution::computeStats('mode', $modeSQL);
35dd1d26 651
ae6884ce 652 $medianSQL = "{$this->_from} {$this->_where}";
653 $median = CRM_Contribute_BAO_Contribution::computeStats('median', $medianSQL, $this->_aliases['civicrm_contribution']);
35dd1d26 654
030eb4f9 655 if ($softCredit) {
656 $softDAO = CRM_Core_DAO::executeQuery($softSQL);
657 while ($softDAO->fetch()) {
6c552737 658 $softTotalAmount[]
030eb4f9 659 = CRM_Utils_Money::format($softDAO->civicrm_contribution_soft_soft_amount_sum, $softDAO->currency) .
660 " (" . $softDAO->civicrm_contribution_soft_soft_amount_count . ")";
661 $softAverage[] = CRM_Utils_Money::format($softDAO->civicrm_contribution_soft_soft_amount_avg, $softDAO->currency);
662 $softCount += $softDAO->civicrm_contribution_soft_soft_amount_count;
9b0380d9
DS
663 }
664 }
c93f6d83 665
9b0380d9 666 if (!$onlySoftCredit) {
35d8497b 667 $statistics['counts']['amount'] = array(
668 'title' => ts('Total Amount'),
669 'value' => implode(', ', $totalAmount),
670 'type' => CRM_Utils_Type::T_STRING,
671 );
672 $statistics['counts']['count'] = array(
be205937 673 'title' => ts('Total Contributions'),
35d8497b 674 'value' => $count,
675 );
676 $statistics['counts']['avg'] = array(
677 'title' => ts('Average'),
678 'value' => implode(', ', $average),
679 'type' => CRM_Utils_Type::T_STRING,
680 );
35dd1d26 681 $statistics['counts']['mode'] = array(
682 'title' => ts('Mode'),
683 'value' => implode(', ', $mode),
684 'type' => CRM_Utils_Type::T_STRING,
685 );
686 $statistics['counts']['median'] = array(
687 'title' => ts('Median'),
688 'value' => implode(', ', $median),
689 'type' => CRM_Utils_Type::T_STRING,
690 );
9b0380d9
DS
691 }
692 if ($softCredit) {
693 $statistics['counts']['soft_amount'] = array(
694 'title' => ts('Total Soft Credit Amount'),
695 'value' => implode(', ', $softTotalAmount),
696 'type' => CRM_Utils_Type::T_STRING,
697 );
698 $statistics['counts']['soft_count'] = array(
699 'title' => ts('Total Soft Credits'),
700 'value' => $softCount,
701 );
702 $statistics['counts']['soft_avg'] = array(
703 'title' => ts('Average Soft Credit'),
704 'value' => implode(', ', $softAverage),
705 'type' => CRM_Utils_Type::T_STRING,
706 );
6a488035
TO
707 }
708 return $statistics;
709 }
710
ae6f7290 711 /**
712 * Post process function.
713 */
00be9182 714 public function postProcess() {
0c00c2f2 715 $this->buildACLClause($this->_aliases['civicrm_contact']);
6a488035
TO
716 parent::postProcess();
717 }
718
ae6f7290 719 /**
720 * Build table rows for output.
721 *
722 * @param string $sql
723 * @param array $rows
724 */
030eb4f9 725 public function buildRows($sql, &$rows) {
726 $dao = CRM_Core_DAO::executeQuery($sql);
727 if (!is_array($rows)) {
728 $rows = array();
729 }
730
731 // use this method to modify $this->_columnHeaders
732 $this->modifyColumnHeaders();
ae6f7290 733 $contriRows = array();
030eb4f9 734 $unselectedSectionColumns = $this->unselectedSectionColumns();
735
736 //CRM-16338 if both soft-credit and contribution are enabled then process the contribution's
737 //total amount's average, count and sum separately and add it to the respective result list
738 $softCredit = (!empty($this->_params['fields']['soft_amount']) && !empty($this->_params['fields']['total_amount'])) ? TRUE : FALSE;
739 if ($softCredit) {
740 $this->from('contribution');
741 $contriSQL = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
742 $contriDAO = CRM_Core_DAO::executeQuery($contriSQL);
743 $contriFields = array(
744 'civicrm_contribution_total_amount_sum',
745 'civicrm_contribution_total_amount_avg',
746 'civicrm_contribution_total_amount_count');
747 $contriRows = array();
748 while ($contriDAO->fetch()) {
749 $contriRow = array();
750 foreach ($contriFields as $column) {
751 $contriRow[$column] = $contriDAO->$column;
752 }
753 $contriRows[] = $contriRow;
754 }
755 }
756
757 $count = 0;
758 while ($dao->fetch()) {
759 $row = array();
760 foreach ($this->_columnHeaders as $key => $value) {
761 if ($softCredit && array_key_exists($key, $contriRows[$count])) {
762 $row[$key] = $contriRows[$count][$key];
763 }
764 elseif (property_exists($dao, $key)) {
765 $row[$key] = $dao->$key;
766 }
767 }
768
769 // section headers not selected for display need to be added to row
770 foreach ($unselectedSectionColumns as $key => $values) {
771 if (property_exists($dao, $key)) {
772 $row[$key] = $dao->$key;
773 }
774 }
775
776 $count++;
777 $rows[] = $row;
778 }
779
780 }
781
74cf4551 782 /**
ae6f7290 783 * Build chart.
784 *
785 * @param array $rows
74cf4551 786 */
00be9182 787 public function buildChart(&$rows) {
6a488035 788 $graphRows = array();
6a488035 789
a7488080
CW
790 if (!empty($this->_params['charts'])) {
791 if (!empty($this->_params['group_bys']['receive_date'])) {
0c98098b 792
0d8afee2
CW
793 $contrib = !empty($this->_params['fields']['total_amount']) ? TRUE : FALSE;
794 $softContrib = !empty($this->_params['fields']['soft_amount']) ? TRUE : FALSE;
0c98098b
DS
795
796 foreach ($rows as $key => $row) {
797 if ($row['civicrm_contribution_receive_date_subtotal']) {
798 $graphRows['receive_date'][] = $row['civicrm_contribution_receive_date_start'];
799 $graphRows[$this->_interval][] = $row['civicrm_contribution_receive_date_interval'];
800 if ($softContrib && $contrib) {
801 // both contri & soft contri stats are present
802 $graphRows['multiValue'][0][] = $row['civicrm_contribution_total_amount_sum'];
803 $graphRows['multiValue'][1][] = $row['civicrm_contribution_soft_soft_amount_sum'];
9d72cede 804 }
4c9b6178 805 elseif ($softContrib) {
0c98098b
DS
806 // only soft contributions
807 $graphRows['multiValue'][0][] = $row['civicrm_contribution_soft_soft_amount_sum'];
9d72cede
EM
808 }
809 else {
0c98098b
DS
810 // only contributions
811 $graphRows['multiValue'][0][] = $row['civicrm_contribution_total_amount_sum'];
812 }
813 }
6a488035 814 }
6a488035 815
0c98098b
DS
816 if ($softContrib && $contrib) {
817 $graphRows['barKeys'][0] = ts('Contributions');
818 $graphRows['barKeys'][1] = ts('Soft Credits');
819 $graphRows['legend'] = ts('Contributions and Soft Credits');
9d72cede 820 }
4c9b6178 821 elseif ($softContrib) {
0c98098b
DS
822 $graphRows['legend'] = ts('Soft Credits');
823 }
6a488035
TO
824
825 // build the chart.
9d72cede 826 $config = CRM_Core_Config::Singleton();
6a488035
TO
827 $graphRows['xname'] = $this->_interval;
828 $graphRows['yname'] = "Amount ({$config->defaultCurrency})";
829 CRM_Utils_OpenFlashChart::chart($graphRows, $this->_params['charts'], $this->_interval);
830 $this->assign('chartType', $this->_params['charts']);
831 }
832 }
833 }
834
74cf4551 835 /**
ced9bfed
EM
836 * Alter display of rows.
837 *
838 * Iterate through the rows retrieved via SQL and make changes for display purposes,
839 * such as rendering contacts as links.
840 *
841 * @param array $rows
842 * Rows generated by SQL, with an array for each row.
74cf4551 843 */
00be9182 844 public function alterDisplay(&$rows) {
6a488035 845 $entryFound = FALSE;
8a347ca5 846 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
6a488035
TO
847
848 foreach ($rows as $rowNum => $row) {
849 // make count columns point to detail report
9d72cede
EM
850 if (!empty($this->_params['group_bys']['receive_date']) &&
851 !empty($row['civicrm_contribution_receive_date_start']) &&
852 CRM_Utils_Array::value('civicrm_contribution_receive_date_start', $row) &&
853 !empty($row['civicrm_contribution_receive_date_subtotal'])
854 ) {
6a488035
TO
855
856 $dateStart = CRM_Utils_Date::customFormat($row['civicrm_contribution_receive_date_start'], '%Y%m%d');
9d72cede
EM
857 $endDate = new DateTime($dateStart);
858 $dateEnd = array();
6a488035
TO
859
860 list($dateEnd['Y'], $dateEnd['M'], $dateEnd['d']) = explode(':', $endDate->format('Y:m:d'));
861
862 switch (strtolower($this->_params['group_bys_freq']['receive_date'])) {
863 case 'month':
864 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] + 1,
9d72cede
EM
865 $dateEnd['d'] - 1, $dateEnd['Y']
866 ));
6a488035
TO
867 break;
868
869 case 'year':
870 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
9d72cede
EM
871 $dateEnd['d'] - 1, $dateEnd['Y'] + 1
872 ));
6a488035
TO
873 break;
874
35dd1d26 875 case 'fiscalyear':
876 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
877 $dateEnd['d'] - 1, $dateEnd['Y'] + 1
878 ));
879 break;
880
6a488035
TO
881 case 'yearweek':
882 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'],
9d72cede
EM
883 $dateEnd['d'] + 6, $dateEnd['Y']
884 ));
6a488035
TO
885 break;
886
887 case 'quarter':
888 $dateEnd = date("Ymd", mktime(0, 0, 0, $dateEnd['M'] + 3,
9d72cede
EM
889 $dateEnd['d'] - 1, $dateEnd['Y']
890 ));
6a488035
TO
891 break;
892 }
893 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
9d72cede
EM
894 "reset=1&force=1&receive_date_from={$dateStart}&receive_date_to={$dateEnd}",
895 $this->_absoluteUrl,
896 $this->_id,
897 $this->_drilldownReport
898 );
6a488035
TO
899 $rows[$rowNum]['civicrm_contribution_receive_date_start_link'] = $url;
900 $rows[$rowNum]['civicrm_contribution_receive_date_start_hover'] = ts('List all contribution(s) for this date unit.');
901 $entryFound = TRUE;
902 }
903
904 // make subtotals look nicer
905 if (array_key_exists('civicrm_contribution_receive_date_subtotal', $row) &&
906 !$row['civicrm_contribution_receive_date_subtotal']
907 ) {
908 $this->fixSubTotalDisplay($rows[$rowNum], $this->_statFields);
909 $entryFound = TRUE;
910 }
911
912 // convert display name to links
913 if (array_key_exists('civicrm_contact_sort_name', $row) &&
914 array_key_exists('civicrm_contact_id', $row)
915 ) {
916 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
917 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'],
918 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
919 );
920 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
921 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("Lists detailed contribution(s) for this record.");
922 $entryFound = TRUE;
923 }
924
8a347ca5
RO
925 // convert contribution status id to status name
926 if ($value = CRM_Utils_Array::value('civicrm_contribution_contribution_status_id', $row)) {
927 $rows[$rowNum]['civicrm_contribution_contribution_status_id'] = $contributionStatus[$value];
928 $entryFound = TRUE;
929 }
930
a7dbbc5d 931 // If using campaigns, convert campaign_id to campaign title
6a488035
TO
932 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
933 if ($value = $row['civicrm_contribution_campaign_id']) {
934 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns[$value];
935 }
936 $entryFound = TRUE;
937 }
2ebf49a4 938
6a488035 939 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s) for this ') ? TRUE : $entryFound;
7a4192f7 940 $entryFound = $this->alterDisplayContactFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s) for this ') ? TRUE : $entryFound;
6a488035 941
6a488035
TO
942 // skip looking further in rows, if first row itself doesn't
943 // have the column we need
944 if (!$entryFound) {
945 break;
946 }
947 }
948 }
96025800 949
6a488035 950}