3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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->addPhoneFromClause();
290 $this->addAddressFromClause();
291 // include email field if email column is to be included
292 if ($this->_emailField
) {
294 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
295 ON ({$this->_aliases['civicrm_contact']}.id =
296 {$this->_aliases['civicrm_email']}.contact_id) AND
297 {$this->_aliases['civicrm_email']}.is_primary = 1\n";
306 public function statistics(&$rows) {
307 $statistics = parent
::statistics($rows);
308 //regenerate the from field without extra left join on pledge payments
309 $totalPaid = $this->_totalPaid
;
310 $this->_totalPaid
= FALSE;
312 $this->customDataFrom();
313 if (!$this->_having
) {
314 $totalAmount = $average = array();
317 SELECT COUNT({$this->_aliases['civicrm_pledge']}.amount ) as count,
318 SUM({$this->_aliases['civicrm_pledge']}.amount ) as amount,
319 ROUND(AVG({$this->_aliases['civicrm_pledge']}.amount), 2) as avg,
320 {$this->_aliases['civicrm_pledge']}.currency as currency
323 $group = "GROUP BY {$this->_aliases['civicrm_pledge']}.currency";
324 $sql = "{$select} {$this->_from} {$this->_where} {$group}";
325 $dao = CRM_Core_DAO
::executeQuery($sql);
326 $count = $index = $totalCount = 0;
327 // this will run once per currency
328 while ($dao->fetch()) {
329 $totalAmount = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
330 $average = CRM_Utils_Money
::format($dao->avg
, $dao->currency
);
331 $count = $dao->count
;
332 $totalCount .= $count;
333 $statistics['counts']['amount' . $index] = array(
334 'title' => ts('Total Pledged') . ' (' . $dao->currency
. ')',
335 'value' => $totalAmount,
336 'type' => CRM_Utils_Type
::T_STRING
,
338 $statistics['counts']['avg' . $index] = array(
339 'title' => ts('Average') . ' (' . $dao->currency
. ')',
341 'type' => CRM_Utils_Type
::T_STRING
,
343 $statistics['counts']['count' . $index] = array(
344 'title' => ts('Total No Pledges') . ' (' . $dao->currency
. ')',
346 'type' => CRM_Utils_Type
::T_INT
,
350 if ($totalCount > $count) {
351 $statistics['counts']['count' . $index] = array(
352 'title' => ts('Total No Pledges'),
353 'value' => $totalCount,
354 'type' => CRM_Utils_Type
::T_INT
,
360 $this->_totalPaid
= TRUE;
366 public function orderBy() {
367 $this->_orderBy
= "ORDER BY {$this->_aliases['civicrm_contact']}.sort_name, {$this->_aliases['civicrm_contact']}.id";
370 public function where() {
372 foreach ($this->_columns
as $tableName => $table) {
373 if (array_key_exists('filters', $table)) {
374 foreach ($table['filters'] as $fieldName => $field) {
376 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
377 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
378 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
379 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
381 if ($relative ||
$from ||
$to) {
382 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
386 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
388 $clause = $this->whereClause($field,
390 CRM_Utils_Array
::value("{$fieldName}_value",
393 CRM_Utils_Array
::value("{$fieldName}_min",
396 CRM_Utils_Array
::value("{$fieldName}_max",
403 if (!empty($clause)) {
404 $clauses[] = $clause;
409 if (empty($clauses)) {
410 $this->_where
= "WHERE ({$this->_aliases['civicrm_pledge']}.is_test=0 ) ";
413 $this->_where
= "WHERE ({$this->_aliases['civicrm_pledge']}.is_test=0 ) AND
414 " . implode(' AND ', $clauses);
417 if ($this->_aclWhere
) {
418 $this->_where
.= " AND {$this->_aclWhere} ";
422 public function postProcess() {
424 $this->beginPostProcess();
426 // get the acl clauses built before we assemble the query
427 $this->buildACLClause($this->_aliases
['civicrm_contact']);
428 $sql = $this->buildQuery();
429 $rows = $payment = array();
431 $dao = CRM_Core_DAO
::executeQuery($sql);
433 // Set pager for the Main Query only which displays basic information
435 $this->assign('columnHeaders', $this->_columnHeaders
);
437 while ($dao->fetch()) {
438 $pledgeID = $dao->civicrm_pledge_id
;
439 foreach ($this->_columnHeaders
as $columnHeadersKey => $columnHeadersValue) {
441 if (property_exists($dao, $columnHeadersKey)) {
442 $display[$pledgeID][$columnHeadersKey] = $dao->$columnHeadersKey;
445 $pledgeIDArray[] = $pledgeID;
448 // Add Special headers
449 $this->_columnHeaders
['scheduled_date'] = array(
450 'type' => CRM_Utils_Type
::T_DATE
,
451 'title' => ts('Next Payment Due'),
453 $this->_columnHeaders
['scheduled_amount'] = array(
454 'type' => CRM_Utils_Type
::T_MONEY
,
455 'title' => ts('Next Payment Amount'),
457 $this->_columnHeaders
['status_id'] = NULL;
460 * this is purely about ordering the total paid & balance due fields off to the end
461 * of the table in case custom or address fields cause them to fall in the middle
462 * (arguably the pledge amount should be moved to after these fields too)
465 $tableHeaders = array(
466 'civicrm_pledge_payment_total_paid',
467 'civicrm_pledge_payment_balance_due',
470 foreach ($tableHeaders as $header) {
471 //per above, unset & reset them so they move to the end
472 if (isset($this->_columnHeaders
[$header])) {
473 $headervalue = $this->_columnHeaders
[$header];
474 unset($this->_columnHeaders
[$header]);
475 $this->_columnHeaders
[$header] = $headervalue;
479 // To Display Payment Details of pledged amount
480 // for pledge payments In Progress
481 if (!empty($display)) {
482 $statusId = array_keys(CRM_Core_PseudoConstant
::accountOptionValues("contribution_status", NULL, " AND v.name IN ('Pending', 'Overdue')"));
483 $statusId = implode(',', $statusId);
484 $select = "payment.pledge_id, payment.scheduled_amount, pledge.contact_id";
486 SELECT min(payment.scheduled_date) as scheduled_date,
489 FROM civicrm_pledge_payment payment
490 LEFT JOIN civicrm_pledge pledge
491 ON pledge.id = payment.pledge_id
493 WHERE payment.status_id IN ({$statusId})
497 $daoPayment = CRM_Core_DAO
::executeQuery($sqlPayment);
499 while ($daoPayment->fetch()) {
500 foreach ($pledgeIDArray as $key => $val) {
501 if ($val == $daoPayment->pledge_id
) {
503 $display[$daoPayment->pledge_id
]['scheduled_date'] = $daoPayment->scheduled_date
;
505 $display[$daoPayment->pledge_id
]['scheduled_amount'] = $daoPayment->scheduled_amount
;
511 // Displaying entire data on the form
512 if (!empty($display)) {
513 foreach ($display as $key => $value) {
515 foreach ($this->_columnHeaders
as $columnKey => $columnValue) {
516 if (array_key_exists($columnKey, $value)) {
517 $row[$columnKey] = !empty($value[$columnKey]) ?
$value[$columnKey] : '';
524 unset($this->_columnHeaders
['status_id']);
525 unset($this->_columnHeaders
['civicrm_pledge_id']);
526 unset($this->_columnHeaders
['civicrm_pledge_contact_id']);
528 $this->formatDisplay($rows, FALSE);
529 $this->doTemplateAssignment($rows);
530 $this->endPostProcess($rows);
534 * Alter display of rows.
536 * Iterate through the rows retrieved via SQL and make changes for display purposes,
537 * such as rendering contacts as links.
540 * Rows generated by SQL, with an array for each row.
542 public function alterDisplay(&$rows) {
544 $checkList = array();
545 $display_flag = $prev_cid = $cid = 0;
547 foreach ($rows as $rowNum => $row) {
548 if (!empty($this->_noRepeats
) && $this->_outputMode
!= 'csv') {
549 // don't repeat contact details if its same as the previous row
550 if (array_key_exists('civicrm_pledge_contact_id', $row)) {
551 if ($cid = $row['civicrm_pledge_contact_id']) {
556 if ($prev_cid == $cid) {
567 foreach ($row as $colName => $colVal) {
568 if (in_array($colName, $this->_noRepeats
)) {
569 unset($rows[$rowNum][$colName]);
578 // convert display name to links
579 if (array_key_exists('civicrm_contact_sort_name', $row) &&
580 array_key_exists('civicrm_pledge_contact_id', $row)
582 $url = CRM_Utils_System
::url("civicrm/contact/view",
583 'reset=1&cid=' . $row['civicrm_pledge_contact_id'],
586 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
587 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contact Summary for this Contact.");
591 if (array_key_exists('civicrm_pledge_financial_type_id', $row)) {
592 if ($value = $row['civicrm_pledge_financial_type_id']) {
593 $rows[$rowNum]['civicrm_pledge_financial_type_id'] = CRM_Contribute_PseudoConstant
::financialType($value, FALSE);
599 if (array_key_exists('civicrm_pledge_status_id', $row)) {
600 if ($value = $row['civicrm_pledge_status_id']) {
601 $rows[$rowNum]['civicrm_pledge_status_id'] = CRM_Core_PseudoConstant
::getLabel('CRM_Pledge_BAO_Pledge', 'status_id', $value);
606 // If using campaigns, convert campaign_id to campaign title
607 if (array_key_exists('civicrm_pledge_campaign_id', $row)) {
608 if ($value = $row['civicrm_pledge_campaign_id']) {
609 $rows[$rowNum]['civicrm_pledge_campaign_id'] = $this->activeCampaigns
[$value];
614 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'pledge/detail', 'List all pledge(s) for this ') ?
TRUE : $entryFound;
616 // skip looking further in rows, if first row itself doesn't
617 // have the column we need