Merge remote-tracking branch 'upstream/4.6' into 4.6-master-2015-09-15-10-14-22
[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 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
222 'options' => CRM_Contribute_PseudoConstant::financialType(),
223 ),
224 ),
225 'grouping' => 'softcredit-fields',
226 ),
227 'civicrm_contribution' => array(
228 'dao' => 'CRM_Contribute_DAO_Contribution',
229 'fields' => array(
230 'contribution_source' => NULL,
231 'currency' => array(
232 'required' => TRUE,
233 'no_display' => TRUE,
234 ),
235 'total_amount' => array(
236 'title' => ts('Amount Statistics'),
237 'default' => TRUE,
238 'statistics' => array(
239 'sum' => ts('Aggregate Amount'),
240 'count' => ts('Contributions'),
241 'avg' => ts('Average'),
242 ),
243 ),
244 ),
245 'grouping' => 'softcredit-fields',
246 'filters' => array(
247 'receive_date' => array('operatorType' => CRM_Report_Form::OP_DATE),
248 'currency' => array(
249 'title' => 'Currency',
250 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
251 'options' => CRM_Core_OptionGroup::values('currencies_enabled'),
252 'default' => NULL,
253 'type' => CRM_Utils_Type::T_STRING,
254 ),
255 'contribution_status_id' => array(
256 'title' => ts('Contribution Status'),
257 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
258 'options' => CRM_Contribute_PseudoConstant::contributionStatus(),
259 'default' => array(1),
260 ),
261 'total_amount' => array(
262 'title' => ts('Contribution Amount'),
263 ),
264 ),
265 ),
266 'civicrm_contribution_soft' => array(
267 'dao' => 'CRM_Contribute_DAO_ContributionSoft',
268 'fields' => array(
269 'contribution_id' => array(
270 'title' => ts('Contribution ID'),
271 'no_display' => TRUE,
272 'default' => TRUE,
273 ),
274 'id' => array(
275 'default' => TRUE,
276 'no_display' => TRUE,
277 ),
278 'soft_credit_type_id' => array('title' => ts('Soft Credit Type')),
279 ),
280 'filters' => array(
281 'soft_credit_type_id' => array(
282 'title' => 'Soft Credit Type',
283 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
284 'options' => CRM_Core_OptionGroup::values('soft_credit_type'),
285 'default' => NULL,
286 'type' => CRM_Utils_Type::T_STRING,
287 ),
288 ),
289 'grouping' => 'softcredit-fields',
290 ),
291 );
292
293 // If we have a campaign, build out the relevant elements
294 if ($campaignEnabled && !empty($this->activeCampaigns)) {
295 $this->_columns['civicrm_contribution']['fields']['campaign_id'] = array(
296 'title' => ts('Campaign'),
297 'default' => 'false',
298 );
299 $this->_columns['civicrm_contribution']['filters']['campaign_id'] = array(
300 'title' => ts('Campaign'),
301 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
302 'options' => $this->activeCampaigns,
303 );
304 }
305
306 $this->_groupFilter = TRUE;
307 $this->_tagFilter = TRUE;
308
309 $this->_currencyColumn = 'civicrm_contribution_currency';
310 parent::__construct();
311 }
312
313 public function preProcess() {
314 parent::preProcess();
315 }
316
317 public function select() {
318 $select = array();
319 $this->_columnHeaders = array();
320 foreach ($this->_columns as $tableName => $table) {
321 if (array_key_exists('fields', $table)) {
322 foreach ($table['fields'] as $fieldName => $field) {
323 if (!empty($field['required']) ||
324 !empty($this->_params['fields'][$fieldName])
325 ) {
326
327 // include email column if set
328 if ($tableName == 'civicrm_email') {
329 $this->_emailField = TRUE;
330 $this->_emailFieldCredit = TRUE;
331 }
332 elseif ($tableName == 'civicrm_email_creditor') {
333 $this->_emailFieldCredit = TRUE;
334 }
335
336 // include phone columns if set
337 if ($tableName == 'civicrm_phone') {
338 $this->_phoneField = TRUE;
339 $this->_phoneFieldCredit = TRUE;
340 }
341 elseif ($tableName == 'civicrm_phone_creditor') {
342 $this->_phoneFieldCredit = TRUE;
343 }
344
345 // only include statistics columns if set
346 if (!empty($field['statistics'])) {
347 foreach ($field['statistics'] as $stat => $label) {
348 switch (strtolower($stat)) {
349 case 'sum':
350 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
351 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
352 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
353 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
354 break;
355
356 case 'count':
357 $select[] = "COUNT({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
358 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT;
359 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
360 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
361 break;
362
363 case 'avg':
364 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as {$tableName}_{$fieldName}_{$stat}";
365 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
366 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
367 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
368 break;
369 }
370 }
371 }
372 else {
373 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
374 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
375 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = $field['title'];
376 }
377 }
378 }
379 }
380 }
381
382 $this->_select = 'SELECT ' . implode(', ', $select) . ' ';
383 }
384
385 /**
386 * @param $fields
387 * @param $files
388 * @param $self
389 *
390 * @return array
391 */
392 public static function formRule($fields, $files, $self) {
393 $errors = $grouping = array();
394 return $errors;
395 }
396
397 public function from() {
398 $alias_constituent = 'constituentname';
399 $alias_creditor = 'contact_civireport';
400 $this->_from = "
401 FROM civicrm_contribution {$this->_aliases['civicrm_contribution']}
402 INNER JOIN civicrm_contribution_soft {$this->_aliases['civicrm_contribution_soft']}
403 ON {$this->_aliases['civicrm_contribution_soft']}.contribution_id =
404 {$this->_aliases['civicrm_contribution']}.id
405 INNER JOIN civicrm_contact {$alias_constituent}
406 ON {$this->_aliases['civicrm_contribution']}.contact_id =
407 {$alias_constituent}.id
408 LEFT JOIN civicrm_financial_type {$this->_aliases['civicrm_financial_type']}
409 ON {$this->_aliases['civicrm_contribution']}.financial_type_id =
410 {$this->_aliases['civicrm_financial_type']}.id
411 LEFT JOIN civicrm_contact {$alias_creditor}
412 ON {$this->_aliases['civicrm_contribution_soft']}.contact_id =
413 {$alias_creditor}.id
414 {$this->_aclFrom} ";
415
416 // include Constituent email field if email column is to be included
417 if ($this->_emailField) {
418 $alias = 'emailconst';
419 $this->_from .= "
420 LEFT JOIN civicrm_email {$alias}
421 ON {$alias_constituent}.id =
422 {$alias}.contact_id AND
423 {$alias}.is_primary = 1\n";
424 }
425
426 // include Creditors email field if email column is to be included
427 if ($this->_emailFieldCredit) {
428 $alias = 'emailcredit';
429 $this->_from .= "
430 LEFT JOIN civicrm_email {$alias}
431 ON {$alias_creditor}.id =
432 {$alias}.contact_id AND
433 {$alias}.is_primary = 1\n";
434 }
435
436 // include Constituents phone field if email column is to be included
437 if ($this->_phoneField) {
438 $alias = 'pconst';
439 $this->_from .= "
440 LEFT JOIN civicrm_phone {$alias}
441 ON {$alias_constituent}.id =
442 {$alias}.contact_id AND
443 {$alias}.is_primary = 1\n";
444 }
445
446 // include Creditors phone field if email column is to be included
447 if ($this->_phoneFieldCredit) {
448 $alias = 'pcredit';
449 $this->_from .= "
450 LEFT JOIN civicrm_phone pcredit
451 ON {$alias_creditor}.id =
452 {$alias}.contact_id AND
453 {$alias}.is_primary = 1\n";
454 }
455 }
456
457 public function groupBy() {
458 $this->_rollup = 'WITH ROLLUP';
459 $this->_groupBy = "
460 GROUP BY {$this->_aliases['civicrm_contribution_soft']}.contact_id, constituentname.id {$this->_rollup}";
461 }
462
463 public function where() {
464 parent::where();
465 $this->_where .= " AND {$this->_aliases['civicrm_contribution']}.is_test = 0 ";
466 }
467
468 /**
469 * @param $rows
470 *
471 * @return array
472 */
473 public function statistics(&$rows) {
474 $statistics = parent::statistics($rows);
475
476 $select = "
477 SELECT COUNT({$this->_aliases['civicrm_contribution']}.total_amount ) as count,
478 SUM({$this->_aliases['civicrm_contribution']}.total_amount ) as amount,
479 ROUND(AVG({$this->_aliases['civicrm_contribution']}.total_amount), 2) as avg,
480 {$this->_aliases['civicrm_contribution']}.currency as currency
481 ";
482
483 $sql = "{$select} {$this->_from} {$this->_where}
484 GROUP BY {$this->_aliases['civicrm_contribution']}.currency
485 ";
486
487 $dao = CRM_Core_DAO::executeQuery($sql);
488 $count = 0;
489 $totalAmount = $average = array();
490 while ($dao->fetch()) {
491 $totalAmount[] = CRM_Utils_Money::format($dao->amount, $dao->currency) . '(' .
492 $dao->count . ')';
493 $average[] = CRM_Utils_Money::format($dao->avg, $dao->currency);
494 $count += $dao->count;
495 }
496 $statistics['counts']['amount'] = array(
497 'title' => ts('Total Amount'),
498 'value' => implode(', ', $totalAmount),
499 'type' => CRM_Utils_Type::T_STRING,
500 );
501 $statistics['counts']['count'] = array(
502 'title' => ts('Total Contributions'),
503 'value' => $count,
504 );
505 $statistics['counts']['avg'] = array(
506 'title' => ts('Average'),
507 'value' => implode(', ', $average),
508 'type' => CRM_Utils_Type::T_STRING,
509 );
510
511 return $statistics;
512 }
513
514 public function postProcess() {
515 $this->beginPostProcess();
516
517 $this->buildACLClause(array('constituentname', 'contact_civireport'));
518 $sql = $this->buildQuery();
519
520 $dao = CRM_Core_DAO::executeQuery($sql);
521 $rows = $graphRows = array();
522 $count = 0;
523 while ($dao->fetch()) {
524 $row = array();
525 foreach ($this->_columnHeaders as $key => $value) {
526 $row[$key] = $dao->$key;
527 }
528 $rows[] = $row;
529 }
530 $this->formatDisplay($rows);
531
532 // to hide the contact ID field from getting displayed
533 unset($this->_columnHeaders['civicrm_contact_id_constituent']);
534 unset($this->_columnHeaders['civicrm_contact_id_creditor']);
535
536 // assign variables to templates
537 $this->doTemplateAssignment($rows);
538 $this->endPostProcess($rows);
539 }
540
541 /**
542 * Alter display of rows.
543 *
544 * Iterate through the rows retrieved via SQL and make changes for display purposes,
545 * such as rendering contacts as links.
546 *
547 * @param array $rows
548 * Rows generated by SQL, with an array for each row.
549 */
550 public function alterDisplay(&$rows) {
551 $entryFound = FALSE;
552 $dispname_flag = $phone_flag = $email_flag = 0;
553 $prev_email = $prev_dispname = $prev_phone = NULL;
554
555 foreach ($rows as $rowNum => $row) {
556 // Link constituent (contributor) to contribution detail
557 if (array_key_exists('civicrm_contact_display_name_constituent', $row) &&
558 array_key_exists('civicrm_contact_id_constituent', $row)
559 ) {
560
561 $url = CRM_Report_Utils_Report::getNextUrl('contribute/detail',
562 'reset=1&force=1&id_op=eq&id_value=' .
563 $row['civicrm_contact_id_constituent'],
564 $this->_absoluteUrl, $this->_id, $this->_drilldownReport
565 );
566 $rows[$rowNum]['civicrm_contact_display_name_constituent_link'] = $url;
567 $rows[$rowNum]['civicrm_contact_display_name_constituent_hover'] = ts('List all direct contribution(s) from this contact.');
568 $entryFound = TRUE;
569 }
570
571 // convert soft credit contact name to link
572 if (array_key_exists('civicrm_contact_display_name_creditor', $row) &&
573 !empty($rows[$rowNum]['civicrm_contact_display_name_creditor']) &&
574 array_key_exists('civicrm_contact_id_creditor', $row)
575 ) {
576 $url = CRM_Utils_System::url("civicrm/contact/view",
577 'reset=1&cid=' . $row['civicrm_contact_id_creditor'],
578 $this->_absoluteUrl
579 );
580 $rows[$rowNum]['civicrm_contact_display_name_creditor_link'] = $url;
581 $rows[$rowNum]['civicrm_contact_display_name_creditor_hover'] = ts("view contact summary");
582 }
583
584 // make subtotals look nicer
585 if (array_key_exists('civicrm_contact_id_constituent', $row) &&
586 !$row['civicrm_contact_id_constituent']
587 ) {
588 $this->fixSubTotalDisplay($rows[$rowNum], $this->_statFields);
589 $entryFound = TRUE;
590 }
591
592 // convert campaign_id to campaign title
593 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
594 if ($value = $row['civicrm_contribution_campaign_id']) {
595 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns[$value];
596 $entryFound = TRUE;
597 }
598 }
599
600 //convert soft_credit_type_id into label
601 if (array_key_exists('civicrm_contribution_soft_soft_credit_type_id', $rows[$rowNum])) {
602 $rows[$rowNum]['civicrm_contribution_soft_soft_credit_type_id'] = CRM_Core_PseudoConstant::getLabel(
603 'CRM_Contribute_BAO_ContributionSoft',
604 'soft_credit_type_id',
605 $row['civicrm_contribution_soft_soft_credit_type_id']
606 );
607 }
608
609 //handle gender
610 if (array_key_exists('civicrm_contact_gender_id', $row)) {
611 if ($value = $row['civicrm_contact_gender_id']) {
612 $gender = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id');
613 $rows[$rowNum]['civicrm_contact_gender_id'] = $gender[$value];
614 }
615 $entryFound = TRUE;
616 }
617
618 // display birthday in the configured custom format
619 if (array_key_exists('civicrm_contact_birth_date', $row)) {
620 $birthDate = $row['civicrm_contact_birth_date'];
621 if ($birthDate) {
622 $rows[$rowNum]['civicrm_contact_birth_date'] = CRM_Utils_Date::customFormat($birthDate, '%Y%m%d');
623 }
624 $entryFound = TRUE;
625 }
626
627 // skip looking further in rows, if first row itself doesn't
628 // have the column we need
629 if (!$entryFound) {
630 break;
631 }
632 }
633
634 $this->removeDuplicates($rows);
635 }
636
637 }