PageRenderTime 65ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/avalaratax/avalaratax.php

https://github.com/DaveBenNoah/PrestaShop-modules
PHP | 1491 lines | 1254 code | 123 blank | 114 comment | 200 complexity | e51b25ab6ebf947b42584f07fb5c2883 MD5 | raw file
Possible License(s): Apache-2.0, CC-BY-SA-3.0

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

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