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