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