3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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 +--------------------------------------------------------------------+
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.
35 * !!!!!!!!!!!!!!!!!!!!
42 * @copyright CiviCRM LLC (c) 2004-2019
44 class CRM_Report_Form_Pledge_Detail
extends CRM_Report_Form
{
46 protected $_summary = NULL;
47 protected $_totalPaid = FALSE;
48 protected $_pledgeStatuses = [];
49 protected $_customGroupExtends = [
55 * This report has not been optimised for group filtering.
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.
65 protected $groupFilterNotOptimised = TRUE;
70 public function __construct() {
71 $this->_pledgeStatuses
= CRM_Core_OptionGroup
::values('pledge_status',
72 FALSE, FALSE, FALSE, NULL, 'label'
76 'civicrm_contact' => [
77 'dao' => 'CRM_Contact_DAO_Contact',
80 'title' => ts('Contact Name'),
86 'sort_name' => ['title' => ts('Contact Name')],
87 'id' => ['no_display' => TRUE],
89 'grouping' => 'contact-fields',
92 'dao' => 'CRM_Core_DAO_Email',
94 'email' => ['no_repeat' => TRUE],
96 'grouping' => 'contact-fields',
99 'dao' => 'CRM_Pledge_DAO_Pledge',
102 'no_display' => TRUE,
106 'no_display' => TRUE,
109 'financial_type_id' => [
110 'title' => ts('Financial Type'),
113 'title' => ts('Pledge Amount'),
115 'type' => CRM_Utils_Type
::T_MONEY
,
119 'no_display' => TRUE,
121 'frequency_unit' => [
122 'title' => ts('Frequency Unit'),
125 'title' => ts('Installments'),
127 'pledge_create_date' => [
128 'title' => ts('Pledge Made Date'),
131 'title' => ts('Pledge Start Date'),
132 'type' => CRM_Utils_Type
::T_DATE
,
135 'title' => ts('Pledge End Date'),
136 'type' => CRM_Utils_Type
::T_DATE
,
139 'title' => ts('Pledge Status'),
144 'pledge_create_date' => [
145 'title' => ts('Pledge Made Date'),
146 'operatorType' => CRM_Report_Form
::OP_DATE
,
149 'title' => ts('Pledged Amount'),
150 'operatorType' => CRM_Report_Form
::OP_INT
,
153 'title' => ts('Currency'),
154 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
155 'options' => CRM_Core_OptionGroup
::values('currencies_enabled'),
157 'type' => CRM_Utils_Type
::T_STRING
,
160 'name' => 'status_id',
161 'title' => ts('Pledge Status'),
162 'type' => CRM_Utils_Type
::T_INT
,
163 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
164 'options' => CRM_Core_OptionGroup
::values('pledge_status'),
166 'financial_type_id' => [
167 'title' => ts('Financial Type'),
168 'type' => CRM_Utils_Type
::T_INT
,
169 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
170 'options' => CRM_Contribute_PseudoConstant
::financialType(),
175 'civicrm_pledge_payment' => [
176 'dao' => 'CRM_Pledge_DAO_PledgePayment',
179 'title' => ts('Total Amount Paid'),
180 'type' => CRM_Utils_Type
::T_MONEY
,
183 'title' => ts('Balance Due'),
185 'type' => CRM_Utils_Type
::T_MONEY
,
191 $this->_columns +
= $this->getAddressColumns(['group_by' => FALSE]) +
$this->getPhoneColumns();
193 // If we have a campaign, build out the relevant elements
194 $this->addCampaignFields('civicrm_pledge', TRUE);
196 $this->_groupFilter
= TRUE;
197 $this->_tagFilter
= TRUE;
198 $this->_currencyColumn
= 'civicrm_pledge_currency';
199 parent
::__construct();
202 public function preProcess() {
203 parent
::preProcess();
206 public function select() {
211 * If we are retrieving total paid we need to define the inclusion of pledge_payment.
213 * @param string $tableName
215 * @param string $fieldName
218 * @return bool|string
220 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
221 if ($fieldName == 'total_paid') {
222 // add pledge_payment join
223 $this->_totalPaid
= TRUE;
224 $this->_columnHeaders
["{$tableName}_{$fieldName}"] = [
225 'title' => $field['title'],
226 'type' => $field['type'],
228 return "COALESCE(sum({$this->_aliases[$tableName]}.actual_amount), 0) as {$tableName}_{$fieldName}";
230 if ($fieldName == 'balance_due') {
231 $cancelledStatus = array_search('Cancelled', $this->_pledgeStatuses
);
232 $completedStatus = array_search('Completed', $this->_pledgeStatuses
);
233 // add pledge_payment join
234 $this->_totalPaid
= TRUE;
235 $this->_columnHeaders
["{$tableName}_{$fieldName}"] = $field['title'];
236 $this->_columnHeaders
["{$tableName}_{$fieldName}"] = [
237 'title' => $field['title'],
238 'type' => $field['type'],
240 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}";
245 public function groupBy() {
247 if (empty($this->_groupBy
) && $this->_totalPaid
) {
248 $groupBy = ["{$this->_aliases['civicrm_pledge']}.id", "{$this->_aliases['civicrm_pledge']}.currency"];
249 $this->_groupBy
= CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($this->_selectClauses
, $groupBy);
253 public function from() {
255 FROM civicrm_pledge {$this->_aliases['civicrm_pledge']}
256 LEFT JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
257 ON ({$this->_aliases['civicrm_contact']}.id =
258 {$this->_aliases['civicrm_pledge']}.contact_id )
261 if ($this->_totalPaid
) {
263 LEFT JOIN civicrm_pledge_payment {$this->_aliases['civicrm_pledge_payment']} ON
264 {$this->_aliases['civicrm_pledge']}.id = {$this->_aliases['civicrm_pledge_payment']}.pledge_id
265 AND {$this->_aliases['civicrm_pledge_payment']}.status_id = 1
269 $this->joinPhoneFromContact();
270 $this->joinAddressFromContact();
271 $this->joinEmailFromContact();
279 public function statistics(&$rows) {
280 $statistics = parent
::statistics($rows);
281 //regenerate the from field without extra left join on pledge payments
282 $totalPaid = $this->_totalPaid
;
283 $this->_totalPaid
= FALSE;
285 $this->customDataFrom();
286 if (!$this->_having
) {
287 $totalAmount = $average = [];
290 SELECT COUNT({$this->_aliases['civicrm_pledge']}.amount ) as count,
291 SUM({$this->_aliases['civicrm_pledge']}.amount ) as amount,
292 ROUND(AVG({$this->_aliases['civicrm_pledge']}.amount), 2) as avg,
293 {$this->_aliases['civicrm_pledge']}.currency as currency
296 $group = "GROUP BY {$this->_aliases['civicrm_pledge']}.currency";
297 $sql = "{$select} {$this->_from} {$this->_where} {$group}";
298 $dao = CRM_Core_DAO
::executeQuery($sql);
299 $count = $index = $totalCount = 0;
300 // this will run once per currency
301 while ($dao->fetch()) {
302 $totalAmount = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
303 $average = CRM_Utils_Money
::format($dao->avg
, $dao->currency
);
304 $count = $dao->count
;
305 $totalCount .= $count;
306 $statistics['counts']['amount' . $index] = [
307 'title' => ts('Total Pledged') . ' (' . $dao->currency
. ')',
308 'value' => $totalAmount,
309 'type' => CRM_Utils_Type
::T_STRING
,
311 $statistics['counts']['avg' . $index] = [
312 'title' => ts('Average') . ' (' . $dao->currency
. ')',
314 'type' => CRM_Utils_Type
::T_STRING
,
316 $statistics['counts']['count' . $index] = [
317 'title' => ts('Total No Pledges') . ' (' . $dao->currency
. ')',
319 'type' => CRM_Utils_Type
::T_INT
,
323 if ($totalCount > $count) {
324 $statistics['counts']['count' . $index] = [
325 'title' => ts('Total No Pledges'),
326 'value' => $totalCount,
327 'type' => CRM_Utils_Type
::T_INT
,
333 $this->_totalPaid
= TRUE;
339 public function orderBy() {
340 $this->_orderBy
= "ORDER BY {$this->_aliases['civicrm_contact']}.sort_name, {$this->_aliases['civicrm_contact']}.id";
343 public function where() {
345 foreach ($this->_columns
as $tableName => $table) {
346 if (array_key_exists('filters', $table)) {
347 foreach ($table['filters'] as $fieldName => $field) {
349 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
350 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
351 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
352 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
354 if ($relative ||
$from ||
$to) {
355 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
359 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
361 $clause = $this->whereClause($field,
363 CRM_Utils_Array
::value("{$fieldName}_value",
366 CRM_Utils_Array
::value("{$fieldName}_min",
369 CRM_Utils_Array
::value("{$fieldName}_max",
376 if (!empty($clause)) {
377 $clauses[] = $clause;
382 if (empty($clauses)) {
383 $this->_where
= "WHERE ({$this->_aliases['civicrm_pledge']}.is_test=0 ) ";
386 $this->_where
= "WHERE ({$this->_aliases['civicrm_pledge']}.is_test=0 ) AND
387 " . implode(' AND ', $clauses);
390 if ($this->_aclWhere
) {
391 $this->_where
.= " AND {$this->_aclWhere} ";
395 public function postProcess() {
397 $this->beginPostProcess();
399 // get the acl clauses built before we assemble the query
400 $this->buildACLClause($this->_aliases
['civicrm_contact']);
401 $sql = $this->buildQuery();
402 $rows = $payment = [];
404 $dao = CRM_Core_DAO
::executeQuery($sql);
406 // Set pager for the Main Query only which displays basic information
408 $this->assign('columnHeaders', $this->_columnHeaders
);
410 while ($dao->fetch()) {
411 $pledgeID = $dao->civicrm_pledge_id
;
412 foreach ($this->_columnHeaders
as $columnHeadersKey => $columnHeadersValue) {
414 if (property_exists($dao, $columnHeadersKey)) {
415 $display[$pledgeID][$columnHeadersKey] = $dao->$columnHeadersKey;
418 $pledgeIDArray[] = $pledgeID;
421 // Add Special headers
422 $this->_columnHeaders
['scheduled_date'] = [
423 'type' => CRM_Utils_Type
::T_DATE
,
424 'title' => ts('Next Payment Due'),
426 $this->_columnHeaders
['scheduled_amount'] = [
427 'type' => CRM_Utils_Type
::T_MONEY
,
428 'title' => ts('Next Payment Amount'),
430 $this->_columnHeaders
['status_id'] = NULL;
433 * this is purely about ordering the total paid & balance due fields off to the end
434 * of the table in case custom or address fields cause them to fall in the middle
435 * (arguably the pledge amount should be moved to after these fields too)
439 'civicrm_pledge_payment_total_paid',
440 'civicrm_pledge_payment_balance_due',
443 foreach ($tableHeaders as $header) {
444 //per above, unset & reset them so they move to the end
445 if (isset($this->_columnHeaders
[$header])) {
446 $headervalue = $this->_columnHeaders
[$header];
447 unset($this->_columnHeaders
[$header]);
448 $this->_columnHeaders
[$header] = $headervalue;
452 // To Display Payment Details of pledged amount
453 // for pledge payments In Progress
454 if (!empty($display)) {
455 $statusId = array_keys(CRM_Core_PseudoConstant
::accountOptionValues("contribution_status", NULL, " AND v.name IN ('Pending', 'Overdue')"));
456 $statusId = implode(',', $statusId);
457 $select = "payment.pledge_id, payment.scheduled_amount, pledge.contact_id";
459 SELECT min(payment.scheduled_date) as scheduled_date,
462 FROM civicrm_pledge_payment payment
463 LEFT JOIN civicrm_pledge pledge
464 ON pledge.id = payment.pledge_id
466 WHERE payment.status_id IN ({$statusId})
470 $daoPayment = CRM_Core_DAO
::executeQuery($sqlPayment);
472 while ($daoPayment->fetch()) {
473 foreach ($pledgeIDArray as $key => $val) {
474 if ($val == $daoPayment->pledge_id
) {
476 $display[$daoPayment->pledge_id
]['scheduled_date'] = $daoPayment->scheduled_date
;
478 $display[$daoPayment->pledge_id
]['scheduled_amount'] = $daoPayment->scheduled_amount
;
484 // Displaying entire data on the form
485 if (!empty($display)) {
486 foreach ($display as $key => $value) {
488 foreach ($this->_columnHeaders
as $columnKey => $columnValue) {
489 if (array_key_exists($columnKey, $value)) {
490 $row[$columnKey] = !empty($value[$columnKey]) ?
$value[$columnKey] : '';
497 unset($this->_columnHeaders
['status_id']);
498 unset($this->_columnHeaders
['civicrm_pledge_id']);
499 unset($this->_columnHeaders
['civicrm_pledge_contact_id']);
501 $this->formatDisplay($rows, FALSE);
502 $this->doTemplateAssignment($rows);
503 $this->endPostProcess($rows);
507 * Alter display of rows.
509 * Iterate through the rows retrieved via SQL and make changes for display purposes,
510 * such as rendering contacts as links.
513 * Rows generated by SQL, with an array for each row.
515 public function alterDisplay(&$rows) {
518 $display_flag = $prev_cid = $cid = 0;
520 foreach ($rows as $rowNum => $row) {
521 if (!empty($this->_noRepeats
) && $this->_outputMode
!= 'csv') {
522 // don't repeat contact details if its same as the previous row
523 if (array_key_exists('civicrm_pledge_contact_id', $row)) {
524 if ($cid = $row['civicrm_pledge_contact_id']) {
529 if ($prev_cid == $cid) {
540 foreach ($row as $colName => $colVal) {
541 if (in_array($colName, $this->_noRepeats
)) {
542 unset($rows[$rowNum][$colName]);
551 // convert display name to links
552 if (array_key_exists('civicrm_contact_sort_name', $row) &&
553 array_key_exists('civicrm_pledge_contact_id', $row)
555 $url = CRM_Utils_System
::url("civicrm/contact/view",
556 'reset=1&cid=' . $row['civicrm_pledge_contact_id'],
559 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
560 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contact Summary for this Contact.");
564 if (array_key_exists('civicrm_pledge_financial_type_id', $row)) {
565 if ($value = $row['civicrm_pledge_financial_type_id']) {
566 $rows[$rowNum]['civicrm_pledge_financial_type_id'] = CRM_Contribute_PseudoConstant
::financialType($value, FALSE);
572 if (array_key_exists('civicrm_pledge_status_id', $row)) {
573 if ($value = $row['civicrm_pledge_status_id']) {
574 $rows[$rowNum]['civicrm_pledge_status_id'] = CRM_Core_PseudoConstant
::getLabel('CRM_Pledge_BAO_Pledge', 'status_id', $value);
579 // If using campaigns, convert campaign_id to campaign title
580 if (array_key_exists('civicrm_pledge_campaign_id', $row)) {
581 if ($value = $row['civicrm_pledge_campaign_id']) {
582 $rows[$rowNum]['civicrm_pledge_campaign_id'] = $this->campaigns
[$value];
587 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'pledge/detail', 'List all pledge(s) for this ') ?
TRUE : $entryFound;
589 // skip looking further in rows, if first row itself doesn't
590 // have the column we need