Ejemplo n.º 1
0
 /** @return \CDBResult */
 public function getData()
 {
     $lid = $this->getFieldValue('LID', null);
     $orderCountFrom = $this->getFieldValue('ORDER_COUNT_FROM', null);
     $orderCountTo = $this->getFieldValue('ORDER_COUNT_TO', null);
     $orderSumFrom = $this->getFieldValue('ORDER_SUM_FROM', null);
     $orderSumTo = $this->getFieldValue('ORDER_SUM_TO', null);
     $orderLastDateFrom = $this->getFieldValue('LAST_ORDER_DATE_FROM', null);
     $orderLastDateTo = $this->getFieldValue('LAST_ORDER_DATE_TO', null);
     $filter = array();
     if ($lid) {
         $filter['LID'] = $lid;
     }
     if ($orderCountFrom) {
         $filter['>=ORDER_COUNT'] = $orderCountFrom;
     }
     if ($orderCountTo) {
         $filter['<ORDER_COUNT'] = $orderCountTo;
     }
     if ($orderSumFrom) {
         $filter['>=ORDER_SUM'] = $orderSumFrom;
     }
     if ($orderSumTo) {
         $filter['<ORDER_SUM'] = $orderSumTo;
     }
     if ($orderLastDateFrom) {
         $filter['>=LAST_ORDER_DATE'] = $orderLastDateFrom;
     }
     if ($orderLastDateTo) {
         $filter['<LAST_ORDER_DATE'] = $orderLastDateTo;
     }
     $dbBuyerList = \CSaleUser::GetBuyersList(array('ID' => 'ASC'), $filter, false, false, array("EMAIL", "NAME", "USER_ID"));
     return $dbBuyerList;
 }
Ejemplo n.º 2
0
    public static function getEdit(Order $order, $showProfiles = false)
    {
        $data = self::prepareData($order);
        $result = '
			<div class="adm-bus-table-container">
				<table border="0" cellspacing="0" cellpadding="0" width="100%" class="adm-detail-content-table edit-table">
					<tbody>
						<tr' . (intval($data["USER_ID"]) > 0 && $data["USER_ID"] != \CSaleUser::GetAnonymousUserID() ? ' style="display: none"' : '') . ' id="sale-order-buyer-find-button-wrap">
							<td class="adm-detail-content-cell-l fwb" width="40%">
								&nbsp;
							</td>
							<td class="adm-detail-content-cell-r">
								<input type="button" name="FIND_BUYER" value="' . Loc::getMessage("SALE_ORDER_BUYER_FIND") . '" onclick="BX.Sale.Admin.OrderBuyer.showChooseBuyerWindow(\'' . LANGUAGE_ID . '\')"><br>
								<i>' . Loc::getMessage("SALE_ORDER_BUYER_START_TO_CREATE") . ':</i>
							</td>
						</tr>
						<tr' . (intval($data["USER_ID"]) <= 0 || $data["USER_ID"] == \CSaleUser::GetAnonymousUserID() ? ' style="display: none"' : '') . ' id="sale-order-buyer-name-wrap">
							<td class="adm-detail-content-cell-l" width="40%">' . Loc::getMessage("SALE_ORDER_BUYER") . ':</td>
							<td class="adm-detail-content-cell-r">
								<div class="adm-s-order-person-choose">
									<a id="BUYER_USER_NAME" href="/bitrix/admin/user_edit.php?lang=' . LANGUAGE_ID . '&ID=' . $data["USER_ID"] . '">' . htmlspecialcharsbx($data["BUYER_USER_NAME"]) . '</a>&nbsp;
									<a class="adm-s-bus-morelinkqhsw" onclick="BX.Sale.Admin.OrderBuyer.showChooseBuyerWindow(\'' . LANGUAGE_ID . '\')" href="javascript:void(0);">
										' . Loc::getMessage("SALE_ORDER_BUYER_CHANGE") . '
									</a>&nbsp;
									<a class="adm-s-bus-morelinkqhsw" onclick="BX.Sale.Admin.OrderBuyer.clearBuyer();" href="javascript:void(0);">
										' . Loc::getMessage("SALE_ORDER_BUYER_CLEAR") . '
									</a>
									<input type="hidden" name="USER_ID" id="USER_ID" value="' . $data["USER_ID"] . '" onchange="BX.Sale.Admin.OrderBuyer.onBuyerIdChange(this);">
								</div>
							</td>
						</tr>
						<tr>
							<td class="adm-detail-content-cell-l fwb">' . Loc::getMessage("SALE_ORDER_BUYER_PAYER_TYPE") . ':</td>
							<td class="adm-detail-content-cell-r">' . \Bitrix\Sale\Helpers\Admin\OrderEdit::makeSelectHtml("PERSON_TYPE_ID", self::getBuyerTypesList($order->getSiteId()), isset($data["PERSON_TYPE_ID"]) ? $data["PERSON_TYPE_ID"] : "", false, array("class" => "adm-bus-select", "id" => "PERSON_TYPE_ID", "onchange" => "BX.Sale.Admin.OrderBuyer.onBuyerTypeChange(this.value);")) . '</td>
						</tr>
						<tr id="sale-order-buyer-profiles-list-row"' . ($showProfiles ? '' : ' style="display:none;"') . '>
							<td class="adm-detail-content-cell-l">' . Loc::getMessage("SALE_ORDER_BUYER_CHOOSE_PROFILE") . ':</td>
							<td class="adm-detail-content-cell-r"><div id="BUYER_PROFILE_ID_CONTAINER">';
        if ($showProfiles) {
            $result .= \Bitrix\Sale\Helpers\Admin\OrderEdit::makeSelectHtml("BUYER_PROFILE_ID", self::getBuyerProfilesList($data["USER_ID"], $data["PERSON_TYPE_ID"]), isset($data["BUYER_PROFILE_ID"]) ? $data["BUYER_PROFILE_ID"] : "", false, array("class" => "adm-bus-select", "id" => "BUYER_PROFILE_ID", "onchange" => "BX.Sale.Admin.OrderBuyer.onBuyerProfileChange();"));
        }
        $result .= '</div></td>
						</tr>
					</tbody>
				</table>
			</div>' . '<div id="order_properties_container"></div>' . '<div>' . self::getOrderPropertiesByJS($order) . '</div>' . '<div class="adm-bus-table-container caption border sale-order-props-group">' . '<div class="adm-bus-table-caption-title">' . Loc::getMessage("SALE_ORDER_BUYER_COMMENT") . '</div>
				<table border="0" cellspacing="0" cellpadding="0" width="100%" class="adm-detail-content-table edit-table ">
					<tbody>
						<tr>
							<td class="adm-detail-content-cell-l" width="40%">' . Loc::getMessage("SALE_ORDER_BUYER_ORDERCOMMENT") . ':</td>
							<td class="adm-detail-content-cell-r">
								<textarea style="width:400px;min-height:100px;" name="USER_DESCRIPTION" id="USER_DESCRIPTION">' . $data["USER_DESCRIPTION"] . '</textarea>
							</td>
						</tr>
					</tbody>
				</table>
			</div>';
        return $result;
    }
Ejemplo n.º 3
0
 public static function catchCatalogBasket($id, $arFields)
 {
     global $APPLICATION;
     // alter b_sale_basket - add recommendation, update it here
     if (!static::isOn()) {
         return;
     }
     // get product id by offer id
     $productInfo = \CCatalogSKU::GetProductInfo($arFields['PRODUCT_ID']);
     if (!empty($productInfo['ID'])) {
         $realProductId = $productInfo['ID'];
     } else {
         $realProductId = $arFields['PRODUCT_ID'];
     }
     // select site user id & recommendation id
     $siteUserId = 0;
     $recommendationId = '';
     // first, try to find in cookies
     $recommendationCookie = $APPLICATION->get_cookie(static::getCookieLogName());
     if (!empty($recommendationCookie)) {
         $recommendations = static::decodeProductLog($recommendationCookie);
         if (is_array($recommendations) && isset($recommendations[$realProductId])) {
             $recommendationId = $recommendations[$realProductId][0];
         }
     }
     if (empty($recommendationId)) {
         // ok then, lets see in views history
         //if(\COption::GetOptionString("sale", "encode_fuser_id", "N") == "Y")
         if (!is_numeric($arFields['FUSER_ID'])) {
             $filter = array('CODE' => $arFields['FUSER_ID']);
         } else {
             $filter = array('ID' => $arFields['FUSER_ID']);
         }
         $result = \CSaleUser::getList($filter);
         if (!empty($result)) {
             $siteUserId = $result['USER_ID'];
             // select recommendation id
             $fuser = $result['ID'];
             $viewResult = CatalogViewedProductTable::getList(array('select' => array('RECOMMENDATION'), 'filter' => array('=FUSER_ID' => $fuser, '=PRODUCT_ID' => $arFields['PRODUCT_ID']), 'order' => array('DATE_VISIT' => 'DESC')))->fetch();
             if (!empty($viewResult['RECOMMENDATION'])) {
                 $recommendationId = $viewResult['RECOMMENDATION'];
             }
         }
     }
     // prepare data
     $data = array('product_id' => $realProductId, 'user_id' => $siteUserId, 'bx_user_id' => static::getBxUserId(), 'domain' => Context::getCurrent()->getServer()->getHttpHost(), 'recommendation' => $recommendationId, 'date' => date(DATE_ISO8601));
     CounterDataTable::add(array('TYPE' => 'basket', 'DATA' => $data));
     // update basket with recommendation id
     if (!empty($recommendationId)) {
         $conn = Application::getConnection();
         $helper = $conn->getSqlHelper();
         $conn->query("UPDATE " . $helper->quote('b_sale_basket') . " SET RECOMMENDATION='" . $helper->forSql($recommendationId) . "' WHERE ID=" . (int) $id);
     }
 }
Ejemplo n.º 4
0
 /**
  * Transfers basket from one user to another one
  *
  * @param integer $from
  * @param integer $to
  * @global object $DB
  * @return boolean
  */
 public static function transferBasket($from, $to)
 {
     global $DB;
     $from = intval($from);
     $to = intval($to);
     CModule::IncludeModule('sale');
     if ($to > 0 && CSaleUser::GetList(array("ID" => $to))) {
         $deleteQuery = "DELETE FROM b_sale_basket WHERE FUSER_ID = " . $to . " ";
         $updateQuery = "UPDATE b_sale_basket SET " . "    FUSER_ID = " . $to . " " . "WHERE FUSER_ID = " . $from . " ";
         $DB->Query($deleteQuery, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
         $DB->Query($updateQuery, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
         return true;
     }
     return false;
 }
Ejemplo n.º 5
0
 public static function catchCatalogBasket($id, $arFields)
 {
     if (!static::isOn()) {
         return;
     }
     // select site user id
     $siteUserId = 0;
     if (\COption::GetOptionString("sale", "encode_fuser_id", "N") == "Y") {
         $filter = array('CODE' => $arFields['FUSER_ID']);
     } else {
         $filter = array('ID' => $arFields['FUSER_ID']);
     }
     $result = \CSaleUser::getList($filter);
     if (!empty($result)) {
         $siteUserId = $result['USER_ID'];
     }
     // prepare data
     $data = array('product_id' => $arFields['PRODUCT_ID'], 'user_id' => $siteUserId, 'bx_user_id' => static::getBxUserId(), 'domain' => Context::getCurrent()->getServer()->getHttpHost(), 'recommendation' => '0', 'date' => date(DATE_ISO8601));
     CounterDataTable::add(array('TYPE' => 'basket', 'DATA' => $data));
 }
Ejemplo n.º 6
0
 /**
  * Return fuser code.
  *
  * @return int
  */
 protected static function getCode()
 {
     return \CSaleUser::getFUserCode();
 }
Ejemplo n.º 7
0
	/**
	 * <p>Метод осуществляет продление подписки с кодом ID.</p> <p><b>Примечание</b>. Метод использует внутреннюю транзакцию. Если у вас используется <b>MySQL</b> и <b>InnoDB</b>, и ранее была открыта транзакция, то ее необходимо закрыть до подключения метода.</p>
	 *
	 *
	 *
	 *
	 * @param int $ID  Код записи с информацией о продлении.
	 *
	 *
	 *
	 * @return bool <p>Метод возвращает <i>true</i> в случае успешного продления или <i>false</i>
	 * в случае ошибки.</p><br><br>
	 *
	 * @static
	 * @link http://dev.1c-bitrix.ru/api_help/sale/classes/csalerecurring/csalerecurring.nextpayment.php
	 * @author Bitrix
	 */
	public static function NextPayment($ID)
	{
		global $DB;
		global $USER;

		$ID = IntVal($ID);
		if ($ID <= 0)
		{
			$GLOBALS["APPLICATION"]->ThrowException(GetMessage("SKGR_NO_RECID"), "NO_RECORD_ID");
			return False;
		}

		$arRecur = CSaleRecurring::GetByID($ID);
		if (!$arRecur)
		{
			$GLOBALS["APPLICATION"]->ThrowException(str_replace("#ID#", $ID, GetMessage("SKGR_NO_RECID1")), "NO_RECORD");
			return False;
		}

		$arOrder = CSaleOrder::GetByID($arRecur["ORDER_ID"]);
		if (!$arOrder)
		{
			$GLOBALS["APPLICATION"]->ThrowException(str_replace("#ID#", $arRecur["ORDER_ID"], GetMessage("SKGR_NO_ORDER1")), "NO_ORDER");
			return False;
		}


		$bSuccess = True;
		$newOrderID = IntVal($arRecur["ORDER_ID"]);

		/** @var $productProvider IBXSaleProductProvider */
		if ($productProvider = CSaleBasket::GetProductProvider($arRecur))
		{
			$arProduct = $productProvider::RecurringOrderProduct(array(
				"PRODUCT_ID" => $arRecur["PRODUCT_ID"],
				"USER_ID"    => $arOrder["USER_ID"]
			));
		}
		else
		{
			$arProduct = CSaleRecurring::ExecuteCallbackFunction(
					$arRecur["CALLBACK_FUNC"],
					$arRecur["MODULE"],
					$arRecur["PRODUCT_ID"],
					$arOrder["USER_ID"]
				);
		}

		if (!$arProduct || !is_array($arProduct) || count($arProduct) <= 0)
		{
			CSaleRecurring::CancelRecurring($arRecur["ID"], "Y", "Product is not found");

			/*
			$arFields = array(
					"CANCELED" => "Y",
					"DATE_CANCELED" => Date(CDatabase::DateFormatToPHP(CLang::GetDateFormat("FULL", LANG))),
					"CANCELED_REASON" => "Product is not found"
				);
			CSaleRecurring::Update($arRecur["ID"], $arFields);
			*/
			//CSaleRecurring::Delete($arRecur["ID"]);

			return True;
		}

		if ($arProduct["WITHOUT_ORDER"] == "Y" || $arRecur["SUCCESS_PAYMENT"] == "Y")
		{
			$baseSiteCurrency = CSaleLang::GetLangCurrency($arOrder["LID"]);
			$productPrice = roundEx(CCurrencyRates::ConvertCurrency($arProduct["PRICE"], $arProduct["CURRENCY"], $baseSiteCurrency), SALE_VALUE_PRECISION);

			// Delivery
			$deliveryPrice = 0;
			$deliveryID = 0;
			$arOrder["DELIVERY_ID"] = IntVal($arOrder["DELIVERY_ID"]);
			if ($arOrder["DELIVERY_ID"] > 0)
			{
				$deliveryLocation = 0;
				$dbOrderPropValues = CSaleOrderPropsValue::GetList(
						array(),
						array(
								"ORDER_ID" => $arRecur["ORDER_ID"],
								"PROP_IS_LOCATION" => "Y"
							),
						false,
						false,
						array("VALUE")
					);
				if ($arOrderPropValues = $dbOrderPropValues->Fetch())
					$deliveryLocation = IntVal($arOrderPropValues["VALUE"]);

				$dbDelivery = CSaleDelivery::GetList(
						array("SORT" => "ASC", "NAME" => "ASC"),
						array(
								"LID" => $arOrder["LID"],
								"WEIGHT" => DoubleVal($arProduct["WEIGHT"]) * DoubleVal($arProduct["QUANTITY"]), // Changed by Sigurd, 2007-08-16
								"ORDER_PRICE" => $productPrice * DoubleVal($arProduct["QUANTITY"]),
								"ACTIVE" => "Y",
								"LOCATION" => $deliveryLocation
							)
					);
				while ($arDelivery = $dbDelivery->Fetch())
				{
					$deliveryPriceTmp = roundEx(CCurrencyRates::ConvertCurrency($arDelivery["PRICE"], $arDelivery["CURRENCY"], $baseSiteCurrency), SALE_VALUE_PRECISION);
					if (IntVal($arDelivery["ID"]) == $arOrder["DELIVERY_ID"])
					{
						$deliveryID = IntVal($arDelivery["ID"]);
						$deliveryPrice = $deliveryPriceTmp;
						break;
					}
					if ($deliveryPriceTmp < $deliveryPrice || $deliveryID <= 0)
					{
						$deliveryID = IntVal($arDelivery["ID"]);
						$deliveryPrice = $deliveryPriceTmp;
					}
				}

				if ($deliveryID <= 0)
				{
					$GLOBALS["APPLICATION"]->ThrowException(GetMessage("SKGR_NO_DELIVERY"), "NO_DELIVERY");
					return False;
				}
			}

			// Sale discounts
			$discount = 0;
			$discountPrice = $productPrice;
			$discountProduct = 0;
			$dbDiscount = CSaleDiscount::GetList(
					array("SORT" => "ASC"),
					array(
							"LID" => $arOrder["LID"],
							"ACTIVE" => "Y",
							"!>ACTIVE_FROM" => Date($DB->DateFormatToPHP(CSite::GetDateFormat("FULL"))),
							"!<ACTIVE_TO" => Date($DB->DateFormatToPHP(CSite::GetDateFormat("FULL"))),
							"<=PRICE_FROM" => $productPrice,
							">=PRICE_TO" => $productPrice,
							"USER_GROUPS" => $USER->GetUserGroup($arOrder['USER_ID']),
						)
				);
			if ($arDiscount = $dbDiscount->Fetch())
			{
				if ($arDiscount["DISCOUNT_TYPE"] == "P")
				{
					$discountProduct = roundEx($productPrice * $arDiscount["DISCOUNT_VALUE"] / 100, SALE_VALUE_PRECISION);
					$discount = roundEx($discountProduct * DoubleVal($arProduct["QUANTITY"]), SALE_VALUE_PRECISION); // Changed by Sigurd, 2007-08-16
					$discountPrice = $productPrice - $discountProduct;
				}
				else
				{
					$discountValue = CCurrencyRates::ConvertCurrency($arDiscount["DISCOUNT_VALUE"], $arDiscount["CURRENCY"], $baseSiteCurrency);
					$discountValue = roundEx($discountValue, SALE_VALUE_PRECISION);

					$discountProduct = roundEx(1.0 * $discountValue / DoubleVal($arProduct["QUANTITY"]), SALE_VALUE_PRECISION);// Changed by Sigurd, 2007-08-16
					$discount = roundEx($curDiscount * DoubleVal($arProduct["QUANTITY"]), SALE_VALUE_PRECISION);
					$discountPrice = $productPrice - $discountProduct;
				}
			}

			$bUseVat = false;
			$vatRate = 0;
			if(DoubleVal($arProduct["VAT_RATE"]) > 0)
			{
				$bUseVat = true;
				$vatRate = $arProduct["VAT_RATE"];
			}

			// Tax
			$arTaxExempt = array();
			$dbUserGroups = CUser::GetUserGroupEx($arOrder["USER_ID"]);
			while ($arUserGroups = $dbUserGroups->Fetch())
			{
				$dbTaxExemptTmp = CSaleTax::GetExemptList(array("GROUP_ID" => $arUserGroups["GROUP_ID"]));
				while ($arTaxExemptTmp = $dbTaxExemptTmp->Fetch())
				{
					$arTaxExemptTmp["TAX_ID"] = IntVal($arTaxExemptTmp["TAX_ID"]);
					if (!in_array($arTaxExemptTmp["TAX_ID"], $arTaxExempt))
						$arTaxExempt[] = $arTaxExemptTmp["TAX_ID"];
				}
			}

			$taxPrice = 0;
			$taxVatPrice = 0;
			if(!$bUseVat)
			{
				$taxLocation = 0;
				$dbOrderPropValues = CSaleOrderPropsValue::GetList(
						array(),
						array(
								"ORDER_ID" => $arRecur["ORDER_ID"],
								"PROP_IS_LOCATION4TAX" => "Y"
							),
						false,
						false,
						array("VALUE")
					);
				if ($arOrderPropValues = $dbOrderPropValues->Fetch())
					$taxLocation = IntVal($arOrderPropValues["VALUE"]);

				$arTaxList = array();
				$dbTaxRateTmp = CSaleTaxRate::GetList(
						array("APPLY_ORDER" => "ASC"),
						array(
								"LID" => $arOrder["LID"],
								"PERSON_TYPE_ID" => $arOrder["PERSON_TYPE_ID"],
								"ACTIVE" => "Y",
								"LOCATION" => $taxLocation
							)
					);
				while ($arTaxRateTmp = $dbTaxRateTmp->Fetch())
				{
					if (!in_array(IntVal($arTaxRateTmp["TAX_ID"]), $arTaxExempt))
					{
						$arTaxList[] = $arTaxRateTmp;
					}
				}
			}
			else
			{
				$arTaxList[] = Array(
							"ID" => 0,
							"TAX_NAME" => GetMessage("SKGR_VAT"),
							"IS_PERCENT" => "Y",
							"VALUE" => $vatRate*100,
							"VALUE_MONEY" => 0,
							"APPLY_ORDER" => 100,
							"IS_IN_PRICE" => "Y",
							"CODE" => "VAT"
				);
			}


			$arTaxSums = array();

			if (!empty($arTaxList))
			{
				if(!$bUseVat)
				{
					$taxPriceTmp = CSaleOrderTax::CountTaxes(
							$discountPrice * DoubleVal($arProduct["QUANTITY"]),
							$arTaxList,
							$baseSiteCurrency
						);

					for ($di = 0, $intCount = count($arTaxList); $di < $intCount; $di++)
					{
						$arTaxList[$di]["VALUE_MONEY"] += $arTaxList[$di]["TAX_VAL"];
					}

					for ($di = 0, $intCount = count($arTaxList); $di < $intCount; $di++)
					{
						$arTaxSums[$arTaxList[$di]["TAX_ID"]]["VALUE"] = $arTaxList[$di]["VALUE_MONEY"];
						$arTaxSums[$arTaxList[$di]["TAX_ID"]]["NAME"] = $arTaxList[$di]["NAME"];
						if ($arTaxList[$di]["IS_IN_PRICE"] != "Y")
						{
							$taxPrice += $arTaxList[$di]["VALUE_MONEY"];
						}
					}
				}
				else
				{
					$arTaxList[0]["VALUE_MONEY"] = (($discountPrice / ($vatRate +1)) * $vatRate) * DoubleVal($arProduct["QUANTITY"]);
					$taxVatPrice = $arTaxList[0]["VALUE_MONEY"];
				}
			}


			// Changed by Sigurd, 2007-08-16
			$totalOrderPrice = $discountPrice * DoubleVal($arProduct["QUANTITY"]) + $deliveryPrice + $taxPrice;

			$arProduct["WITHOUT_ORDER"] = (($arProduct["WITHOUT_ORDER"]=="Y") ? "Y" : "N");
			if ($arProduct["WITHOUT_ORDER"] == "N")
			{
				$DB->StartTransaction();

				// Saving
				$arSaleUser = CSaleUser::GetList(Array(), Array("USER_ID" => $arOrder["USER_ID"]));
				if(!empty($arSaleUser))
				{
					$currentFUser = $arSaleUser["ID"];
				}
				else
				{
					$currentFUser = CSaleUser::_Add(
							array(
									"=DATE_INSERT" => $DB->GetNowFunction(),
									"=DATE_UPDATE" => $DB->GetNowFunction(),
									"USER_ID" => $arOrder["USER_ID"]
								)
						);
				}

				$arFields = array(
						"FUSER_ID" => $currentFUser,
						"PRODUCT_ID" => $arProduct["PRODUCT_ID"],
						"PRODUCT_NAME" => $arProduct["PRODUCT_NAME"],
						"PRODUCT_URL" => $arProduct["PRODUCT_URL"],
						"PRODUCT_PRICE_ID" => $arProduct["PRODUCT_PRICE_ID"],
						"PRICE" => $arProduct["PRICE"],
						"CURRENCY" => $arProduct["CURRENCY"],
						"WEIGHT" => $arProduct["WEIGHT"],
						"QUANTITY" => $arProduct["QUANTITY"],
						"LID" => $arOrder["LID"],
						"DELAY" => "N",
						"CAN_BUY" => "Y",
						"NAME" => $arProduct["NAME"],
						"CALLBACK_FUNC" => $arProduct["CALLBACK_FUNC"],
						"ORDER_CALLBACK_FUNC" => $arProduct["ORDER_CALLBACK_FUNC"],
						"CANCEL_CALLBACK_FUNC" => $arProduct["CANCEL_CALLBACK_FUNC"],
						"PAY_CALLBACK_FUNC" => $arProduct["PAY_CALLBACK_FUNC"],
						"PRODUCT_PROVIDER_CLASS" => $arProduct["PRODUCT_PROVIDER_CLASS"],
						"MODULE" => $arRecur["MODULE"],
						"NOTES" => $arProduct["CATALOG_GROUP_NAME"],
						"DETAIL_PAGE_URL" => $arProduct["DETAIL_PAGE_URL"],
						"VATE_RATE" => $arProduct["VATE_RATE"],
						"PRODUCT_XML_ID" => $arProduct["PRODUCT_XML_ID"],
						"RENEWAL" => "Y"
					);

				$basketID = CSaleBasket::Add($arFields);

				$basketID = IntVal($basketID);
				if ($basketID <= 0)
					$bSuccess = False;

				if ($bSuccess)
				{
					if (CModule::IncludeModule("statistic"))
						CStatistic::Set_Event("eStore", "add2basket", $arFields["PRODUCT_ID"]);

					$arFields = array(
							"LID" => $arOrder["LID"],
							"PERSON_TYPE_ID" => $arOrder["PERSON_TYPE_ID"],
							"PAYED" => "N",
							"CANCELED" => "N",
							"STATUS_ID" => "N",
							"PRICE_DELIVERY" => $deliveryPrice,
							"ALLOW_DELIVERY" => "N",
							"PRICE" => $totalOrderPrice,
							"CURRENCY" => $baseSiteCurrency,
							"DISCOUNT_VALUE" => $discount,
							"USER_ID" => $arOrder["USER_ID"],
							"PAY_SYSTEM_ID" => $arOrder["PAY_SYSTEM_ID"],
							"DELIVERY_ID" => $deliveryID,
							"USER_DESCRIPTION" => $arOrder["USER_DESCRIPTION"],
							"TAX_VALUE" => (($bUseVat)? $taxVatPrice : $taxPrice),
							"STAT_GID" => $arOrder["STAT_GID"],
							"RECURRING_ID" => $arRecur["ID"]
						);

					$newOrderID = CSaleOrder::Add($arFields);

					$newOrderID = IntVal($newOrderID);
					if ($newOrderID <= 0)
						$bSuccess = False;
				}

				if ($bSuccess)
				{
					$arDiscounts = array();
					$arDiscounts[$basketID] = $discountProduct;
					CSaleBasket::OrderBasket($newOrderID, $currentFUser, $arOrder["LID"], $arDiscounts);
				}

				if ($bSuccess)
				{
					for ($it = 0, $intCount = count($arTaxList); $it < $intCount; $it++)
					{
						$arFields = array(
							"ORDER_ID" => $newOrderID,
							"TAX_NAME" => $arTaxList[$it]["TAX_NAME"],
							"IS_PERCENT" => $arTaxList[$it]["IS_PERCENT"],
							"VALUE" => ($arTaxList[$it]["IS_PERCENT"]=="Y") ? $arTaxList[$it]["VALUE"] : RoundEx(CCurrencyRates::ConvertCurrency($arTaxList[$it]["VALUE"], $arTaxList[$it]["CURRENCY"], $baseSiteCurrency), 2),
							"VALUE_MONEY" => $arTaxList[$it]["VALUE_MONEY"],
							"APPLY_ORDER" => $arTaxList[$it]["APPLY_ORDER"],
							"IS_IN_PRICE" => $arTaxList[$it]["IS_IN_PRICE"],
							"CODE" => $arTaxList[$it]["CODE"]
							);
						CSaleOrderTax::Add($arFields);
					}

					$dbOrderPropValues = CSaleOrderPropsValue::GetList(
							array(),
							array("ORDER_ID" => $arRecur["ORDER_ID"]),
							false,
							false,
							array("ORDER_PROPS_ID", "NAME", "CODE", "VALUE", "PROP_IS_PAYER", "PROP_IS_EMAIL")
						);
					while ($arOrderPropValues = $dbOrderPropValues->Fetch())
					{
						$arFields = array(
							"ORDER_ID" => $newOrderID,
							"ORDER_PROPS_ID" => $arOrderPropValues["ORDER_PROPS_ID"],
							"NAME" => $arOrderPropValues["NAME"],
							"CODE" => $arOrderPropValues["CODE"],
							"VALUE" => $arOrderPropValues["VALUE"]
							);
						CSaleOrderPropsValue::Add($arFields);

						if ($arOrderPropValues["PROP_IS_PAYER"] == "Y")
							$payerName = $arOrderPropValues["VALUE"];
						if ($arOrderPropValues["PROP_IS_EMAIL"] == "Y")
							$payerEMail = $arOrderPropValues["VALUE"];
					}
				}

				if ($bSuccess)
				{
					if (CModule::IncludeModule("statistic"))
						CStatistic::Set_Event("eStore", "order_create", $newOrderID);
				}

				if ($bSuccess)
				{
					$strOrderList = "";
					$dbBasketTmp = CSaleBasket::GetList(
						array("NAME" => "ASC"),
						array("ORDER_ID" => $newOrderID)
					);
					while ($arBasketTmp = $dbBasketTmp->Fetch())
					{
						$strOrderList .= $arBasketTmp["NAME"]." - ".$arBasketTmp["QUANTITY"]." ".GetMessage("SALE_QUANTITY_UNIT");
						$strOrderList .= "\n";
					}

					if (strlen($payerName) <= 0 || strlen($payerEMail) <= 0)
					{
						$dbUser = CUser::GetByID($arOrder["USER_ID"]);
						if ($arUser = $dbUser->Fetch())
						{
							if (strlen($payerName) <= 0)
								$payerName = $arUser["NAME"].((strlen($arUser["NAME"])<=0 || strlen($arUser["LAST_NAME"])<=0) ? "" : " ").$arUser["LAST_NAME"];
							if (strlen($payerEMail) <= 0)
								$payerEMail = $arUser["EMAIL"];
						}
					}

					$arFields = Array(
						"ORDER_ID" => $newOrderID,
						"ORDER_DATE" => Date($DB->DateFormatToPHP(CLang::GetDateFormat("SHORT", $arOrder["LID"]))),
						"ORDER_USER" => $payerName,
						"PRICE" => SaleFormatCurrency($totalOrderPrice, $baseSiteCurrency),
						"BCC" => COption::GetOptionString("sale", "order_email", "order@".$SERVER_NAME),
						"EMAIL" => $payerEMail,
						"ORDER_LIST" => $strOrderList,
						"SALE_EMAIL" => COption::GetOptionString("sale", "order_email", "order@".$SERVER_NAME)
					);
					$eventName = "SALE_NEW_ORDER_RECURRING";

					$bSend = true;
					foreach(GetModuleEvents("sale", "OnOrderRecurringSendEmail", true) as $arEvent)
					{
						if (ExecuteModuleEventEx($arEvent, Array($newOrderID, &$eventName, &$arFields))===false)
							$bSend = false;
					}

					if($bSend)
					{
						$event = new CEvent;
						$event->Send($eventName, $arOrder["LID"], $arFields, "N");
					}
				}

				if ($bSuccess)
					$DB->Commit();
				else
					$DB->Rollback();
			}
		}
		else
		{
			$totalOrderPrice = $arOrder["PRICE"];
			$baseSiteCurrency = $arOrder["CURRENCY"];
		}

		$res = False;
		if ($bSuccess)
		{
			$res = CSaleUserAccount::Pay($arOrder["USER_ID"], $totalOrderPrice, $baseSiteCurrency, $newOrderID, True);
			if ($res)
			{
				if ($arProduct["WITHOUT_ORDER"] == "N")
				{
					CSaleOrder::PayOrder($newOrderID, "Y", False, False, $arRecur["ID"]);
					CSaleOrder::DeliverOrder($newOrderID, "Y", $arRecur["ID"]);
					CSaleOrder::DeductOrder($newOrderID, "Y", "", true, array(), $arRecur["ID"]);
				}
				else
				{
					/** @var $productProvider IBXSaleProductProvider */
					if ($productProvider = CSaleBasket::GetProductProvider($arProduct))
					{
						$r = $productProvider::DeliverProduct(array(
							"PRODUCT_ID" => $arProduct["PRODUCT_ID"],
							"USER_ID"    => $arOrder["USER_ID"],
							"PAID"       => true
						));
					}
					else
					{
						$r = CSaleBasket::ExecuteCallbackFunction(
							$arProduct["PAY_CALLBACK_FUNC"],
							$arRecur["MODULE"],
							$arProduct["PRODUCT_ID"],
							$arOrder["USER_ID"],
							true
						);
					}
				}

				$arFields = array(
					"ORDER_ID" => $newOrderID,
					"PRODUCT_NAME" => $arProduct["PRODUCT_NAME"],
					"PRODUCT_URL" => $arProduct["PRODUCT_URL"],
					"PRICE_TYPE" => $arProduct["PRICE_TYPE"],
					"RECUR_SCHEME_TYPE" => $arProduct["RECUR_SCHEME_TYPE"],
					"RECUR_SCHEME_LENGTH" => $arProduct["RECUR_SCHEME_LENGTH"],
					"WITHOUT_ORDER" => $arProduct["WITHOUT_ORDER"],
					"PRIOR_DATE" => Date($GLOBALS["DB"]->DateFormatToPHP(CLang::GetDateFormat("FULL", SITE_ID))),
					"NEXT_DATE" => $arProduct["NEXT_DATE"],
					"REMAINING_ATTEMPTS" => (Defined("SALE_PROC_REC_ATTEMPTS") ? SALE_PROC_REC_ATTEMPTS : 3),
					"SUCCESS_PAYMENT" => "Y"
				);

				CSaleRecurring::Update($arRecur["ID"], $arFields);
			}
			else
			{
				$arFields = array(
						"ORDER_ID" => $newOrderID,
						"PRODUCT_NAME" => $arProduct["PRODUCT_NAME"],
						"PRODUCT_URL" => $arProduct["PRODUCT_URL"],
						"PRICE_TYPE" => $arProduct["PRICE_TYPE"],
						"RECUR_SCHEME_LENGTH" => $arProduct["RECUR_SCHEME_LENGTH"],
						"RECUR_SCHEME_TYPE" => $arProduct["RECUR_SCHEME_TYPE"],
						"WITHOUT_ORDER" => $arProduct["WITHOUT_ORDER"],
						"NEXT_DATE" => Date($GLOBALS["DB"]->DateFormatToPHP(CLang::GetDateFormat("FULL", SITE_ID)), time() + SALE_PROC_REC_TIME + CTimeZone::GetOffset()),
						"REMAINING_ATTEMPTS" => (IntVal($arRecur["REMAINING_ATTEMPTS"]) - 1),
						"SUCCESS_PAYMENT" => "N"
					);
				CSaleRecurring::Update($arRecur["ID"], $arFields);

				if ((IntVal($arRecur["REMAINING_ATTEMPTS"]) - 1) <= 0)
				{
					CSaleRecurring::CancelRecurring($arRecur["ID"], "Y", "Can't pay order");
					/*
					$arFields["CANCELED"] = "Y";
					$arFields["DATE_CANCELED"] = Date(CDatabase::DateFormatToPHP(CLang::GetDateFormat("FULL", LANG)));
					$arFields["CANCELED_REASON"] = "Can't pay order";
					*/
				}
			}
		}

		return $res;
	}
Ejemplo n.º 8
0
 /**
  * The function add viewed product
  *
  * @param array $arFields - params for add
  * @return true false
  */
 public static function Add($arFields)
 {
     global $DB;
     global $USER;
     global $APPLICATION;
     foreach (GetModuleEvents("sale", "OnBeforeViewedAdd", true) as $arEvent) {
         if (ExecuteModuleEventEx($arEvent, array(&$arFields)) === false) {
             return false;
         }
     }
     if (isset($arFields["ID"])) {
         unset($arFields["ID"]);
     }
     $arFields["PRODUCT_ID"] = IntVal($arFields["PRODUCT_ID"]);
     $arFields["USER_ID"] = IntVal($arFields["USER_ID"]);
     $arFields["FUSER_ID"] = IntVal($arFields["FUSER_ID"]);
     $arFields["IBLOCK_ID"] = IntVal($arFields["IBLOCK_ID"]);
     if (strlen($arFields["CALLBACK_FUNC"]) <= 0) {
         $arFields["CALLBACK_FUNC"] = "CatalogViewedProductCallback";
     }
     if (strlen($arFields["MODULE"]) <= 0) {
         $arFields["MODULE"] = "catalog";
     }
     if (strlen($arFields["PRODUCT_PROVIDER_CLASS"]) <= 0 && $arFields["MODULE"] == "catalog") {
         $arFields["PRODUCT_PROVIDER_CLASS"] = "CCatalogProductProvider";
     }
     if ($arFields["PRODUCT_ID"] <= 0) {
         return false;
     }
     if (strlen($arFields["LID"]) <= 0) {
         return false;
     }
     if (\Bitrix\Main\Loader::includeModule("catalog")) {
         if (\Bitrix\Main\Config\Option::get("sale", "viewed_capability", "") == "Y") {
             return \Bitrix\Catalog\CatalogViewedProductTable::refresh($arFields["PRODUCT_ID"], CSaleBasket::GetBasketUserID(), $arFields["LID"]);
         }
     }
     $arFilter = array();
     $arFilter["PRODUCT_ID"] = $arFields["PRODUCT_ID"];
     if ($arFields["USER_ID"] > 0) {
         $arFuserItems = CSaleUser::GetList(array("USER_ID" => $arFields["USER_ID"]));
         $FUSER_ID = $arFuserItems["ID"];
     } elseif (IntVal($arFields["FUSER_ID"]) > 0) {
         $FUSER_ID = $arFields["FUSER_ID"];
     } else {
         $FUSER_ID = CSaleBasket::GetBasketUserID();
     }
     $arFilter["FUSER_ID"] = $FUSER_ID;
     $arFields["FUSER_ID"] = $FUSER_ID;
     $db_res = CSaleViewedProduct::GetList(array(), $arFilter, false, false, array('ID'));
     if (!($arItems = $db_res->Fetch())) {
         if (CModule::IncludeModule('catalog')) {
             /** @var $productProvider IBXSaleProductProvider */
             if ($productProvider = CSaleBasket::GetProductProvider($arFields)) {
                 $arResultTmp = $productProvider::ViewProduct(array("PRODUCT_ID" => $arFields["PRODUCT_ID"], "USER_ID" => $arFields["USER_ID"], "SITE_ID" => $arFields["LID"]));
             } else {
                 $arResultTmp = CSaleBasket::ExecuteCallbackFunction($arFields["CALLBACK_FUNC"], $arFields["MODULE"], $arFields["PRODUCT_ID"], $arFields["USER_ID"], $arFields["LID"]);
             }
             if ($arResultTmp && count($arResultTmp) > 0) {
                 $arFields = array_merge($arFields, $arResultTmp);
             }
             if (strlen($arFields["NAME"]) <= 0) {
                 return false;
             }
             $arInsert = $DB->PrepareInsert("b_sale_viewed_product", $arFields);
             //chance deleted
             $rnd = mt_rand(0, 1000);
             if ($rnd < 100) {
                 $db_res = CSaleViewedProduct::GetList(array(), array("FUSER_ID" => $FUSER_ID), array("COUNT" => "ID"), false);
                 $arCount = $db_res->Fetch();
                 $viewedCount = COption::GetOptionString("sale", "viewed_count", "100");
                 if ($arCount["ID"] > IntVal($viewedCount)) {
                     $limit = $arCount["ID"] - $viewedCount + $viewedCount * 0.2;
                     CSaleViewedProduct::DeleteForUser($FUSER_ID, $limit);
                 }
             }
             $strSql = "INSERT INTO b_sale_viewed_product (" . $arInsert[0] . ", DATE_VISIT) VALUES(" . $arInsert[1] . ", " . $DB->GetNowFunction() . ")";
             $DB->Query($strSql, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
             $ID = IntVal($DB->LastID());
         }
     } else {
         $ID = IntVal($arItems["ID"]);
         $arFields["DATE_VISIT"] = $DB->GetNowFunction();
         $arInsert = $DB->PrepareInsert("b_sale_viewed_product", $arFields);
         CSaleViewedProduct::Update($ID, $arFields);
     }
     foreach (GetModuleEvents("sale", "OnViewedAdd", true) as $arEvent) {
         ExecuteModuleEventEx($arEvent, array($arFields));
     }
     return $ID;
 }
Ejemplo n.º 9
0
 public static function catchCatalogBasket($id, $arFields)
 {
     // exclude empty cookie
     if (!static::getBxUserId()) {
         return;
     }
     if (!isset($arFields['MODULE']) || $arFields['MODULE'] != 'catalog') {
         // catalog items only
         return;
     }
     global $APPLICATION;
     // alter b_sale_basket - add recommendation, update it here
     if (!static::isOn()) {
         return;
     }
     // get product id by offer id
     $productInfo = \CCatalogSKU::GetProductInfo($arFields['PRODUCT_ID']);
     $iblockId = 0;
     if (!empty($productInfo['ID'])) {
         $realProductId = $productInfo['ID'];
         $iblockId = $productInfo['IBLOCK_ID'];
     } else {
         $realProductId = $arFields['PRODUCT_ID'];
         // get iblock id
         $element = \Bitrix\Iblock\ElementTable::getRow(array('select' => array('IBLOCK_ID'), 'filter' => array('=ID' => $realProductId)));
         if (!empty($element)) {
             $iblockId = $element['IBLOCK_ID'];
         }
     }
     // select site user id & recommendation id
     $siteUserId = 0;
     $recommendationId = '';
     // first, try to find in cookies
     $recommendationCookie = $APPLICATION->get_cookie(static::getCookieLogName());
     if (!empty($recommendationCookie)) {
         $recommendations = static::decodeProductLog($recommendationCookie);
         if (is_array($recommendations) && isset($recommendations[$realProductId])) {
             $recommendationId = $recommendations[$realProductId][0];
         }
     }
     if (empty($recommendationId)) {
         // ok then, lets see in views history
         //if(\COption::GetOptionString("sale", "encode_fuser_id", "N") == "Y")
         if (!is_numeric($arFields['FUSER_ID'])) {
             $filter = array('CODE' => $arFields['FUSER_ID']);
         } else {
             $filter = array('ID' => $arFields['FUSER_ID']);
         }
         $result = \CSaleUser::getList($filter);
         if (!empty($result)) {
             $siteUserId = $result['USER_ID'];
             // select recommendation id
             $fuser = $result['ID'];
             $viewResult = CatalogViewedProductTable::getList(array('select' => array('RECOMMENDATION'), 'filter' => array('=FUSER_ID' => $fuser, '=PRODUCT_ID' => $arFields['PRODUCT_ID']), 'order' => array('DATE_VISIT' => 'DESC')))->fetch();
             if (!empty($viewResult['RECOMMENDATION'])) {
                 $recommendationId = $viewResult['RECOMMENDATION'];
             }
         }
     }
     // prepare data
     $data = array('product_id' => $realProductId, 'iblock_id' => $iblockId, 'user_id' => $siteUserId, 'bx_user_id' => static::getBxUserId(), 'domain' => Context::getCurrent()->getServer()->getHttpHost(), 'recommendation' => $recommendationId, 'date' => date(DATE_ISO8601));
     // debug info
     global $USER;
     $data['real_user_id'] = $USER->getId() ?: 0;
     $data['is_admin'] = (int) $USER->IsAdmin();
     $data['admin_section'] = (int) (defined('ADMIN_SECTION') && ADMIN_SECTION);
     $data['admin_panel'] = (int) \CTopPanel::shouldShowPanel();
     // try to guess unnatural baskets
     $data['artificial_basket'] = (int) ($data['user_id'] > 0 && $data['user_id'] != $data['real_user_id'] || $data['is_admin'] || $data['admin_section'] || $data['admin_panel']);
     // save
     CounterDataTable::add(array('TYPE' => 'basket', 'DATA' => $data));
     // update basket with recommendation id
     if (!empty($recommendationId)) {
         $conn = Application::getConnection();
         $helper = $conn->getSqlHelper();
         $conn->query("UPDATE " . $helper->quote('b_sale_basket') . " SET RECOMMENDATION='" . $helper->forSql($recommendationId) . "' WHERE ID=" . (int) $id);
     }
 }
Ejemplo n.º 10
0
 /**
  * @param Order $order
  * @param array $formData
  * @param array $files
  * @return bool|int|string
  * @throws UserMessageException
  */
 protected static function createUserFromForm(Order &$order, array $formData)
 {
     $errors = array();
     $orderProps = $order->getPropertyCollection();
     if ($email = $orderProps->getUserEmail()) {
         $email = $email->getValue();
     }
     if ($name = $orderProps->getPayerName()) {
         $name = $name->getValue();
     }
     $userId = \CSaleUser::DoAutoRegisterUser($email, $name, $formData["SITE_ID"], $errors);
     if (!empty($errors)) {
         $errorMessage = "";
         foreach ($errors as $val) {
             $errorMessage .= $val["TEXT"];
         }
         throw new UserMessageException($errorMessage);
     }
     return $userId;
 }
Ejemplo n.º 11
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;
			}
		}
Ejemplo n.º 12
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");
			}
		}
	}
Ejemplo n.º 13
0
<?php

$_SERVER["DOCUMENT_ROOT"] = realpath(dirname(__FILE__) . "/..");
$DOCUMENT_ROOT = $_SERVER["DOCUMENT_ROOT"];
define("NO_KEEP_STATISTIC", true);
define("NOT_CHECK_PERMISSIONS", true);
define('CHK_EVENT', true);
require $_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/include/prolog_before.php";
@set_time_limit(0);
@ignore_user_abort(true);
CModule::IncludeModule('sale');
$arBasketItemsToUser = array();
$dbBasketItems = CSaleBasket::GetList(array(), array(">DATE_INSERT" => date($DB->DateFormatToPHP(CLang::GetDateFormat("SHORT")), mktime() - 60 * 60 * 24 * 30), ">USER_ID" => 0, "DELAY" => "Y"));
//get list of positions inserted in 30 days
while ($arItem = $dbBasketItems->Fetch()) {
    $arUser = CSaleUser::GetList(array('ID' => $arItem['FUSER_ID']));
    $arItem["USER_ID"] = $arUser["USER_ID"];
    $dbBasketItemsCheck = CSaleBasket::GetList(array(), array("PRODUCT_ID" => $arItem["PRODUCT_ID"], "USER_ID" => $arItem["USER_ID"], ">ORDER_ID" => 0));
    if (!$dbBasketItemsCheck->Fetch()) {
        $arBasketItemsToUser[$arItem["USER_ID"]][] = $arItem;
        //filling array with list of positions to user
    }
}
$ORDERLIST = '';
$arEventFields = array();
//Parameters for post template
foreach ($arBasketItemsToUser as $USER_ID => $basketItems) {
    $rsUser = CUser::GetByID($USER_ID);
    if ($arUser = $rsUser->Fetch()) {
        foreach ($basketItems as $basketItem) {
            $ORDERLIST .= $basketItem["NAME"] . ' - ' . $basketItem["PRICE"] . " " . $basketItem["CURRENCY"] . "<br />";
Ejemplo n.º 14
0
     }
 }
 $lAdmin_tab4->AddGroupActionTable(array("order_basket" => GetMessage("BUYER_PD_ORDER"), "delay_y" => GetMessage("BUYER_PD_DELAY_Y"), "delay_n" => GetMessage("BUYER_PD_DELAY_N"), "delete_basket" => GetMessage("BUYER_PD_DELETE")));
 if ($_REQUEST["table_id"] == $sTableID_tab4) {
     $lAdmin_tab4->CheckListMode();
 }
 //END BUYERS BASKET
 //BUYERS VIEWED PRODUCT
 $sTableID_tab5 = "t_stat_list_tab5";
 $oSort_tab5 = new CAdminSorting($sTableID_tab5);
 $lAdmin_tab5 = new CAdminList($sTableID_tab5, $oSort_tab5);
 //FILTER VIEWED
 $arFilterFields = array("filter_viewed_date_visit", "filter_date_visit_from", "filter_date_visit_to", "filter_viewed_lid");
 $lAdmin_tab5->InitFilter($arFilterFields);
 $arFilter = array();
 $arFuserItems = CSaleUser::GetList(array("USER_ID" => $ID));
 $arFilter["FUSER_ID"] = $arFuserItems["ID"];
 if (strlen($filter_viewed_lid) > 0) {
     $arFilter["LID"] = trim($filter_viewed_lid);
 }
 if (strlen(trim($filter_date_visit_from)) > 0) {
     $arFilter["DATE_FROM"] = FmtDate($filter_date_visit_from, "D.M.Y");
 }
 if (strlen(trim($filter_date_visit_to)) > 0) {
     if ($arDate = ParseDateTime($filter_date_visit_to, CSite::GetDateFormat("FULL", SITE_ID))) {
         if (StrLen($filter_date_visit_to) < 11) {
             $arDate["HH"] = 23;
             $arDate["MI"] = 59;
             $arDate["SS"] = 59;
         }
         $filter_date_visit_to = date($DB->DateFormatToPHP(CSite::GetDateFormat("FULL", SITE_ID)), mktime($arDate["HH"], $arDate["MI"], $arDate["SS"], $arDate["MM"], $arDate["DD"], $arDate["YYYY"]));
Ejemplo n.º 15
0
 function DeleteOld($nDays)
 {
     global $DB;
     $nDays = IntVal($nDays);
     $strSql = "SELECT ID " . "FROM b_sale_fuser " . "WHERE TO_DAYS(DATE_UPDATE)<(TO_DAYS(NOW())-" . $nDays . ") LIMIT 300";
     $db_res = $DB->Query($strSql, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
     while ($ar_res = $db_res->Fetch()) {
         CSaleBasket::DeleteAll($ar_res["ID"], false);
         CSaleUser::Delete($ar_res["ID"]);
     }
     return true;
 }
Ejemplo n.º 16
0
 public static function DeleteOld($nDays)
 {
     global $DB;
     $nDays = IntVal($nDays);
     $strSql = "SELECT f.ID " . "FROM b_sale_fuser f " . "LEFT JOIN b_sale_order o ON (o.USER_ID = f.USER_ID) " . "WHERE " . "\tTO_DAYS(f.DATE_UPDATE)<(TO_DAYS(NOW())-" . $nDays . ") " . "\tAND o.ID is null " . "\tAND f.USER_ID is null " . "LIMIT 300";
     $db_res = $DB->Query($strSql, false, "File: " . __FILE__ . "<br>Line: " . __LINE__);
     while ($ar_res = $db_res->Fetch()) {
         CSaleBasket::DeleteAll($ar_res["ID"], false);
         CSaleUser::Delete($ar_res["ID"]);
     }
     return true;
 }
Ejemplo n.º 17
0
     $arResult["ERRORS"] = 'NOTIFY_ERR_NULL';
 }
 if (COption::GetOptionString("main", "captcha_registration", "N") == "Y" || isset($_SESSION["NOTIFY_PRODUCT"]["CAPTHA"]) && $_SESSION["NOTIFY_PRODUCT"]["CAPTHA"] == "Y") {
     if (!$APPLICATION->CaptchaCheckCode($_REQUEST["captcha_word"], $_REQUEST["captcha_sid"])) {
         $arResult["ERRORS"] = 'NOTIFY_ERR_CAPTHA';
     }
 }
 if (strlen($user_mail) > 0 && strlen($arResult["ERRORS"]) <= 0) {
     $res = CUser::GetList($b, $o, array("=EMAIL" => $user_mail));
     if ($res->Fetch()) {
         $arResult["ERRORS"] = 'NOTIFY_ERR_MAIL_EXIST';
     }
 }
 if (strlen($arResult["ERRORS"]) <= 0) {
     if (strlen($user_mail) > 0 && COption::GetOptionString("main", "new_user_registration", "N") == "Y") {
         $user_id = CSaleUser::DoAutoRegisterUser($user_mail, array(), SITE_ID, $arErrors);
         if ($user_id > 0) {
             $USER->Authorize($user_id);
             if (count($arErrors) > 0) {
                 $arResult["ERRORS"] = $arErrors[0]["TEXT"];
             }
         } else {
             $arResult["ERRORS"] = 'NOTIFY_ERR_REG';
         }
     } else {
         $arAuthResult = $USER->Login($user_login, $user_password, "Y");
         $rs = $APPLICATION->arAuthResult = $arAuthResult;
         if (count($rs) > 0 && $rs["TYPE"] == "ERROR") {
             $arResult["ERRORS"] = $rs["MESSAGE"];
         }
     }
Ejemplo n.º 18
0
 public static function HasProductRows($productID)
 {
     if (!CModule::IncludeModule('sale')) {
         return false;
     }
     $result = false;
     $saleUserId = intval(CSaleUser::GetAnonymousUserID());
     $CSaleBasket = new CSaleBasket();
     $dbRes = $CSaleBasket->GetList(array(), array('PRODUCT_ID' => $productID, '>ORDER_ID' => 0, 'USER_ID' => $saleUserId), false, array('nTopCount' => 1), array('ID'));
     if (is_object($dbRes)) {
         $arRes = $dbRes->Fetch();
         if (is_array($arRes) && isset($arRes['ID']) && intval($arRes['ID']) > 0) {
             $result = true;
         }
     }
     return $result;
 }
Ejemplo n.º 19
0
 public static function Calculate($productRows, $currencyID, $personTypeID, $enableSaleDiscount = false, $siteId = SITE_ID, $arOptions = array())
 {
     if (!CModule::IncludeModule('sale')) {
         return array('err' => '1');
     }
     $saleUserId = intval(CSaleUser::GetAnonymousUserID());
     if ($saleUserId <= 0) {
         return array('err' => '2');
     }
     if (!is_array($productRows) && empty($productRows)) {
         return array('err' => '3');
     }
     $bTaxMode = CCrmTax::isTaxMode();
     if ($bTaxMode) {
         foreach ($productRows as &$productRow) {
             $productRow['TAX_RATE'] = 0.0;
             $productRow['TAX_INCLUDED'] = 'N';
         }
         unset($productRow);
     }
     $cartItems = self::PrepareShoppingCartItems($productRows, $currencyID, $siteId);
     foreach ($cartItems as &$item) {
         $item['ID_TMP'] = $item['ID'];
         unset($item['ID']);
     }
     unset($item);
     $errors = array();
     $cartItems = CSaleBasket::DoGetUserShoppingCart($siteId, $saleUserId, $cartItems, $errors, array(), 0, true);
     foreach ($cartItems as &$item) {
         $item['ID'] = $item['ID_TMP'];
         unset($item['ID_TMP']);
     }
     unset($item);
     $personTypeID = intval($personTypeID);
     if ($personTypeID <= 0) {
         $personTypes = CCrmPaySystem::getPersonTypeIDs();
         if (isset($personTypes['CONTACT'])) {
             $personTypeID = intval($personTypes['CONTACT']);
         }
     }
     if ($personTypeID <= 0) {
         return array('err' => '4');
     }
     $orderPropsValues = array();
     $paySystemId = 0;
     if (is_array($arOptions) && !empty($arOptions)) {
         if (isset($arOptions['LOCATION_ID']) && CCrmTax::isTaxMode()) {
             $locationPropertyID = self::getLocationPropertyId($personTypeID);
             if ($locationPropertyID !== false) {
                 $orderPropsValues[$locationPropertyID] = $arOptions['LOCATION_ID'];
             }
         }
         if (isset($arOptions['PAY_SYSTEM_ID'])) {
             $paySystemId = intval($arOptions['PAY_SYSTEM_ID']);
         }
     }
     $warnings = array();
     $options = array('CURRENCY' => $currencyID);
     if (!$enableSaleDiscount) {
         $options['CART_FIX'] = 'Y';
     }
     return CSaleOrder::DoCalculateOrder($siteId, $saleUserId, $cartItems, $personTypeID, $orderPropsValues, 0, $paySystemId, $options, $errors, $warnings);
 }
Ejemplo n.º 20
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;
 }
Ejemplo n.º 21
0
 function OnUserDelete($userID)
 {
     if ($userID <= 0) {
         return false;
     }
     $arSUser = CSaleUser::GetList(array("USER_ID" => $userID));
     if (!empty($arSUser)) {
         if (!CSaleBasket::DeleteAll($arSUser["ID"])) {
             return false;
         }
         if (!CSaleUser::Delete($arSUser["ID"])) {
             return false;
         }
     }
     return true;
 }
Ejemplo n.º 22
0
 protected function createUser($email, $name)
 {
     $errors = array();
     $userId = \CSaleUser::DoAutoRegisterUser($email, $name, $this->siteId, $errors);
     if (!empty($errors)) {
         $errorMessage = "";
         foreach ($errors as $val) {
             $errorMessage .= $val["TEXT"];
         }
         throw new SystemException($errorMessage);
     }
     return $userId;
 }
Ejemplo n.º 23
0
        $arSitesShop[] = array("ID" => $key, "NAME" => $val["NAME"]);
    }
}
if (empty($arSitesShop)) {
    $arSitesShop = $arSites;
}
$arCountry = GetCountryArray();
$arCountry["reference_id"] = array_flip($arCountry["reference_id"]);
/*
 * select all user (byuers)
 */
$arHeaders = array(array("id" => "USER_ID", "content" => "ID", "sort" => "USER_ID"), array("id" => "BUYER", "content" => GetMessage("BUYER_ROW_BUYER"), "sort" => "NAME", "default" => true), array("id" => "LOGIN", "content" => GetMessage("BUYER_ROW_LOGIN"), "sort" => "LOGIN"), array("id" => "LAST_NAME", "content" => GetMessage("BUYER_ROW_LAST"), "sort" => "LAST_NAME"), array("id" => "NAME", "content" => GetMessage("BUYER_ROW_NAME"), "sort" => "NAME"), array("id" => "SECOND_NAME", "content" => GetMessage("BUYER_ROW_SECOND"), "sort" => "SECOND_NAME"), array("id" => "EMAIL", "content" => GetMessage("BUYER_ROW_MAIL"), "sort" => "EMAIL", "default" => true), array("id" => "PERSONAL_PHONE", "content" => GetMessage("BUYER_ROW_PHONE"), "sort" => "PERSONAL_PHONE", "default" => true), array("id" => "LAST_LOGIN", "content" => GetMessage('BUYER_ROW_LAST_LOGIN'), "sort" => "LAST_LOGIN", "default" => false), array("id" => "DATE_REGISTER", "content" => GetMessage('BUYER_ROW_DATE_REGISTER'), "sort" => "DATE_REGISTER", "default" => true), array("id" => "LAST_ORDER_DATE", "content" => GetMessage('BUYER_ROW_LAST_ORDER_DATE'), "sort" => "LAST_ORDER_DATE", "default" => true), array("id" => "ORDER_COUNT", "content" => GetMessage('BUYER_ROW_COUNT_ORDER'), "sort" => "ORDER_COUNT", "default" => true, "align" => "right"), array("id" => "ORDER_SUM", "content" => GetMessage('BUYER_ROW_SUM_ORDER'), "sort" => "ORDER_SUM", "default" => true, "align" => "right"), array("id" => "GROUPS_ID", "content" => GetMessage('BUYER_ROW_GROUP')));
$lAdmin->AddHeaders($arHeaders);
$arVisibleColumns = $lAdmin->GetVisibleHeaderColumns();
$arOrderBuyer[$by] = $order;
$dbUsersList = CSaleUser::GetBuyersList($arOrderBuyer, $arFilter, false, array("nPageSize" => CAdminResult::GetNavSize($sTableID)), array("ID", "LID", "ACTIVE", "DATE_REGISTER", "LOGIN", "EMAIL", "NAME", "LAST_NAME", "SECOND_NAME", "PERSONAL_PHONE", "USER_ID", "LAST_LOGIN", "ORDER_COUNT", "ORDER_SUM", "CURRENCY", "LAST_ORDER_DATE"));
$dbUsersList = new CAdminResult($dbUsersList, $sTableID);
$dbUsersList->NavStart();
$lAdmin->NavText($dbUsersList->GetNavPrint(GetMessage("BUYER_PRLIST")));
while ($arBuyers = $dbUsersList->Fetch()) {
    $row =& $lAdmin->AddRow($arBuyers["USER_ID"], $arBuyers, "sale_buyers_profile.php?USER_ID=" . $arBuyers["USER_ID"] . "&lang=" . LANGUAGE_ID, GetMessage("BUYER_SUB_ACTION_PROFILE"));
    $profile = '<a href="sale_buyers_profile.php?USER_ID=' . $arBuyers["USER_ID"] . '&lang=' . LANGUAGE_ID . '">' . $arBuyers["USER_ID"] . '</a>';
    $row->AddField("USER_ID", $profile);
    if (floatVal($arBuyers["ORDER_SUM"]) > 0 && in_array("ORDER_SUM", $arVisibleColumns)) {
        $row->AddField("ORDER_SUM", SaleFormatCurrency($arBuyers["ORDER_SUM"], $arBuyers["CURRENCY"]));
    }
    if (floatVal($arBuyers["ORDER_COUNT"]) <= 0) {
        $row->AddField("ORDER_COUNT", '&nbsp;');
    }
    if (in_array("GROUPS_ID", $arVisibleColumns)) {
        $strUserGroup = '';
Ejemplo n.º 24
0
     } elseif (!check_email($payerEMail)) {
         $errorMessage .= GetMessage("STOF_ERROR_REG_BAD_EMAIL") . "<br>";
     }
     $pos = strpos($payerEMail, "@");
     $payerEMailNew = substr($payerEMail, 0, $pos);
     $dbUserLogin = CUser::GetByLogin($payerEMailNew);
     if ($arUserLogin = $dbUserLogin->Fetch()) {
         $errorMessage .= GetMessage("STOF_ERROR_REG_UNIQUE_LOGIN") . "<br>";
     }
     $rsUsers = CUser::GetList($by = "id", $order = "desc", array("EMAIL" => $payerEMail));
     $arUser = $rsUsers->Fetch();
     if (count($arUser) > 1) {
         $errorMessage .= GetMessage("STOF_ERROR_REG_UNIQUE_EMAIL") . "<br>";
     }
     if ('' == $errorMessage) {
         $user_id = CSaleUser::DoAutoRegisterUser($payerEMail, $payerName, SITE_ID, $arErrors, array());
         if ($user_id > 0 && empty($arErrors)) {
             $USER->Authorize($user_id);
             $currentUserId = (int) $USER->GetID();
             //send mail register user
             if ($arParams["SEND_NEW_USER_NOTIFY"] == "Y") {
                 $userNew = str_replace("#FIO#", "(" . $arUser["LOGIN"] . ") " . $payerName, GetMessage("NEWO_BUYER_REG_OK"));
                 CUser::SendUserInfo($user_id, SITE_ID, $userNew, true);
             }
         } else {
             foreach ($arErrors as $val) {
                 $errorMessage .= $val["TEXT"] . "<br>";
             }
         }
     }
 }
Ejemplo n.º 25
0
}
function getPropertyByCode($propertyCollection, $code)
{
    foreach ($propertyCollection as $property) {
        if ($property->getField('CODE') == $code) {
            return $property;
        }
    }
}
$siteId = \Bitrix\Main\Context::getCurrent()->getSite();
$fio = 'Пупкин Василий';
$phone = '9511111111';
$email = '*****@*****.**';
$currencyCode = Option::get('sale', 'default_currency', 'RUB');
DiscountCouponsManager::init();
$order = Order::create($siteId, \CSaleUser::GetAnonymousUserID());
$order->setPersonTypeId(1);
$basket = Sale\Basket::loadItemsForFUser(\CSaleBasket::GetBasketUserID(), $siteId)->getOrderableItems();
/* Действия над товарами
$basketItems = $basket->getBasketItems();
foreach ($basketItems as $basketItem) {
    
}
*/
$order->setBasket($basket);
/*Shipment*/
$shipmentCollection = $order->getShipmentCollection();
$shipment = $shipmentCollection->createItem();
$shipment->setFields(['DELIVERY_ID' => 1, 'CURRENCY' => $currencyCode]);
/**/
/*Payment*/
Ejemplo n.º 26
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(), array("IBLOCK_TYPE" => "offers", "IBLOCK_SITE_ID" => WIZARD_SITE_ID, "PROPERTY_NEWPRODUCT" => false), false, array("nTopCount" => 100), array("ID", "IBLOCK_ID", "XML_ID", "NAME", "DETAIL_PAGE_URL", "IBLOCK_XML_ID"));
     while ($arItem = $dbItem->GetNext()) {
         $arPrd[] = $arItem;
     }
     if (!empty($arPrd)) {
         $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"]);
         $fuserID = 0;
         $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"]);
             $fuserID = CSaleUser::_Add($arFields);
         } else {
             $fuserID = $dbFUserListTmp['ID'];
         }
         $orderID = CSaleOrder::Add($arOrder);
         CCatalogProduct::setPriceVatIncludeMode(true);
         CCatalogProduct::setUsedCurrency(CSaleLang::GetLangCurrency(WIZARD_SITE_ID));
         CCatalogProduct::setUseDiscount(true);
         for ($i = 0; $i < $prdCnt; $i++) {
             $prdID = $arPrd[mt_rand(20, 99)];
             $arProduct = CCatalogProduct::GetByID($prdID["ID"]);
             $arPrice = CCatalogProduct::GetOptimalPrice($prdID["ID"], 1, array(2), 'N', array(), WIZARD_SITE_ID, array());
             $arFields = array("IGNORE_CALLBACK_FUNC" => "Y", "PRODUCT_ID" => $prdID["ID"], "PRODUCT_PRICE_ID" => $arPrice['PRICE']['ID'], "BASE_PRICE" => $arPrice['RESULT_PRICE']['BASE_PRICE'], "PRICE" => $arPrice['RESULT_PRICE']['DISCOUNT_PRICE'], "VAT_RATE" => $arPrice['PRICE']['VAT_RATE'], "CURRENCY" => $arPrice['RESULT_PRICE']['CURRENCY'], "WEIGHT" => $arProduct["WEIGHT"], "DIMENSIONS" => serialize(array("WIDTH" => $arProduct["WIDTH"], "HEIGHT" => $arProduct["HEIGHT"], "LENGTH" => $arProduct["LENGTH"])), "QUANTITY" => 1, "LID" => WIZARD_SITE_ID, "DELAY" => "N", "CAN_BUY" => "Y", "NAME" => $prdID["NAME"], "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"], "NOTES" => $arPrice["PRICE"]["CATALOG_GROUP_NAME"], "FUSER_ID" => $fuserID, "ORDER_ID" => $orderID);
             $addres = CSaleBasket::Add($arFields);
         }
         $dbBasketItems = CSaleBasket::GetList(array(), array("ORDER_ID" => $orderID), false, false, array("ID", "QUANTITY", "PRICE"));
         $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;
     }
 }
Ejemplo n.º 27
0
									$arRecommendedResult = CSaleProduct::GetRecommendetProduct($arOrder["USER_ID"], $arOrder["LID"], $arFilterRecomendet);
									$recomCnt = count($arRecommendedResult);

									if ($recomCnt > 2)
									{
										$arTmp = array();
										$arTmp[] = $arRecommendedResult[0];
										$arTmp[] = $arRecommendedResult[1];
										$arRecommendedResult = $arTmp;
									}
									if ($recomCnt <= 0)
										$displayNone = "none";

									$arErrors = array();
									$arFuserItems = CSaleUser::GetList(array("USER_ID" => intval($arOrder["USER_ID"])));

									$arCartWithoutSetItems = array();
									$arTmpShoppingCart = CSaleBasket::DoGetUserShoppingCart($arOrder["LID"], $arOrder["USER_ID"], $arFuserItems["ID"], $arErrors, array());
									if (is_array($arTmpShoppingCart))
									{
										foreach ($arTmpShoppingCart as $arCartItem)
										{
											if (CSaleBasketHelper::isSetItem($arCartItem))
												continue;

											$arCartWithoutSetItems[] = $arCartItem;
										}
									}
									$basketCnt = count($arCartWithoutSetItems);
									if ($basketCnt > 2)
Ejemplo n.º 28
0
 protected function addProductToBasketAction()
 {
     if (!$this->request["formData"]) {
         throw new ArgumentNullException("formatData");
     }
     if (!$this->request["quantity"]) {
         throw new ArgumentNullException("quantity");
     }
     if (!$this->request["productId"]) {
         throw new ArgumentNullException("productId");
     }
     $productId = isset($this->request['productId']) ? intval($this->request['productId']) : 0;
     $quantity = isset($this->request['quantity']) ? intval($this->request['quantity']) : 1;
     $columns = isset($this->request['columns']) ? $this->request['columns'] : array();
     $alreadyInBasketCode = "";
     $productParams = array();
     if (isset($this->request["formData"]["PRODUCT"]) && is_array($this->request["formData"]["PRODUCT"])) {
         foreach ($this->request["formData"]["PRODUCT"] as $basketCode => &$params) {
             if (!isset($params["MODULE"]) || $params["MODULE"] != "catalog") {
                 continue;
             }
             if (!isset($params["OFFER_ID"]) || $params["OFFER_ID"] != $productId) {
                 continue;
             }
             $params["QUANTITY"] += $quantity;
             $alreadyInBasketCode = $basketCode;
             $productParams = $params;
             break;
         }
     }
     if (empty($productParams)) {
         $productParams = Admin\Blocks\OrderBasket::getProductDetails($productId, $quantity, !empty($this->request["formData"]["USER_ID"]) ? $this->request["formData"]["USER_ID"] : \CSaleUser::GetAnonymousUserID(), isset($this->request["formData"]["SITE_ID"]) ? $this->request["formData"]["SITE_ID"] : SITE_ID, $columns);
     }
     if (isset($this->request["replaceBasketCode"]) && strlen($this->request["replaceBasketCode"]) > 0 && isset($this->request["formData"]["PRODUCT"][$this->request["replaceBasketCode"]])) {
         $this->request["formData"]["PRODUCT"][$this->request["replaceBasketCode"]] = $productParams;
         if (strlen($alreadyInBasketCode) > 0) {
             unset($this->request["formData"]["PRODUCT"][$alreadyInBasketCode]);
         }
     } elseif (strlen($alreadyInBasketCode) <= 0) {
         $this->request["formData"]["PRODUCT"]["new"] = $productParams;
     }
     $this->formDataChanged = true;
 }
Ejemplo n.º 29
0
if (!isset($str_TAX_VALUE) OR $str_TAX_VALUE == "")
	$str_TAX_VALUE = 0;

if (intval($str_PERSON_TYPE_ID) <= 0)
{
	$str_PERSON_TYPE_ID = 0;
	$arFilter = array();
	$arFilter["ACTIVE"] = "Y";
	if(strlen($LID) > 0)
		$arFilter["LID"] = $LID;
	$dbPersonType = CSalePersonType::GetList(array("SORT" => "ASC", "NAME" => "ASC"), $arFilter, false, array('nTopCount' => 1), array('ID'));
	if($arPersonType = $dbPersonType->Fetch())
		$str_PERSON_TYPE_ID = $arPersonType["ID"];
}

$arFuserItems = CSaleUser::GetList(array("USER_ID" => intval($str_USER_ID)));
$FUSER_ID = $arFuserItems["ID"];

/*
 * form select site
 */
if ((!isset($LID) OR $LID == "") AND (defined('BX_PUBLIC_MODE') OR BX_PUBLIC_MODE == 1) )
{
	$arSitesShop = array();
	$arSitesTmp = array();
	$rsSites = CSite::GetList($by="id", $order="asc", array("ACTIVE" => "Y"));
	while ($arSite = $rsSites->Fetch())
	{
		$site = COption::GetOptionString("sale", "SHOP_SITE_".$arSite["ID"], "");
		if ($arSite["ID"] == $site)
		{
Ejemplo n.º 30
0
 /**
  * @param array $basketList
  * @param array $select
  * @return array
  * @throws ObjectNotFoundException
  */
 protected static function createProviderBasketMap(array $basketList, array $select = array())
 {
     $basketProviderMap = array();
     /**
      * @var string $basketKey
      * @var BasketItem $basketItem
      */
     foreach ($basketList as $basketIndex => $basketItemDat) {
         if (is_array($basketItemDat) && isset($basketItemDat['BASKET_ITEM'])) {
             $basketItem = $basketItemDat['BASKET_ITEM'];
         } else {
             $basketItem = $basketItemDat;
         }
         $basketProviderData = array('BASKET_ITEM' => $basketItem, 'BASKET_ID' => $basketItem->getId(), 'BASKET_CODE' => $basketItem->getBasketCode(), 'PRODUCT_ID' => $basketItem->getProductId(), 'MODULE' => $basketItem->getField('MODULE'));
         if ($provider = $basketItem->getProvider()) {
             $basketProviderData['PROVIDER'] = $provider;
         } elseif (strval($basketItem->getField('CALLBACK_FUNC')) != '' || strval($basketItem->getField('PAY_CALLBACK_FUNC')) != '') {
             $basketProviderData['CALLBACK_FUNC'] = strval($basketItem->getField('CALLBACK_FUNC')) != '' ? $basketItem->getField('CALLBACK_FUNC') : $basketItem->getField('PAY_CALLBACK_FUNC');
         } else {
             continue;
         }
         if (in_array('QUANTITY', $select)) {
             $basketProviderData['QUANTITY'] = $basketItem->getQuantity();
             // ????
         }
         if (in_array('RENEWAL', $select)) {
             $basketProviderData['RENEWAL'] = $basketItem->getField('RENEWAL') !== null && $basketItem->getField('RENEWAL') != 'N' ? 'Y' : 'N';
         }
         if (in_array('RESERVED', $select)) {
             $basketProviderData['RESERVED'] = $basketItemDat['RESERVED'];
         }
         if (in_array('SITE_ID', $select)) {
             $basketProviderData['SITE_ID'] = $basketItem->getField('LID');
         }
         if (in_array('ORDER_ID', $select)) {
             /** @var Basket $basket */
             if (!($basket = $basketItem->getCollection())) {
                 throw new ObjectNotFoundException('Entity "Basket" not found');
             }
             if ($basket->getOrder() && $basket->getOrderId() > 0) {
                 $basketProviderData['ORDER_ID'] = $basket->getOrderId();
             }
         }
         if (in_array('USER_ID', $select)) {
             /** @var Basket $basket */
             if (!($basket = $basketItem->getCollection())) {
                 throw new ObjectNotFoundException('Entity "Basket" not found');
             }
             if ($order = $basket->getOrder()) {
                 $userId = $order->getUserId();
                 if ($userId === null) {
                     $userId = \CSaleUser::GetUserID($basket->getFUserId());
                 }
                 if ($userId > 0) {
                     $basketProviderData['USER_ID'] = $userId;
                 }
             }
         }
         if (in_array('PAID', $select)) {
             /** @var Basket $basket */
             if (!($basket = $basketItem->getCollection())) {
                 throw new ObjectNotFoundException('Entity "Basket" not found');
             }
             if ($basket->getOrder() && $basket->getOrderId() > 0) {
                 $order = $basket->getOrder();
                 $basketProviderData['PAID'] = $order->isPaid();
             }
         }
         $basketProviderMap[$basketIndex] = $basketProviderData;
     }
     return $basketProviderMap;
 }