3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
46 class CRM_Report_Form_Pledge_Detail
extends CRM_Report_Form
{
48 protected $_summary = NULL;
49 protected $_totalPaid = FALSE;
50 protected $_pledgeStatuses = array();
51 protected $_customGroupExtends = array(
60 public function __construct() {
61 $this->_pledgeStatuses
= CRM_Contribute_PseudoConstant
::contributionStatus();
62 // Check if CiviCampaign is a) enabled and b) has active campaigns
63 $config = CRM_Core_Config
::singleton();
64 $campaignEnabled = in_array("CiviCampaign", $config->enableComponents
);
65 if ($campaignEnabled) {
66 $getCampaigns = CRM_Campaign_BAO_Campaign
::getPermissionedCampaigns(NULL, NULL, TRUE, FALSE, TRUE);
67 $this->activeCampaigns
= $getCampaigns['campaigns'];
68 asort($this->activeCampaigns
);
71 $this->_columns
= array(
72 'civicrm_contact' => array(
73 'dao' => 'CRM_Contact_DAO_Contact',
76 'title' => ts('Contact Name'),
82 'sort_name' => array('title' => ts('Contact Name')),
83 'id' => array('no_display' => TRUE),
85 'grouping' => 'contact-fields',
87 'civicrm_email' => array(
88 'dao' => 'CRM_Core_DAO_Email',
90 'email' => array('no_repeat' => TRUE),
92 'grouping' => 'contact-fields',
94 'civicrm_pledge' => array(
95 'dao' => 'CRM_Pledge_DAO_Pledge',
101 'contact_id' => array(
102 'no_display' => TRUE,
106 'title' => ts('Pledge Amount'),
108 'type' => CRM_Utils_Type
::T_MONEY
,
112 'no_display' => TRUE,
114 'frequency_unit' => array(
115 'title' => ts('Frequency Unit'),
117 'installments' => array(
118 'title' => ts('Installments'),
120 'pledge_create_date' => array(
121 'title' => ts('Pledge Made Date'),
123 'start_date' => array(
124 'title' => ts('Pledge Start Date'),
125 'type' => CRM_Utils_Type
::T_DATE
,
128 'title' => ts('Pledge End Date'),
129 'type' => CRM_Utils_Type
::T_DATE
,
131 'status_id' => array(
132 'title' => ts('Pledge Status'),
137 'pledge_create_date' => array(
138 'title' => 'Pledge Made Date',
139 'operatorType' => CRM_Report_Form
::OP_DATE
,
141 'pledge_amount' => array(
142 'title' => ts('Pledged Amount'),
143 'operatorType' => CRM_Report_Form
::OP_INT
,
146 'title' => 'Currency',
147 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
148 'options' => CRM_Core_OptionGroup
::values('currencies_enabled'),
150 'type' => CRM_Utils_Type
::T_STRING
,
153 'name' => 'status_id',
154 'title' => ts('Pledge Status'),
155 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
156 'options' => CRM_Core_OptionGroup
::values('contribution_status'),
161 'civicrm_pledge_payment' => array(
162 'dao' => 'CRM_Pledge_DAO_PledgePayment',
164 'total_paid' => array(
165 'title' => ts('Total Amount Paid'),
166 'type' => CRM_Utils_Type
::T_MONEY
,
168 'balance_due' => array(
169 'title' => ts('Balance Due'),
171 'type' => CRM_Utils_Type
::T_MONEY
,
177 $this->_columns +
= $this->getAddressColumns(array('group_by' => FALSE)) +
$this->getPhoneColumns();
179 // If we have a campaign, build out the relevant elements
180 $this->_tagFilter
= TRUE;
181 if ($campaignEnabled && !empty($this->activeCampaigns
)) {
182 $this->_columns
['civicrm_pledge']['fields']['campaign_id'] = array(
183 'title' => 'Campaign',
184 'default' => 'false',
186 $this->_columns
['civicrm_pledge']['filters']['campaign_id'] = array(
187 'title' => ts('Campaign'),
188 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
189 'options' => $this->activeCampaigns
,
191 $this->_columns
['civicrm_pledge']['group_bys']['campaign_id'] = array('title' => ts('Campaign'));
195 $this->_groupFilter
= TRUE;
196 $this->_tagFilter
= TRUE;
197 $this->_currencyColumn
= 'civicrm_pledge_currency';
198 parent
::__construct();
201 public function preProcess() {
202 parent
::preProcess();
205 public function select() {
210 * If we are retrieving total paid we need to define the inclusion of pledge_payment.
212 * @param string $tableName
214 * @param string $fieldName
217 * @return bool|string
219 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
220 if ($fieldName == 'total_paid') {
221 $this->_totalPaid
= TRUE; // add pledge_payment join
222 $this->_columnHeaders
["{$tableName}_{$fieldName}"] = array(
223 'title' => $field['title'],
224 'type' => $field['type'],
226 return "COALESCE(sum({$this->_aliases[$tableName]}.actual_amount), 0) as {$tableName}_{$fieldName}";
228 if ($fieldName == 'balance_due') {
229 $cancelledStatus = array_search('Cancelled', $this->_pledgeStatuses
);
230 $completedStatus = array_search('Completed', $this->_pledgeStatuses
);
231 $this->_totalPaid
= TRUE; // add pledge_payment join
232 $this->_columnHeaders
["{$tableName}_{$fieldName}"] = $field['title'];
233 $this->_columnHeaders
["{$tableName}_{$fieldName}"] = array(
234 'title' => $field['title'],
235 'type' => $field['type'],
237 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}";
242 public function groupBy() {
244 if (empty($this->_groupBy
) && $this->_totalPaid
) {
245 $this->_groupBy
= " GROUP BY {$this->_aliases['civicrm_pledge']}.id, {$this->_aliases['civicrm_pledge']}.currency";
249 public function from() {
251 FROM civicrm_pledge {$this->_aliases['civicrm_pledge']}
252 LEFT JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
253 ON ({$this->_aliases['civicrm_contact']}.id =
254 {$this->_aliases['civicrm_pledge']}.contact_id )
257 if ($this->_totalPaid
) {
259 LEFT JOIN civicrm_pledge_payment {$this->_aliases['civicrm_pledge_payment']} ON
260 {$this->_aliases['civicrm_pledge']}.id = {$this->_aliases['civicrm_pledge_payment']}.pledge_id
261 AND {$this->_aliases['civicrm_pledge_payment']}.status_id = 1
265 $this->addPhoneFromClause();
266 $this->addAddressFromClause();
267 // include email field if email column is to be included
268 if ($this->_emailField
) {
270 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
271 ON ({$this->_aliases['civicrm_contact']}.id =
272 {$this->_aliases['civicrm_email']}.contact_id) AND
273 {$this->_aliases['civicrm_email']}.is_primary = 1\n";
282 public function statistics(&$rows) {
283 $statistics = parent
::statistics($rows);
284 //regenerate the from field without extra left join on pledge payments
285 $this->_totalPaid
= FALSE;
287 $this->customDataFrom();
288 if (!$this->_having
) {
289 $totalAmount = $average = array();
292 SELECT COUNT({$this->_aliases['civicrm_pledge']}.amount ) as count,
293 SUM({$this->_aliases['civicrm_pledge']}.amount ) as amount,
294 ROUND(AVG({$this->_aliases['civicrm_pledge']}.amount), 2) as avg,
295 {$this->_aliases['civicrm_pledge']}.currency as currency
298 $group = "GROUP BY {$this->_aliases['civicrm_pledge']}.currency";
299 $sql = "{$select} {$this->_from} {$this->_where} {$group}";
300 $dao = CRM_Core_DAO
::executeQuery($sql);
301 $count = $index = $totalCount = 0;
302 // this will run once per currency
303 while ($dao->fetch()) {
304 $totalAmount = CRM_Utils_Money
::format($dao->amount
, $dao->currency
);
305 $average = CRM_Utils_Money
::format($dao->avg
, $dao->currency
);
306 $count = $dao->count
;
307 $totalCount .= $count;
308 $statistics['counts']['amount' . $index] = array(
309 'title' => ts('Total Pledged') . ' (' . $dao->currency
. ')',
310 'value' => $totalAmount,
311 'type' => CRM_Utils_Type
::T_STRING
,
313 $statistics['counts']['avg' . $index] = array(
314 'title' => ts('Average') . ' (' . $dao->currency
. ')',
316 'type' => CRM_Utils_Type
::T_STRING
,
318 $statistics['counts']['count' . $index] = array(
319 'title' => ts('Total No Pledges') . ' (' . $dao->currency
. ')',
321 'type' => CRM_Utils_Type
::T_INT
,
325 if ($totalCount > $count) {
326 $statistics['counts']['count' . $index] = array(
327 'title' => ts('Total No Pledges'),
328 'value' => $totalCount,
329 'type' => CRM_Utils_Type
::T_INT
,
336 public function orderBy() {
337 $this->_orderBy
= "ORDER BY {$this->_aliases['civicrm_contact']}.sort_name, {$this->_aliases['civicrm_contact']}.id";
340 public function where() {
342 foreach ($this->_columns
as $tableName => $table) {
343 if (array_key_exists('filters', $table)) {
344 foreach ($table['filters'] as $fieldName => $field) {
346 if (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
347 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
348 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
349 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
351 if ($relative ||
$from ||
$to) {
352 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
356 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
358 $clause = $this->whereClause($field,
360 CRM_Utils_Array
::value("{$fieldName}_value",
363 CRM_Utils_Array
::value("{$fieldName}_min",
366 CRM_Utils_Array
::value("{$fieldName}_max",
373 if (!empty($clause)) {
374 $clauses[] = $clause;
379 if (empty($clauses)) {
380 $this->_where
= "WHERE ({$this->_aliases['civicrm_pledge']}.is_test=0 ) ";
383 $this->_where
= "WHERE ({$this->_aliases['civicrm_pledge']}.is_test=0 ) AND
384 " . implode(' AND ', $clauses);
387 if ($this->_aclWhere
) {
388 $this->_where
.= " AND {$this->_aclWhere} ";
392 public function postProcess() {
394 $this->beginPostProcess();
396 // get the acl clauses built before we assemble the query
397 $this->buildACLClause($this->_aliases
['civicrm_contact']);
398 $sql = $this->buildQuery();
399 $rows = $payment = array();
401 $dao = CRM_Core_DAO
::executeQuery($sql);
403 // Set pager for the Main Query only which displays basic information
405 $this->assign('columnHeaders', $this->_columnHeaders
);
407 while ($dao->fetch()) {
408 $pledgeID = $dao->civicrm_pledge_id
;
409 foreach ($this->_columnHeaders
as $columnHeadersKey => $columnHeadersValue) {
411 if (property_exists($dao, $columnHeadersKey)) {
412 $display[$pledgeID][$columnHeadersKey] = $dao->$columnHeadersKey;
415 $pledgeIDArray[] = $pledgeID;
418 // Add Special headers
419 $this->_columnHeaders
['scheduled_date'] = array(
420 'type' => CRM_Utils_Type
::T_DATE
,
421 'title' => 'Next Payment Due',
423 $this->_columnHeaders
['scheduled_amount'] = array(
424 'type' => CRM_Utils_Type
::T_MONEY
,
425 'title' => 'Next Payment Amount',
427 $this->_columnHeaders
['status_id'] = NULL;
430 * this is purely about ordering the total paid & balance due fields off to the end
431 * of the table in case custom or address fields cause them to fall in the middle
432 * (arguably the pledge amount should be moved to after these fields too)
435 $tableHeaders = array(
436 'civicrm_pledge_payment_total_paid',
437 'civicrm_pledge_payment_balance_due',
440 foreach ($tableHeaders as $header) {
441 //per above, unset & reset them so they move to the end
442 if (isset($this->_columnHeaders
[$header])) {
443 $headervalue = $this->_columnHeaders
[$header];
444 unset($this->_columnHeaders
[$header]);
445 $this->_columnHeaders
[$header] = $headervalue;
449 // To Display Payment Details of pledged amount
450 // for pledge payments In Progress
451 if (!empty($display)) {
452 $statusId = array_keys(CRM_Core_PseudoConstant
::accountOptionValues("contribution_status", NULL, " AND v.name IN ('Pending', 'Overdue')"));
453 $statusId = implode(',', $statusId);
455 SELECT min(payment.scheduled_date) as scheduled_date,
457 payment.scheduled_amount,
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})
466 GROUP BY payment.pledge_id";
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.");
563 if (array_key_exists('civicrm_pledge_status_id', $row)) {
564 if ($value = $row['civicrm_pledge_status_id']) {
565 $rows[$rowNum]['civicrm_pledge_status_id'] = CRM_Contribute_PseudoConstant
::contributionStatus($value);
570 // If using campaigns, convert campaign_id to campaign title
571 if (array_key_exists('civicrm_pledge_campaign_id', $row)) {
572 if ($value = $row['civicrm_pledge_campaign_id']) {
573 $rows[$rowNum]['civicrm_pledge_campaign_id'] = $this->activeCampaigns
[$value];
578 $entryFound = $this->alterDisplayAddressFields($row, $rows, $rowNum, 'pledge/detail', 'List all pledge(s) for this ') ?
TRUE : $entryFound;
580 // skip looking further in rows, if first row itself doesn't
581 // have the column we need