BeezUP_Module_feed_and_tracker - Version 4.6.2

Version Notes

New features :
> Feed pagination
> Minor bugs

Download this release

Release Info

Developer BeezUP
Extension BeezUP_Module_feed_and_tracker
Version 4.6.2
Comparing to
See all releases


Code changes from version 4.6.1 to 4.6.2

app/code/community/BeezUp/Block/Adminhtml/System/Config/Log.php CHANGED
@@ -6,7 +6,7 @@ class Beezup_Block_Adminhtml_System_Config_Log extends Mage_Adminhtml_Block_Syst
6
protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
7
{
8
9
- $logDir = Mage::getModuleDir('', 'BeezUp')."/log/";
10
// $log1 = file_get_contents();
11
$ret = array();
12
if (file_exists($logDir."/log.txt")) {
6
protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
7
{
8
9
+ $logDir = Mage::getBaseDir('base').'/beezup/';
10
// $log1 = file_get_contents();
11
$ret = array();
12
if (file_exists($logDir."/log.txt")) {
app/code/community/BeezUp/Block/Omstatus.php CHANGED
@@ -1,8 +1,8 @@
1
<?php
2
- require_once dirname ( __FILE__ ) . "/../lib/KLogger.php";
3
- require_once dirname ( __FILE__ ) . "/../lib/bootstrap.php";
4
- require_once dirname ( __FILE__ ) . "/../lib/BeezupRepository.php";
5
- require_once dirname ( __FILE__ ) . "/../lib/BeezupMageOrders.php";
6
7
class Beezup_Block_Omstatus extends Mage_core_block_text {
8
protected $repository = null;
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;
app/code/community/BeezUp/Block/Order.php CHANGED
@@ -1,8 +1,8 @@
1
<?php
2
- require_once dirname ( __FILE__ ) . "/../lib/KLogger.php";
3
- require_once dirname ( __FILE__ ) . "/../lib/bootstrap.php";
4
- require_once dirname ( __FILE__ ) . "/../lib/BeezupRepository.php";
5
- require_once dirname ( __FILE__ ) . "/../lib/BeezupMageOrders.php";
6
7
class Beezup_Block_Order extends Mage_core_block_text {
8
@@ -18,8 +18,26 @@
18
private $beezup_order_id;
19
private $mage_order_id = false;
20
21
public function createOrderFromLink($account_id, $marketplace_code, $beezup_order_id) {
22
- $logDir = Mage::getModuleDir('', 'BeezUp')."/log/";
23
if(file_exists($logDir."log2.txt")) {
24
if(filesize($logDir."/log2.txt") >=3000000) {
25
unlink($logDir."log2.txt");
@@ -73,17 +91,17 @@
73
echo "<script>window.location='".Mage::helper('adminhtml')->getUrl("adminhtml/sales_order/view", array('order_id'=> $this->mage_order_id))."';</script>";
74
}
75
// die("Order Importation finalized");
76
-
77
}
78
79
}
80
$configModel->saveConfig('beezup/marketplace/sync_status',0);
81
//die("Error, Order data incorrect");
82
- echo $this->_showLog();
83
}
84
85
public function _showLog() {
86
- $logDir = Mage::getModuleDir('', 'BeezUp')."/log/";
87
// $log1 = file_get_contents();
88
$ret = array();
89
if (file_exists($logDir."/log.txt")) {
@@ -144,10 +162,10 @@
144
145
public function executeCron() {
146
147
-
148
149
set_time_limit(0);
150
- $logDir = Mage::getModuleDir('', 'BeezUp')."/log/";
151
if(file_exists($logDir."log2.txt")) {
152
if(filesize($logDir."/log2.txt") >=3000000) {
153
unlink($logDir."log2.txt");
@@ -208,7 +226,7 @@
208
209
210
public function getLog() {
211
- $logDir = Mage::getModuleDir('', 'BeezUp')."/log/";
212
$log1 = file_get_contents($logDir."/log2.txt");
213
214
echo "<pre>";
@@ -229,1130 +247,1130 @@
229
}
230
231
public function getBeezupOrderId(){
232
- $oIdentifier = new BeezupOMOrderIdentifier();
233
- $oIdentifier
234
- ->setAccountId($this->account_id)
235
- ->setMarketplaceTechnicalCode($this->marketplace_code)
236
- ->setBeezupOrderUUID($this->beezup_order_id);
237
- return $oIdentifier;
238
}
239
240
241
public function createOrder($oBeezupOrderResponse) {
242
-
243
- $etag = $oBeezupOrderResponse->getETag();
244
- $final_order = $oBeezupOrderResponse->getResult();
245
-
246
- $orderid = $final_order->getOrderMarketPlaceOrderId();
247
- $this->orderid = $orderid;
248
- //customer Info
249
- $order_address = $final_order->getOrderBuyerAddressCity();
250
- $order_country = $final_order->getOrderBuyerAddressCountryName();
251
- $order_country_iso = $final_order->getOrderBuyerAddressCountryIsoCodeAlpha2();
252
- $order_address = $this->getBeezupBuyerAddress($final_order);
253
- $order_postalCode = $final_order->getOrderBuyerAddressPostalCode();
254
- $order_customer = $final_order->getOrderBuyerName();
255
- $order_customer_email = $final_order->getOrderBuyerEmail();
256
- $order_customer_phone = $final_order->getOrderBuyerPhone();
257
- $order_customer_mobile = $final_order->getOrderBuyerMobilePhone();
258
- $order_comment = $final_order->getOrderComment();
259
- $order_company = $final_order->getOrderBuyerCompanyName();
260
- $order_city = $final_order->getOrderBuyerAddressCity();
261
- $order_region = $final_order->getOrderBuyerStateOrRegion();
262
- $order_status = $final_order->getOrderStatusBeezUPOrderStatus();
263
- //shipping information
264
- $shipping_city = $final_order->getOrderShippingAddressCity();
265
- $shipping_country = $final_order->getOrderShippingAddressCountryName();
266
- $shipping_country_iso = $final_order->getOrderShippingAddressCountryIsoCodeAlpha2();
267
- $shipping_address = $this->getBeezupShippingAddress($final_order);
268
- $shipping_name = $final_order->getOrderShippingAddressName();
269
- $shipping_postalCode = $final_order->getOrderShippingAddressPostalCode();
270
- $shipping_email = $final_order->getOrderShippingEmail();
271
- $shipping_phone = $final_order->getOrderShippingPhone();
272
- $shipping_mobile = $final_order->getOrderShippingMobilePhone();
273
- $shipping_company = $final_order->getOrderShippingCompanyName();
274
- $shipping_region = $final_order->getOrderShippingAddressStateOrRegion();
275
- $order_currency_code = $final_order->getOrderCurrencyCode();
276
- //order Info
277
- $order_totalPrice = $final_order->getOrderTotalPrice();
278
- $order_shippingPrice = $final_order->getOrderShippingPrice();
279
-
280
- $name_parts = explode(" ", $order_customer);
281
- $order_first_name = array_shift( $name_parts);
282
- $order_last_name = implode(" ", $name_parts);
283
-
284
-
285
- $name_parts = explode(" ", $shipping_name);
286
- $shipping_first_name = array_shift( $name_parts);
287
- $shipping_last_name = implode(" ", $name_parts);
288
-
289
-
290
- //marketplace information
291
- $marketplace_business_code = $final_order->getMarketPlaceBusinessCode();
292
- $marketplace = $final_order->getMarketPlaceTechnicalCode();
293
-
294
- //productInfo
295
-
296
- $mage_productIds = $this->prescanOrder($final_order);
297
-
298
-
299
- if(!$this->checkEtagExists($etag)) {
300
- if(empty($order_customer_email)) {
301
- $order_customer_email = $this->generateEmail($final_order);
302
- }
303
- elseif(!filter_var($order_customer_email, FILTER_VALIDATE_EMAIL)) {
304
- $order_customer_email = $this->generateEmail($final_order);
305
- }
306
-
307
- $mage_productIds = $this->prescanOrder($final_order);
308
- if($mage_productIds) {
309
- $order_data = array(
310
- "etag" => $etag,
311
- "account_id" => $account_id,
312
- "order_status" => $order_status,
313
- "products" => $mage_productIds['products'],
314
- "storeid" => $mage_productIds['store'],
315
- "order_currency" => $order_currency_code ,
316
- "order_address" => $order_adress,
317
- "order_country" => $order_country,
318
- "order_country_iso" => $order_country_iso ,
319
- "order_address" => $order_address ,
320
- "order_postalCode" => $order_postalCode ,
321
- "order_customer" => $order_first_name ,
322
- "order_lastname" => $order_last_name ,
323
- "order_customer_email" => $order_customer_email ,
324
- "order_customer_phone" => $this->getPhone($order_customer_phone, $order_customer_mobile) ,
325
- "order_comment" => $order_comment ,
326
- "order_company" => $order_company ,
327
- "shipping_city" => $shipping_city ,
328
- "shipping_country" => $shipping_country ,
329
- "shipping_country_iso" => $shipping_country_iso ,
330
- "shipping_address" => $shipping_address ,
331
- "shipping_name" => $shipping_first_name ,
332
- "shipping_lastname" => $shipping_last_name ,
333
- "shipping_postalCode" => $shipping_postalCode ,
334
- "shipping_region" =>$shipping_region,
335
- "shipping_email" => $shipping_email ,
336
- "shipping_phone" => $this->getPhone($shipping_phone, $shipping_mobile) ,
337
- "shipping_company" => $shipping_company ,
338
- "order_totalPrice" => $order_totalPrice ,
339
- "order_shippingPrice" => $order_shippingPrice ,
340
- "order_city" => $order_city,
341
- "order_region" => $order_region,
342
- "marketplace" => $marketplace,
343
- "discounts" => $mage_productIds['discounts'],
344
- "marketplace_business_code" => $marketplace_business_code
345
- );
346
-
347
-
348
-
349
- //check if order exists
350
- $Mageorder = $this->loadMageOrder();
351
- if ($Mageorder) {
352
- //if order exists
353
- $this->updateEtag($etag);
354
- $this->updateBilling($Mageorder, $order_data );
355
- $this->updateBeezupInfoTab($Mageorder, $final_order, $order_data);
356
- $this->debugLog("Order Already exists Mage Order ID: " .$Mageorder->getId());
357
- $status1 = $Mageorder->getStatusLabel();
358
- $status = $this->getStatus($status1);
359
- if($status !== $order_status) {
360
- //if order exits and status has changed we update order status
361
- $this->debugLog("Updating Order Status from: ".$status1." to: ".$order_status );
362
- $this->setStatus( $order_status, $Mageorder);
363
- }
364
-
365
- $id_order = $Mageorder->getId();
366
- $BeezupMageOrder = new BeezupMageOrders($id_order);
367
- $BeezupMageOrder->setData(array("shipping" =>(float) $order_data['order_shippingPrice']));
368
- $BeezupMageOrder->updateShippingInfo();
369
- } else {
370
- //if not we create order
371
-
372
-
373
- $this->debugLog("Generating Order");
374
- $this->addOrder($order_data,$final_order );
375
- //die();
376
-
377
- }
378
-
379
-
380
- } else {
381
- //order could not be imported
382
-
383
-
384
- }
385
-
386
-
387
- } else {
388
- //etag has not changed
389
- $this->debugLog("Order Etag has not changed");
390
-
391
- }
392
-
393
-
394
-
395
-
396
-
397
}
398
399
400
401
public function generateEmail(BeezupOMOrderResult $oBeezupOrder)
402
{
403
- $sRawValue = $oBeezupOrder->getBeezupOrderUUID ();
404
- $sFakeDomain = preg_replace ( '/\W/', '', $oBeezupOrder->getMarketPlaceTechnicalCode () ) . '.com';
405
- return 'fakeemail' . md5 ( $sFakeDomain . $sRawValue ) . '@' . strtolower ( $sFakeDomain );
406
}
407
408
409
410
public function getOrderList($orderList = null) {
411
- if($orderList == null) {
412
- $data = $this->createRepository()->createOrderListRequest();
413
- $oRequest = $this->getOrderService()->getClientProxy()->getOrderList($data);
414
- $orderList = $oRequest->getResult();
415
- }
416
- $oPagination = $orderList->getPaginationResult();
417
- if(!empty($oPagination)) {
418
- $oLinksTotal = $oPagination->getLinks();
419
- } else {
420
- $configModel = Mage::getModel('core/config');
421
- $configModel->saveConfig('beezup/marketplace/sync_status',0);
422
- die("No more orders to import");
423
- }
424
-
425
- //$header = $orderList->getOrderHeaders();
426
- foreach($orderList->getOrderHeaders() as $order) {
427
- $order_status = $order->getBeezupOrderState();
428
- $orderLinks = $order->getLinks();
429
- $etag = $order->getETag();
430
- $beezup_order_id = $order->getBeezupOrderUUID();
431
- $account_id = $order->getAccountId();
432
- $orderdata = $this->getOrderService()->getClientProxy()->getOrderByLink($orderLinks[0]);
433
- $this->debugLog("Initializing Order - Link: ".$orderLinks[0]->getHref());
434
- $this->createOrder($orderdata, $oLinksTotal);
435
-
436
- }
437
-
438
- if(!empty($oLinksTotal)) {
439
- //we check if there is next link and get next orders
440
- foreach($oLinksTotal as $link) {
441
- if( $link->getRel() == "next") {
442
-
443
- $this->log->LogInfo("Initializing New Order List ->". $link->getHref());
444
- $this->log2->LogInfo("Initializing New Order List ->". $link->getHref());
445
- $oRequest = $this->getOrderService()->getClientProxy()->getOrderListByLink($link);
446
- $orderList = $oRequest->getResult();
447
- $this->getOrderList($orderList);
448
- }
449
-
450
- }
451
- }
452
-
453
}
454
455
456
457
public function updateBeezupInfoTab($order, $oLink, $data) {
458
- $beezup_last_modification_date = $oLink->getOrderLastModificationUtcDate();
459
- $beezup_last_modification_date = $beezup_last_modification_date->date;
460
- $beezup_marketplace_last_modification_date = $oLink->getOrderMarketPlaceLastModificationUtcDate();
461
- $beezup_marketplace_last_modification_date = $beezup_marketplace_last_modification_date->date;
462
- $beezup_comission = $oLink->getOrderTotalCommission()." ".$data['order_currency'];
463
- $tot_comm = $oLink->getOrderTotalCommission();
464
- if(empty($tot_comm ) || $tot_comm == 0) {
465
- $beezup_comission = 0;
466
- }
467
- $updateData = array("beezup_status" => $data['order_status'],
468
- "beezup_last_modification_date" => $beezup_last_modification_date,
469
- "beezup_marketplace_last_modification_date" => $beezup_marketplace_last_modification_date ,
470
- "beezup_total_paid" => $oLink->getOrderTotalPrice()." ".$data['order_currency'],
471
- "beezup_comission" => $beezup_comission,
472
- "beezup_marketplace_status" => $oLink->getOrderStatusMarketPlaceStatus());
473
- $orderId = $order->getId();
474
- $beezupMageOrder = new BeezupMageOrders($orderId);
475
- $beezupMageOrder->setData($updateData);
476
- $beezupMageOrder->updateBeezupInfo();
477
-
478
-
479
}
480
481
public function getPhone($phone, $phone2) {
482
- $retorno = "";
483
- if(!empty($phone) && $phone !== "") {
484
- $retorno .= $phone;
485
- }
486
- if(!empty($phone2) && $phone2 !=="") {
487
- if(empty($phone) || $phone == "") {
488
- $retorno = $phone2;
489
-
490
- } else {
491
- $retorno .= " - ".$phone2;
492
- }
493
- }
494
- return $retorno;
495
}
496
497
498
public function getBeezupBuyerAddress($order) {
499
- $add1=$order->getOrderBuyerAddressLine1();
500
- $add2=$order->getOrderBuyerAddressLine2();
501
- $add3=$order->getOrderBuyerAddressLine3();
502
- $retorno = "";
503
- if(!empty($add1)) {
504
- $retorno = $order->getOrderBuyerAddressLine1();
505
- }
506
- if(!empty($add2)) {
507
- if(empty($add1)) {
508
- $retorno .= $order->getOrderBuyerAddressLine2();
509
- } else {
510
- $retorno .= " - ". $order->getOrderBuyerAddressLine2();
511
- }
512
- }
513
- if(!empty($add3)){
514
- if(empty($add1) && empty($add2)) {
515
- $retorno .= $order->getOrderBuyerAddressLine3();
516
- } else {
517
- $retorno .= " - ". $order->getOrderBuyerAddressLine3();
518
- }
519
- }
520
- return $retorno;
521
}
522
523
524
public function getBeezupShippingAddress($order) {
525
- $add1 = $order->getOrderShippingAddressLine1();
526
- $add2 = $order->getOrderShippingAddressLine2();
527
- $add3=$order->getOrderBuyerAddressLine3();
528
- $retorno = "";
529
- if(!empty($add1 )) {
530
- $retorno = $order->getOrderShippingAddressLine1();
531
- }
532
- if(!empty($add2)) {
533
- if(empty($add1)) {
534
- $retorno .= $order->getOrderShippingAddressLine2();
535
- } else {
536
- $retorno .= " - ". $order->getOrderShippingAddressLine2();
537
- }
538
- }
539
- if(!empty($add3)){
540
- if(empty($add1) && empty($add2)) {
541
- $retorno .= $order->getOrderShippingAddressLine3();
542
- } else {
543
- $retorno .= " - ". $order->getOrderShippingAddressLine3();
544
- }
545
- }
546
- return $retorno;
547
}
548
549
public function checkEtagExists($etag) {
550
- $resource = Mage::getSingleton('core/resource');
551
- $readConnection = $resource->getConnection('core_read');
552
- $table = $resource->getTableName('sales/order_grid');
553
- $query = 'SELECT increment_id FROM ' . $table . ' WHERE beezup_etag = \''
554
- . $etag . '\' LIMIT 1';
555
- $order = $readConnection->fetchOne($query);
556
- if($order && !empty($order)) {
557
- return true;
558
- }
559
- return false;
560
-
561
}
562
563
564
public function updateEtag($etag) {
565
- $this->debugLog("Updating Etag");
566
- $resource = Mage::getSingleton('core/resource');
567
- $writeConnection = $resource->getConnection('core_write');
568
- $table = $resource->getTableName('sales/order_grid');
569
- $query = "UPDATE {$table} SET beezup_etag = '{$etag}' where beezup_market_order_id = '{$this->orderid}' ";
570
- $writeConnection->query($query);
571
-
572
}
573
574
575
576
public function updateBilling($order, $data) {
577
-
578
-
579
- $addressData = array(
580
- 'billing_firstname' => ($data['order_customer']) ? $data['order_customer'] : "empty",
581
- 'billing_lastname' => ($data['order_lastname']) ? $data['order_lastname'] : "empty",
582
- 'billing_street' => ($data['order_address']) ? $data['order_address'] : "empty",
583
- 'billing_city' => ($data['order_city']) ? $data['order_city'] : "empty",
584
- 'billing_postcode' => ($data['order_postalCode']) ? $data['order_postalCode'] : "empty",
585
- 'billing_telephone' => ($data['order_customer_phone']) ? $data['order_customer_phone'] : "empty",
586
- 'billing_country_id' => ($data['order_country_iso']) ? $data['order_country_iso'] : "empty",
587
- 'billing_region_id' => ($data['order_region ']) ? substr($data['order_region '], 0,2) : "EM",
588
- 'shipping_firstname' => ($data['shipping_name']) ? $data['shipping_name'] : "empty",
589
- 'shipping_lastname' => ($data['shipping_lastname']) ? $data['shipping_lastname'] : "empty",
590
- 'shipping_street' => ($data['shipping_address']) ? $data['shipping_address'] : "empty",
591
- 'shipping_city' => ($data['shipping_city']) ? $data['shipping_city'] : "empty",
592
- 'shipping_postcode' => ($data['shipping_postalCode']) ? $data['shipping_postalCode'] : "empty",
593
- 'shipping_telephone' => ($data['shipping_phone']) ? $data['shipping_phone'] : "empty",
594
- 'shipping_country_id' => ($data['shipping_country_iso']) ? $data['shipping_country_iso'] : "empty",
595
- 'shipping_region_id' => ($data['shipping_region']) ? substr($data['shipping_region'], 0, 2) : "EM" // id from directory_country_region table
596
- );
597
-
598
- $shippingData = array(
599
-
600
- );
601
- // Get the id of the orders shipping address
602
- $orderId = $order->getId();
603
- $beezupMageOrder = new BeezupMageOrders($orderId);
604
- $beezupMageOrder->setData($addressData);
605
- $beezupMageOrder->updateAdresses();
606
}
607
608
public function updateAddresses($shippingData, $address) {
609
- if($shippingData['firstname'] !==$address['firstname']) {
610
- $address->setFirstname($shippingData['firstname']);
611
- }
612
- if($shippingData['lastname'] !==$address['lastname']) {
613
- $address->setLastname($shippingData['lastname']);
614
- }
615
- if($shippingData['street'] !==$address['street']) {
616
- $address->setStreet($shippingData['street']);
617
- }
618
- if($shippingData['city'] !==$address['city']) {
619
- $address->setCity($shippingData['city']);
620
- }
621
- if($shippingData['postcode'] !==$address['postcode']) {
622
- $address->setPostcode($shippingData['postcode']);
623
- }
624
- if($shippingData['telephone'] !==$address['telephone']) {
625
- $address->setTelephone($shippingData['telephone']);
626
- }
627
- $address->save();
628
-
629
-
630
}
631
632
633
public function loadMageOrder() {
634
- $Mageorder = Mage::getModel('sales/order')->loadByIncrementId($this->orderid);
635
- if ($Mageorder->getId()) {
636
- return $Mageorder;
637
- } else {
638
- //we get order from marketplace orderid
639
- $orderInc = $this->checkMarketOrderExists($this->orderid);
640
- if($orderInc) {
641
- // if exists
642
- $Mageorder = Mage::getModel('sales/order')->loadByIncrementId($orderInc);
643
- if ($Mageorder->getId()) {
644
- return $Mageorder;
645
- }
646
- }
647
- }
648
- return false;
649
}
650
651
652
private function debugLog($message) {
653
-
654
- if($this->orderid !== "") {
655
- $message = $this->orderid." | ".$message;
656
- }
657
- $this->log->LogInfo($message);
658
-
659
- $this->log2->LogInfo($message);
660
}
661
662
public function prescanOrder(BeezupOMOrderResult $order) {
663
- $retorno = array();
664
- $orderItems = $order->getOrderItems();
665
- foreach ($orderItems as $item)
666
- {
667
-
668
- if ($item->getOrderItemOrderItemType () !== 'Product')
669
- {
670
- // continue;
671
- }
672
- $beezup_store = $item->getOrderItemBeezUPStoreId(); //beezup storeid
673
- $mage_storeid = $this->checkOrderStore($beezup_store); //magento storeid
674
- $marketplace_orderid = $item->getOrderItemMarketPlaceProductId();
675
- if(!$mage_storeid) {
676
-
677
- if(strpos($marketplace_orderid,'INTERETBCA') !== false || strpos($marketplace_orderid,'interetbca') !== false) { }
678
- else {
679
- $this->log->LogError($this->orderid." | No mapping for store ".$beezup_store);
680
- $this->log2->LogError($this->orderid." | No mapping for store ".$beezup_store);
681
- return false;
682
- }
683
-
684
- }
685
- // $retorno['store'] = 1;
686
- $retorno['store'] = $mage_storeid;
687
- $this->debugLog("Store Matching succesful, Beezup Store: ".$beezup_store." , Magento Store Id: ".$mage_storeid);
688
- $product_ImportedMerchantId = $item->getOrderItemMerchantImportedProductId();
689
- $product_MerchantId = $item->getOrderItemMerchantProductId();
690
-
691
- $product_quantity = $item->getOrderItemQuantity();
692
- $product_price = $item->getOrderItemItemPrice();
693
- $product_title = $item->getOrderItemTitle();
694
- $product_image = $item->getOrderItemImageUrl();
695
- if(strpos($marketplace_orderid,'INTERETBCA') !== false || strpos($marketplace_orderid,'interetbca') !== false) {
696
- $retorno['discounts']= $item->getOrderItemTotalPrice();
697
- } else {
698
- $product = $this->getMageProduct($product_ImportedMerchantId , $product_MerchantId , $beezup_store );
699
- if($product) {
700
- $mage_productId = $product->getId();
701
- $stocklevel = (int)Mage::getModel('cataloginventory/stock_item')
702
- ->loadByProduct($product)->getQty();
703
-
704
- $retorno['products'][] = array("id" => $mage_productId, "qty" => $product_quantity, "price" => $product_price, "curr_stock" => $stocklevel);
705
- //producto existe
706
- } else {
707
- //vendria if de si activada opcion de crear producto creamos
708
- if(!$this->debug) {
709
- return false;
710
- }
711
- $product_data = array(
712
- "sku" => $product_ImportedMerchantId,
713
- "sku2" => $product_MerchantId,
714
- "qty" => $product_quantity,
715
- "price" => $product_price,
716
- "title" => $product_title,
717
- "image" => $product_image,
718
- "storeId" => $mage_storeid
719
- );
720
- $product = $this->createProduct($product_data);
721
- if(!$product) {
722
- return false;
723
- }
724
- $stocklevel = (int)Mage::getModel('cataloginventory/stock_item')
725
- ->loadByProduct($product)->getQty();
726
- $mage_productId = $product->getId();
727
- $retorno['products'][] = array("id" => $mage_productId, "qty" => $product_quantity, "price" => $product_price, "curr_stock" => $stocklevel);
728
- }
729
- }
730
- }
731
-
732
- return $retorno;
733
}
734
735
736
737
public function matchProductAttributes($importedId, $storeId) {
738
- $product = null;
739
- $helper = Mage::helper('beezup');
740
- $attributes = $helper->getConfig('beezup/marketplace/attributes');
741
- $attributes = unserialize ($attributes);
742
-
743
- foreach($attributes['attributes'][$storeId ] as $attribute) {
744
- $att = explode("|", $attribute);
745
- if($storeId == $att[1]) {
746
-
747
- $product=Mage::getModel('catalog/product')->loadByAttribute($att[0],$importedId);
748
- if($product) {
749
- break;
750
- }
751
- }
752
- }
753
-
754
- return $product;
755
}
756
757
758
759
public function getMageProduct($importedId, $merchantId, $storeId){
760
- try {
761
- $product=Mage::getModel('catalog/product')->load($importedId);
762
- if (!$product->getId() || $product->getId() !== $importedId ){
763
- $product = $this->matchProductAttributes($importedId, $storeId);
764
- if($product == null || !is_object($product)) {
765
- $product=Mage::getModel('catalog/product')->load($merchantId);
766
- if(!$product->getId() || $product->getId() !== $merchantId ) {
767
- $product = $this->matchProductAttributes($merchantId, $storeId);
768
-
769
- }
770
- }
771
- }
772
-
773
- if(is_object($product)) {
774
- if($product->getId()) {
775
- $this->debugLog("Product Matching succesful, Beezup Imported Id: ".$importedId." , Magento Product Id: ".$product->getId());
776
- return $product;
777
- }}
778
- $this->log->LogError($this->orderid. "| No Product Matching, Product ".$importedId." could not be found");
779
- $this->log2->LogError($this->orderid. "| No Product Matching, Product ".$importedId." could not be found");
780
- return false;
781
- }catch(Exception $e){
782
- $this->log->LogError($this->orderid. "| Product ".$importedId." could not be found, error: ".$e->getMessage());
783
- $this->log2->LogError($this->orderid. "| Product ".$importedId." could not be found, error: ".$e->getMessage());
784
- return false;
785
- //error no se pudo crear la orden
786
-
787
- }
788
}
789
790
791
public function checkOrderStore($storeId ) {
792
- $helper = Mage::helper('beezup');
793
- $stores = $helper->getConfig('beezup/marketplace/stores');
794
- $stores = unserialize ($stores);
795
- foreach($stores as $store) {
796
- if(isset($store[$storeId]) && $store[$storeId] > 0) {
797
- return $store[$storeId];
798
- }
799
- }
800
- return false;
801
}
802
803
804
805
/**
806
- * @return BeezupOMOrderService
807
*/
808
public function getOrderService(){
809
- if ($this->oOrderService === null){
810
- $this->oOrderService = $this->createOrderService();
811
- // enchufamos debug mode, esta activado? false true $this->oOrderService->setDebugMode(false);
812
- }
813
- return $this->oOrderService;
814
}
815
816
/**
817
- * @return BeezupOMOrderService
818
*/
819
protected function createOrderService(){
820
-
821
- return new BeezupOMOrderService($this->createRepository() );
822
}
823
824
protected function createRepository() {
825
- if ($this->repository == null) {
826
- $this->repository = new BeezupRepository();
827
- }
828
- return $this->repository;
829
-
830
}
831
832
833
834
835
private function createCustomer($customer_email , $data) {
836
- $password = $this->orderid;
837
- $this->debugLog("Creating new Customer");
838
- $customer = Mage::getModel('customer/customer');
839
- $customer->setWebsiteId(Mage::app()->getWebsite()->getId());
840
- $customer->loadByEmail($customer_email);
841
- if(!$customer->getId()) {
842
- $customer->setEmail($customer_email);
843
- $customer->setFirstname($data['firstname']);
844
- $customer->setLastname($data['lastname']);
845
- $customer->setPassword($password);
846
- try {
847
- $customer->save();
848
- $customer->setConfirmation(null);
849
- $customer->save();
850
- $this->debugLog("Customer created succesfully");
851
- return $customer;
852
- //Make a "login" of new customer
853
- // Mage::getSingleton('customer/session')->loginById($customer->getId());
854
- }
855
-
856
- catch (Exception $ex) {
857
- //Zend_Debug::dump($ex->getMessage());
858
- //GUARDAR ERROR CREACION USUARIO
859
- $this->log2->LogError($this->orderid. " | Customer importation failed: ".$ex->getMessage());
860
- return false;
861
- }
862
-
863
- } else {
864
- $this->debugLog("Creating already exists, returning customer object");
865
- return $customer;
866
- }
867
}
868
869
870
871
public function addOrder($data, $oLink, $stop = false) {
872
-
873
-
874
- try {
875
- $helper = Mage::helper('beezup');
876
- $addStock = $helper->getConfig('beezup/marketplace/available_products');
877
- $baseCurrencyCode = Mage::app()->getStore()->getBaseCurrencyCode();
878
- $quote = Mage::getModel('sales/quote')
879
- ->setStoreId($data['storeid']);
880
- $quote->setCustomerEmail($data['order_customer_email']);
881
-
882
-
883
- $currency = Mage::getModel('directory/currency')->load($data['order_currency']);
884
- $quote->setForcedCurrency($currency);
885
-
886
- $blnCreate = true;
887
- $total_new_price = 0;
888
- foreach($data['products'] as $prod) {
889
- if($prod['qty']==0) {
890
- $blnCreate = false;
891
- break;
892
- }
893
- $prod_totality_price = $prod['price']*$prod['qty'];
894
- $total_new_price = $total_new_price + $prod_totality_price;
895
- $product = Mage::getModel('catalog/product')->load($prod['id']);
896
- $buyInfo = array(
897
- 'qty' => $prod['qty'],
898
- );
899
- $this->debugLog("Adding ".$prod['qty']." product/s with id ".$product->getId()." to order, with Beezup Price: ".$prod['price']);
900
- //echo "Product ".$product->getId()."<br><br>";
901
- //para no perder stock:
902
- //Mage::getModel('cataloginventory/stock')->backItemQty($productId,$new_qty);
903
-
904
-
905
- if($addStock == 1) {
906
- $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product);
907
-
908
- if ($stock->getQty() < $prod['qty'] && $product->getStockItem()->getMaxSaleQty() >= $prod['qty']) {
909
- $this->debugLog("Product ".$product->getId()." Stock = 0, Updating to ".$prod['qty']." to generate Order");
910
- // Mage::getModel('cataloginventory/stock')->backItemQty($product->getId(),$prod['qty']);
911
- //$this->_updateStocks(array("id_product" => $product->getId(), "qty" => $prod['qty']));
912
- $product->setStockData(
913
- array(
914
- 'is_in_stock' => 1,
915
- 'qty' => $prod['qty'],
916
- 'manage_stock' => 1,
917
- 'use_config_notify_stock_qty' => 1
918
- )
919
- );
920
- $product->save();
921
- $product = Mage::getModel('catalog/product')->load($product->getId());
922
-
923
- }
924
- }
925
- //fin para no perder stock
926
-
927
- /*
928
- $tax_class = $product->getTaxClassId();
929
- $product->setTaxClassId(0);
930
- $product->getResource()->saveAttribute($product, 'tax_class_id'); */
931
- $price = $prod['price'];
932
-
933
- $quote_item = Mage::getModel('beezup/quote_item');
934
- $quote_item
935
- ->setProduct($product)
936
- ->setPrice((float) $price )
937
- ->setCustomPrice((float)$price )
938
- ->setOriginalCustomPrice((float) $price )
939
- ->setQuote($quote)
940
- ->setQty((integer) $prod['qty'])
941
- ->setBeezupPrice((float) $price );
942
-
943
-
944
- $quote->addItem($quote_item);
945
-
946
- //$quote->addProduct($product, new Varien_Object($buyInfo))->setOriginalCustomPrice($price)->setCustomPrice($price);
947
-
948
- /*
949
- $product->setTaxClassId($tax_class);
950
-
951
- $product->getResource()->saveAttribute($product, 'tax_class_id');
952
- */
953
- }
954
-
955
- if($blnCreate) {
956
- $addressData = array(
957
- 'firstname' => ($data['order_customer']) ? $data['order_customer'] : "empty",
958
- 'lastname' => ($data['order_lastname']) ? $data['order_lastname'] : "empty",
959
- 'street' => ($data['order_address']) ? $data['order_address'] : "empty",
960
- 'city' => ($data['order_city']) ? $data['order_city'] : "empty",
961
- 'postcode' => ($data['order_postalCode']) ? $data['order_postalCode'] : "empty",
962
- 'telephone' => ($data['order_customer_phone']) ? $data['order_customer_phone'] : "empty",
963
- 'country_id' => ($data['order_country_iso']) ? $data['order_country_iso'] : "empty",
964
- 'region_id' => ($data['order_region ']) ? substr($data['order_region '], 0,2) : "EM"// id from directory_country_region table
965
- );
966
-
967
- $shippingData = array(
968
- 'firstname' => ($data['shipping_name']) ? $data['shipping_name'] : "empty",
969
- 'lastname' => ($data['shipping_lastname']) ? $data['shipping_lastname'] : "empty",
970
- 'street' => ($data['shipping_address']) ? $data['shipping_address'] : "empty",
971
- 'city' => ($data['shipping_city']) ? $data['shipping_city'] : "empty",
972
- 'postcode' => ($data['shipping_postalCode']) ? $data['shipping_postalCode'] : "empty",
973
- 'telephone' => ($data['shipping_phone']) ? $data['shipping_phone'] : "empty",
974
- 'country_id' => ($data['shipping_country_iso']) ? $data['shipping_country_iso'] : "empty",
975
- 'region_id' => ($data['shipping_region']) ? substr($data['shipping_region'], 0, 2) : "EM" // id from directory_country_region table
976
- );
977
-
978
- if($this->blnCreateCustomer) {
979
-
980
- $mage_customer = $this->createCustomer($data['order_customer_email'], $addressData);
981
- $quote->assignCustomer($mage_customer);
982
- }
983
-
984
-
985
- $payment_method = $helper->getConfig('beezup/marketplace/payment_method');
986
- $billingAddress = $quote->getBillingAddress()->addData($addressData);
987
- $shippingAddress = $quote->getShippingAddress()->addData($shippingData);
988
- $shipping_cost = (float) $data['order_shippingPrice'];
989
- if($data['order_shippingPrice'] == 0) {
990
- $shipping_cost = 20000;
991
- }
992
- $total_new_price = $total_new_price + $data['order_shippingPrice'] ;
993
- Mage::unregister('shipping_cost');
994
- Mage::register('shipping_cost', $shipping_cost);
995
- $this->debugLog("Adding Order Shipping Cost: ". $data['order_shippingPrice']);
996
-
997
- $shippingAddress->setCollectShippingRates(true)->collectShippingRates()
998
- ->setShippingMethod('flatrate_flatrate')
999
- ->setPaymentMethod($payment_method);
1000
-
1001
- //$shippingAddress->addTotal(array("code" => "specialfee", "title" => "Special Fee", "value" => 20));
1002
- $quote->getPayment()->importData(array('method' => $payment_method));
1003
-
1004
- $quote->collectTotals()->save();
1005
-
1006
- $service = Mage::getModel('sales/service_quote', $quote);
1007
- $service->submitAll();
1008
- $order = $service->getOrder();
1009
-
1010
-
1011
-
1012
- $quoteId = $order->getQuoteId();
1013
- //$this->setStatus($data['order_status'], $order);
1014
-
1015
- $orderid = $order->getId();
1016
-
1017
- $resource = Mage::getSingleton('core/resource');
1018
- $writeConnection = $resource->getConnection('core_write');
1019
- $table = $resource->getTableName('sales/order_grid');
1020
- $this->debugLog("Adding Beezup Marketplace Information to Order");
1021
- $marketplace = $data['marketplace'];
1022
- $marketplace_business_code = ucfirst(strtolower($data['marketplace_business_code']));
1023
- $beezup_name = $data['order_customer'];
1024
- $market_order_id =$this->orderid;
1025
- $beezup_order_id = $oLink->getBeezupOrderUUID();
1026
- $beezup_status = $data['order_status'];
1027
- $beezup_last_modification_date = $oLink->getOrderLastModificationUtcDate();
1028
- $beezup_last_modification_date = $beezup_last_modification_date->date;
1029
- $beezup_marketplace_status = $oLink->getOrderStatusMarketPlaceStatus();
1030
- $beezup_purchase_date = $oLink->getOrderPurchaseUtcDate();
1031
- $beezup_purchase_date = $beezup_purchase_date->date;
1032
- $beezup_marketplace_last_modification_date = $oLink->getOrderMarketPlaceLastModificationUtcDate();
1033
- $beezup_marketplace_last_modification_date = $beezup_marketplace_last_modification_date->date;
1034
- /* $date = new DateTime($beezup_marketplace_last_modification_date);
1035
- $beezup_marketplace_last_modification_date = $date->format('d-m-Y H:i:s'). "(UTC Time)";
1036
- */
1037
-
1038
- $beezup_total_paid = $oLink->getOrderTotalPrice()." ".$data['order_currency'];
1039
- $beezup_account_id = $oLink->getAccountId();
1040
- $beezup_comission = $oLink->getOrderTotalCommission()." ".$data['order_currency'];
1041
- $tot_comm = $oLink->getOrderTotalCommission();
1042
- if(empty($tot_comm ) || $tot_comm == 0) {
1043
- $beezup_comission = 0;
1044
- }
1045
- $query = "UPDATE {$table} SET beezup_marketplace = '{$marketplace}', beezup_name = '{$beezup_account_id}', beezup_order = 1, beezup_market_order_id = '{$market_order_id}',
1046
- beezup_order_id = '{$beezup_order_id}', beezup_status = '{$beezup_status}', beezup_last_modification_date = '{$beezup_last_modification_date}',
1047
- beezup_marketplace_status = '{$beezup_marketplace_status}', beezup_purchase_date = '{$beezup_purchase_date}', beezup_marketplace_last_modification_date = '{$beezup_marketplace_last_modification_date}',
1048
- beezup_total_paid = '{$beezup_total_paid}', beezup_etag = '{$data['etag']}' , beezup_comission = '{$beezup_comission}', beezup_marketplace_business_code = '{$marketplace_business_code}'
1049
- WHERE entity_id = ". (int)$orderid;
1050
- $writeConnection->query($query);
1051
- $disc_price = 0;
1052
- if(!empty($data['discounts']) && $data['discounts'] >0) {
1053
-
1054
-
1055
- $disc_price = round($data['discounts'],2);
1056
- $total_new_price = $total_new_price+$disc_price;
1057
- $table_address = $resource->getTableName("sales/quote_address");
1058
-
1059
- $query = "update {$table_address} set beezup_fee = '{$disc_price}' where quote_id = '{$quoteId}' and address_type = 'shipping'";
1060
- $writeConnection->query($query);
1061
- $this->debugLog("Adding CDISCOUNT products with total price: ".$disc_price);
1062
- }
1063
-
1064
- //if order id exists and has been created
1065
- if ($orderid)
1066
- {
1067
- //we send order id to beezup
1068
- $this->debugLog("Sending Magento Order Id to Beezup, Magento Order Id: ".$orderid);
1069
- $oResult = new BeezupOMSetOrderIdValues ();
1070
- $oResult->setOrderMerchantOrderId ( $orderid )->setOrderMerchantECommerceSoftwareName ( 'Magento' )->setOrderMerchantECommerceSoftwareVersion ( Mage::getVersion() );
1071
- $sendRequest = $this->getOrderService()->getClientProxy()->setOrderMerchantIdByLink($oLink->getLinkByRel('setMerchantOrderId'), $oResult);
1072
- }
1073
-
1074
- $grand_total = $order->getGrandTotal();
1075
- $beezup_price = $oLink->getOrderTotalPrice() - $disc_price;
1076
- if($grand_total != (float) $beezup_price && $beezup_price > 0) {
1077
- $order->setGrandTotal((float) $beezup_price);
1078
- $order->setBaseGrandTotal((float) $beezup_price);
1079
- $diff = (((float) $beezup_price) - $grand_total);
1080
-
1081
- $order->setTaxAmount($order->getTaxAmount() + $diff);
1082
- $order->save();
1083
- }elseif($grand_total != (float)$beezup_price && $beezup_price < 1) {
1084
-
1085
- $order->setGrandTotal((float) $total_new_price);
1086
- $order->setBaseGrandTotal((float) $total_new_price);
1087
- $diff = (((float) $total_new_price) - $grand_total);
1088
-
1089
- $order->setTaxAmount($order->getTaxAmount() + $diff);
1090
- $order->save();
1091
- }
1092
-
1093
- $products = Mage::getResourceModel('sales/order_item_collection')
1094
- ->setOrderFilter($orderid);
1095
- foreach($products as $product) {
1096
- $product->setBaseOriginalPrice($product->getOriginalPrice());
1097
- $product->setBaseTaxAmount($product->getTaxAmount());
1098
- $product->setBaseTaxInvoiced($product->getTaxAmount());
1099
- $product->setBasePriceInclTax($product->getPriceInclTax());
1100
- $product->setBaseRowTotalInclTax($product->getRowTotalInclTax());
1101
- $product->save();
1102
- }
1103
- $order->setBaseTaxAmount($order->getTaxAmount());
1104
- $order->setBaseTaxInvoiced($order->getTaxAmount());
1105
- $order->setBaseTotalInvoiced($order->getTotalPaid());
1106
- $order->setBaseTotalPaid($order->getTotalPaid());
1107
- $order->setBaseGrandTotal($order->getTotalPaid());
1108
- $order->setBaseSubtotalInclTax($order->getSubtotalInclTax());
1109
- $order->save();
1110
-
1111
- $this->setStatus($data['order_status'], $order);
1112
- $this->mage_order_id = $orderid;
1113
- $this->debugLog("Order imported succesfully, Magento Order Id: ".$orderid);
1114
- } else {
1115
- //product stock = 0 we dont create order
1116
- $this->log->LogError($this->orderid. "| Order ".$data['market_place_order_id']." could not be imported, error: Stock from Beezup product = 0 ");
1117
- $this->log2->LogError($this->orderid. "| Order ".$data['market_place_order_id']." could not be imported, error: Stock from Beezup product = 0 ");
1118
- }
1119
- }catch(Exception $e){
1120
-
1121
-
1122
- if($stop) {
1123
- $this->log->LogError($this->orderid. "| Order ".$data['market_place_order_id']." could not be imported, error: ".$e->getMessage());
1124
- $this->log2->LogError($this->orderid. "| Order ".$data['market_place_order_id']." could not be imported, error: ".$e->getMessage());
1125
- $this->restoreStock($data);
1126
- } else {
1127
- $this->debugLog("Order Import failed, Trying to import Order Again");
1128
- $this->addOrder($data, $oLink, true);
1129
-
1130
- }
1131
- //error no se pudo crear la orden
1132
-
1133
- }
1134
-
1135
-
1136
-
1137
}
1138
1139
1140
-
1141
- public function restoreStock($data) {
1142
-
1143
- try {
1144
- foreach($data['products'] as $prod) {
1145
- $product = Mage::getModel('catalog/product')->load($prod['id']);
1146
- $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product);
1147
- if ($stock->getQty() != $prod['curr_stock'] ) {
1148
- $this->debugLog("Restoring Stock from Product ".$product->getId()." to: ".$prod['curr_stock'] ." due to Order Fail");
1149
- $stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product);
1150
- $stockItem->setData('is_in_stock', 0);
1151
- $stockItem->setData('qty', $prod['curr_stock']);
1152
- $stockItem->save();
1153
- $product->save();
1154
- }
1155
-
1156
- }
1157
- } catch(Exception $e){
1158
- $this->log->LogError($this->orderid. "| Failed Restoring Product Stock: ".$e->getMessage());
1159
- $this->log2->LogError($this->orderid. "| Failed Restoring Product Stock: ".$e->getMessage());
1160
- }
1161
-
1162
- }
1163
-
1164
-
1165
-
1166
- private function createProduct($data) {
1167
-
1168
- $sku = $data['sku'];
1169
- if(empty($data['sku'])) {
1170
- $sku = $data['sku2'];
1171
- }
1172
-
1173
- Mage::app()->setCurrentStore($data['storeId']);
1174
- $product = Mage::getModel('catalog/product');
1175
- // if(!$product->getIdBySku('testsku61')):
1176
-
1177
- try{
1178
- $product
1179
- // ->setStoreId(1) //you can set data in store scope
1180
- ->setWebsiteIds(array($data['storeId'])) //website ID the product is assigned to, as an array
1181
- ->setAttributeSetId($product->getDefaultAttributeSetId()) //ID of a attribute set named 'default'
1182
- ->setTypeId('simple') //product type
1183
- ->setCreatedAt(strtotime('now')) //product creation time
1184
- ->setSku($sku ) //SKU
1185
- ->setWeight(0)
1186
- ->setName($data['title']) //product name
1187
- ->setStatus(1) //product status (1 - enabled, 2 - disabled)
1188
- ->setTaxClassId(4) //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
1189
- ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE ) //catalog and search visibility
1190
- ->setPrice($data['price']) //price in form 11.22
1191
- ->setMsrpEnabled(1) //enable MAP
1192
- ->setMsrpDisplayActualPriceType(1) //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
1193
- ->setMsrp(0) //Manufacturer's Suggested Retail Price
1194
- ->setMetaTitle('')
1195
- ->setMetaKeyword('')
1196
- ->setMetaDescription('')
1197
- ->setDescription($data['title'])
1198
- ->setShortDescription($data['title'])
1199
- // ->setMediaGallery (array('images'=>array (), 'values'=>array ())) //media gallery initialization
1200
- //->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
1201
- ->setStockData(array(
1202
- 'use_config_manage_stock' => 0, //'Use config settings' checkbox
1203
- 'manage_stock'=>1, //manage stock
1204
- 'min_sale_qty'=>1, //Minimum Qty Allowed in Shopping Cart
1205
- 'max_sale_qty'=>2, //Maximum Qty Allowed in Shopping Cart
1206
- 'is_in_stock' => 1, //Stock Availability
1207
- 'qty' => 1 //qty
1208
- )
1209
- );
1210
- $product->save();
1211
- return $product;
1212
-
1213
- }catch(Exception $e){
1214
- //log exception
1215
- $this->log->LogError($this->orderid."| Product ".$sku." could not be created, error: ".$e->getMessage());
1216
- $this->log2->LogError($this->orderid."| Product ".$sku." could not be created, error: ".$e->getMessage());
1217
- return false;
1218
- }
1219
- }
1220
-
1221
-
1222
-
1223
- public function setStatus($status, $order) {
1224
- $helper = Mage::helper('beezup');
1225
- $retorno = "";
1226
- $blnCancel = false;
1227
- $blnHold = false;
1228
- switch($status) {
1229
- case "New" :
1230
- $this->debugLog("Setting Order Status to New");
1231
- $retorno = $helper->getConfig('beezup/marketplace/status_new');
1232
- break;
1233
- case "InProgress" :
1234
- $this->debugLog("Setting Order Status to InProgress");
1235
- $retorno = $helper->getConfig('beezup/marketplace/status_progress');
1236
- $this->payOrder($order);
1237
- break;
1238
- case "Aborted" :
1239
- $this->debugLog("Setting Order Status to Aborted");
1240
- $retorno = $helper->getConfig('beezup/marketplace/status_aborted');
1241
- $blnHold = true;
1242
-
1243
-
1244
- break;
1245
- case "Closed" :
1246
- $this->debugLog("Setting Order Status to Closed");
1247
- $blnCancel =true;
1248
- $retorno = $helper->getConfig('beezup/marketplace/status_closed');
1249
- $this->payOrder($order);
1250
- break;
1251
- case "Canceled" :
1252
- $this->debugLog("Setting Order Status to Cancelled");
1253
- $retorno = $helper->getConfig('beezup/marketplace/status_cancelled');
1254
-
1255
- break;
1256
- case "Shipped" :
1257
- $this->debugLog("Setting Order Status to Shipped");
1258
- $retorno = $helper->getConfig('beezup/marketplace/status_shipped');
1259
- $this->payOrder($order);
1260
- break;
1261
-
1262
- }
1263
- $order->setData('state',$retorno);
1264
- $order->setStatus($retorno);
1265
- $history = $order->addStatusHistoryComment('Order was set to '.$retorno.' by Beezup.', false);
1266
- $history->setIsCustomerNotified(false);
1267
- $order->save();
1268
- if($blnCancel) {
1269
- $order->cancel()->save();
1270
- }
1271
- if($blnHold) {
1272
- $order->hold()->save();
1273
- }
1274
-
1275
- return $retorno;
1276
-
1277
- }
1278
-
1279
-
1280
- public function getStatus($status1) {
1281
- $helper = Mage::helper('beezup');
1282
- $retorno = "";
1283
- $status = strtolower($status1);
1284
-
1285
- if($status == strtolower($helper->getConfig('beezup/marketplace/status_new') )) {
1286
- $retorno = "New";
1287
-
1288
- } elseif($status == strtolower($helper->getConfig('beezup/marketplace/status_progress') ) ){
1289
- $retorno = "InProgress";
1290
-
1291
-
1292
- }
1293
- elseif($status == strtolower($helper->getConfig('beezup/marketplace/status_aborted') )) {
1294
-
1295
- $retorno = "Aborted" ;
1296
- }
1297
- elseif($status == strtolower($helper->getConfig('beezup/marketplace/status_closed') )) {
1298
- $retorno = "Closed";
1299
-
1300
- }
1301
- elseif($status == strtolower($helper->getConfig('beezup/marketplace/status_cancelled')) ) {
1302
-
1303
- $retorno = "Canceled";
1304
- }
1305
- elseif($status == strtolower($helper->getConfig('beezup/marketplace/status_shipped') )) {
1306
-
1307
- $retorno = "Shipped";
1308
- }
1309
-
1310
-
1311
- return $retorno;
1312
-
1313
- }
1314
-
1315
-
1316
- public function checkMarketOrderExists($orderid) {
1317
- $resource = Mage::getSingleton('core/resource');
1318
- $readConnection = $resource->getConnection('core_read');
1319
- $table = $resource->getTableName('sales/order_grid');
1320
- $query = 'SELECT increment_id FROM ' . $table . ' WHERE beezup_order = 1 and beezup_market_order_id = \''
1321
- . $orderid . '\' LIMIT 1';
1322
- $order = $readConnection->fetchOne($query);
1323
- if($order && !empty($order) && $this->orderId !== "") {
1324
- return $order;
1325
- }
1326
- return false;
1327
-
1328
- }
1329
-
1330
- public function payOrder($order) {
1331
- try {
1332
- $this->debugLog("Generating Order Payment Invoice");
1333
- if($order->canInvoice()) {
1334
- $invoice = $order->prepareInvoice()
1335
- ->setTransactionId($order->getId())
1336
- ->addComment("Invoice created from Beezup.")
1337
- ->register()
1338
- ->pay();
1339
- $transaction_save = Mage::getModel('core/resource_transaction')
1340
- ->addObject($invoice)
1341
- ->addObject($invoice->getOrder());
1342
- $transaction_save->save();
1343
- $this->debugLog("Order Payment Invoice Generated Succesfully");
1344
- }
1345
- }
1346
- catch(Exception $e){
1347
- //log exception
1348
- $this->log->LogError($this->orderid."| Order Payment Invoice could not be generated, error: ".$e->getMessage());
1349
- $this->log2->LogError($this->orderid."| Order Payment Invoice could not be generated, error: ".$e->getMessage());
1350
- }
1351
- }
1352
-
1353
-
1354
-
1355
-
1356
-
1357
-
1358
- }
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
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");
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")) {
162
163
public function executeCron() {
164
165
+ $this->makeDir();
166
167
set_time_limit(0);
168
+ $logDir = Mage::getBaseDir('base').'/beezup/';
169
if(file_exists($logDir."log2.txt")) {
170
if(filesize($logDir."/log2.txt") >=3000000) {
171
unlink($logDir."log2.txt");
226
227
228
public function getLog() {
229
+ $logDir = Mage::getBaseDir('base').'/beezup/';
230
$log1 = file_get_contents($logDir."/log2.txt");
231
232
echo "<pre>";
247
}
248
249
public function getBeezupOrderId(){
250
+ $oIdentifier = new BeezupOMOrderIdentifier();
251
+ $oIdentifier
252
+ ->setAccountId($this->account_id)
253
+ ->setMarketplaceTechnicalCode($this->marketplace_code)
254
+ ->setBeezupOrderUUID($this->beezup_order_id);
255
+ return $oIdentifier;
256
}
257
258
259
public function createOrder($oBeezupOrderResponse) {
260
+
261
+ $etag = $oBeezupOrderResponse->getETag();
262
+ $final_order = $oBeezupOrderResponse->getResult();
263
+
264
+ $orderid = $final_order->getOrderMarketPlaceOrderId();
265
+ $this->orderid = $orderid;
266
+ //customer Info
267
+ $order_address = $final_order->getOrderBuyerAddressCity();
268
+ $order_country = $final_order->getOrderBuyerAddressCountryName();
269
+ $order_country_iso = $final_order->getOrderBuyerAddressCountryIsoCodeAlpha2();
270
+ $order_address = $this->getBeezupBuyerAddress($final_order);
271
+ $order_postalCode = $final_order->getOrderBuyerAddressPostalCode();
272
+ $order_customer = $final_order->getOrderBuyerName();
273
+ $order_customer_email = $final_order->getOrderBuyerEmail();
274
+ $order_customer_phone = $final_order->getOrderBuyerPhone();
275
+ $order_customer_mobile = $final_order->getOrderBuyerMobilePhone();
276
+ $order_comment = $final_order->getOrderComment();
277
+ $order_company = $final_order->getOrderBuyerCompanyName();
278
+ $order_city = $final_order->getOrderBuyerAddressCity();
279
+ $order_region = $final_order->getOrderBuyerStateOrRegion();
280
+ $order_status = $final_order->getOrderStatusBeezUPOrderStatus();
281
+ //shipping information
282
+ $shipping_city = $final_order->getOrderShippingAddressCity();
283
+ $shipping_country = $final_order->getOrderShippingAddressCountryName();
284
+ $shipping_country_iso = $final_order->getOrderShippingAddressCountryIsoCodeAlpha2();
285
+ $shipping_address = $this->getBeezupShippingAddress($final_order);
286
+ $shipping_name = $final_order->getOrderShippingAddressName();
287
+ $shipping_postalCode = $final_order->getOrderShippingAddressPostalCode();
288
+ $shipping_email = $final_order->getOrderShippingEmail();
289
+ $shipping_phone = $final_order->getOrderShippingPhone();
290
+ $shipping_mobile = $final_order->getOrderShippingMobilePhone();
291
+ $shipping_company = $final_order->getOrderShippingCompanyName();
292
+ $shipping_region = $final_order->getOrderShippingAddressStateOrRegion();
293
+ $order_currency_code = $final_order->getOrderCurrencyCode();
294
+ //order Info
295
+ $order_totalPrice = $final_order->getOrderTotalPrice();
296
+ $order_shippingPrice = $final_order->getOrderShippingPrice();
297
+
298
+ $name_parts = explode(" ", $order_customer);
299
+ $order_first_name = array_shift( $name_parts);
300
+ $order_last_name = implode(" ", $name_parts);
301
+
302
+
303
+ $name_parts = explode(" ", $shipping_name);
304
+ $shipping_first_name = array_shift( $name_parts);
305
+ $shipping_last_name = implode(" ", $name_parts);
306
+
307
+
308
+ //marketplace information
309
+ $marketplace_business_code = $final_order->getMarketPlaceBusinessCode();
310
+ $marketplace = $final_order->getMarketPlaceTechnicalCode();
311
+
312
+ //productInfo
313
+
314
+ $mage_productIds = $this->prescanOrder($final_order);
315
+
316
+
317
+ if(!$this->checkEtagExists($etag)) {
318
+ if(empty($order_customer_email)) {
319
+ $order_customer_email = $this->generateEmail($final_order);
320
+ }
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
+
367
+ //check if order exists
368
+ $Mageorder = $this->loadMageOrder();
369
+ if ($Mageorder) {
370
+ //if order exists
371
+ $this->updateEtag($etag);
372
+ $this->updateBilling($Mageorder, $order_data );
373
+ $this->updateBeezupInfoTab($Mageorder, $final_order, $order_data);
374
+ $this->debugLog("Order Already exists Mage Order ID: " .$Mageorder->getId());
375
+ $status1 = $Mageorder->getStatusLabel();
376
+ $status = $this->getStatus($status1);
377
+ if($status !== $order_status) {
378
+ //if order exits and status has changed we update order status
379
+ $this->debugLog("Updating Order Status from: ".$status1." to: ".$order_status );
380
+ $this->setStatus( $order_status, $Mageorder);
381
+ }
382
+
383
+ $id_order = $Mageorder->getId();
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
+
391
+ $this->debugLog("Generating Order");
392
+ $this->addOrder($order_data,$final_order );
393
+ //die();
394
+
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
+
409
+ }
410
+
411
+
412
+
413
+
414
+
415
}
416
417
418
419
public function generateEmail(BeezupOMOrderResult $oBeezupOrder)
420
{
421
+ $sRawValue = $oBeezupOrder->getBeezupOrderUUID ();
422
+ $sFakeDomain = preg_replace ( '/\W/', '', $oBeezupOrder->getMarketPlaceTechnicalCode () ) . '.com';
423
+ return 'fakeemail' . md5 ( $sFakeDomain . $sRawValue ) . '@' . strtolower ( $sFakeDomain );
424
}
425
426
427
428
public function getOrderList($orderList = null) {
429
+ if($orderList == null) {
430
+ $data = $this->createRepository()->createOrderListRequest();
431
+ $oRequest = $this->getOrderService()->getClientProxy()->getOrderList($data);
432
+ $orderList = $oRequest->getResult();
433
+ }
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");
441
+ }
442
+
443
+ //$header = $orderList->getOrderHeaders();
444
+ foreach($orderList->getOrderHeaders() as $order) {
445
+ $order_status = $order->getBeezupOrderState();
446
+ $orderLinks = $order->getLinks();
447
+ $etag = $order->getETag();
448
+ $beezup_order_id = $order->getBeezupOrderUUID();
449
+ $account_id = $order->getAccountId();
450
+ $orderdata = $this->getOrderService()->getClientProxy()->getOrderByLink($orderLinks[0]);
451
+ $this->debugLog("Initializing Order - Link: ".$orderLinks[0]->getHref());
452
+ $this->createOrder($orderdata, $oLinksTotal);
453
+
454
+ }
455
+
456
+ if(!empty($oLinksTotal)) {
457
+ //we check if there is next link and get next orders
458
+ foreach($oLinksTotal as $link) {
459
+ if( $link->getRel() == "next") {
460
+
461
+ $this->log->LogInfo("Initializing New Order List ->". $link->getHref());
462
+ $this->log2->LogInfo("Initializing New Order List ->". $link->getHref());
463
+ $oRequest = $this->getOrderService()->getClientProxy()->getOrderListByLink($link);
464
+ $orderList = $oRequest->getResult();
465
+ $this->getOrderList($orderList);
466
+ }
467
+
468
+ }
469
+ }
470
+
471
}
472
473
474
475
public function updateBeezupInfoTab($order, $oLink, $data) {
476
+ $beezup_last_modification_date = $oLink->getOrderLastModificationUtcDate();
477
+ $beezup_last_modification_date = $beezup_last_modification_date->date;
478
+ $beezup_marketplace_last_modification_date = $oLink->getOrderMarketPlaceLastModificationUtcDate();
479
+ $beezup_marketplace_last_modification_date = $beezup_marketplace_last_modification_date->date;
480
+ $beezup_comission = $oLink->getOrderTotalCommission()." ".$data['order_currency'];
481
+ $tot_comm = $oLink->getOrderTotalCommission();
482
+ if(empty($tot_comm ) || $tot_comm == 0) {
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);
494
+ $beezupMageOrder->updateBeezupInfo();
495
+
496
+
497
}
498
499
public function getPhone($phone, $phone2) {
500
+ $retorno = "";
501
+ if(!empty($phone) && $phone !== "") {
502
+ $retorno .= $phone;
503
+ }
504
+ if(!empty($phone2) && $phone2 !=="") {
505
+ if(empty($phone) || $phone == "") {
506
+ $retorno = $phone2;
507
+
508
+ } else {
509
+ $retorno .= " - ".$phone2;
510
+ }
511
+ }
512
+ return $retorno;
513
}
514
515
516
public function getBeezupBuyerAddress($order) {
517
+ $add1=$order->getOrderBuyerAddressLine1();
518
+ $add2=$order->getOrderBuyerAddressLine2();
519
+ $add3=$order->getOrderBuyerAddressLine3();
520
+ $retorno = "";
521
+ if(!empty($add1)) {
522
+ $retorno = $order->getOrderBuyerAddressLine1();
523
+ }
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
+ }
538
+ return $retorno;
539
}
540
541
542
public function getBeezupShippingAddress($order) {
543
+ $add1 = $order->getOrderShippingAddressLine1();
544
+ $add2 = $order->getOrderShippingAddressLine2();
545
+ $add3=$order->getOrderBuyerAddressLine3();
546
+ $retorno = "";
547
+ if(!empty($add1 )) {
548
+ $retorno = $order->getOrderShippingAddressLine1();
549
+ }
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
+ }
564
+ return $retorno;
565
}
566
567
public function checkEtagExists($etag) {
568
+ $resource = Mage::getSingleton('core/resource');
569
+ $readConnection = $resource->getConnection('core_read');
570
+ $table = $resource->getTableName('sales/order_grid');
571
+ $query = 'SELECT increment_id FROM ' . $table . ' WHERE beezup_etag = \''
572
+ . $etag . '\' LIMIT 1';
573
+ $order = $readConnection->fetchOne($query);
574
+ if($order && !empty($order)) {
575
+ return true;
576
+ }
577
+ return false;
578
+
579
}
580
581
582
public function updateEtag($etag) {
583
+ $this->debugLog("Updating Etag");
584
+ $resource = Mage::getSingleton('core/resource');
585
+ $writeConnection = $resource->getConnection('core_write');
586
+ $table = $resource->getTableName('sales/order_grid');
587
+ $query = "UPDATE {$table} SET beezup_etag = '{$etag}' where beezup_market_order_id = '{$this->orderid}' ";
588
+ $writeConnection->query($query);
589
+
590
}
591
592
593
594
public function updateBilling($order, $data) {
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);
622
+ $beezupMageOrder->setData($addressData);
623
+ $beezupMageOrder->updateAdresses();
624
}
625
626
public function updateAddresses($shippingData, $address) {
627
+ if($shippingData['firstname'] !==$address['firstname']) {
628
+ $address->setFirstname($shippingData['firstname']);
629
+ }
630
+ if($shippingData['lastname'] !==$address['lastname']) {
631
+ $address->setLastname($shippingData['lastname']);
632
+ }
633
+ if($shippingData['street'] !==$address['street']) {
634
+ $address->setStreet($shippingData['street']);
635
+ }
636
+ if($shippingData['city'] !==$address['city']) {
637
+ $address->setCity($shippingData['city']);
638
+ }
639
+ if($shippingData['postcode'] !==$address['postcode']) {
640
+ $address->setPostcode($shippingData['postcode']);
641
+ }
642
+ if($shippingData['telephone'] !==$address['telephone']) {
643
+ $address->setTelephone($shippingData['telephone']);
644
+ }
645
+ $address->save();
646
+
647
+
648
}
649
650
651
public function loadMageOrder() {
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) {
659
+ // if exists
660
+ $Mageorder = Mage::getModel('sales/order')->loadByIncrementId($orderInc);
661
+ if ($Mageorder->getId()) {
662
+ return $Mageorder;
663
+ }
664
+ }
665
+ }
666
+ return false;
667
}
668
669
670
private function debugLog($message) {
671
+
672
+ if($this->orderid !== "") {
673
+ $message = $this->orderid." | ".$message;
674
+ }
675
+ $this->log->LogInfo($message);
676
+
677
+ $this->log2->LogInfo($message);
678
}
679
680
public function prescanOrder(BeezupOMOrderResult $order) {
681
+ $retorno = array();
682
+ $orderItems = $order->getOrderItems();
683
+ foreach ($orderItems as $item)
684
+ {
685
+
686
+ if ($item->getOrderItemOrderItemType () !== 'Product')
687
+ {
688
+ // continue;
689
+ }
690
+ $beezup_store = $item->getOrderItemBeezUPStoreId(); //beezup storeid
691
+ $mage_storeid = $this->checkOrderStore($beezup_store); //magento storeid
692
+ $marketplace_orderid = $item->getOrderItemMarketPlaceProductId();
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
+ $retorno['store'] = $mage_storeid;
705
+ $this->debugLog("Store Matching succesful, Beezup Store: ".$beezup_store." , Magento Store Id: ".$mage_storeid);
706
+ $product_ImportedMerchantId = $item->getOrderItemMerchantImportedProductId();
707
+ $product_MerchantId = $item->getOrderItemMerchantProductId();
708
+
709
+ $product_quantity = $item->getOrderItemQuantity();
710
+ $product_price = $item->getOrderItemItemPrice();
711
+ $product_title = $item->getOrderItemTitle();
712
+ $product_image = $item->getOrderItemImageUrl();
713
+ if(strpos($marketplace_orderid,'INTERETBCA') !== false || strpos($marketplace_orderid,'interetbca') !== false) {
714
+ $retorno['discounts']= $item->getOrderItemTotalPrice();
715
+ } else {
716
+ $product = $this->getMageProduct($product_ImportedMerchantId , $product_MerchantId , $beezup_store );
717
+ if($product) {
718
+ $mage_productId = $product->getId();
719
+ $stocklevel = (int)Mage::getModel('cataloginventory/stock_item')
720
+ ->loadByProduct($product)->getQty();
721
+
722
+ $retorno['products'][] = array("id" => $mage_productId, "qty" => $product_quantity, "price" => $product_price, "curr_stock" => $stocklevel);
723
+ //producto existe
724
+ } else {
725
+ //vendria if de si activada opcion de crear producto creamos
726
+ if(!$this->debug) {
727
+ return false;
728
+ }
729
+ $product_data = array(
730
+ "sku" => $product_ImportedMerchantId,
731
+ "sku2" => $product_MerchantId,
732
+ "qty" => $product_quantity,
733
+ "price" => $product_price,
734
+ "title" => $product_title,
735
+ "image" => $product_image,
736
+ "storeId" => $mage_storeid
737
+ );
738
+ $product = $this->createProduct($product_data);
739
+ if(!$product) {
740
+ return false;
741
+ }
742
+ $stocklevel = (int)Mage::getModel('cataloginventory/stock_item')
743
+ ->loadByProduct($product)->getQty();
744
+ $mage_productId = $product->getId();
745
+ $retorno['products'][] = array("id" => $mage_productId, "qty" => $product_quantity, "price" => $product_price, "curr_stock" => $stocklevel);
746
+ }
747
+ }
748
+ }
749
+
750
+ return $retorno;
751
}
752
753
754
755
public function matchProductAttributes($importedId, $storeId) {
756
+ $product = null;
757
+ $helper = Mage::helper('beezup');
758
+ $attributes = $helper->getConfig('beezup/marketplace/attributes');
759
+ $attributes = unserialize ($attributes);
760
+
761
+ foreach($attributes['attributes'][$storeId ] as $attribute) {
762
+ $att = explode("|", $attribute);
763
+ if($storeId == $att[1]) {
764
+
765
+ $product=Mage::getModel('catalog/product')->loadByAttribute($att[0],$importedId);
766
+ if($product) {
767
+ break;
768
+ }
769
+ }
770
+ }
771
+
772
+ return $product;
773
}
774
775
776
777
public function getMageProduct($importedId, $merchantId, $storeId){
778
+ try {
779
+ $product=Mage::getModel('catalog/product')->load($importedId);
780
+ if (!$product->getId() || $product->getId() !== $importedId ){
781
+ $product = $this->matchProductAttributes($importedId, $storeId);
782
+ if($product == null || !is_object($product)) {
783
+ $product=Mage::getModel('catalog/product')->load($merchantId);
784
+ if(!$product->getId() || $product->getId() !== $merchantId ) {
785
+ $product = $this->matchProductAttributes($merchantId, $storeId);
786
+
787
+ }
788
+ }
789
+ }
790
+
791
+ if(is_object($product)) {
792
+ if($product->getId()) {
793
+ $this->debugLog("Product Matching succesful, Beezup Imported Id: ".$importedId." , Magento Product Id: ".$product->getId());
794
+ return $product;
795
+ }}
796
+ $this->log->LogError($this->orderid. "| No Product Matching, Product ".$importedId." could not be found");
797
+ $this->log2->LogError($this->orderid. "| No Product Matching, Product ".$importedId." could not be found");
798
+ return false;
799
+ }catch(Exception $e){
800
+ $this->log->LogError($this->orderid. "| Product ".$importedId." could not be found, error: ".$e->getMessage());
801
+ $this->log2->LogError($this->orderid. "| Product ".$importedId." could not be found, error: ".$e->getMessage());
802
+ return false;
803
+ //error no se pudo crear la orden
804
+
805
+ }
806
}
807
808
809
public function checkOrderStore($storeId ) {
810
+ $helper = Mage::helper('beezup');
811
+ $stores = $helper->getConfig('beezup/marketplace/stores');
812
+ $stores = unserialize ($stores);
813
+ foreach($stores as $store) {
814
+ if(isset($store[$storeId]) && $store[$storeId] > 0) {
815
+ return $store[$storeId];
816
+ }
817
+ }
818
+ return false;
819
}
820
821
822
823
/**
824
+ * @return BeezupOMOrderService
825
*/
826
public function getOrderService(){
827
+ if ($this->oOrderService === null){
828
+ $this->oOrderService = $this->createOrderService();
829
+ // enchufamos debug mode, esta activado? false true $this->oOrderService->setDebugMode(false);
830
+ }
831
+ return $this->oOrderService;
832
}
833
834
/**
835
+ * @return BeezupOMOrderService
836
*/
837
protected function createOrderService(){
838
+
839
+ return new BeezupOMOrderService($this->createRepository() );
840
}
841
842
protected function createRepository() {
843
+ if ($this->repository == null) {
844
+ $this->repository = new BeezupRepository();
845
+ }
846
+ return $this->repository;
847
+
848
}
849
850
851
852
853
private function createCustomer($customer_email , $data) {
854
+ $password = $this->orderid;
855
+ $this->debugLog("Creating new Customer");
856
+ $customer = Mage::getModel('customer/customer');
857
+ $customer->setWebsiteId(Mage::app()->getWebsite()->getId());
858
+ $customer->loadByEmail($customer_email);
859
+ if(!$customer->getId()) {
860
+ $customer->setEmail($customer_email);
861
+ $customer->setFirstname($data['firstname']);
862
+ $customer->setLastname($data['lastname']);
863
+ $customer->setPassword($password);
864
+ try {
865
+ $customer->save();
866
+ $customer->setConfirmation(null);
867
+ $customer->save();
868
+ $this->debugLog("Customer created succesfully");
869
+ return $customer;
870
+ //Make a "login" of new customer
871
+ // Mage::getSingleton('customer/session')->loginById($customer->getId());
872
+ }
873
+
874
+ catch (Exception $ex) {
875
+ //Zend_Debug::dump($ex->getMessage());
876
+ //GUARDAR ERROR CREACION USUARIO
877
+ $this->log2->LogError($this->orderid. " | Customer importation failed: ".$ex->getMessage());
878
+ return false;
879
+ }
880
+
881
+ } else {
882
+ $this->debugLog("Creating already exists, returning customer object");
883
+ return $customer;
884
+ }
885
}
886
887
888
889
public function addOrder($data, $oLink, $stop = false) {
890
+
891
+
892
+ try {
893
+ $helper = Mage::helper('beezup');
894
+ $addStock = $helper->getConfig('beezup/marketplace/available_products');
895
+ $baseCurrencyCode = Mage::app()->getStore()->getBaseCurrencyCode();
896
+ $quote = Mage::getModel('sales/quote')
897
+ ->setStoreId($data['storeid']);
898
+ $quote->setCustomerEmail($data['order_customer_email']);
899
+
900
+
901
+ $currency = Mage::getModel('directory/currency')->load($data['order_currency']);
902
+ $quote->setForcedCurrency($currency);
903
+
904
+ $blnCreate = true;
905
+ $total_new_price = 0;
906
+ foreach($data['products'] as $prod) {
907
+ if($prod['qty']==0) {
908
+ $blnCreate = false;
909
+ break;
910
}
911
+ $prod_totality_price = $prod['price']*$prod['qty'];
912
+ $total_new_price = $total_new_price + $prod_totality_price;
913
+ $product = Mage::getModel('catalog/product')->load($prod['id']);
914
+ $buyInfo = array(
915
+ 'qty' => $prod['qty'],
916
+ );
917
+ $this->debugLog("Adding ".$prod['qty']." product/s with id ".$product->getId()." to order, with Beezup Price: ".$prod['price']);
918
+ //echo "Product ".$product->getId()."<br><br>";
919
+ //para no perder stock:
920
+ //Mage::getModel('cataloginventory/stock')->backItemQty($productId,$new_qty);
921
922
923
+ if($addStock == 1) {
924
+ $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product);
925
+
926
+ if ($stock->getQty() < $prod['qty'] && $product->getStockItem()->getMaxSaleQty() >= $prod['qty']) {
927
+ $this->debugLog("Product ".$product->getId()." Stock = 0, Updating to ".$prod['qty']." to generate Order");
928
+ // Mage::getModel('cataloginventory/stock')->backItemQty($product->getId(),$prod['qty']);
929
+ //$this->_updateStocks(array("id_product" => $product->getId(), "qty" => $prod['qty']));
930
+ $product->setStockData(
931
+ array(
932
+ 'is_in_stock' => 1,
933
+ 'qty' => $prod['qty'],
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
+ }
943
+ //fin para no perder stock
944
+
945
+ /*
946
+ $tax_class = $product->getTaxClassId();
947
+ $product->setTaxClassId(0);
948
+ $product->getResource()->saveAttribute($product, 'tax_class_id'); */
949
+ $price = $prod['price'];
950
+
951
+ $quote_item = Mage::getModel('beezup/quote_item');
952
+ $quote_item
953
+ ->setProduct($product)
954
+ ->setPrice((float) $price )
955
+ ->setCustomPrice((float)$price )
956
+ ->setOriginalCustomPrice((float) $price )
957
+ ->setQuote($quote)
958
+ ->setQty((integer) $prod['qty'])
959
+ ->setBeezupPrice((float) $price );
960
+
961
+
962
+ $quote->addItem($quote_item);
963
+
964
+ //$quote->addProduct($product, new Varien_Object($buyInfo))->setOriginalCustomPrice($price)->setCustomPrice($price);
965
+
966
+ /*
967
+ $product->setTaxClassId($tax_class);
968
+
969
+ $product->getResource()->saveAttribute($product, 'tax_class_id');
970
+ */
971
+ }
972
+
973
+ if($blnCreate) {
974
+ $addressData = array(
975
+ 'firstname' => ($data['order_customer']) ? $data['order_customer'] : "empty",
976
+ 'lastname' => ($data['order_lastname']) ? $data['order_lastname'] : "empty",
977
+ 'street' => ($data['order_address']) ? $data['order_address'] : "empty",
978
+ 'city' => ($data['order_city']) ? $data['order_city'] : "empty",
979
+ 'postcode' => ($data['order_postalCode']) ? $data['order_postalCode'] : "empty",
980
+ 'telephone' => ($data['order_customer_phone']) ? $data['order_customer_phone'] : "empty",
981
+ 'country_id' => ($data['order_country_iso']) ? $data['order_country_iso'] : "empty",
982
+ 'region_id' => ($data['order_region ']) ? substr($data['order_region '], 0,2) : "EM"// id from directory_country_region table
983
+ );
984
+
985
+ $shippingData = array(
986
+ 'firstname' => ($data['shipping_name']) ? $data['shipping_name'] : "empty",
987
+ 'lastname' => ($data['shipping_lastname']) ? $data['shipping_lastname'] : "empty",
988
+ 'street' => ($data['shipping_address']) ? $data['shipping_address'] : "empty",
989
+ 'city' => ($data['shipping_city']) ? $data['shipping_city'] : "empty",
990
+ 'postcode' => ($data['shipping_postalCode']) ? $data['shipping_postalCode'] : "empty",
991
+ 'telephone' => ($data['shipping_phone']) ? $data['shipping_phone'] : "empty",
992
+ 'country_id' => ($data['shipping_country_iso']) ? $data['shipping_country_iso'] : "empty",
993
+ 'region_id' => ($data['shipping_region']) ? substr($data['shipping_region'], 0, 2) : "EM" // id from directory_country_region table
994
+ );
995
+
996
+ if($this->blnCreateCustomer) {
997
+
998
+ $mage_customer = $this->createCustomer($data['order_customer_email'], $addressData);
999
+ $quote->assignCustomer($mage_customer);
1000
+ }
1001
+
1002
+
1003
+ $payment_method = $helper->getConfig('beezup/marketplace/payment_method');
1004
+ $billingAddress = $quote->getBillingAddress()->addData($addressData);
1005
+ $shippingAddress = $quote->getShippingAddress()->addData($shippingData);
1006
+ $shipping_cost = (float) $data['order_shippingPrice'];
1007
+ if($data['order_shippingPrice'] == 0) {
1008
+ $shipping_cost = 20000;
1009
+ }
1010
+ $total_new_price = $total_new_price + $data['order_shippingPrice'] ;
1011
+ Mage::unregister('shipping_cost');
1012
+ Mage::register('shipping_cost', $shipping_cost);
1013
+ $this->debugLog("Adding Order Shipping Cost: ". $data['order_shippingPrice']);
1014
+
1015
+ $shippingAddress->setCollectShippingRates(true)->collectShippingRates()
1016
+ ->setShippingMethod('flatrate_flatrate')
1017
+ ->setPaymentMethod($payment_method);
1018
+
1019
+ //$shippingAddress->addTotal(array("code" => "specialfee", "title" => "Special Fee", "value" => 20));
1020
+ $quote->getPayment()->importData(array('method' => $payment_method));
1021
+
1022
+ $quote->collectTotals()->save();
1023
+
1024
+ $service = Mage::getModel('sales/service_quote', $quote);
1025
+ $service->submitAll();
1026
+ $order = $service->getOrder();
1027
+
1028
+
1029
+
1030
+ $quoteId = $order->getQuoteId();
1031
+ //$this->setStatus($data['order_status'], $order);
1032
+
1033
+ $orderid = $order->getId();
1034
+
1035
+ $resource = Mage::getSingleton('core/resource');
1036
+ $writeConnection = $resource->getConnection('core_write');
1037
+ $table = $resource->getTableName('sales/order_grid');
1038
+ $this->debugLog("Adding Beezup Marketplace Information to Order");
1039
+ $marketplace = $data['marketplace'];
1040
+ $marketplace_business_code = ucfirst(strtolower($data['marketplace_business_code']));
1041
+ $beezup_name = $data['order_customer'];
1042
+ $market_order_id =$this->orderid;
1043
+ $beezup_order_id = $oLink->getBeezupOrderUUID();
1044
+ $beezup_status = $data['order_status'];
1045
+ $beezup_last_modification_date = $oLink->getOrderLastModificationUtcDate();
1046
+ $beezup_last_modification_date = $beezup_last_modification_date->date;
1047
+ $beezup_marketplace_status = $oLink->getOrderStatusMarketPlaceStatus();
1048
+ $beezup_purchase_date = $oLink->getOrderPurchaseUtcDate();
1049
+ $beezup_purchase_date = $beezup_purchase_date->date;
1050
+ $beezup_marketplace_last_modification_date = $oLink->getOrderMarketPlaceLastModificationUtcDate();
1051
+ $beezup_marketplace_last_modification_date = $beezup_marketplace_last_modification_date->date;
1052
+ /* $date = new DateTime($beezup_marketplace_last_modification_date);
1053
+ $beezup_marketplace_last_modification_date = $date->format('d-m-Y H:i:s'). "(UTC Time)";
1054
+ */
1055
+
1056
+ $beezup_total_paid = $oLink->getOrderTotalPrice()." ".$data['order_currency'];
1057
+ $beezup_account_id = $oLink->getAccountId();
1058
+ $beezup_comission = $oLink->getOrderTotalCommission()." ".$data['order_currency'];
1059
+ $tot_comm = $oLink->getOrderTotalCommission();
1060
+ if(empty($tot_comm ) || $tot_comm == 0) {
1061
+ $beezup_comission = 0;
1062
+ }
1063
+ $query = "UPDATE {$table} SET beezup_marketplace = '{$marketplace}', beezup_name = '{$beezup_account_id}', beezup_order = 1, beezup_market_order_id = '{$market_order_id}',
1064
+ beezup_order_id = '{$beezup_order_id}', beezup_status = '{$beezup_status}', beezup_last_modification_date = '{$beezup_last_modification_date}',
1065
+ beezup_marketplace_status = '{$beezup_marketplace_status}', beezup_purchase_date = '{$beezup_purchase_date}', beezup_marketplace_last_modification_date = '{$beezup_marketplace_last_modification_date}',
1066
+ beezup_total_paid = '{$beezup_total_paid}', beezup_etag = '{$data['etag']}' , beezup_comission = '{$beezup_comission}', beezup_marketplace_business_code = '{$marketplace_business_code}'
1067
+ WHERE entity_id = ". (int)$orderid;
1068
+ $writeConnection->query($query);
1069
+ $disc_price = 0;
1070
+ if(!empty($data['discounts']) && $data['discounts'] >0) {
1071
+
1072
+
1073
+ $disc_price = round($data['discounts'],2);
1074
+ $total_new_price = $total_new_price+$disc_price;
1075
+ $table_address = $resource->getTableName("sales/quote_address");
1076
+
1077
+ $query = "update {$table_address} set beezup_fee = '{$disc_price}' where quote_id = '{$quoteId}' and address_type = 'shipping'";
1078
+ $writeConnection->query($query);
1079
+ $this->debugLog("Adding CDISCOUNT products with total price: ".$disc_price);
1080
+ }
1081
+
1082
+ //if order id exists and has been created
1083
+ if ($orderid)
1084
+ {
1085
+ //we send order id to beezup
1086
+ $this->debugLog("Sending Magento Order Id to Beezup, Magento Order Id: ".$orderid);
1087
+ $oResult = new BeezupOMSetOrderIdValues ();
1088
+ $oResult->setOrderMerchantOrderId ( $orderid )->setOrderMerchantECommerceSoftwareName ( 'Magento' )->setOrderMerchantECommerceSoftwareVersion ( Mage::getVersion() );
1089
+ $sendRequest = $this->getOrderService()->getClientProxy()->setOrderMerchantIdByLink($oLink->getLinkByRel('setMerchantOrderId'), $oResult);
1090
+ }
1091
+
1092
+ $grand_total = $order->getGrandTotal();
1093
+ $beezup_price = $oLink->getOrderTotalPrice() - $disc_price;
1094
+ if($grand_total != (float) $beezup_price && $beezup_price > 0) {
1095
+ $order->setGrandTotal((float) $beezup_price);
1096
+ $order->setBaseGrandTotal((float) $beezup_price);
1097
+ $diff = (((float) $beezup_price) - $grand_total);
1098
+
1099
+ $order->setTaxAmount($order->getTaxAmount() + $diff);
1100
+ $order->save();
1101
+ }elseif($grand_total != (float)$beezup_price && $beezup_price < 1) {
1102
+
1103
+ $order->setGrandTotal((float) $total_new_price);
1104
+ $order->setBaseGrandTotal((float) $total_new_price);
1105
+ $diff = (((float) $total_new_price) - $grand_total);
1106
+
1107
+ $order->setTaxAmount($order->getTaxAmount() + $diff);
1108
+ $order->save();
1109
+ }
1110
+
1111
+ $products = Mage::getResourceModel('sales/order_item_collection')
1112
+ ->setOrderFilter($orderid);
1113
+ foreach($products as $product) {
1114
+ $product->setBaseOriginalPrice($product->getOriginalPrice());
1115
+ $product->setBaseTaxAmount($product->getTaxAmount());
1116
+ $product->setBaseTaxInvoiced($product->getTaxAmount());
1117
+ $product->setBasePriceInclTax($product->getPriceInclTax());
1118
+ $product->setBaseRowTotalInclTax($product->getRowTotalInclTax());
1119
+ $product->save();
1120
+ }
1121
+ $order->setBaseTaxAmount($order->getTaxAmount());
1122
+ $order->setBaseTaxInvoiced($order->getTaxAmount());
1123
+ $order->setBaseTotalInvoiced($order->getTotalPaid());
1124
+ $order->setBaseTotalPaid($order->getTotalPaid());
1125
+ $order->setBaseGrandTotal($order->getTotalPaid());
1126
+ $order->setBaseSubtotalInclTax($order->getSubtotalInclTax());
1127
+ $order->save();
1128
+
1129
+ $this->setStatus($data['order_status'], $order);
1130
+ $this->mage_order_id = $orderid;
1131
+ $this->debugLog("Order imported succesfully, Magento Order Id: ".$orderid);
1132
+ } else {
1133
+ //product stock = 0 we dont create order
1134
+ $this->log->LogError($this->orderid. "| Order ".$data['market_place_order_id']." could not be imported, error: Stock from Beezup product = 0 ");
1135
+ $this->log2->LogError($this->orderid. "| Order ".$data['market_place_order_id']." could not be imported, error: Stock from Beezup product = 0 ");
1136
+ }
1137
+ }catch(Exception $e){
1138
+
1139
+
1140
+ if($stop) {
1141
+ $this->log->LogError($this->orderid. "| Order ".$data['market_place_order_id']." could not be imported, error: ".$e->getMessage());
1142
+ $this->log2->LogError($this->orderid. "| Order ".$data['market_place_order_id']." could not be imported, error: ".$e->getMessage());
1143
+ $this->restoreStock($data);
1144
+ } else {
1145
+ $this->debugLog("Order Import failed, Trying to import Order Again");
1146
+ $this->addOrder($data, $oLink, true);
1147
+
1148
+ }
1149
+ //error no se pudo crear la orden
1150
+
1151
+ }
1152
+
1153
+
1154
+
1155
+ }
1156
+
1157
+
1158
+
1159
+ public function restoreStock($data) {
1160
+
1161
+ try {
1162
+ foreach($data['products'] as $prod) {
1163
+ $product = Mage::getModel('catalog/product')->load($prod['id']);
1164
+ $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product);
1165
+ if ($stock->getQty() != $prod['curr_stock'] ) {
1166
+ $this->debugLog("Restoring Stock from Product ".$product->getId()." to: ".$prod['curr_stock'] ." due to Order Fail");
1167
+ $stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product);
1168
+ $stockItem->setData('is_in_stock', 0);
1169
+ $stockItem->setData('qty', $prod['curr_stock']);
1170
+ $stockItem->save();
1171
+ $product->save();
1172
+ }
1173
+
1174
+ }
1175
+ } catch(Exception $e){
1176
+ $this->log->LogError($this->orderid. "| Failed Restoring Product Stock: ".$e->getMessage());
1177
+ $this->log2->LogError($this->orderid. "| Failed Restoring Product Stock: ".$e->getMessage());
1178
+ }
1179
+
1180
+ }
1181
+
1182
+
1183
+
1184
+ private function createProduct($data) {
1185
+
1186
+ $sku = $data['sku'];
1187
+ if(empty($data['sku'])) {
1188
+ $sku = $data['sku2'];
1189
+ }
1190
+
1191
+ Mage::app()->setCurrentStore($data['storeId']);
1192
+ $product = Mage::getModel('catalog/product');
1193
+ // if(!$product->getIdBySku('testsku61')):
1194
+
1195
+ try{
1196
+ $product
1197
+ // ->setStoreId(1) //you can set data in store scope
1198
+ ->setWebsiteIds(array($data['storeId'])) //website ID the product is assigned to, as an array
1199
+ ->setAttributeSetId($product->getDefaultAttributeSetId()) //ID of a attribute set named 'default'
1200
+ ->setTypeId('simple') //product type
1201
+ ->setCreatedAt(strtotime('now')) //product creation time
1202
+ ->setSku($sku ) //SKU
1203
+ ->setWeight(0)
1204
+ ->setName($data['title']) //product name
1205
+ ->setStatus(1) //product status (1 - enabled, 2 - disabled)
1206
+ ->setTaxClassId(4) //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
1207
+ ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE ) //catalog and search visibility
1208
+ ->setPrice($data['price']) //price in form 11.22
1209
+ ->setMsrpEnabled(1) //enable MAP
1210
+ ->setMsrpDisplayActualPriceType(1) //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
1211
+ ->setMsrp(0) //Manufacturer's Suggested Retail Price
1212
+ ->setMetaTitle('')
1213
+ ->setMetaKeyword('')
1214
+ ->setMetaDescription('')
1215
+ ->setDescription($data['title'])
1216
+ ->setShortDescription($data['title'])
1217
+ // ->setMediaGallery (array('images'=>array (), 'values'=>array ())) //media gallery initialization
1218
+ //->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
1219
+ ->setStockData(array(
1220
+ 'use_config_manage_stock' => 0, //'Use config settings' checkbox
1221
+ 'manage_stock'=>1, //manage stock
1222
+ 'min_sale_qty'=>1, //Minimum Qty Allowed in Shopping Cart
1223
+ 'max_sale_qty'=>2, //Maximum Qty Allowed in Shopping Cart
1224
+ 'is_in_stock' => 1, //Stock Availability
1225
+ 'qty' => 1 //qty
1226
+ )
1227
+ );
1228
+ $product->save();
1229
+ return $product;
1230
+
1231
+ }catch(Exception $e){
1232
+ //log exception
1233
+ $this->log->LogError($this->orderid."| Product ".$sku." could not be created, error: ".$e->getMessage());
1234
+ $this->log2->LogError($this->orderid."| Product ".$sku." could not be created, error: ".$e->getMessage());
1235
+ return false;
1236
+ }
1237
+ }
1238
+
1239
+
1240
+
1241
+ public function setStatus($status, $order) {
1242
+ $helper = Mage::helper('beezup');
1243
+ $retorno = "";
1244
+ $blnCancel = false;
1245
+ $blnHold = false;
1246
+ switch($status) {
1247
+ case "New" :
1248
+ $this->debugLog("Setting Order Status to New");
1249
+ $retorno = $helper->getConfig('beezup/marketplace/status_new');
1250
+ break;
1251
+ case "InProgress" :
1252
+ $this->debugLog("Setting Order Status to InProgress");
1253
+ $retorno = $helper->getConfig('beezup/marketplace/status_progress');
1254
+ $this->payOrder($order);
1255
+ break;
1256
+ case "Aborted" :
1257
+ $this->debugLog("Setting Order Status to Aborted");
1258
+ $retorno = $helper->getConfig('beezup/marketplace/status_aborted');
1259
+ $blnHold = true;
1260
+
1261
+
1262
+ break;
1263
+ case "Closed" :
1264
+ $this->debugLog("Setting Order Status to Closed");
1265
+ $blnCancel =true;
1266
+ $retorno = $helper->getConfig('beezup/marketplace/status_closed');
1267
+ $this->payOrder($order);
1268
+ break;
1269
+ case "Canceled" :
1270
+ $this->debugLog("Setting Order Status to Cancelled");
1271
+ $retorno = $helper->getConfig('beezup/marketplace/status_cancelled');
1272
+
1273
+ break;
1274
+ case "Shipped" :
1275
+ $this->debugLog("Setting Order Status to Shipped");
1276
+ $retorno = $helper->getConfig('beezup/marketplace/status_shipped');
1277
+ $this->payOrder($order);
1278
+ break;
1279
+
1280
+ }
1281
+ $order->setData('state',$retorno);
1282
+ $order->setStatus($retorno);
1283
+ $history = $order->addStatusHistoryComment('Order was set to '.$retorno.' by Beezup.', false);
1284
+ $history->setIsCustomerNotified(false);
1285
+ $order->save();
1286
+ if($blnCancel) {
1287
+ $order->cancel()->save();
1288
+ }
1289
+ if($blnHold) {
1290
+ $order->hold()->save();
1291
+ }
1292
+
1293
+ return $retorno;
1294
+
1295
+ }
1296
+
1297
+
1298
+ public function getStatus($status1) {
1299
+ $helper = Mage::helper('beezup');
1300
+ $retorno = "";
1301
+ $status = strtolower($status1);
1302
+
1303
+ if($status == strtolower($helper->getConfig('beezup/marketplace/status_new') )) {
1304
+ $retorno = "New";
1305
+
1306
+ } elseif($status == strtolower($helper->getConfig('beezup/marketplace/status_progress') ) ){
1307
+ $retorno = "InProgress";
1308
+
1309
+
1310
+ }
1311
+ elseif($status == strtolower($helper->getConfig('beezup/marketplace/status_aborted') )) {
1312
+
1313
+ $retorno = "Aborted" ;
1314
+ }
1315
+ elseif($status == strtolower($helper->getConfig('beezup/marketplace/status_closed') )) {
1316
+ $retorno = "Closed";
1317
+
1318
+ }
1319
+ elseif($status == strtolower($helper->getConfig('beezup/marketplace/status_cancelled')) ) {
1320
+
1321
+ $retorno = "Canceled";
1322
+ }
1323
+ elseif($status == strtolower($helper->getConfig('beezup/marketplace/status_shipped') )) {
1324
+
1325
+ $retorno = "Shipped";
1326
+ }
1327
+
1328
+
1329
+ return $retorno;
1330
+
1331
+ }
1332
+
1333
+
1334
+ public function checkMarketOrderExists($orderid) {
1335
+ $resource = Mage::getSingleton('core/resource');
1336
+ $readConnection = $resource->getConnection('core_read');
1337
+ $table = $resource->getTableName('sales/order_grid');
1338
+ $query = 'SELECT increment_id FROM ' . $table . ' WHERE beezup_order = 1 and beezup_market_order_id = \''
1339
+ . $orderid . '\' LIMIT 1';
1340
+ $order = $readConnection->fetchOne($query);
1341
+ if($order && !empty($order) && $this->orderId !== "") {
1342
+ return $order;
1343
+ }
1344
+ return false;
1345
+
1346
+ }
1347
+
1348
+ public function payOrder($order) {
1349
+ try {
1350
+ $this->debugLog("Generating Order Payment Invoice");
1351
+ if($order->canInvoice()) {
1352
+ $invoice = $order->prepareInvoice()
1353
+ ->setTransactionId($order->getId())
1354
+ ->addComment("Invoice created from Beezup.")
1355
+ ->register()
1356
+ ->pay();
1357
+ $transaction_save = Mage::getModel('core/resource_transaction')
1358
+ ->addObject($invoice)
1359
+ ->addObject($invoice->getOrder());
1360
+ $transaction_save->save();
1361
+ $this->debugLog("Order Payment Invoice Generated Succesfully");
1362
+ }
1363
+ }
1364
+ catch(Exception $e){
1365
+ //log exception
1366
+ $this->log->LogError($this->orderid."| Order Payment Invoice could not be generated, error: ".$e->getMessage());
1367
+ $this->log2->LogError($this->orderid."| Order Payment Invoice could not be generated, error: ".$e->getMessage());
1368
+ }
1369
+ }
1370
+
1371
+
1372
+
1373
+
1374
+
1375
+
1376
+ }
app/code/community/BeezUp/Block/Xml.php CHANGED
@@ -6,8 +6,9 @@
6
/**
7
Xml permet de r�cup�rer tous les produits simples
8
**/
9
- public function getXml()
10
{
11
$base_url = Mage::getBaseUrl();
12
/* Load Model and Helper */
13
$beezup = Mage::getModel('beezup/products');
@@ -48,7 +49,7 @@
48
$xml = "\xEF\xBB\xBF";
49
$xml .= '<?xml version="1.0" encoding="utf-8"?>' . PHP_EOL . '<catalog>' . PHP_EOL;
50
51
- $products = $beezup->getProducts();
52
if($many_images == 1) {
53
$backendModel = $products->getResource()->getAttribute('media_gallery')->getBackend();
54
}
@@ -161,7 +162,7 @@
161
/**
162
Configurable permet de r�cup�rer tous les produits (p�re, enfant et simple)
163
**/
164
- public function getXmlConfigurable()
165
{
166
$base_url = Mage::getBaseUrl();
167
/* Load Model and Helper */
@@ -202,8 +203,8 @@
202
$xml .= '<?xml version="1.0" encoding="utf-8"?>' . PHP_EOL . '<catalog>' . PHP_EOL;
203
204
//r�cup�re tous les produits
205
- $products = $beezup->getProducts();
206
- $childs = $beezup->getConfigurableProducts(true);
207
$backendModel = $products->getResource()->getAttribute('media_gallery')->getBackend();
208
$products->addAttributeToFilter('type_id', Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE);
209
@@ -408,7 +409,7 @@
408
}
409
}
410
411
- $product_simple = $beezup->getProductsSimple();
412
$backendModelSimple = $product_simple->getResource()->getAttribute('media_gallery')->getBackend();
413
foreach ($product_simple as $p) {
414
@@ -503,7 +504,7 @@
503
/**
504
Children permet de r�cup�rer tous les produits enfants
505
**/
506
- public function getXmlChild()
507
{
508
/* Load Model and Helper */
509
$beezup = Mage::getModel('beezup/products');
@@ -542,7 +543,7 @@
542
$xml = "\xEF\xBB\xBF";
543
$xml .= '<?xml version="1.0" encoding="utf-8"?>' . PHP_EOL . '<catalog>' . PHP_EOL;
544
545
- $childs = $beezup->getConfigurableProducts(false);
546
547
foreach ($childs as $c) {
548
@@ -797,7 +798,7 @@
797
798
protected function createFile($type, $xmlData)
799
{
800
- $fp = fopen('beezup/tmp/'.$type, 'w');
801
if ($fp == false)
802
{
803
echo 'Fail to create file';
@@ -808,7 +809,7 @@
808
809
protected function deleteFeed($type)
810
{
811
- unlink('beezup/tmp/'.$type);
812
}
813
814
protected function needRefreshing($type)
@@ -817,7 +818,7 @@
817
818
$delay = $helper->getConfig('beezup/flux/cachedelay') * 60;
819
$nowtime = time();
820
- $fileTime = filemtime('beezup/tmp/'.$type);
821
if (($nowtime - $fileTime) >= $delay)
822
return (true);
823
else
@@ -858,14 +859,14 @@
858
/*
859
$this->getAssociatedProducto(true);
860
return;*/
861
-
862
if (!$this->createFolder()) // Si on rencontre des probl�mes de cr�ation de dossier on retourne rien
863
return;
864
if ($this->getConfigurable()){ // Appel de l'url http://site.com/beezup/catalog/configurable
865
if ($this->needRefreshing('configurable')){
866
if (file_exists('beezup/tmp/configurable'))
867
$this->deleteFeed('configurable');
868
- $xmlData = $this->getXmlConfigurable();
869
$this->addText($xmlData);
870
if ($helper->getConfig('beezup/flux/cachedelay') != 0)
871
$this->createFile('configurable', $xmlData);
@@ -877,7 +878,7 @@
877
if ($this->needRefreshing('child')){
878
if (file_exists('beezup/tmp/child'))
879
$this->deleteFeed('child');
880
- $xmlData = $this->getXmlChild();
881
$this->addText($xmlData);
882
if ($helper->getConfig('beezup/flux/cachedelay') != 0)
883
$this->createFile('child', $xmlData);
@@ -889,7 +890,7 @@
889
if ($this->needRefreshing('xml')){
890
if (file_exists('beezup/tmp/xml'))
891
$this->deleteFeed('xml');
892
- $xmlData = $this->getXml();
893
$this->addText($xmlData);
894
if ($helper->getConfig('beezup/flux/cachedelay') != 0)
895
$this->createFile('xml', $xmlData);
6
/**
7
Xml permet de r�cup�rer tous les produits simples
8
**/
9
+ public function getXml($paginate = false)
10
{
11
+
12
$base_url = Mage::getBaseUrl();
13
/* Load Model and Helper */
14
$beezup = Mage::getModel('beezup/products');
49
$xml = "\xEF\xBB\xBF";
50
$xml .= '<?xml version="1.0" encoding="utf-8"?>' . PHP_EOL . '<catalog>' . PHP_EOL;
51
52
+ $products = $beezup->getProducts(false, $paginate);
53
if($many_images == 1) {
54
$backendModel = $products->getResource()->getAttribute('media_gallery')->getBackend();
55
}
162
/**
163
Configurable permet de r�cup�rer tous les produits (p�re, enfant et simple)
164
**/
165
+ public function getXmlConfigurable($paginate = false)
166
{
167
$base_url = Mage::getBaseUrl();
168
/* Load Model and Helper */
203
$xml .= '<?xml version="1.0" encoding="utf-8"?>' . PHP_EOL . '<catalog>' . PHP_EOL;
204
205
//r�cup�re tous les produits
206
+ $products = $beezup->getProducts(false, $paginate);
207
+ $childs = $beezup->getConfigurableProducts(true, $paginate);
208
$backendModel = $products->getResource()->getAttribute('media_gallery')->getBackend();
209
$products->addAttributeToFilter('type_id', Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE);
210
409
}
410
}
411
412
+ $product_simple = $beezup->getProductsSimple($paginate);
413
$backendModelSimple = $product_simple->getResource()->getAttribute('media_gallery')->getBackend();
414
foreach ($product_simple as $p) {
415
504
/**
505
Children permet de r�cup�rer tous les produits enfants
506
**/
507
+ public function getXmlChild($paginate = false)
508
{
509
/* Load Model and Helper */
510
$beezup = Mage::getModel('beezup/products');
543
$xml = "\xEF\xBB\xBF";
544
$xml .= '<?xml version="1.0" encoding="utf-8"?>' . PHP_EOL . '<catalog>' . PHP_EOL;
545
546
+ $childs = $beezup->getConfigurableProducts(false, $paginate);
547
548
foreach ($childs as $c) {
549
798
799
protected function createFile($type, $xmlData)
800
{
801
+ $fp = fopen(Mage::getBaseDir('base').'/beezup/tmp/'.$type, 'w');
802
if ($fp == false)
803
{
804
echo 'Fail to create file';
809
810
protected function deleteFeed($type)
811
{
812
+ unlink(Mage::getBaseDir('base').'/beezup/tmp/'.$type);
813
}
814
815
protected function needRefreshing($type)
818
819
$delay = $helper->getConfig('beezup/flux/cachedelay') * 60;
820
$nowtime = time();
821
+ $fileTime = filemtime(Mage::getBaseDir('base').'/beezup/tmp/'.$type);
822
if (($nowtime - $fileTime) >= $delay)
823
return (true);
824
else
859
/*
860
$this->getAssociatedProducto(true);
861
return;*/
862
+ $paginate = $this->getPagination();
863
if (!$this->createFolder()) // Si on rencontre des probl�mes de cr�ation de dossier on retourne rien
864
return;
865
if ($this->getConfigurable()){ // Appel de l'url http://site.com/beezup/catalog/configurable
866
if ($this->needRefreshing('configurable')){
867
if (file_exists('beezup/tmp/configurable'))
868
$this->deleteFeed('configurable');
869
+ $xmlData = $this->getXmlConfigurable($paginate);
870
$this->addText($xmlData);
871
if ($helper->getConfig('beezup/flux/cachedelay') != 0)
872
$this->createFile('configurable', $xmlData);
878
if ($this->needRefreshing('child')){
879
if (file_exists('beezup/tmp/child'))
880
$this->deleteFeed('child');
881
+ $xmlData = $this->getXmlChild($paginate);
882
$this->addText($xmlData);
883
if ($helper->getConfig('beezup/flux/cachedelay') != 0)
884