コード例 #1
0
ファイル: orderdiscount.php プロジェクト: Satariall/izurit
 /**
  * Set manager params.
  *
  * @param array $config			Manager params (site, currency, etc).
  * @return bool
  */
 public static function setManagerConfig($config)
 {
     if (empty($config) || empty($config['SITE_ID'])) {
         return false;
     }
     if (empty($config['CURRENCY'])) {
         $config['CURRENCY'] = Internals\SiteCurrencyTable::getSiteCurrency($config['SITE_ID']);
     }
     if (!isset($config['USE_BASE_PRICE']) || $config['USE_BASE_PRICE'] != 'Y' && $config['USE_BASE_PRICE'] != 'N') {
         $config['USE_BASE_PRICE'] = (string) Main\Config\Option::get('sale', 'get_discount_percent_from_base_price') == 'Y' ? 'Y' : 'N';
     }
     if (empty($config['BASKET_ITEM'])) {
         $config['BASKET_ITEM'] = '$basketItem';
     }
     self::$managerConfig = $config;
     return true;
 }
コード例 #2
0
ファイル: sale_cond.php プロジェクト: webgksupport/alpina
 public static function GetControlShow($arParams)
 {
     $result = array();
     $controls = static::GetControls();
     if (empty($controls) || !is_array($controls)) {
         return false;
     }
     foreach ($controls as &$oneControl) {
         $row = array('controlId' => $oneControl['ID'], 'group' => true, 'label' => $oneControl['LABEL'], 'showIn' => $oneControl['SHOW_IN'], 'visual' => $oneControl['VISUAL'], 'control' => array());
         if (isset($oneControl['PREFIX'])) {
             $row['control'][] = $oneControl['PREFIX'];
         }
         switch ($oneControl['ID']) {
             case 'CondBsktCntGroup':
             case 'CondBsktAmtGroup':
             case 'CondBsktRowGroup':
                 $row['control'][] = $oneControl['ATOMS']['All'];
                 $row['control'][] = $oneControl['ATOMS']['Logic'];
                 $row['control'][] = $oneControl['ATOMS']['Value'];
                 break;
             case 'CondBsktProductGroup':
                 $row['control'][] = $oneControl['ATOMS']['Found'];
                 $row['control'][] = Loc::getMessage('BT_SALE_COND_GROUP_PRODUCT_DESCR');
                 $row['control'][] = $oneControl['ATOMS']['All'];
                 break;
             default:
                 $oneControl['ATOMS'] = array_values($oneControl['ATOMS']);
                 $row['control'] = empty($row['control']) ? $oneControl['ATOMS'] : array_merge($row['control'], $oneControl['ATOMS']);
                 break;
         }
         if ($oneControl['ID'] == 'CondBsktAmtGroup') {
             if (static::$boolInit) {
                 $currency = '';
                 if (isset(static::$arInitParams['CURRENCY'])) {
                     $currency = static::$arInitParams['CURRENCY'];
                 } elseif (isset(static::$arInitParams['SITE_ID'])) {
                     $currency = Sale\Internals\SiteCurrencyTable::getSiteCurrency(static::$arInitParams['SITE_ID']);
                 }
                 if (!empty($currency)) {
                     $row['control'][] = $currency;
                 }
                 unset($currency);
             }
         }
         if (!empty($row['control'])) {
             $result[] = $row;
         }
         unset($row);
     }
     unset($oneControl);
     return $result;
 }
コード例 #3
0
ファイル: order.php プロジェクト: webgksupport/alpina
 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;
 }
コード例 #4
0
ファイル: settings.php プロジェクト: webgksupport/alpina
 public static function GetLangCurrency($siteId)
 {
     return Sale\Internals\SiteCurrencyTable::getSiteCurrency($siteId);
 }
コード例 #5
0
ファイル: orderbase.php プロジェクト: Satariall/izurit
 /**
  * @param string $siteId
  * @param int $userId
  * @param string $currency
  * @return static
  */
 public static function create($siteId, $userId = null, $currency = null)
 {
     $order = new static();
     $order->setFieldNoDemand('LID', $siteId);
     if (intval($userId) > 0) {
         $order->setFieldNoDemand('USER_ID', $userId);
     }
     if ($currency == null) {
         $currency = Internals\SiteCurrencyTable::getSiteCurrency($siteId);
     }
     $order->setFieldNoDemand('CURRENCY', $currency);
     $order->calculateType = static::SALE_ORDER_CALC_TYPE_NEW;
     return $order;
 }
コード例 #6
0
ファイル: discount.php プロジェクト: akniyev/itprom_dobrohost
 public static function DoProcessOrder(&$arOrder, $arOptions, &$arErrors)
 {
     if (empty($arOrder['BASKET_ITEMS']) || !is_array($arOrder['BASKET_ITEMS'])) {
         return;
     }
     $isOrderConverted = \Bitrix\Main\Config\Option::get("main", "~sale_converted_15", 'N');
     $oldDelivery = '';
     $checkIds = true;
     $arIDS = array();
     if ($isOrderConverted == 'Y') {
         if (isset($arOrder['DELIVERY_ID']) && $arOrder['DELIVERY_ID'] != '') {
             $oldDelivery = $arOrder['DELIVERY_ID'];
             $arOrder['DELIVERY_ID'] = \CSaleDelivery::getIdByCode($arOrder['DELIVERY_ID']);
         }
         $adminSection = defined('ADMIN_SECTION') && ADMIN_SECTION === true;
         if (!$adminSection) {
             $mode = Sale\Compatible\DiscountCompatibility::MODE_MANAGER;
             $modeParams = array();
             if (isset($arOrder['CURRENCY'])) {
                 $modeParams['CURRENCY'] = $arOrder['CURRENCY'];
             }
             if (isset($arOrder['SITE_ID'])) {
                 $modeParams['SITE_ID'] = $arOrder['SITE_ID'];
                 if (!isset($modeParams['CURRENCY'])) {
                     $modeParams['CURRENCY'] = Sale\Internals\SiteCurrencyTable::getSiteCurrency($modeParams['SITE_ID']);
                 }
             }
         } else {
             $mode = Sale\Compatible\DiscountCompatibility::MODE_CLIENT;
             $modeParams = array('SITE_ID' => SITE_ID, 'CURRENCY' => Sale\Internals\SiteCurrencyTable::getSiteCurrency(SITE_ID));
         }
         unset($adminSection);
         if (!empty($modeParams)) {
             Sale\Discount\Actions::setUseMode(Sale\Discount\Actions::MODE_CALCULATE, array('USE_BASE_PRICE' => \Bitrix\Main\Config\Option::get('sale', 'get_discount_percent_from_base_price'), 'SITE_ID' => $modeParams['SITE_ID'], 'CURRENCY' => $modeParams['CURRENCY']));
         }
         if (!Sale\Compatible\DiscountCompatibility::isInited()) {
             if (!empty($modeParams)) {
                 Sale\Compatible\DiscountCompatibility::init($mode, $modeParams);
             }
         }
         unset($modeParams, $mode);
         Sale\Compatible\DiscountCompatibility::clearDiscountResult();
         Sale\Compatible\DiscountCompatibility::fillBasketData($arOrder['BASKET_ITEMS']);
         Sale\Compatible\DiscountCompatibility::calculateBasketDiscounts($arOrder['BASKET_ITEMS']);
         Sale\Compatible\DiscountCompatibility::setApplyMode($arOrder['BASKET_ITEMS']);
         $applyMode = Sale\Discount::getApplyMode();
         if ($applyMode == Sale\Discount::APPLY_MODE_FULL_LAST || $applyMode == Sale\Discount::APPLY_MODE_FULL_DISABLE) {
             foreach ($arOrder['BASKET_ITEMS'] as &$basketItem) {
                 if (isset($basketItem['LAST_DISCOUNT']) && $basketItem['LAST_DISCOUNT'] == 'Y') {
                     $checkIds = false;
                     break;
                 }
             }
             unset($basketItem);
         }
     }
     if ($checkIds) {
         $groupDiscountIterator = Sale\Internals\DiscountGroupTable::getList(array('select' => array('DISCOUNT_ID'), 'filter' => array('@GROUP_ID' => CUser::GetUserGroup($arOrder['USER_ID']), '=ACTIVE' => 'Y')));
         while ($groupDiscount = $groupDiscountIterator->fetch()) {
             $groupDiscount['DISCOUNT_ID'] = (int) $groupDiscount['DISCOUNT_ID'];
             if ($groupDiscount['DISCOUNT_ID'] > 0) {
                 $arIDS[$groupDiscount['DISCOUNT_ID']] = true;
             }
         }
     }
     if (!empty($arIDS)) {
         $arIDS = array_keys($arIDS);
         $couponList = Sale\DiscountCouponsManager::getForApply(array('MODULE_ID' => 'sale', 'DISCOUNT_ID' => $arIDS), array(), true);
         //TODO: fix this condition
         $useProps = true;
         $iblockPropList = array();
         $entityList = Sale\Internals\DiscountEntitiesTable::getByDiscount($arIDS, array('=MODULE_ID' => 'catalog', '=ENTITY' => 'ELEMENT_PROPERTY'));
         if (empty($entityList)) {
             $useProps = false;
         } else {
             if (empty($entityList['catalog']['ELEMENT_PROPERTY'])) {
                 $useProps = false;
             } else {
                 foreach ($entityList['catalog']['ELEMENT_PROPERTY'] as $entity) {
                     $entityField = explode(':', $entity['FIELD_TABLE']);
                     if (isset($entityField[1])) {
                         $propId = (int) $entityField[1];
                         if ($propId > 0) {
                             $iblockPropList[$propId] = $propId;
                         }
                         unset($propId);
                     }
                     unset($entityField);
                 }
                 unset($entity);
                 if (empty($iblockPropList)) {
                     $useProps = false;
                 }
             }
         }
         $arExtend = array('catalog' => array('fields' => true, 'props' => $useProps));
         if ($useProps) {
             $arExtend['iblock']['props'] = $iblockPropList;
         }
         unset($iblockPropList, $useProps);
         foreach (GetModuleEvents('sale', 'OnExtendBasketItems', true) as $arEvent) {
             ExecuteModuleEventEx($arEvent, array(&$arOrder['BASKET_ITEMS'], $arExtend));
         }
         foreach ($arOrder['BASKET_ITEMS'] as &$arOneItem) {
             if (array_key_exists('PRODUCT_PROVIDER_CLASS', $arOneItem) && empty($arOneItem['PRODUCT_PROVIDER_CLASS']) && array_key_exists('CALLBACK_FUNC', $arOneItem) && empty($arOneItem['CALLBACK_FUNC']) && (!isset($arOneItem['CUSTOM_PRICE']) || $arOneItem['CUSTOM_PRICE'] != 'Y')) {
                 if (isset($arOneItem['DISCOUNT_PRICE'])) {
                     $arOneItem['PRICE'] += $arOneItem['DISCOUNT_PRICE'];
                     $arOneItem['DISCOUNT_PRICE'] = 0;
                     $arOneItem['BASE_PRICE'] = $arOneItem['PRICE'];
                 }
             }
         }
         if (isset($arOneItem)) {
             unset($arOneItem);
         }
         if (empty(self::$cacheDiscountHandlers)) {
             self::$cacheDiscountHandlers = CSaleDiscount::getDiscountHandlers($arIDS);
         } else {
             $needDiscountHandlers = array();
             foreach ($arIDS as &$discountID) {
                 if (!isset(self::$cacheDiscountHandlers[$discountID])) {
                     $needDiscountHandlers[] = $discountID;
                 }
             }
             unset($discountID);
             if (!empty($needDiscountHandlers)) {
                 $discountHandlersList = CSaleDiscount::getDiscountHandlers($needDiscountHandlers);
                 if (!empty($discountHandlersList)) {
                     foreach ($discountHandlersList as $discountID => $discountHandlers) {
                         self::$cacheDiscountHandlers[$discountID] = $discountHandlers;
                     }
                     unset($discountHandlers, $discountID);
                 }
                 unset($discountHandlersList);
             }
             unset($needDiscountHandlers);
         }
         $currentDatetime = new Main\Type\DateTime();
         $discountSelect = array('ID', 'PRIORITY', 'SORT', 'LAST_DISCOUNT', 'UNPACK', 'APPLICATION', 'USE_COUPONS', 'EXECUTE_MODULE', 'NAME', 'CONDITIONS_LIST', 'ACTIONS_LIST');
         $discountOrder = array('PRIORITY' => 'DESC', 'SORT' => 'ASC', 'ID' => 'ASC');
         $discountFilter = array('@ID' => $arIDS, '=LID' => $arOrder['SITE_ID'], array('LOGIC' => 'OR', 'ACTIVE_FROM' => '', '<=ACTIVE_FROM' => $currentDatetime), array('LOGIC' => 'OR', 'ACTIVE_TO' => '', '>=ACTIVE_TO' => $currentDatetime));
         if (empty($couponList)) {
             $discountFilter['=USE_COUPONS'] = 'N';
         } else {
             $discountFilter[] = array('LOGIC' => 'OR', '=USE_COUPONS' => 'N', array('=USE_COUPONS' => 'Y', '=COUPON.COUPON' => array_keys($couponList)));
             $discountSelect['DISCOUNT_COUPON'] = 'COUPON.COUPON';
         }
         $discountIterator = Sale\Internals\DiscountTable::getList(array('select' => $discountSelect, 'filter' => $discountFilter, 'order' => $discountOrder));
         $discountApply = array();
         $resultDiscountFullList = array();
         $resultDiscountList = array();
         $resultDiscountKeys = array();
         $resultDiscountIndex = 0;
         while ($discount = $discountIterator->fetch()) {
             $discount['ID'] = (int) $discount['ID'];
             if (isset($discountApply[$discount['ID']])) {
                 continue;
             }
             $discount['MODULE'] = 'sale';
             $discount['MODULE_ID'] = 'sale';
             if ($discount['USE_COUPONS'] == 'Y') {
                 $discount['COUPON'] = $couponList[$discount['DISCOUNT_COUPON']];
             }
             $discountApply[$discount['ID']] = true;
             $applyFlag = true;
             if (isset(self::$cacheDiscountHandlers[$discount['ID']])) {
                 $moduleList = self::$cacheDiscountHandlers[$discount['ID']]['MODULES'];
                 if (!empty($moduleList)) {
                     foreach ($moduleList as &$moduleID) {
                         if (!isset(self::$usedModules[$moduleID])) {
                             self::$usedModules[$moduleID] = Loader::includeModule($moduleID);
                         }
                         if (!self::$usedModules[$moduleID]) {
                             $applyFlag = false;
                             break;
                         }
                     }
                     unset($moduleID);
                     if ($applyFlag) {
                         $discount['MODULES'] = $moduleList;
                     }
                 }
                 unset($moduleList);
             }
             if ($isOrderConverted == 'Y') {
                 Sale\Compatible\DiscountCompatibility::setOrderData($arOrder);
             }
             if ($applyFlag && self::__Unpack($arOrder, $discount['UNPACK'])) {
                 $oldOrder = $arOrder;
                 if ($isOrderConverted == 'Y') {
                     Sale\Discount\Actions::clearAction();
                 }
                 self::__ApplyActions($arOrder, $discount['APPLICATION']);
                 if ($isOrderConverted == 'Y') {
                     $resultDiscountFullList[] = $discount;
                     if (Sale\Compatible\DiscountCompatibility::calculateSaleDiscount($arOrder, $discount)) {
                         $resultDiscountList[$resultDiscountIndex] = array('MODULE_ID' => $discount['MODULE_ID'], 'ID' => $discount['ID'], 'NAME' => $discount['NAME'], 'PRIORITY' => $discount['PRIORITY'], 'SORT' => $discount['SORT'], 'LAST_DISCOUNT' => $discount['LAST_DISCOUNT'], 'CONDITIONS' => serialize($discount['CONDITIONS_LIST']), 'UNPACK' => $discount['UNPACK'], 'ACTIONS' => serialize($discount['ACTIONS_LIST']), 'APPLICATION' => $discount['APPLICATION'], 'RESULT' => self::getDiscountResult($oldOrder, $arOrder, false), 'HANDLERS' => self::$cacheDiscountHandlers[$discount['ID']], 'USE_COUPONS' => $discount['USE_COUPONS'], 'COUPON' => $discount['USE_COUPONS'] == 'Y' ? $couponList[$discount['DISCOUNT_COUPON']] : false);
                         $resultDiscountKeys[$discount['ID']] = $resultDiscountIndex;
                         $resultDiscountIndex++;
                         if ($discount['LAST_DISCOUNT'] == 'Y') {
                             break;
                         }
                     }
                     Sale\Discount\Actions::clearAction();
                 } else {
                     $discountResult = self::getDiscountResult($oldOrder, $arOrder, false);
                     if (!empty($discountResult['DELIVERY']) || !empty($discountResult['BASKET'])) {
                         if ($discount['USE_COUPONS'] == 'Y' && !empty($discount['DISCOUNT_COUPON'])) {
                             if ($couponList[$discount['DISCOUNT_COUPON']]['TYPE'] == Sale\Internals\DiscountCouponTable::TYPE_BASKET_ROW) {
                                 self::changeDiscountResult($oldOrder, $arOrder, $discountResult);
                             }
                             $couponApply = Sale\DiscountCouponsManager::setApply($discount['DISCOUNT_COUPON'], $discountResult);
                             unset($couponApply);
                         }
                         $resultDiscountList[$resultDiscountIndex] = array('MODULE_ID' => $discount['MODULE_ID'], 'ID' => $discount['ID'], 'NAME' => $discount['NAME'], 'PRIORITY' => $discount['PRIORITY'], 'SORT' => $discount['SORT'], 'LAST_DISCOUNT' => $discount['LAST_DISCOUNT'], 'CONDITIONS' => serialize($discount['CONDITIONS_LIST']), 'UNPACK' => $discount['UNPACK'], 'ACTIONS' => serialize($discount['ACTIONS_LIST']), 'APPLICATION' => $discount['APPLICATION'], 'RESULT' => $discountResult, 'HANDLERS' => self::$cacheDiscountHandlers[$discount['ID']], 'USE_COUPONS' => $discount['USE_COUPONS'], 'COUPON' => $discount['USE_COUPONS'] == 'Y' ? $couponList[$discount['DISCOUNT_COUPON']] : false);
                         $resultDiscountKeys[$discount['ID']] = $resultDiscountIndex;
                         $resultDiscountIndex++;
                         if ($discount['LAST_DISCOUNT'] == 'Y') {
                             break;
                         }
                     }
                     unset($discountResult);
                 }
             }
         }
         unset($discount, $discountIterator);
         $arOrder["ORDER_PRICE"] = 0;
         $arOrder["ORDER_WEIGHT"] = 0;
         $arOrder["USE_VAT"] = false;
         $arOrder["VAT_RATE"] = 0;
         $arOrder["VAT_SUM"] = 0;
         $arOrder["DISCOUNT_PRICE"] = 0.0;
         $arOrder["DISCOUNT_VALUE"] = $arOrder["DISCOUNT_PRICE"];
         $arOrder["PRICE_DELIVERY"] = roundEx($arOrder["PRICE_DELIVERY"], SALE_VALUE_PRECISION);
         $arOrder["DELIVERY_PRICE"] = $arOrder["PRICE_DELIVERY"];
         foreach ($arOrder['BASKET_ITEMS'] as &$arShoppingCartItem) {
             if (isset($arShoppingCartItem['CATALOG'])) {
                 unset($arShoppingCartItem['CATALOG']);
             }
             if (!CSaleBasketHelper::isSetItem($arShoppingCartItem)) {
                 $customPrice = isset($arShoppingCartItem['CUSTOM_PRICE']) && ($arShoppingCartItem['CUSTOM_PRICE'] = 'Y');
                 if (!$customPrice) {
                     $arShoppingCartItem['DISCOUNT_PRICE'] = roundEx($arShoppingCartItem['DISCOUNT_PRICE'], SALE_VALUE_PRECISION);
                     if ($arShoppingCartItem['DISCOUNT_PRICE'] > 0) {
                         $arShoppingCartItem['PRICE'] = $arShoppingCartItem['BASE_PRICE'] - $arShoppingCartItem['DISCOUNT_PRICE'];
                     } else {
                         $arShoppingCartItem['PRICE'] = roundEx($arShoppingCartItem['PRICE'], SALE_VALUE_PRECISION);
                     }
                 } else {
                     $arShoppingCartItem['DISCOUNT_PRICE'] = 0;
                 }
                 if (isset($arShoppingCartItem['VAT_RATE'])) {
                     $vatRate = (double) $arShoppingCartItem['VAT_RATE'];
                     if ($vatRate > 0) {
                         $arShoppingCartItem['VAT_VALUE'] = $arShoppingCartItem['PRICE'] / ($vatRate + 1) * $vatRate;
                     }
                     unset($vatRate);
                 }
                 $arOrder["ORDER_PRICE"] += $arShoppingCartItem["PRICE"] * $arShoppingCartItem["QUANTITY"];
                 $arOrder["ORDER_WEIGHT"] += $arShoppingCartItem["WEIGHT"] * $arShoppingCartItem["QUANTITY"];
                 $arShoppingCartItem["PRICE_FORMATED"] = CCurrencyLang::CurrencyFormat($arShoppingCartItem["PRICE"], $arShoppingCartItem["CURRENCY"], true);
                 $arShoppingCartItem["DISCOUNT_PRICE_PERCENT"] = 0;
                 if ($arShoppingCartItem["DISCOUNT_PRICE"] + $arShoppingCartItem["PRICE"] > 0) {
                     $arShoppingCartItem["DISCOUNT_PRICE_PERCENT"] = $arShoppingCartItem["DISCOUNT_PRICE"] * 100 / ($arShoppingCartItem["DISCOUNT_PRICE"] + $arShoppingCartItem["PRICE"]);
                 }
                 $arShoppingCartItem["DISCOUNT_PRICE_PERCENT_FORMATED"] = roundEx($arShoppingCartItem["DISCOUNT_PRICE_PERCENT"], SALE_VALUE_PRECISION) . "%";
                 if ($arShoppingCartItem["VAT_RATE"] > 0) {
                     $arOrder["USE_VAT"] = true;
                     if ($arShoppingCartItem["VAT_RATE"] > $arOrder["VAT_RATE"]) {
                         $arOrder["VAT_RATE"] = $arShoppingCartItem["VAT_RATE"];
                     }
                     $arOrder["VAT_SUM"] += $arShoppingCartItem["VAT_VALUE"] * $arShoppingCartItem["QUANTITY"];
                 }
             }
         }
         unset($arShoppingCartItem);
         $arOrder['DISCOUNT_LIST'] = $resultDiscountList;
         $arOrder['FULL_DISCOUNT_LIST'] = $resultDiscountFullList;
         if ($isOrderConverted == 'Y') {
             Sale\Compatible\DiscountCompatibility::setOldDiscountResult($resultDiscountList);
         }
     }
     if ($isOrderConverted == 'Y' && $oldDelivery != '') {
         $arOrder['DELIVERY_ID'] = $oldDelivery;
     }
     $arOrder["ORDER_PRICE"] = roundEx($arOrder["ORDER_PRICE"], SALE_VALUE_PRECISION);
 }
コード例 #7
0
 /**
  * Init use mode.
  *
  * @param int $mode				Save discount information mode.
  * @param array $config			Initial params (site, currency).
  * 		keys are case sensitive:
  * 			<ul>
  * 			<li>string SITE_ID		Current site
  * 			<li>string CURRENCY		Site currency
  * 			<li>string ORDER_ID		Order id
  * 			</ul>.
  * @return void
  */
 public static function initUseMode($mode = self::MODE_CLIENT, $config = array())
 {
     $adminSection = defined('ADMIN_SECTION') && ADMIN_SECTION === true;
     $mode = (int) $mode;
     if (!is_array($config)) {
         $config = array();
     }
     if ($adminSection) {
         self::$useMode = self::MODE_SYSTEM;
         switch ($mode) {
             case self::MODE_MANAGER:
                 if (empty($config['SITE_ID'])) {
                     self::$errors[] = Loc::getMessage('BX_SALE_DCL_ERR_SITE_ABSENT');
                 } elseif (empty($config['CURRENCY'])) {
                     $config['CURRENCY'] = Sale\Internals\SiteCurrencyTable::getCurrency($config['SITE_ID']);
                 }
                 if (empty($config['CURRENCY'])) {
                     self::$errors[] = Loc::getMessage('BX_SALE_DCL_ERR_CURRENCY_ABSENT');
                 }
                 if (empty(self::$errors)) {
                     self::$useMode = self::MODE_MANAGER;
                     $config['SALE_DISCOUNT_ONLY'] = (string) Main\Config\Option::get('sale', 'use_sale_discount_only');
                     self::$config = $config;
                     self::$discountUseMode = Sale\Discount::USE_MODE_FULL;
                 }
                 break;
             case self::MODE_ORDER:
                 if (empty($config['ORDER_ID'])) {
                     self::$errors[] = Loc::getMessage('BX_SALE_DCL_ERR_ORDER_ID_ABSENT');
                 }
                 if (empty($config['SITE_ID'])) {
                     self::$errors[] = Loc::getMessage('BX_SALE_DCL_ERR_SITE_ABSENT');
                 }
                 if (empty($config['CURRENCY'])) {
                     self::$errors[] = Loc::getMessage('BX_SALE_DCL_ERR_CURRENCY_ABSENT');
                 }
                 if (empty(self::$errors)) {
                     self::$useMode = self::MODE_ORDER;
                     self::$order = $config['ORDER_ID'];
                     unset($config['ORDER_ID']);
                     self::$config = $config;
                 }
                 break;
             case self::MODE_SYSTEM:
                 break;
             default:
                 self::$errors[] = Loc::getMessage('BX_SALE_DCL_ERR_BAD_MODE');
         }
     } else {
         self::$useMode = self::MODE_SYSTEM;
         switch ($mode) {
             case self::MODE_CLIENT:
                 self::$useMode = self::MODE_CLIENT;
                 if (empty($config['SITE_ID'])) {
                     $config['SITE_ID'] = SITE_ID;
                 }
                 if (empty($config['CURRENCY'])) {
                     $config['CURRENCY'] = Sale\Internals\SiteCurrencyTable::getSiteCurrency($config['SITE_ID']);
                 }
                 $config['SALE_DISCOUNT_ONLY'] = (string) Main\Config\Option::get('sale', 'use_sale_discount_only');
                 self::$config = $config;
                 self::$discountUseMode = Sale\Discount::USE_MODE_FULL;
                 break;
             case self::MODE_EXTERNAL:
                 self::$useMode = self::MODE_EXTERNAL;
                 if (empty($config['SITE_ID'])) {
                     $config['SITE_ID'] = SITE_ID;
                 }
                 if (empty($config['CURRENCY'])) {
                     $config['CURRENCY'] = Sale\Internals\SiteCurrencyTable::getSiteCurrency($config['SITE_ID']);
                 }
                 $config['SALE_DISCOUNT_ONLY'] = (string) Main\Config\Option::get('sale', 'use_sale_discount_only');
                 self::$config = $config;
                 self::$discountUseMode = Sale\Discount::USE_MODE_FULL;
                 break;
             case self::MODE_SYSTEM:
                 break;
             case self::MODE_DISABLED:
                 self::$useMode = self::MODE_DISABLED;
                 break;
             default:
                 self::$errors[] = Loc::getMessage('BX_SALE_DCL_ERR_BAD_MODE');
                 break;
         }
     }
 }
コード例 #8
0
ファイル: providerbase.php プロジェクト: Satariall/izurit
 /**
  * @param Basket $basketCollection
  * @param array $select
  * @param BasketItem $refreshItem
  * @return array
  * @throws NotSupportedException
  */
 public static function getProductData(Basket $basketCollection, array $select = array(), BasketItem $refreshItem = null)
 {
     $result = array();
     $orderId = null;
     $userId = null;
     $siteId = null;
     $currency = null;
     if (($order = $basketCollection->getOrder()) !== null) {
         $userId = $order->getUserId();
         $siteId = $order->getSiteId();
         $currency = $order->getCurrency();
     }
     if ($userId === null) {
         static $usersIds = array();
         if (empty($usersIds[$basketCollection->getFUserId(true)])) {
             $usersIds[$basketCollection->getFUserId(true)] = \CSaleUser::getUserID($basketCollection->getFUserId(true));
         }
         $userId = $usersIds[$basketCollection->getFUserId(true)];
     }
     if ($siteId === null) {
         $siteId = $basketCollection->getSiteId();
     }
     if ($siteId === null) {
         return array();
     }
     if ($currency === null) {
         $currency = Internals\SiteCurrencyTable::getSiteCurrency($siteId);
         if (!$currency) {
             $currency = Currency\CurrencyManager::getBaseCurrency();
         }
     }
     $basketList = static::makeArrayFromBasketCollection($basketCollection, $refreshItem);
     $basketProviderMap = static::createProviderBasketMap($basketList, array('QUANTITY', 'RENEWAL'));
     $basketProviderList = static::redistributeToProviders($basketProviderMap);
     if (!empty($basketProviderList)) {
         $needPrice = in_array('PRICE', $select);
         $needBasePrice = in_array('BASE_PRICE', $select);
         $needCoupons = in_array('COUPONS', $select);
         $data = array('USER_ID' => (int) $userId, 'SITE_ID' => $siteId, 'CURRENCY' => $currency, 'CHECK_QUANTITY' => in_array('QUANTITY', $select) ? 'Y' : 'N', 'CHECK_PRICE' => $needPrice ? 'Y' : 'N', 'CHECK_COUPONS' => $needCoupons ? 'Y' : 'N', 'RENEWAL' => in_array('RENEWAL', $select) ? 'Y' : 'N');
         if ($needBasePrice) {
             $data['CHECK_DISCOUNT'] = 'N';
         }
         $useOrderProduct = false;
         if ($needPrice) {
             $useOrderProduct = true;
         }
         if ($needCoupons) {
             $useOrderProduct = false;
         }
         unset($needCoupons, $needPrice);
         foreach ($basketProviderList as $provider => $providerBasketItemList) {
             if ($provider instanceof Provider) {
                 throw new NotSupportedException('provider not supported');
             } elseif ($provider && array_key_exists("IBXSaleProductProvider", class_implements($provider))) {
                 foreach ($providerBasketItemList as $providerBasketItem) {
                     $currentUseOrderProduct = $useOrderProduct;
                     if (!isset($providerBasketItem['BASKET_ID']) || (int) $providerBasketItem['BASKET_ID'] <= 0) {
                         $currentUseOrderProduct = false;
                     }
                     $providerFields = $data;
                     if ($providerBasketItem['BASKET_ITEM']->isBundleChild()) {
                         $providerFields['CHECK_DISCOUNT'] = 'N';
                     }
                     $providerFields['PRODUCT_ID'] = $providerBasketItem['PRODUCT_ID'];
                     $providerFields['QUANTITY'] = $providerBasketItem['QUANTITY'];
                     $hasTrustData = false;
                     $trustData = static::getTrustData($siteId, $providerBasketItem['MODULE'], $providerBasketItem['PRODUCT_ID']);
                     if (static::isReadTrustData() === true && !empty($trustData) && is_array($trustData)) {
                         $hasTrustData = true;
                         $resultProductData = $trustData;
                         foreach (static::getProductDataRequiredFields() as $requiredField) {
                             if (!array_key_exists($requiredField, $resultProductData)) {
                                 $hasTrustData = false;
                                 break;
                             }
                         }
                         if ($hasTrustData && in_array('PRICE', $select)) {
                             foreach (static::getProductDataRequiredPriceFields() as $requiredField) {
                                 if (!array_key_exists($requiredField, $resultProductData)) {
                                     $hasTrustData = false;
                                     break;
                                 }
                             }
                         }
                     }
                     if (!$hasTrustData) {
                         $resultProductData = $currentUseOrderProduct ? $provider::OrderProduct($providerFields) : $provider::GetProductData($providerFields);
                     }
                     $basketCode = $providerBasketItem['BASKET_ITEM']->getBasketCode();
                     $result[$basketCode] = $resultProductData;
                 }
             } else {
                 foreach ($providerBasketItemList as $providerBasketItem) {
                     $resultProductData = \CSaleBasket::executeCallbackFunction($providerBasketItem['CALLBACK_FUNC'], $providerBasketItem['MODULE'], $providerBasketItem['PRODUCT_ID'], $providerBasketItem['QUANTITY']);
                     $basketCode = $providerBasketItem['BASKET_ITEM']->getBasketCode();
                     $result[$basketCode] = $resultProductData;
                 }
             }
         }
     }
     return $result;
 }
コード例 #9
0
ファイル: orderbasket.php プロジェクト: DarneoStudio/bitrix
 /**
  * @param $productId
  * @param $quantity
  * @param $userId
  * @param $LID
  * @param $userColumns
  * @param string $tmpId we can suggest that this mean the set_item
  * @return array
  * @throws Main\LoaderException
  */
 protected function getProductDataToFillBasket($productId, $quantity, $userId, $LID, $userColumns, $tmpId = "")
 {
     $isSetItem = $tmpId != "";
     if (self::$catalogIncluded === null) {
         self::$catalogIncluded = Main\Loader::includeModule('catalog');
     }
     if (!self::$catalogIncluded) {
         return array();
     }
     $arParams = array();
     static $proxyIblockElement = array();
     static $proxyCatalogMeasure = array();
     static $proxyParent = array();
     static $proxyIblockProperty = array();
     static $proxyProductData = array();
     static $proxyCatalogProduct = array();
     static $proxyCatalogMeasureRatio = array();
     $productId = (int) $productId;
     if ($productId <= 0) {
         return $arParams;
     }
     if (!empty($proxyIblockElement[$productId])) {
         $iblockId = $proxyIblockElement[$productId];
     } else {
         $iblockId = (int) \CIBlockElement::getIBlockByID($productId);
         if ($iblockId > 0) {
             $proxyIblockElement[$productId] = $iblockId;
         }
     }
     if ($iblockId <= 0) {
         return $arParams;
     }
     $arSku2Parent = array();
     $arElementId = array();
     $arElementId[] = $productId;
     $proxyParentKey = $productId . "|" . $iblockId;
     if (!empty($proxyParent[$proxyParentKey]) && is_array($proxyParent[$proxyParentKey])) {
         $arParent = $proxyParent[$proxyParentKey];
     } else {
         $arParent = \CCatalogSku::getProductInfo($productId, $iblockId);
         $proxyParent[$proxyParentKey] = $arParent;
     }
     if ($arParent) {
         $arElementId[] = $arParent["ID"];
         $arSku2Parent[$productId] = $arParent["ID"];
     }
     $arPropertyInfo = array();
     $userColumns = (string) $userColumns;
     $arUserColumns = $userColumns != '' ? explode(",", $userColumns) : array();
     foreach ($arUserColumns as $key => $column) {
         if (strncmp($column, 'PROPERTY_', 9) != 0) {
             unset($arUserColumns[$key]);
         } else {
             $propertyCode = substr($column, 9);
             if ($propertyCode == '') {
                 unset($arUserColumns[$key]);
                 continue;
             }
             if (!empty($proxyIblockProperty[$propertyCode]) && is_array($proxyIblockProperty[$propertyCode])) {
                 $arPropertyInfo[$column] = $proxyIblockProperty[$propertyCode];
             } else {
                 $dbres = \CIBlockProperty::GetList(array(), array("CODE" => $propertyCode));
                 if ($arPropData = $dbres->GetNext()) {
                     $arPropertyInfo[$column] = $arPropData;
                     $proxyIblockProperty[$propertyCode] = $arPropData;
                 }
             }
         }
     }
     $arSelect = array_merge(array("ID", "NAME", "IBLOCK_ID", "IBLOCK_SECTION_ID", "DETAIL_PICTURE", "PREVIEW_PICTURE", "XML_ID", "IBLOCK_XML_ID"), $arUserColumns);
     $proxyProductDataKey = md5(join('|', $arElementId) . "_" . join('|', $arSelect));
     if (!empty($proxyProductData[$proxyProductDataKey]) && is_array($proxyProductData[$proxyProductDataKey])) {
         $arProductData = $proxyProductData[$proxyProductDataKey];
     } else {
         $arProductData = getProductProps($arElementId, $arSelect);
         $proxyProductData[$proxyProductDataKey] = $arProductData;
     }
     $defaultMeasure = \CCatalogMeasure::getDefaultMeasure(true, true);
     if (!empty($arProductData)) {
         $arElementInfo = array();
         foreach ($arProductData as $elemId => &$arElement) {
             foreach ($arElement as $key => $value) {
                 if (strncmp($key, 'PROPERTY_', 9) == 0 && substr($key, -6) == "_VALUE") {
                     $columnCode = str_replace("_VALUE", "", $key);
                     $arElement[$key] = getIblockPropInfo($value, $arPropertyInfo[$columnCode], array("WIDTH" => 90, "HEIGHT" => 90));
                 }
             }
         }
         unset($arElement);
         if (isset($arProductData[$productId])) {
             $arElementInfo = $arProductData[$productId];
         }
         if (isset($arSku2Parent[$productId])) {
             $arParent = $arProductData[$arSku2Parent[$productId]];
         }
         if (!empty($arSku2Parent)) {
             foreach ($arUserColumns as $field) {
                 $fieldVal = $field . "_VALUE";
                 $parentId = $arSku2Parent[$productId];
                 if ((!isset($arElementInfo[$fieldVal]) || isset($arElementInfo[$fieldVal]) && strlen($arElementInfo[$fieldVal]) == 0) && (isset($arProductData[$parentId][$fieldVal]) && !empty($arProductData[$parentId][$fieldVal]))) {
                     $arElementInfo[$fieldVal] = $arProductData[$parentId][$fieldVal];
                 }
             }
             if (strpos($arElementInfo["~XML_ID"], '#') === false) {
                 $arElementInfo["~XML_ID"] = $arParent['~XML_ID'] . '#' . $arElementInfo["~XML_ID"];
             }
         }
         $arElementInfo["MODULE"] = "catalog";
         $arElementInfo["PRODUCT_PROVIDER_CLASS"] = "CCatalogProductProvider";
         $arElementInfo["PRODUCT_ID"] = $arElementInfo["ID"];
         if ($arElementInfo["IBLOCK_ID"] > 0) {
             $arElementInfo["EDIT_PAGE_URL"] = \CIBlock::GetAdminElementEditLink($arElementInfo["IBLOCK_ID"], $arElementInfo["PRODUCT_ID"], array("find_section_section" => $arElementInfo["IBLOCK_SECTION_ID"], 'WF' => 'Y'));
         }
         static $buyersGroups = array();
         if (empty($buyersGroups[$userId])) {
             $buyersGroups[$userId] = \CUser::getUserGroup($userId);
         }
         $arBuyerGroups = $buyersGroups[$userId];
         // price
         $currentVatMode = \CCatalogProduct::getPriceVatIncludeMode();
         $currentUseDiscount = \CCatalogProduct::getUseDiscount();
         \CCatalogProduct::setUseDiscount(!$isSetItem);
         \CCatalogProduct::setPriceVatIncludeMode(true);
         \CCatalogProduct::setUsedCurrency(Sale\Internals\SiteCurrencyTable::getSiteCurrency($LID));
         $arPrice = \CCatalogProduct::getOptimalPrice($arElementInfo["ID"], 1, $arBuyerGroups, "N", array(), $LID);
         \CCatalogProduct::clearUsedCurrency();
         \CCatalogProduct::setPriceVatIncludeMode($currentVatMode);
         \CCatalogProduct::setUseDiscount($currentUseDiscount);
         unset($currentUseDiscount, $currentVatMode);
         $currentPrice = $arPrice['RESULT_PRICE']['DISCOUNT_PRICE'];
         $arElementInfo['PRICE'] = $currentPrice;
         $arElementInfo['CURRENCY'] = $arPrice['RESULT_PRICE']['CURRENCY'];
         $currentTotalPrice = $arPrice['RESULT_PRICE']['BASE_PRICE'];
         $arProduct = array();
         if (!empty($proxyCatalogProduct[$productId]) && is_array($proxyCatalogProduct[$productId])) {
             $arProduct = $proxyCatalogProduct[$productId];
         } else {
             $rsProducts = \CCatalogProduct::getList(array(), array('ID' => $productId), false, false, array('ID', 'QUANTITY', 'WEIGHT', 'MEASURE', 'TYPE', 'BARCODE_MULTI'));
             if ($arProduct = $rsProducts->Fetch()) {
                 $proxyCatalogProduct[$productId] = $arProduct;
             }
         }
         if (empty($arProduct) || !is_array($arProduct)) {
             return array();
         }
         $balance = floatval($arProduct["QUANTITY"]);
         // sku props
         $arSkuData = array();
         $arProps[] = array("NAME" => "Catalog XML_ID", "CODE" => "CATALOG.XML_ID", "VALUE" => $arElementInfo['~IBLOCK_XML_ID']);
         static $proxySkuProperty = array();
         if (!empty($proxySkuProperty[$productId]) && is_array($proxySkuProperty[$productId])) {
             $arSkuProperty = $proxySkuProperty[$productId];
         } else {
             $arSkuProperty = \CSaleProduct::GetProductSkuProps($productId, '', true);
             $proxySkuProperty[$productId] = $arSkuProperty;
         }
         if (!empty($arSkuProperty)) {
             foreach ($arSkuProperty as &$val) {
                 $arSkuData[] = array('NAME' => $val['NAME'], 'VALUE' => $val['VALUE'], 'CODE' => $val['CODE']);
             }
             unset($val);
         }
         $arSkuData[] = array("NAME" => "Product XML_ID", "CODE" => "PRODUCT.XML_ID", "VALUE" => $arElementInfo["~XML_ID"]);
         $arElementInfo["WEIGHT"] = $arProduct["WEIGHT"];
         // measure
         $arElementInfo["MEASURE_TEXT"] = "";
         $arElementInfo["MEASURE_CODE"] = 0;
         if ((int) $arProduct["MEASURE"] > 0) {
             if (!empty($proxyCatalogMeasure[$arProduct["MEASURE"]]) && is_array($proxyCatalogMeasure[$arProduct["MEASURE"]])) {
                 $arMeasure = $proxyCatalogMeasure[$arProduct["MEASURE"]];
             } else {
                 $dbMeasure = \CCatalogMeasure::GetList(array(), array("ID" => intval($arProduct["MEASURE"])), false, false, array("ID", "SYMBOL_RUS", "SYMBOL_INTL"));
                 if ($arMeasure = $dbMeasure->Fetch()) {
                     $proxyCatalogMeasure[$arProduct["MEASURE"]] = $arMeasure;
                 }
             }
             if (!empty($arMeasure) && is_array($arMeasure)) {
                 $arElementInfo["MEASURE_TEXT"] = $arMeasure["SYMBOL_RUS"] != '' ? $arMeasure["SYMBOL_RUS"] : $arMeasure["SYMBOL_INTL"];
                 $arElementInfo["MEASURE_CODE"] = $arMeasure["CODE"];
             }
         }
         if ($arElementInfo["MEASURE_TEXT"] == '') {
             $arElementInfo["MEASURE_TEXT"] = $defaultMeasure["SYMBOL_RUS"] != '' ? $defaultMeasure["SYMBOL_RUS"] : $defaultMeasure["SYMBOL_INTL"];
         }
         // ratio
         $arElementInfo["RATIO"] = 1;
         if (!empty($proxyCatalogMeasureRatio[$productId]) && is_array($proxyCatalogMeasureRatio[$productId])) {
             $arRatio = $proxyCatalogMeasureRatio[$productId];
         } else {
             $dbratio = \CCatalogMeasureRatio::GetList(array(), array("PRODUCT_ID" => $productId));
             if ($arRatio = $dbratio->Fetch()) {
                 $proxyCatalogMeasureRatio[$productId] = $arRatio;
             }
         }
         if (!empty($arRatio) && is_array($arRatio)) {
             $arElementInfo["RATIO"] = $arRatio["RATIO"];
         }
         // image
         $imgCode = '';
         $imgUrl = '';
         if ($arElementInfo["PREVIEW_PICTURE"] > 0) {
             $imgCode = $arElementInfo["PREVIEW_PICTURE"];
         } elseif ($arElementInfo["DETAIL_PICTURE"] > 0) {
             $imgCode = $arElementInfo["DETAIL_PICTURE"];
         }
         if ($imgCode == "" && count($arParent) > 0) {
             if ($arParent["PREVIEW_PICTURE"] > 0) {
                 $imgCode = $arParent["PREVIEW_PICTURE"];
             } elseif ($arParent["DETAIL_PICTURE"] > 0) {
                 $imgCode = $arParent["DETAIL_PICTURE"];
             }
         }
         if ($imgCode > 0) {
             $arFile = \CFile::GetFileArray($imgCode);
             $arImgProduct = \CFile::ResizeImageGet($arFile, array('width' => 80, 'height' => 80), BX_RESIZE_IMAGE_PROPORTIONAL, false, false);
             if (is_array($arImgProduct)) {
                 $imgUrl = $arImgProduct["src"];
             }
         }
         $arSetInfo = array();
         $arStores = array();
         /** @var $productProvider IBXSaleProductProvider */
         if ($productProvider = \CSaleBasket::GetProductProvider(array("MODULE" => $arElementInfo["MODULE"], "PRODUCT_PROVIDER_CLASS" => $arElementInfo["PRODUCT_PROVIDER_CLASS"]))) {
             // get set items if it is set
             if ($arProduct["TYPE"] == \CCatalogProduct::TYPE_SET) {
                 if (method_exists($productProvider, "GetSetItems")) {
                     $arSets = $productProvider::GetSetItems($productId, \CSaleBasket::TYPE_SET);
                     if ($tmpId == "") {
                         $tmpId = randString(7);
                     }
                     if (!empty($arSets)) {
                         foreach ($arSets as $arSetData) {
                             foreach ($arSetData["ITEMS"] as $setItem) {
                                 $arSetItemParams = self::getProductDataToFillBasket($setItem["PRODUCT_ID"], $setItem["QUANTITY"], $userId, $LID, $userColumns, $tmpId);
                                 // recursive call
                                 // re-define some fields with set data values
                                 $arSetItemParams["PARENT_OFFER_ID"] = $productId;
                                 $arSetItemParams["OFFER_ID"] = $setItem["PRODUCT_ID"];
                                 $arSetItemParams["NAME"] = $setItem["NAME"];
                                 $arSetItemParams["MODULE"] = $setItem["MODULE"];
                                 $arSetItemParams["PRODUCT_PROVIDER_CLASS"] = $setItem["PRODUCT_PROVIDER_CLASS"];
                                 $arSetItemParams["QUANTITY"] = $setItem["QUANTITY"] * $quantity;
                                 $arSetItemParams["BARCODE_MULTI"] = $setItem["BARCODE_MULTI"];
                                 $arSetItemParams["PRODUCT_TYPE"] = $setItem["TYPE"];
                                 $arSetItemParams["WEIGHT"] = $setItem["WEIGHT"];
                                 $arSetItemParams["VAT_RATE"] = $setItem["VAT_RATE"];
                                 $arSetItemParams["SET_ITEMS"] = "";
                                 $arSetItemParams["OLD_PARENT_ID"] = $productId . "_tmp" . $tmpId;
                                 $arSetItemParams["IS_SET_ITEM"] = "Y";
                                 $arSetItemParams["IS_SET_PARENT"] = "N";
                                 $arSetItemParams["PROVIDER_DATA"] = serialize($setItem);
                                 $arSetInfo[] = $arSetItemParams;
                             }
                         }
                     }
                 }
             }
             // get stores
             $storeCount = $productProvider::GetStoresCount(array("SITE_ID" => $LID));
             // with exact SITE_ID or SITE_ID = NULL
             if ($storeCount > 0) {
                 if ($arProductStore = $productProvider::GetProductStores(array("PRODUCT_ID" => $productId, "SITE_ID" => $LID))) {
                     $arStores = $arProductStore;
                 }
             }
         }
         $currentTotalPrice = (double) $currentTotalPrice;
         // params array
         $arParams["OFFER_ID"] = $productId;
         $arParams["NAME"] = $arElementInfo["~NAME"];
         $arParams["EDIT_PAGE_URL"] = $arElementInfo["EDIT_PAGE_URL"];
         $arParams["DETAIL_PAGE_URL"] = htmlspecialcharsex($arElementInfo["~DETAIL_PAGE_URL"]);
         $arParams["PICTURE_URL"] = $imgUrl;
         $arParams["PRICE"] = floatval($arElementInfo["PRICE"]);
         $arParams["PRICE_BASE"] = $currentTotalPrice;
         $arParams["DIMENSIONS"] = serialize(array("WIDTH" => $arElementInfo["WIDTH"], "HEIGHT" => $arElementInfo["HEIGHT"], "LENGTH" => $arElementInfo["LENGTH"]));
         $arParams["QUANTITY"] = $quantity;
         $arParams["MODULE"] = $arElementInfo["MODULE"];
         $arParams["CURRENCY"] = $arElementInfo["CURRENCY"];
         $arParams["WEIGHT"] = $arElementInfo["WEIGHT"];
         $arParams["VAT_RATE"] = $arPrice["PRICE"]["VAT_RATE"];
         $arParams["PRICE_TYPE"] = $arPrice["PRICE"]["CATALOG_GROUP_NAME"];
         $arParams["AVAILABLE"] = $balance;
         $arParams["NOTES"] = !empty($arPrice["PRICE"]["CATALOG_GROUP_NAME"]) ? $arPrice["PRICE"]["CATALOG_GROUP_NAME"] : "";
         $arParams["CATALOG_XML_ID"] = $arElementInfo["~IBLOCK_XML_ID"];
         $arParams["PRODUCT_XML_ID"] = $arElementInfo["~XML_ID"];
         $arParams["PRODUCT_PROVIDER_CLASS"] = $arElementInfo["PRODUCT_PROVIDER_CLASS"];
         $arParams["PROPS"] = $arSkuData;
         $arParams["MEASURE_TEXT"] = $arElementInfo["MEASURE_TEXT"];
         $arParams["MEASURE_CODE"] = $arElementInfo["MEASURE_CODE"];
         $arParams["MEASURE_RATIO"] = $arElementInfo["RATIO"];
         $arParams["BARCODE_MULTI"] = $arProduct["BARCODE_MULTI"];
         $arParams["PRODUCT_TYPE"] = empty($arSetInfo) ? "" : \CSaleBasket::TYPE_SET;
         $arParams["OLD_PARENT_ID"] = empty($arSetInfo) ? "" : $productId . "_tmp" . $tmpId;
         $arParams["SET_ITEMS"] = $arSetInfo;
         $arParams["IS_SET_ITEM"] = "N";
         $arParams["IS_SET_PARENT"] = empty($arSetInfo) ? "N" : "Y";
         $arParams["STORES"] = empty($arSetInfo) ? $arStores : array();
         $arParams["PRODUCT_PROPS_VALUES"] = $arElementInfo;
         // along with other information also contains values of properties with correct keys (after getProductProps)
     }
     return $arParams;
 }
コード例 #10
0
ファイル: discount.php プロジェクト: webgksupport/alpina
 /**
  * Default onBeforeAdd handler. Absolutely necessary.
  *
  * @param Main\Entity\Event $event		Event object.
  * @return Main\Entity\EventResult
  */
 public static function onBeforeAdd(Main\Entity\Event $event)
 {
     $result = new Main\Entity\EventResult();
     $data = $event->getParameter('fields');
     $modifyFieldList = array('DISCOUNT_VALUE' => 0, 'DISCOUNT_TYPE' => 'P');
     if (isset($data['LID'])) {
         $modifyFieldList['CURRENCY'] = SiteCurrencyTable::getSiteCurrency($data['LID']);
     }
     self::setUserID($modifyFieldList, $data, array('CREATED_BY', 'MODIFIED_BY'));
     self::setTimestamp($modifyFieldList, $data, array('DATE_CREATE', 'TIMESTAMP_X'));
     self::copyOldFields($modifyFieldList, $data);
     $result->unsetField('CONDITIONS');
     $result->unsetField('ACTIONS');
     if (!empty($modifyFieldList)) {
         $result->modifyFields($modifyFieldList);
     }
     unset($modifyFieldList);
     return $result;
 }