示例#1
0
 /**
  * Adds the shipping address to the request
  *
  * @param Address
  * @return bool
  */
 protected function _setDestinationAddress($address)
 {
     $street1 = $address->getStreet(1);
     $street2 = $address->getStreet(2);
     $city = $address->getCity();
     $zip = $address->getPostcode();
     $state = Mage::getModel('directory/region')->load($address->getRegionId())->getCode();
     $country = $address->getCountry();
     if ($city && $state || $zip) {
         $address = $this->_newAddress($street1, $street2, $city, $state, $zip, $country);
         return $this->_request->setDestinationAddress($address);
     } else {
         return false;
     }
 }
<?php

require '../../AvaTax4PHP/AvaTax.php';
// include in all Avalara Scripts
require '../Credentials.php';
// where service URL, account, license key are set
$client = new TaxServiceSoap('Development');
$request = new GetTaxRequest();
//Add Origin Address
$origin = new Address();
$origin->setLine1("435 Ericksen Ave NE");
$origin->setLine2("Suite 200");
$origin->setCity("Bainbridge Island");
$origin->setRegion("WA");
$origin->setPostalCode("98110-1896");
$request->setOriginAddress($origin);
//Address
//Add Destination address
$destination = new Address();
$destination->setLine1("900 Winslow Way");
$destination->setLine2("Suite 200");
$destination->setCity("Bainbridge Island");
$destination->setRegion("WA");
$destination->setPostalCode("98110");
$request->setDestinationAddress($destination);
//Address
$request->setCompanyCode('DEFAULT');
// Your Company Code From the Dashboard
$request->setDocType(DocumentType::$SalesInvoice);
// Only supported types are SalesInvoice or SalesOrder
$dateTime = new DateTime();
示例#3
0
 function createStandardRequest($calc, $products, $sign = 1)
 {
     if (!class_exists('TaxServiceSoap')) {
         require VMAVALARA_CLASS_PATH . DS . 'TaxServiceSoap.class.php';
     }
     if (!class_exists('DocumentType')) {
         require VMAVALARA_CLASS_PATH . DS . 'DocumentType.class.php';
     }
     if (!class_exists('DetailLevel')) {
         require VMAVALARA_CLASS_PATH . DS . 'DetailLevel.class.php';
     }
     if (!class_exists('Line')) {
         require VMAVALARA_CLASS_PATH . DS . 'Line.class.php';
     }
     if (!class_exists('ServiceMode')) {
         require VMAVALARA_CLASS_PATH . DS . 'ServiceMode.class.php';
     }
     if (!class_exists('Line')) {
         require VMAVALARA_CLASS_PATH . DS . 'Line.class.php';
     }
     if (!class_exists('GetTaxRequest')) {
         require VMAVALARA_CLASS_PATH . DS . 'GetTaxRequest.class.php';
     }
     if (!class_exists('GetTaxResult')) {
         require VMAVALARA_CLASS_PATH . DS . 'GetTaxResult.class.php';
     }
     if (!class_exists('Address')) {
         require VMAVALARA_CLASS_PATH . DS . 'Address.class.php';
     }
     if (is_object($calc)) {
         $calc = get_object_vars($calc);
     }
     $request = new GetTaxRequest();
     $origin = new Address();
     //In Virtuemart we have not differenct warehouses, but we have a shipment address
     //So when the vendor has a shipment address, we assume that it is his warehouse
     //Later we can combine products with shipment addresses for different warehouse (yehye, future music)
     //But for now we just use the BT address
     if (!class_exists('VirtueMartModelVendor')) {
         require JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'vendor.php';
     }
     $userId = VirtueMartModelVendor::getUserIdByVendorId($calc['virtuemart_vendor_id']);
     $userModel = VmModel::getModel('user');
     $virtuemart_userinfo_id = $userModel->getBTuserinfo_id($userId);
     // this is needed to set the correct user id for the vendor when the user is logged
     $userModel->getVendor($calc['virtuemart_vendor_id']);
     $vendorFieldsArray = $userModel->getUserInfoInUserFields('mail', 'BT', $virtuemart_userinfo_id, FALSE, TRUE);
     $vendorFields = $vendorFieldsArray[$virtuemart_userinfo_id];
     $origin->setLine1($vendorFields['fields']['address_1']['value']);
     $origin->setLine2($vendorFields['fields']['address_2']['value']);
     $origin->setCity($vendorFields['fields']['city']['value']);
     $origin->setCountry($vendorFields['fields']['virtuemart_country_id']['country_2_code']);
     $origin->setRegion($vendorFields['fields']['virtuemart_state_id']['state_2_code']);
     $origin->setPostalCode($vendorFields['fields']['zip']['value']);
     $request->setOriginAddress($origin);
     //Address
     if (isset($this->addresses[0])) {
         $destination = $this->addresses[0];
     } else {
         return FALSE;
     }
     if (!class_exists('calculationHelper')) {
         require JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'calculationh.php';
     }
     $calculator = calculationHelper::getInstance();
     $request->setCurrencyCode($calculator->_currencyDisplay->_vendorCurrency_code_3);
     //CurrencyCode
     $request->setDestinationAddress($destination);
     //Address
     $request->setCompanyCode($calc['company_code']);
     // Your Company Code From the Dashboard
     $request->setDocDate(date('Y-m-d'));
     //date, checked
     $request->setCustomerCode(self::$vmadd['customer_number']);
     //string Required
     if (isset(self::$vmadd['tax_usage_type'])) {
         $request->setCustomerUsageType(self::$vmadd['tax_usage_type']);
         //string   Entity Usage
     }
     if (isset(self::$vmadd['tax_exemption_number'])) {
         $request->setExemptionNo(self::$vmadd['tax_exemption_number']);
         //string   if not using ECMS which keys on customer code
     }
     if (isset(self::$vmadd['taxOverride'])) {
         $request->setTaxOverride(self::$vmadd['taxOverride']);
         avadebug('I set tax override ', self::$vmadd['taxOverride']);
     }
     $setAllDiscounted = false;
     if (isset($products['discountAmount'])) {
         if (!empty($products['discountAmount'])) {
             //$request->setDiscount($sign * $products['discountAmount'] * (-1));            //decimal
             $request->setDiscount($sign * $products['discountAmount']);
             //decimal
             vmdebug('We sent as discount ' . $request->getDiscount());
             $setAllDiscounted = true;
         }
         unset($products['discountAmount']);
     }
     $request->setDetailLevel('Tax');
     //Summary or Document or Line or Tax or Diagnostic
     $lines = array();
     $n = 0;
     $this->_lineNumbersToCartProductId = array();
     foreach ($products as $k => $product) {
         $n++;
         $this->_lineNumbersToCartProductId[$n] = $k;
         $line = new Line();
         $line->setNo($n);
         //string  // line Number of invoice
         $line->setItemCode($product['product_sku']);
         //string
         $line->setDescription($product['product_name']);
         //product description, like in cart, atm only the name, todo add customfields
         if (!empty($product['categories'])) {
             //avadebug('AvaTax setTaxCode Product has categories !',$catNames);
             if (!class_exists('TableCategories')) {
                 require JPATH_VM_ADMINISTRATOR . DS . 'tables' . DS . 'categories.php';
             }
             $db = JFactory::getDbo();
             $catTable = new TableCategories($db);
             foreach ($product['categories'] as $cat) {
                 $catTable->load($cat);
                 $catslug = $catTable->slug;
                 if (strpos($catslug, 'avatax-') !== FALSE) {
                     $taxCode = substr($catslug, 7);
                     if (!empty($taxCode)) {
                         $line->setTaxCode($taxCode);
                     } else {
                         vmError('AvaTax setTaxCode, category could not be parsed ' . $catslug);
                     }
                     break;
                 }
             }
         }
         //$line->setTaxCode("");             //string
         $line->setQty($product['amount']);
         //decimal
         $line->setAmount($sign * $product['price'] * $product['amount']);
         //decimal // TotalAmmount
         if ($setAllDiscounted or !empty($product['discount'])) {
             $line->setDiscounted(1);
         } else {
             $line->setDiscounted(0);
         }
         $line->setRevAcct("");
         //string
         $line->setRef1("");
         //string
         $line->setRef2("");
         //string
         if (isset(self::$vmadd['tax_usage_type'])) {
             $line->setCustomerUsageType(self::$vmadd['tax_usage_type']);
             //string   Entity Usage
         }
         if (isset(self::$vmadd['tax_exemption_number'])) {
             $line->setExemptionNo(self::$vmadd['tax_exemption_number']);
             //string   if not using ECMS which keys on customer code
         }
         if (isset(self::$vmadd['taxOverride'])) {
             //create new TaxOverride Object set
             //$line->setTaxOverride(self::$vmadd['taxOverride']);
         }
         $lines[] = $line;
     }
     $this->newATConfig($calc);
     $request->setLines($lines);
     return $request;
 }
    /**
     * @brief Executes tax actions on documents
     *
     * @param Array $products Array of Product for which taxes need to be calculated
     * @param Array $params
     * 		type : (default SalesOrder) SalesOrder|SalesInvoice|ReturnInvoice
     * 		cart : (required for SalesOrder and SalesInvoice) Cart object
     * 		DocCode : (required in ReturnInvoice, and when 'cart' is not set) Specify the Document Code
     *
     */
    public function getTax($products = array(), $params = array())
    {
        $confValues = Configuration::getMultiple(array('AVALARATAX_COMPANY_CODE', 'AVALARATAX_ADDRESS_LINE1', 'AVALARATAX_ADDRESS_LINE2', 'AVALARATAX_CITY', 'AVALARATAX_STATE', 'AVALARATAX_ZIP_CODE'));
        if (!isset($params['type'])) {
            $params['type'] = 'SalesOrder';
        }
        $this->_connectToAvalara();
        $client = new TaxServiceSoap(Configuration::get('AVALARATAX_MODE'));
        $request = new GetTaxRequest();
        if (isset($params['cart']) && (int) $params['cart']->{Configuration::get('PS_TAX_ADDRESS_TYPE')}) {
            $address = new Address((int) $params['cart']->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
        } elseif (isset($this->context->cookie) && isset($this->contract->cookie->id_customer) && $this->context->cookie->id_customer) {
            $address = new Address((int) Db::getInstance()->getValue('SELECT `id_address` FROM `' . _DB_PREFIX_ . 'address`	WHERE `id_customer` = ' . (int) $this->context->cookie->id_customer . ' AND active = 1 AND deleted = 0'));
        }
        if (isset($address)) {
            if (!empty($address->id_state)) {
                $state = new State((int) $address->id_state);
            }
            $addressDest = array();
            $addressDest['Line1'] = $address->address1;
            $addressDest['Line2'] = $address->address2;
            $addressDest['City'] = $address->city;
            $addressDest['Region'] = isset($state) ? $state->iso_code : '';
            $addressDest['PostalCode'] = $address->postcode;
            $addressDest['Country'] = Country::getIsoById($address->id_country);
            // Try to normalize the address depending on option in the BO
            if (Configuration::get('AVALARATAX_ADDRESS_NORMALIZATION')) {
                $normalizedAddress = $this->validateAddress($address);
            }
            if (isset($normalizedAddress['Normalized'])) {
                $addressDest = $normalizedAddress['Normalized'];
            }
            // Add Destination address (Customer address)
            $destination = new AvalaraAddress();
            $destination->setLine1($addressDest['Line1']);
            $destination->setLine2($addressDest['Line2']);
            $destination->setCity($addressDest['City']);
            $destination->setRegion($addressDest['Region']);
            $destination->setPostalCode($addressDest['PostalCode']);
            $destination->setCountry($addressDest['Country']);
            $request->setDestinationAddress($destination);
        }
        // Origin Address (Store Address or address setup in BO)
        $origin = new AvalaraAddress();
        $origin->setLine1(isset($confValues['AVALARATAX_ADDRESS_LINE1']) ? $confValues['AVALARATAX_ADDRESS_LINE1'] : '');
        $origin->setLine2(isset($confValues['AVALARATAX_ADDRESS_LINE2']) ? $confValues['AVALARATAX_ADDRESS_LINE2'] : '');
        $origin->setCity(isset($confValues['AVALARATAX_CITY']) ? $confValues['AVALARATAX_CITY'] : '');
        $origin->setRegion(isset($confValues['AVALARATAX_STATE']) ? $confValues['AVALARATAX_STATE'] : '');
        $origin->setPostalCode(isset($confValues['AVALARATAX_ZIP_CODE']) ? $confValues['AVALARATAX_ZIP_CODE'] : '');
        $request->setOriginAddress($origin);
        $request->setCompanyCode(isset($confValues['AVALARATAX_COMPANY_CODE']) ? $confValues['AVALARATAX_COMPANY_CODE'] : '');
        $orderId = isset($params['cart']) ? (int) $params['cart']->id : (int) $params['DocCode'];
        $nowTime = date('mdHis');
        // Type: Only supported types are SalesInvoice or SalesOrder
        if ($params['type'] == 'SalesOrder') {
            // SalesOrder: Occurs when customer adds product to the cart (generally to check how much the tax will be)
            $request->setDocType(DocumentType::$SalesOrder);
        } elseif ($params['type'] == 'SalesInvoice') {
            $request->setDocType(DocumentType::$SalesInvoice);
            $orderId = Db::getInstance()->getValue('SELECT `id_order` FROM ' . _DB_PREFIX_ . 'orders WHERE `id_cart` = ' . (int) $params['cart']->id);
            // Make sure we got the orderId, even if it was/wasn't passed in $params['DocCode']
        } elseif ($params['type'] == 'ReturnInvoice') {
            $orderId = isset($params['type']) && $params['type'] == 'ReturnInvoice' ? $orderId . '.' . $nowTime : $orderId;
            $orderDate = Db::getInstance()->ExecuteS('
			SELECT `id_order`, `date_add`
			FROM `' . _DB_PREFIX_ . 'orders`
			WHERE ' . (isset($params['cart']) ? '`id_cart` = ' . (int) $params['cart']->id : '`id_order` = ' . (int) $params['DocCode']));
            $request->setDocType(DocumentType::$ReturnInvoice);
            $request->setCommit(true);
            $taxOverride = new TaxOverride();
            $taxOverride->setTaxOverrideType(TaxOverrideType::$TaxDate);
            $taxOverride->setTaxDate(date('Y-m-d', strtotime($orderDate[0]['date_add'])));
            $taxOverride->setReason('Refund');
            $request->setTaxOverride($taxOverride);
        }
        if (isset($this->context->cookie->id_customer)) {
            $customerCode = $this->context->cookie->id_customer;
        } else {
            if (isset($params['DocCode'])) {
                $id_order = (int) $params['DocCode'];
            } elseif (isset($_POST['id_order'])) {
                $id_order = (int) $_POST['id_order'];
            } elseif (isset($params['id_order'])) {
                $id_order = (int) $params['id_order'];
            } else {
                $id_order = 0;
            }
            $customerCode = (int) Db::getInstance()->getValue('SELECT `id_customer` FROM `' . _DB_PREFIX_ . 'orders` WHERE `id_order` = ' . (int) $id_order);
        }
        $request->setDocCode('Order ' . Tools::safeOutput($orderId));
        // Order Id - has to be float due to the . and more numbers for returns
        $request->setDocDate(date('Y-m-d'));
        // date
        $request->setCustomerCode('CustomerID: ' . (int) $customerCode);
        // string Required
        $request->setCustomerUsageType('');
        // string Entity Usage
        $request->setDiscount(0.0);
        // decimal
        $request->setDetailLevel(DetailLevel::$Tax);
        // Summary or Document or Line or Tax or Diagnostic
        // Add line
        $lines = array();
        $i = 0;
        foreach ($products as $product) {
            // Retrieve the tax_code for the current product if not defined
            if (isset($params['taxable']) && !$params['taxable']) {
                $taxCode = 'NT';
            } else {
                $taxCode = !isset($product['tax_code']) ? $this->getProductTaxCode((int) $product['id_product']) : $product['tax_code'];
            }
            if (isset($product['id_product'])) {
                $line = new Line();
                $line->setNo($i++);
                // string line Number of invoice ($i)
                $line->setItemCode((int) $product['id_product'] . ' - ' . substr($product['name'], 0, 20));
                $line->setDescription(substr(Tools::safeOutput($product['name'] . ' - ' . $product['description_short']), 0, 250));
                $line->setTaxCode($taxCode);
                $line->setQty(isset($product['quantity']) ? (double) $product['quantity'] : 1);
                $line->setAmount($params['type'] == 'ReturnInvoice' && (double) $product['total'] > 0 ? (double) $product['total'] * -1 : (double) $product['total']);
                $line->setDiscounted(false);
                $lines[] = $line;
            }
        }
        // Send shipping as new line
        if (isset($params['cart'])) {
            $line = new Line();
            $line->setNo('Shipping');
            // string line Number of invoice ($i)
            $line->setItemCode('Shipping');
            $line->setDescription('Shipping costs');
            if (isset($params['taxable']) && !$params['taxable']) {
                $line->setTaxCode('NT');
            } else {
                $line->setTaxCode('FR020100');
            }
            // Default TaxCode for Shipping. Avalara will decide depending on the State if taxes should be charged or not
            $line->setQty(1);
            $line->setAmount((double) $params['cart']->getOrderTotal(false, Cart::ONLY_SHIPPING));
            $line->setDiscounted(false);
            $lines[] = $line;
        }
        $request->setLines($lines);
        $buffer = array();
        try {
            $result = $client->getTax($request);
            $buffer['ResultCode'] = Tools::safeOutput($result->getResultCode());
            if ($result->getResultCode() == SeverityLevel::$Success) {
                $buffer['DocCode'] = Tools::safeOutput($request->getDocCode());
                $buffer['TotalAmount'] = Tools::safeOutput($result->getTotalAmount());
                $buffer['TotalTax'] = Tools::safeOutput($result->getTotalTax());
                $buffer['NowTime'] = $nowTime;
                foreach ($result->getTaxLines() as $ctl) {
                    $buffer['TaxLines'][$ctl->getNo()]['GetTax'] = Tools::safeOutput($ctl->getTax());
                    $buffer['TaxLines'][$ctl->getNo()]['TaxCode'] = Tools::safeOutput($ctl->getTaxCode());
                    foreach ($ctl->getTaxDetails() as $ctd) {
                        $buffer['TaxLines'][$ctl->getNo()]['TaxDetails']['JurisType'] = Tools::safeOutput($ctd->getJurisType());
                        $buffer['TaxLines'][$ctl->getNo()]['TaxDetails']['JurisName'] = Tools::safeOutput($ctd->getJurisName());
                        $buffer['TaxLines'][$ctl->getNo()]['TaxDetails']['Region'] = Tools::safeOutput($ctd->getRegion());
                        $buffer['TaxLines'][$ctl->getNo()]['TaxDetails']['Rate'] = Tools::safeOutput($ctd->getRate());
                        $buffer['TaxLines'][$ctl->getNo()]['TaxDetails']['Tax'] = Tools::safeOutput($ctd->getTax());
                    }
                }
            } else {
                foreach ($result->getMessages() as $msg) {
                    $buffer['Messages']['Name'] = Tools::safeOutput($msg->getName());
                    $buffer['Messages']['Summary'] = Tools::safeOutput($msg->getSummary());
                }
            }
        } catch (SoapFault $exception) {
            $buffer['Exception']['FaultString'] = Tools::safeOutput($exception->faultstring);
            $buffer['Exception']['LastRequest'] = Tools::safeOutput($client->__getLastRequest());
            $buffer['Exception']['LastResponse'] = Tools::safeOutput($client->__getLastResponse());
        }
        return $buffer;
    }
 function wc_autoship_taxnow_add_tax_rates($tax_rates, $schedule_id)
 {
     include_once WP_PLUGIN_DIR . '/taxnow_woo/taxnow-woo.class.php';
     include_once WP_PLUGIN_DIR . '/woocommerce-autoship/classes/wc-autoship-schedule.php';
     if (class_exists('class_taxNOW_woo') && class_exists('WC_Autoship_Schedule')) {
         // Create TaxNOW instance
         $taxnow_woo = new class_taxNOW_woo();
         // Get autoship schedule
         $schedule = new WC_Autoship_Schedule($schedule_id);
         // Get autoship customer
         $customer = $schedule->get_customer();
         // Create service
         $service = $taxnow_woo->create_service('TaxServiceSoap', false);
         $request = new GetTaxRequest();
         $request->setDocDate(date('Y-m-d', current_time('timestamp')));
         $request->setDocCode('');
         $request->setCustomerCode($customer->get_email());
         $request->setCompanyCode(get_option('tnwoo_company_code'));
         $request->setDocType(DocumentType::$SalesOrder);
         $request->setDetailLevel(DetailLevel::$Tax);
         $request->setCurrencyCode(get_option('woocommerce_currency'));
         $request->setBusinessIdentificationNo(get_option('tnwoo_business_vat_id'));
         // Origin address
         $origin = new Address();
         $origin->setLine1(get_option('tnwoo_origin_street'));
         $origin->setCity(get_option('tnwoo_origin_city'));
         $origin->setRegion(get_option('tnwoo_origin_state'));
         $origin->setPostalCode(get_option('tnwoo_origin_zip'));
         $origin->setCountry(get_option('tnwoo_origin_country'));
         $request->setOriginAddress($origin);
         // Destination address
         $destination = new Address();
         $destination->setLine1($customer->get('shipping_address_1'));
         $destination->setCity($customer->get('shipping_city'));
         $destination->setRegion($customer->get('shipping_state'));
         $destination->setPostalCode($customer->get('shipping_postcode'));
         $destination->setCountry($customer->get('shipping_country'));
         $request->setDestinationAddress($destination);
         // Lines items
         $items = $schedule->get_items();
         $lines = array();
         $global_tax_code = get_option('tnwoo_default_tax_code');
         foreach ($items as $i => $item) {
             // Get WooCommerce product ID
             $product_id = $item->get_product_id();
             // Create line item
             $line = new Line();
             $line->setItemCode($product_id);
             $line->setDescription($product_id);
             $tax_code = get_post_meta($product_id, '_taxnow_taxcode', true);
             $line->setTaxCode(!empty($tax_code) ? $tax_code : $global_tax_code);
             $line->setQty((int) $item->get_quantity());
             $line->setAmount((double) $item->get_autoship_price());
             $line->setNo($i + 1);
             $line->setDiscounted(0);
             $lines[] = $line;
         }
         $request->setLines($lines);
         // Pretax discount
         $discount_pretax = 0.0;
         // Send request
         $taxnow_woo->log_add_entry('calculate_tax', 'request', $request);
         try {
             $response = $service->getTax($request);
             $taxnow_woo->log_add_entry('calculate_tax', 'response', $response);
             if ($response->getResultCode() == SeverityLevel::$Success) {
                 foreach ($response->GetTaxLines() as $l => $TaxLine) {
                     foreach ($TaxLine->getTaxDetails() as $d => $TaxDetail) {
                         // Create WooCommerce tax rate
                         $tax_rate = array('rate' => 100.0 * $TaxDetail->getRate(), 'label' => $TaxDetail->getTaxName(), 'shipping' => 'no', 'compound' => 'no');
                         $tax_rates["wc_autoship_taxnow_{$l}_{$d}"] = $tax_rate;
                     }
                 }
             }
         } catch (Exception $e) {
             $taxnow_woo->log_add_entry('calculate_tax', 'exception', $e->getMessage());
         }
     }
     // Return tax rates
     return $tax_rates;
 }
示例#6
0
 function getTax($calculationHelper, $calc, $price, $sale = false, $committ = false)
 {
     if ($calc->activated == 0) {
         return false;
     }
     $shopperData = $this->getShopperData();
     if (!$shopperData) {
         return false;
     }
     //if(self::$stop) return self::$stop;
     if (!class_exists('TaxServiceSoap')) {
         require VMAVALARA_CLASS_PATH . DS . 'TaxServiceSoap.class.php';
     }
     if (!class_exists('DocumentType')) {
         require VMAVALARA_CLASS_PATH . DS . 'DocumentType.class.php';
     }
     if (!class_exists('DetailLevel')) {
         require VMAVALARA_CLASS_PATH . DS . 'DetailLevel.class.php';
     }
     if (!class_exists('Line')) {
         require VMAVALARA_CLASS_PATH . DS . 'Line.class.php';
     }
     if (!class_exists('ServiceMode')) {
         require VMAVALARA_CLASS_PATH . DS . 'ServiceMode.class.php';
     }
     if (!class_exists('Line')) {
         require VMAVALARA_CLASS_PATH . DS . 'Line.class.php';
     }
     if (!class_exists('GetTaxRequest')) {
         require VMAVALARA_CLASS_PATH . DS . 'GetTaxRequest.class.php';
     }
     if (!class_exists('GetTaxResult')) {
         require VMAVALARA_CLASS_PATH . DS . 'GetTaxResult.class.php';
     }
     $client = new TaxServiceSoap('Development');
     $request = new GetTaxRequest();
     $origin = new Address();
     //$destination = $this->fillValidateAvalaraAddress($calc);
     //In Virtuemart we have not differenct warehouses, but we have a shipment address
     //So when the vendor has a shipment address, we assume that it is his warehouse
     //Later we can combine products with shipment addresses for different warehouse (yehye, future music)
     //But for now we just use the BT address
     if (!class_exists('VirtueMartModelVendor')) {
         require JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'vendor.php';
     }
     $userId = VirtueMartModelVendor::getUserIdByVendorId($calc->virtuemart_vendor_id);
     $userModel = VmModel::getModel('user');
     $virtuemart_userinfo_id = $userModel->getBTuserinfo_id($userId);
     // this is needed to set the correct user id for the vendor when the user is logged
     $userModel->getVendor($calc->virtuemart_vendor_id);
     $vendorFieldsArray = $userModel->getUserInfoInUserFields('mail', 'BT', $virtuemart_userinfo_id, FALSE, TRUE);
     $vendorFields = $vendorFieldsArray[$virtuemart_userinfo_id];
     //vmdebug('my vendor fields',$vendorFields);
     $origin->setLine1($vendorFields['fields']['address_1']['value']);
     $origin->setLine2($vendorFields['fields']['address_2']['value']);
     $origin->setCity($vendorFields['fields']['city']['value']);
     $origin->setCountry($vendorFields['fields']['virtuemart_country_id']['country_2_code']);
     $origin->setRegion($vendorFields['fields']['virtuemart_state_id']['state_2_code']);
     $origin->setPostalCode($vendorFields['fields']['zip']['value']);
     $request->setOriginAddress($origin);
     //Address
     if (isset($this->addresses[0])) {
         $destination = $this->addresses[0];
     } else {
         return FALSE;
     }
     $request->setDestinationAddress($destination);
     //Address
     //vmdebug('The date',$origin,$destination);
     $request->setCompanyCode($calc->company_code);
     // Your Company Code From the Dashboard
     if ($calc->committ and $sale) {
         $request->setDocType(DocumentType::$SalesInvoice);
         // Only supported types are SalesInvoice or SalesOrder
         $request->setCommit(true);
         //invoice number, problem is that the invoice number is at this time not known, but the order_number may reachable
         $request->setDocCode($committ);
         vmdebug('Request as SalesInvoice with invoiceNumber ' . $committ);
     } else {
         $request->setDocType(DocumentType::$SalesOrder);
         $request->setCommit(false);
         //invoice number, problem is that the invoice number is at this time not known, neither the order_number
         $request->setDocCode('VM2.0.16_order_request');
         vmdebug('Request as SalesOrder');
     }
     $request->setDocDate(date('Y-m-d'));
     //date
     //$request->setSalespersonCode("");             // string Optional
     $request->setCustomerCode($shopperData['customer_id']);
     //string Required
     if (isset($shopperData['tax_usage_type'])) {
         $request->setCustomerUsageType($shopperData['tax_usage_type']);
         //string   Entity Usage
     }
     $cartPrices = $calculationHelper->getCartPrices();
     //vmdebug('$cartPrices',$cartPrices);
     $request->setDiscount($cartPrices['discountAmount']);
     //decimal
     //$request->setDiscount(0.0);
     //	$request->setPurchaseOrderNo("");     //string Optional
     //If I understand correctly, we need to add for this an userfield, for example with the name
     //exemption_no, then user could enter their number.
     if (isset($shopperData['tax_exemption_number'])) {
         $request->setExemptionNo($shopperData['tax_exemption_number']);
         //string   if not using ECMS which keys on customer code
     }
     $request->setDetailLevel('Tax');
     //Summary or Document or Line or Tax or Diagnostic
     //	$request->setReferenceCode1("");       //string Optional
     //	$request->setReferenceCode2("");       //string Optional
     //	$request->setLocationCode("");        //string Optional - aka outlet id for tax forms
     /////////////////////////////////////////
     if (!class_exists('VirtueMartCart')) {
         require JPATH_VM_SITE . DS . 'helpers' . DS . 'cart.php';
     }
     $cart = VirtueMartCart::getCart();
     $products = array();
     if ($calculationHelper->inCart) {
         $products = $cart->products;
         $prices = $calculationHelper->getCartPrices();
         foreach ($products as $k => $product) {
             if (!empty($prices[$k]['discountedPriceWithoutTax'])) {
                 $price = $prices[$k]['discountedPriceWithoutTax'];
             } else {
                 if (!empty($prices[$k]['basePriceVariant'])) {
                     $price = $prices[$k]['basePriceVariant'];
                 } else {
                     vmdebug('There is no price in getTax for product ' . $k . ' ', $prices);
                     $price = 0.0;
                 }
             }
             $product->price = $price;
             if (!empty($price[$k]['discountAmount'])) {
                 $product->discount = $price[$k]['discountAmount'];
             } else {
                 $product->discount = FALSE;
             }
         }
     } else {
         $calculationHelper->_product->price = $price;
         $products[0] = $calculationHelper->_product;
         if (!isset($products[0]->amount)) {
             $products[0]->amount = 1;
         }
         if (isset($calculationHelper->productPrices['discountAmount'])) {
             $products[0]->discount = $calculationHelper->productPrices['discountAmount'];
         } else {
             $products[0]->discount = FALSE;
         }
     }
     $lines = array();
     $n = 0;
     $lineNumbersToCartProductId = array();
     foreach ($products as $k => $product) {
         $n++;
         $lineNumbersToCartProductId[$n] = $k;
         $line = new Line();
         $line->setNo($n);
         //string  // line Number of invoice
         $line->setItemCode($product->product_sku);
         //string
         $line->setDescription($product->product_name);
         //product description, like in cart, atm only the name, todo add customfields
         //$line->setTaxCode("");             //string
         $line->setQty($product->amount);
         //decimal
         $line->setAmount($product->price * $product->amount);
         //decimal // TotalAmmount
         $line->setDiscounted($product->discount * $product->amount);
         //boolean
         $line->setRevAcct("");
         //string
         $line->setRef1("");
         //string
         $line->setRef2("");
         //string
         if (isset($shopperData['tax_exemption_number'])) {
             $line->setExemptionNo($shopperData['tax_exemption_number']);
             //string
         }
         if (isset($shopperData['tax_usage_type'])) {
             $line->setCustomerUsageType($shopperData['tax_usage_type']);
             //string
         }
         $lines[] = $line;
     }
     $line = new Line();
     $line->setNo(++$n);
     //$lineNumbersToCartProductId[$n] = count($products)+1;
     $line->setItemCode($cart->virtuemart_shipmentmethod_id);
     $line->setDescription('Shipment');
     $line->setQty(1);
     //$line->setTaxCode();
     $cartPrices = $calculationHelper->getCartPrices();
     //vmdebug('$calculationHelper $cartPrices',$cartPrices);
     $line->setAmount($cartPrices['shipmentValue']);
     if (isset($shopperData['tax_exemption_number'])) {
         $line->setExemptionNo($shopperData['tax_exemption_number']);
         //string
     }
     if (isset($shopperData['tax_usage_type'])) {
         $line->setCustomerUsageType($shopperData['tax_usage_type']);
         //string
     }
     $lines[] = $line;
     //vmdebug('avalaragetTax setLines',$lines);
     $request->setLines($lines);
     //vmdebug('My request',$request);
     $totalTax = 0.0;
     try {
         if (!class_exists('TaxLine')) {
             require VMAVALARA_CLASS_PATH . DS . 'TaxLine.class.php';
         }
         if (!class_exists('TaxDetail')) {
             require VMAVALARA_CLASS_PATH . DS . 'TaxDetail.class.php';
         }
         vmSetStartTime('avagetTax');
         $getTaxResult = $client->getTax($request);
         vmTime('Avalara getTax', 'avagetTax');
         /*
         * [0] => getDocCode
             [1] => getAdjustmentDescription
             [2] => getAdjustmentReason
             [3] => getDocDate
             [4] => getTaxDate
             [5] => getDocType
             [6] => getDocStatus
             [7] => getIsReconciled
             [8] => getLocked
             [9] => getTimestamp
             [10] => getTotalAmount
             [11] => getTotalDiscount
             [12] => getTotalExemption
             [13] => getTotalTaxable
             [14] => getTotalTax
             [15] => getHashCode
             [16] => getVersion
             [17] => getTaxLines
             [18] => getTotalTaxCalculated
             [19] => getTaxSummary
             [20] => getTaxLine
             [21] => getTransactionId
             [22] => getResultCode
             [23] => getMessages
         */
         //vmdebug( 'GetTax is: '. $getTaxResult->getResultCode(),$getTaxResult);
         if ($getTaxResult->getResultCode() == SeverityLevel::$Success) {
             //vmdebug("DocCode: ".$request->getDocCode() );
             //vmdebug("DocId: ".$getTaxResult->getDocId()."\n");
             vmdebug("TotalAmount: " . $getTaxResult->getTotalAmount());
             $totalTax = $getTaxResult->getTotalTax();
             vmdebug("TotalTax: " . $totalTax);
             foreach ($getTaxResult->getTaxLines() as $ctl) {
                 if ($calculationHelper->inCart) {
                     $nr = $ctl->getNo();
                     if (isset($lineNumbersToCartProductId[$nr])) {
                         $quantity = $products[$lineNumbersToCartProductId[$nr]]->amount;
                         //on the long hand, the taxAmount must be replaced by taxAmountQuantity to avoid rounding errors
                         $prices[$lineNumbersToCartProductId[$ctl->getNo()]]['taxAmount'] = $ctl->getTax() / $quantity;
                         $prices[$lineNumbersToCartProductId[$ctl->getNo()]]['taxAmountQuantity'] = $ctl->getTax();
                     } else {
                         //$this->_cartPrices['shipmentValue'] = 0; //could be automatically set to a default set in the globalconfig
                         //$this->_cartPrices['shipmentTax'] = 0;
                         //$this->_cartPrices['shipmentTotal'] = 0;
                         //$prices = array('shipmentValue'=>$cartPrices['shipmentValue'],'shipmentTax'=> $ctl->getTax(), 'shipmentTotal' =>($cartPrices['shipmentValue'] +$ctl->getTax() ));
                         //vmdebug('my $cartPrices',$cartPrices);
                         $prices['shipmentTax'] = $ctl->getTax();
                         $prices['salesPriceShipment'] = $prices['shipmentValue'] + $ctl->getTax();
                         //$cartPrices = array_merge($prices,$cartPrices);
                         //$calculationHelper->setCartPrices( $cartPrices );
                         $totalTax = $totalTax - $ctl->getTax();
                         //vmdebug('my $cartPrices danach',$cartPrices);
                     }
                 }
                 //vmdebug('my lines ',$ctl);
                 //vmdebug( "     Line: ".$ctl->getNo()." Tax: ".$ctl->getTax()." TaxCode: ".$ctl->getTaxCode());
                 foreach ($ctl->getTaxDetails() as $ctd) {
                     //vmdebug( "          Juris Type: ".$ctd->getJurisType()."; Juris Name: ".$ctd->getJurisName()."; Rate: ".$ctd->getRate()."; Amt: ".$ctd->getTax() );
                 }
             }
             if ($calculationHelper->inCart) {
                 $calculationHelper->setCartPrices($prices);
             }
         } else {
             foreach ($getTaxResult->getMessages() as $msg) {
                 vmError($msg->getName() . ": " . $msg->getSummary());
             }
         }
     } catch (SoapFault $exception) {
         $msg = "Exception: ";
         if ($exception) {
             $msg .= $exception->faultstring;
         }
         vmdebug($msg . '<br />' . $client->__getLastRequest() . '<br />' . $client->__getLastResponse());
     }
     //self::$stop = $totalTax;
     return $totalTax;
 }
function CalcTax($taxSvcSoapClient, $companyCode)
{
    $request = new GetTaxRequest();
    $origin = new Address();
    $destination = new Address();
    $line1 = new Line();
    $origin->setLine1("435 Ericksen Ave NE");
    $origin->setLine2("Suite 200");
    $origin->setCity("Bainbridge Island");
    $origin->setRegion("WA");
    $origin->setPostalCode("98110-1896");
    $destination->setLine1("900 Winslow Way");
    $destination->setLine2("Suite 200");
    $destination->setCity("Bainbridge Island");
    $destination->setRegion("WA");
    $destination->setPostalCode("98110");
    $request->setOriginAddress($origin);
    //Address
    $request->setDestinationAddress($destination);
    //Address
    $request->setCompanyCode($companyCode);
    // Your Company Code From the Dashboard
    $request->setDocType(DocumentType::$SalesInvoice);
    // Only supported types are SalesInvoice or SalesOrder
    $dateTime = new DateTime();
    $docCode = "PHPSample" . date_format($dateTime, "dmyGis");
    $request->setDocCode($docCode);
    //    invoice number
    $request->setDocDate(date_format($dateTime, "Y-m-d"));
    //date
    $request->setSalespersonCode("");
    // string Optional
    $request->setCustomerCode("Cust123");
    //string Required
    $request->setCustomerUsageType("");
    //string   Entity Usage
    $request->setDiscount(0.0);
    //decimal
    $request->setPurchaseOrderNo("");
    //string Optional
    $request->setExemptionNo("");
    //string   if not using ECMS which keys on customer code
    $request->setDetailLevel(DetailLevel::$Document);
    $request->setCommit("true");
    // commit upon tax calc
    $request->setReferenceCode("");
    //string Optional
    $request->setLocationCode("");
    //string Optional - aka outlet id for tax forms
    $line1->setNo("1");
    //string  // line Number of invoice
    $line1->setItemCode("SKU123");
    //string
    $line1->setDescription("Invoice Calculated From PHP SDK");
    //string
    $line1->setTaxCode("");
    //string
    $line1->setQty(1.0);
    //decimal
    $line1->setAmount(1000.0);
    //decimal // TotalAmmount
    $line1->setDiscounted(false);
    //boolean
    $line1->setRevAcct("");
    //string
    $line1->setRef1("");
    //string
    $line1->setRef2("");
    //string
    $line1->setExemptionNo("");
    //string
    $line1->setCustomerUsageType("");
    //string
    $request->setLines(array($line1));
    //array
    try {
        $getTaxResult = $taxSvcSoapClient->getTax($request);
        echo 'GetTax Result: ' . $getTaxResult->getResultCode() . "\n";
        if ($getTaxResult->getResultCode() == SeverityLevel::$Success) {
            echo "DocCode: " . $request->getDocCode() . "\n";
            echo "TotalAmount: " . $getTaxResult->getTotalAmount() . "\n";
            echo "TotalTax: " . $getTaxResult->getTotalTax() . "\n";
        } else {
            foreach ($getTaxResult->getMessages() as $msg) {
                echo $msg->getName() . ": " . $msg->getSummary() . "\n";
            }
        }
    } catch (SoapFault $exception) {
        $msg = "Exception: ";
        if ($exception) {
            $msg .= $exception->faultstring;
        }
        echo $msg . "\n";
        echo $taxSvcSoapClient->__getLastRequest() . "\n";
        echo $taxSvcSoapClient->__getLastResponse() . "\n";
    }
    return $request->getDocCode();
}
 private function CreateTaxRequestForBINo($bino)
 {
     $request = new GetTaxRequest();
     //Set origin Address
     $origin = new Address();
     $origin->setLine1("Avalara");
     $origin->setLine2("900 winslow way");
     $origin->setLine3("Suite 100");
     $origin->setCity("Bainbridge Island");
     $origin->setRegion("WA");
     $origin->setPostalCode("98110-1896");
     $origin->setCountry("USA");
     $request->setOriginAddress($origin);
     //Set destination address
     $destination = new Address();
     $destination->setLine1("3130 Elliott");
     $destination->setCity("Seattle");
     $destination->setRegion("WA");
     $destination->setPostalCode("98121");
     $destination->setCountry("USA");
     $request->setDestinationAddress($destination);
     //Set line
     $line = new Line();
     $line->setNo("1");
     //string  // line Number of invoice
     $line->setBusinessIdentificationNo("LL123");
     $line->setItemCode("Item123");
     //string
     $line->setQty(1.0);
     //decimal
     $line->setAmount(1010.0);
     $request->setLines(array($line));
     $request->setCompanyCode('DEFAULT');
     // Your Company Code From the Dashboard
     $request->setDocCode("DocTypeTest");
     $request->setBusinessIdentificationNo($bino);
     $request->setDocDate(date_format(new DateTime(), "Y-m-d"));
     $request->setCustomerCode("TaxSvcTest");
     //string Required
     $request->setSalespersonCode("");
     // string Optional
     $request->setDetailLevel(DetailLevel::$Tax);
     //Summary or Document or Line or Tax or Diagnostic
     return $request;
 }