PageRenderTime 1393ms CodeModel.GetById 185ms app.highlight 624ms RepoModel.GetById 468ms app.codeStats 1ms

/avalaratax/avalaratax.php

https://github.com/boxdrop/PrestaShop-modules
PHP | 1492 lines | 1255 code | 123 blank | 114 comment | 200 complexity | da98ca1894b4295f70062a28c46107b2 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1<?php
   2/*
   3* 2007-2011 PrestaShop
   4*
   5* NOTICE OF LICENSE
   6*
   7* This source file is subject to the Academic Free License (AFL 3.0)
   8* that is bundled with this package in the file LICENSE.txt.
   9* It is also available through the world-wide-web at this URL:
  10* http://opensource.org/licenses/afl-3.0.php
  11* If you did not receive a copy of the license and are unable to
  12* obtain it through the world-wide-web, please send an email
  13* to license@prestashop.com so we can send you a copy immediately.
  14*
  15* DISCLAIMER
  16*
  17* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
  18* versions in the future. If you wish to customize PrestaShop for your
  19* needs please refer to http://www.prestashop.com for more information.
  20*
  21*  @author PrestaShop SA <contact@prestashop.com>
  22*  @copyright  2007-2014 PrestaShop SA
  23*  @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  24*  International Registered Trademark & Property of PrestaShop SA
  25*/
  26
  27// Security
  28if (!defined('_PS_VERSION_'))
  29	exit;
  30
  31spl_autoload_register('avalaraAutoload');
  32
  33class AvalaraTax extends Module
  34{
  35	/**
  36	 * @brief Constructor
  37	 */
  38	public function __construct()
  39	{
  40		$this->name = 'avalaratax';
  41		$this->tab = 'billing_invoicing';
  42		$this->version = '3.5';
  43		$this->author = 'PrestaShop';
  44		parent::__construct();
  45
  46		$this->displayName = $this->l('Avalara - AvaTax');
  47		$this->description = $this->l('Sales Tax is complicated. AvaTax makes it easy.');
  48		
  49		/** Backward compatibility */
  50		require(_PS_MODULE_DIR_.$this->name.'/backward_compatibility/backward.php');
  51		
  52		if (!extension_loaded('soap') || !class_exists('SoapClient'))
  53			$this->warning = $this->l('SOAP extension should be enabled on your server to use this module.');
  54	}
  55
  56	/**
  57	 * @brief Installation method
  58	 */
  59	public function install()
  60	{
  61		Configuration::updateValue('AVALARATAX_URL', 'https://avatax.avalara.net');
  62		Configuration::updateValue('AVALARATAX_ADDRESS_VALIDATION', 1);
  63		Configuration::updateValue('AVALARATAX_TAX_CALCULATION', 1);
  64		Configuration::updateValue('AVALARATAX_TIMEOUT', 300);
  65
  66		// Value possible : Development / Production
  67		Configuration::updateValue('AVALARATAX_MODE', 'Production');
  68		Configuration::updateValue('AVALARATAX_ADDRESS_NORMALIZATION', 1);
  69		Configuration::updateValue('AVALARATAX_COMMIT_ID', (int)Configuration::get('PS_OS_DELIVERED')); 
  70		Configuration::updateValue('AVALARATAX_CANCEL_ID', (int)Configuration::get('PS_OS_CANCELED'));
  71		Configuration::updateValue('AVALARATAX_REFUND_ID', (int)Configuration::get('PS_OS_REFUND'));
  72		Configuration::updateValue('AVALARATAX_POST_ID', (int)Configuration::get('PS_OS_PAYMENT')); 
  73		Configuration::updateValue('AVALARATAX_STATE', 1);
  74		Configuration::updateValue('PS_TAX_DISPLAY', 1);
  75		Configuration::updateValue('AVALARATAX_COUNTRY', 0);
  76		Configuration::updateValue('AVALARA_CACHE_MAX_LIMIT', 3600); /* The values in cache will be refreshed every 1 minute by default */
  77
  78		// Make sure Avalara Tables don't exist before installation
  79		Db::getInstance()->Execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'avalara_product_cache`');
  80		Db::getInstance()->Execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'avalara_carrier_cache`');
  81		Db::getInstance()->Execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'avalara_address_validation_cache`');
  82		Db::getInstance()->Execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'avalara_returned_products`');
  83		Db::getInstance()->Execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'avalara_temp`');
  84
  85		if (!Db::getInstance()->Execute('
  86		CREATE TABLE `'._DB_PREFIX_.'avalara_product_cache` (
  87		`id_cache` int(10) unsigned NOT NULL auto_increment,
  88		`id_product` int(10) unsigned NOT NULL,
  89		`tax_rate` float(8, 2) unsigned NOT NULL,
  90		`region` varchar(2) NOT NULL,
  91		`id_address` int(10) unsigned NOT NULL,
  92		`update_date` datetime,
  93		PRIMARY KEY (`id_cache`),
  94		UNIQUE (`id_product`, `region`),
  95		KEY `id_product2` (`id_product`,`region`,`id_address`))
  96		ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8') ||
  97			!Db::getInstance()->Execute('
  98		CREATE TABLE `'._DB_PREFIX_.'avalara_carrier_cache` (
  99		`id_cache` int(10) unsigned NOT NULL auto_increment,
 100		`id_carrier` int(10) unsigned NOT NULL,
 101		`tax_rate` float(8, 2) unsigned NOT NULL,
 102		`region` varchar(2) NOT NULL,
 103		`amount` float(8, 2) unsigned NOT NULL,
 104		`update_date` datetime,
 105		`id_cart` int(10) unsigned NOT NULL,
 106		`cart_hash` varchar(32) DEFAULT NULL,
 107		PRIMARY KEY (`id_cache`),
 108		KEY `cart_hash` (`cart_hash`),
 109		KEY `cart_idx` (`id_cart`, `id_carrier`, `region`))
 110		ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8') ||
 111			!Db::getInstance()->Execute('
 112		CREATE TABLE `'._DB_PREFIX_.'avalara_address_validation_cache` (
 113		`id_avalara_address_validation_cache` int(10) unsigned NOT NULL auto_increment,
 114		`id_address` int(10) unsigned NOT NULL,
 115		`date_add` datetime,
 116		PRIMARY KEY (`id_avalara_address_validation_cache`),
 117		UNIQUE (`id_address`))
 118		ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8') ||
 119			!Db::getInstance()->Execute('
 120		CREATE TABLE `'._DB_PREFIX_.'avalara_returned_products` (
 121		`id_returned_product` int(10) unsigned NOT NULL auto_increment,
 122		`id_order` int(10) unsigned NOT NULL,
 123		`id_product` int(10) unsigned NOT NULL,
 124		`total` float(8, 2) unsigned NOT NULL,
 125		`quantity` int(10) unsigned NOT NULL,
 126		`name` varchar(255) NOT NULL,
 127		`description_short` varchar(255) NULL,
 128		`tax_code` varchar(255) NULL,
 129		PRIMARY KEY (`id_returned_product`))
 130		ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8') ||
 131			!Db::getInstance()->Execute('
 132		CREATE TABLE `'._DB_PREFIX_.'avalara_temp` (
 133		`id_order` int(10) unsigned NOT NULL,
 134		`id_order_detail` int(10) unsigned NOT NULL)
 135		ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8') ||
 136			!Db::getInstance()->Execute('
 137		CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'avalara_taxcodes` (
 138		`id_taxcode` int(10) unsigned NOT NULL auto_increment,
 139		`id_product` int(10) unsigned NOT NULL,
 140		`tax_code`  varchar(30) NOT NULL,
 141		`taxable` int(2) unsigned  NOT NULL DEFAULT 1,
 142		PRIMARY KEY (`id_taxcode`),
 143		UNIQUE (`id_product`))
 144		ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8'))
 145			return false;
 146
 147		if (!parent::install() || !$this->registerHook('leftColumn') || !$this->registerHook('updateOrderStatus') ||
 148			!$this->registerHook('cancelProduct') || !$this->registerHook('adminOrder') || !$this->registerHook('backOfficeTop') ||
 149			!$this->registerHook('header') || !$this->overrideFiles())
 150			return false;
 151		return true;
 152	}
 153
 154	public function uninstall()
 155	{
 156		if (!$this->removeOverrideFiles() || !parent::uninstall() ||
 157			!Configuration::deleteByName('AVALARATAX_URL') ||
 158			!Configuration::deleteByName('AVALARATAX_ADDRESS_VALIDATION') ||
 159			!Configuration::deleteByName('AVALARATAX_TAX_CALCULATION') ||
 160			!Configuration::deleteByName('AVALARATAX_TIMEOUT') ||
 161			!Configuration::deleteByName('AVALARATAX_MODE') ||
 162			!Configuration::deleteByName('AVALARATAX_ACCOUNT_NUMBER') ||
 163			!Configuration::deleteByName('AVALARATAX_COMPANY_CODE') ||
 164			!Configuration::deleteByName('AVALARATAX_LICENSE_KEY') ||
 165			!Configuration::deleteByName('AVALARATAX_ADDRESS_NORMALIZATION') ||
 166			!Configuration::deleteByName('AVALARATAX_ADDRESS_LINE1') ||
 167			!Configuration::deleteByName('AVALARATAX_ADDRESS_LINE2') ||
 168			!Configuration::deleteByName('AVALARATAX_CITY') ||
 169			!Configuration::deleteByName('AVALARATAX_STATE') ||
 170			!Configuration::deleteByName('AVALARATAX_ZIP_CODE') ||
 171			!Configuration::deleteByName('AVALARATAX_COUNTRY') ||
 172			!Configuration::deleteByName('AVALARATAX_COMMIT_ID') ||
 173			!Configuration::deleteByName('AVALARATAX_CANCEL_ID') ||
 174			!Configuration::deleteByName('AVALARATAX_REFUND_ID') ||
 175			!Configuration::deleteByName('AVALARA_CACHE_MAX_LIMIT') ||
 176			!Configuration::deleteByName('AVALARATAX_POST_ID') ||
 177			!Configuration::deleteByName('AVALARATAX_CONFIGURATION_OK') ||			
 178			!Db::getInstance()->Execute('DROP TABLE `'._DB_PREFIX_.'avalara_product_cache`') ||
 179			!Db::getInstance()->Execute('DROP TABLE `'._DB_PREFIX_.'avalara_carrier_cache`') ||
 180			!Db::getInstance()->Execute('DROP TABLE `'._DB_PREFIX_.'avalara_address_validation_cache`') ||
 181			!Db::getInstance()->Execute('DROP TABLE `'._DB_PREFIX_.'avalara_returned_products`') ||
 182			!Db::getInstance()->Execute('DROP TABLE `'._DB_PREFIX_.'avalara_temp`'))
 183			return false;
 184		// Do not remove taxcode table
 185		return true;
 186	}
 187
 188	/**
 189	 * @brief Describe the override schema
 190	 */
 191	protected static function getOverrideInfo()
 192	{
 193		return array(
 194			'Tax.php' => array(
 195				'source' => 'override/classes/tax/Tax.php',
 196				'dest' => 'override/classes/Tax.php',
 197				'md5' => array(
 198					'1.1' => '5d9e318d673bfa723b02f14f952e0a7a',
 199					'2.3' => '86c900cd6fff286aa6a52df2ff72228a',
 200					'3.0.2' => 'c558c0b15877980134e301af34e42c3e',
 201				)
 202			),
 203			'Cart.php' => array(
 204				'source' => 'override/classes/Cart.php',
 205				'dest' => 'override/classes/Cart.php',
 206				'md5' => array(
 207					'3.0.2' => 'e4b05425b6dc61f75aad434265f3cac8',
 208					'3.0.3' => 'f7388cb50fbfd300c9f81cc407b7be83',
 209				)
 210			),
 211			'AddressController.php' => array(
 212				'source' => 'override/controllers/front/AddressController.php',
 213				'dest' => 'override/controllers/AddressController.php',
 214				'md5' => array(
 215					'1.1' => 'ebc4f31298395c4b113c7e2d7cc41b4a',
 216					'3.0.2' => 'ff3d9cb2956c35f4229d5277cb2e92e6',
 217					'3.2.1' => 'bc34c1150f7170d3ec7912eb383cd04b',
 218				)
 219			),
 220			'AuthController.php' => array(
 221				'source' => 'override/controllers/front/AuthController.php',
 222				'dest' => 'override/controllers/AuthController.php',
 223				'md5' => array(
 224					'1.1' => '7304d7af971b30f2dcd401b80bbdf805',
 225					'3.0.2' => '3eb86260a7c8d6cfa1d209fb3e8f8bd6',
 226				)
 227			),
 228		);
 229	}
 230
 231	protected function removeOverrideFiles()
 232	{
 233		/** In v1.5, we do not remove override files */
 234		if (version_compare(_PS_VERSION_, '1.5', '<'))
 235			foreach (self::getOverrideInfo() as $key => $params)
 236			{
 237				if (!file_exists(_PS_ROOT_DIR_.'/'.$params['dest']))
 238					continue;
 239
 240				$md5 = md5_file(_PS_ROOT_DIR_.'/'.$params['dest']);
 241				$removed = false;
 242				foreach ($params['md5'] as $hash)
 243					if ($md5 == $hash)
 244					{
 245						if (unlink(_PS_ROOT_DIR_.'/'.$params['dest']))
 246							$removed = true;
 247						break;
 248					}
 249				if (!$removed)
 250					$this->_errors[] = $this->l('Error while removing override: ').$key;
 251			}
 252
 253		return !isset($this->_errors) || !$this->_errors || !count($this->_errors);
 254	}
 255
 256	protected function overrideFiles()
 257	{
 258		/** In v1.5, we do not copy the override files */
 259		if (version_compare(_PS_VERSION_, '1.5', '<') && $this->removeOverrideFiles())
 260		{
 261			/** Check if the override directories exists */
 262			if (!is_dir(_PS_ROOT_DIR_.'/override/classes/'))
 263				mkdir(_PS_ROOT_DIR_.'/override/classes/', 0777, true);
 264			if (!is_dir(_PS_ROOT_DIR_.'/override/controllers/'))
 265				mkdir(_PS_ROOT_DIR_.'/override/controllers/', 0777, true);
 266
 267			foreach (self::getOverrideInfo() as $key => $params)
 268				if (file_exists(_PS_ROOT_DIR_.'/'.$params['dest']))
 269					$this->_errors[] = $this->l('This override file already exists, please merge it manually: ').$key;
 270				elseif (!copy(_PS_MODULE_DIR_.'avalaratax/'.$params['source'], _PS_ROOT_DIR_.'/'.$params['dest']))
 271						$this->_erroors[] = $this->l('Error while copying the override file: ').$key;
 272		}
 273		return !isset($this->_errors) || !$this->_errors || !count($this->_errors);
 274	}
 275
 276	/******************************************************************/
 277	/** Hook Methods **************************************************/
 278	/******************************************************************/
 279
 280	public function hookAdminOrder($params)
 281	{
 282		$this->purgeTempTable();
 283	}
 284
 285	public function hookCancelProduct($params)
 286	{
 287		if (isset($_POST['cancelProduct']))
 288		{
 289			$order = new Order((int)$_POST['id_order']);
 290			if (!Validate::isLoadedObject($order))
 291				return false;
 292			if ($order->invoice_number)
 293			{
 294				// Get all the cancel product's IDs
 295				$cancelledIdsOrderDetail = array();
 296				foreach ($_POST['cancelQuantity'] as $idOrderDetail => $qty)
 297					if ($qty > 0)
 298						$cancelledIdsOrderDetail[] = (int)$idOrderDetail;
 299				$cancelledIdsOrderDetail = implode(', ', $cancelledIdsOrderDetail);
 300
 301				// Fill temp table
 302				Db::getInstance()->Execute('INSERT INTO '._DB_PREFIX_.'avalara_temp (`id_order`, `id_order_detail`)
 303										VALUES ('.(int)$_POST['id_order'].', '.(int)$params['id_order_detail'].')');
 304				// Check if we are at the end of the loop
 305				$totalLoop = Db::getInstance()->ExecuteS('SELECT COUNT(`id_order`) as totalLines
 306														FROM `'._DB_PREFIX_.'avalara_temp`
 307														WHERE `id_order_detail` IN ('.pSQL($cancelledIdsOrderDetail).')');
 308
 309				if ($totalLoop[0]['totalLines'] != count(array_filter($_POST['cancelQuantity'])))
 310					return false;
 311
 312				// Clean the temp table because we are at the end of the loop
 313				$this->purgeTempTable();
 314
 315				// Get details for cancelledIdsOrderDetail (Grab the info to post to Avalara in English.)
 316				$cancelledProdIdsDetails = Db::getInstance()->ExecuteS('SELECT od.`product_id` as id_product, od.`id_order_detail`, pl.`name`,
 317																		pl.`description_short`, od.`product_price` as price, od.`reduction_percent`,
 318																		od.`reduction_amount`, od.`product_quantity` as quantity, atc.`tax_code`
 319																		FROM '._DB_PREFIX_.'order_detail od
 320																		LEFT JOIN '._DB_PREFIX_.'product p ON (p.id_product = od.product_id)
 321																		LEFT JOIN '._DB_PREFIX_.'product_lang pl ON (pl.id_product = p.id_product)
 322																		LEFT JOIN '._DB_PREFIX_.'avalara_taxcodes atc ON (atc.id_product = p.id_product)
 323																		WHERE pl.`id_lang` = '.(int)Configuration::get('PS_LANG_DEFAULT').' AND od.`id_order` = '.(int)$_POST['id_order'].'
 324																		AND od.`id_order_detail` IN ('.pSQL($cancelledIdsOrderDetail).')');
 325				// Build the product list
 326				$products = array();
 327				foreach ($cancelledProdIdsDetails as $cancelProd)
 328					$products[] = array('id_product' => (int)$cancelProd['id_product'],
 329												'quantity' => (int)$_POST['cancelQuantity'][$cancelProd['id_order_detail']],
 330												'total' => pSQL($_POST['cancelQuantity'][$cancelProd['id_order_detail']] * ($cancelProd['price'] - ($cancelProd['price'] * ($cancelProd['reduction_percent'] / 100)) - $cancelProd['reduction_amount'])), // Including those product with discounts
 331												'name' => pSQL(Tools::safeOutput($cancelProd['name'])),
 332												'description_short' => pSQL(Tools::safeOutput($cancelProd['description_short']), true),
 333												'tax_code' => pSQL(Tools::safeOutput($cancelProd['tax_code'])));
 334				// Send to Avalara
 335				$commitResult = $this->getTax($products, array('type' => 'ReturnInvoice', 'DocCode' => (int)$_POST['id_order']));
 336				if ($commitResult['ResultCode'] == 'Warning' || $commitResult['ResultCode'] == 'Error' || $commitResult['ResultCode'] == 'Exception')
 337					echo $this->_displayConfirmation($this->l('The following error was generated while cancelling the orders you selected. <br /> - '.
 338							Tools::safeOutput($commitResult['Messages']['Summary'])), 'error');
 339				else
 340				{
 341					$this->commitToAvalara(array('id_order' => (int)$_POST['id_order']));
 342					echo $this->_displayConfirmation($this->l('The products you selected were cancelled.'));
 343				}
 344			}
 345		}
 346	}
 347
 348	protected function getDestinationAddress($id_order)
 349	{
 350		$order = new Order((int)$id_order);
 351		if (!Validate::isLoadedObject($order))
 352			return false;
 353
 354		$address = new Address((int)$order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
 355		if (!Validate::isLoadedObject($address))
 356			return false;
 357
 358		$state = null;
 359		if (!empty($address->id_state))
 360		{
 361			$state = new State((int)$address->id_state);
 362			if (!Validate::isLoadedObject($state))
 363				return false;
 364		}
 365
 366		return array($address, $state, $order);
 367	}
 368
 369	public function hookUpdateOrderStatus($params)
 370	{
 371		list($params['address'], $params['state'], $params['order']) = self::getDestinationAddress((int)$params['id_order']);
 372
 373		if ($params['newOrderStatus']->id == (int)Configuration::get('AVALARATAX_COMMIT_ID'))
 374			return $this->commitToAvalara($params);
 375		elseif ($params['newOrderStatus']->id == (int)Configuration::get('AVALARATAX_CANCEL_ID'))
 376		{
 377			$params['CancelCode'] = 'V';
 378			$this->cancelFromAvalara($params);
 379			return $this->cancelFromAvalara($params);
 380		}
 381		elseif ($params['newOrderStatus']->id == (int)Configuration::get('AVALARATAX_POST_ID'))
 382			return $this->postToAvalara($params);
 383		elseif ($params['newOrderStatus']->id == (int)Configuration::get('AVALARATAX_REFUND_ID'))
 384			return $this->commitToAvalara($params);
 385
 386		return false;
 387	}
 388
 389	public function hookBackOfficeTop()
 390	{
 391		if (Tools::isSubmit('submitAddproduct') || Tools::isSubmit('submitAddproductAndStay'))
 392			Db::getInstance()->Execute('REPLACE INTO `'._DB_PREFIX_.'avalara_taxcodes` (`id_product`, `tax_code`)
 393				VALUES ('.(isset($_GET['id_product']) ? (int)$_GET['id_product'] : 0).', \''.pSQL(Tools::safeOutput($_POST['tax_code'])).'\')');
 394
 395
 396		if ((isset($_GET['updateproduct']) || isset($_GET['addproduct'])) && isset($_GET['id_product']) && (int)$_GET['id_product'])
 397		{
 398			$r = Db::getInstance()->getRow('
 399			SELECT `tax_code`
 400			FROM `'._DB_PREFIX_.'avalara_taxcodes` atc
 401			WHERE atc.`id_product` = '.(int)Tools::getValue('id_product'));
 402
 403			if (version_compare(_PS_VERSION_, '1.5', '<')) /* v1.4.x an older */
 404			{
 405				return '
 406				<script type="text/javascript">
 407					$(function() {
 408						// Add the Tax Code field
 409						$(\'<tr><td class="col-left">'.$this->l('Tax Code (Avalara)').':</td><td style="padding-bottom:5px;"><input type="text" style="width: 130px; margin-right: 5px;" value="'.
 410							($r ? Tools::safeOutput($r['tax_code']) : '').'" name="tax_code" maxlength="13" size="55"></td></tr>\').appendTo(\'#product #step1 table:eq(0) tbody\');
 411
 412						// override original tax rules
 413						$(\'span #id_tax_rules_group\').parent().html(\'Avalara\');
 414					});
 415				</script>';
 416			}
 417			elseif (version_compare(_PS_VERSION_, '1.6', '<')) /* v1.5.x */
 418			{
 419				return '
 420				<script type="text/javascript">
 421					$(function() {
 422						var done = false;
 423						// Add the Tax Code field
 424						$(\'#link-Informations\').click(function() {
 425										if (done == false) {
 426														done = true;
 427														$(\'<tr><td class="col-left"><label for="tax_code">'.$this->l('Tax Code:').'</label></td><td style="padding-bottom:5px;"><input type="text" style="width: 130px; margin-right: 5px;" value="'.
 428														($r ? Tools::safeOutput($r['tax_code']) : '').'" name="tax_code" maxlength="13" size="55"> <span class="small">(Avalara)</span></td></tr>\').appendTo(\'#step1 table:first tbody\');
 429										}
 430						});
 431
 432						// override original tax rules
 433						$(\'#link-Prices\').click(function() {
 434										$(\'span #id_tax_rules_group\').parent().html(\'Avalara\');
 435						});
 436					});
 437				</script>';
 438			}
 439			else /* v1.6.x and newer */
 440			{
 441				return '
 442				<script type="text/javascript">
 443					$(function() {
 444						var done = false;
 445						// Add the Tax Code field
 446						$(\'#link-Prices\').click(function() {
 447							if (done == false) {
 448								done = true;
 449								$(\'#id_tax_rules_group\').parent().parent().parent().parent().html(\'<div class="form-group"><label class="control-label col-lg-3" for="tax_code"><span class="label-tooltip" data-toggle="tooltip" title="" data-original-title="'.$this->l('Tax rules will be handled by Avalara').'">'.$this->l('Tax Code (Avalara):').'</span></label><div class="input-group col-lg-4"><input type="text" value="'.($r ? Tools::safeOutput($r['tax_code']) : '').'" name="tax_code" maxlength="13" /><div class="alert alert-info" style="margin-top: 40px;">'.$this->l('Tax rules will be handled by Avalara').'</div></div>\');
 450							}
 451						});
 452					});
 453				</script>';
 454			}
 455		}
 456		elseif ((Tools::isSubmit('updatecarrier') || Tools::isSubmit('addcarrier')) && Tools::getValue('id_carrier'))
 457			return '<script type="text/javascript">
 458			$(function() {
 459				// override original tax rules
 460				$(\'div #id_tax_rules_group\').parent().html(\'<label class="t">Avalara</label>\');
 461			});
 462		</script>';
 463
 464		if (Tools::getValue('tab') == 'AdminTaxes' || Tools::getValue('tab') == 'AdminTaxRulesGroup' || Tools::getValue('controller') == 'admintaxes' || Tools::getValue('controller') == 'admintaxrulesgroup')
 465		{
 466			// JS for 1.5
 467			if (version_compare(_PS_VERSION_, '1.5', '>'))
 468				return '<script type="text/javascript">
 469				$(function() {
 470								$(\'#content form\').hide();
 471								$(\'#desc-tax-new\').hide();
 472								$(\'#desc-tax-save\').hide();
 473								$(\'#content div:first\').append(\'<div class="warn">'.$this->l('Tax rules are overwritten by Avalara Tax Module.').'</div>\');
 474				});
 475				</script>';
 476			// JS for 1.4
 477			return '<script type="text/javascript">
 478				$(function() {
 479				if ($(\'#Taxes\').size() || $(\'#submitFiltertax_rules_group\').size())
 480					$(\'#content\').prepend(\'<div class="warn"><img src="../img/admin/warn2.png">'.
 481			$this->l('Tax rules are overwritten by Avalara Tax Module.').'</div>\');
 482				});
 483				</script>';
 484		}
 485		return '';
 486	}
 487
 488	public function hookHeader()
 489	{
 490		if (!$this->context->cart || ((int)$this->context->cart->id_customer && !(int)$this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}))
 491			$id_address = (int)(Db::getInstance()->getValue('SELECT `id_address` FROM `'._DB_PREFIX_.'address` WHERE `id_customer` = '.(int)($this->context->cart->id_customer).' AND `deleted` = 0 ORDER BY `id_address`'));
 492		else
 493			$id_address = $this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')};
 494
 495		if (!(int)$id_address)
 496			return ;
 497		return '<script type="text/javascript">
 498				function refresh_taxes(count)
 499				{
 500					$.ajax({
 501						type : \'POST\',
 502						url : \''.$this->_path.'\' + \'ajax.php\',
 503						data : {
 504							\'id_cart\': "'.(int)$this->context->cart->id.'",
 505							\'id_lang\': "'.(int)$this->context->cookie->id_lang.'",
 506							\'id_address\': "'.(int)$id_address.'",
 507							\'ajax\': "getProductTaxRate",
 508							\'token\': "'.md5(_COOKIE_KEY_.Configuration::get('PS_SHOP_NAME')).'",
 509						},
 510						dataType: \'json\',
 511						success : function(d) {
 512							if (d.hasError == false && d.cached_tax == true)
 513											$(\'#total_tax\').html($(\'body\').data(\'total_tax\'));
 514							else if (d.hasError == false && d.cached_tax == false)
 515											$(\'#total_tax\').html(d.total_tax);
 516							else
 517											$(\'#total_tax\').html(\''.$this->l('Error while calculating taxes').'\');
 518						}
 519					});
 520				}
 521
 522		$(function() {
 523			/* ajax call to cache taxes product taxes that exist in the current cart */
 524			$(\'body\').data(\'total_tax\', $(\'#total_tax\').text());
 525			$(\'#total_tax\').html(\'<img src="img/loader.gif" alt="" />\');
 526			refresh_taxes(1);
 527		});
 528		</script>';
 529	}
 530
 531	/******************************************************************/
 532	/** Main Form Methods *********************************************/
 533	/******************************************************************/
 534	public function getContent()
 535	{
 536		$buffer = '';
 537		
 538		if (version_compare(_PS_VERSION_,'1.5','>'))
 539			$this->context->controller->addJQueryPlugin('fancybox');
 540		else
 541			$buffer .= '<script type="text/javascript" src="'.__PS_BASE_URI__.'js/jquery/jquery.fancybox-1.3.4.js"></script>
 542		  	<link type="text/css" rel="stylesheet" href="'.__PS_BASE_URI__.'css/jquery.fancybox-1.3.4.css" />';
 543
 544		if (Tools::isSubmit('SubmitAvalaraTaxSettings')) 
 545		{
 546			Configuration::updateValue('AVALARATAX_ACCOUNT_NUMBER', Tools::getValue('avalaratax_account_number'));
 547			Configuration::updateValue('AVALARATAX_LICENSE_KEY', Tools::getValue('avalaratax_license_key'));
 548			Configuration::updateValue('AVALARATAX_URL', Tools::getValue('avalaratax_url'));
 549			Configuration::updateValue('AVALARATAX_COMPANY_CODE', Tools::getValue('avalaratax_company_code'));
 550
 551			$connectionTestResult = $this->_testConnection();
 552			if (strpos($connectionTestResult[0], 'Error') === false)
 553			{
 554				Configuration::updateValue('AVALARATAX_CONFIGURATION_OK', true); 
 555				$buffer .= $this->_displayConfirmation();
 556			}
 557		}
 558		elseif (Tools::isSubmit('SubmitAvalaraTaxOptions'))
 559		{
 560			Configuration::updateValue('AVALARATAX_ADDRESS_VALIDATION', Tools::getValue('avalaratax_address_validation'));
 561			Configuration::updateValue('AVALARATAX_TAX_CALCULATION', Tools::getValue('avalaratax_tax_calculation'));
 562			Configuration::updateValue('AVALARATAX_TIMEOUT', (int)Tools::getValue('avalaratax_timeout'));
 563			Configuration::updateValue('AVALARATAX_ADDRESS_NORMALIZATION', Tools::getValue('avalaratax_address_normalization'));
 564			Configuration::updateValue('AVALARATAX_TAX_OUTSIDE', Tools::getValue('avalaratax_tax_outside'));
 565			Configuration::updateValue('AVALARA_CACHE_MAX_LIMIT', (int)Tools::getValue('avalara_cache_max_limit'));
 566
 567			$buffer .= $this->_displayConfirmation();
 568		}
 569		elseif (Tools::isSubmit('SubmitAvalaraTestConnection'))
 570			$connectionTestResult = $this->_testConnection();
 571		elseif (Tools::isSubmit('SubmitAvalaraAddressOptions'))
 572		{
 573			/* Validate address*/
 574			$address = new Address();
 575			$address->address1 = Tools::getValue('avalaratax_address_line1');
 576			$address->address2 = Tools::getValue('avalaratax_address_line2');
 577			$address->city = Tools::getValue('avalaratax_city');
 578			$address->id_state = State::getIdByIso(Tools::getValue('avalaratax_state'));
 579			$address->id_country = Tools::getValue('avalaratax_country');
 580			$address->postcode = Tools::getValue('avalaratax_zip_code');
 581
 582			$normalizedAddress = $this->validateAddress($address);
 583			if (isset($normalizedAddress['ResultCode']) && $normalizedAddress['ResultCode'] == 'Success')
 584			{
 585				$buffer .= $this->_displayConfirmation($this->l('The address you submitted has been validated.'));
 586				Configuration::updateValue('AVALARATAX_ADDRESS_LINE1', $normalizedAddress['Normalized']['Line1']);
 587				Configuration::updateValue('AVALARATAX_ADDRESS_LINE2', $normalizedAddress['Normalized']['Line2']);
 588				Configuration::updateValue('AVALARATAX_CITY', $normalizedAddress['Normalized']['City']);
 589				Configuration::updateValue('AVALARATAX_STATE', $normalizedAddress['Normalized']['Region']);
 590				Configuration::updateValue('AVALARATAX_COUNTRY', $normalizedAddress['Normalized']['Country']);
 591				Configuration::updateValue('AVALARATAX_ZIP_CODE', $normalizedAddress['Normalized']['PostalCode']);
 592			}
 593			else
 594			{
 595				$message = $this->l('The following error was generated while validating your address:');
 596				if (isset($normalizedAddress['Exception']['FaultString']))
 597					$message .= '<br /> - '.Tools::safeOutput($normalizedAddress['Exception']['FaultString']);
 598				if (isset($normalizedAddress['Messages']['Summary']))
 599					foreach ($normalizedAddress['Messages']['Summary'] as $summary)
 600						$message .= '<br /> - '.Tools::safeOutput($summary);
 601				$buffer .= $this->_displayConfirmation($message, 'error');
 602
 603				Configuration::updateValue('AVALARATAX_ADDRESS_LINE1', Tools::getValue('avalaratax_address_line1'));
 604				Configuration::updateValue('AVALARATAX_ADDRESS_LINE2', Tools::getValue('avalaratax_address_line2'));
 605				Configuration::updateValue('AVALARATAX_CITY', Tools::getValue('avalaratax_city'));
 606				Configuration::updateValue('AVALARATAX_STATE', Tools::getValue('avalaratax_state'));
 607				Configuration::updateValue('AVALARATAX_ZIP_CODE', Tools::getValue('avalaratax_zip_code'));
 608			}
 609		}
 610		elseif (Tools::isSubmit('SubmitAvalaraTaxClearCache'))
 611		{
 612			Db::getInstance()->Execute('TRUNCATE TABLE `'._DB_PREFIX_.'avalara_product_cache`');
 613			Db::getInstance()->Execute('TRUNCATE TABLE `'._DB_PREFIX_.'avalara_carrier_cache`');
 614
 615			$buffer .= $this->_displayConfirmation('Cache cleared!');
 616		}
 617
 618		$confValues = Configuration::getMultiple(array(
 619										// Configuration
 620										'AVALARATAX_ACCOUNT_NUMBER', 'AVALARATAX_LICENSE_KEY', 'AVALARATAX_URL', 'AVALARATAX_COMPANY_CODE',
 621										// Options
 622										'AVALARATAX_ADDRESS_VALIDATION', 'AVALARATAX_TAX_CALCULATION', 'AVALARATAX_TIMEOUT',
 623										'AVALARATAX_ADDRESS_NORMALIZATION', 'AVALARATAX_TAX_OUTSIDE', 'AVALARATAX_COMMIT_ID', 'AVALARATAX_CANCEL_ID',
 624										'AVALARATAX_REFUND_ID', 'AVALARATAX_POST_ID', 'AVALARA_CACHE_MAX_LIMIT',
 625										// Default Address
 626										'AVALARATAX_ADDRESS_LINE1', 'AVALARATAX_ADDRESS_LINE2', 'AVALARATAX_CITY', 'AVALARATAX_STATE',
 627										'AVALARATAX_ZIP_CODE', 'AVALARATAX_COUNTRY'));
 628
 629		$stateList = array();
 630		$stateList[] = array('id' => '0', 'name' => $this->l('Choose your state (if applicable)'), 'iso_code' => '--');
 631		foreach (State::getStates((int)$this->context->cookie->id_lang) as $state)
 632			$stateList[] = array('id' => $state['id_state'], 'name' => $state['name'], 'iso_code' => $state['iso_code']);
 633
 634		$countryList = array();
 635		$countryList[] = array('id' => '0', 'name' => $this->l('Choose your country'), 'iso_code' => '--');
 636		foreach (Country::getCountries((int)$this->context->cookie->id_lang, false, null, false) as $country)
 637			$countryList[] = array('id' => $country['id_country'], 'name' => $country['name'], 'iso_code' => $country['iso_code']);
 638
 639		$buffer .= '<link href="'.$this->_path.'css/avalara.css" rel="stylesheet" type="text/css">
 640		<script type="text/javascript">
 641			/* Fancybox */
 642			$(\'a.avalara-video-btn\').live(\'click\', function(){
 643			    $.fancybox({
 644			        \'type\' : \'iframe\',
 645			        \'href\' : this.href.replace(new RegExp("watch\\?v=", "i"), \'embed\') + \'?rel=0&autoplay=1\',
 646			        \'swf\': {\'allowfullscreen\':\'true\', \'wmode\':\'transparent\'},
 647			        \'overlayShow\' : true,
 648			        \'centerOnScroll\' : true,
 649			        \'speedIn\' : 100,
 650			        \'speedOut\' : 50,
 651			        \'width\' : 853,
 652			        \'height\' : 480
 653			    });
 654			    return false;
 655			});
 656		</script>
 657		<script type="text/javascript">
 658			$(document).ready(function(){
 659			    var height1 = 0;
 660			    var height = 0;
 661			     $(\'.field-height1\').each(function(){
 662				if (height1 < $(this).height())
 663				    height1 = $(this).height();
 664			    });
 665			    
 666			    $(\'.field-height\').each(function(){
 667				if (height < $(this).height())
 668				    height = $(this).height();
 669			    });
 670			
 671				$(\'.field-height1\').css({\'height\' : $(\'.field-height1\').css(\'height\', height1+\'px\')});
 672			    $(\'.field-height\').css({\'height\' : $(\'.field-height\').css(\'height\', height+\'px\')});
 673
 674updateAvalaraTaxState($(\'#avalaratax_country\').val());
 675
 676    $(\'#avalaratax_country\').change(function(){
 677updateAvalaraTaxState($(this).val());
 678    });
 679
 680
 681			});
 682function updateAvalaraTaxState(iso_code)
 683{
 684
 685var default_state = "'.$confValues['AVALARATAX_STATE'].'";
 686
 687$(\'#avalaratax_state\').html(\'\');
 688	$.ajax({
 689	    type : \'GET\',
 690	    url : \'../modules/avalaratax/states.php?country_iso_code=\'+iso_code,
 691	    dataType: \'JSON\',
 692	    success: function(data)
 693	    {
 694		if (data != 0)
 695		{
 696		    $.each(data[iso_code], function(i, item){
 697if (default_state == item.state_iso_code)
 698			$(\'#avalaratax_state\').append(\'<option  selected="selected" value="\'+item.state_iso_code+\'">\'+item.name+\'</option>\');
 699else
 700			$(\'#avalaratax_state\').append(\'<option  value="\'+item.state_iso_code+\'">\'+item.name+\'</option>\');
 701			$(\'#avalaratax_state\').show();
 702			$(\'#avalaratax_label_state\').show();
 703		    });
 704		}
 705		else
 706		{
 707		    $(\'#avalaratax_state\').hide();
 708		    $(\'#avalaratax_label_state\').hide();
 709		}
 710	    }
 711	});
 712
 713}
 714
 715		</script>
 716		<div class="avalara-wrap">
 717			<p class="avalara-intro"><a href="http://www.info.avalara.com/prestashop" class="avalara-logo" target="_blank"><img src="'.$this->_path.'img/avalara_logo.png" alt="Avalara" border="0" /></a><a href="http://www.info.avalara.com/prestashop" class="avalara-link" target="_blank">'.$this->l('Create an account').'</a>'.$this->l('Avalara and PrestaShop have partnered to provide the easiest way for you to accurately calculate and file sales tax.').'</p>
 718			<div class="clear"></div>
 719			<div class="avalara-content">
 720				<div class="avalara-video">
 721					<a href="http://www.youtube.com/embed/tm1tENVdcQ8" class="avalara-video-btn"><img src="'.$this->_path.'img/avalara-video-screen.jpg" alt="Avalara Video" /><img src="'.$this->_path.'img/btn-video.png" alt="" class="video-icon" /></a>
 722				</div>
 723				<h3>'.$this->l('Doing sales tax right is simple with Avalara.').'</h3>
 724				<p>'.$this->l('We do all of the research and automate the process for you, ensuring that the system is up-to-date with the most recent sales tax and VAT rates and rules in every state and country, so you don’t have to.  As a cloud-based service, AvaTax eliminates ongoing maintenance and support.  It provides you with a complete solution to manage your sales tax needs.').'</p>
 725				<img src="'.$this->_path.'img/avatax_badge.png" alt="AvaTax Certified" class="avatax-badge" />
 726				<ul>
 727					<li>'.$this->l('Address Validation included').'</li>
 728					<li>'.$this->l('Rooftop Accurate Calculations').'</li>
 729					<li>'.$this->l('Product and Service Taxability Rules').'</li>
 730					<li>'.$this->l('Exemption Certificate Management').'</li>
 731					<li>'.$this->l('Out-of-the-Box Sales Tax Reporting').'</li>
 732				</ul>
 733				<a href="http://www.info.avalara.com/prestashop" class="avalara-link" target="_blank">'.$this->l('Create an account').'</a>
 734				<p class="contact-avalara"><a href="http://www.info.avalara.com/prestashop" target="_blank">'.$this->l('Contact Avalara Today to Start Your Service').'</a></p>
 735			</div>
 736			<fieldset class="field-height1 right-fieldset">
 737			<legend><img src="'.$this->_path.'img/icon-console.gif" alt="" />'.$this->l('AvaTax Admin Console').'</legend>
 738				<p><a href="https://admin-avatax.avalara.net/" target="_blank">'.$this->l('Log-in to AvaTax Admin Console').'</a></p>
 739				<a href="https://admin-avatax.avalara.net/" target="_blank"><img src="'.$this->_path.'img/avatax-logo.png" alt="AvaTax" class="avatax-logo" /></a>
 740			</fieldset>
 741			<form action="'.Tools::safeOutput($_SERVER['REQUEST_URI']).'" method="post" class="left-form">
 742				<fieldset class="field-height1">
 743					<legend><img src="'.$this->_path.'img/icon-config.gif" alt="" />'.$this->l('Configuration').'</legend>
 744					<h4>'.$this->l('AvaTax Credentials').'</h4>';	
 745					if (isset($connectionTestResult))
 746						$buffer .= '<div id="test_connection" style="background: '.Tools::safeOutput($connectionTestResult[1]).';">'.$connectionTestResult[0].'</div>';
 747			
 748					$buffer .= '<label>'.$this->l('Account Number').'</label>
 749					<div class="margin-form">
 750						<input type="text" name="avalaratax_account_number" value="'.(isset($confValues['AVALARATAX_ACCOUNT_NUMBER']) ? Tools::safeOutput($confValues['AVALARATAX_ACCOUNT_NUMBER']) : '').'" />
 751					</div>
 752					<label>'.$this->l('License Key').'</label>
 753					<div class="margin-form">
 754						<input type="text" name="avalaratax_license_key" value="'.(isset($confValues['AVALARATAX_LICENSE_KEY']) ? Tools::safeOutput($confValues['AVALARATAX_LICENSE_KEY']) : '').'" />
 755					</div>
 756					<label>'.$this->l('URL').'</label>
 757					<div class="margin-form">
 758						<input type="text" name="avalaratax_url" value="'.(isset($confValues['AVALARATAX_URL']) ? Tools::safeOutput($confValues['AVALARATAX_URL']) : '').'" />
 759					</div>
 760					<label>'.$this->l('Company Code').'</label>
 761					<div class="margin-form">
 762						<input type="text" name="avalaratax_company_code" value="'.(isset($confValues['AVALARATAX_COMPANY_CODE']) ? Tools::safeOutput($confValues['AVALARATAX_COMPANY_CODE']) : '').'" /> '.$this->l('Located in the top-right corner of your AvaTax Admin Console').'
 763					</div>
 764					<div class="margin-form">
 765						<input type="submit" class="button" name="SubmitAvalaraTaxSettings" value="'.$this->l('Save Settings').'" /><img src="'.$this->_path.'img/icon-connection.gif" alt="" class="icon-connection" /><input type="submit" id="avalaratax_test_connection" class="button" name="SubmitAvalaraTestConnection" value="'.$this->l('Click here to Test Connection').'" />
 766					</div>
 767				</fieldset>
 768			</form>
 769			<form action="'.Tools::safeOutput($_SERVER['REQUEST_URI']).'" method="post" class="form-half reset-label">
 770				<fieldset class="field-height MR7">
 771					<legend><img src="'.$this->_path.'img/icon-options.gif" alt="" />'.$this->l('Options').'</legend>
 772					<label>'.$this->l('Enable address validation').'</label>
 773					<div class="margin-form">
 774						<input type="checkbox" name="avalaratax_address_validation" value="1"'.(isset($confValues['AVALARATAX_ADDRESS_VALIDATION']) && $confValues['AVALARATAX_ADDRESS_VALIDATION'] ? ' checked="checked"' : '').' />
 775						('.$this->l('Not compatible with One Page Checkout').')
 776					</div>
 777					<label>'.$this->l('Enable tax calculation').'</label>
 778					<div class="margin-form">
 779						<input type="checkbox" name="avalaratax_tax_calculation" value="1" '.(isset($confValues['AVALARATAX_TAX_CALCULATION']) && $confValues['AVALARATAX_TAX_CALCULATION'] ? ' checked="checked"' : '').' />
 780					</div>
 781					<label>'.$this->l('Enable address normalization in uppercase').'</label>
 782					<div class="margin-form">
 783						<input type="checkbox" name="avalaratax_address_normalization" value="1" '.(isset($confValues['AVALARATAX_ADDRESS_NORMALIZATION']) && $confValues['AVALARATAX_ADDRESS_NORMALIZATION'] ? ' checked="checked"' : '').' />
 784					</div>
 785					<label>'.$this->l('Enable tax calculation outside of your state').'</label>
 786					<div class="margin-form">
 787						<input type="checkbox" name="avalaratax_tax_outside" value="1" '.(isset($confValues['AVALARATAX_TAX_OUTSIDE']) && $confValues['AVALARATAX_TAX_OUTSIDE'] ? ' checked="checked"' : '').' />
 788					</div>
 789					<label>'.$this->l('Request timeout').'</label>
 790					<div class="margin-form">
 791						<input type="text" name="avalaratax_timeout" value="'.(isset($confValues['AVALARATAX_TIMEOUT']) ? Tools::safeOutput($confValues['AVALARATAX_TIMEOUT']) : '').'" style="width: 40px;" /> '.$this->l('seconds').'
 792					</div>
 793					<label>'.$this->l('Refresh tax rate cache every x seconds (default 3600):').'</label>
 794					<div class="margin-form">
 795						<input type="text" name="avalara_cache_max_limit" value="'.(isset($confValues['AVALARA_CACHE_MAX_LIMIT']) ? (int)Tools::safeOutput($confValues['AVALARA_CACHE_MAX_LIMIT']) : '').'" style="width: 40px;" /> '.$this->l('seconds').'
 796					</div>
 797					<div class="margin-form">
 798						<input type="submit" class="button avalaratax_button" name="SubmitAvalaraTaxOptions" value="'.$this->l('Save Settings').'" />
 799						<input type="submit" class="button avalaratax_button" name="SubmitAvalaraTaxClearCache" value="'.$this->l('Clear Cache').'" style="display: none;"/>
 800					</div>
 801					<div class="sep"></div>
 802					<h4>'.$this->l('Default Post/Commit/Cancel/Refund Options').'</h4>
 803					<span class="avalara-info">'.$this->l('When an order\'s status is updated, the following options will be used to update Avalara\'s records.').'</span>';
 804	
 805			// Check if the order status exist
 806			$orderStatusList = array();
 807			foreach (Db::getInstance()->ExecuteS('SELECT `id_order_state`, `name` FROM `'._DB_PREFIX_.'order_state_lang` WHERE `id_lang` = '.(int)$this->context->cookie->id_lang) as $v)
 808				$orderStatusList[$v['id_order_state']] = Tools::safeOutput($v['name']);
 809			$buffer .= '<table class="avalara-table" cellspacing="0" cellpadding="0" width="100%">
 810						<th>'.$this->l('Action').'</th>
 811						<th>'.$this->l('Order status in your store').'</th>
 812						<tr>
 813							<td class="avalaratax_column">'.$this->l('Post order to Avalara').':</td>
 814							<td>'.(isset($orderStatusList[Configuration::get('AVALARATAX_POST_ID')]) ? html_entity_decode(Tools::safeOutput($orderStatusList[Configuration::get('AVALARATAX_POST_ID')])) :
 815								'<div style="color: red">'.$this->l('[ERROR] A default value was not found. Please, restore PrestaShop\'s default statuses.').'</div>').'
 816							</td>
 817						</tr>
 818						<tr>
 819							<td class="avalaratax_column">'.$this->l('Commit order to Avalara').':</td>
 820							<td>'.(isset($orderStatusList[Configuration::get('AVALARATAX_COMMIT_ID')]) ? html_entity_decode(Tools::safeOutput($orderStatusList[Configuration::get('AVALARATAX_COMMIT_ID')])) :
 821								'<div style="color: red">'.$this->l('[ERROR] A default value was not found. Please, restore PrestaShop\'s default statuses.').'</div>').'
 822							</td>
 823						</tr>
 824						<tr>
 825							<td class="avalaratax_column">'.$this->l('Delete order from Avalara').':</td>
 826							<td>'.(isset($orderStatusList[Configuration::get('AVALARATAX_CANCEL_ID')]) ? html_entity_decode(Tools::safeOutput($orderStatusList[Configuration::get('AVALARATAX_CANCEL_ID')])) :
 827								'<div style="color: red">'.$this->l('[ERROR] A default value was not found. Please, restore PrestaShop\'s default statuses.').'</div>').'
 828							</td>
 829						</tr>
 830						<tr>
 831							<td class="avalaratax_column last">'.$this->l('Void order in Avalara').':</td>
 832							<td class="last">'.(isset($orderStatusList[Configuration::get('AVALARATAX_REFUND_ID')]) ? html_entity_decode(Tools::safeOutput($orderStatusList[Configuration::get('AVALARATAX_REFUND_ID')])) :
 833								'<div style="color: red">'.$this->l('[ERROR] A default value was not found. Please, restore PrestaShop\'s default statuses.').'</div>').'
 834							</td>
 835						</tr>
 836					</table>
 837				</fieldset>
 838			</form>
 839			<form action="'.Tools::safeOutput($_SERVER['REQUEST_URI']).'" method="post" class="form-half">
 840				<fieldset class="field-height ML7">
 841					<legend><img src="'.$this->_path.'img/icon-address.gif" alt="" />'.$this->l('Default Origin Address and Tax Information').'</legend>
 842					<label>'.$this->l('Address Line 1').'</label>
 843					<div class="margin-form">
 844						<input type="text" name="avalaratax_address_line1" value="'.(isset($confValues['AVALARATAX_ADDRESS_LINE1']) ? Tools::safeOutput($confValues['AVALARATAX_ADDRESS_LINE1']) : '').'" />
 845					</div>
 846					<label>'.$this->l('Address Line 2').'</label>
 847					<div class="margin-form">
 848						<input type="text" name="avalaratax_address_line2" value="'.(isset($confValues['AVALARATAX_ADDRESS_LINE2']) ? Tools::safeOutput($confValues['AVALARATAX_ADDRESS_LINE2']) : '').'" />
 849					</div>
 850					<label>'.$this->l('City').'</label>
 851					<div class="margin-form">
 852						<input type="text" name="avalaratax_city" value="'.(isset($confValues['AVALARATAX_CITY']) ? Tools::safeOutput($confValues['AVALARATAX_CITY']) : '').'" />
 853					</div>
 854					<label>'.$this->l('Zip Code').'</label>
 855					<div class="margin-form">
 856						<input type="text" name="avalaratax_zip_code" value="'.(isset($confValues['AVALARATAX_ZIP_CODE']) ? Tools::safeOutput($confValues['AVALARATAX_ZIP_CODE']) : '').'" />
 857					</div>
 858					<label>'.$this->l('Country').'</label>
 859					<div class="margin-form">
 860						<select name="avalaratax_country" id="avalaratax_country">';
 861			foreach ($countryList as $country)
 862				$buffer .= '<option value="'.substr(strtoupper($country['iso_code']), 0, 2).'" '.($country['iso_code'] == $confValues['AVALARATAX_COUNTRY'] ? ' selected="selected"' : '').'>'.Tools::safeOutput($country['name']).'</option>';
 863			$buffer .= '</select>
 864					</div>
 865					<label id="avalaratax_label_state" >'.$this->l('State').'</label>
 866					<div class="margin-form">
 867						<select name="avalaratax_state" id="avalaratax_state">';
 868			foreach ($stateList as $state)
 869				$buffer .= '<option value="'.substr(strtoupper($state['iso_code']), 0, 2).'" '.($state['iso_code'] == $confValues['AVALARATAX_STATE'] ? ' selected="selected"' : '').'>'.Tools::safeOutput($state['name']).'</option>';
 870			
 871			$buffer .= '</select>
 872					</div>
 873					<div class="margin-form">
 874						<input type="submit" class="button" name="SubmitAvalaraAddressOptions" value="'.$this->l('Save Settings').'" />
 875					</div>
 876				</fieldset>
 877			</form>
 878			<div class="clear"></div>
 879		</div>';
 880		
 881		return $buffer;
 882	}
 883
 884	/*
 885	** Display a custom message for settings update
 886	** $text string Text to be displayed in the message
 887	** $type string (confirm|warn|error) Decides what color will the message have (green|yellow)
 888	*/
 889	private function _displayConfirmation($text = '', $type = 'confirm')
 890	{
 891		if ($type == 'confirm')
 892			$img = 'ok.gif';
 893		elseif ($type == 'warn')
 894			$img = 'warn2.png';
 895		elseif ($type == 'error')
 896			$img = 'disabled.gif';
 897		else
 898			die('Invalid type.');
 899
 900		return '<div class="conf '.Tools::safeOutput($type).'">
 901			<img src="../img/admin/'.$img.'" alt="" title="" />
 902			'.(empty($text) ? $this->l('Settings updated') : $text).
 903			'<img src="http://www.prestashop.com/modules/avalaratax.png?sid='.urlencode(Configuration::get('AVALARATAX_ACCOUNT_NUMBER')).'" style="float: right;" />
 904		</div>';
 905	}
 906
 907	/**
 908	 * @brief init the Avatax SDK
 909	 */
 910	private function _connectToAvalara()
 911	{
 912		$timeout = Configuration::get('AVALARATAX_TIMEOUT');
 913		if ((int)$timeout > 0)
 914			ini_set('max_execution_time', (int)$timeout);
 915
 916		include_once(dirname(__FILE__).'/sdk/AvaTax.php');
 917
 918		/* Just instantiate the ATConfig class to init the settings (mandatory...) */
 919		new ATConfig(Configuration::get('AVALARATAX_MODE'), array('url' => Configuration::get('AVALARATAX_URL'), 'account' => Configuration::get('AVALARATAX_ACCOUNT_NUMBER'),
 920				'license' => Configuration::get('AVALARATAX_LICENSE_KEY'), 'trace' => false));
 921	}
 922
 923	/**
 924	 * @brief Connect to Avalara to make sure everything is OK
 925	 */
 926	private function _testConnection()
 927	{
 928		$this->_connectToAvalara();
 929		try
 930		{
 931			$client = new TaxServiceSoap(Configuration::get('AVALARATAX_MODE'));
 932			$connectionTest = $client->ping();
 933			if ($connectionTest->getResultCode() == SeverityLevel::$Success)
 934			{
 935				try
 936				{
 937					$authorizedTest = $client->isAuthorized('GetTax');
 938					if ($authorizedTest->getResultCode() == SeverityLevel::$Success)
 939						$expirationDate = $authorizedTest->getexpires();
 940				}
 941				catch (SoapFault $exception)
 942				{
 943				}
 944
 945				return array('<img src="../img/admin/ok.gif" alt="" /><strong style="color: green;">'.$this->l('Connection Test performed successfully.').'</strong><br /><br />'.$this->l('Ping version is:').' '.Tools::safeOutput($connectionTest->getVersion()).(isset($expirationDate) ? '<br /><br />'.$this->l('License Expiration Date:').' '.Tools::safeOutput($expirationDate) : ''), '#D6F5D6');
 946			}
 947		}
 948		catch (SoapFault $exception)
 949		{
 950			return array('<img src="../img/admin/forbbiden.gif" alt="" /><b style="color: #CC0000;">'.$this->l('Connection Test Failed.').'</b><br /><br />'.$this->l('Either the Account or License Key is incorrect. Please confirm the Account and License Key before testing the connection again.').'<br /><br /><strong style="color: #CC0000;">'.$this->l('Error(s):').' '.Tools::safeOutput($exception->faultstring).'</strong>', '#FFD8D8');
 951		}
 952	}
 953
 954	/**
 955	 * @brief Validates a given address
 956	 */
 957	public function validateAddress(Address $address)
 958	{
 959		$this->_connectToAvalara();
 960		$client = new AddressServiceSoap(Configuration::get('AVALARATAX_MODE'));
 961
 962		if (!empty($address->id_state))
 963			$state = new State((int)$address->id_state);
 964		if (!empty($address->id_country))
 965			$country = new Country((int)$address->id_country);
 966
 967		$avalaraAddress = new AvalaraAddress($address->address1, $address->address2, null, $address->city,
 968											(isset($state) ? $state->iso_code : null), $address->postcode, (isset($country) ? $country->iso_code : null), 0);
 969
 970		$buffer = array();
 971		try
 972		{
 973			$request = new ValidateRequest($avalaraAddress, TextCase::$Upper, false);
 974			$result = $client->Validate($request);
 975			$addresses = $result->ValidAddresses;
 976
 977			$buffer['ResultCode'] = Tools::safeOutput($result->getResultCode());
 978			if ($result->getResultCode() != SeverityLevel::$Success)
 979				foreach ($result->getMessages() as $msg)
 980				{
 981					$buffer['Messages']['Name'][] = Tools::safeOutput($msg->getName());
 982					$buffer['Messages']['Summary'][] = Tools::safeOutput($msg->getSummary());
 983				}
 984			else
 985				foreach ($result->getvalidAddresses() as $valid)
 986				{
 987					$buffer['Normalized']['Line1'] = Tools::safeOutput($valid->getline1());
 988					$buffer['Normalized']['Line2'] = Tools::safeOutput($valid->getline2());
 989					$buffer['Normalized']['City']= Tools::safeOutput($valid->getcity());
 990					$buffer['Normalized']['Region'] = Tools::safeOutput($valid->getregion());
 991					$buffer['Normalized']['PostalCode'] = Tools::safeOutput($valid->getpostalCode());
 992					$buffer['Normalized']['Country'] = Tools::safeOutput($valid->getcountry());
 993					$buffer['Normalized']['County'] = Tools::safeOutput($valid->getcounty());
 994					$buffer['Normalized']['FIPS'] = Tools::safeOutput($valid->getfipsCode());
 995					$buffer['Normalized']['PostNet'] = Tools::safeOutput($valid->getpostNet());
 996					$buffer['Normalized']['CarrierRoute'] = Tools::safeOutput($valid->getcarrierRoute());
 997					$buffer['Normalized']['AddressType'] = Tools::safeOutput($valid->getaddressType());
 998				}
 999		}
1000		catch (SoapFault $exception)
1001		{
1002			$buffer['Exception']['FaultString'] = Tools::safeOutput($exception->faultstring);
1003			$buffer['Exception']['LastRequest'] = Tools::safeOutput($client->__getLastRequest());
1004			$buffer['Exception']['LastResponse'] = Tools::safeOutput($client->__getLastResponse());
1005		}
1006		return $buffer;
1007	}
1008
1009	/**
1010	 * @brief Executes tax actions on documents
1011	 *
1012	 * @param Array $products Array of Product for which taxes need to be calculated
1013	 * @param Array $params
1014	 * 		type : (default SalesOrder) SalesOrder|SalesInvoice|ReturnInvoice
1015	 * 		cart : (required for Sal…

Large files files are truncated, but you can click here to view the full file