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