4 +--------------------------------------------------------------------+
5 | CiviCRM version 4.5 |
6 +--------------------------------------------------------------------+
7 | Copyright CiviCRM LLC (c) 2004-2014 |
8 +--------------------------------------------------------------------+
9 | This file is a part of CiviCRM. |
11 | CiviCRM is free software; you can copy, modify, and distribute it |
12 | under the terms of the GNU Affero General Public License |
13 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
15 | CiviCRM is distributed in the hope that it will be useful, but |
16 | WITHOUT ANY WARRANTY; without even the implied warranty of |
17 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
18 | See the GNU Affero General Public License for more details. |
20 | You should have received a copy of the GNU Affero General Public |
21 | License and the CiviCRM Licensing Exception along |
22 | with this program; if not, contact CiviCRM LLC |
23 | at info[AT]civicrm[DOT]org. If you have questions about the |
24 | GNU Affero General Public License or the licensing of CiviCRM, |
25 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
26 +--------------------------------------------------------------------+
32 * @copyright CiviCRM LLC (c) 2004-2014
36 class CRM_Report_Form_Contribute_History
extends CRM_Report_Form
{
37 // Primary Contacts count limitCONSTROW_COUNT_LIMIT = 10;
39 protected $_addressField = FALSE;
40 protected $_emailField = FALSE;
41 protected $_phoneField = FALSE;
42 protected $_relationshipColumns = array();
44 protected $_customGroupExtends = array('Contribution');
46 protected $_referenceYear = array(
50 protected $_yearStatisticsFrom = '';
52 protected $_yearStatisticsTo = '';
60 function __construct() {
62 $date = CRM_Core_SelectValues
::date('custom', NULL, $yearsInPast, 0);
63 $count = $date['maxYear'];
64 $optionYear = array('' => ts('-- select --'));
66 $this->_yearStatisticsFrom
= $date['minYear'];
67 $this->_yearStatisticsTo
= $date['maxYear'];
69 while ($date['minYear'] <= $count) {
70 $optionYear[$date['minYear']] = $date['minYear'];
74 $relationTypeOp = array();
75 $relationshipTypes = CRM_Core_PseudoConstant
::relationshipType();
76 foreach ($relationshipTypes as $rid => $rtype) {
77 if ($rtype['label_a_b'] != $rtype['label_b_a']) {
78 $relationTypeOp[$rid] = "{$rtype['label_a_b']}/{$rtype['label_b_a']}";
81 $relationTypeOp[$rid] = $rtype['label_a_b'];
85 $this->_columns
= array(
88 'dao' => 'CRM_Contact_DAO_Contact',
92 array('title' => ts('Contact Name'),
105 'title' => ts('Contact Type'),
107 'contact_sub_type' =>
109 'title' => ts('Contact SubType'),
112 'grouping' => 'contact-fields',
116 array('title' => ts('Contact Name')),
118 array('title' => ts('Contact ID'),
119 'no_display' => TRUE,
125 'dao' => 'CRM_Core_DAO_Email',
129 array('title' => ts('Email'),
133 'grouping' => 'contact-fields',
137 'dao' => 'CRM_Core_DAO_Phone',
141 array('title' => ts('Phone'),
145 'grouping' => 'contact-fields',
147 ) +
$this->addAddressFields(FALSE, FALSE, FALSE, array(
148 )) +
array('civicrm_relationship' =>
150 'dao' => 'CRM_Contact_DAO_Relationship',
153 'relationship_type_id' =>
154 array('title' => ts('Relationship Type'),
158 array('no_display' => TRUE),
160 array('no_display' => TRUE),
164 'relationship_type_id' =>
165 array('title' => ts('Relationship Type'),
166 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
167 'options' => $relationTypeOp,
168 'type' => CRM_Utils_Type
::T_STRING
,
173 'civicrm_contribution' =>
175 'dao' => 'CRM_Contribute_DAO_Contribution',
179 array('title' => ts('Amount Statistics'),
182 'no_display' => TRUE,
184 array('sum' => ts('Aggregate Amount')),
190 'no_display' => TRUE,
193 'grouping' => 'contri-fields',
198 'title' => ts('This Year'),
199 'operatorType' => CRM_Report_Form
::OP_SELECT
,
200 'options' => $optionYear,
205 'title' => ts('Other Years'),
206 'operatorType' => CRM_Report_Form
::OP_SELECT
,
207 'options' => $optionYear,
211 array('operatorType' => CRM_Report_Form
::OP_DATE
),
212 'contribution_status_id' =>
213 array('title' => ts('Donation Status'),
214 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
215 'options' => CRM_Contribute_PseudoConstant
::contributionStatus(),
216 'default' => array(1),
218 'financial_type_id' => array(
219 'title' => ts('Financial Type'),
220 'operatorType' => CRM_Report_Form
::OP_MULTISELECT
,
221 'options' => CRM_Contribute_PseudoConstant
::financialType(),
224 array('title' => ts('Donation Amount'),
227 array('title' => ts('Aggregate Amount'),
228 'type' => CRM_Report_Form
::OP_INT
,
229 'dbAlias' => 'civicrm_contribution_total_amount_sum',
236 $this->_columns
['civicrm_contribution']['fields']['civicrm_upto_' . $this->_yearStatisticsFrom
] = array('title' => ts('Up To %1 Donation', array(1 => $this->_yearStatisticsFrom
)),
238 'type' => CRM_Utils_Type
::T_MONEY
,
239 'is_statistics' => TRUE,
242 $yearConter = $this->_yearStatisticsFrom
;
244 while ($yearConter <= $this->_yearStatisticsTo
) {
245 $this->_columns
['civicrm_contribution']['fields'][$yearConter] = array('title' => ts('%1 Donation', array(1 => $yearConter)),
247 'type' => CRM_Utils_Type
::T_MONEY
,
248 'is_statistics' => TRUE,
253 $this->_columns
['civicrm_contribution']['fields']['aggregate_amount'] = array('title' => ts('Aggregate Amount'),
254 'type' => CRM_Utils_Type
::T_MONEY
,
255 'is_statistics' => TRUE,
258 $this->_groupFilter
= TRUE;
259 $this->_tagFilter
= TRUE;
260 parent
::__construct();
263 function preProcess() {
264 parent
::preProcess();
269 $this->_columnHeaders
= array();
271 foreach ($this->_columns
as $tableName => $table) {
272 if (array_key_exists('fields', $table)) {
273 foreach ($table['fields'] as $fieldName => $field) {
275 if (!empty($field['required']) ||
!empty($this->_params
['fields'][$fieldName])) {
276 if ($tableName == 'civicrm_address') {
277 $this->_addressField
= TRUE;
279 if ($tableName == 'civicrm_email') {
280 $this->_emailField
= TRUE;
282 if ($tableName == 'civicrm_phone') {
283 $this->_phoneField
= TRUE;
285 if ($tableName == 'civicrm_relationship') {
286 $this->_relationshipColumns
["{$tableName}_{$fieldName}"] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
287 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
288 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = $field['title'];
292 if (!empty($field['is_statistics'])) {
293 $this->_columnHeaders
[$fieldName]['type'] = $field['type'];
294 $this->_columnHeaders
[$fieldName]['title'] = $field['title'];
297 elseif ($fieldName == 'receive_date') {
298 if ((CRM_Utils_Array
::value('this_year_op', $this->_params
) == 'fiscal' && !empty($this->_params
['this_year_value'])) ||
299 (CRM_Utils_Array
::value('other_year_op', $this->_params
== 'fiscal') && !empty($this->_params
['other_year_value']))){
300 $select[] = self
::fiscalYearOffset($field['dbAlias']) . " as {$tableName}_{$fieldName}";
302 $select[] = " YEAR(".$field['dbAlias'].")" . " as {$tableName}_{$fieldName}";
305 elseif ($fieldName == 'total_amount') {
306 $select[] = "SUM({$field['dbAlias']}) as {$tableName}_{$fieldName}";
309 $select[] = "{$field['dbAlias']} as {$tableName}_{$fieldName}";
310 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array
::value('type', $field);
311 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['title'] = $field['title'];
313 if (!empty($field['no_display'])) {
314 $this->_columnHeaders
["{$tableName}_{$fieldName}"]['no_display'] = TRUE;
321 $this->_select
= "SELECT " . implode(', ', $select) . " ";
326 FROM civicrm_contact {$this->_aliases['civicrm_contact']}
327 INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
328 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND
329 {$this->_aliases['civicrm_contribution']}.is_test = 0 ";
331 if ($this->_emailField
) {
332 $this->_from
.= " LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
333 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
334 {$this->_aliases['civicrm_email']}.is_primary = 1) ";
337 if ($this->_phoneField
) {
338 $this->_from
.= " LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
339 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
340 {$this->_aliases['civicrm_phone']}.is_primary = 1) ";
343 $relContacAlias = 'contact_relationship';
344 $this->_relationshipFrom
= " INNER JOIN civicrm_relationship {$this->_aliases['civicrm_relationship']}
345 ON (({$this->_aliases['civicrm_relationship']}.contact_id_a = {$relContacAlias}.id OR {$this->_aliases['civicrm_relationship']}.contact_id_b = {$relContacAlias}.id ) AND {$this->_aliases['civicrm_relationship']}.is_active = 1) ";
347 if ($this->_addressField
) {
349 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
350 ON {$this->_aliases['civicrm_contact']}.id =
351 {$this->_aliases['civicrm_address']}.contact_id AND
352 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
357 $whereClauses = $havingClauses = $relationshipWhere = array();
358 $this->_relationshipWhere
= '';
359 $this->_statusClause
= '';
361 foreach ($this->_columns
as $tableName => $table) {
362 if (array_key_exists('filters', $table)) {
363 foreach ($table['filters'] as $fieldName => $field) {
365 if ($fieldName == 'this_year' ||
$fieldName == 'other_year') {
367 }elseif (CRM_Utils_Array
::value('type', $field) & CRM_Utils_Type
::T_DATE
) {
368 $relative = CRM_Utils_Array
::value("{$fieldName}_relative", $this->_params
);
369 $from = CRM_Utils_Array
::value("{$fieldName}_from", $this->_params
);
370 $to = CRM_Utils_Array
::value("{$fieldName}_to", $this->_params
);
372 $clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
375 $op = CRM_Utils_Array
::value("{$fieldName}_op", $this->_params
);
377 $clause = $this->whereClause($field,
379 CRM_Utils_Array
::value("{$fieldName}_value", $this->_params
),
380 CRM_Utils_Array
::value("{$fieldName}_min", $this->_params
),
381 CRM_Utils_Array
::value("{$fieldName}_max", $this->_params
)
386 if (!empty($clause)) {
387 if ($tableName == 'civicrm_relationship') {
388 $relationshipWhere[] = $clause;
392 if ($fieldName == 'contribution_status_id') {
393 $this->_statusClause
= " AND " . $clause;
396 if (!empty($field['having'])) {
397 $havingClauses[] = $clause;
400 $whereClauses[] = $clause;
407 if (empty($whereClauses)) {
408 $this->_where
= "WHERE ( 1 ) ";
412 $this->_where
= "WHERE " . implode(' AND ', $whereClauses);
415 if ($this->_aclWhere
) {
416 $this->_where
.= " AND {$this->_aclWhere} ";
419 if (!empty($havingClauses)) {
420 // use this clause to construct group by clause.
421 $this->_having
= "HAVING " . implode(' AND ', $havingClauses);
424 if (!empty($relationshipWhere)) {
425 $this->_relationshipWhere
= ' AND ' . implode(' AND ', $relationshipWhere);
430 $this->_groupBy
= "GROUP BY {$this->_aliases['civicrm_contribution']}.contact_id, YEAR({$this->_aliases['civicrm_contribution']}.receive_date)";
433 //Override to set limit is 10
435 * @param int $rowCount
437 function limit($rowCount = self
::ROW_COUNT_LIMIT
) {
438 parent
::limit($rowCount);
441 //Override to set pager with limit is 10
443 * @param int $rowCount
445 function setPager($rowCount = self
::ROW_COUNT_LIMIT
) {
446 parent
::setPager($rowCount);
454 function statistics(&$rows) {
455 $statistics = parent
::statistics($rows);
457 foreach ($rows as $rownum => $row) {
458 if (is_numeric($rownum)) {
462 $statistics['counts']['rowCount'] = array('title' => ts('Primary Contact(s) Listed'),
466 if ($this->_rowsFound
&& ($this->_rowsFound
> $count)) {
467 $statistics['counts']['rowsFound'] = array('title' => ts('Total Primary Contact(s)'),
468 'value' => $this->_rowsFound
,
482 static function formRule($fields, $files, $self) {
484 if (!empty($fields['this_year_value']) && !empty($fields['other_year_value']) &&
485 ($fields['this_year_value'] == $fields['other_year_value'])
487 $errors['other_year_value'] = ts("Value for filters 'This Year' and 'Other Years' can not be same.");
492 function postProcess() {
493 // get ready with post process params
494 $this->beginPostProcess();
495 $this->fixReportParams();
497 $this->buildACLClause($this->_aliases
['civicrm_contact']);
501 $this->customDataFrom();
506 // build array of result based on column headers. This method also allows
507 // modifying column headers before using it to build result set i.e $rows.
508 $this->buildRows($rows);
510 // format result set.
511 $this->formatDisplay($rows, FALSE);
513 // assign variables to templates
514 $this->doTemplateAssignment($rows);
516 // do print / pdf / instance stuff if needed
517 $this->endPostProcess($rows);
520 function fixReportParams() {
521 if (!empty($this->_params
['this_year_value'])) {
522 $this->_referenceYear
['this_year'] = $this->_params
['this_year_value'];
524 if (!empty($this->_params
['other_year_value'])) {
525 $this->_referenceYear
['other_year'] = $this->_params
['other_year_value'];
532 function buildRows(&$rows) {
533 $contactIds = array();
537 if (!empty($this->_referenceYear
['other_year'])) {
538 (CRM_Utils_Array
::value('other_year_op', $this->_params
) == 'calendar') ?
$other_receive_date = 'YEAR (contri.receive_date)' : $other_receive_date = self
::fiscalYearOffset('contri.receive_date');
539 $addWhere .= " AND {$this->_aliases['civicrm_contact']}.id NOT IN ( SELECT DISTINCT cont.id FROM civicrm_contact cont, civicrm_contribution contri WHERE cont.id = contri.contact_id AND {$other_receive_date} = {$this->_referenceYear['other_year']} AND contri.is_test = 0 ) ";
541 if (!empty($this->_referenceYear
['this_year'])) {
542 (CRM_Utils_Array
::value('this_year_op', $this->_params
) == 'calendar') ?
$receive_date = 'YEAR (contri.receive_date)' : $receive_date = self
::fiscalYearOffset('contri.receive_date');
543 $addWhere .= " AND {$this->_aliases['civicrm_contact']}.id IN ( SELECT DISTINCT cont.id FROM civicrm_contact cont, civicrm_contribution contri WHERE cont.id = contri.contact_id AND {$receive_date} = {$this->_referenceYear['this_year']} AND contri.is_test = 0 ) ";
546 $getContacts = "SELECT SQL_CALC_FOUND_ROWS {$this->_aliases['civicrm_contact']}.id as cid, SUM({$this->_aliases['civicrm_contribution']}.total_amount) as civicrm_contribution_total_amount_sum {$this->_from} {$this->_where} {$addWhere} GROUP BY {$this->_aliases['civicrm_contact']}.id {$this->_having} {$this->_limit}";
548 $dao = CRM_Core_DAO
::executeQuery($getContacts);
550 while ($dao->fetch()) {
551 $contactIds[] = $dao->cid
;
556 $relationshipRows = array();
557 if (empty($contactIds)) {
561 $primaryContributions = $this->buildContributionRows($contactIds);
563 list($relationshipRows, $relatedContactIds) = $this->buildRelationshipRows($contactIds);
565 if (empty($relatedContactIds)) {
566 $rows = $primaryContributions;
570 $relatedContributions = $this->buildContributionRows($relatedContactIds);
572 $summaryYears = array();
573 $summaryYears[] = "civicrm_upto_{$this->_yearStatisticsFrom}";
574 $yearConter = $this->_yearStatisticsFrom
;
576 while ($yearConter <= $this->_yearStatisticsTo
) {
577 $summaryYears[] = $yearConter;
580 $summaryYears[] = 'aggregate_amount';
582 foreach ($primaryContributions as $cid => $primaryRow) {
584 if (!isset($relationshipRows[$cid])) {
589 $total['civicrm_contact_sort_name'] = ts('Total');
590 foreach ($summaryYears as $year) {
591 $total[$year] = CRM_Utils_Array
::value($year, $primaryRow, 0);
594 $relatedContact = FALSE;
596 foreach ($relationshipRows[$cid] as $relcid => $relRow) {
597 if (!isset($relatedContributions[$relcid])) {
600 $relatedContact = TRUE;
601 $relatedRow = $relatedContributions[$relcid];
602 foreach ($summaryYears as $year) {
603 $total[$year] +
= CRM_Utils_Array
::value($year, $relatedRow, 0);
606 foreach (array_keys($this->_relationshipColumns
) as $col) {
607 if (!empty($relRow[$col])) {
608 $relatedRow[$col] = $relRow[$col];
611 $rows["{$cid}_{$relcid}"] = $relatedRow;
613 if ($relatedContact) {
614 $rows["{$cid}_total"] = $total;
615 $rows["{$cid}_bank"] = array('civicrm_contact_sort_name' => ' ');
625 function buildContributionRows($contactIds) {
627 if (empty($contactIds)) {
631 $sqlContribution = "{$this->_select} {$this->_from} WHERE {$this->_aliases['civicrm_contact']}.id IN (" . implode(',', $contactIds) . ") AND {$this->_aliases['civicrm_contribution']}.is_test = 0 {$this->_statusClause} {$this->_groupBy} ";
633 $dao = CRM_Core_DAO
::executeQuery($sqlContribution);
634 $contributionSum = 0;
636 while ($dao->fetch()) {
637 if (!$dao->civicrm_contact_id
) {
641 foreach ($this->_columnHeaders
as $key => $value) {
642 if (property_exists($dao, $key)) {
643 $rows[$dao->civicrm_contact_id
][$key] = $dao->$key;
646 if ($dao->civicrm_contribution_receive_date
) {
647 if ($dao->civicrm_contribution_receive_date
> $this->_yearStatisticsFrom
) {
648 $rows[$dao->civicrm_contact_id
][$dao->civicrm_contribution_receive_date
] = $dao->civicrm_contribution_total_amount
;
651 if (!isset($rows[$dao->civicrm_contact_id
]["civicrm_upto_{$this->_yearStatisticsFrom}"])) {
652 $rows[$dao->civicrm_contact_id
]["civicrm_upto_{$this->_yearStatisticsFrom}"] = 0;
655 $rows[$dao->civicrm_contact_id
]["civicrm_upto_{$this->_yearStatisticsFrom}"] +
= $dao->civicrm_contribution_total_amount
;
659 if (!isset($rows[$dao->civicrm_contact_id
]['aggregate_amount'])) {
660 $rows[$dao->civicrm_contact_id
]['aggregate_amount'] = 0;
662 $rows[$dao->civicrm_contact_id
]['aggregate_amount'] +
= $dao->civicrm_contribution_total_amount
;
673 function buildRelationshipRows($contactIds) {
674 $relationshipRows = $relatedContactIds = array();
675 if (empty($contactIds)) {
676 return array($relationshipRows, $relatedContactIds);
679 $relContactAlias = 'contact_relationship';
681 if (!empty($this->_relationshipColumns
)) {
682 $addRelSelect = ', ' . implode(', ', $this->_relationshipColumns
);
684 $sqlRelationship = "SELECT {$this->_aliases['civicrm_relationship']}.relationship_type_id as relationship_type_id, {$this->_aliases['civicrm_relationship']}.contact_id_a as contact_id_a, {$this->_aliases['civicrm_relationship']}.contact_id_b as contact_id_b {$addRelSelect} FROM civicrm_contact {$relContactAlias} {$this->_relationshipFrom} WHERE {$relContactAlias}.id IN (" . implode(',', $contactIds) . ") AND {$this->_aliases['civicrm_relationship']}.is_active = 1 {$this->_relationshipWhere} GROUP BY {$this->_aliases['civicrm_relationship']}.contact_id_a, {$this->_aliases['civicrm_relationship']}.contact_id_b";
685 $relationshipTypes = CRM_Core_PseudoConstant
::relationshipType();
687 $dao = CRM_Core_DAO
::executeQuery($sqlRelationship);
688 while ($dao->fetch()) {
690 foreach (array_keys($this->_relationshipColumns
) as $rel_column) {
691 $row[$rel_column] = $dao->$rel_column;
693 if (in_array($dao->contact_id_a
, $contactIds)) {
694 $row['civicrm_relationship_relationship_type_id'] = $relationshipTypes[$dao->relationship_type_id
]['label_a_b'];
695 $row['civicrm_relationship_contact_id'] = $dao->contact_id_b
;
696 $relationshipRows[$dao->contact_id_a
][$dao->contact_id_b
] = $row;
697 $relatedContactIds[$dao->contact_id_b
] = $dao->contact_id_b
;
699 if (in_array($dao->contact_id_b
, $contactIds)) {
700 $row['civicrm_relationship_contact_id'] = $dao->contact_id_a
;
701 $row['civicrm_relationship_relationship_type_id'] = $relationshipTypes[$dao->relationship_type_id
]['label_b_a'];
702 $relationshipRows[$dao->contact_id_b
][$dao->contact_id_a
] = $row;
703 $relatedContactIds[$dao->contact_id_a
] = $dao->contact_id_a
;
707 return array($relationshipRows, $relatedContactIds);
710 // Override "This Year" $op options
712 * @param string $type
713 * @param null $fieldName
717 function getOperationPair($type = "string", $fieldName = NULL) {
718 if ($fieldName == 'this_year' ||
$fieldName == 'other_year') {
719 return array('calendar' => ts('Is Calendar Year'), 'fiscal' => ts('Fiscal Year Starting'));
721 return parent
::getOperationPair($type, $fieldName);
727 function alterDisplay(&$rows) {
733 $last_primary = NULL;
734 foreach ($rows as $rowNum => $row) {
735 // Highlight primary contact and amount row
736 if (is_numeric($rowNum) ||
737 ($last_primary && ($rowNum == "{$last_primary}_total"))
739 if (is_numeric($rowNum)) {
740 $last_primary = $rowNum;
742 foreach ($row as $key => $value) {
743 if ($key == 'civicrm_contact_id') {
751 if ($last_primary && ($rowNum == "{$last_primary}_total")) {
752 $value = CRM_Utils_Money
::format($value, ' ');
754 $row[$key] = '<strong>' . $value . '</strong>';
756 $rows[$rowNum] = $row;
759 // Convert Display name into link
760 if (!empty($row['civicrm_contact_sort_name']) && !empty($row['civicrm_contact_id'])) {
761 $url = CRM_Report_Utils_Report
::getNextUrl('contribute/detail',
762 'reset=1&force=1&id_op=eq&id_value=' . $row['civicrm_contact_id'],
763 $this->_absoluteUrl
, $this->_id
765 $rows[$rowNum]['civicrm_contact_sort_name_link'] = $url;
766 $rows[$rowNum]['civicrm_contact_sort_name_hover'] = ts("View Contribution Details for this Contact.");