コード例 #1
0
ファイル: Abstract.php プロジェクト: virtual97/avatax
 /**
  * Adds additional transaction based data
  *
  * @param OnePica_AvaTax_Model_Sales_Quote_Address|Mage_Sales_Model_Order $object
  * @return $this
  */
 protected function _addGeneralInfo($object)
 {
     $storeId = $this->_getStoreIdByObject($object);
     $this->_setCompanyCode($storeId);
     $this->_request->setBusinessIdentificationNo($this->_getVatId($object));
     $this->_request->setDetailLevel(DetailLevel::$Document);
     $this->_request->setDocDate($this->_getDateModel()->date('Y-m-d'));
     $this->_request->setExemptionNo('');
     $this->_request->setDiscount(0.0);
     //cannot be used in Magento
     $this->_request->setSalespersonCode(Mage::helper('avatax')->getSalesPersonCode($storeId));
     $this->_request->setLocationCode(Mage::helper('avatax')->getLocationCode($storeId));
     $this->_request->setCountry(Mage::getStoreConfig('shipping/origin/country_id', $storeId));
     $this->_request->setCurrencyCode(Mage::app()->getStore($storeId)->getBaseCurrencyCode());
     $this->_addCustomer($object);
     if ($object instanceof Mage_Sales_Model_Order && $object->getIncrementId()) {
         $this->_request->setReferenceCode('Magento Order #' . $object->getIncrementId());
     }
     return $this;
 }
コード例 #2
0
 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;
 }
 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;
 }
コード例 #4
0
    /**
     * @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($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')})) {
            $address = new Address((int) $this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
        } elseif (isset($this->context->cookie) && isset($this->context->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')) {
                $last_update = Db::getInstance()->getValue('SELECT date_add FROM ' . _DB_PREFIX_ . 'avalara_address_validation_cache WHERE id_address = ' . (int) $address->id);
                if (empty($last_update) || strtotime($address->date_upd) > strtotime($last_update)) {
                    $normalizedAddress = $this->validateAddress($address);
                    Db::getInstance()->Execute('INSERT INTO ' . _DB_PREFIX_ . 'avalara_address_validation_cache (id_address, date_add) VALUES (' . (int) $address->id . ', \'' . pSQL(date('Y-m-d H:i:s')) . '\') ON DUPLICATE KEY UPDATE date_add = \'' . pSQL(date('Y-m-d H:i:s')) . '\'');
                }
            }
            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'] : '');
        if (isset($address->vat_number) && !empty($address->vat_number) && $address->vat_number != 'undefined') {
            $request->setBusinessIdentificationNo($address->vat_number);
        }
        $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
        if (isset($params['cart'])) {
            $request->setDiscount($params['cart']->getOrderTotal(false, Cart::ONLY_DISCOUNTS));
        } else {
            $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(true);
                $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(true);
            $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;
    }