BeezUP_Module_feed_and_tracker - Version 4.7.5

Version Notes

New features :
- Amazon FBA no stock impact

Download this release

Release Info

Developer BeezUP
Extension BeezUP_Module_feed_and_tracker
Version 4.7.5
Comparing to
See all releases


Code changes from version 4.7.4 to 4.7.5

app/code/community/BeezUp/Block/Adminhtml/System/Config/Orderlink.php CHANGED
@@ -1,16 +1,16 @@
1
- <?php
2
-
3
class Beezup_Block_Adminhtml_System_Config_Orderlink extends Mage_Adminhtml_Block_System_Config_Form_Field
4
{
5
-
6
protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
7
{
8
-
9
$url_link = Mage::getStoreConfig(Mage_Core_Model_Url::XML_PATH_SECURE_URL) . 'beezup/cron/orderlink';
10
$url_order = Mage::getStoreConfig(Mage_Core_Model_Url::XML_PATH_SECURE_URL) . 'beezup/cron/order';
11
-
12
$retorno = "<input type='radio' name='order-link' onclick='openOrderLink(1);' /> ".$this->__('Separated data')." &nbsp;&nbsp;&nbsp;<input type='radio' name='order-link' onclick='openOrderLink(2);' /> ".$this->__('go.beezup.com order link')." ";
13
-
14
$retorno .= "
15
<div id='info-order-link' style='display:none;margin-top:50px;'>
16
<table class='table'>
@@ -32,7 +32,7 @@
32
</tr>
33
</table>
34
</div>
35
-
36
<div id='order-order-link' style='display:none;margin-top:50px;'>
37
<table class='table'>
38
<tr>
@@ -46,7 +46,7 @@
46
</table>
47
</div>
48
";
49
-
50
$retorno .= "
51
<script>
52
function openOrderLink(valor) {
@@ -58,8 +58,8 @@
58
document.getElementById('info-order-link').style.display = 'none';
59
}
60
}
61
-
62
-
63
function sendOrderInfo() {
64
var account = document.getElementById('info-order-account').value;
65
var marketplace = document.getElementById('info-order-marketplace').value;
@@ -67,20 +67,20 @@
67
var orderlink = '".$url_order."?acount_id=' + account + '&marketplace=' + marketplace + '&order_id=' + orderid;
68
window.open(orderlink,'_blank');
69
}
70
-
71
function sendOrderLink() {
72
var link = document.getElementById('order-link-enlace').value;
73
var link = encodeURIComponent(link);
74
var orderlink = '".$url_link."?url=' + link;
75
window.open(orderlink,'_blank');
76
}
77
-
78
</script>
79
";
80
-
81
return $retorno;
82
}
83
-
84
-
85
-
86
- }
1
+ <?php
2
+
3
class Beezup_Block_Adminhtml_System_Config_Orderlink extends Mage_Adminhtml_Block_System_Config_Form_Field
4
{
5
+
6
protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
7
{
8
+
9
$url_link = Mage::getStoreConfig(Mage_Core_Model_Url::XML_PATH_SECURE_URL) . 'beezup/cron/orderlink';
10
$url_order = Mage::getStoreConfig(Mage_Core_Model_Url::XML_PATH_SECURE_URL) . 'beezup/cron/order';
11
+
12
$retorno = "<input type='radio' name='order-link' onclick='openOrderLink(1);' /> ".$this->__('Separated data')." &nbsp;&nbsp;&nbsp;<input type='radio' name='order-link' onclick='openOrderLink(2);' /> ".$this->__('go.beezup.com order link')." ";
13
+
14
$retorno .= "
15
<div id='info-order-link' style='display:none;margin-top:50px;'>
16
<table class='table'>
32
</tr>
33
</table>
34
</div>
35
+
36
<div id='order-order-link' style='display:none;margin-top:50px;'>
37
<table class='table'>
38
<tr>
46
</table>
47
</div>
48
";
49
+
50
$retorno .= "
51
<script>
52
function openOrderLink(valor) {
58
document.getElementById('info-order-link').style.display = 'none';
59
}
60
}
61
+
62
+
63
function sendOrderInfo() {
64
var account = document.getElementById('info-order-account').value;
65
var marketplace = document.getElementById('info-order-marketplace').value;
67
var orderlink = '".$url_order."?acount_id=' + account + '&marketplace=' + marketplace + '&order_id=' + orderid;
68
window.open(orderlink,'_blank');
69
}
70
+
71
function sendOrderLink() {
72
var link = document.getElementById('order-link-enlace').value;
73
var link = encodeURIComponent(link);
74
var orderlink = '".$url_link."?url=' + link;
75
window.open(orderlink,'_blank');
76
}
77
+
78
</script>
79
";
80
+
81
return $retorno;
82
}
83
+
84
+
85
+
86
+ }
app/code/community/BeezUp/Block/Order.php CHANGED
@@ -17,7 +17,7 @@ class Beezup_Block_Order extends Mage_core_block_text {
17
private $marketplace_code;
18
private $beezup_order_id;
19
private $mage_order_id = false;
20
-
21
22
private function makeDir() {
23
@@ -45,6 +45,9 @@ class Beezup_Block_Order extends Mage_core_block_text {
45
}
46
$sync_end_date = new DateTime ( 'now', new DateTimeZone ( 'UTC' ));
47
$helper = Mage::helper('beezup');
48
$sync_status = $helper->getConfig('beezup/marketplace/sync_status');
49
$debug_mode = $helper->getConfig('beezup/marketplace/debug_mode');
50
$create_customer = $helper->getConfig("beezup/marketplace/create_customers");
@@ -162,6 +165,8 @@ class Beezup_Block_Order extends Mage_core_block_text {
162
163
$sync_end_date = new DateTime ( 'now', new DateTimeZone ( 'UTC' ));
164
$helper = Mage::helper('beezup');
165
$sync_status = $helper->getConfig('beezup/marketplace/sync_status');
166
$debug_mode = $helper->getConfig('beezup/marketplace/debug_mode');
167
$create_customer = $helper->getConfig("beezup/marketplace/create_customers");
@@ -271,6 +276,13 @@ class Beezup_Block_Order extends Mage_core_block_text {
271
$order_totalPrice = $final_order->getOrderTotalPrice();
272
$order_shippingPrice = $final_order->getOrderShippingPrice();
273
274
$name_parts = explode(" ", $order_customer);
275
$order_first_name = array_shift( $name_parts);
276
$order_last_name = implode(" ", $name_parts);
@@ -306,6 +318,7 @@ class Beezup_Block_Order extends Mage_core_block_text {
306
$mage_productIds = $this->prescanOrder($final_order);
307
if($mage_productIds) {
308
$order_data = array(
309
"etag" => $etag,
310
"account_id" => $account_id,
311
"order_status" => $order_status,
@@ -832,7 +845,7 @@ class Beezup_Block_Order extends Mage_core_block_text {
832
}
833
834
835
-
836
837
private function createCustomer($customer_email , $data) {
838
$password = $this->orderid;
@@ -902,27 +915,37 @@ class Beezup_Block_Order extends Mage_core_block_text {
902
//echo "Product ".$product->getId()."<br><br>";
903
//para no perder stock:
904
//Mage::getModel('cataloginventory/stock')->backItemQty($productId,$new_qty);
905
-
906
-
907
- if($addStock == 1) {
908
- $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product);
909
-
910
- if ($stock->getQty() < $prod['qty'] && $product->getStockItem()->getMaxSaleQty() >= $prod['qty']) {
911
- $this->debugLog("Product ".$product->getId()." Stock = 0, Updating to ".$prod['qty']." to generate Order");
912
- // Mage::getModel('cataloginventory/stock')->backItemQty($product->getId(),$prod['qty']);
913
- //$this->_updateStocks(array("id_product" => $product->getId(), "qty" => $prod['qty']));
914
- $product->setStockData(
915
- array(
916
- 'is_in_stock' => 1,
917
- 'qty' => $prod['qty'],
918
- 'manage_stock' => 1,
919
- 'use_config_notify_stock_qty' => 1
920
- )
921
- );
922
$product->save();
923
$product = Mage::getModel('catalog/product')->load($product->getId());
924
925
}
926
}
927
//fin para no perder stock
928
@@ -1166,12 +1189,15 @@ class Beezup_Block_Order extends Mage_core_block_text {
1166
1167
try {
1168
foreach($data['products'] as $prod) {
1169
$product = Mage::getModel('catalog/product')->load($prod['id']);
1170
$stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product);
1171
if ($stock->getQty() != $prod['curr_stock'] ) {
1172
$this->debugLog("Restoring Stock from Product ".$product->getId()." to: ".$prod['curr_stock'] ." due to Order Fail");
1173
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product);
1174
- $stockItem->setData('is_in_stock', 0);
1175
$stockItem->setData('qty', $prod['curr_stock']);
1176
$stockItem->save();
1177
$product->save();
17
private $marketplace_code;
18
private $beezup_order_id;
19
private $mage_order_id = false;
20
+ private $marketChannelFilters = array();
21
22
private function makeDir() {
23
45
}
46
$sync_end_date = new DateTime ( 'now', new DateTimeZone ( 'UTC' ));
47
$helper = Mage::helper('beezup');
48
+
49
+ $marketChannelFilters = $helper->getConfig('beezup/marketplace/market_channel_filters');
50
+ $this->marketChannelFilters = explode(",", $marketChannelFilters);
51
$sync_status = $helper->getConfig('beezup/marketplace/sync_status');
52
$debug_mode = $helper->getConfig('beezup/marketplace/debug_mode');
53
$create_customer = $helper->getConfig("beezup/marketplace/create_customers");
165
166
$sync_end_date = new DateTime ( 'now', new DateTimeZone ( 'UTC' ));
167
$helper = Mage::helper('beezup');
168
+ $marketChannelFilters = $helper->getConfig('beezup/marketplace/market_channel_filters');
169
+ $this->marketChannelFilters = explode(",", $marketChannelFilters);
170
$sync_status = $helper->getConfig('beezup/marketplace/sync_status');
171
$debug_mode = $helper->getConfig('beezup/marketplace/debug_mode');
172
$create_customer = $helper->getConfig("beezup/marketplace/create_customers");
276
$order_totalPrice = $final_order->getOrderTotalPrice();
277
$order_shippingPrice = $final_order->getOrderShippingPrice();
278
279
+ $marketChannel = $final_order->getOrderMarketplaceChannel();
280
+ $resetStock = false;
281
+ foreach($this->marketChannelFilters as $filter) {
282
+ if($filter == $marketChannel) {
283
+ $resetStock = true;
284
+ }
285
+ }
286
$name_parts = explode(" ", $order_customer);
287
$order_first_name = array_shift( $name_parts);
288
$order_last_name = implode(" ", $name_parts);
318
$mage_productIds = $this->prescanOrder($final_order);
319
if($mage_productIds) {
320
$order_data = array(
321
+ "resetStock" => $resetStock,
322
"etag" => $etag,
323
"account_id" => $account_id,
324
"order_status" => $order_status,
845
}
846
847
848
+ private $currentStock = null;
849
850
private function createCustomer($customer_email , $data) {
851
$password = $this->orderid;
915
//echo "Product ".$product->getId()."<br><br>";
916
//para no perder stock:
917
//Mage::getModel('cataloginventory/stock')->backItemQty($productId,$new_qty);
918
+ $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product);
919
+ $this->currentStock[$prod['id']] = $stock->getQty();
920
+ if($addStock == 1 || $data['resetStock'] == true) {
921
+
922
+
923
+ if (($stock->getQty() < $prod['qty'] && $product->getStockItem()->getMaxSaleQty() >= $prod['qty'] ) || $data['resetStock']
924
+ == true) {
925
+ $stockQty = $this->currentStock[$prod['id']] + $prod['qty'];
926
+ $this->debugLog("Product ".$product->getId()." Stock = ".(int)$this->currentStock[$prod['id']] .", Adding 1 to stock to generate Order");
927
+ // Mage::getModel('cataloginventory/stock')->backItemQty($product->getId(),$prod['qty']);
928
+ //$this->_updateStocks(array("id_product" => $product->getId(), "qty" => $prod['qty']));
929
+
930
+ $product->setStockData(
931
+ array(
932
+ 'is_in_stock' => 1,
933
+ 'qty' => $stockQty,
934
+ 'manage_stock' => 1,
935
+ 'use_config_notify_stock_qty' => 1
936
+ )
937
+ );
938
$product->save();
939
$product = Mage::getModel('catalog/product')->load($product->getId());
940
941
}
942
+ } elseif($this->currentStock[$prod['id']] == 0) {
943
+ $this->log->LogError($this->orderid. "| Order ".$data['market_place_order_id']." could not be imported, error: Product with id ".$product->getId()." has stock 0");
944
+ $this->restoreStock($data);
945
+ $blnCreate = false;
946
+ return;
947
+ break;
948
+
949
}
950
//fin para no perder stock
951
1189
1190
try {
1191
foreach($data['products'] as $prod) {
1192
+ if(!isset($this->currentStock[$prod['id']])) {
1193
+ continue;
1194
+ }
1195
$product = Mage::getModel('catalog/product')->load($prod['id']);
1196
$stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product);
1197
if ($stock->getQty() != $prod['curr_stock'] ) {
1198
$this->debugLog("Restoring Stock from Product ".$product->getId()." to: ".$prod['curr_stock'] ." due to Order Fail");
1199
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product);
1200
+ $stockItem->setData('is_in_stock', (int)$this->currentStock[$prod['id']]);
1201
$stockItem->setData('qty', $prod['curr_stock']);
1202
$stockItem->save();
1203
$product->save();
app/code/community/BeezUp/Block/Order_old.php DELETED
@@ -1,1553 +0,0 @@
1
- <?php
2
- require_once Mage::getModuleDir('', 'BeezUp') . DS . 'lib' . DS ."KLogger.php";
3
- require_once Mage::getModuleDir('', 'BeezUp') . DS . 'lib' . DS ."bootstrap.php";
4
- require_once Mage::getModuleDir('', 'BeezUp') . DS . 'lib' . DS ."BeezupRepository.php";
5
- require_once Mage::getModuleDir('', 'BeezUp') . DS . 'lib' . DS ."BeezupMageOrders.php";
6
-
7
- class Beezup_Block_Order extends Mage_core_block_text {
8
-
9
- protected $repository = null;
10
- protected $oOrderService;
11
- public $log = null;
12
- public $log2 = null;
13
- public $orderid = "";
14
- public $debug = false;
15
- public $blnCreateCustomer = false;
16
- private $account_id;
17
- private $marketplace_code;
18
- private $beezup_order_id;
19
- private $mage_order_id = false;
20
-
21
-
22
- private function makeDir() {
23
-
24
- if (file_exists(Mage::getBaseDir('base').'/beezup/tmp')) { return true;}
25
-
26
- if (!mkdir(Mage::getBaseDir('base').'/beezup/tmp', 0777, true))
27
- {
28
- echo "[ERROR] : Seems we can't create 'beezup' directory inside your root directory."."<br/>"
29
- ."You can try one of these solutions :"."<br/>"
30
- ."1 - Create by yourself the beezup/tmp inside your root directory with 777 permissions"."<br/>"
31
- ."2 - Change the permissions on your root directory (777)"."<br/>"
32
- ."3 - Change the 'cache delay' option to 'None' inside beezup plugin settings"."<br/>";
33
- return false;
34
- }
35
- return true;
36
-
37
- }
38
- public function createOrderFromLink($account_id, $marketplace_code, $beezup_order_id) {
39
- $this->makeDir();
40
- $logDir = Mage::getBaseDir('base').'/beezup/';
41
- if(file_exists($logDir."log2.txt")) {
42
- if(filesize($logDir."/log2.txt") >=3000000) {
43
- unlink($logDir."log2.txt");
44
- }
45
- }
46
- $sync_end_date = new DateTime ( 'now', new DateTimeZone ( 'UTC' ));
47
- $helper = Mage::helper('beezup');
48
- $sync_status = $helper->getConfig('beezup/marketplace/sync_status');
49
- $debug_mode = $helper->getConfig('beezup/marketplace/debug_mode');
50
- $create_customer = $helper->getConfig("beezup/marketplace/create_customers");
51
- if($create_customer == 0) {
52
- $this->blnCreateCustomer = true;
53
- }
54
-
55
- if($debug_mode==1) {
56
- $this->debug = true;
57
- }
58
- if($sync_status!==1) {
59
- $configModel = Mage::getModel('core/config');
60
- $configModel->saveConfig('beezup/marketplace/sync_status',1);
61
-
62
-
63
- unlink($logDir."log.txt");
64
- $this->log = new KLogger ( $logDir."log.txt" , KLogger::DEBUG );
65
- $this->log2 = new KLogger ( $logDir."log2.txt" , KLogger::DEBUG );
66
- $this->debugLog("Initializing OM Importation");
67
- $shiiping_disabled = Mage::getStoreConfig('carriers/flatrate/active');
68
-
69
- $this->account_id = $account_id;
70
- $this->marketplace_code = $marketplace_code;
71
- $this->beezup_order_id = $beezup_order_id;
72
- $orderResponse = $this->getBeezupOrder();
73
- if($orderResponse) {
74
-
75
- if($shiiping_disabled == 0) {
76
- Mage::getConfig()
77
- ->saveConfig('carriers/flatrate/active', 1)
78
- ->cleanCache();
79
- Mage::app()->reinitStores();
80
- }
81
- $this->createOrder($orderResponse);
82
- //OCI sinon le shiiping flate reste actif ...
83
- //if($shiiping_disabled == 1) {
84
- if($shiiping_disabled == 1) {
85
- Mage::getConfig()
86
- ->saveConfig('carriers/flatrate/active', 0)
87
- ->cleanCache();
88
- Mage::app()->reinitStores();
89
- }
90
- $configModel->saveConfig('beezup/marketplace/sync_status',0);
91
- if($this->mage_order_id) {
92
- echo "<script>window.location='".Mage::helper('adminhtml')->getUrl("adminhtml/sales_order/view", array('order_id'=> $this->mage_order_id))."';</script>";
93
- }
94
- // die("Order Importation finalized");
95
-
96
- }
97
-
98
- }
99
- $configModel->saveConfig('beezup/marketplace/sync_status',0);
100
- //die("Error, Order data incorrect");
101
- echo $this->_showLog();
102
- }
103
-
104
- public function _showLog() {
105
- $logDir = Mage::getBaseDir('base').'/beezup/';
106
- // $log1 = file_get_contents();
107
- $ret = array();
108
- if (file_exists($logDir."/log.txt")) {
109
- $f = fopen($logDir."/log.txt", 'r');
110
-
111
- if ($f) {
112
- while (!feof($f)) {
113
- $ret[] = fgetcsv($f, 0, '|');
114
- }
115
- fclose($f);
116
- }
117
- }
118
- array_slice(array_reverse($ret), 1, 10);
119
-
120
- return $this->_getTable($ret);
121
-
122
- }
123
-
124
-
125
- public function _getTable($data) {
126
- $url = Mage::getBaseUrl( Mage_Core_Model_Store::URL_TYPE_WEB, true );
127
- $html = "<td></td><td></td><tr></tr></tbody></table>
128
-
129
- <div class='grid' style=' height: 600px;overflow-y: scroll;padding: 16px;border: 3px solid #e6e6e6;' id='marketPlaceLogBlock'>";
130
- $html .= '<p>'. Mage::helper('beezup')->__('For full logs see here:').' <a href="'.$url .'beezup/log/load" target="_blank">'.$url .'beezup/log/load</a></p>';
131
- $html .= "<table class='data' style='margin-top:0px;width:100%;'>";
132
- $html .= "<tr class='headings'>";
133
- $html .= '<th><span class="nobr">Time</span></th>';
134
- $html .= '<th><span class="nobr">Type</span></th>';
135
- $html .= '<th><span class="nobr">Order Id</span></th>';
136
- $html .= '<th><span class="nobr">Message</span></th>';
137
- $html .= "</tr>";
138
- $html .= "<tbody>";
139
- foreach($data as $d) {
140
- $background = " background: rgb(240, 184, 184)";
141
- if($d[1] == " INFO " ) {
142
- $background = " background: rgb(210, 227, 253)";
143
- }
144
- $orderId = (isset($d[3])) ? $d[2] : "";
145
- $message = (isset($d[3])) ? $d[3] : $d[2];
146
- $html .= "<tr class='even pointer' style='".$background."'>";
147
- $html .= "<td>".$d[0]."</td>";
148
- $html .= "<td>".$d[1]."</td>";
149
- $html .= "<td>".$orderId."</td>";
150
- $html .= "<td>".$message."</td>";
151
- $html .= "</tr>";
152
-
153
- }
154
-
155
- $html .= "<tbody>";
156
- $html .= '</table>';
157
- $html .= "</div>";
158
-
159
- return $html;
160
- }
161
-
162
-
163
-
164
- public function executeCron() {
165
-
166
- $this->makeDir();
167
-
168
- set_time_limit(0);
169
- $logDir = Mage::getBaseDir('base').'/beezup/';
170
- if(file_exists($logDir."log2.txt")) {
171
- if(filesize($logDir."/log2.txt") >=3000000) {
172
- unlink($logDir."log2.txt");
173
- }
174
- }
175
-
176
- $sync_end_date = new DateTime ( 'now', new DateTimeZone ( 'UTC' ));
177
- $helper = Mage::helper('beezup');
178
- $sync_status = $helper->getConfig('beezup/marketplace/sync_status');
179
- $debug_mode = $helper->getConfig('beezup/marketplace/debug_mode');
180
- $create_customer = $helper->getConfig("beezup/marketplace/create_customers");
181
- if($create_customer == 0) {
182
- $this->blnCreateCustomer = true;
183
- }
184
-
185
- if($debug_mode==1) {
186
- $this->debug = true;
187
- }
188
-
189
- if($sync_status!==1) {
190
- $configModel = Mage::getModel('core/config');
191
- $configModel->saveConfig('beezup/marketplace/sync_status',1);
192
-
193
-
194
-
195
- unlink($logDir."log.txt");
196
- $this->log = new KLogger ( $logDir."log.txt" , KLogger::DEBUG );
197
- $this->log2 = new KLogger ( $logDir."log2.txt" , KLogger::DEBUG );
198
-
199
-
200
- $shiiping_disabled = Mage::getStoreConfig('carriers/flatrate/active');
201
- $this->debugLog("## flatrate active yes or no : ".$shiiping_disabled."##");
202
-
203
-
204
- if($shiiping_disabled == 0) {
205
- Mage::getConfig()
206
- ->saveConfig('carriers/flatrate/active', 1)
207
- ->cleanCache();
208
- Mage::app()->reinitStores();
209
-
210
- }
211
-
212
-
213
- $this->getOrderList();
214
-
215
- //OCI shiiping_disabled 1 et pas 0...
216
-
217
- if($shiiping_disabled == 1) {
218
- Mage::getConfig()
219
- ->saveConfig('carriers/flatrate/active', 0)
220
- ->cleanCache();
221
- Mage::app()->reinitStores();
222
-
223
- }
224
- $this->repository->updateLastSynchronizationDate( $sync_end_date);
225
- $this->orderid = "";
226
- $this->debugLog("OM Importation finalized succesfully");
227
- $configModel->saveConfig('beezup/marketplace/sync_status',0);
228
- echo "OM Importation finalized succesfully";
229
-
230
- } else {
231
-
232
- echo "Order Importation is already being executed";
233
- }
234
-
235
- }
236
-
237
-
238
- public function getLog() {
239
- $logDir = Mage::getBaseDir('base').'/beezup/';
240
- $log1 = file_get_contents($logDir."/log2.txt");
241
-
242
- echo "<pre>";
243
- print_r($log1);
244
- echo "</pre>";
245
-
246
- }
247
- public function getBeezupOrder() {
248
-
249
- $oOrderIdentifier = $this->getBeezupOrderId();
250
- $oBeezupOMOrderResponse = $this->getOrderService()->getOrder($oOrderIdentifier);
251
- if ($oBeezupOMOrderResponse && $oBeezupOMOrderResponse->getResult()){
252
- return $oBeezupOMOrderResponse;
253
- }
254
-
255
-
256
- return false;
257
- }
258
-
259
- public function getBeezupOrderId(){
260
- $oIdentifier = new BeezupOMOrderIdentifier();
261
- $oIdentifier
262
- ->setAccountId($this->account_id)
263
- ->setMarketplaceTechnicalCode($this->marketplace_code)
264
- ->setBeezupOrderUUID($this->beezup_order_id);
265
- return $oIdentifier;
266
- }
267
-
268
-
269
- public function createOrder($oBeezupOrderResponse) {
270
-
271
- $etag = $oBeezupOrderResponse->getETag();
272
- $final_order = $oBeezupOrderResponse->getResult();
273
-
274
- $orderid = $final_order->getOrderMarketPlaceOrderId();
275
- $this->orderid = $orderid;
276
- //customer Info
277
- $order_address = $final_order->getOrderBuyerAddressCity();
278
- $order_country = $final_order->getOrderBuyerAddressCountryName();
279
- $order_country_iso = $final_order->getOrderBuyerAddressCountryIsoCodeAlpha2();
280
- $order_address = $this->getBeezupBuyerAddress($final_order);
281
- $order_postalCode = $final_order->getOrderBuyerAddressPostalCode();
282
- $order_customer = $final_order->getOrderBuyerName();
283
- $order_customer_email = $final_order->getOrderBuyerEmail();
284
- $order_customer_phone = $final_order->getOrderBuyerPhone();
285
- $order_customer_mobile = $final_order->getOrderBuyerMobilePhone();
286
- $order_comment = $final_order->getOrderComment();
287
- $order_company = $final_order->getOrderBuyerCompanyName();
288
- $order_city = $final_order->getOrderBuyerAddressCity();
289
- $order_region = $final_order->getOrderBuyerStateOrRegion();
290
- $order_status = $final_order->getOrderStatusBeezUPOrderStatus();
291
- //shipping information
292
- $shipping_city = $final_order->getOrderShippingAddressCity();
293
- $shipping_country = $final_order->getOrderShippingAddressCountryName();
294
- $shipping_country_iso = $final_order->getOrderShippingAddressCountryIsoCodeAlpha2();
295
- $shipping_address = $this->getBeezupShippingAddress($final_order);
296
- $shipping_name = $final_order->getOrderShippingAddressName();
297
- $shipping_postalCode = $final_order->getOrderShippingAddressPostalCode();
298
- $shipping_email = $final_order->getOrderShippingEmail();
299
- $shipping_phone = $final_order->getOrderShippingPhone();
300
- $shipping_method_BEEZUP = $final_order->getOrderShippingMethod();
301
- $shipping_mobile = $final_order->getOrderShippingMobilePhone();
302
- $shipping_company = $final_order->getOrderShippingCompanyName();
303
- $shipping_region = $final_order->getOrderShippingAddressStateOrRegion();
304
- $order_currency_code = $final_order->getOrderCurrencyCode();
305
- //order Info
306
- $order_totalPrice = $final_order->getOrderTotalPrice();
307
- $order_shippingPrice = $final_order->getOrderShippingPrice();
308
-
309
- $name_parts = explode(" ", $order_customer);
310
- $order_first_name = array_shift( $name_parts);
311
- $order_last_name = implode(" ", $name_parts);
312
-
313
-
314
- $name_parts = explode(" ", $shipping_name);
315
- $shipping_first_name = array_shift( $name_parts);
316
- $shipping_last_name = implode(" ", $name_parts);
317
-
318
-
319
- //marketplace information
320
- $marketplace_business_code = $final_order->getMarketPlaceBusinessCode();
321
- $marketplace = $final_order->getMarketPlaceTechnicalCode();
322
-
323
- //productInfo
324
-
325
- $mage_productIds = $this->prescanOrder($final_order);
326
-
327
-
328
-
329
- if(!$this->checkEtagExists($etag)) {
330
- if(empty($order_customer_email)) {
331
- $order_customer_email = $this->generateEmail($final_order);
332
- }
333
- elseif(!filter_var($order_customer_email, FILTER_VALIDATE_EMAIL)) {
334
- $order_customer_email = $this->generateEmail($final_order);
335
- }
336
- if($order_country_iso == "FX" || $order_country_iso == "fx") {
337
- $order_country_iso = "FR";
338
- }
339
- if($shipping_country_iso == "FX" || $shipping_country_iso == "fx") {
340
- $shipping_country_iso = "FR";
341
- }
342
- $mage_productIds = $this->prescanOrder($final_order);
343
- if($mage_productIds) {
344
-
345
- if ($shipping_last_name=='') $shipping_last_name = $shipping_first_name;
346
-
347
- $order_data = array(
348
- "etag" => $etag,
349
- "account_id" => $account_id,
350
- "order_status" => $order_status,
351
- "products" => $mage_productIds['products'],
352
- "storeid" => $mage_productIds['store'],
353
- "order_currency" => $order_currency_code ,
354
- "order_address" => $order_adress,
355
- "order_country" => $order_country,
356
- "order_country_iso" => $order_country_iso ,
357
- "order_address" => $order_address ,
358
- "order_postalCode" => $order_postalCode ,
359
- "order_customer" => $order_first_name ,
360
- "order_lastname" => $order_last_name ,
361
- "order_customer_email" => $order_customer_email ,
362
- "order_customer_phone" => $this->getPhone($order_customer_phone, $order_customer_mobile) ,
363
- "order_comment" => $order_comment ,
364
- "order_company" => $order_company ,
365
- "shipping_city" => $shipping_city ,
366
- "shipping_country" => $shipping_country ,
367
- "shipping_country_iso" => $shipping_country_iso ,
368
- "shipping_address" => $shipping_address ,
369
- "shipping_name" => $shipping_first_name ,
370
- "shipping_lastname" => $shipping_last_name ,
371
- "shipping_postalCode" => $shipping_postalCode ,
372
- "shipping_region" =>$shipping_region,
373
- "shipping_email" => $shipping_email ,
374
- "shipping_phone" => $this->getPhone($shipping_phone, $shipping_mobile) ,
375
- "shipping_company" => $shipping_company ,
376
- "order_totalPrice" => $order_totalPrice ,
377
- "order_shippingPrice" => $order_shippingPrice ,
378
- "order_city" => $order_city,
379
- "order_region" => $order_region,
380
- "marketplace" => $marketplace,
381
- "discounts" => $mage_productIds['discounts'],
382
- "marketplace_business_code" => $marketplace_business_code,
383
- //ajout OCI pour passer la methode
384
- "shipping_method_BEEZUP" => $shipping_method_BEEZUP
385
- );
386
- // $this->debugLog(printf($order_data));
387
-
388
-
389
- $this->debugLog("Order data : ");
390
- foreach ($order_data as $key => $value){
391
- $this->debugLog($key . " : " . $value);
392
- }
393
-
394
-
395
- //check if order exists
396
- $Mageorder = $this->loadMageOrder();
397
- if ($Mageorder) {
398
- //if order exists
399
- $this->updateEtag($etag);
400
- $this->updateBilling($Mageorder, $order_data);
401
- $this->updateBeezupInfoTab($Mageorder, $final_order, $order_data);
402
- $this->debugLog("Order Already exists Mage Order ID: " .$Mageorder->getId());
403
- $status1 = $Mageorder->getStatusLabel();
404
- $status = $this->getStatus($status1);
405
- if($status !== $order_status) {
406
- //if order exits and status has changed we update order status
407
- $this->debugLog("Updating Order Status from: ".$status1." to: ".$order_status );
408
- $this->setStatus( $order_status, $Mageorder);
409
- }
410
-
411
- $id_order = $Mageorder->getId();
412
- $BeezupMageOrder = new BeezupMageOrders($id_order);
413
- $BeezupMageOrder->setData(array("shipping" =>(float) $order_data['order_shippingPrice']));
414
- $BeezupMageOrder->updateShippingInfo();
415
- } else {
416
- //if not we create order
417
-
418
-
419
- $this->debugLog("Generating Order");
420
- $this->addOrder($order_data,$final_order);
421
- //die();
422
-
423
- }
424
-
425
-
426
- } else {
427
- //order could not be imported
428
-
429
-
430
- }
431
-
432
-
433
- } else {
434
- //etag has not changed
435
- $shiiping_disabled = Mage::getStoreConfig('carriers/flatrate/active');
436
- // On remet le Flat à 0 !!!
437
- if($shiiping_disabled == 1) {
438
- Mage::getConfig()
439
- ->saveConfig('carriers/flatrate/active', 0)
440
- ->cleanCache();
441
- Mage::app()->reinitStores();
442
-
443
- }
444
-
445
- $this->debugLog("Order Etag has not changed");
446
-
447
- }
448
-
449
-
450
-
451
-
452
-
453
- }
454
-
455
-
456
-
457
- public function generateEmail(BeezupOMOrderResult $oBeezupOrder)
458
- {
459
- $sRawValue = $oBeezupOrder->getBeezupOrderUUID ();
460
- $sFakeDomain = preg_replace ( '/\W/', '', $oBeezupOrder->getMarketPlaceTechnicalCode () ) . '.com';
461
- return 'fakeemail' . md5 ( $sFakeDomain . $sRawValue ) . '@' . strtolower ( $sFakeDomain );
462
- }
463
-
464
-
465
-
466
- public function getOrderList($orderList = null) {
467
- if($orderList == null) {
468
- $data = $this->createRepository()->createOrderListRequest();
469
- $oRequest = $this->getOrderService()->getClientProxy()->getOrderList($data);
470
- $orderList = $oRequest->getResult();
471
- }
472
- $oPagination = $orderList->getPaginationResult();
473
- if(!empty($oPagination)) {
474
- $oLinksTotal = $oPagination->getLinks();
475
- } else {
476
- $configModel = Mage::getModel('core/config');
477
- $configModel->saveConfig('beezup/marketplace/sync_status',0);
478
- // Correction FRED On remet le shipping à 0 !!!
479
- $shiiping_disabled = Mage::getStoreConfig('carriers/flatrate/active');
480
-
481
- if($shiiping_disabled == 1) {
482
- Mage::getConfig()
483
- ->saveConfig('carriers/flatrate/active', 0)
484
- ->cleanCache();
485
- Mage::app()->reinitStores();
486
-
487
- }
488
- die("No more orders to import");
489
- }
490
-
491
- //$header = $orderList->getOrderHeaders();
492
- foreach($orderList->getOrderHeaders() as $order) {
493
- $order_status = $order->getBeezupOrderState();
494
- $orderLinks = $order->getLinks();
495
- $etag = $order->getETag();
496
- $beezup_order_id = $order->getBeezupOrderUUID();
497
- $account_id = $order->getAccountId();
498
- $orderdata = $this->getOrderService()->getClientProxy()->getOrderByLink($orderLinks[0]);
499
- $this->debugLog("Initializing Order - Link: ".$orderLinks[0]->getHref());
500
- $this->createOrder($orderdata);
501
-
502
- }
503
-
504
- if(!empty($oLinksTotal)) {
505
- //we check if there is next link and get next orders
506
- foreach($oLinksTotal as $link) {
507
- if( $link->getRel() == "next") {
508
-
509
- $this->log->LogInfo("Initializing New Order List ->". $link->getHref());
510
- $this->log2->LogInfo("Initializing New Order List ->". $link->getHref());
511
- $oRequest = $this->getOrderService()->getClientProxy()->getOrderListByLink($link);
512
- $orderList = $oRequest->getResult();
513
- $this->getOrderList($orderList);
514
- }
515
-
516
- }
517
- }
518
-
519
- }
520
-
521
-
522
-
523
- public function updateBeezupInfoTab($order, $oLink, $data) {
524
- $beezup_last_modification_date = $oLink->getOrderLastModificationUtcDate();
525
- $beezup_last_modification_date = $beezup_last_modification_date->date;
526
- $beezup_marketplace_last_modification_date = $oLink->getOrderMarketPlaceLastModificationUtcDate();
527
- $beezup_marketplace_last_modification_date = $beezup_marketplace_last_modification_date->date;
528
- $beezup_comission = $oLink->getOrderTotalCommission()." ".$data['order_currency'];
529
- $tot_comm = $oLink->getOrderTotalCommission();
530
- if(empty($tot_comm ) || $tot_comm == 0) {
531
- $beezup_comission = 0;
532
- }
533
- $updateData = array("beezup_status" => $data['order_status'],
534
- "beezup_last_modification_date" => $beezup_last_modification_date,
535
- "beezup_marketplace_last_modification_date" => $beezup_marketplace_last_modification_date ,
536
- "beezup_total_paid" => $oLink->getOrderTotalPrice()." ".$data['order_currency'],
537
- "beezup_comission" => $beezup_comission,
538
- "beezup_marketplace_status" => $oLink->getOrderStatusMarketPlaceStatus());
539
- $orderId = $order->getId();
540
- $beezupMageOrder = new BeezupMageOrders($orderId);
541
- $beezupMageOrder->setData($updateData);
542
- $beezupMageOrder->updateBeezupInfo();
543
-
544
-
545
- }
546
-
547
- public function getPhone($phone, $phone2) {
548
- $retorno = "";
549
- if(!empty($phone) && $phone !== "") {
550
- $retorno .= $phone;
551
- }
552
- if(!empty($phone2) && $phone2 !=="") {
553
- if(empty($phone) || $phone == "") {
554
- $retorno = $phone2;
555
-
556
- } else {
557
- $retorno .= " - ".$phone2;
558
- }
559
- }
560
- return $retorno;
561
- }
562
-
563
-
564
- public function getBeezupBuyerAddress($order) {
565
- $add1=$order->getOrderBuyerAddressLine1();
566
- $add2=$order->getOrderBuyerAddressLine2();
567
- $add3=$order->getOrderBuyerAddressLine3();
568
- $retorno = "";
569
- if(!empty($add1)) {
570
- $retorno = $order->getOrderBuyerAddressLine1();
571
- }
572
- if(!empty($add2)) {
573
- if(empty($add1)) {
574
- $retorno .= $order->getOrderBuyerAddressLine2();
575
- } else {
576
- $retorno .= " - ". $order->getOrderBuyerAddressLine2();
577
- }
578
- }
579
- if(!empty($add3)){
580
- if(empty($add1) && empty($add2)) {
581
- $retorno .= $order->getOrderBuyerAddressLine3();
582
- } else {
583
- $retorno .= " - ". $order->getOrderBuyerAddressLine3();
584
- }
585
- }
586
- return $retorno;
587
- }
588
-
589
-
590
- public function getBeezupShippingAddress($order) {
591
- $add1 = $order->getOrderShippingAddressLine1();
592
- $add2 = $order->getOrderShippingAddressLine2();
593
- $add3=$order->getOrderBuyerAddressLine3();
594
- $retorno = "";
595
- if(!empty($add1 )) {
596
- $retorno = $order->getOrderShippingAddressLine1();
597
- }
598
- if(!empty($add2)) {
599
- if(empty($add1)) {
600
- $retorno .= $order->getOrderShippingAddressLine2();
601
- } else {
602
- $retorno .= " - ". $order->getOrderShippingAddressLine2();
603
- }
604
- }
605
- if(!empty($add3)){
606
- if(empty($add1) && empty($add2)) {
607
- $retorno .= $order->getOrderShippingAddressLine3();
608
- } else {
609
- $retorno .= " - ". $order->getOrderShippingAddressLine3();
610
- }
611
- }
612
- return $retorno;
613
- }
614
-
615
- public function checkEtagExists($etag) {
616
- $resource = Mage::getSingleton('core/resource');
617
- $readConnection = $resource->getConnection('core_read');
618
- $table = $resource->getTableName('sales/order_grid');
619
- $query = 'SELECT increment_id FROM ' . $table . ' WHERE beezup_etag = \''
620
- . $etag . '\' LIMIT 1';
621
- $order = $readConnection->fetchOne($query);
622
- if($order && !empty($order)) {
623
- return true;
624
- }
625
- return false;
626
-
627
- }
628
-
629
-
630
- public function updateEtag($etag) {
631
- $this->debugLog("Updating Etag");
632
- $resource = Mage::getSingleton('core/resource');
633
- $writeConnection = $resource->getConnection('core_write');
634
- $table = $resource->getTableName('sales/order_grid');
635
- $query = "UPDATE {$table} SET beezup_etag = '{$etag}' where beezup_market_order_id = '{$this->orderid}' ";
636
- $writeConnection->query($query);
637
-
638
- }
639
-
640
-
641
-
642
- public function updateBilling($order, $data) {
643
-
644
- $addressData = array(
645
- 'billing_company' => ($data['order_company']) ? $data['order_company'] : "",
646
- 'billing_firstname' => ($data['order_customer']) ? $data['order_customer'] : "empty",
647
- 'billing_lastname' => ($data['order_lastname']) ? $data['order_lastname'] : "empty",
648
- 'billing_street' => ($data['order_address']) ? $data['order_address'] : "empty",
649
- 'billing_city' => ($data['order_city']) ? $data['order_city'] : "empty",
650
- 'billing_postcode' => ($data['order_postalCode']) ? $data['order_postalCode'] : "empty",
651
- 'billing_telephone' => ($data['order_customer_phone']) ? $data['order_customer_phone'] : "empty",
652
- 'billing_country_id' => ($data['order_country_iso']) ? $data['order_country_iso'] : "empty",
653
- 'billing_region_id' => ($data['order_region ']) ? substr($data['order_region '], 0,2) : "EM",
654
- 'shipping_firstname' => ($data['shipping_name']) ? $data['shipping_name'] : "empty",
655
- 'shipping_lastname' => ($data['shipping_lastname']) ? $data['shipping_lastname'] : $data['shipping_name'],
656
- 'shipping_street' => ($data['shipping_address']) ? $data['shipping_address'] : "empty",
657
- 'shipping_city' => ($data['shipping_city']) ? $data['shipping_city'] : "empty",
658
- 'shipping_postcode' => ($data['shipping_postalCode']) ? $data['shipping_postalCode'] : "empty",
659
- 'shipping_telephone' => ($data['shipping_phone']) ? $data['shipping_phone'] : "empty",
660
- 'shipping_country_id' => ($data['shipping_country_iso']) ? $data['shipping_country_iso'] : "empty",
661
- 'shipping_company' => ($data['shipping_company']) ? $data['shipping_company'] : "",
662
- 'shipping_region_id' => ($data['shipping_region']) ? substr($data['shipping_region'], 0, 2) : "EM" // id from directory_country_region table
663
- );
664
-
665
- $shippingData = array(
666
-
667
- );
668
- // Get the id of the orders shipping address
669
- $orderId = $order->getId();
670
- $beezupMageOrder = new BeezupMageOrders($orderId);
671
- $beezupMageOrder->setData($addressData);
672
- $beezupMageOrder->updateAdresses();
673
- }
674
-
675
- public function updateAddresses($shippingData, $address) {
676
- if($shippingData['firstname'] !==$address['firstname']) {
677
- $address->setFirstname($shippingData['firstname']);
678
- }
679
- if($shippingData['lastname'] !==$address['lastname']) {
680
- $address->setLastname($shippingData['lastname']);
681
- }
682
- if($shippingData['street'] !==$address['street']) {
683
- $address->setStreet($shippingData['street']);
684
- }
685
- if($shippingData['city'] !==$address['city']) {
686
- $address->setCity($shippingData['city']);
687
- }
688
- if($shippingData['postcode'] !==$address['postcode']) {
689
- $address->setPostcode($shippingData['postcode']);
690
- }
691
- if($shippingData['telephone'] !==$address['telephone']) {
692
- $address->setTelephone($shippingData['telephone']);
693
- }
694
- $address->save();
695
-
696
-
697
- }
698
-
699
-
700
- public function loadMageOrder() {
701
- $Mageorder = Mage::getModel('sales/order')->loadByIncrementId($this->orderid);
702
- if ($Mageorder->getId()) {
703
- return $Mageorder;
704
- } else {
705
- //we get order from marketplace orderid
706
- $orderInc = $this->checkMarketOrderExists($this->orderid);
707
- if($orderInc) {
708
- // if exists
709
- $Mageorder = Mage::getModel('sales/order')->loadByIncrementId($orderInc);
710
- if ($Mageorder->getId()) {
711
- return $Mageorder;
712
- }
713
- }
714
- }
715
- return false;
716
- }
717
-
718
-
719
- private function debugLog($message) {
720
-
721
- if($this->orderid !== "") {
722
- $message = $this->orderid." | ".$message;
723
- }
724
- $this->log->LogInfo($message);
725
-
726
- $this->log2->LogInfo($message);
727
- }
728
-
729
- public function prescanOrder(BeezupOMOrderResult $order) {
730
- $retorno = array();
731
- $orderItems = $order->getOrderItems();
732
- foreach ($orderItems as $item)
733
- {
734
-
735
- if ($item->getOrderItemOrderItemType () !== 'Product')
736
- {
737
- // continue;
738
- }
739
- $beezup_store = $item->getOrderItemBeezUPStoreId(); //beezup storeid
740
- $mage_storeid = $this->checkOrderStore($beezup_store); //magento storeid
741
- $marketplace_orderid = $item->getOrderItemMarketPlaceProductId();
742
- if(!$mage_storeid) {
743
-
744
- if(strpos($marketplace_orderid,'INTERETBCA') !== false || strpos($marketplace_orderid,'interetbca') !== false) { }
745
- else {
746
- $this->log->LogError($this->orderid." | No mapping for store ".$beezup_store);
747
- $this->log2->LogError($this->orderid." | No mapping for store ".$beezup_store);
748
- return false;
749
- }
750
-
751
- }
752
- // $retorno['store'] = 1;
753
-
754
- $product_ImportedMerchantId = $item->getOrderItemMerchantImportedProductId();
755
- $product_MerchantId = $item->getOrderItemMerchantProductId();
756
-
757
- $product_quantity = $item->getOrderItemQuantity();
758
- $product_price = $item->getOrderItemItemPrice();
759
- $product_title = $item->getOrderItemTitle();
760
- $product_image = $item->getOrderItemImageUrl();
761
- if(strpos($marketplace_orderid,'INTERETBCA') !== false || strpos($marketplace_orderid,'interetbca') !== false) {
762
- $retorno['discounts']= $item->getOrderItemTotalPrice();
763
- } else {
764
- $retorno['store'] = $mage_storeid;
765
- $this->debugLog("Store Matching succesful, Beezup Store: ".$beezup_store." , Magento Store Id: ".$mage_storeid);
766
- $product = $this->getMageProduct($product_ImportedMerchantId , $product_MerchantId , $beezup_store );
767
- if($product) {
768
- $mage_productId = $product->getId();
769
- $stocklevel = (int)Mage::getModel('cataloginventory/stock_item')
770
- ->loadByProduct($product)->getQty();
771
-
772
- $retorno['products'][] = array("id" => $mage_productId, "qty" => $product_quantity, "price" => $product_price, "curr_stock" => $stocklevel);
773
- //producto existe
774
- } else {
775
- //vendria if de si activada opcion de crear producto creamos
776
- if(!$this->debug) {
777
- return false;
778
- }
779
- $product_data = array(
780
- "sku" => $product_ImportedMerchantId,
781
- "sku2" => $product_MerchantId,
782
- "qty" => $product_quantity,
783
- "price" => $product_price,
784
- "title" => $product_title,
785
- "image" => $product_image,
786
- "storeId" => $mage_storeid
787
- );
788
- $product = $this->createProduct($product_data);
789
- if(!$product) {
790
- return false;
791
- }
792
- $stocklevel = (int)Mage::getModel('cataloginventory/stock_item')
793
- ->loadByProduct($product)->getQty();
794
- $mage_productId = $product->getId();
795
- $retorno['products'][] = array("id" => $mage_productId, "qty" => $product_quantity, "price" => $product_price, "curr_stock" => $stocklevel);
796
- }
797
- }
798
- }
799
-
800
- return $retorno;
801
- }
802
-
803
-
804
-
805
- public function matchProductAttributes($importedId, $storeId) {
806
- $product = null;
807
- $helper = Mage::helper('beezup');
808
- $attributes = $helper->getConfig('beezup/marketplace/attributes');
809
- $attributes = unserialize ($attributes);
810
-
811
- foreach($attributes['attributes'][$storeId ] as $attribute) {
812
- $att = explode("|", $attribute);
813
- if($storeId == $att[1]) {
814
-
815
- $product=Mage::getModel('catalog/product')->loadByAttribute($att[0],$importedId);
816
- if($product) {
817
- break;
818
- }
819
- }
820
- }
821
-
822
- return $product;
823
- }
824
-
825
-
826
-
827
- public function getMageProduct($importedId, $merchantId, $storeId){
828
- try {
829
- $product=Mage::getModel('catalog/product')->load($importedId);
830
- if (!$product->getId() || $product->getId() !== $importedId ){
831
- $product = $this->matchProductAttributes($importedId, $storeId);
832
- if($product == null || !is_object($product)) {
833
- $product=Mage::getModel('catalog/product')->load($merchantId);
834
- if(!$product->getId() || $product->getId() !== $merchantId ) {
835
- $product = $this->matchProductAttributes($merchantId, $storeId);
836
-
837
- }
838
- }
839
- }
840
-
841
- if(is_object($product)) {
842
- if($product->getId()) {
843
- $this->debugLog("Product Matching succesful, Beezup Imported Id: ".$importedId." , Magento Product Id: ".$product->getId());
844
- return $product;
845
- }}
846
- $this->log->LogError($this->orderid. "| No Product Matching, Product ".$importedId." could not be found");
847
- $this->log2->LogError($this->orderid. "| No Product Matching, Product ".$importedId." could not be found");
848
- return false;
849
- }catch(Exception $e){
850
- $this->log->LogError($this->orderid. "| Product ".$importedId." could not be found, error: ".$e->getMessage());
851
- $this->log2->LogError($this->orderid. "| Product ".$importedId." could not be found, error: ".$e->getMessage());
852
- return false;
853
- //error no se pudo crear la orden
854
-
855
- }
856
- }
857
-
858
-
859
- public function checkOrderStore($storeId ) {
860
- $helper = Mage::helper('beezup');
861
- $stores = $helper->getConfig('beezup/marketplace/stores');
862
- $stores = unserialize ($stores);
863
- foreach($stores as $store) {
864
- if(isset($store[$storeId]) && $store[$storeId] > 0) {
865
- return $store[$storeId];
866
- }
867
- }
868
- return false;
869
- }
870
-
871
-
872
-
873
- /**
874
- * @return BeezupOMOrderService
875
- */
876
- public function getOrderService(){
877
- if ($this->oOrderService === null){
878
- $this->oOrderService = $this->createOrderService();
879
- // enchufamos debug mode, esta activado? false true $this->oOrderService->setDebugMode(false);
880
- }
881
- return $this->oOrderService;
882
- }
883
-
884
- /**
885
- * @return BeezupOMOrderService
886
- */
887
- protected function createOrderService(){
888
-
889
- return new BeezupOMOrderService($this->createRepository() );
890
- }
891
-
892
- protected function createRepository() {
893
- if ($this->repository == null) {
894
- $this->repository = new BeezupRepository();
895
- }
896
- return $this->repository;
897
-
898
- }
899
-
900
-
901
-
902
-
903
- private function createCustomer($customer_email , $data) {
904
- $password = $this->orderid;
905
- $this->debugLog("Creating new Customer");
906
- $customer = Mage::getModel('customer/customer');
907
- $customer->setWebsiteId(Mage::app()->getWebsite()->getId());
908
- $customer->loadByEmail($customer_email);
909
- if(!$customer->getId()) {
910
- $customer->setEmail($customer_email);
911
- $customer->setFirstname($data['firstname']);
912
- $customer->setLastname($data['lastname']);
913
- $customer->setPassword($password);
914
- try {
915
- $customer->save();
916
- $customer->setConfirmation(null);
917
- $customer->save();
918
- $this->debugLog("Customer created succesfully");
919
- return $customer;
920
- //Make a "login" of new customer
921
- // Mage::getSingleton('customer/session')->loginById($customer->getId());
922
- }
923
-
924
- catch (Exception $ex) {
925
- //Zend_Debug::dump($ex->getMessage());
926
- //GUARDAR ERROR CREACION USUARIO
927
- $this->log2->LogError($this->orderid. " | Customer importation failed: ".$ex->getMessage());
928
- return false;
929
- }
930
-
931
- } else {
932
- $this->debugLog("Creating already exists, returning customer object");
933
- return $customer;
934
- }
935
- }
936
-
937
-
938
-
939
- public function addOrder($data, $oLink, $stop = false) {
940
-
941
-
942
- try {
943
- // BUG OCI du nom vide sur les commandes CDISOUNT... et Amazon en Disable...
944
- $this->debugLog('status de la commande->'.$data['order_status']);
945
- $this->debugLog('Nom vide->'.$data['shipping_lastname']);
946
- if ($data['shipping_lastname']=='' && $data['order_status'] != 'Canceled'){
947
-
948
- Mage::getConfig()
949
- ->saveConfig('carriers/flatrate/active', 0)
950
- ->cleanCache();
951
- Mage::app()->reinitStores();
952
-
953
- $configModel = Mage::getModel('core/config');
954
- $configModel->saveConfig('beezup/marketplace/sync_status',0);
955
-
956
- $this->debugLog('status de la commande->'.$data['order_status']);
957
- $this->debugLog('status de la commande->'.$data['order_status']);
958
- die("Nom Vide on attends que le nom arrive...");
959
-
960
- }
961
-
962
- $helper = Mage::helper('beezup');
963
- $addStock = $helper->getConfig('beezup/marketplace/available_products');
964
- $baseCurrencyCode = Mage::app()->getStore()->getBaseCurrencyCode();
965
- $quote = Mage::getModel('sales/quote')
966
- ->setStoreId($data['storeid']);
967
-
968
- $this->debugLog("## test quote storeid ##".$data['storeid']);
969
-
970
- $quote->setCustomerEmail($data['order_customer_email']);
971
-
972
- $this->debugLog("## test quote order_customer_email ##".$data['order_customer_email']);
973
-
974
-
975
- $currency = Mage::getModel('directory/currency')->load($data['order_currency']);
976
- $quote->setForcedCurrency($currency);
977
-
978
- $this->debugLog("## test quote currency ##".$currency);
979
-
980
- $blnCreate = true;
981
- $total_new_price = 0;
982
-
983
- foreach($data['products'] as $prod) {
984
-
985
- if($prod['qty']==0) {
986
- $blnCreate = false;
987
- break;
988
- }
989
- $prod_totality_price = $prod['price']*$prod['qty'];
990
- $total_new_price = $total_new_price + $prod_totality_price;
991
- $product = Mage::getModel('catalog/product')->load($prod['id']);
992
- $buyInfo = array(
993
- 'qty' => $prod['qty'],
994
- );
995
-
996
- $this->debugLog("Adding ".$prod['qty']." product/s with id ".$product->getId()." to order, with Beezup Price: ".$prod['price']);
997
- //echo "Product ".$product->getId()."<br><br>";
998
- //para no perder stock:
999
- //Mage::getModel('cataloginventory/stock')->backItemQty($productId,$new_qty);
1000
-
1001
-
1002
- if($addStock == 1) {
1003
- $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product);
1004
-
1005
- if ($stock->getQty() < $prod['qty'] && $product->getStockItem()->getMaxSaleQty() >= $prod['qty']) {
1006
- $this->debugLog("Product ".$product->getId()." Stock = 0, Updating to ".$prod['qty']." to generate Order");
1007
- // Mage::getModel('cataloginventory/stock')->backItemQty($product->getId(),$prod['qty']);
1008
- //$this->_updateStocks(array("id_product" => $product->getId(), "qty" => $prod['qty']));
1009
-
1010
- //BUG OCI s'emmele les pédales dans le tiers price avec la methode en dessous...->
1011
- $stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product);
1012
- $stockItem->setData('is_in_stock', 1);
1013
- $stockItem->setData('qty', $prod['qty']);
1014
- $stockItem->setData('manage_stock', 1);
1015
- $stockItem->setData('use_config_notify_stock_qty', 1);
1016
- $stockItem->save();
1017
- $product->save();
1018
-
1019
- // $product->setStockData(
1020
- // array(
1021
- // 'is_in_stock' => 1,
1022
- // 'qty' => $prod['qty'],
1023
- // 'manage_stock' => 1,
1024
- // 'use_config_notify_stock_qty' => 1
1025
- // )
1026
- // );
1027
-
1028
-
1029
- //$product->save();
1030
-
1031
- $this->debugLog("APRES TRAITEMENT 2 ->".$stock->getQty());
1032
- $product = Mage::getModel('catalog/product')->load($product->getId());
1033
-
1034
- }
1035
- }
1036
- //fin para no perder stock
1037
-
1038
- /*
1039
- $tax_class = $product->getTaxClassId();
1040
- $product->setTaxClassId(0);
1041
- $product->getResource()->saveAttribute($product, 'tax_class_id'); */
1042
- $price = $prod['price'];
1043
-
1044
- $quote_item = Mage::getModel('beezup/quote_item');
1045
- $quote_item
1046
- ->setProduct($product)
1047
- ->setPrice((float) $price )
1048
- ->setCustomPrice((float)$price )
1049
- ->setOriginalCustomPrice((float) $price )
1050
- ->setQuote($quote)
1051
- ->setQty((integer) $prod['qty'])
1052
- ->setBeezupPrice((float) $price );
1053
-
1054
- $this->debugLog("## test quote price ##".$price);
1055
- $this->debugLog("## test quote qty ##".$prod['qty']);
1056
-
1057
-
1058
- $quote->addItem($quote_item);
1059
-
1060
- //$quote->addProduct($product, new Varien_Object($buyInfo))->setOriginalCustomPrice($price)->setCustomPrice($price);
1061
-
1062
- /*
1063
- $product->setTaxClassId($tax_class);
1064
-
1065
- $product->getResource()->saveAttribute($product, 'tax_class_id');
1066
- */
1067
- }
1068
-
1069
- if($blnCreate) {
1070
- $addressData = array(
1071
- 'firstname' => ($data['order_customer']) ? $data['order_customer'] : "empty",
1072
- 'lastname' => ($data['order_lastname']) ? $data['order_lastname'] : "empty",
1073
- 'street' => ($data['order_address']) ? $data['order_address'] : "empty",
1074
- 'city' => ($data['order_city']) ? $data['order_city'] : "empty",
1075
- 'postcode' => ($data['order_postalCode']) ? $data['order_postalCode'] : "empty",
1076
- 'telephone' => ($data['order_customer_phone']) ? $data['order_customer_phone'] : "empty",
1077
- 'country_id' => ($data['order_country_iso']) ? $data['order_country_iso'] : "empty",
1078
- 'company' => ($data['order_company']) ? $data['order_company'] : "",
1079
- 'region_id' => ($data['order_region ']) ? substr($data['order_region '], 0,2) : "EM"// id from directory_country_region table
1080
- );
1081
-
1082
- $this->debugLog("## test quote addressData : ");
1083
- foreach ($addressData as $key => $value){
1084
- $this->debugLog($key . " : " . $value);
1085
- }
1086
-
1087
- $shippingData = array(
1088
- 'firstname' => ($data['shipping_name']) ? $data['shipping_name'] : "empty",
1089
- 'lastname' => ($data['shipping_lastname']) ? $data['shipping_lastname'] : $data['shipping_name'],
1090
- 'street' => ($data['shipping_address']) ? $data['shipping_address'] : "empty",
1091
- 'city' => ($data['shipping_city']) ? $data['shipping_city'] : "empty",
1092
- 'postcode' => ($data['shipping_postalCode']) ? $data['shipping_postalCode'] : "empty",
1093
- 'telephone' => ($data['shipping_phone']) ? $data['shipping_phone'] : "empty",
1094
- 'country_id' => ($data['shipping_country_iso']) ? $data['shipping_country_iso'] : "empty",
1095
- 'shipping_company' => ($data['shipping_company']) ? $data['shipping_company'] : "",
1096
- // il faudra penser a mettre une condtionnel seulement pour monechelle...
1097
- //'socolissimo_relay_id' => ($data['shipping_company']) ? $data['shipping_company'] : "",
1098
- 'region_id' => ($data['shipping_region']) ? substr($data['shipping_region'], 0, 2) : "EM" // id from directory_country_region table
1099
- );
1100
-
1101
- $this->debugLog("## test quote shippingData : ");
1102
- foreach ($shippingData as $key => $value){
1103
- $this->debugLog($key . " : " . $value);
1104
- }
1105
-
1106
- if($this->blnCreateCustomer) {
1107
-
1108
- $mage_customer = $this->createCustomer($data['order_customer_email'], $addressData);
1109
- $quote->assignCustomer($mage_customer);
1110
- $this->debugLog("## test quote order_customer_email ##".$data['order_customer_email']);
1111
- }
1112
-
1113
-
1114
- $payment_method = $helper->getConfig('beezup/marketplace/payment_method');
1115
- $billingAddress = $quote->getBillingAddress()->addData($addressData);
1116
- $shippingAddress = $quote->getShippingAddress()->addData($shippingData);
1117
- $shipping_cost = (float) $data['order_shippingPrice'];
1118
- if($data['order_shippingPrice'] == 0) {
1119
- $shipping_cost = 20000;
1120
- }
1121
- $total_new_price = $total_new_price + $data['order_shippingPrice'] ;
1122
- Mage::unregister('shipping_cost');
1123
- Mage::register('shipping_cost', $shipping_cost);
1124
- $this->debugLog("Adding Order Shipping Cost: ". $data['order_shippingPrice']);
1125
-
1126
- $shippingAddress->setCollectShippingRates(true)->collectShippingRates()
1127
- ->setShippingMethod('flatrate_flatrate')
1128
- ->setPaymentMethod($payment_method);
1129
-
1130
- //$shippingAddress->addTotal(array("code" => "specialfee", "title" => "Special Fee", "value" => 20));
1131
- $quote->getPayment()->importData(array('method' => $payment_method));
1132
-
1133
- $this->debugLog("## test quote payment_method ##".$payment_method);
1134
-
1135
- $quote->collectTotals()->save();
1136
-
1137
- $service = Mage::getModel('sales/service_quote', $quote);
1138
- //$this->debugLog("## test flatrate2 ##".var_dump($quote)); // test commande qui s'importe pas -> quote mal formaté ?
1139
- $service->submitAll();
1140
-
1141
- $order = $service->getOrder();
1142
-
1143
- $quoteId = $order->getQuoteId();
1144
- //$this->setStatus($data['order_status'], $order);
1145
-
1146
- $orderid = $order->getId();
1147
-
1148
- $resource = Mage::getSingleton('core/resource');
1149
- $writeConnection = $resource->getConnection('core_write');
1150
- $table = $resource->getTableName('sales/order_grid');
1151
- $this->debugLog("Adding Beezup Marketplace Information to Order");
1152
- $marketplace = $data['marketplace'];
1153
- $marketplace_business_code = ucfirst(strtolower($data['marketplace_business_code']));
1154
- $beezup_name = $data['order_customer'];
1155
- $market_order_id =$this->orderid;
1156
- $beezup_order_id = $oLink->getBeezupOrderUUID();
1157
- $beezup_status = $data['order_status'];
1158
- $beezup_last_modification_date = $oLink->getOrderLastModificationUtcDate();
1159
- $beezup_last_modification_date = $beezup_last_modification_date->date;
1160
- $beezup_marketplace_status = $oLink->getOrderStatusMarketPlaceStatus();
1161
- $beezup_purchase_date = $oLink->getOrderPurchaseUtcDate();
1162
- $beezup_purchase_date = $beezup_purchase_date->date;
1163
- $beezup_marketplace_last_modification_date = $oLink->getOrderMarketPlaceLastModificationUtcDate();
1164
- $beezup_marketplace_last_modification_date = $beezup_marketplace_last_modification_date->date;
1165
- /* $date = new DateTime($beezup_marketplace_last_modification_date);
1166
- $beezup_marketplace_last_modification_date = $date->format('d-m-Y H:i:s'). "(UTC Time)";
1167
- */
1168
-
1169
- $beezup_total_paid = $oLink->getOrderTotalPrice()." ".$data['order_currency'];
1170
- $beezup_account_id = $oLink->getAccountId();
1171
- $beezup_comission = $oLink->getOrderTotalCommission()." ".$data['order_currency'];
1172
- $tot_comm = $oLink->getOrderTotalCommission();
1173
- if(empty($tot_comm ) || $tot_comm == 0) {
1174
- $beezup_comission = 0;
1175
- }
1176
- $query = "UPDATE {$table} SET beezup_marketplace = '{$marketplace}', beezup_name = '{$beezup_account_id}', beezup_order = 1, beezup_market_order_id = '{$market_order_id}',
1177
- beezup_order_id = '{$beezup_order_id}', beezup_status = '{$beezup_status}', beezup_last_modification_date = '{$beezup_last_modification_date}',
1178
- beezup_marketplace_status = '{$beezup_marketplace_status}', beezup_purchase_date = '{$beezup_purchase_date}', beezup_marketplace_last_modification_date = '{$beezup_marketplace_last_modification_date}',
1179
- beezup_total_paid = '{$beezup_total_paid}', beezup_etag = '{$data['etag']}' , beezup_comission = '{$beezup_comission}', beezup_marketplace_business_code = '{$marketplace_business_code}'
1180
- WHERE entity_id = ". (int)$orderid;
1181
- $writeConnection->query($query);
1182
- $disc_price = 0;
1183
- if(!empty($data['discounts']) && $data['discounts'] >0) {
1184
-
1185
-
1186
- $disc_price = round($data['discounts'],2);
1187
- $total_new_price = $total_new_price+$disc_price;
1188
- $table_address = $resource->getTableName("sales/quote_address");
1189
-
1190
- $query = "update {$table_address} set beezup_fee = '{$disc_price}' where quote_id = '{$quoteId}' and address_type = 'shipping'";
1191
- $writeConnection->query($query);
1192
- $this->debugLog("Adding CDISCOUNT products with total price: ".$disc_price);
1193
- }
1194
-
1195
- //if order id exists and has been created
1196
- if ($orderid)
1197
- {
1198
- //we send order id to beezup
1199
- $this->debugLog("Sending Magento Order Id to Beezup, Magento Order Id: ".$orderid);
1200
- $oResult = new BeezupOMSetOrderIdValues ();
1201
- $oResult->setOrderMerchantOrderId ( $orderid )->setOrderMerchantECommerceSoftwareName ( 'Magento' )->setOrderMerchantECommerceSoftwareVersion ( Mage::getVersion() );
1202
- $sendRequest = $this->getOrderService()->getClientProxy()->setOrderMerchantIdByLink($oLink->getLinkByRel('setMerchantOrderId'), $oResult);
1203
- }
1204
-
1205
- $grand_total = $order->getGrandTotal();
1206
- $beezup_price = $oLink->getOrderTotalPrice() - $disc_price;
1207
- if($grand_total != (float) $beezup_price && $beezup_price > 0) {
1208
- $order->setGrandTotal((float) $beezup_price);
1209
- $order->setBaseGrandTotal((float) $beezup_price);
1210
- $diff = (((float) $beezup_price) - $grand_total);
1211
-
1212
- $order->setTaxAmount($order->getTaxAmount() + $diff);
1213
- $order->save();
1214
- }elseif($grand_total != (float)$beezup_price && $beezup_price < 1) {
1215
-
1216
- $order->setGrandTotal((float) $total_new_price);
1217
- $order->setBaseGrandTotal((float) $total_new_price);
1218
- $diff = (((float) $total_new_price) - $grand_total);
1219
-
1220
- $order->setTaxAmount($order->getTaxAmount() + $diff);
1221
- $order->save();
1222
- }
1223
-
1224
- if($order->getShippingInclTax() != $data['order_shippingPrice']) {
1225
- $shipping_cost = (float)$data['order_shippingPrice'];
1226
- $diff_shipping = ($shipping_cost - $order->getShippingInclTax());
1227
- //$order->setShippingAmount($order->getShippingAmount() + $diff_shipping);
1228
- //$order->setBaseShippingAmount($order->getShippingAmount());
1229
- $order->setShippingInclTax($shipping_cost);
1230
- $order->setBaseShippingInclTax($order->getShippingInclTax());
1231
- /*
1232
- $order->setSubtotalInclTax($order->getSubtotalInclTax() + $diff_shipping);
1233
- $order->setBaseSubtotalInclTax($order->getSubtotalInclTax());
1234
- $order->setSubtotal($order->getSubtotal() + $diff_shipping);
1235
- $order->setBaseSubtotal($order->getSubtotal());
1236
- */
1237
- $order->save();
1238
- }
1239
- $products = Mage::getResourceModel('sales/order_item_collection')
1240
- ->setOrderFilter($orderid);
1241
- foreach($products as $product) {
1242
- $product->setBaseOriginalPrice($product->getOriginalPrice());
1243
- $product->setBaseTaxAmount($product->getTaxAmount());
1244
- $product->setBaseTaxInvoiced($product->getTaxAmount());
1245
- $product->setBasePriceInclTax($product->getPriceInclTax());
1246
- $product->setBaseRowTotalInclTax($product->getRowTotalInclTax());
1247
- $product->save();
1248
- }
1249
- $order->setBaseTaxAmount($order->getTaxAmount());
1250
- $order->setBaseTaxInvoiced($order->getTaxAmount());
1251
- $order->setBaseTotalInvoiced($order->getTotalPaid());
1252
- $order->setBaseTotalPaid($order->getTotalPaid());
1253
- $order->setBaseGrandTotal($order->getTotalPaid());
1254
- $order->setBaseSubtotalInclTax($order->getSubtotalInclTax());
1255
- $order->save();
1256
-
1257
- $this->setStatus($data['order_status'], $order);
1258
- $this->mage_order_id = $orderid;
1259
-
1260
- // update table sale flat order OCI
1261
-
1262
- $this->debugLog("Quelle Livraison: ->".$data['shipping_method_BEEZUP']);
1263
- if ($data['shipping_method_BEEZUP']=='Livraison Colissimo'|| $data['shipping_method_BEEZUP']=='Standard' || $data['shipping_method_BEEZUP']=='Expedited' || $data['shipping_method_BEEZUP']=='TRK' || $data['shipping_method_BEEZUP']=='STD' || $data['shipping_method_BEEZUP']=='REG' || $data['shipping_method_BEEZUP']=='Transporteur' || $data['shipping_method_BEEZUP']=='FR_Autre' || $data['shipping_method_BEEZUP']=='Colissimo Domicile' || $data['shipping_method_BEEZUP']=='A' ) {
1264
- //update flat_order
1265
- $table_update="sales_flat_order";
1266
- $desc="La Poste : Colissimo - Livraison à Domicile";
1267
- $methode="socolissimo_3";
1268
- $query = "UPDATE {$table_update} SET shipping_description = '{$desc}', shipping_method = '{$methode}' WHERE entity_id = ". (int)$orderid;
1269
- $writeConnection->query($query);
1270
-
1271
- //update flat_order_address
1272
- $table_update2="sales_flat_order_address";
1273
- $socolissimo_method_id = '3';
1274
- $socolissimo_method_name = 'Livraison à Domicile';
1275
- $socolissimo_delivery_mode = 'DOM';
1276
- $socolissimo_code = 'home_without_signature';
1277
- $query2 = "UPDATE {$table_update2} SET socolissimo_method_id = '{$socolissimo_method_id}', socolissimo_method_name = '{$socolissimo_method_name}', socolissimo_delivery_mode = '{$socolissimo_delivery_mode}', socolissimo_code = '{$socolissimo_code}' WHERE address_type ='shipping' AND parent_id = ". (int)$orderid ;
1278
- $writeConnection->query($query2);
1279
- //$this->debugLog("changement methode: ".$query);
1280
- }
1281
- else if ($data['shipping_method_BEEZUP']=='Std ES Dom_3' || $data['shipping_method_BEEZUP']=='Exp IT Dom_1' || $data['shipping_method_BEEZUP']=='Std UK Dom_5' || $data['shipping_method_BEEZUP']=='Std IT Dom_4' || $data['shipping_method_BEEZUP']=='UK Second') {
1282
- $table_update="sales_flat_order";
1283
- $desc="Chronopost Livraison express partout dans le monde - Chronopost Livraison partout dans le monde";
1284
- $methode="chronoexpress_chronoexpress";
1285
- $query = "UPDATE {$table_update} SET shipping_description = '{$desc}', shipping_method = '{$methode}' WHERE entity_id = ". (int)$orderid;
1286
- $writeConnection->query($query);
1287
- }
1288
- else if ($data['shipping_method_BEEZUP']=='Colissimo Relais') { // ajout antonin pour prise en compte pt relais manomano
1289
-
1290
- $table_update="sales_flat_order";
1291
- $desc="La Poste Colissimo - Livraison en Point de retrait";
1292
- $methode="socolissimo_4";
1293
- $query = "UPDATE {$table_update} SET shipping_description = '{$desc}', shipping_method = '{$methode}' WHERE entity_id = ". (int)$orderid;
1294
- $writeConnection->query($query);
1295
-
1296
- $table_update2="sales_flat_order_address";
1297
- $socolissimo_method_id = '4';
1298
- $socolissimo_method_name = 'Livraison en Point de retrait';
1299
- $socolissimo_delivery_mode = 'A2P';
1300
- $socolissimo_relay_id = substr($data['shipping_company'], 10);
1301
- $socolissimo_code = 'pickup';
1302
- $query2 = "UPDATE {$table_update2} SET socolissimo_method_id = '{$socolissimo_method_id}', socolissimo_method_name = '{$socolissimo_method_name}', company = '', socolissimo_relay_id = '{$socolissimo_relay_id}', socolissimo_delivery_mode = '{$socolissimo_delivery_mode}', socolissimo_code = '{$socolissimo_code}' WHERE address_type ='shipping' AND parent_id = ". (int)$orderid ;
1303
- $writeConnection->query($query2);
1304
-
1305
- }
1306
-
1307
- $this->debugLog("Order imported succesfully, Magento Order Id: ".$orderid);
1308
-
1309
- } else {
1310
- //product stock = 0 we dont create order
1311
- $this->log->LogError($this->orderid. "| Order ".$data['market_place_order_id']." could not be imported, error: Stock from Beezup product = 0 ");
1312
- $this->log2->LogError($this->orderid. "| Order ".$data['market_place_order_id']." could not be imported, error: Stock from Beezup product = 0 ");
1313
- }
1314
- }catch(Exception $e){
1315
-
1316
-
1317
- if($stop) {
1318
- $this->log->LogError($this->orderid. "| Order ".$data['market_place_order_id']." could not be imported, error: ".$e->getMessage());
1319
- $this->log2->LogError($this->orderid. "| Order ".$data['market_place_order_id']." could not be imported, error: ".$e->getMessage());
1320
- $this->restoreStock($data);
1321
- } else {
1322
- $this->debugLog("Order Import failed, Trying to import Order Again ->".$e->getMessage());
1323
- $this->addOrder($data, $oLink, true);
1324
-
1325
- }
1326
- //error no se pudo crear la orden
1327
-
1328
- }
1329
-
1330
-
1331
-
1332
- }
1333
-
1334
-
1335
-
1336
- public function restoreStock($data) {
1337
-
1338
- try {
1339
- foreach($data['products'] as $prod) {
1340
- $product = Mage::getModel('catalog/product')->load($prod['id']);
1341
- $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product);
1342
- if ($stock->getQty() != $prod['curr_stock'] ) {
1343
- $this->debugLog("Restoring Stock from Product ".$product->getId()." to: ".$prod['curr_stock'] ." due to Order Fail");
1344
- $stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product);
1345
- $stockItem->setData('is_in_stock', 0);
1346
- $stockItem->setData('qty', $prod['curr_stock']);
1347
- $stockItem->save();
1348
- $product->save();
1349
- }
1350
-
1351
- }
1352
- } catch(Exception $e){
1353
- $this->log->LogError($this->orderid. "| Failed Restoring Product Stock: ".$e->getMessage());
1354
- $this->log2->LogError($this->orderid. "| Failed Restoring Product Stock: ".$e->getMessage());
1355
- }
1356
-
1357
- }
1358
-
1359
-
1360
-
1361
- private function createProduct($data) {
1362
-
1363
- $sku = $data['sku'];
1364
- if(empty($data['sku'])) {
1365
- $sku = $data['sku2'];
1366
- }
1367
-
1368
- Mage::app()->setCurrentStore($data['storeId']);
1369
- $product = Mage::getModel('catalog/product');
1370
- // if(!$product->getIdBySku('testsku61')):
1371
-
1372
- try{
1373
- $product
1374
- // ->setStoreId(1) //you can set data in store scope
1375
- ->setWebsiteIds(array($data['storeId'])) //website ID the product is assigned to, as an array
1376
- ->setAttributeSetId($product->getDefaultAttributeSetId()) //ID of a attribute set named 'default'
1377
- ->setTypeId('simple') //product type
1378
- ->setCreatedAt(strtotime('now')) //product creation time
1379
- ->setSku($sku ) //SKU
1380
- ->setWeight(0)
1381
- ->setName($data['title']) //product name
1382
- ->setStatus(1) //product status (1 - enabled, 2 - disabled)
1383
- ->setTaxClassId(4) //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
1384
- ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE ) //catalog and search visibility
1385
- ->setPrice($data['price']) //price in form 11.22
1386
- ->setMsrpEnabled(1) //enable MAP
1387
- ->setMsrpDisplayActualPriceType(1) //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
1388
- ->setMsrp(0) //Manufacturer's Suggested Retail Price
1389
- ->setMetaTitle('')
1390
- ->setMetaKeyword('')
1391
- ->setMetaDescription('')
1392
- ->setDescription($data['title'])
1393
- ->setShortDescription($data['title'])
1394
- // ->setMediaGallery (array('images'=>array (), 'values'=>array ())) //media gallery initialization
1395
- //->addImageToMediaGallery('media/catalog/product/1/0/10243-1.png', array('image','thumbnail','small_image'), false, false) //assigning image, thumb and small image to media gallery
1396
- ->setStockData(array(
1397
- 'use_config_manage_stock' => 0, //'Use config settings' checkbox
1398
- 'manage_stock'=>1, //manage stock
1399
- 'min_sale_qty'=>1, //Minimum Qty Allowed in Shopping Cart
1400
- 'max_sale_qty'=>2, //Maximum Qty Allowed in Shopping Cart
1401
- 'is_in_stock' => 1, //Stock Availability
1402
- 'qty' => 1 //qty
1403
- )
1404
- );
1405
- $product->save();
1406
- return $product;
1407
-
1408
- }catch(Exception $e){
1409
- //log exception
1410
- $this->log->LogError($this->orderid."| Product ".$sku." could not be created, error: ".$e->getMessage());
1411
- $this->log2->LogError($this->orderid."| Product ".$sku." could not be created, error: ".$e->getMessage());
1412
- return false;
1413
- }
1414
- }
1415
-
1416
-
1417
-
1418
- public function setStatus($status, $order) {
1419
- $helper = Mage::helper('beezup');
1420
- $retorno = "";
1421
- $blnCancel = false;
1422
- $blnHold = false;
1423
- switch($status) {
1424
- case "New" :
1425
- $this->debugLog("Setting Order Status to New");
1426
- $retorno = $helper->getConfig('beezup/marketplace/status_new');
1427
- break;
1428
- case "InProgress" :
1429
- $this->debugLog("Setting Order Status to InProgress");
1430
- $retorno = $helper->getConfig('beezup/marketplace/status_progress');
1431
- $this->payOrder($order);
1432
- break;
1433
- case "Aborted" :
1434
- $this->debugLog("Setting Order Status to Aborted");
1435
- $retorno = $helper->getConfig('beezup/marketplace/status_aborted');
1436
- $blnHold = true;
1437
-
1438
-
1439
- break;
1440
- case "Closed" :
1441
- $this->debugLog("Setting Order Status to Closed");
1442
- $blnCancel =true;
1443
- $retorno = $helper->getConfig('beezup/marketplace/status_closed');
1444
- $this->payOrder($order);
1445
- break;
1446
- case "Canceled" :
1447
- $this->debugLog("Setting Order Status to Cancelled");
1448
- $retorno = $helper->getConfig('beezup/marketplace/status_cancelled');
1449
-
1450
- break;
1451
- case "Shipped" :
1452
- $this->debugLog("Setting Order Status to Shipped");
1453
- $retorno = $helper->getConfig('beezup/marketplace/status_shipped');
1454
- $this->payOrder($order);
1455
- break;
1456
-
1457
- }
1458
- $order->setData('state',$retorno);
1459
- $order->setStatus($retorno);
1460
- $history = $order->addStatusHistoryComment('Order was set to '.$retorno.' by Beezup.', false);
1461
- $history->setIsCustomerNotified(false);
1462
- $order->save();
1463
- if($blnCancel) {
1464
- $order->cancel()->save();
1465
- }
1466
- if($blnHold) {
1467
- $order->hold()->save();
1468
- }
1469
-
1470
- return $retorno;
1471
-
1472
- }
1473
-
1474
-
1475
- public function getStatus($status1) {
1476
- $helper = Mage::helper('beezup');
1477
- $retorno = "";
1478
- $status = strtolower($status1);
1479
-
1480
- if($status == strtolower($helper->getConfig('beezup/marketplace/status_new') )) {
1481
- $retorno = "New";
1482
-
1483
- } elseif($status == strtolower($helper->getConfig('beezup/marketplace/status_progress') ) ){
1484
- $retorno = "InProgress";
1485
-
1486
-
1487
- }
1488
- elseif($status == strtolower($helper->getConfig('beezup/marketplace/status_aborted') )) {
1489
-
1490
- $retorno = "Aborted" ;
1491
- }
1492
- elseif($status == strtolower($helper->getConfig('beezup/marketplace/status_closed') )) {
1493
- $retorno = "Closed";
1494
-
1495
- }
1496
- elseif($status == strtolower($helper->getConfig('beezup/marketplace/status_cancelled')) ) {
1497
-
1498
- $retorno = "Canceled";
1499
- }
1500
- elseif($status == strtolower($helper->getConfig('beezup/marketplace/status_shipped') )) {
1501
-
1502
- $retorno = "Shipped";
1503
- }
1504
-
1505
-
1506
- return $retorno;
1507
-
1508
- }
1509
-
1510
-
1511
- public function checkMarketOrderExists($orderid) {
1512
- $resource = Mage::getSingleton('core/resource');
1513
- $readConnection = $resource->getConnection('core_read');
1514
- $table = $resource->getTableName('sales/order_grid');
1515
- $query = 'SELECT increment_id FROM ' . $table . ' WHERE beezup_order = 1 and beezup_market_order_id = \''
1516
- . $orderid . '\' LIMIT 1';
1517
- $order = $readConnection->fetchOne($query);
1518
- if($order && !empty($order) && $this->orderId !== "") {
1519
- return $order;
1520
- }
1521
- return false;
1522
-
1523
- }
1524
-
1525
- public function payOrder($order) {
1526
- try {
1527
- $this->debugLog("Generating Order Payment Invoice");
1528
- if($order->canInvoice()) {
1529
- $invoice = $order->prepareInvoice()
1530
- ->setTransactionId($order->getId())
1531
- ->addComment("Invoice created from Beezup.")
1532
- ->register()
1533
- ->pay();
1534
- $transaction_save = Mage::getModel('core/resource_transaction')
1535
- ->addObject($invoice)
1536
- ->addObject($invoice->getOrder());
1537
- $transaction_save->save();
1538
- $this->debugLog("Order Payment Invoice Generated Succesfully");
1539
- }
1540
- }
1541
- catch(Exception $e){
1542
- //log exception
1543
- $this->log->LogError($this->orderid."| Order Payment Invoice could not be generated, error: ".$e->getMessage());
1544
- $this->log2->LogError($this->orderid."| Order Payment Invoice could not be generated, error: ".$e->getMessage());
1545
- }
1546
- }
1547
-
1548
-
1549
-
1550
-
1551
-
1552
-
1553
- }
app/code/community/BeezUp/Block/Order_original.php DELETED
@@ -1,1382 +0,0 @@
1
- <?php
2
- require_once Mage::getModuleDir('', 'BeezUp') . DS . 'lib' . DS ."KLogger.php";
3
- require_once Mage::getModuleDir('', 'BeezUp') . DS . 'lib' . DS ."bootstrap.php";
4
- require_once Mage::getModuleDir('', 'BeezUp') . DS . 'lib' . DS ."BeezupRepository.php";
5
- require_once Mage::getModuleDir('', 'BeezUp') . DS . 'lib' . DS ."BeezupMageOrders.php";
6
-
7
- class Beezup_Block_Order extends Mage_core_block_text {
8
-
9
- protected $repository = null;
10
- protected $oOrderService;
11
- public $log = null;
12
- public $log2 = null;
13
- public $orderid = "";
14
- public $debug = false;
15
- public $blnCreateCustomer = false;
16
- private $account_id;
17
- private $marketplace_code;
18
- private $beezup_order_id;
19
- private $mage_order_id = false;
20
-
21
-
22
- private function makeDir() {
23
-
24
- if (file_exists(Mage::getBaseDir('base').'/beezup/tmp')) { return true;}
25
-
26
- if (!mkdir(Mage::getBaseDir('base').'/beezup/tmp', 0777, true))
27
- {
28
- echo "[ERROR] : Seems we can't create 'beezup' directory inside your root directory."."<br/>"
29
- ."You can try one of these solutions :"."<br/>"
30
- ."1 - Create by yourself the beezup/tmp inside your root directory with 777 permissions"."<br/>"
31
- ."2 - Change the permissions on your root directory (777)"."<br/>"
32
- ."3 - Change the 'cache delay' option to 'None' inside beezup plugin settings"."<br/>";
33
- return false;
34
- }
35
- return true;
36
-
37
- }
38
- public function createOrderFromLink($account_id, $marketplace_code, $beezup_order_id) {
39
- $this->makeDir();
40
- $logDir = Mage::getBaseDir('base').'/beezup/';
41
- if(file_exists($logDir."log2.txt")) {
42
- if(filesize($logDir."/log2.txt") >=3000000) {
43
- unlink($logDir."log2.txt");
44
- }
45
- }
46
- $sync_end_date = new DateTime ( 'now', new DateTimeZone ( 'UTC' ));
47
- $helper = Mage::helper('beezup');
48
- $sync_status = $helper->getConfig('beezup/marketplace/sync_status');
49
- $debug_mode = $helper->getConfig('beezup/marketplace/debug_mode');
50
- $create_customer = $helper->getConfig("beezup/marketplace/create_customers");
51
- if($create_customer == 0) {
52
- $this->blnCreateCustomer = true;
53
- }
54
-
55
- if($debug_mode==1) {
56
- $this->debug = true;
57
- }
58
- if($sync_status!==1) {
59
- $configModel = Mage::getModel('core/config');
60
- $configModel->saveConfig('beezup/marketplace/sync_status',1);
61
-
62
-
63
-
64
- unlink($logDir."log.txt");
65
- $this->log = new KLogger ( $logDir."log.txt" , KLogger::DEBUG );
66
- $this->log2 = new KLogger ( $logDir."log2.txt" , KLogger::DEBUG );
67
- $this->debugLog("Initializing OM Importation");
68
- $this->account_id = $account_id;
69
- $this->marketplace_code = $marketplace_code;
70
- $this->beezup_order_id = $beezup_order_id;
71
- $orderResponse = $this->getBeezupOrder();
72
- if($orderResponse) {
73
-
74
-
75
- $this->createOrder($orderResponse);
76
-
77
- $configModel->saveConfig('beezup/marketplace/sync_status',0);
78
- if($this->mage_order_id) {
79
- echo "<script>window.location='".Mage::helper('adminhtml')->getUrl("adminhtml/sales_order/view", array('order_id'=> $this->mage_order_id))."';</script>";
80
- }
81
- // die("Order Importation finalized");
82
-
83
- }
84
-
85
- }
86
- $configModel->saveConfig('beezup/marketplace/sync_status',0);
87
- //die("Error, Order data incorrect");
88
- echo $this->_showLog();
89
- }
90
-
91
- public function _showLog() {
92
- $logDir = Mage::getBaseDir('base').'/beezup/';
93
- // $log1 = file_get_contents();
94
- $ret = array();
95
- if (file_exists($logDir."/log.txt")) {
96
- $f = fopen($logDir."/log.txt", 'r');
97
-
98
- if ($f) {
99
- while (!feof($f)) {
100
- $ret[] = fgetcsv($f, 0, '|');
101
- }
102
- fclose($f);
103
- }
104
- }
105
- array_slice(array_reverse($ret), 1, 10);
106
-
107
- return $this->_getTable($ret);
108
-
109
- }
110
-
111
-
112
- public function _getTable($data) {
113
- $url = Mage::getBaseUrl( Mage_Core_Model_Store::URL_TYPE_WEB, true );
114
- $html = "<td></td><td></td><tr></tr></tbody></table>
115
-
116
- <div class='grid' style=' height: 600px;overflow-y: scroll;padding: 16px;border: 3px solid #e6e6e6;' id='marketPlaceLogBlock'>";
117
- $html .= '<p>'. Mage::helper('beezup')->__('For full logs see here:').' <a href="'.$url .'beezup/log/load" target="_blank">'.$url .'beezup/log/load</a></p>';
118
- $html .= "<table class='data' style='margin-top:0px;width:100%;'>";
119
- $html .= "<tr class='headings'>";
120
- $html .= '<th><span class="nobr">Time</span></th>';
121
- $html .= '<th><span class="nobr">Type</span></th>';
122
- $html .= '<th><span class="nobr">Order Id</span></th>';
123
- $html .= '<th><span class="nobr">Message</span></th>';
124
- $html .= "</tr>";
125
- $html .= "<tbody>";
126
- foreach($data as $d) {
127
- $background = " background: rgb(240, 184, 184)";
128
- if($d[1] == " INFO " ) {
129
- $background = " background: rgb(210, 227, 253)";
130
- }
131
- $orderId = (isset($d[3])) ? $d[2] : "";
132
- $message = (isset($d[3])) ? $d[3] : $d[2];
133
- $html .= "<tr class='even pointer' style='".$background."'>";
134
- $html .= "<td>".$d[0]."</td>";
135
- $html .= "<td>".$d[1]."</td>";
136
- $html .= "<td>".$orderId."</td>";
137
- $html .= "<td>".$message."</td>";
138
- $html .= "</tr>";
139
-
140
- }
141
-
142
- $html .= "<tbody>";
143
- $html .= '</table>';
144
- $html .= "</div>";
145
-
146
- return $html;
147
- }
148
-
149
-
150
-
151
- public function executeCron() {
152
-
153
- $this->makeDir();
154
-
155
- set_time_limit(0);
156
- $logDir = Mage::getBaseDir('base').'/beezup/';
157
- if(file_exists($logDir."log2.txt")) {
158
- if(filesize($logDir."/log2.txt") >=3000000) {
159
- unlink($logDir."log2.txt");
160
- }
161
- }
162
-
163
- $sync_end_date = new DateTime ( 'now', new DateTimeZone ( 'UTC' ));
164
- $helper = Mage::helper('beezup');
165
- $sync_status = $helper->getConfig('beezup/marketplace/sync_status');
166
- $debug_mode = $helper->getConfig('beezup/marketplace/debug_mode');
167
- $create_customer = $helper->getConfig("beezup/marketplace/create_customers");
168
- if($create_customer == 0) {
169
- $this->blnCreateCustomer = true;
170
- }
171
-
172
- if($debug_mode==1) {
173
- $this->debug = true;
174
- }
175
-
176
- if($sync_status!==1) {
177
- $configModel = Mage::getModel('core/config');
178
- $configModel->saveConfig('beezup/marketplace/sync_status',1);
179
-
180
-
181
-
182
- unlink($logDir."log.txt");
183
- $this->log = new KLogger ( $logDir."log.txt" , KLogger::DEBUG );
184
- $this->log2 = new KLogger ( $logDir."log2.txt" , KLogger::DEBUG );
185
- $this->debugLog("Initializing OM Importation");
186
-
187
-
188
- $this->getOrderList();
189
-
190
- $this->repository->updateLastSynchronizationDate( $sync_end_date);
191
- $this->orderid = "";
192
- $this->debugLog("OM Importation finalized succesfully");
193
- $configModel->saveConfig('beezup/marketplace/sync_status',0);
194
- echo "OM Importation finalized succesfully";
195
-
196
- } else {
197
-
198
- echo "Order Importation is already being executed";
199
- }
200
-
201
- }
202
-
203
-
204
- public function getLog() {
205
- $logDir = Mage::getBaseDir('base').'/beezup/';
206
- $log1 = file_get_contents($logDir."/log2.txt");
207
-
208
- echo "<pre>";
209
- print_r($log1);
210
- echo "</pre>";
211
-
212
- }
213
- public function getBeezupOrder() {
214
-
215
- $oOrderIdentifier = $this->getBeezupOrderId();
216
- $oBeezupOMOrderResponse = $this->getOrderService()->getOrder($oOrderIdentifier);
217
- if ($oBeezupOMOrderResponse && $oBeezupOMOrderResponse->getResult()){
218
- return $oBeezupOMOrderResponse;
219
- }
220
-
221
-
222
- return false;
223
- }
224
-
225
- public function getBeezupOrderId(){
226
- $oIdentifier = new BeezupOMOrderIdentifier();
227
- $oIdentifier
228
- ->setAccountId($this->account_id)
229
- ->setMarketplaceTechnicalCode($this->marketplace_code)
230
- ->setBeezupOrderUUID($this->beezup_order_id);
231
- return $oIdentifier;
232
- }
233
-
234
-
235
- public function createOrder($oBeezupOrderResponse) {
236
-
237
- $etag = $oBeezupOrderResponse->getETag();
238
- $final_order = $oBeezupOrderResponse->getResult();
239
-
240
- $orderid = $final_order->getOrderMarketPlaceOrderId();
241
- $this->orderid = $orderid;
242
- //customer Info
243
- $order_address = $final_order->getOrderBuyerAddressCity();
244
- $order_country = $final_order->getOrderBuyerAddressCountryName();
245
- $order_country_iso = $final_order->getOrderBuyerAddressCountryIsoCodeAlpha2();
246
- $order_address = $this->getBeezupBuyerAddress($final_order);
247
- $order_postalCode = $final_order->getOrderBuyerAddressPostalCode();
248
- $order_customer = $final_order->getOrderBuyerName();
249
- $order_customer_email = $final_order->getOrderBuyerEmail();
250
- $order_customer_phone = $final_order->getOrderBuyerPhone();
251
- $order_customer_mobile = $final_order->getOrderBuyerMobilePhone();
252
- $order_comment = $final_order->getOrderComment();
253
- $order_company = $final_order->getOrderBuyerCompanyName();
254
- $order_city = $final_order->getOrderBuyerAddressCity();
255
- $order_region = $final_order->getOrderBuyerStateOrRegion();
256
- $order_status = $final_order->getOrderStatusBeezUPOrderStatus();
257
- //shipping information
258
- $shipping_city = $final_order->getOrderShippingAddressCity();
259
- $shipping_country = $final_order->getOrderShippingAddressCountryName();
260
- $shipping_country_iso = $final_order->getOrderShippingAddressCountryIsoCodeAlpha2();
261
- $shipping_address = $this->getBeezupShippingAddress($final_order);
262
- $shipping_name = $final_order->getOrderShippingAddressName();
263
- $shipping_postalCode = $final_order->getOrderShippingAddressPostalCode();
264
- $shipping_email = $final_order->getOrderShippingEmail();
265
- $shipping_phone = $final_order->getOrderShippingPhone();
266
- $shipping_mobile = $final_order->getOrderShippingMobilePhone();
267
- $shipping_company = $final_order->getOrderShippingCompanyName();
268
- $shipping_region = $final_order->getOrderShippingAddressStateOrRegion();
269
- $order_currency_code = $final_order->getOrderCurrencyCode();
270
- //order Info
271
- $order_totalPrice = $final_order->getOrderTotalPrice();
272
- $order_shippingPrice = $final_order->getOrderShippingPrice();
273
-
274
- $name_parts = explode(" ", $order_customer);
275
- $order_first_name = array_shift( $name_parts);
276
- $order_last_name = implode(" ", $name_parts);
277
-
278
-
279
- $name_parts = explode(" ", $shipping_name);
280
- $shipping_first_name = array_shift( $name_parts);
281
- $shipping_last_name = implode(" ", $name_parts);
282
-
283
-
284
- //marketplace information
285