3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2018
33 class CRM_Report_Form_Contribute_Detail
extends CRM_Report_Form
{
35 protected $_summary = NULL;
37 protected $_softFrom = NULL;
39 protected $_customGroupExtends = array(
46 * This report has been optimised for group filtering.
52 protected $groupFilterNotOptimised = FALSE;
57 public function __construct() {
58 $this->_autoIncludeIndexedFieldsAsOrderBys
= 1;
59 // Check if CiviCampaign is a) enabled and b) has active campaigns
60 $config = CRM_Core_Config
::singleton();
61 $campaignEnabled = in_array("CiviCampaign", $config->enableComponents
);
62 if ($campaignEnabled) {
63 $getCampaigns = CRM_Campaign_BAO_Campaign
::getPermissionedCampaigns(NULL, NULL, TRUE, FALSE, TRUE);
64 $this->activeCampaigns
= $getCampaigns['campaigns'];
65 asort($this->activeCampaigns
);
68 $this->_columns
= array_merge($this->getColumns('Contact', array(
69 'order_bys_defaults' => array('sort_name' => 'ASC '),
70 'fields_defaults' => array('sort_name'),
71 'fields_excluded' => array('id'),
72 'fields_required' => array('id'),
73 'filters_defaults' => array('is_deleted' => 0),
74 'no_field_disambiguation' => TRUE,
76 'civicrm_email' => array(
77 'dao' => 'CRM_Core_DAO_Email',
80 'title' => ts('Donor Email'),
84 'grouping' => 'contact-fields',
86 'civicrm_line_item' => array(
87 'dao' => 'CRM_Price_DAO_LineItem',
89 'civicrm_phone' => array(
90 'dao' => 'CRM_Core_DAO_Phone',
93 'title' => ts('Donor Phone'),
98 'grouping' => 'contact-fields',
100 'civicrm_contribution' => array(
101 'dao' => 'CRM_Contribute_DAO_Contribution',
103 'contribution_id' => array(
105 'no_display' => TRUE,
108 'list_contri_id' => array(
110 'title' => ts('Contribution ID'),
112 'financial_type_id' => array(
113 'title' => ts('Financial Type'),
116 'contribution_status_id' => array(
117 'title' => ts('Contribution Status'),
119 'contribution_page_id' => array(
120 'title' => ts('Contribution Page'),
123 'title' => ts('Source'),
125 'payment_instrument_id' => array(
126 'title' => ts('Payment Type'),
128 'check_number' => array(
129 'title' => ts('Check Number'),
133 'no_display' => TRUE,
136 'receive_date' => array('default' => TRUE),
137 'receipt_date' => NULL,
138 'total_amount' => array(
139 'title' => ts('Amount'),
141 'statistics' => array('sum' => ts('Amount')),
143 'non_deductible_amount' => array(
144 'title' => ts('Non-deductible Amount'),
146 'fee_amount' => NULL,
147 'net_amount' => NULL,
148 'contribution_or_soft' => array(
149 'title' => ts('Contribution OR Soft Credit?'),
150 'dbAlias' => "'Contribution'",
152 'soft_credits' => array(
153 'title' => ts('Soft Credits'),
156 'soft_credit_for' => array(
157 'title' => ts('Soft Credit For'),
162 'contribution_or_soft' => array(
163 'title' => ts('Contribution OR Soft Credit?'),
165 'operatorType' => CRM_Report_Form
::OP_SELECT
,
166 'type' => CRM_Utils_Type
::T_STRING
,
168 'contributions_only' => ts('Contributions Only'),
169 'soft_credits_only' => ts('Soft Credits Only'),
170 'both' => ts('Both'),
173 'receive_date' => array('operatorType' => CRM_Report_Form
::OP_DATE
),
174 'contribution_source' => array(
175 'title' => ts('Source'),
177 'type' => CRM_Utils_Type
::T_STRING
,
180 'title' => ts('Currency'),
181 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
182 'options' => CRM_Core_OptionGroup
::values('currencies_enabled'),
184 'type' => CRM_Utils_Type
::T_STRING
,
186 'non_deductible_amount' => array(
187 'title' => ts('Non-deductible Amount'),
189 'financial_type_id' => array(
190 'title' => ts('Financial Type'),
191 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
192 'options' => CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes(),
193 'type' => CRM_Utils_Type
::T_INT
,
195 'contribution_page_id' => array(
196 'title' => ts('Contribution Page'),
197 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
198 'options' => CRM_Contribute_PseudoConstant
::contributionPage(),
199 'type' => CRM_Utils_Type
::T_INT
,
201 'payment_instrument_id' => array(
202 'title' => ts('Payment Type'),
203 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
204 'options' => CRM_Contribute_PseudoConstant
::paymentInstrument(),
205 'type' => CRM_Utils_Type
::T_INT
,
207 'contribution_status_id' => array(
208 'title' => ts('Contribution Status'),
209 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
210 'options' => CRM_Contribute_PseudoConstant
::contributionStatus(),
211 'default' => array(1),
212 'type' => CRM_Utils_Type
::T_INT
,
214 'total_amount' => array('title' => ts('Contribution Amount')),
216 'order_bys' => array(
217 'financial_type_id' => array('title' => ts('Financial Type')),
218 'contribution_status_id' => array('title' => ts('Contribution Status')),
219 'payment_instrument_id' => array('title' => ts('Payment Method')),
220 'receive_date' => array('title' => ts('Date Received')),
222 'grouping' => 'contri-fields',
224 'civicrm_contribution_soft' => array(
225 'dao' => 'CRM_Contribute_DAO_ContributionSoft',
227 'soft_credit_type_id' => array('title' => ts('Soft Credit Type')),
230 'soft_credit_type_id' => array(
231 'title' => ts('Soft Credit Type'),
232 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
233 'options' => CRM_Core_OptionGroup
::values('soft_credit_type'),
235 'type' => CRM_Utils_Type
::T_STRING
,
239 'civicrm_financial_trxn' => array(
240 'dao' => 'CRM_Financial_DAO_FinancialTrxn',
242 'card_type_id' => array(
243 'title' => ts('Credit Card Type'),
244 'dbAlias' => 'GROUP_CONCAT(financial_trxn_civireport.card_type_id SEPARATOR ",")',
248 'card_type_id' => array(
249 'title' => ts('Credit Card Type'),
250 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
251 'options' => CRM_Financial_DAO_FinancialTrxn
::buildOptions('card_type_id'),
253 'type' => CRM_Utils_Type
::T_STRING
,
257 'civicrm_batch' => array(
258 'dao' => 'CRM_Batch_DAO_EntityBatch',
259 'grouping' => 'contri-fields',
262 'name' => 'batch_id',
263 'title' => ts('Batch Name'),
268 'title' => ts('Batch Name'),
269 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
270 'options' => CRM_Batch_BAO_Batch
::getBatches(),
271 'type' => CRM_Utils_Type
::T_INT
,
272 'dbAlias' => 'batch_civireport.batch_id',
276 'civicrm_contribution_ordinality' => array(
277 'dao' => 'CRM_Contribute_DAO_Contribution',
278 'alias' => 'cordinality',
280 'ordinality' => array(
281 'title' => ts('Contribution Ordinality'),
282 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
284 0 => 'First by Contributor',
285 1 => 'Second or Later by Contributor',
287 'type' => CRM_Utils_Type
::T_INT
,
291 'civicrm_note' => array(
292 'dao' => 'CRM_Core_DAO_Note',
294 'contribution_note' => array(
296 'title' => ts('Contribution Note'),
302 'title' => ts('Contribution Note'),
303 'operator' => 'like',
304 'type' => CRM_Utils_Type
::T_STRING
,
308 )) +
$this->addAddressFields(FALSE);
309 // The tests test for this variation of the sort_name field. Don't argue with the tests :-).
310 $this->_columns
['civicrm_contact']['fields']['sort_name']['title'] = ts('Donor Name');
311 $this->_groupFilter
= TRUE;
312 $this->_tagFilter
= TRUE;
314 // If we have active campaigns add those elements to both the fields and filters
315 if ($campaignEnabled && !empty($this->activeCampaigns
)) {
316 $this->_columns
['civicrm_contribution']['fields']['campaign_id'] = array(
317 'title' => ts('Campaign'),
318 'default' => 'false',
320 $this->_columns
['civicrm_contribution']['filters']['campaign_id'] = array(
321 'title' => ts('Campaign'),
322 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
323 'options' => $this->activeCampaigns
,
324 'type' => CRM_Utils_Type
::T_INT
,
326 $this->_columns
['civicrm_contribution']['order_bys']['campaign_id'] = array('title' => ts('Campaign'));
329 $this->_currencyColumn
= 'civicrm_contribution_currency';
330 parent
::__construct();
333 public function preProcess() {
334 parent
::preProcess();
337 public function select() {
338 $this->_columnHeaders
= array();
341 //total_amount was affected by sum as it is considered as one of the stat field
342 //so it is been replaced with correct alias, CRM-13833
343 $this->_select
= str_replace("sum({$this->_aliases['civicrm_contribution']}.total_amount)", "{$this->_aliases['civicrm_contribution']}.total_amount", $this->_select
);
344 $this->_selectClauses
= str_replace("sum({$this->_aliases['civicrm_contribution']}.total_amount)", "{$this->_aliases['civicrm_contribution']}.total_amount", $this->_selectClauses
);
347 public function orderBy() {
350 // please note this will just add the order-by columns to select query, and not display in column-headers.
351 // This is a solution to not throw fatal errors when there is a column in order-by, not present in select/display columns.
352 foreach ($this->_orderByFields
as $orderBy) {
353 if (!array_key_exists($orderBy['name'], $this->_params
['fields']) &&
354 empty($orderBy['section']) && (strpos($this->_select
, $orderBy['dbAlias']) === FALSE)
356 $this->_select
.= ", {$orderBy['dbAlias']} as {$orderBy['tplField']}";
362 * Set the FROM clause for the report.
364 public function from() {
365 $this->setFromBase('civicrm_contact');
367 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
368 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id
369 AND {$this->_aliases['civicrm_contribution']}.is_test = 0";
371 if (CRM_Utils_Array
::value('contribution_or_soft_value', $this->_params
) ==
374 $this->_from
.= "\n LEFT JOIN civicrm_contribution_soft contribution_soft_civireport
375 ON contribution_soft_civireport.contribution_id = {$this->_aliases['civicrm_contribution']}.id";
377 elseif (CRM_Utils_Array
::value('contribution_or_soft_value', $this->_params
) ==
380 $this->_from
.= "\n INNER JOIN civicrm_contribution_soft contribution_soft_civireport
381 ON contribution_soft_civireport.contribution_id = {$this->_aliases['civicrm_contribution']}.id";
383 $this->appendAdditionalFromJoins();
386 public function groupBy() {
387 $groupBy = array("{$this->_aliases['civicrm_contact']}.id", "{$this->_aliases['civicrm_contribution']}.id");
388 $this->_groupBy
= CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($this->_selectClauses
, $groupBy);
396 public function statistics(&$rows) {
397 $statistics = parent
::statistics($rows);
399 $totalAmount = $average = $fees = $net = array();
402 SELECT COUNT({$this->_aliases['civicrm_contribution']}.total_amount ) as count,
403 SUM( {$this->_aliases['civicrm_contribution']}.total_amount ) as amount,
404 ROUND(AVG({$this->_aliases['civicrm_contribution']}.total_amount), 2) as avg,
405 {$this->_aliases['civicrm_contribution']}.currency as currency,
406 SUM( {$this->_aliases['civicrm_contribution']}.fee_amount ) as fees,
407 SUM( {$this->_aliases['civicrm_contribution']}.net_amount ) as net
410 $group = "\nGROUP BY {$this->_aliases['civicrm_contribution']}.currency";
411 $sql = "{$select} {$this->_from} {$this->_where} {$group}";
412 $dao = CRM_Core_DAO
::executeQuery($sql);
413 $this->addToDeveloperTab($sql);
415 while ($dao->fetch()) {
416 $totalAmount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
) . " (" . $dao->count
. ")";
417 $fees[] = CRM_Utils_Money
::format($dao->fees
, $dao->currency
);
418 $net[] = CRM_Utils_Money
::format($dao->net
, $dao->currency
);
419 $average[] = CRM_Utils_Money
::format($dao->avg
, $dao->currency
);
420 $count +
= $dao->count
;
422 $statistics['counts']['amount'] = array(
423 'title' => ts('Total Amount (Contributions)'),
424 'value' => implode(', ', $totalAmount),
425 'type' => CRM_Utils_Type
::T_STRING
,
427 $statistics['counts']['count'] = array(
428 'title' => ts('Total Contributions'),
431 $statistics['counts']['fees'] = array(
432 'title' => ts('Fees'),
433 'value' => implode(', ', $fees),
434 'type' => CRM_Utils_Type
::T_STRING
,
436 $statistics['counts']['net'] = array(
437 'title' => ts('Net'),
438 'value' => implode(', ', $net),
439 'type' => CRM_Utils_Type
::T_STRING
,
441 $statistics['counts']['avg'] = array(
442 'title' => ts('Average'),
443 'value' => implode(', ', $average),
444 'type' => CRM_Utils_Type
::T_STRING
,
447 // Stats for soft credits
448 if ($this->_softFrom
&&
449 CRM_Utils_Array
::value('contribution_or_soft_value', $this->_params
) !=
452 $totalAmount = $average = array();
455 SELECT COUNT(contribution_soft_civireport.amount ) as count,
456 SUM(contribution_soft_civireport.amount ) as amount,
457 ROUND(AVG(contribution_soft_civireport.amount), 2) as avg,
458 {$this->_aliases['civicrm_contribution']}.currency as currency";
462 GROUP BY {$this->_aliases['civicrm_contribution']}.currency";
463 $dao = CRM_Core_DAO
::executeQuery($sql);
464 $this->addToDeveloperTab($sql);
465 while ($dao->fetch()) {
466 $totalAmount[] = CRM_Utils_Money
::format($dao->amount
, $dao->currency
) . " (" .
468 $average[] = CRM_Utils_Money
::format($dao->avg
, $dao->currency
);
469 $count +
= $dao->count
;
471 $statistics['counts']['softamount'] = array(
472 'title' => ts('Total Amount (Soft Credits)'),
473 'value' => implode(', ', $totalAmount),
474 'type' => CRM_Utils_Type
::T_STRING
,
476 $statistics['counts']['softcount'] = array(
477 'title' => ts('Total Soft Credits'),
480 $statistics['counts']['softavg'] = array(
481 'title' => ts('Average (Soft Credits)'),
482 'value' => implode(', ', $average),
483 'type' => CRM_Utils_Type
::T_STRING
,
491 * This function appears to have been overrriden for the purposes of facilitating soft credits in the report.
493 * The report appears to have 2 different functions:
494 * 1) contribution report
495 * 2) soft credit report - showing a row per 'payment engagement' (payment or soft credit). There is a separate
496 * soft credit report as well.
498 * Somewhat confusingly this report returns multiple rows per contribution when soft credits are included. It feels
499 * like there is a case to split it into 2 separate reports.
501 * Soft credit functionality is not currently unit tested for this report.
503 public function postProcess() {
504 // get the acl clauses built before we assemble the query
505 $this->buildACLClause($this->_aliases
['civicrm_contact']);
507 $this->beginPostProcess();
508 // CRM-18312 - display soft_credits and soft_credits_for column
509 // when 'Contribution or Soft Credit?' column is not selected
510 if (empty($this->_params
['fields']['contribution_or_soft'])) {
511 $this->_params
['fields']['contribution_or_soft'] = 1;
512 $this->noDisplayContributionOrSoftColumn
= TRUE;
515 if (CRM_Utils_Array
::value('contribution_or_soft_value', $this->_params
) ==
516 'contributions_only' &&
517 !empty($this->_params
['fields']['soft_credit_type_id'])
519 unset($this->_params
['fields']['soft_credit_type_id']);
520 if (!empty($this->_params
['soft_credit_type_id_value'])) {
521 $this->_params
['soft_credit_type_id_value'] = array();
525 // 1. use main contribution query to build temp table 1
526 $sql = $this->buildQuery();
527 $tempQuery = "CREATE TEMPORARY TABLE civireport_contribution_detail_temp1 {$this->_databaseAttributes} AS {$sql}";
528 $this->addToDeveloperTab($tempQuery);
529 CRM_Core_DAO
::executeQuery($tempQuery);
532 // 2. customize main contribution query for soft credit, and build temp table 2 with soft credit contributions only
533 $this->softCreditFrom();
534 // also include custom group from if included
535 // since this might be included in select
536 $this->customDataFrom();
538 $select = str_ireplace('contribution_civireport.total_amount', 'contribution_soft_civireport.amount', $this->_select
);
539 $select = str_ireplace("'Contribution' as", "'Soft Credit' as", $select);
540 // We really don't want to join soft credit in if not required.
541 if (!empty($this->_groupBy
) && !$this->noDisplayContributionOrSoftColumn
) {
542 $this->_groupBy
.= ', contribution_soft_civireport.amount';
544 // we inner join with temp1 to restrict soft contributions to those in temp1 table
545 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy}";
546 $tempQuery = "CREATE TEMPORARY TABLE civireport_contribution_detail_temp2 {$this->_databaseAttributes} AS {$sql}";
547 $this->addToDeveloperTab($tempQuery);
548 CRM_Core_DAO
::executeQuery($tempQuery);
549 if (CRM_Utils_Array
::value('contribution_or_soft_value', $this->_params
) ==
552 // revise pager : prev, next based on soft-credits only
556 // copy _from for later use of stats calculation for soft credits, and reset $this->_from to main query
557 $this->_softFrom
= $this->_from
;
559 // simple reset of ->_from
562 // also include custom group from if included
563 // since this might be included in select
564 $this->customDataFrom();
566 // 3. Decide where to populate temp3 table from
567 if (CRM_Utils_Array
::value('contribution_or_soft_value', $this->_params
) ==
570 $tempQuery = "(SELECT * FROM civireport_contribution_detail_temp1)";
572 elseif (CRM_Utils_Array
::value('contribution_or_soft_value', $this->_params
) ==
575 $tempQuery = "(SELECT * FROM civireport_contribution_detail_temp2)";
579 (SELECT * FROM civireport_contribution_detail_temp1)
581 (SELECT * FROM civireport_contribution_detail_temp2)";
584 // 4. build temp table 3
585 $sql = "CREATE TEMPORARY TABLE civireport_contribution_detail_temp3 {$this->_databaseAttributes} AS {$tempQuery}";
586 $this->addToDeveloperTab($sql);
587 CRM_Core_DAO
::executeQuery($sql);
589 // 5. Re-construct order-by to make sense for final query on temp3 table
591 if (!empty($this->_orderByArray
)) {
592 $aliases = array_flip($this->_aliases
);
593 $orderClause = array();
594 foreach ($this->_orderByArray
as $clause) {
595 list($alias, $rest) = explode('.', $clause);
596 // CRM-17280 -- In case, we are ordering by custom fields
597 // modify $rest to match the alias used for them in temp3 table
598 $grp = new CRM_Core_DAO_CustomGroup();
599 $grp->table_name
= $aliases[$alias];
601 list($fld, $order) = explode(' ', $rest);
602 foreach ($this->_columns
[$aliases[$alias]]['fields'] as $fldName => $value) {
603 if ($value['name'] == $fld) {
607 $rest = "{$fld} {$order}";
609 $orderClause[] = $aliases[$alias] . "_" . $rest;
611 $orderBy = (!empty($orderClause)) ?
"ORDER BY " . implode(', ', $orderClause) : '';
614 // 6. show result set from temp table 3
616 $sql = "SELECT * FROM civireport_contribution_detail_temp3 {$orderBy}";
617 $this->buildRows($sql, $rows);
619 // format result set.
620 $this->formatDisplay($rows, FALSE);
622 // assign variables to templates
623 $this->doTemplateAssignment($rows);
624 // do print / pdf / instance stuff if needed
625 $this->endPostProcess($rows);
629 * Alter display of rows.
631 * Iterate through the rows retrieved via SQL and make changes for display purposes,
632 * such as rendering contacts as links.
635 * Rows generated by SQL, with an array for each row.
637 public function alterDisplay(&$rows) {
638 $checkList = array();
640 $display_flag = $prev_cid = $cid = 0;
641 $contributionTypes = CRM_Contribute_PseudoConstant
::financialType();
642 $contributionStatus = CRM_Contribute_PseudoConstant
::contributionStatus();
643 $paymentInstruments = CRM_Contribute_PseudoConstant
::paymentInstrument();
644 $contributionPages = CRM_Contribute_PseudoConstant
::contributionPage();
645 $batches = CRM_Batch_BAO_Batch
::getBatches();
646 foreach ($rows as $rowNum => $row) {
647 if (!empty($this->_noRepeats
) && $this->_outputMode
!= 'csv') {
648 // don't repeat contact details if its same as the previous row
649 if (array_key_exists('civicrm_contact_id', $row)) {
650 if ($cid = $row['civicrm_contact_id']) {
655 if ($prev_cid == $cid) {
666 foreach ($row as $colName => $colVal) {
667 // Hide repeats in no-repeat columns, but not if the field's a section header
668 if (in_array($colName, $this->_noRepeats
) &&
669 !array_key_exists($colName, $this->_sections
)
671 unset($rows[$rowNum][$colName]);
680 if (CRM_Utils_Array
::value('civicrm_contribution_contribution_or_soft', $rows[$rowNum]) ==
683 unset($rows[$rowNum]['civicrm_contribution_soft_soft_credit_type_id']);
686 $entryFound = $this->alterDisplayContactFields($row, $rows, $rowNum, 'contribution/detail', ts('View Contribution Details')) ?
TRUE : $entryFound;
687 // convert donor sort name to link
688 if (array_key_exists('civicrm_contact_sort_name', $row) &&
689 !empty($rows[$rowNum]['civicrm_contact_sort_name']) &&
690 array_key_exists('civicrm_contact_id', $row)
692 $url = CRM_Utils_System
::url("civicrm/contact/view",
693 'reset=1&cid=' . $row['civicrm_contact_id'],
696 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
697 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contact Summary for this Contact.");
700 if ($value = CRM_Utils_Array
::value('civicrm_contribution_financial_type_id', $row)) {
701 $rows[$rowNum]['civicrm_contribution_financial_type_id'] = $contributionTypes[$value];
704 if ($value = CRM_Utils_Array
::value('civicrm_contribution_contribution_status_id', $row)) {
705 $rows[$rowNum]['civicrm_contribution_contribution_status_id'] = $contributionStatus[$value];
708 if ($value = CRM_Utils_Array
::value('civicrm_contribution_contribution_page_id', $row)) {
709 $rows[$rowNum]['civicrm_contribution_contribution_page_id'] = $contributionPages[$value];
712 if ($value = CRM_Utils_Array
::value('civicrm_contribution_payment_instrument_id', $row)) {
713 $rows[$rowNum]['civicrm_contribution_payment_instrument_id'] = $paymentInstruments[$value];
716 if (!empty($row['civicrm_batch_batch_id'])) {
717 $rows[$rowNum]['civicrm_batch_batch_id'] = CRM_Utils_Array
::value($row['civicrm_batch_batch_id'], $batches);
720 if (!empty($row['civicrm_financial_trxn_card_type_id'])) {
721 $rows[$rowNum]['civicrm_financial_trxn_card_type_id'] = $this->getLabels($row['civicrm_financial_trxn_card_type_id'], 'CRM_Financial_DAO_FinancialTrxn', 'card_type_id');
725 // Contribution amount links to viewing contribution
726 if (($value = CRM_Utils_Array
::value('civicrm_contribution_total_amount_sum', $row)) &&
727 CRM_Core_Permission
::check('access CiviContribute')
729 $url = CRM_Utils_System
::url("civicrm/contact/view/contribution",
730 "reset=1&id=" . $row['civicrm_contribution_contribution_id'] .
731 "&cid=" . $row['civicrm_contact_id'] .
732 "&action=view&context=contribution&selectedChild=contribute",
735 $rows[$rowNum]['civicrm_contribution_total_amount_sum_link'] = $url;
736 $rows[$rowNum]['civicrm_contribution_total_amount_sum_hover'] = ts("View Details of this Contribution.");
740 // convert campaign_id to campaign title
741 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
742 if ($value = $row['civicrm_contribution_campaign_id']) {
743 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns
[$value];
749 if (array_key_exists('civicrm_contribution_soft_credits', $row) &&
751 CRM_Utils_Array
::value('civicrm_contribution_contribution_or_soft', $rows[$rowNum]) &&
752 array_key_exists('civicrm_contribution_contribution_id', $row)
755 SELECT civicrm_contact_id, civicrm_contact_sort_name, civicrm_contribution_total_amount_sum, civicrm_contribution_currency
756 FROM civireport_contribution_detail_temp2
757 WHERE civicrm_contribution_contribution_id={$row['civicrm_contribution_contribution_id']}";
758 $this->addToDeveloperTab($query);
759 $dao = CRM_Core_DAO
::executeQuery($query);
761 $separator = ($this->_outputMode
!== 'csv') ?
"<br/>" : ' ';
762 while ($dao->fetch()) {
763 $url = CRM_Utils_System
::url("civicrm/contact/view", 'reset=1&cid=' .
764 $dao->civicrm_contact_id
);
765 $string = $string . ($string ?
$separator : '') .
766 "<a href='{$url}'>{$dao->civicrm_contact_sort_name}</a> " .
767 CRM_Utils_Money
::format($dao->civicrm_contribution_total_amount_sum
, $dao->civicrm_contribution_currency
);
769 $rows[$rowNum]['civicrm_contribution_soft_credits'] = $string;
772 if (array_key_exists('civicrm_contribution_soft_credit_for', $row) &&
774 CRM_Utils_Array
::value('civicrm_contribution_contribution_or_soft', $rows[$rowNum]) &&
775 array_key_exists('civicrm_contribution_contribution_id', $row)
778 SELECT civicrm_contact_id, civicrm_contact_sort_name
779 FROM civireport_contribution_detail_temp1
780 WHERE civicrm_contribution_contribution_id={$row['civicrm_contribution_contribution_id']}";
781 $this->addToDeveloperTab($query);
782 $dao = CRM_Core_DAO
::executeQuery($query);
784 while ($dao->fetch()) {
785 $url = CRM_Utils_System
::url("civicrm/contact/view", 'reset=1&cid=' .
786 $dao->civicrm_contact_id
);
788 "\n<a href='{$url}'>{$dao->civicrm_contact_sort_name}</a>";
790 $rows[$rowNum]['civicrm_contribution_soft_credit_for'] = $string;
793 // CRM-18312 - hide 'contribution_or_soft' column if unchecked.
794 if (!empty($this->noDisplayContributionOrSoftColumn
)) {
795 unset($rows[$rowNum]['civicrm_contribution_contribution_or_soft']);
796 unset($this->_columnHeaders
['civicrm_contribution_contribution_or_soft']);
799 //convert soft_credit_type_id into label
800 if (array_key_exists('civicrm_contribution_soft_soft_credit_type_id', $rows[$rowNum])) {
801 $rows[$rowNum]['civicrm_contribution_soft_soft_credit_type_id'] = CRM_Core_PseudoConstant
::getLabel(
802 'CRM_Contribute_BAO_ContributionSoft',
803 'soft_credit_type_id',
804 $row['civicrm_contribution_soft_soft_credit_type_id']
808 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s) for this ') ?
TRUE : $entryFound;
810 // skip looking further in rows, if first row itself doesn't
811 // have the column we need
819 public function sectionTotals() {
821 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
822 if (empty($this->_selectAliases
)) {
826 if (!empty($this->_sections
)) {
827 // build the query with no LIMIT clause
828 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select
);
829 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
831 // pull section aliases out of $this->_sections
832 $sectionAliases = array_keys($this->_sections
);
835 foreach (array_merge($sectionAliases, $this->_selectAliases
) as $alias) {
836 $ifnulls[] = "ifnull($alias, '') as $alias";
838 $this->_select
= "SELECT " . implode(", ", $ifnulls);
839 $this->_select
= CRM_Contact_BAO_Query
::appendAnyValueToSelect($ifnulls, $sectionAliases);
841 /* Group (un-limited) report by all aliases and get counts. This might
842 * be done more efficiently when the contents of $sql are known, ie. by
843 * overriding this method in the report class.
848 if (array_search("civicrm_contribution_total_amount_sum", $this->_selectAliases
) !==
851 $addtotals = ", sum(civicrm_contribution_total_amount_sum) as sumcontribs";
852 $showsumcontribs = TRUE;
855 $query = $this->_select
.
856 "$addtotals, count(*) as ct from civireport_contribution_detail_temp3 group by " .
857 implode(", ", $sectionAliases);
858 // initialize array of total counts
859 $sumcontribs = $totals = array();
860 $dao = CRM_Core_DAO
::executeQuery($query);
861 $this->addToDeveloperTab($query);
862 while ($dao->fetch()) {
864 // let $this->_alterDisplay translate any integer ids to human-readable values.
865 $rows[0] = $dao->toArray();
866 $this->alterDisplay($rows);
869 // add totals for all permutations of section values
872 $aliasCount = count($sectionAliases);
873 foreach ($sectionAliases as $alias) {
874 $values[] = $row[$alias];
875 $key = implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $values);
876 if ($i == $aliasCount) {
877 // the last alias is the lowest-level section header; use count as-is
878 $totals[$key] = $dao->ct
;
879 if ($showsumcontribs) {
880 $sumcontribs[$key] = $dao->sumcontribs
;
884 // other aliases are higher level; roll count into their total
885 $totals[$key] = (array_key_exists($key, $totals)) ?
$totals[$key] +
$dao->ct
: $dao->ct
;
886 if ($showsumcontribs) {
887 $sumcontribs[$key] = array_key_exists($key, $sumcontribs) ?
$sumcontribs[$key] +
$dao->sumcontribs
: $dao->sumcontribs
;
892 if ($showsumcontribs) {
893 $totalandsum = array();
894 // ts exception to avoid having ts("%1 %2: %3")
895 $title = '%1 contributions / soft-credits: %2';
897 if (CRM_Utils_Array
::value('contribution_or_soft_value', $this->_params
) ==
900 $title = '%1 contributions: %2';
902 elseif (CRM_Utils_Array
::value('contribution_or_soft_value', $this->_params
) ==
905 $title = '%1 soft-credits: %2';
907 foreach ($totals as $key => $total) {
908 $totalandsum[$key] = ts($title, array(
910 2 => CRM_Utils_Money
::format($sumcontribs[$key]),
913 $this->assign('sectionTotals', $totalandsum);
916 $this->assign('sectionTotals', $totals);
922 * Generate the from clause as it relates to the soft credits.
924 public function softCreditFrom() {
927 FROM civireport_contribution_detail_temp1 temp1_civireport
928 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
929 ON temp1_civireport.civicrm_contribution_contribution_id = {$this->_aliases['civicrm_contribution']}.id
930 INNER JOIN civicrm_contribution_soft contribution_soft_civireport
931 ON contribution_soft_civireport.contribution_id = {$this->_aliases['civicrm_contribution']}.id
932 INNER JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
933 ON {$this->_aliases['civicrm_contact']}.id = contribution_soft_civireport.contact_id
937 $this->appendAdditionalFromJoins();
941 * Append the joins that are required regardless of context.
943 public function appendAdditionalFromJoins() {
944 if (!empty($this->_params
['ordinality_value'])) {
946 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']}
947 ON {$this->_aliases['civicrm_contribution_ordinality']}.id = {$this->_aliases['civicrm_contribution']}.id";
949 $this->joinPhoneFromContact();
950 $this->joinAddressFromContact();
951 $this->joinEmailFromContact();
953 // include contribution note
954 if (!empty($this->_params
['fields']['contribution_note']) ||
955 !empty($this->_params
['note_value'])
958 LEFT JOIN civicrm_note {$this->_aliases['civicrm_note']}
959 ON ( {$this->_aliases['civicrm_note']}.entity_table = 'civicrm_contribution' AND
960 {$this->_aliases['civicrm_contribution']}.id = {$this->_aliases['civicrm_note']}.entity_id )";
962 //for contribution batches
963 if (!empty($this->_params
['fields']['batch_id']) ||
964 !empty($this->_params
['bid_value'])
967 LEFT JOIN civicrm_entity_financial_trxn eft
968 ON eft.entity_id = {$this->_aliases['civicrm_contribution']}.id AND
969 eft.entity_table = 'civicrm_contribution'
970 LEFT JOIN civicrm_entity_batch {$this->_aliases['civicrm_batch']}
971 ON ({$this->_aliases['civicrm_batch']}.entity_id = eft.financial_trxn_id
972 AND {$this->_aliases['civicrm_batch']}.entity_table = 'civicrm_financial_trxn')";
974 // for credit card type
975 $this->addFinancialTrxnFromClause();