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 +--------------------------------------------------------------------+
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-2018
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'
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
);
83 $this->_columns
= array(
84 'civicrm_contact' => array(
85 'dao' => 'CRM_Contact_DAO_Contact',
88 'title' => ts('Contact Name'),
94 'sort_name' => array('title' => ts('Contact Name')),
95 'id' => array('no_display' => TRUE),
97 'grouping' => 'contact-fields',
99 'civicrm_email' => array(
100 'dao' => 'CRM_Core_DAO_Email',
102 'email' => array('no_repeat' => TRUE),
104 'grouping' => 'contact-fields',
106 'civicrm_pledge' => array(
107 'dao' => 'CRM_Pledge_DAO_Pledge',
110 'no_display' => TRUE,
113 'contact_id' => array(
114 'no_display' => TRUE,
117 'financial_type_id' => array(
118 'title' => ts('Financial Type'),
121 'title' => ts('Pledge Amount'),
123 'type' => CRM_Utils_Type
::T_MONEY
,
127 'no_display' => TRUE,
129 'frequency_unit' => array(
130 'title' => ts('Frequency Unit'),
132 'installments' => array(
133 'title' => ts('Installments'),
135 'pledge_create_date' => array(
136 'title' => ts('Pledge Made Date'),
138 'start_date' => array(
139 'title' => ts('Pledge Start Date'),
140 'type' => CRM_Utils_Type
::T_DATE
,
143 'title' => ts('Pledge End Date'),
144 'type' => CRM_Utils_Type
::T_DATE
,
146 'status_id' => array(
147 'title' => ts('Pledge Status'),
152 'pledge_create_date' => array(
153 'title' => ts('Pledge Made Date'),
154 'operatorType' => CRM_Report_Form
::OP_DATE
,
156 'pledge_amount' => array(
157 'title' => ts('Pledged Amount'),
158 'operatorType' => CRM_Report_Form
::OP_INT
,
161 'title' => ts('Currency'),
162 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
163 'options' => CRM_Core_OptionGroup
::values('currencies_enabled'),
165 'type' => CRM_Utils_Type
::T_STRING
,
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'),
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(),
183 'civicrm_pledge_payment' => array(
184 'dao' => 'CRM_Pledge_DAO_PledgePayment',
186 'total_paid' => array(
187 'title' => ts('Total Amount Paid'),
188 'type' => CRM_Utils_Type
::T_MONEY
,
190 'balance_due' => array(
191 'title' => ts('Balance Due'),
193 'type' => CRM_Utils_Type
::T_MONEY
,
199 $this->_columns +
= $this->getAddressColumns(array('group_by' => FALSE)) +
$this->getPhoneColumns();
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',
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
,
214 $this->_columns
['civicrm_pledge']['group_bys']['campaign_id'] = array('title' => ts('Campaign'));
218 $this->_groupFilter
= TRUE;
219 $this->_tagFilter
= TRUE;
220 $this->_currencyColumn
= 'civicrm_pledge_currency';
221 parent
::__construct();
224 public function preProcess() {
225 parent
::preProcess();
228 public function select() {
233 * If we are retrieving total paid we need to define the inclusion of pledge_payment.
235 * @param string $tableName
237 * @param string $fieldName
240 * @return bool|string
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'],
249 return "COALESCE(sum({$this->_aliases[$tableName]}.actual_amount), 0) as {$tableName}_{$fieldName}";
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'],
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}";
265 public function 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);
273 public function 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 )
281 if ($this->_totalPaid
) {
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
289 $this->joinPhoneFromContact();
290 $this->joinAddressFromContact();
291 $this->joinEmailFromContact();
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;
305 $this->customDataFrom();
306 if (!$this->_having
) {
307 $totalAmount = $average = array();
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
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
,
331 $statistics['counts']['avg' . $index] = array(
332 'title' => ts('Average') . ' (' . $dao->currency
. ')',
334 'type' => CRM_Utils_Type
::T_STRING
,
336 $statistics['counts']['count' . $index] = array(
337 'title' => ts('Total No Pledges') . ' (' . $dao->currency
. ')',
339 'type' => CRM_Utils_Type
::T_INT
,
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
,
353 $this->_totalPaid
= TRUE;
359 public function orderBy() {
360 $this->_orderBy
= "ORDER BY {$this->_aliases['civicrm_contact']}.sort_name, {$this->_aliases['civicrm_contact']}.id";
363 public function where() {
365 foreach ($this->_columns
as $tableName => $table) {
366 if (array_key_exists('filters', $table)) {
367 foreach ($table['filters'] as $fieldName => $field) {
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
);
374 if ($relative ||
$from ||
$to) {
375 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
379 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
381 $clause = $this->whereClause($field,
383 CRM_Utils_Array
::value("{$fieldName}_value",
386 CRM_Utils_Array
::value("{$fieldName}_min",
389 CRM_Utils_Array
::value("{$fieldName}_max",
396 if (!empty($clause)) {
397 $clauses[] = $clause;
402 if (empty($clauses)) {
403 $this->_where
= "WHERE ({$this->_aliases['civicrm_pledge']}.is_test=0 ) ";
406 $this->_where
= "WHERE ({$this->_aliases['civicrm_pledge']}.is_test=0 ) AND
407 " . implode(' AND ', $clauses);
410 if ($this->_aclWhere
) {
411 $this->_where
.= " AND {$this->_aclWhere} ";
415 public function postProcess() {
417 $this->beginPostProcess();
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();
424 $dao = CRM_Core_DAO
::executeQuery($sql);
426 // Set pager for the Main Query only which displays basic information
428 $this->assign('columnHeaders', $this->_columnHeaders
);
430 while ($dao->fetch()) {
431 $pledgeID = $dao->civicrm_pledge_id
;
432 foreach ($this->_columnHeaders
as $columnHeadersKey => $columnHeadersValue) {
434 if (property_exists($dao, $columnHeadersKey)) {
435 $display[$pledgeID][$columnHeadersKey] = $dao->$columnHeadersKey;
438 $pledgeIDArray[] = $pledgeID;
441 // Add Special headers
442 $this->_columnHeaders
['scheduled_date'] = array(
443 'type' => CRM_Utils_Type
::T_DATE
,
444 'title' => ts('Next Payment Due'),
446 $this->_columnHeaders
['scheduled_amount'] = array(
447 'type' => CRM_Utils_Type
::T_MONEY
,
448 'title' => ts('Next Payment Amount'),
450 $this->_columnHeaders
['status_id'] = NULL;
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)
458 $tableHeaders = array(
459 'civicrm_pledge_payment_total_paid',
460 'civicrm_pledge_payment_balance_due',
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;
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";
479 SELECT min(payment.scheduled_date) as scheduled_date,
482 FROM civicrm_pledge_payment payment
483 LEFT JOIN civicrm_pledge pledge
484 ON pledge.id = payment.pledge_id
486 WHERE payment.status_id IN ({$statusId})
490 $daoPayment = CRM_Core_DAO
::executeQuery($sqlPayment);
492 while ($daoPayment->fetch()) {
493 foreach ($pledgeIDArray as $key => $val) {
494 if ($val == $daoPayment->pledge_id
) {
496 $display[$daoPayment->pledge_id
]['scheduled_date'] = $daoPayment->scheduled_date
;
498 $display[$daoPayment->pledge_id
]['scheduled_amount'] = $daoPayment->scheduled_amount
;
504 // Displaying entire data on the form
505 if (!empty($display)) {
506 foreach ($display as $key => $value) {
508 foreach ($this->_columnHeaders
as $columnKey => $columnValue) {
509 if (array_key_exists($columnKey, $value)) {
510 $row[$columnKey] = !empty($value[$columnKey]) ?
$value[$columnKey] : '';
517 unset($this->_columnHeaders
['status_id']);
518 unset($this->_columnHeaders
['civicrm_pledge_id']);
519 unset($this->_columnHeaders
['civicrm_pledge_contact_id']);
521 $this->formatDisplay($rows, FALSE);
522 $this->doTemplateAssignment($rows);
523 $this->endPostProcess($rows);
527 * Alter display of rows.
529 * Iterate through the rows retrieved via SQL and make changes for display purposes,
530 * such as rendering contacts as links.
533 * Rows generated by SQL, with an array for each row.
535 public function alterDisplay(&$rows) {
537 $checkList = array();
538 $display_flag = $prev_cid = $cid = 0;
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']) {
549 if ($prev_cid == $cid) {
560 foreach ($row as $colName => $colVal) {
561 if (in_array($colName, $this->_noRepeats
)) {
562 unset($rows[$rowNum][$colName]);
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)
575 $url = CRM_Utils_System
::url("civicrm/contact/view",
576 'reset=1&cid=' . $row['civicrm_pledge_contact_id'],
579 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
580 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contact Summary for this Contact.");
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);
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);
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];
607 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'pledge/detail', 'List all pledge(s) for this ') ?
TRUE : $entryFound;
609 // skip looking further in rows, if first row itself doesn't
610 // have the column we need