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