CRM-18246 Lybunt group clause not being included in temp table due to order of operations
[civicrm-core.git] / CRM / Report / Form / Contribute / SoftCredit.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2015
32 * $Id$
33 *
34 */
35 class CRM_Report_Form_Contribute_SoftCredit extends CRM_Report_Form {
36
37 protected $_emailField = FALSE;
38 protected $_emailFieldCredit = FALSE;
39 protected $_phoneField = FALSE;
40 protected $_phoneFieldCredit = FALSE;
41 protected $_charts = array(
42 '' => 'Tabular',
43 'barChart' => 'Bar Chart',
44 'pieChart' => 'Pie Chart',
45 );
46
47 protected $_customGroupExtends = array(
48 'Contact',
49 'Individual',
50 'Contribution',
51 );
52
53 public $_drilldownReport = array('contribute/detail' => 'Link to Detail Report');
54
55 /**
56 */
57 public function __construct() {
58
59 // Check if CiviCampaign is a) enabled and b) has active campaigns
60 $config = CRM_Core_Config::singleton();
61 $campaignEnabled = in_array("CiviCampaign", $config->enableComponents);
62 if ($campaignEnabled) {
63 $getCampaigns = CRM_Campaign_BAO_Campaign::getPermissionedCampaigns(NULL, NULL, TRUE, FALSE, TRUE);
64 $this->activeCampaigns = $getCampaigns['campaigns'];
65 asort($this->activeCampaigns);
66 }
67
68 $this->_columns = array(
69 'civicrm_contact' => array(
70 'dao' => 'CRM_Contact_DAO_Contact',
71 'fields' => array(
72 'display_name_creditor' => array(
73 'title' => ts('Soft Credit Name'),
74 'name' => 'sort_name',
75 'alias' => 'contact_civireport',
76 'required' => TRUE,
77 'no_repeat' => TRUE,
78 ),
79 'id_creditor' => array(
80 'title' => ts('Soft Credit Id'),
81 'name' => 'id',
82 'alias' => 'contact_civireport',
83 'no_display' => TRUE,
84 'required' => TRUE,
85 ),
86 'display_name_constituent' => array(
87 'title' => ts('Contributor Name'),
88 'name' => 'sort_name',
89 'alias' => 'constituentname',
90 'required' => TRUE,
91 ),
92 'id_constituent' => array(
93 'title' => ts('Const Id'),
94 'name' => 'id',
95 'alias' => 'constituentname',
96 'no_display' => TRUE,
97 'required' => TRUE,
98 ),
99 'first_name' => array(
100 'title' => ts('First Name'),
101 ),
102 'middle_name' => array(
103 'title' => ts('Middle Name'),
104 ),
105 'last_name' => array(
106 'title' => ts('Last Name'),
107 ),
108 'gender_id' => array(
109 'title' => ts('Gender'),
110 ),
111 'birth_date' => array(
112 'title' => ts('Birth Date'),
113 ),
114 'age' => array(
115 'title' => ts('Age'),
116 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
117 ),
118 'contact_type' => array(
119 'title' => ts('Contact Type'),
120 ),
121 'contact_sub_type' => array(
122 'title' => ts('Contact Subtype'),
123 ),
124 ),
125 'grouping' => 'contact-fields',
126 'order_bys' => array(
127 'sort_name' => array(
128 'title' => ts('Last Name, First Name'),
129 'default' => '1',
130 'default_weight' => '0',
131 'default_order' => 'ASC',
132 ),
133 'first_name' => array(
134 'name' => 'first_name',
135 'title' => ts('First Name'),
136 ),
137 'gender_id' => array(
138 'name' => 'gender_id',
139 'title' => ts('Gender'),
140 ),
141 'birth_date' => array(
142 'name' => 'birth_date',
143 'title' => ts('Birth Date'),
144 ),
145 'age_at_event' => array(
146 'name' => 'age_at_event',
147 'title' => ts('Age at Event'),
148 ),
149 'contact_type' => array(
150 'title' => ts('Contact Type'),
151 ),
152 'contact_sub_type' => array(
153 'title' => ts('Contact Subtype'),
154 ),
155 ),
156 'filters' => array(
157 'sort_name' => array(
158 'name' => 'sort_name',
159 'title' => ts('Soft Credit Name'),
160 ),
161 'gender_id' => array(
162 'title' => ts('Gender'),
163 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
164 'options' => CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'),
165 ),
166 'birth_date' => array(
167 'title' => ts('Birth Date'),
168 'operatorType' => CRM_Report_Form::OP_DATE,
169 ),
170 'contact_type' => array(
171 'title' => ts('Contact Type'),
172 ),
173 'contact_sub_type' => array(
174 'title' => ts('Contact Subtype'),
175 ),
176 ),
177 ),
178 'civicrm_email' => array(
179 'dao' => 'CRM_Core_DAO_Email',
180 'fields' => array(
181 'email_creditor' => array(
182 'title' => ts('Soft Credit Email'),
183 'name' => 'email',
184 'alias' => 'emailcredit',
185 'default' => TRUE,
186 'no_repeat' => TRUE,
187 ),
188 'email_constituent' => array(
189 'title' => ts('Contributor\'s Email'),
190 'name' => 'email',
191 'alias' => 'emailconst',
192 ),
193 ),
194 'grouping' => 'contact-fields',
195 ),
196 'civicrm_phone' => array(
197 'dao' => 'CRM_Core_DAO_Phone',
198 'fields' => array(
199 'phone_creditor' => array(
200 'title' => ts('Soft Credit Phone'),
201 'name' => 'phone',
202 'alias' => 'pcredit',
203 'default' => TRUE,
204 ),
205 'phone_constituent' => array(
206 'title' => ts('Contributor\'s Phone'),
207 'name' => 'phone',
208 'alias' => 'pconst',
209 'no_repeat' => TRUE,
210 ),
211 ),
212 'grouping' => 'contact-fields',
213 ),
214 'civicrm_financial_type' => array(
215 'dao' => 'CRM_Financial_DAO_FinancialType',
216 'fields' => array('financial_type' => NULL),
217 'filters' => array(
218 'id' => array(
219 'name' => 'id',
220 'title' => ts('Financial Type'),
221 'type' => CRM_Utils_Type::T_INT,
222 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
223 'options' => CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes(),
224 ),
225 ),
226 'grouping' => 'softcredit-fields',
227 ),
228 'civicrm_contribution' => array(
229 'dao' => 'CRM_Contribute_DAO_Contribution',
230 'fields' => array(
231 'contribution_source' => NULL,
232 'currency' => array(
233 'required' => TRUE,
234 'no_display' => TRUE,
235 ),
236 ),
237 'grouping' => 'softcredit-fields',
238 'filters' => array(
239 'receive_date' => array('operatorType' => CRM_Report_Form::OP_DATE),
240 'currency' => array(
241 'title' => 'Currency',
242 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
243 'options' => CRM_Core_OptionGroup::values('currencies_enabled'),
244 'default' => NULL,
245 'type' => CRM_Utils_Type::T_STRING,
246 ),
247 'contribution_status_id' => array(
248 'title' => ts('Contribution Status'),
249 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
250 'options' => CRM_Contribute_PseudoConstant::contributionStatus(),
251 'default' => array(1),
252 ),
253 ),
254 ),
255 'civicrm_contribution_soft' => array(
256 'dao' => 'CRM_Contribute_DAO_ContributionSoft',
257 'fields' => array(
258 'contribution_id' => array(
259 'title' => ts('Contribution ID'),
260 'no_display' => TRUE,
261 'default' => TRUE,
262 ),
263 'amount' => array(
264 'title' => ts('Amount Statistics'),
265 'default' => TRUE,
266 'statistics' => array(
267 'sum' => ts('Aggregate Amount'),
268 'count' => ts('Contributions'),
269 'avg' => ts('Average'),
270 ),
271 ),
272 'id' => array(
273 'default' => TRUE,
274 'no_display' => TRUE,
275 ),
276 'soft_credit_type_id' => array('title' => ts('Soft Credit Type')),
277 ),
278 'filters' => array(
279 'soft_credit_type_id' => array(
280 'title' => 'Soft Credit Type',
281 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
282 'options' => CRM_Core_OptionGroup::values('soft_credit_type'),
283 'default' => NULL,
284 'type' => CRM_Utils_Type::T_STRING,
285 ),
286 'amount' => array(
287 'title' => ts('Soft Credit Amount'),
288 ),
289 ),
290 'grouping' => 'softcredit-fields',
291 ),
292 );
293
294 // If we have a campaign, build out the relevant elements
295 if ($campaignEnabled && !empty($this->activeCampaigns)) {
296 $this->_columns['civicrm_contribution']['fields']['campaign_id'] = array(
297 'title' => ts('Campaign'),
298 'default' => 'false',
299 );
300 $this->_columns['civicrm_contribution']['filters']['campaign_id'] = array(
301 'title' => ts('Campaign'),
302 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
303 'options' => $this->activeCampaigns,
304 );
305 }
306
307 $this->_groupFilter = TRUE;
308 $this->_tagFilter = TRUE;
309
310 $this->_currencyColumn = 'civicrm_contribution_currency';
311 parent::__construct();
312 }
313
314 public function preProcess() {
315 parent::preProcess();
316 }
317
318 public function select() {
319 $select = array();
320 $this->_columnHeaders = array();
321 foreach ($this->_columns as $tableName => $table) {
322 if (array_key_exists('fields', $table)) {
323 foreach ($table['fields'] as $fieldName => $field) {
324 if (!empty($field['required']) ||
325 !empty($this->_params['fields'][$fieldName])
326 ) {
327
328 // include email column if set
329 if ($tableName == 'civicrm_email') {
330 $this->_emailField = TRUE;
331 $this->_emailFieldCredit = TRUE;
332 }
333 elseif ($tableName == 'civicrm_email_creditor') {
334 $this->_emailFieldCredit = TRUE;
335 }
336
337 // include phone columns if set
338 if ($tableName == 'civicrm_phone') {
339 $this->_phoneField = TRUE;
340 $this->_phoneFieldCredit = TRUE;
341 }
342 elseif ($tableName == 'civicrm_phone_creditor') {
343 $this->_phoneFieldCredit = TRUE;
344 }
345
346 // only include statistics columns if set
347 if (!empty($field['statistics'])) {
348 foreach ($field['statistics'] as $stat => $label) {
349 switch (strtolower($stat)) {
350 case 'sum':
351 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
352 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
353 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
354 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
355 break;
356
357 case 'count':
358 $select[] = "COUNT({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
359 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT;
360 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
361 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
362 break;
363
364 case 'avg':
365 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as {$tableName}_{$fieldName}_{$stat}";
366 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
367 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
368 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
369 break;
370 }
371 }
372 }
373 else {
374 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
375 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
376 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = $field['title'];
377 }
378 }
379 }
380 }
381 }
382
383 $this->_select = 'SELECT ' . implode(', ', $select) . ' ';
384 }
385
386 /**
387 * @param $fields
388 * @param $files
389 * @param $self
390 *
391 * @return array
392 */
393 public static function formRule($fields, $files, $self) {
394 $errors = $grouping = array();
395 return $errors;
396 }
397
398 public function from() {
399 $alias_constituent = 'constituentname';
400 $alias_creditor = 'contact_civireport';
401 $this->_from = "
402 FROM civicrm_contribution {$this->_aliases['civicrm_contribution']}
403 INNER JOIN civicrm_contribution_soft {$this->_aliases['civicrm_contribution_soft']}
404 ON {$this->_aliases['civicrm_contribution_soft']}.contribution_id =
405 {$this->_aliases['civicrm_contribution']}.id
406 INNER JOIN civicrm_contact {$alias_constituent}
407 ON {$this->_aliases['civicrm_contribution']}.contact_id =
408 {$alias_constituent}.id
409 LEFT JOIN civicrm_financial_type {$this->_aliases['civicrm_financial_type']}
410 ON {$this->_aliases['civicrm_contribution']}.financial_type_id =
411 {$this->_aliases['civicrm_financial_type']}.id
412 LEFT JOIN civicrm_contact {$alias_creditor}
413 ON {$this->_aliases['civicrm_contribution_soft']}.contact_id =
414 {$alias_creditor}.id
415 {$this->_aclFrom} ";
416
417 // include Constituent email field if email column is to be included
418 if ($this->_emailField) {
419 $alias = 'emailconst';
420 $this->_from .= "
421 LEFT JOIN civicrm_email {$alias}
422 ON {$alias_constituent}.id =
423 {$alias}.contact_id AND
424 {$alias}.is_primary = 1\n";
425 }
426
427 // include Creditors email field if email column is to be included
428 if ($this->_emailFieldCredit) {
429 $alias = 'emailcredit';
430 $this->_from .= "
431 LEFT JOIN civicrm_email {$alias}
432 ON {$alias_creditor}.id =
433 {$alias}.contact_id AND
434 {$alias}.is_primary = 1\n";
435 }
436
437 // include Constituents phone field if email column is to be included
438 if ($this->_phoneField) {
439 $alias = 'pconst';
440 $this->_from .= "
441 LEFT JOIN civicrm_phone {$alias}
442 ON {$alias_constituent}.id =
443 {$alias}.contact_id AND
444 {$alias}.is_primary = 1\n";
445 }
446
447 // include Creditors phone field if email column is to be included
448 if ($this->_phoneFieldCredit) {
449 $alias = 'pcredit';
450 $this->_from .= "
451 LEFT JOIN civicrm_phone pcredit
452 ON {$alias_creditor}.id =
453 {$alias}.contact_id AND
454 {$alias}.is_primary = 1\n";
455 }
456 }
457
458 public function groupBy() {
459 $this->_rollup = 'WITH ROLLUP';
460 $this->_groupBy = "
461 GROUP BY {$this->_aliases['civicrm_contribution_soft']}.contact_id, constituentname.id {$this->_rollup}";
462 }
463
464 public function where() {
465 parent::where();
466 $this->_where .= " AND {$this->_aliases['civicrm_contribution']}.is_test = 0 ";
467 }
468
469 /**
470 * @param $rows
471 *
472 * @return array
473 */
474 public function statistics(&$rows) {
475 $statistics = parent::statistics($rows);
476
477 $select = "
478 SELECT COUNT({$this->_aliases['civicrm_contribution_soft']}.amount ) as count,
479 SUM({$this->_aliases['civicrm_contribution_soft']}.amount ) as amount,
480 ROUND(AVG({$this->_aliases['civicrm_contribution_soft']}.amount), 2) as avg,
481 {$this->_aliases['civicrm_contribution']}.currency as currency
482 ";
483
484 $sql = "{$select} {$this->_from} {$this->_where}
485 GROUP BY {$this->_aliases['civicrm_contribution']}.currency
486 ";
487
488 $dao = CRM_Core_DAO::executeQuery($sql);
489 $count = 0;
490 $totalAmount = $average = array();
491 while ($dao->fetch()) {
492 $totalAmount[] = CRM_Utils_Money::format($dao->amount, $dao->currency) . '(' .
493 $dao->count . ')';
494 $average[] = CRM_Utils_Money::format($dao->avg, $dao->currency);
495 $count += $dao->count;
496 }
497 $statistics['counts']['amount'] = array(
498 'title' => ts('Total Amount'),
499 'value' => implode(', ', $totalAmount),
500 'type' => CRM_Utils_Type::T_STRING,
501 );
502 $statistics['counts']['count'] = array(
503 'title' => ts('Total Contributions'),
504 'value' => $count,
505 );
506 $statistics['counts']['avg'] = array(
507 'title' => ts('Average'),
508 'value' => implode(', ', $average),
509 'type' => CRM_Utils_Type::T_STRING,
510 );
511
512 return $statistics;
513 }
514
515 public function postProcess() {
516 $this->beginPostProcess();
517
518 $this->buildACLClause(array('constituentname', 'contact_civireport'));
519 $sql = $this->buildQuery();
520
521 $dao = CRM_Core_DAO::executeQuery($sql);
522 $rows = $graphRows = array();
523 $count = 0;
524 while ($dao->fetch()) {
525 $row = array();
526 foreach ($this->_columnHeaders as $key => $value) {
527 $row[$key] = $dao->$key;
528 }
529 $rows[] = $row;
530 }
531 $this->formatDisplay($rows);
532
533 // to hide the contact ID field from getting displayed
534 unset($this->_columnHeaders['civicrm_contact_id_constituent']);
535 unset($this->_columnHeaders['civicrm_contact_id_creditor']);
536
537 // assign variables to templates
538 $this->doTemplateAssignment($rows);
539 $this->endPostProcess($rows);
540 }
541
542 /**
543 * Alter display of rows.
544 *
545 * Iterate through the rows retrieved via SQL and make changes for display purposes,
546 * such as rendering contacts as links.
547 *
548 * @param array $rows
549 * Rows generated by SQL, with an array for each row.
550 */
551 public function alterDisplay(&$rows) {
552 $entryFound = FALSE;
553 $dispname_flag = $phone_flag = $email_flag = 0;
554 $prev_email = $prev_dispname = $prev_phone = NULL;
555
556 foreach ($rows as $rowNum => $row) {
557 // Link constituent (contributor) to contribution detail
558 if (array_key_exists('civicrm_contact_display_name_constituent', $row) &&
559 array_key_exists('civicrm_contact_id_constituent', $row)
560 ) {
561
562 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
563 'reset=1&force=1&id_op=eq&id_value=' .
564 $row['civicrm_contact_id_constituent'],
565 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
566 );
567 $rows[$rowNum]['civicrm_contact_display_name_constituent_link'] = $url;
568 $rows[$rowNum]['civicrm_contact_display_name_constituent_hover'] = ts('List all direct contribution(s) from this contact.');
569 $entryFound = TRUE;
570 }
571
572 // convert soft credit contact name to link
573 if (array_key_exists('civicrm_contact_display_name_creditor', $row) &&
574 !empty($rows[$rowNum]['civicrm_contact_display_name_creditor']) &&
575 array_key_exists('civicrm_contact_id_creditor', $row)
576 ) {
577 $url = CRM_Utils_System::url("civicrm/contact/view",
578 'reset=1&cid=' . $row['civicrm_contact_id_creditor'],
579 $this->_absoluteUrl
580 );
581 $rows[$rowNum]['civicrm_contact_display_name_creditor_link'] = $url;
582 $rows[$rowNum]['civicrm_contact_display_name_creditor_hover'] = ts("view contact summary");
583 }
584
585 // make subtotals look nicer
586 if (array_key_exists('civicrm_contact_id_constituent', $row) &&
587 !$row['civicrm_contact_id_constituent']
588 ) {
589 $this->fixSubTotalDisplay($rows[$rowNum], $this->_statFields);
590 $entryFound = TRUE;
591 }
592
593 // convert campaign_id to campaign title
594 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
595 if ($value = $row['civicrm_contribution_campaign_id']) {
596 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns[$value];
597 $entryFound = TRUE;
598 }
599 }
600
601 //convert soft_credit_type_id into label
602 if (array_key_exists('civicrm_contribution_soft_soft_credit_type_id', $rows[$rowNum])) {
603 $rows[$rowNum]['civicrm_contribution_soft_soft_credit_type_id'] = CRM_Core_PseudoConstant::getLabel(
604 'CRM_Contribute_BAO_ContributionSoft',
605 'soft_credit_type_id',
606 $row['civicrm_contribution_soft_soft_credit_type_id']
607 );
608 }
609
610 //handle gender
611 if (array_key_exists('civicrm_contact_gender_id', $row)) {
612 if ($value = $row['civicrm_contact_gender_id']) {
613 $gender = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id');
614 $rows[$rowNum]['civicrm_contact_gender_id'] = $gender[$value];
615 }
616 $entryFound = TRUE;
617 }
618
619 // display birthday in the configured custom format
620 if (array_key_exists('civicrm_contact_birth_date', $row)) {
621 $birthDate = $row['civicrm_contact_birth_date'];
622 if ($birthDate) {
623 $rows[$rowNum]['civicrm_contact_birth_date'] = CRM_Utils_Date::customFormat($birthDate, '%Y%m%d');
624 }
625 $entryFound = TRUE;
626 }
627
628 // skip looking further in rows, if first row itself doesn't
629 // have the column we need
630 if (!$entryFound) {
631 break;
632 }
633 }
634
635 $this->removeDuplicates($rows);
636 }
637
638 }