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