Merge pull request #8062 from jitendrapurohit/CRM-18312
[civicrm-core.git] / CRM / Report / Form / Contribute / Detail.php
index a400fd36f580cb9ed250925a1fd57214d074514b..79d78c68e00559deac8f2c6ce38d8c5a810ee09f 100644 (file)
@@ -3,7 +3,7 @@
  +--------------------------------------------------------------------+
  | CiviCRM version 4.7                                                |
  +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2015                                |
+ | Copyright CiviCRM LLC (c) 2004-2016                                |
  +--------------------------------------------------------------------+
  | This file is a part of CiviCRM.                                    |
  |                                                                    |
@@ -28,7 +28,7 @@
 /**
  *
  * @package CRM
- * @copyright CiviCRM LLC (c) 2004-2015
+ * @copyright CiviCRM LLC (c) 2004-2016
  * $Id$
  *
  */
@@ -163,6 +163,9 @@ class CRM_Report_Form_Contribute_Detail extends CRM_Report_Form {
         ),
         'grouping' => 'contact-fields',
       ),
+      'civicrm_line_item' => array(
+        'dao' => 'CRM_Price_DAO_LineItem',
+      ),
       'civicrm_phone' => array(
         'dao' => 'CRM_Core_DAO_Phone',
         'fields' => array(
@@ -255,7 +258,7 @@ class CRM_Report_Form_Contribute_Detail extends CRM_Report_Form {
           'financial_type_id' => array(
             'title' => ts('Financial Type'),
             'operatorType' => CRM_Report_Form::OP_MULTISELECT,
-            'options' => CRM_Contribute_PseudoConstant::financialType(),
+            'options' => CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes(),
             'type' => CRM_Utils_Type::T_INT,
           ),
           'contribution_page_id' => array(
@@ -372,6 +375,7 @@ class CRM_Report_Form_Contribute_Detail extends CRM_Report_Form {
         'title' => ts('Campaign'),
         'operatorType' => CRM_Report_Form::OP_MULTISELECT,
         'options' => $this->activeCampaigns,
+        'type' => CRM_Utils_Type::T_INT,
       );
       $this->_columns['civicrm_contribution']['order_bys']['campaign_id'] = array('title' => ts('Campaign'));
     }
@@ -400,7 +404,7 @@ class CRM_Report_Form_Contribute_Detail extends CRM_Report_Form {
     // This is a solution to not throw fatal errors when there is a column in order-by, not present in select/display columns.
     foreach ($this->_orderByFields as $orderBy) {
       if (!array_key_exists($orderBy['name'], $this->_params['fields']) &&
-        empty($orderBy['section'])
+        empty($orderBy['section']) && (strpos($this->_select, $orderBy['dbAlias']) === FALSE)
       ) {
         $this->_select .= ", {$orderBy['dbAlias']} as {$orderBy['tplField']}";
       }
@@ -415,6 +419,7 @@ class CRM_Report_Form_Contribute_Detail extends CRM_Report_Form {
         FROM  civicrm_contact      {$this->_aliases['civicrm_contact']} {$this->_aclFrom}
               INNER JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
                       ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_contribution']}.contact_id AND {$this->_aliases['civicrm_contribution']}.is_test = 0";
+    $this->getPermissionedFTQuery($this);
 
     if (CRM_Utils_Array::value('contribution_or_soft_value', $this->_params) ==
       'both'
@@ -480,15 +485,18 @@ class CRM_Report_Form_Contribute_Detail extends CRM_Report_Form {
         !empty($this->_params['bid_value']))
     ) {
       $this->_from .= "
-                LEFT JOIN civicrm_entity_financial_trxn tx ON (tx.entity_id = {$this->_aliases['civicrm_contribution']}.id AND
-                   tx.entity_table = 'civicrm_contribution')
-                 LEFT JOIN  civicrm_entity_batch {$this->_aliases['civicrm_entity_batch']}
-                        ON ({$this->_aliases['civicrm_entity_batch']}.entity_id = tx.financial_trxn_id AND
-                        {$this->_aliases['civicrm_entity_batch']}.entity_table = 'civicrm_financial_trxn')
-                 LEFT JOIN civicrm_batch {$this->_aliases['civicrm_batch']}
-                        ON {$this->_aliases['civicrm_batch']}.id = {$this->_aliases['civicrm_entity_batch']}.batch_id";
+        LEFT JOIN (
+          SELECT entity_id, financial_trxn_id
+          FROM civicrm_entity_financial_trxn
+          WHERE entity_table = 'civicrm_contribution'
+          GROUP BY entity_id
+        ) tx ON tx.entity_id = {$this->_aliases['civicrm_contribution']}.id
+        LEFT JOIN  civicrm_entity_batch {$this->_aliases['civicrm_entity_batch']}
+          ON ({$this->_aliases['civicrm_entity_batch']}.entity_id = tx.financial_trxn_id
+          AND {$this->_aliases['civicrm_entity_batch']}.entity_table = 'civicrm_financial_trxn')
+        LEFT JOIN civicrm_batch {$this->_aliases['civicrm_batch']}
+          ON {$this->_aliases['civicrm_batch']}.id = {$this->_aliases['civicrm_entity_batch']}.batch_id";
     }
-
   }
 
   public function groupBy() {
@@ -503,13 +511,15 @@ class CRM_Report_Form_Contribute_Detail extends CRM_Report_Form {
   public function statistics(&$rows) {
     $statistics = parent::statistics($rows);
 
-    $totalAmount = $average = array();
+    $totalAmount = $average = $fees = $net = array();
     $count = 0;
     $select = "
         SELECT COUNT({$this->_aliases['civicrm_contribution']}.total_amount ) as count,
                SUM( {$this->_aliases['civicrm_contribution']}.total_amount ) as amount,
                ROUND(AVG({$this->_aliases['civicrm_contribution']}.total_amount), 2) as avg,
-               {$this->_aliases['civicrm_contribution']}.currency as currency
+               {$this->_aliases['civicrm_contribution']}.currency as currency,
+               SUM( {$this->_aliases['civicrm_contribution']}.fee_amount ) as fees,
+               SUM( {$this->_aliases['civicrm_contribution']}.net_amount ) as net
         ";
 
     $group = "\nGROUP BY {$this->_aliases['civicrm_contribution']}.currency";
@@ -517,8 +527,9 @@ class CRM_Report_Form_Contribute_Detail extends CRM_Report_Form {
     $dao = CRM_Core_DAO::executeQuery($sql);
 
     while ($dao->fetch()) {
-      $totalAmount[] = CRM_Utils_Money::format($dao->amount, $dao->currency) . " (" .
-        $dao->count . ")";
+      $totalAmount[] = CRM_Utils_Money::format($dao->amount, $dao->currency) . " (" . $dao->count . ")";
+      $fees[] = CRM_Utils_Money::format($dao->fees, $dao->currency);
+      $net[] = CRM_Utils_Money::format($dao->net, $dao->currency);
       $average[] = CRM_Utils_Money::format($dao->avg, $dao->currency);
       $count += $dao->count;
     }
@@ -531,6 +542,16 @@ class CRM_Report_Form_Contribute_Detail extends CRM_Report_Form {
       'title' => ts('Total Contributions'),
       'value' => $count,
     );
+    $statistics['counts']['fees'] = array(
+      'title' => ts('Fees'),
+      'value' => implode(',  ', $fees),
+      'type' => CRM_Utils_Type::T_STRING,
+    );
+    $statistics['counts']['net'] = array(
+      'title' => ts('Net'),
+      'value' => implode(',  ', $net),
+      'type' => CRM_Utils_Type::T_STRING,
+    );
     $statistics['counts']['avg'] = array(
       'title' => ts('Average'),
       'value' => implode(',  ', $average),
@@ -584,6 +605,12 @@ GROUP BY {$this->_aliases['civicrm_contribution']}.currency";
     $this->buildACLClause($this->_aliases['civicrm_contact']);
 
     $this->beginPostProcess();
+    // CRM-18312 - display soft_credits and soft_credits_for column
+    // when 'Contribution or Soft Credit?' column is not selected
+    if (empty($this->_params['fields']['contribution_or_soft'])) {
+      $this->_params['fields']['contribution_or_soft'] = 1;
+      $this->noDisplayContributionOrSoftColumn = TRUE;
+    }
 
     if (CRM_Utils_Array::value('contribution_or_soft_value', $this->_params) ==
       'contributions_only' &&
@@ -659,6 +686,19 @@ UNION ALL
       $orderClause = array();
       foreach ($this->_orderByArray as $clause) {
         list($alias, $rest) = explode('.', $clause);
+        // CRM-17280 -- In case, we are ordering by custom fields
+        // modify $rest to match the alias used for them in temp3 table
+        $grp = new CRM_Core_DAO_CustomGroup();
+        $grp->table_name = $aliases[$alias];
+        if ($grp->find()) {
+          list($fld, $order) = explode(' ', $rest);
+          foreach ($this->_columns[$aliases[$alias]]['fields'] as $fldName => $value) {
+            if ($value['name'] == $fld) {
+              $fld = $fldName;
+            }
+          }
+          $rest = "{$fld} {$order}";
+        }
         $orderClause[] = $aliases[$alias] . "_" . $rest;
       }
       $orderBy = (!empty($orderClause)) ? "ORDER BY " . implode(', ', $orderClause) : '';
@@ -839,6 +879,12 @@ WHERE  civicrm_contribution_contribution_id={$row['civicrm_contribution_contribu
         $rows[$rowNum]['civicrm_contribution_soft_credit_for'] = $string;
       }
 
+      // CRM-18312 - hide 'contribution_or_soft' column if unchecked.
+      if (!empty($this->noDisplayContributionOrSoftColumn)) {
+        unset($rows[$rowNum]['civicrm_contribution_contribution_or_soft']);
+        unset($this->_columnHeaders['civicrm_contribution_contribution_or_soft']);
+      }
+
       //convert soft_credit_type_id into label
       if (array_key_exists('civicrm_contribution_soft_soft_credit_type_id', $rows[$rowNum])) {
         $rows[$rowNum]['civicrm_contribution_soft_soft_credit_type_id'] = CRM_Core_PseudoConstant::getLabel(