Merge pull request #141 from pradpnayak/CRM-12065
[civicrm-core.git] / CRM / Report / Form / Member / ContributionDetail.php
1 <?php
2 // $Id$
3
4 /*
5 +--------------------------------------------------------------------+
6 | CiviCRM version 4.3 |
7 +--------------------------------------------------------------------+
8 | Copyright CiviCRM LLC (c) 2004-2013 |
9 +--------------------------------------------------------------------+
10 | This file is a part of CiviCRM. |
11 | |
12 | CiviCRM is free software; you can copy, modify, and distribute it |
13 | under the terms of the GNU Affero General Public License |
14 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
15 | |
16 | CiviCRM is distributed in the hope that it will be useful, but |
17 | WITHOUT ANY WARRANTY; without even the implied warranty of |
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
19 | See the GNU Affero General Public License for more details. |
20 | |
21 | You should have received a copy of the GNU Affero General Public |
22 | License and the CiviCRM Licensing Exception along |
23 | with this program; if not, contact CiviCRM LLC |
24 | at info[AT]civicrm[DOT]org. If you have questions about the |
25 | GNU Affero General Public License or the licensing of CiviCRM, |
26 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
27 +--------------------------------------------------------------------+
28 */
29
30 /**
31 *
32 * @package CRM
33 * @copyright CiviCRM LLC (c) 2004-2013
34 * $Id$
35 *
36 */
37 class CRM_Report_Form_Member_ContributionDetail extends CRM_Report_Form {
38 protected $_addressField = FALSE;
39
40 protected $_emailField = FALSE;
41 protected $_emailFieldHonor = FALSE;
42
43 protected $_nameFieldHonor = FALSE;
44
45 protected $_summary = NULL;
46
47 protected $_customGroupExtends = array(
48 'Contribution', 'Membership');
49
50 function __construct() {
51 $config = CRM_Core_Config::singleton();
52 $campaignEnabled = in_array("CiviCampaign", $config->enableComponents);
53 if ($campaignEnabled) {
54 $getCampaigns = CRM_Campaign_BAO_Campaign::getPermissionedCampaigns(NULL, NULL, TRUE, FALSE, TRUE);
55 $this->activeCampaigns = $getCampaigns['campaigns'];
56 asort($this->activeCampaigns);
57 }
58 $this->_columns = array(
59 'civicrm_contact' =>
60 array(
61 'dao' => 'CRM_Contact_DAO_Contact',
62 'fields' =>
63 array(
64 'sort_name' =>
65 array('title' => ts('Donor Name'),
66 'required' => TRUE,
67 'no_repeat' => TRUE,
68 ),
69 'first_name' =>
70 array('title' => ts('First Name'),
71 'no_repeat' => TRUE,
72 ),
73 'last_name' =>
74 array('title' => ts('Last Name'),
75 'no_repeat' => TRUE,
76 ),
77 'contact_type' =>
78 array('title' => ts('Contact Type'),
79 'no_repeat' => TRUE,
80 ),
81 'do_not_email' =>
82 array('title' => ts('Do Not Email'),
83 'no_repeat' => TRUE,
84 ),
85 'is_opt_out' =>
86 array('title' => ts('No Bulk Email(Is Opt Out)'),
87 'no_repeat' => TRUE,
88 ),
89 'id' =>
90 array(
91 'no_display' => TRUE,
92 'required' => TRUE,
93 'csv_display' => TRUE,
94 'title' => ts('Contact ID'),
95 ),
96 ),
97 'filters' =>
98 array(
99 'sort_name' =>
100 array('title' => ts('Donor Name'),
101 'operator' => 'like',
102 ),
103 'id' =>
104 array('title' => ts('Contact ID'),
105 'no_display' => TRUE,
106 ),
107 ),
108 'grouping' => 'contact-fields',
109 ),
110 'civicrm_email' =>
111 array(
112 'dao' => 'CRM_Core_DAO_Email',
113 'fields' =>
114 array(
115 'email' =>
116 array('title' => ts('Donor Email'),
117 'default' => TRUE,
118 'no_repeat' => TRUE,
119 ),
120 ),
121 'grouping' => 'contact-fields',
122 ),
123 'civicrm_phone' =>
124 array(
125 'dao' => 'CRM_Core_DAO_Phone',
126 'fields' =>
127 array(
128 'phone' =>
129 array('title' => ts('Donor Phone'),
130 'default' => TRUE,
131 'no_repeat' => TRUE,
132 ),
133 ),
134 'grouping' => 'contact-fields',
135 ),
136 'civicrm_contact_honor' =>
137 array(
138 'dao' => 'CRM_Contact_DAO_Contact',
139 'fields' =>
140 array(
141 'sort_name_honor' =>
142 array('title' => ts('Honoree Name'),
143 'name' => 'sort_name',
144 'alias' => 'contacthonor',
145 'default' => FALSE,
146 'no_repeat' => TRUE,
147 ),
148 'id_honor' =>
149 array(
150 'no_display' => TRUE,
151 'title' => ts('Honoree ID'),
152 'name' => 'id',
153 'alias' => 'contacthonor',
154 'required' => TRUE,
155 ),
156 ),
157 ),
158 'civicrm_email_honor' =>
159 array(
160 'dao' => 'CRM_Core_DAO_Email',
161 'fields' =>
162 array(
163 'email_honor' =>
164 array('title' => ts('Honoree Email'),
165 'name' => 'email',
166 'alias' => 'emailhonor',
167 'default' => FALSE,
168 'no_repeat' => TRUE,
169 ),
170 ),
171 'grouping' => 'contact-fields',
172 ),
173 'first_donation' => array(
174 'dao' => 'CRM_Contribute_DAO_Contribution',
175 'fields' =>
176 array(
177 'first_donation_date' => array(
178 'title' => ts('First Contribution Date'),
179 'base_field' => 'receive_date',
180 'no_repeat' => TRUE,
181 ),
182 'first_donation_amount' => array(
183 'title' => ts('First Contribution Amount'),
184 'base_field' => 'total_amount',
185 'no_repeat' => TRUE,
186 ),
187 ),
188 ),
189 'civicrm_contribution' =>
190 array(
191 'dao' => 'CRM_Contribute_DAO_Contribution',
192 'fields' =>
193 array(
194 'contribution_id' => array(
195 'name' => 'id',
196 'no_display' => TRUE,
197 'required' => TRUE,
198 'csv_display' => TRUE,
199 'title' => ts('Contribution ID'),
200 ),
201 'financial_type_id' => array('title' => ts('Financial Type'),
202 'default' => TRUE,
203 ),
204 'contribution_recur_id' => array('title' => ts('Recurring Contribution Id'),
205 'name' => 'contribution_recur_id',
206 'required' => TRUE,
207 'no_display' => TRUE,
208 'csv_display' => TRUE,
209 ),
210 'contribution_status_id' => array('title' => ts('Contribution Status'),
211 ),
212 'payment_instrument_id' => array('title' => ts('Payment Type'),
213 ),
214 'contribution_source' => array(
215 'name' => 'source',
216 'title' => ts('Contribution Source'),
217 ),
218 'trxn_id' => NULL,
219 'receive_date' => array('default' => TRUE),
220 'receipt_date' => NULL,
221 'honor_type_id' => array('title' => ts('Honor Type'),
222 'default' => FALSE,
223 ),
224 'fee_amount' => NULL,
225 'net_amount' => NULL,
226 'total_amount' => array('title' => ts('Amount'),
227 'required' => TRUE,
228 ),
229 ),
230 'filters' =>
231 array(
232 'receive_date' =>
233 array('operatorType' => CRM_Report_Form::OP_DATE),
234 'financial_type_id' =>
235 array('title' => ts('Financial Type'),
236 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
237 'options' => CRM_Contribute_PseudoConstant::financialType(),
238 ),
239 'payment_instrument_id' =>
240 array('title' => ts('Payment Type'),
241 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
242 'options' => CRM_Contribute_PseudoConstant::paymentInstrument(),
243 ),
244 'contribution_status_id' =>
245 array('title' => ts('Contribution Status'),
246 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
247 'options' => CRM_Contribute_PseudoConstant::contributionStatus(),
248 'default' => array(1),
249 ),
250 'total_amount' =>
251 array('title' => ts('Contribution Amount')),
252 ),
253 'grouping' => 'contri-fields',
254 ),
255 'civicrm_product' =>
256 array(
257 'dao' => 'CRM_Contribute_DAO_Product',
258 'fields' =>
259 array(
260 'product_name' => array(
261 'name' => 'name',
262 'title' => ts('Premium'),
263 ),
264 ),
265 ),
266 'civicrm_contribution_product' =>
267 array(
268 'dao' => 'CRM_Contribute_DAO_ContributionProduct',
269 'fields' =>
270 array(
271 'product_id' => array(
272 'no_display' => TRUE,
273 ),
274 'product_option' => array(
275 'title' => ts('Premium Option'),
276 ),
277 'contribution_id' => array(
278 'no_display' => TRUE,
279 ),
280 ),
281 ),
282 'civicrm_group' =>
283 array(
284 'dao' => 'CRM_Contact_DAO_GroupContact',
285 'alias' => 'cgroup',
286 'filters' =>
287 array(
288 'gid' =>
289 array(
290 'name' => 'group_id',
291 'title' => ts('Group'),
292 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
293 'group' => TRUE,
294 'options' => CRM_Core_PseudoConstant::group(),
295 ),
296 ),
297 ),
298 'civicrm_contribution_ordinality' =>
299 array(
300 'dao' => 'CRM_Contribute_DAO_Contribution',
301 'alias' => 'cordinality',
302 'filters' =>
303 array(
304 'ordinality' =>
305 array('title' => ts('Contribution Ordinality'),
306 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
307 'options' => array(
308 0 => 'First by Contributor',
309 1 => 'Second or Later by Contributor',
310 ),
311 ),
312 ),
313 ),
314 'civicrm_membership' =>
315 array(
316 'dao' => 'CRM_Member_DAO_Membership',
317 'fields' =>
318 array(
319 'membership_type_id' => array('title' => ts('Membership Type'),
320 'required' => TRUE,
321 'no_repeat' => TRUE,
322 ),
323 'membership_start_date' => array('title' => ts('Start Date'),
324 'default' => TRUE,
325 ),
326 'membership_end_date' => array('title' => ts('End Date'),
327 'default' => TRUE,
328 ),
329 'join_date' => array('title' => ts('Join Date'),
330 'default' => TRUE,
331 ),
332 'source' => array('title' => ts('Membership Source')),
333 ),
334 'filters' => array(
335 'join_date' =>
336 array('operatorType' => CRM_Report_Form::OP_DATE),
337 'membership_start_date' =>
338 array('operatorType' => CRM_Report_Form::OP_DATE),
339 'membership_end_date' =>
340 array('operatorType' => CRM_Report_Form::OP_DATE),
341 'owner_membership_id' =>
342 array('title' => ts('Membership Owner ID'),
343 'operatorType' => CRM_Report_Form::OP_INT,
344 ),
345 'tid' =>
346 array(
347 'name' => 'membership_type_id',
348 'title' => ts('Membership Types'),
349 'type' => CRM_Utils_Type::T_INT,
350 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
351 'options' => CRM_Member_PseudoConstant::membershipType(),
352 ),
353 ),
354 'grouping' => 'member-fields',
355 ),
356 'civicrm_membership_status' =>
357 array(
358 'dao' => 'CRM_Member_DAO_MembershipStatus',
359 'alias' => 'mem_status',
360 'fields' =>
361 array(
362 'membership_status_name' =>
363 array(
364 'name' => 'name',
365 'title' => ts('Membership Status'),
366 'default' => TRUE,
367 ),
368 ),
369 'filters' => array(
370 'sid' =>
371 array(
372 'name' => 'id',
373 'title' => ts('Membership Status'),
374 'type' => CRM_Utils_Type::T_INT,
375 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
376 'options' => CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'label'),
377 ),
378 ),
379 'grouping' => 'member-fields',
380 ),
381 'civicrm_note' =>
382 array(
383 'dao' => 'CRM_Core_DAO_Note',
384 'fields' =>
385 array(
386 'contribution_note' =>
387 array(
388 'name' => 'note',
389 'title' => ts('Contribution Note'),
390 ),
391 ),
392 'filters' =>
393 array(
394 'note' =>
395 array(
396 'name' => 'note',
397 'title' => ts('Contribution Note'),
398 'operator' => 'like',
399 'type' => CRM_Utils_Type::T_STRING,
400 ),
401 ),
402 ),
403 ) + $this->addAddressFields(FALSE);
404
405 $this->_tagFilter = TRUE;
406
407 // Don't show Batch display column and filter unless batches are being used
408 $this->_closedBatches = CRM_Batch_BAO_Batch::getBatches();
409 if (!empty($this->_closedBatches)) {
410 $this->_columns['civicrm_batch']['dao'] = 'CRM_Batch_DAO_Batch';
411 $this->_columns['civicrm_batch']['fields']['batch_id'] = array(
412 'name' => 'id',
413 'title' => ts('Batch Name'),
414 );
415 $this->_columns['civicrm_batch']['filters']['bid'] = array(
416 'name' => 'id',
417 'title' => ts('Batch Name'),
418 'type' => CRM_Utils_Type::T_INT,
419 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
420 'options' => $this->_closedBatches,
421 );
422 $this->_columns['civicrm_entity_batch']['dao'] = 'CRM_Batch_DAO_EntityBatch';
423 $this->_columns['civicrm_entity_batch']['fields']['entity_batch_id'] = array(
424 'name' => 'batch_id',
425 'default' => TRUE,
426 'no_display' => TRUE,
427 );
428 }
429
430 if ($campaignEnabled && !empty($this->activeCampaigns)) {
431 $this->_columns['civicrm_contribution']['fields']['campaign_id'] = array(
432 'title' => ts('Campaign'),
433 'default' => 'false',
434 );
435 $this->_columns['civicrm_contribution']['filters']['campaign_id'] = array('title' => ts('Campaign'),
436 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
437 'options' => $this->activeCampaigns,
438 );
439 $this->_columns['civicrm_contribution']['order_bys']['campaign_id'] = array('title' => ts('Campaign'));
440 }
441
442
443 parent::__construct();
444 }
445
446 function preProcess() {
447 parent::preProcess();
448 }
449
450 function select() {
451 $select = array();
452
453 $this->_columnHeaders = array();
454 foreach ($this->_columns as $tableName => $table) {
455 if (array_key_exists('fields', $table)) {
456 foreach ($table['fields'] as $fieldName => $field) {
457 if (CRM_Utils_Array::value('required', $field) ||
458 CRM_Utils_Array::value($fieldName, $this->_params['fields'])
459 ) {
460 if ($tableName == 'civicrm_address') {
461 $this->_addressField = TRUE;
462 }
463 if ($tableName == 'civicrm_email') {
464 $this->_emailField = TRUE;
465 }
466 elseif ($tableName == 'civicrm_email_honor') {
467 $this->_emailFieldHonor = TRUE;
468 }
469
470 if ($tableName == 'civicrm_contact_honor') {
471 $this->_nameFieldHonor = TRUE;
472 }
473
474 // only include statistics columns if set
475 if (CRM_Utils_Array::value('statistics', $field)) {
476 foreach ($field['statistics'] as $stat => $label) {
477 switch (strtolower($stat)) {
478 case 'sum':
479 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
480 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
481 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
482 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
483 break;
484
485 case 'count':
486 $select[] = "COUNT({$field['dbAlias']}) as {$tableName}_{$fieldName}_{$stat}";
487 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
488 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
489 break;
490
491 case 'avg':
492 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as {$tableName}_{$fieldName}_{$stat}";
493 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
494 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
495 $this->_statFields[] = "{$tableName}_{$fieldName}_{$stat}";
496 break;
497 }
498 }
499 }
500 elseif ($fieldName == 'first_donation_date' || $fieldName == 'first_donation_amount') {
501 $baseField = CRM_Utils_Array::value('base_field', $field);
502 $select[] = "{$this->_aliases['civicrm_contribution']}.{$baseField} as {$tableName}_{$fieldName}";
503 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array::value('title', $field);
504 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
505 }
506 else {
507 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
508
509 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array::value('title', $field);
510 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
511 }
512 }
513 }
514 }
515 }
516
517 $this->_select = "SELECT " . implode(', ', $select) . " ";
518 }
519
520 function from() {
521 $this->_from = "
522 FROM civireport_membership_contribution_detail
523 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
524 ON (civireport_membership_contribution_detail.contribution_id = {$this->_aliases['civicrm_contribution']}.id)
525 LEFT JOIN civicrm_membership {$this->_aliases['civicrm_membership']}
526 ON (civireport_membership_contribution_detail.membership_id = {$this->_aliases['civicrm_membership']}.id)
527 INNER JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
528 ON (civireport_membership_contribution_detail.contact_id = {$this->_aliases['civicrm_contact']}.id)
529 LEFT JOIN civicrm_membership_status {$this->_aliases['civicrm_membership_status']}
530 ON {$this->_aliases['civicrm_membership_status']}.id =
531 {$this->_aliases['civicrm_membership']}.status_id
532 ";
533
534 //for premiums
535 if (CRM_Utils_Array::value('product_name', $this->_params['fields']) || CRM_Utils_Array::value('product_option', $this->_params['fields'])) {
536 $this->_from .= "
537 LEFT JOIN civicrm_contribution_product {$this->_aliases['civicrm_contribution_product']}
538 ON ({$this->_aliases['civicrm_contribution_product']}.contribution_id = {$this->_aliases['civicrm_contribution']}.id)
539 LEFT JOIN civicrm_product {$this->_aliases['civicrm_product']} ON ({$this->_aliases['civicrm_product']}.id = {$this->_aliases['civicrm_contribution_product']}.product_id)";
540 }
541
542 if (!empty($this->_params['ordinality_value'])) {
543 $this->_from .= "
544 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']}
545 ON {$this->_aliases['civicrm_contribution_ordinality']}.id = {$this->_aliases['civicrm_contribution']}.id";
546 }
547
548 // include contribution note
549 if (CRM_Utils_Array::value('contribution_note', $this->_params['fields']) || !empty($this->_params['note_value'])) {
550 $this->_from.= "
551 LEFT JOIN civicrm_note {$this->_aliases['civicrm_note']}
552 ON ( {$this->_aliases['civicrm_note']}.entity_table = 'civicrm_contribution' AND
553 {$this->_aliases['civicrm_contribution']}.id = {$this->_aliases['civicrm_note']}.entity_id )";
554
555 }
556
557 if (CRM_Utils_Array::value('phone', $this->_params['fields'])) {
558 $this->_from .= "
559 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
560 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
561 {$this->_aliases['civicrm_phone']}.is_primary = 1)";
562 }
563 //for contribution batches
564 if ($this->_closedBatches &&
565 (CRM_Utils_Array::value('batch_id', $this->_params['fields']) || !empty($this->_params['bid_value']))) {
566 $this->_from .= "
567 LEFT JOIN civicrm_entity_batch {$this->_aliases['civicrm_entity_batch']}
568 ON ({$this->_aliases['civicrm_entity_batch']}.entity_id = {$this->_aliases['civicrm_contribution']}.id AND
569 {$this->_aliases['civicrm_entity_batch']}.entity_table = 'civicrm_contribution')
570 LEFT JOIN civicrm_batch {$this->_aliases['civicrm_batch']}
571 ON {$this->_aliases['civicrm_batch']}.id = {$this->_aliases['civicrm_entity_batch']}.batch_id";
572 }
573
574 if ($this->_addressField OR (!empty($this->_params['state_province_id_value']) OR !empty($this->_params['country_id_value']))) {
575 $this->_from .= "
576 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
577 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id AND
578 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
579 }
580
581 if ($this->_emailField) {
582 $this->_from .= "
583 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
584 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
585 {$this->_aliases['civicrm_email']}.is_primary = 1\n";
586 }
587
588 // include Honor name field
589 if ($this->_nameFieldHonor) {
590 $this->_from .= "
591 LEFT JOIN civicrm_contact contacthonor
592 ON contacthonor.id = {$this->_aliases['civicrm_contribution']}.honor_contact_id";
593 }
594
595 // include Honor email field
596 if ($this->_emailFieldHonor) {
597 $this->_from .= "
598 LEFT JOIN civicrm_email emailhonor
599 ON emailhonor.contact_id = {$this->_aliases['civicrm_contribution']}.honor_contact_id
600 AND emailhonor.is_primary = 1\n";
601 }
602 }
603
604 function tempTable($applyLimit = TRUE) {
605 // create temp table with contact ids,contribtuion id,membership id
606 $dropTempTable = "DROP TABLE IF EXISTS civireport_membership_contribution_detail";
607 CRM_Core_DAO::executeQuery($dropTempTable);
608
609 $sql = "CREATE TEMPORARY TABLE civireport_membership_contribution_detail
610 (contribution_id int, contact_id int, membership_id int, payment_id int) ENGINE=HEAP";
611 CRM_Core_DAO::executeQuery($sql);
612
613 $fillTemp = "
614 INSERT INTO civireport_membership_contribution_detail (contribution_id, contact_id, membership_id)
615 SELECT contribution.id, contact.id, m.id
616 FROM civicrm_contribution contribution
617 INNER JOIN civicrm_contact contact {$this->_aclFrom}
618 ON contact.id = contribution.contact_id AND contribution.is_test = 0
619 LEFT JOIN civicrm_membership_payment mp
620 ON contribution.id = mp.contribution_id
621 LEFT JOIN civicrm_membership m
622 ON mp.membership_id = m.id AND m.is_test = 0 ";
623
624 CRM_Core_DAO::executeQuery($fillTemp);
625 }
626
627 function buildQuery($applyLimit = TRUE) {
628 $this->select();
629 //create temp table to be used as base table
630 $this->tempTable();
631 $this->from();
632 $this->customDataFrom();
633 $this->where();
634 $this->groupBy();
635 $this->orderBy();
636
637 // order_by columns not selected for display need to be included in SELECT
638 $unselectedSectionColumns = $this->unselectedSectionColumns();
639 foreach ($unselectedSectionColumns as $alias => $section) {
640 $this->_select .= ", {$section['dbAlias']} as {$alias}";
641 }
642
643 if ($applyLimit && !CRM_Utils_Array::value('charts', $this->_params)) {
644 $this->limit();
645 }
646
647 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
648 return $sql;
649 }
650
651 function groupBy() {
652 $this->_groupBy = " GROUP BY {$this->_aliases['civicrm_contact']}.id, {$this->_aliases['civicrm_contribution']}.id ";
653 }
654
655 function orderBy() {
656 $this->_orderBy = " ORDER BY {$this->_aliases['civicrm_contact']}.sort_name, {$this->_aliases['civicrm_contact']}.id ";
657 if (CRM_Utils_Array::value('first_donation_date', $this->_params['fields'])
658 || CRM_Utils_Array::value('first_donation_amount', $this->_params['fields'])) {
659 $this->_orderBy .= ", {$this->_aliases['civicrm_contribution']}.receive_date";
660 }
661 }
662
663 function statistics(&$rows) {
664 $statistics = parent::statistics($rows);
665
666 $select = "
667 SELECT ROUND(AVG({$this->_aliases['civicrm_contribution']}.total_amount), 2) as amt
668 ";
669
670 $groupBy = "
671 GROUP BY contribution_id
672 ";
673
674 $sql = "{$select} {$this->_from} {$this->_where} {$groupBy}";
675
676 $dao = CRM_Core_DAO::executeQuery($sql);
677 $amount = 0;
678 while ($dao->fetch()) {
679 $amount = $amount + $dao->amt;
680 }
681 $statistics['counts']['amount'] = array(
682 'value' => $amount,
683 'title' => 'Total Amount',
684 'type' => CRM_Utils_Type::T_MONEY,
685 );
686
687 $avg = 0;
688 if ($dao->N) {
689 $avg = (float ) $amount / $dao->N;
690 }
691 $statistics['counts']['avg'] = array(
692 'value' => $avg,
693 'title' => 'Average',
694 'type' => CRM_Utils_Type::T_MONEY,
695 );
696
697 return $statistics;
698 }
699
700 function postProcess() {
701 // get the acl clauses built before we assemble the query
702 $this->buildACLClause($this->_aliases['civicrm_contact']);
703 parent::postProcess();
704 }
705
706 function alterDisplay(&$rows) {
707 // custom code to alter rows
708 $checkList = array();
709
710 $entryFound = FALSE;
711 $contributionTypes = CRM_Contribute_PseudoConstant::financialType();
712 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
713 $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument();
714 $honorTypes = CRM_Core_OptionGroup::values('honor_type', FALSE, FALSE, FALSE, NULL, 'label');
715
716 //altering the csv display adding additional fields
717 if ($this->_outputMode == 'csv') {
718 foreach ($this->_columns as $tableName => $table) {
719 if (array_key_exists('fields', $table)) {
720 foreach ($table['fields'] as $fieldName => $field) {
721 if (CRM_Utils_Array::value('csv_display', $field) && CRM_Utils_Array::value('no_display', $field)) {
722 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array::value('title', $field);
723 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
724 }
725 }
726 }
727 }
728 }
729
730 // allow repeat for first donation amount and date in csv
731 $fAmt = '';
732 $fDate = '';
733 foreach ($rows as $rowNum => $row) {
734 if ($this->_outputMode == 'csv') {
735 if (array_key_exists('civicrm_contact_id', $row)) {
736 if ($contactId = $row['civicrm_contact_id']) {
737 if ($rowNum == 0) {
738 $pcid = $contactId;
739 $fAmt = $row['first_donation_first_donation_amount'];
740 $fDate = $row['first_donation_first_donation_date'];
741 }
742 else {
743 if ($pcid == $contactId) {
744 $rows[$rowNum]['first_donation_first_donation_amount'] = $fAmt;
745 $rows[$rowNum]['first_donation_first_donation_date'] = $fDate;
746 $pcid = $contactId;
747 }
748 else {
749 $fAmt = $row['first_donation_first_donation_amount'];
750 $fDate = $row['first_donation_first_donation_date'];
751 $pcid = $contactId;
752 }
753 }
754 }
755 }
756 }
757
758 if (!empty($this->_noRepeats) && $this->_outputMode != 'csv') {
759 $repeatFound = FALSE;
760
761
762 $display_flag = NULL;
763 if (array_key_exists('civicrm_contact_id', $row)) {
764 if ($cid = $row['civicrm_contact_id']) {
765 if ($rowNum == 0) {
766 $prev_cid = $cid;
767 }
768 else {
769 if ($prev_cid == $cid) {
770 $display_flag = 1;
771 $prev_cid = $cid;
772 }
773 else {
774 $display_flag = 0;
775 $prev_cid = $cid;
776 }
777 }
778
779 if ($display_flag) {
780 foreach ($row as $colName => $colVal) {
781 if (in_array($colName, $this->_noRepeats)) {
782 unset($rows[$rowNum][$colName]);
783 }
784 }
785 }
786 $entryFound = TRUE;
787 }
788 }
789 }
790
791
792 if (array_key_exists('civicrm_membership_membership_type_id', $row)) {
793 if ($value = $row['civicrm_membership_membership_type_id']) {
794 $rows[$rowNum]['civicrm_membership_membership_type_id'] = CRM_Member_PseudoConstant::membershipType($value, FALSE);
795 }
796 $entryFound = TRUE;
797 }
798
799 if (array_key_exists('civicrm_batch_batch_id', $row)) {
800 if ($value = $row['civicrm_batch_batch_id']) {
801 $rows[$rowNum]['civicrm_batch_batch_id'] = CRM_Core_DAO::getFieldValue('CRM_Batch_DAO_Batch', $value, 'title');
802 }
803 $entryFound = TRUE;
804 }
805
806 if (array_key_exists('civicrm_address_state_province_id', $row)) {
807 if ($value = $row['civicrm_address_state_province_id']) {
808 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($value, FALSE);
809 }
810 $entryFound = TRUE;
811 }
812
813 if (array_key_exists('civicrm_address_country_id', $row)) {
814 if ($value = $row['civicrm_address_country_id']) {
815 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($value, FALSE);
816 }
817 $entryFound = TRUE;
818 }
819
820 // convert donor sort name to link
821 if (array_key_exists('civicrm_contact_sort_name', $row) &&
822 CRM_Utils_Array::value('civicrm_contact_sort_name', $rows[$rowNum]) &&
823 array_key_exists('civicrm_contact_id', $row)
824 ) {
825 $url = CRM_Utils_System::url("civicrm/contact/view",
826 'reset=1&cid=' . $row['civicrm_contact_id'],
827 $this->_absoluteUrl
828 );
829
830 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
831 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contact Summary for this Contact.");
832 }
833
834 // convert honoree sort name to link
835 if (array_key_exists('civicrm_contact_honor_sort_name_honor', $row) &&
836 CRM_Utils_Array::value('civicrm_contact_honor_sort_name_honor', $rows[$rowNum]) &&
837 array_key_exists('civicrm_contact_honor_id_honor', $row)
838 ) {
839
840 $url = CRM_Utils_System::url("civicrm/contact/view",
841 'reset=1&cid=' . $row['civicrm_contact_honor_id_honor'],
842 $this->_absoluteUrl
843 );
844 $rows[$rowNum]['civicrm_contact_honor_sort_name_honor_link'] = $url;
845 $rows[$rowNum]['civicrm_contact_honor_sort_name_honor_hover'] = ts("View Contact Summary for Honoree.");
846 }
847
848 if ($value = CRM_Utils_Array::value('civicrm_contribution_financial_type_id', $row)) {
849 $rows[$rowNum]['civicrm_contribution_financial_type_id'] = $contributionTypes[$value];
850 $entryFound = TRUE;
851 }
852 if ($value = CRM_Utils_Array::value('civicrm_contribution_contribution_status_id', $row)) {
853 $rows[$rowNum]['civicrm_contribution_contribution_status_id'] = $contributionStatus[$value];
854 $entryFound = TRUE;
855 }
856 if ($value = CRM_Utils_Array::value('civicrm_contribution_payment_instrument_id', $row)) {
857 $rows[$rowNum]['civicrm_contribution_payment_instrument_id'] = $paymentInstruments[$value];
858 $entryFound = TRUE;
859 }
860 if ($value = CRM_Utils_Array::value('civicrm_contribution_honor_type_id', $row)) {
861 $rows[$rowNum]['civicrm_contribution_honor_type_id'] = $honorTypes[$value];
862 $entryFound = TRUE;
863 }
864 if (($value = CRM_Utils_Array::value('civicrm_contribution_total_amount_sum', $row)) &&
865 CRM_Core_Permission::check('access CiviContribute')
866 ) {
867 $url = CRM_Utils_System::url("civicrm/contact/view/contribution",
868 "reset=1&id=" . $row['civicrm_contribution_contribution_id'] . "&cid=" . $row['civicrm_contact_id'] . "&action=view&context=contribution&selectedChild=contribute",
869 $this->_absoluteUrl
870 );
871 $rows[$rowNum]['civicrm_contribution_total_amount_sum_link'] = $url;
872 $rows[$rowNum]['civicrm_contribution_total_amount_sum_hover'] = ts("View Details of this Contribution.");
873 $entryFound = TRUE;
874 }
875
876 // convert campaign_id to campaign title
877 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
878 if ($value = $row['civicrm_contribution_campaign_id']) {
879 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns[$value];
880 $entryFound = TRUE;
881 }
882 }
883
884 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'member/contributionDetail', 'List all contribution(s) for this ') ? TRUE : $entryFound;
885
886 // skip looking further in rows, if first row itself doesn't
887 // have the column we need
888 if (!$entryFound) {
889 break;
890 }
891 $lastKey = $rowNum;
892 }
893 }
894 }
895