Merge pull request #5 from rohankatkar/VAT-389
[civicrm-core.git] / CRM / Contribute / BAO / Contribution.php
index 39aaa173703a1564c34f07d9f9a39e9f19571321..715ea11aba417daf2c83fbc12944afab55f1c615 100644 (file)
@@ -69,6 +69,15 @@ class CRM_Contribute_BAO_Contribution extends CRM_Contribute_DAO_Contribution {
   /*
    * construct method
    */
+  /**
+   * class constructor
+   *
+   * @access public
+   * @return \CRM_Contribute_DAO_Contribution
+   */
+  /**
+   *
+   */
   function __construct() {
     parent::__construct();
   }
@@ -239,7 +248,7 @@ class CRM_Contribute_BAO_Contribution extends CRM_Contribute_DAO_Contribution {
    * @access public
    * @static
    */
-  static function &create(&$params, $ids = array()) {
+  static function create(&$params, $ids = array()) {
     $dateFields = array('receive_date', 'cancel_date', 'receipt_date', 'thankyou_date');
     foreach ($dateFields as $df) {
       if (isset($params[$df])) {
@@ -491,6 +500,9 @@ class CRM_Contribute_BAO_Contribution extends CRM_Contribute_DAO_Contribution {
    * scheme. Adding weight is super important and should be done in the
    * next week or so, before this can be called complete.
    *
+   * @param string $contactType
+   * @param bool $status
+   *
    * @return array array of importable Fields
    * @access public
    * @static
@@ -558,6 +570,9 @@ class CRM_Contribute_BAO_Contribution extends CRM_Contribute_DAO_Contribution {
     return self::$_importableFields;
   }
 
+  /**
+   * @return array
+   */
   static function &exportableFields() {
     if (!self::$_exportableFields) {
       if (!self::$_exportableFields) {
@@ -639,6 +654,13 @@ class CRM_Contribute_BAO_Contribution extends CRM_Contribute_DAO_Contribution {
     return self::$_exportableFields;
   }
 
+  /**
+   * @param null $status
+   * @param null $startDate
+   * @param null $endDate
+   *
+   * @return array|null
+   */
   static function getTotalAmountAndCount($status = NULL, $startDate = NULL, $endDate = NULL) {
     $where = array();
     switch ($status) {
@@ -690,8 +712,9 @@ INNER JOIN  civicrm_contact contact ON ( contact.id = civicrm_contribution.conta
   /**
    * Delete the indirect records associated with this contribution first
    *
-   * @return $results no of deleted Contribution on success, false otherwise
-   * @access public
+   * @param $id
+   *
+   * @return mixed|null $results no of deleted Contribution on success, false otherwise@access public
    * @static
    */
   static function deleteContribution($id) {
@@ -761,9 +784,12 @@ INNER JOIN  civicrm_contact contact ON ( contact.id = civicrm_contribution.conta
   /**
    * Check if there is a contribution with the same trxn_id or invoice_id
    *
-   * @param array  $params (reference ) an assoc array of name/value pairs
-   * @param array  $duplicates (reference ) store ids of duplicate contribs
+   * @param $input
+   * @param array $duplicates (reference ) store ids of duplicate contribs
    *
+   * @param null $id
+   *
+   * @internal param array $params (reference ) an assoc array of name/value pairs
    * @return boolean true if duplicate, false otherwise
    * @access public
    * static
@@ -869,30 +895,6 @@ INNER JOIN  civicrm_contact contact ON ( contact.id = civicrm_contribution.conta
    */
   static function getSpecialContributionFields() {
     $extraFields = array(
-      'honor_contact_name' => array(
-        'name' => 'honor_contact_name',
-        'title' => 'Honor Contact Name',
-        'headerPattern' => '/^honor_contact_name$/i',
-        'where' => 'civicrm_contact_c.display_name',
-      ),
-      'honor_contact_email' => array(
-        'name' => 'honor_contact_email',
-        'title' => 'Honor Contact Email',
-        'headerPattern' => '/^honor_contact_email$/i',
-        'where' => 'honor_email.email',
-      ),
-      'honor_contact_id' => array(
-        'name' => 'honor_contact_id',
-        'title' => 'Honor Contact ID',
-        'headerPattern' => '/^honor_contact_id$/i',
-        'where' => 'civicrm_contribution.honor_contact_id',
-      ),
-      'honor_type_label' => array(
-        'name' => 'honor_type_label',
-        'title' => 'Honor Type Label',
-        'headerPattern' => '/^honor_type_label$/i',
-        'where' => 'honor_type.label',
-      ),
       'contribution_soft_credit_name' => array(
         'name' => 'contribution_soft_credit_name',
         'title' => 'Soft Credit Name',
@@ -922,6 +924,11 @@ INNER JOIN  civicrm_contact contact ON ( contact.id = civicrm_contribution.conta
     return $extraFields;
   }
 
+  /**
+   * @param $pageID
+   *
+   * @return array
+   */
   static function getCurrentandGoalAmount($pageID) {
     $query = "
 SELECT p.goal_amount as goal, sum( c.total_amount ) as total
@@ -1004,6 +1011,11 @@ WHERE  civicrm_contribution.contact_id = civicrm_contact.id
     return CRM_Core_DAO::singleValueQuery($query, CRM_Core_DAO::$_nullArray);
   }
 
+  /**
+   * @param $contactID
+   *
+   * @return array
+   */
   static function annual($contactID) {
     if (is_array($contactID)) {
       $contactIDs = implode(',', $contactID);
@@ -1174,11 +1186,14 @@ LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.cont
 
   /**
    *  Function to create address associated with contribution record.
-   *  @param array $params an associated array
-   *  @param int   $billingID $billingLocationTypeID
    *
-   *  @return address id
-   *  @static
+   * @param array $params an associated array
+   * @param $billingLocationTypeID
+   *
+   * @internal param int $billingID $billingLocationTypeID
+   *
+   * @return address id
+   * @static
    */
   static function createAddress(&$params, $billingLocationTypeID) {
     $billingFields = array(
@@ -1211,8 +1226,11 @@ LEFT JOIN civicrm_option_value contribution_status ON (civicrm_contribution.cont
   /**
    * Delete billing address record related contribution
    *
-   * @param int $contact_id contact id
-   * @param int $contribution_id contributionId
+   * @param null $contributionId
+   * @param null $contactId
+   *
+   * @internal param int $contact_id contact id
+   * @internal param int $contribution_id contributionId
    * @access public
    * @static
    */
@@ -1698,6 +1716,12 @@ LEFT JOIN  civicrm_contribution contribution ON ( componentPayment.contribution_
     return $componentDetails;
   }
 
+  /**
+   * @param $contactId
+   * @param bool $includeSoftCredit
+   *
+   * @return null|string
+   */
   static function contributionCount($contactId, $includeSoftCredit = TRUE) {
     if (!$contactId) {
       return 0;
@@ -1845,6 +1869,15 @@ INNER JOIN civicrm_activity ON civicrm_activity_contact.activity_id = civicrm_ac
    * @param boolean $loadAll - load all related objects - even where id not passed in? (allows API to call this)
    * Note that the unit test for the BaseIPN class tests this function
    */
+  /**
+   * @param $input
+   * @param $ids
+   * @param bool $required
+   * @param bool $loadAll
+   *
+   * @return bool
+   * @throws Exception
+   */
   function loadRelatedObjects(&$input, &$ids, $required = FALSE, $loadAll = false) {
     if($loadAll){
       $ids = array_merge($this->getComponentDetails($this->id),$ids);
@@ -2017,6 +2050,15 @@ WHERE  contribution_id = %1 ";
    *   function doing emails / pdfs with it
    * @return array $messageArray - messages
    */
+  /**
+   * @param $input
+   * @param $ids
+   * @param $values
+   * @param bool $recur
+   * @param bool $returnMessageText
+   *
+   * @throws Exception
+   */
   function composeMessageArray(&$input, &$ids, &$values, $recur = FALSE, $returnMessageText = TRUE) {
     if (empty($this->_relatedObjects)) {
       $this->loadRelatedObjects($input, $ids);
@@ -2146,6 +2188,13 @@ WHERE  contribution_id = %1 ";
    *
    * NB don't add direct calls to the function as we intend to change the signature
    */
+  /**
+   * @param $input
+   * @param $values
+   * @param array $ids
+   *
+   * @return mixed
+   */
   function _gatherMessageValues($input, &$values, $ids = array()) {
     // set display address of contributor
     if ($this->address_id) {
@@ -2436,6 +2485,8 @@ WHERE  contribution_id = %1 ";
    *
    * @param int $contributionId contribution id
    *
+   * @param bool $isNotCancelled
+   *
    * @return boolean
    * @access public
    * @static
@@ -2492,6 +2543,9 @@ WHERE  contribution_id = %1 ";
    * @param array $params contribution object, line item array and params for trxn
    *
    *
+   * @param null $financialTrxnVals
+   *
+   * @return null|object
    * @access public
    * @static
    */
@@ -2762,6 +2816,8 @@ WHERE  contribution_id = %1 ";
    *
    * @param string $context update scenarios
    *
+   * @param null $skipTrxn
+   *
    * @access public
    * @static
    */
@@ -2878,7 +2934,8 @@ WHERE  contribution_id = %1 ";
           }
           else {
             $diff = 1;
-            if ($context == 'changeFinancialType' || $params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus)) {
+            if ($context == 'changeFinancialType' || $params['contribution']->contribution_status_id == array_search('Cancelled', $contributionStatus)
+              || $params['contribution']->contribution_status_id == array_search('Refunded', $contributionStatus)) {
              $diff = -1;
             }
             $amount = $diff * $fieldValues['line_total'];
@@ -2910,6 +2967,7 @@ WHERE  contribution_id = %1 ";
    *
    * @param array $errors list of errors
    *
+   * @return bool
    * @access public
    * @static
    */
@@ -2958,8 +3016,10 @@ WHERE  contribution_id = %1 ";
    * @see CRM_Core_DAO::buildOptions
    *
    * @param String $fieldName
-   * @param String $context: @see CRM_Core_DAO::buildOptionsContext
-   * @param Array $props: whatever is known about this dao object
+   * @param String $context : @see CRM_Core_DAO::buildOptionsContext
+   * @param Array $props : whatever is known about this dao object
+   *
+   * @return Array|bool
    */
   public static function buildOptions($fieldName, $context = NULL, $props = array()) {
     $className = __CLASS__;
@@ -2988,6 +3048,9 @@ WHERE  contribution_id = %1 ";
    *
    * @param integer $financialTypeId Financial Type id
    *
+   * @param string $relationName
+   *
+   * @return array|bool
    * @access public
    * @static
    */
@@ -3009,6 +3072,14 @@ WHERE  contribution_id = %1 ";
    * @param array $trxnData : to take user provided input of transaction details.
    * @param string $paymentType 'owed' for purpose of recording partial payments, 'refund' for purpose of recording refund payments
    */
+  /**
+   * @param $contributionId
+   * @param $trxnsData
+   * @param string $paymentType
+   * @param null $participantId
+   *
+   * @return null|object
+   */
   static function recordAdditionalPayment($contributionId, $trxnsData, $paymentType = 'owed', $participantId = NULL) {
     $statusId = CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name');
     $getInfoOf['id'] = $contributionId;
@@ -3059,10 +3130,13 @@ WHERE eft.entity_table = 'civicrm_contribution'
 
         if ($participantId) {
           // update participant status
-          $participantUpdate['id'] = $participantId;
           $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
-          $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
-          CRM_Event_BAO_Participant::add($participantUpdate);
+          $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
+          foreach ($ids as $val) {
+            $participantUpdate['id'] = $val;
+            $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
+            CRM_Event_BAO_Participant::add($participantUpdate);
+          }
         }
 
         // update financial item statuses
@@ -3105,23 +3179,27 @@ WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
       $getLine['entity_id'] = $contributionDAO->id;
       $getLine['entity_table'] = 'civicrm_contribution';
       $lineItemId = CRM_Price_BAO_LineItem::retrieve($getLine, CRM_Core_DAO::$_nullArray);
-      $addFinancialEntry = array(
-        'transaction_date' => $financialTrxn->trxn_date,
-        'contact_id' => $contributionDAO->contact_id,
-        'amount' => $financialTrxn->total_amount,
-        'status_id' => array_search('Paid', $financialItemStatus),
-        'entity_id' => $lineItemId->id,
-        'entity_table' => 'civicrm_line_item'
-      );
-      $trxnIds['id'] =  $financialTrxn->id;
-      CRM_Financial_BAO_FinancialItem::create($addFinancialEntry, NULL, $trxnIds);
-
+      if (!empty($lineItemId->id)) {
+        $addFinancialEntry = array(
+          'transaction_date' => $financialTrxn->trxn_date,
+          'contact_id' => $contributionDAO->contact_id,
+          'amount' => $financialTrxn->total_amount,
+          'status_id' => array_search('Paid', $financialItemStatus),
+          'entity_id' => $lineItemId->id,
+          'entity_table' => 'civicrm_line_item'
+        );
+        $trxnIds['id'] =  $financialTrxn->id;
+        CRM_Financial_BAO_FinancialItem::create($addFinancialEntry, NULL, $trxnIds);
+      }
       if ($participantId) {
         // update participant status
-        $participantUpdate['id'] = $participantId;
         $participantStatuses = CRM_Event_PseudoConstant::participantStatus();
-        $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
-        CRM_Event_BAO_Participant::add($participantUpdate);
+        $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
+        foreach ($ids as $val) {
+          $participantUpdate['id'] = $val;
+          $participantUpdate['status_id'] = array_search('Registered', $participantStatuses);
+          CRM_Event_BAO_Participant::add($participantUpdate);
+        }
       }
     }
 
@@ -3142,6 +3220,15 @@ WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
     return $financialTrxn;
   }
 
+  /**
+   * @param $entityObj
+   * @param $trxnObj
+   * @param $activityType
+   * @param $component
+   * @param $contributionId
+   *
+   * @throws CRM_Core_Exception
+   */
   static function addActivityForPayment($entityObj, $trxnObj, $activityType, $component, $contributionId) {
     if ($component == 'event') {
       $date = CRM_Utils_Date::isoToMysql($trxnObj->trxn_date);
@@ -3180,11 +3267,26 @@ WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
     CRM_Activity_BAO_Activity::create($activityParams);
   }
 
+  /**
+   * @param $id
+   * @param $component
+   * @param bool $getTrxnInfo
+   * @param bool $usingLineTotal
+   *
+   * @return mixed
+   */
   static function getPaymentInfo($id, $component, $getTrxnInfo = FALSE, $usingLineTotal = FALSE) {
     if ($component == 'event') {
       $entity = 'participant';
       $entityTable = 'civicrm_participant';
       $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $id, 'contribution_id', 'participant_id');
+
+      if (!$contributionId) {
+        if ($primaryParticipantId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_Participant', $id, 'registered_by_id')) {
+          $contributionId = CRM_Core_DAO::getFieldValue('CRM_Event_BAO_ParticipantPayment', $primaryParticipantId, 'contribution_id', 'participant_id');
+          $id = $primaryParticipantId;
+        }
+      }
     }
     $total = CRM_Core_BAO_FinancialTrxn::getBalanceTrxnAmt($contributionId);
     $baseTrxnId = !empty($total['trxn_id']) ? $total['trxn_id'] : NULL;
@@ -3198,7 +3300,17 @@ WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
       $isBalance = FALSE;
     }
     if (empty($total) || $usingLineTotal) {
-      $total = CRM_Price_BAO_LineItem::getLineTotal($id, $entityTable);
+      // for additional participants
+      if ($entityTable == 'civicrm_participant') {
+       $ids = CRM_Event_BAO_Participant::getParticipantIds($contributionId);
+       $total = 0;
+       foreach ($ids as $val) {
+         $total += CRM_Price_BAO_LineItem::getLineTotal($val, $entityTable);
+       }
+      }
+      else {
+        $total = CRM_Price_BAO_LineItem::getLineTotal($id, $entityTable);
+      }
     }
     else {
       $baseTrxnId = $total['trxn_id'];
@@ -3206,11 +3318,17 @@ WHERE eft.financial_trxn_id IN ({$trxnId}, {$baseTrxnId['financialTrxnId']})
     }
 
     $paymentBalance = CRM_Core_BAO_FinancialTrxn::getPartialPaymentWithType($id, $entity, FALSE, $total);
+    $contributionIsPayLater = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'is_pay_later');
+    if ($paymentBalance == 0 && $contributionIsPayLater) {
+      $paymentBalance = $total;
+    }
+
     $info['total'] = $total;
     $info['paid'] = $total - $paymentBalance;
     $info['balance'] = $paymentBalance;
     $info['id'] = $id;
     $info['component'] = $component;
+    $info['payLater'] = $contributionIsPayLater;
     $rows = array();
     if ($getTrxnInfo && $baseTrxnId) {
       $sql = "
@@ -3250,4 +3368,19 @@ WHERE con.id = {$contributionId}
     }
     return $info;
   }
+
+  /**
+   * Function to retreive the admin page data for contribution
+   *
+   */
+  static function getContributionSettings() {
+    $fields = array('invoice_prefix','due_date','due_date_period','notes','credit_notes_prefix','tax_display_settings');
+    foreach ($fields as $values) {
+      $fieldName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_Setting',$values, 'value','name');
+      if (preg_match('/"([^"]+)"/', $fieldName, $fieldData)) {
+        $fieldValue[$values] = $fieldData[1];
+      }
+    }
+    return $fieldValue;
+  }
 }