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