Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
order.php
1<?php
2
4
7use \Bitrix\Main\SystemException;
8use \Bitrix\Main\ArgumentNullException;
14use \Bitrix\Sale\TradingPlatform\Logger;
15use \Bitrix\Sale\TradingPlatform\Ebay\Ebay;
17
18Loc::loadMessages(__FILE__);
19
20
21class Order extends DataProcessor
22{
23 protected $siteId;
24
25 public function __construct($params)
26 {
27 if(!isset($params["SITE_ID"]) || $params["SITE_ID"] == '')
28 throw new ArgumentNullException("SITE_ID");
29
30 $this->siteId = $params["SITE_ID"];
31 }
32
33 public function process($data)
34 {
35 if(!is_array($data))
36 throw new SystemException("Data must be an array! ".__METHOD__);
37
38 foreach($data as $order)
39 {
40 try
41 {
42 if(intval($this->processOrder($order)) > 0)
43 {
44 Ebay::log(
46 "EBAY_DATA_PROCESSOR_ORDER_PROCESSED",
47 $order["OrderID"],
49 "SALE_TP_EBAY_FDPO_ORDER_PROCESSED",
50 array("#ORDER_ID" => $order["OrderID"])
51 ),
52 $this->siteId
53 );
54 }
55 else
56 {
57 Ebay::log(
59 "EBAY_DATA_PROCESSOR_ORDER_ERROR",
60 $order["OrderID"],
62 "SALE_TP_EBAY_FDPO_ORDER_ERROR",
63 array("#ORDER_ID" => $order["OrderID"])
64 ),
65 $this->siteId
66 );
67 }
68 }
69 catch(SystemException $e)
70 {
71 Ebay::log(
73 "EBAY_DATA_PROCESSOR_ORDER_ERROR",
74 $order["OrderID"],
76 "SALE_TP_EBAY_FDPO_ORDER_ERROR",
77 array("#ORDER_ID" => $order["OrderID"])
78 ).".".$e->getMessage(),
79 $this->siteId
80 );
81 }
82 }
83
84 \Bitrix\Sale\TradingPlatform\Ebay\Agent::add('ORDER_ACK', $this->siteId, 1, true);
85 return true;
86 }
87
88 protected function getSku($ebaySku)
89 {
90 $result = "";
91 $sku = explode("_", $ebaySku);
92
93 if(isset($sku[1]) && $sku[1] <> '')
94 $result = $sku[1];
95
96 return $result;
97 }
98
99 protected function getSkuVariation($ebaySku)
100 {
101 $result = "";
102
103 $sku = explode("_", $ebaySku);
104
105 if(isset($sku[2]) && $sku[2] <> '')
106 $result = $sku[2];
107
108 return $result;
109 }
110
111 protected function normalizeTransactionsArray($transactArray)
112 {
113 foreach($transactArray["Transaction"] as $key => $transaction)
114 {
115 if(intval($key) !== $key)
116 $transactArray["Transaction"] = array($transactArray["Transaction"]);
117
118 break;
119 }
120
121 return $transactArray["Transaction"];
122 }
123
124 public function processOrder($orderEbay)
125 {
126 Ebay::log(Logger::LOG_LEVEL_DEBUG, "EBAY_DATA_PROCESSOR_ORDER_PROCESSING", $orderEbay["ExtendedOrderID"], print_r($orderEbay,true), $this->siteId);
127
128 /*
129 * only in this case order is completely ready for shipping
130 */
131
132 if($orderEbay["OrderStatus"]!= "Completed"
133 || !isset($orderEbay["CheckoutStatus"]["eBayPaymentStatus"])
134 || $orderEbay["CheckoutStatus"]["eBayPaymentStatus"] != "NoPaymentFailure"
135// || empty($orderEbay["PaymentClearedTime"])
136 )
137 {
138 Ebay::log(
140 "EBAY_DATA_PROCESSOR_ORDER_SKIPPED",
141 $orderEbay["ExtendedOrderID"],
143 "SALE_TP_EBAY_FDPO_ORDER_SKIPPED",
144 array("#ORDER_ID#" => $orderEbay["ExtendedOrderID"])
145 ),
146 $this->siteId
147 );
148 return array();
149 }
150
151 $ebay = \Bitrix\Sale\TradingPlatform\Ebay\Ebay::getInstance();
152 $settings = $ebay->getSettings();
153
154 if(!isset($settings[$this->siteId]["ORDER_PROPS"]) || !is_array($settings[$this->siteId]["ORDER_PROPS"]))
155 throw new SystemException("Can't get order props map");
156
157 $propsMap = $settings[$this->siteId]["ORDER_PROPS"];
158
159 $dbRes = TradeBindingCollection::getList(array(
160 "filter" => array(
161 "TRADING_PLATFORM_ID" => $ebay->getId(),
162 "EXTERNAL_ORDER_ID" => $orderEbay["ExtendedOrderID"]
163 )
164 ));
165
166 if($orderCorrespondence = $dbRes->fetch())
167 {
168 Ebay::log(
170 "EBAY_DATA_PROCESSOR_ORDER_ALREADY_EXIST",
171 $orderEbay["ExtendedOrderID"],
173 "SALE_TP_EBAY_FDPO_ORDER_SKIPPED_EXIST",
174 array("#ORDER_ID#" => $orderEbay["ExtendedOrderID"])
175 ),
176 $this->siteId
177 );
178
179 return array();
180 }
181
182 $registry = Sale\Registry::getInstance(Sale\Registry::REGISTRY_TYPE_ORDER);
184 $orderClass = $registry->getOrderClassName();
185
187 $order = $orderClass::create($this->siteId);
188 $order->setPersonTypeId($settings[$this->siteId]["PERSON_TYPE"]);
189 $propsCollection = $order->getPropertyCollection();
190
192 if(intval($propsMap["FIO"]) > 0)
193 {
194 $prop = $propsCollection->getItemByOrderPropertyId($propsMap["FIO"]);
195 $prop->setValue($orderEbay["ShippingAddress"]["Name"]);
196 }
197
198 if(intval($propsMap["CITY"]) > 0)
199 {
200 $prop = $propsCollection->getItemByOrderPropertyId($propsMap["CITY"]);
201 $prop->setValue($orderEbay["ShippingAddress"]["CityName"]);
202 }
203
204 if(intval($propsMap["PHONE"]) > 0)
205 {
206 $prop = $propsCollection->getItemByOrderPropertyId($propsMap["PHONE"]);
207 $prop->setValue($orderEbay["ShippingAddress"]["Phone"]);
208 }
209
210 if(intval($propsMap["ZIP"]) > 0)
211 {
212 $prop = $propsCollection->getItemByOrderPropertyId($propsMap["ZIP"]);
213 $prop->setValue($orderEbay["ShippingAddress"]["PostalCode"]);
214 }
215
216 if(intval($propsMap["ADDRESS"]) > 0)
217 {
218 $prop = $propsCollection->getItemByOrderPropertyId($propsMap["ADDRESS"]);
219 $prop->setValue(
220 $orderEbay["ShippingAddress"]["CountryName"]." ".
221 $orderEbay["ShippingAddress"]["CityName"]." ".
222 $orderEbay["ShippingAddress"]["Street1"]." ".
223 (!empty($orderEbay["ShippingAddress"]["Street2"]) ? $orderEbay["ShippingAddress"]["Street2"]." " : "")
224 );
225 }
226
227 $basket = null;
228 $bitrixOrderId = 0;
229 $userId = 0;
230 $orderLineItemsIds = array();
231 $transactionsArray = $this->normalizeTransactionsArray($orderEbay["TransactionArray"]);
232
233 foreach($transactionsArray as $transaction)
234 {
235 //if we have more than one transaction let's create user from the first
236 if($userId <= 0)
237 {
238 if(intval($propsMap["EMAIL"]) > 0 && !empty($transaction["Buyer"]["Email"]))
239 {
240 $prop = $propsCollection->getItemByOrderPropertyId($propsMap["EMAIL"]);
241 $prop->setValue($transaction["Buyer"]["Email"]);
242
243 $userId = $this->createUser(
244 $transaction["Buyer"]["Email"],
245 array(
246 "NAME" => $transaction["Buyer"]["UserFirstName"],
247 "LAST_NAME" => $transaction["Buyer"]["UserLastName"]
248 )
249 );
250 }
251
252 if($userId <= 0)
253 $userId = \CSaleUser::GetAnonymousUserID();
254 }
255
256 if(intval($userId > 0))
257 $order->setFieldNoDemand("USER_ID", $userId);
258
259 $fUserId = null;
260
261 if ($order->getUserId() > 0)
262 $fUserId = Fuser::getIdByUserId($order->getUserId());
263
265 if(!$basket)
266 {
267 $basketClass = $registry->getBasketClassName();
268 $basket = $basketClass::create($this->siteId);
269 $basket->setFUserId($fUserId);
270 }
271
272 $items = array();
273 $isVariation = false;
274
275 if(!empty($transaction["Item"]))
276 {
277 $items = Xml2Array::normalize($transaction["Item"]);
278 }
279 elseif(!empty($transaction["Variation"]))
280 {
281 $items = Xml2Array::normalize($transaction["Variation"]);
282 $isVariation = true;
283 }
284
285 if(empty($items))
286 {
287 Ebay::log(Logger::LOG_LEVEL_INFO, "EBAY_DATA_PROCESSOR_ORDER_PROCESSING_TRANSACTION_ITEM_NOT_FOUND", $transaction["OrderLineItemID"], print_r($transaction,true), $this->siteId);
288 continue;
289 }
290
291 foreach($items as $transactionItem)
292 {
293 $ebaySku = $isVariation ? $this->getSkuVariation($transactionItem["SKU"]) : $this->getSku($transactionItem["SKU"]);
294
295 if($ebaySku == '')
296 {
297 Ebay::log(Logger::LOG_LEVEL_INFO, "EBAY_DATA_PROCESSOR_ORDER_PROCESSING_TRANSACTION_ITEM_SKU_NOT_FOUND", $transaction["OrderLineItemID"], print_r($transaction,true), $this->siteId);
298 continue;
299 }
300
301 $item = null;
302 $itemData = array(
303 "PRODUCT_ID" => $ebaySku,
304 "QUANTITY" => floatval($transaction["QuantityPurchased"]),
305 "CUSTOM_PRICE" => "Y",
306 "PRICE" => floatval($transaction["TransactionPrice"]),
307 "QUANTITY" => floatval($transaction["QuantityPurchased"]),
308 "NAME" => !empty($transactionItem["VariationTitle"]) ? $transactionItem["VariationTitle"] : $transactionItem["Title"],
309 );
310
311 $context = array(
312 'SITE_ID' => $this->siteId,
313 "CURRENCY" => SiteCurrencyTable::getSiteCurrency($this->siteId)
314 );
315
316 if ($order->getUserId() > 0)
317 {
318 $context['USER_ID'] = $order->getUserId();
319 }
320
321
322 $res = Catalog\Product\Basket::addProductToBasket($basket, $itemData, $context);
323 $resultData = $res->getData();
324 if (!empty($resultData['BASKET_ITEM']))
325 {
327 $item = $resultData['BASKET_ITEM'];
328 }
329
330 if (!$res->isSuccess())
331 {
332 if ($item)
333 {
334 $item->delete();
335 }
336
337 $itemData['MODULE'] = '';
338 $itemData['PRODUCT_PROVIDER_CLASS'] = '';
339
340 $res = Catalog\Product\Basket::addProductToBasket($basket, $itemData, $context);
341 }
342
343 $res = $item->setFields($itemData);
344
345 if($res->isSuccess())
346 {
347 $orderLineItemsIds[] = $transaction["OrderLineItemID"];
348 }
349 else
350 {
351 foreach($res->getErrors() as $error)
352 Ebay::log(Logger::LOG_LEVEL_ERROR, "EBAY_DATA_PROCESSOR_ORDER_TRANSACTION_ITEM_CREATE_ERROR", $transaction["OrderLineItemID"], $error->getMessage(), $this->siteId);
353 }
354 }
355 }
356
357 $res = $order->setBasket($basket);
358
359 if(!$res->isSuccess())
360 foreach($res->getErrors() as $error)
361 Ebay::log(Logger::LOG_LEVEL_ERROR, "EBAY_DATA_PROCESSOR_ORDER_CREATE_ERROR_SET_BASKET", $orderEbay["ExtendedOrderID"], $error->getMessage(), $this->siteId);
362
363 //payments
364 if(intval($settings[$this->siteId]["MAPS"]["PAYMENT"]["PayPal"]) > 0)
365 {
366 $payments = $order->getPaymentCollection();
367
369 if($payments->count() > 0)
370 {
371 foreach ($payments as $payment)
372 {
373 if($payment->isPaid())
374 $payment->setPaid("N");
375
376 $payment->delete();
377 }
378 }
379
380 $payment = $payments->createItem();
381 $payment->setField('PAY_SYSTEM_ID', $settings[$this->siteId]["MAPS"]["PAYMENT"]["PayPal"]);
382 $payment->setField('PAY_SYSTEM_NAME', "PayPal via Ebay");
383
384 if($orderEbay["CheckoutStatus"]["eBayPaymentStatus"] == "NoPaymentFailure"
385 && $orderEbay["MonetaryDetails"]["Payments"]["Payment"]["PaymentStatus"]
386 && $orderEbay["MonetaryDetails"]["Payments"]["Payment"]["PaymentAmount"] == $orderEbay["Total"]
387 )
388 {
389 $payment->setField("SUM", $orderEbay["AmountPaid"]);
390 $payment->setPaid("Y");
391 }
392 }
393
394 //shipment
395 if(intval($settings[$this->siteId]["MAPS"]["SHIPMENT"][$orderEbay["ShippingServiceSelected"]["ShippingService"]]) > 0)
396 {
397 $shipments = $order->getShipmentCollection();
398
400 if($shipments->count() > 0)
401 foreach ($shipments as $shipment)
402 if(!$shipment->isSystem())
403 $shipment->delete();
404
405 $shipment = $shipments->createItem();
406 $shipment->setField('DELIVERY_ID', $settings[$this->siteId]["MAPS"]["SHIPMENT"][$orderEbay["ShippingServiceSelected"]["ShippingService"]]);
407 $shipment->setField('CUSTOM_PRICE_DELIVERY', "Y");
408 $shipment->setField('BASE_PRICE_DELIVERY', $orderEbay["ShippingServiceSelected"]["ShippingServiceCost"]);
409 $basket = $order->getBasket();
410
411 if($basket)
412 {
413 $shipmentItemCollection = $shipment->getShipmentItemCollection();
414 $basketItems = $basket->getBasketItems();
415
416 foreach ($basketItems as $basketItem)
417 {
418 $shipmentItem = $shipmentItemCollection->createItem($basketItem);
419 $shipmentItem->setQuantity($basketItem->getField('QUANTITY'));
420 }
421 }
422 // todo: delivery price changed. Probably bug.
423 $shipment->setField('BASE_PRICE_DELIVERY', $orderEbay["ShippingServiceSelected"]["ShippingServiceCost"]);
424 }
425 else
426 {
427 Ebay::log(
429 "EBAY_DATA_PROCESSOR_ORDER_SHIPPING_ERROR",
430 $orderEbay["ExtendedOrderID"],
432 "SALE_TP_EBAY_FDPO_NOT_MAPPED_SHIPPING",
433 array(
434 "#ORDER_ID#" => $orderEbay["ExtendedOrderID"],
435 "#EBAY_SHIPPING#" => $orderEbay["ShippingServiceSelected"]["ShippingService"]
436 )
437 ),
438 $this->siteId
439 );
440
441 return 0;
442 }
443
444 // order status
445 if($settings[$this->siteId]["STATUS_MAP"][$orderEbay["OrderStatus"]] <> '')
446 {
447 switch($settings[$this->siteId]["STATUS_MAP"][$orderEbay["OrderStatus"]])
448 {
449 /* flags */
450 case "CANCELED":
451
452 if(!$order->setField("CANCELED", "Y"))
453 {
454 Ebay::log(
456 "EBAY_DATA_PROCESSOR_ORDER_CANCELING_ERROR",
457 $orderEbay["ExtendedOrderID"],
459 "SALE_TP_EBAY_FDPO_ORDER_CANCEL_ERROR",
460 array(
461 "#ORDER_ID#" => $orderEbay["ExtendedOrderID"]
462 )
463 ),
464 $this->siteId
465 );
466 }
467
468 break;
469
470 case "PAYED":
471 $payments = $order->getPaymentCollection();
472
473 foreach ($payments as $payment)
474 $payment->setPaid("Y");
475
476 break;
477
478 case "ALLOW_DELIVERY":
479 // we suggest that only one shipment exists
480 $shipments = $order->getShipmentCollection();
481
482 foreach ($shipments as $shipment)
483 {
484 if(!$shipment->isSystem())
485 {
486 if(!$shipment->allowDelivery())
487 {
488 Ebay::log(
490 "EBAY_DATA_PROCESSOR_ORDER_ALLOW_DELIVERY_ERROR",
491 $orderEbay["ExtendedOrderID"],
493 "SALE_TP_EBAY_FDPO_ORDER_ALLOW_DELIVERY_ERROR",
494 array(
495 "#ORDER_ID#" => $orderEbay["ExtendedOrderID"]
496 )
497 ),
498 $this->siteId
499 );
500 }
501 }
502 }
503
504 break;
505
506 case "DEDUCTED":
507 $shipments = $order->getShipmentCollection();
508
509 foreach ($shipments as $shipment)
510 {
511 if(!$shipment->isSystem())
512 {
513 if(!$shipment->setField('DEDUCTED', 'Y'))
514 {
515 Ebay::log(
517 "EBAY_DATA_PROCESSOR_ORDER_DEDUCTIOING_ERROR",
518 $orderEbay["ExtendedOrderID"],
520 "SALE_TP_EBAY_FDPO_ORDER_DEDUCT_ERROR",
521 array("#ORDER_ID#" => $orderEbay["ExtendedOrderID"])
522 ),
523 $this->siteId
524 );
525 }
526 }
527 }
528
529 break;
530
531 /* statuses */
532 default:
533 $res = $order->setField("STATUS_ID", $settings[$this->siteId]["STATUS_MAP"][$orderEbay["OrderStatus"]]);
534
536 if(!$res->isSuccess())
537 {
538 Ebay::log(
540 "EBAY_DATA_PROCESSOR_ORDER_CHANGE_STATUS_ERROR",
541 $orderEbay["OrderLineItemID"],
543 "SALE_TP_EBAY_FDPO_ORDER_SET_STATUS_ERROR",
544 array(
545 "#ORDER_ID#" => $orderEbay["ExtendedOrderID"],
546 "#STATUS#" => $orderEbay["OrderStatus"]
547 )
548 ),
549 $this->siteId
550 );
551 }
552 }
553 }
554
555 $order->setField("PRICE", $orderEbay["Total"]);
556 $order->setField("XML_ID", Ebay::TRADING_PLATFORM_CODE."_".$orderEbay["ExtendedOrderID"]);
557
558 $tradeCollection = $order->getTradeBindingCollection();
559
561 $entity = TradeBindingEntity::create($tradeCollection);
562 $entity->setFields([
563 "TRADING_PLATFORM_ID" => $ebay->getId(),
564 "EXTERNAL_ORDER_ID" => $orderEbay["ExtendedOrderID"],
565 "PARAMS" => [
566 "ORDER_LINES" => $orderLineItemsIds,
567 "ORDER_ID" => $orderEbay["OrderID"]
568 ]
569 ]);
570
571 $tradeCollection->addItem($entity);
572
573 $res = $order->save();
574
575 if(!$res->isSuccess())
576 {
577 foreach($res->getErrors() as $error)
578 Ebay::log(Logger::LOG_LEVEL_ERROR, "EBAY_DATA_PROCESSOR_ORDER_SAVE_ERROR", $orderEbay["ExtendedOrderID"], print_r($error->getMessage(),true), $this->siteId);
579 }
580 else
581 {
582 Ebay::log(
584 "EBAY_DATA_PROCESSOR_ORDER_CREATED",
585 $bitrixOrderId,
587 "SALE_TP_EBAY_FDPO_ORDER_SAVED",
588 array("#ORDER_ID#" => $bitrixOrderId)
589 ),
590 $this->siteId
591 );
592
593 \CSaleMobileOrderPush::send("ORDER_CREATED", array("ORDER_ID" => $order->getId()));
594 }
595
596 // send confirmation
597 if($bitrixOrderId > 0 && !empty($orderLineItemsIds))
598 {
599 $ebayFeed = \Bitrix\Sale\TradingPlatform\Ebay\Feed\Manager::createFeed("ORDER_ACK", $this->siteId);
600 $sourceData = array();
601
602 foreach($orderLineItemsIds as $id)
603 $sourceData[] = array("ORDER_ID" => $orderEbay["OrderID"], "ORDER_LINE_ITEM_ID" => $id);
604
605 $ebayFeed->setSourceData(array($sourceData));
606 $ebayFeed->processData();
607 }
608 return $bitrixOrderId;
609 }
610
611 protected function createUser($email, $name)
612 {
613 $errors = array();
614
615 $userId = \CSaleUser::DoAutoRegisterUser(
616 $email,
617 $name,
618 $this->siteId,
619 $errors);
620
621 if (!empty($errors))
622 {
623 $errorMessage = "";
624
625 foreach($errors as $val)
626 $errorMessage .= $val["TEXT"];
627
628 throw new SystemException($errorMessage);
629 }
630
631 return $userId;
632 }
633}
static loadMessages($file)
Definition loc.php:64
static getMessage($code, $replace=null, $language=null)
Definition loc.php:29
static getIdByUserId($userId)
Definition fuser.php:151
static getList(array $parameters=array())
static normalize(array $branch)
Definition xml2array.php:75