dev/core#170 fix regression on soft_credits with unit test
[civicrm-core.git] / CRM / Report / Form / Contribute / Detail.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
8c9251b3 6 | Copyright CiviCRM LLC (c) 2004-2018 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
8c9251b3 31 * @copyright CiviCRM LLC (c) 2004-2018
6a488035
TO
32 */
33class CRM_Report_Form_Contribute_Detail extends CRM_Report_Form {
6a488035
TO
34
35 protected $_summary = NULL;
36
e9b25936
E
37 protected $_softFrom = NULL;
38
f568f786 39 protected $noDisplayContributionOrSoftColumn = FALSE;
40
70bea8e2 41 protected $_customGroupExtends = array(
42 'Contact',
43 'Individual',
7d793900 44 'Contribution',
70bea8e2 45 );
6a488035 46
81a22d3d 47 protected $groupConcatTested = TRUE;
48
e6bab5ea 49 protected $isTempTableBuilt = FALSE;
50
51 /**
52 * Query mode.
53 *
54 * This can be 'Main' or 'SoftCredit' to denote which query we are building.
55 *
56 * @var string
57 */
58 protected $queryMode = 'Main';
59
60 /**
61 * Is this report being run on contributions as the base entity.
62 *
63 * The report structure is generally designed around a base entity but
64 * depending on input it can be run in a sort of hybrid way that causes a lot
65 * of complexity.
66 *
67 * If it is in isContributionsOnlyMode we can simplify.
68 *
69 * (arguably there should be 2 separate report templates, not one doing double duty.)
70 *
71 * @var bool
72 */
73 protected $isContributionBaseMode = FALSE;
74
74cf4551 75 /**
1728e9a0 76 * This report has been optimised for group filtering.
77 *
78 * CRM-19170
79 *
80 * @var bool
81 */
82 protected $groupFilterNotOptimised = FALSE;
83
84 /**
85 * Class constructor.
74cf4551 86 */
00be9182 87 public function __construct() {
70bea8e2 88 $this->_autoIncludeIndexedFieldsAsOrderBys = 1;
f813f78e 89 // Check if CiviCampaign is a) enabled and b) has active campaigns
6a488035
TO
90 $config = CRM_Core_Config::singleton();
91 $campaignEnabled = in_array("CiviCampaign", $config->enableComponents);
92 if ($campaignEnabled) {
93 $getCampaigns = CRM_Campaign_BAO_Campaign::getPermissionedCampaigns(NULL, NULL, TRUE, FALSE, TRUE);
94 $this->activeCampaigns = $getCampaigns['campaigns'];
95 asort($this->activeCampaigns);
96 }
70bea8e2 97
d7e34fc6 98 $this->_columns = array_merge($this->getColumns('Contact', array(
99 'order_bys_defaults' => array('sort_name' => 'ASC '),
100 'fields_defaults' => array('sort_name'),
101 'fields_excluded' => array('id'),
102 'fields_required' => array('id'),
bc390081 103 'filters_defaults' => array('is_deleted' => 0),
d7e34fc6 104 'no_field_disambiguation' => TRUE,
105 )), array(
a1a2a83d
TO
106 'civicrm_email' => array(
107 'dao' => 'CRM_Core_DAO_Email',
108 'fields' => array(
109 'email' => array(
110 'title' => ts('Donor Email'),
111 'default' => TRUE,
1ebef749 112 ),
a1a2a83d
TO
113 ),
114 'grouping' => 'contact-fields',
115 ),
4a39d437
E
116 'civicrm_line_item' => array(
117 'dao' => 'CRM_Price_DAO_LineItem',
118 ),
a1a2a83d
TO
119 'civicrm_phone' => array(
120 'dao' => 'CRM_Core_DAO_Phone',
121 'fields' => array(
122 'phone' => array(
123 'title' => ts('Donor Phone'),
124 'default' => TRUE,
125 'no_repeat' => TRUE,
126 ),
127 ),
128 'grouping' => 'contact-fields',
129 ),
130 'civicrm_contribution' => array(
131 'dao' => 'CRM_Contribute_DAO_Contribution',
132 'fields' => array(
133 'contribution_id' => array(
134 'name' => 'id',
135 'no_display' => TRUE,
136 'required' => TRUE,
137 ),
138 'list_contri_id' => array(
139 'name' => 'id',
140 'title' => ts('Contribution ID'),
141 ),
142 'financial_type_id' => array(
143 'title' => ts('Financial Type'),
144 'default' => TRUE,
145 ),
146 'contribution_status_id' => array(
147 'title' => ts('Contribution Status'),
148 ),
149 'contribution_page_id' => array(
150 'title' => ts('Contribution Page'),
151 ),
152 'source' => array(
153 'title' => ts('Source'),
154 ),
155 'payment_instrument_id' => array(
156 'title' => ts('Payment Type'),
157 ),
158 'check_number' => array(
159 'title' => ts('Check Number'),
160 ),
161 'currency' => array(
162 'required' => TRUE,
163 'no_display' => TRUE,
164 ),
165 'trxn_id' => NULL,
166 'receive_date' => array('default' => TRUE),
167 'receipt_date' => NULL,
168 'total_amount' => array(
169 'title' => ts('Amount'),
170 'required' => TRUE,
171 'statistics' => array('sum' => ts('Amount')),
6a488035 172 ),
5afce5ad 173 'non_deductible_amount' => array(
174 'title' => ts('Non-deductible Amount'),
175 ),
a1a2a83d
TO
176 'fee_amount' => NULL,
177 'net_amount' => NULL,
178 'contribution_or_soft' => array(
179 'title' => ts('Contribution OR Soft Credit?'),
180 'dbAlias' => "'Contribution'",
181 ),
182 'soft_credits' => array(
183 'title' => ts('Soft Credits'),
184 'dbAlias' => "NULL",
185 ),
186 'soft_credit_for' => array(
187 'title' => ts('Soft Credit For'),
188 'dbAlias' => "NULL",
6a488035 189 ),
6a488035 190 ),
a1a2a83d
TO
191 'filters' => array(
192 'contribution_or_soft' => array(
193 'title' => ts('Contribution OR Soft Credit?'),
194 'clause' => "(1)",
195 'operatorType' => CRM_Report_Form::OP_SELECT,
196 'type' => CRM_Utils_Type::T_STRING,
197 'options' => array(
a1a2a83d
TO
198 'contributions_only' => ts('Contributions Only'),
199 'soft_credits_only' => ts('Soft Credits Only'),
f072e08f 200 'both' => ts('Both'),
9d72cede 201 ),
51fa20cb 202 ),
a1a2a83d 203 'receive_date' => array('operatorType' => CRM_Report_Form::OP_DATE),
db96d968 204 'contribution_source' => array(
205 'title' => ts('Source'),
206 'name' => 'source',
207 'type' => CRM_Utils_Type::T_STRING,
208 ),
a1a2a83d 209 'currency' => array(
fd6a6828 210 'title' => ts('Currency'),
a1a2a83d
TO
211 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
212 'options' => CRM_Core_OptionGroup::values('currencies_enabled'),
213 'default' => NULL,
214 'type' => CRM_Utils_Type::T_STRING,
215 ),
5afce5ad 216 'non_deductible_amount' => array(
217 'title' => ts('Non-deductible Amount'),
218 ),
a1a2a83d
TO
219 'financial_type_id' => array(
220 'title' => ts('Financial Type'),
221 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
4f166b15 222 'options' => CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes(),
a1a2a83d
TO
223 'type' => CRM_Utils_Type::T_INT,
224 ),
225 'contribution_page_id' => array(
226 'title' => ts('Contribution Page'),
227 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
228 'options' => CRM_Contribute_PseudoConstant::contributionPage(),
229 'type' => CRM_Utils_Type::T_INT,
230 ),
231 'payment_instrument_id' => array(
232 'title' => ts('Payment Type'),
233 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
234 'options' => CRM_Contribute_PseudoConstant::paymentInstrument(),
235 'type' => CRM_Utils_Type::T_INT,
236 ),
237 'contribution_status_id' => array(
238 'title' => ts('Contribution Status'),
239 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
240 'options' => CRM_Contribute_PseudoConstant::contributionStatus(),
241 'default' => array(1),
242 'type' => CRM_Utils_Type::T_INT,
243 ),
244 'total_amount' => array('title' => ts('Contribution Amount')),
51fa20cb 245 ),
a1a2a83d
TO
246 'order_bys' => array(
247 'financial_type_id' => array('title' => ts('Financial Type')),
248 'contribution_status_id' => array('title' => ts('Contribution Status')),
536f0e02 249 'payment_instrument_id' => array('title' => ts('Payment Method')),
7bc6b5bb 250 'receive_date' => array('title' => ts('Date Received')),
a1a2a83d 251 ),
81a22d3d 252 'group_bys' => array(
253 'contribution_id' => array(
254 'name' => 'id',
255 'required' => TRUE,
256 'title' => ts('Contribution'),
257 ),
258 ),
a1a2a83d
TO
259 'grouping' => 'contri-fields',
260 ),
261 'civicrm_contribution_soft' => array(
262 'dao' => 'CRM_Contribute_DAO_ContributionSoft',
263 'fields' => array(
264 'soft_credit_type_id' => array('title' => ts('Soft Credit Type')),
265 ),
266 'filters' => array(
267 'soft_credit_type_id' => array(
fd6a6828 268 'title' => ts('Soft Credit Type'),
a1a2a83d
TO
269 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
270 'options' => CRM_Core_OptionGroup::values('soft_credit_type'),
271 'default' => NULL,
272 'type' => CRM_Utils_Type::T_STRING,
6a488035
TO
273 ),
274 ),
a1a2a83d 275 ),
e5f5c94b
E
276 'civicrm_financial_trxn' => array(
277 'dao' => 'CRM_Financial_DAO_FinancialTrxn',
278 'fields' => array(
5e0343e8 279 'card_type_id' => array(
d72b084a 280 'title' => ts('Credit Card Type'),
ea754d42 281 ),
e5f5c94b
E
282 ),
283 'filters' => array(
5e0343e8 284 'card_type_id' => array(
d72b084a 285 'title' => ts('Credit Card Type'),
e5f5c94b 286 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
5e0343e8 287 'options' => CRM_Financial_DAO_FinancialTrxn::buildOptions('card_type_id'),
e5f5c94b
E
288 'default' => NULL,
289 'type' => CRM_Utils_Type::T_STRING,
290 ),
291 ),
292 ),
433465bc
PN
293 'civicrm_batch' => array(
294 'dao' => 'CRM_Batch_DAO_EntityBatch',
295 'grouping' => 'contri-fields',
296 'fields' => array(
297 'batch_id' => array(
49d516c6 298 'name' => 'batch_id',
433465bc
PN
299 'title' => ts('Batch Name'),
300 ),
301 ),
302 'filters' => array(
303 'bid' => array(
304 'title' => ts('Batch Name'),
305 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
306 'options' => CRM_Batch_BAO_Batch::getBatches(),
307 'type' => CRM_Utils_Type::T_INT,
308 'dbAlias' => 'batch_civireport.batch_id',
309 ),
310 ),
311 ),
a1a2a83d
TO
312 'civicrm_contribution_ordinality' => array(
313 'dao' => 'CRM_Contribute_DAO_Contribution',
314 'alias' => 'cordinality',
315 'filters' => array(
316 'ordinality' => array(
317 'title' => ts('Contribution Ordinality'),
318 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
319 'options' => array(
320 0 => 'First by Contributor',
321 1 => 'Second or Later by Contributor',
322 ),
323 'type' => CRM_Utils_Type::T_INT,
6a488035 324 ),
a1a2a83d
TO
325 ),
326 ),
327 'civicrm_note' => array(
328 'dao' => 'CRM_Core_DAO_Note',
329 'fields' => array(
330 'contribution_note' => array(
331 'name' => 'note',
332 'title' => ts('Contribution Note'),
333 ),
334 ),
335 'filters' => array(
336 'note' => array(
337 'name' => 'note',
338 'title' => ts('Contribution Note'),
339 'operator' => 'like',
340 'type' => CRM_Utils_Type::T_STRING,
6a488035
TO
341 ),
342 ),
a1a2a83d 343 ),
d7e34fc6 344 )) + $this->addAddressFields(FALSE);
a703d90c 345 // The tests test for this variation of the sort_name field. Don't argue with the tests :-).
25cf1ac5 346 $this->_columns['civicrm_contact']['fields']['sort_name']['title'] = ts('Donor Name');
16e2e80c 347 $this->_groupFilter = TRUE;
6a488035 348 $this->_tagFilter = TRUE;
1c4d8c3e 349
9d72cede 350 // If we have active campaigns add those elements to both the fields and filters
6a488035
TO
351 if ($campaignEnabled && !empty($this->activeCampaigns)) {
352 $this->_columns['civicrm_contribution']['fields']['campaign_id'] = array(
353 'title' => ts('Campaign'),
354 'default' => 'false',
355 );
9d72cede
EM
356 $this->_columns['civicrm_contribution']['filters']['campaign_id'] = array(
357 'title' => ts('Campaign'),
6a488035
TO
358 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
359 'options' => $this->activeCampaigns,
942b1d01 360 'type' => CRM_Utils_Type::T_INT,
6a488035
TO
361 );
362 $this->_columns['civicrm_contribution']['order_bys']['campaign_id'] = array('title' => ts('Campaign'));
363 }
7a961f19 364
365 $this->_currencyColumn = 'civicrm_contribution_currency';
6a488035
TO
366 parent::__construct();
367 }
368
74cf4551 369 /**
8b7f2513 370 * Set the FROM clause for the report.
74cf4551 371 */
8b7f2513 372 public function from() {
97b4dc6b 373 $this->setFromBase('civicrm_contact');
374 $this->_from .= "
375 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
376 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id
377 AND {$this->_aliases['civicrm_contribution']}.is_test = 0";
40c655aa 378
9d72cede
EM
379 if (CRM_Utils_Array::value('contribution_or_soft_value', $this->_params) ==
380 'both'
381 ) {
51fa20cb 382 $this->_from .= "\n LEFT JOIN civicrm_contribution_soft contribution_soft_civireport
383 ON contribution_soft_civireport.contribution_id = {$this->_aliases['civicrm_contribution']}.id";
384 }
9d72cede
EM
385 elseif (CRM_Utils_Array::value('contribution_or_soft_value', $this->_params) ==
386 'soft_credits_only'
387 ) {
51fa20cb 388 $this->_from .= "\n INNER JOIN civicrm_contribution_soft contribution_soft_civireport
389 ON contribution_soft_civireport.contribution_id = {$this->_aliases['civicrm_contribution']}.id";
c548e07b 390 }
8b7f2513 391 $this->appendAdditionalFromJoins();
6a488035
TO
392 }
393
74cf4551
EM
394 /**
395 * @param $rows
396 *
397 * @return array
398 */
00be9182 399 public function statistics(&$rows) {
6a488035
TO
400 $statistics = parent::statistics($rows);
401
7010bab9 402 $totalAmount = $average = $fees = $net = array();
7a961f19 403 $count = 0;
6a488035
TO
404 $select = "
405 SELECT COUNT({$this->_aliases['civicrm_contribution']}.total_amount ) as count,
406 SUM( {$this->_aliases['civicrm_contribution']}.total_amount ) as amount,
7a961f19 407 ROUND(AVG({$this->_aliases['civicrm_contribution']}.total_amount), 2) as avg,
7010bab9 408 {$this->_aliases['civicrm_contribution']}.currency as currency,
e468f7a2 409 SUM( {$this->_aliases['civicrm_contribution']}.fee_amount ) as fees,
7010bab9 410 SUM( {$this->_aliases['civicrm_contribution']}.net_amount ) as net
6a488035
TO
411 ";
412
7a961f19 413 $group = "\nGROUP BY {$this->_aliases['civicrm_contribution']}.currency";
414 $sql = "{$select} {$this->_from} {$this->_where} {$group}";
6a488035 415 $dao = CRM_Core_DAO::executeQuery($sql);
3b2bbbfb 416 $this->addToDeveloperTab($sql);
6a488035 417
7a961f19 418 while ($dao->fetch()) {
7010bab9
DG
419 $totalAmount[] = CRM_Utils_Money::format($dao->amount, $dao->currency) . " (" . $dao->count . ")";
420 $fees[] = CRM_Utils_Money::format($dao->fees, $dao->currency);
421 $net[] = CRM_Utils_Money::format($dao->net, $dao->currency);
9d72cede 422 $average[] = CRM_Utils_Money::format($dao->avg, $dao->currency);
1c4d8c3e 423 $count += $dao->count;
6a488035 424 }
7a961f19 425 $statistics['counts']['amount'] = array(
be205937 426 'title' => ts('Total Amount (Contributions)'),
7a961f19 427 'value' => implode(', ', $totalAmount),
428 'type' => CRM_Utils_Type::T_STRING,
429 );
430 $statistics['counts']['count'] = array(
be205937 431 'title' => ts('Total Contributions'),
7a961f19 432 'value' => $count,
433 );
7010bab9
DG
434 $statistics['counts']['fees'] = array(
435 'title' => ts('Fees'),
436 'value' => implode(', ', $fees),
437 'type' => CRM_Utils_Type::T_STRING,
438 );
439 $statistics['counts']['net'] = array(
440 'title' => ts('Net'),
441 'value' => implode(', ', $net),
442 'type' => CRM_Utils_Type::T_STRING,
443 );
7a961f19 444 $statistics['counts']['avg'] = array(
445 'title' => ts('Average'),
446 'value' => implode(', ', $average),
447 'type' => CRM_Utils_Type::T_STRING,
448 );
6a488035 449
70c41bce 450 // Stats for soft credits
9d72cede
EM
451 if ($this->_softFrom &&
452 CRM_Utils_Array::value('contribution_or_soft_value', $this->_params) !=
453 'contributions_only'
454 ) {
c548e07b 455 $totalAmount = $average = array();
9d72cede 456 $count = 0;
c548e07b 457 $select = "
70c41bce
DS
458SELECT COUNT(contribution_soft_civireport.amount ) as count,
459 SUM(contribution_soft_civireport.amount ) as amount,
460 ROUND(AVG(contribution_soft_civireport.amount), 2) as avg,
461 {$this->_aliases['civicrm_contribution']}.currency as currency";
c548e07b 462 $sql = "
f813f78e 463{$select}
464{$this->_softFrom}
c548e07b
DS
465GROUP BY {$this->_aliases['civicrm_contribution']}.currency";
466 $dao = CRM_Core_DAO::executeQuery($sql);
3b2bbbfb 467 $this->addToDeveloperTab($sql);
c548e07b 468 while ($dao->fetch()) {
6c552737 469 $totalAmount[] = CRM_Utils_Money::format($dao->amount, $dao->currency) . " (" .
9d72cede
EM
470 $dao->count . ")";
471 $average[] = CRM_Utils_Money::format($dao->avg, $dao->currency);
c548e07b
DS
472 $count += $dao->count;
473 }
474 $statistics['counts']['softamount'] = array(
475 'title' => ts('Total Amount (Soft Credits)'),
476 'value' => implode(', ', $totalAmount),
477 'type' => CRM_Utils_Type::T_STRING,
478 );
479 $statistics['counts']['softcount'] = array(
480 'title' => ts('Total Soft Credits'),
481 'value' => $count,
482 );
483 $statistics['counts']['softavg'] = array(
484 'title' => ts('Average (Soft Credits)'),
485 'value' => implode(', ', $average),
486 'type' => CRM_Utils_Type::T_STRING,
487 );
70c41bce 488 }
70c41bce 489
6a488035
TO
490 return $statistics;
491 }
492
8b7f2513 493 /**
e6bab5ea 494 * Build the report query.
8b7f2513 495 *
e6bab5ea 496 * @param bool $applyLimit
8b7f2513 497 *
e6bab5ea 498 * @return string
8b7f2513 499 */
e6bab5ea 500 public function buildQuery($applyLimit = TRUE) {
501 if ($this->isTempTableBuilt) {
502 return "SELECT * FROM civireport_contribution_detail_temp3 $this->_orderBy";
503 }
504 return parent::buildQuery($applyLimit);
505 }
70c41bce 506
e6bab5ea 507 /**
508 * Shared function for preliminary processing.
509 *
510 * This is called by the api / unit tests and the form layer and is
511 * the right place to do 'initial analysis of input'.
512 */
513 public function beginPostProcessCommon() {
514 // CRM-18312 - display soft_credits and soft_credits_for column
515 // when 'Contribution or Soft Credit?' column is not selected
516 if (empty($this->_params['fields']['contribution_or_soft'])) {
517 $this->_params['fields']['contribution_or_soft'] = 1;
518 $this->noDisplayContributionOrSoftColumn = TRUE;
519 }
51fa20cb 520
e6bab5ea 521 if (CRM_Utils_Array::value('contribution_or_soft_value', $this->_params) == 'contributions_only') {
522 $this->isContributionBaseMode = TRUE;
523 }
524 if ($this->isContributionBaseMode &&
525 (!empty($this->_params['fields']['soft_credit_type_id'])
526 || !empty($this->_params['soft_credit_type_id_value']))
527 ) {
528 unset($this->_params['fields']['soft_credit_type_id']);
529 if (!empty($this->_params['soft_credit_type_id_value'])) {
530 $this->_params['soft_credit_type_id_value'] = array();
531 CRM_Core_Session::setStatus(ts('Is it not possible to filter on soft contribution type when not including soft credits.'));
532 }
533 }
70c41bce
DS
534 // 1. use main contribution query to build temp table 1
535 $sql = $this->buildQuery();
a2e4e741 536 $tempQuery = "CREATE TEMPORARY TABLE civireport_contribution_detail_temp1 {$this->_databaseAttributes} AS {$sql}";
e6bab5ea 537 $this->temporaryTables['civireport_contribution_detail_temp1'] = ['name' => 'civireport_contribution_detail_temp1', 'temporary' => TRUE];
538 $this->executeReportQuery($tempQuery);
70c41bce
DS
539 $this->setPager();
540
c548e07b 541 // 2. customize main contribution query for soft credit, and build temp table 2 with soft credit contributions only
e6bab5ea 542 $this->queryMode = 'SoftCredit';
543 // Rebuild select with no groupby. Do not let column headers change.
544 $headers = $this->_columnHeaders;
545 $this->select();
546 $this->_columnHeaders = $headers;
8b7f2513 547 $this->softCreditFrom();
be78fc2d
DL
548 // also include custom group from if included
549 // since this might be included in select
550 $this->customDataFrom();
551
70c41bce
DS
552 $select = str_ireplace('contribution_civireport.total_amount', 'contribution_soft_civireport.amount', $this->_select);
553 $select = str_ireplace("'Contribution' as", "'Soft Credit' as", $select);
8b7f2513 554 // We really don't want to join soft credit in if not required.
555 if (!empty($this->_groupBy) && !$this->noDisplayContributionOrSoftColumn) {
3636b520 556 $this->_groupBy .= ', contribution_soft_civireport.amount';
557 }
e6bab5ea 558 // we inner join with temp1 to restrict soft contributions to those in temp1 table.
559 // no group by here as we want to display as many soft credit rows as actually exist.
560 $sql = "{$select} {$this->_from} {$this->_where}";
a2e4e741 561 $tempQuery = "CREATE TEMPORARY TABLE civireport_contribution_detail_temp2 {$this->_databaseAttributes} AS {$sql}";
e6bab5ea 562 $this->executeReportQuery($tempQuery);
563 $this->temporaryTables['civireport_contribution_detail_temp2'] = ['name' => 'civireport_contribution_detail_temp2', 'temporary' => TRUE];
564
9d72cede
EM
565 if (CRM_Utils_Array::value('contribution_or_soft_value', $this->_params) ==
566 'soft_credits_only'
567 ) {
c548e07b
DS
568 // revise pager : prev, next based on soft-credits only
569 $this->setPager();
f813f78e 570 }
70c41bce
DS
571
572 // copy _from for later use of stats calculation for soft credits, and reset $this->_from to main query
573 $this->_softFrom = $this->_from;
c93f6d83
DL
574
575 // simple reset of ->_from
576 $this->from();
be78fc2d
DL
577
578 // also include custom group from if included
579 // since this might be included in select
c93f6d83 580 $this->customDataFrom();
70c41bce 581
c548e07b 582 // 3. Decide where to populate temp3 table from
e6bab5ea 583 if ($this->isContributionBaseMode
9d72cede 584 ) {
e6bab5ea 585 $this->executeReportQuery(
586 "CREATE TEMPORARY TABLE civireport_contribution_detail_temp3 {$this->_databaseAttributes} AS (SELECT * FROM civireport_contribution_detail_temp1)"
587 );
9d72cede 588 }
4c9b6178 589 elseif (CRM_Utils_Array::value('contribution_or_soft_value', $this->_params) ==
9d72cede
EM
590 'soft_credits_only'
591 ) {
e6bab5ea 592 $this->executeReportQuery(
593 "CREATE TEMPORARY TABLE civireport_contribution_detail_temp3 {$this->_databaseAttributes} AS (SELECT * FROM civireport_contribution_detail_temp2)"
594 );
9d72cede
EM
595 }
596 else {
e6bab5ea 597 $this->executeReportQuery("CREATE TEMPORARY TABLE civireport_contribution_detail_temp3 {$this->_databaseAttributes}
1ebef749 598(SELECT * FROM civireport_contribution_detail_temp1)
c548e07b 599UNION ALL
e6bab5ea 600(SELECT * FROM civireport_contribution_detail_temp2)");
c548e07b 601 }
e6bab5ea 602 $this->temporaryTables['civireport_contribution_detail_temp3'] = ['name' => 'civireport_contribution_detail_temp3', 'temporary' => TRUE];
603 $this->isTempTableBuilt = TRUE;
6a488035
TO
604 }
605
a9cf37f5 606 /**
e6bab5ea 607 * Store group bys into array - so we can check elsewhere what is grouped.
a9cf37f5 608 *
e6bab5ea 609 * If we are generating a table of soft credits we do not want to be using
610 * group by.
a9cf37f5 611 */
e6bab5ea 612 protected function storeGroupByArray() {
613 if ($this->queryMode === 'SoftCredit') {
614 $this->_groupByArray = [];
a9cf37f5 615 }
e6bab5ea 616 else {
617 parent::storeGroupByArray();
a9cf37f5 618 }
619 }
620
74cf4551 621 /**
ced9bfed
EM
622 * Alter display of rows.
623 *
624 * Iterate through the rows retrieved via SQL and make changes for display purposes,
625 * such as rendering contacts as links.
626 *
627 * @param array $rows
628 * Rows generated by SQL, with an array for each row.
74cf4551 629 */
00be9182 630 public function alterDisplay(&$rows) {
9d72cede
EM
631 $entryFound = FALSE;
632 $display_flag = $prev_cid = $cid = 0;
633 $contributionTypes = CRM_Contribute_PseudoConstant::financialType();
6a488035
TO
634 $contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
635 $paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument();
9d72cede 636 $contributionPages = CRM_Contribute_PseudoConstant::contributionPage();
433465bc 637 $batches = CRM_Batch_BAO_Batch::getBatches();
6a488035
TO
638 foreach ($rows as $rowNum => $row) {
639 if (!empty($this->_noRepeats) && $this->_outputMode != 'csv') {
640 // don't repeat contact details if its same as the previous row
641 if (array_key_exists('civicrm_contact_id', $row)) {
642 if ($cid = $row['civicrm_contact_id']) {
643 if ($rowNum == 0) {
644 $prev_cid = $cid;
645 }
646 else {
647 if ($prev_cid == $cid) {
648 $display_flag = 1;
649 $prev_cid = $cid;
650 }
651 else {
652 $display_flag = 0;
653 $prev_cid = $cid;
654 }
655 }
656
657 if ($display_flag) {
658 foreach ($row as $colName => $colVal) {
659 // Hide repeats in no-repeat columns, but not if the field's a section header
9d72cede
EM
660 if (in_array($colName, $this->_noRepeats) &&
661 !array_key_exists($colName, $this->_sections)
662 ) {
6a488035
TO
663 unset($rows[$rowNum][$colName]);
664 }
665 }
666 }
667 $entryFound = TRUE;
668 }
669 }
670 }
671
9d72cede
EM
672 if (CRM_Utils_Array::value('civicrm_contribution_contribution_or_soft', $rows[$rowNum]) ==
673 'Contribution'
674 ) {
8e3ad5e0
WA
675 unset($rows[$rowNum]['civicrm_contribution_soft_soft_credit_type_id']);
676 }
6a488035 677
a703d90c 678 $entryFound = $this->alterDisplayContactFields($row, $rows, $rowNum, 'contribution/detail', ts('View Contribution Details')) ? TRUE : $entryFound;
6a488035 679 // convert donor sort name to link
9d72cede
EM
680 if (array_key_exists('civicrm_contact_sort_name', $row) &&
681 !empty($rows[$rowNum]['civicrm_contact_sort_name']) &&
6a488035
TO
682 array_key_exists('civicrm_contact_id', $row)
683 ) {
684 $url = CRM_Utils_System::url("civicrm/contact/view",
685 'reset=1&cid=' . $row['civicrm_contact_id'],
686 $this->_absoluteUrl
687 );
688 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
689 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contact Summary for this Contact.");
690 }
691
6a488035
TO
692 if ($value = CRM_Utils_Array::value('civicrm_contribution_financial_type_id', $row)) {
693 $rows[$rowNum]['civicrm_contribution_financial_type_id'] = $contributionTypes[$value];
694 $entryFound = TRUE;
695 }
696 if ($value = CRM_Utils_Array::value('civicrm_contribution_contribution_status_id', $row)) {
697 $rows[$rowNum]['civicrm_contribution_contribution_status_id'] = $contributionStatus[$value];
698 $entryFound = TRUE;
699 }
0d0e945a
DG
700 if ($value = CRM_Utils_Array::value('civicrm_contribution_contribution_page_id', $row)) {
701 $rows[$rowNum]['civicrm_contribution_contribution_page_id'] = $contributionPages[$value];
702 $entryFound = TRUE;
703 }
6a488035
TO
704 if ($value = CRM_Utils_Array::value('civicrm_contribution_payment_instrument_id', $row)) {
705 $rows[$rowNum]['civicrm_contribution_payment_instrument_id'] = $paymentInstruments[$value];
706 $entryFound = TRUE;
707 }
433465bc
PN
708 if (!empty($row['civicrm_batch_batch_id'])) {
709 $rows[$rowNum]['civicrm_batch_batch_id'] = CRM_Utils_Array::value($row['civicrm_batch_batch_id'], $batches);
6a488035
TO
710 $entryFound = TRUE;
711 }
5e0343e8 712 if (!empty($row['civicrm_financial_trxn_card_type_id'])) {
713 $rows[$rowNum]['civicrm_financial_trxn_card_type_id'] = $this->getLabels($row['civicrm_financial_trxn_card_type_id'], 'CRM_Financial_DAO_FinancialTrxn', 'card_type_id');
e5f5c94b
E
714 $entryFound = TRUE;
715 }
6a488035
TO
716
717 // Contribution amount links to viewing contribution
f568f786 718 if (($value = CRM_Utils_Array::value('civicrm_contribution_total_amount', $row)) &&
6a488035
TO
719 CRM_Core_Permission::check('access CiviContribute')
720 ) {
721 $url = CRM_Utils_System::url("civicrm/contact/view/contribution",
9d72cede
EM
722 "reset=1&id=" . $row['civicrm_contribution_contribution_id'] .
723 "&cid=" . $row['civicrm_contact_id'] .
724 "&action=view&context=contribution&selectedChild=contribute",
6a488035
TO
725 $this->_absoluteUrl
726 );
f568f786 727 $rows[$rowNum]['civicrm_contribution_total_amount_link'] = $url;
728 $rows[$rowNum]['civicrm_contribution_total_amount_hover'] = ts("View Details of this Contribution.");
6a488035
TO
729 $entryFound = TRUE;
730 }
731
732 // convert campaign_id to campaign title
733 if (array_key_exists('civicrm_contribution_campaign_id', $row)) {
734 if ($value = $row['civicrm_contribution_campaign_id']) {
735 $rows[$rowNum]['civicrm_contribution_campaign_id'] = $this->activeCampaigns[$value];
736 $entryFound = TRUE;
737 }
738 }
739
70c41bce
DS
740 // soft credits
741 if (array_key_exists('civicrm_contribution_soft_credits', $row) &&
9d72cede
EM
742 'Contribution' ==
743 CRM_Utils_Array::value('civicrm_contribution_contribution_or_soft', $rows[$rowNum]) &&
70c41bce
DS
744 array_key_exists('civicrm_contribution_contribution_id', $row)
745 ) {
746 $query = "
e6bab5ea 747SELECT civicrm_contact_id, civicrm_contact_sort_name, civicrm_contribution_total_amount, civicrm_contribution_currency
70c41bce
DS
748FROM civireport_contribution_detail_temp2
749WHERE civicrm_contribution_contribution_id={$row['civicrm_contribution_contribution_id']}";
3b2bbbfb 750 $this->addToDeveloperTab($query);
9d72cede 751 $dao = CRM_Core_DAO::executeQuery($query);
70c41bce 752 $string = '';
1ebef749 753 $separator = ($this->_outputMode !== 'csv') ? "<br/>" : ' ';
70c41bce 754 while ($dao->fetch()) {
9d72cede
EM
755 $url = CRM_Utils_System::url("civicrm/contact/view", 'reset=1&cid=' .
756 $dao->civicrm_contact_id);
757 $string = $string . ($string ? $separator : '') .
758 "<a href='{$url}'>{$dao->civicrm_contact_sort_name}</a> " .
e6bab5ea 759 CRM_Utils_Money::format($dao->civicrm_contribution_total_amount, $dao->civicrm_contribution_currency);
70c41bce
DS
760 }
761 $rows[$rowNum]['civicrm_contribution_soft_credits'] = $string;
762 }
763
764 if (array_key_exists('civicrm_contribution_soft_credit_for', $row) &&
9d72cede
EM
765 'Soft Credit' ==
766 CRM_Utils_Array::value('civicrm_contribution_contribution_or_soft', $rows[$rowNum]) &&
70c41bce
DS
767 array_key_exists('civicrm_contribution_contribution_id', $row)
768 ) {
769 $query = "
f813f78e 770SELECT civicrm_contact_id, civicrm_contact_sort_name
70c41bce
DS
771FROM civireport_contribution_detail_temp1
772WHERE civicrm_contribution_contribution_id={$row['civicrm_contribution_contribution_id']}";
3b2bbbfb 773 $this->addToDeveloperTab($query);
9d72cede 774 $dao = CRM_Core_DAO::executeQuery($query);
70c41bce
DS
775 $string = '';
776 while ($dao->fetch()) {
9d72cede
EM
777 $url = CRM_Utils_System::url("civicrm/contact/view", 'reset=1&cid=' .
778 $dao->civicrm_contact_id);
779 $string = $string .
780 "\n<a href='{$url}'>{$dao->civicrm_contact_sort_name}</a>";
70c41bce
DS
781 }
782 $rows[$rowNum]['civicrm_contribution_soft_credit_for'] = $string;
783 }
784
e468f7a2 785 // CRM-18312 - hide 'contribution_or_soft' column if unchecked.
786 if (!empty($this->noDisplayContributionOrSoftColumn)) {
787 unset($rows[$rowNum]['civicrm_contribution_contribution_or_soft']);
788 unset($this->_columnHeaders['civicrm_contribution_contribution_or_soft']);
789 }
790
51fa20cb 791 //convert soft_credit_type_id into label
792 if (array_key_exists('civicrm_contribution_soft_soft_credit_type_id', $rows[$rowNum])) {
7a4192f7 793 $rows[$rowNum]['civicrm_contribution_soft_soft_credit_type_id'] = CRM_Core_PseudoConstant::getLabel(
794 'CRM_Contribute_BAO_ContributionSoft',
795 'soft_credit_type_id',
796 $row['civicrm_contribution_soft_soft_credit_type_id']
797 );
51fa20cb 798 }
799
6a488035
TO
800 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'contribute/detail', 'List all contribution(s) for this ') ? TRUE : $entryFound;
801
802 // skip looking further in rows, if first row itself doesn't
803 // have the column we need
804 if (!$entryFound) {
805 break;
806 }
807 $lastKey = $rowNum;
808 }
809 }
1c4d8c3e 810
00be9182 811 public function sectionTotals() {
6a488035
TO
812
813 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
814 if (empty($this->_selectAliases)) {
815 return;
816 }
817
818 if (!empty($this->_sections)) {
819 // build the query with no LIMIT clause
9d72cede 820 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select);
6a488035
TO
821 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
822
823 // pull section aliases out of $this->_sections
824 $sectionAliases = array_keys($this->_sections);
825
826 $ifnulls = array();
827 foreach (array_merge($sectionAliases, $this->_selectAliases) as $alias) {
828 $ifnulls[] = "ifnull($alias, '') as $alias";
829 }
b708c08d 830 $this->_select = "SELECT " . implode(", ", $ifnulls);
36d2f4d5 831 $this->_select = CRM_Contact_BAO_Query::appendAnyValueToSelect($ifnulls, $sectionAliases);
6a488035
TO
832
833 /* Group (un-limited) report by all aliases and get counts. This might
e70a7fc0
TO
834 * be done more efficiently when the contents of $sql are known, ie. by
835 * overriding this method in the report class.
836 */
6a488035
TO
837
838 $addtotals = '';
839
f568f786 840 if (array_search("civicrm_contribution_total_amount", $this->_selectAliases) !==
9d72cede
EM
841 FALSE
842 ) {
f568f786 843 $addtotals = ", sum(civicrm_contribution_total_amount) as sumcontribs";
6a488035
TO
844 $showsumcontribs = TRUE;
845 }
846
b708c08d 847 $query = $this->_select .
9d72cede
EM
848 "$addtotals, count(*) as ct from civireport_contribution_detail_temp3 group by " .
849 implode(", ", $sectionAliases);
6a488035
TO
850 // initialize array of total counts
851 $sumcontribs = $totals = array();
852 $dao = CRM_Core_DAO::executeQuery($query);
3b2bbbfb 853 $this->addToDeveloperTab($query);
6a488035
TO
854 while ($dao->fetch()) {
855
856 // let $this->_alterDisplay translate any integer ids to human-readable values.
857 $rows[0] = $dao->toArray();
858 $this->alterDisplay($rows);
859 $row = $rows[0];
860
861 // add totals for all permutations of section values
862 $values = array();
863 $i = 1;
864 $aliasCount = count($sectionAliases);
865 foreach ($sectionAliases as $alias) {
866 $values[] = $row[$alias];
867 $key = implode(CRM_Core_DAO::VALUE_SEPARATOR, $values);
868 if ($i == $aliasCount) {
869 // the last alias is the lowest-level section header; use count as-is
870 $totals[$key] = $dao->ct;
9d72cede
EM
871 if ($showsumcontribs) {
872 $sumcontribs[$key] = $dao->sumcontribs;
873 }
1c4d8c3e 874 }
6a488035
TO
875 else {
876 // other aliases are higher level; roll count into their total
84178120 877 $totals[$key] = (array_key_exists($key, $totals)) ? $totals[$key] + $dao->ct : $dao->ct;
1c4d8c3e 878 if ($showsumcontribs) {
84178120 879 $sumcontribs[$key] = array_key_exists($key, $sumcontribs) ? $sumcontribs[$key] + $dao->sumcontribs : $dao->sumcontribs;
6a488035
TO
880 }
881 }
882 }
883 }
884 if ($showsumcontribs) {
885 $totalandsum = array();
0161a899
ML
886 // ts exception to avoid having ts("%1 %2: %3")
887 $title = '%1 contributions / soft-credits: %2';
888
9d72cede
EM
889 if (CRM_Utils_Array::value('contribution_or_soft_value', $this->_params) ==
890 'contributions_only'
891 ) {
0161a899 892 $title = '%1 contributions: %2';
9d72cede 893 }
4c9b6178 894 elseif (CRM_Utils_Array::value('contribution_or_soft_value', $this->_params) ==
9d72cede
EM
895 'soft_credits_only'
896 ) {
0161a899 897 $title = '%1 soft-credits: %2';
bec9ef32 898 }
6a488035 899 foreach ($totals as $key => $total) {
0161a899 900 $totalandsum[$key] = ts($title, array(
1c4d8c3e 901 1 => $total,
21dfd5f5 902 2 => CRM_Utils_Money::format($sumcontribs[$key]),
10a5be27 903 ));
6a488035
TO
904 }
905 $this->assign('sectionTotals', $totalandsum);
906 }
907 else {
908 $this->assign('sectionTotals', $totals);
909 }
910 }
911 }
96025800 912
8b7f2513 913 /**
914 * Generate the from clause as it relates to the soft credits.
915 */
916 public function softCreditFrom() {
917
97b4dc6b 918 $this->_from = "
919 FROM civireport_contribution_detail_temp1 temp1_civireport
920 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
921 ON temp1_civireport.civicrm_contribution_contribution_id = {$this->_aliases['civicrm_contribution']}.id
922 INNER JOIN civicrm_contribution_soft contribution_soft_civireport
923 ON contribution_soft_civireport.contribution_id = {$this->_aliases['civicrm_contribution']}.id
924 INNER JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
925 ON {$this->_aliases['civicrm_contact']}.id = contribution_soft_civireport.contact_id
926 {$this->_aclFrom}
927 ";
8b7f2513 928
929 $this->appendAdditionalFromJoins();
930 }
931
932 /**
933 * Append the joins that are required regardless of context.
934 */
935 public function appendAdditionalFromJoins() {
936 if (!empty($this->_params['ordinality_value'])) {
937 $this->_from .= "
938 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']}
939 ON {$this->_aliases['civicrm_contribution_ordinality']}.id = {$this->_aliases['civicrm_contribution']}.id";
940 }
3b2bbbfb 941 $this->joinPhoneFromContact();
942 $this->joinAddressFromContact();
943 $this->joinEmailFromContact();
8b7f2513 944
8b7f2513 945 // include contribution note
946 if (!empty($this->_params['fields']['contribution_note']) ||
947 !empty($this->_params['note_value'])
948 ) {
949 $this->_from .= "
950 LEFT JOIN civicrm_note {$this->_aliases['civicrm_note']}
951 ON ( {$this->_aliases['civicrm_note']}.entity_table = 'civicrm_contribution' AND
952 {$this->_aliases['civicrm_contribution']}.id = {$this->_aliases['civicrm_note']}.entity_id )";
953 }
954 //for contribution batches
955 if (!empty($this->_params['fields']['batch_id']) ||
956 !empty($this->_params['bid_value'])
957 ) {
958 $this->_from .= "
959 LEFT JOIN civicrm_entity_financial_trxn eft
960 ON eft.entity_id = {$this->_aliases['civicrm_contribution']}.id AND
961 eft.entity_table = 'civicrm_contribution'
962 LEFT JOIN civicrm_entity_batch {$this->_aliases['civicrm_batch']}
963 ON ({$this->_aliases['civicrm_batch']}.entity_id = eft.financial_trxn_id
964 AND {$this->_aliases['civicrm_batch']}.entity_table = 'civicrm_financial_trxn')";
965 }
e5f5c94b 966 // for credit card type
125bbb86 967 $this->addFinancialTrxnFromClause();
8b7f2513 968 }
969
6a488035 970}