Merge pull request #11986 from eileenmcnaughton/test
[civicrm-core.git] / CRM / Report / Form / Pledge / Detail.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28
29 /*
30 * !!!!!!!!!!!!!!!!!!!!
31 * NB: this is named detail but behaves like a summary report.
32 * It is also accessed through the Pledge Summary link in the UI
33 * This should presumably be changed.
34 * ~ Doten
35 * !!!!!!!!!!!!!!!!!!!!
36 *
37 */
38
39 /**
40 *
41 * @package CRM
42 * @copyright CiviCRM LLC (c) 2004-2018
43 */
44 class CRM_Report_Form_Pledge_Detail extends CRM_Report_Form {
45
46 protected $_summary = NULL;
47 protected $_totalPaid = FALSE;
48 protected $_pledgeStatuses = array();
49 protected $_customGroupExtends = array(
50 'Pledge',
51 'Individual',
52 );
53
54 /**
55 * This report has not been optimised for group filtering.
56 *
57 * The functionality for group filtering has been improved but not
58 * all reports have been adjusted to take care of it. This report has not
59 * and will run an inefficient query until fixed.
60 *
61 * CRM-19170
62 *
63 * @var bool
64 */
65 protected $groupFilterNotOptimised = TRUE;
66
67 /**
68 * Class constructor.
69 */
70 public function __construct() {
71 $this->_pledgeStatuses = CRM_Core_OptionGroup::values('pledge_status',
72 FALSE, FALSE, FALSE, NULL, 'label'
73 );
74 // Check if CiviCampaign is a) enabled and b) has active campaigns
75 $config = CRM_Core_Config::singleton();
76 $campaignEnabled = in_array("CiviCampaign", $config->enableComponents);
77 if ($campaignEnabled) {
78 $getCampaigns = CRM_Campaign_BAO_Campaign::getPermissionedCampaigns(NULL, NULL, TRUE, FALSE, TRUE);
79 $this->activeCampaigns = $getCampaigns['campaigns'];
80 asort($this->activeCampaigns);
81 }
82
83 $this->_columns = array(
84 'civicrm_contact' => array(
85 'dao' => 'CRM_Contact_DAO_Contact',
86 'fields' => array(
87 'sort_name' => array(
88 'title' => ts('Contact Name'),
89 'required' => TRUE,
90 'no_repeat' => TRUE,
91 ),
92 ),
93 'filters' => array(
94 'sort_name' => array('title' => ts('Contact Name')),
95 'id' => array('no_display' => TRUE),
96 ),
97 'grouping' => 'contact-fields',
98 ),
99 'civicrm_email' => array(
100 'dao' => 'CRM_Core_DAO_Email',
101 'fields' => array(
102 'email' => array('no_repeat' => TRUE),
103 ),
104 'grouping' => 'contact-fields',
105 ),
106 'civicrm_pledge' => array(
107 'dao' => 'CRM_Pledge_DAO_Pledge',
108 'fields' => array(
109 'id' => array(
110 'no_display' => TRUE,
111 'required' => TRUE,
112 ),
113 'contact_id' => array(
114 'no_display' => TRUE,
115 'required' => TRUE,
116 ),
117 'financial_type_id' => array(
118 'title' => ts('Financial Type'),
119 ),
120 'amount' => array(
121 'title' => ts('Pledge Amount'),
122 'required' => TRUE,
123 'type' => CRM_Utils_Type::T_MONEY,
124 ),
125 'currency' => array(
126 'required' => TRUE,
127 'no_display' => TRUE,
128 ),
129 'frequency_unit' => array(
130 'title' => ts('Frequency Unit'),
131 ),
132 'installments' => array(
133 'title' => ts('Installments'),
134 ),
135 'pledge_create_date' => array(
136 'title' => ts('Pledge Made Date'),
137 ),
138 'start_date' => array(
139 'title' => ts('Pledge Start Date'),
140 'type' => CRM_Utils_Type::T_DATE,
141 ),
142 'end_date' => array(
143 'title' => ts('Pledge End Date'),
144 'type' => CRM_Utils_Type::T_DATE,
145 ),
146 'status_id' => array(
147 'title' => ts('Pledge Status'),
148 'required' => TRUE,
149 ),
150 ),
151 'filters' => array(
152 'pledge_create_date' => array(
153 'title' => ts('Pledge Made Date'),
154 'operatorType' => CRM_Report_Form::OP_DATE,
155 ),
156 'pledge_amount' => array(
157 'title' => ts('Pledged Amount'),
158 'operatorType' => CRM_Report_Form::OP_INT,
159 ),
160 'currency' => array(
161 'title' => ts('Currency'),
162 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
163 'options' => CRM_Core_OptionGroup::values('currencies_enabled'),
164 'default' => NULL,
165 'type' => CRM_Utils_Type::T_STRING,
166 ),
167 'sid' => array(
168 'name' => 'status_id',
169 'title' => ts('Pledge Status'),
170 'type' => CRM_Utils_Type::T_INT,
171 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
172 'options' => CRM_Core_OptionGroup::values('pledge_status'),
173 ),
174 'financial_type_id' => array(
175 'title' => ts('Financial Type'),
176 'type' => CRM_Utils_Type::T_INT,
177 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
178 'options' => CRM_Contribute_PseudoConstant::financialType(),
179 ),
180
181 ),
182 ),
183 'civicrm_pledge_payment' => array(
184 'dao' => 'CRM_Pledge_DAO_PledgePayment',
185 'fields' => array(
186 'total_paid' => array(
187 'title' => ts('Total Amount Paid'),
188 'type' => CRM_Utils_Type::T_MONEY,
189 ),
190 'balance_due' => array(
191 'title' => ts('Balance Due'),
192 'default' => TRUE,
193 'type' => CRM_Utils_Type::T_MONEY,
194 ),
195 ),
196 ),
197 );
198
199 $this->_columns += $this->getAddressColumns(array('group_by' => FALSE)) + $this->getPhoneColumns();
200
201 // If we have a campaign, build out the relevant elements
202 $this->_tagFilter = TRUE;
203 if ($campaignEnabled && !empty($this->activeCampaigns)) {
204 $this->_columns['civicrm_pledge']['fields']['campaign_id'] = array(
205 'title' => ts('Campaign'),
206 'default' => 'false',
207 );
208 $this->_columns['civicrm_pledge']['filters']['campaign_id'] = array(
209 'title' => ts('Campaign'),
210 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
211 'options' => $this->activeCampaigns,
212 'type' => CRM_Utils_Type::T_INT,
213 );
214 $this->_columns['civicrm_pledge']['group_bys']['campaign_id'] = array('title' => ts('Campaign'));
215
216 }
217
218 $this->_groupFilter = TRUE;
219 $this->_tagFilter = TRUE;
220 $this->_currencyColumn = 'civicrm_pledge_currency';
221 parent::__construct();
222 }
223
224 public function preProcess() {
225 parent::preProcess();
226 }
227
228 public function select() {
229 parent::select();
230 }
231
232 /**
233 * If we are retrieving total paid we need to define the inclusion of pledge_payment.
234 *
235 * @param string $tableName
236 * @param $tableKey
237 * @param string $fieldName
238 * @param $field
239 *
240 * @return bool|string
241 */
242 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
243 if ($fieldName == 'total_paid') {
244 $this->_totalPaid = TRUE; // add pledge_payment join
245 $this->_columnHeaders["{$tableName}_{$fieldName}"] = array(
246 'title' => $field['title'],
247 'type' => $field['type'],
248 );
249 return "COALESCE(sum({$this->_aliases[$tableName]}.actual_amount), 0) as {$tableName}_{$fieldName}";
250 }
251 if ($fieldName == 'balance_due') {
252 $cancelledStatus = array_search('Cancelled', $this->_pledgeStatuses);
253 $completedStatus = array_search('Completed', $this->_pledgeStatuses);
254 $this->_totalPaid = TRUE; // add pledge_payment join
255 $this->_columnHeaders["{$tableName}_{$fieldName}"] = $field['title'];
256 $this->_columnHeaders["{$tableName}_{$fieldName}"] = array(
257 'title' => $field['title'],
258 'type' => $field['type'],
259 );
260 return "IF({$this->_aliases['civicrm_pledge']}.status_id IN({$cancelledStatus}, $completedStatus), 0, COALESCE({$this->_aliases['civicrm_pledge']}.amount, 0) - COALESCE(sum({$this->_aliases[$tableName]}.actual_amount),0)) as {$tableName}_{$fieldName}";
261 }
262 return FALSE;
263 }
264
265 public function groupBy() {
266 parent::groupBy();
267 if (empty($this->_groupBy) && $this->_totalPaid) {
268 $groupBy = array("{$this->_aliases['civicrm_pledge']}.id", "{$this->_aliases['civicrm_pledge']}.currency");
269 $this->_groupBy = CRM_Contact_BAO_Query::getGroupByFromSelectColumns($this->_selectClauses, $groupBy);
270 }
271 }
272
273 public function from() {
274 $this->_from = "
275 FROM civicrm_pledge {$this->_aliases['civicrm_pledge']}
276 LEFT JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
277 ON ({$this->_aliases['civicrm_contact']}.id =
278 {$this->_aliases['civicrm_pledge']}.contact_id )
279 {$this->_aclFrom} ";
280
281 if ($this->_totalPaid) {
282 $this->_from .= "
283 LEFT JOIN civicrm_pledge_payment {$this->_aliases['civicrm_pledge_payment']} ON
284 {$this->_aliases['civicrm_pledge']}.id = {$this->_aliases['civicrm_pledge_payment']}.pledge_id
285 AND {$this->_aliases['civicrm_pledge_payment']}.status_id = 1
286 ";
287 }
288
289 $this->joinPhoneFromContact();
290 $this->joinAddressFromContact();
291 $this->joinEmailFromContact();
292 }
293
294 /**
295 * @param $rows
296 *
297 * @return array
298 */
299 public function statistics(&$rows) {
300 $statistics = parent::statistics($rows);
301 //regenerate the from field without extra left join on pledge payments
302 $totalPaid = $this->_totalPaid;
303 $this->_totalPaid = FALSE;
304 $this->from();
305 $this->customDataFrom();
306 if (!$this->_having) {
307 $totalAmount = $average = array();
308 $count = 0;
309 $select = "
310 SELECT COUNT({$this->_aliases['civicrm_pledge']}.amount ) as count,
311 SUM({$this->_aliases['civicrm_pledge']}.amount ) as amount,
312 ROUND(AVG({$this->_aliases['civicrm_pledge']}.amount), 2) as avg,
313 {$this->_aliases['civicrm_pledge']}.currency as currency
314 ";
315
316 $group = "GROUP BY {$this->_aliases['civicrm_pledge']}.currency";
317 $sql = "{$select} {$this->_from} {$this->_where} {$group}";
318 $dao = CRM_Core_DAO::executeQuery($sql);
319 $count = $index = $totalCount = 0;
320 // this will run once per currency
321 while ($dao->fetch()) {
322 $totalAmount = CRM_Utils_Money::format($dao->amount, $dao->currency);
323 $average = CRM_Utils_Money::format($dao->avg, $dao->currency);
324 $count = $dao->count;
325 $totalCount .= $count;
326 $statistics['counts']['amount' . $index] = array(
327 'title' => ts('Total Pledged') . ' (' . $dao->currency . ')',
328 'value' => $totalAmount,
329 'type' => CRM_Utils_Type::T_STRING,
330 );
331 $statistics['counts']['avg' . $index] = array(
332 'title' => ts('Average') . ' (' . $dao->currency . ')',
333 'value' => $average,
334 'type' => CRM_Utils_Type::T_STRING,
335 );
336 $statistics['counts']['count' . $index] = array(
337 'title' => ts('Total No Pledges') . ' (' . $dao->currency . ')',
338 'value' => $count,
339 'type' => CRM_Utils_Type::T_INT,
340 );
341 $index++;
342 }
343 if ($totalCount > $count) {
344 $statistics['counts']['count' . $index] = array(
345 'title' => ts('Total No Pledges'),
346 'value' => $totalCount,
347 'type' => CRM_Utils_Type::T_INT,
348 );
349 }
350 }
351 // reset from clause
352 if ($totalPaid) {
353 $this->_totalPaid = TRUE;
354 $this->from();
355 }
356 return $statistics;
357 }
358
359 public function orderBy() {
360 $this->_orderBy = "ORDER BY {$this->_aliases['civicrm_contact']}.sort_name, {$this->_aliases['civicrm_contact']}.id";
361 }
362
363 public function where() {
364 $clauses = array();
365 foreach ($this->_columns as $tableName => $table) {
366 if (array_key_exists('filters', $table)) {
367 foreach ($table['filters'] as $fieldName => $field) {
368 $clause = NULL;
369 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
370 $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
371 $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
372 $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
373
374 if ($relative || $from || $to) {
375 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
376 }
377 }
378 else {
379 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
380 if ($op) {
381 $clause = $this->whereClause($field,
382 $op,
383 CRM_Utils_Array::value("{$fieldName}_value",
384 $this->_params
385 ),
386 CRM_Utils_Array::value("{$fieldName}_min",
387 $this->_params
388 ),
389 CRM_Utils_Array::value("{$fieldName}_max",
390 $this->_params
391 )
392 );
393 }
394 }
395
396 if (!empty($clause)) {
397 $clauses[] = $clause;
398 }
399 }
400 }
401 }
402 if (empty($clauses)) {
403 $this->_where = "WHERE ({$this->_aliases['civicrm_pledge']}.is_test=0 ) ";
404 }
405 else {
406 $this->_where = "WHERE ({$this->_aliases['civicrm_pledge']}.is_test=0 ) AND
407 " . implode(' AND ', $clauses);
408 }
409
410 if ($this->_aclWhere) {
411 $this->_where .= " AND {$this->_aclWhere} ";
412 }
413 }
414
415 public function postProcess() {
416
417 $this->beginPostProcess();
418
419 // get the acl clauses built before we assemble the query
420 $this->buildACLClause($this->_aliases['civicrm_contact']);
421 $sql = $this->buildQuery();
422 $rows = $payment = array();
423
424 $dao = CRM_Core_DAO::executeQuery($sql);
425
426 // Set pager for the Main Query only which displays basic information
427 $this->setPager();
428 $this->assign('columnHeaders', $this->_columnHeaders);
429
430 while ($dao->fetch()) {
431 $pledgeID = $dao->civicrm_pledge_id;
432 foreach ($this->_columnHeaders as $columnHeadersKey => $columnHeadersValue) {
433 $row = array();
434 if (property_exists($dao, $columnHeadersKey)) {
435 $display[$pledgeID][$columnHeadersKey] = $dao->$columnHeadersKey;
436 }
437 }
438 $pledgeIDArray[] = $pledgeID;
439 }
440
441 // Add Special headers
442 $this->_columnHeaders['scheduled_date'] = array(
443 'type' => CRM_Utils_Type::T_DATE,
444 'title' => ts('Next Payment Due'),
445 );
446 $this->_columnHeaders['scheduled_amount'] = array(
447 'type' => CRM_Utils_Type::T_MONEY,
448 'title' => ts('Next Payment Amount'),
449 );
450 $this->_columnHeaders['status_id'] = NULL;
451
452 /*
453 * this is purely about ordering the total paid & balance due fields off to the end
454 * of the table in case custom or address fields cause them to fall in the middle
455 * (arguably the pledge amount should be moved to after these fields too)
456 *
457 */
458 $tableHeaders = array(
459 'civicrm_pledge_payment_total_paid',
460 'civicrm_pledge_payment_balance_due',
461 );
462
463 foreach ($tableHeaders as $header) {
464 //per above, unset & reset them so they move to the end
465 if (isset($this->_columnHeaders[$header])) {
466 $headervalue = $this->_columnHeaders[$header];
467 unset($this->_columnHeaders[$header]);
468 $this->_columnHeaders[$header] = $headervalue;
469 }
470 }
471
472 // To Display Payment Details of pledged amount
473 // for pledge payments In Progress
474 if (!empty($display)) {
475 $statusId = array_keys(CRM_Core_PseudoConstant::accountOptionValues("contribution_status", NULL, " AND v.name IN ('Pending', 'Overdue')"));
476 $statusId = implode(',', $statusId);
477 $select = "payment.pledge_id, payment.scheduled_amount, pledge.contact_id";
478 $sqlPayment = "
479 SELECT min(payment.scheduled_date) as scheduled_date,
480 {$select}
481
482 FROM civicrm_pledge_payment payment
483 LEFT JOIN civicrm_pledge pledge
484 ON pledge.id = payment.pledge_id
485
486 WHERE payment.status_id IN ({$statusId})
487
488 GROUP BY {$select}";
489
490 $daoPayment = CRM_Core_DAO::executeQuery($sqlPayment);
491
492 while ($daoPayment->fetch()) {
493 foreach ($pledgeIDArray as $key => $val) {
494 if ($val == $daoPayment->pledge_id) {
495
496 $display[$daoPayment->pledge_id]['scheduled_date'] = $daoPayment->scheduled_date;
497
498 $display[$daoPayment->pledge_id]['scheduled_amount'] = $daoPayment->scheduled_amount;
499 }
500 }
501 }
502 }
503
504 // Displaying entire data on the form
505 if (!empty($display)) {
506 foreach ($display as $key => $value) {
507 $row = array();
508 foreach ($this->_columnHeaders as $columnKey => $columnValue) {
509 if (array_key_exists($columnKey, $value)) {
510 $row[$columnKey] = !empty($value[$columnKey]) ? $value[$columnKey] : '';
511 }
512 }
513 $rows[] = $row;
514 }
515 }
516
517 unset($this->_columnHeaders['status_id']);
518 unset($this->_columnHeaders['civicrm_pledge_id']);
519 unset($this->_columnHeaders['civicrm_pledge_contact_id']);
520
521 $this->formatDisplay($rows, FALSE);
522 $this->doTemplateAssignment($rows);
523 $this->endPostProcess($rows);
524 }
525
526 /**
527 * Alter display of rows.
528 *
529 * Iterate through the rows retrieved via SQL and make changes for display purposes,
530 * such as rendering contacts as links.
531 *
532 * @param array $rows
533 * Rows generated by SQL, with an array for each row.
534 */
535 public function alterDisplay(&$rows) {
536 $entryFound = FALSE;
537 $checkList = array();
538 $display_flag = $prev_cid = $cid = 0;
539
540 foreach ($rows as $rowNum => $row) {
541 if (!empty($this->_noRepeats) && $this->_outputMode != 'csv') {
542 // don't repeat contact details if its same as the previous row
543 if (array_key_exists('civicrm_pledge_contact_id', $row)) {
544 if ($cid = $row['civicrm_pledge_contact_id']) {
545 if ($rowNum == 0) {
546 $prev_cid = $cid;
547 }
548 else {
549 if ($prev_cid == $cid) {
550 $display_flag = 1;
551 $prev_cid = $cid;
552 }
553 else {
554 $display_flag = 0;
555 $prev_cid = $cid;
556 }
557 }
558
559 if ($display_flag) {
560 foreach ($row as $colName => $colVal) {
561 if (in_array($colName, $this->_noRepeats)) {
562 unset($rows[$rowNum][$colName]);
563 }
564 }
565 }
566 $entryFound = TRUE;
567 }
568 }
569 }
570
571 // convert display name to links
572 if (array_key_exists('civicrm_contact_sort_name', $row) &&
573 array_key_exists('civicrm_pledge_contact_id', $row)
574 ) {
575 $url = CRM_Utils_System::url("civicrm/contact/view",
576 'reset=1&cid=' . $row['civicrm_pledge_contact_id'],
577 $this->_absoluteUrl
578 );
579 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
580 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contact Summary for this Contact.");
581 $entryFound = TRUE;
582 }
583
584 if (array_key_exists('civicrm_pledge_financial_type_id', $row)) {
585 if ($value = $row['civicrm_pledge_financial_type_id']) {
586 $rows[$rowNum]['civicrm_pledge_financial_type_id'] = CRM_Contribute_PseudoConstant::financialType($value, FALSE);
587 }
588 $entryFound = TRUE;
589 }
590
591 //handle status id
592 if (array_key_exists('civicrm_pledge_status_id', $row)) {
593 if ($value = $row['civicrm_pledge_status_id']) {
594 $rows[$rowNum]['civicrm_pledge_status_id'] = CRM_Core_PseudoConstant::getLabel('CRM_Pledge_BAO_Pledge', 'status_id', $value);
595 }
596 $entryFound = TRUE;
597 }
598
599 // If using campaigns, convert campaign_id to campaign title
600 if (array_key_exists('civicrm_pledge_campaign_id', $row)) {
601 if ($value = $row['civicrm_pledge_campaign_id']) {
602 $rows[$rowNum]['civicrm_pledge_campaign_id'] = $this->activeCampaigns[$value];
603 }
604 $entryFound = TRUE;
605 }
606
607 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'pledge/detail', 'List all pledge(s) for this ') ? TRUE : $entryFound;
608
609 // skip looking further in rows, if first row itself doesn't
610 // have the column we need
611 if (!$entryFound) {
612 break;
613 }
614 }
615 }
616
617 }