Merge pull request #7924 from lucianov88/master
[civicrm-core.git] / CRM / Report / Form / Contribute / Detail.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_Detail extends CRM_Report_Form {
36 protected $_addressField = FALSE;
37
38 protected $_emailField = FALSE;
39
40 protected $_summary = NULL;
41 protected $_allBatches = NULL;
42
43 protected $_softFrom = NULL;
44
45 protected $_customGroupExtends = array(
46 'Contact',
47 'Individual',
48 'Contribution',
49 );
50
51 /**
52 */
53 public function __construct() {
54 $this->_autoIncludeIndexedFieldsAsOrderBys = 1;
55 // Check if CiviCampaign is a) enabled and b) has active campaigns
56 $config = CRM_Core_Config::singleton();
57 $campaignEnabled = in_array("CiviCampaign", $config->enableComponents);
58 if ($campaignEnabled) {
59 $getCampaigns = CRM_Campaign_BAO_Campaign::getPermissionedCampaigns(NULL, NULL, TRUE, FALSE, TRUE);
60 $this->activeCampaigns = $getCampaigns['campaigns'];
61 asort($this->activeCampaigns);
62 }
63 $this->_columns = array(
64 'civicrm_contact' => array(
65 'dao' => 'CRM_Contact_DAO_Contact',
66 'fields' => array(
67 'sort_name' => array(
68 'title' => ts('Donor Name'),
69 'required' => TRUE,
70 ),
71 'first_name' => array(
72 'title' => ts('First Name'),
73 ),
74 'middle_name' => array(
75 'title' => ts('Middle Name'),
76 ),
77 'last_name' => array(
78 'title' => ts('Last Name'),
79 ),
80 'id' => array(
81 'no_display' => TRUE,
82 'required' => TRUE,
83 ),
84 'gender_id' => array(
85 'title' => ts('Gender'),
86 ),
87 'birth_date' => array(
88 'title' => ts('Birth Date'),
89 ),
90 'age' => array(
91 'title' => ts('Age'),
92 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
93 ),
94 'contact_type' => array(
95 'title' => ts('Contact Type'),
96 ),
97 'contact_sub_type' => array(
98 'title' => ts('Contact Subtype'),
99 ),
100 ),
101 'filters' => array(
102 'sort_name' => array(
103 'title' => ts('Donor Name'),
104 'operator' => 'like',
105 ),
106 'id' => array(
107 'title' => ts('Contact ID'),
108 'no_display' => TRUE,
109 'type' => CRM_Utils_Type::T_INT,
110 ),
111 'gender_id' => array(
112 'title' => ts('Gender'),
113 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
114 'options' => CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'),
115 ),
116 'birth_date' => array(
117 'title' => ts('Birth Date'),
118 'operatorType' => CRM_Report_Form::OP_DATE,
119 ),
120 'contact_type' => array(
121 'title' => ts('Contact Type'),
122 ),
123 'contact_sub_type' => array(
124 'title' => ts('Contact Subtype'),
125 ),
126 ),
127 'grouping' => 'contact-fields',
128 'order_bys' => array(
129 'sort_name' => array(
130 'title' => ts('Last Name, First Name'),
131 'default' => '1',
132 'default_weight' => '0',
133 'default_order' => 'ASC',
134 ),
135 'first_name' => array(
136 'name' => 'first_name',
137 'title' => ts('First Name'),
138 ),
139 'gender_id' => array(
140 'name' => 'gender_id',
141 'title' => ts('Gender'),
142 ),
143 'birth_date' => array(
144 'name' => 'birth_date',
145 'title' => ts('Birth Date'),
146 ),
147 'contact_type' => array(
148 'title' => ts('Contact Type'),
149 ),
150 'contact_sub_type' => array(
151 'title' => ts('Contact Subtype'),
152 ),
153 ),
154
155 ),
156 'civicrm_email' => array(
157 'dao' => 'CRM_Core_DAO_Email',
158 'fields' => array(
159 'email' => array(
160 'title' => ts('Donor Email'),
161 'default' => TRUE,
162 ),
163 ),
164 'grouping' => 'contact-fields',
165 ),
166 'civicrm_line_item' => array(
167 'dao' => 'CRM_Price_DAO_LineItem',
168 ),
169 'civicrm_phone' => array(
170 'dao' => 'CRM_Core_DAO_Phone',
171 'fields' => array(
172 'phone' => array(
173 'title' => ts('Donor Phone'),
174 'default' => TRUE,
175 'no_repeat' => TRUE,
176 ),
177 ),
178 'grouping' => 'contact-fields',
179 ),
180 'civicrm_contribution' => array(
181 'dao' => 'CRM_Contribute_DAO_Contribution',
182 'fields' => array(
183 'contribution_id' => array(
184 'name' => 'id',
185 'no_display' => TRUE,
186 'required' => TRUE,
187 ),
188 'list_contri_id' => array(
189 'name' => 'id',
190 'title' => ts('Contribution ID'),
191 ),
192 'financial_type_id' => array(
193 'title' => ts('Financial Type'),
194 'default' => TRUE,
195 ),
196 'contribution_status_id' => array(
197 'title' => ts('Contribution Status'),
198 ),
199 'contribution_page_id' => array(
200 'title' => ts('Contribution Page'),
201 ),
202 'source' => array(
203 'title' => ts('Source'),
204 ),
205 'payment_instrument_id' => array(
206 'title' => ts('Payment Type'),
207 ),
208 'check_number' => array(
209 'title' => ts('Check Number'),
210 ),
211 'currency' => array(
212 'required' => TRUE,
213 'no_display' => TRUE,
214 ),
215 'trxn_id' => NULL,
216 'receive_date' => array('default' => TRUE),
217 'receipt_date' => NULL,
218 'total_amount' => array(
219 'title' => ts('Amount'),
220 'required' => TRUE,
221 'statistics' => array('sum' => ts('Amount')),
222 ),
223 'fee_amount' => NULL,
224 'net_amount' => NULL,
225 'contribution_or_soft' => array(
226 'title' => ts('Contribution OR Soft Credit?'),
227 'dbAlias' => "'Contribution'",
228 ),
229 'soft_credits' => array(
230 'title' => ts('Soft Credits'),
231 'dbAlias' => "NULL",
232 ),
233 'soft_credit_for' => array(
234 'title' => ts('Soft Credit For'),
235 'dbAlias' => "NULL",
236 ),
237 ),
238 'filters' => array(
239 'contribution_or_soft' => array(
240 'title' => ts('Contribution OR Soft Credit?'),
241 'clause' => "(1)",
242 'operatorType' => CRM_Report_Form::OP_SELECT,
243 'type' => CRM_Utils_Type::T_STRING,
244 'options' => array(
245 'both' => ts('Both'),
246 'contributions_only' => ts('Contributions Only'),
247 'soft_credits_only' => ts('Soft Credits Only'),
248 ),
249 ),
250 'receive_date' => array('operatorType' => CRM_Report_Form::OP_DATE),
251 'currency' => array(
252 'title' => 'Currency',
253 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
254 'options' => CRM_Core_OptionGroup::values('currencies_enabled'),
255 'default' => NULL,
256 'type' => CRM_Utils_Type::T_STRING,
257 ),
258 'financial_type_id' => array(
259 'title' => ts('Financial Type'),
260 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
261 'options' => CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes(),
262 'type' => CRM_Utils_Type::T_INT,
263 ),
264 'contribution_page_id' => array(
265 'title' => ts('Contribution Page'),
266 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
267 'options' => CRM_Contribute_PseudoConstant::contributionPage(),
268 'type' => CRM_Utils_Type::T_INT,
269 ),
270 'payment_instrument_id' => array(
271 'title' => ts('Payment Type'),
272 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
273 'options' => CRM_Contribute_PseudoConstant::paymentInstrument(),
274 'type' => CRM_Utils_Type::T_INT,
275 ),
276 'contribution_status_id' => array(
277 'title' => ts('Contribution Status'),
278 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
279 'options' => CRM_Contribute_PseudoConstant::contributionStatus(),
280 'default' => array(1),
281 'type' => CRM_Utils_Type::T_INT,
282 ),
283 'total_amount' => array('title' => ts('Contribution Amount')),
284 ),
285 'order_bys' => array(
286 'financial_type_id' => array('title' => ts('Financial Type')),
287 'contribution_status_id' => array('title' => ts('Contribution Status')),
288 'payment_instrument_id' => array('title' => ts('Payment Method')),
289 'receive_date' => array('title' => ts('Date Received')),
290 ),
291 'grouping' => 'contri-fields',
292 ),
293 'civicrm_contribution_soft' => array(
294 'dao' => 'CRM_Contribute_DAO_ContributionSoft',
295 'fields' => array(
296 'soft_credit_type_id' => array('title' => ts('Soft Credit Type')),
297 ),
298 'filters' => array(
299 'soft_credit_type_id' => array(
300 'title' => 'Soft Credit Type',
301 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
302 'options' => CRM_Core_OptionGroup::values('soft_credit_type'),
303 'default' => NULL,
304 'type' => CRM_Utils_Type::T_STRING,
305 ),
306 ),
307 ),
308 'civicrm_contribution_ordinality' => array(
309 'dao' => 'CRM_Contribute_DAO_Contribution',
310 'alias' => 'cordinality',
311 'filters' => array(
312 'ordinality' => array(
313 'title' => ts('Contribution Ordinality'),
314 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
315 'options' => array(
316 0 => 'First by Contributor',
317 1 => 'Second or Later by Contributor',
318 ),
319 'type' => CRM_Utils_Type::T_INT,
320 ),
321 ),
322 ),
323 'civicrm_note' => array(
324 'dao' => 'CRM_Core_DAO_Note',
325 'fields' => array(
326 'contribution_note' => array(
327 'name' => 'note',
328 'title' => ts('Contribution Note'),
329 ),
330 ),
331 'filters' => array(
332 'note' => array(
333 'name' => 'note',
334 'title' => ts('Contribution Note'),
335 'operator' => 'like',
336 'type' => CRM_Utils_Type::T_STRING,
337 ),
338 ),
339 ),
340 ) + $this->addAddressFields(FALSE);
341
342 $this->_groupFilter = TRUE;
343 $this->_tagFilter = TRUE;
344
345 // Don't show Batch display column and filter unless batches are being used
346 $this->_allBatches = CRM_Batch_BAO_Batch::getBatches();
347 if (!empty($this->_allBatches)) {
348 $this->_columns['civicrm_batch']['dao'] = 'CRM_Batch_DAO_Batch';
349 $this->_columns['civicrm_batch']['fields']['batch_id'] = array(
350 'name' => 'id',
351 'title' => ts('Batch Name'),
352 );
353 $this->_columns['civicrm_batch']['filters']['bid'] = array(
354 'name' => 'id',
355 'title' => ts('Batch Name'),
356 'type' => CRM_Utils_Type::T_INT,
357 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
358 'options' => $this->_allBatches,
359 );
360 $this->_columns['civicrm_entity_batch']['dao'] = 'CRM_Batch_DAO_EntityBatch';
361 $this->_columns['civicrm_entity_batch']['fields']['entity_batch_id'] = array(
362 'name' => 'batch_id',
363 'default' => TRUE,
364 'no_display' => TRUE,
365 );
366 }
367
368 // If we have active campaigns add those elements to both the fields and filters
369 if ($campaignEnabled && !empty($this->activeCampaigns)) {
370 $this->_columns['civicrm_contribution']['fields']['campaign_id'] = array(
371 'title' => ts('Campaign'),
372 'default' => 'false',
373 );
374 $this->_columns['civicrm_contribution']['filters']['campaign_id'] = array(
375 'title' => ts('Campaign'),
376 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
377 'options' => $this->activeCampaigns,
378 );
379 $this->_columns['civicrm_contribution']['order_bys']['campaign_id'] = array('title' => ts('Campaign'));
380 }
381
382 $this->_currencyColumn = 'civicrm_contribution_currency';
383 parent::__construct();
384 }
385
386 public function preProcess() {
387 parent::preProcess();
388 }
389
390 public function select() {
391 $this->_columnHeaders = array();
392
393 parent::select();
394 //total_amount was affected by sum as it is considered as one of the stat field
395 //so it is been replaced with correct alias, CRM-13833
396 $this->_select = str_replace("sum({$this->_aliases['civicrm_contribution']}.total_amount)", "{$this->_aliases['civicrm_contribution']}.total_amount", $this->_select);
397 }
398
399 public function orderBy() {
400 parent::orderBy();
401
402 // please note this will just add the order-by columns to select query, and not display in column-headers.
403 // This is a solution to not throw fatal errors when there is a column in order-by, not present in select/display columns.
404 foreach ($this->_orderByFields as $orderBy) {
405 if (!array_key_exists($orderBy['name'], $this->_params['fields']) &&
406 empty($orderBy['section']) && (strpos($this->_select, $orderBy['dbAlias']) === FALSE)
407 ) {
408 $this->_select .= ", {$orderBy['dbAlias']} as {$orderBy['tplField']}";
409 }
410 }
411 }
412
413 /**
414 * @param bool $softcredit
415 */
416 public function from($softcredit = FALSE) {
417 $this->_from = "
418 FROM civicrm_contact {$this->_aliases['civicrm_contact']} {$this->_aclFrom}
419 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
420 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND {$this->_aliases['civicrm_contribution']}.is_test = 0";
421 $this->getPermissionedFTQuery($this);
422
423 if (CRM_Utils_Array::value('contribution_or_soft_value', $this->_params) ==
424 'both'
425 ) {
426 $this->_from .= "\n LEFT JOIN civicrm_contribution_soft contribution_soft_civireport
427 ON contribution_soft_civireport.contribution_id = {$this->_aliases['civicrm_contribution']}.id";
428 }
429 elseif (CRM_Utils_Array::value('contribution_or_soft_value', $this->_params) ==
430 'soft_credits_only'
431 ) {
432 $this->_from .= "\n INNER JOIN civicrm_contribution_soft contribution_soft_civireport
433 ON contribution_soft_civireport.contribution_id = {$this->_aliases['civicrm_contribution']}.id";
434 }
435
436 if ($softcredit) {
437 $this->_from = "
438 FROM civireport_contribution_detail_temp1 temp1_civireport
439 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
440 ON temp1_civireport.civicrm_contribution_contribution_id = {$this->_aliases['civicrm_contribution']}.id
441 INNER JOIN civicrm_contribution_soft contribution_soft_civireport
442 ON contribution_soft_civireport.contribution_id = {$this->_aliases['civicrm_contribution']}.id
443 INNER JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
444 ON {$this->_aliases['civicrm_contact']}.id = contribution_soft_civireport.contact_id
445 {$this->_aclFrom}";
446 }
447
448 if (!empty($this->_params['ordinality_value'])) {
449 $this->_from .= "
450 INNER JOIN (SELECT c.id, IF(COUNT(oc.id) = 0, 0, 1) AS ordinality FROM civicrm_contribution c LEFT JOIN civicrm_contribution oc ON c.contact_id = oc.contact_id AND oc.receive_date < c.receive_date GROUP BY c.id) {$this->_aliases['civicrm_contribution_ordinality']}
451 ON {$this->_aliases['civicrm_contribution_ordinality']}.id = {$this->_aliases['civicrm_contribution']}.id";
452 }
453
454 $this->addPhoneFromClause();
455
456 if ($this->_addressField OR
457 (!empty($this->_params['state_province_id_value']) OR
458 !empty($this->_params['country_id_value']))
459 ) {
460 $this->_from .= "
461 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
462 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id AND
463 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
464 }
465
466 if ($this->_emailField) {
467 $this->_from .= "
468 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
469 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
470 {$this->_aliases['civicrm_email']}.is_primary = 1\n";
471 }
472 // include contribution note
473 if (!empty($this->_params['fields']['contribution_note']) ||
474 !empty($this->_params['note_value'])
475 ) {
476 $this->_from .= "
477 LEFT JOIN civicrm_note {$this->_aliases['civicrm_note']}
478 ON ( {$this->_aliases['civicrm_note']}.entity_table = 'civicrm_contribution' AND
479 {$this->_aliases['civicrm_contribution']}.id = {$this->_aliases['civicrm_note']}.entity_id )";
480 }
481 //for contribution batches
482 if ($this->_allBatches &&
483 (!empty($this->_params['fields']['batch_id']) ||
484 !empty($this->_params['bid_value']))
485 ) {
486 $this->_from .= "
487 LEFT JOIN (
488 SELECT entity_id, financial_trxn_id
489 FROM civicrm_entity_financial_trxn
490 WHERE entity_table = 'civicrm_contribution'
491 GROUP BY entity_id
492 ) tx ON tx.entity_id = {$this->_aliases['civicrm_contribution']}.id
493 LEFT JOIN civicrm_entity_batch {$this->_aliases['civicrm_entity_batch']}
494 ON ({$this->_aliases['civicrm_entity_batch']}.entity_id = tx.financial_trxn_id
495 AND {$this->_aliases['civicrm_entity_batch']}.entity_table = 'civicrm_financial_trxn')
496 LEFT JOIN civicrm_batch {$this->_aliases['civicrm_batch']}
497 ON {$this->_aliases['civicrm_batch']}.id = {$this->_aliases['civicrm_entity_batch']}.batch_id";
498 }
499 }
500
501 public function groupBy() {
502 $this->_groupBy = " GROUP BY {$this->_aliases['civicrm_contact']}.id, {$this->_aliases['civicrm_contribution']}.id ";
503 }
504
505 /**
506 * @param $rows
507 *
508 * @return array
509 */
510 public function statistics(&$rows) {
511 $statistics = parent::statistics($rows);
512
513 $totalAmount = $average = $fees = $net = array();
514 $count = 0;
515 $select = "
516 SELECT COUNT({$this->_aliases['civicrm_contribution']}.total_amount ) as count,
517 SUM( {$this->_aliases['civicrm_contribution']}.total_amount ) as amount,
518 ROUND(AVG({$this->_aliases['civicrm_contribution']}.total_amount), 2) as avg,
519 {$this->_aliases['civicrm_contribution']}.currency as currency,
520 SUM( {$this->_aliases['civicrm_contribution']}.fee_amount ) as fees,
521 SUM( {$this->_aliases['civicrm_contribution']}.net_amount ) as net
522 ";
523
524 $group = "\nGROUP BY {$this->_aliases['civicrm_contribution']}.currency";
525 $sql = "{$select} {$this->_from} {$this->_where} {$group}";
526 $dao = CRM_Core_DAO::executeQuery($sql);
527
528 while ($dao->fetch()) {
529 $totalAmount[] = CRM_Utils_Money::format($dao->amount, $dao->currency) . " (" . $dao->count . ")";
530 $fees[] = CRM_Utils_Money::format($dao->fees, $dao->currency);
531 $net[] = CRM_Utils_Money::format($dao->net, $dao->currency);
532 $average[] = CRM_Utils_Money::format($dao->avg, $dao->currency);
533 $count += $dao->count;
534 }
535 $statistics['counts']['amount'] = array(
536 'title' => ts('Total Amount (Contributions)'),
537 'value' => implode(', ', $totalAmount),
538 'type' => CRM_Utils_Type::T_STRING,
539 );
540 $statistics['counts']['count'] = array(
541 'title' => ts('Total Contributions'),
542 'value' => $count,
543 );
544 $statistics['counts']['fees'] = array(
545 'title' => ts('Fees'),
546 'value' => implode(', ', $fees),
547 'type' => CRM_Utils_Type::T_STRING,
548 );
549 $statistics['counts']['net'] = array(
550 'title' => ts('Net'),
551 'value' => implode(', ', $net),
552 'type' => CRM_Utils_Type::T_STRING,
553 );
554 $statistics['counts']['avg'] = array(
555 'title' => ts('Average'),
556 'value' => implode(', ', $average),
557 'type' => CRM_Utils_Type::T_STRING,
558 );
559
560 // Stats for soft credits
561 if ($this->_softFrom &&
562 CRM_Utils_Array::value('contribution_or_soft_value', $this->_params) !=
563 'contributions_only'
564 ) {
565 $totalAmount = $average = array();
566 $count = 0;
567 $select = "
568 SELECT COUNT(contribution_soft_civireport.amount ) as count,
569 SUM(contribution_soft_civireport.amount ) as amount,
570 ROUND(AVG(contribution_soft_civireport.amount), 2) as avg,
571 {$this->_aliases['civicrm_contribution']}.currency as currency";
572 $sql = "
573 {$select}
574 {$this->_softFrom}
575 GROUP BY {$this->_aliases['civicrm_contribution']}.currency";
576 $dao = CRM_Core_DAO::executeQuery($sql);
577 while ($dao->fetch()) {
578 $totalAmount[] = CRM_Utils_Money::format($dao->amount, $dao->currency) . " (" .
579 $dao->count . ")";
580 $average[] = CRM_Utils_Money::format($dao->avg, $dao->currency);
581 $count += $dao->count;
582 }
583 $statistics['counts']['softamount'] = array(
584 'title' => ts('Total Amount (Soft Credits)'),
585 'value' => implode(', ', $totalAmount),
586 'type' => CRM_Utils_Type::T_STRING,
587 );
588 $statistics['counts']['softcount'] = array(
589 'title' => ts('Total Soft Credits'),
590 'value' => $count,
591 );
592 $statistics['counts']['softavg'] = array(
593 'title' => ts('Average (Soft Credits)'),
594 'value' => implode(', ', $average),
595 'type' => CRM_Utils_Type::T_STRING,
596 );
597 }
598
599 return $statistics;
600 }
601
602 public function postProcess() {
603 // get the acl clauses built before we assemble the query
604 $this->buildACLClause($this->_aliases['civicrm_contact']);
605
606 $this->beginPostProcess();
607
608 if (CRM_Utils_Array::value('contribution_or_soft_value', $this->_params) ==
609 'contributions_only' &&
610 !empty($this->_params['fields']['soft_credit_type_id'])
611 ) {
612 unset($this->_params['fields']['soft_credit_type_id']);
613 if (!empty($this->_params['soft_credit_type_id_value'])) {
614 $this->_params['soft_credit_type_id_value'] = array();
615 }
616 }
617
618 // 1. use main contribution query to build temp table 1
619 $sql = $this->buildQuery();
620 $tempQuery = 'CREATE TEMPORARY TABLE civireport_contribution_detail_temp1 AS ' . $sql;
621 CRM_Core_DAO::executeQuery($tempQuery);
622 $this->setPager();
623
624 // 2. customize main contribution query for soft credit, and build temp table 2 with soft credit contributions only
625 $this->from(TRUE);
626 // also include custom group from if included
627 // since this might be included in select
628 $this->customDataFrom();
629
630 $select = str_ireplace('contribution_civireport.total_amount', 'contribution_soft_civireport.amount', $this->_select);
631 $select = str_ireplace("'Contribution' as", "'Soft Credit' as", $select);
632 // we inner join with temp1 to restrict soft contributions to those in temp1 table
633 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy}";
634 $tempQuery = 'CREATE TEMPORARY TABLE civireport_contribution_detail_temp2 AS ' . $sql;
635 CRM_Core_DAO::executeQuery($tempQuery);
636 if (CRM_Utils_Array::value('contribution_or_soft_value', $this->_params) ==
637 'soft_credits_only'
638 ) {
639 // revise pager : prev, next based on soft-credits only
640 $this->setPager();
641 }
642
643 // copy _from for later use of stats calculation for soft credits, and reset $this->_from to main query
644 $this->_softFrom = $this->_from;
645
646 // simple reset of ->_from
647 $this->from();
648
649 // also include custom group from if included
650 // since this might be included in select
651 $this->customDataFrom();
652
653 // 3. Decide where to populate temp3 table from
654 if (CRM_Utils_Array::value('contribution_or_soft_value', $this->_params) ==
655 'contributions_only'
656 ) {
657 $tempQuery = "(SELECT * FROM civireport_contribution_detail_temp1)";
658 }
659 elseif (CRM_Utils_Array::value('contribution_or_soft_value', $this->_params) ==
660 'soft_credits_only'
661 ) {
662 $tempQuery = "(SELECT * FROM civireport_contribution_detail_temp2)";
663 }
664 else {
665 $tempQuery = "
666 (SELECT * FROM civireport_contribution_detail_temp1)
667 UNION ALL
668 (SELECT * FROM civireport_contribution_detail_temp2)";
669 }
670
671 // 4. build temp table 3
672 $sql = "CREATE TEMPORARY TABLE civireport_contribution_detail_temp3 AS {$tempQuery}";
673 CRM_Core_DAO::executeQuery($sql);
674
675 // 5. Re-construct order-by to make sense for final query on temp3 table
676 $orderBy = '';
677 if (!empty($this->_orderByArray)) {
678 $aliases = array_flip($this->_aliases);
679 $orderClause = array();
680 foreach ($this->_orderByArray as $clause) {
681 list($alias, $rest) = explode('.', $clause);
682 // CRM-17280 -- In case, we are ordering by custom fields
683 // modify $rest to match the alias used for them in temp3 table
684 $grp = new CRM_Core_DAO_CustomGroup();
685 $grp->table_name = $aliases[$alias];
686 if ($grp->find()) {
687 list($fld, $order) = explode(' ', $rest);
688 foreach ($this->_columns[$aliases[$alias]]['fields'] as $fldName => $value) {
689 if ($value['name'] == $fld) {
690 $fld = $fldName;
691 }
692 }
693 $rest = "{$fld} {$order}";
694 }
695 $orderClause[] = $aliases[$alias] . "_" . $rest;
696 }
697 $orderBy = (!empty($orderClause)) ? "ORDER BY " . implode(', ', $orderClause) : '';
698 }
699
700 // 6. show result set from temp table 3
701 $rows = array();
702 $sql = "SELECT * FROM civireport_contribution_detail_temp3 {$orderBy}";
703 $this->buildRows($sql, $rows);
704
705 // format result set.
706 $this->formatDisplay($rows, FALSE);
707
708 // assign variables to templates
709 $this->doTemplateAssignment($rows);
710
711 // do print / pdf / instance stuff if needed
712 $this->endPostProcess($rows);
713 }
714
715 /**
716 * Alter display of rows.
717 *
718 * Iterate through the rows retrieved via SQL and make changes for display purposes,
719 * such as rendering contacts as links.
720 *
721 * @param array $rows
722 * Rows generated by SQL, with an array for each row.
723 */
724 public function alterDisplay(&$rows) {
725 $checkList = array();
726 $entryFound = FALSE;
727 $display_flag = $prev_cid = $cid = 0;
728 $contributionTypes = CRM_Contribute_PseudoConstant::financialType();
729 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
730 $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument();
731 $contributionPages = CRM_Contribute_PseudoConstant::contributionPage();
732
733 foreach ($rows as $rowNum => $row) {
734 if (!empty($this->_noRepeats) && $this->_outputMode != 'csv') {
735 // don't repeat contact details if its same as the previous row
736 if (array_key_exists('civicrm_contact_id', $row)) {
737 if ($cid = $row['civicrm_contact_id']) {
738 if ($rowNum == 0) {
739 $prev_cid = $cid;
740 }
741 else {
742 if ($prev_cid == $cid) {
743 $display_flag = 1;
744 $prev_cid = $cid;
745 }
746 else {
747 $display_flag = 0;
748 $prev_cid = $cid;
749 }
750 }
751
752 if ($display_flag) {
753 foreach ($row as $colName => $colVal) {
754 // Hide repeats in no-repeat columns, but not if the field's a section header
755 if (in_array($colName, $this->_noRepeats) &&
756 !array_key_exists($colName, $this->_sections)
757 ) {
758 unset($rows[$rowNum][$colName]);
759 }
760 }
761 }
762 $entryFound = TRUE;
763 }
764 }
765 }
766
767 if (CRM_Utils_Array::value('civicrm_contribution_contribution_or_soft', $rows[$rowNum]) ==
768 'Contribution'
769 ) {
770 unset($rows[$rowNum]['civicrm_contribution_soft_soft_credit_type_id']);
771 }
772
773 // convert donor sort name to link
774 if (array_key_exists('civicrm_contact_sort_name', $row) &&
775 !empty($rows[$rowNum]['civicrm_contact_sort_name']) &&
776 array_key_exists('civicrm_contact_id', $row)
777 ) {
778 $url = CRM_Utils_System::url("civicrm/contact/view",
779 'reset=1&cid=' . $row['civicrm_contact_id'],
780 $this->_absoluteUrl
781 );
782 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
783 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contact Summary for this Contact.");
784 }
785
786 if ($value = CRM_Utils_Array::value('civicrm_contribution_financial_type_id', $row)) {
787 $rows[$rowNum]['civicrm_contribution_financial_type_id'] = $contributionTypes[$value];
788 $entryFound = TRUE;
789 }
790 if ($value = CRM_Utils_Array::value('civicrm_contribution_contribution_status_id', $row)) {
791 $rows[$rowNum]['civicrm_contribution_contribution_status_id'] = $contributionStatus[$value];
792 $entryFound = TRUE;
793 }
794 if ($value = CRM_Utils_Array::value('civicrm_contribution_contribution_page_id', $row)) {
795 $rows[$rowNum]['civicrm_contribution_contribution_page_id'] = $contributionPages[$value];
796 $entryFound = TRUE;
797 }
798 if ($value = CRM_Utils_Array::value('civicrm_contribution_payment_instrument_id', $row)) {
799 $rows[$rowNum]['civicrm_contribution_payment_instrument_id'] = $paymentInstruments[$value];
800 $entryFound = TRUE;
801 }
802 if (array_key_exists('civicrm_batch_batch_id', $row)) {
803 if ($value = $row['civicrm_batch_batch_id']) {
804 $rows[$rowNum]['civicrm_batch_batch_id'] = CRM_Core_DAO::getFieldValue('CRM_Batch_DAO_Batch', $value, 'title');
805 }
806 $entryFound = TRUE;
807 }
808
809 // Contribution amount links to viewing contribution
810 if (($value = CRM_Utils_Array::value('civicrm_contribution_total_amount_sum', $row)) &&
811 CRM_Core_Permission::check('access CiviContribute')
812 ) {
813 $url = CRM_Utils_System::url("civicrm/contact/view/contribution",
814 "reset=1&id=" . $row['civicrm_contribution_contribution_id'] .
815 "&cid=" . $row['civicrm_contact_id'] .
816 "&action=view&context=contribution&selectedChild=contribute",
817 $this->_absoluteUrl
818 );
819 $rows[$rowNum]['civicrm_contribution_total_amount_sum_link'] = $url;
820 $rows[$rowNum]['civicrm_contribution_total_amount_sum_hover'] = ts("View Details of this Contribution.");
821 $entryFound = TRUE;
822 }
823
824 // convert campaign_id to campaign title
825 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
826 if ($value = $row['civicrm_contribution_campaign_id']) {
827 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns[$value];
828 $entryFound = TRUE;
829 }
830 }
831
832 // soft credits
833 if (array_key_exists('civicrm_contribution_soft_credits', $row) &&
834 'Contribution' ==
835 CRM_Utils_Array::value('civicrm_contribution_contribution_or_soft', $rows[$rowNum]) &&
836 array_key_exists('civicrm_contribution_contribution_id', $row)
837 ) {
838 $query = "
839 SELECT civicrm_contact_id, civicrm_contact_sort_name, civicrm_contribution_total_amount_sum, civicrm_contribution_currency
840 FROM civireport_contribution_detail_temp2
841 WHERE civicrm_contribution_contribution_id={$row['civicrm_contribution_contribution_id']}";
842 $dao = CRM_Core_DAO::executeQuery($query);
843 $string = '';
844 $separator = ($this->_outputMode !== 'csv') ? "<br/>" : ' ';
845 while ($dao->fetch()) {
846 $url = CRM_Utils_System::url("civicrm/contact/view", 'reset=1&cid=' .
847 $dao->civicrm_contact_id);
848 $string = $string . ($string ? $separator : '') .
849 "<a href='{$url}'>{$dao->civicrm_contact_sort_name}</a> " .
850 CRM_Utils_Money::format($dao->civicrm_contribution_total_amount_sum, $dao->civicrm_contribution_currency);
851 }
852 $rows[$rowNum]['civicrm_contribution_soft_credits'] = $string;
853 }
854
855 if (array_key_exists('civicrm_contribution_soft_credit_for', $row) &&
856 'Soft Credit' ==
857 CRM_Utils_Array::value('civicrm_contribution_contribution_or_soft', $rows[$rowNum]) &&
858 array_key_exists('civicrm_contribution_contribution_id', $row)
859 ) {
860 $query = "
861 SELECT civicrm_contact_id, civicrm_contact_sort_name
862 FROM civireport_contribution_detail_temp1
863 WHERE civicrm_contribution_contribution_id={$row['civicrm_contribution_contribution_id']}";
864 $dao = CRM_Core_DAO::executeQuery($query);
865 $string = '';
866 while ($dao->fetch()) {
867 $url = CRM_Utils_System::url("civicrm/contact/view", 'reset=1&cid=' .
868 $dao->civicrm_contact_id);
869 $string = $string .
870 "\n<a href='{$url}'>{$dao->civicrm_contact_sort_name}</a>";
871 }
872 $rows[$rowNum]['civicrm_contribution_soft_credit_for'] = $string;
873 }
874
875 //convert soft_credit_type_id into label
876 if (array_key_exists('civicrm_contribution_soft_soft_credit_type_id', $rows[$rowNum])) {
877 $rows[$rowNum]['civicrm_contribution_soft_soft_credit_type_id'] = CRM_Core_PseudoConstant::getLabel(
878 'CRM_Contribute_BAO_ContributionSoft',
879 'soft_credit_type_id',
880 $row['civicrm_contribution_soft_soft_credit_type_id']
881 );
882 }
883
884 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s) for this ') ? TRUE : $entryFound;
885
886 //handle gender
887 if (array_key_exists('civicrm_contact_gender_id', $row)) {
888 if ($value = $row['civicrm_contact_gender_id']) {
889 $gender = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id');
890 $rows[$rowNum]['civicrm_contact_gender_id'] = $gender[$value];
891 }
892 $entryFound = TRUE;
893 }
894
895 // display birthday in the configured custom format
896 if (array_key_exists('civicrm_contact_birth_date', $row)) {
897 $birthDate = $row['civicrm_contact_birth_date'];
898 if ($birthDate) {
899 $rows[$rowNum]['civicrm_contact_birth_date'] = CRM_Utils_Date::customFormat($birthDate, '%Y%m%d');
900 }
901 $entryFound = TRUE;
902 }
903
904 // skip looking further in rows, if first row itself doesn't
905 // have the column we need
906 if (!$entryFound) {
907 break;
908 }
909 $lastKey = $rowNum;
910 }
911 }
912
913 public function sectionTotals() {
914
915 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
916 if (empty($this->_selectAliases)) {
917 return;
918 }
919
920 if (!empty($this->_sections)) {
921 // build the query with no LIMIT clause
922 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select);
923 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
924
925 // pull section aliases out of $this->_sections
926 $sectionAliases = array_keys($this->_sections);
927
928 $ifnulls = array();
929 foreach (array_merge($sectionAliases, $this->_selectAliases) as $alias) {
930 $ifnulls[] = "ifnull($alias, '') as $alias";
931 }
932
933 /* Group (un-limited) report by all aliases and get counts. This might
934 * be done more efficiently when the contents of $sql are known, ie. by
935 * overriding this method in the report class.
936 */
937
938 $addtotals = '';
939
940 if (array_search("civicrm_contribution_total_amount_sum", $this->_selectAliases) !==
941 FALSE
942 ) {
943 $addtotals = ", sum(civicrm_contribution_total_amount_sum) as sumcontribs";
944 $showsumcontribs = TRUE;
945 }
946
947 $query = "select "
948 . implode(", ", $ifnulls)
949 .
950 "$addtotals, count(*) as ct from civireport_contribution_detail_temp3 group by " .
951 implode(", ", $sectionAliases);
952 // initialize array of total counts
953 $sumcontribs = $totals = array();
954 $dao = CRM_Core_DAO::executeQuery($query);
955 while ($dao->fetch()) {
956
957 // let $this->_alterDisplay translate any integer ids to human-readable values.
958 $rows[0] = $dao->toArray();
959 $this->alterDisplay($rows);
960 $row = $rows[0];
961
962 // add totals for all permutations of section values
963 $values = array();
964 $i = 1;
965 $aliasCount = count($sectionAliases);
966 foreach ($sectionAliases as $alias) {
967 $values[] = $row[$alias];
968 $key = implode(CRM_Core_DAO::VALUE_SEPARATOR, $values);
969 if ($i == $aliasCount) {
970 // the last alias is the lowest-level section header; use count as-is
971 $totals[$key] = $dao->ct;
972 if ($showsumcontribs) {
973 $sumcontribs[$key] = $dao->sumcontribs;
974 }
975 }
976 else {
977 // other aliases are higher level; roll count into their total
978 $totals[$key] = (array_key_exists($key, $totals)) ? $totals[$key] + $dao->ct : $dao->ct;
979 if ($showsumcontribs) {
980 $sumcontribs[$key] = array_key_exists($key, $sumcontribs) ? $sumcontribs[$key] + $dao->sumcontribs : $dao->sumcontribs;
981 }
982 }
983 }
984 }
985 if ($showsumcontribs) {
986 $totalandsum = array();
987 // ts exception to avoid having ts("%1 %2: %3")
988 $title = '%1 contributions / soft-credits: %2';
989
990 if (CRM_Utils_Array::value('contribution_or_soft_value', $this->_params) ==
991 'contributions_only'
992 ) {
993 $title = '%1 contributions: %2';
994 }
995 elseif (CRM_Utils_Array::value('contribution_or_soft_value', $this->_params) ==
996 'soft_credits_only'
997 ) {
998 $title = '%1 soft-credits: %2';
999 }
1000 foreach ($totals as $key => $total) {
1001 $totalandsum[$key] = ts($title, array(
1002 1 => $total,
1003 2 => CRM_Utils_Money::format($sumcontribs[$key]),
1004 ));
1005 }
1006 $this->assign('sectionTotals', $totalandsum);
1007 }
1008 else {
1009 $this->assign('sectionTotals', $totals);
1010 }
1011 }
1012 }
1013
1014 }