forked from PrestaShopCorp/avalaratax
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCacheTools.php
187 lines (159 loc) · 8.13 KB
/
CacheTools.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
<?php
/*
* 2007-2011 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2015 PrestaShop SA
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class CacheTools
{
public static function checkProductCache($ids_product, $region, Cart $cart)
{
$result = Db::getInstance()->ExecuteS(
'SELECT ac.`tax_rate`, ac.`update_date`
FROM `'._DB_PREFIX_.'avalara_product_cache` ac
WHERE ac.`id_product` IN ('.pSQL($ids_product).') AND ac.`region` = \''.pSQL($region).'\' AND ac.`id_address` = '.(int)$cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}
);
if (count($result) == count($cart->getProducts())) {
// Compare date/time
date_default_timezone_set(@date_default_timezone_get());
$date2 = time();
foreach ($result as $line) {
if (abs($date2 - strtotime($line['update_date'])) > Configuration::get('AVALARA_CACHE_MAX_LIMIT')) {
return true;
}
}
return false;
}
return true;
}
/**
* @brief Check the Carrier Cache
*
* @param cart Cart object
*
* @return True if the cache expired, false otherwise
*/
public static function checkCarrierCache(Cart $cart)
{
$tmp = array('id_carrier' => (int)$cart->id_carrier, 'id_address' => (int)$cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
foreach ($cart->getProducts() as $product) {
$tmp[] = array('id_product' => (int)$product['id_product'], 'id_product_attribute' => (int)$product['id_product_attribute'], 'quantity' => (int)$product['quantity']);
}
$result = Db::getInstance()->getRow(
'SELECT `cart_hash`, `update_date`
FROM `'._DB_PREFIX_.'avalara_carrier_cache`
WHERE `cart_hash` = \''.pSQL(md5(serialize($tmp))).'\'
ORDER BY update_date DESC'
);
if (!$result) {
return true;
}
// Compare date/time
date_default_timezone_set(@date_default_timezone_get());
if (abs(time() - strtotime($result['update_date'])) > Configuration::get('AVALARA_CACHE_MAX_LIMIT')) {
return true;
}
return false;
}
public static function updateProductsTax(AvalaraTax $avalaraModule, Cart $cart, $id_address, $region, $taxable = true)
{
$p = array();
foreach ($cart->getProducts() as $product) {
$avalaraProducts = array(
'id_product' => (int)$product['id_product'],
'name' => $product['name'],
'description_short' => $product['description_short'],
'quantity' => 1, // This is a per product, so qty is 1
'total' => (float)1000000,
'tax_code' => $taxable ? $avalaraModule->getProductTaxCode((int)$product['id_product']) : 'NT'
);
$p[] = $avalaraProducts;
// Call Avalara
$getTaxResult = $avalaraModule->getTax(array($avalaraProducts), array('type' => 'SalesOrder', 'DocCode' => 1, 'taxable' => $taxable));
// Store the taxrate in cache
// If taxrate exists (but it's outdated), then update, else insert (REPLACE INTO)
if (isset($getTaxResult['TotalTax']) && isset($getTaxResult['TotalAmount'])) {
$total_tax = $getTaxResult['TotalTax'];
$total_amount = $getTaxResult['TotalAmount'];
if ($total_amount == 0) {
$db_rate = 0;
} else {
$db_rate = (float)($total_tax * 100 / $total_amount);
}
Db::getInstance()->Execute('REPLACE INTO `'._DB_PREFIX_.'avalara_product_cache` (`id_product`, `tax_rate`, `region`, `update_date`, `id_address`)
VALUES ('.(int)$product['id_product'].', '.$db_rate.',
\''.($region ? pSQL($region) : '').'\', \''.date('Y-m-d H:i:s').'\', '.(int)$cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}.')');
}
}
return $p;
}
public static function updateCarrierTax(AvalaraTax $avalaraModule, Cart $cart, $id_address, $region, $taxable = true)
{
/** Update cache only if it is outdated */
if (self::checkCarrierCache($cart)) {
$avalaraProducts = array();
foreach ($cart->getProducts() as $product) {
$avalaraProducts[] = array('id_product' => (int)$product['id_product'],
'name' => $product['name'],
'description_short' => $product['description_short'],
'quantity' => (int)$product['quantity'],
'total' => (float)$product['price'],
'tax_code' => $taxable ? $avalaraModule->getProductTaxCode((int)$product['id_product']) : 'NT');
}
if (count($avalaraProducts)) {
// Calculate the carrier taxes
$getTaxResult = $avalaraModule->getTax($avalaraProducts, array('cart' => $cart));
$amount = (float)(isset($getTaxResult['TaxLines']['Shipping']['GetTax']) ? (float)$getTaxResult['TaxLines']['Shipping']['GetTax'] : 0);
$total_tax = (float)(isset($getTaxResult['TotalTax']) ? $getTaxResult['TotalTax'] : 0);
$total_amount = (float)(isset($getTaxResult['TotalAmount']) ? $getTaxResult['TotalAmount'] : 0);
$tax_rate = (float)(($total_amount != 0) ? ($total_tax * 100 / $total_amount) : 0);
$tmp = array('id_carrier' => (int)$cart->id_carrier, 'id_address' => (int)$cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
foreach ($cart->getProducts() as $product) {
$tmp[] = array('id_product' => (int)$product['id_product'], 'id_product_attribute' => (int)$product['id_product_attribute'], 'quantity' => (int)$product['quantity']);
}
Db::getInstance()->Execute('
INSERT INTO `'._DB_PREFIX_.'avalara_carrier_cache` (`id_carrier`, `tax_rate`, `region`, `amount`, `update_date`, `id_cart`, `cart_hash`)
VALUES ('.(int)$cart->id_carrier.', '.(float)$tax_rate.', \''.pSQL($region).'\', '.(float)$amount.', \''.date('Y-m-d H:i:s').'\', '.(int)$cart->id.', \''.md5(serialize($tmp)).'\')');
}
}
}
public static function getCarrierTaxAmount(Cart $cart)
{
$region = null;
$id_address = $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')};
if ($id_address) {
$address = new Address((int)$id_address);
if (Validate::isLoadedObject($address) && isset($address->id_state) && $address->id_state) {
$state = new State((int)$address->id_state);
if (Validate::isLoadedObject($state) && isset($state->iso_code) && !empty($state->iso_code)) {
$region = $state->iso_code;
}
}
}
return (float)Db::getInstance()->getValue(
'SELECT `amount`
FROM `'._DB_PREFIX_.'avalara_carrier_cache`
WHERE `id_cart` = '.(int)$cart->id.' AND `id_carrier` = '.(int)$cart->id_carrier.(!empty($region) ? ' AND region = \''.pSQL($region).'\'' : '').'
ORDER BY update_date DESC'
);
}
}