예제 #1
2
/**
 * [addOrder функция добавления заказа]
 * @param array $arParams
 * @return array or false
 */
function addOrder($arParams)
{
    if (!CModule::IncludeModule('sale')) {
        return false;
    }
    global $USER;
    global $DB;
    $addCommentsOrder = false;
    $commentForManager = "";
    updateBasketPreOrder();
    // обновляем корзину
    $arBasketItems = array();
    $dbBasketItems = CSaleBasket::GetList(array("NAME" => "ASC", "ID" => "ASC"), array("FUSER_ID" => CSaleBasket::GetBasketUserID(), "LID" => SITE_ID, "ORDER_ID" => "NULL"), false, false, array("ID", "CALLBACK_FUNC", "MODULE", "PRODUCT_ID", "QUANTITY", "DELAY", "CAN_BUY", "PRICE", "WEIGHT", "NAME", "CURRENCY", "CATALOG_XML_ID", "VAT_RATE", "NOTES", "DISCOUNT_PRICE", "PRODUCT_PROVIDER_CLASS", "DIMENSIONS", "TYPE", "SET_PARENT_ID", "DETAIL_PAGE_URL"));
    while ($arItem = $dbBasketItems->Fetch()) {
        $arPropItem = getItemCart($arItem["PRODUCT_ID"]);
        $db_res = CSaleBasket::GetPropsList(array("SORT" => "ASC", "NAME" => "ASC"), array("BASKET_ID" => $arItem['ID']), false, array());
        while ($ar_res = $db_res->Fetch()) {
            if ($ar_res["CODE"] == "DEPOSIT" && $ar_res["VALUE"] == "N") {
                $addCommentsOrder = true;
            }
        }
        $arBasketItems[] = $arItem;
        $arItem["ARTIKUL"] = $arPropItem["PROPERTY_ARTIKUL_VALUE"];
        $strOrderList .= '<a href="http://' . $_SERVER["HTTP_HOST"] . $arItem["DETAIL_PAGE_URL"] . '">' . $arItem["ARTIKUL"] . '</a> ' . $arItem["NAME"] . ' - ' . $arItem["QUANTITY"] * 1 . ' шт. x ' . SaleFormatCurrency($arItem["PRICE"], $arItem["CURRENCY"]);
        $strOrderList .= "<br />";
        $allDiscountItems += $arItem["DISCOUNT_PRICE"];
    }
    if (!$arBasketItems) {
        return false;
    }
    $arOrderDat = CSaleOrder::DoCalculateOrder(SITE_ID, $USER->GetID(), $arBasketItems, 1, $arUserResult["ORDER_PROP"], $arParams["DELIVERY_ID"], $arParams["PAY_SYSTEM_ID"], array(), $arErrors, $arWarnings);
    $arOrderDat["ORDER_PROP"][20] = $arParams["ORDER_PROP_20"];
    $arOrderDat["ORDER_PROP"][7] = $arParams["ORDER_PROP_7"];
    $arOrderDat["ORDER_PROP"][3] = $arParams["ORDER_PROP_3"];
    //echo "<pre>";print_r($PRICE);echo "</pre>";die();
    //echo "<pre>";print_r($arOrderDat);echo "</pre>";die();
    //echo "<pre>";print_r($arParams);echo "</pre>";die();
    $arFields = array("LID" => SITE_ID, "PERSON_TYPE_ID" => 1, "PAYED" => "N", "CANCELED" => "N", "STATUS_ID" => "N", "PRICE" => $arOrderDat["ORDER_PRICE"], "CURRENCY" => $arOrderDat["CURRENCY"], "USER_ID" => IntVal($USER->GetID()), "PAY_SYSTEM_ID" => $arOrderDat["PAY_SYSTEM_ID"], "PRICE_DELIVERY" => $arOrderDat["PRICE_DELIVERY"], "DELIVERY_ID" => $arOrderDat["DELIVERY_ID"], "DISCOUNT_VALUE" => $arOrderDat["DISCOUNT_VALUE"], "TAX_VALUE" => $arOrderDat["TAX_VALUE"], "DELIVERY_LOCATION" => $arOrderDat["DELIVERY_LOCATION"], "USER_DESCRIPTION" => $arParams["ORDER_DESCRIPTION"], "COMMENTS" => $commentForManager);
    $ORDER_ID = (int) CSaleOrder::DoSaveOrder($arOrderDat, $arFields, 0, $arResult["ERROR"]);
    if ($ORDER_ID > 0) {
        $arOrder = getOrder($ORDER_ID);
        // для менеджера
        if ($addCommentsOrder === true && $arParams["PAY_SYSTEM_ID"] == 10) {
            // сообщение для менеджера
            $commentForManager .= 'Выбран способ оплаты PayKeeper, но в заказе есть товары "По запросу".';
            $commentForManager .= "\n";
            $commentForManager .= "Ссылка для оплаты: http://" . $_SERVER["HTTP_HOST"] . "/personal/order/payment/?ORDER_ID=" . $ORDER_ID;
            $arFields = array("COMMENTS" => $commentForManager);
            CSaleOrder::Update($ORDER_ID, $arFields);
        }
        // отправляем письмо
        $arFieldsEvent = array("ORDER_ID" => getNumberOrder($ORDER_ID), "ORDER_DATE" => Date($DB->DateFormatToPHP(CLang::GetDateFormat("SHORT", SITE_ID))), "ORDER_USER" => $USER->GetFormattedName(false), "PRICE" => SaleFormatCurrency($arOrderDat["ORDER_PRICE"], $arOrderDat["CURRENCY"]), "BCC" => COption::GetOptionString("sale", "order_email", "order@" . $SERVER_NAME), "EMAIL" => strlen($arUserResult["USER_EMAIL"]) > 0 ? $arUserResult["USER_EMAIL"] : $USER->GetEmail(), "ORDER_LIST" => $strOrderList, "SALE_EMAIL" => COption::GetOptionString("sale", "order_email", "order@" . $SERVER_NAME), "DISCOUNT" => $allDiscountItems . " руб.", "DELIVERY_PRICE" => "", "DELIVERY_TYPE" => getDeliveryName($arOrderDat["DELIVERY_ID"]), "ADDRESS" => strlen($arParams["ORDER_PROP_7"]) > 0 ? $arParams["ORDER_PROP_7"] : "Адрес не указан", "COMMENT" => strlen($arParams["ORDER_DESCRIPTION"]) > 0 ? $arParams["ORDER_DESCRIPTION"] : "Нет комментария");
        //Формируем писмо для отправки менеджеру
        switch ($arParams["PAY_SYSTEM_ID"]) {
            case 10:
                $price_method = 'Оплата банковской картой VISA, MASTERCARD, MAESTRO';
                break;
            case 8:
                $price_method = 'Безналичный расчет';
                break;
            case 1:
                $price_method = 'Наличными при получении';
                break;
        }
        $rsGroups = CGroup::GetList($by = "c_sort", $order = "asc", array("ID" => implode('|', $USER->GetUserGroupArray())));
        $groups = array();
        if (intval($rsGroups->SelectedRowsCount()) > 0) {
            while ($arGroups = $rsGroups->Fetch()) {
                if ((int) $arGroups['ID'] != 2 && (int) $arGroups['ID'] != 3 && (int) $arGroups['ID'] != 4) {
                    $groups[] = $arGroups['NAME'];
                }
            }
        }
        $arFieldsManager = array('NUMBER' => getNumberOrder($ORDER_ID), 'DATE' => Date($DB->DateFormatToPHP(CLang::GetDateFormat("SHORT", SITE_ID))), 'SELLER_TYPE' => implode(',', $groups), 'FIO' => $USER->GetFormattedName(false), 'PHONE' => strlen($arParams["ORDER_PROP_3"]) > 0 ? $arParams["ORDER_PROP_3"] : "Телефон не указан", 'EMAIL' => $USER->GetEmail(), 'ADRESS' => strlen($arParams["ORDER_PROP_7"]) > 0 ? $arParams["ORDER_PROP_7"] : "Адрес не указан", 'DOSTAVKA' => getDeliveryName($arOrderDat["DELIVERY_ID"]), 'PRICE_METHOD' => $price_method, 'ORDERS' => $strOrderList . '<br />Итого: ' . $arOrderDat["ORDER_PRICE"], 'DISCOUNT' => $allDiscountItems . " руб.", 'COMMENT' => strlen($arParams["ORDER_DESCRIPTION"]) > 0 ? $arParams["ORDER_DESCRIPTION"] : "Нет комментария");
        $eventName = "SALE_NEW_ORDER";
        $eventNameManager = "FORM_FILLING_NEW_ORDER";
        $bSend = true;
        foreach (GetModuleEvents("sale", "OnOrderNewSendEmail", true) as $arEvent) {
            if (ExecuteModuleEventEx($arEvent, array($arResult["ORDER_ID"], &$eventName, &$arFields)) === false) {
                $bSend = false;
            }
        }
        if ($bSend) {
            $event = new CEvent();
            $event->Send($eventName, SITE_ID, $arFieldsEvent, "N");
            $event->Send($eventNameManager, SITE_ID, $arFieldsManager, "N");
        }
        return $ORDER_ID;
    }
    return false;
}
예제 #2
0
			$arAdditionalFields['ADDITIONAL_INFO'] = $str_ADDITIONAL_INFO;
		}

		if (!empty($arOrder))
		{
			$arErrors = array();
			$OrderNewSendEmail = false;

			$arOldOrder = CSaleOrder::GetByID($ID);

			if ($ID <= 0 || $arOldOrder["STATUS_ID"] == $str_STATUS_ID)
				$arAdditionalFields["STATUS_ID"] = $str_STATUS_ID;

			$bSaveBarcodes = ($hasSavedBarcodes || $DEDUCTED == "Y") ? true : false;

			$tmpID = CSaleOrder::DoSaveOrder($arOrder, $arAdditionalFields, $ID, $arErrors, $arCoupon, $arStoreBarcodeOrderFormData, $bSaveBarcodes);

			//delete from basket
			if ($tmpID > 0)
			{
				foreach($_POST["PRODUCT"] as $key => $val)
				{
					if (!isset($val["BASKET_ID"]) && intVal($val["BASKET_ID"]) <= 0)
					{
						$dbBasket = CSaleBasket::GetList(
							array(),
							array(
								"ORDER_ID" => "NULL",
								"PRODUCT_ID" => $val["PRODUCT_ID"],
								"USER_ID" => $str_USER_ID,
								"LID" => $LID
예제 #3
0
 if ($PAYSYSTEM_ID == "") {
     $errorMessage .= GetMessage("SBB_ERR_PAYSYSTEM") . "<br>";
 }
 if ('' == $errorMessage) {
     $arAdditionalFields = array("LID" => SITE_ID, "STATUS_ID" => "N", "PAYED" => "N", "CANCELED" => "N", "USER_DESCRIPTION" => $ORDER_DESCRIPTION);
     $affiliateID = CSaleAffiliate::GetAffiliate();
     if ($affiliateID > 0) {
         $dbAffiliat = CSaleAffiliate::GetList(array(), array("SITE_ID" => SITE_ID, "ID" => $affiliateID));
         $arAffiliates = $dbAffiliat->Fetch();
         if (count($arAffiliates) > 1) {
             $arAdditionalFields["AFFILIATE_ID"] = $affiliateID;
         }
     } else {
         $arAdditionalFields["AFFILIATE_ID"] = false;
     }
     $ORDER_ID = CSaleOrder::DoSaveOrder($arBasketItems, $arAdditionalFields, 0, $arErrors);
     if ($ORDER_ID > 0 && empty($arErrors)) {
         CSaleBasket::OrderBasket($ORDER_ID, CSaleBasket::GetBasketUserID(), SITE_ID, false);
         /*send mail order*/
         $strOrderList = "";
         foreach ($arBasketItems["BASKET_ITEMS"] as $val) {
             if (CSaleBasketHelper::isSetItem($val)) {
                 continue;
             }
             $strOrderList .= $val["NAME"] . " - " . $val["QUANTITY"] . " " . GetMessage("SOA_SHT") . ": " . SaleFormatCurrency($val["PRICE"], $arBasketItems["CURRENCY"]);
             $strOrderList .= "\n";
         }
         $arFields = array("ORDER_ID" => $ORDER_ID, "ORDER_DATE" => Date($DB->DateFormatToPHP(CLang::GetDateFormat("SHORT", SITE_ID))), "ORDER_USER" => strlen($payerName) > 0 ? $payerName : $USER->GetFullName(), "PRICE" => SaleFormatCurrency($arBasketItems["PRICE"], $arBasketItems["CURRENCY"]), "BCC" => COption::GetOptionString("sale", "order_email", "order@" . $SERVER_NAME), "EMAIL" => strlen($payerEMail) > 0 ? $payerEMail : $USER->GetEmail(), "ORDER_LIST" => $strOrderList, "SALE_EMAIL" => COption::GetOptionString("sale", "order_email", "order@" . $SERVER_NAME), "DELIVERY_PRICE" => $arBasketItems["PRICE_DELIVERY"]);
         $eventName = "SALE_NEW_ORDER";
         $bSend = true;
         foreach (GetModuleEvents("sale", "OnOrderNewSendEmail", true) as $arEvent) {
예제 #4
0
 }
 // add Guest ID
 if (CModule::IncludeModule("statistic")) {
     $arFields["STAT_GID"] = CStatistic::GetEventParam();
 }
 $affiliateID = CSaleAffiliate::GetAffiliate();
 if ($affiliateID > 0) {
     $dbAffiliat = CSaleAffiliate::GetList(array(), array("SITE_ID" => SITE_ID, "ID" => $affiliateID));
     $arAffiliates = $dbAffiliat->Fetch();
     if (count($arAffiliates) > 1) {
         $arFields["AFFILIATE_ID"] = $affiliateID;
     }
 } else {
     $arFields["AFFILIATE_ID"] = false;
 }
 $arResult["ORDER_ID"] = CSaleOrder::DoSaveOrder($arOrderDat, $arFields, 0, $arResult["ERROR"]);
 $arResult["ORDER_ID"] = IntVal($arResult["ORDER_ID"]);
 if ($arResult["ORDER_ID"] > 0 && empty($arResult["ERROR"])) {
     $arOrder = CSaleOrder::GetByID($arResult["ORDER_ID"]);
     CSaleBasket::OrderBasket($arResult["ORDER_ID"], CSaleBasket::GetBasketUserID(), SITE_ID, false);
     $arResult["ACCOUNT_NUMBER"] = $arResult["ORDER_ID"] <= 0 ? $arResult["ORDER_ID"] : $arOrder["ACCOUNT_NUMBER"];
 }
 $withdrawSum = 0.0;
 if (empty($arResult["ERROR"])) {
     if ($arResult["PAY_FROM_ACCOUNT"] == "Y" && $arUserResult["PAY_CURRENT_ACCOUNT"] == "Y" && ($arParams["ONLY_FULL_PAY_FROM_ACCOUNT"] == "Y" && DoubleVal($arResult["USER_ACCOUNT"]["CURRENT_BUDGET"]) >= DoubleVal($orderTotalSum) || $arParams["ONLY_FULL_PAY_FROM_ACCOUNT"] != "Y")) {
         $withdrawSum = CSaleUserAccount::Withdraw($USER->GetID(), $orderTotalSum, $arResult["BASE_LANG_CURRENCY"], $arResult["ORDER_ID"]);
         if ($withdrawSum > 0) {
             $arFields = array("SUM_PAID" => $withdrawSum, "USER_ID" => $USER->GetID());
             CSaleOrder::Update($arResult["ORDER_ID"], $arFields);
             if ($withdrawSum == $orderTotalSum) {
                 CSaleOrder::PayOrder($arResult["ORDER_ID"], "Y", False, False);
예제 #5
0
	function nodeHandler(CDataXML $value)
	{
		$value = $value->GetArray();

		if(!empty($value[GetMessage("CC_BSC1_DOCUMENT")]))
		{
			$value = $value[GetMessage("CC_BSC1_DOCUMENT")];

			$arOrder = $this->collectOrderInfo($value);

			if(!empty($arOrder))
			{
				if(strlen($arOrder["ID"]) <= 0 && strlen($arOrder["ID_1C"]) > 0)//try to search order from 1C
				{
					$dbOrder = CSaleOrder::GetList(array("ID" => "DESC"), array("ID_1C" => $arOrder["ID_1C"]), false, false, array("ID", "ID_1C"));
					if($orderInfo = $dbOrder->Fetch())
					{
						$arOrder["ID"] = $orderInfo["ID"];
					}
				}
				if(strlen($arOrder["ID"]) > 0) // exists site order
				{
					$dbOrder = CSaleOrder::GetList(array(), array("ACCOUNT_NUMBER" => $arOrder["ID"]), false, false, array("ID", "LID", "PERSON_TYPE_ID", "PAYED", "DATE_PAYED", "CANCELED", "DATE_CANCELED", "REASON_CANCELED", "STATUS_ID", "DATE_STATUS", "PAY_VOUCHER_NUM", "PAY_VOUCHER_DATE", "PRICE_DELIVERY", "ALLOW_DELIVERY", "DATE_ALLOW_DELIVERY", "PRICE", "CURRENCY", "DISCOUNT_VALUE", "USER_ID", "PAY_SYSTEM_ID", "DELIVERY_ID", "DATE_INSERT", "DATE_INSERT_FORMAT", "DATE_UPDATE", "USER_DESCRIPTION", "ADDITIONAL_INFO", "COMMENTS", "TAX_VALUE", "DELIVERY_DOC_NUM", "DELIVERY_DOC_DATE", "STORE_ID", "ACCOUNT_NUMBER", "VERSION", "VERSION_1C", "ID_1C"));
					if($orderInfo = $dbOrder->Fetch())
					{
						if($arOrder["VERSION_1C"] != $orderInfo["VERSION_1C"] || (strlen($orderInfo["VERSION_1C"]) <= 0 || strlen($arOrder["VERSION_1C"]) <= 0)) // skip update if the same version
						{
							$arOrderFields = array();
							$orderId = $orderInfo["ID"];
							CSaleOrderChange::AddRecord($orderId, "ORDER_1C_IMPORT");
							if($arOrder["ID_1C"] != $orderInfo["ID_1C"])
								$arOrderFields["ID_1C"] = $arOrder["ID_1C"];
							$arOrderFields["VERSION_1C"] = $arOrder["VERSION_1C"];

							if($orderInfo["PAYED"] != "Y" && $orderInfo["ALLOW_DELIVERY"] != "Y" && $orderInfo["STATUS_ID"] != "F")
							{
								$dbOrderTax = CSaleOrderTax::GetList(
									array(),
									array("ORDER_ID" => $orderId),
									false,
									false,
									array("ID", "TAX_NAME", "VALUE", "VALUE_MONEY", "CODE", "IS_IN_PRICE")
								);
								$bTaxFound = false;
								if($arOrderTax = $dbOrderTax->Fetch())
								{
									$bTaxFound = true;
									if(IntVal($arOrderTax["VALUE_MONEY"]) != IntVal($arOrder["TAX"]["VALUE_MONEY"]) || IntVal($arOrderTax["VALUE"]) != IntVal($arOrder["TAX"]["VALUE"]) || ($arOrderTax["IS_IN_PRICE"] != $arOrder["TAX"]["IS_IN_PRICE"]))
									{
										if(IntVal($arOrder["TAX"]["VALUE"])>0)
										{
											$arFields = Array(
												"TAX_NAME" => $arOrder["TAX"]["NAME"],
												"ORDER_ID" => $orderId,
												"VALUE" => $arOrder["TAX"]["VALUE"],
												"IS_PERCENT" => "Y",
												"IS_IN_PRICE" => $arOrder["TAX"]["IS_IN_PRICE"],
												"VALUE_MONEY" => $arOrder["TAX"]["VALUE_MONEY"],
												"CODE" => "VAT1C",
												"APPLY_ORDER" => "100"
											);
											CSaleOrderTax::Update($arOrderTax["ID"], $arFields);
											$arOrderFields["TAX_VALUE"] = $arOrder["TAX"]["VALUE_MONEY"];
										}
										else
										{
											CSaleOrderTax::Delete($arOrderTax["ID"]);
											$arOrderFields["TAX_VALUE"] = 0;
										}
									}
								}

								if(!$bTaxFound)
								{
									if(IntVal($arOrder["TAX"]["VALUE"])>0)
									{
										$arFields = Array(
											"TAX_NAME" => $arOrder["TAX"]["NAME"],
											"ORDER_ID" => $orderId,
											"VALUE" => $arOrder["TAX"]["VALUE"],
											"IS_PERCENT" => "Y",
											"IS_IN_PRICE" => $arOrder["TAX"]["IS_IN_PRICE"],
											"VALUE_MONEY" => $arOrder["TAX"]["VALUE_MONEY"]
										);
										CSaleOrderTax::Add($arFields);
										$arOrderFields["TAX_VALUE"] = $arOrder["TAX"]["VALUE_MONEY"];
									}
								}

								$arShoppingCart = array();
								$bNeedUpdate = false;
								$dbBasket = CSaleBasket::GetList(
									array("NAME" => "ASC"),
									array("ORDER_ID" => $orderId),
									false,
									false,
									array(
										"ID",
										"QUANTITY",
										"CANCEL_CALLBACK_FUNC",
										"MODULE",
										"PRODUCT_ID",
										"PRODUCT_PROVIDER_CLASS",
										"RESERVED",
										"RESERVE_QUANTITY",
										"TYPE",
										"SET_PARENT_ID",
										"PRICE",
										"VAT_RATE",
										"DISCOUNT_PRICE",
										"PRODUCT_XML_ID",
									)
								);

								while ($arBasket = $dbBasket->Fetch())
								{
									$arFields = Array();
									if(!empty($arOrder["items"][$arBasket["PRODUCT_XML_ID"]]))
									{
										if($arBasket["QUANTITY"] != $arOrder["items"][$arBasket["PRODUCT_XML_ID"]]["QUANTITY"])
											$arFields["QUANTITY"] = $arOrder["items"][$arBasket["PRODUCT_XML_ID"]]["QUANTITY"];
										if($arBasket["PRICE"] != $arOrder["items"][$arBasket["PRODUCT_XML_ID"]]["PRICE"])
											$arFields["PRICE"] = $arOrder["items"][$arBasket["PRODUCT_XML_ID"]]["PRICE"];
										if($arBasket["VAT_RATE"] != $arOrder["items"][$arBasket["PRODUCT_XML_ID"]]["VAT_RATE"])
											$arFields["VAT_RATE"] = $arOrder["items"][$arBasket["PRODUCT_XML_ID"]]["VAT_RATE"];
										if($arBasket["DISCOUNT_PRICE"] != $arOrder["items"][$arBasket["PRODUCT_XML_ID"]]["DISCOUNT_PRICE"])
											$arFields["DISCOUNT_PRICE"] = $arOrder["items"][$arBasket["PRODUCT_XML_ID"]]["DISCOUNT_PRICE"];

										if(count($arFields)>0)
										{
											$arFields["ID"] = $arBasket["ID"];
											if(DoubleVal($arFields["QUANTITY"]) <= 0)
												$arFields["QUANTITY"] = $arBasket["QUANTITY"];
											$bNeedUpdate = true;
											$arShoppingCart[] = $arFields;
										}
										else
										{
											$arShoppingCart[] = $arBasket;
										}
										//CSaleBasket::Update($arBasket["ID"], $arFields);

										$arOrder["items"][$arBasket["PRODUCT_XML_ID"]]["CHECKED"] = "Y";
									}
									else
									{
										if($arOrder["TRAITS"][GetMessage("CC_BSC1_CANCELED")] != "true" && $orderInfo["CANCELED"] == "N")
										{
											$bNeedUpdate = true;
											//CSaleBasket::Delete($arBasket["ID"]);
										}
									}
								}

								if(!empty($arOrder["items"]))
								{
									foreach ($arOrder["items"] as $itemID => $arItem)
									{
										if ($arItem["CHECKED"] != "Y")
										{
											if ($arItem["TYPE"] == GetMessage("CC_BSC1_ITEM"))
											{
												if ($arBasketFields = $this->prepareProduct4Basket($itemID, $arItem, $orderId, $orderInfo))
												{
													$arShoppingCart[] = $arBasketFields;
													$bNeedUpdate = true;
												}
											}
											elseif ($arItem["TYPE"] == GetMessage("CC_BSC1_SERVICE"))
											{
												if (IntVal($arItem["PRICE"]) != IntVal($orderInfo["PRICE_DELIVERY"]))
													$arOrderFields["PRICE_DELIVERY"] = $arItem["PRICE"];
											}
										}
									}
								}

								if($bNeedUpdate)
								{
									$arErrors = array();
									CSaleBasket::DoSaveOrderBasket($orderId, $orderInfo["LID"], $orderInfo["USER_ID"], $arShoppingCart, $arErrors);
								}

								if(DoubleVal($arOrder["AMOUNT"]) > 0 && $arOrder["AMOUNT"] != $orderInfo["PRICE"])
									$arOrderFields["PRICE"] = $arOrder["AMOUNT"];
								if(DoubleVal($orderInfo["DISCOUNT_VALUE"]) > 0)
									$arOrderFields["DISCOUNT_VALUE"] = 0;
								if(strlen($arOrder["COMMENT"]) > 0 && $arOrder["COMMENT"] != $orderInfo["COMMENTS"])
									$arOrderFields["COMMENTS"] = $arOrder["COMMENT"];
								$arOrderFields["UPDATED_1C"] = "Y";
								if(!empty($arOrderFields))
									CSaleOrder::Update($orderId, $arOrderFields);
							}
							else
							{
								$this->strError .= "\n".GetMessage("CC_BSC1_FINAL_NOT_EDIT", Array("#ID#" => $orderId));
							}
						}

						$arAditFields = Array();
						if($arOrder["TRAITS"][GetMessage("CC_BSC1_CANCELED")] == "true")
						{
							if($orderInfo["CANCELED"] == "N")
								CSaleOrder::CancelOrder($orderInfo["ID"], "Y", $arOrder["COMMENT"]);
							$arAditFields["UPDATED_1C"] = "Y";
						}
						else
						{
							if(strlen($arOrder["TRAITS"][GetMessage("CC_BSC1_1C_PAYED_DATE")])>1)
							{
								if($orderInfo["PAYED"]=="N")
									CSaleOrder::PayOrder($orderInfo["ID"], "Y");
								$arAditFields["PAY_VOUCHER_DATE"] = CDatabase::FormatDate(str_replace("T", " ", $arOrder["TRAITS"][GetMessage("CC_BSC1_1C_PAYED_DATE")]), "YYYY-MM-DD HH:MI:SS", CLang::GetDateFormat("FULL", LANG));
								if(strlen($arOrder["TRAITS"][GetMessage("CC_BSC1_1C_PAYED_NUM")])>0)
									$arAditFields["PAY_VOUCHER_NUM"] = $arOrder["TRAITS"][GetMessage("CC_BSC1_1C_PAYED_NUM")];
								$arAditFields["UPDATED_1C"] = "Y";
							}

							if(strlen($arOrder["TRAITS"][GetMessage("CC_BSC1_1C_DELIVERY_DATE")])>1)
							{
								if($orderInfo["ALLOW_DELIVERY"]=="N")
									CSaleOrder::DeliverOrder($orderInfo["ID"], "Y");
								$arAditFields["DATE_ALLOW_DELIVERY"] = CDatabase::FormatDate(str_replace("T", " ", $arOrder["TRAITS"][GetMessage("CC_BSC1_1C_DELIVERY_DATE")]), "YYYY-MM-DD HH:MI:SS", CLang::GetDateFormat("FULL", LANG));
								if(strlen($this->arParams["FINAL_STATUS_ON_DELIVERY"])>0 && $orderInfo["STATUS_ID"] != "F" && $orderInfo["STATUS_ID"] != $this->arParams["FINAL_STATUS_ON_DELIVERY"])
									CSaleOrder::StatusOrder($orderInfo["ID"], $this->arParams["FINAL_STATUS_ON_DELIVERY"]);
								$arAditFields["UPDATED_1C"] = "Y";
							}
						}

						if(count($arAditFields)>0)
							CSaleOrder::Update($orderInfo["ID"], $arAditFields);
					}
					else
						$this->strError .= "\n".GetMessage("CC_BSC1_ORDER_NOT_FOUND", Array("#ID#" => $arOrder["ID"]));
				}
				elseif($this->arParams["IMPORT_NEW_ORDERS"] == "Y") // create new order (ofline 1C)
				{
					if(!empty($arOrder["AGENT"]) && strlen($arOrder["AGENT"]["ID"]) > 0)
					{
						$arOrder["PERSON_TYPE_ID"] = 0;
						$arOrder["USER_ID"] = 0;
						$arErrors = array();
						$dbUProp = CSaleOrderUserProps::GetList(array(), array("XML_ID" => $arOrder["AGENT"]["ID"]), false, false, array("ID", "NAME", "USER_ID", "PERSON_TYPE_ID", "XML_ID", "VERSION_1C"));
						if($arUProp = $dbUProp->Fetch())
						{
							$arOrder["USER_ID"] = $arUProp["USER_ID"];
							$arOrder["PERSON_TYPE_ID"] = $arUProp["PERSON_TYPE_ID"];
							$arOrder["USER_PROFILE_ID"] = $arUProp["ID"];
							$arOrder["USER_PROFILE_VERSION"] = $arUProp["VERSION_1C"];

							$dbUPropValue = CSaleOrderUserPropsValue::GetList(array(), array("USER_PROPS_ID" => $arUProp["ID"]));
							while($arUPropValue = $dbUPropValue->Fetch())
							{
								$arOrder["USER_PROPS"][$arUPropValue["ORDER_PROPS_ID"]] = $arUPropValue["VALUE"];
							}
						}
						else
						{
							if(strlen($arOrder["AGENT"]["ID"]) > 0)
							{
								$arAI = explode("#", $arOrder["AGENT"]["ID"]);
								if(IntVal($arAI[0]) > 0)
								{
									$dbUser = CUser::GetByID($arAI[0]);
									if($arU = $dbUser->Fetch())
									{
										if(htmlspecialcharsback(substr(htmlspecialcharsbx($arU["ID"]."#".$arU["LOGIN"]."#".$arU["LAST_NAME"]." ".$arU["NAME"]." ".$arU["SECOND_NAME"]), 0, 80)) == $arOrder["AGENT"]["ID"])
										{
											$arOrder["USER_ID"] = $arU["ID"];
										}
									}
								}
							}

							if(IntVal($arOrder["USER_ID"]) <= 0)
							{
								//create new user
								$arUser = array(
									"NAME"  => $arOrder["AGENT"]["ITEM_NAME"],
									"EMAIL" => $arOrder["AGENT"]["CONTACT"]["MAIL_NEW"],
								);

								if (strlen($arUser["NAME"]) <= 0)
									$arUser["NAME"] = $arOrder["AGENT"]["CONTACT"]["CONTACT_PERSON"];
								if (strlen($arUser["EMAIL"]) <= 0)
									$arUser["EMAIL"] = "buyer".time().GetRandomCode(2)."@".$_SERVER["SERVER_NAME"];
								$arOrder["USER_ID"] = CSaleUser::DoAutoRegisterUser($arUser["EMAIL"], $arUser["NAME"], $this->arParams["SITE_NEW_ORDERS"], $arErrors);
							}
						}

						if(empty($this->arPersonTypesIDs))
						{
							$dbPT = CSalePersonType::GetList(array(), array("ACTIVE" => "Y", "LIDS" => $this->arParams["SITE_NEW_ORDERS"]));
							while($arPT = $dbPT->Fetch())
							{
								$this->arPersonTypesIDs[] = $arPT["ID"];
							}
						}

						if(empty($this->arExportInfo))
						{
							$dbExport = CSaleExport::GetList(array(), array("PERSON_TYPE_ID" => $this->arPersonTypesIDs));
							while($arExport = $dbExport->Fetch())
							{
								$this->arExportInfo[$arExport["PERSON_TYPE_ID"]] = unserialize($arExport["VARS"]);
							}
						}

						if(IntVal($arOrder["PERSON_TYPE_ID"]) <= 0)
						{
							foreach($this->arExportInfo as $pt => $value)
							{
								if(
									(($value["IS_FIZ"] == "Y" && $arOrder["AGENT"]["TYPE"] == "FIZ")
									|| ($value["IS_FIZ"] == "N" && $arOrder["AGENT"]["TYPE"] != "FIZ"))
									)
									$arOrder["PERSON_TYPE_ID"] = $pt;
							}
						}

						if(IntVal($arOrder["PERSON_TYPE_ID"]) > 0)
						{
							$arAgent = $this->arExportInfo[$arOrder["PERSON_TYPE_ID"]];
							foreach($arAgent as $k => $v)
							{
								if((strlen($v["VALUE"]) <= 0 || $v["TYPE"] != "PROPERTY") && (empty($arOrder["USER_PROPS"]) || empty($arOrder["USER_PROPS"][$v["VALUE"]])))
									unset($arAgent[$k]);
							}

							if(IntVal($arOrder["USER_ID"]) > 0)
							{
								$orderFields = array(
									"SITE_ID" => $this->arParams["SITE_NEW_ORDERS"],
									"PERSON_TYPE_ID" => $arOrder["PERSON_TYPE_ID"],
									"PAYED" => "N",
									"CANCELED" => "N",
									"STATUS_ID" => "N",
									"PRICE" => $arOrder["AMOUNT"],
									"CURRENCY" => CSaleLang::GetLangCurrency($this->arParams["SITE_NEW_ORDERS"]),
									"USER_ID" => $arOrder["USER_ID"],
									"TAX_VALUE" => doubleval($arOrder["TAX"]["VALUE_MONEY"]),
									"COMMENTS" => $arOrder["COMMENT"],
									"BASKET_ITEMS" => array(),
									"TAX_LIST" => array(),
									"ORDER_PROP" => array(),
								);
								$arAditFields = array(
									"EXTERNAL_ORDER" => "Y",
									"ID_1C" => $arOrder["ID_1C"],
									"VERSION_1C" => $arOrder["VERSION_1C"],
									"UPDATED_1C" => "Y",
									"DATE_INSERT" => CDatabase::FormatDate($arOrder["DATE"]." ".$arOrder["TIME"], "YYYY-MM-DD HH:MI:SS", CLang::GetDateFormat("FULL", LANG)),
								);

								foreach($arOrder["items"] as $productID => $val)
								{
									$orderFields["BASKET_ITEMS"][] = $this->prepareProduct4Basket($productID, $val, false, $orderFields);
								}

								if(!empty($arOrder["TAX"]))
								{
									$orderFields["TAX_LIST"][] = array(
										"NAME" => $arOrder["TAX"]["NAME"],
										"IS_PERCENT" => "Y",
										"VALUE" => $arOrder["TAX"]["VALUE"],
										"VALUE_MONEY" => $arOrder["TAX"]["VALUE_MONEY"],
										"IS_IN_PRICE" => $arOrder["TAX"]["IS_IN_PRICE"],
									);
								}

								foreach($arAgent as $k => $v)
								{
									if(!empty($arOrder["ORDER_PROPS"][$k]))
									{
										$orderFields["ORDER_PROP"][$v["VALUE"]] = $arOrder["ORDER_PROPS"][$k];
									}
									if(empty($orderFields["ORDER_PROP"][$v["VALUE"]]) && !empty($arOrder["USER_PROPS"][$v["VALUE"]]))
									{
										$orderFields["ORDER_PROP"][$v["VALUE"]] = $arOrder["USER_PROPS"][$v["VALUE"]];
									}
								}

								if($arOrder["ID"] = CSaleOrder::DoSaveOrder($orderFields, $arAditFields, 0, $arErrors))
								{
									$arAditFields = array("UPDATED_1C" => "Y");
									CSaleOrder::Update($arOrder["ID"], $arAditFields);

									//add/update user profile
									if(IntVal($arOrder["USER_PROFILE_ID"]) > 0)
									{
										if($arOrder["USER_PROFILE_VERSION"] != $arOrder["AGENT"]["VERSION"])
											CSaleOrderUserProps::Update($arOrder["USER_PROFILE_ID"], array("VERSION_1C" => $arOrder["AGENT"]["VERSION"], "NAME" => $arOrder["AGENT"]["AGENT_NAME"]));
										$dbUPV = CSaleOrderUserPropsValue::GetList(array(), array("USER_PROPS_ID" =>$arOrder["USER_PROFILE_ID"]));
										while($arUPV = $dbUPV->Fetch())
										{
											$arOrder["AGENT"]["PROFILE_PROPS_VALUE"][$arUPV["ORDER_PROPS_ID"]] = array("ID" => $arUPV["ID"], "VALUE" => $arUPV["VALUE"]);
										}
									}

									if(IntVal($arOrder["USER_PROFILE_ID"]) <= 0 || (IntVal($arOrder["USER_PROFILE_ID"]) > 0 && $arOrder["USER_PROFILE_VERSION"] != $arOrder["AGENT"]["VERSION"]))
									{
										$dbOrderProperties = CSaleOrderProps::GetList(
											array("SORT" => "ASC"),
											array(
												"PERSON_TYPE_ID" => $arOrder["PERSON_TYPE_ID"],
												"ACTIVE" => "Y",
												"UTIL" => "N",
												"USER_PROPS" => "Y",
											),
											false,
											false,
											array("ID", "TYPE", "NAME", "CODE", "USER_PROPS", "SORT", "MULTIPLE")
										);
										while ($arOrderProperties = $dbOrderProperties->Fetch())
										{
											$curVal = $orderFields["ORDER_PROP"][$arOrderProperties["ID"]];

											if (strlen($curVal) > 0)
											{
												if (IntVal($arOrder["USER_PROFILE_ID"]) <= 0)
												{
													$arFields = array(
														"NAME" => $arOrder["AGENT"]["AGENT_NAME"],
														"USER_ID" => $arOrder["USER_ID"],
														"PERSON_TYPE_ID" => $arOrder["PERSON_TYPE_ID"],
														"XML_ID" => $arOrder["AGENT"]["ID"],
														"VERSION_1C" => $arOrder["AGENT"]["VERSION"],
													);
													$arOrder["USER_PROFILE_ID"] = CSaleOrderUserProps::Add($arFields);
												}
												if(IntVal($arOrder["USER_PROFILE_ID"]) > 0)
												{
													$arFields = array(
														"USER_PROPS_ID" => $arOrder["USER_PROFILE_ID"],
														"ORDER_PROPS_ID" => $arOrderProperties["ID"],
														"NAME" => $arOrderProperties["NAME"],
														"VALUE" => $curVal
													);
													if(empty($arOrder["AGENT"]["PROFILE_PROPS_VALUE"][$arOrderProperties["ID"]]))
													{
														CSaleOrderUserPropsValue::Add($arFields);
													}
													elseif($arOrder["AGENT"]["PROFILE_PROPS_VALUE"][$arOrderProperties["ID"]]["VALUE"] != $curVal)
													{
														CSaleOrderUserPropsValue::Update($arOrder["AGENT"]["PROFILE_PROPS_VALUE"][$arOrderProperties["ID"]]["ID"], $arFields);
													}
												}
											}
										}
									}
								}
								else
								{
									$this->strError .= "\n".GetMessage("CC_BSC1_ORDER_ADD_PROBLEM", Array("#ID#" => $arOrder["ID_1C"]));
								}
							}
							else
							{
								$this->strError .= "\n".GetMessage("CC_BSC1_ORDER_USER_PROBLEM", Array("#ID#" => $arOrder["ID_1C"]));
								if(!empty($arErrors))
								{
									foreach($arErrors as $v)
									{
										$this->strError .= "\n".$v["TEXT"];
									}
								}
							}
						}
						else
						{
							$this->strError .= "\n".GetMessage("CC_BSC1_ORDER_PERSON_TYPE_PROBLEM", Array("#ID#" => $arOrder["ID_1C"]));
						}
					}
					else
					{
						$this->strError .= "\n".GetMessage("CC_BSC1_ORDER_NO_AGENT_ID", Array("#ID#" => $arOrder["ID_1C"]));
					}
				}
			}
		}
		elseif($this->arParams["IMPORT_NEW_ORDERS"] == "Y")
		{

			$value = $value[GetMessage("CC_BSC1_AGENT")]["#"];
			$arAgentInfo = $this->collectAgentInfo($value);

			if(!empty($arAgentInfo["AGENT"]))
			{
				$mode = false;
				$arErrors = array();
				$dbUProp = CSaleOrderUserProps::GetList(array(), array("XML_ID" => $arAgentInfo["AGENT"]["ID"]), false, false, array("ID", "NAME", "USER_ID", "PERSON_TYPE_ID", "XML_ID", "VERSION_1C"));
				if($arUProp = $dbUProp->Fetch())
				{
					if($arUProp["VERSION_1C"] != $arAgentInfo["AGENT"]["VERSION"])
					{
						$mode = "update";
						$arAgentInfo["PROFILE_ID"] = $arUProp["ID"];
						$arAgentInfo["PERSON_TYPE_ID"] = $arUProp["PERSON_TYPE_ID"];
					}
				}
				else
				{
					$arUser = array(
						"NAME" => $arAgentInfo["AGENT"]["ITEM_NAME"],
						"EMAIL" => $arAgentInfo["AGENT"]["CONTACT"]["MAIL_NEW"],
					);

					if(strlen($arUser["NAME"]) <= 0)
						$arUser["NAME"] = $arAgentInfo["AGENT"]["CONTACT"]["CONTACT_PERSON"];

					$emServer = $_SERVER["SERVER_NAME"];
					if(strpos($_SERVER["SERVER_NAME"], ".") === false)
						$emServer .= ".bx";
					if(strlen($arUser["EMAIL"]) <= 0)
						$arUser["EMAIL"] = "buyer".time().GetRandomCode(2)."@".$emServer;
					$arAgentInfo["USER_ID"] = CSaleUser::DoAutoRegisterUser($arUser["EMAIL"], $arUser["NAME"], $this->arParams["SITE_NEW_ORDERS"], $arErrors);

					if(IntVal($arAgentInfo["USER_ID"]) > 0)
					{
						$mode = "add";
					}
					else
					{
						$this->strError .= "\n".GetMessage("CC_BSC1_AGENT_USER_PROBLEM", Array("#ID#" => $arAgentInfo["AGENT"]["ID"]));
						if(!empty($arErrors))
						{
							foreach($arErrors as $v)
							{
								$this->strError .= "\n".$v["TEXT"];
							}
						}
					}
				}

				if($mode)
				{
					if(empty($this->arPersonTypesIDs))
					{
						$dbPT = CSalePersonType::GetList(array(), array("ACTIVE" => "Y", "LIDS" => $this->arParams["SITE_NEW_ORDERS"]));
						while($arPT = $dbPT->Fetch())
						{
							$this->arPersonTypesIDs[] = $arPT["ID"];
						}
					}

					if(empty($this->arExportInfo))
					{
						$dbExport = CSaleExport::GetList(array(), array("PERSON_TYPE_ID" => $this->arPersonTypesIDs));
						while($arExport = $dbExport->Fetch())
						{
							$this->arExportInfo[$arExport["PERSON_TYPE_ID"]] = unserialize($arExport["VARS"]);
						}
					}

					if(IntVal($arAgentInfo["PERSON_TYPE_ID"]) <= 0)
					{
						foreach($this->arExportInfo as $pt => $value)
						{
							if(($value["IS_FIZ"] == "Y" && $arAgentInfo["AGENT"]["TYPE"] == "FIZ")
								|| ($value["IS_FIZ"] == "N" && $arAgentInfo["AGENT"]["TYPE"] != "FIZ")
							)
								$arAgentInfo["PERSON_TYPE_ID"] = $pt;
						}
					}

					if(IntVal($arAgentInfo["PERSON_TYPE_ID"]) > 0)
					{
						$arAgentInfo["ORDER_PROPS_VALUE"] = array();
						$arAgentInfo["PROFILE_PROPS_VALUE"] = array();

						$arAgent = $this->arExportInfo[$arAgentInfo["PERSON_TYPE_ID"]];

						foreach($arAgent as $k => $v)
						{
							if(strlen($v["VALUE"]) <= 0 || $v["TYPE"] != "PROPERTY")
								unset($arAgent[$k]);
						}

						foreach($arAgent as $k => $v)
						{
							if(!empty($arAgentInfo["ORDER_PROPS"][$k]))
								$arAgentInfo["ORDER_PROPS_VALUE"][$v["VALUE"]] = $arAgentInfo["ORDER_PROPS"][$k];
						}

						if (IntVal($arAgentInfo["PROFILE_ID"]) > 0)
						{
							CSaleOrderUserProps::Update($arUProp["ID"], array("VERSION_1C" => $arAgentInfo["AGENT"]["VERSION"], "NAME" => $arAgentInfo["AGENT"]["AGENT_NAME"]));
							$dbUPV = CSaleOrderUserPropsValue::GetList(array(), array("USER_PROPS_ID" => $arAgentInfo["PROFILE_ID"]));
							while($arUPV = $dbUPV->Fetch())
							{
								$arAgentInfo["PROFILE_PROPS_VALUE"][$arUPV["ORDER_PROPS_ID"]] = array("ID" => $arUPV["ID"], "VALUE" => $arUPV["VALUE"]);
							}
						}

						if(empty($this->arOrderProps[$arAgentInfo["PERSON_TYPE_ID"]]))
						{
							$dbOrderProperties = CSaleOrderProps::GetList(
								array("SORT" => "ASC"),
								array(
									"PERSON_TYPE_ID" => $arAgentInfo["PERSON_TYPE_ID"],
									"ACTIVE" => "Y",
									"UTIL" => "N",
									"USER_PROPS" => "Y",
								),
								false,
								false,
								array("ID", "TYPE", "NAME", "CODE", "USER_PROPS", "SORT", "MULTIPLE")
							);
							while ($arOrderProperties = $dbOrderProperties->Fetch())
							{
								$this->arOrderProps[$arAgentInfo["PERSON_TYPE_ID"]][] = $arOrderProperties;
							}
						}

						foreach($this->arOrderProps[$arAgentInfo["PERSON_TYPE_ID"]] as $arOrderProperties)
						{
							$curVal = $arAgentInfo["ORDER_PROPS_VALUE"][$arOrderProperties["ID"]];

							if (strlen($curVal) > 0)
							{
								if (IntVal($arAgentInfo["PROFILE_ID"]) <= 0)
								{
									$arFields = array(
										"NAME" => $arAgentInfo["AGENT"]["AGENT_NAME"],
										"USER_ID" => $arAgentInfo["USER_ID"],
										"PERSON_TYPE_ID" => $arAgentInfo["PERSON_TYPE_ID"],
										"XML_ID" => $arAgentInfo["AGENT"]["ID"],
										"VERSION_1C" => $arAgentInfo["AGENT"]["VERSION"],
									);
									$arAgentInfo["PROFILE_ID"] = CSaleOrderUserProps::Add($arFields);
								}
								if(IntVal($arAgentInfo["PROFILE_ID"]) > 0)
								{
									$arFields = array(
										"USER_PROPS_ID" => $arAgentInfo["PROFILE_ID"],
										"ORDER_PROPS_ID" => $arOrderProperties["ID"],
										"NAME" => $arOrderProperties["NAME"],
										"VALUE" => $curVal
									);
									if(empty($arAgentInfo["PROFILE_PROPS_VALUE"][$arOrderProperties["ID"]]))
									{
										CSaleOrderUserPropsValue::Add($arFields);
									}
									elseif($arAgentInfo["PROFILE_PROPS_VALUE"][$arOrderProperties["ID"]]["VALUE"] != $curVal)
									{
										CSaleOrderUserPropsValue::Update($arAgentInfo["PROFILE_PROPS_VALUE"][$arOrderProperties["ID"]]["ID"], $arFields);
									}
								}
							}
						}
					}
					else
					{
						$this->strError .= "\n".GetMessage("CC_BSC1_AGENT_PERSON_TYPE_PROBLEM", Array("#ID#" => $arAgentInfo["AGENT"]["ID"]));
					}
				}
			}
			else
			{
				$this->strError .= "\n".GetMessage("CC_BSC1_AGENT_NO_AGENT_ID");
			}
		}
	}
예제 #6
0
 public function saveOrder()
 {
     $arErrors = $arWarnings = array();
     $user = $this->getUser();
     $arOrderDat = \CSaleOrder::DoCalculateOrder(SITE_ID, $user['ID'], $this->getItemsRaw(), 1, array(), $this->getDeliveryId(), $this->getPaymentId(), array(), $arErrors, $arWarnings);
     $data = array('LID' => SITE_ID, 'PERSON_TYPE_ID' => 1, 'PAYED' => 'N', 'CANCELED' => 'N', 'STATUS_ID' => 'N', 'PRICE' => $this->getTotalDelivery(), 'CURRENCY' => 'RUB', 'USER_ID' => $user['ID'], 'PAY_SYSTEM_ID' => $this->getPaymentId(), 'PRICE_DELIVERY' => $this->getDeliveryPrice(), 'DELIVERY_ID' => $this->getDeliveryId(), 'DISCOUNT_VALUE' => 0, 'TAX_VALUE' => 0.0);
     $arOrderDat['ORDER_PROP'][3] = $user['PERSONAL_PHONE'];
     $errors = array();
     $orderId = \CSaleOrder::DoSaveOrder($arOrderDat, $data, 0, $errors);
     return $orderId;
 }
예제 #7
0
 protected function processOrderAcceptRequest($arPostData)
 {
     $arResult = array();
     DiscountCompatibility::reInit(DiscountCompatibility::MODE_EXTERNAL, array('SITE_ID' => $this->siteId));
     if ($this->checkOrderAcceptStructure($arPostData)) {
         $dbRes = \Bitrix\Sale\TradingPlatform\OrderTable::getList(array("filter" => array("TRADING_PLATFORM_ID" => YandexMarket::getInstance()->getId(), "EXTERNAL_ORDER_ID" => $arPostData["order"]["id"])));
         if (!($orderCorrespondence = $dbRes->fetch())) {
             require_once $_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/sale/general/admin_tool.php";
             $arProducts = array();
             foreach ($arPostData["order"]["items"] as $arItem) {
                 $arProduct = $this->getProductById($arItem["offerId"], $arItem["count"]);
                 $arProduct["PRODUCT_ID"] = $arItem["offerId"];
                 $arProduct["MODULE"] = "catalog";
                 $arProduct["PRODUCT_PROVIDER_CLASS"] = "CCatalogProductProvider";
                 $dbIblockElement = CIBlockElement::GetList(array(), array("ID" => $arItem["offerId"]), false, false, array('XML_ID', 'IBLOCK_EXTERNAL_ID'));
                 if ($IblockElement = $dbIblockElement->Fetch()) {
                     if (strlen($IblockElement["XML_ID"]) > 0) {
                         $arProduct["PRODUCT_XML_ID"] = $IblockElement["XML_ID"];
                     }
                     if (strlen($IblockElement["IBLOCK_EXTERNAL_ID"]) > 0) {
                         $arProduct["CATALOG_XML_ID"] = $IblockElement["IBLOCK_EXTERNAL_ID"];
                     }
                 }
                 if ($arProduct["CAN_BUY"] == "Y") {
                     $arProducts[] = $arProduct;
                 }
             }
             $arOrderProductPrice = fGetUserShoppingCart($arProducts, $this->siteId, "N");
             $arErrors = array();
             $userId = intval(CSaleUser::GetAnonymousUserID());
             $arShoppingCart = CSaleBasket::DoGetUserShoppingCart($this->siteId, $userId, $arOrderProductPrice, $arErrors);
             $deliveryId = $arPostData["order"]["delivery"]["id"];
             $paySystemId = $this->mapPaySystems[$arPostData["order"]["paymentMethod"]];
             $locationId = $this->locationMapper->getLocationByCityName($arPostData["order"]["delivery"]["region"]["name"]);
             if ($locationId === false) {
                 $this->log(self::LOG_LEVEL_INFO, "YMARKET_LOCATION_MAPPING", $arPostData["order"]["delivery"]["region"]["name"], GetMessage("SALE_YMH_LOCATION_NOT_FOUND"));
             }
             $arErrors = $arWarnings = array();
             $arOptions = array();
             $arOrderPropsValues = $this->makeAdditionalOrderProps($arPostData["order"]["delivery"]["address"], array(), $this->mapPaySystems[$arPostData["order"]["paymentMethod"]], $arPostData["order"]["delivery"]["id"], $locationId);
             $CSaleOrder = new CSaleOrder();
             $arOrder = $CSaleOrder->DoCalculateOrder($this->siteId, $userId, $arShoppingCart, $this->personTypeId, $arOrderPropsValues, $deliveryId, $paySystemId, $arOptions, $arErrors, $arWarnings);
             $arErrors = array();
             $arAdditionalFields = array("XML_ID" => self::XML_ID_PREFIX . $arPostData["order"]["id"]);
             $arOrder["LID"] = $this->siteId;
             if (isset($arPostData["order"]["notes"])) {
                 $arAdditionalFields["USER_DESCRIPTION"] = $arPostData["order"]["notes"];
             }
             $orderID = $CSaleOrder->DoSaveOrder($arOrder, $arAdditionalFields, 0, $arErrors);
             $res = \Bitrix\Sale\TradingPlatform\OrderTable::add(array("ORDER_ID" => $orderID, "TRADING_PLATFORM_ID" => YandexMarket::getInstance()->getId(), "EXTERNAL_ORDER_ID" => $arPostData["order"]["id"]));
             if (!$res->isSuccess()) {
                 foreach ($res->getErrors() as $error) {
                     $this->log(self::LOG_LEVEL_ERROR, "YMARKET_PLATFORM_ORDER_ADD_ERROR", $orderID, $error);
                 }
             }
         } else {
             $orderID = $orderCorrespondence["ORDER_ID"];
         }
         if (intval($orderID > 0)) {
             $arResult["order"]["accepted"] = true;
             $arResult["order"]["id"] = strval($orderID);
             $this->log(self::LOG_LEVEL_INFO, "YMARKET_ORDER_CREATE", $arPostData["order"]["id"], GetMessage("SALE_YMH_ORDER_CREATED") . " " . $orderID);
         } else {
             $arResult["order"]["accepted"] = false;
             $arResult["order"]["reason"] = "OUT_OF_DATE";
             $this->log(self::LOG_LEVEL_ERROR, "YMARKET_ORDER_CREATE", $arPostData["order"]["id"], print_r($arErrors, true));
         }
     } else {
         $arResult = $this->processError(self::ERROR_STATUS_400, GetMessage("SALE_YMH_ERROR_BAD_STRUCTURE"));
     }
     return $arResult;
 }
예제 #8
0
 public function Add($arFields, &$arRecalculated = false, $siteId = SITE_ID, $options = array())
 {
     /** @global \CDatabase $DB */
     global $DB;
     if (!CModule::IncludeModule('sale')) {
         return false;
     }
     if (!is_array($options)) {
         $options = array();
     }
     $bRecalculate = is_array($arRecalculated);
     $orderID = false;
     $tmpOrderId = intval($arFields['ID']) <= 0 ? 0 : $arFields['ID'];
     if (isset($arFields['ID'])) {
         unset($arFields['ID']);
     }
     $arPrevOrder = $tmpOrderId !== 0 ? CCrmInvoice::GetByID($tmpOrderId) : null;
     $userId = CCrmSecurityHelper::GetCurrentUserID();
     if (!isset($arFields['RESPONSIBLE_ID']) || (int) $arFields['RESPONSIBLE_ID'] <= 0) {
         if (is_array($arPrevOrder) && isset($arPrevOrder['RESPONSIBLE_ID']) && intval($arPrevOrder['RESPONSIBLE_ID']) > 0) {
             $arFields['RESPONSIBLE_ID'] = $arPrevOrder['RESPONSIBLE_ID'];
         } else {
             $arFields['RESPONSIBLE_ID'] = $userId;
         }
     }
     $orderStatus = '';
     if (isset($arFields['STATUS_ID'])) {
         $orderStatus = $arFields['STATUS_ID'];
         unset($arFields['STATUS_ID']);
     }
     // prepare entity permissions
     $arAttr = array();
     if (!empty($arFields['OPENED'])) {
         $arAttr['OPENED'] = $arFields['OPENED'];
     }
     $sPermission = $tmpOrderId > 0 ? 'WRITE' : 'ADD';
     if ($this->bCheckPermission) {
         $arEntityAttr = self::BuildEntityAttr($userId, $arAttr);
         $userPerms = $userId == CCrmPerms::GetCurrentUserID() ? $this->cPerms : CCrmPerms::GetUserPermissions($userId);
         $sEntityPerm = $userPerms->GetPermType('INVOICE', $sPermission, $arEntityAttr);
         if ($sEntityPerm == BX_CRM_PERM_NONE) {
             $this->LAST_ERROR = GetMessage('CRM_PERMISSION_DENIED');
             $GLOBALS['APPLICATION']->ThrowException($this->LAST_ERROR);
             return false;
         }
         $responsibleID = intval($arFields['RESPONSIBLE_ID']);
         if ($sEntityPerm == BX_CRM_PERM_SELF && $responsibleID != $userId) {
             $arFields['RESPONSIBLE_ID'] = $userId;
         }
         if ($sEntityPerm == BX_CRM_PERM_OPEN && $userId == $responsibleID) {
             $arFields['OPENED'] = 'Y';
         }
     }
     $responsibleID = intval($arFields['RESPONSIBLE_ID']);
     $arEntityAttr = self::BuildEntityAttr($responsibleID, $arAttr);
     $userPerms = $responsibleID == CCrmPerms::GetCurrentUserID() ? $this->cPerms : CCrmPerms::GetUserPermissions($responsibleID);
     $sEntityPerm = $userPerms->GetPermType('INVOICE', $sPermission, $arEntityAttr);
     $this->PrepareEntityAttrs($arEntityAttr, $sEntityPerm);
     // date fields
     if ($tmpOrderId === 0) {
         $arFields['~DATE_BILL'] = $DB->CharToDateFunction(isset($arFields['DATE_BILL']) && $arFields['DATE_BILL'] !== '' ? $arFields['DATE_BILL'] : ConvertTimeStamp(time(), 'SHORT', SITE_ID), 'SHORT', false);
     } else {
         if (isset($arFields['DATE_BILL']) && $arFields['DATE_BILL'] !== '') {
             $arFields['~DATE_BILL'] = $DB->CharToDateFunction($arFields['DATE_BILL'], 'SHORT', false);
         }
     }
     unset($arFields['DATE_BILL']);
     if (isset($arFields['DATE_PAY_BEFORE']) && $arFields['DATE_PAY_BEFORE'] !== '') {
         $arFields['~DATE_PAY_BEFORE'] = $DB->CharToDateFunction($arFields['DATE_PAY_BEFORE'], 'SHORT', false);
     }
     unset($arFields['DATE_PAY_BEFORE']);
     if ($tmpOrderId !== 0 && !isset($arFields['PRODUCT_ROWS']) && !isset($arFields['INVOICE_PROPERTIES'])) {
         if (!is_array($arPrevOrder)) {
             return false;
         }
         $prevResponsibleID = isset($arPrevOrder['RESPONSIBLE_ID']) ? intval($arPrevOrder['RESPONSIBLE_ID']) : 0;
         $responsibleID = isset($arFields['RESPONSIBLE_ID']) ? intval($arFields['RESPONSIBLE_ID']) : 0;
         $prevStatusID = isset($arPrevOrder['STATUS_ID']) ? $arPrevOrder['STATUS_ID'] : '';
         // simple update order fields
         $CSaleOrder = new CSaleOrder();
         $orderID = $CSaleOrder->Update($tmpOrderId, $arFields);
         CCrmEntityHelper::NormalizeUserFields($arFields, self::$sUFEntityID, $GLOBALS['USER_FIELD_MANAGER'], array('IS_NEW' => false));
         $GLOBALS['USER_FIELD_MANAGER']->Update(self::$sUFEntityID, $tmpOrderId, $arFields);
         $registerSonetEvent = isset($options['REGISTER_SONET_EVENT']) && $options['REGISTER_SONET_EVENT'] === true;
         if (is_int($orderID) && $orderID > 0) {
             if ($registerSonetEvent) {
                 $newDealID = isset($arFields['UF_DEAL_ID']) ? intval($arFields['UF_DEAL_ID']) : 0;
                 $oldDealID = isset($arPrevOrder['UF_DEAL_ID']) ? intval($arPrevOrder['UF_DEAL_ID']) : 0;
                 $newCompanyID = isset($arFields['UF_COMPANY_ID']) ? intval($arFields['UF_COMPANY_ID']) : 0;
                 $oldCompanyID = isset($arPrevOrder['UF_COMPANY_ID']) ? intval($arPrevOrder['UF_COMPANY_ID']) : 0;
                 $newContactID = isset($arFields['UF_CONTACT_ID']) ? intval($arFields['UF_CONTACT_ID']) : 0;
                 $oldContactID = isset($arPrevOrder['UF_CONTACT_ID']) ? intval($arPrevOrder['UF_CONTACT_ID']) : 0;
                 $parents = array();
                 $parentsChanged = $newDealID !== $oldDealID || $newCompanyID !== $oldCompanyID || $newContactID !== $oldContactID;
                 if ($parentsChanged) {
                     if ($newDealID > 0) {
                         $parents[] = array('ENTITY_TYPE_ID' => CCrmOwnerType::Deal, 'ENTITY_ID' => $newDealID);
                     }
                     if ($newCompanyID > 0) {
                         $parents[] = array('ENTITY_TYPE_ID' => CCrmOwnerType::Company, 'ENTITY_ID' => $newCompanyID);
                     }
                     if ($newContactID > 0) {
                         $parents[] = array('ENTITY_TYPE_ID' => CCrmOwnerType::Contact, 'ENTITY_ID' => $newContactID);
                     }
                 }
                 $oldOrderStatus = isset($arPrevOrder['STATUS_ID']) ? $arPrevOrder['STATUS_ID'] : '';
                 self::SynchronizeLiveFeedEvent($orderID, array('PROCESS_PARENTS' => $parentsChanged, 'PARENTS' => $parents, 'REFRESH_DATE' => $orderStatus !== $oldOrderStatus, 'START_RESPONSIBLE_ID' => $prevResponsibleID, 'FINAL_RESPONSIBLE_ID' => $responsibleID, 'TOPIC' => isset($arPrevOrder['ORDER_TOPIC']) ? $arPrevOrder['ORDER_TOPIC'] : $orderID));
             }
             if ($responsibleID !== $prevResponsibleID) {
                 CCrmSonetSubscription::ReplaceSubscriptionByEntity(CCrmOwnerType::Invoice, $orderID, CCrmSonetSubscriptionType::Responsibility, $responsibleID, $prevResponsibleID, $registerSonetEvent);
             }
         }
     } else {
         // check product rows
         if (!isset($arFields['PRODUCT_ROWS']) || !is_array($arFields['PRODUCT_ROWS']) || count($arFields['PRODUCT_ROWS']) <= 0) {
             return false;
         }
         $arProduct = $arFields['PRODUCT_ROWS'];
         // prepare shopping cart data
         // <editor-fold defaultstate="collapsed" desc="prepare shopping cart data ...">
         // get xml_id fields
         $catalogXmlId = CCrmCatalog::GetDefaultCatalogXmlId();
         $arNewProducts = array();
         $bGetBasketXmlIds = false;
         foreach ($arProduct as &$productRow) {
             if (isset($productRow['ID']) && intval($productRow['ID']) === 0 && isset($productRow['PRODUCT_ID'])) {
                 $arNewProducts[] = $productRow['PRODUCT_ID'];
             } else {
                 $bGetBasketXmlIds = true;
             }
         }
         unset($productRow);
         $arXmlIds = array();
         $oldProductRows = null;
         if ($bGetBasketXmlIds && intval($tmpOrderId) > 0) {
             $oldProductRows = CCrmInvoice::GetProductRows($tmpOrderId);
             if (count($oldProductRows) > 0) {
                 foreach ($oldProductRows as $row) {
                     $arXmlIds[intval($row['ID'])][$row['PRODUCT_ID']] = array('CATALOG_XML_ID' => $row['CATALOG_XML_ID'], 'PRODUCT_XML_ID' => $row['PRODUCT_XML_ID']);
                 }
                 unset($row);
             }
         }
         unset($bGetBasketXmlIds);
         if (count($arNewProducts) > 0) {
             $dbRes = CCrmProduct::GetList(array(), array('ID' => $arNewProducts), array('ID', 'XML_ID'));
             while ($row = $dbRes->Fetch()) {
                 $arXmlIds[0][$row['ID']] = array('CATALOG_XML_ID' => $catalogXmlId, 'PRODUCT_XML_ID' => $row['XML_ID']);
             }
             unset($dbRes, $row);
         }
         unset($arNewProducts, $arOldProducts);
         // products without measures
         $productMeasures = array();
         $productId = 0;
         $productIds = array();
         foreach ($arProduct as $productRow) {
             $productId = intval($productRow['PRODUCT_ID']);
             if ($productId > 0 && (!array_key_exists('MEASURE_CODE', $productRow) || intval($productRow['MEASURE_CODE']) <= 0)) {
                 $productIds[] = $productId;
             }
         }
         unset($productId, $productRow);
         if (count($productIds) > 0) {
             $productMeasures = \Bitrix\Crm\Measure::getProductMeasures($productIds);
         }
         unset($productIds);
         $currencyId = CCrmInvoice::GetCurrencyID($siteId);
         $i = 0;
         $defaultMeasure = null;
         $oldProductRowsById = null;
         foreach ($arProduct as &$productRow) {
             $productXmlId = $catalogXmlId = null;
             $rowIndex = intval($productRow['ID']);
             $productId = $productRow['PRODUCT_ID'];
             $isCustomized = isset($productRow['CUSTOMIZED']) && $productRow['CUSTOMIZED'] === 'Y';
             $productRow['MODULE'] = $productRow['PRODUCT_PROVIDER_CLASS'] = '';
             if ($productId > 0) {
                 if (!$isCustomized) {
                     $productRow['MODULE'] = 'catalog';
                     $productRow['PRODUCT_PROVIDER_CLASS'] = 'CCatalogProductProvider';
                 }
                 if (is_array($arXmlIds[$rowIndex]) && isset($arXmlIds[$rowIndex][$productId])) {
                     $catalogXmlId = $arXmlIds[$rowIndex][$productId]['CATALOG_XML_ID'];
                     $productXmlId = $arXmlIds[$rowIndex][$productId]['PRODUCT_XML_ID'];
                 }
                 $productRow['CATALOG_XML_ID'] = $catalogXmlId;
                 $productRow['PRODUCT_XML_ID'] = $productXmlId;
             } else {
                 $productRow["PRODUCT_XML_ID"] = "CRM-" . randString(8);
                 $ri = new \Bitrix\Main\Type\RandomSequence($productRow["PRODUCT_XML_ID"]);
                 $productRow["PRODUCT_ID"] = $ri->rand(1000000, 9999999);
                 $productRow['CATALOG_XML_ID'] = '';
             }
             if ($isCustomized) {
                 $productRow['CUSTOM_PRICE'] = 'Y';
             }
             if (isset($productRow['PRODUCT_NAME'])) {
                 $productRow['NAME'] = $productRow['PRODUCT_NAME'];
                 unset($productRow['PRODUCT_NAME']);
             }
             if (isset($productRow['PRICE'])) {
                 $productRow['PRICE_DEFAULT'] = $productRow['PRICE'];
             }
             if (!isset($productRow['CURRENCY'])) {
                 $productRow['CURRENCY'] = $currencyId;
             }
             // measures
             $bRefreshMeasureName = false;
             if (!array_key_exists('MEASURE_CODE', $productRow) || intval($productRow['MEASURE_CODE'] <= 0)) {
                 if ($oldProductRows === null && $tmpOrderId > 0) {
                     $oldProductRows = CCrmInvoice::GetProductRows($tmpOrderId);
                 }
                 if (is_array($oldProductRows) && count($oldProductRows) > 0 && $oldProductRowsById === null) {
                     $oldProductRowsById = array();
                     foreach ($oldProductRows as $row) {
                         $oldProductRowsById[intval($row['ID'])] = $row;
                     }
                     unset($row);
                 }
                 if (is_array($oldProductRowsById) && isset($oldProductRowsById[$rowIndex])) {
                     $row = $oldProductRowsById[$rowIndex];
                     if (intval($productId) === intval($row['PRODUCT_ID'])) {
                         if (isset($row['MEASURE_CODE'])) {
                             $productRow['MEASURE_CODE'] = $row['MEASURE_CODE'];
                         }
                         if (isset($row['MEASURE_NAME'])) {
                             $productRow['MEASURE_NAME'] = $row['MEASURE_NAME'];
                         } else {
                             $bRefreshMeasureName = true;
                         }
                         unset($row);
                     }
                 }
             }
             if (!isset($productRow['MEASURE_CODE']) || intval($productRow['MEASURE_CODE']) <= 0) {
                 if ($productId > 0 && isset($productMeasures[$productId])) {
                     $measure = is_array($productMeasures[$productId][0]) ? $productMeasures[$productId][0] : null;
                     if (is_array($measure)) {
                         if (isset($measure['CODE'])) {
                             $productRow['MEASURE_CODE'] = $measure['CODE'];
                         }
                         if (isset($measure['SYMBOL'])) {
                             $productRow['MEASURE_NAME'] = $measure['SYMBOL'];
                         }
                     }
                     unset($measure);
                 }
             }
             if (!isset($productRow['MEASURE_CODE']) || intval($productRow['MEASURE_CODE']) <= 0) {
                 if ($defaultMeasure === null) {
                     $defaultMeasure = \Bitrix\Crm\Measure::getDefaultMeasure();
                 }
                 if (is_array($defaultMeasure)) {
                     $productRow['MEASURE_CODE'] = $defaultMeasure['CODE'];
                     $productRow['MEASURE_NAME'] = $defaultMeasure['SYMBOL'];
                 }
             }
             if (isset($productRow['MEASURE_CODE']) && intval($productRow['MEASURE_CODE']) > 0 && ($bRefreshMeasureName || !array_key_exists('MEASURE_NAME', $productRow) || empty($productRow['MEASURE_NAME']))) {
                 $measure = \Bitrix\Crm\Measure::getMeasureByCode($productRow['MEASURE_CODE']);
                 if (is_array($measure) && isset($measure['SYMBOL'])) {
                     $productRow['MEASURE_NAME'] = $measure['SYMBOL'];
                 }
                 unset($measure);
             }
             $i++;
         }
         unset($productRow, $productMeasures, $catalogXmlId, $productXmlId);
         $arOrderProductPrice = self::__fGetUserShoppingCart($arProduct, $siteId, 'N');
         foreach ($arOrderProductPrice as &$arItem) {
             $arItem["ID_TMP"] = $arItem["ID"];
             $arItem["NAME_TMP"] = $arItem["NAME"];
             unset($arItem["ID"]);
         }
         unset($arItem);
         // user id for order
         $saleUserId = intval(CSaleUser::GetAnonymousUserID());
         if ($saleUserId <= 0) {
             return false;
         }
         $arErrors = array();
         $arShoppingCart = CSaleBasket::DoGetUserShoppingCart($siteId, $saleUserId, $arOrderProductPrice, $arErrors, array(), $tmpOrderId);
         if (!is_array($arShoppingCart) || count($arShoppingCart) === 0) {
             $GLOBALS['APPLICATION']->ThrowException(GetMessage('CRM_ERROR_EMPTY_INVOICE_SPEC'));
             return false;
         }
         foreach ($arShoppingCart as $key => &$arItem) {
             $arItem["ID"] = $arItem["ID_TMP"];
             $arItem["NAME"] = $arItem["NAME_TMP"];
             unset($arItem["NAME_TMP"], $arItem["ID_TMP"]);
             //$arShoppingCart[$key]["ID"] = $arItem["ID"];
         }
         unset($key, $arItem);
         // </editor-fold>
         // person type
         $personTypeId = 0;
         if (!isset($arFields['PERSON_TYPE_ID']) || intval($arFields['PERSON_TYPE_ID']) <= 0) {
             $arPersonTypes = CCrmPaySystem::getPersonTypeIDs();
             if (isset($arPersonTypes['CONTACT'])) {
                 $personTypeId = intval($arPersonTypes['CONTACT']);
             }
         } else {
             $personTypeId = $arFields['PERSON_TYPE_ID'];
         }
         if ($personTypeId <= 0) {
             return false;
         }
         // preparing order to save
         // <editor-fold defaultstate="collapsed" desc="preparing order to save ...">
         $arOrderPropsValues = array();
         if (isset($arFields['INVOICE_PROPERTIES']) && is_array($arFields['INVOICE_PROPERTIES']) && count($arFields['INVOICE_PROPERTIES']) > 0) {
             $arOrderPropsValues = $arFields['INVOICE_PROPERTIES'];
         }
         if (isset($arFields['INVOICE_PROPERTIES'])) {
             unset($arFields['INVOICE_PROPERTIES']);
         }
         if (count($arOrderPropsValues) <= 0) {
             return false;
         }
         $deliveryId = null;
         $paySystemId = $arFields['PAY_SYSTEM_ID'];
         $arOptions = array('LOCATION_IN_CODES' => true);
         // let DoCalculateOrder know we send location in CODEs
         $arErrors = $arWarnings = array();
         $CSaleOrder = new CSaleOrder();
         $arOrder = $CSaleOrder->DoCalculateOrder($siteId, $saleUserId, $arShoppingCart, $personTypeId, $arOrderPropsValues, $deliveryId, $paySystemId, $arOptions, $arErrors, $arWarnings);
         if (count($arOrder) <= 0) {
             return false;
         }
         // </editor-fold>
         if ($bRecalculate) {
             foreach ($arOrder as $k => $v) {
                 $arRecalculated[$k] = $v;
             }
             return true;
         }
         // merge order fields
         $arAdditionalFields = array();
         foreach ($arFields as $k => $v) {
             if ($k === 'PRODUCT_ROWS') {
                 continue;
             }
             $arAdditionalFields[$k] = $v;
         }
         $arOrder['LOCATION_IN_CODES'] = true;
         // let DoSaveOrder know we send location in IDs
         // saving order
         $arErrors = array();
         $orderID = $CSaleOrder->DoSaveOrder($arOrder, $arAdditionalFields, $tmpOrderId, $arErrors);
         if (is_int($orderID) && $orderID > 0) {
             CCrmEntityHelper::NormalizeUserFields($arFields, self::$sUFEntityID, $GLOBALS['USER_FIELD_MANAGER'], array('IS_NEW' => $tmpOrderId === 0));
             $GLOBALS['USER_FIELD_MANAGER']->Update(self::$sUFEntityID, $orderID, $arFields);
         }
         if (is_int($orderID) && $orderID > 0 && isset($options['REGISTER_SONET_EVENT']) && $options['REGISTER_SONET_EVENT'] === true) {
             $prevResponsibleID = is_array($arPrevOrder) && isset($arPrevOrder['RESPONSIBLE_ID']) ? intval($arPrevOrder['RESPONSIBLE_ID']) : 0;
             $responsibleID = isset($arFields['RESPONSIBLE_ID']) ? intval($arFields['RESPONSIBLE_ID']) : 0;
             if ($tmpOrderId <= 0) {
                 self::RegisterLiveFeedEvent($arFields, $orderID, $userId);
                 if ($responsibleID > 0) {
                     CCrmSonetSubscription::RegisterSubscription(CCrmOwnerType::Invoice, $orderID, CCrmSonetSubscriptionType::Responsibility, $responsibleID);
                 }
             } else {
                 $newDealID = isset($arFields['UF_DEAL_ID']) ? intval($arFields['UF_DEAL_ID']) : 0;
                 $oldDealID = isset($arPrevOrder['UF_DEAL_ID']) ? intval($arPrevOrder['UF_DEAL_ID']) : 0;
                 $newCompanyID = isset($arFields['UF_COMPANY_ID']) ? intval($arFields['UF_COMPANY_ID']) : 0;
                 $oldCompanyID = isset($arPrevOrder['UF_COMPANY_ID']) ? intval($arPrevOrder['UF_COMPANY_ID']) : 0;
                 $newContactID = isset($arFields['UF_CONTACT_ID']) ? intval($arFields['UF_CONTACT_ID']) : 0;
                 $oldContactID = isset($arPrevOrder['UF_CONTACT_ID']) ? intval($arPrevOrder['UF_CONTACT_ID']) : 0;
                 $parents = array();
                 $parentsChanged = $newDealID !== $oldDealID || $newCompanyID !== $oldCompanyID || $newContactID !== $oldContactID;
                 if ($parentsChanged) {
                     if ($newDealID > 0) {
                         $parents[] = array('ENTITY_TYPE_ID' => CCrmOwnerType::Deal, 'ENTITY_ID' => $newDealID);
                     }
                     if ($newCompanyID > 0) {
                         $parents[] = array('ENTITY_TYPE_ID' => CCrmOwnerType::Company, 'ENTITY_ID' => $newCompanyID);
                     }
                     if ($newContactID > 0) {
                         $parents[] = array('ENTITY_TYPE_ID' => CCrmOwnerType::Contact, 'ENTITY_ID' => $newContactID);
                     }
                 }
                 $oldOrderStatus = isset($arPrevOrder['STATUS_ID']) ? $arPrevOrder['STATUS_ID'] : '';
                 self::SynchronizeLiveFeedEvent($orderID, array('PROCESS_PARENTS' => $parentsChanged, 'PARENTS' => $parents, 'REFRESH_DATE' => $orderStatus !== $oldOrderStatus, 'START_RESPONSIBLE_ID' => $prevResponsibleID, 'FINAL_RESPONSIBLE_ID' => $responsibleID, 'TOPIC' => isset($arPrevOrder['ORDER_TOPIC']) ? $arPrevOrder['ORDER_TOPIC'] : $orderID));
                 if ($responsibleID !== $prevResponsibleID) {
                     CCrmSonetSubscription::ReplaceSubscriptionByEntity(CCrmOwnerType::Invoice, $orderID, CCrmSonetSubscriptionType::Responsibility, $responsibleID, $prevResponsibleID, true);
                 }
             }
         }
     }
     if (intval($orderID) > 0 && !empty($orderStatus)) {
         // set status
         $this->SetStatus($orderID, $orderStatus);
         // update entity permissions
         CCrmPerms::UpdateEntityAttr('INVOICE', $orderID, $arEntityAttr);
         $newDealID = isset($arFields['UF_DEAL_ID']) ? (int) $arFields['UF_DEAL_ID'] : 0;
         $oldDealID = is_array($arPrevOrder) && isset($arPrevOrder['UF_DEAL_ID']) ? (int) $arPrevOrder['UF_DEAL_ID'] : 0;
         if ($newDealID) {
             Bitrix\Crm\Statistics\DealInvoiceStatisticEntry::register($newDealID);
         }
         if ($oldDealID > 0 && $oldDealID !== $newDealID) {
             Bitrix\Crm\Statistics\DealInvoiceStatisticEntry::register($oldDealID);
         }
         if (isset($options['UPDATE_SEARCH']) && $options['UPDATE_SEARCH'] === true) {
             $arFilterTmp = array('ID' => $orderID);
             if (!$this->bCheckPermission) {
                 $arFilterTmp["CHECK_PERMISSIONS"] = "N";
             }
             CCrmSearch::UpdateSearch($arFilterTmp, 'INVOICE', true);
         }
     }
     return $orderID;
 }