/**	function to save the product tax information in vtiger_producttaxrel table
  *	@param string $tablename - vtiger_tablename to save the product tax relationship (producttaxrel)
  *	@param string $module	 - current module name
  *	$return void
  */
 function insertTaxInformation($tablename, $module)
 {
     global $adb, $log;
     $log->debug("Entering into insertTaxInformation({$tablename}, {$module}) method ...");
     $tax_details = getAllTaxes();
     $tax_per = '';
     //Save the Product - tax relationship if corresponding tax check box is enabled
     //Delete the existing tax if any
     if ($this->mode == 'edit') {
         for ($i = 0; $i < count($tax_details); $i++) {
             $taxid = getTaxId($tax_details[$i]['taxname']);
             $sql = "delete from vtiger_producttaxrel where productid=? and taxid=?";
             $adb->pquery($sql, array($this->id, $taxid));
         }
     }
     for ($i = 0; $i < count($tax_details); $i++) {
         $tax_name = $tax_details[$i]['taxname'];
         $tax_checkname = $tax_details[$i]['taxname'] . "_check";
         if ($_REQUEST[$tax_checkname] == 'on' || $_REQUEST[$tax_checkname] == 1) {
             $taxid = getTaxId($tax_name);
             $tax_per = $_REQUEST[$tax_name];
             if ($tax_per == '') {
                 $log->debug("Tax selected but value not given so default value will be saved.");
                 $tax_per = getTaxPercentage($tax_name);
             }
             $log->debug("Going to save the Product - {$tax_name} tax relationship");
             $query = "insert into vtiger_producttaxrel values(?,?,?)";
             $adb->pquery($query, array($this->id, $taxid, $tax_per));
         }
     }
     $log->debug("Exiting from insertTaxInformation({$tablename}, {$module}) method ...");
 }
 function __construct($fieldname = '')
 {
     InventoryLineField::$ILFieldsLabel = array('item name' => InventoryLineField::$ILFieldsName['productid'], 'quantity' => InventoryLineField::$ILFieldsName['quantity'], 'list price' => InventoryLineField::$ILFieldsName['listprice'], 'item comment' => InventoryLineField::$ILFieldsName['comment'], 'item discount amount' => InventoryLineField::$ILFieldsName['discount_amount'], 'item discount percent' => InventoryLineField::$ILFieldsName['discount_percent']);
     $taxes = getAllTaxes('all');
     foreach ($taxes as $key => $tax) {
         $fieldlabel = strtolower($tax['taxlabel']);
         InventoryLineField::$ILFieldsLabel[$fieldlabel] = array('uitype' => 7, 'fieldtype' => 'double', 'fieldname' => $tax['taxname'], 'columnname' => $tax['taxname'], 'fieldlabel' => $tax['taxlabel'], 'tablename' => 'vtiger_inventoryproductrel', 'typeofdata' => 'N~O', 'mandatory' => 'false');
         InventoryLineField::$ILFieldsName[$tax['taxname']] = InventoryLineField::$ILFieldsLabel[$fieldlabel];
     }
     $this->fieldname = $fieldname;
 }
 function getShippingTaxes()
 {
     $shippingTaxDetails = $this->get('shippingTaxDetails');
     if ($shippingTaxDetails) {
         return $shippingTaxDetails;
     }
     $record = $this->getId();
     if ($record) {
         $relatedProducts = getAssociatedProducts($this->getModuleName(), $this->getEntity());
         $shippingTaxDetails = $relatedProducts[1]['final_details']['sh_taxes'];
     } else {
         $shippingTaxDetails = getAllTaxes('available', 'sh', 'edit', $this->getId());
     }
     $this->set('shippingTaxDetails', $shippingTaxDetails);
     return $shippingTaxDetails;
 }
Example #4
0
 function getProductTaxes()
 {
     $taxDetails = $this->get('taxDetails');
     if ($taxDetails) {
         return $taxDetails;
     }
     $record = $this->getId();
     if ($record) {
         $relatedProducts = getAssociatedProducts($this->getModuleName(), $this->getEntity());
         $taxDetails = $relatedProducts[1]['final_details']['taxes'];
     } else {
         $taxDetails = getAllTaxes('available', '', $this->getEntity()->mode, $this->getId());
     }
     $this->set('taxDetails', $taxDetails);
     return $taxDetails;
 }
 private function initTax($element, $parent)
 {
     if (!empty($element['parent_id'])) {
         $this->taxType = $parent['hdnTaxType'];
     }
     $productId = vtws_getIdComponents($element['productid']);
     $productId = $productId[1];
     if (strcasecmp($parent['hdnTaxType'], $this->Individual) === 0) {
         $found = false;
         $meta = $this->getMeta();
         $moduleFields = $meta->getModuleFields();
         $productTaxList = $this->getProductTaxList($productId);
         if (count($productTaxList) > 0) {
             foreach ($moduleFields as $fieldName => $field) {
                 if (preg_match('/tax\\d+/', $fieldName) != 0) {
                     if (!empty($element[$fieldName])) {
                         $found = true;
                         if (is_array($productTaxList[$fieldName])) {
                             $this->taxList[$fieldName] = array('label' => $field->getFieldLabelKey(), 'percentage' => $element[$fieldName]);
                         }
                     }
                 }
             }
         } elseif ($found == false) {
             array_merge($this->taxList, $productTaxList);
         }
     } else {
         $meta = $this->getMeta();
         $moduleFields = $meta->getModuleFields();
         $availableTaxes = getAllTaxes('available');
         $found = false;
         foreach ($moduleFields as $fieldName => $field) {
             if (preg_match('/tax\\d+/', $fieldName) != 0) {
                 $found = true;
                 if (!empty($element[$fieldName])) {
                     $this->taxList[$fieldName] = array('label' => $field->getFieldLabelKey(), 'percentage' => $element[$fieldName]);
                 }
             }
         }
         if (!$found) {
             foreach ($availableTaxes as $taxInfo) {
                 $this->taxList[$taxInfo['taxname']] = array('label' => $field->getFieldLabelKey(), 'percentage' => $taxInfo['percentage']);
             }
         }
     }
     $this->taxList;
 }
Example #6
0
 public static function getProductTaxes()
 {
     vimport('~~/include/utils/InventoryUtils.php');
     $taxes = getAllTaxes();
     $recordList = array();
     foreach ($taxes as $taxInfo) {
         $taxRecord = new self();
         $taxRecord->setData($taxInfo)->setType(self::PRODUCT_AND_SERVICE_TAX);
         $recordList[] = $taxRecord;
     }
     return $recordList;
 }
 public function beforeGetTaskform($viewer)
 {
     global $adb;
     $new_module = $this->getWorkflow()->getSettings();
     $new_module = $new_module["module_name"];
     if (!empty($new_module) && $new_module != -1) {
         $viewer->assign("new_module", $new_module);
     }
     $sql = "SELECT\r\n                    vtiger_crmentity.crmid, vtiger_crmentity.smownerid, vtiger_crmentity.description,\r\n                    vtiger_products.*,\r\n                    vtiger_productcf.*\r\n                FROM vtiger_products\r\n                    INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid = vtiger_products.productid\r\n                    INNER JOIN vtiger_productcf ON vtiger_products.productid = vtiger_productcf.productid\r\n                    LEFT JOIN vtiger_vendor ON vtiger_vendor.vendorid = vtiger_products.vendor_id\r\n                    LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid\r\n                    LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid\r\n                WHERE\r\n                    vtiger_products.productid > 0 AND\r\n                    vtiger_crmentity.deleted = 0 and\r\n                    vtiger_products.discontinued <> 0 AND\r\n                    (vtiger_products.productid NOT IN (\r\n                        SELECT crmid FROM vtiger_seproductsrel WHERE vtiger_products.productid > 0 AND setype='Products'\r\n                        )\r\n                    )";
     $result = $adb->query($sql);
     $products = array();
     $taxes = array();
     while ($row = $adb->fetchByAssoc($result)) {
         $products[$row["productid"]] = $row;
         $taxes[$row["productid"]] = getTaxDetailsForProduct($row["productid"], 'all');
         if (empty($taxes[$row["productid"]])) {
             $taxes[$row["productid"]] = array("a" => "b");
         }
     }
     $viewer->assign("taxlist", $taxes);
     $viewer->assign("productlist", $products);
     $workflows = Workflow2::getWorkflowsForModule($new_module, 1);
     $viewer->assign("extern_workflows", $workflows);
     $module = array();
     $module["Invoice"] = getTranslatedString("Invoice", "Invoice");
     $module["Quotes"] = getTranslatedString("Quotes", "Quotes");
     $module["PurchaseOrder"] = getTranslatedString("PurchaseOrder", "PurchaseOrder");
     $module["SalesOrder"] = getTranslatedString("SalesOrder", "SalesOrder");
     asort($module);
     $viewer->assign("avail_module", $module);
     $viewer->assign("orig_module_name", $this->getModuleName());
     $viewer->assign("availCurrency", getAllCurrencies());
     $viewer->assign("availTaxes", getAllTaxes("available"));
 }
/** This function returns a HTML output of associated vtiger_products for a given entity (Quotes,Invoice,Sales order or Purchase order)
 * Param $module - module name
 * Param $focus - module object
 * Return type string
 */
function getDetailAssociatedProducts($module, $focus)
{
    global $log;
    $log->debug("Entering getDetailAssociatedProducts(" . $module . "," . get_class($focus) . ") method ...");
    global $adb, $default_charset;
    global $mod_strings;
    global $theme;
    global $log;
    global $app_strings, $current_user, $current_language;
    $theme_path = "themes/" . $theme . "/";
    $image_path = $theme_path . "images/";
    //crm-now: added to select comma or dot as numberformat
    //European Format
    if ($current_language == 'en_us') {
        //US Format
        $decimal_precision = 2;
        $decimals_separator = '.';
        $thousands_separator = ',';
    } else {
        //European Format
        $decimal_precision = 2;
        $decimals_separator = ',';
        $thousands_separator = '.';
    }
    if ($module != 'PurchaseOrder') {
        $colspan = '2';
    } else {
        $colspan = '1';
    }
    //Get the taxtype of this entity
    $taxtype = getInventoryTaxType($module, $focus->id);
    $currencytype = getInventoryCurrencyInfo($module, $focus->id);
    $output = '';
    //Header Rows
    $output .= '

	<table width="100%"  border="0" align="center" cellpadding="5" cellspacing="0" class="crmTable" id="proTab">
	   <tr valign="top">
	   	<td colspan="' . $colspan . '" class="dvInnerHeader"><b>' . $app_strings['LBL_ITEM_DETAILS'] . '</b></td>
		<td class="dvInnerHeader" align="center" colspan="2"><b>' . $app_strings['LBL_CURRENCY'] . ' : </b>' . getTranslatedCurrencyString($currencytype['currency_name']) . ' (' . $currencytype['currency_symbol'] . ')
		</td>
		<td class="dvInnerHeader" align="center" colspan="2"><b>' . $app_strings['LBL_TAX_MODE'] . ' : </b>' . $app_strings[$taxtype] . '
		</td>
	   </tr>
	   <tr valign="top">
		<td width=40% class="lvtCol"><font color="red">*</font>
			<b>' . $app_strings['LBL_ITEM_NAME'] . '</b>
		</td>';
    //Add Quantity in Stock column for SO, Quotes and Invoice
    if ($module == 'Quotes' || $module == 'SalesOrder' || $module == 'Invoice') {
        $output .= '<td width=10% class="lvtCol"><b>' . $app_strings['LBL_QTY_IN_STOCK'] . '</b></td>';
    }
    $output .= '
	
		<td width=10% class="lvtCol"><b>' . $app_strings['LBL_QTY'] . '</b></td>
		<td width=10% class="lvtCol" align="right"><b>' . $app_strings['LBL_LIST_PRICE'] . '</b></td>
		<td width=12% nowrap class="lvtCol" align="right"><b>' . $app_strings['LBL_TOTAL'] . '</b></td>
		<td width=13% valign="top" class="lvtCol" align="right"><b>' . $app_strings['LBL_NET_PRICE'] . '</b></td>
	   </tr>
	   	';
    // DG 15 Aug 2006
    // Add "ORDER BY sequence_no" to retain add order on all inventoryproductrel items
    if ($module == 'Quotes' || $module == 'PurchaseOrder' || $module == 'SalesOrder' || $module == 'Invoice') {
        $query = "select case when vtiger_products.productid != '' then vtiger_products.productname else vtiger_service.servicename end as productname," . " case when vtiger_products.productid != '' then 'Products' else 'Services' end as entitytype," . " case when vtiger_products.productid != '' then vtiger_products.unit_price else vtiger_service.unit_price end as unit_price," . " case when vtiger_products.productid != '' then vtiger_products.productcode else 'NA' end as productcode," . " case when vtiger_products.productid != '' then vtiger_products.qtyinstock else 'NA' end as qtyinstock, vtiger_inventoryproductrel.* " . " from vtiger_inventoryproductrel" . " left join vtiger_products on vtiger_products.productid=vtiger_inventoryproductrel.productid " . " left join vtiger_service on vtiger_service.serviceid=vtiger_inventoryproductrel.productid " . " where id=? ORDER BY sequence_no";
    }
    $result = $adb->pquery($query, array($focus->id));
    $num_rows = $adb->num_rows($result);
    $netTotal = '0.00';
    for ($i = 1; $i <= $num_rows; $i++) {
        $sub_prod_query = $adb->pquery("SELECT productid from vtiger_inventorysubproductrel WHERE id=? AND sequence_no=?", array($focus->id, $i));
        $subprodname_str = '';
        if ($adb->num_rows($sub_prod_query) > 0) {
            for ($j = 0; $j < $adb->num_rows($sub_prod_query); $j++) {
                $sprod_id = $adb->query_result($sub_prod_query, $j, 'productid');
                $sprod_name = getProductName($sprod_id);
                $str_sep = "";
                if ($j > 0) {
                    $str_sep = ":";
                }
                $subprodname_str .= $str_sep . " - " . $sprod_name;
            }
        }
        $subprodname_str = str_replace(":", "<br>", $subprodname_str);
        $productid = $adb->query_result($result, $i - 1, 'productid');
        $entitytype = $adb->query_result($result, $i - 1, 'entitytype');
        $productname = $adb->query_result($result, $i - 1, 'productname');
        //crm-now added to display product code and description
        $productcode = $adb->query_result($result, $i - 1, 'productcode');
        //html to utf8 conversion (necessary because stored at inventoryproductrel table)
        $productdescription = nl2br($adb->query_result($result, $i - 1, 'description'));
        $productdescription = html_entity_decode($productdescription, ENT_QUOTES, $default_charset);
        $comment = nl2br(from_html($adb->query_result($result, $i - 1, 'comment')));
        if ($subprodname_str != '') {
            $productname .= "<br/><span style='color:#C0C0C0;font-style:italic;'>" . $subprodname_str . "</span>";
        }
        //$comment=$adb->query_result($result,$i-1,'comment');
        $qtyinstock = $adb->query_result($result, $i - 1, 'qtyinstock');
        $qty = $adb->query_result($result, $i - 1, 'quantity');
        $unitprice = $adb->query_result($result, $i - 1, 'unit_price');
        $listprice = $adb->query_result($result, $i - 1, 'listprice');
        $listpriceformated = number_format($listprice, $decimal_precision, $decimals_separator, $thousands_separator);
        $total = $qty * $listprice;
        $totalformated = number_format($total, $decimal_precision, $decimals_separator, $thousands_separator);
        //Product wise Discount calculation - starts
        $discount_percent = $adb->query_result($result, $i - 1, 'discount_percent');
        $discount_amount = $adb->query_result($result, $i - 1, 'discount_amount');
        $totalAfterDiscount = $total;
        $totalAfterDiscountformated = number_format($total, $decimal_precision, $decimals_separator, $thousands_separator);
        $productDiscount = '0.00';
        $productDiscountformated = number_format($productDiscount, $decimal_precision, $decimals_separator, $thousands_separator);
        if ($discount_percent != 'NULL' && $discount_percent != '') {
            $productDiscount = $total * $discount_percent / 100;
            $productDiscountformated = number_format($productDiscount, $decimal_precision, $decimals_separator, $thousands_separator);
            $totalAfterDiscount = $total - $productDiscount;
            $totalAfterDiscountformated = number_format($totalAfterDiscount, $decimal_precision, $decimals_separator, $thousands_separator);
            //if discount is percent then show the percentage
            $discount_info_message = "{$discount_percent} % " . $app_strings['of_string'] . " {$total} = {$productDiscountformated}";
        } elseif ($discount_amount != 'NULL' && $discount_amount != '') {
            $productDiscount = $discount_amount;
            $productDiscountformated = number_format($productDiscount, $decimal_precision, $decimals_separator, $thousands_separator);
            $totalAfterDiscount = $total - $productDiscount;
            $totalAfterDiscountformated = number_format($totalAfterDiscount, $decimal_precision, $decimals_separator, $thousands_separator);
            $discount_info_message = $app_strings['LBL_DIRECT_AMOUNT_DISCOUNT'] . " = {$productDiscountformated}";
        } else {
            $discount_info_message = $app_strings['LBL_NO_DISCOUNT_FOR_THIS_LINE_ITEM'];
        }
        //Product wise Discount calculation - ends
        $netprice = $totalAfterDiscount;
        //Calculate the individual tax if taxtype is individual
        if ($taxtype == 'individual') {
            $taxtotal = '0.00';
            $tax_info_message = $app_strings['LBL_TOTAL_AFTER_DISCOUNT'] . " = {$totalAfterDiscountformated} \\n";
            $tax_details = getTaxDetailsForProduct($productid, 'all');
            for ($tax_count = 0; $tax_count < count($tax_details); $tax_count++) {
                $tax_name = $tax_details[$tax_count]['taxname'];
                $tax_label = $tax_details[$tax_count]['taxlabel'];
                $tax_value = getInventoryProductTaxValue($focus->id, $productid, $tax_name);
                $individual_taxamount = $totalAfterDiscount * $tax_value / 100;
                $individual_taxamountformated = number_format(round($individual_taxamount, 2), $decimal_precision, $decimals_separator, $thousands_separator);
                $taxtotal = $taxtotal + $individual_taxamount;
                $taxtotalformated = number_format(round($taxtotal, 2), $decimal_precision, $decimals_separator, $thousands_separator);
                $tax_info_message .= "{$tax_label} : {$tax_value} % = {$individual_taxamountformated} \\n";
            }
            $tax_info_message .= "\\n " . $app_strings['LBL_TOTAL_TAX_AMOUNT'] . " = {$taxtotalformated}";
            $netprice = $netprice + $taxtotal;
        }
        $sc_image_tag = '';
        if ($entitytype == 'Services') {
            $sc_image_tag = '<a href="index.php?module=ServiceContracts&action=EditView&service_id=' . $productid . '&return_module=' . $module . '&return_id=' . $focus->id . '">' . '<img border="0" src="' . vtiger_imageurl('handshake.gif', $theme) . '" title="' . getTranslatedString('Add Service Contract', $module) . '" style="cursor: pointer;" align="absmiddle" />' . '</a>';
        }
        //For Product Name
        $output .= '
			   <tr valign="top">
				<td class="crmTableRow small lineOnTop">
					<font color="gray">' . $productcode . '</font>
					<br><font color="black">' . $productname . '</font>
					<br><font color="gray">' . $productdescription . '</font>
					<br><font color="gray">' . $comment . '</font>
				</td>';
        //Upto this added to display the Product name and comment
        if ($module != 'PurchaseOrder') {
            $output .= '<td class="crmTableRow small lineOnTop">' . $qtyinstock . '</td>';
        }
        $output .= '<td class="crmTableRow small lineOnTop">' . $qty . '</td>';
        $output .= '
			<td class="crmTableRow small lineOnTop" align="right">
				<table width="100%" border="0" cellpadding="5" cellspacing="0">
				   <tr>
				   	<td align="right">' . $listpriceformated . '</td>
				   </tr>
				   <tr>
					   <td align="right">(-)&nbsp;<b><a href="javascript:;" onclick="alert(\'' . $discount_info_message . '\'); ">' . $app_strings['LBL_DISCOUNT'] . ' : </a></b></td>
				   </tr>
				   <tr>
				   	<td align="right" nowrap>' . $app_strings['LBL_TOTAL_AFTER_DISCOUNT'] . ' : </td>
				   </tr>';
        if ($taxtype == 'individual') {
            $output .= '
				   <tr>
					   <td align="right" nowrap>(+)&nbsp;<b><a href="javascript:;" onclick="alert(\'' . $tax_info_message . '\');">' . $app_strings['LBL_TAX'] . ' : </a></b></td>
				   </tr>';
        }
        $output .= '
				</table>
			</td>';
        $output .= '
			<td class="crmTableRow small lineOnTop" align="right">
				<table width="100%" border="0" cellpadding="5" cellspacing="0">
				   <tr><td align="right">' . $totalformated . '</td></tr>
				   <tr><td align="right">' . $productDiscountformated . '</td></tr>
				   <tr><td align="right" nowrap>' . $totalAfterDiscountformated . '</td></tr>';
        if ($taxtype == 'individual') {
            $output .= '<tr><td align="right" nowrap>' . $taxtotalformated . '</td></tr>';
        }
        $output .= '		   
				</table>
			</td>';
        $output .= '<td class="crmTableRow small lineOnTop" valign="bottom" align="right">' . number_format(round($netprice, 2), $decimal_precision, $decimals_separator, $thousands_separator) . '</td>';
        $output .= '</tr>';
        $netTotal = $netTotal + $netprice;
    }
    $output .= '</table>';
    //$netTotal should be equal to $focus->column_fields['hdnSubTotal']
    $netTotal = $focus->column_fields['hdnSubTotal'];
    $netTotalformated = number_format($netTotal, $decimal_precision, $decimals_separator, $thousands_separator);
    //Display the total, adjustment, S&H details
    $output .= '<table width="100%" border="0" cellspacing="0" cellpadding="5" class="crmTable">';
    $output .= '<tr>';
    $output .= '<td width="88%" class="crmTableRow small" align="right"><b>' . $app_strings['LBL_NET_TOTAL'] . '</td>';
    $output .= '<td width="12%" class="crmTableRow small" align="right"><b>' . $netTotalformated . '</b></td>';
    $output .= '</tr>';
    //Decide discount
    $finalDiscount = '0.00';
    $final_discount_info = '0';
    //if($focus->column_fields['hdnDiscountPercent'] != '') - previously (before changing to prepared statement) the selected option (either percent or amount) will have value and the other remains empty. So we can find the non selected item by empty check. But now with prepared statement, the non selected option stored as 0
    if ($focus->column_fields['hdnDiscountPercent'] != '0') {
        $finalDiscount = $netTotal * $focus->column_fields['hdnDiscountPercent'] / 100;
        $finalDiscountformated = number_format($finalDiscount, $decimal_precision, $decimals_separator, $thousands_separator);
        $final_discount_info = $focus->column_fields['hdnDiscountPercent'] . " % " . $app_strings['of_string'] . " {$netTotalformated} = {$finalDiscountformated}";
    } elseif ($focus->column_fields['hdnDiscountAmount'] != '0') {
        $finalDiscount = $focus->column_fields['hdnDiscountAmount'];
        $finalDiscountformated = number_format($finalDiscount, $decimal_precision, $decimals_separator, $thousands_separator);
        $final_discount_info = $finalDiscount;
    }
    //Alert the Final Discount amount even it is zero
    $final_discount_info = $app_strings['LBL_FINAL_DISCOUNT_AMOUNT'] . " = {$final_discount_info}";
    $final_discount_info = 'onclick="alert(\'' . $final_discount_info . '\');"';
    $output .= '<tr>';
    $output .= '<td align="right" class="crmTableRow small lineOnTop">(-)&nbsp;<b><a href="javascript:;" ' . $final_discount_info . '>' . $app_strings['LBL_DISCOUNT'] . '</a></b></td>';
    $output .= '<td align="right" class="crmTableRow small lineOnTop">' . $finalDiscountformated . '</td>';
    $output .= '</tr>';
    if ($taxtype == 'group') {
        $taxtotal = '0.00';
        $final_totalAfterDiscount = $netTotal - $finalDiscount;
        $final_totalAfterDiscountformated = number_format($final_totalAfterDiscount, $decimal_precision, $decimals_separator, $thousands_separator);
        $tax_info_message = $app_strings['LBL_TOTAL_AFTER_DISCOUNT'] . " = {$final_totalAfterDiscountformated} \\n";
        //First we should get all available taxes and then retrieve the corresponding tax values
        $tax_details = getAllTaxes('available', '', 'edit', $focus->id);
        //if taxtype is group then the tax should be same for all products in vtiger_inventoryproductrel table
        for ($tax_count = 0; $tax_count < count($tax_details); $tax_count++) {
            $tax_name = $tax_details[$tax_count]['taxname'];
            $tax_label = $tax_details[$tax_count]['taxlabel'];
            $tax_value = $adb->query_result($result, 0, $tax_name);
            if ($tax_value == '' || $tax_value == 'NULL') {
                $tax_value = '0.00';
            }
            $taxamount = ($netTotal - $finalDiscount) * $tax_value / 100;
            $taxamountformated = number_format($taxamount, $decimal_precision, $decimals_separator, $thousands_separator);
            $taxtotal = $taxtotal + $taxamount;
            $taxtotalformated = number_format($taxtotal, $decimal_precision, $decimals_separator, $thousands_separator);
            $tax_info_message .= "{$tax_label} : {$tax_value} % = {$taxamountformated} \\n";
        }
        $tax_info_message .= "\\n " . $app_strings['LBL_TOTAL_TAX_AMOUNT'] . " = {$taxtotalformated}";
        $output .= '<tr>';
        $output .= '<td align="right" class="crmTableRow small">(+)&nbsp;<b><a href="javascript:;" onclick="alert(\'' . $tax_info_message . '\');">' . $app_strings['LBL_TAX'] . '</a></b></td>';
        $output .= '<td align="right" class="crmTableRow small">' . $taxtotalformated . '</td>';
        $output .= '</tr>';
    }
    $shAmount = $focus->column_fields['hdnS_H_Amount'] != '' ? $focus->column_fields['hdnS_H_Amount'] : '0.00';
    $shAmountformated = number_format($shAmount, $decimal_precision, $decimals_separator, $thousands_separator);
    $output .= '<tr>';
    $output .= '<td align="right" class="crmTableRow small">(+)&nbsp;<b>' . $app_strings['LBL_SHIPPING_AND_HANDLING_CHARGES'] . '</b></td>';
    $output .= '<td align="right" class="crmTableRow small">' . $shAmountformated . '</td>';
    $output .= '</tr>';
    //calculate S&H tax
    $shtaxtotal = '0.00';
    //First we should get all available taxes and then retrieve the corresponding tax values
    $shtax_details = getAllTaxes('available', 'sh', 'edit', $focus->id);
    //if taxtype is group then the tax should be same for all products in vtiger_inventoryproductrel table
    $shtax_info_message = $app_strings['LBL_SHIPPING_AND_HANDLING_CHARGE'] . " = {$shAmountformated} \\n";
    for ($shtax_count = 0; $shtax_count < count($shtax_details); $shtax_count++) {
        $shtax_name = $shtax_details[$shtax_count]['taxname'];
        $shtax_label = $shtax_details[$shtax_count]['taxlabel'];
        $shtax_percent = getInventorySHTaxPercent($focus->id, $shtax_name);
        $shtaxamount = $shAmount * $shtax_percent / 100;
        $shtaxamountformated = number_format($shtaxamount, $decimal_precision, $decimals_separator, $thousands_separator);
        $shtaxtotal = $shtaxtotal + $shtaxamount;
        $shtaxtotalformated = number_format($shtaxtotal, $decimal_precision, $decimals_separator, $thousands_separator);
        $shtax_info_message .= "{$shtax_label} : {$shtax_percent} % = {$shtaxamountformated} \\n";
    }
    $shtax_info_message .= "\\n " . $app_strings['LBL_TOTAL_TAX_AMOUNT'] . " = {$shtaxtotalformated}";
    $output .= '<tr>';
    $output .= '<td align="right" class="crmTableRow small">(+)&nbsp;<b><a href="javascript:;" onclick="alert(\'' . $shtax_info_message . '\')">' . $app_strings['LBL_TAX_FOR_SHIPPING_AND_HANDLING'] . '</a></b></td>';
    $output .= '<td align="right" class="crmTableRow small">' . $shtaxtotalformated . '</td>';
    $output .= '</tr>';
    $adjustment = $focus->column_fields['txtAdjustment'] != '' ? $focus->column_fields['txtAdjustment'] : '0.00';
    $adjustmentformated = number_format($adjustment, $decimal_precision, $decimals_separator, $thousands_separator);
    $output .= '<tr>';
    $output .= '<td align="right" class="crmTableRow small">&nbsp;<b>' . $app_strings['LBL_ADJUSTMENT'] . '</b></td>';
    $output .= '<td align="right" class="crmTableRow small">' . $adjustmentformated . '</td>';
    $output .= '</tr>';
    $grandTotal = $focus->column_fields['hdnGrandTotal'] != '' ? $focus->column_fields['hdnGrandTotal'] : '0.00';
    $grandTotalformated = number_format($grandTotal, $decimal_precision, $decimals_separator, $thousands_separator);
    $output .= '<tr>';
    $output .= '<td align="right" class="crmTableRow small lineOnTop"><b>' . $app_strings['LBL_GRAND_TOTAL'] . '</b></td>';
    $output .= '<td align="right" class="crmTableRow small lineOnTop">' . $grandTotalformated . '</td>';
    $output .= '</tr>';
    $output .= '</table>';
    $log->debug("Exiting getDetailAssociatedProducts method ...");
    return $output;
}
Example #9
0
    } else {
        changeDeleted($_REQUEST['taxname'], 0);
    }
    $getlist = true;
} elseif (($_REQUEST['sh_disable'] == 'true' || $_REQUEST['sh_enable'] == 'true') && $_REQUEST['sh_taxname'] != '') {
    if ($_REQUEST['sh_disable'] == 'true') {
        changeDeleted($_REQUEST['sh_taxname'], 1, 'sh');
    } else {
        changeDeleted($_REQUEST['sh_taxname'], 0, 'sh');
    }
    $getlist = true;
}
//after done save or enable/disable or added new tax the list will be retrieved again from db
if ($getlist) {
    $tax_details = getAllTaxes();
    $sh_tax_details = getAllTaxes('all', 'sh');
}
$smarty->assign("TAX_COUNT", count($tax_details));
$smarty->assign("SH_TAX_COUNT", count($sh_tax_details));
if (count($tax_details) == 0) {
    $smarty->assign("TAX_COUNT", 0);
}
if (count($sh_tax_details) == 0) {
    $smarty->assign("SH_TAX_COUNT", 0);
}
$smarty->assign("TAX_VALUES", $tax_details);
$smarty->assign("SH_TAX_VALUES", $sh_tax_details);
$smarty->assign("MOD", return_module_language($current_language, 'Settings'));
$smarty->assign("THEME", $theme);
$smarty->assign("IMAGE_PATH", $image_path);
$smarty->assign("APP", $app_strings);
Example #10
0
    $mod_seq_no = $adb->query_result($mod_seq_string, 0, 'cur_id');
    if ($adb->num_rows($mod_seq_string) == 0 || $focus->checkModuleSeqNumber($focus->table_name, $mod_seq_field['column'], $mod_seq_prefix . $mod_seq_no)) {
        echo '<br><font color="#FF0000"><b>' . getTranslatedString('LBL_DUPLICATE') . ' ' . getTranslatedString($mod_seq_field['label']) . ' - ' . getTranslatedString('LBL_CLICK') . ' <a href="index.php?module=Settings&action=CustomModEntityNo&parenttab=Settings&selmodule=' . $currentModule . '">' . getTranslatedString('LBL_HERE') . '</a> ' . getTranslatedString('LBL_TO_CONFIGURE') . ' ' . getTranslatedString($mod_seq_field['label']) . '</b></font>';
    } else {
        $smarty->assign("MOD_SEQ_ID", $autostr);
    }
} else {
    $smarty->assign("MOD_SEQ_ID", $focus->column_fields[$mod_seq_field['name']]);
}
//if create PO, get all available product taxes and shipping & Handling taxes
if ($focus->mode != 'edit') {
    $tax_details = getAllTaxes('available');
    $sh_tax_details = getAllTaxes('available', 'sh');
} else {
    $tax_details = getAllTaxes('available', '', $focus->mode, $focus->id);
    $sh_tax_details = getAllTaxes('available', 'sh', 'edit', $focus->id);
}
$smarty->assign('GROUP_TAXES', $tax_details);
$smarty->assign('SH_TAXES', $sh_tax_details);
$smarty->assign("CURRENCIES_LIST", getAllCurrencies());
if ($focus->mode == 'edit') {
    $inventory_cur_info = getInventoryCurrencyInfo('PurchaseOrder', $focus->id);
    $smarty->assign("INV_CURRENCY_ID", $inventory_cur_info['currency_id']);
} else {
    $smarty->assign("INV_CURRENCY_ID", $currencyid);
}
$smarty->assign('CREATEMODE', vtlib_purify($_REQUEST['createmode']));
// Gather the help information associated with fields
$smarty->assign('FIELDHELPINFO', vtlib_getFieldHelpInfo($currentModule));
$picklistDependencyDatasource = Vtiger_DependencyPicklist::getPicklistDependencyDatasource($currentModule);
$smarty->assign("PICKIST_DEPENDENCY_DATASOURCE", Zend_Json::encode($picklistDependencyDatasource));
 public function save()
 {
     ${"GLOBALS"}["ducixeik"] = "additionalProductFields";
     ${${"GLOBALS"}["wtrcwdueuts"]} = PearDatabase::getInstance();
     ${${"GLOBALS"}["ducixeik"]} = $this->getAdditionalProductFields();
     ${"GLOBALS"}["molcrpc"] = "manualUpdateFields";
     ${"GLOBALS"}["gbmhcqh"] = "tmp";
     ${"GLOBALS"}["ewjsruuy"] = "fieldName";
     ${${"GLOBALS"}["molcrpc"]} = array();
     foreach (${${"GLOBALS"}["vptmrj"]} as ${${"GLOBALS"}["ewjsruuy"]} => ${${"GLOBALS"}["gbmhcqh"]}) {
         if (${${"GLOBALS"}["ykppheofobwk"]}["implemented"] == false) {
             $jpmxewcq = "relData";
             ${"GLOBALS"}["fkfnvsuaox"] = "manualUpdateFields";
             ${${"GLOBALS"}["fkfnvsuaox"]}[] = ${${"GLOBALS"}["thpgoyrlu"]};
             ${$jpmxewcq} = $this->_getProductRelData();
         }
     }
     require_once "modules/Emails/mail.php";
     if (!empty($this->_id) && $this->_changed == true) {
         $this->_changedProducts = $this->_changed;
         if ($this->_listitems === null) {
             $this->_loadProducts();
         }
     }
     parent::save();
     $this->prepareTransfer();
     if (!empty($this->_currencyID)) {
         ${${"GLOBALS"}["xkutivbm"]} = $this->_currencyID;
     } else {
         $ogqhrcro = "currency_id";
         ${$ogqhrcro} = false;
     }
     $this->clearData();
     if ($this->_changedProducts === true) {
         ${"GLOBALS"}["tgkrfb"] = "shipping_handling_charge";
         ${"GLOBALS"}["negltbro"] = "field";
         ${${"GLOBALS"}["amsupsflnmf"]} = $this->get("hdnTaxType");
         ${"GLOBALS"}["hxnewftfdqn"] = "i";
         ${"GLOBALS"}["etqhqirsnh"] = "taxtype";
         $agoclef = "adjustment";
         ${$agoclef} = 0;
         ${${"GLOBALS"}["tgkrfb"]} = 0;
         $qwpblm = "i";
         ${"GLOBALS"}["krxwtxw"] = "fields";
         ${${"GLOBALS"}["whqnrjvsw"]} = getAllTaxes();
         $nxxrnbh = "intObject";
         $mdwcbjhvim = "availTaxes";
         $vaqwwrr = "value";
         $_REQUEST["totalProductCount"] = count($this->_listitems);
         $_REQUEST["taxtype"] = ${${"GLOBALS"}["etqhqirsnh"]};
         $_REQUEST["subtotal"] = 0;
         ${${"GLOBALS"}["pponynktout"]} = $this->getProductFields();
         foreach (${${"GLOBALS"}["krxwtxw"]} as ${${"GLOBALS"}["negltbro"]} => ${$vaqwwrr}) {
             $_REQUEST[${${"GLOBALS"}["mlsoidilfq"]}] = ${${"GLOBALS"}["cqlhrtj"]};
         }
         for (${${"GLOBALS"}["hxnewftfdqn"]} = 1; ${${"GLOBALS"}["jsntgvnqkf"]} <= count($this->_listitems); ${${"GLOBALS"}["jsntgvnqkf"]}++) {
             ${"GLOBALS"}["zepdlqparq"] = "i";
             $_REQUEST["subtotal"] += ${${"GLOBALS"}["pponynktout"]}["productTotal" . ${${"GLOBALS"}["zepdlqparq"]}];
         }
         $klivirms = "intObject";
         $cnavotvg = "globalTaxValue";
         ${"GLOBALS"}["ouawiowlgku"] = "shipTaxValue";
         $_REQUEST["discount_percentage_final"] = $this->get("hdnDiscountPercent");
         $_REQUEST["discount_percentage_final"] = floatval($_REQUEST["discount_percentage_final"]);
         $_REQUEST["discount_amount_final"] = $this->get("hdnDiscountAmount");
         $_REQUEST["discount_amount_final"] = floatval($_REQUEST["discount_amount_final"]);
         $_REQUEST["discount_type_final"] = !empty($_REQUEST["discount_percentage_final"]) ? "percentage" : "amount";
         $_REQUEST["total"] = $_REQUEST["subtotal"];
         if ($_REQUEST["discount_type_final"] == "amount") {
             $_REQUEST["total"] -= $_REQUEST["discount_amount_final"];
         } elseif ($_REQUEST["discount_type_final"] == "percentage") {
             $_REQUEST["total"] -= $_REQUEST["total"] * ($_REQUEST["discount_percentage_final"] / 100);
         }
         ${$cnavotvg} = 0;
         if (${${"GLOBALS"}["amsupsflnmf"]} == "group") {
             ${"GLOBALS"}["yirabwmnwgyp"] = "globalTaxValue";
             $oplkjyxi = "availTaxes";
             foreach (${$oplkjyxi} as ${${"GLOBALS"}["wfuwxbmiwytq"]}) {
                 $psuluqnb = "request_tax_name";
                 $enefpgduf = "tax";
                 ${"GLOBALS"}["wxlvsgkcw"] = "request_tax_name";
                 ${${"GLOBALS"}["hvjpdk"]} = ${$enefpgduf}["taxname"];
                 ${${"GLOBALS"}["wxlvsgkcw"]} = ${${"GLOBALS"}["hvjpdk"]} . "_group_percentage";
                 $lifliipv = "request_tax_name";
                 $_REQUEST[${${"GLOBALS"}["hwivgkl"]}] = isset($this->_groupTax[${${"GLOBALS"}["hwivgkl"]}]) ? $this->_groupTax[${$psuluqnb}] : 0;
                 $bltbxkcxbjyp = "tmpTaxValue";
                 ${${"GLOBALS"}["fvbuscvwjf"]} = $_REQUEST["total"] * ($_REQUEST[${$lifliipv}] / 100);
                 ${${"GLOBALS"}["zjswudci"]} += ${$bltbxkcxbjyp};
             }
             $_REQUEST["total"] += ${${"GLOBALS"}["yirabwmnwgyp"]};
         }
         $_REQUEST["shipping_handling_charge"] = $this->_shippingCost;
         ${${"GLOBALS"}["cxnjuagap"]} = 0;
         $bbluqvmmcrl = "tax";
         foreach (${$mdwcbjhvim} as ${$bbluqvmmcrl}) {
             $rbwcrso = "request_tax_name";
             ${"GLOBALS"}["woxvppdlct"] = "tmpTaxValue";
             $xeqhidsvg = "shipTaxValue";
             ${"GLOBALS"}["rihoezbjibn"] = "tax_name";
             ${${"GLOBALS"}["rihoezbjibn"]} = ${${"GLOBALS"}["wfuwxbmiwytq"]}["taxname"];
             ${$rbwcrso} = ${${"GLOBALS"}["hvjpdk"]} . "_sh_percent";
             $uaabpfjmwc = "request_tax_name";
             $_REQUEST["sh" . ${${"GLOBALS"}["hwivgkl"]}] = isset($this->_shipTaxes[${${"GLOBALS"}["hwivgkl"]}]) ? $this->_shipTaxes[${${"GLOBALS"}["hwivgkl"]}] : 0;
             ${${"GLOBALS"}["fvbuscvwjf"]} = $_REQUEST["shipping_handling_charge"] * ($_REQUEST["sh" . ${$uaabpfjmwc}] / 100);
             ${$xeqhidsvg} += ${${"GLOBALS"}["woxvppdlct"]};
         }
         $_REQUEST["total"] += ${${"GLOBALS"}["ouawiowlgku"]} + $_REQUEST["shipping_handling_charge"];
         $_REQUEST["adjustment"] = floatval($this->get("txtAdjustment"));
         $_REQUEST["total"] += $_REQUEST["adjustment"];
         ${$nxxrnbh} = $this->getInternalObject();
         $intObject->mode = "edit";
         $intObject->isLineItemUpdate = true;
         @saveInventoryProductDetails(${$klivirms}, $this->getModuleName());
         for (${${"GLOBALS"}["jsntgvnqkf"]} = 1; ${${"GLOBALS"}["jsntgvnqkf"]} <= count($this->_listitems); ${$qwpblm}++) {
             ${"GLOBALS"}["xzgznik"] = "values";
             ${${"GLOBALS"}["xzgznik"]} = array();
             $dqnotemwlbq = "params";
             ${$dqnotemwlbq} = array();
             foreach (${${"GLOBALS"}["ogvkpmc"]} as ${${"GLOBALS"}["nctgtuliixp"]}) {
                 ${"GLOBALS"}["fjordnwx"] = "values";
                 ${${"GLOBALS"}["fjordnwx"]}[] = "`" . ${${"GLOBALS"}["nctgtuliixp"]} . "` = ?";
                 ${${"GLOBALS"}["tjyzhfdvth"]}[] = $this->_listitems[${${"GLOBALS"}["jsntgvnqkf"]} - 1][${${"GLOBALS"}["nctgtuliixp"]}];
             }
             if (count(${${"GLOBALS"}["ibmlnecaubpt"]}) > 0) {
                 $nvtwyqcc = "params";
                 $wbzhsv = "i";
                 $glpeqaibe = "params";
                 ${${"GLOBALS"}["tjyzhfdvth"]}[] = $this->getId();
                 $mjhhtobppu = "sql";
                 ${$nvtwyqcc}[] = ${$wbzhsv};
                 ${${"GLOBALS"}["hdblop"]} = "UPDATE vtiger_inventoryproductrel SET " . implode(",", ${${"GLOBALS"}["ibmlnecaubpt"]}) . " WHERE id = ? AND sequence_no = ?";
                 $adb->pquery(${$mjhhtobppu}, ${$glpeqaibe});
             }
         }
     }
     if (!empty(${${"GLOBALS"}["xkutivbm"]})) {
         $wrqjvjvs = "update_query";
         ${"GLOBALS"}["ryhoienvnsn"] = "cur_sym_rate";
         $xepbzcbhw = "update_params";
         ${"GLOBALS"}["ohiigcodbwo"] = "conversion_rate";
         $pcrolhc = "currency_id";
         ${"GLOBALS"}["udferc"] = "conversion_rate";
         $fkgwwhoop = "intObject";
         ${"GLOBALS"}["nglnmk"] = "update_query";
         ${"GLOBALS"}["nvezfxsotm"] = "currency_id";
         if (strpos(${${"GLOBALS"}["nvezfxsotm"]}, "x") !== false) {
             ${"GLOBALS"}["twtpeleg"] = "parts";
             ${${"GLOBALS"}["bbeqpsqwehf"]} = explode("x", ${${"GLOBALS"}["xkutivbm"]});
             ${${"GLOBALS"}["xkutivbm"]} = ${${"GLOBALS"}["twtpeleg"]}[1];
         } else {
             ${"GLOBALS"}["kuscdvfpt"] = "currency_id";
             ${${"GLOBALS"}["kuscdvfpt"]} = ${${"GLOBALS"}["xkutivbm"]};
         }
         $ksoimju = "cur_sym_rate";
         ${$ksoimju} = getCurrencySymbolandCRate(${${"GLOBALS"}["xkutivbm"]});
         ${${"GLOBALS"}["ohiigcodbwo"]} = ${${"GLOBALS"}["ryhoienvnsn"]}["rate"];
         ${"GLOBALS"}["epcnplti"] = "update_params";
         ${$fkgwwhoop} = $this->getInternalObject();
         ${$wrqjvjvs} = "update " . $intObject->table_name . " set currency_id = ?, conversion_rate = ? WHERE " . $intObject->table_index . " = ?";
         ${$xepbzcbhw} = array(${$pcrolhc}, ${${"GLOBALS"}["udferc"]}, $this->_id);
         $adb->pquery(${${"GLOBALS"}["nglnmk"]}, ${${"GLOBALS"}["epcnplti"]});
     }
     if (file_exists(vglobal("root_directory") . DIRECTORY_SEPARATOR . "modules" . DIRECTORY_SEPARATOR . "Invoice" . DIRECTORY_SEPARATOR . "InvoiceHandler.php")) {
         ${"GLOBALS"}["hebripdxg"] = "entityData";
         ${"GLOBALS"}["llplslhg"] = "adb";
         require_once "modules/Invoice/InvoiceHandler.php";
         require_once "include/events/VTEventHandler.inc";
         require_once "data/VTEntityDelta.php";
         ${${"GLOBALS"}["hebripdxg"]} = \VTEntityData::fromEntityId(${${"GLOBALS"}["llplslhg"]}, $this->getId(), $this->getModuleName());
         $omsgxnkjeni = "handler";
         ${$omsgxnkjeni} = new \InvoiceHandler();
         $handler->handleEvent("vtiger.entity.aftersave", ${${"GLOBALS"}["xxguhqgid"]});
     }
     $this->afterTransfer();
     $this->_data = false;
 }
Example #12
0
function createpdffile($idnumber, $purpose = '', $path = '', $current_id = '')
{
    require_once 'include/tcpdf/tcpdf.php';
    require_once 'include/tcpdf/config/tcpdf_config.php';
    require_once 'modules/SalesOrder/SalesOrder.php';
    require_once 'include/database/PearDatabase.php';
    require_once 'include/utils/InventoryUtils.php';
    require_once 'include/utils/PDFutils.php';
    require_once 'test/contact/bank.php';
    global $FOOTER_PAGE, $default_font, $font_size_footer, $NUM_FACTURE_NAME, $pdf_strings, $SalesOrder_no, $footer_margin;
    global $org_name, $org_address, $org_city, $org_code, $org_country, $org_irs, $org_taxid, $org_phone, $org_fax, $org_website;
    global $VAR40_NAME, $VAR3_NAME, $VAR4_NAME, $ORG_POSITION, $VAR_PAGE, $VAR_OF;
    //bank information - content
    global $bank_name, $bank_street, $bank_city, $bank_zip, $bank_country, $bank_account, $bank_routing, $bank_iban, $bank_swift;
    //bank information - labels from language files
    global $ACCOUNT_NUMBER, $ROUTING_NUMBER, $SWIFT_NUMBER, $IBAN_NUMBER;
    global $columns, $logoradio, $logo_name, $footerradio, $pageradio;
    global $adb, $app_strings, $focus, $current_user;
    $module = 'SalesOrder';
    //get bank information
    $bank_name = $bank_array['bank_name'];
    $bank_street = $bank_array['bank_street'];
    $bank_city = $bank_array['bank_city'];
    $bank_zip = $bank_array['bank_zip'];
    $bank_country = $bank_array['bank_country'];
    $bank_account = $bank_array['bank_account'];
    $bank_routing = $bank_array['bank_routing'];
    $bank_iban = $bank_array['bank_iban'];
    $bank_swift = $bank_array['bank_swift'];
    //get tax information
    $org_taxid = $tax_array['org_taxid'];
    $org_irs = $tax_array['org_irs'];
    //get the stored configuration values
    $pdf_config_details = getAllPDFDetails('SalesOrder');
    //set font
    $default_font = getTCPDFFontsname($pdf_config_details[fontid]);
    if ($default_font == '') {
        $default_font = 'freesans';
    }
    $font_size_header = $pdf_config_details[fontsizeheader];
    $font_size_address = $pdf_config_details[fontsizeaddress];
    $font_size_body = $pdf_config_details[fontsizebody];
    $font_size_footer = $pdf_config_details[fontsizefooter];
    //select comma or dot as number format
    //European Format
    $decimal_precision = 2;
    $decimals_separator = ',';
    $thousands_separator = '.';
    //US Format
    //$decimal_precision = 2;
    //$decimals_separator = '.';
    //$thousands_separator = ',';
    //get users data
    //select language file
    if (file_exists("modules/SalesOrder/language/" . $pdf_config_details[pdflang] . ".lang.pdf.php")) {
        include "modules/SalesOrder/language/" . $pdf_config_details[pdflang] . ".lang.pdf.php";
        $language = strtoupper(substr($pdf_config_details[pdflang], -2, 2));
    } else {
        include "modules/SalesOrder/language/en_us.lang.pdf.php";
        $language = "EN";
    }
    //internal number
    $id = $idnumber;
    //retreiving the salesorder info
    $focus = new SalesOrder();
    $focus->retrieve_entity_info($_REQUEST['record'], "SalesOrder");
    $account_name = decode_html(getAccountName($focus->column_fields['account_id']));
    $SalesOrder_no = $focus->column_fields['salesorder_no'];
    $sql = "select vtiger_currency_info.currency_symbol from vtiger_currency_info where vtiger_currency_info.id= " . $focus->column_fields['currency_id'];
    $currency_symbol = $adb->query_result($adb->query($sql), 0, 'currency_symbol');
    //get the SO date set
    $date_to_display_array = array(str_replace("-", ".", getDisplayDate(date("Y-m-d"))));
    $date_created = getDisplayDate($focus->column_fields['createdtime']);
    $date_array = explode(" ", $date_created);
    $date_to_display_array[1] = str_replace("-", ".", $date_array[0]);
    $date_modified = getDisplayDate($focus->column_fields['modifiedtime']);
    $date_array = explode(" ", $date_modified);
    $date_to_display_array[2] = str_replace("-", ".", $date_array[0]);
    $date_to_display = $date_to_display_array[$pdf_config_details['dateused']];
    //number of lines after headline
    $space_headline = $pdf_config_details['space_headline'];
    //display logo?
    $logoradio = $pdf_config_details['logoradio'];
    //display customer sign?
    $clientid = $pdf_config_details['clientid'];
    //display summary?
    $summaryradio = $pdf_config_details['summaryradio'];
    //display footer?
    $footerradio = $pdf_config_details['footerradio'];
    //display footer page number?
    $pageradio = $pdf_config_details['pageradio'];
    // get company information from settings
    $add_query = "select * from vtiger_organizationdetails";
    $result = $adb->query($add_query);
    $num_rows = $adb->num_rows($result);
    if ($num_rows > 0) {
        $org_name = $adb->query_result($result, 0, "organizationname");
        $org_address = $adb->query_result($result, 0, "address");
        $org_city = $adb->query_result($result, 0, "city");
        $org_state = $adb->query_result($result, 0, "state");
        $org_country = $adb->query_result($result, 0, "country");
        $org_code = $adb->query_result($result, 0, "code");
        $org_phone = $adb->query_result($result, 0, "phone");
        $org_fax = $adb->query_result($result, 0, "fax");
        $org_website = $adb->query_result($result, 0, "website");
        $logo_name = $adb->query_result($result, 0, "logoname");
    }
    // get owner information
    $recordOwnerArr = getRecordOwnerId($_REQUEST['record']);
    foreach ($recordOwnerArr as $type => $id) {
        $ownertype = $type;
        $ownerid = $id;
    }
    if ($ownertype == 'Users') {
        // get owner information for user
        $sql = "SELECT * FROM vtiger_users,vtiger_crmentity WHERE vtiger_users.id = vtiger_crmentity.smownerid AND vtiger_crmentity.crmid = '" . $_REQUEST['record'] . "'";
        $result = $adb->query($sql);
        $owner_lastname = $adb->query_result($result, 0, 'last_name');
        $owner_firstname = $adb->query_result($result, 0, 'first_name');
        $owner_id = $adb->query_result($result, 0, 'smownerid');
        $owner_phone = $adb->query_result($result, 0, 'phone_work');
        $owner_title = decode_html(trim($adb->query_result($result, 0, 'title')));
    } else {
        // get owner information for Groups
        $sql = "SELECT * FROM vtiger_groups,vtiger_crmentity WHERE vtiger_groups.groupid  = vtiger_crmentity.smownerid AND vtiger_crmentity.crmid = '" . $_REQUEST['record'] . "'";
        $result = $adb->query($sql);
        $owner_lastname = '';
        $owner_firstname = $adb->query_result($result, 0, 'groupname');
        $owner_id = $adb->query_result($result, 0, 'smownerid');
        $owner_phone = $org_phone;
        $owner_title = '';
    }
    //display owner?
    $owner = $pdf_config_details['owner'];
    //display owner phone#?
    $ownerphone = $pdf_config_details['ownerphone'];
    //to display at product description based on tax type
    $gproddetailarray = array($pdf_config_details[gprodname], $pdf_config_details[gproddes], $pdf_config_details[gprodcom]);
    $gproddetails = 0;
    foreach ($gproddetailarray as $key => $value) {
        if ($value == 'true') {
            if ($key == 0) {
                $gproddetails = $gproddetails + 1;
            } else {
                $gproddetails = $gproddetails + $key * 2;
            }
        }
    }
    $iproddetails = 0;
    $iproddetailarray = array($pdf_config_details[iprodname], $pdf_config_details[iproddes], $pdf_config_details[iprodcom]);
    foreach ($iproddetailarray as $key => $value) {
        if ($value == 'true') {
            if ($key == 0) {
                $iproddetails = $iproddetails + 1;
            } else {
                $iproddetails = $iproddetails + $key * 2;
            }
        }
    }
    // SO Requisition Nummer
    $requisition_no = $focus->column_fields['vtiger_purchaseorder'];
    // CustomerMark
    $customermark = $focus->column_fields['customerno'];
    if ($focus->column_fields['hdnTaxType'] == 'individual') {
        $product_taxes = 'true';
    } else {
        $product_taxes = 'false';
    }
    // **************** BEGIN POPULATE DATA ********************
    $account_id = $focus->column_fields[account_id];
    $so_id = $_REQUEST['record'];
    if ($focus->column_fields["quote_id"] != '') {
        $quote_name = getQuoteName($focus->column_fields["quote_id"]);
    } else {
        $quote_name = '';
    }
    $po_name = $focus->column_fields["vtiger_purchaseorder"];
    $subject = $focus->column_fields["subject"];
    $delivery_date = $focus->column_fields["duedate"];
    $delivery_date = str_replace("-", ".", getDisplayDate($delivery_date));
    $bill_street = decode_html($focus->column_fields["bill_street"]);
    $bill_city = decode_html($focus->column_fields["bill_city"]);
    $bill_state = decode_html($focus->column_fields["bill_state"]);
    $bill_code = decode_html($focus->column_fields["bill_code"]);
    $bill_country = decode_html($focus->column_fields["bill_country"]);
    //format contact name
    $contact_name = decode_html(getContactforPDF($focus->column_fields["contact_id"]));
    //get department of contact or account, contact wins
    $contact_department = '';
    //get contact department
    if (trim($focus->column_fields["contact_id"]) != '') {
        $sql = "select * from vtiger_contactdetails where contactid=" . $focus->column_fields["contact_id"];
        $result = $adb->query($sql);
        $contact_department = decode_html(trim($adb->query_result($result, 0, "department")));
        $contact_firstname = decode_html(trim($adb->query_result($result, 0, "firstname")));
        $contact_lastname = decode_html(trim($adb->query_result($result, 0, "lastname")));
        $contact_salutation = decode_html(trim($adb->query_result($result, 0, "salutation")));
    }
    //get account department
    if ($contact_department == '') {
        $sql = "select * from vtiger_account where accountid=" . $account_id;
        $result = $adb->query($sql);
        $contact_department = decode_html(trim($adb->query_result($result, 0, "tickersymbol")));
    }
    $ship_street = $focus->column_fields["ship_street"];
    $ship_city = $focus->column_fields["ship_city"];
    $ship_state = $focus->column_fields["ship_state"];
    $ship_code = $focus->column_fields["ship_code"];
    $ship_country = $focus->column_fields["ship_country"];
    // condition field for last page
    $conditions = decode_html($focus->column_fields["terms_conditions"]);
    // description field for first page
    $description = decode_html($focus->column_fields["description"]);
    // ************************ BEGIN POPULATE DATA ***************************
    //get the Associated Products for this Sales Order
    $focus->id = $focus->column_fields["record_id"];
    $associated_products = getAssociatedProducts("SalesOrder", $focus);
    $num_products = count($associated_products);
    //This $final_details array will contain the final total, discount, Group Tax, S&H charge, S&H taxes and adjustment
    $final_details = $associated_products[1]['final_details'];
    //getting the Net Total
    $price_subtotal = $final_details["hdnSubTotal"];
    $price_subtotal_formated = number_format($price_subtotal, $decimal_precision, $decimals_separator, $thousands_separator);
    //Final discount amount/percentage
    $discount_amount = $final_details["discount_amount_final"];
    $discount_percent = $final_details["discount_percentage_final"];
    if ($discount_amount != "") {
        $price_discount = $discount_amount;
        $price_discount_formated = number_format($price_discount, $decimal_precision, $decimals_separator, $thousands_separator);
    } else {
        if ($discount_percent != "") {
            //This will be displayed near Discount label
            $final_price_discount_percent = "(" . number_format($discount_percent, $decimal_precision, $decimals_separator, $thousands_separator) . " %)";
            $price_discount = $discount_percent * $final_details["hdnSubTotal"] / 100;
            $price_discount_formated = number_format($price_discount, $decimal_precision, $decimals_separator, $thousands_separator);
        } else {
            $price_discount = "0.00";
        }
    }
    //Adjustment
    $price_adjustment = $final_details["adjustment"];
    $price_adjustment_formated = number_format($price_adjustment, $decimal_precision, $decimals_separator, $thousands_separator);
    //Grand Total
    $price_total = $final_details["grandTotal"];
    $price_total_formated = number_format($price_total, $decimal_precision, $decimals_separator, $thousands_separator);
    //To calculate the group tax amount
    if ($final_details['taxtype'] == 'group') {
        $group_tax_total = $final_details['tax_totalamount'];
        $price_salestax = $group_tax_total;
        $price_salestax_formated = number_format($price_salestax, $decimal_precision, $decimals_separator, $thousands_separator);
        $group_total_tax_percent = '0.00';
        $group_tax_details = $final_details['taxes'];
        for ($i = 0; $i < count($group_tax_details); $i++) {
            $group_total_tax_percent = $group_total_tax_percent + $group_tax_details[$i]['percentage'];
        }
    }
    //S&H amount
    $sh_amount = $final_details['shipping_handling_charge'];
    $price_shipping_formated = number_format($sh_amount, $decimal_precision, $decimals_separator, $thousands_separator);
    //S&H taxes
    $sh_tax_details = $final_details['sh_taxes'];
    $sh_tax_percent = '0.00';
    for ($i = 0; $i < count($sh_tax_details); $i++) {
        $sh_tax_percent = $sh_tax_percent + $sh_tax_details[$i]['percentage'];
    }
    $sh_tax_amount = $final_details['shtax_totalamount'];
    $price_shipping_tax = number_format($sh_tax_amount, $decimal_precision, $decimals_separator, $thousands_separator);
    //to calculate the individuel tax amounts included we should get all available taxes and then retrieve the corresponding tax values
    $tax_details = getAllTaxes('available');
    $numer_of_tax_types = count($tax_details);
    for ($tax_count = 0; $tax_count < count($tax_details); $tax_count++) {
        $taxtype_listings[taxname . $tax_count] = $tax_details[$tax_count]['taxname'];
        $taxtype_listings[percentage . $tax_count] = $tax_details[$tax_count]['percentage'];
        $taxtype_listings[value . $tax_count] = '0';
    }
    //This is to get all prodcut details as row basis
    for ($i = 1, $j = $i - 1; $i <= $num_products; $i++, $j++) {
        $product_code[$i] = $associated_products[$i]['hdnProductcode' . $i];
        $product_name[$i] = decode_html($associated_products[$i]['productName' . $i]);
        $prod_description[$i] = decode_html($associated_products[$i]['productDescription' . $i]);
        $qty[$i] = $associated_products[$i]['qty' . $i];
        $qty_formated[$i] = number_format($associated_products[$i]['qty' . $i], $decimal_precision, $decimals_separator, $thousands_separator);
        $comment[$i] = decode_html($associated_products[$i]['comment' . $i]);
        $unit_price[$i] = number_format($associated_products[$i]['unitPrice' . $i], $decimal_precision, $decimals_separator, $thousands_separator);
        $list_price[$i] = number_format($associated_products[$i]['listPrice' . $i], $decimal_precision, $decimals_separator, $thousands_separator);
        $list_pricet[$i] = $associated_products[$i]['listPrice' . $i];
        $discount_total[$i] = $associated_products[$i]['discountTotal' . $i];
        $discount_totalformated[$i] = number_format($associated_products[$i]['discountTotal' . $i], $decimal_precision, $decimals_separator, $thousands_separator);
        //added by crm-now
        $usageunit[$i] = $associated_products[$i]['usageunit' . $i];
        //look whether the entry already exists, if the translated string is available then the translated string other wise original string will be returned
        $usageunit[$i] = getTranslatedString($usageunit[$i], 'Products');
        $taxable_total = $qty[$i] * $list_pricet[$i] - $discount_total[$i];
        $producttotal = $taxable_total;
        $total_taxes = '0.00';
        if ($focus->column_fields["hdnTaxType"] == "individual") {
            $total_tax_percent = '0.00';
            //This loop is to get all tax percentage and then calculate the total of all taxes
            for ($tax_count = 0; $tax_count < count($associated_products[$i]['taxes']); $tax_count++) {
                $tax_percent = $associated_products[$i]['taxes'][$tax_count]['percentage'];
                $total_tax_percent = $total_tax_percent + $tax_percent;
                $tax_amount = $taxable_total * $tax_percent / 100;
                //calculate the tax amount for any available tax percentage
                $detected_tax = substr(array_search($total_tax_percent, $taxtype_listings), -1);
                $taxtype_listings[value . $detected_tax] = $taxtype_listings[value . $detected_tax] + $tax_amount;
                $total_taxes = $total_taxes + $tax_amount;
            }
            $producttotal = $taxable_total + $total_taxes;
            $product_line[$j][$pdf_strings['Tax']] = " ({$total_tax_percent} %) " . number_format($total_taxes, $decimal_precision, $decimals_separator, $thousands_separator);
            // combine product name, description and comment to one field based on settings
        }
        // combine product name, description and comment to one field based on settings
        if ($focus->column_fields["hdnTaxType"] == "individual") {
            $product_selection = $iproddetails;
        } else {
            $product_selection = $gproddetails;
        }
        switch ($product_selection) {
            case 1:
                $product_name_long[$i] = $product_name[$i];
                break;
            case 2:
                $product_name_long[$i] = $prod_description[$i];
                break;
            case 3:
                $product_name_long[$i] = $product_name[$i] . "\n" . $prod_description[$i];
                break;
            case 4:
                $product_name_long[$i] = $comment[$i];
                break;
            case 5:
                $product_name_long[$i] = $product_name[$i] . "\n" . $comment[$i];
                break;
            case 6:
                if ($prod_description[$i] != '') {
                    $product_name_long[$i] = $prod_description[$i] . "\n" . $comment[$i];
                } else {
                    $product_name_long[$i] = $comment[$i];
                }
                break;
            case 7:
                if ($prod_description[$i] != '') {
                    $product_name_long[$i] = $product_name[$i] . "\n" . $prod_description[$i] . "\n" . $comment[$i];
                } else {
                    $product_name_long[$i] = $product_name[$i] . "\n" . $comment[$i];
                }
                break;
            default:
                if ($prod_description[$i] != '') {
                    $product_name_long[$i] = $product_name[$i] . "\n" . $prod_description[$i] . "\n" . $comment[$i];
                } else {
                    $product_name_long[$i] = $product_name[$i] . "\n" . $comment[$i];
                }
                break;
        }
        $prod_total[$i] = number_format($producttotal, $decimal_precision, $decimals_separator, $thousands_separator);
        $product_line[$j][$pdf_strings['Position']] = $j + 1;
        $product_line[$j][$pdf_strings['OrderCode']] = $product_code[$i];
        $product_line[$j][$pdf_strings['Description']] = $product_name_long[$i];
        $product_line[$j][$pdf_strings['Qty']] = $qty_formated[$i];
        $product_line[$j][$pdf_strings['Unit']] = $usageunit[$i];
        $product_line[$j][$pdf_strings['UnitPrice']] = $list_price[$i];
        $product_line[$j][$pdf_strings['Discount']] = $discount_totalformated[$i];
        $product_line[$j][$pdf_strings['LineTotal']] = $prod_total[$i];
    }
    //Population of current date
    $addyear = strtotime("+0 year");
    $dat_fmt = $current_user->date_format == '' ? 'dd-mm-yyyy' : $current_user->date_format;
    $date_issued = $dat_fmt == 'dd-mm-yyyy' ? date('d-m-Y', $addyear) : ($dat_fmt == 'mm-dd-yyyy' ? date('m-d-Y', $addyear) : ($dat_fmt == 'yyyy-mm-dd' ? date('Y-m-d', $addyear) : ''));
    // ************************ END POPULATE DATA ***************************
    //************************BEGIN PDF FORMATING**************************
    // Extend the TCPDF class to create custom Header and Footer
    class MYPDF extends TCPDF
    {
        //modifiy tcpdf class footer
        public function Footer()
        {
            //To make the function Footer() work properly
            $this->AliasNbPages();
            if (!isset($this->original_lMargin)) {
                $this->original_lMargin = $this->lMargin;
            }
            if (!isset($this->original_rMargin)) {
                $this->original_rMargin = $this->rMargin;
            }
            include "modules/SalesOrder/pdf_templates/footer.php";
        }
    }
    $page_num = '1';
    // create new PDF document
    //$pdf = new PDF( 'P', 'mm', 'A4' );
    $pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true);
    // set font
    $pdf->SetFont($default_font, " ", $default_font_size);
    $pdf->setPrintHeader(0);
    //header switched off permanently
    // auto break on
    //$pdf->SetAutoPageBreak(true);
    // set footer fonts
    //$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
    //set margins
    $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
    $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
    $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
    // set pdf information
    $pdf->SetTitle($pdf_strings['FACTURE'] . ": " . $account_name);
    $pdf->SetAuthor($owner_firstname . " " . $owner_lastname . ", " . $org_name);
    $pdf->SetSubject($account_name);
    $pdf->SetCreator('PDF Creator from www.crm-now.com');
    //list product names as keywords
    $productlisting = implode(", ", $product_name);
    $pdf->SetKeywords($productlisting);
    //Disable automatic page break
    $pdf->SetAutoPageBreak(true, PDF_MARGIN_FOOTER);
    //set image scale factor
    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
    //set some language-dependent strings
    $pdf->setLanguageArray($l);
    //initialize document
    $pdf->AliasNbPages();
    //in reference to body.php -> if a new page must be added if the space available for summary is too small
    $new_page_started = false;
    $pdf->AddPage();
    $pdf->setImageScale(1.5);
    //$pdf->SetY(PDF_MARGIN_HEADER);
    include "modules/SalesOrder/pdf_templates/header.php";
    $pdf->SetFont($default_font, " ", $font_size_body);
    include "modules/SalesOrder/pdf_templates/body.php";
    // issue pdf
    if ($purpose == 'print') {
        $pdf->Output($pdf_strings['FACTURE'] . '_' . $date_issued . '.pdf', 'D');
    } elseif ($purpose == 'send') {
        // send pdf with mail
        switch ($language) {
            case "EN":
                $pdf->Output('storage/SalesOrder_' . $_REQUEST['record'] . '.pdf', 'F');
                //added file name to make it work in IE, also forces the download giving the user the option to save
                break;
            case "DE":
                $pdf->Output('storage/Bestellung_' . $_REQUEST['record'] . '.pdf', 'F');
                //added file name to make it work in IE, also forces the download giving the user the option to save
                break;
        }
        return;
    }
    exit;
}
Example #13
0
}
if (isset($cust_fld)) {
    $smarty->assign("CUSTOMFIELD", $cust_fld);
}
$smarty->assign("CALENDAR_DATEFORMAT", parse_calendardate($app_strings['NTC_DATE_FORMAT']));
//Tax handling (get the available taxes only) - starts
if ($focus->mode == 'edit') {
    $retrieve_taxes = true;
    $productid = $focus->id;
    $tax_details = getTaxDetailsForProduct($productid, 'available_associated');
} elseif ($_REQUEST['isDuplicate'] == 'true') {
    $retrieve_taxes = true;
    $productid = $_REQUEST['record'];
    $tax_details = getTaxDetailsForProduct($productid, 'available_associated');
} else {
    $tax_details = getAllTaxes('available');
}
for ($i = 0; $i < count($tax_details); $i++) {
    $tax_details[$i]['check_name'] = $tax_details[$i]['taxname'] . '_check';
    $tax_details[$i]['check_value'] = 0;
}
//For Edit and Duplicate we have to retrieve the product associated taxes and show them
if ($retrieve_taxes) {
    for ($i = 0; $i < count($tax_details); $i++) {
        $tax_value = getProductTaxPercentage($tax_details[$i]['taxname'], $productid);
        $tax_details[$i]['percentage'] = $tax_value;
        $tax_details[$i]['check_value'] = 1;
        //if the tax is not associated with the product then we should get the default value and unchecked
        if ($tax_value == '') {
            $tax_details[$i]['check_value'] = 0;
            $tax_details[$i]['percentage'] = getTaxPercentage($tax_details[$i]['taxname']);
 public function beforeGetTaskform($viewer)
 {
     global $adb;
     $new_module = $this->get("new_module");
     if (!empty($_POST["task"]["new_module_setter"])) {
         $new_module = $_POST["task"]["new_module_setter"];
         #            $viewer->assign("module_name", $_POST["task"]["new_module_setter"]);
         $mandatoryFields = VtUtils::getMandatoryFields(getTabId($_POST["task"]["new_module_setter"]));
         $startFields = array();
         $counter = 1;
         foreach ($mandatoryFields as $field) {
             if ('productid' != $field['fieldname']) {
                 $startFields["" . $counter] = array("field" => $field["fieldname"], "mode" => "value", "value" => "", "fixed" => true);
                 $counter++;
             }
         }
         $startFields["" . $counter++] = array("field" => "currency_id", "mode" => "value", "value" => "", "fixed" => true);
         $startFields["" . $counter++] = array("field" => "hdnTaxType", "mode" => "value", "value" => "", "fixed" => true);
         $startFields["" . $counter++] = array("field" => "hdnS_H_Amount", "mode" => "value", "value" => "", "fixed" => true);
         $this->set("setter", $startFields);
         $this->set("global", array());
     }
     if (!empty($new_module) && $new_module != -1) {
         $field = new StdClass();
         $field->name = "hdnS_H_Amount";
         $field->label = getTranslatedString("Shipping & Handling Charges", $_POST["task"]["new_module_setter"]);
         $additionalFields = array($field);
         $viewer->assign("new_module", $new_module);
     }
     $workflows = Workflow2::getWorkflowsForModule($new_module, 1);
     $viewer->assign("extern_workflows", $workflows);
     $module = array();
     $module["Invoice"] = getTranslatedString("Invoice", "Invoice");
     $module["Quotes"] = getTranslatedString("Quotes", "Quotes");
     $module["PurchaseOrder"] = getTranslatedString("PurchaseOrder", "PurchaseOrder");
     $module["SalesOrder"] = getTranslatedString("SalesOrder", "SalesOrder");
     asort($module);
     $viewer->assign("avail_module", $module);
     $viewer->assign("orig_module_name", $this->getModuleName());
     $viewer->assign("availCurrency", getAllCurrencies());
     $viewer->assign("availTaxes", getAllTaxes("available"));
 }
Example #15
0
function getValue($field_result, $list_result, $fieldname, $focus, $module, $entity_id, $list_result_count, $mode, $popuptype, $returnset = '', $viewid = '')
{
    global $log, $listview_max_textlength, $app_strings, $current_language, $currentModule;
    $log->debug("Entering getValue(" . $field_result . "," . $list_result . "," . $fieldname . "," . get_class($focus) . "," . $module . "," . $entity_id . "," . $list_result_count . "," . $mode . "," . $popuptype . "," . $returnset . "," . $viewid . ") method ...");
    global $adb, $current_user, $default_charset;
    require 'user_privileges/user_privileges_' . $current_user->id . '.php';
    $tabname = getParentTab();
    $tabid = getTabid($module);
    $current_module_strings = return_module_language($current_language, $module);
    $uicolarr = $field_result[$fieldname];
    foreach ($uicolarr as $key => $value) {
        $uitype = $key;
        $colname = $value;
    }
    //added for getting event status in Custom view - Jaguar
    if ($module == 'Calendar' && ($colname == "status" || $colname == "eventstatus")) {
        $colname = "activitystatus";
    }
    //Ends
    $field_val = $adb->query_result($list_result, $list_result_count, $colname);
    if (stristr(html_entity_decode($field_val), "<a href") === false && $uitype != 8) {
        $temp_val = textlength_check($field_val);
    } elseif ($uitype != 8) {
        $temp_val = html_entity_decode($field_val, ENT_QUOTES);
    } else {
        $temp_val = $field_val;
    }
    // vtlib customization: New uitype to handle relation between modules
    if ($uitype == '10') {
        $parent_id = $field_val;
        if (!empty($parent_id)) {
            $parent_module = getSalesEntityType($parent_id);
            $valueTitle = $parent_module;
            if ($app_strings[$valueTitle]) {
                $valueTitle = $app_strings[$valueTitle];
            }
            $displayValueArray = getEntityName($parent_module, $parent_id);
            if (!empty($displayValueArray)) {
                foreach ($displayValueArray as $key => $value) {
                    $displayValue = $value;
                }
            }
            $value = "<a href='index.php?module={$parent_module}&action=DetailView&record={$parent_id}' title='{$valueTitle}'>{$displayValue}</a>";
        } else {
            $value = '';
        }
    } else {
        if ($uitype == 53) {
            $value = textlength_check($adb->query_result($list_result, $list_result_count, 'user_name'));
            // When Assigned To field is used in Popup window
            if ($value == '') {
                $user_id = $adb->query_result($list_result, $list_result_count, 'smownerid');
                if ($user_id != null && $user_id != '') {
                    $value = getOwnerName($user_id);
                }
            }
        } elseif ($uitype == 52) {
            $value = getUserName($adb->query_result($list_result, $list_result_count, $colname));
        } elseif ($uitype == 51) {
            $parentid = $adb->query_result($list_result, $list_result_count, "parentid");
            if ($module == 'Accounts') {
                $entity_name = textlength_check(getAccountName($parentid));
            } elseif ($module == 'Products') {
                $entity_name = textlength_check(getProductName($parentid));
            }
            $value = '<a href="index.php?module=' . $module . '&action=DetailView&record=' . $parentid . '&parenttab=' . $tabname . '" style="' . $P_FONT_COLOR . '">' . $entity_name . '</a>';
        } elseif ($uitype == 77) {
            $value = getUserName($adb->query_result($list_result, $list_result_count, 'inventorymanager'));
        } elseif ($uitype == 5 || $uitype == 6 || $uitype == 23 || $uitype == 70) {
            if ($temp_val != '' && $temp_val != '0000-00-00') {
                $value = getDisplayDate($temp_val);
            } elseif ($temp_val == '0000-00-00') {
                $value = '';
            } else {
                $value = $temp_val;
            }
        } elseif ($uitype == 15 || $uitype == 55 && $fieldname == "salutationtype") {
            $temp_val = decode_html($adb->query_result($list_result, $list_result_count, $colname));
            if ($is_admin == false && $profileGlobalPermission[1] == 1 && $profileGlobalPermission[2] == 1 && $temp_val != '') {
                $temp_acttype = $adb->query_result($list_result, $list_result_count, 'activitytype');
                if ($temp_acttype != 'Task' && $fieldname == "taskstatus") {
                    $temptable = "eventstatus";
                } else {
                    $temptable = $fieldname;
                }
                $roleid = $current_user->roleid;
                $roleids = array();
                $subrole = getRoleSubordinates($roleid);
                if (count($subrole) > 0) {
                    $roleids = $subrole;
                }
                array_push($roleids, $roleid);
                //here we are checking wheather the table contains the sortorder column .If  sortorder is present in the main picklist table, then the role2picklist will be applicable for this table...
                $sql = "select * from vtiger_{$temptable} where {$temptable}=?";
                $res = $adb->pquery($sql, array(decode_html($temp_val)));
                $picklistvalueid = $adb->query_result($res, 0, 'picklist_valueid');
                if ($picklistvalueid != null) {
                    $pick_query = "select * from vtiger_role2picklist where picklistvalueid={$picklistvalueid} and roleid in (" . generateQuestionMarks($roleids) . ")";
                    $res_val = $adb->pquery($pick_query, array($roleids));
                    $num_val = $adb->num_rows($res_val);
                }
                if ($num_val > 0 || $temp_acttype == 'Task' && $fieldname == 'activitytype') {
                    $temp_val = $temp_val;
                } else {
                    $temp_val = "<font color='red'>" . $app_strings['LBL_NOT_ACCESSIBLE'] . "</font>";
                }
            }
            $value = $current_module_strings[$temp_val] != '' ? $current_module_strings[$temp_val] : ($app_strings[$temp_val] != '' ? $app_strings[$temp_val] : $temp_val);
            if ($value != "<font color='red'>" . $app_strings['LBL_NOT_ACCESSIBLE'] . "</font>") {
                $value = textlength_check($value);
            }
        } elseif ($uitype == 16) {
            $value = getTranslatedString($temp_val, $currentModule);
        } elseif ($uitype == 71 || $uitype == 72) {
            if ($temp_val != '') {
                if ($fieldname == 'unit_price') {
                    $currency_id = getProductBaseCurrency($entity_id, $module);
                    $cursym_convrate = getCurrencySymbolandCRate($currency_id);
                    $value = "<font style='color:grey;'>" . $cursym_convrate['symbol'] . "</font> " . $temp_val;
                } else {
                    $rate = $user_info['conv_rate'];
                    //changes made to remove vtiger_currency symbol infront of each vtiger_potential amount
                    if ($temp_val != 0) {
                        $value = convertFromDollar($temp_val, $rate);
                    } else {
                        $value = $temp_val;
                    }
                }
            } else {
                $value = '';
            }
        } elseif ($uitype == 17) {
            $value = '<a href="http://' . $field_val . '" target="_blank">' . $temp_val . '</a>';
        } elseif ($uitype == 13 || $uitype == 104 && ($_REQUEST['action'] != 'Popup' && $_REQUEST['file'] != 'Popup')) {
            if ($_SESSION['internal_mailer'] == 1) {
                //check added for email link in user detailview
                if ($module == 'Calendar') {
                    if (getActivityType($entity_id) == 'Task') {
                        $tabid = 9;
                    } else {
                        $tabid = 16;
                    }
                } else {
                    $tabid = getTabid($module);
                }
                $fieldid = getFieldid($tabid, $fieldname);
                if (empty($popuptype)) {
                    $value = '<a href="javascript:InternalMailer(' . $entity_id . ',' . $fieldid . ',\'' . $fieldname . '\',\'' . $module . '\',\'record_id\');">' . $temp_val . '</a>';
                } else {
                    $value = $temp_val;
                }
            } else {
                $value = '<a href="mailto:' . $field_val . '">' . $temp_val . '</a>';
            }
        } elseif ($uitype == 56) {
            if ($temp_val == 1) {
                $value = $app_strings['yes'];
            } elseif ($temp_val == 0) {
                $value = $app_strings['no'];
            } else {
                $value = '';
            }
        } elseif ($uitype == 57) {
            if ($temp_val != '') {
                $sql = "SELECT * FROM vtiger_contactdetails WHERE contactid=?";
                $result = $adb->pquery($sql, array($temp_val));
                $value = '';
                if ($adb->num_rows($result)) {
                    $name = getFullNameFromQResult($result, 0, "Contacts");
                    $value = '<a href=index.php?module=Contacts&action=DetailView&record=' . $temp_val . '>' . $name . '</a>';
                }
            } else {
                $value = '';
            }
        } elseif ($uitype == 58) {
            if ($temp_val != '') {
                $sql = "SELECT * FROM vtiger_campaign WHERE campaignid=?";
                $result = $adb->pquery($sql, array($temp_val));
                $campaignname = $adb->query_result($result, 0, "campaignname");
                $value = '<a href=index.php?module=Campaigns&action=DetailView&record=' . $temp_val . '>' . $campaignname . '</a>';
            } else {
                $value = '';
            }
        } elseif ($uitype == 59) {
            if ($temp_val != '') {
                $value = getProductName($temp_val);
            } else {
                $value = '';
            }
        } elseif ($uitype == 61) {
            $attachmentid = $adb->query_result($adb->pquery("SELECT * FROM vtiger_seattachmentsrel WHERE crmid = ?", array($entity_id)), 0, 'attachmentsid');
            $value = '<a href = "index.php?module=uploads&action=downloadfile&return_module=' . $module . '&fileid=' . $attachmentid . '&filename=' . $temp_val . '">' . $temp_val . '</a>';
        } elseif ($uitype == 62) {
            $parentid = $adb->query_result($list_result, $list_result_count, "parent_id");
            $parenttype = $adb->query_result($list_result, $list_result_count, "parent_type");
            if ($parenttype == "Leads") {
                $tablename = "vtiger_leaddetails";
                $fieldname = "lastname";
                $idname = "leadid";
            }
            if ($parenttype == "Accounts") {
                $tablename = "vtiger_account";
                $fieldname = "accountname";
                $idname = "accountid";
            }
            if ($parenttype == "Products") {
                $tablename = "vtiger_products";
                $fieldname = "productname";
                $idname = "productid";
            }
            if ($parenttype == "HelpDesk") {
                $tablename = "vtiger_troubletickets";
                $fieldname = "title";
                $idname = "ticketid";
            }
            if ($parenttype == "Invoice") {
                $tablename = "vtiger_invoice";
                $fieldname = "subject";
                $idname = "invoiceid";
            }
            if ($parentid != '') {
                $sql = "SELECT * FROM {$tablename} WHERE {$idname} = ?";
                $fieldvalue = $adb->query_result($adb->pquery($sql, array($parentid)), 0, $fieldname);
                $value = '<a href=index.php?module=' . $parenttype . '&action=DetailView&record=' . $parentid . '&parenttab=' . urlencode($tabname) . '>' . $fieldvalue . '</a>';
            } else {
                $value = '';
            }
        } elseif ($uitype == 66) {
            $parentid = $adb->query_result($list_result, $list_result_count, "parent_id");
            $parenttype = $adb->query_result($list_result, $list_result_count, "parent_type");
            if ($parenttype == "Leads") {
                $tablename = "vtiger_leaddetails";
                $fieldname = "lastname";
                $idname = "leadid";
            }
            if ($parenttype == "Accounts") {
                $tablename = "vtiger_account";
                $fieldname = "accountname";
                $idname = "accountid";
            }
            if ($parenttype == "HelpDesk") {
                $tablename = "vtiger_troubletickets";
                $fieldname = "title";
                $idname = "ticketid";
            }
            if ($parentid != '') {
                $sql = "SELECT * FROM {$tablename} WHERE {$idname} = ?";
                $fieldvalue = $adb->query_result($adb->pquery($sql, array($parentid)), 0, $fieldname);
                $value = '<a href=index.php?module=' . $parenttype . '&action=DetailView&record=' . $parentid . '&parenttab=' . urlencode($tabname) . '>' . $fieldvalue . '</a>';
            } else {
                $value = '';
            }
        } elseif ($uitype == 67) {
            $parentid = $adb->query_result($list_result, $list_result_count, "parent_id");
            $parenttype = $adb->query_result($list_result, $list_result_count, "parent_type");
            if ($parenttype == "Leads") {
                $tablename = "vtiger_leaddetails";
                $fieldname = "lastname";
                $idname = "leadid";
            }
            if ($parenttype == "Contacts") {
                $tablename = "vtiger_contactdetails";
                $fieldname = "contactname";
                $idname = "contactid";
            }
            if ($parentid != '') {
                $sql = "SELECT * FROM {$tablename} WHERE {$idname} = ?";
                $fieldvalue = $adb->query_result($adb->pquery($sql, array($parentid)), 0, $fieldname);
                $value = '<a href=index.php?module=' . $parenttype . '&action=DetailView&record=' . $parentid . '&parenttab=' . urlencode($tabname) . '>' . $fieldvalue . '</a>';
            } else {
                $value = '';
            }
        } elseif ($uitype == 68) {
            $parentid = $adb->query_result($list_result, $list_result_count, "parent_id");
            $parenttype = $adb->query_result($list_result, $list_result_count, "parent_type");
            if ($parenttype == '' && $parentid != '') {
                $parenttype = getSalesEntityType($parentid);
            }
            if ($parenttype == "Contacts") {
                $tablename = "vtiger_contactdetails";
                $fieldname = "contactname";
                $idname = "contactid";
            }
            if ($parenttype == "Accounts") {
                $tablename = "vtiger_account";
                $fieldname = "accountname";
                $idname = "accountid";
            }
            if ($parentid != '') {
                $sql = "SELECT * FROM {$tablename} WHERE {$idname} = ?";
                $fieldvalue = $adb->query_result($adb->pquery($sql, array($parentid)), 0, $fieldname);
                $value = '<a href=index.php?module=' . $parenttype . '&action=DetailView&record=' . $parentid . '&parenttab=' . urlencode($tabname) . '>' . $fieldvalue . '</a>';
            } else {
                $value = '';
            }
        } elseif ($uitype == 78) {
            if ($temp_val != '') {
                $quote_name = getQuoteName($temp_val);
                $value = '<a href=index.php?module=Quotes&action=DetailView&record=' . $temp_val . '&parenttab=' . urlencode($tabname) . '>' . textlength_check($quote_name) . '</a>';
            } else {
                $value = '';
            }
        } elseif ($uitype == 79) {
            if ($temp_val != '') {
                $purchaseorder_name = getPoName($temp_val);
                $value = '<a href=index.php?module=PurchaseOrder&action=DetailView&record=' . $temp_val . '&parenttab=' . urlencode($tabname) . '>' . textlength_check($purchaseorder_name) . '</a>';
            } else {
                $value = '';
            }
        } elseif ($uitype == 80) {
            if ($temp_val != '') {
                $salesorder_name = getSoName($temp_val);
                $value = "<a href=index.php?module=SalesOrder&action=DetailView&record={$temp_val}&parenttab=" . urlencode($tabname) . ">" . textlength_check($salesorder_name) . '</a>';
            } else {
                $value = '';
            }
        } elseif ($uitype == 75 || $uitype == 81) {
            if ($temp_val != '') {
                $vendor_name = getVendorName($temp_val);
                $value = '<a href=index.php?module=Vendors&action=DetailView&record=' . $temp_val . '&parenttab=' . urlencode($tabname) . '>' . textlength_check($vendor_name) . '</a>';
            } else {
                $value = '';
            }
        } elseif ($uitype == 98) {
            $value = '<a href="index.php?action=RoleDetailView&module=Settings&parenttab=Settings&roleid=' . $temp_val . '">' . textlength_check(getRoleName($temp_val)) . '</a>';
        } elseif ($uitype == 33) {
            $value = $temp_val != "" ? str_ireplace(' |##| ', ', ', $temp_val) : "";
            if (!$is_admin && $value != '') {
                $value = $field_val != "" ? str_ireplace(' |##| ', ', ', $field_val) : "";
                if ($value != '') {
                    $value_arr = explode(',', trim($value));
                    $roleid = $current_user->roleid;
                    $subrole = getRoleSubordinates($roleid);
                    if (count($subrole) > 0) {
                        $roleids = $subrole;
                        array_push($roleids, $roleid);
                    } else {
                        $roleids = $roleid;
                    }
                    if (count($roleids) > 0) {
                        $pick_query = "select distinct {$fieldname} from vtiger_{$fieldname} inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_{$fieldname}.picklist_valueid where roleid in (" . generateQuestionMarks($roleids) . ") and picklistid in (select picklistid from vtiger_{$fieldname}) order by {$fieldname} asc";
                        $params = array($roleids);
                    } else {
                        $pick_query = "select distinct {$fieldname} from vtiger_{$fieldname} inner join vtiger_role2picklist on vtiger_role2picklist.picklistvalueid = vtiger_{$fieldname}.picklist_valueid where picklistid in (select picklistid from vtiger_{$fieldname}) order by {$fieldname} asc";
                        $params = array();
                    }
                    $pickListResult = $adb->pquery($pick_query, $params);
                    $picklistval = array();
                    for ($i = 0; $i < $adb->num_rows($pickListResult); $i++) {
                        $picklistarr[] = $adb->query_result($pickListResult, $i, $fieldname);
                    }
                    $value_temp = array();
                    $string_temp = '';
                    $str_c = 0;
                    foreach ($value_arr as $ind => $val) {
                        $notaccess = '<font color="red">' . $app_strings['LBL_NOT_ACCESSIBLE'] . "</font>";
                        if (!$listview_max_textlength || !(strlen(preg_replace("/(<\\/?)(\\w+)([^>]*>)/i", "", $string_temp)) > $listview_max_textlength)) {
                            $value_temp1 = in_array(trim($val), $picklistarr) ? $val : $notaccess;
                            if ($str_c != 0) {
                                $string_temp .= ' , ';
                            }
                            $string_temp .= $value_temp1;
                            $str_c++;
                        } else {
                            $string_temp .= '...';
                        }
                    }
                    $value = $string_temp;
                }
            }
        } elseif ($uitype == 85) {
            $value = $temp_val != "" ? "<a href='skype:{$temp_val}?call'>{$temp_val}</a>" : "";
        } elseif ($uitype == 116) {
            $value = $temp_val != "" ? getCurrencyName($temp_val) : "";
        } elseif ($uitype == 117) {
            // NOTE: Without symbol the value could be used for filtering/lookup hence avoiding the translation
            $value = $temp_val != "" ? getCurrencyName($temp_val, false) : "";
        } elseif ($uitype == 26) {
            $sql = "select foldername from vtiger_attachmentsfolder where folderid = ?";
            $res = $adb->pquery($sql, array($temp_val));
            $foldername = $adb->query_result($res, 0, 'foldername');
            $value = $foldername;
        } elseif ($uitype == 11) {
            // Fix added for Trac Id: 6139
            if (vtlib_isModuleActive('PBXManager')) {
                $value = "<a href='javascript:;' onclick='startCall(&quot;{$temp_val}&quot;, &quot;{$entity_id}&quot;)'>" . $temp_val . "</a>";
            } else {
                $value = $temp_val;
            }
        } elseif ($uitype == 25) {
            $contactid = $_REQUEST['record'];
            $emailid = $adb->query_result($list_result, $list_result_count, "activityid");
            $result = $adb->pquery("SELECT access_count FROM vtiger_email_track WHERE crmid=? AND mailid=?", array($contactid, $emailid));
            $value = $adb->query_result($result, 0, "access_count");
            if (!$value) {
                $value = 0;
            }
        } elseif ($uitype == 8) {
            if (!empty($temp_val)) {
                $temp_val = html_entity_decode($temp_val, ENT_QUOTES, $default_charset);
                $json = new Zend_Json();
                $value = vt_suppressHTMLTags(implode(',', $json->decode($temp_val)));
            }
        } else {
            if ($fieldname == $focus->list_link_field) {
                if ($mode == "search") {
                    if ($popuptype == "specific" || $popuptype == "toDospecific") {
                        // Added for get the first name of contact in Popup window
                        if ($colname == "lastname" && $module == 'Contacts') {
                            $temp_val = getFullNameFromQResult($list_result, $list_result_count, "Contacts");
                        }
                        $slashes_temp_val = popup_from_html($temp_val);
                        $slashes_temp_val = htmlspecialchars($slashes_temp_val, ENT_QUOTES, $default_charset);
                        //Added to avoid the error when select SO from Invoice through AjaxEdit
                        if ($module == 'SalesOrder') {
                            $value = '<a href="javascript:window.close();" onclick=\'set_return_specific("' . $entity_id . '", "' . nl2br(decode_html($slashes_temp_val)) . '","' . $_REQUEST['form'] . '");\'>' . $temp_val . '</a>';
                        } elseif ($module == 'Contacts') {
                            require_once 'modules/Contacts/Contacts.php';
                            $cntct_focus = new Contacts();
                            $cntct_focus->retrieve_entity_info($entity_id, "Contacts");
                            $slashes_temp_val = popup_from_html($temp_val);
                            //ADDED TO CHECK THE FIELD PERMISSIONS FOR
                            $xyz = array('mailingstreet', 'mailingcity', 'mailingzip', 'mailingpobox', 'mailingcountry', 'mailingstate', 'otherstreet', 'othercity', 'otherzip', 'otherpobox', 'othercountry', 'otherstate');
                            for ($i = 0; $i < 12; $i++) {
                                if (getFieldVisibilityPermission($module, $current_user->id, $xyz[$i]) == '0') {
                                    $cntct_focus->column_fields[$xyz[$i]] = $cntct_focus->column_fields[$xyz[$i]];
                                } else {
                                    $cntct_focus->column_fields[$xyz[$i]] = '';
                                }
                            }
                            // For ToDo creation the underlying form is not named as EditView
                            $form = !empty($_REQUEST['form']) ? $_REQUEST['form'] : '';
                            if (!empty($form)) {
                                $form = htmlspecialchars($form, ENT_QUOTES, $default_charset);
                            }
                            $value = '<a href="javascript:window.close();" onclick=\'set_return_contact_address("' . $entity_id . '", "' . nl2br(decode_html($slashes_temp_val)) . '", "' . popup_decode_html($cntct_focus->column_fields['mailingstreet']) . '", "' . popup_decode_html($cntct_focus->column_fields['otherstreet']) . '", "' . popup_decode_html($cntct_focus->column_fields['mailingcity']) . '", "' . popup_decode_html($cntct_focus->column_fields['othercity']) . '", "' . popup_decode_html($cntct_focus->column_fields['mailingstate']) . '", "' . popup_decode_html($cntct_focus->column_fields['otherstate']) . '", "' . popup_decode_html($cntct_focus->column_fields['mailingzip']) . '", "' . popup_decode_html($cntct_focus->column_fields['otherzip']) . '", "' . popup_decode_html($cntct_focus->column_fields['mailingcountry']) . '", "' . popup_decode_html($cntct_focus->column_fields['othercountry']) . '","' . popup_decode_html($cntct_focus->column_fields['mailingpobox']) . '", "' . popup_decode_html($cntct_focus->column_fields['otherpobox']) . '","' . $form . '");\'>' . $temp_val . '</a>';
                        } else {
                            if ($popuptype == 'toDospecific') {
                                $value = '<a href="javascript:window.close();" onclick=\'set_return_toDospecific("' . $entity_id . '", "' . nl2br(decode_html($slashes_temp_val)) . '");\'>' . $temp_val . '</a>';
                            } else {
                                $value = '<a href="javascript:window.close();" onclick=\'set_return_specific("' . $entity_id . '", "' . nl2br(decode_html($slashes_temp_val)) . '");\'>' . $temp_val . '</a>';
                            }
                        }
                    } elseif ($popuptype == "detailview") {
                        if ($colname == "lastname" && ($module == 'Contacts' || $module == 'Leads')) {
                            $temp_val = getFullNameFromQResult($list_result, $list_result_count, $module);
                        }
                        $slashes_temp_val = popup_from_html($temp_val);
                        $slashes_temp_val = htmlspecialchars($slashes_temp_val, ENT_QUOTES, $default_charset);
                        $focus->record_id = $_REQUEST['recordid'];
                        if ($_REQUEST['return_module'] == "Calendar") {
                            $value = '<a href="javascript:window.close();" id="calendarCont' . $entity_id . '" LANGUAGE=javascript onclick=\'add_data_to_relatedlist_incal("' . $entity_id . '","' . decode_html($slashes_temp_val) . '");\'>' . $temp_val . '</a>';
                        } else {
                            $value = '<a href="javascript:window.close();" onclick=\'add_data_to_relatedlist("' . $entity_id . '","' . $focus->record_id . '","' . $module . '");\'>' . $temp_val . '</a>';
                        }
                    } elseif ($popuptype == "formname_specific") {
                        $slashes_temp_val = popup_from_html($temp_val);
                        $slashes_temp_val = htmlspecialchars($slashes_temp_val, ENT_QUOTES, $default_charset);
                        $value = '<a href="javascript:window.close();" onclick=\'set_return_formname_specific("' . $_REQUEST['form'] . '", "' . $entity_id . '", "' . nl2br(decode_html($slashes_temp_val)) . '");\'>' . $temp_val . '</a>';
                    } elseif ($popuptype == "inventory_prod") {
                        $row_id = $_REQUEST['curr_row'];
                        //To get all the tax types and values and pass it to product details
                        $tax_str = '';
                        $tax_details = getAllTaxes();
                        for ($tax_count = 0; $tax_count < count($tax_details); $tax_count++) {
                            $tax_str .= $tax_details[$tax_count]['taxname'] . '=' . $tax_details[$tax_count]['percentage'] . ',';
                        }
                        $tax_str = trim($tax_str, ',');
                        $rate = $user_info['conv_rate'];
                        if (getFieldVisibilityPermission('Products', $current_user->id, 'unit_price') == '0') {
                            $unitprice = $adb->query_result($list_result, $list_result_count, 'unit_price');
                            if ($_REQUEST['currencyid'] != null) {
                                $prod_prices = getPricesForProducts($_REQUEST['currencyid'], array($entity_id));
                                $unitprice = $prod_prices[$entity_id];
                            }
                        } else {
                            $unit_price = '';
                        }
                        $sub_products = '';
                        $sub_prod = '';
                        $sub_prod_query = $adb->pquery("SELECT vtiger_products.productid,vtiger_products.productname,vtiger_products.qtyinstock,vtiger_crmentity.description from vtiger_products INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_products.productid INNER JOIN vtiger_seproductsrel on vtiger_seproductsrel.crmid=vtiger_products.productid WHERE vtiger_seproductsrel.productid=? and vtiger_seproductsrel.setype='Products'", array($entity_id));
                        for ($i = 0; $i < $adb->num_rows($sub_prod_query); $i++) {
                            //$sub_prod=array();
                            $id = $adb->query_result($sub_prod_query, $i, "productid");
                            $str_sep = '';
                            if ($i > 0) {
                                $str_sep = ":";
                            }
                            $sub_products .= $str_sep . $id;
                            $sub_prod .= $str_sep . " - " . $adb->query_result($sub_prod_query, $i, "productname");
                        }
                        $sub_det = $sub_products . "::" . str_replace(":", "<br>", $sub_prod);
                        $qty_stock = $adb->query_result($list_result, $list_result_count, 'qtyinstock');
                        //fix for T6943
                        $slashes_temp_val = popup_from_html($field_val);
                        $slashes_temp_val = htmlspecialchars($slashes_temp_val, ENT_QUOTES, $default_charset);
                        $description = popup_from_html($adb->query_result($list_result, $list_result_count, 'description'));
                        $slashes_temp_desc = decode_html(htmlspecialchars($description, ENT_QUOTES, $default_charset));
                        $slashes_desc = str_replace(array("\r", "\n"), array('\\r', '\\n'), $slashes_temp_desc);
                        $tmp_arr = array("entityid" => $entity_id, "prodname" => "" . stripslashes(decode_html(nl2br($slashes_temp_val))) . "", "unitprice" => "{$unitprice}", "qtyinstk" => "{$qty_stock}", "taxstring" => "{$tax_str}", "rowid" => "{$row_id}", "desc" => "{$slashes_desc}", "subprod_ids" => "{$sub_det}");
                        require_once 'include/Zend/Json.php';
                        $prod_arr = Zend_Json::encode($tmp_arr);
                        $value = '<a href="javascript:window.close();" id=\'popup_product_' . $entity_id . '\' onclick=\'set_return_inventory("' . $entity_id . '", "' . decode_html(nl2br($slashes_temp_val)) . '", "' . $unitprice . '", "' . $qty_stock . '","' . $tax_str . '","' . $row_id . '","' . $slashes_desc . '","' . $sub_det . '");\' vt_prod_arr=\'' . $prod_arr . '\' >' . $temp_val . '</a>';
                    } elseif ($popuptype == "inventory_prod_po") {
                        $row_id = $_REQUEST['curr_row'];
                        //To get all the tax types and values and pass it to product details
                        $tax_str = '';
                        $tax_details = getAllTaxes();
                        for ($tax_count = 0; $tax_count < count($tax_details); $tax_count++) {
                            $tax_str .= $tax_details[$tax_count]['taxname'] . '=' . $tax_details[$tax_count]['percentage'] . ',';
                        }
                        $tax_str = trim($tax_str, ',');
                        $rate = $user_info['conv_rate'];
                        if (getFieldVisibilityPermission($module, $current_user->id, 'unit_price') == '0') {
                            $unitprice = $adb->query_result($list_result, $list_result_count, 'unit_price');
                            if ($_REQUEST['currencyid'] != null) {
                                $prod_prices = getPricesForProducts($_REQUEST['currencyid'], array($entity_id), $module);
                                $unitprice = $prod_prices[$entity_id];
                            }
                        } else {
                            $unit_price = '';
                        }
                        $sub_products = '';
                        $sub_prod = '';
                        $sub_prod_query = $adb->pquery("SELECT vtiger_products.productid,vtiger_products.productname,vtiger_products.qtyinstock,vtiger_crmentity.description from vtiger_products INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_products.productid INNER JOIN vtiger_seproductsrel on vtiger_seproductsrel.crmid=vtiger_products.productid WHERE vtiger_seproductsrel.productid=? and vtiger_seproductsrel.setype='Products'", array($entity_id));
                        for ($i = 0; $i < $adb->num_rows($sub_prod_query); $i++) {
                            //$sub_prod=array();
                            $id = $adb->query_result($sub_prod_query, $i, "productid");
                            $str_sep = '';
                            if ($i > 0) {
                                $str_sep = ":";
                            }
                            $sub_products .= $str_sep . $id;
                            $sub_prod .= $str_sep . " - {$id}." . $adb->query_result($sub_prod_query, $i, "productname");
                        }
                        $sub_det = $sub_products . "::" . str_replace(":", "<br>", $sub_prod);
                        $slashes_temp_val = popup_from_html($field_val);
                        $slashes_temp_val = htmlspecialchars($slashes_temp_val, ENT_QUOTES, $default_charset);
                        $description = popup_from_html($adb->query_result($list_result, $list_result_count, 'description'));
                        $slashes_temp_desc = decode_html(htmlspecialchars($description, ENT_QUOTES, $default_charset));
                        $slashes_desc = str_replace(array("\r", "\n"), array('\\r', '\\n'), $slashes_temp_desc);
                        $tmp_arr = array("entityid" => $entity_id, "prodname" => "" . stripslashes(decode_html(nl2br($slashes_temp_val))) . "", "unitprice" => "{$unitprice}", "qtyinstk" => "{$qty_stock}", "taxstring" => "{$tax_str}", "rowid" => "{$row_id}", "desc" => "{$slashes_desc}", "subprod_ids" => "{$sub_det}");
                        require_once 'include/Zend/Json.php';
                        $prod_arr = Zend_Json::encode($tmp_arr);
                        $value = '<a href="javascript:window.close();" id=\'popup_product_' . $entity_id . '\' onclick=\'set_return_inventory_po("' . $entity_id . '", "' . decode_html(nl2br($slashes_temp_val)) . '", "' . $unitprice . '", "' . $tax_str . '","' . $row_id . '","' . $slashes_desc . '","' . $sub_det . '"); \'  vt_prod_arr=\'' . $prod_arr . '\' >' . $temp_val . '</a>';
                    } elseif ($popuptype == "inventory_service") {
                        $row_id = $_REQUEST['curr_row'];
                        //To get all the tax types and values and pass it to product details
                        $tax_str = '';
                        $tax_details = getAllTaxes();
                        for ($tax_count = 0; $tax_count < count($tax_details); $tax_count++) {
                            $tax_str .= $tax_details[$tax_count]['taxname'] . '=' . $tax_details[$tax_count]['percentage'] . ',';
                        }
                        $tax_str = trim($tax_str, ',');
                        $rate = $user_info['conv_rate'];
                        if (getFieldVisibilityPermission('Services', $current_user->id, 'unit_price') == '0') {
                            $unitprice = $adb->query_result($list_result, $list_result_count, 'unit_price');
                            if ($_REQUEST['currencyid'] != null) {
                                $prod_prices = getPricesForProducts($_REQUEST['currencyid'], array($entity_id), $module);
                                $unitprice = $prod_prices[$entity_id];
                            }
                        } else {
                            $unit_price = '';
                        }
                        $slashes_temp_val = popup_from_html($field_val);
                        $slashes_temp_val = htmlspecialchars($slashes_temp_val, ENT_QUOTES, $default_charset);
                        $description = popup_from_html($adb->query_result($list_result, $list_result_count, 'description'));
                        $slashes_temp_desc = decode_html(htmlspecialchars($description, ENT_QUOTES, $default_charset));
                        $slashes_desc = str_replace(array("\r", "\n"), array('\\r', '\\n'), $slashes_temp_desc);
                        $tmp_arr = array("entityid" => $entity_id, "prodname" => "" . stripslashes(decode_html(nl2br($slashes_temp_val))) . "", "unitprice" => "{$unitprice}", "taxstring" => "{$tax_str}", "rowid" => "{$row_id}", "desc" => "{$slashes_desc}");
                        require_once 'include/Zend/Json.php';
                        $prod_arr = Zend_Json::encode($tmp_arr);
                        $value = '<a href="javascript:window.close();" id=\'popup_product_' . $entity_id . '\' onclick=\'set_return_inventory("' . $entity_id . '", "' . decode_html(nl2br($slashes_temp_val)) . '", "' . $unitprice . '", "' . $tax_str . '","' . $row_id . '","' . $slashes_desc . '");\'  vt_prod_arr=\'' . $prod_arr . '\' >' . $temp_val . '</a>';
                    } elseif ($popuptype == "inventory_pb") {
                        $prod_id = $_REQUEST['productid'];
                        $flname = $_REQUEST['fldname'];
                        $listprice = getListPrice($prod_id, $entity_id);
                        $temp_val = popup_from_html($temp_val);
                        $value = '<a href="javascript:window.close();" onclick=\'set_return_inventory_pb("' . $listprice . '", "' . $flname . '"); \'>' . $temp_val . '</a>';
                    } elseif ($popuptype == "specific_account_address") {
                        require_once 'modules/Accounts/Accounts.php';
                        $acct_focus = new Accounts();
                        $acct_focus->retrieve_entity_info($entity_id, "Accounts");
                        $slashes_temp_val = popup_from_html($temp_val);
                        $slashes_temp_val = htmlspecialchars($slashes_temp_val, ENT_QUOTES, $default_charset);
                        $xyz = array('bill_street', 'bill_city', 'bill_code', 'bill_pobox', 'bill_country', 'bill_state', 'ship_street', 'ship_city', 'ship_code', 'ship_pobox', 'ship_country', 'ship_state');
                        for ($i = 0; $i < 12; $i++) {
                            if (getFieldVisibilityPermission($module, $current_user->id, $xyz[$i]) == '0') {
                                $acct_focus->column_fields[$xyz[$i]] = $acct_focus->column_fields[$xyz[$i]];
                            } else {
                                $acct_focus->column_fields[$xyz[$i]] = '';
                            }
                        }
                        $bill_street = str_replace(array("\r", "\n"), array('\\r', '\\n'), popup_decode_html($acct_focus->column_fields['bill_street']));
                        $ship_street = str_replace(array("\r", "\n"), array('\\r', '\\n'), popup_decode_html($acct_focus->column_fields['ship_street']));
                        $value = '<a href="javascript:window.close();" onclick=\'set_return_address("' . $entity_id . '", "' . nl2br(decode_html($slashes_temp_val)) . '", "' . $bill_street . '", "' . $ship_street . '", "' . popup_decode_html($acct_focus->column_fields['bill_city']) . '", "' . popup_decode_html($acct_focus->column_fields['ship_city']) . '", "' . popup_decode_html($acct_focus->column_fields['bill_state']) . '", "' . popup_decode_html($acct_focus->column_fields['ship_state']) . '", "' . popup_decode_html($acct_focus->column_fields['bill_code']) . '", "' . popup_decode_html($acct_focus->column_fields['ship_code']) . '", "' . popup_decode_html($acct_focus->column_fields['bill_country']) . '", "' . popup_decode_html($acct_focus->column_fields['ship_country']) . '","' . popup_decode_html($acct_focus->column_fields['bill_pobox']) . '", "' . popup_decode_html($acct_focus->column_fields['ship_pobox']) . '");\'>' . $temp_val . '</a>';
                    } elseif ($popuptype == "specific_contact_account_address") {
                        require_once 'modules/Accounts/Accounts.php';
                        $acct_focus = new Accounts();
                        $acct_focus->retrieve_entity_info($entity_id, "Accounts");
                        $slashes_temp_val = popup_from_html($temp_val);
                        $slashes_temp_val = htmlspecialchars($slashes_temp_val, ENT_QUOTES, $default_charset);
                        $bill_street = str_replace(array("\r", "\n"), array('\\r', '\\n'), popup_decode_html($acct_focus->column_fields['bill_street']));
                        $ship_street = str_replace(array("\r", "\n"), array('\\r', '\\n'), popup_decode_html($acct_focus->column_fields['ship_street']));
                        $value = '<a href="javascript:window.close();" onclick=\'set_return_contact_address("' . $entity_id . '", "' . nl2br(decode_html($slashes_temp_val)) . '", "' . $bill_street . '", "' . $ship_street . '", "' . popup_decode_html($acct_focus->column_fields['bill_city']) . '", "' . popup_decode_html($acct_focus->column_fields['ship_city']) . '", "' . popup_decode_html($acct_focus->column_fields['bill_state']) . '", "' . popup_decode_html($acct_focus->column_fields['ship_state']) . '", "' . popup_decode_html($acct_focus->column_fields['bill_code']) . '", "' . popup_decode_html($acct_focus->column_fields['ship_code']) . '", "' . popup_decode_html($acct_focus->column_fields['bill_country']) . '", "' . popup_decode_html($acct_focus->column_fields['ship_country']) . '","' . popup_decode_html($acct_focus->column_fields['bill_pobox']) . '", "' . popup_decode_html($acct_focus->column_fields['ship_pobox']) . '");\'>' . $temp_val . '</a>';
                    } elseif ($popuptype == "specific_potential_account_address") {
                        $slashes_temp_val = popup_from_html($temp_val);
                        $slashes_temp_val = htmlspecialchars($slashes_temp_val, ENT_QUOTES, $default_charset);
                        // For B2C support, Potential was enabled to be linked to Contacts also.
                        // Hence we need case handling for it.
                        $relatedid = $adb->query_result($list_result, $list_result_count, "related_to");
                        $relatedentity = getSalesEntityType($relatedid);
                        if ($relatedentity == 'Accounts') {
                            require_once 'modules/Accounts/Accounts.php';
                            $acct_focus = new Accounts();
                            $acct_focus->retrieve_entity_info($relatedid, "Accounts");
                            $account_name = getAccountName($relatedid);
                            $slashes_account_name = popup_from_html($account_name);
                            $slashes_account_name = htmlspecialchars($slashes_account_name, ENT_QUOTES, $default_charset);
                            $xyz = array('bill_street', 'bill_city', 'bill_code', 'bill_pobox', 'bill_country', 'bill_state', 'ship_street', 'ship_city', 'ship_code', 'ship_pobox', 'ship_country', 'ship_state');
                            for ($i = 0; $i < 12; $i++) {
                                if (getFieldVisibilityPermission('Accounts', $current_user->id, $xyz[$i]) == '0') {
                                    $acct_focus->column_fields[$xyz[$i]] = $acct_focus->column_fields[$xyz[$i]];
                                } else {
                                    $acct_focus->column_fields[$xyz[$i]] = '';
                                }
                            }
                            $bill_street = str_replace(array("\r", "\n"), array('\\r', '\\n'), popup_decode_html($acct_focus->column_fields['bill_street']));
                            $ship_street = str_replace(array("\r", "\n"), array('\\r', '\\n'), popup_decode_html($acct_focus->column_fields['ship_street']));
                            $value = '<a href="javascript:window.close();" onclick=\'set_return_address("' . $entity_id . '", "' . nl2br(decode_html($slashes_temp_val)) . '", "' . $relatedid . '", "' . nl2br(decode_html($slashes_account_name)) . '", "' . $bill_street . '", "' . $ship_street . '", "' . popup_decode_html($acct_focus->column_fields['bill_city']) . '", "' . popup_decode_html($acct_focus->column_fields['ship_city']) . '", "' . popup_decode_html($acct_focus->column_fields['bill_state']) . '", "' . popup_decode_html($acct_focus->column_fields['ship_state']) . '", "' . popup_decode_html($acct_focus->column_fields['bill_code']) . '", "' . popup_decode_html($acct_focus->column_fields['ship_code']) . '", "' . popup_decode_html($acct_focus->column_fields['bill_country']) . '", "' . popup_decode_html($acct_focus->column_fields['ship_country']) . '","' . popup_decode_html($acct_focus->column_fields['bill_pobox']) . '", "' . popup_decode_html($acct_focus->column_fields['ship_pobox']) . '");\'>' . $temp_val . '</a>';
                        } else {
                            if ($relatedentity == 'Contacts') {
                                require_once 'modules/Contacts/Contacts.php';
                                $contact_name = getContactName($relatedid);
                                $slashes_contact_name = popup_from_html($contact_name);
                                $slashes_contact_name = htmlspecialchars($slashes_contact_name, ENT_QUOTES, $default_charset);
                                $value = '<a href="javascript:window.close();" onclick=\'set_return_contact("' . $entity_id . '", "' . nl2br(decode_html($slashes_temp_val)) . '", "' . $relatedid . '", "' . nl2br(decode_html($slashes_contact_name)) . '");\'>' . $temp_val . '</a>';
                            } else {
                                $value = $temp_val;
                            }
                        }
                    } elseif ($popuptype == "set_return_emails") {
                        if ($module == 'Accounts') {
                            $name = $adb->query_result($list_result, $list_result_count, 'accountname');
                            $accid = $adb->query_result($list_result, $list_result_count, 'accountid');
                            if (CheckFieldPermission('email1', $module) == "true") {
                                $emailaddress = $adb->query_result($list_result, $list_result_count, "email1");
                                $email_check = 1;
                            } else {
                                $email_check = 0;
                            }
                            if ($emailaddress == '') {
                                if (CheckFieldPermission('email2', $module) == 'true') {
                                    $emailaddress2 = $adb->query_result($list_result, $list_result_count, "email2");
                                    $email_check = 2;
                                } else {
                                    if ($email_check == 1) {
                                        $email_check = 4;
                                    } else {
                                        $email_check = 3;
                                    }
                                }
                            }
                            $querystr = "SELECT fieldid,fieldlabel,columnname FROM vtiger_field WHERE tabid=? and uitype=13 and vtiger_field.presence in (0,2)";
                            $queryres = $adb->pquery($querystr, array(getTabid($module)));
                            //Change this index 0 - to get the vtiger_fieldid based on email1 or email2
                            $fieldid = $adb->query_result($queryres, 0, 'fieldid');
                            $slashes_name = popup_from_html($name);
                            $slashes_name = htmlspecialchars($slashes_name, ENT_QUOTES, $default_charset);
                            $value = '<a href="javascript:window.close();" onclick=\'return set_return_emails(' . $entity_id . ',' . $fieldid . ',"' . decode_html($slashes_name) . '","' . $emailaddress . '","' . $emailaddress2 . '","' . $email_check . '"); \'>' . textlength_check($name) . '</a>';
                        } elseif ($module == 'Vendors') {
                            $name = $adb->query_result($list_result, $list_result_count, 'vendorname');
                            $venid = $adb->query_result($list_result, $list_result_count, 'vendorid');
                            if (CheckFieldPermission('email', $module) == "true") {
                                $emailaddress = $adb->query_result($list_result, $list_result_count, "email");
                                $email_check = 1;
                            } else {
                                $email_check = 0;
                            }
                            $querystr = "SELECT fieldid,fieldlabel,columnname FROM vtiger_field WHERE tabid=? and uitype=13 and vtiger_field.presence in (0,2)";
                            $queryres = $adb->pquery($querystr, array(getTabid($module)));
                            //Change this index 0 - to get the vtiger_fieldid based on email1 or email2
                            $fieldid = $adb->query_result($queryres, 0, 'fieldid');
                            $slashes_name = popup_from_html($name);
                            $slashes_name = htmlspecialchars($slashes_name, ENT_QUOTES, $default_charset);
                            $value = '<a href="javascript:window.close();" onclick=\'return set_return_emails(' . $entity_id . ',' . $fieldid . ',"' . decode_html($slashes_name) . '","' . $emailaddress . '","' . $emailaddress2 . '","' . $email_check . '"); \'>' . textlength_check($name) . '</a>';
                        } elseif ($module == 'Contacts' || $module == 'Leads') {
                            $name = getFullNameFromQResult($list_result, $list_result_count, $module);
                            if (CheckFieldPermission('email', $module) == "true") {
                                $emailaddress = $adb->query_result($list_result, $list_result_count, "email");
                                $email_check = 1;
                            } else {
                                $email_check = 0;
                            }
                            if ($emailaddress == '') {
                                if (CheckFieldPermission('yahooid', $module) == 'true') {
                                    $emailaddress2 = $adb->query_result($list_result, $list_result_count, "yahooid");
                                    $email_check = 2;
                                } else {
                                    if ($email_check == 1) {
                                        $email_check = 4;
                                    } else {
                                        $email_check = 3;
                                    }
                                }
                            }
                            $querystr = "SELECT fieldid,fieldlabel,columnname FROM vtiger_field WHERE tabid=? and uitype=13 and vtiger_field.presence in (0,2)";
                            $queryres = $adb->pquery($querystr, array(getTabid($module)));
                            //Change this index 0 - to get the vtiger_fieldid based on email or yahooid
                            $fieldid = $adb->query_result($queryres, 0, 'fieldid');
                            $slashes_name = popup_from_html($name);
                            $slashes_name = htmlspecialchars($slashes_name, ENT_QUOTES, $default_charset);
                            $value = '<a href="javascript:window.close();" onclick=\'return set_return_emails(' . $entity_id . ',' . $fieldid . ',"' . decode_html($slashes_name) . '","' . $emailaddress . '","' . $emailaddress2 . '","' . $email_check . '"); \'>' . $name . '</a>';
                        } else {
                            $firstname = $adb->query_result($list_result, $list_result_count, "first_name");
                            $lastname = $adb->query_result($list_result, $list_result_count, "last_name");
                            $name = $lastname . ' ' . $firstname;
                            $emailaddress = $adb->query_result($list_result, $list_result_count, "email1");
                            $slashes_name = popup_from_html($name);
                            $slashes_name = htmlspecialchars($slashes_name, ENT_QUOTES, $default_charset);
                            $email_check = 1;
                            $value = '<a href="javascript:window.close();" onclick=\'return set_return_emails(' . $entity_id . ',-1,"' . decode_html($slashes_name) . '","' . $emailaddress . '","' . $emailaddress2 . '","' . $email_check . '"); \'>' . textlength_check($name) . '</a>';
                        }
                    } elseif ($popuptype == "specific_vendor_address") {
                        require_once 'modules/Vendors/Vendors.php';
                        $acct_focus = new Vendors();
                        $acct_focus->retrieve_entity_info($entity_id, "Vendors");
                        $slashes_temp_val = popup_from_html($temp_val);
                        $slashes_temp_val = htmlspecialchars($slashes_temp_val, ENT_QUOTES, $default_charset);
                        $xyz = array('street', 'city', 'postalcode', 'pobox', 'country', 'state');
                        for ($i = 0; $i < 6; $i++) {
                            if (getFieldVisibilityPermission($module, $current_user->id, $xyz[$i]) == '0') {
                                $acct_focus->column_fields[$xyz[$i]] = $acct_focus->column_fields[$xyz[$i]];
                            } else {
                                $acct_focus->column_fields[$xyz[$i]] = '';
                            }
                        }
                        $bill_street = str_replace(array("\r", "\n"), array('\\r', '\\n'), popup_decode_html($acct_focus->column_fields['street']));
                        $value = '<a href="javascript:window.close();" onclick=\'set_return_address("' . $entity_id . '", "' . nl2br(decode_html($slashes_temp_val)) . '", "' . $bill_street . '", "' . popup_decode_html($acct_focus->column_fields['city']) . '", "' . popup_decode_html($acct_focus->column_fields['state']) . '", "' . popup_decode_html($acct_focus->column_fields['postalcode']) . '", "' . popup_decode_html($acct_focus->column_fields['country']) . '","' . popup_decode_html($acct_focus->column_fields['pobox']) . '");\'>' . $temp_val . '</a>';
                    } elseif ($popuptype == "specific_campaign") {
                        $slashes_temp_val = popup_from_html($temp_val);
                        $slashes_temp_val = htmlspecialchars($slashes_temp_val, ENT_QUOTES, $default_charset);
                        $value = '<a href="javascript:window.close();" onclick=\'set_return_specific_campaign("' . $entity_id . '", "' . nl2br(decode_html($slashes_temp_val)) . '");\'>' . $temp_val . '</a>';
                    } else {
                        if ($colname == "lastname") {
                            $temp_val = getFullNameFromQResult($list_result, $list_result_count, $module);
                        }
                        $slashes_temp_val = popup_from_html($temp_val);
                        $slashes_temp_val = htmlspecialchars($slashes_temp_val, ENT_QUOTES, $default_charset);
                        $log->debug("Exiting getValue method ...");
                        if ($_REQUEST['maintab'] == 'Calendar') {
                            $value = '<a href="javascript:window.close();" onclick=\'set_return_todo("' . $entity_id . '", "' . nl2br(decode_html($slashes_temp_val)) . '");\'>' . $temp_val . '</a>';
                        } else {
                            $value = '<a href="javascript:window.close();" onclick=\'set_return("' . $entity_id . '", "' . nl2br(decode_html($slashes_temp_val)) . '");\'>' . $temp_val . '</a>';
                        }
                    }
                } else {
                    if ($module == "Leads" && $colname == "lastname" || $module == "Contacts" && $colname == "lastname") {
                        $value = '<a href="index.php?action=DetailView&module=' . $module . '&record=' . $entity_id . '&parenttab=' . $tabname . '">' . $temp_val . '</a>';
                    } elseif ($module == "Calendar") {
                        $actvity_type = $adb->query_result($list_result, $list_result_count, 'activitytype');
                        $actvity_type = $actvity_type != '' ? $actvity_type : $adb->query_result($list_result, $list_result_count, 'type');
                        if ($actvity_type == "Task") {
                            $value = '<a href="index.php?action=DetailView&module=' . $module . '&record=' . $entity_id . '&activity_mode=Task&parenttab=' . $tabname . '">' . $temp_val . '</a>';
                        } else {
                            $value = '<a href="index.php?action=DetailView&module=' . $module . '&record=' . $entity_id . '&activity_mode=Events&parenttab=' . $tabname . '">' . $temp_val . '</a>';
                        }
                    } elseif ($module == "Vendors") {
                        $value = '<a href="index.php?action=DetailView&module=Vendors&record=' . $entity_id . '&parenttab=' . $tabname . '">' . $temp_val . '</a>';
                    } elseif ($module == "PriceBooks") {
                        $value = '<a href="index.php?action=DetailView&module=PriceBooks&record=' . $entity_id . '&parenttab=' . $tabname . '">' . $temp_val . '</a>';
                    } elseif ($module == "SalesOrder") {
                        $value = '<a href="index.php?action=DetailView&module=SalesOrder&record=' . $entity_id . '&parenttab=' . $tabname . '">' . $temp_val . '</a>';
                    } elseif ($module == 'Emails') {
                        $value = $temp_val;
                    } else {
                        $value = '<a href="index.php?action=DetailView&module=' . $module . '&record=' . $entity_id . '&parenttab=' . $tabname . '">' . $temp_val . '</a>';
                    }
                }
            } elseif ($fieldname == 'expectedroi' || $fieldname == 'actualroi' || $fieldname == 'actualcost' || $fieldname == 'budgetcost' || $fieldname == 'expectedrevenue') {
                $rate = $user_info['conv_rate'];
                $value = convertFromDollar($temp_val, $rate);
            } elseif (($module == 'Invoice' || $module == 'Quotes' || $module == 'PurchaseOrder' || $module == 'SalesOrder') && ($fieldname == 'hdnGrandTotal' || $fieldname == 'hdnSubTotal' || $fieldname == 'txtAdjustment' || $fieldname == 'hdnDiscountAmount' || $fieldname == 'hdnS_H_Amount')) {
                $currency_info = getInventoryCurrencyInfo($module, $entity_id);
                $currency_id = $currency_info['currency_id'];
                $currency_symbol = $currency_info['currency_symbol'];
                $value = $currency_symbol . $temp_val;
            } else {
                $value = $temp_val;
            }
        }
    }
    // Mike Crowe Mod --------------------------------------------------------Make right justified and vtiger_currency value
    if (in_array($uitype, array(71, 72, 7, 9, 90))) {
        $value = '<span align="right">' . $value . '</div>';
    }
    $log->debug("Exiting getValue method ...");
    return $value;
}
Example #16
0
/** This function returns the detailed list of vtiger_products associated to a given entity or a record.
* Param $module - module name
* Param $focus - module object
* Param $seid - sales entity id
* Return type is an object array
*/
function getAssociatedProducts($module, $focus, $seid = '')
{
    global $log, $adb, $theme, $current_user;
    $log->debug("Entering getAssociatedProducts(" . $module . "," . get_class($focus) . "," . $seid . "='') method ...");
    $theme_path = "themes/" . $theme . "/";
    $image_path = $theme_path . "images/";
    $product_Detail = array();
    if ($module == 'Quotes' || $module == 'PurchaseOrder' || $module == 'SalesOrder' || $module == 'Invoice') {
        $query = "SELECT\n\t\t\tcase when vtiger_products.productid != '' then vtiger_products.productname else vtiger_service.servicename end as productname,\n\t\t\tcase when vtiger_products.productid != '' then vtiger_products.productcode else vtiger_service.service_no end as productcode,\n\t\t\tcase when vtiger_products.productid != '' then vtiger_products.unit_price else vtiger_service.unit_price end as unit_price,\n\t\t\tcase when vtiger_products.productid != '' then vtiger_products.qtyinstock else 'NA' end as qtyinstock,\n\t\t\tcase when vtiger_products.productid != '' then 'Products' else 'Services' end as entitytype,\n\t\t\tvtiger_inventoryproductrel.listprice,\n\t\t\tvtiger_inventoryproductrel.description AS product_description,\n\t\t\tvtiger_inventoryproductrel.*\n\t\t\tFROM vtiger_inventoryproductrel\n\t\t\tLEFT JOIN vtiger_products ON vtiger_products.productid=vtiger_inventoryproductrel.productid\n\t\t\tLEFT JOIN vtiger_service ON vtiger_service.serviceid=vtiger_inventoryproductrel.productid\n\t\t\tWHERE id=? ORDER BY sequence_no";
        $params = array($focus->id);
        if ($module != 'PurchaseOrder') {
            if (GlobalVariable::getVariable('B2B', '1') == '1') {
                $acvid = $focus->column_fields['account_id'];
            } else {
                $acvid = $focus->column_fields['contact_id'];
            }
        } else {
            $acvid = $focus->column_fields['vendor_id'];
        }
    } elseif ($module == 'Potentials') {
        $query = "SELECT vtiger_products.productid, vtiger_products.productname, vtiger_products.productcode,\n\t\t\tvtiger_products.unit_price, vtiger_products.qtyinstock, vtiger_crmentity.description AS product_description,\n\t\t\t'Products' AS entitytype\n\t\t\tFROM vtiger_products\n\t\t\tINNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_products.productid\n\t\t\tINNER JOIN vtiger_seproductsrel ON vtiger_seproductsrel.productid=vtiger_products.productid\n\t\t\tWHERE vtiger_seproductsrel.crmid=?";
        $query .= " UNION SELECT vtiger_service.serviceid AS productid, vtiger_service.servicename AS productname,\n\t\t\t'NA' AS productcode, vtiger_service.unit_price AS unit_price, 'NA' AS qtyinstock,\n\t\t\tvtiger_crmentity.description AS product_description, 'Services' AS entitytype\n\t\t\tFROM vtiger_service\n\t\t\tINNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_service.serviceid\n\t\t\tINNER JOIN vtiger_crmentityrel ON vtiger_crmentityrel.relcrmid=vtiger_service.serviceid\n\t\t\tWHERE vtiger_crmentityrel.crmid=?";
        $params = array($seid, $seid);
    } elseif ($module == 'Products') {
        $query = "SELECT vtiger_products.productid, vtiger_products.productcode, vtiger_products.productname,\n\t\t\tvtiger_products.unit_price, vtiger_products.qtyinstock, vtiger_crmentity.description AS product_description,\n\t\t\t'Products' AS entitytype\n\t\t\tFROM vtiger_products\n\t\t\tINNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_products.productid\n\t\t\tWHERE vtiger_crmentity.deleted=0 AND productid=?";
        $params = array($seid);
    } elseif ($module == 'Services') {
        $query = "SELECT vtiger_service.serviceid AS productid, 'NA' AS productcode, vtiger_service.servicename AS productname,\n\t\t\tvtiger_service.unit_price AS unit_price, 'NA' AS qtyinstock, vtiger_crmentity.description AS product_description,\n\t\t\t'Services' AS entitytype\n\t\t\tFROM vtiger_service\n\t\t\tINNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_service.serviceid\n\t\t\tWHERE vtiger_crmentity.deleted=0 AND serviceid=?";
        $params = array($seid);
    }
    $cbMap = cbMap::getMapByName($module . 'InventoryDetails', 'MasterDetailLayout');
    $MDMapFound = $cbMap != null;
    if ($MDMapFound) {
        $cbMapFields = $cbMap->MasterDetailLayout();
    }
    $result = $adb->pquery($query, $params);
    $num_rows = $adb->num_rows($result);
    for ($i = 1; $i <= $num_rows; $i++) {
        $hdnProductId = $adb->query_result($result, $i - 1, 'productid');
        $hdnProductcode = $adb->query_result($result, $i - 1, 'productcode');
        $productname = $adb->query_result($result, $i - 1, 'productname');
        $productdescription = $adb->query_result($result, $i - 1, 'product_description');
        $comment = $adb->query_result($result, $i - 1, 'comment');
        $qtyinstock = $adb->query_result($result, $i - 1, 'qtyinstock');
        $qty = $adb->query_result($result, $i - 1, 'quantity');
        $unitprice = $adb->query_result($result, $i - 1, 'unit_price');
        $listprice = $adb->query_result($result, $i - 1, 'listprice');
        $entitytype = $adb->query_result($result, $i - 1, 'entitytype');
        if (!empty($entitytype)) {
            $product_Detail[$i]['entityType' . $i] = $entitytype;
        }
        $product_Detail[$i]['lineitem_id' . $i] = $adb->query_result($result, $i - 1, 'lineitem_id');
        if ($listprice == '') {
            $listprice = $unitprice;
        }
        if ($qty == '') {
            $qty = 1;
        }
        //calculate productTotal
        $productTotal = $qty * $listprice;
        //Delete link in First column
        if ($i != 1) {
            $product_Detail[$i]['delRow' . $i] = "Del";
        }
        if (empty($focus->mode) && $seid != '') {
            $sub_prod_query = $adb->pquery("SELECT crmid as prod_id from vtiger_seproductsrel WHERE productid=? AND setype='Products'", array($seid));
        } else {
            $sub_prod_query = $adb->pquery("SELECT productid as prod_id from vtiger_inventorysubproductrel WHERE id=? AND sequence_no=?", array($focus->id, $i));
        }
        $subprodid_str = '';
        $subprodname_str = '';
        $subProductArray = array();
        if ($adb->num_rows($sub_prod_query) > 0) {
            for ($j = 0; $j < $adb->num_rows($sub_prod_query); $j++) {
                $sprod_id = $adb->query_result($sub_prod_query, $j, 'prod_id');
                $sprod_name = $subProductArray[] = getProductName($sprod_id);
                $str_sep = "";
                if ($j > 0) {
                    $str_sep = ":";
                }
                $subprodid_str .= $str_sep . $sprod_id;
                $subprodname_str .= $str_sep . " - " . $sprod_name;
            }
        }
        $subprodname_str = str_replace(":", "<br>", $subprodname_str);
        $product_Detail[$i]['subProductArray' . $i] = $subProductArray;
        $product_Detail[$i]['hdnProductId' . $i] = $hdnProductId;
        $product_Detail[$i]['productName' . $i] = from_html($productname);
        /* Added to fix the issue Product Pop-up name display*/
        if ($_REQUEST['action'] == 'CreateSOPDF' || $_REQUEST['action'] == 'CreatePDF' || $_REQUEST['action'] == 'SendPDFMail') {
            $product_Detail[$i]['productName' . $i] = htmlspecialchars($product_Detail[$i]['productName' . $i]);
        }
        $product_Detail[$i]['hdnProductcode' . $i] = $hdnProductcode;
        $product_Detail[$i]['productDescription' . $i] = from_html($productdescription);
        if ($module == 'Potentials' || $module == 'Products' || $module == 'Services') {
            $product_Detail[$i]['comment' . $i] = $productdescription;
        } else {
            $product_Detail[$i]['comment' . $i] = $comment;
        }
        if ($MDMapFound) {
            foreach ($cbMapFields['detailview']['fields'] as $mdfield) {
                $mdrs = $adb->pquery('select ' . $mdfield['fieldinfo']['name'] . ' from vtiger_inventorydetails
						inner join vtiger_crmentity on crmid=vtiger_inventorydetails.inventorydetailsid
						inner join vtiger_inventorydetailscf on vtiger_inventorydetailscf.inventorydetailsid=vtiger_inventorydetails.inventorydetailsid
						where deleted=0 and related_to=? and lineitem_id=?', array($focus->id, $adb->query_result($result, $i - 1, 'lineitem_id')));
                if ($mdrs) {
                    $col_fields = array();
                    $col_fields[$mdfield['fieldinfo']['name']] = $adb->query_result($mdrs, 0, 0);
                    $foutput = getOutputHtml($mdfield['fieldinfo']['uitype'], $mdfield['fieldinfo']['name'], $mdfield['fieldinfo']['label'], 100, $col_fields, 0, 'InventoryDetails', 'edit', $mdfield['fieldinfo']['typeofdata']);
                    $product_Detail[$i]['moreinfo' . $i][] = $foutput;
                }
            }
        }
        if ($module != 'PurchaseOrder' && $focus->object_name != 'Order') {
            $product_Detail[$i]['qtyInStock' . $i] = $qtyinstock;
        }
        $qty = number_format($qty, 2, '.', '');
        //Convert to 2 decimals
        $listprice = number_format($listprice, 2, '.', '');
        //Convert to 2 decimals
        $product_Detail[$i]['qty' . $i] = $qty;
        $product_Detail[$i]['listPrice' . $i] = $listprice;
        $product_Detail[$i]['unitPrice' . $i] = $unitprice;
        $product_Detail[$i]['productTotal' . $i] = $productTotal;
        $product_Detail[$i]['subproduct_ids' . $i] = $subprodid_str;
        $product_Detail[$i]['subprod_names' . $i] = $subprodname_str;
        $discount_percent = $adb->query_result($result, $i - 1, 'discount_percent');
        $discount_amount = $adb->query_result($result, $i - 1, 'discount_amount');
        $discount_amount = number_format(is_numeric($discount_amount) ? $discount_amount : 0, 2, '.', '');
        //Convert to 2 decimals
        $discountTotal = '0.00';
        //Based on the discount percent or amount we will show the discount details
        //To avoid NaN javascript error, here we assign 0 initially to' %of price' and 'Direct Price reduction'(for Each Product)
        $product_Detail[$i]['discount_percent' . $i] = 0;
        $product_Detail[$i]['discount_amount' . $i] = 0;
        if ($discount_percent != 'NULL' && $discount_percent != '') {
            $product_Detail[$i]['discount_type' . $i] = "percentage";
            $product_Detail[$i]['discount_percent' . $i] = $discount_percent;
            $product_Detail[$i]['checked_discount_percent' . $i] = ' checked';
            $product_Detail[$i]['style_discount_percent' . $i] = ' style="visibility:visible"';
            $product_Detail[$i]['style_discount_amount' . $i] = ' style="visibility:hidden"';
            $discountTotal = $productTotal * $discount_percent / 100;
        } elseif ($discount_amount != 'NULL' && $discount_amount != '') {
            $product_Detail[$i]['discount_type' . $i] = "amount";
            $product_Detail[$i]['discount_amount' . $i] = $discount_amount;
            $product_Detail[$i]['checked_discount_amount' . $i] = ' checked';
            $product_Detail[$i]['style_discount_amount' . $i] = ' style="visibility:visible"';
            $product_Detail[$i]['style_discount_percent' . $i] = ' style="visibility:hidden"';
            $discountTotal = $discount_amount;
        } else {
            $product_Detail[$i]['checked_discount_zero' . $i] = ' checked';
        }
        $totalAfterDiscount = $productTotal - $discountTotal;
        $product_Detail[$i]['discountTotal' . $i] = $discountTotal;
        $product_Detail[$i]['totalAfterDiscount' . $i] = $totalAfterDiscount;
        $taxTotal = '0.00';
        $product_Detail[$i]['taxTotal' . $i] = $taxTotal;
        //Calculate netprice
        $netPrice = $totalAfterDiscount + $taxTotal;
        //if condition is added to call this function when we create PO/SO/Quotes/Invoice from Product module
        if ($module == 'PurchaseOrder' || $module == 'SalesOrder' || $module == 'Quotes' || $module == 'Invoice') {
            $taxtype = getInventoryTaxType($module, $focus->id);
            if ($taxtype == 'individual') {
                //Add the tax with product total and assign to netprice
                $netPrice = $netPrice + $taxTotal;
            }
        }
        $product_Detail[$i]['netPrice' . $i] = $netPrice;
        //First we will get all associated taxes as array
        $tax_details = getTaxDetailsForProduct($hdnProductId, 'all', $acvid);
        //Now retrieve the tax values from the current query with the name
        for ($tax_count = 0; $tax_count < count($tax_details); $tax_count++) {
            $tax_name = $tax_details[$tax_count]['taxname'];
            $tax_label = $tax_details[$tax_count]['taxlabel'];
            $tax_value = '0.00';
            //condition to avoid this function call when create new PO/SO/Quotes/Invoice from Product module
            if ($focus->id != '') {
                if ($taxtype == 'individual') {
                    //if individual then show the entered tax percentage
                    $tax_value = getInventoryProductTaxValue($focus->id, $hdnProductId, $tax_name);
                } else {
                    //if group tax then we have to show the default value when change to individual tax
                    $tax_value = $tax_details[$tax_count]['percentage'];
                }
            } else {
                //if the above function not called then assign the default associated value of the product
                $tax_value = $tax_details[$tax_count]['percentage'];
            }
            $product_Detail[$i]['taxes'][$tax_count]['taxname'] = $tax_name;
            $product_Detail[$i]['taxes'][$tax_count]['taxlabel'] = $tax_label;
            $product_Detail[$i]['taxes'][$tax_count]['percentage'] = $tax_value;
        }
    }
    //set the taxtype
    $product_Detail[1]['final_details']['taxtype'] = $taxtype;
    //Get the Final Discount, S&H charge, Tax for S&H and Adjustment values
    //To set the Final Discount details
    $finalDiscount = '0.00';
    $product_Detail[1]['final_details']['discount_type_final'] = 'zero';
    $subTotal = $focus->column_fields['hdnSubTotal'] != '' ? $focus->column_fields['hdnSubTotal'] : '0.00';
    $subTotal = number_format($subTotal, 2, '.', '');
    //Convert to 2 decimals
    $product_Detail[1]['final_details']['hdnSubTotal'] = $subTotal;
    $discountPercent = $focus->column_fields['hdnDiscountPercent'] != '' ? $focus->column_fields['hdnDiscountPercent'] : '0.00';
    $discountAmount = $focus->column_fields['hdnDiscountAmount'] != '' ? $focus->column_fields['hdnDiscountAmount'] : '0.00';
    $discountAmount = number_format($discountAmount, 2, '.', '');
    //Convert to 2 decimals
    //To avoid NaN javascript error, here we assign 0 initially to' %of price' and 'Direct Price reduction'(For Final Discount)
    $product_Detail[1]['final_details']['discount_percentage_final'] = 0;
    $product_Detail[1]['final_details']['discount_amount_final'] = 0;
    if ($focus->column_fields['hdnDiscountPercent'] != '0') {
        $finalDiscount = $subTotal * $discountPercent / 100;
        $product_Detail[1]['final_details']['discount_type_final'] = 'percentage';
        $product_Detail[1]['final_details']['discount_percentage_final'] = $discountPercent;
        $product_Detail[1]['final_details']['checked_discount_percentage_final'] = ' checked';
        $product_Detail[1]['final_details']['style_discount_percentage_final'] = ' style="visibility:visible"';
        $product_Detail[1]['final_details']['style_discount_amount_final'] = ' style="visibility:hidden"';
    } elseif ($focus->column_fields['hdnDiscountAmount'] != '0') {
        $finalDiscount = $focus->column_fields['hdnDiscountAmount'];
        $product_Detail[1]['final_details']['discount_type_final'] = 'amount';
        $product_Detail[1]['final_details']['discount_amount_final'] = $discountAmount;
        $product_Detail[1]['final_details']['checked_discount_amount_final'] = ' checked';
        $product_Detail[1]['final_details']['style_discount_amount_final'] = ' style="visibility:visible"';
        $product_Detail[1]['final_details']['style_discount_percentage_final'] = ' style="visibility:hidden"';
    }
    $finalDiscount = number_format($finalDiscount, 2, '.', '');
    //Convert to 2 decimals
    $product_Detail[1]['final_details']['discountTotal_final'] = $finalDiscount;
    //To set the Final Tax values
    //we will get all taxes. if individual then show the product related taxes only else show all taxes
    //suppose user want to change individual to group or vice versa in edit time the we have to show all taxes. so that here we will store all the taxes and based on need we will show the corresponding taxes
    $taxtotal = '0.00';
    //First we should get all available taxes and then retrieve the corresponding tax values
    $tax_details = getAllTaxes('available', '', 'edit', $focus->id);
    $ipr_cols = $adb->getColumnNames('vtiger_inventoryproductrel');
    for ($tax_count = 0; $tax_count < count($tax_details); $tax_count++) {
        $tax_name = $tax_details[$tax_count]['taxname'];
        $tax_label = $tax_details[$tax_count]['taxlabel'];
        //if taxtype is individual and want to change to group during edit time then we have to show the all available taxes and their default values
        //Also taxtype is group and want to change to individual during edit time then we have to provide the asspciated taxes and their default tax values for individual products
        if ($taxtype == 'group') {
            if (in_array($tax_name, $ipr_cols)) {
                $tax_percent = $adb->query_result($result, 0, $tax_name);
            } else {
                $tax_percent = $tax_details[$tax_count]['percentage'];
            }
        } else {
            $tax_percent = $tax_details[$tax_count]['percentage'];
        }
        //$adb->query_result($result,0,$tax_name);
        if ($tax_percent == '' || $tax_percent == 'NULL') {
            $tax_percent = '0.00';
        }
        $taxamount = ($subTotal - $finalDiscount) * $tax_percent / 100;
        $taxamount = number_format($taxamount, 2, '.', '');
        //Convert to 2 decimals
        $taxtotal = $taxtotal + $taxamount;
        $product_Detail[1]['final_details']['taxes'][$tax_count]['taxname'] = $tax_name;
        $product_Detail[1]['final_details']['taxes'][$tax_count]['taxlabel'] = $tax_label;
        $product_Detail[1]['final_details']['taxes'][$tax_count]['percentage'] = $tax_percent;
        $product_Detail[1]['final_details']['taxes'][$tax_count]['amount'] = $taxamount;
    }
    $product_Detail[1]['final_details']['tax_totalamount'] = $taxtotal;
    //To set the Shipping & Handling charge
    $shCharge = $focus->column_fields['hdnS_H_Amount'] != '' ? $focus->column_fields['hdnS_H_Amount'] : '0.00';
    $shCharge = number_format($shCharge, 2, '.', '');
    //Convert to 2 decimals
    $product_Detail[1]['final_details']['shipping_handling_charge'] = $shCharge;
    //To set the Shipping & Handling tax values
    //calculate S&H tax
    $shtaxtotal = '0.00';
    //First we should get all available taxes and then retrieve the corresponding tax values
    $shtax_details = getAllTaxes('available', 'sh', 'edit', $focus->id);
    //if taxtype is group then the tax should be same for all products in vtiger_inventoryproductrel table
    for ($shtax_count = 0; $shtax_count < count($shtax_details); $shtax_count++) {
        $shtax_name = $shtax_details[$shtax_count]['taxname'];
        $shtax_label = $shtax_details[$shtax_count]['taxlabel'];
        $shtax_percent = '0.00';
        //if condition is added to call this function when we create PO/SO/Quotes/Invoice from Product module
        if ($module == 'PurchaseOrder' || $module == 'SalesOrder' || $module == 'Quotes' || $module == 'Invoice') {
            $shtax_percent = getInventorySHTaxPercent($focus->id, $shtax_name);
        }
        $shtaxamount = $shCharge * $shtax_percent / 100;
        $shtaxtotal = $shtaxtotal + $shtaxamount;
        $product_Detail[1]['final_details']['sh_taxes'][$shtax_count]['taxname'] = $shtax_name;
        $product_Detail[1]['final_details']['sh_taxes'][$shtax_count]['taxlabel'] = $shtax_label;
        $product_Detail[1]['final_details']['sh_taxes'][$shtax_count]['percentage'] = $shtax_percent;
        $product_Detail[1]['final_details']['sh_taxes'][$shtax_count]['amount'] = $shtaxamount;
    }
    $product_Detail[1]['final_details']['shtax_totalamount'] = $shtaxtotal;
    //To set the Adjustment value
    $adjustment = $focus->column_fields['txtAdjustment'] != '' ? $focus->column_fields['txtAdjustment'] : '0.00';
    $adjustment = number_format($adjustment, 2, '.', '');
    //Convert to 2 decimals
    $product_Detail[1]['final_details']['adjustment'] = $adjustment;
    //To set the grand total
    $grandTotal = $focus->column_fields['hdnGrandTotal'] != '' ? $focus->column_fields['hdnGrandTotal'] : '0.00';
    $grandTotal = number_format($grandTotal, 2, '.', '');
    //Convert to 2 decimals
    $product_Detail[1]['final_details']['grandTotal'] = $grandTotal;
    $log->debug("Exiting getAssociatedProducts method ...");
    return $product_Detail;
}
Example #17
0
 private function x15()
 {
     global $x0b, $x0c, $x0d, $x0e, $x0f, $x10, $x11, $x12, $x13, $x14, $x15, $x16, $x17, $x18, $x19, $x1a, $x1b, $x1c, $x1d, $x1e, $x1f, $x20, $x21, $x22, $x23, $x24, $x25, $x26;
     $taxtype = $this->x1d();
     $currencytype = $this->x1c();
     $query = "select case when vtiger_products.productid != '' then vtiger_products.productname else vtiger_service.servicename end as productname," . " case when vtiger_products.productid != '' then vtiger_products.productid else vtiger_service.serviceid end as psid," . " case when vtiger_products.productid != '' then vtiger_products.product_no else vtiger_service.service_no end as psno," . " case when vtiger_products.productid != '' then 'Products' else 'Services' end as entitytype," . " case when vtiger_products.productid != '' then vtiger_products.unit_price else vtiger_service.unit_price end as unit_price," . " case when vtiger_products.productid != '' then vtiger_products.usageunit else vtiger_service.service_usageunit end as usageunit," . " case when vtiger_products.productid != '' then vtiger_products.qty_per_unit else vtiger_service.qty_per_unit end as qty_per_unit," . " case when vtiger_products.productid != '' then vtiger_products.qtyinstock else 'NA' end as qtyinstock," . " case when vtiger_products.productid != '' then c1.description else c2.description end as psdescription, vtiger_inventoryproductrel.* " . " from vtiger_inventoryproductrel" . " left join vtiger_products on vtiger_products.productid=vtiger_inventoryproductrel.productid " . " left join vtiger_crmentity as c1 on c1.crmid = vtiger_products.productid " . " left join vtiger_service on vtiger_service.serviceid=vtiger_inventoryproductrel.productid " . " left join vtiger_crmentity as c2 on c2.crmid = vtiger_service.serviceid " . " where id=? ORDER BY sequence_no";
     $result = $this->db->pquery($query, array($this->focus->id));
     $num_rows = $this->db->num_rows($result);
     $netTotal = "0.00";
     $totalAfterDiscount_subtotal = 0;
     $total_subtotal = 0;
     $totalsum_subtotal = 0;
     $images = $this->x17();
     $Total_Tax_Values = array();
     for ($i = 1; $i <= $num_rows; $i++) {
         $sub_prod_query = $this->db->pquery("SELECT productid from vtiger_inventorysubproductrel WHERE id=? AND sequence_no=?", array($this->focus->id, $i));
         $subprodname_str = '';
         if ($this->db->num_rows($sub_prod_query) > 0) {
             for ($j = 0; $j < $this->db->num_rows($sub_prod_query); $j++) {
                 $sprod_id = $this->db->query_result($sub_prod_query, $j, "productid");
                 $sprod_name = getProductName($sprod_id);
                 $str_sep = "";
                 if ($j > 0) {
                     $str_sep = ":";
                 }
                 $subprodname_str .= $str_sep . " - " . $sprod_name;
             }
         }
         $subprodname_str = $x1e(":", "<br>", $subprodname_str);
         $psid = $this->db->query_result($result, $i - 1, "psid");
         $psno = $this->db->query_result($result, $i - 1, "psno");
         $productid = $this->db->query_result($result, $i - 1, "productid");
         $entitytype = $this->db->query_result($result, $i - 1, "entitytype");
         $producttitle = $productname = $this->db->query_result($result, $i - 1, "productname");
         if ($subprodname_str != "") {
             $productname .= "<br/><span style='color:#C0C0C0;font-style:italic;'>" . $subprodname_str . "</span>";
         }
         $comment = $this->db->query_result($result, $i - 1, "comment");
         $psdescription = $this->db->query_result($result, $i - 1, "psdescription");
         $inventory_prodrel_desc = $this->db->query_result($result, $i - 1, "description");
         $qtyinstock = $this->db->query_result($result, $i - 1, "qtyinstock");
         $qty = $this->db->query_result($result, $i - 1, "quantity");
         $qty_per_unit = $this->db->query_result($result, $i - 1, "qty_per_unit");
         $usageunit = $this->db->query_result($result, $i - 1, "usageunit");
         $unitprice = $this->db->query_result($result, $i - 1, "unit_price");
         $listprice = $this->db->query_result($result, $i - 1, "listprice");
         $total = $qty * $listprice;
         $discount_percent = $this->db->query_result($result, $i - 1, "discount_percent");
         $discount_amount = $this->db->query_result($result, $i - 1, "discount_amount");
         $totalAfterDiscount = $total;
         $productDiscount = "0.00";
         $productDiscountPercent = "";
         if ($discount_percent != "NULL" && $discount_percent != "") {
             $productDiscount = $total * $discount_percent / 100;
             $totalAfterDiscount = $total - $productDiscount;
             $productDiscountPercent = $discount_percent;
         } elseif ($discount_amount != "NULL" && $discount_amount != "") {
             $productDiscount = $discount_amount;
             $totalAfterDiscount = $total - $productDiscount;
         }
         $netprice = $totalAfterDiscount;
         if ($taxtype == "individual") {
             $taxtotal = "0.00";
             $tax_info_message = $mod_strings["LBL_TOTAL_AFTER_DISCOUNT"] . " = {$totalAfterDiscount} \\n";
             $tax_details = getTaxDetailsForProduct($productid, "all");
             $Tax_Values = array();
             for ($tax_count = 0; $tax_count < $x0f($tax_details); $tax_count++) {
                 $tax_name = $tax_details[$tax_count]["taxname"];
                 $tax_label = $tax_details[$tax_count]["taxlabel"];
                 $tax_value = getInventoryProductTaxValue($this->focus->id, $productid, $tax_name);
                 $individual_taxamount = $totalAfterDiscount * $tax_value / 100;
                 $taxtotal = $taxtotal + $individual_taxamount;
                 if ($tax_name != "" && $tax_value > 0) {
                     $vatblock[$tax_name . "-" . $tax_value]["label"] = $tax_label;
                     $vatblock[$tax_name . "-" . $tax_value]["netto"] += $totalAfterDiscount;
                     $vatblock[$tax_name . "-" . $tax_value]["vat"] += $x1c($individual_taxamount, $this->decimals);
                     $vatblock[$tax_name . "-" . $tax_value]["value"] = $tax_value;
                     $x0c($Tax_Values, $tax_value);
                     $x0c($Total_Tax_Values, $tax_value);
                 }
                 $netprice = $netprice + $taxtotal;
             }
             if ($x0f($Tax_Values) > 0) {
                 $tax_avg_value = $x0e($Tax_Values);
             } else {
                 $tax_avg_value = "0.00";
             }
             $Details["P"][$i]["PRODUCTVATPERCENT"] = $this->x1e($tax_avg_value);
             $Details["P"][$i]["PRODUCTVATSUM"] = $this->x1e($taxtotal);
         }
         if ($entitytype == "Products") {
             $Details["P"][$i]["PRODUCTS_CRMID"] = $psid;
             $Details["P"][$i]["SERVICES_CRMID"] = "";
         } else {
             $Details["P"][$i]["PRODUCTS_CRMID"] = "";
             $Details["P"][$i]["SERVICES_CRMID"] = $psid;
         }
         $Details["P"][$i]["PS_CRMID"] = $psid;
         $Details["P"][$i]["PS_NO"] = $psno;
         if ($comment != "") {
             $comment = $x1e("\\n", "<br>", $x1a($comment));
             $comment = $x14($comment, ENT_QUOTES, "utf-8");
             $productname .= "<br /><small>" . $comment . "</small>";
         }
         $Details["P"][$i]["PRODUCTNAME"] = $productname;
         $Details["P"][$i]["PRODUCTTITLE"] = $producttitle;
         $psdescription = $x1e("\\n", "<br>", $x1a($psdescription));
         $Details["P"][$i]["PRODUCTDESCRIPTION"] = $x14($psdescription, ENT_QUOTES, "utf-8");
         $Details["P"][$i]["PRODUCTEDITDESCRIPTION"] = $comment;
         $inventory_prodrel_desc = $x1e("\\n", "<br>", $x1a($inventory_prodrel_desc));
         $Details["P"][$i]["CRMNOWPRODUCTDESCRIPTION"] = $x14($inventory_prodrel_desc, ENT_QUOTES, "utf-8");
         $Details["P"][$i]["PRODUCTLISTPRICE"] = $this->x1e($listprice);
         $Details["P"][$i]["PRODUCTTOTAL"] = $this->x1e($total);
         $Details["P"][$i]["PRODUCTQUANTITY"] = $this->x1e($qty);
         $Details["P"][$i]["PRODUCTQINSTOCK"] = $this->x1e($qtyinstock);
         $Details["P"][$i]["PRODUCTPRICE"] = $this->x1e($unitprice);
         $Details["P"][$i]["PRODUCTPOSITION"] = $i;
         $Details["P"][$i]["PRODUCTQTYPERUNIT"] = $this->x1e($qty_per_unit);
         $Details["P"][$i]["PRODUCTUSAGEUNIT"] = $this->x1b($usageunit, "Products/Services");
         $Details["P"][$i]["PRODUCTDISCOUNT"] = $this->x1e($productDiscount);
         $Details["P"][$i]["PRODUCTDISCOUNTPERCENT"] = $this->x1e($productDiscountPercent);
         $Details["P"][$i]["PRODUCTSTOTALAFTERDISCOUNTSUM"] = $totalAfterDiscount;
         $Details["P"][$i]["PRODUCTSTOTALAFTERDISCOUNT"] = $this->x1e($totalAfterDiscount);
         $Details["P"][$i]["PRODUCTTOTALSUM"] = $this->x1e($totalAfterDiscount + $taxtotal);
         $totalAfterDiscount_subtotal += $totalAfterDiscount;
         $total_subtotal += $total;
         $totalsum_subtotal += $totalAfterDiscount + $taxtotal;
         $Details["P"][$i]["PRODUCTSTOTALAFTERDISCOUNT_SUBTOTAL"] = $this->x1e($totalAfterDiscount_subtotal);
         $Details["P"][$i]["PRODUCTTOTAL_SUBTOTAL"] = $this->x1e($total_subtotal);
         $Details["P"][$i]["PRODUCTTOTALSUM_SUBTOTAL"] = $this->x1e($totalsum_subtotal);
         $sequence = $this->db->query_result($result, $i - 1, "sequence_no");
         $Details["P"][$i]["PRODUCTSEQUENCE"] = $sequence;
         if (isset($images[$productid . "_" . $sequence])) {
             $width = "";
             $height = "";
             if ($images[$productid . "_" . $sequence]["width"] > 0) {
                 $width = " width='" . $images[$productid . "_" . $sequence]["width"] . "' ";
             }
             if ($images[$productid . "_" . $sequence]["height"] > 0) {
                 $height = " height='" . $images[$productid . "_" . $sequence]["height"] . "' ";
             }
             $Details["P"][$i]["PRODUCTS_IMAGENAME"] = "<img src='" . $this->site_url . "/" . $images[$productid . "_" . $sequence]["src"] . "' " . $width . $height . "/>";
         }
         $focus_p = CRMEntity::getInstance("Products");
         if ($entitytype == "Products" && $psid != "") {
             $focus_p->id = $psid;
             $this->x1f($focus_p, $psid, "Products");
         }
         $Array_P = $this->x0e("Products", $focus_p, false, true);
         $Details["P"][$i] = $x0d($Array_P, $Details["P"][$i]);
         unset($focus_p);
         $focus_s = CRMEntity::getInstance("Services");
         if ($entitytype == "Services" && $psid != "") {
             $focus_s->id = $psid;
             $this->x1f($focus_s, $psid, "Services");
         }
         $Array_S = $this->x0e("Services", $focus_s, false, true);
         $Details["P"][$i] = $x0d($Array_S, $Details["P"][$i]);
         unset($focus_s);
         $sumwithoutvat += $totalAfterDiscount;
         $netTotal = $netTotal + $netprice;
     }
     $finalDiscount = "0.00";
     $final_discount_info = "0";
     $finalDiscountPercent = "";
     if ($this->focus->column_fields["hdnDiscountPercent"] != "0") {
         $finalDiscount = $netTotal * $this->focus->column_fields["hdnDiscountPercent"] / 100;
         $finalDiscountPercent = $this->focus->column_fields["hdnDiscountPercent"];
     } elseif ($this->focus->column_fields["hdnDiscountAmount"] != "0") {
         $finalDiscount = $this->focus->column_fields["hdnDiscountAmount"];
     }
     $taxtotal = "0.00";
     if ($taxtype == "group") {
         $final_totalAfterDiscount = $netTotal - $finalDiscount;
         $tax_details = getAllTaxes("available", "", "edit", $this->focus->id);
         for ($tax_count = 0; $tax_count < $x0f($tax_details); $tax_count++) {
             $tax_name = $tax_details[$tax_count]["taxname"];
             $tax_label = $tax_details[$tax_count]["taxlabel"];
             $tax_value = $this->db->query_result($result, 0, $tax_name);
             if ($tax_value == "" || $tax_value == "NULL") {
                 $tax_value = "0.00";
             }
             $taxamount = ($netTotal - $finalDiscount) * $tax_value / 100;
             $taxtotal = $taxtotal + $taxamount;
             if ($tax_name != "" && $tax_value > 0) {
                 $vatblock[$tax_name]["label"] = $tax_label;
                 $vatblock[$tax_name]["netto"] = $final_totalAfterDiscount;
                 $vatblock[$tax_name]["vat"] += $taxamount;
                 $vatblock[$tax_name]["value"] = $tax_value;
             }
             $total_vat_percent += $tax_value;
         }
         $vat_value = $taxtotal;
         foreach ($Details["P"] as $keyP => $valueP) {
             $productvatsum = $Details["P"][$keyP]["PRODUCTSTOTALAFTERDISCOUNTSUM"] * $total_vat_percent / 100;
             $producttotalsum = $Details["P"][$keyP]["PRODUCTSTOTALAFTERDISCOUNTSUM"] + $productvatsum;
             $Details["P"][$keyP]["PRODUCTVATPERCENT"] = $this->x1e($total_vat_percent);
             $Details["P"][$keyP]["PRODUCTVATSUM"] = $this->x1e($productvatsum);
             $Details["P"][$keyP]["PRODUCTTOTALSUM"] = $this->x1e($producttotalsum);
         }
     } else {
         if ($x0f($vatblock) > 0) {
             foreach ($vatblock as $keyM => $valueM) {
                 $vat_value += $valueM["vat"];
             }
         } else {
             $vat_value = "0.00";
         }
     }
     $shAmount = $this->focus->column_fields["hdnS_H_Amount"] != "" ? $this->focus->column_fields["hdnS_H_Amount"] : "0.00";
     $shtaxtotal = "0.00";
     $shtax_details = getAllTaxes("available", "sh", "edit", $this->focus->id);
     for ($shtax_count = 0; $shtax_count < $x0f($shtax_details); $shtax_count++) {
         $shtax_name = $shtax_details[$shtax_count]["taxname"];
         $shtax_label = $shtax_details[$shtax_count]["taxlabel"];
         $shtax_percent = getInventorySHTaxPercent($this->focus->id, $shtax_name);
         $shtaxamount = $shAmount * $shtax_percent / 100;
         $shtaxtotal = $shtaxtotal + $shtaxamount;
     }
     $totalafterdiscount = $sumwithoutvat - $finalDiscount;
     $totalwithvat = $sumwithoutvat - $finalDiscount + $vat_value;
     $Details["TOTAL"]["NETTOTAL"] = $this->x1e($netTotal);
     $Details["TOTAL"]["TOTALWITHOUTVAT"] = $this->x1e($sumwithoutvat);
     $Details["TOTAL"]["FINALDISCOUNT"] = $this->x1e($finalDiscount);
     $Details["TOTAL"]["FINALDISCOUNTPERCENT"] = $this->x1e($finalDiscountPercent);
     $Details["TOTAL"]["TOTALAFTERDISCOUNT"] = $this->x1e($totalafterdiscount);
     $Details["TOTAL"]["TAXTOTAL"] = $this->x1e($vat_value);
     $Details["TOTAL"]["TAXTOTALPERCENT"] = $this->x1e($total_vat_percent);
     $Details["TOTAL"]["TOTALWITHVAT"] = $this->x1e($totalwithvat);
     $Details["TOTAL"]["SHTAXAMOUNT"] = $this->x1e($shAmount);
     $Details["TOTAL"]["SHTAXTOTAL"] = $this->x1e($shtaxtotal);
     $Details["TOTAL"]["VATBLOCK"] = $vatblock;
     return $Details;
 }
Example #18
0
 /**
  * Function to get all taxes
  * @return <Array> List of taxes
  */
 public function getAllTaxes()
 {
     $allTaxesList = $this->get('alltaxes');
     if (!empty($allTaxesList)) {
         return $allTaxesList;
     }
     $allTaxesList = getAllTaxes('available');
     $noOfTaxes = count($allTaxesList);
     for ($i = 0; $i < $noOfTaxes; $i++) {
         $allTaxesList[$i]['check_name'] = $allTaxesList[$i]['taxname'] . '_check';
         $allTaxesList[$i]['check_value'] = 0;
     }
     $this->set('alltaxes', $allTaxesList);
     return $allTaxesList;
 }
Example #19
0
 static function getAllShippingTaxes()
 {
     return getAllTaxes('available', 'sh');
 }
Example #20
0
 static function getAllProductTaxes()
 {
     return getAllTaxes('available');
 }
Example #21
0
/** This function returns a HTML output of associated vtiger_products for a given entity (Quotes,Invoice,Sales order or Purchase order)
 * Param $module - module name
 * Param $focus - module object
 * Return type string
 */
function getDetailAssociatedProducts($module, $focus)
{
    global $log;
    $log->debug("Entering getDetailAssociatedProducts(" . $module . "," . get_class($focus) . ") method ...");
    global $adb;
    global $mod_strings;
    global $theme;
    global $log;
    global $app_strings, $current_user;
    $theme_path = "themes/" . $theme . "/";
    $image_path = $theme_path . "images/";
    if (vtlib_isModuleActive("Products")) {
        $hide_stock = 'no';
    } else {
        $hide_stock = 'yes';
    }
    if ($module != 'PurchaseOrder') {
        if (GlobalVariable::getVariable('B2B', '1') == '1') {
            $acvid = $focus->column_fields['account_id'];
        } else {
            $acvid = $focus->column_fields['contact_id'];
        }
        if ($hide_stock == 'no') {
            $colspan = '2';
        } else {
            $colspan = '1';
        }
    } else {
        $acvid = $focus->column_fields['vendor_id'];
        $colspan = '1';
    }
    //Get the taxtype of this entity
    $taxtype = getInventoryTaxType($module, $focus->id);
    $currencytype = getInventoryCurrencyInfo($module, $focus->id);
    $output = '';
    //Header Rows
    $output .= '

	<table width="100%"  border="0" align="center" cellpadding="5" cellspacing="0" class="crmTable" id="proTab">
	   <tr valign="top">
	   	<td colspan="' . $colspan . '" class="dvInnerHeader"><b>' . $app_strings['LBL_ITEM_DETAILS'] . '</b></td>
		<td class="dvInnerHeader" align="center" colspan="2"><b>' . $app_strings['LBL_CURRENCY'] . ' : </b>' . getTranslatedCurrencyString($currencytype['currency_name']) . ' (' . $currencytype['currency_symbol'] . ')
		</td>
		<td class="dvInnerHeader" align="center" colspan="2"><b>' . $app_strings['LBL_TAX_MODE'] . ' : </b>' . $app_strings[$taxtype] . '
		</td>
	   </tr>
	   <tr valign="top">
		<td width=40% class="lvtCol"><font color="red">*</font>
			<b>' . $app_strings['LBL_ITEM_NAME'] . '</b>
		</td>';
    //Add Quantity in Stock column for SO, Quotes and Invoice
    if (($module == 'Quotes' || $module == 'SalesOrder' || $module == 'Invoice') && $hide_stock == 'no') {
        $output .= '<td width=10% class="lvtCol"><b>' . $app_strings['LBL_QTY_IN_STOCK'] . '</b></td>';
    }
    $output .= '

		<td width=10% class="lvtCol"><b>' . $app_strings['LBL_QTY'] . '</b></td>
		<td width=10% class="lvtCol" align="right"><b>' . $app_strings['LBL_LIST_PRICE'] . '</b></td>
		<td width=12% nowrap class="lvtCol" align="right"><b>' . $app_strings['LBL_TOTAL'] . '</b></td>
		<td width=13% valign="top" class="lvtCol" align="right"><b>' . $app_strings['LBL_NET_PRICE'] . '</b></td>
	   </tr>
	   	';
    // DG 15 Aug 2006
    // Add "ORDER BY sequence_no" to retain add order on all inventoryproductrel items
    if ($module == 'Quotes' || $module == 'PurchaseOrder' || $module == 'SalesOrder' || $module == 'Invoice') {
        $query = "select case when vtiger_products.productid != '' then vtiger_products.productname else vtiger_service.servicename end as productname," . " case when vtiger_products.productid != '' then 'Products' else 'Services' end as entitytype," . " case when vtiger_products.productid != '' then vtiger_products.unit_price else vtiger_service.unit_price end as unit_price," . " case when vtiger_products.productid != '' then vtiger_products.qtyinstock else 'NA' end as qtyinstock, vtiger_inventoryproductrel.* " . " from vtiger_inventoryproductrel" . " left join vtiger_products on vtiger_products.productid=vtiger_inventoryproductrel.productid " . " left join vtiger_service on vtiger_service.serviceid=vtiger_inventoryproductrel.productid " . " where id=? ORDER BY sequence_no";
    }
    $result = $adb->pquery($query, array($focus->id));
    $num_rows = $adb->num_rows($result);
    $netTotal = '0.00';
    for ($i = 1; $i <= $num_rows; $i++) {
        $sub_prod_query = $adb->pquery("SELECT productid from vtiger_inventorysubproductrel WHERE id=? AND sequence_no=?", array($focus->id, $i));
        $subprodname_str = '';
        if ($adb->num_rows($sub_prod_query) > 0) {
            for ($j = 0; $j < $adb->num_rows($sub_prod_query); $j++) {
                $sprod_id = $adb->query_result($sub_prod_query, $j, 'productid');
                $sprod_name = getProductName($sprod_id);
                $str_sep = "";
                if ($j > 0) {
                    $str_sep = ":";
                }
                $subprodname_str .= $str_sep . " - " . $sprod_name;
            }
        }
        $subprodname_str = str_replace(":", "<br>", $subprodname_str);
        $productid = $adb->query_result($result, $i - 1, 'productid');
        $entitytype = $adb->query_result($result, $i - 1, 'entitytype');
        $productname = $adb->query_result($result, $i - 1, 'productname');
        $productname = '<a href="index.php?action=DetailView&record=' . $productid . '&module=' . $entitytype . '">' . $productname . '</a>';
        if ($subprodname_str != '') {
            $productname .= "<br/><span style='color:#C0C0C0;font-style:italic;'>" . $subprodname_str . "</span>";
        }
        $comment = $adb->query_result($result, $i - 1, 'comment');
        $qtyinstock = $adb->query_result($result, $i - 1, 'qtyinstock');
        $qty = $adb->query_result($result, $i - 1, 'quantity');
        $qty = number_format($qty, 2, '.', '');
        //Convert to 2 decimals
        $unitprice = $adb->query_result($result, $i - 1, 'unit_price');
        $listprice = $adb->query_result($result, $i - 1, 'listprice');
        $total = $qty * $listprice;
        $listprice = number_format($listprice, 2, '.', '');
        //Convert to 2 decimals
        //Product wise Discount calculation - starts
        $discount_percent = $adb->query_result($result, $i - 1, 'discount_percent');
        $discount_amount = $adb->query_result($result, $i - 1, 'discount_amount');
        $totalAfterDiscount = $total;
        $productDiscount = '0.00';
        if ($discount_percent != 'NULL' && $discount_percent != '') {
            $productDiscount = $total * $discount_percent / 100;
            $productDiscount = number_format($productDiscount, 2, '.', '');
            $totalAfterDiscount = $total - $productDiscount;
            //if discount is percent then show the percentage
            $discount_info_message = "{$discount_percent} % of " . CurrencyField::convertToUserFormat($total, null, true) . " = " . CurrencyField::convertToUserFormat($productDiscount, null, true);
        } elseif ($discount_amount != 'NULL' && $discount_amount != '') {
            $productDiscount = $discount_amount;
            $productDiscount = number_format($productDiscount, 2, '.', '');
            $totalAfterDiscount = $total - $productDiscount;
            $discount_info_message = $app_strings['LBL_DIRECT_AMOUNT_DISCOUNT'] . " = " . CurrencyField::convertToUserFormat($productDiscount, null, true);
        } else {
            $discount_info_message = $app_strings['LBL_NO_DISCOUNT_FOR_THIS_LINE_ITEM'];
        }
        //Product wise Discount calculation - ends
        $totalAfterDiscount = number_format($totalAfterDiscount, 2, '.', '');
        //Convert to 2 decimals
        $netprice = $totalAfterDiscount;
        //Calculate the individual tax if taxtype is individual
        if ($taxtype == 'individual') {
            $taxtotal = '0.00';
            $tax_info_message = $app_strings['LBL_TOTAL_AFTER_DISCOUNT'] . " = " . CurrencyField::convertToUserFormat($totalAfterDiscount, null, true) . " \\n";
            $tax_details = getTaxDetailsForProduct($productid, 'all', $acvid);
            for ($tax_count = 0; $tax_count < count($tax_details); $tax_count++) {
                $tax_name = $tax_details[$tax_count]['taxname'];
                $tax_label = $tax_details[$tax_count]['taxlabel'];
                $tax_value = getInventoryProductTaxValue($focus->id, $productid, $tax_name);
                $individual_taxamount = $totalAfterDiscount * $tax_value / 100;
                $individual_taxamount = number_format($individual_taxamount, 2, '.', '');
                //Convert to 2 decimals
                $taxtotal = $taxtotal + $individual_taxamount;
                $taxtotal = number_format($taxtotal, 2, '.', '');
                //Convert to 2 decimals
                $tax_info_message .= "{$tax_label} : {$tax_value} % = " . CurrencyField::convertToUserFormat($individual_taxamount, null, true) . " \\n";
            }
            $tax_info_message .= "\\n " . $app_strings['LBL_TOTAL_TAX_AMOUNT'] . " = " . CurrencyField::convertToUserFormat($taxtotal, null, true);
            $netprice = $netprice + $taxtotal;
            $netprice = number_format($netprice, 2, '.', '');
            //Convert to 2 decimals
        }
        $sc_image_tag = '';
        if ($module == 'Invoice') {
            switch ($entitytype) {
                case 'Services':
                    if (vtlib_isModuleActive('ServiceContracts')) {
                        $sc_image_tag = '<a href="index.php?module=ServiceContracts&action=EditView&service_id=' . $productid . '&sc_related_to=' . $focus->column_fields['account_id'] . '&start_date=' . DateTimeField::convertToUserFormat($focus->column_fields['invoicedate']) . '&return_module=' . $module . '&return_id=' . $focus->id . '">' . '<img border="0" src="' . vtiger_imageurl('handshake.gif', $theme) . '" title="' . getTranslatedString('LBL_ADD_NEW', $module) . " " . getTranslatedString('ServiceContracts', 'ServiceContracts') . '" style="cursor: pointer;" align="absmiddle" />' . '</a>';
                    }
                    break;
                case 'Products':
                    if (vtlib_isModuleActive('Assets')) {
                        $sc_image_tag = '<a href="index.php?module=Assets&action=EditView&invoiceid=' . $focus->id . '&product=' . $productid . '&account=' . $focus->column_fields['account_id'] . '&datesold=' . DateTimeField::convertToUserFormat($focus->column_fields['invoicedate']) . '&return_module=' . $module . '&return_id=' . $focus->id . '" onmouseout="vtlib_listview.trigger(\'invoiceasset.onmouseout\', $(this))" onmouseover="vtlib_listview.trigger(\'cell.onmouseover\', $(this))">' . '<img border="0" src="' . vtiger_imageurl('barcode.png', $theme) . '" title="' . getTranslatedString('LBL_ADD_NEW', $module) . " " . getTranslatedString('Assets', 'Assets') . '" style="cursor: pointer;" align="absmiddle" />' . '<span style="display:none;" vtmodule="Assets" vtfieldname="invoice_product" vtrecordid="' . $focus->id . '::' . $productid . '::' . $i . '" type="vtlib_metainfo"></span>' . '</a>';
                    }
                    break;
                default:
                    $sc_image_tag = '';
            }
        }
        //For Product Name
        $output .= '
			   <tr valign="top">
				<td class="crmTableRow small lineOnTop">
					' . $productname . '&nbsp;' . $sc_image_tag . '
					<br>' . $comment . '
				</td>';
        //Upto this added to display the Product name and comment
        if ($module != 'PurchaseOrder' && $hide_stock == 'no') {
            $output .= '<td class="crmTableRow small lineOnTop">' . $qtyinstock . '</td>';
        }
        $output .= '<td class="crmTableRow small lineOnTop">' . $qty . '</td>';
        $output .= '
			<td class="crmTableRow small lineOnTop" align="right">
				<table width="100%" border="0" cellpadding="5" cellspacing="0">
				   <tr>
				   	<td align="right">' . CurrencyField::convertToUserFormat($listprice, null, true) . '</td>
				   </tr>
				   <tr>
					   <td align="right">(-)&nbsp;<b><a href="javascript:;" onclick="alert(\'' . $discount_info_message . '\'); ">' . $app_strings['LBL_DISCOUNT'] . ' : </a></b></td>
				   </tr>
				   <tr>
				   	<td align="right" nowrap>' . $app_strings['LBL_TOTAL_AFTER_DISCOUNT'] . ' : </td>
				   </tr>';
        if ($taxtype == 'individual') {
            $output .= '
				   <tr>
					   <td align="right" nowrap>(+)&nbsp;<b><a href="javascript:;" onclick="alert(\'' . $tax_info_message . '\');">' . $app_strings['LBL_TAX'] . ' : </a></b></td>
				   </tr>';
        }
        $output .= '
				</table>
			</td>';
        $output .= '
			<td class="crmTableRow small lineOnTop" align="right">
				<table width="100%" border="0" cellpadding="5" cellspacing="0">
				   <tr><td align="right">' . CurrencyField::convertToUserFormat($total, null, true) . '</td></tr>
				   <tr><td align="right">' . CurrencyField::convertToUserFormat($productDiscount, null, true) . '</td></tr>
				   <tr><td align="right" nowrap>' . CurrencyField::convertToUserFormat($totalAfterDiscount, null, true) . '</td></tr>';
        if ($taxtype == 'individual') {
            $output .= '<tr><td align="right" nowrap>' . CurrencyField::convertToUserFormat($taxtotal, null, true) . '</td></tr>';
        }
        $output .= '
				</table>
			</td>';
        $output .= '<td class="crmTableRow small lineOnTop" valign="bottom" align="right">' . CurrencyField::convertToUserFormat($netprice, null, true) . '</td>';
        $output .= '</tr>';
        $netTotal = $netTotal + $netprice;
    }
    $output .= '</table>';
    //$netTotal should be equal to $focus->column_fields['hdnSubTotal']
    $netTotal = $focus->column_fields['hdnSubTotal'];
    $netTotal = number_format($netTotal, 2, '.', '');
    //Convert to 2 decimals
    //Display the total, adjustment, S&H details
    $output .= '<table width="100%" border="0" cellspacing="0" cellpadding="5" class="crmTable">';
    $output .= '<tr>';
    $output .= '<td width="88%" class="crmTableRow small" align="right"><b>' . $app_strings['LBL_NET_TOTAL'] . '</td>';
    $output .= '<td width="12%" class="crmTableRow small" align="right"><b>' . CurrencyField::convertToUserFormat($netTotal, null, true) . '</b></td>';
    $output .= '</tr>';
    //Decide discount
    $finalDiscount = '0.00';
    $final_discount_info = '0';
    //if($focus->column_fields['hdnDiscountPercent'] != '') - previously (before changing to prepared statement) the selected option (either percent or amount) will have value and the other remains empty. So we can find the non selected item by empty check. But now with prepared statement, the non selected option stored as 0
    if ($focus->column_fields['hdnDiscountPercent'] != '0') {
        $finalDiscount = $netTotal * $focus->column_fields['hdnDiscountPercent'] / 100;
        $finalDiscount = number_format($finalDiscount, 2, '.', '');
        $final_discount_info = $focus->column_fields['hdnDiscountPercent'] . " % of " . CurrencyField::convertToUserFormat($netTotal, null, true) . " = " . CurrencyField::convertToUserFormat($finalDiscount, null, true);
    } elseif ($focus->column_fields['hdnDiscountAmount'] != '0') {
        $finalDiscount = $focus->column_fields['hdnDiscountAmount'];
        $finalDiscount = number_format($finalDiscount, 2, '.', '');
        $final_discount_info = CurrencyField::convertToUserFormat($finalDiscount, null, true);
    }
    //Alert the Final Discount amount even it is zero
    $final_discount_info = $app_strings['LBL_FINAL_DISCOUNT_AMOUNT'] . " = {$final_discount_info}";
    $final_discount_info = 'onclick="alert(\'' . $final_discount_info . '\');"';
    $output .= '<tr>';
    $output .= '<td align="right" class="crmTableRow small lineOnTop">(-)&nbsp;<b><a href="javascript:;" ' . $final_discount_info . '>' . $app_strings['LBL_DISCOUNT'] . '</a></b></td>';
    $output .= '<td align="right" class="crmTableRow small lineOnTop">' . CurrencyField::convertToUserFormat($finalDiscount, null, true) . '</td>';
    $output .= '</tr>';
    if ($taxtype == 'group') {
        $taxtotal = '0.00';
        $final_totalAfterDiscount = $netTotal - $finalDiscount;
        $tax_info_message = $app_strings['LBL_TOTAL_AFTER_DISCOUNT'] . " = " . CurrencyField::convertToUserFormat($final_totalAfterDiscount, null, true) . " \\n";
        //First we should get all available taxes and then retrieve the corresponding tax values
        $tax_details = getAllTaxes('available', '', 'edit', $focus->id);
        $ipr_cols = $adb->getColumnNames('vtiger_inventoryproductrel');
        //if taxtype is group then the tax should be same for all products in vtiger_inventoryproductrel table
        for ($tax_count = 0; $tax_count < count($tax_details); $tax_count++) {
            $tax_name = $tax_details[$tax_count]['taxname'];
            $tax_label = $tax_details[$tax_count]['taxlabel'];
            if (in_array($tax_name, $ipr_cols)) {
                $tax_value = $adb->query_result($result, 0, $tax_name);
            } else {
                $tax_value = $tax_details[$tax_count]['percentage'];
            }
            if ($tax_value == '' || $tax_value == 'NULL') {
                $tax_value = '0.00';
            }
            $taxamount = ($netTotal - $finalDiscount) * $tax_value / 100;
            $taxtotal = $taxtotal + $taxamount;
            $tax_info_message .= "{$tax_label} : {$tax_value} % = " . CurrencyField::convertToUserFormat($taxtotal, null, true) . " \\n";
        }
        $tax_info_message .= "\\n " . $app_strings['LBL_TOTAL_TAX_AMOUNT'] . " = " . CurrencyField::convertToUserFormat($taxtotal, null, true);
        $output .= '<tr>';
        $output .= '<td align="right" class="crmTableRow small">(+)&nbsp;<b><a href="javascript:;" onclick="alert(\'' . $tax_info_message . '\');">' . $app_strings['LBL_TAX'] . '</a></b></td>';
        $output .= '<td align="right" class="crmTableRow small">' . CurrencyField::convertToUserFormat($taxtotal, null, true) . '</td>';
        $output .= '</tr>';
    }
    $shAmount = $focus->column_fields['hdnS_H_Amount'] != '' ? $focus->column_fields['hdnS_H_Amount'] : '0.00';
    $shAmount = number_format($shAmount, 2, '.', '');
    //Convert to 2 decimals
    $output .= '<tr>';
    $output .= '<td align="right" class="crmTableRow small">(+)&nbsp;<b>' . $app_strings['LBL_SHIPPING_AND_HANDLING_CHARGES'] . '</b></td>';
    $output .= '<td align="right" class="crmTableRow small">' . CurrencyField::convertToUserFormat($shAmount, null, true) . '</td>';
    $output .= '</tr>';
    //calculate S&H tax
    $shtaxtotal = '0.00';
    //First we should get all available taxes and then retrieve the corresponding tax values
    $shtax_details = getAllTaxes('available', 'sh', 'edit', $focus->id);
    //if taxtype is group then the tax should be same for all products in vtiger_inventoryproductrel table
    $shtax_info_message = $app_strings['LBL_SHIPPING_AND_HANDLING_CHARGE'] . " = " . CurrencyField::convertToUserFormat($shAmount, null, true) . "\\n";
    for ($shtax_count = 0; $shtax_count < count($shtax_details); $shtax_count++) {
        $shtax_name = $shtax_details[$shtax_count]['taxname'];
        $shtax_label = $shtax_details[$shtax_count]['taxlabel'];
        $shtax_percent = getInventorySHTaxPercent($focus->id, $shtax_name);
        $shtaxamount = $shAmount * $shtax_percent / 100;
        $shtaxamount = number_format($shtaxamount, 2, '.', '');
        $shtaxtotal = $shtaxtotal + $shtaxamount;
        $shtax_info_message .= "{$shtax_label} : {$shtax_percent} % = " . CurrencyField::convertToUserFormat($shtaxamount, null, true) . " \\n";
    }
    $shtax_info_message .= "\\n " . $app_strings['LBL_TOTAL_TAX_AMOUNT'] . " = " . CurrencyField::convertToUserFormat($shtaxtotal, null, true);
    $output .= '<tr>';
    $output .= '<td align="right" class="crmTableRow small">(+)&nbsp;<b><a href="javascript:;" onclick="alert(\'' . $shtax_info_message . '\')">' . $app_strings['LBL_TAX_FOR_SHIPPING_AND_HANDLING'] . '</a></b></td>';
    $output .= '<td align="right" class="crmTableRow small">' . CurrencyField::convertToUserFormat($shtaxtotal, null, true) . '</td>';
    $output .= '</tr>';
    $adjustment = $focus->column_fields['txtAdjustment'] != '' ? $focus->column_fields['txtAdjustment'] : '0.00';
    $adjustment = number_format($adjustment, 2, '.', '');
    //Convert to 2 decimals
    $output .= '<tr>';
    $output .= '<td align="right" class="crmTableRow small">&nbsp;<b>' . $app_strings['LBL_ADJUSTMENT'] . '</b></td>';
    $output .= '<td align="right" class="crmTableRow small">' . CurrencyField::convertToUserFormat($adjustment, null, true) . '</td>';
    $output .= '</tr>';
    $grandTotal = $focus->column_fields['hdnGrandTotal'] != '' ? $focus->column_fields['hdnGrandTotal'] : '0.00';
    $grandTotal = number_format($grandTotal, 2, '.', '');
    //Convert to 2 decimals
    $output .= '<tr>';
    $output .= '<td align="right" class="crmTableRow small lineOnTop"><b>' . $app_strings['LBL_GRAND_TOTAL'] . '</b></td>';
    $output .= '<td align="right" class="crmTableRow small lineOnTop">' . CurrencyField::convertToUserFormat($grandTotal, null, true) . '</td>';
    $output .= '</tr>';
    $output .= '</table>';
    $log->debug("Exiting getDetailAssociatedProducts method ...");
    return $output;
}
Example #22
0
 function getAssociatedProducts($module, $focus, $seid = '')
 {
     $adb = PearDatabase::getInstance();
     $current_user = vglobal('current_user');
     $log = vglobal('log');
     $theme = vglobal('theme');
     $log->debug("Entering OSSCosts_Record_Model getAssociatedProducts(" . $module . "," . get_class($focus) . "," . $seid . "='') method ...");
     $output = '';
     $no_of_decimal_places = getCurrencyDecimalPlaces();
     $theme_path = "themes/" . $theme . "/";
     $image_path = $theme_path . "images/";
     $product_Detail = array();
     if ($module == 'OSSCosts') {
         $query = "SELECT\n\t\t\t\t\t\tcase when vtiger_products.productid != '' then vtiger_products.productname else vtiger_service.servicename end as productname,\n\t\t\t\t\t\tcase when vtiger_products.productid != '' then vtiger_products.productcode else vtiger_service.service_no end as productcode,\n\t\t\t\t\t\tcase when vtiger_products.productid != '' then vtiger_products.unit_price else vtiger_service.unit_price end as unit_price,\n\t\t\t\t\t\tcase when vtiger_products.productid != '' then vtiger_products.qtyinstock else 'NA' end as qtyinstock,\n\t\t\t\t\t\tcase when vtiger_products.productid != '' then 'Products' else 'Services' end as entitytype,\n\t\t\t\t\t\t\t\t\tvtiger_inventoryproductrel.listprice,\n\t\t\t\t\t\t\t\t\tvtiger_inventoryproductrel.description AS product_description,\n\t\t\t\t\t\t\t\t\tvtiger_inventoryproductrel.*,vtiger_crmentity.deleted,\n\t\t\t\t\t\t\t\t\tvtiger_products.usageunit,\n\t\t\t\t\t\t\t\t\tvtiger_service.service_usageunit\n\t\t\t\t\t\t\t\t\tFROM vtiger_inventoryproductrel\n\t\t\t\t\t\t\t\t\tLEFT JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_inventoryproductrel.productid\n\t\t\t\t\t\t\t\t\tLEFT JOIN vtiger_products\n\t\t\t\t\t\t\t\t\t\t\tON vtiger_products.productid=vtiger_inventoryproductrel.productid\n\t\t\t\t\t\t\t\t\tLEFT JOIN vtiger_service\n\t\t\t\t\t\t\t\t\t\t\tON vtiger_service.serviceid=vtiger_inventoryproductrel.productid\n\t\t\t\t\t\t\t\t\tWHERE id=?\n\t\t\t\t\t\t\t\t\tORDER BY sequence_no";
         $params = array($focus->id);
     } elseif ($module == 'Products') {
         $query = "SELECT\n\t\t\t\t\t\t\t\t\tvtiger_products.productid,\n\t\t\t\t\t\t\t\t\tvtiger_products.productcode,\n\t\t\t\t\t\t\t\t\tvtiger_products.productname,\n\t\t\t\t\t\t\t\t\tvtiger_products.unit_price,\n\t\t\t\t\t\t\t\t\tvtiger_products.usageunit,\n\t\t\t\t\t\t\t\t\tvtiger_products.qtyinstock,vtiger_crmentity.deleted,\n\t\t\t\t\t\t\t\t\tvtiger_crmentity.description AS product_description,\n\t\t\t\t\t\t\t\t\t'Products' AS entitytype\n\t\t\t\t\t\t\t\t\tFROM vtiger_products\n\t\t\t\t\t\t\t\t\tINNER JOIN vtiger_crmentity\n\t\t\t\t\t\t\t\t\t\t\tON vtiger_crmentity.crmid=vtiger_products.productid\n\t\t\t\t\t\t\t\t\tWHERE vtiger_crmentity.deleted=0\n\t\t\t\t\t\t\t\t\t\t\tAND productid=?";
         $params = array($seid);
     } elseif ($module == 'Services') {
         $query = "SELECT\n\t\t\t\t\t\t\t\t\tvtiger_service.serviceid AS productid,\n\t\t\t\t\t\t\t\t\t'NA' AS productcode,\n\t\t\t\t\t\t\t\t\tvtiger_service.servicename AS productname,\n\t\t\t\t\t\t\t\t\tvtiger_service.unit_price AS unit_price,\n\t\t\t\t\t\t\t\t\tvtiger_service.service_usageunit AS usageunit,\n\t\t\t\t\t\t\t\t\t'NA' AS qtyinstock,vtiger_crmentity.deleted,\n\t\t\t\t\t\t\t\t\tvtiger_crmentity.description AS product_description,\n\t\t\t\t\t\t\t\t\t'Services' AS entitytype\n\t\t\t\t\t\t\t\t\tFROM vtiger_service\n\t\t\t\t\t\t\t\t\tINNER JOIN vtiger_crmentity\n\t\t\t\t\t\t\t\t\t\t\tON vtiger_crmentity.crmid=vtiger_service.serviceid\n\t\t\t\t\t\t\t\t\tWHERE vtiger_crmentity.deleted=0\n\t\t\t\t\t\t\t\t\t\t\tAND serviceid=?";
         $params = array($seid);
     }
     $result = $adb->pquery($query, $params);
     $num_rows = $adb->num_rows($result);
     $finalTaxTotal = '0.00';
     for ($i = 1; $i <= $num_rows; $i++) {
         $deleted = $adb->query_result($result, $i - 1, 'deleted');
         $hdnProductId = $adb->query_result($result, $i - 1, 'productid');
         $hdnProductcode = $adb->query_result($result, $i - 1, 'productcode');
         $productname = $adb->query_result($result, $i - 1, 'productname');
         $productdescription = $adb->query_result($result, $i - 1, 'product_description');
         $comment = $adb->query_result($result, $i - 1, 'comment');
         $qtyinstock = $adb->query_result($result, $i - 1, 'qtyinstock');
         $qty = $adb->query_result($result, $i - 1, 'quantity');
         $unitprice = $adb->query_result($result, $i - 1, 'unit_price');
         $listprice = $adb->query_result($result, $i - 1, 'listprice');
         $entitytype = $adb->query_result($result, $i - 1, 'entitytype');
         if ($entitytype == 'Services') {
             $usageunit = vtranslate($adb->query_result($result, $i - 1, 'service_usageunit'), $entitytype);
         } else {
             $usageunit = vtranslate($adb->query_result($result, $i - 1, 'usageunit'), $entitytype);
         }
         $tax = $adb->query_result($result, $i - 1, 'tax');
         if ($deleted || !isset($deleted)) {
             $product_Detail[$i]['productDeleted' . $i] = true;
         } elseif (!$deleted) {
             $product_Detail[$i]['productDeleted' . $i] = false;
         }
         if (!empty($entitytype)) {
             $product_Detail[$i]['entityType' . $i] = $entitytype;
         }
         if ($listprice == '') {
             $listprice = $unitprice;
         }
         if ($qty == '') {
             $qty = 1;
         }
         //calculate productTotal
         $productTotal = $qty * $listprice;
         //Delete link in First column
         if ($i != 1) {
             $product_Detail[$i]['delRow' . $i] = "Del";
         }
         if (empty($focus->mode) && $seid != '') {
             $sub_prod_query = $adb->pquery("SELECT crmid as prod_id from vtiger_seproductsrel WHERE productid=? AND setype='Products'", array($seid));
         } else {
             $sub_prod_query = $adb->pquery("SELECT productid as prod_id from vtiger_inventorysubproductrel WHERE id=? AND sequence_no=?", array($focus->id, $i));
         }
         $subprodid_str = '';
         $subprodname_str = '';
         $subProductArray = array();
         if ($adb->num_rows($sub_prod_query) > 0) {
             for ($j = 0; $j < $adb->num_rows($sub_prod_query); $j++) {
                 $sprod_id = $adb->query_result($sub_prod_query, $j, 'prod_id');
                 $sprod_name = $subProductArray[] = getProductName($sprod_id);
                 $str_sep = "";
                 if ($j > 0) {
                     $str_sep = ":";
                 }
                 $subprodid_str .= $str_sep . $sprod_id;
                 $subprodname_str .= $str_sep . " - " . $sprod_name;
             }
         }
         $subprodname_str = str_replace(":", "<br>", $subprodname_str);
         $product_Detail[$i]['subProductArray' . $i] = $subProductArray;
         $product_Detail[$i]['hdnProductId' . $i] = $hdnProductId;
         $product_Detail[$i]['productName' . $i] = from_html($productname);
         /* Added to fix the issue Product Pop-up name display*/
         if ($_REQUEST['action'] == 'CreateSOPDF' || $_REQUEST['action'] == 'CreatePDF' || $_REQUEST['action'] == 'SendPDFMail') {
             $product_Detail[$i]['productName' . $i] = htmlspecialchars($product_Detail[$i]['productName' . $i]);
         }
         $product_Detail[$i]['hdnProductcode' . $i] = $hdnProductcode;
         $product_Detail[$i]['productDescription' . $i] = from_html($productdescription);
         if ($module == 'Potentials' || $module == 'Products' || $module == 'Services') {
             $product_Detail[$i]['comment' . $i] = $productdescription;
         } else {
             $product_Detail[$i]['comment' . $i] = $comment;
         }
         if ($module != 'PurchaseOrder' && $focus->object_name != 'Order') {
             $product_Detail[$i]['qtyInStock' . $i] = decimalFormat($qtyinstock);
         }
         $listprice = number_format($listprice, $no_of_decimal_places, '.', '');
         $product_Detail[$i]['qty' . $i] = decimalFormat($qty);
         $product_Detail[$i]['listPrice' . $i] = $listprice;
         $product_Detail[$i]['unitPrice' . $i] = number_format($unitprice, $no_of_decimal_places, '.', '');
         $product_Detail[$i]['usageUnit' . $i] = $usageunit;
         $product_Detail[$i]['productTotal' . $i] = $productTotal;
         $product_Detail[$i]['subproduct_ids' . $i] = $subprodid_str;
         $product_Detail[$i]['subprod_names' . $i] = $subprodname_str;
         $product_Detail[$i]['tax' . $i] = $tax;
         $discount_percent = decimalFormat($adb->query_result($result, $i - 1, 'discount_percent'));
         $discount_amount = $adb->query_result($result, $i - 1, 'discount_amount');
         $discount_amount = decimalFormat(number_format($discount_amount, $no_of_decimal_places, '.', ''));
         $discountTotal = '0.00';
         //Based on the discount percent or amount we will show the discount details
         //To avoid NaN javascript error, here we assign 0 initially to' %of price' and 'Direct Price reduction'(for Each Product)
         $product_Detail[$i]['discount_percent' . $i] = 0;
         $product_Detail[$i]['discount_amount' . $i] = 0;
         if ($discount_percent != 'NULL' && $discount_percent != '') {
             $product_Detail[$i]['discount_type' . $i] = "percentage";
             $product_Detail[$i]['discount_percent' . $i] = $discount_percent;
             $product_Detail[$i]['checked_discount_percent' . $i] = ' checked';
             $product_Detail[$i]['style_discount_percent' . $i] = ' style="visibility:visible"';
             $product_Detail[$i]['style_discount_amount' . $i] = ' style="visibility:hidden"';
             $discountTotal = $productTotal * $discount_percent / 100;
         } elseif ($discount_amount != 'NULL' && $discount_amount != '') {
             $product_Detail[$i]['discount_type' . $i] = "amount";
             $product_Detail[$i]['discount_amount' . $i] = $discount_amount;
             $product_Detail[$i]['checked_discount_amount' . $i] = ' checked';
             $product_Detail[$i]['style_discount_amount' . $i] = ' style="visibility:visible"';
             $product_Detail[$i]['style_discount_percent' . $i] = ' style="visibility:hidden"';
             $discountTotal = $discount_amount;
         } else {
             $product_Detail[$i]['checked_discount_zero' . $i] = ' checked';
         }
         $totalAfterDiscount = $productTotal - $discountTotal;
         $totalAfterDiscount = number_format($totalAfterDiscount, $no_of_decimal_places, '.', '');
         $discountTotal = number_format($discountTotal, $no_of_decimal_places, '.', '');
         $product_Detail[$i]['discountTotal' . $i] = $discountTotal;
         $product_Detail[$i]['totalAfterDiscount' . $i] = $totalAfterDiscount;
         $amount = '0.00';
         $tax_details = getTaxDetailsForProduct($hdnProductId, 'all');
         //First we should get all available taxes and then retrieve the corresponding tax values
         $allTaxes = getAllTaxes('available', '', 'edit', $focus->id);
         $taxtype = $this->getInventoryTaxType($module, $focus->id);
         for ($tax_count = 0; $tax_count < count($tax_details); $tax_count++) {
             $tax_name = $tax_details[$tax_count]['taxname'];
             $tax_label = $tax_details[$tax_count]['taxlabel'];
             $tax_value = '0.00';
             //condition to avoid this function call when create new PO/SO/Quotes/Invoice from Product module
             if ($focus->id != '') {
                 if ($taxtype == 'individual') {
                     //if individual then show the entered tax percentage
                     $tax_value = getInventoryProductTaxValue($focus->id, $hdnProductId, $tax_name);
                 } else {
                     //if group tax then we have to show the default value when change to individual tax
                     $tax_value = $tax_details[$tax_count]['percentage'];
                 }
             } else {
                 //if the above function not called then assign the default associated value of the product
                 $tax_value = $tax_details[$tax_count]['percentage'];
             }
             $product_Detail[$i]['taxes'][$tax_count]['taxname'] = $tax_name;
             $product_Detail[$i]['taxes'][$tax_count]['taxlabel'] = $tax_label;
             $product_Detail[$i]['taxes'][$tax_count]['percentage'] = $tax_value;
             $amount = $totalAfterDiscount * $tax_value / 100;
             $amount = number_format($amount, $no_of_decimal_places, '.', '');
             $product_Detail[$i]['taxes'][$tax_count]['amount'] = $amount;
             if ($tax == $tax_name) {
                 $finalTaxTotal += $amount;
                 $product_Detail[$i]['taxTotal' . $i] = $amount;
             }
         }
         if ($taxtype == 'group') {
             foreach ($allTaxes as $key => $value) {
                 if ($tax == $value['taxname']) {
                     $amount = $totalAfterDiscount * $value['percentage'] / 100;
                     $amount = number_format($amount, $no_of_decimal_places, '.', '');
                     $product_Detail[$i]['taxes'][$tax]['amount'] = $amount;
                     $finalTaxTotal += $amount;
                     $product_Detail[$i]['taxTotal' . $i] = $amount;
                 }
             }
         }
         //Calculate netprice
         $netPrice = $totalAfterDiscount + number_format($product_Detail[$i]['taxTotal' . $i], $no_of_decimal_places, '.', '');
         //if condition is added to call this function when we create PO/SO/Quotes/Invoice from Product module
         $product_Detail[$i]['netPrice' . $i] = $netPrice;
     }
     //set the taxtype
     $product_Detail[1]['final_details']['taxtype'] = $taxtype;
     //Get the Final Discount, S&H charge, Tax for S&H  values
     //To set the Final Discount details
     $finalDiscount = '0.00';
     $product_Detail[1]['final_details']['discount_type_final'] = 'zero';
     $subTotal = $focus->column_fields['hdnSubTotal'] != '' ? $focus->column_fields['hdnSubTotal'] : '0.00';
     $subTotal = number_format($subTotal, $no_of_decimal_places, '.', '');
     $product_Detail[1]['final_details']['hdnSubTotal'] = $subTotal;
     $discountPercent = $focus->column_fields['hdnDiscountPercent'] != '' ? $focus->column_fields['hdnDiscountPercent'] : '0.00';
     $discountAmount = $focus->column_fields['hdnDiscountAmount'] != '' ? $focus->column_fields['hdnDiscountAmount'] : '0.00';
     if ($discountPercent != '0') {
         $discountAmount = $product_Detail[1]['final_details']['hdnSubTotal'] * $discountPercent / 100;
     }
     //To avoid NaN javascript error, here we assign 0 initially to' %of price' and 'Direct Price reduction'(For Final Discount)
     $discount_amount_final = '0.00';
     $discount_amount_final = number_format($discount_amount_final, $no_of_decimal_places, '.', '');
     $product_Detail[1]['final_details']['discount_percentage_final'] = 0;
     $product_Detail[1]['final_details']['discount_amount_final'] = $discount_amount_final;
     if ($focus->column_fields['hdnDiscountPercent'] != '0') {
         $finalDiscount = $subTotal * $discountPercent / 100;
         $product_Detail[1]['final_details']['discount_type_final'] = 'percentage';
         $product_Detail[1]['final_details']['discount_percentage_final'] = $discountPercent;
         $product_Detail[1]['final_details']['checked_discount_percentage_final'] = ' checked';
         $product_Detail[1]['final_details']['style_discount_percentage_final'] = ' style="visibility:visible"';
         $product_Detail[1]['final_details']['style_discount_amount_final'] = ' style="visibility:hidden"';
     } elseif ($focus->column_fields['hdnDiscountAmount'] != '0' && $focus->column_fields['hdnDiscountAmount'] != '') {
         $finalDiscount = $focus->column_fields['hdnDiscountAmount'];
         $product_Detail[1]['final_details']['discount_type_final'] = 'amount';
         $product_Detail[1]['final_details']['discount_amount_final'] = $discountAmount;
         $product_Detail[1]['final_details']['checked_discount_amount_final'] = ' checked';
         $product_Detail[1]['final_details']['style_discount_amount_final'] = ' style="visibility:visible"';
         $product_Detail[1]['final_details']['style_discount_percentage_final'] = ' style="visibility:hidden"';
     }
     $finalDiscount = number_format($finalDiscount, $no_of_decimal_places, '.', '');
     $product_Detail[1]['final_details']['discountTotal_final'] = $finalDiscount;
     //To set the Final Tax values
     //we will get all taxes. if individual then show the product related taxes only else show all taxes
     //suppose user want to change individual to group or vice versa in edit time the we have to show all taxes. so that here we will store all the taxes and based on need we will show the corresponding taxes
     for ($tax_count = 0; $tax_count < count($allTaxes); $tax_count++) {
         $tax_name = $allTaxes[$tax_count]['taxname'];
         $tax_label = $allTaxes[$tax_count]['taxlabel'];
         //if taxtype is individual and want to change to group during edit time then we have to show the all available taxes and their default values
         //Also taxtype is group and want to change to individual during edit time then we have to provide the asspciated taxes and their default tax values for individual products
         if ($taxtype == 'group') {
             $tax_percent = $adb->query_result($result, 0, $tax_name);
         } else {
             $tax_percent = $allTaxes[$tax_count]['percentage'];
         }
         //$adb->query_result($result,0,$tax_name);
         if ($tax_percent == '' || $tax_percent == 'NULL') {
             $tax_percent = '0.00';
         }
         $taxamount = ($subTotal - $finalDiscount) * $tax_percent / 100;
         $taxamount = number_format($taxamount, $no_of_decimal_places, '.', '');
         $product_Detail[1]['final_details']['taxes'][$tax_count]['taxname'] = $tax_name;
         $product_Detail[1]['final_details']['taxes'][$tax_count]['taxlabel'] = $tax_label;
         $product_Detail[1]['final_details']['taxes'][$tax_count]['percentage'] = $tax_percent;
         $product_Detail[1]['final_details']['taxes'][$tax_count]['amount'] = $taxamount;
     }
     $product_Detail[1]['final_details']['tax_totalamount'] = $finalTaxTotal;
     $product_Detail[1]['final_details']['tax'] = $tax;
     //To set the grand total
     $grandTotal = $focus->column_fields['hdnGrandTotal'] != '' ? $focus->column_fields['hdnGrandTotal'] : '0.00';
     $grandTotal = number_format($grandTotal, $no_of_decimal_places, '.', '');
     $product_Detail[1]['final_details']['grandTotal'] = $grandTotal;
     $log->debug("Exiting OSSCosts_Record_Model getAssociatedProducts method ...");
     return $product_Detail;
 }
Example #23
0
/**	Function used to save the Inventory product details for the passed entity
 *	@param object reference $focus - object reference to which we want to save the product details from REQUEST values where as the entity will be Purchase Order, Sales Order, Quotes or Invoice
 *	@param string $module - module name
 *	@param $update_prod_stock - true or false (default), if true we have to update the stock for PO only
 *	@return void
 */
function saveInventoryProductDetails(&$focus, $module, $update_prod_stock = 'false', $updateDemand = '')
{
    global $log, $adb;
    $id = $focus->id;
    $log->debug("Entering into function saveInventoryProductDetails({$module}).");
    //Added to get the convertid
    if (isset($_REQUEST['convert_from']) && $_REQUEST['convert_from'] != '') {
        $id = vtlib_purify($_REQUEST['return_id']);
    } else {
        if (isset($_REQUEST['duplicate_from']) && $_REQUEST['duplicate_from'] != '') {
            $id = vtlib_purify($_REQUEST['duplicate_from']);
        }
    }
    $ipr_cols = $adb->getColumnNames('vtiger_inventoryproductrel');
    $ext_prod_arr = array();
    if ($focus->mode == 'edit') {
        if ($_REQUEST['taxtype'] == 'group') {
            $all_available_taxes = getAllTaxes('available', '', 'edit', $id);
        }
        $return_old_values = '';
        if ($module != 'PurchaseOrder') {
            $return_old_values = 'return_old_values';
        }
        //we will retrieve the existing product details and store it in a array and then delete all the existing product details and save new values, retrieve the old value and update stock only for SO, Quotes and Invoice not for PO
        //$ext_prod_arr = deleteInventoryProductDetails($focus->id,$return_old_values);
        deleteInventoryProductDetails($focus);
    } else {
        if ($_REQUEST['taxtype'] == 'group') {
            $all_available_taxes = getAllTaxes('available', '', 'edit', $id);
        }
    }
    $tot_no_prod = $_REQUEST['totalProductCount'];
    if ($module != 'PurchaseOrder') {
        if (GlobalVariable::getVariable('B2B', '1') == '1') {
            $acvid = $focus->column_fields['account_id'];
        } else {
            $acvid = $focus->column_fields['contact_id'];
        }
    } else {
        $acvid = $focus->column_fields['vendor_id'];
    }
    //If the taxtype is group then retrieve all available taxes, else retrive associated taxes for each product inside loop
    $prod_seq = 1;
    for ($i = 1; $i <= $tot_no_prod; $i++) {
        //if the product is deleted then we should avoid saving the deleted products
        if ($_REQUEST["deleted" . $i] == 1) {
            continue;
        }
        $prod_id = vtlib_purify($_REQUEST['hdnProductId' . $i]);
        if (isset($_REQUEST['productDescription' . $i])) {
            $description = vtlib_purify($_REQUEST['productDescription' . $i]);
        }
        /*else{
        			$desc_duery = "select vtiger_crmentity.description AS product_description from vtiger_crmentity where vtiger_crmentity.crmid=?";
        			$desc_res = $adb->pquery($desc_duery,array($prod_id));
        			$description = $adb->query_result($desc_res,0,"product_description");
        		}	*/
        $qty = vtlib_purify($_REQUEST['qty' . $i]);
        $listprice = vtlib_purify($_REQUEST['listPrice' . $i]);
        $comment = vtlib_purify($_REQUEST['comment' . $i]);
        //we have to update the Product stock for PurchaseOrder if $update_prod_stock is true
        if ($module == 'PurchaseOrder' && $update_prod_stock == 'true') {
            addToProductStock($prod_id, $qty);
        }
        if ($module == 'SalesOrder') {
            if ($updateDemand == '-') {
                deductFromProductDemand($prod_id, $qty);
            } elseif ($updateDemand == '+') {
                addToProductDemand($prod_id, $qty);
            }
        }
        $query = "insert into vtiger_inventoryproductrel(id, productid, sequence_no, quantity, listprice, comment, description) values(?,?,?,?,?,?,?)";
        $qparams = array($focus->id, $prod_id, $prod_seq, $qty, $listprice, $comment, $description);
        $adb->pquery($query, $qparams);
        $lineitem_id = $adb->getLastInsertID();
        $sub_prod_str = $_REQUEST['subproduct_ids' . $i];
        if (!empty($sub_prod_str)) {
            $sub_prod = explode(":", $sub_prod_str);
            for ($j = 0; $j < count($sub_prod); $j++) {
                $query = "insert into vtiger_inventorysubproductrel(id, sequence_no, productid) values(?,?,?)";
                $qparams = array($focus->id, $prod_seq, $sub_prod[$j]);
                $adb->pquery($query, $qparams);
            }
        }
        $prod_seq++;
        if ($module != 'PurchaseOrder') {
            //update the stock with existing details
            updateStk($prod_id, $qty, $focus->mode, $ext_prod_arr, $module);
        }
        //we should update discount and tax details
        $updatequery = "update vtiger_inventoryproductrel set ";
        $updateparams = array();
        //set the discount percentage or discount amount in update query, then set the tax values
        if ($_REQUEST['discount_type' . $i] == 'percentage') {
            $updatequery .= " discount_percent=?,";
            array_push($updateparams, $_REQUEST['discount_percentage' . $i]);
        } elseif ($_REQUEST['discount_type' . $i] == 'amount') {
            $updatequery .= " discount_amount=?,";
            $discount_amount = $_REQUEST['discount_amount' . $i];
            array_push($updateparams, $discount_amount);
        }
        if ($_REQUEST['taxtype'] == 'group') {
            for ($tax_count = 0; $tax_count < count($all_available_taxes); $tax_count++) {
                $tax_name = $all_available_taxes[$tax_count]['taxname'];
                if (!in_array($tax_name, $ipr_cols)) {
                    continue;
                }
                $tax_val = $all_available_taxes[$tax_count]['percentage'];
                $request_tax_name = $tax_name . "_group_percentage";
                if (isset($_REQUEST[$request_tax_name])) {
                    $tax_val = vtlib_purify($_REQUEST[$request_tax_name]);
                }
                $updatequery .= " {$tax_name} = ?,";
                array_push($updateparams, $tax_val);
            }
            $updatequery = trim($updatequery, ',') . " where id=? and productid=? and lineitem_id = ?";
            array_push($updateparams, $focus->id, $prod_id, $lineitem_id);
        } else {
            $taxes_for_product = getTaxDetailsForProduct($prod_id, 'all', $acvid);
            for ($tax_count = 0; $tax_count < count($taxes_for_product); $tax_count++) {
                $tax_name = $taxes_for_product[$tax_count]['taxname'];
                if (!in_array($tax_name, $ipr_cols)) {
                    continue;
                }
                $request_tax_name = $tax_name . "_percentage" . $i;
                $updatequery .= " {$tax_name} = ?,";
                array_push($updateparams, vtlib_purify($_REQUEST[$request_tax_name]));
            }
            $updatequery = trim($updatequery, ',') . " where id=? and productid=? and lineitem_id = ?";
            array_push($updateparams, $focus->id, $prod_id, $lineitem_id);
        }
        // jens 2006/08/19 - protect against empy update queries
        if (!preg_match('/set\\s+where/i', $updatequery)) {
            $adb->pquery($updatequery, $updateparams);
        }
    }
    //we should update the netprice (subtotal), taxtype, group discount, S&H charge, S&H taxes, adjustment and total
    //netprice, group discount, taxtype, S&H amount, adjustment and total to entity table
    $updatequery = " update {$focus->table_name} set ";
    $updateparams = array();
    $subtotal = $_REQUEST['subtotal'];
    $updatequery .= " subtotal=?,";
    array_push($updateparams, $subtotal);
    $updatequery .= " taxtype=?,";
    array_push($updateparams, $_REQUEST['taxtype']);
    //for discount percentage or discount amount
    if ($_REQUEST['discount_type_final'] == 'percentage') {
        $updatequery .= " discount_percent=?,";
        array_push($updateparams, vtlib_purify($_REQUEST['discount_percentage_final']));
    } elseif ($_REQUEST['discount_type_final'] == 'amount') {
        $discount_amount_final = vtlib_purify($_REQUEST['discount_amount_final']);
        $updatequery .= " discount_amount=?,";
        array_push($updateparams, $discount_amount_final);
    }
    $shipping_handling_charge = vtlib_purify($_REQUEST['shipping_handling_charge']);
    $updatequery .= " s_h_amount=?,";
    array_push($updateparams, $shipping_handling_charge);
    //if the user gave - sign in adjustment then add with the value
    $adjustmentType = '';
    if ($_REQUEST['adjustmentType'] == '-') {
        $adjustmentType = vtlib_purify($_REQUEST['adjustmentType']);
    }
    $adjustment = vtlib_purify($_REQUEST['adjustment']);
    $updatequery .= " adjustment=?,";
    array_push($updateparams, $adjustmentType . $adjustment);
    $total = vtlib_purify($_REQUEST['total']);
    $updatequery .= " total=?";
    array_push($updateparams, $total);
    //$id_array = Array('PurchaseOrder'=>'purchaseorderid','SalesOrder'=>'salesorderid','Quotes'=>'quoteid','Invoice'=>'invoiceid');
    //Added where condition to which entity we want to update these values
    $updatequery .= " where " . $focus->table_index . "=?";
    array_push($updateparams, $focus->id);
    $adb->pquery($updatequery, $updateparams);
    //to save the S&H tax details in vtiger_inventoryshippingrel table
    $isr_cols = $adb->getColumnNames('vtiger_inventoryshippingrel');
    $sh_tax_details = getAllTaxes('all', 'sh');
    $sh_query_fields = "id,";
    $sh_query_values = "?,";
    $sh_query_params = array($focus->id);
    for ($i = 0; $i < count($sh_tax_details); $i++) {
        $tax_name = $sh_tax_details[$i]['taxname'] . "_sh_percent";
        if ($_REQUEST[$tax_name] != '' and in_array($sh_tax_details[$i]['taxname'], $isr_cols)) {
            $sh_query_fields .= $sh_tax_details[$i]['taxname'] . ",";
            $sh_query_values .= "?,";
            array_push($sh_query_params, vtlib_purify($_REQUEST[$tax_name]));
        }
    }
    $sh_query_fields = trim($sh_query_fields, ',');
    $sh_query_values = trim($sh_query_values, ',');
    if ($sh_query_fields != 'id') {
        $sh_query = "insert into vtiger_inventoryshippingrel({$sh_query_fields}) values({$sh_query_values})";
        $adb->pquery($sh_query, $sh_query_params);
    }
    $log->debug("Exit from function saveInventoryProductDetails({$module}).");
}
 * Copyright 2015 JPL TSolucio, S.L. -- This file is a part of TSOLUCIO coreBOS Customizations.
 * Licensed under the vtiger CRM Public License Version 1.1 (the "License"); you may not use this
 * file except in compliance with the License. You can redistribute it and/or modify it
 * under the terms of the License. JPL TSolucio, S.L. reserves all rights not expressly
 * granted by the License. coreBOS distributed by JPL TSolucio S.L. is distributed in
 * the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Unless required by
 * applicable law or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT ANY WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language governing
 * permissions and limitations under the License. You may obtain a copy of the License
 * at <http://corebos.org/documentation/doku.php?id=en:devel:vpl11>
 *************************************************************************************************
 *  Module       : Group Tax Calculation
 *  Version      : 1.0
 *  Author       : JPL TSolucio, S. L.
 *************************************************************************************************/
require_once 'Smarty_setup.php';
global $mod_strings, $app_strings;
$smarty = new vtigerCRM_Smarty();
$smarty->assign("MOD", $mod_strings);
$smarty->assign("APP", $app_strings);
$editmode = vtlib_purify($_REQUEST['editmode']);
if ($editmode != 'edit') {
    $tax_details = getAllTaxes('available');
} else {
    $invid = vtlib_purify($_REQUEST['invid']);
    $tax_details = getAllTaxes('available', '', $editmode, $invid);
}
$smarty->assign("GROUP_TAXES", $tax_details);
$smarty->display('Inventory/GroupTax.tpl');
 public static function getShippingTaxes()
 {
     vimport('~~/include/utils/InventoryUtils.php');
     $taxes = getAllTaxes('all', 'sh');
     $recordList = array();
     foreach ($taxes as $taxInfo) {
         $taxRecord = new self();
         $taxRecord->setData($taxInfo)->setType(self::SHIPPING_AND_HANDLING_TAX);
         $recordList[] = $taxRecord;
     }
     return $recordList;
 }
Example #26
0
/** 	Function used to save the Inventory product details for the passed entity
 * 	@param object reference $focus - object reference to which we want to save the product details from REQUEST values where as the entity will be Purchase Order, Sales Order, Quotes or Invoice
 * 	@param string $module - module name
 * 	@param $update_prod_stock - true or false (default), if true we have to update the stock for PO only
 * 	@return void
 */
function saveInventoryProductDetails(&$focus, $module, $update_prod_stock = 'false', $updateDemand = '')
{
    $adb = PearDatabase::getInstance();
    $log = vglobal('log');
    $id = $focus->id;
    $log->debug("Entering into function saveInventoryProductDetails({$module}).");
    //Added to get the convertid
    if (isset($_REQUEST['convert_from']) && $_REQUEST['convert_from'] != '') {
        $id = vtlib_purify($_REQUEST['return_id']);
    } else {
        if (isset($_REQUEST['duplicate_from']) && $_REQUEST['duplicate_from'] != '') {
            $id = vtlib_purify($_REQUEST['duplicate_from']);
        }
    }
    $ext_prod_arr = array();
    if ($focus->mode == 'edit') {
        if ($_REQUEST['taxtype'] == 'group') {
            $all_available_taxes = getAllTaxes('available', '', 'edit', $id);
        }
        $return_old_values = '';
        if ($module != 'PurchaseOrder') {
            $return_old_values = 'return_old_values';
        }
        //we will retrieve the existing product details and store it in a array and then delete all the existing product details and save new values, retrieve the old value and update stock only for SO, Quotes and Invoice not for PO
        //$ext_prod_arr = deleteInventoryProductDetails($focus->id,$return_old_values);
        deleteInventoryProductDetails($focus);
    } else {
        if ($_REQUEST['taxtype'] == 'group') {
            $all_available_taxes = getAllTaxes('available', '', 'edit', $id);
        }
    }
    $tot_no_prod = $_REQUEST['totalProductCount'];
    //If the taxtype is group then retrieve all available taxes, else retrive associated taxes for each product inside loop
    $prod_seq = 1;
    $total_purchase = 0;
    $total_margin = 0;
    for ($i = 1; $i <= $tot_no_prod; $i++) {
        //if the product is deleted then we should avoid saving the deleted products
        if ($_REQUEST["deleted" . $i] == 1) {
            continue;
        }
        $prod_id = vtlib_purify($_REQUEST['hdnProductId' . $i]);
        if (isset($_REQUEST['productDescription' . $i])) {
            $description = vtlib_purify($_REQUEST['productDescription' . $i]);
        }
        /* else{
        	  $desc_duery = "select vtiger_crmentity.description AS product_description from vtiger_crmentity where vtiger_crmentity.crmid=?";
        	  $desc_res = $adb->pquery($desc_duery,array($prod_id));
        	  $description = $adb->query_result($desc_res,0,"product_description");
        	  } */
        $qty = vtlib_purify($_REQUEST['qty' . $i]);
        $listprice = vtlib_purify($_REQUEST['listPrice' . $i]);
        $comment = vtlib_purify($_REQUEST['comment' . $i]);
        $purchaseCost = vtlib_purify($_REQUEST['purchaseCost' . $i]);
        $calculationsid = vtlib_purify($_REQUEST['calculationId' . $i]);
        $purchase = vtlib_purify($_REQUEST['purchase' . $i]);
        $margin = vtlib_purify($_REQUEST['margin' . $i]);
        $marginp = vtlib_purify($_REQUEST['marginp' . $i]);
        $total_purchase += $purchase * $qty;
        $total_margin += $margin;
        //we have to update the Product stock for PurchaseOrder if $update_prod_stock is true
        if ($module == 'PurchaseOrder' && $update_prod_stock == 'true') {
            addToProductStock($prod_id, $qty);
        }
        if ($module == 'SalesOrder') {
            if ($updateDemand == '-') {
                deductFromProductDemand($prod_id, $qty);
            } elseif ($updateDemand == '+') {
                addToProductDemand($prod_id, $qty);
            }
        }
        $query = "insert into vtiger_inventoryproductrel(id, productid, sequence_no, quantity, listprice, comment, description, calculationsid, purchase, margin, marginp) values(?,?,?,?,?,?,?,?,?,?,?)";
        $qparams = array($focus->id, $prod_id, $prod_seq, $qty, $listprice, $comment, $description, $calculationsid, $purchase, $margin, $marginp);
        $adb->pquery($query, $qparams);
        $lineitem_id = $adb->getLastInsertID();
        $sub_prod_str = $_REQUEST['subproduct_ids' . $i];
        if (!empty($sub_prod_str)) {
            $sub_prod = explode(":", $sub_prod_str);
            for ($j = 0; $j < count($sub_prod); $j++) {
                $query = "insert into vtiger_inventorysubproductrel(id, sequence_no, productid) values(?,?,?)";
                $qparams = array($focus->id, $prod_seq, $sub_prod[$j]);
                $adb->pquery($query, $qparams);
            }
        }
        $prod_seq++;
        if ($module != 'PurchaseOrder') {
            //update the stock with existing details
            updateStk($prod_id, $qty, $focus->mode, $ext_prod_arr, $module);
        }
        //we should update discount and tax details
        $updatequery = "update vtiger_inventoryproductrel set ";
        $updateparams = array();
        //set the discount percentage or discount amount in update query, then set the tax values
        if ($_REQUEST['discount_type' . $i] == 'percentage') {
            $updatequery .= " discount_percent=?,";
            array_push($updateparams, $_REQUEST['discount_percentage' . $i]);
        } elseif ($_REQUEST['discount_type' . $i] == 'amount') {
            $updatequery .= " discount_amount=?,";
            $discount_amount = $_REQUEST['discount_amount' . $i];
            array_push($updateparams, $discount_amount);
        }
        if ($_REQUEST['taxtype'] == 'group') {
            for ($tax_count = 0; $tax_count < count($all_available_taxes); $tax_count++) {
                $selected_tax = $_REQUEST['group_tax_option'];
                $updatequery .= " tax = ?,";
                array_push($updateparams, $selected_tax);
                $tax_name = $all_available_taxes[$tax_count]['taxname'];
                $request_tax_name = $tax_name . "_group_percentage";
                if (isset($_REQUEST[$request_tax_name])) {
                    $tax_val = vtlib_purify($_REQUEST[$request_tax_name]);
                }
                $updatequery .= " {$tax_name} = ?,";
                array_push($updateparams, $tax_val);
            }
        } else {
            $taxes_for_product = getTaxDetailsForProduct($prod_id, 'all');
            $selected_tax = $_REQUEST['tax_option' . $i];
            $updatequery .= " tax = ?,";
            array_push($updateparams, $selected_tax);
            for ($tax_count = 0; $tax_count < count($taxes_for_product); $tax_count++) {
                $tax_name = $taxes_for_product[$tax_count]['taxname'];
                $request_tax_name = $tax_name . "_percentage" . $i;
                $updatequery .= " {$tax_name} = ?,";
                array_push($updateparams, vtlib_purify($_REQUEST[$request_tax_name]));
            }
        }
        $updatequery = trim($updatequery, ',') . " where id=? and productid=? and lineitem_id = ?";
        array_push($updateparams, $focus->id, $prod_id, $lineitem_id);
        // jens 2006/08/19 - protect against empy update queries
        if (!preg_match('/set\\s+where/i', $updatequery)) {
            $adb->pquery($updatequery, $updateparams);
        }
    }
    //we should update the netprice (subtotal), taxtype, group discount, S&H charge, S&H taxes total
    //netprice, group discount, taxtype, total to entity table
    $updatequery = " update {$focus->table_name} set ";
    $updateparams = array();
    $subtotal = $_REQUEST['subtotal'];
    $updatequery .= " subtotal=?,";
    array_push($updateparams, $subtotal);
    $updatequery .= " total_purchase=?,";
    array_push($updateparams, $total_purchase);
    $updatequery .= " total_margin=?,";
    array_push($updateparams, $total_margin);
    $updatequery .= " total_marginp=?,";
    $total_marginp = 0;
    if ($total_purchase != 0) {
        $total_marginp = $total_margin / $total_purchase * 100;
    }
    array_push($updateparams, $total_marginp);
    $updatequery .= " taxtype=?,";
    array_push($updateparams, $_REQUEST['taxtype']);
    //for discount percentage or discount amount
    if ($_REQUEST['discount_type_final'] == 'percentage') {
        $updatequery .= " discount_percent=?,discount_amount=?,";
        array_push($updateparams, vtlib_purify($_REQUEST['discount_percentage_final']));
        array_push($updateparams, null);
    } elseif ($_REQUEST['discount_type_final'] == 'amount') {
        $discount_amount_final = vtlib_purify($_REQUEST['discount_amount_final']);
        $updatequery .= " discount_amount=?,discount_percent=?,";
        array_push($updateparams, $discount_amount_final);
        array_push($updateparams, null);
    } elseif ($_REQUEST['discount_type_final'] == 'zero') {
        $updatequery .= "discount_amount=?,discount_percent=?,";
        array_push($updateparams, null);
        array_push($updateparams, null);
    }
    $total = vtlib_purify($_REQUEST['total']);
    $updatequery .= " total=?";
    array_push($updateparams, $total);
    //$id_array = Array('PurchaseOrder'=>'purchaseorderid','SalesOrder'=>'salesorderid','Quotes'=>'quoteid','Invoice'=>'invoiceid');
    //Added where condition to which entity we want to update these values
    $updatequery .= " where " . $focus->table_index . "=?";
    array_push($updateparams, $focus->id);
    $adb->pquery($updatequery, $updateparams);
    $log->debug("Exit from function saveInventoryProductDetails({$module}).");
}
Example #27
0
 private function x18($x0c, $x0e)
 {
     global $x15d, $x15e, $x15f, $x160, $x161, $x162, $x163, $x164, $x165, $x166, $x167, $x168, $x169, $x16a, $x16b, $x16c, $x16d, $x16e, $x16f, $x170, $x171, $x172, $x173, $x174, $x175, $x176, $x177, $x178;
     $xc5 = $this->x22($x0c, $x0e);
     $x6e = "select case when vtiger_products.productid != '' then vtiger_products.productname else vtiger_service.servicename end as productname," . " case when vtiger_products.productid != '' then vtiger_products.productid else vtiger_service.serviceid end as psid," . " case when vtiger_products.productid != '' then vtiger_products.product_no else vtiger_service.service_no end as psno," . " case when vtiger_products.productid != '' then 'Products' else 'Services' end as entitytype," . " case when vtiger_products.productid != '' then vtiger_products.unit_price else vtiger_service.unit_price end as unit_price," . " case when vtiger_products.productid != '' then vtiger_products.usageunit else vtiger_service.service_usageunit end as usageunit," . " case when vtiger_products.productid != '' then vtiger_products.qty_per_unit else vtiger_service.qty_per_unit end as qty_per_unit," . " case when vtiger_products.productid != '' then vtiger_products.qtyinstock else 'NA' end as qtyinstock," . " case when vtiger_products.productid != '' then c1.description else c2.description end as psdescription, vtiger_inventoryproductrel.* " . " from vtiger_inventoryproductrel" . " left join vtiger_products on vtiger_products.productid=vtiger_inventoryproductrel.productid " . " left join vtiger_crmentity as c1 on c1.crmid = vtiger_products.productid " . " left join vtiger_service on vtiger_service.serviceid=vtiger_inventoryproductrel.productid " . " left join vtiger_crmentity as c2 on c2.crmid = vtiger_service.serviceid " . " where id=? ORDER BY sequence_no";
     $x3e = self::$x0f->pquery($x6e, array($x0e->id));
     $x43 = self::$x0f->num_rows($x3e);
     $xc6 = "0.00";
     $xc7 = 0;
     $xc8 = 0;
     $xc9 = 0;
     list($xca, $xcb) = $this->x1a($x0e->id);
     $xcc = array();
     $xcd = array();
     for ($x2d = 1; $x2d <= $x43; $x2d++) {
         $xce = self::$x0f->pquery("SELECT productid from vtiger_inventorysubproductrel WHERE id=? AND sequence_no=?", array($x0e->id, $x2d));
         $xcf = '';
         if (self::$x0f->num_rows($xce) > 0) {
             for ($x8d = 0; $x8d < self::$x0f->num_rows($xce); $x8d++) {
                 $xd0 = self::$x0f->query_result($xce, $x8d, "productid");
                 $xd1 = getProductName($xd0);
                 $xd2 = "";
                 if ($x8d > 0) {
                     $xd2 = ":";
                 }
                 $xcf .= $xd2 . " - " . $xd1;
             }
         }
         $xcf = $x172(":", "<br>", $xcf);
         $xd3 = self::$x0f->query_result($x3e, $x2d - 1, "psid");
         $xd4 = self::$x0f->query_result($x3e, $x2d - 1, "psno");
         $xd5 = self::$x0f->query_result($x3e, $x2d - 1, "productid");
         $xd6 = self::$x0f->query_result($x3e, $x2d - 1, "entitytype");
         $xd7 = $xd8 = self::$x0f->query_result($x3e, $x2d - 1, "productname");
         if ($xcf != "") {
             $xd8 .= "<br/><span style='color:#C0C0C0;font-style:italic;'>" . $xcf . "</span>";
         }
         $xd9 = self::$x0f->query_result($x3e, $x2d - 1, "comment");
         $xda = self::$x0f->query_result($x3e, $x2d - 1, "psdescription");
         $xdb = self::$x0f->query_result($x3e, $x2d - 1, "description");
         $xdc = self::$x0f->query_result($x3e, $x2d - 1, "qtyinstock");
         $xdd = self::$x0f->query_result($x3e, $x2d - 1, "quantity");
         $xde = self::$x0f->query_result($x3e, $x2d - 1, "qty_per_unit");
         $xdf = self::$x0f->query_result($x3e, $x2d - 1, "usageunit");
         $xe0 = self::$x0f->query_result($x3e, $x2d - 1, "unit_price");
         $xe1 = self::$x0f->query_result($x3e, $x2d - 1, "listprice");
         $xe2 = $xdd * $xe1;
         $xe3 = self::$x0f->query_result($x3e, $x2d - 1, "discount_percent");
         $xe4 = self::$x0f->query_result($x3e, $x2d - 1, "discount_amount");
         $xe5 = $xe2;
         $xe6 = "0.00";
         $xe7 = "";
         if ($xe3 != "NULL" && $xe3 != "") {
             $xe6 = $xe2 * $xe3 / 100;
             $xe5 = $xe2 - $xe6;
             $xe7 = $xe3;
         } elseif ($xe4 != "NULL" && $xe4 != "") {
             $xe6 = $xe4;
             $xe5 = $xe2 - $xe6;
         }
         $xe8 = $xe5;
         if ($xc5 == "individual") {
             $xe9 = "0.00";
             $xea = $x10["LBL_TOTAL_AFTER_DISCOUNT"] . " = {$xe5} \\n";
             $xeb = getTaxDetailsForProduct($xd5, "all");
             $xec = array();
             for ($xed = 0; $xed < $x161($xeb); $xed++) {
                 $xee = $xeb[$xed]["taxname"];
                 $xef = $xeb[$xed]["taxlabel"];
                 $xf0 = getInventoryProductTaxValue($x0e->id, $xd5, $xee);
                 $xf1 = $xe5 * $xf0 / 100;
                 $xe9 = $xe9 + $xf1;
                 if ($xee != "" && $xf0 > 0) {
                     $xf2[$xee . "-" . $xf0]["label"] = $xef;
                     $xf2[$xee . "-" . $xf0]["netto"] += $xe5;
                     $xf2[$xee . "-" . $xf0]["vat"] += $x16f($xf1, self::$x15);
                     $xf2[$xee . "-" . $xf0]["value"] = $xf0;
                     $x15e($xec, $xf0);
                     $x15e($xcd, $xf0);
                 }
             }
             $xe8 = $xe8 + $xe9;
             if ($x161($xec) > 0) {
                 $xf3 = $x160($xec);
             } else {
                 $xf3 = "0.00";
             }
             $xf4["P"][$x2d]["PRODUCTVATPERCENT"] = $this->x23($xf3);
             $xf4["P"][$x2d]["PRODUCTVATSUM"] = $this->x23($xe9);
         }
         if ($xd6 == "Products") {
             $xf4["P"][$x2d]["PRODUCTS_CRMID"] = $xd3;
             $xf4["P"][$x2d]["SERVICES_CRMID"] = "";
         } else {
             $xf4["P"][$x2d]["PRODUCTS_CRMID"] = "";
             $xf4["P"][$x2d]["SERVICES_CRMID"] = $xd3;
         }
         $xf4["P"][$x2d]["PS_CRMID"] = $xd3;
         $xf4["P"][$x2d]["PS_NO"] = $xd4;
         if ($xd9 != "") {
             $xd9 = $x172("\\n", "<br>", $x16d($xd9));
             $xd9 = $x165($xd9, ENT_QUOTES, self::$x11);
             $xd8 .= "<br /><small>" . $xd9 . "</small>";
         }
         $xf4["P"][$x2d]["PRODUCTNAME"] = $xd8;
         $xf4["P"][$x2d]["PRODUCTTITLE"] = $xd7;
         $xda = $x172("\\n", "<br>", $x16d($xda));
         $xf4["P"][$x2d]["PRODUCTDESCRIPTION"] = $x165($xda, ENT_QUOTES, self::$x11);
         $xf4["P"][$x2d]["PRODUCTEDITDESCRIPTION"] = $xd9;
         $xdb = $x172("\\n", "<br>", $x16d($xdb));
         $xf4["P"][$x2d]["CRMNOWPRODUCTDESCRIPTION"] = $x165($xdb, ENT_QUOTES, self::$x11);
         $xf4["P"][$x2d]["PRODUCTLISTPRICE"] = $this->x23($xe1);
         $xf4["P"][$x2d]["PRODUCTTOTAL"] = $this->x23($xe2);
         $xf4["P"][$x2d]["PRODUCTQUANTITY"] = $this->x23($xdd);
         $xf4["P"][$x2d]["PRODUCTQINSTOCK"] = $this->x23($xdc);
         $xf4["P"][$x2d]["PRODUCTPRICE"] = $this->x23($xe0);
         $xf4["P"][$x2d]["PRODUCTPOSITION"] = $x2d;
         $xf4["P"][$x2d]["PRODUCTQTYPERUNIT"] = $this->x23($xde);
         $x83 = $xdf;
         if (!$x168($x178($x83), self::$x18)) {
             $x83 = $this->x20($x83, "Products/Services");
         } else {
             $x83 = "";
         }
         $xf4["P"][$x2d]["PRODUCTUSAGEUNIT"] = $x83;
         $xf4["P"][$x2d]["PRODUCTDISCOUNT"] = $this->x23($xe6);
         $xf4["P"][$x2d]["PRODUCTDISCOUNTPERCENT"] = $this->x23($xe7);
         $xf4["P"][$x2d]["PRODUCTSTOTALAFTERDISCOUNTSUM"] = $xe5;
         $xf4["P"][$x2d]["PRODUCTSTOTALAFTERDISCOUNT"] = $this->x23($xe5);
         $xf4["P"][$x2d]["PRODUCTTOTALSUM"] = $this->x23($xe5 + $xe9);
         $xc7 += $xe5;
         $xc8 += $xe2;
         $xc9 += $xe5 + $xe9;
         $xf4["P"][$x2d]["PRODUCTSTOTALAFTERDISCOUNT_SUBTOTAL"] = $this->x23($xc7);
         $xf4["P"][$x2d]["PRODUCTTOTAL_SUBTOTAL"] = $this->x23($xc8);
         $xf4["P"][$x2d]["PRODUCTTOTALSUM_SUBTOTAL"] = $this->x23($xc9);
         $xcc[$x2d]["\$" . "TOTALAFTERDISCOUNT_SUBTOTAL\$"] = $xf4["P"][$x2d]["PRODUCTSTOTALAFTERDISCOUNT_SUBTOTAL"];
         $xcc[$x2d]["\$" . "TOTAL_SUBTOTAL\$"] = $xf4["P"][$x2d]["PRODUCTTOTAL_SUBTOTAL"];
         $xcc[$x2d]["\$" . "TOTALSUM_SUBTOTAL\$"] = $xf4["P"][$x2d]["PRODUCTTOTALSUM_SUBTOTAL"];
         $xf5 = self::$x0f->query_result($x3e, $x2d - 1, "sequence_no");
         $xf4["P"][$x2d]["PRODUCTSEQUENCE"] = $xf5;
         if (isset($xca[$xd5 . "_" . $xf5])) {
             $xf6 = "";
             $xf7 = "";
             if ($xca[$xd5 . "_" . $xf5]["width"] > 0) {
                 $xf6 = " width='" . $xca[$xd5 . "_" . $xf5]["width"] . "' ";
             }
             if ($xca[$xd5 . "_" . $xf5]["height"] > 0) {
                 $xf7 = " height='" . $xca[$xd5 . "_" . $xf5]["height"] . "' ";
             }
             $xf4["P"][$x2d]["PRODUCTS_IMAGENAME"] = "<img src='" . self::$x12 . "/" . $xca[$xd5 . "_" . $xf5]["src"] . "' " . $xf6 . $xf7 . "/>";
         } elseif (isset($xcb[$xd5 . "_" . $xf5])) {
             $xf4["P"][$x2d]["PRODUCTS_IMAGENAME"] = "<img src='" . self::$x12 . "/" . $xcb[$xd5 . "_" . $xf5]["src"] . "' width='83' />";
         }
         $xf8 = CRMEntity::getInstance("Products");
         if ($xd6 == "Products" && $xd3 != "") {
             $xf8->id = $xd3;
             $this->x24($xf8, $xd3, "Products");
         }
         $xf9 = $this->x21($x0c, $x0e);
         $xfa = $this->x10("Products", $xf8, false, $xf9);
         $xf4["P"][$x2d] = $x15f($xfa, $xf4["P"][$x2d]);
         unset($xf8);
         $xfb = CRMEntity::getInstance("Services");
         if ($xd6 == "Services" && $xd3 != "") {
             $xfb->id = $xd3;
             $this->x24($xfb, $xd3, "Services");
         }
         $xfc = $this->x10("Services", $xfb, false, $xf9);
         $xf4["P"][$x2d] = $x15f($xfc, $xf4["P"][$x2d]);
         unset($xfb);
         $xfd += $xe5;
         $xc6 = $xc6 + $xe8;
     }
     if (self::$x0c == $x0c) {
         self::$x26["subtotalsArray"] = $xcc;
     }
     $xfe = "0.00";
     $xff = "0";
     $x100 = "";
     if ($x0e->column_fields["hdnDiscountPercent"] != "0") {
         $xfe = $xc6 * $x0e->column_fields["hdnDiscountPercent"] / 100;
         $x100 = $x0e->column_fields["hdnDiscountPercent"];
     } elseif ($x0e->column_fields["hdnDiscountAmount"] != "0") {
         $xfe = $x0e->column_fields["hdnDiscountAmount"];
     }
     $xe9 = "0.00";
     if ($xc5 == "group") {
         $x101 = $xc6 - $xfe;
         $xeb = getAllTaxes("available", "", "edit", $x0e->id);
         for ($xed = 0; $xed < $x161($xeb); $xed++) {
             $xee = $xeb[$xed]["taxname"];
             $xef = $xeb[$xed]["taxlabel"];
             $xf0 = self::$x0f->query_result($x3e, 0, $xee);
             if ($xf0 == "" || $xf0 == "NULL") {
                 $xf0 = "0.00";
             }
             $x102 = ($xc6 - $xfe) * $xf0 / 100;
             $xe9 = $xe9 + $x102;
             if ($xee != "" && $xf0 > 0) {
                 $xf2[$xee]["label"] = $xef;
                 $xf2[$xee]["netto"] = $x101;
                 $xf2[$xee]["vat"] += $x102;
                 $xf2[$xee]["value"] = $xf0;
             }
             $x103 += $xf0;
         }
         $x104 = $xe9;
         foreach ($xf4["P"] as $x105 => $x106) {
             $x107 = $xf4["P"][$x105]["PRODUCTSTOTALAFTERDISCOUNTSUM"] * $x103 / 100;
             $x108 = $xf4["P"][$x105]["PRODUCTSTOTALAFTERDISCOUNTSUM"] + $x107;
             $xf4["P"][$x105]["PRODUCTVATPERCENT"] = $this->x23($x103);
             $xf4["P"][$x105]["PRODUCTVATSUM"] = $this->x23($x107);
             $xf4["P"][$x105]["PRODUCTTOTALSUM"] = $this->x23($x108);
         }
     } else {
         if ($x161($xf2) > 0) {
             foreach ($xf2 as $x109 => $x10a) {
                 $x104 += $x10a["vat"];
             }
         } else {
             $x104 = "0.00";
         }
     }
     $x10b = $x0e->column_fields["hdnS_H_Amount"] != "" ? $x0e->column_fields["hdnS_H_Amount"] : "0.00";
     $x10c = "0.00";
     $x10d = getAllTaxes("available", "sh", "edit", $x0e->id);
     for ($x10e = 0; $x10e < $x161($x10d); $x10e++) {
         $x10f = $x10d[$x10e]["taxname"];
         $x110 = $x10d[$x10e]["taxlabel"];
         $x111 = getInventorySHTaxPercent($x0e->id, $x10f);
         $x112 = $x10b * $x111 / 100;
         $x10c = $x10c + $x112;
     }
     $x113 = $xfd - $xfe;
     $x114 = $xfd - $xfe + $x104;
     $xf4["TOTAL"]["NETTOTAL"] = $this->x23($xc6);
     $xf4["TOTAL"]["TOTALWITHOUTVAT"] = $this->x23($xfd);
     $xf4["TOTAL"]["FINALDISCOUNT"] = $this->x23($xfe);
     $xf4["TOTAL"]["FINALDISCOUNTPERCENT"] = $this->x23($x100);
     $xf4["TOTAL"]["TOTALAFTERDISCOUNT"] = $this->x23($x113);
     $xf4["TOTAL"]["TAXTOTAL"] = $this->x23($x104);
     $xf4["TOTAL"]["TAXTOTALPERCENT"] = $this->x23($x103);
     $xf4["TOTAL"]["TOTALWITHVAT"] = $this->x23($x114);
     $xf4["TOTAL"]["SHTAXAMOUNT"] = $this->x23($x10b);
     $xf4["TOTAL"]["SHTAXTOTAL"] = $this->x23($x10c);
     $xf4["TOTAL"]["VATBLOCK"] = $xf2;
     return $xf4;
 }
Example #28
0
$_REQUEST['subtotal'] = round($subtotal + $totalwithtax, 2);
if ($taxtype == "individual") {
    $totaldoc = $subtotal + $totalwithtax;
    if ($element['discount_type_final'] == 'amount') {
        $totaldoc = $totaldoc - $element['hdnDiscountAmount'];
    } elseif ($element['discount_type_final'] == 'percentage') {
        $totaldoc = $totaldoc - $totaldoc * $element['hdnDiscountPercent'] / 100;
    }
} else {
    $totaldoc = $subtotal;
    if ($element['discount_type_final'] == 'amount') {
        $totaldoc = $totaldoc - $element['hdnDiscountAmount'];
    } elseif ($element['discount_type_final'] == 'percentage') {
        $totaldoc = $totaldoc - $totaldoc * $element['hdnDiscountPercent'] / 100;
    }
    $all_available_taxes = getAllTaxes('available', '');
    for ($tax_count = 0; $tax_count < count($all_available_taxes); $tax_count++) {
        $tax_val += $all_available_taxes[$tax_count]['percentage'];
    }
    $totaldoc = $totaldoc + $totaldoc * $tax_val / 100;
}
if (!empty($element['shipping_handling_charge'])) {
    $_REQUEST['shipping_handling_charge'] = $element['shipping_handling_charge'];
    $totaldoc = $totaldoc + $element['shipping_handling_charge'];
    $shtaxes = $adb->query('select taxname from vtiger_shippingtaxinfo where deleted=0');
    while ($sht = $adb->fetch_array($shtaxes)) {
        $shname = $sht['taxname'];
        if (!empty($element[$shname])) {
            $_REQUEST[$shname . '_sh_percent'] = $element[$shname];
            $totaldoc = $totaldoc + $element['shipping_handling_charge'] * $element[$shname] / 100;
        }
 public function updateParent($createdElement, $parent)
 {
     $discount = 0;
     $parentId = vtws_getIdComponents($parent['id']);
     $parentId = $parentId[1];
     $lineItemList = $this->getAllLineItemForParent($parentId);
     $parent['hdnSubTotal'] = 0;
     $taxAmount = 0;
     foreach ($lineItemList as $lineItem) {
         $discount = 0;
         $lineItemTotal = $lineItem['listprice'] * $lineItem['quantity'];
         $lineItem['discount_amount'] = (double) $lineItem['discount_amount'];
         $lineItem['discount_percent'] = (double) $lineItem['discount_percent'];
         if (!empty($lineItem['discount_amount'])) {
             $discount = $lineItem['discount_amount'];
         } elseif (!empty($lineItem['discount_percent'])) {
             $discount = $lineItem['discount_percent'] / 100 * $lineItemTotal;
         }
         $this->initTax($lineItem, $parent);
         $lineItemTotal = $lineItemTotal - $discount;
         $parent['hdnSubTotal'] = $parent['hdnSubTotal'] + $lineItemTotal;
         if (strcasecmp($parent['hdnTaxType'], $this->Individual) === 0) {
             foreach ($this->taxList as $taxInfo) {
                 $lineItemTaxAmount = $taxInfo['percentage'] / 100 * $lineItemTotal;
                 $parent['hdnSubTotal'] += $lineItemTaxAmount;
             }
         }
     }
     if (!empty($parent['hdnDiscountAmount']) && (double) $parent['hdnDiscountAmount'] > 0) {
         $discount = $parent['hdnDiscountAmount'];
     } elseif (!empty($parent['hdnDiscountPercent'])) {
         $discount = $parent['hdnDiscountPercent'] / 100 * $parent['hdnSubTotal'];
     }
     $parent['pre_tax_total'] = $total = $parent['hdnSubTotal'] - $discount + $parent['hdnS_H_Amount'];
     $taxTotal = $parent['hdnSubTotal'] - $discount;
     if (strcasecmp($parent['hdnTaxType'], $this->Individual) !== 0) {
         $this->initTax($createdElement, $parent);
         foreach ($this->taxList as $taxInfo) {
             $taxAmount += $taxInfo['percentage'] / 100 * $taxTotal;
         }
     }
     $shippingTax = getAllTaxes('all', 'sh', 'edit', $parentId);
     $shippingTaxInfo = array();
     foreach ($shippingTax as $taxInfo) {
         $taxAmount += $taxInfo['percentage'] / 100 * $parent['hdnS_H_Amount'];
         $shippingTaxInfo[$taxInfo['taxname']] = $taxInfo['percentage'];
     }
     $parent['hdnGrandTotal'] = $total + $taxAmount + $parent['txtAdjustment'];
     $parentTypeHandler = vtws_getModuleHandlerFromId($parent['id'], $this->user);
     $parentTypeMeta = $parentTypeHandler->getMeta();
     $parentType = $parentTypeMeta->getEntityName();
     $parentInstance = CRMEntity::getInstance($parentType);
     $sql = 'update ' . $parentInstance->table_name . ' set subtotal=?, total=?, pre_tax_total=? where ' . $parentInstance->tab_name_index[$parentInstance->table_name] . '=?';
     $params = array($parent['hdnSubTotal'], $parent['hdnGrandTotal'], $parent['pre_tax_total'], $parentId);
     $transactionSuccessful = vtws_runQueryAsTransaction($sql, $params, $result);
     self::$parentCache[$parent['id']] = $parent;
     if (!$transactionSuccessful) {
         throw new WebServiceException(WebServiceErrorCode::$DATABASEQUERYERROR, "Database error while performing required operation");
     }
 }
 public function addProducts2Entity($products, \Workflow\VTEntity $context, \Workflow\VTEntity $newObj)
 {
     $ntuvkohe = "newObj";
     $byrhbpbrk = "availTaxes";
     ${"GLOBALS"}["whorey"] = "index";
     $ffgqftdius = "products";
     ${$byrhbpbrk} = getAllTaxes("available");
     foreach (${$ffgqftdius} as ${${"GLOBALS"}["whorey"]} => ${${"GLOBALS"}["sjtfmhhrl"]}) {
         ${"GLOBALS"}["iidnejxe"] = "productid";
         ${"GLOBALS"}["mkhslsympqx"] = "value";
         ${"GLOBALS"}["dwhdtozvynqw"] = "additionalProductFields";
         $kruolocojg = "aTax";
         $hovdgrthnuug = "productid";
         $qtcncloye = "value";
         if (!empty(${${"GLOBALS"}["mkhslsympqx"]}["productid_individual"])) {
             $wyriktxohly = "value";
             ${"GLOBALS"}["sgtcyhxie"] = "context";
             ${${"GLOBALS"}["abiiqvys"]} = \Workflow\VTTemplate::parse(${$wyriktxohly}["productid_individual"], ${${"GLOBALS"}["sgtcyhxie"]});
         } else {
             $upfwkclmyw = "value";
             ${${"GLOBALS"}["abiiqvys"]} = ${$upfwkclmyw}["productid"];
         }
         $ftfrgn = "additional";
         $rjivvcng = "value";
         $txyfsrjjlt = "key";
         if (strpos(${${"GLOBALS"}["abiiqvys"]}, "x") !== false) {
             $iicydljc = "productid";
             ${${"GLOBALS"}["beraxrr"]} = explode("x", ${${"GLOBALS"}["abiiqvys"]});
             ${$iicydljc} = ${${"GLOBALS"}["beraxrr"]}[1];
         }
         ${${"GLOBALS"}["exevmtidn"]} = \CRMEntity::getInstance("Products");
         $crmProduct->id = ${${"GLOBALS"}["abiiqvys"]};
         ${"GLOBALS"}["sjserddrpvq"] = "template";
         ${"GLOBALS"}["yxkoqgfdppa"] = "tax";
         $tzdqzqwys = "value";
         $crmProduct->retrieve_entity_info(${${"GLOBALS"}["iidnejxe"]}, "Products");
         ${"GLOBALS"}["wwkmvdqqkc"] = "value";
         ${"GLOBALS"}["kefwiymrs"] = "notUsed";
         $context->setEnvironment("product", $crmProduct->column_fields);
         ${${"GLOBALS"}["yxkoqgfdppa"]} = array();
         foreach (${${"GLOBALS"}["vplitvux"]} as ${$kruolocojg}) {
             $aupvkbaasytu = "aTax";
             if (${${"GLOBALS"}["sjtfmhhrl"]}["tax" . ${$aupvkbaasytu}["taxid"] . "_enable"] == 1) {
                 ${"GLOBALS"}["ogkgbpocs"] = "value";
                 ${"GLOBALS"}["ijrycbkkr"] = "aTax";
                 $mkhbocmhrmpk = "tax";
                 ${"GLOBALS"}["dtghrs"] = "context";
                 ${$mkhbocmhrmpk}[${${"GLOBALS"}["umtsmnroiv"]}["taxid"]] = \Workflow\VTTemplate::parse(${${"GLOBALS"}["ogkgbpocs"]}["tax" . ${${"GLOBALS"}["ijrycbkkr"]}["taxid"]], ${${"GLOBALS"}["dtghrs"]});
             }
         }
         foreach (${${"GLOBALS"}["wwkmvdqqkc"]} as ${$txyfsrjjlt} => ${${"GLOBALS"}["sjserddrpvq"]}) {
             ${"GLOBALS"}["xlrnmfcvpv"] = "context";
             ${"GLOBALS"}["zhharvcx"] = "value";
             ${"GLOBALS"}["qhcuwjgl"] = "template";
             ${${"GLOBALS"}["zhharvcx"]}[${${"GLOBALS"}["emvpxgxubu"]}] = \Workflow\VTTemplate::parse(${${"GLOBALS"}["qhcuwjgl"]}, ${${"GLOBALS"}["xlrnmfcvpv"]});
         }
         ${${"GLOBALS"}["blrjuuukpb"]} = \Workflow\VTInventoryEntity::getAdditionalProductFields();
         ${${"GLOBALS"}["cjsxrrce"]} = array();
         foreach (${${"GLOBALS"}["dwhdtozvynqw"]} as ${${"GLOBALS"}["mvrectngpf"]} => ${${"GLOBALS"}["kefwiymrs"]}) {
             $fvxbkhyucq = "fieldIndex";
             ${"GLOBALS"}["wqqxwewdo"] = "value";
             ${"GLOBALS"}["scwnykwdcxs"] = "additional";
             $gjgvfrgxj = "fieldIndex";
             ${${"GLOBALS"}["scwnykwdcxs"]}[${$gjgvfrgxj}] = ${${"GLOBALS"}["wqqxwewdo"]}[${$fvxbkhyucq}];
         }
         $newObj->addProduct(${$hovdgrthnuug}, ${$tzdqzqwys}["description"], ${${"GLOBALS"}["sjtfmhhrl"]}["comment"], ${${"GLOBALS"}["sjtfmhhrl"]}["quantity"], ${${"GLOBALS"}["sjtfmhhrl"]}["unitprice"], ${$qtcncloye}["discount_mode"] == "percentage" ? ${${"GLOBALS"}["sjtfmhhrl"]}["discount_value"] : 0, ${${"GLOBALS"}["sjtfmhhrl"]}["discount_mode"] == "amount" ? ${$rjivvcng}["discount_value"] : 0, ${${"GLOBALS"}["itmavwvym"]}, ${$ftfrgn});
     }
     return ${$ntuvkohe};
 }