PageRenderTime 57ms CodeModel.GetById 18ms 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
  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. * DocCode : (required in ReturnInvoice, and when 'cart' is not set) Specify the Document Code
  935. *
  936. */
  937. public function getTax($products = array(), $params = array())
  938. {
  939. $confValues = Configuration::getMultiple(array('AVALARATAX_COMPANY_CODE', 'AVALARATAX_ADDRESS_LINE1',
  940. 'AVALARATAX_ADDRESS_LINE2', 'AVALARATAX_CITY', 'AVALARATAX_STATE', 'AVALARATAX_ZIP_CODE'));
  941. if (!isset($params['type']))
  942. $params['type'] = 'SalesOrder';
  943. $this->_connectToAvalara();
  944. $client = new TaxServiceSoap(Configuration::get('AVALARATAX_MODE'));
  945. $request = new GetTaxRequest();
  946. if (isset($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}))
  947. $address = new Address((int)$this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
  948. elseif (isset($this->context->cookie) && isset($this->context->cookie->id_customer) && $this->context->cookie->id_customer)
  949. $address = new Address((int)Db::getInstance()->getValue('SELECT `id_address` FROM `'._DB_PREFIX_.'address` WHERE `id_customer` = '.(int)$this->context->cookie->id_customer.' AND active = 1 AND deleted = 0'));
  950. if (isset($address))
  951. {
  952. if (!empty($address->id_state))
  953. $state = new State((int)$address->id_state);
  954. $addressDest = array();
  955. $addressDest['Line1'] = $address->address1;
  956. $addressDest['Line2'] = $address->address2;
  957. $addressDest['City'] = $address->city;
  958. $addressDest['Region'] = isset($state) ? $state->iso_code : '';
  959. $addressDest['PostalCode'] = $address->postcode;
  960. $addressDest['Country'] = Country::getIsoById($address->id_country);
  961. // Try to normalize the address depending on option in the BO
  962. if (Configuration::get('AVALARATAX_ADDRESS_NORMALIZATION'))
  963. {
  964. $last_update = Db::getInstance()->getValue('SELECT date_add FROM '._DB_PREFIX_.'avalara_address_validation_cache WHERE id_address = '.(int)$address->id);
  965. if (empty($last_update) || (strtotime($address->date_upd) > strtotime($last_update)))
  966. {
  967. $normalizedAddress = $this->validateAddress($address);
  968. Db::getInstance()->Execute('INSERT INTO '._DB_PREFIX_.'avalara_address_validation_cache (id_address, date_add) VALUES ('.(int)$address->id.', \''.pSQL(date('Y-m-d H:i:s')).'\') ON DUPLICATE KEY UPDATE date_add = \''.pSQL(date('Y-m-d H:i:s')).'\'');
  969. }
  970. }
  971. if (isset($normalizedAddress['Normalized']))
  972. $addressDest = $normalizedAddress['Normalized'];
  973. // Add Destination address (Customer address)
  974. $destination = new AvalaraAddress();
  975. $destination->setLine1($addressDest['Line1']);
  976. $destination->setLine2($addressDest['Line2']);
  977. $destination->setCity($addressDest['City']);
  978. $destination->setRegion($addressDest['Region']);
  979. $destination->setPostalCode($addressDest['PostalCode']);
  980. $destination->setCountry($addressDest['Country']);
  981. $request->setDestinationAddress($destination);
  982. }
  983. // Origin Address (Store Address or address setup in BO)
  984. $origin = new AvalaraAddress();
  985. $origin->setLine1(isset($confValues['AVALARATAX_ADDRESS_LINE1']) ? $confValues['AVALARATAX_ADDRESS_LINE1'] : '');
  986. $origin->setLine2(isset($confValues['AVALARATAX_ADDRESS_LINE2']) ? $confValues['AVALARATAX_ADDRESS_LINE2'] : '');
  987. $origin->setCity(isset($confValues['AVALARATAX_CITY']) ? $confValues['AVALARATAX_CITY'] : '');
  988. $origin->setRegion(isset($confValues['AVALARATAX_STATE']) ? $confValues['AVALARATAX_STATE'] : '');
  989. $origin->setPostalCode(isset($confValues['AVALARATAX_ZIP_CODE']) ? $confValues['AVALARATAX_ZIP_CODE'] : '');
  990. $request->setOriginAddress($origin);
  991. $request->setCompanyCode(isset($confValues['AVALARATAX_COMPANY_CODE']) ? $confValues['AVALARATAX_COMPANY_CODE'] : '');
  992. if (isset($address->vat_number) && !empty($address->vat_number) && $address->vat_number != 'undefined')
  993. $request->setBusinessIdentificationNo($address->vat_number);
  994. $orderId = isset($params['cart']) ? (int)$params['cart']->id : (int)$params['DocCode'];
  995. $nowTime = date('mdHis');
  996. // Type: Only supported types are SalesInvoice or SalesOrder
  997. if ($params['type'] == 'SalesOrder') // SalesOrder: Occurs when customer adds product to the cart (generally to check how much the tax will be)
  998. $request->setDocType(DocumentType::$SalesOrder);
  999. elseif ($params['type'] == 'SalesInvoice') // SalesInvoice: Occurs when customer places an order (It works like commitToAvalara()).
  1000. {
  1001. $request->setDocType(DocumentType::$SalesInvoice);
  1002. $orderId = Db::getInstance()->getValue('SELECT `id_order` FROM '._DB_PREFIX_.'orders WHERE `id_cart` = '.(int)$params['cart']->id); // Make sure we got the orderId, even if it was/wasn't passed in $params['DocCode']
  1003. }
  1004. elseif ($params['type'] == 'ReturnInvoice')
  1005. {
  1006. $orderId = isset($params['type']) && $params['type'] == 'ReturnInvoice' ? $orderId.'.'.$nowTime : $orderId;
  1007. $orderDate = Db::getInstance()->ExecuteS('
  1008. SELECT `id_order`, `date_add`
  1009. FROM `'._DB_PREFIX_.'orders`
  1010. WHERE '.(isset($params['cart']) ? '`id_cart` = '.(int)$params['cart']->id : '`id_order` = '.(int)$params['DocCode']));
  1011. $request->setDocType(DocumentType::$ReturnInvoice);
  1012. $request->setCommit(true);
  1013. $taxOverride = new TaxOverride();
  1014. $taxOverride->setTaxOverrideType(TaxOverrideType::$TaxDate);
  1015. $taxOverride->setTaxDate(date('Y-m-d', strtotime($orderDate[0]['date_add'])));
  1016. $taxOverride->setReason('Refund');
  1017. $request->setTaxOverride($taxOverride);
  1018. }
  1019. if (isset($this->context->cookie->id_customer))
  1020. $customerCode = $this->context->cookie->id_customer;
  1021. else
  1022. {
  1023. if (isset($params['DocCode']))
  1024. $id_order = (int)$params['DocCode'];
  1025. elseif (isset($_POST['id_order']))
  1026. $id_order = (int)$_POST['id_order'];
  1027. elseif (isset($params['id_order']))
  1028. $id_order = (int)$params['id_order'];
  1029. else
  1030. $id_order = 0;
  1031. $customerCode = (int)Db::getInstance()->getValue('SELECT `id_customer` FROM `'._DB_PREFIX_.'orders` WHERE `id_order` = '.(int)$id_order);
  1032. }
  1033. $request->setDocCode('Order '.Tools::safeOutput($orderId)); // Order Id - has to be float due to the . and more numbers for returns
  1034. $request->setDocDate(date('Y-m-d')); // date
  1035. $request->setCustomerCode('CustomerID: '.(int)$customerCode); // string Required
  1036. $request->setDiscount($this->context->cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS)); // decimal
  1037. $request->setDetailLevel(DetailLevel::$Tax); // Summary or Document or Line or Tax or Diagnostic
  1038. // Add line
  1039. $lines = array();
  1040. $i = 0;
  1041. foreach ($products as $product)
  1042. {
  1043. // Retrieve the tax_code for the current product if not defined
  1044. if (isset($params['taxable']) && !$params['taxable'])
  1045. $taxCode = 'NT';
  1046. else
  1047. $taxCode = !isset($product['tax_code']) ? $this->getProductTaxCode((int)$product['id_product']) : $product['tax_code'];
  1048. if (isset($product['id_product']))
  1049. {
  1050. $line = new Line();
  1051. $line->setNo($i++); // string line Number of invoice ($i)
  1052. $line->setItemCode((int)$product['id_product'].' - '.substr($product['name'], 0, 20));
  1053. $line->setDescription(substr(Tools::safeOutput($product['name'].' - '.$product['description_short']), 0, 250));
  1054. $line->setTaxCode($taxCode);
  1055. $line->setQty(isset($product['quantity']) ? (float)$product['quantity'] : 1);
  1056. $line->setAmount($params['type'] == 'ReturnInvoice' && (float)$product['total'] > 0 ? (float)$product['total'] * -1 : (float)$product['total']);
  1057. $line->setDiscounted(false);
  1058. $lines[] = $line;
  1059. }
  1060. }
  1061. // Send shipping as new line
  1062. if (isset($params['cart']))
  1063. {
  1064. $line = new Line();
  1065. $line->setNo('Shipping'); // string line Number of invoice ($i)
  1066. $line->setItemCode('Shipping');
  1067. $line->setDescription('Shipping costs');
  1068. if (isset($params['taxable']) && !$params['taxable'])
  1069. $line->setTaxCode('NT');
  1070. else
  1071. $line->setTaxCode('FR020100'); // Default TaxCode for Shipping. Avalara will decide depending on the State if taxes should be charged or not
  1072. $line->setQty(1);
  1073. $line->setAmount((float)$params['cart']->getOrderTotal(false, Cart::ONLY_SHIPPING));
  1074. $line->setDiscounted(false);
  1075. $lines[] = $line;
  1076. }
  1077. $request->setLines($lines);
  1078. $buffer = array();
  1079. try
  1080. {
  1081. $result = $client->getTax($request);
  1082. $buffer['ResultCode'] = Tools::safeOutput($result->getResultCode());
  1083. if ($result->getResultCode() == SeverityLevel::$Success)
  1084. {
  1085. $buffer['DocCode'] = Tools::safeOutput($request->getDocCode());
  1086. $buffer['TotalAmount'] = Tools::safeOutput($result->getTotalAmount());
  1087. $buffer['TotalTax'] = Tools::safeOutput($result->getTotalTax());
  1088. $buffer['NowTime'] = $nowTime;
  1089. foreach ($result->getTaxLines() as $ctl)
  1090. {
  1091. $buffer['TaxLines'][$ctl->getNo()]['GetTax'] = Tools::safeOutput($ctl->getTax());
  1092. $buffer['TaxLines'][$ctl->getNo()]['TaxCode'] = Tools::safeOutput($ctl->getTaxCode());
  1093. foreach ($ctl->getTaxDetails() as $ctd)
  1094. {
  1095. $buffer['TaxLines'][$ctl->getNo()]['TaxDetails']['JurisType'] = Tools::safeOutput($ctd->getJurisType());
  1096. $buffer['TaxLines'][$ctl->getNo()]['TaxDetails']['JurisName'] = Tools::safeOutput($ctd->getJurisName());
  1097. $buffer['TaxLines'][$ctl->getNo()]['TaxDetails']['Region'] = Tools::safeOutput($ctd->getRegion());
  1098. $buffer['TaxLines'][$ctl->getNo()]['TaxDetails']['Rate'] = Tools::safeOutput($ctd->getRate());
  1099. $buffer['TaxLines'][$ctl->getNo()]['TaxDetails']['Tax'] = Tools::safeOutput($ctd->getTax());
  1100. }
  1101. }
  1102. }
  1103. else
  1104. foreach ($result->getMessages() as $msg)
  1105. {
  1106. $buffer['Messages']['Name'] = Tools::safeOutput($msg->getName());
  1107. $buffer['Messages']['Summary'] = Tools::safeOutput($msg->getSummary());
  1108. }
  1109. }
  1110. catch (SoapFault $exception)
  1111. {
  1112. $buffer['Exception']['FaultString'] = Tools::safeOutput($exception->faultstring);
  1113. $buffer['Exception']['LastRequest'] = Tools::safeOutput($client->__getLastRequest());
  1114. $buffer['Exception']['LastResponse'] = Tools::safeOutput($client->__getLastResponse());
  1115. }
  1116. return $buffer;
  1117. }
  1118. /*
  1119. ** Make changes to an order, get order history or checks if the module is authorized
  1120. **
  1121. ** $type string commit|post|cancel|history Transaction type
  1122. ** $params array Key=>Values depending on the transaction type
  1123. ** DocCode: (required for ALL except for isAuthorized) Document unique identifier
  1124. ** DocDate: (required for post) Date in which the transaction was made (today's date if post)
  1125. ** IdCustomer: (required for post) Customer ID
  1126. ** TotalAmount: (required for post) Order total amount in case of Post type
  1127. ** TotalTax: (required for post) Total tax amount for current order
  1128. ** CancelCode: (required for cancel only) D|P Sets the cancel code (D: Document Deleted | P: Post Failed)
  1129. */
  1130. public function tax($type, $params = array())
  1131. {
  1132. $this->_connectToAvalara();
  1133. $client = new TaxServiceSoap(Configuration::get('AVALARATAX_MODE'));
  1134. if ($type == 'commit')
  1135. $request= new CommitTaxRequest();
  1136. elseif ($type == 'post')
  1137. {
  1138. $request= new PostTaxRequest();
  1139. $request->setDocDate($params['DocDate']);
  1140. $request->setTotalAmount($params['TotalAmount']);
  1141. $request->setTotalTax($params['TotalTax']);
  1142. }
  1143. elseif ($type == 'cancel')
  1144. {
  1145. $request= new CancelTaxRequest();
  1146. if ($params['CancelCode'] == 'D')
  1147. $code = CancelCode::$DocDeleted;
  1148. elseif ($params['CancelCode'] == 'P')
  1149. $code = CancelCode::$PostFailed;
  1150. elseif ($params['CancelCode'] == 'V')
  1151. $code = CancelCode::$DocVoided;
  1152. else
  1153. die('Invalid cancel code.');
  1154. $request->setCancelCode($code);
  1155. }
  1156. elseif ($type == 'history')
  1157. {
  1158. $request= new GetTaxHistoryRequest();
  1159. $request->setDetailLevel(DetailLevel::$Document);
  1160. }
  1161. if ($type != 'isAuthorized')
  1162. {
  1163. $request->setDocCode('Order '.(int)$params['DocCode']);
  1164. $request->setDocType(DocumentType::$SalesInvoice);
  1165. $request->setCompanyCode(Configuration::get('AVALARATAX_COMPANY_CODE'));
  1166. }
  1167. $buffer = array();
  1168. try
  1169. {
  1170. if ($type == 'commit')
  1171. $result = $client->commitTax($request);
  1172. elseif ($type == 'post')
  1173. $result = $client->postTax($request);
  1174. elseif ($type == 'cancel')
  1175. $result = $client->cancelTax($request);
  1176. elseif ($type == 'isAuthorized')
  1177. $result = $client->isAuthorized('GetTax');
  1178. elseif ($type == 'history')
  1179. {
  1180. $result = $client->getTaxHistory($request);
  1181. $buffer['Invoice'] = $result->getGetTaxRequest()->getDocCode();
  1182. $buffer['Status'] = $result->getGetTaxResult()->getDocStatus();
  1183. }
  1184. $buffer['ResultCode'] = $result->getResultCode();
  1185. if ($result->getResultCode() != SeverityLevel::$Success)
  1186. foreach ($result->getMessages() as $msg)
  1187. {
  1188. $buffer['Messages']['Name'] = Tools::safeOutput($msg->getName());
  1189. $buffer['Messages']['Summary'] = Tools::safeOutput($msg->getSummary());
  1190. }
  1191. }
  1192. catch (SoapFault $exception)
  1193. {
  1194. $buffer['Exception']['FaultString'] = Tools::safeOutput($exception->faultstring);
  1195. $buffer['Exception']['LastRequest'] = Tools::safeOutput($client->__getLastRequest());
  1196. $buffer['Exception']['LastResponse'] = Tools::safeOutput($client->__getLastResponse());
  1197. }
  1198. return $buffer;
  1199. }
  1200. public function postToAvalara($params)
  1201. {
  1202. if (!isset($params['address']))
  1203. list($params['address'], $params['state'], $params['order']) = self::getDestinationAddress((int)$params['id_order']);
  1204. $destination = new AvalaraAddress();
  1205. $destination->setLine1($params['address']->address1);
  1206. $destination->setLine2($params['address']->address2);
  1207. $destination->setCity($params['address']->city);
  1208. $destination->setRegion(isset($params['state']) ? $params['state']->iso_code : '');
  1209. $destination->setPostalCode($params['address']->postcode);
  1210. $commitResult = $this->tax('history', array('DocCode' => (int)$params['id_order'], 'Destination' => $destination));
  1211. if (isset($commitResult['ResultCode']) && $commitResult['ResultCode'] == 'Success')
  1212. {
  1213. $params['CancelCode'] = 'D';
  1214. $this->cancelFromAvalara($params);
  1215. $this->cancelFromAvalara($params); // Twice because first call only voids the order, and 2nd call deletes it
  1216. }
  1217. // Grab the info to post to Avalara in English.
  1218. $order = new Order((isset($_POST['id_order']) ? (int)$_POST['id_order'] : (int)$params['id_order']));
  1219. $allProducts = Db::getInstance()->ExecuteS('SELECT p.`id_product`, pl.`name`, pl.`description_short`,
  1220. od.`product_price` as price, od.`reduction_percent`,
  1221. od.`reduction_amount`, od.`product_quantity` as quantity, atc.`tax_code`
  1222. FROM `'._DB_PREFIX_.'order_detail` od
  1223. LEFT JOIN `'._DB_PREFIX_.'product` p ON (p.id_product = od.product_id)
  1224. LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (pl.id_product = p.id_product)
  1225. LEFT JOIN `'._DB_PREFIX_.'avalara_taxcodes` atc ON (atc.id_product = p.id_product)
  1226. WHERE pl.`id_lang` = '.(int)Configuration::get('PS_LANG_DEFAULT').' AND od.`id_order` = '.(isset($_POST['id_order']) ? (int)$_POST['id_order'] : (int)$params['id_order']));
  1227. $products = array();
  1228. foreach ($allProducts as $v)
  1229. $products[] = array('id_product' => $v['id_product'],
  1230. 'name' => $v['name'],
  1231. 'description_short' => $v['description_short'],
  1232. 'quantity' => $v['quantity'],
  1233. 'total' => $v['quantity'] * ($v['price'] - ($v['price'] * ($v['reduction_percent'] / 100)) - ($v['reduction_amount'])), // Including those products with discounts
  1234. 'tax_code' => $v['tax_code'],
  1235. 'taxable' => (bool)$this->getProductTaxable((int)$v['id_product']));
  1236. $taxable = true;
  1237. //check if it is outside the state and if we are in united state and if conf AVALARATAX_TAX_OUTSIDE IS ENABLE
  1238. if (isset($params['state']) && !Configuration::get('AVALARATAX_TAX_OUTSIDE') && $params['state']->iso_code != Configuration::get('AVALARATAX_STATE'))
  1239. $taxable = false;
  1240. $cart = new Cart((int)$order->id_cart);
  1241. $getTaxResult = $this->getTax($products, array('type' => 'SalesInvoice', 'cart' => $cart, 'id_order' => isset($_POST['id_order']) ? (int)$_POST['id_order'] : (int)$params['id_order'], 'taxable' => $taxable), $params['address']->id);
  1242. $commitResult = $this->tax('post', array('DocCode' => (isset($_POST['id_order']) ? (int)$_POST['id_order'] : (int)$params['id_order']),
  1243. 'DocDate' => date('Y-m-d'), 'IdCustomer' => (int)$cart->id_customer, 'TotalAmount' => (float)$getTaxResult['TotalAmount'],
  1244. 'TotalTax' => (float)$getTaxResult['TotalTax']));
  1245. if (isset($commitResult['ResultCode']) && ($commitResult['ResultCode'] == 'Warning' || $commitResult['ResultCode'] == 'Error' || $commitResult['ResultCode'] == 'Exception'))
  1246. return $this->_displayConfirmation($this->l('The following error was generated while cancelling the orders you selected.'.
  1247. '<br /> - '.Tools::safeOutput($commitResult['Messages']['Summary'])), 'error');
  1248. return $this->_displayConfirmation($this->l('The orders you selected were posted.'));
  1249. }
  1250. public function commitToAvalara($params)
  1251. {
  1252. // Create the order before commiting to Avalara
  1253. $this->postToAvalara($params);
  1254. $commitResult = $this->tax('history', array('DocCode' => $params['id_order']));
  1255. if (isset($commitResult['ResultCode']) && $commitResult['ResultCode'] == 'Success')
  1256. {
  1257. $commitResult = $this->tax('commit', array('DocCode' => (int)$params['id_order']));
  1258. if (isset($commitResult['Exception']) || isset($commitResult['ResultCode']) && ($commitResult['ResultCode'] == 'Warning' || $commitResult['ResultCode'] == 'Error' || $commitResult['ResultCode'] == 'Exception'))
  1259. return ($this->_displayConfirmation($this->l('The following error was generated while committing the orders you selected to Avalara.').
  1260. (isset($commitResult['Messages']) ? '<br /> - '.Tools::safeOutput($commitResult['Messages']['Summary']) : '').
  1261. (isset($commitResult['Exception']) ? '<br /> - '.Tools::safeOutput($commitResult['Exception']['FaultString']) : ''), 'error'));
  1262. else
  1263. return $this->_displayConfirmation($this->l('The orders you selected were committed.'));
  1264. }
  1265. // Orders prior Avalara module installation will trigger an "Invalid Status" error. For this reason, the user won't be alerted here.
  1266. }
  1267. public function cancelFromAvalara($params)
  1268. {
  1269. $commitResult = $this->tax('history', array('DocCode' => $params['id_order']));
  1270. $hasRefund = Db::getInstance()->ExecuteS('SELECT COUNT(`id_order`) as qtyProductRefunded
  1271. FROM `ps_order_detail`
  1272. WHERE `id_order` = '.(int)$params['id_order'].'
  1273. AND (`product_quantity_refunded` IS NOT NULL AND `product_quantity_refunded` > 0)');
  1274. if (!($commitResult['Status'] == 'Committed' && (int)$hasRefund[0]['qtyProductRefunded'] > 0))
  1275. {
  1276. if (isset($commitResult['Status']) && $commitResult['Status'] == 'Temporary')
  1277. $this->postToAvalara($params);
  1278. $commitResult = $this->tax('cancel', array('DocCode' => (int)$params['id_order'],
  1279. 'CancelCode' => isset($params['CancelCode']) ? $params['CancelCode'] : 'V' ));
  1280. if (isset($commitResult['ResultCode'])
  1281. && ( $commitResult['ResultCode'] == 'Warning'
  1282. || $commitResult['ResultCode'] == 'Error'
  1283. || $commitResult['ResultCode'] == 'Exception'))
  1284. return $this->_displayConfirmation($this->l('The following error was generated while cancelling the orders you selected.').
  1285. ' <br /> - '.Tools::safeOutput($commitResult['Messages']['Summary']), 'error');
  1286. else
  1287. return $this->_displayConfirmation($this->l('The orders you selected were cancelled.'));
  1288. }
  1289. }
  1290. /*
  1291. ** Fix $_POST to validate/normalize the address on address creation/update
  1292. */
  1293. public function fixPOST()
  1294. {
  1295. /* Validate address only in the U.S. and Canada - if the Address Validation feature has been turned on in the module's configuration */
  1296. if (($address->id_country == Country::getByIso('US') || $address->id_country == Country::getByIso('CA')) && $this->tax('isAuthorized') && Configuration::get('AVALARATAX_ADDRESS_VALIDATION'))
  1297. {
  1298. $address = new Address(isset($_POST['id_address']) ? (int)$_POST['id_address'] : null);
  1299. $address->address1 = isset($_POST['address1']) ? $_POST['address1'] : null;
  1300. $address->address2 = isset($_POST['address2']) ? $_POST['address2'] : null;
  1301. $address->city = isset($_POST['city']) ? $_POST['city'] : null;
  1302. $address->region = isset($_POST['region']) ? $_POST['region'] : null;
  1303. $address->postcode = isset($_POST['postcode']) ? $_POST['postcode'] : null;
  1304. $address->id_country = isset($_POST['id_country']) ? $_POST['id_country'] : null;
  1305. $address->id_state = isset($_POST['id_state']) ? (int)$_POST['id_state'] : null;
  1306. $normalizedAddress = $this->validateAddress($address);
  1307. if (isset($normalizedAddress['ResultCode']) && $normalizedAddress['ResultCode'] == 'Success')
  1308. {
  1309. Db::getInstance()->Execute('INSERT INTO '._DB_PREFIX_.'avalara_address_validation_cache (id_address, date_add) VALUES ('.(int)$address->id.', \''.pSQL(date('Y-m-d H:i:s')).'\') ON DUPLICATE KEY UPDATE date_add = \''.pSQL(date('Y-m-d H:i:s')).'\'');
  1310. $_POST['address1'] = Tools::safeOutput($normalizedAddress['Normalized']['Line1']);
  1311. $_POST['address2'] = Tools::safeOutput($normalizedAddress['Normalized']['Line2']);
  1312. $_POST['city'] = Tools::safeOutput($normalizedAddress['Normalized']['City']);
  1313. $_POST['postcode'] = Tools::safeOutput(substr($normalizedAddress['Normalized']['PostalCode'], 0, strpos($normalizedAddress['Normalized']['PostalCode'], '-')));
  1314. }
  1315. return $normalizedAddress;
  1316. }
  1317. }
  1318. public function getProductTaxCode($id_product)
  1319. {
  1320. $result = Db::getInstance()->getValue('
  1321. SELECT `tax_code`
  1322. FROM `'._DB_PREFIX_.'avalara_taxcodes` atc
  1323. WHERE atc.`id_product` = '.(int)$id_product);
  1324. return $result ? Tools::safeOutput($result) : '0';
  1325. }
  1326. public function getProductTaxable($idProduct)
  1327. {
  1328. // !== and not != because it can fail if getProductTaxCode return an int.
  1329. return $this->getProductTaxCode($idProduct) !== 'NT';
  1330. }
  1331. private function purgeTempTable()
  1332. {
  1333. return Db::getInstance()->Execute('TRUNCATE TABLE `'._DB_PREFIX_.'avalara_temp`');
  1334. }
  1335. private function getCurrentURL($htmlEntities = false)
  1336. {
  1337. $url = Tools::safeOutput($_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'], true);
  1338. return (!empty($_SERVER['HTTPS']) ? 'https' : 'http').'://'.($htmlEntities ? preg_replace('/&/', '&amp;', $url): $url);
  1339. }
  1340. }
  1341. function avalaraAutoload($className)
  1342. {
  1343. $className = str_replace(chr(0), '', $className);
  1344. if (!preg_match('/^\w+$/', $className))
  1345. die('Invalid classname.');
  1346. $moduleDir = dirname(__FILE__).'/';
  1347. if (file_exists($moduleDir.$className.'.php'))
  1348. require_once($moduleDir.$className.'.php');
  1349. elseif (file_exists($moduleDir.'sdk/classes/'.$className.'.class.php'))
  1350. require_once($moduleDir.'sdk/classes/'.$className.'.class.php');
  1351. elseif (file_exists($moduleDir.'sdk/classes/BatchSvc/'.$className.'.class.php'))
  1352. require_once($moduleDir.'sdk/classes/BatchSvc/'.$className.'.class.php');
  1353. elseif (function_exists('__autoload'))
  1354. __autoload($className);
  1355. }