Пример #1
0
/**
 * This function returns the Product detail block values in array format.
 * Input Parameter are $module - module name, $focus - module object, $num_of_products - no.of vtiger_products associated with it  * $associated_prod = associated product details
 * column vtiger_fields/
 */
function getProductDetailsBlockInfo($mode, $module, $focus = '', $num_of_products = '', $associated_prod = '')
{
    global $log;
    $log->debug("Entering getProductDetailsBlockInfo(" . $mode . "," . $module . "," . $num_of_products . "," . $associated_prod . ") method ...");
    $productDetails = array();
    $productBlock = array();
    if ($num_of_products == '') {
        $num_of_products = getNoOfAssocProducts($module, $focus);
    }
    $productDetails['no_products'] = $num_of_products;
    if ($associated_prod == '') {
        $productDetails['product_details'] = getAssociatedProducts($module, $focus);
    } else {
        $productDetails['product_details'] = $associated_prod;
    }
    if ($focus != '') {
        $productBlock[] = array('mode' => $focus->mode);
        $productBlock[] = $productDetails['product_details'];
        $productBlock[] = array('taxvalue' => $focus->column_fields['txtTax']);
        $productBlock[] = array('taxAdjustment' => $focus->column_fields['txtAdjustment']);
        $productBlock[] = array('hdnSubTotal' => $focus->column_fields['hdnSubTotal']);
        $productBlock[] = array('hdnGrandTotal' => $focus->column_fields['hdnGrandTotal']);
    } else {
        $productBlock[] = array(array());
    }
    $log->debug("Exiting getProductDetailsBlockInfo method ...");
    return $productBlock;
}
Пример #2
0
 /**
  * Function get details of taxes for this record
  * Function calls from Edit/Create view of Inventory Records
  * @param <Object> $focus
  * @return <Array> List of individual taxes
  */
 function getDetailsForInventoryModule($focus)
 {
     $productId = $this->getId();
     $currentUser = Users_Record_Model::getCurrentUserModel();
     $productDetails = getAssociatedProducts($this->getModuleName(), $focus, $productId);
     $currentUserModel = Users_Record_Model::getCurrentUserModel();
     $convertedPriceDetails = $this->getModule()->getPricesForProducts($currentUserModel->get('currency_id'), array($productId));
     $productDetails[1]['listPrice1'] = number_format($convertedPriceDetails[$productId], $currentUserModel->get('no_of_currency_decimals'), '.', '');
     $totalAfterDiscount = $productDetails[1]['totalAfterDiscount1'];
     $productTaxes = $productDetails[1]['taxes'];
     if (!empty($productDetails)) {
         $taxCount = count($productTaxes);
         $taxTotal = '0';
         for ($i = 0; $i < $taxCount; $i++) {
             $taxValue = $productTaxes[$i]['percentage'];
             $taxAmount = $totalAfterDiscount * $taxValue / 100;
             $taxTotal = $taxTotal + $taxAmount;
             $productDetails[1]['taxes'][$i]['amount'] = $taxAmount;
             $productDetails[1]['taxTotal1'] = $taxTotal;
         }
         $netPrice = $totalAfterDiscount + $taxTotal;
         $productDetails[1]['netPrice1'] = $netPrice;
         $productDetails[1]['final_details']['hdnSubTotal'] = $netPrice;
         $productDetails[1]['final_details']['grandTotal'] = $netPrice;
     }
     for ($i = 1; $i <= count($productDetails); $i++) {
         $productId = $productDetails[$i]['hdnProductId' . $i];
         $productPrices = $this->getModule()->getPricesForProducts($currentUser->get('currency_id'), array($productId), $this->getModuleName());
         $productDetails[$i]['listPrice' . $i] = number_format($productPrices[$productId], $currentUser->get('no_of_currency_decimals'), '.', '');
     }
     return $productDetails;
 }
 function getProducts()
 {
     $numOfCurrencyDecimalPlaces = getCurrencyDecimalPlaces();
     $relatedProducts = getAssociatedProducts($this->getModuleName(), $this->getEntity());
     $productsCount = count($relatedProducts);
     //Updating Pre tax total
     $preTaxTotal = (double) $relatedProducts[1]['final_details']['hdnSubTotal'] + (double) $relatedProducts[1]['final_details']['shipping_handling_charge'] - (double) $relatedProducts[1]['final_details']['discountTotal_final'];
     $relatedProducts[1]['final_details']['preTaxTotal'] = number_format($preTaxTotal, $numOfCurrencyDecimalPlaces, '.', '');
     //Updating Total After Discount
     $totalAfterDiscount = (double) $relatedProducts[1]['final_details']['hdnSubTotal'] - (double) $relatedProducts[1]['final_details']['discountTotal_final'];
     $relatedProducts[1]['final_details']['totalAfterDiscount'] = number_format($totalAfterDiscount, $numOfCurrencyDecimalPlaces, '.', '');
     //Updating Tax details
     $taxtype = $relatedProducts[1]['final_details']['taxtype'];
     for ($i = 1; $i <= $productsCount; $i++) {
         $product = $relatedProducts[$i];
         $productId = $product['hdnProductId' . $i];
         $totalAfterDiscount = $product['totalAfterDiscount' . $i];
         if ($taxtype == 'individual') {
             $taxDetails = getTaxDetailsForProduct($productId, 'all');
             $taxCount = count($taxDetails);
             $taxTotal = '0';
             for ($j = 0; $j < $taxCount; $j++) {
                 $taxValue = $product['taxes'][$j]['percentage'];
                 $taxAmount = $totalAfterDiscount * $taxValue / 100;
                 $taxTotal = $taxTotal + $taxAmount;
                 $relatedProducts[$i]['taxes'][$j]['amount'] = $taxAmount;
                 $relatedProducts[$i]['taxTotal' . $i] = $taxTotal;
             }
             $netPrice = $totalAfterDiscount + $taxTotal;
             $relatedProducts[$i]['netPrice' . $i] = $netPrice;
         }
     }
     return $relatedProducts;
 }
 function loadRecord($id)
 {
     global $current_user;
     $this->focus = $focus = CRMEntity::getInstance($this->moduleName);
     $focus->retrieve_entity_info($id, $this->moduleName);
     $focus->apply_field_security();
     $focus->id = $id;
     $this->associated_products = getAssociatedProducts($this->moduleName, $focus);
 }
Пример #5
0
 function getProducts()
 {
     $relatedProducts = getAssociatedProducts($this->getModuleName(), $this->getEntity());
     $relatedProducts[1]['final_details']['grandTotal'] = number_format($this->get('hdnGrandTotal'), getCurrencyDecimalPlaces(), '.', '');
     $relatedProducts[1]['final_details']['total_purchase'] = number_format($this->get('total_purchase'), getCurrencyDecimalPlaces(), '.', '');
     $relatedProducts[1]['final_details']['total_margin'] = number_format($this->get('total_margin'), getCurrencyDecimalPlaces(), '.', '');
     $relatedProducts[1]['final_details']['total_marginp'] = number_format($this->get('total_marginp'), getCurrencyDecimalPlaces(), '.', '');
     //Updating Pre tax total
     $preTaxTotal = (double) $relatedProducts[1]['final_details']['hdnSubTotal'] - (double) $relatedProducts[1]['final_details']['discountTotal_final'];
     $relatedProducts[1]['final_details']['preTaxTotal'] = number_format($preTaxTotal, getCurrencyDecimalPlaces(), '.', '');
     //Updating Total After Discount
     $totalAfterDiscount = (double) $relatedProducts[1]['final_details']['hdnSubTotal'] - (double) $relatedProducts[1]['final_details']['discountTotal_final'];
     $relatedProducts[1]['final_details']['totalAfterDiscount'] = number_format($totalAfterDiscount, getCurrencyDecimalPlaces(), '.', '');
     return $relatedProducts;
 }
Пример #6
0
function replaceProductList($pdftype, $id, $templateid, $content, $tcpdf)
{
    require_once 'include/utils/CommonUtils.php';
    require_once 'include/fields/CurrencyField.php';
    require_once 'modules/' . $pdftype . '/' . $pdftype . '.php';
    $focus = new $pdftype();
    $focus->retrieve_entity_info($id, $pdftype);
    $focus->id = $focus->column_fields["record_id"];
    $associated_products = getAssociatedProducts($pdftype, $focus);
    $num_products = count($associated_products);
    //This $final_details array will contain the final total, discount, Group Tax, S&H charge, S&H taxes
    $final_details = $associated_products[1]['final_details'];
    //getting the Net Total
    $price_subtotal = number_format($final_details["hdnSubTotal"], 2, '.', ',');
    //Final discount amount/percentage
    $discount_amount = $final_details["discount_amount_final"];
    $discount_percent = $final_details["discount_percentage_final"];
    if ($discount_amount != "") {
        $price_discount = number_format($discount_amount, 2, '.', ',');
    } else {
        if ($discount_percent != "") {
            //This will be displayed near Discount label - used in include/fpdf/templates/body.php
            $final_price_discount_percent = "(" . number_format($discount_percent, 2, '.', ',') . " %)";
            $price_discount = number_format($discount_percent * $final_details["hdnSubTotal"] / 100, 2, '.', ',');
        } else {
            $price_discount = "0.00";
        }
    }
    //Grand Total
    $price_total = number_format($final_details["grandTotal"], 2, '.', ',');
    //To calculate the group tax amount
    if ($final_details['taxtype'] == 'group') {
        $group_tax_total = $final_details['tax_totalamount'];
        $price_salestax = number_format($group_tax_total, 2, '.', ',');
        $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'];
        }
    }
    $prod_line = array();
    $lines = 0;
    //This is to get all prodcut details as row basis
    for ($i = 1, $j = $i - 1; $i <= $num_products; $i++, $j++) {
        $product_name[$i] = $associated_products[$i]['productName' . $i];
        $subproduct_name[$i] = split("<br>", $associated_products[$i]['subprod_names' . $i]);
        $comment[$i] = $associated_products[$i]['comment' . $i];
        $product_id[$i] = $associated_products[$i]['hdnProductId' . $i];
        $qty[$i] = $associated_products[$i]['qty' . $i];
        $unit_price[$i] = number_format($associated_products[$i]['unitPrice' . $i], 2, '.', ',');
        $list_price[$i] = $associated_products[$i]['listPrice' . $i];
        // number_format($associated_products[$i]['listPrice'.$i],2,'.',',');
        $list_pricet[$i] = $associated_products[$i]['listPrice' . $i];
        $discount_total[$i] = $associated_products[$i]['discountTotal' . $i];
        //aded for 5.0.3 pdf changes
        $product_code[$i] = $associated_products[$i]['hdnProductcode' . $i];
        $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;
                $total_taxes = $total_taxes + $tax_amount;
            }
            $producttotal = $taxable_total + $total_taxes;
            $product_line[$j]["tax_percentage"] = $total_tax_percent;
            $product_line[$j]["Tax"] = $total_taxes;
            $price_salestax += $total_taxes;
        }
        $prod_total[$i] = $producttotal;
        // number_format($producttotal,2,'.',',');
        $product_line[$j]["Product Code"] = $product_code[$i];
        $product_line[$j]["Qty"] = $qty[$i];
        $product_line[$j]["Price"] = $list_price[$i];
        $product_line[$j]["Discount"] = $discount_total[$i];
        $product_line[$j]["Total"] = $prod_total[$i];
        $lines++;
        $product_line[$j]["Product Name"] = decode_html($product_name[$i]);
        $prod_line[$j] = 1;
        for ($count = 0; $count < count($subproduct_name[$i]); $count++) {
            if ($lines % 12 != 0) {
                $product_line[$j]["Product Name"] .= "\n" . decode_html($subproduct_name[$i][$count]);
                $prod_line[$j]++;
            } else {
                $j++;
                $product_line[$j]["Product Name"] = decode_html($product_name[$i]);
                $product_line[$j]["Product Name"] .= "\n" . decode_html($subproduct_name[$i][$count]);
                $prod_line[$j] = 2;
                $lines++;
            }
            $lines++;
        }
        if ($comment[$i] != '') {
            $product_line[$j]["Product Name"] .= "\n" . decode_html($comment[$i]);
            $prod_line[$j]++;
            $lines++;
        }
    }
    $price_salestax = number_format($price_salestax, 2, '.', ',');
    $header = array(vtranslate('LBL_nr', 'OSSPdf'), vtranslate('LBL_productname', 'OSSPdf'), vtranslate('LBL_Quantity', 'OSSPdf'));
    $data = array();
    $i = 0;
    foreach ($product_line as $item) {
        $currfield = new CurrencyField($item["tax_percentage"]);
        $tax_percentage = $currfield->getDisplayValue();
        $data[$i++] = array($i, $item['Product Name'], $item['Qty']);
    }
    $width = array(35, 400, 100, 45, 45, 45, 45, 45, 45);
    $align = array("center", "center", "center", "center", "center", "center", "center", "center", "center");
    $format = array(0, "s", 0, 2, 2, 2, 2, 2, 2);
    $product_table = '<table align="center" border="1" cellpadding="2">';
    $product_table .= '<tr valign="middle">';
    for ($i = 0; $i < count($header); $i++) {
        $product_table .= '<td width="' . $width[$i] . '" height="20" align="' . $align[$i] . '"><b><small>' . $header[$i] . '</small></b></td>';
    }
    $product_table .= '</tr>';
    $align = array("center", "left", "center", "center", "center", "center", "center", "center", "center");
    //Data
    foreach ($data as $row) {
        $product_table .= '<tr>';
        $i = 0;
        foreach ($row as $item) {
            $sum[$i] += (double) $item;
            if ($format[$i] != 's') {
                $currfield = new CurrencyField($item);
                $item = $currfield->getDisplayValue();
            } else {
                $itarr = explode("\n\n", $item);
                $item = '<b>' . $itarr[0] . '</b><br/><small>' . $itarr[1] . '</small>';
            }
            $product_table .= '<td width="' . $width[$i] . '" align="' . $align[$i++] . '"><small>' . $item . '</small></td>';
        }
        $product_table .= '</tr>';
    }
    $product_table .= "</table><br/></center>";
    $i = 0;
    return $product_table;
}
Пример #7
0
    $smarty->assign("NAME", "");
}
if (isset($_REQUEST['convertmode']) && $_REQUEST['convertmode'] == 'quotetoinvoice') {
    $smarty->assign("MODE", $quote_focus->mode);
    $se_array = getProductDetailsBlockInfo($quote_focus->mode, "Quotes", $quote_focus);
} elseif (isset($_REQUEST['convertmode']) && ($_REQUEST['convertmode'] == 'sotoinvoice' || $_REQUEST['convertmode'] == 'update_so_val')) {
    $smarty->assign("MODE", $focus->mode);
    $se_array = getProductDetailsBlockInfo($focus->mode, "SalesOrder", $so_focus);
    $txtTax = $so_focus->column_fields['txtTax'] != '' ? $so_focus->column_fields['txtTax'] : '0.000';
    $txtAdj = $so_focus->column_fields['txtAdjustment'] != '' ? $so_focus->column_fields['txtAdjustment'] : '0.000';
    $associated_prod = getAssociatedProducts("SalesOrder", $so_focus);
    $smarty->assign("ASSOCIATEDPRODUCTS", $associated_prod);
    $smarty->assign("MODE", $focus->mode);
} elseif ($focus->mode == 'edit') {
    $smarty->assign("UPDATEINFO", updateInfo($focus->id));
    $associated_prod = getAssociatedProducts("Invoice", $focus);
    $smarty->assign("ASSOCIATEDPRODUCTS", $associated_prod);
    $smarty->assign("MODE", $focus->mode);
} elseif (isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') {
    $associated_prod = $INVOICE_associated_prod;
    $smarty->assign("AVAILABLE_PRODUCTS", 'true');
    $smarty->assign("MODE", $focus->mode);
} elseif (isset($_REQUEST['product_id']) && $_REQUEST['product_id'] != '' || isset($_REQUEST['opportunity_id']) && $_REQUEST['opportunity_id'] != '') {
    $smarty->assign("ASSOCIATEDPRODUCTS", $associated_prod);
    $InvTotal = getInventoryTotal($_REQUEST['return_module'], $_REQUEST['return_id']);
    $smarty->assign("MODE", $focus->mode);
    //this is to display the Product Details in first row when we create new PO from Product relatedlist
    if ($_REQUEST['return_module'] == 'Products') {
        $smarty->assign("PRODUCT_ID", vtlib_purify($_REQUEST['product_id']));
        $smarty->assign("PRODUCT_NAME", getProductName($_REQUEST['product_id']));
        $smarty->assign("UNIT_PRICE", vtlib_purify($_REQUEST['product_id']));
Пример #8
0
$smarty->assign("CATEGORY", $category);
$log->info("Order view");
if (isset($focus->name)) {
    $smarty->assign("NAME", $focus->name);
} else {
    $smarty->assign("NAME", "");
}
if (isset($_REQUEST['convertmode']) && ($_REQUEST['convertmode'] == 'quotetoso' || $_REQUEST['convertmode'] == 'update_quote_val')) {
    $txtTax = $quote_focus->column_fields['txtTax'] != '' ? $quote_focus->column_fields['txtTax'] : '0.000';
    $txtAdj = $quote_focus->column_fields['txtAdjustment'] != '' ? $quote_focus->column_fields['txtAdjustment'] : '0.000';
    $associated_prod = getAssociatedProducts("Quotes", $quote_focus);
    $smarty->assign("ASSOCIATEDPRODUCTS", $associated_prod);
    $smarty->assign("MODE", $focus->mode);
} elseif ($focus->mode == 'edit') {
    $smarty->assign("UPDATEINFO", updateInfo($focus->id));
    $associated_prod = getAssociatedProducts("SalesOrder", $focus);
    $smarty->assign("ASSOCIATEDPRODUCTS", $associated_prod);
    $smarty->assign("MODE", $focus->mode);
} elseif (isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') {
    $smarty->assign("ASSOCIATEDPRODUCTS", $SO_associated_prod);
    $smarty->assign("AVAILABLE_PRODUCTS", 'true');
    $smarty->assign("MODE", $focus->mode);
} elseif (isset($_REQUEST['potential_id']) && $_REQUEST['potential_id'] != '' || isset($_REQUEST['product_id']) && $_REQUEST['product_id'] != '') {
    $smarty->assign("ASSOCIATEDPRODUCTS", $associated_prod);
    $InvTotal = getInventoryTotal($_REQUEST['return_module'], $_REQUEST['return_id']);
    $smarty->assign("MODE", $focus->mode);
    //this is to display the Product Details in first row when we create new PO from Product relatedlist
    if ($_REQUEST['return_module'] == 'Products') {
        $smarty->assign("PRODUCT_ID", vtlib_purify($_REQUEST['product_id']));
        $smarty->assign("PRODUCT_NAME", getProductName($_REQUEST['product_id']));
        $smarty->assign("UNIT_PRICE", vtlib_purify($_REQUEST['product_id']));
Пример #9
0
function get_inventory_products($id, $module, $customerid, $sessionid)
{
    require_once 'include/utils/UserInfoUtil.php';
    require_once 'include/utils/utils.php';
    global $adb, $site_URL, $log;
    $user = new Users();
    $userid = getPortalUserid();
    $current_user = $user->retrieveCurrentUserInfoFromFile($userid);
    $isPermitted = check_permission($customerid, $module, $id);
    if ($isPermitted == false) {
        return array("#NOT AUTHORIZED#");
    }
    include_once "modules/{$module}/{$module}.php";
    $focus = CRMEntity::getInstance($module);
    $focus->id = $id;
    $associated_prod = getAssociatedProducts($module, $focus);
    $output[0] = $associated_prod;
    return $output;
}
 function loadRecord($id)
 {
     parent::loadRecord($id);
     $this->associated_products = getAssociatedProducts($this->moduleName, $this->focus);
 }
Пример #11
0
$smarty->assign("THEME", $theme);
$smarty->assign('IMAGE_PATH', "themes/{$theme}/images/");
$smarty->assign('ID', $focus->id);
$smarty->assign('MODE', $focus->mode);
$smarty->assign('CREATEMODE', isset($_REQUEST['createmode']) ? vtlib_purify($_REQUEST['createmode']) : '');
$smarty->assign('CHECK', Button_Check($currentModule));
$smarty->assign('DUPLICATE', $isduplicate);
if ($focus->mode == 'edit' || $isduplicate) {
    $recordName = array_values(getEntityName($currentModule, $record));
    $recordName = $recordName[0];
    $smarty->assign('NAME', $recordName);
    $smarty->assign('UPDATEINFO', updateInfo($record));
}
if ($focus->mode == 'edit') {
    $smarty->assign('UPDATEINFO', updateInfo($focus->id));
    $associated_prod = getAssociatedProducts('Issuecards', $focus);
    $smarty->assign('ASSOCIATEDPRODUCTS', $associated_prod);
    $smarty->assign('MODE', $focus->mode);
} elseif (isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') {
    $smarty->assign('ASSOCIATEDPRODUCTS', $associated_prod);
    $smarty->assign('AVAILABLE_PRODUCTS', 'true');
    $smarty->assign('MODE', $focus->mode);
}
$cbMap = cbMap::getMapByName($currentModule . 'InventoryDetails', 'MasterDetailLayout');
if ($cbMap != null) {
    $cbMapFields = $cbMap->MasterDetailLayout();
    $smarty->assign('moreinfofields', "'" . implode("','", $cbMapFields['detailview']['fieldnames']) . "'");
    if (empty($associated_prod)) {
        // creating
        $product_Detail = $col_fields = array();
        foreach ($cbMapFields['detailview']['fields'] as $mdfield) {
Пример #12
0
$smarty->assign('DUPLICATE', $isduplicate);
if ($focus->mode == 'edit' || $isduplicate) {
    $recordName = array_values(getEntityName($currentModule, $record));
    $recordName = $recordName[0];
    $smarty->assign('NAME', $recordName);
    $smarty->assign('UPDATEINFO', updateInfo($record));
}
if (isset($_REQUEST['convertmode']) && ($_REQUEST['convertmode'] == 'quotetoso' || $_REQUEST['convertmode'] == 'update_quote_val')) {
    $txtTax = $quote_focus->column_fields['txtTax'] != '' ? $quote_focus->column_fields['txtTax'] : '0.000';
    $txtAdj = $quote_focus->column_fields['txtAdjustment'] != '' ? $quote_focus->column_fields['txtAdjustment'] : '0.000';
    $associated_prod = getAssociatedProducts('Quotes', $quote_focus);
    $smarty->assign('ASSOCIATEDPRODUCTS', $associated_prod);
    $smarty->assign('MODE', $focus->mode);
} elseif ($focus->mode == 'edit') {
    $smarty->assign('UPDATEINFO', updateInfo($focus->id));
    $associated_prod = getAssociatedProducts('SalesOrder', $focus);
    $smarty->assign('ASSOCIATEDPRODUCTS', $associated_prod);
    $smarty->assign('MODE', $focus->mode);
} elseif (isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') {
    $smarty->assign('ASSOCIATEDPRODUCTS', $SO_associated_prod);
    $smarty->assign('AVAILABLE_PRODUCTS', 'true');
    $smarty->assign('MODE', $focus->mode);
}
if (isset($_REQUEST['return_module'])) {
    $smarty->assign("RETURN_MODULE", vtlib_purify($_REQUEST['return_module']));
} else {
    $smarty->assign("RETURN_MODULE", "SalesOrder");
}
if (isset($_REQUEST['return_action'])) {
    $smarty->assign("RETURN_ACTION", vtlib_purify($_REQUEST['return_action']));
} else {
Пример #13
0
function replaceProductTable($pdftype, $id, $templateid, $content, $tcpdf)
{
    $permitted_modules = vglobal('permitted_modules');
    if (in_array($pdftype, $permitted_modules)) {
        /* ------------------- COLUMN CONFIGURATION -------------------
        
              In this part, you can decide which columns you want to appear
                               and which are not in the table of positions and invoice summary table
        
                               If the variable responsible for this column has the value TRUE
                               will be displayed and if FALSE it will not be displayed
        
             */
        // The columns for the table from the list of items on the invoice
        $kolumnyDlaPozycjiFaktur = array();
        // column ordinal
        $enable_ordinal_column = TRUE;
        // Column name of the product
        $enable_productname_column = TRUE;
        // column number
        $enable_amount_column = TRUE;
        // unit price column
        $enable_listprice_column = TRUE;
        // net price column
        $enable_netprice_column = TRUE;
        // discount column
        $enable_discount_column = TRUE;
        // Vat column (%)
        $enable_vatpercentage_column = TRUE;
        // Vat column (currency)
        $enable_vatamount_column = TRUE;
        // Gross column
        $enable_gross_column = TRUE;
        // Taxes in PLN
        $enable_taxes_inPLN = TRUE;
        // Column for a summary in the gray box
        $wyswietlaj = array($enable_ordinal_column, $enable_productname_column, $enable_amount_column, $enable_listprice_column, $enable_netprice_column, $enable_discount_column, $enable_vatpercentage_column, $enable_vatamount_column, $enable_gross_column, $enable_taxes_inPLN);
        $kolumnyDlaPodsumowaniaFaktur = array();
        // shipping costs
        $enable_summary_shipping = TRUE;
        // tax on shipping costs
        $enable_summary_shippingtax = TRUE;
        // correction
        $enable_summary_correction = TRUE;
        // to pay
        $enable_summary_topay = TRUE;
        // total rebate
        $enable_summary_rebate = TRUE;
        // the percentage of tax column
        $enable_summary_taxpercentage = TRUE;
        // tax amount column
        $enable_summary_taxamount = TRUE;
        //show the date of the course
        $enable_date_of_the_course = TRUE;
        //----------------------------------------------------
        $newdate = vglobal('newdate');
        $current_user = vglobal('current_user');
        $adb = PearDatabase::getInstance();
        $currentModule = vglobal('currentModule');
        require_once 'include/utils/utils.php';
        $current_language = Users_Record_Model::getCurrentUserModel()->get('language');
        include "languages/" . $current_language . "/OSSPdf.php";
        include_once "languages/" . $current_language . "/Vtiger.php";
        require_once 'include/utils/CommonUtils.php';
        require_once 'include/fields/CurrencyField.php';
        require_once 'modules/' . $pdftype . '/' . $pdftype . '.php';
        $displays_a_summary_of_invoices = TRUE;
        if ($pdftype == 'OSSCorrectedInvoice') {
            require_once 'modules/' . $pdftype . '/utils.php';
            $displays_a_summary_of_invoices = FALSE;
            $pdftype = 'Invoice';
            $id_sql = "SELECT invoiceid FROM vtiger_osscorrectedinvoice WHERE osscorrectedinvoiceid = {$id}";
            $id_result = $adb->query($id_sql, true);
            $id = $adb->query_result($id_result, 0, 'invoiceid');
        }
        $focus = new $pdftype();
        $focus->retrieve_entity_info($id, $pdftype);
        $currency_id = $focus->column_fields['currency_id'];
        $pobierz = $adb->query("select currency_symbol, currency_code from vtiger_currency_info where id = '{$currency_id}'", true);
        $symbol_waluty = $adb->query_result($pobierz, 0, "currency_symbol");
        $kod_aktualnej_waluty = $adb->query_result($pobierz, 0, "currency_code");
        $focus->id = $focus->column_fields["record_id"];
        if ($pdftype == 'OSSInvoiceCost') {
            $associated_products = OSSgetAssociatedProducts($pdftype, $focus);
        } else {
            $associated_products = getAssociatedProducts($pdftype, $focus);
        }
        $czyDrukowacKolumneZPrzeliczonymPodatkiem = FALSE;
        $moduleFilePath = "modules/OSSCurrencyUpdate/OSSCurrencyUpdate.php";
        $moduleFilePathTpl = "Smarty/templates/modules/OSSCurrencyUpdate/index.tpl";
        $checkInDatabaseSql = "SELECT * FROM vtiger_tab WHERE name = 'OSSCurrencyUpdate'";
        $pobierzGluwnaWaluteSql = $adb->query("select currency_code from vtiger_currency_info where id = '1'", true);
        $kod_waluty = $adb->query_result($pobierzGluwnaWaluteSql, 0, "currency_code");
        $checkInDatabaseResult = $adb->query($checkInDatabaseSql, true);
        $numDB = $adb->num_rows($checkInDatabaseResult);
        if (file_exists($moduleFilePath) && file_exists($moduleFilePathTpl) && $numDB > 0 && $kod_waluty == 'PLN' && $kod_aktualnej_waluty != 'PLN' && vtlib_isModuleActive('OSSCurrencyUpdate')) {
            $czyDrukowacKolumneZPrzeliczonymPodatkiem = TRUE;
        }
        if ($czyDrukowacKolumneZPrzeliczonymPodatkiem == TRUE) {
            require_once $moduleFilePath;
        }
        $num_products = count($associated_products);
        $vat = array();
        $sales = array();
        $service = array();
        $total_discount = 0.0;
        $suma_netto = 0.0;
        $suma_brutto = $associated_products[1]['final_details']['grandTotal'];
        $rabat_calkowity = $associated_products[1]['final_details']['discountTotal_final'];
        $suma_vat = 0;
        /////////////////////////////
        /// Create a table summary of VAT
        if ($focus->column_fields['hdnTaxType'] == 'group') {
            for ($i = 1; $i <= count($associated_products); $i++) {
                $total_discount += $associated_products[$i]['discountTotal' . $i];
                $suma_netto += $associated_products[$i]['listPrice' . $i] - $total_discount;
            }
        } else {
            for ($i = 1; $i <= count($associated_products); $i++) {
                $TotalAfterDiscount = $associated_products[$i]['totalAfterDiscount' . $i];
                $suma_netto += $TotalAfterDiscount;
                foreach ($associated_products[$i]['taxes'] as $podatek) {
                    if ($podatek['taxlabel'] == 'VAT') {
                        $vat[$podatek['percentage']] += $TotalAfterDiscount * ($podatek['percentage'] / 100.0);
                        $suma_vat += $TotalAfterDiscount * ($podatek['percentage'] / 100.0);
                    }
                    if ($podatek['taxlabel'] == 'Sales') {
                        $sales[$podatek['percentage']] += $TotalAfterDiscount * ($podatek['percentage'] / 100.0);
                    }
                    if ($podatek['taxlabel'] == 'Service') {
                        $service[$podatek['percentage']] += $TotalAfterDiscount * ($podatek['percentage'] / 100.0);
                    }
                }
                // Calculating the total discount
                $total_discount += $associated_products[$i]['discountTotal' . $i];
            }
        }
        ///////////////////////////////////////////////////////////
        //This $final_details array will contain the final total, discount, Group Tax, S&H charge, S&H taxes
        $final_details = $associated_products[1]['final_details'];
        //getting the Net Total
        $price_subtotal = number_format($final_details["hdnSubTotal"], 2, '.', ',');
        //Final discount amount/percentage
        $discount_amount = $final_details["discount_amount_final"];
        $discount_percent = $final_details["discount_percentage_final"];
        if ($discount_amount != "") {
            $price_discount = number_format($discount_amount, 2, '.', ',');
            $price_disc = $discount_amount;
        } else {
            if ($discount_percent != "") {
                //This will be displayed near Discount label - used in include/fpdf/templates/body.php
                $final_price_discount_percent = "(" . number_format($discount_percent, 2, '.', ',') . " %)";
                $price_discount = number_format($discount_percent * $final_details["hdnSubTotal"] / 100, 2, '.', ',');
                $price_disc = $discount_percent * $final_details["hdnSubTotal"];
            } else {
                $price_discount = "0.00";
            }
        }
        //Grand Total
        $price_total = number_format($final_details["grandTotal"], 2, '.', ',');
        //To calculate the group tax amount
        if ($final_details['taxtype'] == 'group') {
            $group_tax_total = $final_details['tax_totalamount'];
            $price_salestax = number_format($group_tax_total, 2, '.', ',');
            $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'];
            }
        }
        $podatek_grupowy = ($final_details["hdnSubTotal"] - $price_disc) * ($group_total_tax_percent / 100.0);
        $prod_line = array();
        $lines = 0;
        //This is to get all prodcut details as row basis
        for ($i = 1, $j = $i - 1; $i <= $num_products; $i++, $j++) {
            $product_name[$i] = $associated_products[$i]['productName' . $i];
            $subproduct_name[$i] = split("<br>", $associated_products[$i]['subprod_names' . $i]);
            $comment[$i] = $associated_products[$i]['comment' . $i];
            $product_id[$i] = $associated_products[$i]['hdnProductId' . $i];
            $qty[$i] = $associated_products[$i]['qty' . $i];
            $unit_price[$i] = number_format($associated_products[$i]['unitPrice' . $i], 2, '.', ',');
            $list_price[$i] = $associated_products[$i]['listPrice' . $i];
            // number_format($associated_products[$i]['listPrice'.$i],2,'.',',');
            $list_pricet[$i] = $associated_products[$i]['listPrice' . $i];
            $discount_total[$i] = $associated_products[$i]['discountTotal' . $i];
            $product_code[$i] = $associated_products[$i]['hdnProductcode' . $i];
            $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;
                    $total_taxes = $total_taxes + $tax_amount;
                }
                $producttotal = $taxable_total + $total_taxes;
                $product_line[$j]["tax_percentage"] = $total_tax_percent;
                $product_line[$j]["Tax"] = $total_taxes;
                $price_salestax += $total_taxes;
            }
            $prod_total[$i] = $producttotal;
            // number_format($producttotal,2,'.',',');
            $product_line[$j]["Product Code"] = $product_code[$i];
            $product_line[$j]["Qty"] = $qty[$i];
            $product_line[$j]["Price"] = $list_price[$i];
            $product_line[$j]["Discount"] = $discount_total[$i];
            $product_line[$j]["Total"] = $prod_total[$i];
            $lines++;
            $product_line[$j]["Product Name"] = '<b>' . decode_html($product_name[$i]) . '</b>';
            $prod_line[$j] = 1;
            for ($count = 0; $count < count($subproduct_name[$i]); $count++) {
                if ($lines % 12 != 0) {
                    if ($subproduct_name[$i][$count] != '') {
                        $product_line[$j]["Product Name"] .= "\n <br />" . '<font color="grey" size="-1"><em>' . decode_html($subproduct_name[$i][$count]) . '</em></font>';
                        $prod_line[$j]++;
                    }
                } else {
                    $j++;
                    $product_line[$j]["Product Name"] = decode_html($product_name[$i]);
                    $product_line[$j]["Product Name"] .= "\n <br />" . decode_html($subproduct_name[$i][$count]);
                    $prod_line[$j] = 2;
                    $lines++;
                }
                $lines++;
            }
            if ($comment[$i] != '') {
                $product_line[$j]["Product Name"] .= "\n" . '<br />' . decode_html($comment[$i]);
                $prod_line[$j]++;
                $lines++;
            }
        }
        $tax_pl = 0;
        if ($czyDrukowacKolumneZPrzeliczonymPodatkiem == TRUE) {
            //invoicedate
            $invoice_date_sql = "SELECT invoicedate FROM `vtiger_invoice` WHERE invoiceid = {$id}";
            $invoice_date_result = $adb->query($invoice_date_sql, true);
            $invoice_date = $adb->query_result($invoice_date_result, 0, 'invoicedate');
            $date = $invoice_date;
            $newdate = strtotime('-1 day', strtotime($date));
            $newdate = date('Y-m-d', $newdate);
            $CurrencyUpdate = Vtiger_Record_Model::getCleanInstance('OSSCurrencyUpdate');
            $kurs_waluty_result = $CurrencyUpdate->getCurrencyRate($newdate, $currency_id);
            $num_rate = $adb->num_rows($kurs_waluty_result, true);
            $kurs_waluty = '0.00';
            if ($num_rate != 0) {
                $kurs_waluty = (double) $adb->query_result($kurs_waluty_result, 0, 'kurs');
                $newdate = date('Y-m-d', strtotime($adb->query_result($kurs_waluty_result, 0, "data_faktyczna_kursu")));
            } else {
                $CurrencyUpdate->getCurrency($newdate);
                $kurs_waluty_result = $CurrencyUpdate->getCurrencyRate($newdate, $currency_id);
                $num_rate = $adb->num_rows($kurs_waluty_result);
                if ($num_rate != 0) {
                    $kurs_waluty = (double) $adb->query_result($kurs_waluty_result, 0, 'kurs');
                }
            }
        }
        $price_salestax = number_format($price_salestax, 2, '.', ',');
        if ($final_details['taxtype'] == 'group') {
            $header = array();
            if ($enable_ordinal_column) {
                $header[0] = vtranslate('LBL_nr', 'OSSPdf');
            }
            if ($enable_productname_column) {
                $header[1] = vtranslate('LBL_productname', 'OSSPdf');
            }
            if ($enable_amount_column) {
                $header[2] = vtranslate('LBL_Quantity', 'OSSPdf');
            }
            if ($enable_listprice_column) {
                $header[3] = vtranslate('LBL_price', 'OSSPdf');
            }
            if ($enable_netprice_column) {
                $header[4] = vtranslate('LBL_rabat', 'OSSPdf');
            }
            if ($enable_discount_column) {
                $header[5] = vtranslate('LBL_netto', 'OSSPdf');
            }
            if ($enable_gross_column) {
                $header[6] = vtranslate('LBL_brutto', 'OSSPdf');
            }
        } else {
            $header = array();
            if ($enable_ordinal_column) {
                $header[0] = vtranslate('LBL_nr', 'OSSPdf');
            }
            if ($enable_productname_column) {
                $header[1] = vtranslate('LBL_productname', 'OSSPdf');
            }
            if ($enable_amount_column) {
                $header[2] = vtranslate('LBL_Quantity', 'OSSPdf');
            }
            if ($enable_listprice_column) {
                $header[3] = vtranslate('LBL_price', 'OSSPdf');
            }
            if ($enable_netprice_column) {
                $header[4] = vtranslate('LBL_rabat', 'OSSPdf');
            }
            if ($enable_discount_column) {
                $header[5] = vtranslate('LBL_netto', 'OSSPdf');
            }
            if ($enable_vatpercentage_column) {
                $header[6] = vtranslate('LBL_vat', 'OSSPdf');
            }
            if ($enable_vatamount_column) {
                $header[7] = vtranslate('LBL_vat_waluta', 'OSSPdf') . " (" . $symbol_waluty . ")";
            }
            if ($enable_gross_column) {
                $header[8] = vtranslate('LBL_brutto', 'OSSPdf');
            }
            if ($enable_taxes_inPLN == TRUE && $czyDrukowacKolumneZPrzeliczonymPodatkiem == TRUE) {
                $header[9] = vtranslate('TAXES_IN_PLN', 'OSSPdf');
            }
        }
        $data = array();
        $i = 1;
        $suma_podatku_w_pln = 0.0;
        $tax_percentage_array = array();
        foreach ($product_line as $item) {
            $currfield = new CurrencyField($item["tax_percentage"]);
            $tax_percentage = $currfield->getDisplayValue();
            $tax_percentage_array[$i] = $tax_percentage;
            if ($final_details['taxtype'] == 'group') {
                $netto = $item['Price'] * $item['Qty'] - $item['Discount'];
                // $currfield = new CurrencyField($netto);
                // $currfield->getDBInsertedValue();
                // $netto = $currfield->getDisplayValue();
                // $currfield = new CurrencyField((float) $item['Price']);
                // $currfield->getDBInsertedValue();
                $item['Price'] = (double) $item['Price'];
                // $currfield = new CurrencyField((float) $item['Discount']);
                // $currfield->getDBInsertedValue();
                $item['Discount'] = (double) $item['Discount'];
                // $currfield = new CurrencyField((float) $item['Total']);
                // $currfield->getDBInsertedValue();
                $item['Total'] = (double) $item['Total'];
                $data[$i] = array($i, $item['Product Name'], $item['Qty'], $item['Price'], $item['Discount'], $netto, $item['Total']);
            } else {
                $tax_pln = $item['Tax'] * $kurs_waluty;
                $suma_podatku_w_pln += $tax_pln;
                //$currfield = new CurrencyField( $tax_pln );
                //$tax_pln = $currfield->getDisplayValue();
                $netto = $item['Price'] * $item['Qty'] - $item['Discount'];
                //$currfield = new CurrencyField( $netto );
                //$currfield->getDBInsertedValue();
                //$netto = $currfield->getDisplayValue();
                ////////
                //$currfield = new CurrencyField( (float)$item['Price'] );
                //$currfield->getDBInsertedValue();
                $item['Price'] = (double) $item['Price'];
                //$currfield->getDisplayValue();
                ////////
                $currfield = new CurrencyField((double) $item['Discount']);
                $currfield->getDBInsertedValue();
                $item['Discount'] = (double) $item['Discount'];
                //$currfield->getDisplayValue();
                /////////
                //$currfield = new CurrencyField( (float)$item['tax_percentage'] );
                //$currfield->getDBInsertedValue();
                $tax_percentage = (double) $item['tax_percentage'];
                //$currfield->getDisplayValue();
                //////////
                //$currfield = new CurrencyField( (float)$item['Tax'] );
                //$currfield->getDBInsertedValue();
                $item['Tax'] = (double) $item['Tax'];
                //$currfield->getDisplayValue();
                ///////////
                //$currfield = new CurrencyField( (float)$item['Total'] );
                //$currfield->getDBInsertedValue();
                $item['Total'] = (double) $item['Total'];
                //$currfield->getDisplayValue();
                ////////////
                $data[$i] = array($i, $item['Product Name'], $item['Qty'], $item['Price'], $item['Discount'], $netto, $tax_percentage, $item['Tax'], $item['Total'], $tax_pln);
            }
            $i++;
        }
        if ($final_details['taxtype'] == 'group') {
            $width = array(30, 200, 50, 60, 50, 70, 70);
            $align = array("center", "center", "center", "center", "center", "center", "center");
            $format = array(0, "s", 0, 2, 2, 2, 2);
        } else {
            $width = array(30, 180, 50, 60, 50, 40, 40, 40, 40, 40);
            $align = array("center", "center", "center", "center", "center", "center", "center", "center", "center", "center");
            $format = array(0, "s", 0, 2, 2, 2, 2, 2, 2);
        }
        $product_table = '<table cellpadding="2">';
        $product_table .= '<tr style="background-color: #c8c8c8;" >';
        foreach ($header as $lastKey => $val) {
            $product_table .= '<td style="border:0.2mm solid black;" width="' . $width[$lastKey] . '" height="20" align="' . $align[$lastKey] . '"><b><small>' . $val . '</small></b></td>';
        }
        $product_table .= '</tr>';
        $group_sep = ' ';
        $separatorSql = "SELECT currency_decimal_separator FROM vtiger_users WHERE id = '{$current_user->id}'";
        $separatorResult = $adb->query($separatorSql, true);
        $dec_sep = $adb->query_result($separatorResult, 0, 'currency_decimal_separator');
        $group_sep = $adb->query_result($separatorResult, 0, 'currency_grouping_separator');
        if ($dec_sep == '') {
            $dec_sep = ' ';
        }
        $align = array("center", "left", "center", "center", "center", "center", "center", "center", "center", "center");
        $i = 0;
        foreach ($data as $row) {
            $product_table .= '<tr>';
            $tax_percentage = $tax_percentage_array[$i];
            foreach ($row as $key => $item) {
                if ($format[$i] != 's') {
                    //echo $item;
                } else {
                    $itarr = explode("\n\n", $item);
                    $item = $itarr[0] . ' ' . $itarr[1];
                }
                if ($wyswietlaj[$key]) {
                    if ($key == 9) {
                        if ($czyDrukowacKolumneZPrzeliczonymPodatkiem == TRUE) {
                            $currfield = new CurrencyField(0);
                            $zero = $currfield->getDisplayValue();
                            if ($item != 0 && $kurs_waluty) {
                                //var_dump($item);
                                //exit();
                                $product_table .= '<td style="border: 0.2mm solid black;" width="' . $width[$key] . '" align="' . $align[$key] . '"><small>' . number_format((double) $item, 2, $dec_sep, $group_sep) . '</small></td>';
                            } else {
                                $product_table .= '<td style="border: 0.2mm solid black;" width="' . $width[$key] . '" align="' . $align[$key] . '"><small>np</small></td>';
                            }
                        }
                    } else {
                        if ($key != 0 && $key != 1) {
                            $product_table .= '<td style="border: 0.2mm solid black;' . ($lastKey == 7 ? ' border-right: 0.2mm solid black;' : '') . '" width="' . $width[$key] . '" align="' . $align[$key] . '"><small>' . number_format($item, 2, $dec_sep, $group_sep) . '</small></td>';
                        } else {
                            $product_table .= '<td style="border: 0.2mm solid black;" width="' . $width[$key] . '" align="' . $align[$key] . '"><small>' . $item . '</small></td>';
                        }
                    }
                }
            }
            $product_table .= '</tr>';
            $i++;
        }
        $product_table .= "</table>";
        $i = 0;
        $product_table .= '<table cellpadding="0" cellspacing="0"><tr border="0">';
        if ($enable_ordinal_column) {
            $product_table .= '<td width="' . $width[0] . '"></td>';
        }
        if ($enable_productname_column) {
            $product_table .= '<td width="' . $width[1] . '"></td>';
        }
        if ($enable_amount_column) {
            $product_table .= '<td width="' . $width[2] . '"></td>';
        }
        if ($enable_listprice_column) {
            $product_table .= '<td width="' . $width[3] . '"></td>';
        }
        if ($enable_netprice_column) {
            $product_table .= '<td width="' . $width[4] . '" align="center" valign="middle" style="border: 0.2mm solid black;" ><small><b>' . number_format($total_discount, 2, $dec_sep, $group_sep) . '</b></small></td>';
        }
        if ($enable_discount_column) {
            $product_table .= '<td width="' . $width[5] . '" align="center" valign="middle" style="border: 0.2mm solid black;"><small><b>' . number_format($suma_netto, 2, $dec_sep, $group_sep) . '</b></small></td>';
        }
        if ($enable_vatpercentage_column && $final_details['taxtype'] != 'group') {
            $product_table .= '<td width="' . $width[6] . '"></td>';
        }
        if ($enable_vatamount_column && $final_details['taxtype'] != 'group') {
            $product_table .= '<td width="' . $width[7] . '" align="center" valign="middle" style="border: 0.2mm solid black;"><small><b>' . number_format($suma_vat, 2, $dec_sep, $group_sep) . '</b></small></td>';
        }
        if ($enable_gross_column) {
            $product_table .= '<td width="' . $width[5] . '" align="center" valign="middle" style="border: 0.2mm solid black;"><small><b>' . number_format($suma_brutto, 2, $dec_sep, $group_sep) . '</b></small></td>';
        }
        if ($enable_gross_column && $suma_podatku_w_pln != 0 && $czyDrukowacKolumneZPrzeliczonymPodatkiem == TRUE) {
            $product_table .= '<td width="' . $width[9] . '" align="center" valign="middle" style="border: 0.2mm solid black;"><small><b>' . number_format($suma_podatku_w_pln, 2, $dec_sep, $group_sep) . '</b></small></td>';
        }
        $product_table .= '</tr></table><br/>';
        if ($final_details['taxtype'] == 'group') {
            $grup_tax = 0.0;
            for ($i = 0; $i < 3; $i++) {
                if ($associated_products[1]['final_details']['tax'] == $associated_products[1]['final_details']['taxes'][$i]['taxname']) {
                    $grup_tax = (double) $associated_products[1]['final_details']['taxes'][$i]['amount'];
                    $grup_tax_percent = (double) $associated_products[1]['final_details']['taxes'][$i]['percentage'];
                }
            }
            $currfield = new CurrencyField($grup_tax);
            $grup_tax = $currfield->getDisplayValue();
            $currfield = new CurrencyField($grup_tax_percent);
            $grup_tax_percent = $currfield->getDisplayValue();
        }
        $mod = strtolower($pdftype);
        if ($mod == 'quotes') {
            $idcol = "quoteid";
        } else {
            $idcol = $mod . "id";
        }
        $sql = "SELECT discount_percent, discount_amount, subtotal, total FROM vtiger_{$mod} WHERE {$idcol} = " . $id;
        $result = $adb->query($sql, true);
        $grand_total = $adb->query_result($result, 0, 'total');
        $subtotal = $adb->query_result($result, 0, "subtotal");
        $discount_percent = $adb->query_result($result, 0, 'discount_percent');
        $discount_amount = $adb->query_result($result, 0, 'discount_amount');
        if ($discount_percent != 0) {
            $discount = $subtotal * ($discount_percent / 100.0);
        } else {
            $discount = $discount_amount;
        }
        //$currfield = new CurrencyField( $grand_total );
        //$grand_total = $currfield->getDisplayValue();
        $currfield = new CurrencyField($subtotal);
        $subtotal = $currfield->getDisplayValue();
        $currfield = new CurrencyField($discount);
        $discount = $currfield->getDisplayValue();
        $currfield = new CurrencyField($netto);
        $netto = $currfield->getDisplayValue();
        if ($displays_a_summary_of_invoices == TRUE) {
            $product_table .= '<table width="535px" border="0" cellpadding="2">
                            <tr>
                            <td width="85px"></td>
                            <td width="270px"><br /><br />
                            <table bgcolor="#e8e8e8">';
            $product_table .= '<tr valign="middle"><td align="right"><small><b>' . $languageStrings["SUMMARY"] . '</b></small></td></tr>';
            if ($enable_summary_rebate) {
                $product_table .= '<tr valign="middle"><td align="right"><small><b>' . $languageStrings["Discount Amount"] . '</b> :</small></td></tr>';
            }
            if ($enable_summary_taxpercentage && $final_details['taxtype'] == 'group') {
                $product_table .= '<tr valign="middle"><td align="right"><small><b>' . $languageStrings["The percentage of tax"] . '</b> :</small></td></tr>';
            }
            if ($enable_summary_taxamount && $final_details['taxtype'] == 'group') {
                $product_table .= '<tr valign="middle"><td align="right"><small><b>' . $languageStrings["The amount of tax"] . '</b> :</small></td></tr>';
            }
            if ($enable_summary_topay) {
                $product_table .= '<tr valign="middle"><td align="right"><small><b>' . $languageStrings["Grand Total"] . '</b> :</small></td></tr>';
            }
            if ($enable_date_of_the_course == TRUE && $czyDrukowacKolumneZPrzeliczonymPodatkiem == TRUE) {
                $product_table .= '<tr valign="middle"><td align="right"><small></small></td></tr>';
                $product_table .= '<tr valign="middle"><td align="right"><small><b>' . $languageStrings["rate"] . ' ' . $kod_aktualnej_waluty . ' ' . $languageStrings["on"] . ': ' . $CurrencyUpdate->getCorrectDate($newdate) . '</b> </small></td></tr>';
            }
            $product_table .= '</table>
			</td>
			<td width="160px" ><br />
                <table>';
            $product_table .= '<tr valign="middle"><td align="left"> </td></tr><tr valign="middle"><td align="left"> </td></tr>';
            if ($enable_summary_rebate) {
                $product_table .= '<tr valign="middle"><td align="left"><small>' . number_format($rabat_calkowity, 2, $dec_sep, $group_sep) . ' (' . $symbol_waluty . ')</small></td></tr>';
            }
            if ($enable_summary_taxpercentage && $final_details['taxtype'] == 'group') {
                $product_table .= '<tr valign="middle"><td align="left"><small>' . $grup_tax_percent . ' (%)</small></td></tr>';
            }
            if ($enable_summary_taxpercentage && $final_details['taxtype'] == 'group') {
                $product_table .= '<tr valign="middle"><td align="left"><small>' . number_format($grup_tax, 2, $dec_sep, $group_sep) . ' (' . $symbol_waluty . ')</small></td></tr>';
            }
            if ($enable_summary_topay) {
                $product_table .= '<tr valign="middle"><td align="left"><small>' . number_format($grand_total, 2, $dec_sep, $group_sep) . ' (' . $symbol_waluty . ')</small></td></tr>';
            }
            if ($enable_date_of_the_course == TRUE && $czyDrukowacKolumneZPrzeliczonymPodatkiem == TRUE) {
                if ($kurs_waluty != 0) {
                    $product_table .= '<tr valign="middle"><td align="left"><small></small></td></tr>';
                    $product_table .= '<tr valign="middle"><td align="left"><small>' . $kurs_waluty . '</small></td></tr>';
                } else {
                    $product_table .= '<tr valign="middle"><td align="left"><small></small></td></tr>';
                    $product_table .= '<tr valign="middle"><td align="left"><small>np</small></td></tr>';
                }
            }
            $product_table .= '         
				</table>
			</td>
		</tr></table>
		<br/>';
        }
        return $product_table;
    }
}
Пример #14
0
/**
 * Function to generate Quote pdf
 */
function get_quote_pdf()
{
    require_once 'include/tcpdf/pdf.php';
    require_once 'include/tcpdf/pdfconfig.php';
    require_once 'include/database/PearDatabase.php';
    require_once 'modules/Quotes/Quotes.php';
    global $adb, $app_strings, $current_user;
    // would you like and end page?  1 for yes 0 for no
    $endpage = "1";
    $focus = new Quotes();
    $focus->retrieve_entity_info($_REQUEST['record'], "Quotes");
    $focus->apply_field_security();
    $account_name = getAccountName($focus->column_fields[account_id]);
    $quote_no = $focus->column_fields[quote_no];
    if ($focus->column_fields["hdnTaxType"] == "individual") {
        $product_taxes = 'true';
    } else {
        $product_taxes = 'false';
    }
    $sql = "select currency_symbol from vtiger_currency_info where id=?";
    $result = $adb->pquery($sql, array($focus->column_fields['currency_id']));
    $currency_symbol = $adb->query_result($result, 0, 'currency_symbol');
    // **************** BEGIN POPULATE DATA ********************
    $account_id = $focus->column_fields[account_id];
    $quote_id = $_REQUEST['record'];
    // Quote Information
    $valid_till = $focus->column_fields["validtill"];
    $valid_till = getDisplayDate($valid_till);
    $bill_street = $focus->column_fields["bill_street"];
    $bill_city = $focus->column_fields["bill_city"];
    $bill_state = $focus->column_fields["bill_state"];
    $bill_code = $focus->column_fields["bill_code"];
    $bill_country = $focus->column_fields["bill_country"];
    $contact_name = getContactName($focus->column_fields["contact_id"]);
    $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"];
    $conditions = from_html($focus->column_fields["terms_conditions"]);
    $description = from_html($focus->column_fields["description"]);
    $status = $focus->column_fields["quotestage"];
    // Company information
    $add_query = "select * from vtiger_organizationdetails";
    $result = $adb->pquery($add_query, array());
    $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");
    }
    //Population of Product Details - Starts
    //we can cut and paste the following lines in a file and include that file here is enough. For that we have to put a new common file. we will do this later
    //NOTE : Removed currency symbols and added with Grand Total text. it is enough to show the currency symbol in one place
    //we can also get the NetTotal, Final Discount Amount/Percent, Adjustment and GrandTotal from the array $associated_products[1]['final_details']
    //get the Associated Products for this Invoice
    $focus->id = $focus->column_fields["record_id"];
    $associated_products = getAssociatedProducts("Quotes", $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 = number_format($final_details["hdnSubTotal"], 2, '.', ',');
    //Final discount amount/percentage
    $discount_amount = $final_details["discount_amount_final"];
    $discount_percent = $final_details["discount_percentage_final"];
    if ($discount_amount != "") {
        $price_discount = number_format($discount_amount, 2, '.', ',');
    } else {
        if ($discount_percent != "") {
            //This will be displayed near Discount label - used in include/fpdf/templates/body.php
            $final_price_discount_percent = "(" . number_format($discount_percent, 2, '.', ',') . " %)";
            $price_discount = number_format($discount_percent * $final_details["hdnSubTotal"] / 100, 2, '.', ',');
        } else {
            $price_discount = "0.00";
        }
    }
    //Adjustment
    $price_adjustment = number_format($final_details["adjustment"], 2, '.', ',');
    //Grand Total
    $price_total = number_format($final_details["grandTotal"], 2, '.', ',');
    //To calculate the group tax amount
    if ($final_details['taxtype'] == 'group') {
        $group_tax_total = $final_details['tax_totalamount'];
        $price_salestax = number_format($group_tax_total, 2, '.', ',');
        $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 = number_format($sh_amount, 2, '.', ',');
    //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, 2, '.', ',');
    $prod_line = array();
    $lines = 0;
    //This is to get all prodcut details as row basis
    for ($i = 1, $j = $i - 1; $i <= $num_products; $i++, $j++) {
        $product_name[$i] = $associated_products[$i]['productName' . $i];
        $subproduct_name[$i] = split("<br>", $associated_products[$i]['subprod_names' . $i]);
        //$prod_description[$i] = $associated_products[$i]['productDescription'.$i];
        $comment[$i] = $associated_products[$i]['comment' . $i];
        $product_id[$i] = $associated_products[$i]['hdnProductId' . $i];
        $qty[$i] = $associated_products[$i]['qty' . $i];
        $unit_price[$i] = number_format($associated_products[$i]['unitPrice' . $i], 2, '.', ',');
        $list_price[$i] = number_format($associated_products[$i]['listPrice' . $i], 2, '.', ',');
        $list_pricet[$i] = $associated_products[$i]['listPrice' . $i];
        $discount_total[$i] = $associated_products[$i]['discountTotal' . $i];
        //aded for 5.0.3 pdf changes
        $product_code[$i] = $associated_products[$i]['hdnProductcode' . $i];
        $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;
                $total_taxes = $total_taxes + $tax_amount;
            }
            $producttotal = $taxable_total + $total_taxes;
            $product_line[$j]["Tax"] = number_format($total_taxes, 2, '.', ',') . "\n ({$total_tax_percent} %) ";
            $price_salestax += $total_taxes;
        }
        $prod_total[$i] = number_format($producttotal, 2, '.', ',');
        $product_line[$j]["Product Code"] = $product_code[$i];
        $product_line[$j]["Qty"] = $qty[$i];
        $product_line[$j]["Price"] = $list_price[$i];
        $product_line[$j]["Discount"] = $discount_total[$i];
        $product_line[$j]["Total"] = $prod_total[$i];
        $lines++;
        $product_line[$j]["Product Name"] = decode_html($product_name[$i]);
        $prod_line[$j] = 1;
        for ($count = 0; $count < count($subproduct_name[$i]); $count++) {
            if ($lines % 12 != 0) {
                $product_line[$j]["Product Name"] .= "\n" . decode_html($subproduct_name[$i][$count]);
                $prod_line[$j]++;
            } else {
                $j++;
                $product_line[$j]["Product Name"] = decode_html($product_name[$i]);
                $product_line[$j]["Product Name"] .= "\n" . decode_html($subproduct_name[$i][$count]);
                $prod_line[$j] = 2;
                $lines++;
            }
            $lines++;
        }
        if ($comment[$i] != '') {
            $product_line[$j]["Product Name"] .= "\n" . decode_html($comment[$i]);
            $prod_line[$j]++;
            $lines++;
        }
    }
    $price_salestax = number_format($price_salestax, 2, '.', ',');
    //echo '<pre>Product Details ==>';print_r($product_line);echo '</pre>';
    //echo '<pre>';print_r($associated_products);echo '</pre>';
    //Population of Product Details - Ends
    // ************************ END POPULATE DATA ***************************8
    $page_num = '1';
    $pdf = new PDF('P', 'mm', 'A4');
    $pdf->Open();
    //	$num_pages=ceil(($num_products/$products_per_page));
    //STARTS - Placement of products in pages as per the lines count
    $lines_per_page = "12";
    $prod_cnt = 0;
    $num_pages = ceil($lines / $lines_per_page);
    $tmp = 0;
    for ($count = 0; $count < $num_pages; $count++) {
        for ($k = $tmp; $k < $j; $k++) {
            if ($prod_cnt != 12) {
                $products[$count][] = $k;
                $prod_cnt += $prod_line[$k];
            } else {
                $tmp = $k;
                $prod_cnt = 0;
                break;
            }
        }
    }
    //ENDS - Placement of products in pages as per the lines count
    $current_product = 0;
    for ($l = 0; $l < $num_pages; $l++) {
        $line = array();
        if ($num_pages == $page_num) {
            $lastpage = 1;
        }
        /*while($current_product != $page_num*$products_per_page)
        		{
        			$line[]=$product_line[$current_product];
        			$current_product++;
        		}/*/
        foreach ($products[$l] as $index => $key) {
            $line[] = $product_line[$key];
        }
        $pdf->AddPage();
        include "modules/Quotes/pdf_templates/header.php";
        include "include/tcpdf/templates/body.php";
        //if bottom > 145 then we skip the Description and T&C in every page and display only in lastpage
        //if you want to display the description and T&C in each page then set the display_desc_tc='true' and bottom <= 145 in pdfconfig.php
        if ($display_desc_tc == 'true') {
            if ($bottom <= 145) {
                include "modules/Quotes/pdf_templates/footer.php";
            }
        }
        $page_num++;
        if ($endpage && $lastpage) {
            $pdf->AddPage();
            include "modules/Quotes/pdf_templates/header.php";
            include "modules/Quotes/pdf_templates/lastpage/body.php";
            include "modules/Quotes/pdf_templates/lastpage/footer.php";
        }
    }
    return $pdf;
}
Пример #15
0
    $smarty->assign('UPDATEINFO', updateInfo($record));
}
if (isset($_REQUEST['convertmode']) && $_REQUEST['convertmode'] == 'quotetoinvoice') {
    $smarty->assign("MODE", $quote_focus->mode);
    $se_array = getProductDetailsBlockInfo($quote_focus->mode, "Quotes", $quote_focus);
} elseif (isset($_REQUEST['convertmode']) && ($_REQUEST['convertmode'] == 'sotoinvoice' || $_REQUEST['convertmode'] == 'update_so_val')) {
    $smarty->assign('MODE', $focus->mode);
    $se_array = getProductDetailsBlockInfo($focus->mode, "SalesOrder", $so_focus);
    $txtTax = $so_focus->column_fields['txtTax'] != '' ? $so_focus->column_fields['txtTax'] : '0.000';
    $txtAdj = $so_focus->column_fields['txtAdjustment'] != '' ? $so_focus->column_fields['txtAdjustment'] : '0.000';
    $associated_prod = getAssociatedProducts('SalesOrder', $so_focus);
    $smarty->assign('ASSOCIATEDPRODUCTS', $associated_prod);
    $smarty->assign('MODE', $focus->mode);
} elseif ($focus->mode == 'edit') {
    $smarty->assign('UPDATEINFO', updateInfo($focus->id));
    $associated_prod = getAssociatedProducts('Invoice', $focus);
    $smarty->assign('ASSOCIATEDPRODUCTS', $associated_prod);
    $smarty->assign('MODE', $focus->mode);
} elseif (isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') {
    $associated_prod = $INVOICE_associated_prod;
    $smarty->assign('AVAILABLE_PRODUCTS', 'true');
    $smarty->assign('MODE', $focus->mode);
}
$smarty->assign('ASSOCIATEDPRODUCTS', $associated_prod);
if (isset($_REQUEST['return_module'])) {
    $smarty->assign("RETURN_MODULE", vtlib_purify($_REQUEST['return_module']));
} else {
    $smarty->assign("RETURN_MODULE", "Invoice");
}
if (isset($_REQUEST['return_action'])) {
    $smarty->assign("RETURN_ACTION", vtlib_purify($_REQUEST['return_action']));
Пример #16
0
$smarty->assign("CATEGORY", $category);
$log->info("Quote view");
$smarty->assign("MOD", $mod_strings);
$smarty->assign("APP", $app_strings);
if (isset($focus->name)) {
    $smarty->assign("NAME", $focus->name);
} else {
    $smarty->assign("NAME", "");
}
if (isset($cust_fld)) {
    $log->debug("Custom Field is present");
    $smarty->assign("CUSTOMFIELD", $cust_fld);
}
if ($focus->mode == 'edit') {
    $smarty->assign("UPDATEINFO", updateInfo($focus->id));
    $associated_prod = getAssociatedProducts("Quotes", $focus);
    //getProductDetailsBlockInfo('edit','Quotes',$focus);
    $smarty->assign("ASSOCIATEDPRODUCTS", $associated_prod);
    $smarty->assign("MODE", $focus->mode);
} elseif (isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') {
    $smarty->assign("ASSOCIATEDPRODUCTS", $QUOTE_associated_prod);
    $smarty->assign("AVAILABLE_PRODUCTS", 'true');
    $smarty->assign("MODE", $focus->mode);
} elseif (isset($_REQUEST['potential_id']) && $_REQUEST['potential_id'] != '' || isset($_REQUEST['product_id']) && $_REQUEST['product_id'] != '') {
    $smarty->assign("ASSOCIATEDPRODUCTS", $associated_prod);
    $smarty->assign("MODE", $focus->mode);
    //this is to display the Product Details in first row when we create new PO from Product relatedlist
    if ($_REQUEST['return_module'] == 'Products') {
        $smarty->assign("PRODUCT_ID", vtlib_purify($_REQUEST['product_id']));
        $smarty->assign("PRODUCT_NAME", getProductName($_REQUEST['product_id']));
        $smarty->assign("UNIT_PRICE", vtlib_purify($_REQUEST['product_id']));
Пример #17
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;
}
function replaceCorrectedTableProducts($pdftype, $id, $templateid, $content, $tcpdf)
{
    /* ------------------- COLUMN CONFIGURATION -------------------
    
          In this part, you can decide which columns you want to appear
                           and which are not in the table of positions and invoice summary table
    
                           If the variable responsible for this column has the value TRUE
                           will be displayed and if FALSE it will not be displayed
    
         */
    // The columns for the table from the list of items on the invoice
    $kolumnyDlaPozycjiFaktur = array();
    // column ordinal
    $enable_ordinal_column = TRUE;
    // Column name of the product
    $enable_productname_column = TRUE;
    // column number
    $enable_amount_column = TRUE;
    // unit price column
    $enable_listprice_column = TRUE;
    // net price column
    $enable_netprice_column = TRUE;
    // discount column
    $enable_discount_column = TRUE;
    // Vat column (%)
    $enable_vatpercentage_column = TRUE;
    // Vat column (currency)
    $enable_vatamount_column = TRUE;
    // Gross column
    $enable_gross_column = TRUE;
    // Taxes in PLN
    $enable_taxes_inPLN = TRUE;
    // Column for a summary in the gray box
    $wyswietlaj = array($enable_ordinal_column, $enable_productname_column, $enable_amount_column, $enable_listprice_column, $enable_netprice_column, $enable_discount_column, $enable_vatpercentage_column, $enable_vatamount_column, $enable_gross_column, $enable_taxes_inPLN);
    $kolumnyDlaPodsumowaniaFaktur = array();
    $enable_summary_before_correction = TRUE;
    $enable_summary_including = TRUE;
    $enable_summary_after_correction = TRUE;
    $enable_summary_together = TRUE;
    $db = PearDatabase::getInstance();
    require_once 'include/utils/utils.php';
    include "languages/pl_pl/OSSPdf.php";
    $tab_pl = $languageStrings;
    include "languages/en_us/OSSPdf.php";
    $tab_us = $languageStrings;
    $displays_a_summary_of_invoices = TRUE;
    require_once 'include/utils/CommonUtils.php';
    require_once 'include/fields/CurrencyField.php';
    require_once 'modules/' . $pdftype . '/' . $pdftype . '.php';
    require_once 'modules/' . $pdftype . '/utils.php';
    require_once 'modules/Invoice/Invoice.php';
    $focus = new $pdftype();
    $focus->retrieve_entity_info($id, $pdftype);
    $currency_id = $focus->column_fields['currency_id'];
    $pobierz = $db->query("select currency_symbol, currency_code from vtiger_currency_info where id = '{$currency_id}'", true);
    $kod_aktualnej_waluty = $db->query_result($pobierz, 0, "currency_code");
    $symbol_waluty = $db->query_result($pobierz, 0, "currency_symbol");
    //////////////////////////////
    // check if the module is OSSCurrencyUpdate exist
    $czyDrukowacKolumneZPrzeliczonymPodatkiem = FALSE;
    $moduleFilePath = "modules/OSSCurrencyUpdate/OSSCurrencyUpdate.php";
    $moduleFilePathTpl = "Smarty/templates/modules/OSSCurrencyUpdate/index.tpl";
    $checkInDatabaseSql = "SELECT * FROM vtiger_tab WHERE name = 'OSSCurrencyUpdate'";
    $pobierzGluwnaWaluteSql = $db->query("select currency_code from vtiger_currency_info where id = '1'", true);
    $kod_waluty = $db->query_result($pobierzGluwnaWaluteSql, 0, "currency_code");
    $checkInDatabaseResult = $db->query($checkInDatabaseSql, true);
    $numDB = $db->num_rows($checkInDatabaseResult);
    //var_dump($kod_aktualnej_waluty);
    //$log->error( 'kod waluty: '.$kod_waluty.'; $kod aktualnej: '.$kod_aktualnej_waluty );
    if (file_exists($moduleFilePath) && $numDB > 0 && $kod_waluty == 'PLN' && $kod_aktualnej_waluty != 'PLN' && vtlib_isModuleActive('OSSCurrencyUpdate')) {
        $czyDrukowacKolumneZPrzeliczonymPodatkiem = TRUE;
    }
    if ($czyDrukowacKolumneZPrzeliczonymPodatkiem == TRUE) {
        require_once $moduleFilePath;
    }
    $focus->id = $focus->column_fields["record_id"];
    $associated_products = OSSgetAssociatedProducts($pdftype, $focus);
    $num_products = count($associated_products);
    $vat = array();
    $sales = array();
    $service = array();
    $total_discount = 0.0;
    $suma_netto = 0.0;
    $suma_brutto = $associated_products[1]['final_details']['hdnSubTotal'];
    $rabat_calkowity = $associated_products[1]['final_details']['discount_amount_final'];
    $korekta_rabat = 0.0;
    for ($i = 1; $i <= count($associated_products); $i++) {
        $korekta_rabat += (double) $associated_products[$i]['discount_amount' . $i];
    }
    $suma_vat = 0;
    $inoice_id_sql = "SELECT vtiger_invoice.invoiceid FROM vtiger_invoice JOIN vtiger_osscorrectedinvoice ON vtiger_invoice.invoiceid = vtiger_osscorrectedinvoice.invoiceid WHERE osscorrectedinvoiceid = {$id}";
    $inoice_result = $db->query($inoice_id_sql, true);
    $invoice_id = $db->query_result($inoice_result, 0, 'invoiceid');
    $focus_invoice = new Invoice();
    $focus_invoice->retrieve_entity_info($invoice_id, 'Invoice');
    $focus_invoice->id = $focus_invoice->column_fields["record_id"];
    $associated_products_in = getAssociatedProducts('Invoice', $focus_invoice);
    $subtotal_invoice = $associated_products_in[1]['final_details']['hdnSubTotal'];
    $faktura_rabat = 0.0;
    for ($i = 1; $i <= count($associated_products_in); $i++) {
        $faktura_rabat += (double) $associated_products_in[$i]['discount_amount' . $i];
    }
    $suma_brutto = (double) $suma_brutto;
    $wartosc_korekty_brutto = $suma_brutto - $subtotal_invoice;
    $suma_netto_invoice = 0.0;
    $suma_vat_inv = 0.0;
    $suma_netto_invoice = $associated_products_in[1]['final_details']['hdnSubTotal'];
    for ($i = 1; $i <= count($associated_products_in); $i++) {
        $TotalAfterDiscount_inv = $associated_products_in[$i]['totalAfterDiscount' . $i];
        foreach ($associated_products_in[$i]['taxes'] as $podatek) {
            if ($podatek['taxlabel'] == 'VAT') {
                //$vat[$podatek['percentage']] += $TotalAfterDiscount_inv*($podatek['percentage'] / 100.0);
                $suma_vat_inv += $TotalAfterDiscount_inv * ($podatek['percentage'] / 100.0);
            }
        }
    }
    //var_dump($suma_vat_inv);
    //exit();
    /////////////////////////////
    /// Create a table summary of VAT
    if ($focus->column_fields['hdnTaxType'] == 'group') {
        for ($i = 1; $i <= count($associated_products); $i++) {
            $suma_netto += $associated_products[$i]['totalAfterDiscount' . $i];
            $total_discount += $associated_products[$i]['discountTotal' . $i];
        }
    } else {
        for ($i = 1; $i <= count($associated_products); $i++) {
            $suma_netto += $associated_products[$i]['totalAfterDiscount' . $i];
            $TotalAfterDiscount = $associated_products[$i]['totalAfterDiscount' . $i];
            foreach ($associated_products[$i]['taxes'] as $podatek) {
                if ($podatek['taxlabel'] == 'VAT') {
                    $vat[$podatek['percentage']] += $TotalAfterDiscount * ($podatek['percentage'] / 100.0);
                    $suma_vat += $TotalAfterDiscount * ($podatek['percentage'] / 100.0);
                }
                if ($podatek['taxlabel'] == 'Sales') {
                    $sales[$podatek['percentage']] += $TotalAfterDiscount * ($podatek['percentage'] / 100.0);
                }
                if ($podatek['taxlabel'] == 'Service') {
                    $service[$podatek['percentage']] += $TotalAfterDiscount * ($podatek['percentage'] / 100.0);
                }
            }
            // Calculating the total discount
            $total_discount += $associated_products[$i]['discountTotal' . $i];
        }
    }
    /*
          echo "<br/>vat: ".$suma_vat;
          echo "<br/>netto: ".$suma_netto;
          echo "<br/>brutto: ".$suma_brutto;
          print_r($vat);
          echo "<br /><br />";
          print_r($sales);
          echo "<br /><br />";
          print_r($service);
          echo "<br /><br />";
    
    
          print_r($associated_products);
          exit; */
    ///////////////////////////////////////////////////////////
    //This $final_details array will contain the final total, discount, Group Tax, S&H charge, S&H taxes
    $final_details = $associated_products[1]['final_details'];
    //getting the Net Total
    $price_subtotal = number_format($final_details["hdnSubTotal"], 2, '.', ',');
    //Final discount amount/percentage
    $discount_amount = $final_details["discount_amount_final"];
    $discount_percent = $final_details["discount_percentage_final"];
    if ($discount_amount != "") {
        $price_discount = number_format($discount_amount, 2, '.', ',');
        $price_disc = $discount_amount;
    } else {
        if ($discount_percent != "") {
            //This will be displayed near Discount label - used in include/fpdf/templates/body.php
            $final_price_discount_percent = "(" . number_format($discount_percent, 2, '.', ',') . " %)";
            $price_discount = number_format($discount_percent * $final_details["hdnSubTotal"] / 100, 2, '.', ',');
            $price_disc = $discount_percent * $final_details["hdnSubTotal"];
        } else {
            $price_discount = "0.00";
        }
    }
    //Grand Total
    $price_total = number_format($final_details["grandTotal"], 2, '.', ',');
    //To calculate the group tax amount
    if ($final_details['taxtype'] == 'group') {
        $group_tax_total = $final_details['tax_totalamount'];
        $price_salestax = number_format($group_tax_total, 2, '.', ',');
        $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'];
        }
    }
    $podatek_grupowy = ($final_details["hdnSubTotal"] - $price_disc) * ($group_total_tax_percent / 100.0);
    $tax_pl = 0;
    $suma_podatku_w_pln = 0.0;
    //var_dump($czyDrukowacKolumneZPrzeliczonymPodatkiem);
    //exit;
    if ($czyDrukowacKolumneZPrzeliczonymPodatkiem == TRUE) {
        $invoice_date_sql = "SELECT datecorrection FROM vtiger_osscorrectedinvoice WHERE osscorrectedinvoiceid = {$id}";
        $invoice_date_result = $db->query($invoice_date_sql, true);
        $invoice_date = $db->query_result($invoice_date_result, 0, 'datecorrection');
        $date_tab = explode(" ", $invoice_date);
        $date = $date_tab[0];
        $newdate = strtotime('-1 day', strtotime($date));
        $newdate = date('Y-m-d', $newdate);
        $CurrencyUpdate = Vtiger_Record_Model::getCleanInstance('OSSCurrencyUpdate');
        $kurs_waluty_result = $CurrencyUpdate->getCurrencyRate($newdate, $currency_id);
        $num_rate = $db->num_rows($kurs_waluty_result);
        if ($num_rate == 0) {
            $CurrencyUpdate->getCurrency($newdate);
            $kurs_waluty_result = $CurrencyUpdate->getCurrencyRate($newdate, $currency_id);
            $num_rate = $db->num_rows($kurs_waluty_result);
            if ($num_rate != 0) {
                $kurs_waluty = (double) $db->query_result($kurs_waluty_result, 0, 'kurs');
            }
        } else {
            $kurs_waluty = (double) $db->query_result($kurs_waluty_result, 0, 'kurs');
            $newdate = date('Y-m-d', strtotime($db->query_result($kurs_waluty_result, 0, "data_faktyczna_kursu")));
        }
    }
    $prod_line = array();
    $lines = 0;
    //This is to get all prodcut details as row basis
    for ($i = 1, $j = $i - 1; $i <= $num_products; $i++, $j++) {
        $product_name[$i] = $associated_products[$i]['productName' . $i];
        $subproduct_name[$i] = split("<br>", $associated_products[$i]['subprod_names' . $i]);
        $comment[$i] = $associated_products[$i]['comment' . $i];
        $product_id[$i] = $associated_products[$i]['hdnProductId' . $i];
        $qty[$i] = $associated_products[$i]['qty' . $i];
        $unit_price[$i] = number_format($associated_products[$i]['unitPrice' . $i], 2, '.', ',');
        $list_price[$i] = $associated_products[$i]['listPrice' . $i];
        // number_format($associated_products[$i]['listPrice'.$i],2,'.',',');
        $list_pricet[$i] = $associated_products[$i]['listPrice' . $i];
        $discount_total[$i] = $associated_products[$i]['discountTotal' . $i];
        $product_code[$i] = $associated_products[$i]['hdnProductcode' . $i];
        $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;
                $total_taxes = $total_taxes + $tax_amount;
            }
            $producttotal = $taxable_total + $total_taxes;
            $product_line[$j]["tax_percentage"] = $total_tax_percent;
            $product_line[$j]["Tax"] = $total_taxes;
            $price_salestax += $total_taxes;
        }
        $prod_total[$i] = $producttotal;
        // number_format($producttotal,2,'.',',');
        $product_line[$j]["Product Code"] = $product_code[$i];
        $product_line[$j]["Qty"] = $qty[$i];
        $product_line[$j]["Price"] = $list_price[$i];
        $product_line[$j]["Discount"] = $discount_total[$i];
        $product_line[$j]["Total"] = $prod_total[$i];
        $lines++;
        $product_line[$j]["Product Name"] = '<b>' . decode_html($product_name[$i]) . '</b>';
        $prod_line[$j] = 1;
        for ($count = 0; $count < count($subproduct_name[$i]); $count++) {
            if ($lines % 12 != 0) {
                if ($subproduct_name[$i][$count] != '') {
                    $product_line[$j]["Product Name"] .= "\n <br />" . '<font color="grey" size="-1"><em>' . decode_html($subproduct_name[$i][$count]) . '</em></font>';
                    $prod_line[$j]++;
                }
            } else {
                $j++;
                $product_line[$j]["Product Name"] = decode_html($product_name[$i]);
                $product_line[$j]["Product Name"] .= "\n <br />" . decode_html($subproduct_name[$i][$count]);
                $prod_line[$j] = 2;
                $lines++;
            }
            $lines++;
        }
        if ($comment[$i] != '') {
            $product_line[$j]["Product Name"] .= "\n <br />" . decode_html($comment[$i]);
            $prod_line[$j]++;
            $lines++;
        }
    }
    //Number
    //	print_r($product_line);
    //echo ;
    $price_salestax = number_format($price_salestax, 2, '.', ',');
    if ($final_details['taxtype'] == 'group') {
        $header = array();
        if ($enable_ordinal_column) {
            $header[0] = $mod_strings['LBL_nr'];
        }
        if ($enable_productname_column) {
            $header[1] = $mod_strings['LBL_productname'];
        }
        if ($enable_amount_column) {
            $header[2] = $mod_strings['LBL_Quantity'];
        }
        if ($enable_listprice_column) {
            $header[3] = $mod_strings['LBL_price'];
        }
        if ($enable_discount_column) {
            $header[4] = $mod_strings['LBL_rabat'];
        }
        if ($enable_netprice_column) {
            $header[5] = $mod_strings['LBL_netto'];
        }
        if ($enable_gross_column) {
            $header[6] = $mod_strings['LBL_brutto'];
        }
    } else {
        $header = array();
        if ($enable_ordinal_column) {
            $header[0] = $mod_strings['LBL_nr'];
        }
        if ($enable_productname_column) {
            $header[1] = $mod_strings['LBL_productname'];
        }
        if ($enable_amount_column) {
            $header[2] = $mod_strings['LBL_Quantity'];
        }
        if ($enable_listprice_column) {
            $header[3] = $mod_strings['LBL_price'];
        }
        if ($enable_discount_column) {
            $header[4] = $mod_strings['LBL_rabat'];
        }
        if ($enable_netprice_column) {
            $header[5] = $mod_strings['LBL_netto'];
        }
        if ($enable_vatpercentage_column) {
            $header[6] = $mod_strings['LBL_vat'];
        }
        if ($enable_vatamount_column) {
            $header[7] = $mod_strings['LBL_vat_waluta'] . " (" . $symbol_waluty . ")";
        }
        if ($enable_gross_column) {
            $header[8] = $mod_strings['LBL_brutto'];
        }
        if ($enable_taxes_inPLN && $czyDrukowacKolumneZPrzeliczonymPodatkiem == TRUE) {
            $header[9] = $mod_strings['TAXES_IN_PLN'];
        }
    }
    $data = array();
    $i = 1;
    foreach ($product_line as $item) {
        $currfield = new CurrencyField($item["tax_percentage"]);
        $tax_percentage = $currfield->getDisplayValue();
        if ($final_details['taxtype'] == 'group') {
            $netto = $item['Price'] * $item['Qty'] - $item['Discount'];
            $data[$i] = array($i, $item['Product Name'], $item['Qty'], $item['Price'], $item['Discount'], $netto, $item['Total']);
        } else {
            $tax_pln = $item['Tax'] * $kurs_waluty;
            $suma_podatku_w_pln += $tax_pln;
            $currfield = new CurrencyField($tax_pln);
            $tax_pln = $currfield->getDisplayValue();
            $netto = $item['Price'] * $item['Qty'] - $item['Discount'];
            $data[$i] = array($i, $item['Product Name'], $item['Qty'], $item['Price'], $item['Discount'], $netto, $tax_percentage, $item['Tax'], $item['Total'], $tax_pln);
        }
        $i++;
    }
    if ($final_details['taxtype'] == 'group') {
        $width = array(30, 290, 35, 45, 45, 45, 45);
        $align = array("center", "center", "center", "center", "center", "center", "center");
        $format = array(0, "s", 0, 2, 2, 2, 2);
    } else {
        $width = array(30, 200, 35, 40, 40, 40, 40, 40, 40, 40);
        $align = array("center", "center", "center", "center", "center", "center", "center", "center", "center", "center");
        $format = array(0, "s", 0, 2, 2, 2, 2, 2, 2);
    }
    $group_sep = ' ';
    $separatorSql = "SELECT currency_decimal_separator FROM vtiger_users WHERE id = '{$current_user->id}'";
    $separatorResult = $db->query($separatorSql, true);
    $dec_sep = $db->query_result($separatorResult, 0, 'currency_decimal_separator');
    //$group_sep = $db->query_result($separatorResult, 0, 'currency_grouping_separator');
    //var_dump($data);
    //exit;
    if ($dec_sep == '') {
        $dec_sep = ' ';
    }
    if ($group_sep == $dec_sep) {
        $dec_sep = '.';
    }
    $product_table = '<table border="1" cellpadding="2">';
    $product_table .= '<tr valign="middle">';
    foreach ($header as $key => $val) {
        $product_table .= '<td width="' . $width[$key] . '" height="20" align="' . $align[$key] . '"><b><small>' . $val . '</small></b></td>';
    }
    $product_table .= '</tr>';
    $align = array("center", "left", "center", "center", "center", "center", "center", "center", "center", "center");
    foreach ($data as $row) {
        $product_table .= '<tr>';
        $i = 0;
        $j = 1;
        foreach ($row as $key => $item) {
            $sum[$i] += (double) $item;
            if ($format[$i] == 's') {
                $itarr = explode("\n\n", $item);
                $item = $itarr[0] . ' ' . $itarr[1];
            }
            if ($wyswietlaj[$key]) {
                if ($key == 9) {
                    if ($czyDrukowacKolumneZPrzeliczonymPodatkiem == TRUE) {
                        $currfield = new CurrencyField(0);
                        $zero = $currfield->getDisplayValue();
                        /* echo "<br/>".$tax_percentage;
                            echo "<br/>".$zero;
                            echo "<br/>porownanie".($item != 0 );
                            echo "<br/>".$item;
                           */
                        if ($item != 0 && $kurs_waluty) {
                            $product_table .= '<td width="' . $width[$key] . '" align="' . $align[$key] . '"><small>' . number_format((double) $item, 2, $dec_sep, $group_sep) . '</small></td>';
                        } else {
                            $product_table .= '<td width="' . $width[$key] . '" align="' . $align[$key] . '"><small>np</small></td>';
                        }
                    }
                } else {
                    if ($key != 0 && $key != 1) {
                        //var_dump($item);
                        $product_table .= '<td width="' . $width[$key] . '" align="' . $align[$key] . '"><small>' . number_format((double) $item, 2, $dec_sep, $group_sep) . '</small></td>';
                    } else {
                        $product_table .= '<td width="' . $width[$key] . '" align="' . $align[$key] . '"><small>' . $item . '</small></td>';
                    }
                }
            }
            $i++;
        }
        $product_table .= '</tr>';
    }
    //exit;
    $product_table .= "</table>";
    $i = 0;
    $roznica_vat = $suma_vat - $suma_vat_inv;
    $roznica_netto = $suma_netto - (double) $suma_netto_invoice;
    $suma_netto_poz = $suma_netto;
    $suma_brutto_poz = $suma_brutto;
    /*
     $currfield = new CurrencyField( $suma_netto_poz );
     $suma_netto_poz = $currfield->getDisplayValue();
    
     $currfield = new CurrencyField( $total_discount );
     $total_discount = $currfield->getDisplayValue();
    
     $currfield = new CurrencyField( $suma_vat );
     $suma_vat = $currfield->getDisplayValue();
    
     $currfield = new CurrencyField( $suma_brutto_poz );
     $suma_brutto_poz = $currfield->getDisplayValue();
    */
    $product_table .= '<table cellpadding="0" cellspacing="0"><tr border="0">';
    if ($enable_ordinal_column) {
        $product_table .= '<td width="' . $width[0] . '"></td>';
    }
    if ($enable_productname_column) {
        $product_table .= '<td width="' . $width[1] . '"></td>';
    }
    if ($enable_amount_column) {
        $product_table .= '<td width="' . $width[2] . '"></td>';
    }
    if ($enable_listprice_column) {
        $product_table .= '<td width="' . $width[3] . '"></td>';
    }
    if ($enable_netprice_column) {
        $product_table .= '<td width="' . $width[5] . '"><table border="1"><tr><td width="40" cellpadding="0" align="center" valign="middle"><small><b>' . number_format($total_discount, 2, $dec_sep, $group_sep) . '</b></small></td></tr></table></td>';
    }
    if ($enable_discount_column) {
        $product_table .= '<td width="' . $width[4] . '"><table border="1"><tr><td width="40" cellpadding="0" align="center" valign="middle"><small><b>' . number_format($suma_netto_poz, 2, $dec_sep, $group_sep) . '</b></small></td></tr></table></td>';
    }
    if ($enable_vatpercentage_column && $final_details['taxtype'] != 'group') {
        $product_table .= '<td width="' . $width[6] . '"></td>';
    }
    if ($enable_vatamount_column && $final_details['taxtype'] != 'group') {
        $product_table .= '<td width="' . $width[7] . '"><table border="1"><tr><td width="40" cellpadding="0" align="center" valign="middle"><small><b>' . number_format($suma_vat, 2, $dec_sep, $group_sep) . '</b></small></td></tr></table></td>';
    }
    if ($enable_gross_column) {
        $product_table .= '<td width="' . $width[8] . '"><table border="1"><tr><td width="40" cellpadding="0" align="center" valign="middle"><small><b>' . number_format($suma_brutto_poz, 2, $dec_sep, $group_sep) . '</b></small></td></tr></table></td>';
    }
    if ($enable_taxes_inPLN == TRUE && $czyDrukowacKolumneZPrzeliczonymPodatkiem == TRUE) {
        if ($suma_podatku_w_pln != 0) {
            $product_table .= '<td width="' . $width[9] . '"><table border="1"><tr><td width="40" cellpadding="0" align="center" valign="middle"><small><b>' . number_format($suma_podatku_w_pln, 2) . '</b></small></td></tr></table></td>';
        } else {
            $product_table .= '<td width="' . $width[9] . '"><table border="1"><tr><td width="40" cellpadding="0" align="center" valign="middle"><small><b>np</b></small></td></tr></table></td>';
        }
    }
    $product_table .= '</tr></table>';
    if ($final_details['taxtype'] == 'group') {
        $grup_tax = 0.0;
        for ($i = 0; $i < 3; $i++) {
            if ($associated_products[1]['final_details']['taxes'] == $associated_products[1]['final_details']['taxes'][$i]['taxname']) {
                $grup_tax += (double) $associated_products[1]['final_details']['taxes'][$i]['amount'];
                $grup_tax_percent += (double) $associated_products[1]['final_details']['taxes'][$i]['percentage'];
            }
        }
        $currfield = new CurrencyField($grup_tax);
        $grup_tax = $currfield->getDisplayValue();
        $currfield = new CurrencyField($grup_tax_percent);
        $grup_tax_percent = $currfield->getDisplayValue();
    }
    $mod = strtolower($pdftype);
    if ($mod == 'quotes') {
        $idcol = "quoteid";
    } else {
        $idcol = $mod . "id";
    }
    $sql = "SELECT discount_percent, discount_amount, subtotal, total FROM vtiger_{$mod} WHERE {$idcol} = " . $id;
    $result = $db->query($sql, true);
    $grand_total = $db->query_result($result, 0, 'total');
    $subtotal = $db->query_result($result, 0, "subtotal");
    $discount_percent = $db->query_result($result, 0, 'discount_percent');
    $discount_amount = $db->query_result($result, 0, 'discount_amount');
    if ($discount_percent != 0) {
        $discount = $subtotal * ($discount_percent / 100.0);
    } else {
        $discount = $discount_amount;
    }
    $currfield = new CurrencyField($grand_total);
    $grand_total = $currfield->getDisplayValue();
    $currfield = new CurrencyField($subtotal);
    $subtotal = $currfield->getDisplayValue();
    $currfield = new CurrencyField($discount);
    $discount = $currfield->getDisplayValue();
    $currfield = new CurrencyField($rabat_calkowity);
    $rabat_calkowity = $currfield->getDisplayValue();
    $currfield = new CurrencyField($netto);
    $netto = $currfield->getDisplayValue();
    if ($displays_a_summary_of_invoices) {
        $product_table .= '<table width="535px" border="0" cellpadding="0" cellspacing="0">
                            <tr>
                            <td width="85px"></td>
                            <td width="220px"><br />
                            <table bgcolor="#C0C0C0">';
        $product_table .= '<tr valign="middle"><td align="right"><small><b>' . $tab_pl["SUMMARY"] . ' / ' . $tab_us["SUMMARY"] . '</b></small></td></tr>';
        if ($enable_summary_together) {
            $product_table .= '<tr valign="middle"><td align="right"><small><b>' . $tab_pl["LBL_TOGETHER"] . ' / ' . $tab_us["LBL_TOGETHER"] . '</b> :</small></td></tr>';
        }
        if ($enable_summary_before_correction) {
            $product_table .= '<tr valign="middle"><td align="right"><small><b>' . $tab_pl["LBL_BEFORE_CORRECTION"] . ' / ' . $tab_us["LBL_BEFORE_CORRECTION"] . '</b> :</small></td></tr>';
        }
        if ($enable_summary_after_correction) {
            $product_table .= '<tr valign="middle"><td align="right"><small><b>' . $tab_pl["LBL_AFTER_CORRECTION"] . ' / ' . $tab_us["LBL_AFTER_CORRECTION"] . '</b> :</small></td></tr>';
        }
        if ($enable_summary_including) {
            $product_table .= '<tr valign="middle"><td align="right"><small><b>' . $tab_pl["LBL_INCLUDING"] . ' / ' . $tab_us["LBL_INCLUDING"] . '</b> :</small></td></tr>';
        }
        $razem_rabat = $faktura_rabat - $korekta_rabat;
        $product_table .= '</table>
                    </td>
                    <td width="40px" ><br />
                            <table border="1">';
        $product_table .= '<tr valign="middle"><td align="left"></td></tr>';
        if ($enable_summary_together) {
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($razem_rabat, 2, $dec_sep, $group_sep) . '</small></td></tr>';
        }
        if ($enable_summary_before_correction) {
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($faktura_rabat, 2, $dec_sep, $group_sep) . '</small></td></tr>';
        }
        if ($enable_summary_after_correction) {
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($korekta_rabat, 2, $dec_sep, $group_sep) . '</small></td></tr>';
        }
        if ($enable_summary_including) {
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($razem_rabat, 2, $dec_sep, $group_sep) . '</small></td></tr>';
        }
        $product_table .= '</table>
                    </td>
                    <td width="40px" ><br />
                            <table border="1">';
        $product_table .= '<tr valign="middle"><td align="left"></td></tr>';
        if ($enable_summary_together) {
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($roznica_netto, 2, $dec_sep, $group_sep) . '</small></td></tr>';
        }
        if ($enable_summary_before_correction) {
            //$suma_netto_invoice = $suma_netto_invoice - $faktura_rabat;
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($suma_netto_invoice, 2, $dec_sep, $group_sep) . ' </small></td></tr>';
        }
        if ($enable_summary_after_correction) {
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($suma_netto, 2, $dec_sep, $group_sep) . ' </small></td></tr>';
        }
        if ($enable_summary_including) {
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($roznica_netto, 2, $dec_sep, $group_sep) . ' </small></td></tr>';
        }
        $product_table .= '</table>
                    </td>
                    <td width="40px" ><br />
                            <table border="1">';
        $product_table .= '<tr valign="middle"><td align="left"></td></tr>';
        if ($enable_summary_together) {
            $product_table .= '<tr valign="middle"><td align="center"><small>X</small></td></tr>';
        }
        if ($enable_summary_before_correction) {
            $product_table .= '<tr valign="middle"><td align="center"><small>X</small></td></tr>';
        }
        if ($enable_summary_after_correction) {
            $product_table .= '<tr valign="middle"><td align="center"><small>X</small></td></tr>';
        }
        if ($enable_summary_including) {
            $product_table .= '<tr valign="middle"><td align="center"><small>X</small></td></tr>';
        }
        $product_table .= '</table>
                    </td>
                    <td width="40px" ><br />
                            <table border="1">';
        $product_table .= '<tr valign="middle"><td align="left"></td></tr>';
        if ($enable_summary_together) {
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($roznica_vat, 2, $dec_sep, $group_sep) . '</small></td></tr>';
        }
        if ($enable_summary_before_correction) {
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($suma_vat_inv, 2, $dec_sep, $group_sep) . ' </small></td></tr>';
        }
        if ($enable_summary_after_correction) {
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($suma_vat, 2, $dec_sep, $group_sep) . ' </small></td></tr>';
        }
        if ($enable_summary_including) {
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($roznica_vat, 2, $dec_sep, $group_sep) . ' </small></td></tr>';
        }
        $product_table .= '</table>
                    </td>
                    <td width="40px" ><br />
                            <table border="1">';
        $product_table .= '<tr valign="middle"><td align="left"></td></tr>';
        if ($enable_summary_together) {
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($wartosc_korekty_brutto, 2, $dec_sep, $group_sep) . '</small></td></tr>';
        }
        if ($enable_summary_before_correction) {
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($subtotal_invoice, 2, $dec_sep, $group_sep) . ' </small></td></tr>';
        }
        if ($enable_summary_after_correction) {
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($suma_brutto, 2, $dec_sep, $group_sep) . ' </small></td></tr>';
        }
        if ($enable_summary_including) {
            $product_table .= '<tr valign="middle"><td align="center"><small>' . number_format($wartosc_korekty_brutto, 2, $dec_sep, $group_sep) . ' </small></td></tr>';
        }
        $product_table .= '         
                            </table>
                    </td>
                    </tr></table>
                    <br/>';
    }
    //		$currfield = new CurrencyField( $grand_total );
    //$grand_total = $currfield->getDBInsertedValue( $grand_total );
    //$kwota = $this->slownie( $grand_total );
    //$content = str_replace( "#amount_words#",  $kwota , $content );
    return $product_table;
}
Пример #19
0
    function replaceProductTableNP($content, $pdftype, $id)
    {
        $current_language = Users_Record_Model::getCurrentUserModel()->get('language');
        require_once 'include/utils/utils.php';
        include "modules/OSSPdf/language/" . $current_language . ".lang.php";
        require_once 'include/utils/CommonUtils.php';
        require_once 'include/fields/CurrencyField.php';
        require_once 'modules/' . $pdftype . '/' . $pdftype . '.php';
        $db = PearDatabase::getInstance();
        $focus = new $pdftype();
        $focus->retrieve_entity_info($id, $pdftype);
        $focus->id = $focus->column_fields["record_id"];
        $associated_products = getAssociatedProducts($pdftype, $focus);
        $num_products = count($associated_products);
        $currency_id = $focus->column_fields['currency_id'];
        $pobierz = $db->query("select currency_symbol from vtiger_currency_info where id = '{$currency_id}'", true);
        $symbol_waluty = $db->query_result($pobierz, 0, "currency_symbol");
        //This $final_details array will contain the final total, discount, Group Tax, S&H charge, S&H taxes
        $final_details = $associated_products[1]['final_details'];
        //getting the Net Total
        $price_subtotal = number_format($final_details["hdnSubTotal"], 2, '.', ',');
        //Final discount amount/percentage
        $discount_amount = $final_details["discount_amount_final"];
        $discount_percent = $final_details["discount_percentage_final"];
        if ($discount_amount != "") {
            $price_discount = number_format($discount_amount, 2, '.', ',');
        } else {
            if ($discount_percent != "") {
                //This will be displayed near Discount label - used in include/fpdf/templates/body.php
                $final_price_discount_percent = "(" . number_format($discount_percent, 2, '.', ',') . " %)";
                $price_discount = number_format($discount_percent * $final_details["hdnSubTotal"] / 100, 2, '.', ',');
            } else {
                $price_discount = "0.00";
            }
        }
        //Grand Total
        $price_total = number_format($final_details["grandTotal"], 2, '.', ',');
        //To calculate the group tax amount
        if ($final_details['taxtype'] == 'group') {
            $group_tax_total = $final_details['tax_totalamount'];
            $price_salestax = number_format($group_tax_total, 2, '.', ',');
            $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'];
            }
        }
        $prod_line = array();
        $lines = 0;
        //This is to get all prodcut details as row basis
        for ($i = 1, $j = $i - 1; $i <= $num_products; $i++, $j++) {
            $product_name[$i] = $associated_products[$i]['productName' . $i];
            $subproduct_name[$i] = split("<br>", $associated_products[$i]['subprod_names' . $i]);
            //$prod_description[$i] = $associated_products[$i]['productDescription'.$i];
            $comment[$i] = $associated_products[$i]['comment' . $i];
            $product_id[$i] = $associated_products[$i]['hdnProductId' . $i];
            $qty[$i] = $associated_products[$i]['qty' . $i];
            $unit_price[$i] = number_format($associated_products[$i]['unitPrice' . $i], 2, '.', ',');
            $list_price[$i] = $associated_products[$i]['listPrice' . $i];
            // number_format($associated_products[$i]['listPrice'.$i],2,'.',',');
            $list_pricet[$i] = $associated_products[$i]['listPrice' . $i];
            $discount_total[$i] = $associated_products[$i]['discountTotal' . $i];
            //aded for 5.0.3 pdf changes
            $product_code[$i] = $associated_products[$i]['hdnProductcode' . $i];
            $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;
                    $total_taxes = $total_taxes + $tax_amount;
                }
                $producttotal = $taxable_total + $total_taxes;
                $product_line[$j]["tax_percentage"] = $total_tax_percent;
                $product_line[$j]["Tax"] = $total_taxes;
                $price_salestax += $total_taxes;
            }
            $prod_total[$i] = $producttotal;
            $product_line[$j]["Product Code"] = $product_code[$i];
            $product_line[$j]["Qty"] = $qty[$i];
            $product_line[$j]["Price"] = $list_price[$i];
            $product_line[$j]["Discount"] = $discount_total[$i];
            $product_line[$j]["Total"] = $prod_total[$i];
            $lines++;
            $product_line[$j]["Product Name"] = decode_html($product_name[$i]);
            $prod_line[$j] = 1;
            for ($count = 0; $count < count($subproduct_name[$i]); $count++) {
                if ($lines % 12 != 0) {
                    $product_line[$j]["Product Name"] .= "\n" . decode_html($subproduct_name[$i][$count]);
                    $prod_line[$j]++;
                } else {
                    $j++;
                    $product_line[$j]["Product Name"] = decode_html($product_name[$i]);
                    $product_line[$j]["Product Name"] .= "\n" . decode_html($subproduct_name[$i][$count]);
                    $prod_line[$j] = 2;
                    $lines++;
                }
                $lines++;
            }
            if ($comment[$i] != '') {
                $product_line[$j]["Product Name"] .= "\n" . decode_html($comment[$i]);
                $prod_line[$j]++;
                $lines++;
            }
        }
        $price_salestax = number_format($price_salestax, 2, '.', ',');
        $header = array($mod_strings['LBL_nr'], $mod_strings['LBL_productname'], $mod_strings['LBL_Quantity'], $mod_strings['LBL_price'], $mod_strings['LBL_netto'], $mod_strings['LBL_rabat'], $mod_strings['LBL_vat'], $mod_strings['LBL_brutto']);
        $data = array();
        $i = 0;
        foreach ($product_line as $item) {
            $data[$i++] = array($i, $item['Product Name'], $item['Qty'], $item['Price'], $item['Price'] * $item['Qty'], $item['Discount'], 'NP', $item['Total']);
        }
        $width = array(30, 245, 35, 45, 45, 45, 45, 45);
        $align = array("center", "center", "center", "center", "center", "center", "center", "center");
        $format = array(0, "s", 0, 2, 2, 2, "np", 2);
        $product_table = '<table border="1" cellpadding="2">';
        $product_table .= '<tr valign="middle">';
        for ($i = 0; $i < count($header); $i++) {
            $product_table .= '<td width="' . $width[$i] . '" height="20" align="' . $align[$i] . '"><b><small>' . $header[$i] . '</small></b></td>';
        }
        $product_table .= '</tr>';
        $align = array("center", "left", "center", "center", "center", "center", "center", "center", "center");
        //Data
        foreach ($data as $row) {
            $product_table .= '<tr>';
            $i = 0;
            foreach ($row as $item) {
                $sum[$i] += (double) $item;
                if ($format[$i] == 's') {
                    $itarr = explode("\n\n", $item);
                    $item = '<b>' . $itarr[0] . '</b><br/><small>' . $itarr[1] . '</small>';
                } elseif ($format[$i] == 'np') {
                } else {
                    $currfield = new CurrencyField($item);
                    $item = $currfield->getDisplayValue();
                }
                $product_table .= '<td width="' . $width[$i] . '" align="' . $align[$i++] . '"><small>' . $item . '</small></td>';
            }
            $product_table .= '</tr>';
        }
        $product_table .= "</table>";
        $i = 0;
        $mod = strtolower($pdftype);
        if ($mod == 'quotes') {
            $idcol = "quoteid";
        } else {
            $idcol = $mod . "id";
        }
        $sql = "SELECT discount_percent, discount_amount, subtotal, total FROM vtiger_{$mod} WHERE {$idcol} = " . $this->id;
        $result = $db->query($sql, true);
        $grand_total = $db->query_result($result, 0, 'total');
        $subtotal = $db->query_result($result, 0, "subtotal");
        $discount_percent = $db->query_result($result, 0, 'discount_percent');
        $discount_amount = $db->query_result($result, 0, 'discount_amount');
        if ($discount_percent != 0) {
            $discount = $subtotal * ($discount_percent / 100.0);
        } else {
            $discount = $discount_amount;
        }
        $currfield = new CurrencyField($grand_total);
        $grand_total = $currfield->getDisplayValue();
        $currfield = new CurrencyField($subtotal);
        $subtotal = $currfield->getDisplayValue();
        $currfield = new CurrencyField($discount);
        $discount = $currfield->getDisplayValue();
        $product_table .= '<table width="535px" border="1" cellpadding="2">
			<tr height="10"><td align="right" valign="middle"><small><b>' . getTranslatedString('Net Total', "OSSPdf") . '</b> : ' . $subtotal . '</small></td></tr>
			<tr valign="middle"><td align="right"><small><b>' . getTranslatedString("Discount Amount", "OSSPdf") . '</b> : ' . $discount . '</small></td></tr>
			<tr valign="middle"><td align="right"><small><b>' . getTranslatedString("Grand Total", "OSSPdf") . '</b> : ' . $grand_total . ' (' . $symbol_waluty . ')</small></td></tr>
		</table><br/>';
        $content = str_replace("#product_tableNP#", $product_table, $content);
        $currfield = new CurrencyField($grand_total);
        $grand_total = $currfield->getDBInsertedValue($grand_total);
        $kwota = $this->slownie($grand_total);
        $content = str_replace("#amount_words#", $kwota, $content);
        return $content;
    }
Пример #20
0
$smarty->assign('CATEGORY', $category);
$smarty->assign("THEME", $theme);
$smarty->assign('IMAGE_PATH', "themes/{$theme}/images/");
$smarty->assign('ID', $focus->id);
$smarty->assign('MODE', $focus->mode);
$smarty->assign('CREATEMODE', isset($_REQUEST['createmode']) ? vtlib_purify($_REQUEST['createmode']) : '');
$smarty->assign('CHECK', Button_Check($currentModule));
$smarty->assign('DUPLICATE', $isduplicate);
if ($focus->mode == 'edit' || $isduplicate) {
    $recordName = array_values(getEntityName($currentModule, $record));
    $recordName = $recordName[0];
    $smarty->assign('NAME', $recordName);
    $smarty->assign('UPDATEINFO', updateInfo($record));
}
if ($focus->mode == 'edit') {
    $associated_prod = getAssociatedProducts('Quotes', $focus);
    //getProductDetailsBlockInfo('edit','Quotes',$focus);
    $smarty->assign('ASSOCIATEDPRODUCTS', $associated_prod);
} elseif (isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') {
    $smarty->assign('ASSOCIATEDPRODUCTS', $QUOTE_associated_prod);
    $smarty->assign('AVAILABLE_PRODUCTS', 'true');
    $smarty->assign('MODE', $focus->mode);
} else {
    $smarty->assign('ROWCOUNT', '1');
}
if (isset($_REQUEST['return_module'])) {
    $smarty->assign("RETURN_MODULE", vtlib_purify($_REQUEST['return_module']));
} else {
    $smarty->assign("RETURN_MODULE", "Quotes");
}
if (isset($_REQUEST['return_action'])) {
Пример #21
0
$smarty->assign('CATEGORY', $category);
$smarty->assign("THEME", $theme);
$smarty->assign('IMAGE_PATH', "themes/{$theme}/images/");
$smarty->assign('ID', $focus->id);
$smarty->assign('MODE', $focus->mode);
$smarty->assign('CREATEMODE', isset($_REQUEST['createmode']) ? vtlib_purify($_REQUEST['createmode']) : '');
$smarty->assign('CHECK', Button_Check($currentModule));
$smarty->assign('DUPLICATE', $isduplicate);
if ($focus->mode == 'edit' || $isduplicate) {
    $recordName = array_values(getEntityName($currentModule, $record));
    $recordName = $recordName[0];
    $smarty->assign('NAME', $recordName);
    $smarty->assign('UPDATEINFO', updateInfo($record));
}
if ($focus->mode == 'edit') {
    $associated_prod = getAssociatedProducts("PurchaseOrder", $focus);
    $smarty->assign('ASSOCIATEDPRODUCTS', $associated_prod);
} elseif (isset($_REQUEST['isDuplicate']) && $_REQUEST['isDuplicate'] == 'true') {
    $smarty->assign('ASSOCIATEDPRODUCTS', $PO_associated_prod);
    $smarty->assign('AVAILABLE_PRODUCTS', 'true');
    $smarty->assign('MODE', $focus->mode);
}
if (isset($_REQUEST['return_module'])) {
    $smarty->assign("RETURN_MODULE", vtlib_purify($_REQUEST['return_module']));
} else {
    $smarty->assign("RETURN_MODULE", "PurchaseOrder");
}
if (isset($_REQUEST['return_action'])) {
    $smarty->assign("RETURN_ACTION", vtlib_purify($_REQUEST['return_action']));
} else {
    $smarty->assign("RETURN_ACTION", "index");
 private function _loadProducts()
 {
     $focus = $this->getInternalObject();
     $this->_listitems = array();
     $products = getAssociatedProducts($this->_moduleName, $focus);
     $final_details = $products[1]["final_details"];
     if (isset($final_details)) {
         if (count($this->_groupTax) == 0) {
             $taxes = array();
             if ($final_details["taxtype"] == "group") {
                 foreach ($final_details["taxes"] as $tax) {
                     $taxes[$tax["taxname"] . "_group_percentage"] = $tax["percentage"];
                 }
                 $this->setGroupTaxes($taxes);
             }
         }
         if (count($this->_shipTaxes) == 0) {
             $taxes = array();
             foreach ($final_details["sh_taxes"] as $tax) {
                 $taxes[substr($tax["taxname"], 2) . "_sh_percent"] = $tax["percentage"];
             }
             $this->setShipTaxes($taxes);
         }
         $this->setShippingCost($final_details["shipping_handling_charge"]);
     }
     if (is_array($products) && count($products) > 0) {
         foreach ($products as $index => $product) {
             if (empty($product["hdnProductId" . $index])) {
                 continue;
             }
             $productArray = array("productid" => $product["hdnProductId" . $index], "quantity" => $product["qty" . $index], "comment" => $product["comment" . $index], "description" => $product["productDescription" . $index], "unitprice" => $product["listPrice" . $index], "discount_percent" => $product["discount_percent" . $index], "discount_amount" => $product["discount_amount" . $index]);
             if (!empty($product["taxes"]) && is_array($product["taxes"])) {
                 foreach ($product["taxes"] as $key => $value) {
                     $productArray[$value["taxname"]] = $value["percentage"];
                 }
             }
             $this->_listitems[] = $productArray;
         }
     }
 }