Exemplo n.º 1
0
 /**
  * Returns copy of current basket.
  * For example, the copy will be used to calculate discounts.
  * So, basket does not contain full information about BasketItem with bundleCollection, because now it is not
  * necessary.
  *
  * Attention! Don't save the basket.
  *
  * @internal
  * @return Basket
  * @throws Main\SystemException
  */
 public function copy()
 {
     if ($this->order !== null) {
         throw new Main\SystemException('Could not clone basket which has order.');
     }
     $basket = Basket::create($this->siteId);
     /**@var BasketItem $item */
     foreach ($this as $originalItem) {
         $item = $basket->createItem($originalItem->getField("MODULE"), $originalItem->getProductId());
         $item->setFields(array_intersect_key($originalItem->getFields()->getValues(), array_flip($item->getSettableFields())));
     }
     return $basket;
 }
Exemplo n.º 2
0
 /**
  * @return bool
  */
 protected function loadBundleCollection()
 {
     return Basket::loadBundleChild($this);
 }
Exemplo n.º 3
0
 public function processOrder($orderEbay)
 {
     Ebay::log(Logger::LOG_LEVEL_DEBUG, "EBAY_DATA_PROCESSOR_ORDER_PROCESSING", $orderEbay["ExtendedOrderID"], print_r($orderEbay, true), $this->siteId);
     /*
      * only in this case order is completely ready for shipping
      */
     if ($orderEbay["OrderStatus"] != "Completed" || !isset($orderEbay["CheckoutStatus"]["eBayPaymentStatus"]) || $orderEbay["CheckoutStatus"]["eBayPaymentStatus"] != "NoPaymentFailure") {
         Ebay::log(Logger::LOG_LEVEL_INFO, "EBAY_DATA_PROCESSOR_ORDER_SKIPPED", $orderEbay["ExtendedOrderID"], Loc::getMessage("SALE_TP_EBAY_FDPO_ORDER_SKIPPED", array("#ORDER_ID#" => $orderEbay["ExtendedOrderID"])), $this->siteId);
         return array();
     }
     $ebay = \Bitrix\Sale\TradingPlatform\Ebay\Ebay::getInstance();
     $settings = $ebay->getSettings();
     if (!isset($settings[$this->siteId]["ORDER_PROPS"]) || !is_array($settings[$this->siteId]["ORDER_PROPS"])) {
         throw new SystemException("Can't get order props map");
     }
     $propsMap = $settings[$this->siteId]["ORDER_PROPS"];
     /*
     if(strtolower(SITE_CHARSET) != 'utf-8')
     	$orderEbay = \Bitrix\Main\Text\Encoding::convertEncodingArray($orderEbay, 'UTF-8', SITE_CHARSET);
     */
     $dbRes = OrderTable::getList(array("filter" => array("TRADING_PLATFORM_ID" => $ebay->getId(), "EXTERNAL_ORDER_ID" => $orderEbay["ExtendedOrderID"])));
     if ($orderCorrespondence = $dbRes->fetch()) {
         Ebay::log(Logger::LOG_LEVEL_INFO, "EBAY_DATA_PROCESSOR_ORDER_ALREADY_EXIST", $orderEbay["ExtendedOrderID"], Loc::getMessage("SALE_TP_EBAY_FDPO_ORDER_SKIPPED_EXIST", array("#ORDER_ID#" => $orderEbay["ExtendedOrderID"])), $this->siteId);
         return array();
     }
     /** @var \Bitrix\Sale\Order $order */
     $order = \Bitrix\Sale\Order::create($this->siteId);
     $order->setPersonTypeId($settings[$this->siteId]["PERSON_TYPE"]);
     $propsCollection = $order->getPropertyCollection();
     /** @var \Bitrix\Sale\PropertyValueCollection $propCollection */
     if (intval($propsMap["FIO"]) > 0) {
         $prop = $propsCollection->getItemByOrderPropertyId($propsMap["FIO"]);
         $prop->setValue($orderEbay["ShippingAddress"]["Name"]);
     }
     if (intval($propsMap["CITY"]) > 0) {
         $prop = $propsCollection->getItemByOrderPropertyId($propsMap["CITY"]);
         $prop->setValue($orderEbay["ShippingAddress"]["CityName"]);
     }
     if (intval($propsMap["PHONE"]) > 0) {
         $prop = $propsCollection->getItemByOrderPropertyId($propsMap["PHONE"]);
         $prop->setValue($orderEbay["ShippingAddress"]["Phone"]);
     }
     if (intval($propsMap["ZIP"]) > 0) {
         $prop = $propsCollection->getItemByOrderPropertyId($propsMap["ZIP"]);
         $prop->setValue($orderEbay["ShippingAddress"]["PostalCode"]);
     }
     if (intval($propsMap["ADDRESS"]) > 0) {
         $prop = $propsCollection->getItemByOrderPropertyId($propsMap["ADDRESS"]);
         $prop->setValue($orderEbay["ShippingAddress"]["CountryName"] . " " . $orderEbay["ShippingAddress"]["CityName"] . " " . $orderEbay["ShippingAddress"]["Street1"] . " " . (!empty($orderEbay["ShippingAddress"]["Street2"]) ? $orderEbay["ShippingAddress"]["Street2"] . " " : ""));
     }
     $basket = null;
     $bitrixOrderId = 0;
     $userId = 0;
     $orderLineItemsIds = array();
     $transactionsArray = $this->normalizeTransactionsArray($orderEbay["TransactionArray"]);
     foreach ($transactionsArray as $transaction) {
         //if we have more than one transaction let's create user from the first
         if ($userId <= 0) {
             if (intval($propsMap["EMAIL"]) > 0 && !empty($transaction["Buyer"]["Email"])) {
                 $prop = $propsCollection->getItemByOrderPropertyId($propsMap["EMAIL"]);
                 $prop->setValue($transaction["Buyer"]["Email"]);
                 $userId = $this->createUser($transaction["Buyer"]["Email"], array("NAME" => $transaction["Buyer"]["UserFirstName"], "LAST_NAME" => $transaction["Buyer"]["UserLastName"]));
             }
             if ($userId <= 0) {
                 $userId = \CSaleUser::GetAnonymousUserID();
             }
         }
         if (intval($userId > 0)) {
             $order->setFieldNoDemand("USER_ID", $userId);
         }
         $fUserId = null;
         if ($order->getUserId() > 0) {
             $fUserId = Fuser::getIdByUserId($order->getUserId());
         }
         /** @var \Bitrix\Sale\Basket $basket */
         if (!$basket) {
             $basket = \Bitrix\Sale\Basket::create($this->siteId);
             $basket->setFUserId($fUserId);
         }
         $items = array();
         $isVariation = false;
         if (!empty($transaction["Item"])) {
             $items = Xml2Array::normalize($transaction["Item"]);
         } elseif (!empty($transaction["Variation"])) {
             $items = Xml2Array::normalize($transaction["Variation"]);
             $isVariation = true;
         }
         if (empty($items)) {
             Ebay::log(Logger::LOG_LEVEL_INFO, "EBAY_DATA_PROCESSOR_ORDER_PROCESSING_TRANSACTION_ITEM_NOT_FOUND", $transaction["OrderLineItemID"], print_r($transaction, true), $this->siteId);
             continue;
         }
         foreach ($items as $transactionItem) {
             $ebaySku = $isVariation ? $this->getSkuVariation($transactionItem["SKU"]) : $this->getSku($transactionItem["SKU"]);
             if (strlen($ebaySku) <= 0) {
                 Ebay::log(Logger::LOG_LEVEL_INFO, "EBAY_DATA_PROCESSOR_ORDER_PROCESSING_TRANSACTION_ITEM_SKU_NOT_FOUND", $transaction["OrderLineItemID"], print_r($transaction, true), $this->siteId);
                 continue;
             }
             $item = $basket->createItem('catalog', $ebaySku);
             $item->setField("PRODUCT_PROVIDER_CLASS", "CCatalogProductProvider");
             $itemData = array("CUSTOM_PRICE" => "Y", "PRICE" => floatval($transaction["TransactionPrice"]), "QUANTITY" => floatval($transaction["QuantityPurchased"]), "NAME" => !empty($transactionItem["VariationTitle"]) ? $transactionItem["VariationTitle"] : $transactionItem["Title"], "CURRENCY" => SiteCurrencyTable::getSiteCurrency($this->siteId));
             $data = Provider::getProductData($basket);
             if (!empty($data[$item->getBasketCode()])) {
                 $itemData = array_merge($data[$item->getBasketCode()], $itemData);
             } else {
                 $item->delete();
                 $item = $basket->createItem('', $ebaySku);
             }
             $res = $item->setFields($itemData);
             if ($res->isSuccess()) {
                 $orderLineItemsIds[] = $transaction["OrderLineItemID"];
             } else {
                 foreach ($res->getErrors() as $error) {
                     Ebay::log(Logger::LOG_LEVEL_ERROR, "EBAY_DATA_PROCESSOR_ORDER_TRANSACTION_ITEM_CREATE_ERROR", $transaction["OrderLineItemID"], $error->getMessage(), $this->siteId);
                 }
             }
         }
     }
     $res = $order->setBasket($basket);
     if (!$res->isSuccess()) {
         foreach ($res->getErrors() as $error) {
             Ebay::log(Logger::LOG_LEVEL_ERROR, "EBAY_DATA_PROCESSOR_ORDER_CREATE_ERROR_SET_BASKET", $orderEbay["ExtendedOrderID"], $error->getMessage(), $this->siteId);
         }
     }
     //payments
     if (intval($settings[$this->siteId]["MAPS"]["PAYMENT"]["PayPal"]) > 0) {
         $payments = $order->getPaymentCollection();
         /** @var \Bitrix\Sale\Payment $payment */
         if ($payments->count() > 0) {
             foreach ($payments as $payment) {
                 if ($payment->isPaid()) {
                     $payment->setPaid("N");
                 }
                 $payment->delete();
             }
         }
         $payment = $payments->createItem();
         $payment->setField('PAY_SYSTEM_ID', $settings[$this->siteId]["MAPS"]["PAYMENT"]["PayPal"]);
         $payment->setField('PAY_SYSTEM_NAME', "PayPal via Ebay");
         if ($orderEbay["CheckoutStatus"]["eBayPaymentStatus"] == "NoPaymentFailure" && $orderEbay["MonetaryDetails"]["Payments"]["Payment"]["PaymentStatus"] && $orderEbay["MonetaryDetails"]["Payments"]["Payment"]["PaymentAmount"] == $orderEbay["Total"]) {
             $payment->setField("SUM", $orderEbay["AmountPaid"]);
             $payment->setPaid("Y");
         }
     }
     //shipment
     if (intval($settings[$this->siteId]["MAPS"]["SHIPMENT"][$orderEbay["ShippingServiceSelected"]["ShippingService"]]) > 0) {
         $shipments = $order->getShipmentCollection();
         /** @var \Bitrix\Sale\Shipment $shipment */
         if ($shipments->count() > 0) {
             foreach ($shipments as $shipment) {
                 if (!$shipment->isSystem()) {
                     $shipment->delete();
                 }
             }
         }
         $shipment = $shipments->createItem();
         $shipment->setField('DELIVERY_ID', $settings[$this->siteId]["MAPS"]["SHIPMENT"][$orderEbay["ShippingServiceSelected"]["ShippingService"]]);
         $shipment->setField('CUSTOM_PRICE_DELIVERY', "Y");
         $shipment->setField('BASE_PRICE_DELIVERY', $orderEbay["ShippingServiceSelected"]["ShippingServiceCost"]);
         $basket = $order->getBasket();
         if ($basket) {
             $shipmentItemCollection = $shipment->getShipmentItemCollection();
             $basketItems = $basket->getBasketItems();
             foreach ($basketItems as $basketItem) {
                 $shipmentItem = $shipmentItemCollection->createItem($basketItem);
                 $shipmentItem->setQuantity($basketItem->getField('QUANTITY'));
             }
         }
         // todo: delivery price changed. Probably bug.
         $shipment->setField('BASE_PRICE_DELIVERY', $orderEbay["ShippingServiceSelected"]["ShippingServiceCost"]);
     } else {
         Ebay::log(Logger::LOG_LEVEL_ERROR, "EBAY_DATA_PROCESSOR_ORDER_SHIPPING_ERROR", $orderEbay["ExtendedOrderID"], Loc::getMessage("SALE_TP_EBAY_FDPO_NOT_MAPPED_SHIPPING", array("#ORDER_ID#" => $orderEbay["ExtendedOrderID"], "#EBAY_SHIPPING#" => $orderEbay["ShippingServiceSelected"]["ShippingService"])), $this->siteId);
         return 0;
     }
     // order status
     if (strlen($settings[$this->siteId]["STATUS_MAP"][$orderEbay["OrderStatus"]]) > 0) {
         switch ($settings[$this->siteId]["STATUS_MAP"][$orderEbay["OrderStatus"]]) {
             /* flags */
             case "CANCELED":
                 if (!$order->setField("CANCELED", "Y")) {
                     Ebay::log(Logger::LOG_LEVEL_ERROR, "EBAY_DATA_PROCESSOR_ORDER_CANCELING_ERROR", $orderEbay["ExtendedOrderID"], Loc::getMessage("SALE_TP_EBAY_FDPO_ORDER_CANCEL_ERROR", array("#ORDER_ID#" => $orderEbay["ExtendedOrderID"])), $this->siteId);
                 }
                 break;
             case "PAYED":
                 $payments = $order->getPaymentCollection();
                 foreach ($payments as $payment) {
                     $payment->setPaid("Y");
                 }
                 break;
             case "ALLOW_DELIVERY":
                 // we suggest that only one shipment exists
                 $shipments = $order->getShipmentCollection();
                 foreach ($shipments as $shipment) {
                     if (!$shipment->isSystem()) {
                         if (!$shipment->allowDelivery()) {
                             Ebay::log(Logger::LOG_LEVEL_ERROR, "EBAY_DATA_PROCESSOR_ORDER_ALLOW_DELIVERY_ERROR", $orderEbay["ExtendedOrderID"], Loc::getMessage("SALE_TP_EBAY_FDPO_ORDER_ALLOW_DELIVERY_ERROR", array("#ORDER_ID#" => $orderEbay["ExtendedOrderID"])), $this->siteId);
                         }
                     }
                 }
                 break;
             case "DEDUCTED":
                 $shipments = $order->getShipmentCollection();
                 foreach ($shipments as $shipment) {
                     if (!$shipment->isSystem()) {
                         if (!$shipment->setField('DEDUCTED', 'Y')) {
                             Ebay::log(Logger::LOG_LEVEL_ERROR, "EBAY_DATA_PROCESSOR_ORDER_DEDUCTIOING_ERROR", $orderEbay["ExtendedOrderID"], Loc::getMessage("SALE_TP_EBAY_FDPO_ORDER_DEDUCT_ERROR", array("#ORDER_ID#" => $orderEbay["ExtendedOrderID"])), $this->siteId);
                         }
                     }
                 }
                 break;
                 /* statuses */
             /* statuses */
             default:
                 $res = $order->setField("STATUS_ID", $settings[$this->siteId]["STATUS_MAP"][$orderEbay["OrderStatus"]]);
                 /** @var \Bitrix\Sale\Result $res */
                 if (!$res->isSuccess()) {
                     Ebay::log(Logger::LOG_LEVEL_ERROR, "EBAY_DATA_PROCESSOR_ORDER_CHANGE_STATUS_ERROR", $orderEbay["OrderLineItemID"], Loc::getMessage("SALE_TP_EBAY_FDPO_ORDER_SET_STATUS_ERROR", array("#ORDER_ID#" => $orderEbay["ExtendedOrderID"], "#STATUS#" => $orderEbay["OrderStatus"])), $this->siteId);
                 }
         }
     }
     $order->setField("PRICE", $orderEbay["Total"]);
     $order->setField("XML_ID", Ebay::TRADING_PLATFORM_CODE . "_" . $orderEbay["ExtendedOrderID"]);
     $res = $order->save();
     if (!$res->isSuccess()) {
         foreach ($res->getErrors() as $error) {
             Ebay::log(Logger::LOG_LEVEL_ERROR, "EBAY_DATA_PROCESSOR_ORDER_SAVE_ERROR", $orderEbay["ExtendedOrderID"], print_r($error->getMessage(), true), $this->siteId);
         }
     } else {
         $bitrixOrderId = $order->getId();
         Ebay::log(Logger::LOG_LEVEL_INFO, "EBAY_DATA_PROCESSOR_ORDER_CREATED", $bitrixOrderId, Loc::getMessage("SALE_TP_EBAY_FDPO_ORDER_SAVED", array("#ORDER_ID#" => $bitrixOrderId)), $this->siteId);
         \CSaleMobileOrderPush::send("ORDER_CREATED", array("ORDER_ID" => $bitrixOrderId));
         $res = OrderTable::add(array("ORDER_ID" => $bitrixOrderId, "TRADING_PLATFORM_ID" => $ebay->getId(), "EXTERNAL_ORDER_ID" => $orderEbay["ExtendedOrderID"], "PARAMS" => array("ORDER_LINES" => $orderLineItemsIds, "ORDER_ID" => $orderEbay["OrderID"])));
         if (!$res->isSuccess()) {
             foreach ($res->getErrors() as $error) {
                 Ebay::log(Logger::LOG_LEVEL_ERROR, "EBAY_DATA_PROCESSOR_ORDER_DELIVERY_SAVE_ERROR", $orderEbay["ExtendedOrderID"], $error->getMessage(), $this->siteId);
             }
         }
     }
     // send confirmation
     if ($bitrixOrderId > 0 && !empty($orderLineItemsIds)) {
         $ebayFeed = \Bitrix\Sale\TradingPlatform\Ebay\Feed\Manager::createFeed("ORDER_ACK", $this->siteId);
         $sourceData = array();
         foreach ($orderLineItemsIds as $id) {
             $sourceData[] = array("ORDER_ID" => $orderEbay["OrderID"], "ORDER_LINE_ITEM_ID" => $id);
         }
         $ebayFeed->setSourceData(array($sourceData));
         $ebayFeed->processData();
     }
     return $bitrixOrderId;
 }
Exemplo n.º 4
0
 /**
  * @internal
  *
  * @param Sale\Basket $basket
  * @param array $requestFields
  *
  * @return bool
  */
 public function resetOrderPrice(Sale\Basket $basket, array $requestFields)
 {
     if (empty($requestFields['BASKET_ITEMS'])) {
         return false;
     }
     $resetPrice = false;
     $resetPriceDelivery = false;
     /** @var Sale\Order $order */
     $order = $this->getOrder();
     if ($order->getId() == 0) {
         $order->resetData(array('PRICE_DELIVERY'));
         $resetPriceDelivery = true;
     }
     foreach ($requestFields['BASKET_ITEMS'] as $basketData) {
         if (!isset($basketData['ID']) || intval($basketData['ID']) <= 0) {
             continue;
         }
         /** @var Sale\BasketItem $basketItem */
         if (!($basketItem = $basket->getItemById($basketData['ID']))) {
             continue;
         }
         if ($resetPriceDelivery === false) {
             if ($order->getId() == 0 || isset($basketData['PRICE']) && floatval($basketData['PRICE']) != $basketItem->getPrice()) {
                 $order->resetData(array('PRICE'));
                 $resetPrice = true;
             }
         }
         //			if ($resetPriceDelivery === false)
         //			{
         //				if ($order->getId() == 0 || isset($basketData['QUANTITY'])
         //					&& floatval($basketData['QUANTITY']) != $basketItem->getQuantity())
         //				{
         //					$order->resetData(array('PRICE_DELIVERY'));
         //					$resetPriceDelivery = true;
         //				}
         //			}
         if ($resetPriceDelivery && $resetPrice) {
             return true;
         }
     }
     //
     return false;
 }
Exemplo n.º 5
0
 /**
  * @param array $oldOrder
  * @return Shipment
  * @internal
  */
 public static function convertOrderOldToNew(array $oldOrder)
 {
     $siteId = isset($oldOrder["SITE_ID"]) ? $oldOrder["SITE_ID"] : SITE_ID;
     $newOrder = \Bitrix\Sale\Order::create($siteId, null, $oldOrder["CURRENCY"]);
     $dbPersonType = \CSalePersonType::GetList(array("SORT" => "ASC", "NAME" => "ASC"), array("ACTIVE" => "Y", "LID" => $siteId));
     if ($arPersonType = $dbPersonType->GetNext()) {
         $personTypeId = $arPersonType["ID"];
     } else {
         $personTypeId = 1;
     }
     $newOrder->setPersonTypeId($personTypeId);
     $newOrder->setFieldNoDemand("PRICE", $oldOrder["PRICE"]);
     $basket = \Bitrix\Sale\Basket::create($siteId);
     $settableFields = array_flip(\Bitrix\Sale\BasketItemBase::getSettableFields());
     if (!empty($oldOrder["ITEMS"]) && is_array($oldOrder["ITEMS"])) {
         foreach ($oldOrder["ITEMS"] as $oldBasketItem) {
             $newBasketItem = $basket->createItem($oldBasketItem["MODULE"], $oldBasketItem["PRODUCT_ID"]);
             $oldBasketItem = array_intersect_key($oldBasketItem, $settableFields);
             $newBasketItem->setFieldsNoDemand($oldBasketItem);
         }
     }
     $props = $newOrder->getPropertyCollection();
     if (!empty($oldOrder['PROPERTIES']) && is_array($oldOrder['PROPERTIES'])) {
         $r = $props->setValuesFromPost($oldOrder, $_FILES);
     }
     $newOrder->setBasket($basket);
     if ($loc = $props->getDeliveryLocation()) {
         $loc->setValue($oldOrder["LOCATION_TO"]);
     }
     if ($loc = $props->getDeliveryLocationZip()) {
         $loc->setValue($oldOrder["LOCATION_ZIP"]);
     }
     /** @var \Bitrix\Sale\ShipmentCollection $shipmentCollection */
     $shipmentCollection = $newOrder->getShipmentCollection();
     $shipment = $shipmentCollection->createItem();
     $shipment->setField("CURRENCY", $oldOrder["CURRENCY"]);
     $shipmentItemCollection = $shipment->getShipmentItemCollection();
     foreach ($newOrder->getBasket() as $item) {
         $shipmentItem = $shipmentItemCollection->createItem($item);
         $shipmentItem->setQuantity($item->getQuantity());
         if (strlen($shipmentItem->getField("DIMENSIONS"))) {
             $shipmentItem->setField("DIMENSIONS", unserialize($shipmentItem->getField("DIMENSIONS")));
         }
     }
     if (isset($arOrder["DELIVERY_EXTRA_SERVICES"])) {
         $shipment->setExtraServices($arOrder["DELIVERY_EXTRA_SERVICES"]);
     }
     return $shipment;
 }
Exemplo n.º 6
0
 /**
  * @param Basket $basket
  * @return Result
  * @throws Main\NotSupportedException
  */
 public function setBasket(Basket $basket)
 {
     if ($this->getId()) {
         throw new Main\NotSupportedException();
     }
     $result = new Result();
     $basket->setOrder($this);
     $this->basketCollection = $basket;
     //		$basket->refreshData(array('PRICE', 'QUANTITY'));
     if (!$this->isMathActionOnly()) {
         /** @var Result $r */
         $r = $basket->refreshData(array('PRICE', 'QUANTITY', 'COUPONS'));
         if (!$r->isSuccess()) {
             $result->addErrors($r->getErrors());
             return $result;
         }
     }
     //		/** @var Result $r */
     //		$r = $this->setField("PRICE", $basket->getPrice());
     //		if (!$r->isSuccess(true))
     //		{
     //			$result->addErrors($r->getErrors());
     //			return $result;
     //		}
     //$this->setField("CURRENCY", $basket->get)
     return $result;
 }
Exemplo n.º 7
0
 /**
  * @internal
  * @return array
  */
 public static function getRoundFields()
 {
     $isOrderConverted = \Bitrix\Main\Config\Option::get("main", "~sale_converted_15", 'N');
     if ($isOrderConverted == "Y") {
         return Sale\Basket::getRoundFields();
     }
     return array('PRICE', 'DISCOUNT_PRICE', 'VAT_RATE', 'VAT_VALUE', 'DISCOUNT_PRICE_PERCENT');
 }
Exemplo n.º 8
0
            $basket->usePrepayment = isset($_POST["use_prepayment"]) && $_POST["use_prepayment"] == "Y" ? "Y" : "N";
            $res = $basket->recalculateBasket($_POST);
            foreach ($res as $key => $value) {
                $arRes[$key] = $value;
            }
            $arRes["BASKET_DATA"] = $basket->getBasketItems();
            $arRes["BASKET_DATA"]["GRID"]["HEADERS"] = $basket->getCustomColumns();
            $arRes["COLUMNS"] = $strColumns;
            $arRes["CODE"] = "SUCCESS";
            if (!empty($_POST["coupon"]) && $arRes['VALID_COUPON'] === true) {
                if (!empty($arRes['BASKET_DATA']['FULL_DISCOUNT_LIST'])) {
                    global $USER;
                    $userId = $USER instanceof CAllUser ? $USER->getId() : null;
                    $giftManager = \Bitrix\Sale\Discount\Gift\Manager::getInstance()->setUserId($userId);
                    \Bitrix\Sale\Compatible\DiscountCompatibility::stopUsageCompatible();
                    $collections = $giftManager->getCollectionsByBasket(\Bitrix\Sale\Basket::loadItemsForFUser(\Bitrix\Sale\Fuser::getId(), SITE_ID), $arRes['BASKET_DATA']['FULL_DISCOUNT_LIST'], $arRes['BASKET_DATA']['APPLIED_DISCOUNT_LIST']);
                    \Bitrix\Sale\Compatible\DiscountCompatibility::revertUsageCompatible();
                    if (count($collections)) {
                        $arRes['BASKET_DATA']['NEED_TO_RELOAD_FOR_GETTING_GIFTS'] = true;
                    }
                }
            }
        }
    }
}
unset($arRes['BASKET_DATA']['APPLIED_DISCOUNT_LIST'], $arRes['BASKET_DATA']['FULL_DISCOUNT_LIST']);
$arRes["PARAMS"]["QUANTITY_FLOAT"] = isset($_POST["quantity_float"]) && $_POST["quantity_float"] == "Y" ? "Y" : "N";
$APPLICATION->RestartBuffer();
header('Content-Type: application/json; charset=' . LANG_CHARSET);
echo CUtil::PhpToJSObject($arRes);
die;
Exemplo n.º 9
0
 /**
  * @param \Bitrix\Sale\Basket $basket
  *
  * @return float
  */
 protected static function getActualBasketQuantity(\Bitrix\Sale\Basket $basket)
 {
     $basketQuantity = 0;
     /** @var \Bitrix\Sale\Basket $basketOrderable */
     $basketOrderable = $basket->getOrderableItems();
     foreach ($basketOrderable as $basketItem) {
         if (intval($basketItem->getField('ORDER_ID')) > 0) {
             continue;
         }
         if (!$basketItem->isBundleChild()) {
             $basketQuantity++;
         }
     }
     return $basketQuantity;
 }
Exemplo n.º 10
0
 foreach ($originalPropCollection as $prop) {
     if ($prop->getField('TYPE') == 'FILE') {
         $propValue = $prop->getValue();
         if ($propValue) {
             $files[] = CAllFile::MakeFileArray($propValue['ID']);
             $properties['PROPERTIES'][$prop->getPropertyId()] = $propValue['ID'];
         }
     } else {
         $properties['PROPERTIES'][$prop->getPropertyId()] = $prop->getValue();
     }
 }
 $propCollection = $order->getPropertyCollection();
 $propCollection->setValuesFromPost($properties, $files);
 $originalBasket = $originalOrder->getBasket();
 $originalBasketItems = $originalBasket->getBasketItems();
 $basket = \Bitrix\Sale\Basket::create($originalOrder->getSiteId(), $originalBasket->getFUserId());
 /** @var \Bitrix\Sale\BasketItem $originalBasketItem */
 foreach ($originalBasketItems as $originalBasketItem) {
     $item = $basket->createItem($originalBasketItem->getField("MODULE"), $originalBasketItem->getProductId());
     $item->setFields(array_intersect_key($originalBasketItem->getFields()->getValues(), array_flip($originalBasketItem->getAvailableFields())));
 }
 $res = $order->setBasket($basket);
 if (!$res->isSuccess()) {
     $result->addErrors($res->getErrors());
 }
 $paymentCollection = $originalOrder->getPaymentCollection();
 $originalPayment = $paymentCollection->current();
 if ($originalPayment) {
     $payment = $order->getPaymentCollection()->createItem();
     /** @var \Bitrix\Sale\Payment $payment */
     $payment->setField('PAY_SYSTEM_ID', $originalPayment->getPaymentSystemId());
Exemplo n.º 11
0
 function DeleteOldAgent($nDays, $speed = 0)
 {
     return Sale\Basket::deleteOldAgent($nDays, $speed);
 }
Exemplo n.º 12
0
 /**
  * @param array $formData
  * @param $creatorUserId
  * @param bool $createUserIfNeed
  * @param array $files
  * @param Result &$opResult
  * @return Order|static
  * @throws ArgumentNullException
  * @throws SystemException
  */
 public static function createOrderFromForm(array $formData, $creatorUserId, $createUserIfNeed = true, array $files = array(), Result &$opResult)
 {
     if (!isset($formData["SITE_ID"]) || strlen($formData["SITE_ID"]) <= 0) {
         throw new ArgumentNullException('formData["SITE_ID"]');
     }
     $order = Order::create($formData["SITE_ID"]);
     /** @var \Bitrix\Sale\Result $res */
     $res = self::fillSimpleFields($order, $formData, $creatorUserId);
     if (!$res->isSuccess()) {
         $opResult->addErrors($res->getErrors());
     }
     $propCollection = $order->getPropertyCollection();
     $res = $propCollection->setValuesFromPost($formData, $files);
     if (!$res->isSuccess()) {
         $opResult->addErrors($res->getErrors());
     }
     //creates new user if need
     $order->setFieldNoDemand("USER_ID", self::getUserId($order, $formData, $createUserIfNeed, $opResult));
     $fUserId = null;
     if ($order->getUserId() > 0) {
         $fUserId = Fuser::getIdByUserId($order->getUserId());
     }
     //init basket
     if (isset($formData["PRODUCT"]) && is_array($formData["PRODUCT"])) {
         $basket = \Bitrix\Sale\Basket::create($formData["SITE_ID"]);
         $basket->setFUserId($fUserId);
         sortByColumn($formData["PRODUCT"], array("BASE_PRICE" => SORT_DESC, "PRICE" => SORT_DESC));
         foreach ($formData["PRODUCT"] as $basketCode => $productData) {
             if ($productData["IS_SET_ITEM"] == "Y") {
                 continue;
             }
             if (!isset($productData["PROPS"]) || !is_array($productData["PROPS"])) {
                 $productData["PROPS"] = array();
             }
             $item = $basket->getExistsItem($productData["MODULE"], $productData["OFFER_ID"], $productData["PROPS"]);
             if ($item == null && $basketCode != "new") {
                 $item = $basket->getItemByBasketCode($basketCode);
             }
             if ($item && $item->isBundleChild()) {
                 $item = null;
             }
             if ($item) {
                 //Let's extract cached provider product data from field
                 if (!empty($productData["PROVIDER_DATA"])) {
                     $providerData = unserialize($productData["PROVIDER_DATA"]);
                     if (is_array($providerData) && !empty($providerData)) {
                         self::setProviderTrustData($item, $order, $providerData);
                     }
                 }
                 if (!empty($productData["SET_ITEMS_DATA"])) {
                     $productData["SET_ITEMS"] = unserialize($productData["SET_ITEMS_DATA"]);
                 }
                 $res = $item->setField("QUANTITY", $item->getField("QUANTITY") + $productData["QUANTITY"]);
                 if (!$res->isSuccess()) {
                     $opResult->addErrors($res->getErrors());
                 }
             } else {
                 $setBasketCode = $basketCode != "new" ? $basketCode : null;
                 $item = $basket->createItem($productData["MODULE"], $productData["OFFER_ID"], $setBasketCode);
                 if ($basketCode != $productData["BASKET_CODE"]) {
                     $productData["BASKET_CODE"] = $item->getBasketCode();
                 }
                 $needDataUpdate = false;
                 if ($basketCode == "new") {
                     $opResult->setData(array("NEW_ITEM_BASKET_CODE" => $productData["BASKET_CODE"]));
                     $needDataUpdate = true;
                 }
                 $fbRes = self::fillBasketItem($item, $productData, $order, $basket, $needDataUpdate);
                 if (!$fbRes->isSuccess()) {
                     $opResult->addErrors($fbRes->getErrors());
                 }
                 if (isset($productData["PROPS"]) && !empty($productData["PROPS"]) && is_array($productData["PROPS"])) {
                     /** @var \Bitrix\Sale\BasketPropertiesCollection $property */
                     $property = $item->getPropertyCollection();
                     $property->setProperty($productData["PROPS"]);
                 }
             }
         }
         $res = $order->setBasket($basket);
         if (!$res->isSuccess()) {
             $opResult->addErrors($res->getErrors());
         }
         if (isset($formData["DISCOUNTS"]) && is_array($formData["DISCOUNTS"])) {
             $order->getDiscount()->setApplyResult($formData["DISCOUNTS"]);
         }
     } else {
         $opResult->addError(new EntityError(Loc::getMessage("SALE_ORDEREDIT_ERROR_NO_PRODUCTS")));
     }
     return $order;
 }
Exemplo n.º 13
0
 /**
  * Round basket results.
  * @return void
  */
 protected function roundBasketPrices()
 {
     $roundFields = Basket::getRoundFields();
     if (empty($roundFields)) {
         return;
     }
     $roundFields = array_fill_keys($roundFields, true);
     foreach ($this->orderData['BASKET_ITEMS'] as $basketCode => $basketItem) {
         foreach ($basketItem as $field => $value) {
             if (isset($roundFields[$field])) {
                 $basketItem[$field] = roundEx($value, SALE_VALUE_PRECISION);
             }
         }
         unset($field, $value);
         $this->orderData['BASKET_ITEMS'][$basketCode] = $basketItem;
     }
     unset($basketCode, $basketItem);
 }
Exemplo n.º 14
0
{
    foreach ($propertyCollection as $property) {
        if ($property->getField('CODE') == $code) {
            return $property;
        }
    }
}
$siteId = \Bitrix\Main\Context::getCurrent()->getSite();
$fio = 'Пупкин Василий';
$phone = '9511111111';
$email = '*****@*****.**';
$currencyCode = Option::get('sale', 'default_currency', 'RUB');
DiscountCouponsManager::init();
$order = Order::create($siteId, \CSaleUser::GetAnonymousUserID());
$order->setPersonTypeId(1);
$basket = Sale\Basket::loadItemsForFUser(\CSaleBasket::GetBasketUserID(), $siteId)->getOrderableItems();
/* Действия над товарами
$basketItems = $basket->getBasketItems();
foreach ($basketItems as $basketItem) {
    
}
*/
$order->setBasket($basket);
/*Shipment*/
$shipmentCollection = $order->getShipmentCollection();
$shipment = $shipmentCollection->createItem();
$shipment->setFields(['DELIVERY_ID' => 1, 'CURRENCY' => $currencyCode]);
/**/
/*Payment*/
$paymentCollection = $order->getPaymentCollection();
$extPayment = $paymentCollection->createItem();
Exemplo n.º 15
0
 /**
  * @return mixed|static
  */
 protected function loadBasket()
 {
     if (intval($this->getId()) > 0) {
         return Basket::loadItemsForOrder($this);
     } else {
         return false;
     }
 }
Exemplo n.º 16
0
 /**
  * @param $id
  * @return Sale\BasketItem|Sale\Result|null
  * @throws \Bitrix\Main\ArgumentException
  * @throws \Bitrix\Main\ArgumentNullException
  */
 protected static function loadEntityFromBasket($id)
 {
     $result = new Sale\Result();
     $order = null;
     $basket = null;
     $item = null;
     $res = BasketTable::getList(array('filter' => array('ID' => $id), 'select' => array('ID', 'ORDER_ID', 'SET_PARENT_ID', 'TYPE', 'FUSER_ID', 'LID')));
     if (!($itemDat = $res->fetch())) {
         $result->addError(new Sale\ResultError(Main\Localization\Loc::getMessage('SALE_BASKET_COMPATIBLE_BASKET_ITEM_NOT_FOUND'), 'BASKET_ITEM_NOT_FOUND'));
         return $result;
     }
     if (intval($itemDat['ORDER_ID']) > 0) {
         /** @var Sale\Order $order */
         if ($order = Sale\Order::load(intval($itemDat['ORDER_ID']))) {
             if ($basket = $order->getBasket()) {
                 /** @var Sale\BasketItem $item */
                 $item = $basket->getItemById($id);
             }
         }
     } else {
         //			if (!array_key_exists('FUSER_ID', $itemDat) || intval($itemDat['FUSER_ID']) <= 0)
         //			{
         //				$itemDat['FUSER_ID'] = Sale\Fuser::getId();
         //			}
         /** @var Sale\Basket $basket */
         $basket = Sale\Basket::loadItemsForFUser($itemDat["FUSER_ID"], $itemDat['LID']);
         if ($basket) {
             /** @var Sale\BasketItem $item */
             $item = $basket->getItemById($id);
         }
     }
     $data = array('BASKET_ITEM' => $item);
     if ($order !== null) {
         $data['ORDER'] = $order;
     }
     $result->addData($data);
     return $result;
 }
Exemplo n.º 17
0
 /**
  * @param Basket $basketCollection
  * @param array $productList
  */
 public static function recurringOrderProduct(Basket $basketCollection, array $productList = array())
 {
     $userId = null;
     if (!($orderId = $basketCollection->getOrderId())) {
         if (($order = $basketCollection->getOrder()) !== null) {
             $userId = $order->getUserId();
         }
     }
     if ($userId === null) {
         $userId = \CSaleUser::GetUserID($basketCollection->getFUserId());
     }
     $basketList = static::makeArrayFromBasketCollection($basketCollection);
     $basketProviderMap = static::createProviderBasketMap($basketList);
     $basketProviderList = static::redistributeToProviders($basketProviderMap);
     if (!empty($basketProviderList)) {
         foreach ($basketProviderList as $provider => $providerBasketItemList) {
             $result = $provider::recurringOrderProduct($userId, $providerBasketItemList, $productList);
         }
     }
 }