Merge remote-tracking branch 'upstream/4.6' into 4.6-master-2015-04-26-09-47-18
[civicrm-core.git] / CRM / Contribute / BAO / Contribution.php
index fcbdacecb892481cc991d77f03ad4382611e137e..811b51d87b3d9669396d1d4e0a65712339040652 100644 (file)
@@ -3,7 +3,7 @@
  +--------------------------------------------------------------------+
  | CiviCRM version 4.6                                                |
  +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2014                                |
+ | Copyright CiviCRM LLC (c) 2004-2015                                |
  +--------------------------------------------------------------------+
  | This file is a part of CiviCRM.                                    |
  |                                                                    |
@@ -28,7 +28,7 @@
 /**
  *
  * @package CRM
- * @copyright CiviCRM LLC (c) 2004-2014
+ * @copyright CiviCRM LLC (c) 2004-2015
  * $Id$
  *
  */
@@ -367,22 +367,6 @@ class CRM_Contribute_BAO_Contribution extends CRM_Contribute_DAO_Contribution {
       }
     }
 
-    // check if activity record exist for this contribution, if
-    // not add activity
-    $activity = new CRM_Activity_DAO_Activity();
-    $activity->source_record_id = $contribution->id;
-    $activity->activity_type_id = CRM_Core_OptionGroup::getValue('activity_type',
-      'Contribution',
-      'name'
-    );
-    if (!$activity->find(TRUE)) {
-      CRM_Activity_BAO_Activity::addActivity($contribution, 'Offline');
-    }
-    else {
-      // CRM-13237 : if activity record found, update it with campaign id of contribution
-      CRM_Core_DAO::setFieldValue('CRM_Activity_BAO_Activity', $activity->id, 'campaign_id', $contribution->campaign_id);
-    }
-
     // Handle soft credit and / or link to personal campaign page
     $softIDs = CRM_Contribute_BAO_ContributionSoft::getSoftCreditIds($contribution->id);
 
@@ -436,6 +420,22 @@ class CRM_Contribute_BAO_Contribution extends CRM_Contribute_DAO_Contribution {
 
     $transaction->commit();
 
+    // check if activity record exist for this contribution, if
+    // not add activity
+    $activity = new CRM_Activity_DAO_Activity();
+    $activity->source_record_id = $contribution->id;
+    $activity->activity_type_id = CRM_Core_OptionGroup::getValue('activity_type',
+      'Contribution',
+      'name'
+    );
+    if (!$activity->find(TRUE)) {
+      CRM_Activity_BAO_Activity::addActivity($contribution, 'Offline');
+    }
+    else {
+      // CRM-13237 : if activity record found, update it with campaign id of contribution
+      CRM_Core_DAO::setFieldValue('CRM_Activity_BAO_Activity', $activity->id, 'campaign_id', $contribution->campaign_id);
+    }
+
     // do not add to recent items for import, CRM-4399
     if (empty($params['skipRecentView'])) {
       $url = CRM_Utils_System::url('civicrm/contact/view/contribution',
@@ -1632,7 +1632,9 @@ LEFT JOIN  civicrm_contribution contribution ON ( componentPayment.contribution_
             }
 
             // CRM-15735-to update the membership status as per the contribution receive date
+            $joinDate = NULL;
             if (!empty($params['receive_date'])) {
+              $joinDate = $params['receive_date'];
               $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($membership->start_date,
                 $membership->end_date,
                 $membership->join_date,
@@ -1651,7 +1653,7 @@ LEFT JOIN  civicrm_contribution contribution ON ( componentPayment.contribution_
               $dates['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
             }
             else {
-              $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, NULL, NULL, NULL, $numterms);
+              $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membership->membership_type_id, $joinDate, NULL, NULL, $numterms);
             }
 
             //get the status for membership.
@@ -1776,6 +1778,7 @@ LEFT JOIN  civicrm_contribution contribution ON ( componentPayment.contribution_
     $query = "
       SELECT    c.id                 as contribution_id,
                 c.contact_id         as contact_id,
+                c.contribution_recur_id,
                 mp.membership_id     as membership_id,
                 m.membership_type_id as membership_type_id,
                 pp.participant_id    as participant_id,
@@ -1811,6 +1814,9 @@ LEFT JOIN  civicrm_contribution contribution ON ( componentPayment.contribution_
       if ($dao->pledge_payment_id) {
         $pledgePayment[] = $dao->pledge_payment_id;
       }
+      if ($dao->contribution_recur_id) {
+        $componentDetails['contributionRecur'] = $dao->contribution_recur_id;
+      }
     }
 
     if ($pledgePayment) {
@@ -2775,7 +2781,7 @@ WHERE  contribution_id = %1 ";
         'trxn_date' => date('YmdHis'),
         'total_amount' => $totalAmount,
         'fee_amount' => CRM_Utils_Array::value('fee_amount', $params),
-        'net_amount' => CRM_Utils_Array::value('net_amount', $params),
+        'net_amount' => CRM_Utils_Array::value('net_amount', $params, $totalAmount),
         'currency' => $params['contribution']->currency,
         'trxn_id' => $params['contribution']->trxn_id,
         'status_id' => $statusId,
@@ -2843,6 +2849,7 @@ WHERE  contribution_id = %1 ";
 
         //Update contribution status
         $params['trxnParams']['status_id'] = $params['contribution']->contribution_status_id;
+        $params['trxnParams']['trxn_id'] = $params['contribution']->trxn_id;
         if (!empty($params['contribution_status_id']) &&
           $params['prevContribution']->contribution_status_id != $params['contribution']->contribution_status_id
         ) {
@@ -3117,6 +3124,14 @@ WHERE  contribution_id = %1 ";
         }
       }
     }
+    if ($context == 'changeFinancialType') {
+      $params['skipLineItem'] = FALSE;
+      foreach ($params['line_item'] as &$lineItems) {
+        foreach ($lineItems as &$line) {
+          $line['financial_type_id'] = $params['financial_type_id'];
+        }
+      }
+    }
   }
 
   /**
@@ -3263,6 +3278,7 @@ WHERE  contribution_id = %1 ";
       $params['partial_payment_total'] = $contributionDAO->total_amount;
       $params['partial_amount_pay'] = $trxnsData['total_amount'];
       $trxnsData['trxn_date'] = !empty($trxnsData['trxn_date']) ? $trxnsData['trxn_date'] : date('YmdHis');
+      $trxnsData['net_amount'] = !empty($trxnsData['net_amount']) ? $trxnsData['net_amount'] : $trxnsData['total_amount'];
 
       // record the entry
       $financialTrxn = CRM_Contribute_BAO_Contribution::recordFinancialAccounts($params, $trxnsData);
@@ -3284,7 +3300,7 @@ WHERE  contribution_id = %1 ";
 
       // update statuses
       // criteria for updates contribution total_amount == financial_trxns of partial_payments
-      $sql = "SELECT SUM(ft.total_amount) as sum_of_payments
+      $sql = "SELECT SUM(ft.total_amount) as sum_of_payments, SUM(ft.net_amount) as net_amount_total
 FROM civicrm_financial_trxn ft
 LEFT JOIN civicrm_entity_financial_trxn eft
   ON (ft.id = eft.financial_trxn_id)
@@ -3293,7 +3309,9 @@ WHERE eft.entity_table = 'civicrm_contribution'
   AND ft.to_financial_account_id != {$toFinancialAccount}
   AND ft.status_id = {$statusId}
 ";
-      $sumOfPayments = CRM_Core_DAO::singleValueQuery($sql);
+      $query = CRM_Core_DAO::executeQuery($sql);
+      $query->fetch();
+      $sumOfPayments = $query->sum_of_payments;
 
       // update statuses
       if ($contributionDAO->total_amount == $sumOfPayments) {
@@ -3302,8 +3320,9 @@ WHERE eft.entity_table = 'civicrm_contribution'
         $contributionDAO->contribution_status_id = $statusId;
         $contributionDAO->cancel_date = 'null';
         $contributionDAO->cancel_reason = NULL;
-        $netAmount = !empty($trxnsData['net_amount']) ? $trxnsData['net_amount'] : $trxnsData['total_amount'];
-        $contributionDAO->net_amount = $contributionDAO->net_amount + $netAmount;
+        $netAmount = !empty($trxnsData['net_amount']) ? NULL : $trxnsData['total_amount'];
+        $contributionDAO->net_amount = $query->net_amount_total + $netAmount;
+        $contributionDAO->fee_amount = $contributionDAO->total_amount - $contributionDAO->net_amount;
         $contributionDAO->save();
 
         //Change status of financial record too
@@ -3491,7 +3510,7 @@ WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
       $baseTrxnId = $baseTrxnId['financialTrxnId'];
       $isBalance = FALSE;
     }
-    if (empty($total) || $usingLineTotal) {
+    if (!CRM_Utils_Array::value('total_amount', $total) || $usingLineTotal) {
       // for additional participants
       if ($entityTable == 'civicrm_participant') {
         $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
@@ -3670,4 +3689,35 @@ WHERE con.id = {$contributionId}
     return $params;
   }
 
+  /**
+   * Check financial type validation on update of a contribution.
+   *
+   * @param Integer $financialTypeId
+   *   Value of latest Financial Type.
+   *
+   * @param Integer $contributionId
+   *   Contribution Id.
+   *
+   * @param array $errors
+   *   List of errors.
+   *
+   * @return bool
+   */
+  public static function checkFinancialTypeChange($financialTypeId, $contributionId, &$errors) {
+    if (!empty($financialTypeId)) {
+      $oldFinancialTypeId = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'financial_type_id');
+      if ($oldFinancialTypeId == $financialTypeId) {
+        return FALSE;
+      }
+    }
+    $sql = 'SELECT financial_type_id FROM civicrm_line_item WHERE contribution_id = %1 GROUP BY financial_type_id;';
+    $params = array(
+      '1' => array($contributionId, 'Integer'),
+    );
+    $result = CRM_Core_DAO::executeQuery($sql, $params);
+    if ($result->N > 1) {
+      $errors['financial_type_id'] = ts('One or more line items have a different financial type than the contribution. Editing the financial type is not yet supported in this situation.');
+    }
+  }
+
 }