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