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 = array();
49 protected $_customGroupExtends = array(
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'
75 $this->_columns
= array(
76 'civicrm_contact' => array(
77 'dao' => 'CRM_Contact_DAO_Contact',
80 'title' => ts('Contact Name'),
86 'sort_name' => array('title' => ts('Contact Name')),
87 'id' => array('no_display' => TRUE),
89 'grouping' => 'contact-fields',
91 'civicrm_email' => array(
92 'dao' => 'CRM_Core_DAO_Email',
94 'email' => array('no_repeat' => TRUE),
96 'grouping' => 'contact-fields',
98 'civicrm_pledge' => array(
99 'dao' => 'CRM_Pledge_DAO_Pledge',
102 'no_display' => TRUE,
105 'contact_id' => array(
106 'no_display' => TRUE,
109 'financial_type_id' => array(
110 'title' => ts('Financial Type'),
113 'title' => ts('Pledge Amount'),
115 'type' => CRM_Utils_Type
::T_MONEY
,
119 'no_display' => TRUE,
121 'frequency_unit' => array(
122 'title' => ts('Frequency Unit'),
124 'installments' => array(
125 'title' => ts('Installments'),
127 'pledge_create_date' => array(
128 'title' => ts('Pledge Made Date'),
130 'start_date' => array(
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
,
138 'status_id' => array(
139 'title' => ts('Pledge Status'),
144 'pledge_create_date' => array(
145 'title' => ts('Pledge Made Date'),
146 'operatorType' => CRM_Report_Form
::OP_DATE
,
148 'pledge_amount' => array(
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' => array(
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' => array(
176 'dao' => 'CRM_Pledge_DAO_PledgePayment',
178 'total_paid' => array(
179 'title' => ts('Total Amount Paid'),
180 'type' => CRM_Utils_Type
::T_MONEY
,
182 'balance_due' => array(
183 'title' => ts('Balance Due'),
185 'type' => CRM_Utils_Type
::T_MONEY
,
191 $this->_columns +
= $this->getAddressColumns(array('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 $this->_totalPaid
= TRUE; // add pledge_payment join
223 $this->_columnHeaders
["{$tableName}_{$fieldName}"] = array(
224 'title' => $field['title'],
225 'type' => $field['type'],
227 return "COALESCE(sum({$this->_aliases[$tableName]}.actual_amount), 0) as {$tableName}_{$fieldName}";
229 if ($fieldName == 'balance_due') {
230 $cancelledStatus = array_search('Cancelled', $this->_pledgeStatuses
);
231 $completedStatus = array_search('Completed', $this->_pledgeStatuses
);
232 $this->_totalPaid
= TRUE; // add pledge_payment join
233 $this->_columnHeaders
["{$tableName}_{$fieldName}"] = $field['title'];
234 $this->_columnHeaders
["{$tableName}_{$fieldName}"] = array(
235 'title' => $field['title'],
236 'type' => $field['type'],
238 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}";
243 public function groupBy() {
245 if (empty($this->_groupBy
) && $this->_totalPaid
) {
246 $groupBy = array("{$this->_aliases['civicrm_pledge']}.id", "{$this->_aliases['civicrm_pledge']}.currency");
247 $this->_groupBy
= CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($this->_selectClauses
, $groupBy);
251 public function from() {
253 FROM civicrm_pledge {$this->_aliases['civicrm_pledge']}
254 LEFT JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
255 ON ({$this->_aliases['civicrm_contact']}.id =
256 {$this->_aliases['civicrm_pledge']}.contact_id )
259 if ($this->_totalPaid
) {
261 LEFT JOIN civicrm_pledge_payment {$this->_aliases['civicrm_pledge_payment']} ON
262 {$this->_aliases['civicrm_pledge']}.id = {$this->_aliases['civicrm_pledge_payment']}.pledge_id
263 AND {$this->_aliases['civicrm_pledge_payment']}.status_id = 1
267 $this->joinPhoneFromContact();
268 $this->joinAddressFromContact();
269 $this->joinEmailFromContact();
277 public function statistics(&$rows) {
278 $statistics = parent
::statistics($rows);
279 //regenerate the from field without extra left join on pledge payments
280 $totalPaid = $this->_totalPaid
;
281 $this->_totalPaid
= FALSE;
283 $this->customDataFrom();
284 if (!$this->_having
) {
285 $totalAmount = $average = array();
288 SELECT COUNT({$this->_aliases['civicrm_pledge']}.amount ) as count,
289 SUM({$this->_aliases['civicrm_pledge']}.amount ) as amount,
290 ROUND(AVG({$this->_aliases['civicrm_pledge']}.amount), 2) as avg,
291 {$this->_aliases['civicrm_pledge']}.currency as currency
294 $group = "GROUP BY {$this->_aliases['civicrm_pledge']}.currency";
295 $sql = "{$select} {$this->_from} {$this->_where} {$group}";
296 $dao = CRM_Core_DAO
::executeQuery($sql);
297 $count = $index = $totalCount = 0;
298 // this will run once per currency
299 while ($dao->fetch()) {
300 $totalAmount = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
301 $average = CRM_Utils_Money
::format($dao->avg
, $dao->currency
);
302 $count = $dao->count
;
303 $totalCount .= $count;
304 $statistics['counts']['amount' . $index] = array(
305 'title' => ts('Total Pledged') . ' (' . $dao->currency
. ')',
306 'value' => $totalAmount,
307 'type' => CRM_Utils_Type
::T_STRING
,
309 $statistics['counts']['avg' . $index] = array(
310 'title' => ts('Average') . ' (' . $dao->currency
. ')',
312 'type' => CRM_Utils_Type
::T_STRING
,
314 $statistics['counts']['count' . $index] = array(
315 'title' => ts('Total No Pledges') . ' (' . $dao->currency
. ')',
317 'type' => CRM_Utils_Type
::T_INT
,
321 if ($totalCount > $count) {
322 $statistics['counts']['count' . $index] = array(
323 'title' => ts('Total No Pledges'),
324 'value' => $totalCount,
325 'type' => CRM_Utils_Type
::T_INT
,
331 $this->_totalPaid
= TRUE;
337 public function orderBy() {
338 $this->_orderBy
= "ORDER BY {$this->_aliases['civicrm_contact']}.sort_name, {$this->_aliases['civicrm_contact']}.id";
341 public function where() {
343 foreach ($this->_columns
as $tableName => $table) {
344 if (array_key_exists('filters', $table)) {
345 foreach ($table['filters'] as $fieldName => $field) {
347 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
348 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
349 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
350 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
352 if ($relative ||
$from ||
$to) {
353 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
357 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
359 $clause = $this->whereClause($field,
361 CRM_Utils_Array
::value("{$fieldName}_value",
364 CRM_Utils_Array
::value("{$fieldName}_min",
367 CRM_Utils_Array
::value("{$fieldName}_max",
374 if (!empty($clause)) {
375 $clauses[] = $clause;
380 if (empty($clauses)) {
381 $this->_where
= "WHERE ({$this->_aliases['civicrm_pledge']}.is_test=0 ) ";
384 $this->_where
= "WHERE ({$this->_aliases['civicrm_pledge']}.is_test=0 ) AND
385 " . implode(' AND ', $clauses);
388 if ($this->_aclWhere
) {
389 $this->_where
.= " AND {$this->_aclWhere} ";
393 public function postProcess() {
395 $this->beginPostProcess();
397 // get the acl clauses built before we assemble the query
398 $this->buildACLClause($this->_aliases
['civicrm_contact']);
399 $sql = $this->buildQuery();
400 $rows = $payment = array();
402 $dao = CRM_Core_DAO
::executeQuery($sql);
404 // Set pager for the Main Query only which displays basic information
406 $this->assign('columnHeaders', $this->_columnHeaders
);
408 while ($dao->fetch()) {
409 $pledgeID = $dao->civicrm_pledge_id
;
410 foreach ($this->_columnHeaders
as $columnHeadersKey => $columnHeadersValue) {
412 if (property_exists($dao, $columnHeadersKey)) {
413 $display[$pledgeID][$columnHeadersKey] = $dao->$columnHeadersKey;
416 $pledgeIDArray[] = $pledgeID;
419 // Add Special headers
420 $this->_columnHeaders
['scheduled_date'] = array(
421 'type' => CRM_Utils_Type
::T_DATE
,
422 'title' => ts('Next Payment Due'),
424 $this->_columnHeaders
['scheduled_amount'] = array(
425 'type' => CRM_Utils_Type
::T_MONEY
,
426 'title' => ts('Next Payment Amount'),
428 $this->_columnHeaders
['status_id'] = NULL;
431 * this is purely about ordering the total paid & balance due fields off to the end
432 * of the table in case custom or address fields cause them to fall in the middle
433 * (arguably the pledge amount should be moved to after these fields too)
436 $tableHeaders = array(
437 'civicrm_pledge_payment_total_paid',
438 'civicrm_pledge_payment_balance_due',
441 foreach ($tableHeaders as $header) {
442 //per above, unset & reset them so they move to the end
443 if (isset($this->_columnHeaders
[$header])) {
444 $headervalue = $this->_columnHeaders
[$header];
445 unset($this->_columnHeaders
[$header]);
446 $this->_columnHeaders
[$header] = $headervalue;
450 // To Display Payment Details of pledged amount
451 // for pledge payments In Progress
452 if (!empty($display)) {
453 $statusId = array_keys(CRM_Core_PseudoConstant
::accountOptionValues("contribution_status", NULL, " AND v.name IN ('Pending', 'Overdue')"));
454 $statusId = implode(',', $statusId);
455 $select = "payment.pledge_id, payment.scheduled_amount, pledge.contact_id";
457 SELECT min(payment.scheduled_date) as scheduled_date,
460 FROM civicrm_pledge_payment payment
461 LEFT JOIN civicrm_pledge pledge
462 ON pledge.id = payment.pledge_id
464 WHERE payment.status_id IN ({$statusId})
468 $daoPayment = CRM_Core_DAO
::executeQuery($sqlPayment);
470 while ($daoPayment->fetch()) {
471 foreach ($pledgeIDArray as $key => $val) {
472 if ($val == $daoPayment->pledge_id
) {
474 $display[$daoPayment->pledge_id
]['scheduled_date'] = $daoPayment->scheduled_date
;
476 $display[$daoPayment->pledge_id
]['scheduled_amount'] = $daoPayment->scheduled_amount
;
482 // Displaying entire data on the form
483 if (!empty($display)) {
484 foreach ($display as $key => $value) {
486 foreach ($this->_columnHeaders
as $columnKey => $columnValue) {
487 if (array_key_exists($columnKey, $value)) {
488 $row[$columnKey] = !empty($value[$columnKey]) ?
$value[$columnKey] : '';
495 unset($this->_columnHeaders
['status_id']);
496 unset($this->_columnHeaders
['civicrm_pledge_id']);
497 unset($this->_columnHeaders
['civicrm_pledge_contact_id']);
499 $this->formatDisplay($rows, FALSE);
500 $this->doTemplateAssignment($rows);
501 $this->endPostProcess($rows);
505 * Alter display of rows.
507 * Iterate through the rows retrieved via SQL and make changes for display purposes,
508 * such as rendering contacts as links.
511 * Rows generated by SQL, with an array for each row.
513 public function alterDisplay(&$rows) {
515 $checkList = array();
516 $display_flag = $prev_cid = $cid = 0;
518 foreach ($rows as $rowNum => $row) {
519 if (!empty($this->_noRepeats
) && $this->_outputMode
!= 'csv') {
520 // don't repeat contact details if its same as the previous row
521 if (array_key_exists('civicrm_pledge_contact_id', $row)) {
522 if ($cid = $row['civicrm_pledge_contact_id']) {
527 if ($prev_cid == $cid) {
538 foreach ($row as $colName => $colVal) {
539 if (in_array($colName, $this->_noRepeats
)) {
540 unset($rows[$rowNum][$colName]);
549 // convert display name to links
550 if (array_key_exists('civicrm_contact_sort_name', $row) &&
551 array_key_exists('civicrm_pledge_contact_id', $row)
553 $url = CRM_Utils_System
::url("civicrm/contact/view",
554 'reset=1&cid=' . $row['civicrm_pledge_contact_id'],
557 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
558 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contact Summary for this Contact.");
562 if (array_key_exists('civicrm_pledge_financial_type_id', $row)) {
563 if ($value = $row['civicrm_pledge_financial_type_id']) {
564 $rows[$rowNum]['civicrm_pledge_financial_type_id'] = CRM_Contribute_PseudoConstant
::financialType($value, FALSE);
570 if (array_key_exists('civicrm_pledge_status_id', $row)) {
571 if ($value = $row['civicrm_pledge_status_id']) {
572 $rows[$rowNum]['civicrm_pledge_status_id'] = CRM_Core_PseudoConstant
::getLabel('CRM_Pledge_BAO_Pledge', 'status_id', $value);
577 // If using campaigns, convert campaign_id to campaign title
578 if (array_key_exists('civicrm_pledge_campaign_id', $row)) {
579 if ($value = $row['civicrm_pledge_campaign_id']) {
580 $rows[$rowNum]['civicrm_pledge_campaign_id'] = $this->campaigns
[$value];
585 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'pledge/detail', 'List all pledge(s) for this ') ?
TRUE : $entryFound;
587 // skip looking further in rows, if first row itself doesn't
588 // have the column we need