Merge pull request #4752 from davecivicrm/CRM-15180
[civicrm-core.git] / CRM / Price / BAO / LineItem.php
index 428d3131b44aa7013d2c3dad6f399cf648706c49..f399343cef1e4dd29981530dfafa2e2771edf8fe 100644 (file)
@@ -50,7 +50,7 @@ class CRM_Price_BAO_LineItem extends CRM_Price_DAO_LineItem {
    *
    * @param array $params (reference) an assoc array of name/value pairs
    *
-   * @return object CRM_Price_DAO_LineItem object
+   * @return CRM_Price_DAO_LineItem object
    * @access public
    * @static
    */
@@ -93,7 +93,7 @@ class CRM_Price_BAO_LineItem extends CRM_Price_DAO_LineItem {
    * @param array $params   (reference ) an assoc array of name/value pairs
    * @param array $defaults (reference ) an assoc array to hold the flattened values
    *
-   * @return object CRM_Price_BAO_LineItem object
+   * @return CRM_Price_BAO_LineItem object
    * @access public
    * @static
    */
@@ -108,13 +108,13 @@ class CRM_Price_BAO_LineItem extends CRM_Price_DAO_LineItem {
   }
 
   /**
-   * @param $entityId
+   * @param int $entityId
    * @param $entityTable
    *
    * @return null|string
    */
   static function getLineTotal($entityId, $entityTable) {
-    $sqlLineItemTotal = "SELECT SUM(li.line_total)
+    $sqlLineItemTotal = "SELECT SUM(li.line_total + COALESCE(li.tax_amount,0))
 FROM civicrm_line_item li
 WHERE li.entity_table = '{$entityTable}'
 AND li.entity_id = {$entityId}
@@ -123,6 +123,16 @@ AND li.entity_id = {$entityId}
     return $lineItemTotal;
   }
 
+  /**
+   * Wrapper for line item retrieval when contribution ID is known
+   * @param int $contributionID
+   *
+   * @return array
+   */
+  static function getLineItemsByContributionID($contributionID) {
+     return self::getLineItems($contributionID,'contribution', NULL, TRUE, TRUE, " WHERE contribution_id = " . (int) $contributionID);
+  }
+
   /**
    * Given a participant id/contribution id,
    * return contribution/fee line items
@@ -134,10 +144,14 @@ AND li.entity_id = {$entityId}
    * @param bool $isQtyZero
    * @param bool $relatedEntity
    *
+   * @param string $overrideWhereClause e.g "WHERE contribution id = 7 " per the getLineItemsByContributionID wrapper.
+   * this function precedes the convenience of the contribution id but since it does quite a bit more than just a db retrieval we need to be able to use it even
+   * when we don't want it's entity-id magix
+   *
    * @return array of line items
    */
-  static function getLineItems($entityId, $entity = 'participant', $isQuick = NULL , $isQtyZero = TRUE, $relatedEntity = FALSE) {
-    $selectClause = $whereClause = $fromClause = NULL;
+  static function getLineItems($entityId, $entity = 'participant', $isQuick = NULL , $isQtyZero = TRUE, $relatedEntity = FALSE, $overrideWhereClause = '') {
+    $whereClause = $fromClause = NULL;
     $selectClause = "
       SELECT    li.id,
       li.label,
@@ -145,6 +159,8 @@ AND li.entity_id = {$entityId}
       li.qty,
       li.unit_price,
       li.line_total,
+      li.entity_table,
+      li.entity_id,
       pf.label as field_title,
       pf.html_type,
       pfv.membership_type_id,
@@ -153,6 +169,7 @@ AND li.entity_id = {$entityId}
       li.participant_count,
       li.price_field_value_id,
       li.financial_type_id,
+      li.tax_amount,
       pfv.description";
 
     $condition = "li.entity_id = %2.id AND li.entity_table = 'civicrm_%2'";
@@ -190,6 +207,13 @@ AND li.entity_id = {$entityId}
       2 => array($entity, 'Text'),
     );
 
+    $getTaxDetails = FALSE;
+    $invoiceSettings = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,'contribution_invoice_settings');
+    $invoicing = CRM_Utils_Array::value('invoicing', $invoiceSettings);
+    if ($overrideWhereClause) {
+      $whereClause = $overrideWhereClause;
+    }
+
     $dao = CRM_Core_DAO::executeQuery("$selectClause $fromClause $whereClause $orderByClause", $params);
     while ($dao->fetch()) {
       if (!$dao->id) {
@@ -206,12 +230,27 @@ AND li.entity_id = {$entityId}
         'field_title' => $dao->field_title,
         'html_type' => $dao->html_type,
         'description' => $dao->description,
-        'entity_id' => $entityId,
+        // the entity id seems prone to randomness but not sure if it has a reason - so if we are overriding the Where clause we assume
+        // we also JUST WANT TO KNOW the the entity_id in the DB
+        'entity_id' => empty($overrideWhereClause) ? $entityId : $dao->entity_id,
+        'entity_table' => $dao->entity_table,
         'contribution_id' => $dao->contribution_id,
         'financial_type_id' => $dao->financial_type_id,
         'membership_type_id' => $dao->membership_type_id,
         'membership_num_terms' => $dao->membership_num_terms,
+        'tax_amount' => $dao->tax_amount,
       );
+      $lineItems[$dao->id]['tax_rate'] = CRM_Price_BAO_LineItem::calculateTaxRate($lineItems[$dao->id]);
+      $lineItems[$dao->id]['subTotal'] = $lineItems[$dao->id]['qty'] * $lineItems[$dao->id]['unit_price'];
+      if ($lineItems[$dao->id]['tax_amount'] != '') {
+        $getTaxDetails = TRUE;
+      }
+    }
+    if ($invoicing) {
+      $taxTerm = CRM_Utils_Array::value('tax_term', $invoiceSettings);
+      $smarty = CRM_Core_Smarty::singleton();
+      $smarty->assign('taxTerm', $taxTerm);
+      $smarty->assign('getTaxDetails', $getTaxDetails);
     }
     return $lineItems;
   }
@@ -277,6 +316,7 @@ AND li.entity_id = {$entityId}
         'auto_renew' => CRM_Utils_Array::value('auto_renew', $options[$oid]),
         'html_type' => $fields['html_type'],
         'financial_type_id' => CRM_Utils_Array::value('financial_type_id', $options[$oid]),
+        'tax_amount' => CRM_Utils_Array::value('tax_amount', $options[$oid]),
       );
 
       if ($values[$oid]['membership_type_id'] && empty($values[$oid]['auto_renew'])) {
@@ -310,17 +350,15 @@ AND li.entity_id = {$entityId}
   }
 
   /**
-   * Function to process price set and line items.
+   * Process price set and line items.
    *
-   * @param $entityId
+   * @param int $entityId
    * @param array $lineItem line item array
    * @param object $contributionDetails
    * @param string $entityTable entity table
    *
    * @param bool $update
    *
-   * @internal param int $contributionId contribution id
-   * @internal param \decimal $initAmount amount
    * @access public
    * @return void
    * @static
@@ -339,7 +377,9 @@ AND li.entity_id = {$entityId}
 
       foreach ($values as $line) {
         $line['entity_table'] = $entityTable;
-        $line['entity_id'] = $entityId;
+        if (empty($line['entity_id'])) {
+          $line['entity_id'] = $entityId;
+        }
         if(!empty($line['membership_type_id'])) {
           $line['entity_table'] = 'civicrm_membership';
         }
@@ -358,16 +398,19 @@ AND li.entity_id = {$entityId}
         $lineItems = CRM_Price_BAO_LineItem::create($line);
         if (!$update && $contributionDetails) {
           CRM_Financial_BAO_FinancialItem::add($lineItems, $contributionDetails);
+          if (isset($line['tax_amount'])) {
+            CRM_Financial_BAO_FinancialItem::add($lineItems, $contributionDetails, TRUE);
+          }
         }
       }
     }
   }
 
   /**
-   * @param $entityId
+   * @param int $entityId
    * @param string $entityTable
    * @param $amount
-   * @param null $otherParams
+   * @param array $otherParams
    */
   public static function syncLineItems($entityId, $entityTable = 'civicrm_contribution', $amount, $otherParams = NULL) {
     if (!$entityId || CRM_Utils_System::isNull($amount))
@@ -418,7 +461,7 @@ AND li.entity_id = {$entityId}
   }
 
    /**
-   * Function to build line items array.
+   * Build line items array.
    * @param array $params form values
    *
    * @param string $entityId entity id
@@ -478,4 +521,24 @@ AND li.entity_id = {$entityId}
       }
     }
   }
+
+  /**
+   * Calculate tax rate in percentage
+   *
+   * @param $lineItemId an assoc array of lineItem
+   *
+   * @return tax rate
+   *
+   * @access public
+   * @static
+   */
+  public static function calculateTaxRate($lineItemId) {
+    if ($lineItemId['html_type'] == 'Text') {
+      $tax = $lineItemId['tax_amount']/($lineItemId['unit_price'] * $lineItemId['qty'])*100;
+    }
+    else {
+      $tax = ($lineItemId['tax_amount']/$lineItemId['unit_price']) * 100;
+    }
+    return $tax;
+  }
 }