BeezUP_Module_feed_and_tracker - Version 4.6.7

Version Notes

New features :
> Fixed a specific case for PriceMinister orders

Download this release

Release Info

Developer BeezUP
Extension BeezUP_Module_feed_and_tracker
Version 4.6.7
Comparing to
See all releases


Code changes from version 4.6.6 to 4.6.7

app/code/community/BeezUp/Block/Omstatus.php CHANGED
@@ -1,181 +1,186 @@
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_Omstatus extends Mage_core_block_text {
8
- protected $repository = null;
9
- protected $oOrderService;
10
- public $log = null;
11
- public $log2 = null;
12
- public $orderid = "";
13
- public $debug = false;
14
- private $account_id;
15
- private $marketplace_code;
16
- private $beezup_order_id;
17
-
18
-
19
- public function getLoader() {
20
- $dir = Mage::getModuleDir("etc", "BeezUp");
21
- $dir = str_replace("etc", "img", $dir);
22
- header('Content-Type: image/jpeg');
23
- readfile($dir."/ajax-loader.gif");
24
-
25
- }
26
-
27
-
28
- public function getBeezupBuyerAddress($order) {
29
- $add1=$order->getOrderBuyerAddressLine1();
30
- $add2=$order->getOrderBuyerAddressLine2();
31
- $add3=$order->getOrderBuyerAddressLine3();
32
- $retorno = "";
33
- if(!empty($add1)) {
34
- $retorno = $order->getOrderBuyerAddressLine1();
35
- }
36
- if(!empty($add2)) {
37
- if(empty($add1)) {
38
- $retorno .= $order->getOrderBuyerAddressLine2();
39
- } else {
40
- $retorno .= " - ". $order->getOrderBuyerAddressLine2();
41
- }
42
- }
43
- if(!empty($add3)){
44
- if(empty($add1) && empty($add2)) {
45
- $retorno .= $order->getOrderBuyerAddressLine3();
46
- } else {
47
- $retorno .= " - ". $order->getOrderBuyerAddressLine3();
48
- }
49
- }
50
- return $retorno;
51
- }
52
-
53
-
54
- public function getBeezupShippingAddress($order) {
55
- $add1 = $order->getOrderShippingAddressLine1();
56
- $add2 = $order->getOrderShippingAddressLine2();
57
- $add3=$order->getOrderBuyerAddressLine3();
58
- $retorno = "";
59
- if(!empty($add1 )) {
60
- $retorno = $order->getOrderShippingAddressLine1();
61
- }
62
- if(!empty($add2)) {
63
- if(empty($add1)) {
64
- $retorno .= $order->getOrderShippingAddressLine2();
65
- } else {
66
- $retorno .= " - ". $order->getOrderShippingAddressLine2();
67
- }
68
- }
69
- if(!empty($add3)){
70
- if(empty($add1) && empty($add2)) {
71
- $retorno .= $order->getOrderShippingAddressLine3();
72
- } else {
73
- $retorno .= " - ". $order->getOrderShippingAddressLine3();
74
- }
75
- }
76
- return $retorno;
77
- }
78
-
79
80
- public function checkEtagExists($etag) {
81
- $resource = Mage::getSingleton('core/resource');
82
- $readConnection = $resource->getConnection('core_read');
83
- $table = $resource->getTableName('sales/order_grid');
84
- $query = 'SELECT increment_id FROM ' . $table . ' WHERE beezup_etag = \''
85
- . $etag . '\' LIMIT 1';
86
- $order = $readConnection->fetchOne($query);
87
- if($order && !empty($order)) {
88
- return true;
89
}
90
- return false;
91
-
92
}
93
94
- public function loadMageOrder() {
95
- $Mageorder = Mage::getModel('sales/order')->load($this->orderid);
96
- if ($Mageorder->getId()) {
97
- return $Mageorder;
98
- } else {
99
//we get order from marketplace orderid
100
- $orderInc = $this->checkMarketOrderExists($this->orderid);
101
- if($orderInc) {
102
// if exists
103
- $Mageorder = Mage::getModel('sales/order')->loadByIncrementId($orderInc);
104
- if ($Mageorder->getId()) {
105
- return $Mageorder;
106
- }
107
}
108
}
109
-
110
-
111
- return false;
112
}
113
114
115
- public function checkMarketOrderExists($orderid) {
116
- $resource = Mage::getSingleton('core/resource');
117
- $readConnection = $resource->getConnection('core_read');
118
- $table = $resource->getTableName('sales/order_grid');
119
- $query = 'SELECT increment_id FROM ' . $table . ' WHERE beezup_order = 1 and beezup_market_order_id = \''
120
- . $orderid . '\' LIMIT 1';
121
- $order = $readConnection->fetchOne($query);
122
-
123
- if($order && !empty($order) && $this->orderId !== "") {
124
- return $order;
125
- }
126
- return false;
127
-
128
}
129
130
- public function resynOrder($orderId) {
131
-
132
- $this->orderid = $orderId;
133
- $oBeezupOrderResponse= $this->getBeezupOrderFromMage();
134
-
135
- $etag = $oBeezupOrderResponse->getETag();
136
-
137
- $final_order = $oBeezupOrderResponse->getResult();
138
- $order_status = $final_order->getOrderStatusBeezUPOrderStatus();
139
- $isPending = $final_order->getIsPendingSynchronization();
140
- $order_address = $this->getBeezupBuyerAddress($final_order);
141
- $order_city = $final_order->getOrderBuyerAddressCity();
142
- $order_region = $final_order->getOrderBuyerStateOrRegion();
143
- $order_postalCode = $final_order->getOrderBuyerAddressPostalCode();
144
- $order_customer = $final_order->getOrderBuyerName();
145
- $order_customer_email = $final_order->getOrderBuyerEmail();
146
- $order_customer_phone = $final_order->getOrderBuyerPhone();
147
- $order_customer_mobile = $final_order->getOrderBuyerMobilePhone();
148
- $order_country = $final_order->getOrderBuyerAddressCountryName();
149
- $order_country_iso = $final_order->getOrderBuyerAddressCountryIsoCodeAlpha2();
150
-
151
- $shipping_city = $final_order->getOrderShippingAddressCity();
152
- $shipping_country = $final_order->getOrderShippingAddressCountryName();
153
- $shipping_name = $final_order->getOrderShippingAddressName();
154
- $shipping_postalCode = $final_order->getOrderShippingAddressPostalCode();
155
- $shipping_email = $final_order->getOrderShippingEmail();
156
- $shipping_phone = $final_order->getOrderShippingPhone();
157
- $shipping_mobile = $final_order->getOrderShippingMobilePhone();
158
- $shipping_company = $final_order->getOrderShippingCompanyName();
159
- $shipping_region = $final_order->getOrderShippingAddressStateOrRegion();
160
- $order_currency_code = $final_order->getOrderCurrencyCode();
161
//order Info
162
- $order_totalPrice = $final_order->getOrderTotalPrice();
163
- $order_shippingPrice = $final_order->getOrderShippingPrice();
164
- $shipping_address = $this->getBeezupShippingAddress($final_order);
165
-
166
- $name_parts = explode(" ", $order_customer);
167
- $order_first_name = array_shift( $name_parts);
168
- $order_last_name = implode(" ", $name_parts);
169
-
170
-
171
- $name_parts = explode(" ", $shipping_name);
172
- $shipping_first_name = array_shift( $name_parts);
173
- $shipping_last_name = implode(" ", $name_parts);
174
-
175
- $etag_exists = $this->checkEtagExists($etag);
176
-
177
- if(!$isPending && !$etag_exists ) {
178
- $order_data = array(
179
"etag" => $etag,
180
"order_status" => $order_status,
181
"order_address" => $order_adress,
@@ -203,199 +208,199 @@
203
"order_city" => $order_city,
204
"order_region" => $order_region,
205
);
206
-
207
-
208
- $Mageorder = $this->loadMageOrder();
209
- if ($Mageorder) {
210
//if order exists
211
- $this->updateEtag($etag);
212
- $this->updateBilling($Mageorder, $order_data );
213
- $this->updateBeezupInfoTab($Mageorder, $final_order, $order_data);
214
- $status1 = $Mageorder->getStatusLabel();
215
- $status = $this->getStatus($status1);
216
- if($status !== $order_status) {
217
//if order exits and status has changed we update order status
218
- $this->setStatus( $order_status, $Mageorder);
219
- }
220
-
221
- $id_order = $Mageorder->getId();
222
- $BeezupMageOrder = new BeezupMageOrders($id_order);
223
- $BeezupMageOrder->setData(array("shipping" =>(float) $order_data['order_shippingPrice']));
224
- $BeezupMageOrder->updateShippingInfo();
225
-
226
- echo 1;
227
- } else {
228
-
229
- echo 2;
230
}
231
232
233
- }
234
- else {
235
- if($isPending) {
236
- echo 3;
237
- } else {
238
- echo 2;
239
-
240
- }
241
}
242
243
}
244
245
246
-
247
- public function getStatus($status1) {
248
- $helper = Mage::helper('beezup');
249
- $retorno = "";
250
- $status = strtolower($status1);
251
252
- if($status == strtolower($helper->getConfig('beezup/marketplace/status_new') )) {
253
- $retorno = "New";
254
-
255
- } elseif($status == strtolower($helper->getConfig('beezup/marketplace/status_progress') ) ){
256
- $retorno = "InProgress";
257
-
258
-
259
- }
260
- elseif($status == strtolower($helper->getConfig('beezup/marketplace/status_aborted') )) {
261
-
262
- $retorno = "Aborted" ;
263
- }
264
- elseif($status == strtolower($helper->getConfig('beezup/marketplace/status_closed') )) {
265
- $retorno = "Closed";
266
-
267
- }
268
- elseif($status == strtolower($helper->getConfig('beezup/marketplace/status_cancelled')) ) {
269
-
270
- $retorno = "Canceled";
271
- }
272
- elseif($status == strtolower($helper->getConfig('beezup/marketplace/status_shipped') )) {
273
-
274
- $retorno = "Shipped";
275
- }
276
277
278
- return $retorno;
279
280
}
281
-
282
- public function setStatus($status, $order) {
283
- $helper = Mage::helper('beezup');
284
- $retorno = "";
285
- $blnCancel = false;
286
- $blnHold = false;
287
- switch($status) {
288
- case "New" :
289
- $retorno = $helper->getConfig('beezup/marketplace/status_new');
290
- break;
291
- case "InProgress" :
292
- $retorno = $helper->getConfig('beezup/marketplace/status_progress');
293
- $this->payOrder($order);
294
- break;
295
- case "Aborted" :
296
- $retorno = $helper->getConfig('beezup/marketplace/status_aborted');
297
- $blnHold = true;
298
-
299
-
300
- break;
301
- case "Closed" :
302
- $blnCancel =true;
303
- $retorno = $helper->getConfig('beezup/marketplace/status_closed');
304
- $this->payOrder($order);
305
- break;
306
- case "Canceled" :
307
- $retorno = $helper->getConfig('beezup/marketplace/status_cancelled');
308
-
309
- break;
310
- case "Shipped" :
311
- $retorno = $helper->getConfig('beezup/marketplace/status_shipped');
312
- $this->payOrder($order);
313
- break;
314
-
315
- }
316
- $order->setData('state',$retorno);
317
- $order->setStatus($retorno);
318
- $history = $order->addStatusHistoryComment('Order was set to '.$retorno.' by Beezup.', false);
319
- $history->setIsCustomerNotified(false);
320
- $order->save();
321
- if($blnCancel) {
322
- $order->cancel()->save();
323
- }
324
- if($blnHold) {
325
- $order->hold()->save();
326
- }
327
328
- return $retorno;
329
330
}
331
- public function getPhone($phone, $phone2) {
332
- $retorno = "";
333
- if(!empty($phone) && $phone !== "") {
334
- $retorno .= $phone;
335
- }
336
- if(!empty($phone2) && $phone2 !=="") {
337
- if(empty($phone) || $phone == "") {
338
- $retorno = $phone2;
339
-
340
- } else {
341
- $retorno .= " - ".$phone2;
342
- }
343
- }
344
- return $retorno;
345
}
346
347
- public function payOrder($order) {
348
- try {
349
350
- if($order->canInvoice()) {
351
- $invoice = $order->prepareInvoice()
352
- ->setTransactionId($order->getId())
353
- ->addComment("Invoice created from Beezup.")
354
- ->register()
355
- ->pay();
356
- $transaction_save = Mage::getModel('core/resource_transaction')
357
- ->addObject($invoice)
358
- ->addObject($invoice->getOrder());
359
- $transaction_save->save();
360
-
361
- }
362
}
363
- catch(Exception $e){
364
365
}
366
}
367
-
368
-
369
- public function updateBeezupInfoTab($order, $oLink, $data) {
370
- $beezup_last_modification_date = $oLink->getOrderLastModificationUtcDate();
371
- $beezup_last_modification_date = $beezup_last_modification_date->date;
372
- $beezup_marketplace_last_modification_date = $oLink->getOrderMarketPlaceLastModificationUtcDate();
373
- $beezup_marketplace_last_modification_date = $beezup_marketplace_last_modification_date->date;
374
- $beezup_comission = $oLink->getOrderTotalCommission()." ".$data['order_currency'];
375
- $tot_comm = $oLink->getOrderTotalCommission();
376
- if(empty($tot_comm ) || $tot_comm == 0) {
377
- $beezup_comission = 0;
378
- }
379
- $updateData = array("beezup_status" => $data['order_status'],
380
"beezup_last_modification_date" => $beezup_last_modification_date,
381
"beezup_marketplace_last_modification_date" => $beezup_marketplace_last_modification_date ,
382
"beezup_total_paid" => $oLink->getOrderTotalPrice()." ".$data['order_currency'],
383
"beezup_comission" => $beezup_comission,
384
"beezup_marketplace_status" => $oLink->getOrderStatusMarketPlaceStatus());
385
- $orderId = $order->getId();
386
- $beezupMageOrder = new BeezupMageOrders($orderId);
387
- $beezupMageOrder->setData($updateData);
388
- $beezupMageOrder->updateBeezupInfo();
389
-
390
-
391
- }
392
393
394
395
- public function updateBilling($order, $data) {
396
-
397
-
398
- $addressData = array(
399
'billing_firstname' => ($data['order_customer']) ? $data['order_customer'] : "empty",
400
'billing_lastname' => ($data['order_lastname']) ? $data['order_lastname'] : "empty",
401
'billing_street' => ($data['order_address']) ? $data['order_address'] : "empty",
@@ -404,7 +409,7 @@
404
'billing_telephone' => ($data['order_customer_phone']) ? $data['order_customer_phone'] : "empty",
405
'billing_country_id' => ($data['order_country_iso']) ? $data['order_country_iso'] : "empty",
406
'billing_region_id' => ($data['order_region ']) ? substr($data['order_region '], 0,2) : "EM",
407
- 'shipping_firstname' => ($data['shipping_name']) ? $data['shipping_name'] : "empty",
408
'shipping_lastname' => ($data['shipping_lastname']) ? $data['shipping_lastname'] : "empty",
409
'shipping_street' => ($data['shipping_address']) ? $data['shipping_address'] : "empty",
410
'shipping_city' => ($data['shipping_city']) ? $data['shipping_city'] : "empty",
@@ -413,162 +418,162 @@
413
'shipping_country_id' => ($data['shipping_country_iso']) ? $data['shipping_country_iso'] : "empty",
414
'shipping_region_id' => ($data['shipping_region']) ? substr($data['shipping_region'], 0, 2) : "EM" // id from directory_country_region table
415
);
416
-
417
- $shippingData = array(
418
419
);
420
// Get the id of the orders shipping address
421
- $orderId = $order->getId();
422
- $beezupMageOrder = new BeezupMageOrders($orderId);
423
- $beezupMageOrder->setData($addressData);
424
- $beezupMageOrder->updateAdresses();
425
- }
426
427
428
429
430
- public function updateEtag($etag) {
431
- $resource = Mage::getSingleton('core/resource');
432
- $writeConnection = $resource->getConnection('core_write');
433
- $table = $resource->getTableName('sales/order_grid');
434
- $query = "UPDATE {$table} SET beezup_etag = '{$etag}' where entity_id = '{$this->orderid}' ";
435
- $writeConnection->query($query);
436
437
}
438
439
-
440
- public function changeOrder($aData) {
441
442
- $errmsg = "";
443
- $this->orderid = $aData['order_id'];
444
- $aResult = array('errors' => array(), 'warnings' => array(), 'infos' => array(),'successes' => array());
445
-
446
- if (!isset($aData['order_id']) || !is_numeric($aData['order_id'])){
447
- $errmsg .= "ERROR: ".Mage::helper('beezup')->__('Invalid order id')."<br>";
448
- echo $errmsg;
449
- }
450
-
451
- $oBeezupOrderResponse= $this->getBeezupOrderFromMage();
452
- $oBeezupOrder = $oBeezupOrderResponse->getResult();
453
-
454
- if (!$oBeezupOrder){
455
- $errmsg .="ERROR: ". Mage::helper('beezup')->__('Unable load BeezUP order')."<br>";
456
-
457
- echo $errmsg;
458
- }
459
-
460
- if (!isset($aData['action_id'])){
461
- $errmsg .= "ERROR: ".Mage::helper('beezup')->__('No action id')."<br>";
462
-
463
- echo $errmsg;
464
- }
465
-
466
- $oLink = $oBeezupOrder->getTransitionLinkByRel($aData['action_id']);
467
468
- if (!$oLink){
469
-
470
- $errmsg .= "ERROR: ".Mage::helper('beezup')->__('Invalid action')."<br>";
471
- }
472
- $aParams = array(
473
'TestMode' => $this->isTestModeActivated() ? 1 : 0,
474
'userName' => $aData['adminUser']
475
);
476
477
- if ($oLink){
478
-
479
-
480
- list($bResult, $oResult) = $this->getOrderService()->changeOrder($oLink, $aParams, $aData);
481
482
- if ($bResult){
483
- $errmsg .= "SUCCESS: ". Mage::helper('beezup')->__('Order update well executed and is currently resyncing')."<br>";
484
- $aResult['aResult'] = true;
485
- $oCachedOrder = $this->getBeezupOrderFromMage();
486
-
487
/**
488
* @var BeezupOMOrderResult
489
*/
490
- $oBeezupOrderResult = $oCachedOrder->getResult();
491
-
492
- $oBeezupOrderResult->setIsPendingSynchronization(true);
493
-
494
} else {
495
// how to know what happened?
496
-
497
-
498
- if ($oResult && $oResult->getInfo()){
499
500
501
- foreach ($oResult->getInfo()->getErrors() as $oError){
502
// ie we have 404 because of bad query params, we don't need to display those 404
503
- if ($oError->getMessage() === 'HTTP Error' && !empty($aResult['errors'])){
504
- continue;
505
}
506
- $errmsg .= "ERROR: ".$oError->getCode() .' : ' . $oError->getMessage()."<br>";
507
- }
508
} else {
509
- $errmsg .= "ERROR: ". Mage::helper('beezup')->__('Unable to update')."<br>";
510
}
511
}
512
}
513
514
515
-
516
- echo $errmsg;
517
-
518
-
519
- }
520
-
521
- public function isTestModeActivated() {
522
- return false;
523
- }
524
-
525
//function to get beezup info list
526
- public function getInfo($order_id) {
527
- $this->orderid = $order_id;
528
- try {
529
- $order = $this->getBeezupOrderFromMage();
530
- if ($order && $order->getResult()) {
531
- $order_result = $order->getResult();
532
- $beezup_infos = $order? $order->getInfo()->getInformations() : array();
533
- $order_actions = $this->getOrderActions($order_result );
534
/*
535
echo "<pre>";
536
print_r($order_actions);
537
538
echo "</pre>";
539
*/
540
- echo "<label>Status</label><br>";
541
- echo "<select id='status_value'>";
542
- foreach($order_actions as $action) {
543
544
- echo "<option value='".$action['id']."'>".$action['translated_name']."</option>";
545
- echo "<input type='hidden' id='lovs_".$action['id']."' value='".$action['lovs']."' />";
546
- }
547
-
548
- echo "</select>";
549
- echo "<button class='button' onclick='changeStatus();'>Change Status</button>";
550
-
551
- echo ' <div id="closed"></div>
552
-
553
- <div class="popup-wrapper" id="popup">
554
- <div class="popup-container"><!-- Popup Contents, just modify with your own -->
555
-
556
- <h2>Update Order Status</h2>
557
- <hr>
558
- <div class="input-group"><div id="contenido-form"></div>';
559
-
560
-
561
- echo '<br><button class="button">Update</button>
562
- </div>
563
-
564
- <a class="popup-close" href="#closed">X</a>
565
- </div>
566
</div>
567
';
568
569
570
}
571
- } catch (Exception $ex ) {
572
die($ex->getMessage());
573
}
574
@@ -630,59 +635,59 @@
630
/**
631
* @return BeezupOMOrderService
632
*/
633
- public function getOrderService(){
634
- if ($this->oOrderService === null){
635
- $this->oOrderService = $this->createOrderService();
636
// enchufamos debug mode, esta activado? false true $this->oOrderService->setDebugMode(false);
637
}
638
- return $this->oOrderService;
639
- }
640
-
641
/**
642
* @return BeezupOMOrderService
643
*/
644
- protected function createOrderService(){
645
646
- return new BeezupOMOrderService($this->createRepository() );
647
- }
648
-
649
- protected function createRepository() {
650
- if ($this->repository == null) {
651
- $this->repository = new BeezupRepository();
652
- }
653
- return $this->repository;
654
655
- }
656
-
657
-
658
/**
659
* Returns disponible order actions
660
* @param unknown_type $oBeezupOrder
661
* @param unknown_type $oPsOrder
662
* @return multitype:|multitype:multitype:string NULL unknown
663
*/
664
- public function getOrderActions($oBeezupOrder = null, $oPsOrder = null){
665
- $aResult = array();
666
- if (!$oBeezupOrder || !($oBeezupOrder instanceof BeezupOMOrderResult)) {
667
- return $aResult;
668
- }
669
-
670
// $aLovValues = $this->getOrderService()->getLovValues('OrderChangeBusinessOperationType', Context::getContext()->language->iso_code);
671
-
672
- foreach ($oBeezupOrder->getTransitionLinks() as $oLink){
673
674
- $aResult[] = array(
675
- 'link' => $oLink,
676
- 'href' => $oLink->getHref(),
677
- 'id' => $oLink->getRel(),
678
- 'name' => $oLink->getRel(),
679
- 'translated_name' => $oLink->getRel(),
680
- 'fields' => json_encode($oLink->toArray()),
681
- 'lovs' => json_encode($this->getOrderService()->getLOVValuesForParams($oLink))
682
/*,
683
'values' => json_encode($this->getFieldsValues($oLink, $oPsOrder)),
684
- 'info' => json_encode($this->getTransitionLinkInfo($oLink))*/
685
- );
686
/*
687
echo "<pre>";
688
print_r(json_decode($aResult[0]['lovs']));
@@ -692,9 +697,9 @@
692
print_r(json_decode($aResult[0]['fields']));
693
echo "</pre>";
694
*/
695
}
696
697
- return $aResult;
698
- }
699
-
700
- }
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_Omstatus extends Mage_core_block_text {
8
+ protected $repository = null;
9
+ protected $oOrderService;
10
+ public $log = null;
11
+ public $log2 = null;
12
+ public $orderid = "";
13
+ public $debug = false;
14
+ private $account_id;
15
+ private $marketplace_code;
16
+ private $beezup_order_id;
17
18
+
19
+ public function getLoader() {
20
+ $dir = Mage::getModuleDir("etc", "BeezUp");
21
+ $dir = str_replace("etc", "img", $dir);
22
+ header('Content-Type: image/jpeg');
23
+ readfile($dir."/ajax-loader.gif");
24
25
+ }
26
+
27
+
28
+ public function getBeezupBuyerAddress($order) {
29
+ $add1=$order->getOrderBuyerAddressLine1();
30
+ $add2=$order->getOrderBuyerAddressLine2();
31
+ $add3=$order->getOrderBuyerAddressLine3();
32
+ $retorno = "";
33
+ if(!empty($add1)) {
34
+ $retorno = $order->getOrderBuyerAddressLine1();
35
+ }
36
+ if(!empty($add2)) {
37
+ if(empty($add1)) {
38
+ $retorno .= $order->getOrderBuyerAddressLine2();
39
+ } else {
40
+ $retorno .= " - ". $order->getOrderBuyerAddressLine2();
41
}
42
+ }
43
+ if(!empty($add3)){
44
+ if(empty($add1) && empty($add2)) {
45
+ $retorno .= $order->getOrderBuyerAddressLine3();
46
+ } else {
47
+ $retorno .= " - ". $order->getOrderBuyerAddressLine3();
48
+ }
49
+ }
50
+ return $retorno;
51
+ }
52
+
53
+
54
+ public function getBeezupShippingAddress($order) {
55
+ $add1 = $order->getOrderShippingAddressLine1();
56
+ $add2 = $order->getOrderShippingAddressLine2();
57
+ $add3=$order->getOrderBuyerAddressLine3();
58
+ $retorno = "";
59
+ if(!empty($add1 )) {
60
+ $retorno = $order->getOrderShippingAddressLine1();
61
+ }
62
+ if(!empty($add2)) {
63
+ if(empty($add1)) {
64
+ $retorno .= $order->getOrderShippingAddressLine2();
65
+ } else {
66
+ $retorno .= " - ". $order->getOrderShippingAddressLine2();
67
+ }
68
+ }
69
+ if(!empty($add3)){
70
+ if(empty($add1) && empty($add2)) {
71
+ $retorno .= $order->getOrderShippingAddressLine3();
72
+ } else {
73
+ $retorno .= " - ". $order->getOrderShippingAddressLine3();
74
+ }
75
+ }
76
+ return $retorno;
77
+ }
78
+
79
+
80
+ public function checkEtagExists($etag) {
81
+ $resource = Mage::getSingleton('core/resource');
82
+ $readConnection = $resource->getConnection('core_read');
83
+ $table = $resource->getTableName('sales/order_grid');
84
+ $query = 'SELECT increment_id FROM ' . $table . ' WHERE beezup_etag = \''
85
+ . $etag . '\' LIMIT 1';
86
+ $order = $readConnection->fetchOne($query);
87
+ if($order && !empty($order)) {
88
+ return true;
89
}
90
+ return false;
91
92
+ }
93
+
94
+ public function loadMageOrder() {
95
+ $Mageorder = Mage::getModel('sales/order')->load($this->orderid);
96
+ if ($Mageorder->getId()) {
97
+ return $Mageorder;
98
+ } else {
99
//we get order from marketplace orderid
100
+ $orderInc = $this->checkMarketOrderExists($this->orderid);
101
+ if($orderInc) {
102
// if exists
103
+ $Mageorder = Mage::getModel('sales/order')->loadByIncrementId($orderInc);
104
+ if ($Mageorder->getId()) {
105
+ return $Mageorder;
106
}
107
}
108
}
109
110
111
+ return false;
112
+ }
113
+
114
+
115
+ public function checkMarketOrderExists($orderid) {
116
+ $resource = Mage::getSingleton('core/resource');
117
+ $readConnection = $resource->getConnection('core_read');
118
+ $table = $resource->getTableName('sales/order_grid');
119
+ $query = 'SELECT increment_id FROM ' . $table . ' WHERE beezup_order = 1 and beezup_market_order_id = \''
120
+ . $orderid . '\' LIMIT 1';
121
+ $order = $readConnection->fetchOne($query);
122
+
123
+ if($order && !empty($order) && $this->orderId !== "") {
124
+ return $order;
125
}
126
+ return false;
127
128
+ }
129
+
130
+ public function resynOrder($orderId) {
131
+
132
+ $this->orderid = $orderId;
133
+ $oBeezupOrderResponse= $this->getBeezupOrderFromMage();
134
+
135
+ $etag = $oBeezupOrderResponse->getETag();
136
+
137
+ $final_order = $oBeezupOrderResponse->getResult();
138
+ $order_status = $final_order->getOrderStatusBeezUPOrderStatus();
139
+ $isPending = $final_order->getIsPendingSynchronization();
140
+ $order_address = $this->getBeezupBuyerAddress($final_order);
141
+ $order_city = $final_order->getOrderBuyerAddressCity();
142
+ $order_region = $final_order->getOrderBuyerStateOrRegion();
143
+ $order_postalCode = $final_order->getOrderBuyerAddressPostalCode();
144
+ $order_customer = $final_order->getOrderBuyerName();
145
+ $order_customer_email = $final_order->getOrderBuyerEmail();
146
+ $order_customer_phone = $final_order->getOrderBuyerPhone();
147
+ $order_customer_mobile = $final_order->getOrderBuyerMobilePhone();
148
+ $order_country = $final_order->getOrderBuyerAddressCountryName();
149
+ $order_country_iso = $final_order->getOrderBuyerAddressCountryIsoCodeAlpha2();
150
+
151
+ $shipping_city = $final_order->getOrderShippingAddressCity();
152
+ $shipping_country = $final_order->getOrderShippingAddressCountryName();
153
+ $shipping_name = $final_order->getOrderShippingAddressName();
154
+ $shipping_postalCode = $final_order->getOrderShippingAddressPostalCode();
155
+ $shipping_email = $final_order->getOrderShippingEmail();
156
+ $shipping_phone = $final_order->getOrderShippingPhone();
157
+ $shipping_mobile = $final_order->getOrderShippingMobilePhone();
158
+ $shipping_company = $final_order->getOrderShippingCompanyName();
159
+ $shipping_region = $final_order->getOrderShippingAddressStateOrRegion();
160
+ $order_currency_code = $final_order->getOrderCurrencyCode();
161
//order Info
162
+ $order_totalPrice = $final_order->getOrderTotalPrice();
163
+ $order_shippingPrice = $final_order->getOrderShippingPrice();
164
+ $shipping_address = $this->getBeezupShippingAddress($final_order);
165
+
166
+ $name_parts = explode(" ", $order_customer);
167
+ $order_first_name = array_shift( $name_parts);
168
+ $order_last_name = implode(" ", $name_parts);
169
+
170
+
171
+ $name_parts = explode(" ", $shipping_name);
172
+ $shipping_first_name = array_shift( $name_parts);
173
+ $shipping_last_name = implode(" ", $name_parts);
174
+
175
+ $etag_exists = $this->checkEtagExists($etag);
176
+ if($order_country_iso == "FX" || $order_country_iso == "fx") {
177
+ $order_country_iso = "FR";
178
+ }
179
+ if($shipping_country_iso == "FX" || $shipping_country_iso == "fx") {
180
+ $shipping_country_iso = "FR";
181
+ }
182
+ if(!$isPending && !$etag_exists ) {
183
+ $order_data = array(
184
"etag" => $etag,
185
"order_status" => $order_status,
186
"order_address" => $order_adress,
208
"order_city" => $order_city,
209
"order_region" => $order_region,
210
);
211
+
212
+
213
+ $Mageorder = $this->loadMageOrder();
214
+ if ($Mageorder) {
215
//if order exists
216
+ $this->updateEtag($etag);
217
+ $this->updateBilling($Mageorder, $order_data );
218
+ $this->updateBeezupInfoTab($Mageorder, $final_order, $order_data);
219
+ $status1 = $Mageorder->getStatusLabel();
220
+ $status = $this->getStatus($status1);
221
+ if($status !== $order_status) {
222
//if order exits and status has changed we update order status
223
+ $this->setStatus( $order_status, $Mageorder);
224
}
225
226
+ $id_order = $Mageorder->getId();
227
+ $BeezupMageOrder = new BeezupMageOrders($id_order);
228
+ $BeezupMageOrder->setData(array("shipping" =>(float) $order_data['order_shippingPrice']));
229
+ $BeezupMageOrder->updateShippingInfo();
230
231
+ echo 1;
232
+ } else {
233
+
234
+ echo 2;
235
}
236
237
+
238
+ }
239
+ else {
240
+ if($isPending) {
241
+ echo 3;
242
+ } else {
243
+ echo 2;
244
+
245
+ }
246
}
247
248
+ }
249
+
250
+
251
+
252
+ public function getStatus($status1) {
253
+ $helper = Mage::helper('beezup');
254
+ $retorno = "";
255
+ $status = strtolower($status1);
256
257
+ if($status == strtolower($helper->getConfig('beezup/marketplace/status_new') )) {
258
+ $retorno = "New";
259
260
+ } elseif($status == strtolower($helper->getConfig('beezup/marketplace/status_progress') ) ){
261
+ $retorno = "InProgress";
262
263
264
+ }
265
+ elseif($status == strtolower($helper->getConfig('beezup/marketplace/status_aborted') )) {
266
267
+ $retorno = "Aborted" ;
268
}
269
+ elseif($status == strtolower($helper->getConfig('beezup/marketplace/status_closed') )) {
270
+ $retorno = "Closed";
271
272
+ }
273
+ elseif($status == strtolower($helper->getConfig('beezup/marketplace/status_cancelled')) ) {
274
275
+ $retorno = "Canceled";
276
}
277
+ elseif($status == strtolower($helper->getConfig('beezup/marketplace/status_shipped') )) {
278
+
279
+ $retorno = "Shipped";
280
}
281
282
+
283
+ return $retorno;
284
+
285
+ }
286
+
287
+ public function setStatus($status, $order) {
288
+ $helper = Mage::helper('beezup');
289
+ $retorno = "";
290
+ $blnCancel = false;
291
+ $blnHold = false;
292
+ switch($status) {
293
+ case "New" :
294
+ $retorno = $helper->getConfig('beezup/marketplace/status_new');
295
+ break;
296
+ case "InProgress" :
297
+ $retorno = $helper->getConfig('beezup/marketplace/status_progress');
298
+ $this->payOrder($order);
299
+ break;
300
+ case "Aborted" :
301
+ $retorno = $helper->getConfig('beezup/marketplace/status_aborted');
302
+ $blnHold = true;
303
+
304
+
305
+ break;
306
+ case "Closed" :
307
+ $blnCancel =true;
308
+ $retorno = $helper->getConfig('beezup/marketplace/status_closed');
309
+ $this->payOrder($order);
310
+ break;
311
+ case "Canceled" :
312
+ $retorno = $helper->getConfig('beezup/marketplace/status_cancelled');
313
+
314
+ break;
315
+ case "Shipped" :
316
+ $retorno = $helper->getConfig('beezup/marketplace/status_shipped');
317
+ $this->payOrder($order);
318
+ break;
319
+
320
+ }
321
+ $order->setData('state',$retorno);
322
+ $order->setStatus($retorno);
323
+ $history = $order->addStatusHistoryComment('Order was set to '.$retorno.' by Beezup.', false);
324
+ $history->setIsCustomerNotified(false);
325
+ $order->save();
326
+ if($blnCancel) {
327
+ $order->cancel()->save();
328
+ }
329
+ if($blnHold) {
330
+ $order->hold()->save();
331
+ }
332
+
333
+ return $retorno;
334
+
335
+ }
336
+ public function getPhone($phone, $phone2) {
337
+ $retorno = "";
338
+ if(!empty($phone) && $phone !== "") {
339
+ $retorno .= $phone;
340
+ }
341
+ if(!empty($phone2) && $phone2 !=="") {
342
+ if(empty($phone) || $phone == "") {
343
+ $retorno = $phone2;
344
345
+ } else {
346
+ $retorno .= " - ".$phone2;
347
}
348
+ }
349
+ return $retorno;
350
+ }
351
+
352
+ public function payOrder($order) {
353
+ try {
354
+
355
+ if($order->canInvoice()) {
356
+ $invoice = $order->prepareInvoice()
357
+ ->setTransactionId($order->getId())
358
+ ->addComment("Invoice created from Beezup.")
359
+ ->register()
360
+ ->pay();
361
+ $transaction_save = Mage::getModel('core/resource_transaction')
362
+ ->addObject($invoice)
363
+ ->addObject($invoice->getOrder());
364
+ $transaction_save->save();
365
366
}
367
}
368
+ catch(Exception $e){
369
+
370
+ }
371
+ }
372
+
373
+
374
+ public function updateBeezupInfoTab($order, $oLink, $data) {
375
+ $beezup_last_modification_date = $oLink->getOrderLastModificationUtcDate();
376
+ $beezup_last_modification_date = $beezup_last_modification_date->date;
377
+ $beezup_marketplace_last_modification_date = $oLink->getOrderMarketPlaceLastModificationUtcDate();
378
+ $beezup_marketplace_last_modification_date = $beezup_marketplace_last_modification_date->date;
379
+ $beezup_comission = $oLink->getOrderTotalCommission()." ".$data['order_currency'];
380
+ $tot_comm = $oLink->getOrderTotalCommission();
381
+ if(empty($tot_comm ) || $tot_comm == 0) {
382
+ $beezup_comission = 0;
383
+ }
384
+ $updateData = array("beezup_status" => $data['order_status'],
385
"beezup_last_modification_date" => $beezup_last_modification_date,
386
"beezup_marketplace_last_modification_date" => $beezup_marketplace_last_modification_date ,
387
"beezup_total_paid" => $oLink->getOrderTotalPrice()." ".$data['order_currency'],
388
"beezup_comission" => $beezup_comission,
389
"beezup_marketplace_status" => $oLink->getOrderStatusMarketPlaceStatus());
390
+ $orderId = $order->getId();
391
+ $beezupMageOrder = new BeezupMageOrders($orderId);
392
+ $beezupMageOrder->setData($updateData);
393
+ $beezupMageOrder->updateBeezupInfo();
394
395
396
+ }
397
+
398
+
399
+
400
+ public function updateBilling($order, $data) {
401
+
402
403
+ $addressData = array(
404
'billing_firstname' => ($data['order_customer']) ? $data['order_customer'] : "empty",
405
'billing_lastname' => ($data['order_lastname']) ? $data['order_lastname'] : "empty",
406
'billing_street' => ($data['order_address']) ? $data['order_address'] : "empty",
409
'billing_telephone' => ($data['order_customer_phone']) ? $data['order_customer_phone'] : "empty",
410
'billing_country_id' => ($data['order_country_iso']) ? $data['order_country_iso'] : "empty",
411
'billing_region_id' => ($data['order_region ']) ? substr($data['order_region '], 0,2) : "EM",
412
+ 'shipping_firstname' => ($data['shipping_name']) ? $data['shipping_name'] : "empty",
413
'shipping_lastname' => ($data['shipping_lastname']) ? $data['shipping_lastname'] : "empty",
414
'shipping_street' => ($data['shipping_address']) ? $data['shipping_address'] : "empty",
415
'shipping_city' => ($data['shipping_city']) ? $data['shipping_city'] : "empty",
418
'shipping_country_id' => ($data['shipping_country_iso']) ? $data['shipping_country_iso'] : "empty",
419
'shipping_region_id' => ($data['shipping_region']) ? substr($data['shipping_region'], 0, 2) : "EM" // id from directory_country_region table
420
);
421
+
422
+ $shippingData = array(
423
424
);
425
// Get the id of the orders shipping address
426
+ $orderId = $order->getId();
427
+ $beezupMageOrder = new BeezupMageOrders($orderId);
428
+ $beezupMageOrder->setData($addressData);
429
+ $beezupMageOrder->updateAdresses();
430
+ }
431
+
432
+
433
+
434
+
435
+ public function updateEtag($etag) {
436
+ $resource = Mage::getSingleton('core/resource');
437
+ $writeConnection = $resource->getConnection('core_write');
438
+ $table = $resource->getTableName('sales/order_grid');
439
+ $query = "UPDATE {$table} SET beezup_etag = '{$etag}' where entity_id = '{$this->orderid}' ";
440
+ $writeConnection->query($query);
441
+
442
+ }
443
+
444
+
445
+ public function changeOrder($aData) {
446
447
+ $errmsg = "";
448
+ $this->orderid = $aData['order_id'];
449
+ $aResult = array('errors' => array(), 'warnings' => array(), 'infos' => array(),'successes' => array());
450
451
+ if (!isset($aData['order_id']) || !is_numeric($aData['order_id'])){
452
+ $errmsg .= "ERROR: ".Mage::helper('beezup')->__('Invalid order id')."<br>";
453
+ echo $errmsg;
454
+ }
455
456
+ $oBeezupOrderResponse= $this->getBeezupOrderFromMage();
457
+ $oBeezupOrder = $oBeezupOrderResponse->getResult();
458
459
+ if (!$oBeezupOrder){
460
+ $errmsg .="ERROR: ". Mage::helper('beezup')->__('Unable load BeezUP order')."<br>";
461
462
+ echo $errmsg;
463
}
464
465
+ if (!isset($aData['action_id'])){
466
+ $errmsg .= "ERROR: ".Mage::helper('beezup')->__('No action id')."<br>";
467
468
+ echo $errmsg;
469
+ }
470
+
471
+ $oLink = $oBeezupOrder->getTransitionLinkByRel($aData['action_id']);
472
+
473
+ if (!$oLink){
474
475
+ $errmsg .= "ERROR: ".Mage::helper('beezup')->__('Invalid action')."<br>";
476
+ }
477
+ $aParams = array(
478
'TestMode' => $this->isTestModeActivated() ? 1 : 0,
479
'userName' => $aData['adminUser']
480
);
481
+
482
+ if ($oLink){
483
484
+
485
+ list($bResult, $oResult) = $this->getOrderService()->changeOrder($oLink, $aParams, $aData);
486
+
487
+ if ($bResult){
488
+ $errmsg .= "SUCCESS: ". Mage::helper('beezup')->__('Order update well executed and is currently resyncing')."<br>";
489
+ $aResult['aResult'] = true;
490
+ $oCachedOrder = $this->getBeezupOrderFromMage();
491
492
/**
493
* @var BeezupOMOrderResult
494
*/
495
+ $oBeezupOrderResult = $oCachedOrder->getResult();
496
+
497
+ $oBeezupOrderResult->setIsPendingSynchronization(true);
498
+
499
} else {
500
// how to know what happened?
501
502
503
+ if ($oResult && $oResult->getInfo()){
504
+
505
+
506
+ foreach ($oResult->getInfo()->getErrors() as $oError){
507
// ie we have 404 because of bad query params, we don't need to display those 404
508
+ if ($oError->getMessage() === 'HTTP Error' && !empty($aResult['errors'])){
509
+ continue;
510
+ }
511
+ $errmsg .= "ERROR: ".$oError->getCode() .' : ' . $oError->getMessage()."<br>";
512
}
513
} else {
514
+ $errmsg .= "ERROR: ". Mage::helper('beezup')->__('Unable to update')."<br>";
515
+ }
516
}
517
}
518
+
519
+
520
+
521
+ echo $errmsg;
522
+
523
+
524
}
525
526
+ public function isTestModeActivated() {
527
+ return false;
528
+ }
529
530
//function to get beezup info list
531
+ public function getInfo($order_id) {
532
+ $this->orderid = $order_id;
533
+ try {
534
+ $order = $this->getBeezupOrderFromMage();
535
+ if ($order && $order->getResult()) {
536
+ $order_result = $order->getResult();
537
+ $beezup_infos = $order? $order->getInfo()->getInformations() : array();
538
+ $order_actions = $this->getOrderActions($order_result );
539
/*
540
echo "<pre>";
541
print_r($order_actions);
542
543
echo "</pre>";
544
*/
545
+ echo "<label>Status</label><br>";
546
+ echo "<select id='status_value'>";
547
+ foreach($order_actions as $action) {
548
+
549
+ echo "<option value='".$action['id']."'>".$action['translated_name']."</option>";
550
+ echo "<input type='hidden' id='lovs_".$action['id']."' value='".$action['lovs']."' />";
551
+ }
552
553
+ echo "</select>";
554
+ echo "<button class='button' onclick='changeStatus();'>Change Status</button>";
555
+
556
+ echo ' <div id="closed"></div>
557
+
558
+ <div class="popup-wrapper" id="popup">
559
+ <div class="popup-container"><!-- Popup Contents, just modify with your own -->
560
+
561
+ <h2>Update Order Status</h2>
562
+ <hr>
563
+ <div class="input-group"><div id="contenido-form"></div>';
564
+
565
+
566
+ echo '<br><button class="button">Update</button>
567
+ </div>
568
+
569
+ <a class="popup-close" href="#closed">X</a>
570
+ </div>
571
</div>
572
';
573
574
575
}
576
+ } catch (Exception $ex ) {
577
die($ex->getMessage());
578
}
579
635
/**
636
* @return BeezupOMOrderService
637
*/
638
+ public function getOrderService(){
639
+ if ($this->oOrderService === null){
640
+ $this->oOrderService = $this->createOrderService();
641
// enchufamos debug mode, esta activado? false true $this->oOrderService->setDebugMode(false);
642
+ }
643
+ return $this->oOrderService;
644
}
645
+
646
/**
647
* @return BeezupOMOrderService
648
*/
649
+ protected function createOrderService(){
650
+
651
+ return new BeezupOMOrderService($this->createRepository() );
652
+ }
653
+
654
+ protected function createRepository() {
655
+ if ($this->repository == null) {
656
+ $this->repository = new BeezupRepository();
657
+ }
658
+ return $this->repository;
659
+
660
+ }
661
662
663
/**
664
* Returns disponible order actions
665
* @param unknown_type $oBeezupOrder
666
* @param unknown_type $oPsOrder
667
* @return multitype:|multitype:multitype:string NULL unknown
668
*/
669
+ public function getOrderActions($oBeezupOrder = null, $oPsOrder = null){
670
+ $aResult = array();
671
+ if (!$oBeezupOrder || !($oBeezupOrder instanceof BeezupOMOrderResult)) {
672
+ return $aResult;
673
+ }
674
+
675
// $aLovValues = $this->getOrderService()->getLovValues('OrderChangeBusinessOperationType', Context::getContext()->language->iso_code);
676
677
+ foreach ($oBeezupOrder->getTransitionLinks() as $oLink){
678
+
679
+ $aResult[] = array(
680
+ 'link' => $oLink,
681
+ 'href' => $oLink->getHref(),
682
+ 'id' => $oLink->getRel(),
683
+ 'name' => $oLink->getRel(),
684
+ 'translated_name' => $oLink->getRel(),
685
+ 'fields' => json_encode($oLink->toArray()),
686
+ 'lovs' => json_encode($this->getOrderService()->getLOVValuesForParams($oLink))
687
/*,
688
'values' => json_encode($this->getFieldsValues($oLink, $oPsOrder)),
689
+ 'info' => json_encode($this->getTransitionLinkInfo($oLink))*/
690
+ );
691
/*
692
echo "<pre>";
693
print_r(json_decode($aResult[0]['lovs']));
697
print_r(json_decode($aResult[0]['fields']));
698
echo "</pre>";
699
*/
700
+ }
701
+
702
+ return $aResult;
703
}
704
705
+ }
app/code/community/BeezUp/Block/Order.php CHANGED
@@ -1,131 +1,131 @@
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
- $shiiping_disabled = Mage::getStoreConfig('carriers/flatrate/active');
69
-
70
- $this->account_id = $account_id;
71
- $this->marketplace_code = $marketplace_code;
72
- $this->beezup_order_id = $beezup_order_id;
73
- $orderResponse = $this->getBeezupOrder();
74
- if($orderResponse) {
75
-
76
- if($shiiping_disabled == 0) {
77
- Mage::getConfig()
78
- ->saveConfig('carriers/flatrate/active', 1)
79
- ->cleanCache();
80
- Mage::app()->reinitStores();
81
- }
82
- $this->createOrder($orderResponse);
83
- if($shiiping_disabled == 0) {
84
- Mage::getConfig()
85
- ->saveConfig('carriers/flatrate/active', 0)
86
- ->cleanCache();
87
- Mage::app()->reinitStores();
88
- }
89
- $configModel->saveConfig('beezup/marketplace/sync_status',0);
90
- if($this->mage_order_id) {
91
- echo "<script>window.location='".Mage::helper('adminhtml')->getUrl("adminhtml/sales_order/view", array('order_id'=> $this->mage_order_id))."';</script>";
92
- }
93
- // die("Order Importation finalized");
94
-
95
}
96
97
}
98
- $configModel->saveConfig('beezup/marketplace/sync_status',0);
99
- //die("Error, Order data incorrect");
100
- echo $this->_showLog();
101
}
102
-
103
- public function _showLog() {
104
- $logDir = Mage::getBaseDir('base').'/beezup/';
105
// $log1 = file_get_contents();
106
- $ret = array();
107
- if (file_exists($logDir."/log.txt")) {
108
- $f = fopen($logDir."/log.txt", 'r');
109
-
110
- if ($f) {
111
- while (!feof($f)) {
112
- $ret[] = fgetcsv($f, 0, '|');
113
- }
114
- fclose($f);
115
}
116
}
117
- array_slice(array_reverse($ret), 1, 10);
118
-
119
- return $this->_getTable($ret);
120
-
121
}
122
123
124
- public function _getTable($data) {
125
- $url = Mage::getBaseUrl( Mage_Core_Model_Store::URL_TYPE_WEB, true );
126
- $html = "<td></td><td></td><tr></tr></tbody></table>
127
-
128
- <div class='grid' style=' height: 600px;overflow-y: scroll;padding: 16px;border: 3px solid #e6e6e6;' id='marketPlaceLogBlock'>";
129
$html .= '<p>'. Mage::helper('beezup')->__('For full logs see here:').' <a href="'.$url .'beezup/log/load" target="_blank">'.$url .'beezup/log/load</a></p>';
130
$html .= "<table class='data' style='margin-top:0px;width:100%;'>";
131
$html .= "<tr class='headings'>";
@@ -217,7 +217,7 @@
217
$configModel->saveConfig('beezup/marketplace/sync_status',0);
218
echo "OM Importation finalized succesfully";
219
220
- } else {
221
222
echo "Order Importation is already being executed";
223
}
@@ -321,46 +321,51 @@
321
elseif(!filter_var($order_customer_email, FILTER_VALIDATE_EMAIL)) {
322
$order_customer_email = $this->generateEmail($final_order);
323
}
324
-
325
$mage_productIds = $this->prescanOrder($final_order);
326
if($mage_productIds) {
327
$order_data = array(
328
- "etag" => $etag,
329
- "account_id" => $account_id,
330
- "order_status" => $order_status,
331
- "products" => $mage_productIds['products'],
332
- "storeid" => $mage_productIds['store'],
333
- "order_currency" => $order_currency_code ,
334
- "order_address" => $order_adress,
335
- "order_country" => $order_country,
336
- "order_country_iso" => $order_country_iso ,
337
- "order_address" => $order_address ,
338
- "order_postalCode" => $order_postalCode ,
339
- "order_customer" => $order_first_name ,
340
- "order_lastname" => $order_last_name ,
341
- "order_customer_email" => $order_customer_email ,
342
- "order_customer_phone" => $this->getPhone($order_customer_phone, $order_customer_mobile) ,
343
- "order_comment" => $order_comment ,
344
- "order_company" => $order_company ,
345
- "shipping_city" => $shipping_city ,
346
- "shipping_country" => $shipping_country ,
347
- "shipping_country_iso" => $shipping_country_iso ,
348
- "shipping_address" => $shipping_address ,
349
- "shipping_name" => $shipping_first_name ,
350
- "shipping_lastname" => $shipping_last_name ,
351
- "shipping_postalCode" => $shipping_postalCode ,
352
- "shipping_region" =>$shipping_region,
353
- "shipping_email" => $shipping_email ,
354
- "shipping_phone" => $this->getPhone($shipping_phone, $shipping_mobile) ,
355
- "shipping_company" => $shipping_company ,
356
- "order_totalPrice" => $order_totalPrice ,
357
- "order_shippingPrice" => $order_shippingPrice ,
358
- "order_city" => $order_city,
359
- "order_region" => $order_region,
360
- "marketplace" => $marketplace,
361
- "discounts" => $mage_productIds['discounts'],
362
- "marketplace_business_code" => $marketplace_business_code
363
- );
364
365
366
@@ -384,7 +389,7 @@
384
$BeezupMageOrder = new BeezupMageOrders($id_order);
385
$BeezupMageOrder->setData(array("shipping" =>(float) $order_data['order_shippingPrice']));
386
$BeezupMageOrder->updateShippingInfo();
387
- } else {
388
//if not we create order
389
390
@@ -395,14 +400,14 @@
395
}
396
397
398
- } else {
399
//order could not be imported
400
401
402
}
403
404
405
- } else {
406
//etag has not changed
407
$this->debugLog("Order Etag has not changed");
408
@@ -434,7 +439,7 @@
434
$oPagination = $orderList->getPaginationResult();
435
if(!empty($oPagination)) {
436
$oLinksTotal = $oPagination->getLinks();
437
- } else {
438
$configModel = Mage::getModel('core/config');
439
$configModel->saveConfig('beezup/marketplace/sync_status',0);
440
die("No more orders to import");
@@ -483,11 +488,11 @@
483
$beezup_comission = 0;
484
}
485
$updateData = array("beezup_status" => $data['order_status'],
486
- "beezup_last_modification_date" => $beezup_last_modification_date,
487
- "beezup_marketplace_last_modification_date" => $beezup_marketplace_last_modification_date ,
488
- "beezup_total_paid" => $oLink->getOrderTotalPrice()." ".$data['order_currency'],
489
- "beezup_comission" => $beezup_comission,
490
- "beezup_marketplace_status" => $oLink->getOrderStatusMarketPlaceStatus());
491
$orderId = $order->getId();
492
$beezupMageOrder = new BeezupMageOrders($orderId);
493
$beezupMageOrder->setData($updateData);
@@ -505,7 +510,7 @@
505
if(empty($phone) || $phone == "") {
506
$retorno = $phone2;
507
508
- } else {
509
$retorno .= " - ".$phone2;
510
}
511
}
@@ -524,14 +529,14 @@
524
if(!empty($add2)) {
525
if(empty($add1)) {
526
$retorno .= $order->getOrderBuyerAddressLine2();
527
- } else {
528
$retorno .= " - ". $order->getOrderBuyerAddressLine2();
529
}
530
}
531
if(!empty($add3)){
532
if(empty($add1) && empty($add2)) {
533
$retorno .= $order->getOrderBuyerAddressLine3();
534
- } else {
535
$retorno .= " - ". $order->getOrderBuyerAddressLine3();
536
}
537
}
@@ -550,14 +555,14 @@
550
if(!empty($add2)) {
551
if(empty($add1)) {
552
$retorno .= $order->getOrderShippingAddressLine2();
553
- } else {
554
$retorno .= " - ". $order->getOrderShippingAddressLine2();
555
}
556
}
557
if(!empty($add3)){
558
if(empty($add1) && empty($add2)) {
559
$retorno .= $order->getOrderShippingAddressLine3();
560
- } else {
561
$retorno .= " - ". $order->getOrderShippingAddressLine3();
562
}
563
}
@@ -595,27 +600,27 @@
595
596
597
$addressData = array(
598
- 'billing_firstname' => ($data['order_customer']) ? $data['order_customer'] : "empty",
599
- 'billing_lastname' => ($data['order_lastname']) ? $data['order_lastname'] : "empty",
600
- 'billing_street' => ($data['order_address']) ? $data['order_address'] : "empty",
601
- 'billing_city' => ($data['order_city']) ? $data['order_city'] : "empty",
602
- 'billing_postcode' => ($data['order_postalCode']) ? $data['order_postalCode'] : "empty",
603
- 'billing_telephone' => ($data['order_customer_phone']) ? $data['order_customer_phone'] : "empty",
604
- 'billing_country_id' => ($data['order_country_iso']) ? $data['order_country_iso'] : "empty",
605
- 'billing_region_id' => ($data['order_region ']) ? substr($data['order_region '], 0,2) : "EM",
606
- 'shipping_firstname' => ($data['shipping_name']) ? $data['shipping_name'] : "empty",
607
- 'shipping_lastname' => ($data['shipping_lastname']) ? $data['shipping_lastname'] : "empty",
608
- 'shipping_street' => ($data['shipping_address']) ? $data['shipping_address'] : "empty",
609
- 'shipping_city' => ($data['shipping_city']) ? $data['shipping_city'] : "empty",
610
- 'shipping_postcode' => ($data['shipping_postalCode']) ? $data['shipping_postalCode'] : "empty",
611
- 'shipping_telephone' => ($data['shipping_phone']) ? $data['shipping_phone'] : "empty",
612
- 'shipping_country_id' => ($data['shipping_country_iso']) ? $data['shipping_country_iso'] : "empty",
613
'shipping_region_id' => ($data['shipping_region']) ? substr($data['shipping_region'], 0, 2) : "EM" // id from directory_country_region table
614
);
615
616
$shippingData = array(
617
-
618
- );
619
// Get the id of the orders shipping address
620
$orderId = $order->getId();
621
$beezupMageOrder = new BeezupMageOrders($orderId);
@@ -652,7 +657,7 @@
652
$Mageorder = Mage::getModel('sales/order')->loadByIncrementId($this->orderid);
653
if ($Mageorder->getId()) {
654
return $Mageorder;
655
- } else {
656
//we get order from marketplace orderid
657
$orderInc = $this->checkMarketOrderExists($this->orderid);
658
if($orderInc) {
@@ -693,256 +698,256 @@
693
if(!$mage_storeid) {
694
695
if(strpos($marketplace_orderid,'INTERETBCA') !== false || strpos($marketplace_orderid,'interetbca') !== false) { }
696
- else {
697
- $this->log->LogError($this->orderid." | No mapping for store ".$beezup_store);
698
- $this->log2->LogError($this->orderid." | No mapping for store ".$beezup_store);
699
- return false;
700
- }
701
-
702
- }
703
// $retorno['store'] = 1;
704
-
705
- $product_ImportedMerchantId = $item->getOrderItemMerchantImportedProductId();
706
- $product_MerchantId = $item->getOrderItemMerchantProductId();
707
-
708
- $product_quantity = $item->getOrderItemQuantity();
709
- $product_price = $item->getOrderItemItemPrice();
710
- $product_title = $item->getOrderItemTitle();
711
- $product_image = $item->getOrderItemImageUrl();
712
- if(strpos($marketplace_orderid,'INTERETBCA') !== false || strpos($marketplace_orderid,'interetbca') !== false) {
713
- $retorno['discounts']= $item->getOrderItemTotalPrice();
714
} else {
715
- $retorno['store'] = $mage_storeid;
716
- $this->debugLog("Store Matching succesful, Beezup Store: ".$beezup_store." , Magento Store Id: ".$mage_storeid);
717
- $product = $this->getMageProduct($product_ImportedMerchantId , $product_MerchantId , $beezup_store );
718
- if($product) {
719
- $mage_productId = $product->getId();
720
- $stocklevel = (int)Mage::getModel('cataloginventory/stock_item')
721
- ->loadByProduct($product)->getQty();
722
-
723
- $retorno['products'][] = array("id" => $mage_productId, "qty" => $product_quantity, "price" => $product_price, "curr_stock" => $stocklevel);
724
//producto existe
725
} else {
726
//vendria if de si activada opcion de crear producto creamos
727
- if(!$this->debug) {
728
- return false;
729
}
730
- $product_data = array(
731
- "sku" => $product_ImportedMerchantId,
732
- "sku2" => $product_MerchantId,
733
- "qty" => $product_quantity,
734
- "price" => $product_price,
735
- "title" => $product_title,
736
- "image" => $product_image,
737
- "storeId" => $mage_storeid
738
- );
739
- $product = $this->createProduct($product_data);
740
- if(!$product) {
741
- return false;
742
- }
743
- $stocklevel = (int)Mage::getModel('cataloginventory/stock_item')
744
- ->loadByProduct($product)->getQty();
745
- $mage_productId = $product->getId();
746
- $retorno['products'][] = array("id" => $mage_productId, "qty" => $product_quantity, "price" => $product_price, "curr_stock" => $stocklevel);
747
- }
748
}
749
- }
750
-
751
- return $retorno;
752
- }
753
-
754
-
755
-
756
- public function matchProductAttributes($importedId, $storeId) {
757
- $product = null;
758
- $helper = Mage::helper('beezup');
759
- $attributes = $helper->getConfig('beezup/marketplace/attributes');
760
- $attributes = unserialize ($attributes);
761
-
762
- foreach($attributes['attributes'][$storeId ] as $attribute) {
763
$att = explode("|", $attribute);
764
if($storeId == $att[1]) {
765
-
766
- $product=Mage::getModel('catalog/product')->loadByAttribute($att[0],$importedId);
767
- if($product) {
768
- break;
769
- }
770
- }
771
- }
772
-
773
- return $product;
774
}
775
-
776
-
777
-
778
- public function getMageProduct($importedId, $merchantId, $storeId){
779
- try {
780
$product=Mage::getModel('catalog/product')->load($importedId);
781
if (!$product->getId() || $product->getId() !== $importedId ){
782
- $product = $this->matchProductAttributes($importedId, $storeId);
783
- if($product == null || !is_object($product)) {
784
- $product=Mage::getModel('catalog/product')->load($merchantId);
785
- if(!$product->getId() || $product->getId() !== $merchantId ) {
786
- $product = $this->matchProductAttributes($merchantId, $storeId);
787
-
788
- }
789
- }
790
}
791
792
if(is_object($product)) {
793
- if($product->getId()) {
794
- $this->debugLog("Product Matching succesful, Beezup Imported Id: ".$importedId." , Magento Product Id: ".$product->getId());
795
- return $product;
796
- }}
797
- $this->log->LogError($this->orderid. "| No Product Matching, Product ".$importedId." could not be found");
798
- $this->log2->LogError($this->orderid. "| No Product Matching, Product ".$importedId." could not be found");
799
- return false;
800
}catch(Exception $e){
801
- $this->log->LogError($this->orderid. "| Product ".$importedId." could not be found, error: ".$e->getMessage());
802
- $this->log2->LogError($this->orderid. "| Product ".$importedId." could not be found, error: ".$e->getMessage());
803
- return false;
804
//error no se pudo crear la orden
805
-
806
- }
807
}
808
-
809
-
810
- public function checkOrderStore($storeId ) {
811
$helper = Mage::helper('beezup');
812
$stores = $helper->getConfig('beezup/marketplace/stores');
813
$stores = unserialize ($stores);
814
foreach($stores as $store) {
815
- if(isset($store[$storeId]) && $store[$storeId] > 0) {
816
- return $store[$storeId];
817
- }
818
}
819
return false;
820
- }
821
-
822
-
823
-
824
/**
825
* @return BeezupOMOrderService
826
*/
827
public function getOrderService(){
828
- if ($this->oOrderService === null){
829
- $this->oOrderService = $this->createOrderService();
830
// enchufamos debug mode, esta activado? false true $this->oOrderService->setDebugMode(false);
831
- }
832
- return $this->oOrderService;
833
}
834
835
/**
836
* @return BeezupOMOrderService
837
*/
838
protected function createOrderService(){
839
-
840
- return new BeezupOMOrderService($this->createRepository() );
841
}
842
843
protected function createRepository() {
844
- if ($this->repository == null) {
845
- $this->repository = new BeezupRepository();
846
- }
847
- return $this->repository;
848
-
849
}
850
851
852
853
854
private function createCustomer($customer_email , $data) {
855
- $password = $this->orderid;
856
- $this->debugLog("Creating new Customer");
857
- $customer = Mage::getModel('customer/customer');
858
- $customer->setWebsiteId(Mage::app()->getWebsite()->getId());
859
- $customer->loadByEmail($customer_email);
860
- if(!$customer->getId()) {
861
- $customer->setEmail($customer_email);
862
- $customer->setFirstname($data['firstname']);
863
- $customer->setLastname($data['lastname']);
864
- $customer->setPassword($password);
865
- try {
866
- $customer->save();
867
- $customer->setConfirmation(null);
868
- $customer->save();
869
- $this->debugLog("Customer created succesfully");
870
- return $customer;
871
//Make a "login" of new customer
872
// Mage::getSingleton('customer/session')->loginById($customer->getId());
873
- }
874
-
875
- catch (Exception $ex) {
876
//Zend_Debug::dump($ex->getMessage());
877
//GUARDAR ERROR CREACION USUARIO
878
- $this->log2->LogError($this->orderid. " | Customer importation failed: ".$ex->getMessage());
879
- return false;
880
- }
881
-
882
- } else {
883
- $this->debugLog("Creating already exists, returning customer object");
884
- return $customer;
885
- }
886
}
887
888
889
890
public function addOrder($data, $oLink, $stop = false) {
891
-
892
-
893
- try {
894
- $helper = Mage::helper('beezup');
895
- $addStock = $helper->getConfig('beezup/marketplace/available_products');
896
- $baseCurrencyCode = Mage::app()->getStore()->getBaseCurrencyCode();
897
- $quote = Mage::getModel('sales/quote')
898
- ->setStoreId($data['storeid']);
899
- $quote->setCustomerEmail($data['order_customer_email']);
900
-
901
-
902
- $currency = Mage::getModel('directory/currency')->load($data['order_currency']);
903
- $quote->setForcedCurrency($currency);
904
-
905
- $blnCreate = true;
906
- $total_new_price = 0;
907
- foreach($data['products'] as $prod) {
908
- if($prod['qty']==0) {
909
- $blnCreate = false;
910
- break;
911
- }
912
- $prod_totality_price = $prod['price']*$prod['qty'];
913
- $total_new_price = $total_new_price + $prod_totality_price;
914
- $product = Mage::getModel('catalog/product')->load($prod['id']);
915
- $buyInfo = array(
916
- 'qty' => $prod['qty'],
917
- );
918
- $this->debugLog("Adding ".$prod['qty']." product/s with id ".$product->getId()." to order, with Beezup Price: ".$prod['price']);
919
//echo "Product ".$product->getId()."<br><br>";
920
//para no perder stock:
921
//Mage::getModel('cataloginventory/stock')->backItemQty($productId,$new_qty);
922
-
923
-
924
- if($addStock == 1) {
925
- $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product);
926
-
927
- if ($stock->getQty() < $prod['qty'] && $product->getStockItem()->getMaxSaleQty() >= $prod['qty']) {
928
- $this->debugLog("Product ".$product->getId()." Stock = 0, Updating to ".$prod['qty']." to generate Order");
929
// Mage::getModel('cataloginventory/stock')->backItemQty($product->getId(),$prod['qty']);
930
//$this->_updateStocks(array("id_product" => $product->getId(), "qty" => $prod['qty']));
931
- $product->setStockData(
932
- array(
933
- 'is_in_stock' => 1,
934
- 'qty' => $prod['qty'],
935
- 'manage_stock' => 1,
936
- 'use_config_notify_stock_qty' => 1
937
- )
938
- );
939
- $product->save();
940
- $product = Mage::getModel('catalog/product')->load($product->getId());
941
-
942
- }
943
- }
944
//fin para no perder stock
945
-
946
/*
947
$tax_class = $product->getTaxClassId();
948
$product->setTaxClassId(0);
@@ -969,35 +974,35 @@
969
970
$product->getResource()->saveAttribute($product, 'tax_class_id');
971
*/
972
- }
973
-
974
- if($blnCreate) {
975
$addressData = array(
976
- 'firstname' => ($data['order_customer']) ? $data['order_customer'] : "empty",
977
- 'lastname' => ($data['order_lastname']) ? $data['order_lastname'] : "empty",
978
- 'street' => ($data['order_address']) ? $data['order_address'] : "empty",
979
- 'city' => ($data['order_city']) ? $data['order_city'] : "empty",
980
- 'postcode' => ($data['order_postalCode']) ? $data['order_postalCode'] : "empty",
981
- 'telephone' => ($data['order_customer_phone']) ? $data['order_customer_phone'] : "empty",
982
- 'country_id' => ($data['order_country_iso']) ? $data['order_country_iso'] : "empty",
983
'region_id' => ($data['order_region ']) ? substr($data['order_region '], 0,2) : "EM"// id from directory_country_region table
984
);
985
986
$shippingData = array(
987
- 'firstname' => ($data['shipping_name']) ? $data['shipping_name'] : "empty",
988
- 'lastname' => ($data['shipping_lastname']) ? $data['shipping_lastname'] : "empty",
989
- 'street' => ($data['shipping_address']) ? $data['shipping_address'] : "empty",
990
- 'city' => ($data['shipping_city']) ? $data['shipping_city'] : "empty",
991
- 'postcode' => ($data['shipping_postalCode']) ? $data['shipping_postalCode'] : "empty",
992
- 'telephone' => ($data['shipping_phone']) ? $data['shipping_phone'] : "empty",
993
- 'country_id' => ($data['shipping_country_iso']) ? $data['shipping_country_iso'] : "empty",
994
'region_id' => ($data['shipping_region']) ? substr($data['shipping_region'], 0, 2) : "EM" // id from directory_country_region table
995
);
996
997
if($this->blnCreateCustomer) {
998
-
999
- $mage_customer = $this->createCustomer($data['order_customer_email'], $addressData);
1000
- $quote->assignCustomer($mage_customer);
1001
}
1002
1003
@@ -1006,7 +1011,7 @@
1006
$shippingAddress = $quote->getShippingAddress()->addData($shippingData);
1007
$shipping_cost = (float) $data['order_shippingPrice'];
1008
if($data['order_shippingPrice'] == 0) {
1009
- $shipping_cost = 20000;
1010
}
1011
$total_new_price = $total_new_price + $data['order_shippingPrice'] ;
1012
Mage::unregister('shipping_cost');
@@ -1059,7 +1064,7 @@
1059
$beezup_comission = $oLink->getOrderTotalCommission()." ".$data['order_currency'];
1060
$tot_comm = $oLink->getOrderTotalCommission();
1061
if(empty($tot_comm ) || $tot_comm == 0) {
1062
- $beezup_comission = 0;
1063
}
1064
$query = "UPDATE {$table} SET beezup_marketplace = '{$marketplace}', beezup_name = '{$beezup_account_id}', beezup_order = 1, beezup_market_order_id = '{$market_order_id}',
1065
beezup_order_id = '{$beezup_order_id}', beezup_status = '{$beezup_status}', beezup_last_modification_date = '{$beezup_last_modification_date}',
@@ -1069,55 +1074,55 @@
1069
$writeConnection->query($query);
1070
$disc_price = 0;
1071
if(!empty($data['discounts']) && $data['discounts'] >0) {
1072
-
1073
-
1074
- $disc_price = round($data['discounts'],2);
1075
- $total_new_price = $total_new_price+$disc_price;
1076
- $table_address = $resource->getTableName("sales/quote_address");
1077
-
1078
- $query = "update {$table_address} set beezup_fee = '{$disc_price}' where quote_id = '{$quoteId}' and address_type = 'shipping'";
1079
- $writeConnection->query($query);
1080
- $this->debugLog("Adding CDISCOUNT products with total price: ".$disc_price);
1081
}
1082
1083
//if order id exists and has been created
1084
if ($orderid)
1085
{
1086
//we send order id to beezup
1087
- $this->debugLog("Sending Magento Order Id to Beezup, Magento Order Id: ".$orderid);
1088
- $oResult = new BeezupOMSetOrderIdValues ();
1089
- $oResult->setOrderMerchantOrderId ( $orderid )->setOrderMerchantECommerceSoftwareName ( 'Magento' )->setOrderMerchantECommerceSoftwareVersion ( Mage::getVersion() );
1090
- $sendRequest = $this->getOrderService()->getClientProxy()->setOrderMerchantIdByLink($oLink->getLinkByRel('setMerchantOrderId'), $oResult);
1091
}
1092
1093
$grand_total = $order->getGrandTotal();
1094
$beezup_price = $oLink->getOrderTotalPrice() - $disc_price;
1095
if($grand_total != (float) $beezup_price && $beezup_price > 0) {
1096
- $order->setGrandTotal((float) $beezup_price);
1097
- $order->setBaseGrandTotal((float) $beezup_price);
1098
- $diff = (((float) $beezup_price) - $grand_total);
1099
-
1100
- $order->setTaxAmount($order->getTaxAmount() + $diff);
1101
- $order->save();
1102
}elseif($grand_total != (float)$beezup_price && $beezup_price < 1) {
1103
-
1104
- $order->setGrandTotal((float) $total_new_price);
1105
- $order->setBaseGrandTotal((float) $total_new_price);
1106
- $diff = (((float) $total_new_price) - $grand_total);
1107
-
1108
- $order->setTaxAmount($order->getTaxAmount() + $diff);
1109
- $order->save();
1110
}
1111
1112
$products = Mage::getResourceModel('sales/order_item_collection')
1113
->setOrderFilter($orderid);
1114
foreach($products as $product) {
1115
- $product->setBaseOriginalPrice($product->getOriginalPrice());
1116
- $product->setBaseTaxAmount($product->getTaxAmount());
1117
- $product->setBaseTaxInvoiced($product->getTaxAmount());
1118
- $product->setBasePriceInclTax($product->getPriceInclTax());
1119
- $product->setBaseRowTotalInclTax($product->getRowTotalInclTax());
1120
- $product->save();
1121
}
1122
$order->setBaseTaxAmount($order->getTaxAmount());
1123
$order->setBaseTaxInvoiced($order->getTaxAmount());
@@ -1130,71 +1135,71 @@
1130
$this->setStatus($data['order_status'], $order);
1131
$this->mage_order_id = $orderid;
1132
$this->debugLog("Order imported succesfully, Magento Order Id: ".$orderid);
1133
- } else {
1134
//product stock = 0 we dont create order
1135
$this->log->LogError($this->orderid. "| Order ".$data['market_place_order_id']." could not be imported, error: Stock from Beezup product = 0 ");
1136
$this->log2->LogError($this->orderid. "| Order ".$data['market_place_order_id']." could not be imported, error: Stock from Beezup product = 0 ");
1137
- }
1138
- }catch(Exception $e){
1139
-
1140
-
1141
- if($stop) {
1142
$this->log->LogError($this->orderid. "| Order ".$data['market_place_order_id']." could not be imported, error: ".$e->getMessage());
1143
$this->log2->LogError($this->orderid. "| Order ".$data['market_place_order_id']." could not be imported, error: ".$e->getMessage());
1144
$this->restoreStock($data);
1145
- } else {
1146
$this->debugLog("Order Import failed, Trying to import Order Again");
1147
$this->addOrder($data, $oLink, true);
1148
1149
- }
1150
//error no se pudo crear la orden
1151
-
1152
- }
1153
-
1154
-
1155
-
1156
- }
1157
-
1158
-
1159
-
1160
- public function restoreStock($data) {
1161
-
1162
- try {
1163
- foreach($data['products'] as $prod) {
1164
$product = Mage::getModel('catalog/product')->load($prod['id']);
1165
$stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product);
1166
if ($stock->getQty() != $prod['curr_stock'] ) {
1167
- $this->debugLog("Restoring Stock from Product ".$product->getId()." to: ".$prod['curr_stock'] ." due to Order Fail");
1168
- $stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product);
1169
- $stockItem->setData('is_in_stock', 0);
1170
- $stockItem->setData('qty', $prod['curr_stock']);
1171
- $stockItem->save();
1172
- $product->save();
1173
}
1174
1175
- }
1176
- } catch(Exception $e){
1177
- $this->log->LogError($this->orderid. "| Failed Restoring Product Stock: ".$e->getMessage());
1178
- $this->log2->LogError($this->orderid. "| Failed Restoring Product Stock: ".$e->getMessage());
1179
- }
1180
-
1181
- }
1182
-
1183
-
1184
-
1185
- private function createProduct($data) {
1186
-
1187
- $sku = $data['sku'];
1188
- if(empty($data['sku'])) {
1189
- $sku = $data['sku2'];
1190
- }
1191
-
1192
- Mage::app()->setCurrentStore($data['storeId']);
1193
- $product = Mage::getModel('catalog/product');
1194
// if(!$product->getIdBySku('testsku61')):
1195
-
1196
- try{
1197
- $product
1198
// ->setStoreId(1) //you can set data in store scope
1199
->setWebsiteIds(array($data['storeId'])) //website ID the product is assigned to, as an array
1200
->setAttributeSetId($product->getDefaultAttributeSetId()) //ID of a attribute set named 'default'
@@ -1229,22 +1234,22 @@
1229
$product->save();
1230
return $product;
1231
1232
- }catch(Exception $e){
1233
//log exception
1234
$this->log->LogError($this->orderid."| Product ".$sku." could not be created, error: ".$e->getMessage());
1235
$this->log2->LogError($this->orderid."| Product ".$sku." could not be created, error: ".$e->getMessage());
1236
return false;
1237
- }
1238
- }
1239
-
1240
-
1241
-
1242
- public function setStatus($status, $order) {
1243
- $helper = Mage::helper('beezup');
1244
- $retorno = "";
1245
- $blnCancel = false;
1246
- $blnHold = false;
1247
- switch($status) {
1248
case "New" :
1249
$this->debugLog("Setting Order Status to New");
1250
$retorno = $helper->getConfig('beezup/marketplace/status_new');
@@ -1278,100 +1283,100 @@
1278
$this->payOrder($order);
1279
break;
1280
1281
- }
1282
- $order->setData('state',$retorno);
1283
- $order->setStatus($retorno);
1284
- $history = $order->addStatusHistoryComment('Order was set to '.$retorno.' by Beezup.', false);
1285
- $history->setIsCustomerNotified(false);
1286
- $order->save();
1287
- if($blnCancel) {
1288
$order->cancel()->save();
1289
- }
1290
- if($blnHold) {
1291
$order->hold()->save();
1292
- }
1293
-
1294
- return $retorno;
1295
-
1296
- }
1297
-
1298
-
1299
- public function getStatus($status1) {
1300
- $helper = Mage::helper('beezup');
1301
- $retorno = "";
1302
- $status = strtolower($status1);
1303
-
1304
- if($status == strtolower($helper->getConfig('beezup/marketplace/status_new') )) {
1305
$retorno = "New";
1306
1307
- } elseif($status == strtolower($helper->getConfig('beezup/marketplace/status_progress') ) ){
1308
$retorno = "InProgress";
1309
1310
1311
- }
1312
- elseif($status == strtolower($helper->getConfig('beezup/marketplace/status_aborted') )) {
1313
1314
$retorno = "Aborted" ;
1315
- }
1316
- elseif($status == strtolower($helper->getConfig('beezup/marketplace/status_closed') )) {
1317
$retorno = "Closed";
1318
1319
- }
1320
- elseif($status == strtolower($helper->getConfig('beezup/marketplace/status_cancelled')) ) {
1321
1322
$retorno = "Canceled";
1323
- }
1324
- elseif($status == strtolower($helper->getConfig('beezup/marketplace/status_shipped') )) {
1325
1326
$retorno = "Shipped";
1327
- }
1328
-
1329
-
1330
- return $retorno;
1331
-
1332
- }
1333
-
1334
-
1335
- public function checkMarketOrderExists($orderid) {
1336
- $resource = Mage::getSingleton('core/resource');
1337
- $readConnection = $resource->getConnection('core_read');
1338
- $table = $resource->getTableName('sales/order_grid');
1339
- $query = 'SELECT increment_id FROM ' . $table . ' WHERE beezup_order = 1 and beezup_market_order_id = \''
1340
- . $orderid . '\' LIMIT 1';
1341
- $order = $readConnection->fetchOne($query);
1342
- if($order && !empty($order) && $this->orderId !== "") {
1343
return $order;
1344
- }
1345
- return false;
1346
-
1347
- }
1348
-
1349
- public function payOrder($order) {
1350
- try {
1351
$this->debugLog("Generating Order Payment Invoice");
1352
if($order->canInvoice()) {
1353
- $invoice = $order->prepareInvoice()
1354
- ->setTransactionId($order->getId())
1355
- ->addComment("Invoice created from Beezup.")
1356
- ->register()
1357
- ->pay();
1358
- $transaction_save = Mage::getModel('core/resource_transaction')
1359
- ->addObject($invoice)
1360
- ->addObject($invoice->getOrder());
1361
- $transaction_save->save();
1362
- $this->debugLog("Order Payment Invoice Generated Succesfully");
1363
- }
1364
}
1365
- catch(Exception $e){
1366
//log exception
1367
$this->log->LogError($this->orderid."| Order Payment Invoice could not be generated, error: ".$e->getMessage());
1368
$this->log2->LogError($this->orderid."| Order Payment Invoice could not be generated, error: ".$e->getMessage());
1369
- }
1370
- }
1371
-
1372
-
1373
-
1374
-
1375
-
1376
-
1377
- }
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
+ $shiiping_disabled = Mage::getStoreConfig('carriers/flatrate/active');
69
70
+ $this->account_id = $account_id;
71
+ $this->marketplace_code = $marketplace_code;
72
+ $this->beezup_order_id = $beezup_order_id;
73
+ $orderResponse = $this->getBeezupOrder();
74
+ if($orderResponse) {
75
76
+ if($shiiping_disabled == 0) {
77
+ Mage::getConfig()
78
+ ->saveConfig('carriers/flatrate/active', 1)
79
+ ->cleanCache();
80
+ Mage::app()->reinitStores();
81
+ }
82
+ $this->createOrder($orderResponse);
83
+ if($shiiping_disabled == 0) {
84
+ Mage::getConfig()
85
+ ->saveConfig('carriers/flatrate/active', 0)
86
+ ->cleanCache();
87
+ Mage::app()->reinitStores();
88
+ }
89
+ $configModel->saveConfig('beezup/marketplace/sync_status',0);
90
+ if($this->mage_order_id) {
91
+ echo "<script>window.location='".Mage::helper('adminhtml')->getUrl("adminhtml/sales_order/view", array('order_id'=> $this->mage_order_id))."';</script>";
92
}
93
+ // die("Order Importation finalized");
94
95
}
96
+
97
}
98
+ $configModel->saveConfig('beezup/marketplace/sync_status',0);
99
+ //die("Error, Order data incorrect");
100
+ echo $this->_showLog();
101
+ }
102
+
103
+ public function _showLog() {
104
+ $logDir = Mage::getBaseDir('base').'/beezup/';
105
// $log1 = file_get_contents();
106
+ $ret = array();
107
+ if (file_exists($logDir."/log.txt")) {
108
+ $f = fopen($logDir."/log.txt", 'r');
109
+
110
+ if ($f) {
111
+ while (!feof($f)) {
112
+ $ret[] = fgetcsv($f, 0, '|');
113
}
114
+ fclose($f);
115
}
116
}
117
+ array_slice(array_reverse($ret), 1, 10);
118
119
+ return $this->_getTable($ret);
120
121
+ }
122
+
123
+
124
+ public function _getTable($data) {
125
+ $url = Mage::getBaseUrl( Mage_Core_Model_Store::URL_TYPE_WEB, true );
126
+ $html = "<td></td><td></td><tr></tr></tbody></table>
127
+
128
+ <div class='grid' style=' height: 600px;overflow-y: scroll;padding: 16px;border: 3px solid #e6e6e6;' id='marketPlaceLogBlock'>";
129
$html .= '<p>'. Mage::helper('beezup')->__('For full logs see here:').' <a href="'.$url .'beezup/log/load" target="_blank">'.$url .'beezup/log/load</a></p>';
130
$html .= "<table class='data' style='margin-top:0px;width:100%;'>";
131
$html .= "<tr class='headings'>";
217
$configModel->saveConfig('beezup/marketplace/sync_status',0);
218
echo "OM Importation finalized succesfully";
219
220
+ } else {
221
222
echo "Order Importation is already being executed";
223
}
321
elseif(!filter_var($order_customer_email, FILTER_VALIDATE_EMAIL)) {
322
$order_customer_email = $this->generateEmail($final_order);
323
}
324
+ if($order_country_iso == "FX" || $order_country_iso == "fx") {
325
+ $order_country_iso = "FR";
326
+ }
327
+ if($shipping_country_iso == "FX" || $shipping_country_iso == "fx") {
328
+ $shipping_country_iso = "FR";
329
+ }
330
$mage_productIds = $this->prescanOrder($final_order);
331
if($mage_productIds) {
332
$order_data = array(
333
+ "etag" => $etag,
334
+ "account_id" => $account_id,
335
+ "order_status" => $order_status,
336
+ "products" => $mage_productIds['products'],
337
+ "storeid" => $mage_productIds['store'],
338
+ "order_currency" => $order_currency_code ,
339
+ "order_address" => $order_adress,
340
+ "order_country" => $order_country,
341
+ "order_country_iso" => $order_country_iso ,
342
+ "order_address" => $order_address ,
343
+ "order_postalCode" => $order_postalCode ,
344
+ "order_customer" => $order_first_name ,
345
+ "order_lastname" => $order_last_name ,
346
+ "order_customer_email" => $order_customer_email ,
347
+ "order_customer_phone" => $this->getPhone($order_customer_phone, $order_customer_mobile) ,
348
+ "order_comment" => $order_comment ,
349
+ "order_company" => $order_company ,
350
+ "shipping_city" => $shipping_city ,
351
+ "shipping_country" => $shipping_country ,
352
+ "shipping_country_iso" => $shipping_country_iso ,
353
+ "shipping_address" => $shipping_address ,
354
+ "shipping_name" => $shipping_first_name ,
355
+ "shipping_lastname" => $shipping_last_name ,
356
+ "shipping_postalCode" => $shipping_postalCode ,
357
+ "shipping_region" =>$shipping_region,
358
+ "shipping_email" => $shipping_email ,
359
+ "shipping_phone" => $this->getPhone($shipping_phone, $shipping_mobile) ,
360
+ "shipping_company" => $shipping_company ,
361
+ "order_totalPrice" => $order_totalPrice ,
362
+ "order_shippingPrice" => $order_shippingPrice ,
363
+ "order_city" => $order_city,
364
+ "order_region" => $order_region,
365
+ "marketplace" => $marketplace,
366
+ "discounts" => $mage_productIds['discounts'],
367
+ "marketplace_business_code" => $marketplace_business_code
368
+ );
369
370
371
389
$BeezupMageOrder = new BeezupMageOrders($id_order);
390
$BeezupMageOrder->setData(array("shipping" =>(float) $order_data['order_shippingPrice']));
391
$BeezupMageOrder->updateShippingInfo();
392
+ } else {
393
//if not we create order
394
395
400
}
401
402
403
+ } else {
404
//order could not be imported
405
406
407
}
408
409
410
+ } else {
411
//etag has not changed
412
$this->debugLog("Order Etag has not changed");
413
439
$oPagination = $orderList->getPaginationResult();
440
if(!empty($oPagination)) {
441
$oLinksTotal = $oPagination->getLinks();
442
+ } else {
443
$configModel = Mage::getModel('core/config');
444
$configModel->saveConfig('beezup/marketplace/sync_status',0);
445
die("No more orders to import");
488
$beezup_comission = 0;
489
}
490
$updateData = array("beezup_status" => $data['order_status'],
491
+ "beezup_last_modification_date" => $beezup_last_modification_date,
492
+ "beezup_marketplace_last_modification_date" => $beezup_marketplace_last_modification_date ,
493
+ "beezup_total_paid" => $oLink->getOrderTotalPrice()." ".$data['order_currency'],
494
+ "beezup_comission" => $beezup_comission,
495
+ "beezup_marketplace_status" => $oLink->getOrderStatusMarketPlaceStatus());
496
$orderId = $order->getId();
497
$beezupMageOrder = new BeezupMageOrders($orderId);
498
$beezupMageOrder->setData($updateData);
510
if(empty($phone) || $phone == "") {
511
$retorno = $phone2;
512
513
+ } else {
514
$retorno .= " - ".$phone2;
515
}
516
}
529
if(!empty($add2)) {
530
if(empty($add1)) {
531
$retorno .= $order->getOrderBuyerAddressLine2();
532
+ } else {
533
$retorno .= " - ". $order->getOrderBuyerAddressLine2();
534
}
535
}
536
if(!empty($add3)){
537
if(empty($add1) && empty($add2)) {
538
$retorno .= $order->getOrderBuyerAddressLine3();
539
+ } else {
540
$retorno .= " - ". $order->getOrderBuyerAddressLine3();
541
}
542
}
555
if(!empty($add2)) {
556
if(empty($add1)) {
557
$retorno .= $order->getOrderShippingAddressLine2();
558
+ } else {
559
$retorno .= " - ". $order->getOrderShippingAddressLine2();
560
}
561
}
562
if(!empty($add3)){
563
if(empty($add1) && empty($add2)) {
564
$retorno .= $order->getOrderShippingAddressLine3();
565
+ } else {
566
$retorno .= " - ". $order->getOrderShippingAddressLine3();
567
}
568
}
600
601
602
$addressData = array(
603
+ 'billing_firstname' => ($data['order_customer']) ? $data['order_customer'] : "empty",
604
+ 'billing_lastname' => ($data['order_lastname']) ? $data['order_lastname'] : "empty",
605
+ 'billing_street' => ($data['order_address']) ? $data['order_address'] : "empty",
606
+ 'billing_city' => ($data['order_city']) ? $data['order_city'] : "empty",
607
+ 'billing_postcode' => ($data['order_postalCode']) ? $data['order_postalCode'] : "empty",
608
+ 'billing_telephone' => ($data['order_customer_phone']) ? $data['order_customer_phone'] : "empty",
609
+ 'billing_country_id' => ($data['order_country_iso']) ? $data['order_country_iso'] : "empty",
610
+ 'billing_region_id' => ($data['order_region ']) ? substr($data['order_region '], 0,2) : "EM",
611
+ 'shipping_firstname' => ($data['shipping_name']) ? $data['shipping_name'] : "empty",
612
+ 'shipping_lastname' => ($data['shipping_lastname']) ? $data['shipping_lastname'] : "empty",
613
+ 'shipping_street' => ($data['shipping_address']) ? $data['shipping_address'] : "empty",
614
+ 'shipping_city' => ($data['shipping_city']) ? $data['shipping_city'] : "empty",
615
+ 'shipping_postcode' => ($data['shipping_postalCode']) ? $data['shipping_postalCode'] : "empty",
616
+ 'shipping_telephone' => ($data['shipping_phone']) ? $data['shipping_phone'] : "empty",
617
+ 'shipping_country_id' => ($data['shipping_country_iso']) ? $data['shipping_country_iso'] : "empty",
618
'shipping_region_id' => ($data['shipping_region']) ? substr($data['shipping_region'], 0, 2) : "EM" // id from directory_country_region table
619
);
620
621
$shippingData = array(
622
+
623
+ );
624
// Get the id of the orders shipping address
625
$orderId = $order->getId();
626
$beezupMageOrder = new BeezupMageOrders($orderId);
657
$Mageorder = Mage::getModel('sales/order')->loadByIncrementId($this->orderid);
658
if ($Mageorder->getId()) {
659
return $Mageorder;
660
+ } else {
661
//we get order from marketplace orderid
662
$orderInc = $this->checkMarketOrderExists($this->orderid);
663
if($orderInc) {
698
if(!$mage_storeid) {
699
700
if(strpos($marketplace_orderid,'INTERETBCA') !== false || strpos($marketplace_orderid,'interetbca') !== false) { }
701
+ else {
702
+ $this->log->LogError($this->orderid." | No mapping for store ".$beezup_store);
703
+ $this->log2->LogError($this->orderid." | No mapping for store ".$beezup_store);
704
+ return false;
705
+ }
706
+
707
+ }
708
// $retorno['store'] = 1;
709
+
710
+ $product_ImportedMerchantId = $item->getOrderItemMerchantImportedProductId();
711
+ $product_MerchantId = $item->getOrderItemMerchantProductId();
712
+
713
+ $product_quantity = $item->getOrderItemQuantity();
714
+ $product_price = $item->getOrderItemItemPrice();
715
+ $product_title = $item->getOrderItemTitle();
716
+ $product_image = $item->getOrderItemImageUrl();
717
+ if(strpos($marketplace_orderid,'INTERETBCA') !== false || strpos($marketplace_orderid,'interetbca') !== false) {
718
+ $retorno['discounts']= $item->getOrderItemTotalPrice();
719
} else {
720
+ $retorno['store'] = $mage_storeid;
721
+ $this->debugLog("Store Matching succesful, Beezup Store: ".$beezup_store." , Magento Store Id: ".$mage_storeid);
722
+ $product = $this->getMageProduct($product_ImportedMerchantId , $product_MerchantId , $beezup_store );
723
+ if($product) {
724
+ $mage_productId = $product->getId();
725
+ $stocklevel = (int)Mage::getModel('cataloginventory/stock_item')
726
+ ->loadByProduct($product)->getQty();
727
+
728
+ $retorno['products'][] = array("id" => $mage_productId, "qty" => $product_quantity, "price" => $product_price, "curr_stock" => $stocklevel);
729
//producto existe
730
} else {
731
//vendria if de si activada opcion de crear producto creamos
732
+ if(!$this->debug) {
733
+ return false;
734
+ }
735
+ $product_data = array(
736
+ "sku" => $product_ImportedMerchantId,
737
+ "sku2" => $product_MerchantId,
738
+ "qty" => $product_quantity,
739
+ "price" => $product_price,
740
+ "title" => $product_title,
741
+ "image" => $product_image,
742
+ "storeId" => $mage_storeid
743
+ );
744
+ $product = $this->createProduct($product_data);
745
+ if(!$product) {
746
+ return false;
747
+ }
748
+ $stocklevel = (int)Mage::getModel('cataloginventory/stock_item')
749
+ ->loadByProduct($product)->getQty();
750
+ $mage_productId = $product->getId();
751
+ $retorno['products'][] = array("id" => $mage_productId, "qty" => $product_quantity, "price" => $product_price, "curr_stock" => $stocklevel);
752
}
753
}
754
+ }
755
+
756
+ return $retorno;
757
+ }
758
+
759
+
760
+
761
+ public function matchProductAttributes($importedId, $storeId) {
762
+ $product = null;
763
+ $helper = Mage::helper('beezup');
764
+ $attributes = $helper->getConfig('beezup/marketplace/attributes');
765
+ $attributes = unserialize ($attributes);
766
+
767
+ foreach($attributes['attributes'][$storeId ] as $attribute) {
768
$att = explode("|", $attribute);
769
if($storeId == $att[1]) {
770
+
771
+ $product=Mage::getModel('catalog/product')->loadByAttribute($att[0],$importedId);
772
+ if($product) {
773
+ break;
774
+ }
775
}
776
+ }
777
+
778
+ return $product;
779
+ }
780
+
781
+
782
+
783
+ public function getMageProduct($importedId, $merchantId, $storeId){
784
+ try {
785
$product=Mage::getModel('catalog/product')->load($importedId);
786
if (!$product->getId() || $product->getId() !== $importedId ){
787
+ $product = $this->matchProductAttributes($importedId, $storeId);
788
+ if($product == null || !is_object($product)) {
789
+ $product=Mage::getModel('catalog/product')->load($merchantId);
790
+ if(!$product->getId() || $product->getId() !== $merchantId ) {
791
+ $product = $this->matchProductAttributes($merchantId, $storeId);
792
+
793
+ }
794
+ }
795
}
796
797
if(is_object($product)) {
798
+ if($product->getId()) {
799
+ $this->debugLog("Product Matching succesful, Beezup Imported Id: ".$importedId." , Magento Product Id: ".$product->getId());
800
+ return $product;
801
+ }}
802
+ $this->log->LogError($this->orderid. "| No Product Matching, Product ".$importedId." could not be found");
803
+ $this->log2->LogError($this->orderid. "| No Product Matching, Product ".$importedId." could not be found");
804
+ return false;
805
}catch(Exception $e){
806
+ $this->log->LogError($this->orderid. "| Product ".$importedId." could not be found, error: ".$e->getMessage());
807
+ $this->log2->LogError($this->orderid. "| Product ".$importedId." could not be found, error: ".$e->getMessage());
808
+ return false;
809
//error no se pudo crear la orden
810
+
811
}
812
+ }
813
+
814
+
815
+ public function checkOrderStore($storeId ) {
816
$helper = Mage::helper('beezup');
817
$stores = $helper->getConfig('beezup/marketplace/stores');
818
$stores = unserialize ($stores);
819
foreach($stores as $store) {
820
+ if(isset($store[$storeId]) && $store[$storeId] > 0) {
821
+ return $store[$storeId];
822
+ }
823
}
824
return false;
825
+ }
826
+
827
+
828
+
829
/**
830
* @return BeezupOMOrderService
831
*/
832
public function getOrderService(){
833
+ if ($this->oOrderService === null){
834
+ $this->oOrderService = $this->createOrderService();
835
// enchufamos debug mode, esta activado? false true $this->oOrderService->setDebugMode(false);
836
+ }
837
+ return $this->oOrderService;
838
}
839
840
/**
841
* @return BeezupOMOrderService
842
*/
843
protected function createOrderService(){
844
+
845
+ return new BeezupOMOrderService($this->createRepository() );
846
}
847
848
protected function createRepository() {
849
+ if ($this->repository == null) {
850
+ $this->repository = new BeezupRepository();
851
+ }
852
+ return $this->repository;
853
+
854
}
855
856
857
858
859
private function createCustomer($customer_email , $data) {
860
+ $password = $this->orderid;
861
+ $this->debugLog("Creating new Customer");
862
+ $customer = Mage::getModel('customer/customer');
863
+ $customer->setWebsiteId(Mage::app()->getWebsite()->getId());
864
+ $customer->loadByEmail($customer_email);
865
+ if(!$customer->getId()) {
866
+ $customer->setEmail($customer_email);
867
+ $customer->setFirstname($data['firstname']);
868
+ $customer->setLastname($data['lastname']);
869
+ $customer->setPassword($password);
870