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