Exemple #1
0
	public static function PrepareCurrency4Where($val, $key, $operation, $negative, $field, &$arField, &$arFilter)
	{
		$val = DoubleVal($val);

		$baseSiteCurrency = "";
		if (isset($arFilter["LID"]) && strlen($arFilter["LID"]) > 0)
			$baseSiteCurrency = CSaleLang::GetLangCurrency($arFilter["LID"]);
		elseif (isset($arFilter["CURRENCY"]) && strlen($arFilter["CURRENCY"]) > 0)
			$baseSiteCurrency = $arFilter["CURRENCY"];

		if (strlen($baseSiteCurrency) <= 0)
			return False;

		$strSqlSearch = "";

		$dbCurrency = CCurrency::GetList(($by = "sort"), ($order = "asc"));
		while ($arCurrency = $dbCurrency->Fetch())
		{
			$val1 = roundEx(CCurrencyRates::ConvertCurrency($val, $baseSiteCurrency, $arCurrency["CURRENCY"]), SALE_VALUE_PRECISION);
			if (strlen($strSqlSearch) > 0)
				$strSqlSearch .= " OR ";

			$strSqlSearch .= "(D.ORDER_CURRENCY = '".$arCurrency["CURRENCY"]."' AND ";
			if ($negative == "Y")
				$strSqlSearch .= "NOT";
			$strSqlSearch .= "(".$field." ".$operation." ".$val1." OR ".$field." IS NULL OR ".$field." = 0)";
			$strSqlSearch .= ")";
		}

		return "(".$strSqlSearch.")";
	}
 public static function DoLoadDelivery($location, $locationZip, $weight, $price, $currency, $siteId = null)
 {
     $location = intval($location);
     if ($location <= 0) {
         return null;
     }
     if ($siteId == null) {
         $siteId = SITE_ID;
     }
     $arResult = array();
     $arFilter = array("COMPABILITY" => array("WEIGHT" => $weight, "PRICE" => $price, "LOCATION_FROM" => COption::GetOptionString('sale', 'location', false, $siteId), "LOCATION_TO" => $location, "LOCATION_ZIP" => $locationZip), "SITE_ID" => $siteId);
     $dbDeliveryServices = CSaleDeliveryHandler::GetList(array("SORT" => "ASC"), $arFilter);
     while ($arDeliveryService = $dbDeliveryServices->GetNext()) {
         if (!is_array($arDeliveryService) || !is_array($arDeliveryService["PROFILES"])) {
             continue;
         }
         foreach ($arDeliveryService["PROFILES"] as $profileId => $arDeliveryProfile) {
             if ($arDeliveryProfile["ACTIVE"] != "Y") {
                 continue;
             }
             if (!array_key_exists($arDeliveryService["SID"], $arResult)) {
                 $arResult[$arDeliveryService["SID"]] = array("SID" => $arDeliveryService["SID"], "TITLE" => $arDeliveryService["NAME"], "DESCRIPTION" => $arDeliveryService["DESCRIPTION"], "PROFILES" => array());
             }
             $arResult[$arDeliveryService["SID"]]["PROFILES"][$profileId] = array("ID" => $arDeliveryService["SID"] . ":" . $profileId, "SID" => $profileId, "TITLE" => $arDeliveryProfile["TITLE"], "DESCRIPTION" => $arDeliveryProfile["DESCRIPTION"], "FIELD_NAME" => "DELIVERY_ID");
             $arDeliveryPriceTmp = CSaleDeliveryHandler::CalculateFull($arDeliveryService["SID"], $profileId, array("PRICE" => $price, "WEIGHT" => $weight, "LOCATION_FROM" => COption::GetOptionString('sale', 'location', false, $siteId), "LOCATION_TO" => $location, "LOCATION_ZIP" => $locationZip), $currency);
             if ($arDeliveryPriceTmp["RESULT"] != "ERROR") {
                 $arResult[$arDeliveryService["SID"]]["PROFILES"][$profileId]["DELIVERY_PRICE"] = roundEx($arDeliveryPriceTmp["VALUE"], SALE_VALUE_PRECISION);
                 $arResult[$arDeliveryService["SID"]]["PROFILES"][$profileId]["CURRENCY"] = $currency;
             }
         }
     }
     $dbDelivery = CSaleDelivery::GetList(array("SORT" => "ASC", "NAME" => "ASC"), array("LID" => $siteId, "+<=WEIGHT_FROM" => $weight, "+>=WEIGHT_TO" => $weight, "+<=ORDER_PRICE_FROM" => $price, "+>=ORDER_PRICE_TO" => $price, "ACTIVE" => "Y", "LOCATION" => $location));
     while ($arDelivery = $dbDelivery->GetNext()) {
         $arDeliveryDescription = CSaleDelivery::GetByID($arDelivery["ID"]);
         $arDelivery["DESCRIPTION"] = $arDeliveryDescription["DESCRIPTION"];
         $arDelivery["FIELD_NAME"] = "DELIVERY_ID";
         if (intval($arDelivery["PERIOD_FROM"]) > 0 || intval($arDelivery["PERIOD_TO"]) > 0) {
             $arDelivery["PERIOD_TEXT"] = GetMessage("SALE_DELIV_PERIOD");
             if (intval($arDelivery["PERIOD_FROM"]) > 0) {
                 $arDelivery["PERIOD_TEXT"] .= " " . GetMessage("SOA_FROM") . " " . intval($arDelivery["PERIOD_FROM"]);
             }
             if (intval($arDelivery["PERIOD_TO"]) > 0) {
                 $arDelivery["PERIOD_TEXT"] .= " " . GetMessage("SOA_TO") . " " . intval($arDelivery["PERIOD_TO"]);
             }
             if ($arDelivery["PERIOD_TYPE"] == "H") {
                 $arDelivery["PERIOD_TEXT"] .= " " . GetMessage("SOA_HOUR") . " ";
             } elseif ($arDelivery["PERIOD_TYPE"] == "M") {
                 $arDelivery["PERIOD_TEXT"] .= " " . GetMessage("SOA_MONTH") . " ";
             } else {
                 $arDelivery["PERIOD_TEXT"] .= " " . GetMessage("SOA_DAY") . " ";
             }
         }
         $arResult[] = $arDelivery;
     }
     return $arResult;
 }
Exemple #3
0
 public function getBasketItems()
 {
     global $APPLICATION;
     if (self::$catalogIncluded === null) {
         self::$catalogIncluded = Loader::includeModule('catalog');
     }
     self::$iblockIncluded = self::$catalogIncluded;
     CSaleBasket::UpdateBasketPrices(CSaleBasket::GetBasketUserID(), SITE_ID);
     $bShowReady = false;
     $bShowDelay = false;
     $bShowSubscribe = false;
     $bShowNotAvail = false;
     $allSum = 0;
     $allWeight = 0;
     $allCurrency = CSaleLang::GetLangCurrency(SITE_ID);
     $allVATSum = 0;
     $arParents = array();
     $arResult["ITEMS"]["AnDelCanBuy"] = array();
     $arResult["ITEMS"]["DelDelCanBuy"] = array();
     $arResult["ITEMS"]["nAnCanBuy"] = array();
     $arResult["ITEMS"]["ProdSubscribe"] = array();
     $DISCOUNT_PRICE_ALL = 0;
     // BASKET PRODUCTS (including measures, ratio, iblock properties data)
     $arImgFields = array("PREVIEW_PICTURE", "DETAIL_PICTURE");
     $arBasketItems = array();
     $basketKey = 0;
     $basketIds = array();
     $arSku2Parent = array();
     $arSetParentWeight = array();
     $arElementId = array();
     $dbItems = CSaleBasket::GetList(array("ID" => "ASC"), array("FUSER_ID" => CSaleBasket::GetBasketUserID(), "LID" => SITE_ID, "ORDER_ID" => "NULL"), false, false, array("ID", "NAME", "CALLBACK_FUNC", "MODULE", "PRODUCT_ID", "QUANTITY", "DELAY", "CAN_BUY", "PRICE", "WEIGHT", "DETAIL_PAGE_URL", "NOTES", "CURRENCY", "VAT_RATE", "CATALOG_XML_ID", "PRODUCT_XML_ID", "SUBSCRIBE", "DISCOUNT_PRICE", "PRODUCT_PROVIDER_CLASS", "TYPE", "SET_PARENT_ID"));
     while ($arItem = $dbItems->GetNext()) {
         $arItem['PROPS'] = array();
         $arBasketItems[$basketKey] = $arItem;
         $basketIds[$arItem['ID']] =& $arBasketItems[$basketKey];
         $basketKey++;
         if (CSaleBasketHelper::isSetItem($arItem)) {
             continue;
         }
         $arElementId[] = $arItem["PRODUCT_ID"];
     }
     if (!empty($arElementId) && self::$catalogIncluded) {
         $productList = CCatalogSKU::getProductList($arElementId);
         if (!empty($productList)) {
             foreach ($productList as $offerId => $offerInfo) {
                 $offerInfo['PRODUCT_ID'] = $offerInfo['ID'];
                 $arElementId[] = $offerInfo['ID'];
                 $arSku2Parent[$offerId] = $offerInfo['ID'];
                 $arParents[$offerId] = $offerInfo;
             }
             unset($offerInfo, $offerId);
         }
         unset($productList);
         // get measures, ratio, sku props data and available quantity
         $arBasketItems = getMeasures($arBasketItems);
         $arBasketItems = getRatio($arBasketItems);
         $arBasketItems = $this->getAvailableQuantity($arBasketItems);
         $propsIterator = CSaleBasket::GetPropsList(array('BASKET_ID' => 'ASC', 'SORT' => 'ASC', 'ID' => 'ASC'), array('BASKET_ID' => array_keys($basketIds)));
         while ($property = $propsIterator->GetNext()) {
             $property['CODE'] = (string) $property['CODE'];
             if ($property['CODE'] == 'CATALOG.XML_ID' || $property['CODE'] == 'PRODUCT.XML_ID') {
                 continue;
             }
             if (!isset($basketIds[$property['BASKET_ID']])) {
                 continue;
             }
             $basketIds[$property['BASKET_ID']]['PROPS'][] = $property;
         }
         unset($property, $propsIterator, $basketIds);
     }
     // get product properties data
     $arProductData = getProductProps($arElementId, array_merge(array("ID"), $arImgFields, $this->arCustomSelectFields));
     foreach ($arBasketItems as &$arItem) {
         $quantityIsFloat = false;
         if (number_format(doubleval($arItem['QUANTITY']), 2, '.', '') != intval($arItem['QUANTITY'])) {
             $quantityIsFloat = true;
         }
         $arItem["QUANTITY"] = $quantityIsFloat === false && $this->quantityFloat != "Y" ? intval($arItem['QUANTITY']) : number_format(doubleval($arItem['QUANTITY']), 2, '.', '');
         $arItem["PRICE_VAT_VALUE"] = $arItem["PRICE"] / ($arItem["VAT_RATE"] + 1) * $arItem["VAT_RATE"];
         $arItem["PRICE_FORMATED"] = CCurrencyLang::CurrencyFormat($arItem["PRICE"], $arItem["CURRENCY"], true);
         $arItem["WEIGHT"] = doubleval($arItem["WEIGHT"]);
         $arItem["WEIGHT_FORMATED"] = roundEx(doubleval($arItem["WEIGHT"] / $this->weightKoef), SALE_WEIGHT_PRECISION) . " " . $this->weightUnit;
         if (CSaleBasketHelper::isSetItem($arItem)) {
             $arSetParentWeight[$arItem["SET_PARENT_ID"]] += $arItem["WEIGHT"] * $arItem["QUANTITY"];
         }
         if (isset($arProductData[$arItem['PRODUCT_ID']]) && is_array($arProductData[$arItem['PRODUCT_ID']])) {
             foreach ($arProductData[$arItem["PRODUCT_ID"]] as $key => $value) {
                 if (strpos($key, "PROPERTY_") !== false || in_array($key, $arImgFields)) {
                     $arItem[$key] = $value;
                 }
             }
         }
         if (array_key_exists($arItem["PRODUCT_ID"], $arSku2Parent)) {
             $arFieldsToFill = array_merge($this->arCustomSelectFields, $arImgFields);
             // fields to be filled with parents' values if empty
             foreach ($arFieldsToFill as $field) {
                 $fieldVal = in_array($field, $arImgFields) ? $field : $field . "_VALUE";
                 $parentId = $arSku2Parent[$arItem["PRODUCT_ID"]];
                 if ((!isset($arItem[$fieldVal]) || isset($arItem[$fieldVal]) && strlen($arItem[$fieldVal]) == 0) && (isset($arProductData[$parentId][$fieldVal]) && !empty($arProductData[$parentId][$fieldVal]))) {
                     $arItem[$fieldVal] = $arProductData[$parentId][$fieldVal];
                 }
             }
         }
         foreach ($arItem as $key => $value) {
             if (strpos($key, "PROPERTY_", 0) === 0 && strrpos($key, "_VALUE") == strlen($key) - 6) {
                 $code = str_replace(array("PROPERTY_", "_VALUE"), "", $key);
                 $propData = $this->arIblockProps[$code];
                 $arItem[$key] = CSaleHelper::getIblockPropInfo($value, $propData);
             }
         }
         $arItem["PREVIEW_PICTURE_SRC"] = "";
         if (isset($arItem["PREVIEW_PICTURE"]) && intval($arItem["PREVIEW_PICTURE"]) > 0) {
             $arImage = CFile::GetFileArray($arItem["PREVIEW_PICTURE"]);
             if ($arImage) {
                 $arFileTmp = CFile::ResizeImageGet($arImage, array("width" => "110", "height" => "110"), BX_RESIZE_IMAGE_PROPORTIONAL, true);
                 $arItem["PREVIEW_PICTURE_SRC"] = $arFileTmp["src"];
             }
         }
         $arItem["DETAIL_PICTURE_SRC"] = "";
         if (isset($arItem["DETAIL_PICTURE"]) && intval($arItem["DETAIL_PICTURE"]) > 0) {
             $arImage = CFile::GetFileArray($arItem["DETAIL_PICTURE"]);
             if ($arImage) {
                 $arFileTmp = CFile::ResizeImageGet($arImage, array("width" => "110", "height" => "110"), BX_RESIZE_IMAGE_PROPORTIONAL, true);
                 $arItem["DETAIL_PICTURE_SRC"] = $arFileTmp["src"];
             }
         }
     }
     unset($arItem);
     // get sku props data
     if (!empty($arBasketItems) && self::$catalogIncluded && isset($this->offersProps) && !empty($this->offersProps)) {
         $arBasketItems = $this->getSkuPropsData($arBasketItems, $arParents, $this->offersProps);
     }
     // count weight for set parent products
     foreach ($arBasketItems as &$arItem) {
         if (CSaleBasketHelper::isSetParent($arItem)) {
             $arItem["WEIGHT"] = $arSetParentWeight[$arItem["ID"]] / $arItem["QUANTITY"];
             $arItem["WEIGHT_FORMATED"] = roundEx(doubleval($arItem["WEIGHT"] / $this->weightKoef), SALE_WEIGHT_PRECISION) . " " . $this->weightUnit;
         }
     }
     if (isset($arItem)) {
         unset($arItem);
     }
     // fill item arrays for old templates
     foreach ($arBasketItems as &$arItem) {
         if (CSaleBasketHelper::isSetItem($arItem)) {
             continue;
         }
         $arItem['DISCOUNT_PRICE'] = (double) $arItem['DISCOUNT_PRICE'];
         $arItem['PRICE'] = (double) $arItem['PRICE'];
         $arItem['DISCOUNT_PRICE_PERCENT'] = 0;
         $arItem['DISCOUNT_PRICE_PERCENT_FORMATED'] = '';
         $arItem['FULL_PRICE'] = $arItem['PRICE'];
         if ($arItem['DISCOUNT_PRICE'] > 0) {
             if ($arItem['DISCOUNT_PRICE'] + $arItem['PRICE'] > 0) {
                 $arItem['DISCOUNT_PRICE_PERCENT'] = $arItem['DISCOUNT_PRICE'] * 100 / ($arItem['DISCOUNT_PRICE'] + $arItem['PRICE']);
                 $arItem['DISCOUNT_PRICE_PERCENT_FORMATED'] = roundEx($arItem['DISCOUNT_PRICE_PERCENT'], SALE_VALUE_PRECISION) . '%';
                 $arItem['FULL_PRICE'] = $arItem["PRICE"] + $arItem["DISCOUNT_PRICE"];
             }
         }
         $arItem['FULL_PRICE_FORMATED'] = CCurrencyLang::CurrencyFormat($arItem['FULL_PRICE'], $arItem['CURRENCY'], true);
         if ($arItem["CAN_BUY"] == "Y" && $arItem["DELAY"] == "N") {
             $allSum += $arItem["PRICE"] * $arItem["QUANTITY"];
             $allWeight += $arItem["WEIGHT"] * $arItem["QUANTITY"];
             $allVATSum += roundEx($arItem["PRICE_VAT_VALUE"] * $arItem["QUANTITY"], SALE_VALUE_PRECISION);
             $bShowReady = true;
             if ($arItem["DISCOUNT_PRICE"] > 0) {
                 $DISCOUNT_PRICE_ALL += $arItem["DISCOUNT_PRICE"] * $arItem["QUANTITY"];
             }
             $arResult["ITEMS"]["AnDelCanBuy"][] = $arItem;
         } elseif ($arItem["CAN_BUY"] == "Y" && $arItem["DELAY"] == "Y") {
             $bShowDelay = true;
             $arResult["ITEMS"]["DelDelCanBuy"][] = $arItem;
         } elseif ($arItem["CAN_BUY"] == "N" && $arItem["SUBSCRIBE"] == "Y") {
             $bShowSubscribe = true;
             $arResult["ITEMS"]["ProdSubscribe"][] = $arItem;
         } else {
             $bShowNotAvail = true;
             $arItem["NOT_AVAILABLE"] = true;
             $arResult["ITEMS"]["nAnCanBuy"][] = $arItem;
         }
     }
     unset($arItem);
     $arResult["ShowReady"] = $bShowReady ? "Y" : "N";
     $arResult["ShowDelay"] = $bShowDelay ? "Y" : "N";
     $arResult["ShowNotAvail"] = $bShowNotAvail ? "Y" : "N";
     $arResult["ShowSubscribe"] = $bShowSubscribe ? "Y" : "N";
     $arOrder = array('SITE_ID' => SITE_ID, 'USER_ID' => $GLOBALS["USER"]->GetID(), 'ORDER_PRICE' => $allSum, 'ORDER_WEIGHT' => $allWeight, 'BASKET_ITEMS' => $arResult["ITEMS"]["AnDelCanBuy"]);
     $arOptions = array('COUNT_DISCOUNT_4_ALL_QUANTITY' => $this->countDiscount4AllQuantity);
     $arErrors = array();
     CSaleDiscount::DoProcessOrder($arOrder, $arOptions, $arErrors);
     if (isset($arOrder['ORDER_PRICE'])) {
         $roundOrderFields = CSaleOrder::getRoundFields();
         foreach ($arOrder as $fieldName => $fieldValue) {
             if (in_array($fieldName, $roundOrderFields)) {
                 $arOrder[$fieldName] = roundEx($arOrder[$fieldName], SALE_VALUE_PRECISION);
             }
         }
     }
     if (!empty($arOrder['BASKET_ITEMS']) && is_array($arOrder['BASKET_ITEMS'])) {
         $arOrder['ORDER_PRICE'] = 0;
         $roundBasketFields = CSaleBasket::getRoundFields();
         foreach ($arOrder['BASKET_ITEMS'] as &$basketItem) {
             foreach ($basketItem as $fieldName => $fieldValue) {
                 if (in_array($fieldName, $roundBasketFields)) {
                     if (isset($basketItem[$fieldName])) {
                         $basketItem[$fieldName] = roundEx($basketItem[$fieldName], SALE_VALUE_PRECISION);
                     }
                 }
             }
             $arOrder['ORDER_PRICE'] += $basketItem['PRICE'] * $basketItem['QUANTITY'];
         }
         $arOrder['ORDER_PRICE'] = roundEx($arOrder['ORDER_PRICE'], SALE_VALUE_PRECISION);
     }
     $allSum = 0;
     $allWeight = 0;
     $allVATSum = 0;
     $DISCOUNT_PRICE_ALL = 0;
     $priceWithoutDiscount = 0;
     foreach ($arOrder["BASKET_ITEMS"] as &$arOneItem) {
         $allWeight += $arOneItem["WEIGHT"] * $arOneItem["QUANTITY"];
         $allSum += $arOneItem["PRICE"] * $arOneItem["QUANTITY"];
         if (array_key_exists('VAT_VALUE', $arOneItem)) {
             $arOneItem["PRICE_VAT_VALUE"] = $arOneItem["VAT_VALUE"];
         }
         $allVATSum += roundEx($arOneItem["PRICE_VAT_VALUE"] * $arOneItem["QUANTITY"], SALE_VALUE_PRECISION);
         $arOneItem["PRICE_FORMATED"] = CCurrencyLang::CurrencyFormat($arOneItem["PRICE"], $arOneItem["CURRENCY"], true);
         $arOneItem["FULL_PRICE"] = $arOneItem["PRICE"] + $arOneItem["DISCOUNT_PRICE"];
         $arOneItem["FULL_PRICE_FORMATED"] = CCurrencyLang::CurrencyFormat($arOneItem["FULL_PRICE"], $arOneItem["CURRENCY"], true);
         $arOneItem["SUM"] = CCurrencyLang::CurrencyFormat($arOneItem["PRICE"] * $arOneItem["QUANTITY"], $arOneItem["CURRENCY"], true);
         if (0 < doubleval($arOneItem["DISCOUNT_PRICE"] + $arOneItem["PRICE"])) {
             $arOneItem["DISCOUNT_PRICE_PERCENT"] = $arOneItem["DISCOUNT_PRICE"] * 100 / ($arOneItem["DISCOUNT_PRICE"] + $arOneItem["PRICE"]);
         } else {
             $arOneItem["DISCOUNT_PRICE_PERCENT"] = 0;
         }
         $arOneItem["DISCOUNT_PRICE_PERCENT_FORMATED"] = roundEx($arOneItem["DISCOUNT_PRICE_PERCENT"], SALE_VALUE_PRECISION) . "%";
         $DISCOUNT_PRICE_ALL += $arOneItem["DISCOUNT_PRICE"] * $arOneItem["QUANTITY"];
     }
     unset($arOneItem);
     $arResult["ITEMS"]["AnDelCanBuy"] = $arOrder["BASKET_ITEMS"];
     // fill grid data (for new templates with custom columns)
     foreach ($arResult["ITEMS"] as $type => $arItems) {
         foreach ($arItems as $k => $arItem) {
             $arResult["GRID"]["ROWS"][$arItem["ID"]] = $arItem;
         }
     }
     $arResult["allSum"] = roundEx($allSum, SALE_VALUE_PRECISION);
     $arResult["allWeight"] = $allWeight;
     $arResult["allWeight_FORMATED"] = roundEx(doubleval($allWeight / $this->weightKoef), SALE_WEIGHT_PRECISION) . " " . $this->weightUnit;
     $arResult["allSum_FORMATED"] = CCurrencyLang::CurrencyFormat($allSum, $allCurrency, true);
     $arResult["DISCOUNT_PRICE_FORMATED"] = CCurrencyLang::CurrencyFormat($arResult["DISCOUNT_PRICE"], $allCurrency, true);
     $arResult["PRICE_WITHOUT_DISCOUNT"] = CCurrencyLang::CurrencyFormat($allSum + $DISCOUNT_PRICE_ALL, $allCurrency, true);
     if ($this->priceVatShowValue == 'Y') {
         $arResult["allVATSum"] = roundEx($allVATSum, SALE_VALUE_PRECISION);
         $arResult["allVATSum_FORMATED"] = CCurrencyLang::CurrencyFormat($allVATSum, $allCurrency, true);
         $arResult["allSum_wVAT_FORMATED"] = CCurrencyLang::CurrencyFormat(doubleval($arResult["allSum"] - $allVATSum), $allCurrency, true);
     }
     $arResult['COUPON_LIST'] = array();
     $arResult['COUPON'] = '';
     if ($this->hideCoupon != "Y") {
         $arCoupons = DiscountCouponsManager::get(true, array(), true, true);
         if (!empty($arCoupons)) {
             foreach ($arCoupons as &$oneCoupon) {
                 if ($arResult['COUPON'] == '') {
                     $arResult['COUPON'] = $oneCoupon['COUPON'];
                 }
                 if ($oneCoupon['STATUS'] == DiscountCouponsManager::STATUS_NOT_FOUND || $oneCoupon['STATUS'] == DiscountCouponsManager::STATUS_FREEZE) {
                     $oneCoupon['JS_STATUS'] = 'BAD';
                 } elseif ($oneCoupon['STATUS'] == DiscountCouponsManager::STATUS_NOT_APPLYED || $oneCoupon['STATUS'] == DiscountCouponsManager::STATUS_ENTERED) {
                     $oneCoupon['JS_STATUS'] = 'ENTERED';
                 } else {
                     $oneCoupon['JS_STATUS'] = 'APPLYED';
                 }
                 $oneCoupon['JS_CHECK_CODE'] = '';
                 if (isset($oneCoupon['CHECK_CODE_TEXT'])) {
                     $oneCoupon['JS_CHECK_CODE'] = is_array($oneCoupon['CHECK_CODE_TEXT']) ? implode('<br>', $oneCoupon['CHECK_CODE_TEXT']) : $oneCoupon['CHECK_CODE_TEXT'];
                 }
                 $arResult['COUPON_LIST'][] = $oneCoupon;
             }
             unset($oneCoupon);
             $arResult['COUPON_LIST'] = array_values($arCoupons);
         }
         unset($arCoupons);
     }
     if (empty($arBasketItems)) {
         $arResult["ERROR_MESSAGE"] = Loc::getMessage("SALE_EMPTY_BASKET");
     }
     $arResult["DISCOUNT_PRICE_ALL"] = $DISCOUNT_PRICE_ALL;
     $arResult["DISCOUNT_PRICE_ALL_FORMATED"] = CCurrencyLang::CurrencyFormat($DISCOUNT_PRICE_ALL, $allCurrency, true);
     if ($this->usePrepayment == "Y") {
         if (doubleval($arResult["allSum"]) > 0) {
             $personType = array();
             $dbPersonType = CSalePersonType::GetList(array("SORT" => "ASC", "NAME" => "ASC"), array("LID" => SITE_ID, "ACTIVE" => "Y"));
             while ($arPersonType = $dbPersonType->Fetch()) {
                 $personType[] = $arPersonType["ID"];
             }
             if (!empty($personType)) {
                 $dbPaySysAction = CSalePaySystemAction::GetList(array(), array("PS_ACTIVE" => "Y", "HAVE_PREPAY" => "Y", "PERSON_TYPE_ID" => $personType), false, false, array("ID", "PAY_SYSTEM_ID", "PERSON_TYPE_ID", "NAME", "ACTION_FILE", "RESULT_FILE", "NEW_WINDOW", "PARAMS", "ENCODING", "LOGOTIP"));
                 if ($arPaySysAction = $dbPaySysAction->Fetch()) {
                     CSalePaySystemAction::InitParamarrays(false, false, $arPaySysAction["PARAMS"]);
                     $pathToAction = $_SERVER["DOCUMENT_ROOT"] . $arPaySysAction["ACTION_FILE"];
                     $pathToAction = str_replace("\\", "/", $pathToAction);
                     while (substr($pathToAction, strlen($pathToAction) - 1, 1) == "/") {
                         $pathToAction = substr($pathToAction, 0, strlen($pathToAction) - 1);
                     }
                     if (file_exists($pathToAction)) {
                         if (is_dir($pathToAction) && file_exists($pathToAction . "/pre_payment.php")) {
                             $pathToAction .= "/pre_payment.php";
                         }
                         try {
                             include_once $pathToAction;
                         } catch (\Bitrix\Main\SystemException $e) {
                             if ($e->getCode() == CSalePaySystemAction::GET_PARAM_VALUE) {
                                 $message = Loc::getMessage("SOA_TEMPL_ORDER_PS_ERROR");
                             } else {
                                 $message = $e->getMessage();
                             }
                             $arResult["ERROR_MESSAGE"] = $message;
                         }
                         $psPreAction = new CSalePaySystemPrePayment();
                         if ($psPreAction->init()) {
                             $orderData = array("PATH_TO_ORDER" => $this->pathToOrder, "AMOUNT" => $arResult["allSum"], "BASKET_ITEMS" => $arResult["ITEMS"]["AnDelCanBuy"]);
                             if (!$psPreAction->BasketButtonAction($orderData)) {
                                 if ($e = $APPLICATION->GetException()) {
                                     $arResult["WARNING_MESSAGE"][] = $e->GetString();
                                 }
                             }
                             $arResult["PREPAY_BUTTON"] = $psPreAction->BasketButtonShow();
                         }
                     }
                 }
             }
         }
     }
     return $arResult;
 }
Exemple #4
0
 /**
  * Function formats weight info in arResult
  * @return void
  */
 protected function formatResultWeight()
 {
     $arResult =& $this->arResult;
     $arResult["ORDER_WEIGHT_FORMATED"] = roundEx(doubleval($arResult["ORDER_WEIGHT"] / $arResult["WEIGHT_KOEF"]), SALE_WEIGHT_PRECISION) . " " . $arResult["WEIGHT_UNIT"];
 }
Exemple #5
0
	/**
	 * <p>Метод возвращает параметры наименьшей цены товара productID в количестве quantity для посетителя, входящего в группы пользователей arUserGroups.</p>
	 *
	 *
	 *
	 *
	 * @param int $productID  Код товара.
	 *
	 *
	 *
	 * @param  $int  Приобретаемое количество.
	 *
	 *
	 *
	 * @param quantit $y = 1[ массив групп, которым принадлежит пользователь. Для текущего
	 * пользователя он возвращается методом $USER-&gt;GetUserGroupArray() 
	 *
	 *
	 *
	 * @param array $arUserGroups = array()[ "Y", если вычисляется для продления товара (продажа контента), "N" в
	 * остальных случаях.
	 *
	 *
	 *
	 * @param string $renewal = "N"[ Массив цен. Если он установлен, то пересчет идет не по ценам из
	 * базы данных, а по ценам из этого массива. Представляет собой
	 * массив ассоциативных массивов с ключами: <ul> <li> <b>ID</b> - код цены;</li>
	 * <li> <b>PRICE</b> - цена;</li> <li> <b>CURRENCY</b> - валюта;</li> <li> <b>CATALOG_GROUP_ID</b> - код
	 * типа цен.</li> </ul>
	 *
	 *
	 *
	 * @param array $arPrices = array()[ Сайт, для которого производится вычисление. Если парамерт равен
	 * <i>false</i>, то берется текущий сайт.
	 *
	 *
	 *
	 * @param string $siteID = false]]]]] 
	 *
	 *
	 *
	 * @return array <p>Массив вида:</p><pre class="syntax">array( "PRICE" =&gt;
	 * массив_параметров_минимальной_цены, "DISCOUNT_PRICE" =&gt;
	 * минимальная_цена_в_базовой_валюте, "DISCOUNT" =&gt;
	 * массив_параметров_максимальной_доступной_скидки )</pre><p><b>Обратите
	 * внимание, что</b> <i>DISCOUNT_PRICE</i> это минимальная цена в <b>базовой
	 * валюте</b>. Чтобы перевести эту цену в валюту товара,
	 * необходимо:</p><pre class="syntax">array( $baseCurrency = CCurrency::GetBaseCurrency();
	 * $arPrice["DISCOUNT_PRICE"] = CCurrencyRates::ConvertCurrency($arPrice['DISCOUNT_PRICE'], $baseCurrency,
	 * $arPrice["PRICE"]["CURRENCY"]); )</pre><a name="examples"></a>
	 *
	 *
	 * <h4>Example</h4> 
	 * <pre>
	 * &lt;?
	 * $arPrice = CCatalogProduct::GetOptimalPrice($productID, $quantity, $USER-&gt;GetUserGroupArray(), $renewal);
	 * if (!$arPrice || count($arPrice) &lt;= 0)
	 * {
	 *     if ($nearestQuantity = CCatalogProduct::GetNearestQuantityPrice($productID, $quantity, $USER-&gt;GetUserGroupArray()))
	 *     {
	 *         $quantity = $nearestQuantity;
	 *         $arPrice = CCatalogProduct::GetOptimalPrice($productID, $quantity, $USER-&gt;GetUserGroupArray(), $renewal);
	 *     }
	 * }
	 * echo "&lt;pre&gt;";
	 * print_r($arPrice);
	 * echo "&lt;/pre&gt;";
	 * ?&gt;
	 * </pre>
	 *
	 *
	 * @static
	 * @link http://dev.1c-bitrix.ru/api_help/catalog/classes/ccatalogproduct/ccatalogproduct__getoptimalprice.7c16046d.php
	 * @author Bitrix
	 */
	public static function GetOptimalPrice($intProductID, $quantity = 1, $arUserGroups = array(), $renewal = "N", $arPrices = array(), $siteID = false, $arDiscountCoupons = false)
	{
		global $APPLICATION;

		$mxResult = true;
		foreach (GetModuleEvents("catalog", "OnGetOptimalPrice", true) as $arEvent)
		{
			$mxResult = ExecuteModuleEventEx($arEvent, array($intProductID, $quantity, $arUserGroups, $renewal, $arPrices, $siteID, $arDiscountCoupons));
			if (true !== $mxResult)
				return $mxResult;
		}

		$intProductID = intval($intProductID);
		if (0 >= $intProductID)
		{
			$APPLICATION->ThrowException(GetMessage("BT_MOD_CATALOG_PROD_ERR_PRODUCT_ID_ABSENT"), "NO_PRODUCT_ID");
			return false;
		}

		$quantity = doubleval($quantity);
		if (0 >= $quantity)
		{
			$APPLICATION->ThrowException(GetMessage("BT_MOD_CATALOG_PROD_ERR_QUANTITY_ABSENT"), "NO_QUANTITY");
			return false;
		}

		if (!is_array($arUserGroups) && intval($arUserGroups)."|" == $arUserGroups."|")
			$arUserGroups = array(intval($arUserGroups));

		if (!is_array($arUserGroups))
			$arUserGroups = array();

		if (!in_array(2, $arUserGroups))
			$arUserGroups[] = 2;

		$rsVAT = CCatalogProduct::GetVATInfo($intProductID);
		if ($arVAT = $rsVAT->Fetch())
		{
			$arVAT['RATE'] = doubleval($arVAT['RATE'] * 0.01);
		}
		else
		{
			$arVAT = array('RATE' => 0.0, 'VAT_INCLUDED' => 'N');
		}

		$renewal = (($renewal == "N") ? "N" : "Y");

		if (false === $siteID)
			$siteID = SITE_ID;

		if (false === $arDiscountCoupons)
			$arDiscountCoupons = CCatalogDiscountCoupon::GetCoupons();

		$strBaseCurrency = CCurrency::GetBaseCurrency();
		if (empty($strBaseCurrency))
		{
			$APPLICATION->ThrowException(GetMessage("BT_MOD_CATALOG_PROD_ERR_NO_BASE_CURRENCY"), "NO_BASE_CURRENCY");
			return false;
		}

		$intIBlockID = intval(CIBlockElement::GetIBlockByID($intProductID));
		if (0 >= $intIBlockID)
		{
			$APPLICATION->ThrowException(str_replace("#ID#", $intProductID, GetMessage('BT_MOD_CATALOG_PROD_ERR_ELEMENT_ID_NOT_FOUND')), "NO_ELEMENT");
			return false;
		}

		if (!isset($arPrices) || !is_array($arPrices))
			$arPrices = array();

		if (empty($arPrices))
		{
			$arPrices = array();
			$dbPriceList = CPrice::GetListEx(
				array(),
				array(
						"PRODUCT_ID" => $intProductID,
						"GROUP_GROUP_ID" => $arUserGroups,
						"GROUP_BUY" => "Y",
						"+<=QUANTITY_FROM" => $quantity,
						"+>=QUANTITY_TO" => $quantity
					),
				false,
				false,
				array("ID", "CATALOG_GROUP_ID", "PRICE", "CURRENCY")
			);
			while ($arPriceList = $dbPriceList->Fetch())
			{
				$arPriceList['ELEMENT_IBLOCK_ID'] = $intIBlockID;
				$arPrices[] = $arPriceList;
			}
		}
		else
		{
			foreach ($arPrices as &$arOnePrice)
			{
				$arOnePrice['ELEMENT_IBLOCK_ID'] = $intIBlockID;
			}
			if (isset($arOnePrice))
				unset($arOnePrice);
		}

		if (empty($arPrices))
			return false;

//		$boolDiscountVat = ('N' != COption::GetOptionString('catalog', 'discount_vat', 'Y'));
		$boolDiscountVat = true;
		$strDiscSaveApply = COption::GetOptionString('catalog', 'discsave_apply', 'R');

		$dblMinPrice = -1;
		$arMinPrice = array();
		$arMinDiscounts = array();

		foreach ($arPrices as &$arPriceList)
		{
			$arPriceList['VAT_RATE'] = $arVAT['RATE'];
			$arPriceList['VAT_INCLUDED'] = $arVAT['VAT_INCLUDED'];
			$arPriceList['ORIG_VAT_INCLUDED'] = $arPriceList['VAT_INCLUDED'];

			if ($boolDiscountVat)
			{
				if ('N' == $arPriceList['VAT_INCLUDED'])
				{
					$arPriceList['PRICE'] *= (1 + $arPriceList['VAT_RATE']);
					$arPriceList['VAT_INCLUDED'] = 'Y';
				}
			}
			else
			{
				if ('Y' == $arPriceList['VAT_INCLUDED'])
				{
					$arPriceList['PRICE'] /= (1 + $arPriceList['VAT_RATE']);
					$arPriceList['VAT_INCLUDED'] = 'N';
				}
			}

			if ($arPriceList["CURRENCY"] == $strBaseCurrency)
				$dblCurrentPrice = $arPriceList["PRICE"];
			else
				$dblCurrentPrice = CCurrencyRates::ConvertCurrency($arPriceList["PRICE"], $arPriceList["CURRENCY"], $strBaseCurrency);

			$arDiscounts = CCatalogDiscount::GetDiscount($intProductID, $intIBlockID, $arPriceList["CATALOG_GROUP_ID"], $arUserGroups, $renewal, $siteID, $arDiscountCoupons);

			$arDiscSave = array();
			$arPriceDiscount = array();

			$arResultPrice = array(
				'PRICE' => $dblCurrentPrice,
				'CURRENCY' => $strBaseCurrency,
			);
			$arDiscountApply = array();

			if (!empty($arDiscounts))
			{
				CCatalogProduct::__PrimaryDiscountFilter($arDiscounts, $arPriceDiscount, $arDiscSave, $arResultPrice);

				if (!empty($arPriceDiscount))
				{
					foreach ($arPriceDiscount as &$arOnePriority)
					{
						$boolResultPriority = CCatalogProduct::__CalcOnePriority($arOnePriority, $arDiscountApply, $arResultPrice);
						if (!$boolResultPriority)
						{
							return false;
						}
						else
						{
							if (isset($arResultPrice['LAST_DISCOUNT']) && 'Y' == $arResultPrice['LAST_DISCOUNT'])
								break;
						}
					}
					if (isset($arOnePriority))
						unset($arOnePriority);
				}

				if (!empty($arDiscSave))
				{
					switch($strDiscSaveApply)
					{
					case 'R':
						$arDiscSaveResult = array(
							'PRICE' => $dblCurrentPrice,
							'CURRENCY' => $strBaseCurrency,
						);
						$arDiscSaveApply = array();
						$boolResultDiscSave = CCatalogProduct::__CalcDiscSave($arDiscSave, $arDiscSaveApply, $arDiscSaveResult);
						if (!$boolResultDiscSave)
						{
							return false;
						}
						else
						{
							if ($arDiscSaveResult['PRICE'] < $arResultPrice['PRICE'])
							{
								$arResultPrice = $arDiscSaveResult;
								$arDiscountApply = $arDiscSaveApply;
							}
						}
						break;
					case 'A':
						$boolResultDiscSave = CCatalogProduct::__CalcDiscSave($arDiscSave, $arDiscountApply, $arResultPrice);
						if (!$boolResultDiscSave)
						{
							return false;
						}
						break;
					case 'D':
						if (empty($arDiscountApply))
						{
							$boolResultDiscSave = CCatalogProduct::__CalcDiscSave($arDiscSave, $arDiscountApply, $arResultPrice);
							if (!$boolResultDiscSave)
							{
								return false;
							}
						}
						break;
					}
				}
			}

			if (-1 == $dblMinPrice || $dblMinPrice > $arResultPrice['PRICE'])
			{
				$dblMinPrice = $arResultPrice['PRICE'];
				$arMinPrice = $arPriceList;
				$arMinDiscounts = $arDiscountApply;
			}
		}
		if (isset($arPriceList))
			unset($arPriceList);

		if ($boolDiscountVat)
		{
			if ('N' == $arMinPrice['ORIG_VAT_INCLUDED'])
			{
				$arMinPrice['PRICE'] /= (1 + $arMinPrice['VAT_RATE']);
				$arMinPrice['VAT_INCLUDED'] = $arMinPrice['ORIG_VAT_INCLUDED'];
			}
		}
		else
		{
			if ('Y' == $arMinPrice['ORIG_VAT_INCLUDED'])
			{
				$arMinPrice['PRICE'] *= (1 + $arMinPrice['VAT_RATE']);
				$arMinPrice['VAT_INCLUDED'] = $arMinPrice['ORIG_VAT_INCLUDED'];
			}
		}
		unset($arMinPrice['ORIG_VAT_INCLUDED']);

		$dblMinPrice = roundEx($dblMinPrice, CATALOG_VALUE_PRECISION);

		$arResult = array(
			'PRICE' => $arMinPrice,
			'DISCOUNT_PRICE' => $dblMinPrice,
			'DISCOUNT' => array(),
			'DISCOUNT_LIST' => array(),
		);
		if (!empty($arMinDiscounts))
		{
			reset($arMinDiscounts);
			$arResult['DISCOUNT'] = current($arMinDiscounts);
			$arResult['DISCOUNT_LIST'] = $arMinDiscounts;
		}

		foreach (GetModuleEvents("catalog", "OnGetOptimalPriceResult", true) as $arEvent)
		{
			if (ExecuteModuleEventEx($arEvent, array(&$arResult))===false)
				return false;
		}

		return $arResult;
	}
Exemple #6
0
										<?php 
echo SaleFormatCurrency($str_TAX_VALUE, $str_CURRENCY);
?>
									</div>
								</td>
							</tr>
							<tr>
								<td class="title">
									<?php 
echo GetMessage("NEWO_TOTAL_WEIGHT");
?>
								</td>
								<td nowrap>
									<div id="ORDER_WAIGHT" style="white-space:nowrap;">
										<?php 
echo roundEx(floatval($productWeight / $WEIGHT_KOEF), SALE_WEIGHT_PRECISION) . " " . $WEIGHT_UNIT;
?>
									</div>
								</td>
							</tr>
						<tr>
						<td class="title">
							<?php 
echo GetMessage("NEWO_TOTAL_PAY_ACCOUNT2");
?>
						</td>
						<td nowrap class="sum_paid" onclick="fEditSumPaid(true);">
							<span id="ORDER_PAY_FROM_ACCOUNT" style="white-space:nowrap;" onclick="fEditSumPaid(true);">
								<?
								$str_SUM_PAID = floatval($str_SUM_PAID);
								?>
Exemple #7
0
     $allSum = 0;
     $allVatSumm = 0;
     $allVatRate = 0;
     foreach ($arOrderForDiscount['BASKET_ITEMS'] as &$arOneItem) {
         $arOneItem["PRICE_FORMATED"] = SaleFormatCurrency($arOneItem["PRICE"], $arOneItem["CURRENCY"]);
         $arOneItem["DISCOUNT_PRICE_PERCENT"] = $arOneItem["DISCOUNT_PRICE"] * 100 / ($arOneItem["DISCOUNT_PRICE"] + $arOneItem["PRICE"]);
         $arOneItem["DISCOUNT_PRICE_PERCENT_FORMATED"] = roundEx($arOneItem["DISCOUNT_PRICE_PERCENT"], SALE_VALUE_PRECISION) . "%";
         $allSum += $arOneItem["PRICE"] * $arOneItem["QUANTITY"];
         $allVatSumm += 0;
         if (0 < $arOneItem["VAT_RATE"]) {
             $arResult["bUsingVat"] = "Y";
             if ($arOneItem["VAT_RATE"] > $allVatRate) {
                 $allVatRate = $arOneItem["VAT_RATE"];
             }
             $arOneItem["VAT_VALUE"] = $arOneItem["PRICE"] / ($arOneItem["VAT_RATE"] + 1) * $arOneItem["VAT_RATE"];
             $allVatSumm += roundEx($arOneItem["VAT_VALUE"] * $arOneItem["QUANTITY"], SALE_VALUE_PRECISION);
         }
     }
     if (isset($arOneItem)) {
         unset($arOneItem);
     }
     $arResult["ORDER_PRICE"] = $allSum;
     $arResult["ORDER_PRICE_FORMATED"] = SaleFormatCurrency($arResult["ORDER_PRICE"], $arResult["BASE_LANG_CURRENCY"]);
     $arResult["VAT_RATE"] = $allVatRate;
     $arResult["VAT_SUM"] = $allVatSumm;
     $arResult["VAT_SUM_FORMATED"] = SaleFormatCurrency($arResult["VAT_SUM"], $arResult["BASE_LANG_CURRENCY"]);
     $arResult['DELIVERY_PRICE'] = $arOrderForDiscount['PRICE_DELIVERY'];
     $arResult['DELIVERY_PRICE_FORMATED'] = SaleFormatCurrency($arResult["DELIVERY_PRICE"], $arResult["BASE_LANG_CURRENCY"]);
     $arResult["ITEMS"]["AnDelCanBuy"] = $arOrderForDiscount['BASKET_ITEMS'];
 }
 //end if array basket
Exemple #8
0
 function Show2Images($strImage1, $strImage2, $iMaxW = 0, $iMaxH = 0, $sParams = false, $sPopupTitle = false, $iSizeWHTTP = 0, $iSizeHHTTP = 0)
 {
     if (!($arImgParams = CFile::_GetImgParams($strImage1, $iSizeWHTTP, $iSizeHHTTP))) {
         return "";
     }
     $strImage1 = htmlspecialcharsbx($arImgParams["SRC"]);
     $intWidth = $arImgParams["WIDTH"];
     $intHeight = $arImgParams["HEIGHT"];
     $strAlt = $arImgParams["ALT"];
     if ($sParams == false) {
         $sParams = 'border="0" alt="' . htmlspecialcharsEx($strAlt) . '"';
     } elseif (!preg_match("/(^|\\s)alt\\s*=\\s*([\"']?)(.*?)(\\2)/is", $sParams)) {
         $sParams .= ' alt="' . htmlspecialcharsEx($strAlt) . '"';
     }
     if ($iMaxW > 0 && $iMaxH > 0 && ($intWidth > $iMaxW || $intHeight > $iMaxH)) {
         $coeff = $intWidth / $iMaxW > $intHeight / $iMaxH ? $intWidth / $iMaxW : $intHeight / $iMaxH;
         $iHeight = intval(roundEx($intHeight / $coeff));
         $iWidth = intval(roundEx($intWidth / $coeff));
     } else {
         $iHeight = $intHeight;
         $iWidth = $intWidth;
     }
     if ($arImgParams = CFile::_GetImgParams($strImage2, $iSizeWHTTP, $iSizeHHTTP)) {
         if ($sPopupTitle === false) {
             $sPopupTitle = GetMessage("FILE_ENLARGE");
         }
         $strImage2 = htmlspecialcharsbx($arImgParams["SRC"]);
         $intWidth2 = $arImgParams["WIDTH"];
         $intHeight2 = $arImgParams["HEIGHT"];
         $strAlt2 = $arImgParams["ALT"];
         CFile::OutputJSImgShw();
         $strReturn = "<a title=\"" . $sPopupTitle . "\" onclick=\"ImgShw('" . CUtil::addslashes($strImage2) . "','" . $intWidth2 . "','" . $intHeight2 . "', '" . CUtil::addslashes(htmlspecialcharsEx(htmlspecialcharsEx($strAlt2))) . "'); return false;\" href=\"" . $strImage2 . "\" target=_blank>" . "<img src=\"" . $strImage1 . "\" " . $sParams . " width=" . $iWidth . " height=" . $iHeight . " /></a>";
     } else {
         $strReturn = "<img src=\"" . $strImage1 . "\" " . $sParams . " width=" . $iWidth . " height=" . $iHeight . " />";
     }
     return $strReturn;
 }
Exemple #9
0
</td>
		<td width="50%">
			<input type="text" name="SUM_MIN" size="10" maxlength="10" value="<?php 
echo DoubleVal($arResult["SUM_MIN"]) > 0 ? roundEx($arResult["SUM_MIN"], SALE_VALUE_PRECISION) : "";
?>
">
		</td>
	</tr>
	<tr>
		<td width="50%" align="right"><?php 
echo GetMessage("STPC_MAX_SUM");
?>
</td>
		<td width="50%">
			<input type="text" name="SUM_MAX" size="10" maxlength="10" value="<?php 
echo DoubleVal($arResult["SUM_MAX"]) > 0 ? roundEx($arResult["SUM_MAX"], SALE_VALUE_PRECISION) : "";
?>
">
		</td>
	</tr>
	<tr>
		<td align="right"><?php 
echo GetMessage("STPC_SUM_CURR");
?>
</td>
		<td>
			<select name="SUM_CURRENCY">
				<?php 
foreach ($arResult["CURRENCY_INFO"] as $val) {
    ?>
<option value="<?php 
Exemple #10
0
 /**
  * calculate the cost according to the order basket
  * @param array $arBasketItems
  * @return array|bool
  */
 public static function CalculateOrderPrices($arBasketItems)
 {
     if (!isset($arBasketItems) || isset($arBasketItems) && sizeof($arBasketItems) <= 0) {
         return false;
     }
     $arResult = array("ORDER_PRICE" => 0, "ORDER_WEIGHT" => 0, "VAT_RATE" => 0, "VAT_SUM" => 0, "USE_VAT" => 'N', "BASKET_ITEMS" => $arBasketItems);
     foreach ($arResult['BASKET_ITEMS'] as &$arItem) {
         if (!CSaleBasketHelper::isSetItem($arItem)) {
             if (array_key_exists('CUSTOM_PRICE', $arItem) && $arItem['CUSTOM_PRICE'] == 'Y') {
                 $arItem['DISCOUNT_PRICE'] = $arItem['DEFAULT_PRICE'] - $arItem['PRICE'];
                 if ($arItem['DISCOUNT_PRICE'] < 0) {
                     $arItem['DISCOUNT_PRICE'] = 0;
                 }
                 if (doubleval($arItem['DEFAULT_PRICE']) > 0) {
                     $arItem['DISCOUNT_PRICE_PERCENT'] = $arItem['DISCOUNT_PRICE'] * 100 / $arItem['DEFAULT_PRICE'];
                 } else {
                     $arItem['DISCOUNT_PRICE_PERCENT'] = 0;
                 }
                 $arItem["DISCOUNT_PRICE_PERCENT_FORMATED"] = roundEx($arItem["DISCOUNT_PRICE_PERCENT"], SALE_VALUE_PRECISION) . "%";
             }
             if (isset($arItem['CURRENCY']) && strlen($arItem['CURRENCY']) > 0) {
                 $arItem["PRICE_FORMATED"] = SaleFormatCurrency($arItem["PRICE"], $arItem["CURRENCY"]);
             }
             $arResult['ORDER_PRICE'] += CSaleBasketHelper::getFinalPrice($arItem);
             $arResult['ORDER_WEIGHT'] += $arItem["WEIGHT"] * $arItem["QUANTITY"];
             if ($arItem["VAT_RATE"] > 0) {
                 $arResult['USE_VAT'] = 'Y';
                 if ($arItem["VAT_RATE"] > $arResult['VAT_RATE']) {
                     $arResult['VAT_RATE'] = $arItem["VAT_RATE"];
                 }
                 $v = CSaleBasketHelper::getVat($arItem);
                 $arItem["VAT_VALUE"] = \Bitrix\Sale\PriceMaths::roundPrecision($v / $arItem["QUANTITY"]);
                 $arResult["VAT_SUM"] += $v;
             }
         }
     }
     $arResult['ORDER_PRICE'] = \Bitrix\Sale\PriceMaths::roundPrecision($arResult['ORDER_PRICE']);
     $arResult['VAT_SUM'] = \Bitrix\Sale\PriceMaths::roundPrecision($arResult['VAT_SUM']);
     unset($arItem);
     return $arResult;
 }
Exemple #11
0
                 $vats[$vatRate] += abs($delta) / $delta / pow(10, SALE_VALUE_PRECISION);
                 $delta -= abs($delta) / $delta;
                 if ($delta == 0) {
                     break 2;
                 }
             }
         }
     }
     foreach ($vats as $vatRate => $vatSum) {
         $arCells[++$n] = array(1 => null, null, null, null, null, CSalePdf::prepareToPdf(sprintf("zzgl. %s%% MwSt:", roundEx($vatRate * 100, SALE_VALUE_PRECISION))), CSalePdf::prepareToPdf(SaleFormatCurrency($vatSum, $GLOBALS["SALE_INPUT_PARAMS"]["ORDER"]["CURRENCY"], false)));
         $arRowsWidth[7] = max($arRowsWidth[7], $pdf->GetStringWidth($arCells[$n][7]));
     }
 } else {
     $dbTaxList = CSaleOrderTax::GetList(array("APPLY_ORDER" => "ASC"), array("ORDER_ID" => $ORDER_ID));
     while ($arTaxList = $dbTaxList->Fetch()) {
         $arCells[++$n] = array(1 => null, null, null, null, null, CSalePdf::prepareToPdf(sprintf("%s%s%s:", $arTaxList["IS_IN_PRICE"] == "Y" ? "inkl." : "zzgl.", sprintf(' %s%% ', roundEx($arTaxList["VALUE"], SALE_VALUE_PRECISION)), $arTaxList["TAX_NAME"])), CSalePdf::prepareToPdf(SaleFormatCurrency($arTaxList["VALUE_MONEY"], $GLOBALS["SALE_INPUT_PARAMS"]["ORDER"]["CURRENCY"], false)));
         $arRowsWidth[7] = max($arRowsWidth[7], $pdf->GetStringWidth($arCells[$n][7]));
     }
 }
 if (DoubleVal($GLOBALS["SALE_INPUT_PARAMS"]["ORDER"]["SUM_PAID"]) > 0) {
     $arCells[++$n] = array(1 => null, null, null, null, null, CSalePdf::prepareToPdf("Payment made:"), CSalePdf::prepareToPdf(SaleFormatCurrency($GLOBALS["SALE_INPUT_PARAMS"]["ORDER"]["SUM_PAID"], $GLOBALS["SALE_INPUT_PARAMS"]["ORDER"]["CURRENCY"], false)));
     $arRowsWidth[7] = max($arRowsWidth[7], $pdf->GetStringWidth($arCells[$n][7]));
 }
 if (DoubleVal($GLOBALS["SALE_INPUT_PARAMS"]["ORDER"]["DISCOUNT_VALUE"]) > 0) {
     $arCells[++$n] = array(1 => null, null, null, null, null, CSalePdf::prepareToPdf("Rabatt:"), CSalePdf::prepareToPdf(SaleFormatCurrency($GLOBALS["SALE_INPUT_PARAMS"]["ORDER"]["DISCOUNT_VALUE"], $GLOBALS["SALE_INPUT_PARAMS"]["ORDER"]["CURRENCY"], false)));
     $arRowsWidth[7] = max($arRowsWidth[7], $pdf->GetStringWidth($arCells[$n][7]));
 }
 $arCells[++$n] = array(1 => null, null, null, null, null, CSalePdf::prepareToPdf("Gesamtbetrag:"), CSalePdf::prepareToPdf(SaleFormatCurrency($GLOBALS["SALE_INPUT_PARAMS"]["ORDER"]["SHOULD_PAY"], $GLOBALS["SALE_INPUT_PARAMS"]["ORDER"]["CURRENCY"], false)));
 $arRowsWidth[7] = max($arRowsWidth[7], $pdf->GetStringWidth($arCells[$n][7]));
 for ($i = 1; $i <= 7; $i++) {
     $arRowsWidth[$i] += 10;
Exemple #12
0
            ?>
															onclick="submitForm();" />


										<?php 
            if ($arParams["SHOW_PAYMENT_SERVICES_NAMES"] != "N") {
                ?>
                                
										<div class="selection_unit-title"><?php 
                echo $arPaySystem["PSA_NAME"];
                ?>
</div>
										<div class="selection_unit-text">
										<?php 
                if (intval($arPaySystem["PRICE"]) > 0) {
                    echo str_replace("#PAYSYSTEM_PRICE#", SaleFormatCurrency(roundEx($arPaySystem["PRICE"], SALE_VALUE_PRECISION), $arResult["BASE_LANG_CURRENCY"]), GetMessage("SOA_TEMPL_PAYSYSTEM_PRICE"));
                } else {
                    echo $arPaySystem["DESCRIPTION"];
                }
                ?>
										</div>
										<?php 
            }
            ?>
    <?php 
            if (count($arPaySystem["PSA_LOGOTIP"]) > 0) {
                print '<div class="selection_unit-img"><img src="' . $arPaySystem["PSA_LOGOTIP"]["SRC"] . '" /></div>';
            }
            ?>
										                        
						</a>
Exemple #13
0
		function __MakeOrder($prdCnt=1, $arData = Array())
		{
			global $APPLICATION, $USER, $DB;
			CModule::IncludeModule("iblock");
			CModule::IncludeModule("sale");
			CModule::IncludeModule("catalog");
			$arPrd = Array();
			$dbItem = CIBlockElement::GetList(Array("PROPERTY_MORE_PHOTO" => "DESC", "ID" => "ASC"), Array("IBLOCK_TYPE" => "offers", "IBLOCK_SITE_ID" => WIZARD_SITE_ID, "PROPERTY_NEWPRODUCT" => false), false, Array("nTopCount" => 10), Array("ID", "IBLOCK_ID", "XML_ID", "NAME", "DETAIL_PAGE_URL", "IBLOCK_XML_ID"));
			while($arItem = $dbItem->GetNext())
				$arPrd[] = $arItem;

			if(!empty($arPrd))
			{
				for($i=0; $i<$prdCnt;$i++)
				{
					$prdID = $arPrd[mt_rand(0, 9)];
					$arProduct = CCatalogProduct::GetByID($prdID["ID"]);
					$CALLBACK_FUNC = "";
					$arCallbackPrice = CSaleBasket::ReReadPrice($CALLBACK_FUNC, "catalog", $prdID["ID"], 1);

					$arFields = array(
							"PRODUCT_ID" => $prdID["ID"],
							"PRODUCT_PRICE_ID" => $arCallbackPrice["PRODUCT_PRICE_ID"],
							"PRICE" => $arCallbackPrice["PRICE"],
							"CURRENCY" => $arCallbackPrice["CURRENCY"],
							"WEIGHT" => $arProduct["WEIGHT"],
							"QUANTITY" => 1,
							"LID" => WIZARD_SITE_ID,
							"DELAY" => "N",
							"CAN_BUY" => "Y",
							"NAME" => $prdID["NAME"],
							"CALLBACK_FUNC" => $CALLBACK_FUNC,
							"MODULE" => "catalog",
							"PRODUCT_PROVIDER_CLASS" => "CCatalogProductProvider",
							"ORDER_CALLBACK_FUNC" => "",
							"CANCEL_CALLBACK_FUNC" => "",
							"PAY_CALLBACK_FUNC" => "",
							"DETAIL_PAGE_URL" => $prdID["DETAIL_PAGE_URL"],
							"CATALOG_XML_ID" => $prdID["IBLOCK_XML_ID"],
							"PRODUCT_XML_ID" => $prdID["XML_ID"],
							"VAT_RATE" => $arCallbackPrice['VAT_RATE'],
						);
					$addres = CSaleBasket::Add($arFields);
				}

				$arOrder = Array(
						"LID" => $arData["SITE_ID"],
						"PERSON_TYPE_ID" => $arData["PERSON_TYPE_ID"],
						"PAYED" => "N",
						"CANCELED" => "N",
						"STATUS_ID" => "N",
						"PRICE" => 1,
						"CURRENCY" => $arData["CURRENCY"],
						"USER_ID" => $arData["USER_ID"],
						"PAY_SYSTEM_ID" => $arData["PAY_SYSTEM_ID"],
						//"PRICE_DELIVERY" => $arData["PRICE_DELIVERY"],
						//"DELIVERY_ID" => $arData["DELIVERY_ID"],
					);

				$dbFUserListTmp = CSaleUser::GetList(array("USER_ID" => $arData["USER_ID"]));
				if(empty($dbFUserListTmp))
				{
					$arFields = array(
							"=DATE_INSERT" => $DB->GetNowFunction(),
							"=DATE_UPDATE" => $DB->GetNowFunction(),
							"USER_ID" => $arData["USER_ID"]
						);

					$ID = CSaleUser::_Add($arFields);
				}

				$orderID = CSaleOrder::Add($arOrder);
				CSaleBasket::OrderBasket($orderID, CSaleBasket::GetBasketUserID(), WIZARD_SITE_ID);
				$dbBasketItems = CSaleBasket::GetList(
						array("NAME" => "ASC"),
						array(
								"FUSER_ID" => CSaleBasket::GetBasketUserID(),
								"LID" => WIZARD_SITE_ID,
								"ORDER_ID" => $orderID
							),
						false,
						false,
						array("ID", "CALLBACK_FUNC", "MODULE", "PRODUCT_ID", "QUANTITY", "DELAY", "CAN_BUY", "PRICE", "WEIGHT", "NAME")
					);
				$ORDER_PRICE = 0;
				while ($arBasketItems = $dbBasketItems->GetNext())
				{
					$ORDER_PRICE += roundEx($arBasketItems["PRICE"], SALE_VALUE_PRECISION) * DoubleVal($arBasketItems["QUANTITY"]);
				}

				$totalOrderPrice = $ORDER_PRICE + $arData["PRICE_DELIVERY"];
				CSaleOrder::Update($orderID, Array("PRICE" => $totalOrderPrice));
				foreach($arData["PROPS"] as $val)
				{
					$arFields = Array(
							"ORDER_ID" => $orderID,
							"ORDER_PROPS_ID" => $val["ID"],
							"NAME" => $val["NAME"],
							"CODE" => $val["CODE"],
							"VALUE" => $val["VALUE"],
						);
					CSaleOrderPropsValue::Add($arFields);
				}
				return $orderID;
			}
		}
Exemple #14
0
    'USER_NAME'     => $USER_NAME,
    'USER_PASSWORD' => $USER_PASSWORD,
    'REST_ID'       => $REST_ID
);

$startImportExecTime = getmicrotime();

// получаем номенклатуру из облака
$iikoCloud = \Iiko\Connect::getInstance($params);
$arNomenclature = $iikoCloud->getNomenclature();

// импортируем номенклатуру в наш каталог
try
{
    $strImportOKMessage .= \Iiko\Import::getInstance($CATALOG_ID, $arNomenclature)->catalog()->report();
    $strImportOKMessage .= str_replace("#TIME#", roundEx(getmicrotime() - $startImportExecTime, 2), "<br />Загрузка заняла <b>#TIME#</b> сек<br />");
}
catch (Exception $e)
{
    $strImportErrorMessage .= $e->getMessage()."\n";
}

// делаем экспорт в айку
try
{
    /** @var $provider \Iiko\IExportOrder */
    $provider = \Iiko\Config\Option::getProvider();
    if (!\Iiko\Export::getOrderProvider($provider))
    {
        $provider = '\Iiko\OrderProvider';
    }
Exemple #15
0
										"LOCATION_FROM" => COption::GetOptionInt('sale', 'location'),
										"LOCATION_TO" => $arUserResult["DELIVERY_LOCATION"],
										"LOCATION_ZIP" => $arUserResult["DELIVERY_LOCATION_ZIP"],
										"ITEMS" => $arResult["BASKET_ITEMS"],
										"EXTRA_PARAMS" => $arResult["DELIVERY_EXTRA"]
									);

									$arDeliveryPrice = CSaleDeliveryHandler::CalculateFull($k, $kk, $arOrderTmpDel, $arResult["BASE_LANG_CURRENCY"]);

									if ($arDeliveryPrice["RESULT"] == "ERROR")
									{
										$arResult["ERROR"][] = $arDeliveryPrice["TEXT"];
									}
									else
									{
										$arResult["DELIVERY_PRICE"] = roundEx($arDeliveryPrice["VALUE"], SALE_VALUE_PRECISION);
										$arResult["PACKS_COUNT"] = $arDeliveryPrice["PACKS_COUNT"];
									}
									break;
								}
							}
						}
					}
				}
			}

			if ($arUserResult["PAY_SYSTEM_ID"] > 0 || strlen($arUserResult["DELIVERY_ID"]) > 0)
			{
				if (strlen($arUserResult["DELIVERY_ID"]) > 0 && $arParams["DELIVERY_TO_PAYSYSTEM"] == "d2p")
				{
					if (strpos($arUserResult["DELIVERY_ID"], ":"))
:</td>
		<td width="60%">
			<input type="text" name="NAME" size="50" value="<?php 
echo htmlspecialcharsbx($str_NAME);
?>
">
		</td>
	</tr>
	<tr>
		<td><?php 
echo GetMessage("CEEN_PERCENTAGE");
?>
:</td>
		<td>
			<input type="text" name="PERCENTAGE" size="10" maxlength="20" value="<?php 
echo roundEx($str_PERCENTAGE, CATALOG_VALUE_PRECISION);
?>
" />%
		</td>
	</tr>
	<?php 
if ($ID > 0) {
    ?>
		<tr>
			<td><?php 
    echo GetMessage("CEEN_RECALC");
    ?>
:</td>
			<td>
				<input type="checkbox" name="RECALCULATE" value="Y"<?php 
    if ($str_RECALCULATE == "Y") {
Exemple #17
0
											</td>
											<td nowrap style="white-space:nowrap;">
													<div><?php 
echo SaleFormatCurrency($arOrder["DISCOUNT_VALUE"], $arOrder["CURRENCY"]);
?>
</div>
											</td>
										</tr>
										<?endif;?>

										<?if ($ORDER_TOTAL_WEIGHT > 0):?>
										<tr>
											<td class="title"><?echo GetMessage("NEWO_TOTAL_WEIGHT")?></td>
											<td nowrap style="white-space:nowrap;">
												<?php 
echo roundEx(DoubleVal($ORDER_TOTAL_WEIGHT / $WEIGHT_KOEF), SALE_WEIGHT_PRECISION) . " " . $WEIGHT_UNIT;
?>
											</td>
										</tr>
										<?endif;?>

										<tr class="itog">
											<td class="ileft"><div style="white-space:nowrap;"><?echo GetMessage("SOD_TOTAL_PRICE_TOTAL")?></div></td>
											<td class="iright" nowrap><div style="white-space:nowrap;"><?php 
echo SaleFormatCurrency($arOrder["PRICE"], $arOrder["CURRENCY"]);
?>
</div></td>
										</tr>
										<?if (floatval($arOrder["SUM_PAID"]) > 0):?>
											<tr class="price">
												<td class="title"><?echo GetMessage("SOD_TOTAL_PRICE_PAYED")?></td>
     if ($arStoreTmp["IMAGE_ID"] > 0) {
         $arStoreTmp["IMAGE_ID"] = CFile::GetFileArray($arStoreTmp["IMAGE_ID"]);
     }
     $arStore[$arStoreTmp["ID"]] = $arStoreTmp;
 }
 $arResult["STORE_LIST"] = $arStore;
 if (!$bFound && !empty($arUserResult["DELIVERY_ID"]) && strpos($arUserResult["DELIVERY_ID"], ":") === false) {
     $arUserResult["DELIVERY_ID"] = "";
 }
 foreach ($arDeliveryAll as $arDelivery) {
     if (count($arP2D[$arUserResult["PAY_SYSTEM_ID"]]) <= 0 || in_array($arDelivery["ID"], $arP2D[$arUserResult["PAY_SYSTEM_ID"]])) {
         $arDelivery["FIELD_NAME"] = "DELIVERY_ID";
         if (IntVal($arUserResult["DELIVERY_ID"]) == IntVal($arDelivery["ID"])) {
             $arDelivery["CHECKED"] = "Y";
             $arUserResult["DELIVERY_ID"] = $arDelivery["ID"];
             $arResult["DELIVERY_PRICE"] = roundEx(CCurrencyRates::ConvertCurrency($arDelivery["PRICE"], $arDelivery["CURRENCY"], $arResult["BASE_LANG_CURRENCY"]), SALE_VALUE_PRECISION);
             $bSelected = true;
         }
         if (IntVal($arDelivery["PERIOD_FROM"]) > 0 || IntVal($arDelivery["PERIOD_TO"]) > 0) {
             $arDelivery["PERIOD_TEXT"] = GetMessage("SALE_DELIV_PERIOD");
             if (IntVal($arDelivery["PERIOD_FROM"]) > 0) {
                 $arDelivery["PERIOD_TEXT"] .= " " . GetMessage("SOA_FROM") . " " . IntVal($arDelivery["PERIOD_FROM"]);
             }
             if (IntVal($arDelivery["PERIOD_TO"]) > 0) {
                 $arDelivery["PERIOD_TEXT"] .= " " . GetMessage("SOA_TO") . " " . IntVal($arDelivery["PERIOD_TO"]);
             }
             if ($arDelivery["PERIOD_TYPE"] == "H") {
                 $arDelivery["PERIOD_TEXT"] .= " " . GetMessage("SOA_HOUR") . " ";
             } elseif ($arDelivery["PERIOD_TYPE"] == "M") {
                 $arDelivery["PERIOD_TEXT"] .= " " . GetMessage("SOA_MONTH") . " ";
             } else {
Exemple #19
0
 static function DoProcessOrderDelivery(&$arOrder, $arOptions, &$arErrors)
 {
     if ((!array_key_exists("TAX_LOCATION", $arOrder) || intval($arOrder["TAX_LOCATION"]) <= 0) && (!$arOrder["USE_VAT"] || $arOrder["USE_VAT"] != "Y")) {
         return;
     }
     if (!array_key_exists("COUNT_DELIVERY_TAX", $arOptions)) {
         $arOptions["COUNT_DELIVERY_TAX"] = COption::GetOptionString("sale", "COUNT_DELIVERY_TAX", "N");
     }
     if (doubleval($arOrder["DELIVERY_PRICE"]) <= 0 || $arOptions["COUNT_DELIVERY_TAX"] != "Y") {
         return;
     }
     if (!$arOrder["USE_VAT"] || $arOrder["USE_VAT"] != "Y") {
         if (!array_key_exists("TAX_EXEMPT", $arOrder)) {
             $arUserGroups = CUser::GetUserGroup($arOrder["USER_ID"]);
             $dbTaxExemptList = CSaleTax::GetExemptList(array("GROUP_ID" => $arUserGroups));
             while ($TaxExemptList = $dbTaxExemptList->Fetch()) {
                 if (!in_array(intval($TaxExemptList["TAX_ID"]), $arOrder["TAX_EXEMPT"])) {
                     $arOrder["TAX_EXEMPT"][] = intval($TaxExemptList["TAX_ID"]);
                 }
             }
         }
         if (!array_key_exists("TAX_LIST", $arOrder)) {
             $arOrder["TAX_LIST"] = array();
             $dbTaxRate = CSaleTaxRate::GetList(array("APPLY_ORDER" => "ASC"), array("LID" => $arOrder["SITE_ID"], "PERSON_TYPE_ID" => $arOrder["PERSON_TYPE_ID"], "ACTIVE" => "Y", "LOCATION" => $arOrder["TAX_LOCATION"]));
             while ($arTaxRate = $dbTaxRate->GetNext()) {
                 if (!in_array(intval($arTaxRate["TAX_ID"]), $arOrder["TAX_EXEMPT"])) {
                     if ($arTaxRate["IS_PERCENT"] != "Y") {
                         $arTaxRate["VALUE"] = RoundEx(CCurrencyRates::ConvertCurrency($arTaxRate["VALUE"], $arTaxRate["CURRENCY"], $arOrder["CURRENCY"]), SALE_VALUE_PRECISION);
                         $arTaxRate["CURRENCY"] = $arOrder["CURRENCY"];
                     }
                     $arOrder["TAX_LIST"][] = $arTaxRate;
                 }
             }
         }
         if (count($arOrder["TAX_LIST"]) > 0) {
             CSaleOrderTax::CountTaxes($arOrder["DELIVERY_PRICE"], $arOrder["TAX_LIST"], $arOrder["CURRENCY"]);
             $arOrder["TAX_PRICE"] = 0;
             foreach ($arOrder["TAX_LIST"] as &$arTax) {
                 $arTax["VALUE_MONEY"] += roundEx($arTax["TAX_VAL"], SALE_VALUE_PRECISION);
                 $arTax['VALUE_MONEY_FORMATED'] = SaleFormatCurrency($arTax["VALUE_MONEY"], $arOrder["CURRENCY"]);
                 if ($arTax["IS_IN_PRICE"] != "Y") {
                     $arOrder["TAX_PRICE"] += $arTax["VALUE_MONEY"];
                 }
             }
             unset($arTax);
         }
     } else {
         $deliveryVat = $arOrder["DELIVERY_PRICE"] * $arOrder["VAT_RATE"] / (1 + $arOrder["VAT_RATE"]);
         $arOrder["VAT_SUM"] += $deliveryVat;
         $arOrder["VAT_DELIVERY"] += $deliveryVat;
         //if (!array_key_exists("TAX_LIST", $arOrder))
         //{
         $arOrder["TAX_LIST"][0] = array("NAME" => GetMessage("SOA_VAT"), "IS_PERCENT" => "Y", "VALUE" => $arOrder["VAT_RATE"] * 100, "VALUE_FORMATED" => "(" . $arOrder["VAT_RATE"] * 100 . "%, " . GetMessage("SOA_VAT_INCLUDED") . ")", "VALUE_MONEY" => $arOrder["VAT_SUM"], "VALUE_MONEY_FORMATED" => SaleFormatCurrency($arOrder["VAT_SUM"], $arOrder["CURRENCY"]), "APPLY_ORDER" => 100, "IS_IN_PRICE" => "Y", "CODE" => "VAT");
         //}
     }
     $arOrder["TAX_PRICE"] = roundEx($arOrder["TAX_PRICE"], SALE_VALUE_PRECISION);
     $arOrder["VAT_SUM"] = roundEx($arOrder["VAT_SUM"], SALE_VALUE_PRECISION);
     $arOrder["VAT_DELIVERY"] = roundEx($arOrder["VAT_DELIVERY"], SALE_VALUE_PRECISION);
 }
Exemple #20
0
 function makeDetailClassFromOrder($arOrder)
 {
     $saleModulePermissions = $GLOBALS["APPLICATION"]->GetGroupRight("sale");
     $mad = new CAdminMobileDetail();
     $arSection = array("TITLE" => GetMessage("SMOB_ORDER_INFO"), "OPEN" => true, "ROWS" => array(array("TITLE" => GetMessage("SMOB_CREATED") . ":", "VALUE" => self::getDateTime($arOrder['DATE_INSERT'])), array("TITLE" => GetMessage("SMOB_CHANGED") . ":", "VALUE" => self::getDateTime($arOrder['DATE_UPDATE'])), array("TITLE" => GetMessage("SMOB_STATUS") . ":", "VALUE" => $arOrder['STATUS_NAME'])));
     $dateCChanged = false;
     if (strlen($arOrder["DATE_CANCELED"]) > 0) {
         $dateCChanged = self::getDateTime($arOrder["DATE_CANCELED"]);
     }
     if (IntVal($arOrder["EMP_CANCELED_ID"]) > 0) {
         $dateCChanged .= " " . self::GetFormatedUserName($arOrder["EMP_CANCELED_ID"]);
     }
     if ($arOrder['CANCELED'] == 'Y') {
         $arSection["BOTTOM"] = array("STYLE" => "red", "VALUE" => GetMessage("SMOB_ORDER_CANCELED"));
     }
     if ($arOrder['CANCELED'] == 'N' && IntVal($arOrder["EMP_CANCELED_ID"]) > 0) {
         $arSection["BOTTOM"] = array("STYLE" => "green", "VALUE" => GetMessage("SMOB_ORDER_CANCEL_CANCELED"));
     }
     if ($dateCChanged) {
         $arSection["BOTTOM"]["VALUE"] .= "<br>" . $dateCChanged;
     }
     $mad->addSection($arSection);
     $arSection = array("TITLE" => GetMessage("SMOB_BUYER"), "ROWS" => array(array("TITLE" => GetMessage("SMOB_LOGIN") . ":", "VALUE" => $arOrder['USER_LOGIN']), array("TITLE" => GetMessage("SMOB_PAYER_TYPE") . ":", "VALUE" => $arOrder['PERSON_TYPE_NAME']), array("TITLE" => GetMessage("SMOB_FIO") . ":", "VALUE" => $arOrder['CUSTOMER_FIO']), array("TITLE" => GetMessage("SMOB_EMAIL") . ":", "VALUE" => '<a href="mailto:' . $arOrder['CUSTOMER_EMAIL'] . '">' . $arOrder['CUSTOMER_EMAIL'] . '</a>'), array("TITLE" => GetMessage("SMOB_PHONE") . ":", "VALUE" => '<a href="tel:' . $arOrder['CUSTOMER_PHONE'] . '">' . $arOrder['CUSTOMER_PHONE'] . '</a>'), array("TITLE" => GetMessage("SMOB_ZIP") . ":", "VALUE" => $arOrder['CUSTOMER_ZIP']), array("TITLE" => GetMessage("SMOB_LOCATION") . ":", "VALUE" => $arOrder['CUSTOMER_LOCATION'])));
     if (strlen(trim($arOrder['CUSTOMER_CITY'])) > 0) {
         $arSection["ROWS"][] = array("TITLE" => GetMessage("SMOB_CITY") . ":", "VALUE" => $arOrder['CUSTOMER_CITY']);
     }
     $arSection["ROWS"][] = array("TITLE" => GetMessage("SMOB_ADDRESS") . ":", "VALUE" => $arOrder['CUSTOMER_ADDRESS']);
     $mad->addSection($arSection);
     $dateDChange = false;
     if (strlen($arOrder["DATE_ALLOW_DELIVERY"]) > 0) {
         $dateDChange = self::getDateTime($arOrder["DATE_ALLOW_DELIVERY"]);
     }
     if (IntVal($arOrder["EMP_ALLOW_DELIVERY_ID"]) > 0) {
         $dateDChange .= " " . self::GetFormatedUserName($arOrder["EMP_ALLOW_DELIVERY_ID"]);
     }
     $arSection = array("TITLE" => GetMessage("SMOB_DELIVERY"), "ROWS" => array(array("TITLE" => GetMessage("SMOB_D_SERVICE") . ":", "VALUE" => $arOrder['DELIVERY_NAME'])));
     if ($arOrder['ALLOW_DELIVERY'] == 'Y') {
         $arSection["BOTTOM"] = array("STYLE" => "green", "VALUE" => GetMessage("SMOB_D_ALLOWED"));
     }
     if ($arOrder['ALLOW_DELIVERY'] == 'N' && !is_null($arOrder["DATE_ALLOW_DELIVERY"])) {
         $arSection["BOTTOM"] = array("STYLE" => "red", "VALUE" => GetMessage("SMOB_D_DISALLOWED"));
     }
     if ($dateDChange) {
         $arSection["BOTTOM"]["VALUE"] .= "<br>" . $dateDChange;
     }
     $mad->addSection($arSection);
     $arSection = array("TITLE" => GetMessage("SMOB_PAYMENT"), "ROWS" => array(array("TITLE" => GetMessage("SMOB_P_METHOD") . ":", "VALUE" => $arOrder['PAY_SYSTEM_NAME']), array("TITLE" => GetMessage("SMOB_P_PRICE") . ":", "VALUE" => $arOrder['PRICE_STR'])));
     $datePChange = false;
     if (strlen($arOrder['DATE_PAYED']) > 0) {
         $datePChange = self::getDateTime($arOrder['DATE_PAYED']);
     }
     if (IntVal($arOrder["EMP_PAYED_ID"]) > 0) {
         $datePChange .= " " . self::GetFormatedUserName($arOrder["EMP_PAYED_ID"]);
     }
     if ($arOrder['PAYED'] == 'Y') {
         $arSection["BOTTOM"] = array("STYLE" => "green", "VALUE" => GetMessage("SMOB_PAYED"));
     }
     if ($arOrder['PAYED'] == 'N' && !is_null($arOrder['DATE_PAYED'])) {
         $arSection["BOTTOM"] = array("STYLE" => "red", "VALUE" => GetMessage("SMOB_PAY_CANCELED"));
     }
     if ($datePChange) {
         $arSection["BOTTOM"]["VALUE"] .= "<br>" . $datePChange;
     }
     $mad->addSection($arSection);
     $arSection = array("TITLE" => GetMessage("SMOB_COMMENTS"), "ROWS" => array(array("TITLE" => GetMessage("SMOB_C_BUYER") . ":", "VALUE" => $arOrder['USER_DESCRIPTION'])));
     if ($saleModulePermissions > D) {
         $arSection["ROWS"][] = array("TITLE" => GetMessage("SMOB_C_MANAGER") . ":", "VALUE" => $arOrder['COMMENTS']);
     }
     $mad->addSection($arSection);
     if ($arOrder['MARKED'] == 'Y') {
         $arSection = array("TITLE" => GetMessage("SMOB_MARK"), "OPEN" => true);
         $reason = strlen($arOrder["REASON_MARKED"]) > 0 ? $arOrder["REASON_MARKED"] : GetMessage("SMOB_MARK_NO_DESCRIPTION");
         if (strlen($arOrder['DATE_MARKED']) > 0) {
             $reason .= '<br>' . self::getDateTime($arOrder['DATE_MARKED']);
         }
         if (intval($arOrder['EMP_MARKED_ID']) > 0) {
             $reason .= " (" . self::GetFormatedUserName($arOrder["EMP_MARKED_ID"]) . ")";
         }
         $arSection["BOTTOM"] = array("STYLE" => "red", "VALUE" => $reason);
         $mad->addSection($arSection);
     }
     $arSection = array("TITLE" => GetMessage("SMOB_DEDUCT"));
     if ($arOrder['DEDUCTED'] == 'Y') {
         $arSection["BOTTOM"] = array("STYLE" => "green", "VALUE" => GetMessage("SMOB_ORDER_DEDUCTED"));
     } elseif ($arOrder['DEDUCTED'] == 'N' && strlen($arOrder["DATE_DEDUCTED"]) > 0) {
         $arSection["BOTTOM"] = array("STYLE" => "red", "VALUE" => GetMessage("SMOB_ORDER_DEDUCTED_UNDO"));
     } else {
         $arSection["ROWS"][] = array("TITLE" => GetMessage("SMOB_ORDER_NOT_DEDUCTED"), "VALUE" => "");
     }
     if (strlen($arOrder["REASON_UNDO_DEDUCTED"]) > 0) {
         $arSection["BOTTOM"]["VALUE"] .= '<br>' . $arOrder["REASON_UNDO_DEDUCTED"];
     }
     if (strlen($arOrder["DATE_DEDUCTED"]) > 0) {
         $arSection["BOTTOM"]["VALUE"] .= '<br>' . self::getDateTime($arOrder["DATE_DEDUCTED"]);
     }
     if (intval($arOrder['EMP_DEDUCTED_ID']) > 0) {
         $arSection["BOTTOM"]["VALUE"] .= " (" . self::GetFormatedUserName($arOrder["EMP_DEDUCTED_ID"]) . ")";
     }
     $mad->addSection($arSection);
     ob_start();
     $productListReturn = $GLOBALS["APPLICATION"]->IncludeComponent('bitrix:sale.mobile.product.list', '.default', array("ORDER_ID" => $arOrder['ID']), false);
     $productListHtml = ob_get_contents();
     ob_end_clean();
     $mad->addSection(array("TITLE" => GetMessage("SMOB_PRODUCT_LIST"), "TYPE" => "container", "HTML" => $productListHtml));
     $WEIGHT_UNIT = htmlspecialcharsbx(COption::GetOptionString('sale', 'weight_unit', "", $arOrder['LID']));
     $WEIGHT_KOEF = htmlspecialcharsbx(COption::GetOptionString('sale', 'weight_koef', 1, $arOrder['LID']));
     $arSection = array("TITLE" => GetMessage("SMOB_TOTAL"), "TOTAL" => true, "ROWS" => array(array("TITLE" => GetMessage("SMOB_PRICE_ALL") . ":", "VALUE" => SaleFormatCurrency($productListReturn['PRICE_TOTAL'], $arOrder["CURRENCY"])), array("TITLE" => GetMessage("SMOB_P_DELIVERY") . ":", "VALUE" => SaleFormatCurrency($productListReturn['PRICE'], $arOrder["CURRENCY"])), array("TITLE" => GetMessage("SMOB_DELIVERY") . ":", "VALUE" => SaleFormatCurrency($arOrder['PRICE_DELIVERY'], $arOrder["CURRENCY"]))));
     if ($arOrder['TAX_VALUE'] > 0) {
         $arSection["ROWS"][] = array("TITLE" => GetMessage("SMOB_TAX") . ":", "VALUE" => SaleFormatCurrency($arOrder['TAX_VALUE'], $arOrder["CURRENCY"]));
     }
     if ($arOrder['DISCOUNT_VALUE'] > 0) {
         $arSection["ROWS"][] = array("TITLE" => GetMessage("SMOB_DISCOUNT") . ":", "VALUE" => SaleFormatCurrency($arOrder['DISCOUNT_VALUE'], $arOrder["CURRENCY"]));
     }
     $arSection["ROWS"][] = array("TITLE" => GetMessage("SMOB_WEIGHT") . ":", "VALUE" => roundEx(DoubleVal($productListReturn['WEIGHT'] / $WEIGHT_KOEF), SALE_WEIGHT_PRECISION) . " " . $WEIGHT_UNIT);
     $arSection["ROWS"][] = array("TITLE" => GetMessage("SMOB_TOTALLY") . ":", "VALUE" => SaleFormatCurrency($arOrder['PRICE'], $arOrder["CURRENCY"]), "HIGLIGHTED" => true);
     $mad->addSection($arSection);
     /*
     alternative:
     $arDetail = $mad->getItem();
     return  CAdminMobileDetailTmpl::getHtml($arDetail);
     */
     return $mad->getHtml();
 }
Exemple #21
0
 /**
  * @return float|int
  */
 public function getVatSum()
 {
     $vatSum = 0;
     /** @var BasketItem $basketItem */
     foreach ($this->collection as $basketItem) {
         if (!$basketItem->isBundleChild()) {
             // BasketItem that is removed is not involved
             if ($basketItem->getQuantity() == 0) {
                 continue;
             }
             if ($basketItem->getVatRate() > 0) {
                 $vatValue = $basketItem->getPrice() / ($basketItem->getVatRate() + 1) * $basketItem->getVatRate();
                 $vatSum += roundEx($vatValue * $basketItem->getQuantity(), SALE_VALUE_PRECISION);
             }
         }
     }
     return $vatSum;
 }
Exemple #22
0
/**
 * событие вызывается перед отправкой письма о новом заказе
 * @param $orderID
 * @param $eventName
 * @param $arFields
 */
function bxModifySaleMails($order_id, &$eventName, &$arFieldsEmail)
{
                                             
    //unset($_SESSION['OnBeforeOrderAddHandler']);
    //$_SESSION['OnBeforeOrderAddHandler']['bxModifySaleMails']='bxModifySaleMails';
    //$_SESSION['OnBeforeOrderAddHandler']['id']=$order_id;
    //$_SESSION['OnBeforeOrderAddHandler']['arFields']=$arFieldsorder_old;
    $basket_props="";
    $post['INFO']="";
    $id_product=array();
    if(
        (CModule::IncludeModule("main"))
        &&
        (CModule::IncludeModule("iblock"))
        &&
        (CModule::IncludeModule("catalog"))
        &&
        (CModule::IncludeModule("sale"))
    ){


        /**
         * получаем параметры сформировавшегося старого заказа
         */
        $arFieldsorder_old = CSaleOrder::GetByID($order_id);
        /*
        echo "<pre>";
        var_dump($arFieldsorder_old);die();
        echo "</pre>";*/
        /**
         * выборка свойства сформировавшегося заказа по id заказа
         */
        $db_props = CSaleOrderPropsValue::GetOrderProps($order_id);
        $arFields_props = array();

        while ($arProps = $db_props->Fetch())
        {
            $arFields_props_old[$arProps['CODE']]=$arProps;

        }
        //_debug($arFields_props_old);

        /**
         * выборка из корзины по id заказа
         * получаем масси id продукта
         */
         
         $rsUser = CUser::GetByID(CUser::GetID());
         $arUser = $rsUser->Fetch();
         /*if (!$ORDER_ID = CSaleOrder::Add(array(
                                        "LID"              => SITE_ID,
                                        "PERSON_TYPE_ID"   => 1,
                                        "PAYED"            => "N",
                                        "CANCELED"         => "N",
                                        "STATUS_ID"        => "N",
                                        "PRICE"            => 0,
                                        "CURRENCY"         => CSaleLang::GetLangCurrency(SITE_ID),
                                        "USER_ID"          => $arUser['ID'],
                                        "PAY_SYSTEM_ID"    => $arFieldsorder_old['PAY_SYSTEM_ID'],
                                        "PRICE_DELIVERY"   => 0,
                                        "DELIVERY_ID"      => $arFieldsorder_old['DELIVERY_ID'],
                                        "DISCOUNT_VALUE"   => $arFieldsorder_old['DISCOUNT_VALUE'],
                                        "TAX_VALUE"        => $arFieldsorder_old['TAX_VALUE'],
                                        "USER_DESCRIPTION" => $post['INFO']
         ))){

                                        $rows['msg'] = 'Ошибка создания заказа';
                                        $fail          = true;
        }else{
                                        $rows['msg']=$ORDER_ID;
                                        //continue;
        }*/

        $dbBasketItems = CSaleBasket::GetList(
            array("ID" => "ASC"),
            array(
                "LID" => SITE_ID,
                "ORDER_ID" => $order_id
            ),
            false,
            false,
            array()
        );
        while ($arItem = $dbBasketItems->Fetch()){
            $id_product[] = $arItem['PRODUCT_ID'];
            $products_basket[$arItem['PRODUCT_ID']]=$arItem;
        }
        
        foreach($products_basket as $product){
            $price_product+=$product['PRICE']*$product['QUANTITY'];
            $products_descriptions.=$product['NAME']." - ".$product['QUANTITY']." шт: ".intval($product['PRICE'])." руб <br/>";
        
        }
        $price_product+=$arFieldsorder_old["PRICE_DELIVERY"];
        //$_SESSION['OnBeforeOrderAddHandler']['products_basket']=$products_basket;

        /**
         * получаем массив id партнеров из продукта
         */
        //var_dump($id_product);die();         

        if($id_product){
            $id_partner=array();
            $partner_product=array();
            $arSelect = Array("ID", "NAME","IBLOCK_ID","PROPERTY_PARTNER");
            $arFilter = Array("ID"=>$id_product, "ACTIVE"=>"Y");
            $res = CIBlockElement::GetList(Array(), $arFilter, false, false, $arSelect);
            
            while($ob = $res->GetNextElement())
            {
                $arFields = $ob->GetFields();
                $partner_product[$arFields['PROPERTY_PARTNER_VALUE']][]=$products_basket[$arFields['ID']];
                if($arFields['PROPERTY_PARTNER_VALUE']){
                    $id_partner[]=$arFields['PROPERTY_PARTNER_VALUE'];
                }
            }
            //$_SESSION['OnBeforeOrderAddHandler']['id_partner']=$id_partner;

            /**
             * получаем массив данных партнера
             */
         
            if($id_partner){
                            
                            
                $delivery_sum = null;
                $arSelect2 = Array("ID", "IBLOCK_ID", "NAME","PROPERTY_*");
                $arFilter2 = Array("IBLOCK_ID"=>9, "ACTIVE"=>"Y","ID"=>$id_partner,);
                $res2 = CIBlockElement::GetList(Array(), $arFilter2, false, false, $arSelect2);
                /**
                 * eсли в выборке корзине в продуктах больше чем один партнер
                 * то разбиваем заказ по количеству партнеров
                 */
                if (intval($res2->SelectedRowsCount())>0){
                    while($ob2 = $res2->GetNextElement()){
                        $arFields_partners = $ob2->GetFields();
                        $arProperties_partners = $ob2->GetProperties();
                        //_debug($arProperties_partners);
                        //$price_product=0;
                        //$products_descriptions="";
                        $arEventFields=array();
                        //echo $arFields_partners['ID'];
                        
                        
                        if($partner_product[$arFields_partners['ID']]){

                            $i=0;
                            $size_of_productpartner=sizeof($partner_product[$arFields_partners['ID']]);
                            foreach($partner_product[$arFields_partners['ID']] as $key_price=>$item_price){
                                //_debug($item_price);
                                $quantity=1;
                                /**
                                 * формируем новый пустой заказ
                                 */
                                if(!$i){


                                    if (!$ORDER_ID = CSaleOrder::Add(array(
                                        "LID"              => SITE_ID,
                                        "PERSON_TYPE_ID"   => 1,
                                        "PAYED"            => "N",
                                        "CANCELED"         => "N",
                                        "STATUS_ID"        => "N",
                                        "PRICE"            => 0,
                                        "CURRENCY"         => CSaleLang::GetLangCurrency(SITE_ID),
                                        "USER_ID"          => $arUser['ID'],
                                        "PAY_SYSTEM_ID"    => $arFieldsorder_old['PAY_SYSTEM_ID'],
                                        "PRICE_DELIVERY"   => 0,
                                        "DELIVERY_ID"      => $arFieldsorder_old['DELIVERY_ID'],
                                        "DISCOUNT_VALUE"   => $arFieldsorder_old['DISCOUNT_VALUE'],
                                        "TAX_VALUE"        => $arFieldsorder_old['TAX_VALUE'],
                                        "USER_DESCRIPTION" => $post['INFO']
                                    ))){

                                        $rows['msg'] = 'Ошибка создания заказа';
                                        $fail          = true;
                                    }else{
                                        $rows['msg']=$ORDER_ID;
                                        //continue;
                                    }
                                }

                                /**
                                 * добавляем по id заказа в корзину товары партнера
                                 */
                                if (!Add2BasketByProductID($item_price['PRODUCT_ID'], $item_price['QUANTITY'], array(
                                    'ORDER_ID' => $ORDER_ID,
                                ), $basket_props)) {
                                    $rows['err'] = 'Ошибка добавления товара в заказ';
                                    $fail          = true;
                                }

                                /*$price_product+=$item_price['PRICE']*$item_price['QUANTITY'];
                                $products_descriptions.=$item_price['NAME']." - ".$item_price['QUANTITY']." шт: ".intval($item_price['PRICE'])." руб <br/>";
                                */


                                $i++;
                                /**
                                 * обновляем параметры нового заказа на актуальные
                                 */
                                if($size_of_productpartner==$i){
                                    if (!$fail) {
                                        $dbBasketItems = CSaleBasket::GetList(
                                            array("NAME" => "ASC", "ID" => "ASC"), array(
                                                "LID"      => SITE_ID,
                                                "ORDER_ID" => $ORDER_ID
                                            ), false, false, array(
                                                "ID", "NAME", "QUANTITY", "CURRENCY", "CAN_BUY", "PRICE", "WEIGHT", "DISCOUNT_PRICE"
                                            )
                                        );

                                        $summ          = $weight        = 0;
                                        $strOrderList  = "";


                                        $arBasket      = array();
                                        while ($arBasketItems = $dbBasketItems->GetNext()) {
                                            $strOrderList .= $arBasketItems["NAME"] . " - " . $arBasketItems["QUANTITY"] . " шт на " . SaleFormatCurrency($arBasketItems["PRICE"] * $arBasketItems["QUANTITY"], $arBasketItems["CURRENCY"]);
                                            $strOrderList .= "\n";
                                            $rows['summ']=$summ += roundEx($arBasketItems["PRICE"], SALE_VALUE_PRECISION) * DoubleVal($arBasketItems["QUANTITY"]);
                                            $weight += doubleval($arBasketItems['WEIGHT']);
                                            $arBasket[] = $arBasketItems;
                                        }
                                        $arOrderForDiscount = array(
                                            'SITE_ID'      => SITE_ID,
                                            'USER_ID'      => $arUser['ID'],
                                            'ORDER_PRICE'  => $summ,
                                            'ORDER_WEIGHT' => $weight,
                                            'BASKET_ITEMS' => $arBasket,
                                        );
                                        $arDiscountOptions  = array();
                                        $arDiscountErrors   = array();
                                        CSaleDiscount::DoProcessOrder($arOrderForDiscount, $arDiscountOptions, $arDiscountErrors);
                                        if($_REQUEST['comment'])
                                            $arOrderForDiscount['COMMENTS'] = $_REQUEST['comment'];
                                        if($arProperties_partners['DOSTAVKA']['VALUE']){
                                            $arOrderForDiscount["PRICE_DELIVERY"] = $arProperties_partners['DOSTAVKA']['VALUE'];
                                            $arOrderForDiscount["DELIVERY_ID"] = 3;
                                            $summ += intval($arProperties_partners['DOSTAVKA']['VALUE']);
                                            $arOrderForDiscount['ORDER_PRICE']=$summ;
                                        }
                                        $arOrderForDiscount['PRICE_BEFORE'] = $summ;
                                        $arOrderForDiscount['PRICE']        = $summ;
                                        $arOrderForDiscount['WEIGHT']       = $arOrderForDiscount['ORDER_WEIGHT'];
                                        /**
                                         * обновляем заказ
                                         */
                                        if (!CSaleOrder::Update($ORDER_ID, $arOrderForDiscount)) {
                                            $rows['err'] = 'Ошибка расчета цены заказа.';
                                            $fail          = true;
                                        }else{

                                            /**
                                             * перезагружаем свойства заказ из старого
                                             */
                                            $db_props_new = CSaleOrderPropsValue::GetOrderProps($ORDER_ID);
                                            $arFields_props_new = array();
                                            while ($arProps_new = $db_props_new->Fetch())
                                            {
                                                //_debug($arProps_new);
                                                foreach($arFields_props_old as $key_props_old=>$item_props_old){
                                                    if($arProps_new['CODE']==$key_props_old){
                                                        CSaleOrderPropsValue::Update($arProps_new['ID'], array("VALUE"=>$item_props_old['VALUE']));
                                                        unset($arFields_props_old[$key_props_old]);
                                                    }
                                                }

                                            }
                                            if(sizeof($arFields_props_old)>0){
                                                foreach($arFields_props_old as $key_props_old2=>$item_props_old2){
                                                    CSaleOrderPropsValue::Add(array(
                                                        'NAME'           => $item_props_old2['NAME'],
                                                        'CODE'           => $item_props_old2['CODE'],
                                                        'ORDER_PROPS_ID' => $item_props_old2['ORDER_PROPS_ID'],
                                                        'ORDER_ID'       => $ORDER_ID,
                                                        'VALUE'          => $item_props_old2['VALUE']
                                                    ));
                                                }
                                            }
                                            /**
                                             * добавляем в свойство заказа id партнера для дальнейшей фильтрации по партнерским заказам
                                             */
                                            CSaleOrderPropsValue::Add(array(
                                                'NAME'           => "Привязка по партнеру",
                                                'CODE'           => "PATNERID",
                                                'ORDER_PROPS_ID' => 21,
                                                'ORDER_ID'       => $ORDER_ID,
                                                'VALUE'          => $arFields_partners['ID']
                                            ));


                                            //$price_product+=$arProperties_partners['DOSTAVKA']['VALUE'];
                                            //$price_product+=$arFieldsorder_old["PRICE_DELIVERY"];
                                            /**
                                             * отправляем данные о товаре Партнерам
                                             */
           
                                            if($arFields_partners['NAME']){  //если есть партнер у товара                              
                                                $arEventFields = Array(
                                                    "ORDER_ID"=> $ORDER_ID,
                                                    "ORDER_DATE"=> date("d.m.Y H:i:s"),
                                                    "ORDER_USER"=> $arFields_partners['NAME'],
                                                    "PRICE"=> $price_product,
                                                    "EMAIL"=> $arProperties_partners['EMAIL']['VALUE'],
                                                    "ORDER_LIST"=> $products_descriptions,
                                                    //"DELIVERY_PRICE"=>$arProperties_partners['DOSTAVKA']['VALUE']
                                                    "DELIVERY_PRICE"=>$arFieldsorder_old["PRICE_DELIVERY"]
                                                );
                                                $event = new CEvent;
                                                $event->SendImmediate("SALE_NEW_ORDERPARTNER", SITE_ID, $arEventFields);
                                            }
                                            
                                            
                                        }
                                    }
                                    //                        if(!$fail){
                                    //                            $ar_res_product=CCatalogProduct::GetByID($PRODUCT['ID']);
                                    //                            $arFields_quant = array(
                                    //                                'QUANTITY' => $ar_res_product['QUANTITY']-1
                                    //                            );
                                    //                            CCatalogProduct::Update($PRODUCT['ID'], $arFields_quant);
                                    //                        }

                                }

                            }
                        }
                    }
                    /**
                     * удаляем старый заказ после разбивки на новые
                     */
                    if($ORDER_ID ){
                        CSaleOrder::Delete($order_id);
                    }
                }
            }
            
            
            $arEventFields = Array(
                "ORDER_ID" =>$order_id,
                "ORDER_DATE" =>date("d.m.Y H:i:s"),
                "ORDER_USER" =>$arUser['NAME'],
                "PRICE" =>$price_product,
                "EMAIL" => $arUser['EMAIL'],
                "ORDER_LIST" =>$products_descriptions,
                "DELIVERY_PRICE"=>$arFieldsorder_old["PRICE_DELIVERY"]
            );
            $event = new CEvent;
            $event->SendImmediate("SALE_NEW_BILET", SITE_ID, $arEventFields); 
            
            
        }
    }
    //$_SESSION['OnBeforeOrderAddHandler']['rows']=$rows;
    return false;

}
Exemple #23
0
                foreach ($vatRates as $vatRate) {
                    $vats[$vatRate] += abs($delta) / $delta / pow(10, SALE_VALUE_PRECISION);
                    $delta -= abs($delta) / $delta;
                    if ($delta == 0) {
                        break 2;
                    }
                }
            }
        }
        foreach ($vats as $vatRate => $vatSum) {
            $arCells[++$n] = array(1 => null, null, null, null, null, sprintf("Impuesto (%s%%):", roundEx($vatRate * 100, SALE_VALUE_PRECISION)), SaleFormatCurrency($vatSum, $GLOBALS["SALE_INPUT_PARAMS"]["ORDER"]["CURRENCY"], false));
        }
    } else {
        $dbTaxList = CSaleOrderTax::GetList(array("APPLY_ORDER" => "ASC"), array("ORDER_ID" => $ORDER_ID));
        while ($arTaxList = $dbTaxList->Fetch()) {
            $arCells[++$n] = array(1 => null, null, null, null, null, htmlspecialcharsbx(sprintf("%s%s%s:", $arTaxList["IS_IN_PRICE"] == "Y" ? "Incluido " : "", $arTaxList["TAX_NAME"], sprintf(' (%s%%)', roundEx($arTaxList["VALUE"], SALE_VALUE_PRECISION)))), SaleFormatCurrency($arTaxList["VALUE_MONEY"], $GLOBALS["SALE_INPUT_PARAMS"]["ORDER"]["CURRENCY"], false));
        }
    }
    if (DoubleVal($GLOBALS["SALE_INPUT_PARAMS"]["ORDER"]["SUM_PAID"]) > 0) {
        $arCells[++$n] = array(1 => null, null, null, null, null, "Pago hecho:", SaleFormatCurrency($GLOBALS["SALE_INPUT_PARAMS"]["ORDER"]["SUM_PAID"], $GLOBALS["SALE_INPUT_PARAMS"]["ORDER"]["CURRENCY"], false));
    }
    if (DoubleVal($GLOBALS["SALE_INPUT_PARAMS"]["ORDER"]["DISCOUNT_VALUE"]) > 0) {
        $arCells[++$n] = array(1 => null, null, null, null, null, "Descuento:", SaleFormatCurrency($GLOBALS["SALE_INPUT_PARAMS"]["ORDER"]["DISCOUNT_VALUE"], $GLOBALS["SALE_INPUT_PARAMS"]["ORDER"]["CURRENCY"], false));
    }
    $arCells[++$n] = array(1 => null, null, null, null, null, "Total:", SaleFormatCurrency($GLOBALS["SALE_INPUT_PARAMS"]["ORDER"]["SHOULD_PAY"], $GLOBALS["SALE_INPUT_PARAMS"]["ORDER"]["CURRENCY"], false));
}
?>
<table class="it" width="100%">
	<tr>
		<td><nobr>#</nobr></td>
		<td><nobr>Artículo / Descripción</nobr></td>
Exemple #24
0
 /**
  * apply discount.
  * @internal
  * @param array $data			Order data.
  * @return Result
  */
 public function applyDiscount(array $data)
 {
     if (!empty($data['BASKET_ITEMS']) && is_array($data['BASKET_ITEMS'])) {
         /** @var Basket $basket */
         $basket = $this->getBasket();
         foreach ($data['BASKET_ITEMS'] as $basketCode => $basketItemData) {
             /** @var BasketItem $basketItem */
             if ($basketItem = $basket->getItemByBasketCode($basketCode)) {
                 if (isset($basketItemData['DISCOUNT_PRICE']) && floatval($basketItemData['DISCOUNT_PRICE']) >= 0 && $basketItem->getDiscountPrice() != floatval($basketItemData['DISCOUNT_PRICE'])) {
                     $basketItemData['DISCOUNT_PRICE'] = roundEx(floatval($basketItemData['DISCOUNT_PRICE']), SALE_VALUE_PRECISION);
                     $basketItem->setField('DISCOUNT_PRICE', $basketItemData['DISCOUNT_PRICE']);
                     if (!$basketItem->isCustomPrice()) {
                         $basketItem->setField('PRICE', $basketItem->getBasePrice() - $basketItemData['DISCOUNT_PRICE']);
                     }
                 }
             }
         }
     }
     if (isset($data['SHIPMENT']) && intval($data['SHIPMENT']) > 0 && isset($data['PRICE_DELIVERY']) && floatval($data['PRICE_DELIVERY']) >= 0) {
         /** @var ShipmentCollection $shipmentCollection */
         if ($shipmentCollection = $this->getShipmentCollection()) {
             /** @var Shipment $shipment */
             if ($shipment = $shipmentCollection->getItemByShipmentCode($data['SHIPMENT'])) {
                 if (floatval($data['PRICE_DELIVERY']) > 0) {
                     $data['PRICE_DELIVERY'] = roundEx(floatval($data['PRICE_DELIVERY']), SALE_VALUE_PRECISION);
                     $shipment->setField('PRICE_DELIVERY', $data['PRICE_DELIVERY']);
                 }
             }
         }
     }
     if (isset($data['DISCOUNT_PRICE']) && floatval($data['DISCOUNT_PRICE']) >= 0) {
         $data['DISCOUNT_PRICE'] = roundEx(floatval($data['DISCOUNT_PRICE']), SALE_VALUE_PRECISION);
         $this->setField('DISCOUNT_PRICE', $data['DISCOUNT_PRICE']);
     }
     return new Result();
 }
 /**
  * Apply catalog discount by basket item.
  *
  * @param array &$product			Product data.
  * @param array $discount			Discount data.
  * @return void
  */
 public static function applyDiscount(&$product, $discount)
 {
     if (empty($product) || !is_array($product)) {
         return;
     }
     if (empty($discount) || empty($discount['TYPE'])) {
         return;
     }
     if (isset($discount['CURRENCY']) && $discount['CURRENCY'] != $product['CURRENCY']) {
         return;
     }
     if (!isset($product['DISCOUNT_PRICE'])) {
         $product['DISCOUNT_PRICE'] = 0;
     }
     $getPercentFromBasePrice = isset($discount['USE_BASE_PRICE']) && $discount['USE_BASE_PRICE'] == 'Y';
     $basePrice = (double) (isset($product['BASE_PRICE']) ? $product['BASE_PRICE'] : $product['PRICE'] + $product['DISCOUNT_PRICE']);
     switch ($discount['TYPE']) {
         case Catalog\DiscountTable::VALUE_TYPE_PERCENT:
             $discountValue = roundEx(($getPercentFromBasePrice ? $basePrice : $product['PRICE']) * $discount['VALUE'] / 100, CATALOG_VALUE_PRECISION);
             if (isset($discount['MAX_VALUE']) && $discount['MAX_VALUE'] > 0) {
                 if ($discountValue > $discount['MAX_VALUE']) {
                     $discountValue = $discount['MAX_VALUE'];
                 }
             }
             $discountValue = roundEx($discountValue, CATALOG_VALUE_PRECISION);
             $product['PRICE'] -= $discountValue;
             $product['DISCOUNT_PRICE'] += $discountValue;
             if (!empty($product['DISCOUNT_RESULT'])) {
                 $product['DISCOUNT_RESULT']['BASKET'][0]['RESULT_VALUE'] = (string) abs($discountValue);
                 $product['DISCOUNT_RESULT']['BASKET'][0]['RESULT_UNIT'] = $product['CURRENCY'];
             }
             unset($discountValue);
             break;
         case Catalog\DiscountTable::VALUE_TYPE_FIX:
             $discount['VALUE'] = roundEx($discount['VALUE'], CATALOG_VALUE_PRECISION);
             $product['PRICE'] -= $discount['VALUE'];
             $product['DISCOUNT_PRICE'] += $discount['VALUE'];
             break;
         case Catalog\DiscountTable::VALUE_TYPE_SALE:
             $discount['VALUE'] = roundEx($discount['VALUE'], CATALOG_VALUE_PRECISION);
             $product['DISCOUNT_PRICE'] += $product['PRICE'] - $discount['VALUE'];
             $product['PRICE'] = $discount['VALUE'];
             break;
     }
 }
Exemple #26
0
function roundDB($value, $len=18, $dec=4)
{
	if($value>=0)
		$value = "0".$value;
	$value = roundEx(DoubleVal($value), $len);
	$value = sprintf("%01.".$dec."f", $value);
	if($len>0 && strlen($value)>$len-$dec)
		$value = trim(substr($value, 0, $len-$dec), ".");
	return $value;
}
Exemple #27
0
    $mrh_pass2 = CSalePaySystemAction::GetParamValue("ShopPassword2");
    if (strlen($mrh_pass2) <= 0) {
        $bCorrectPayment = False;
    }
    $strCheck = md5($out_summ . ":" . $inv_id . ":" . $mrh_pass2 . ':shp_payment_id=' . $paymentId);
    if ($bCorrectPayment && ToUpper($crc) != ToUpper($strCheck)) {
        $bCorrectPayment = False;
    }
    if ($bCorrectPayment) {
        $strPS_STATUS_DESCRIPTION = GetMessage('SALE_RES_NUMBER') . ": " . $inv_id;
        $strPS_STATUS_DESCRIPTION .= "; " . GetMessage('SALE_RES_DATEPAY') . ": " . date("d.m.Y H:i:s");
        if (isset($_REQUEST["IncCurrLabel"]) && strlen($_REQUEST["IncCurrLabel"]) > 0) {
            $strPS_STATUS_DESCRIPTION .= "; " . GetMessage('SASP_RES_PAY_TYPE') . ": " . $_REQUEST["IncCurrLabel"];
        }
        $strPS_STATUS_MESSAGE = GetMessage('SASP_RES_PAYED');
        $arFields = array("PS_STATUS" => "Y", "PS_STATUS_CODE" => "-", "PS_STATUS_DESCRIPTION" => $strPS_STATUS_DESCRIPTION, "PS_STATUS_MESSAGE" => $strPS_STATUS_MESSAGE, "PS_SUM" => $out_summ, "PS_CURRENCY" => $arOrder["CURRENCY"], "PS_RESPONSE_DATE" => new \Bitrix\Main\Type\DateTime());
        if (roundEx(CSalePaySystemAction::GetParamValue("SHOULD_PAY"), 2) == roundEx($out_summ, 2) && $changePayStatus == "Y") {
            $result = $payment->setField('PAID', 'Y');
            $APPLICATION->RestartBuffer();
            if ($result->isSuccess()) {
                $result = $payment->setFields($arFields);
                if ($result->isSuccess()) {
                    $result = $order->save();
                    if ($result->isSuccess()) {
                        echo "OK" . $arOrder["ID"];
                    }
                }
            }
        }
    }
}
             if ($arFind["find_payed_" . $k1] == "Y") {
                 $arY[] = roundEx($v["PAYED"][$k1], SALE_VALUE_PRECISION);
                 $arPayedY[$k1][] = roundEx($v["PAYED"][$k1], SALE_VALUE_PRECISION);
             }
             if ($arFind["find_allow_delivery_" . $k1] == "Y") {
                 $arY[] = roundEx($v["ALLOW_DELIVERY"][$k1], SALE_VALUE_PRECISION);
                 $arDelivY[$k1][] = roundEx($v["ALLOW_DELIVERY"][$k1], SALE_VALUE_PRECISION);
             }
             if ($arFind["find_canceled_" . $k1] == "Y") {
                 $arY[] = roundEx($v["CANCELED"][$k1], SALE_VALUE_PRECISION);
                 $arCancelY[$k1][] = roundEx($v["CANCELED"][$k1], SALE_VALUE_PRECISION);
             }
             foreach ($arStatus as $k2 => $v2) {
                 if ($arFind["find_status_" . $k2 . "_" . $k1] == "Y") {
                     $arY[] = roundEx($v["STATUS"][$k2][$k1], SALE_VALUE_PRECISION);
                     $arStatusY[$k2][$k1][] = roundEx($v["STATUS"][$k2][$k1], SALE_VALUE_PRECISION);
                 }
             }
         }
     }
 }
 $arrayY = GetArrayY($arY, $MinY, $MaxY, 10);
 if ($arFind["filter_by"] == "day") {
     $arrayX = GetArrayX($arX, $MinX, $MaxX);
 } elseif ($arFind["filter_by"] == "weekday") {
     $arrayX = $arX1;
     $MinX = 0;
     $MaxX = 6;
 } else {
     $arrayX = $arX1;
 }
Exemple #29
0
 protected function __ConvertOldFormat($strAction, &$arFields)
 {
     global $APPLICATION;
     $arMsg = array();
     $boolResult = true;
     $arNeedFields = array('LID', 'CURRENCY', 'DISCOUNT_TYPE', 'DISCOUNT_VALUE', 'PRICE_FROM', 'PRICE_TO');
     $arUpdateFields = array('DISCOUNT_VALUE', 'PRICE_FROM', 'PRICE_TO');
     $strAction = ToUpper($strAction);
     if (!array_key_exists('CONDITIONS', $arFields) && !array_key_exists('ACTIONS', $arFields)) {
         $strSiteCurrency = '';
         $boolUpdate = false;
         if ('UPDATE' == $strAction) {
             $boolNeedQuery = false;
             foreach ($arUpdateFields as &$strFieldID) {
                 if (array_key_exists($strFieldID, $arFields)) {
                     $boolUpdate = true;
                     break;
                 }
             }
             if (isset($strFieldID)) {
                 unset($strFieldID);
             }
             if ($boolUpdate) {
                 foreach ($arNeedFields as &$strFieldID) {
                     if (!array_key_exists($strFieldID, $arFields)) {
                         $boolNeedQuery = true;
                         break;
                     }
                 }
                 if (isset($strFieldID)) {
                     unset($strFieldID);
                 }
                 if ($boolNeedQuery) {
                     $rsDiscounts = CSaleDiscount::GetList(array(), array('ID' => $arFields['ID']), false, false, $arNeedFields);
                     if ($arDiscount = $rsDiscounts->Fetch()) {
                         foreach ($arNeedFields as &$strFieldID) {
                             if (!array_key_exists($strFieldID, $arFields)) {
                                 $arFields[$strFieldID] = $arDiscount[$strFieldID];
                             }
                         }
                         if (isset($strFieldID)) {
                             unset($strFieldID);
                         }
                     } else {
                         $boolUpdate = false;
                         $boolResult = false;
                         $arMsg[] = array('id' => 'ID', 'text' => Loc::getMessage('BT_MOD_SALE_ERR_DSC_ABSENT'));
                     }
                 }
             }
         }
         if ('ADD' == $strAction || $boolUpdate) {
             if (!array_key_exists('LID', $arFields)) {
                 $boolResult = false;
                 $arMsg[] = array('id' => 'LID', 'text' => Loc::getMessage('BT_MOD_SALE_ERR_DSC_SITE_ID_ABSENT'));
             } else {
                 $arFields['LID'] = strval($arFields['LID']);
                 if ('' == $arFields['LID']) {
                     $boolResult = false;
                     $arMsg[] = array('id' => 'LID', 'text' => Loc::getMessage('BT_MOD_SALE_ERR_DSC_SITE_ID_ABSENT'));
                 } else {
                     $rsSites = CSite::GetByID($arFields["LID"]);
                     if (!($arSite = $rsSites->Fetch())) {
                         $boolResult = false;
                         $arMsg[] = array('id' => 'LID', 'text' => Loc::getMessage('SKGD_NO_SITE', array('#ID#' => $arFields['LID'])));
                     } else {
                         $strSiteCurrency = CSaleLang::GetLangCurrency($arFields['LID']);
                     }
                 }
             }
             if (!array_key_exists('CURRENCY', $arFields)) {
                 $boolResult = false;
                 $arMsg[] = array('id' => 'CURRENCY', 'text' => Loc::getMessage('BT_MOD_SALE_ERR_DSC_CURRENCY_ABSENT'));
             } else {
                 $arFields['CURRENCY'] = strval($arFields['CURRENCY']);
                 if ('' == $arFields['CURRENCY']) {
                     $boolResult = false;
                     $arMsg[] = array('id' => 'CURRENCY', 'text' => Loc::getMessage('BT_MOD_SALE_ERR_DSC_CURRENCY_ABSENT'));
                 } else {
                     if (!($arCurrency = CCurrency::GetByID($arFields["CURRENCY"]))) {
                         $boolResult = false;
                         $arMsg[] = array('id' => 'CURRENCY', 'text' => Loc::getMessage('SKGD_NO_CURRENCY', array('#ID#' => $arFields['CURRENCY'])));
                     }
                 }
             }
             if (!array_key_exists("DISCOUNT_TYPE", $arFields)) {
                 $boolResult = false;
                 $arMsg[] = array('id' => 'DISCOUNT_TYPE', 'text' => Loc::getMessage('BT_MOD_SALE_ERR_DSC_TYPE_ABSENT'));
             } else {
                 $arFields["DISCOUNT_TYPE"] = strval($arFields["DISCOUNT_TYPE"]);
                 if (CSaleDiscount::OLD_DSC_TYPE_PERCENT != $arFields["DISCOUNT_TYPE"] && CSaleDiscount::OLD_DSC_TYPE_FIX != $arFields["DISCOUNT_TYPE"]) {
                     $boolResult = false;
                     $arMsg[] = array('id' => 'DISCOUNT_TYPE', 'text' => Loc::getMessage('BT_MOD_SALE_ERR_DSC_TYPE_BAD'));
                 }
             }
             if (!array_key_exists('DISCOUNT_VALUE', $arFields)) {
                 $boolResult = false;
                 $arMsg[] = array('id' => 'DISCOUNT_VALUE', 'text' => Loc::getMessage('BT_MOD_SALE_ERR_DSC_VALUE_ABSENT'));
             } else {
                 $arFields['DISCOUNT_VALUE'] = (double) str_replace(',', '.', $arFields['DISCOUNT_VALUE']);
                 if (0 >= $arFields['DISCOUNT_VALUE']) {
                     $boolResult = false;
                     $arMsg[] = array('id' => 'DISCOUNT_VALUE', 'text' => Loc::getMessage('BT_MOD_SALE_ERR_DSC_VALUE_BAD'));
                 }
             }
             if ($boolResult) {
                 $arConditions = array('CLASS_ID' => 'CondGroup', 'DATA' => array('All' => 'AND', 'True' => 'True'), 'CHILDREN' => array());
                 $arActions = array('CLASS_ID' => 'CondGroup', 'DATA' => array('All' => 'AND', 'True' => 'True'), 'CHILDREN' => array());
                 $boolCurrency = $arFields['CURRENCY'] == $strSiteCurrency;
                 if (array_key_exists('PRICE_FROM', $arFields)) {
                     $arFields["PRICE_FROM"] = str_replace(",", ".", strval($arFields["PRICE_FROM"]));
                     $arFields["PRICE_FROM"] = doubleval($arFields["PRICE_FROM"]);
                     if (0 < $arFields["PRICE_FROM"]) {
                         $dblValue = roundEx($boolCurrency ? $arFields['PRICE_FROM'] : CCurrencyRates::ConvertCurrency($arFields['PRICE_FROM'], $arFields['CURRENCY'], $strSiteCurrency), SALE_VALUE_PRECISION);
                         $arConditions['CHILDREN'][] = array('CLASS_ID' => 'CondBsktAmtGroup', 'DATA' => array('logic' => 'EqGr', 'Value' => (string) $dblValue, 'All' => 'AND'), 'CHILDREN' => array());
                         $arFields["PRICE_FROM"] = $dblValue;
                     }
                 }
                 if (array_key_exists('PRICE_TO', $arFields)) {
                     $arFields["PRICE_TO"] = str_replace(",", ".", strval($arFields["PRICE_TO"]));
                     $arFields["PRICE_TO"] = doubleval($arFields["PRICE_TO"]);
                     if (0 < $arFields["PRICE_TO"]) {
                         $dblValue = roundEx($boolCurrency ? $arFields['PRICE_TO'] : CCurrencyRates::ConvertCurrency($arFields['PRICE_TO'], $arFields['CURRENCY'], $strSiteCurrency), SALE_VALUE_PRECISION);
                         $arConditions['CHILDREN'][] = array('CLASS_ID' => 'CondBsktAmtGroup', 'DATA' => array('logic' => 'EqLs', 'Value' => (string) $dblValue, 'All' => 'AND'), 'CHILDREN' => array());
                         $arFields["PRICE_TO"] = $dblValue;
                     }
                 }
                 if (self::OLD_DSC_TYPE_PERCENT == $arFields['DISCOUNT_TYPE']) {
                     $arActions['CHILDREN'][] = array('CLASS_ID' => 'ActSaleBsktGrp', 'DATA' => array('Type' => 'Discount', 'Value' => (string) roundEx($arFields['DISCOUNT_VALUE'], SALE_VALUE_PRECISION), 'Unit' => 'Perc', 'All' => 'AND'), 'CHILDREN' => array());
                 } else {
                     $dblValue = roundEx($boolCurrency ? $arFields['DISCOUNT_VALUE'] : CCurrencyRates::ConvertCurrency($arFields['DISCOUNT_VALUE'], $arFields['CURRENCY'], $strSiteCurrency), SALE_VALUE_PRECISION);
                     $arActions['CHILDREN'][] = array('CLASS_ID' => 'ActSaleBsktGrp', 'DATA' => array('Type' => 'Discount', 'Value' => (string) $dblValue, 'Unit' => 'CurAll', 'All' => 'AND'), 'CHILDREN' => array());
                     $arFields['DISCOUNT_VALUE'] = $dblValue;
                 }
                 $arFields['CONDITIONS'] = $arConditions;
                 $arFields['ACTIONS'] = $arActions;
                 $arFields['CURRENCY'] = $strSiteCurrency;
             } else {
                 $obError = new CAdminException($arMsg);
                 $APPLICATION->ThrowException($obError);
             }
         }
     }
     return $boolResult;
 }
Exemple #30
0
 /**
  * Convert discount data to other currency (sale currency).
  *
  * @param array &$discount				Discout data.
  * @param string $currency				New currency.
  * @return void
  */
 public static function convertCurrency(&$discount, $currency)
 {
     $currency = Currency\CurrencyManager::checkCurrencyID($currency);
     if ($currency === false || empty($discount) || !is_array($discount)) {
         return;
     }
     if (!isset($discount['VALUE_TYPE']) || !isset($discount['CURRENCY']) || $discount['CURRENCY'] == $currency) {
         return;
     }
     switch ($discount['VALUE_TYPE']) {
         case self::VALUE_TYPE_FIX:
         case self::VALUE_TYPE_SALE:
             $discount['VALUE'] = roundEx(\CCurrencyRates::convertCurrency($discount['VALUE'], $discount['CURRENCY'], $currency), CATALOG_VALUE_PRECISION);
             $discount['CURRENCY'] = $currency;
             break;
         case self::VALUE_TYPE_PERCENT:
             if ($discount['MAX_DISCOUNT'] > 0) {
                 $discount['MAX_DISCOUNT'] = roundEx(\CCurrencyRates::convertCurrency($discount['MAX_DISCOUNT'], $discount['CURRENCY'], $currency), CATALOG_VALUE_PRECISION);
             }
             $discount['CURRENCY'] = $currency;
             break;
     }
 }