Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <? if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED !== true) die();
- use \Bitrix\Main,
- \Bitrix\Main\Localization\Loc as Loc,
- Bitrix\Main\Loader,
- Bitrix\Main\Config\Option,
- Bitrix\Sale\Delivery,
- Bitrix\Sale\PaySystem,
- Bitrix\Sale,
- Bitrix\Sale\Order,
- Bitrix\Sale\DiscountCouponsManager,
- Bitrix\Main\Context;
- class OrderComponent extends \CBitrixComponent
- {
- protected $siteId;
- protected $currencyCode;
- protected $userType = [
- 'phisic' => 1,
- ];
- /**
- * cache keys in arResult
- * @var array()
- */
- protected $cacheKeys = array();
- /**
- * add parameters from cache dependence
- * @var array
- */
- protected $cacheAddon = array();
- /**
- * pager navigation params
- * @var array
- */
- protected $navParams = array();
- protected function getPropertyByCode($propertyCollection, $code)
- {
- $tmpAr = $propertyCollection->getArray();
- $codes = [];
- foreach($tmpAr['properties'] as $property){
- $codes[] = $property['CODE'];
- }
- if (!in_array($code, $codes)) return;
- foreach ($propertyCollection as $property)
- {
- if($property->getField('CODE') == $code)
- return $property;
- }
- }
- /**
- * include lang files
- */
- public function onIncludeComponentLang()
- {
- $this->includeComponentLang(basename(__FILE__));
- Loc::loadMessages(__FILE__);
- }
- /**
- * prepare input params
- * @param array $arParams
- * @return array
- */
- public function onPrepareComponentParams($params)
- {
- $params['CACHE_TIME'] = intval($params['CACHE_TIME']) > 0 ? intval($params['CACHE_TIME']) : 3600;
- return $params;
- }
- /**
- * read data from cache or not
- * @return bool
- */
- protected function readDataFromCache()
- {
- if ($this->arParams['CACHE_TYPE'] == 'N') // no cache
- return false;
- return !($this->StartResultCache(false, $this->cacheAddon));
- }
- /**
- * cache arResult keys
- */
- protected function putDataToCache()
- {
- if (is_array($this->cacheKeys) && sizeof($this->cacheKeys) > 0)
- {
- $this->SetResultCacheKeys($this->cacheKeys);
- }
- }
- /**
- * abort cache process
- */
- protected function abortDataCache()
- {
- $this->AbortResultCache();
- }
- /**
- * check needed modules
- * @throws LoaderException
- */
- protected function checkModules()
- {
- if (!Main\Loader::includeModule('sale'))
- throw new Main\LoaderException('Модуль интернет магазина не установлен');
- }
- /**
- * check required input params
- * @throws SystemException
- */
- protected function checkParams()
- {
- }
- /**
- * some actions before cache
- */
- protected function executeProlog()
- {
- }
- /**
- * get component results
- */
- protected function getResult()
- {
- global $APPLICATION, $USER;
- $this->siteId = Context::getCurrent()->getSite();
- $this->currencyCode = Option::get('sale', 'default_currency', 'RUB');
- $this->arResult['DATA'] = $this->getData();
- if (check_bitrix_sessid() && $_SERVER['REQUEST_METHOD'] == 'POST'&& $_REQUEST['final'] == 'yes')
- $this->validOrder();
- if (check_bitrix_sessid() && $_SERVER['REQUEST_METHOD'] == 'POST'&& !$USER->isAuthorized() && !$this->getErrors() && $_REQUEST['final'] == 'yes')
- $this->autoRegiser();
- $this->arResult['USER_ID'] = $this->getUserId();
- $this->arResult['PERSON_TYPE_ID'] = $this->getPersonTypeId();
- DiscountCouponsManager::init();
- $this->initOrder();
- if (isset($_REQUEST['ORDER_ID'])){
- if ($this->order){
- $this->initPaymentForm();
- }
- }else{
- $this->order->setPersonTypeId($this->arResult['PERSON_TYPE_ID']);
- $this->order->setField('CURRENCY', $this->currencyCode);
- $basket = Sale\Basket::loadItemsForFUser(\CSaleBasket::GetBasketUserID(), $this->siteId)->getOrderableItems();
- if (!$basket->getBasketItems() || !$this->canOrder())
- LocalRedirect('/cart/');
- $this->order->setBasket($basket);
- $this->initShipment();
- $this->initPayment($this->arResult['DATA']['PAYMENT_ID']);
- if (check_bitrix_sessid() && $_SERVER['REQUEST_METHOD'] == 'POST'){
- $propertyCollection = $this->order->getPropertyCollection();
- foreach ($this->arResult['DATA'] as $key => $item){
- $property = $this->getPropertyByCode($propertyCollection, $key);
- if ($property)
- $property->setValue($item);
- }
- $this->order->setField('COMMENTS', $this->arResult['DATA']['COMMENTS']);
- if ($_REQUEST['final'] == 'yes' && !$this->getErrors()){
- $this->order->save();
- $this->saveProfile();
- $id = $this->order->getId();
- LocalRedirect($APPLICATION->GetCurPageParam('ORDER_ID=' . $id, ['ORDER_ID']));
- }
- }
- $this->arResult['ORDER_PRICE'] = SaleFormatCurrency($this->order->getPrice(), $this->order->getCurrency());
- }
- /*result*/
- $this->arResult['ORDER'] = $this->order;
- }
- private function getPersonTypeId()
- {
- return $this->userType['phisic'];
- }
- private function getUserId(){
- global $USER;
- if ($this->userId)
- return $this->userId;
- if ($USER->getId())
- $this->userId = $USER->getId();
- elseif(check_bitrix_sessid()){
- $this->userId = \CSaleUser::GetAnonymousUserID();
- }
- return $this->userId;
- }
- private function initShipment()
- {
- $shipmentCollection = $this->order->getShipmentCollection();
- $shipment = $shipmentCollection->createItem();
- $shipmentItemCollection = $shipment->getShipmentItemCollection();
- $shipment->setField('CURRENCY', $this->order->getCurrency());
- foreach ($this->order->getBasket() as $item)
- {
- $shipmentItem = $shipmentItemCollection->createItem($item);
- $shipmentItem->setQuantity($item->getQuantity());
- }
- $arDeliveryServiceAll = Delivery\Services\Manager::getRestrictedObjectsList($shipment);
- $shipmentCollection = $shipment->getCollection();
- if (!empty($arDeliveryServiceAll)) {
- reset($arDeliveryServiceAll);
- $deliveryObj = current($arDeliveryServiceAll);
- if ($deliveryObj->isProfile()) {
- $name = $deliveryObj->getNameWithParent();
- } else {
- $name = $deliveryObj->getName();
- }
- $shipment->setFields(array(
- 'DELIVERY_ID' => $deliveryObj->getId(),
- 'DELIVERY_NAME' => $name,
- 'CURRENCY' => $this->order->getCurrency()
- ));
- $shipmentCollection->calculateDelivery();
- }
- $this->arResult['DELIVERY'] = $arDeliveryServiceAll;
- }
- private function initPayment($paySystemId)
- {
- global $USER;
- $arPaySystemServiceAll = [];
- $paymentCollection = $this->order->getPaymentCollection();
- $remainingSum = $this->order->getPrice() - $paymentCollection->getSum();
- if ($remainingSum > 0 || $this->order->getPrice() == 0)
- {
- $extPayment = $paymentCollection->createItem();
- $extPayment->setField('SUM', $remainingSum);
- $arPaySystemServices = PaySystem\Manager::getListWithRestrictions($extPayment);
- foreach($arPaySystemServices as $key => $service){
- if ($service['CODE'] == 'card' && Site\User::isAnonymous() && !$USER->isAuthorized())
- unset($arPaySystemServices[$key]);
- }
- $arPaySystemServiceAll += $arPaySystemServices;
- if (array_key_exists($paySystemId, $arPaySystemServiceAll))
- {
- $arPaySystem = $arPaySystemServiceAll[$paySystemId];
- }
- else
- {
- reset($arPaySystemServiceAll);
- $arPaySystem = current($arPaySystemServiceAll);
- }
- if (!empty($arPaySystem))
- {
- $extPayment->setFields(array(
- 'PAY_SYSTEM_ID' => $arPaySystem["ID"],
- 'PAY_SYSTEM_NAME' => $arPaySystem["NAME"]
- ));
- }
- else
- $extPayment->delete();
- }
- $this->arResult['PAY_SYSTEMS'] = $arPaySystemServiceAll;
- }
- private function getData()
- {
- global $USER;
- $userId = $USER->getId();
- $return = [];
- if ($userId){
- $filter = ["ID"=> $userId];
- $rsUsers = CUser::GetList(($by="personal_country"), ($order="desc"), $filter, ["SELECT" => ["UF_*"]]);
- if($user = $rsUsers->fetch()){
- $return = [
- 'EMAIL' => $user['EMAIL'],
- 'NAME' => $user['NAME'],
- 'LAST_NAME' => $user['LAST_NAME'],
- 'SECOND_NAME' => $user['SECOND_NAME'],
- 'PHONE' => $user['PERSONAL_PHONE'],
- 'COMPANY' => $user['WORK_COMPANY'],
- 'COMPANY_ADRESS' => $user['WORK_ZIP'] . ' ' . $user['WORK_STREET'],
- 'ADDRESS' => $user['PERSONAL_STREET'],
- ];
- }
- /**/
- $profileData = $this->getProfile();
- if ($profileData)
- $return = $profileData + $return;
- /**/
- }
- if (check_bitrix_sessid() && $_SERVER['REQUEST_METHOD'] == 'POST'){
- $return = $_REQUEST + $return;
- }
- return $return;
- }
- /**
- * some actions after component work
- */
- protected function executeEpilog()
- {
- }
- /**
- * component logic
- */
- public function executeComponent()
- {
- try
- {
- $this->checkModules();
- $this->checkParams();
- $this->executeProlog();
- if (!$this->readDataFromCache())
- {
- $this->getResult();
- $this->putDataToCache();
- $this->includeComponentTemplate();
- }
- $this->executeEpilog();
- }
- catch (Exception $e)
- {
- $this->abortDataCache();
- ShowError($e->getMessage());
- }
- }
- private function initOrder()
- {
- if (isset($_REQUEST['ORDER_ID'])) {
- $orderId = intval($_REQUEST['ORDER_ID']);
- $this->order = Sale\Order::loadByAccountNumber($orderId);
- }else{
- $userId = $this->arResult['USER_ID'];
- if (!$userId)
- $userId = \CSaleUser::GetAnonymousUserID();
- $this->order = Order::create($this->siteId, $userId);
- }
- }
- private function initPaymentForm()
- {
- $paymentCollection = $this->order->getPaymentCollection();
- foreach ($paymentCollection as $payment)
- {
- $this->arResult["PAYMENT"][$payment->getId()] = $payment->getFieldValues();
- if (intval($payment->getPaymentSystemId()) > 0 && !$payment->isPaid())
- {
- $paySystemService = PaySystem\Manager::getObjectById($payment->getPaymentSystemId());
- if (!empty($paySystemService))
- {
- $arPaySysAction = $paySystemService->getFieldsValues();
- $initResult = $paySystemService->initiatePay($payment, null, PaySystem\BaseServiceHandler::STRING);
- if ($initResult->isSuccess())
- $arPaySysAction['BUFFERED_OUTPUT'] = $initResult->getTemplate();
- else
- $arPaySysAction["ERROR"] = $initResult->getErrorMessages();
- $this->arResult["PAYMENT"][$payment->getId()]['PAID'] = $payment->getField('PAID');
- $arPaySysAction["NAME"] = htmlspecialcharsEx($arPaySysAction["NAME"]);
- $arPaySysAction["IS_AFFORD_PDF"] = $paySystemService->isAffordPdf();
- if ($arPaySysAction > 0)
- $arPaySysAction["LOGOTIP"] = CFile::GetFileArray($arPaySysAction["LOGOTIP"]);
- $this->arResult["PAY_SYSTEM_LIST"][$payment->getPaymentSystemId()] = $arPaySysAction;
- }
- else
- $this->arResult["PAY_SYSTEM_LIST"][$payment->getPaymentSystemId()] = array('ERROR' => true);
- }
- }
- }
- private function getProfile()
- {
- $userId = $this->getUserId();
- if (!$userId) return [];
- $profileData = [];
- $dbUserProfiles = \CSaleOrderUserProps::GetList(
- ["DATE_UPDATE" => "DESC"],
- [
- "PERSON_TYPE_ID" => $this->getPersonTypeId(),
- "USER_ID" => $userId
- ]
- );
- if ($arUserProfiles = $dbUserProfiles->fetch())
- {
- $this->profileId = intval($arUserProfiles["ID"]);
- }
- if (!$this->profileId)
- return;
- $res = \CSaleOrderUserPropsValue::GetList(
- [],
- [
- "PERSON_TYPE_ID" => $this->getPersonTypeId(),
- "USER_PROPS_ID" => $this->profileId,
- ],
- false,
- false,
- []
- );
- while ($profileItem = $res->fetch())
- {
- $profileData[$profileItem['PROP_CODE']] = $profileItem['VALUE'];
- }
- return $profileData;
- }
- private function saveProfile()
- {
- \CSaleOrderUserProps::DoSaveUserProfile(
- $this->order->getUserId(),
- $this->profileId,
- 'Профиль пользователя [ID: ' . $this->order->getUserId() . ']',
- $this->order->getPersonTypeId(),
- $this->order->getId(),
- $errors
- );
- }
- private function getErrors()
- {
- return $this->arResult['ERRORS'];
- }
- private function validOrder()
- {
- if (!$this->arResult['DATA']['EMAIL'])
- $this->arResult['ERRORS']['EMAIL'] = 'Не указан электронный адрес';
- if (!$this->arResult['DATA']['NAME'])
- $this->arResult['ERRORS']['NAME'] = 'Не указано имя покупателя';
- if (!$this->arResult['DATA']['PHONE'])
- $this->arResult['ERRORS']['PHONE'] = 'Не указан номер телефона';
- if (!$this->arResult['DATA']['DELIVERY_ID'])
- $this->arResult['ERRORS']['DELIVERY_ID'] = 'Не указан способ доставки';
- if (!$this->arResult['DATA']['PAYMENT_ID'])
- $this->arResult['ERRORS']['PAYMENT_ID'] = 'Не указан способ оплаты';
- if (!$this->arResult['DATA']['ADDRESS'])
- $this->arResult['ERRORS']['ADDRESS'] = 'Укажите пожалуйста адрес доставки';
- if ($this->arResult['DATA']['NAME'] && strlen($this->arResult['DATA']['NAME']) < 4)
- $this->arResult['ERRORS']['NAME'] = 'Имя покупателя не должно быть короче 4-х символов';
- if ($this->arResult['DATA']['PHONE'] && !\Shantilab\Tools\Helpers\Str::isPhone($this->arResult['DATA']['PHONE']))
- $this->arResult['ERRORS']['PHONE'] = 'Неверно указан номер телефона';
- if ($this->arResult['DATA']['EMAIL'] && !check_email($this->arResult['DATA']['EMAIL']))
- $this->arResult['ERRORS']['EMAIL'] = 'Неверно указан электронный адрес';
- }
- private function canOrder()
- {
- $qnt = 0;
- $basket = Sale\Basket::loadItemsForFUser(\CSaleBasket::GetBasketUserID(), $this->siteId)->getOrderableItems();
- foreach($basket as $basketItem){
- if($basketItem->canBuy() && !$basketItem->isDelay()){
- $qnt += $basketItem->getQuantity();
- }
- }
- if ($qnt > 6)
- return false;
- return true;
- }
- private function autoRegiser()
- {
- global $USER;
- global $APPLICATION;
- $userEmail = $this->arResult['DATA']['EMAIL'];
- $newLogin = $userEmail;
- $newEmail = $userEmail;
- $payerName = $this->arResult['DATA']['NAME'];
- $newName = "";
- $newLastName = "";
- if (strlen($payerName) > 0)
- {
- $arNames = explode(" ", $payerName);
- if (count($arNames) > 1){
- $newName = $arNames[1];
- $newLastName = $arNames[0];
- }else{
- $newName = $arNames[0];
- }
- }
- if (strlen($newLogin) > 47)
- $newLogin = substr($newLogin, 0, 47);
- if (strlen($newLogin) < 3)
- $newLogin .= "_";
- if (strlen($newLogin) < 3)
- $newLogin .= "_";
- $dbUserLogin = \CUser::GetByLogin($newLogin);
- if ($arUserLogin = $dbUserLogin->Fetch())
- {
- $newLoginTmp = $newLogin;
- $uind = 0;
- do
- {
- $uind++;
- if ($uind == 10)
- {
- $newLogin = $userEmail;
- $newLoginTmp = $newLogin;
- }
- elseif ($uind > 10)
- {
- $newLogin = "buyer".time().GetRandomCode(2);
- $newLoginTmp = $newLogin;
- break;
- }
- else
- {
- $newLoginTmp = $newLogin.$uind;
- }
- $dbUserLogin = \CUser::GetByLogin($newLoginTmp);
- }
- while ($arUserLogin = $dbUserLogin->Fetch());
- $newLogin = $newLoginTmp;
- }
- $def_group = Option::get("main", "new_user_registration_def_group", "");
- if ($def_group != "")
- {
- $groupID = explode(",", $def_group);
- $arPolicy = $USER->GetGroupPolicy($groupID);
- }
- else
- {
- $arPolicy = $USER->GetGroupPolicy(array());
- }
- $password_min_length = intval($arPolicy["PASSWORD_LENGTH"]);
- if ($password_min_length <= 0)
- $password_min_length = 6;
- $password_chars = array(
- "abcdefghijklnmopqrstuvwxyz",
- "ABCDEFGHIJKLNMOPQRSTUVWXYZ",
- "0123456789",
- );
- if ($arPolicy["PASSWORD_PUNCTUATION"] === "Y")
- $password_chars[] = ",.<>/?;:'\"[]{}\|`~!@#\$%^&*()-_+=";
- $newPassword = $newPasswordConfirm = randString($password_min_length+2, $password_chars);
- $registerInfo = array(
- 'NEW_EMAIL' => $newEmail,
- 'NEW_LOGIN' => $newLogin,
- 'NEW_NAME' => $newName,
- 'NEW_LAST_NAME' => $newLastName,
- 'NEW_PASSWORD' => $newPassword,
- 'NEW_PASSWORD_CONFIRM' => $newPasswordConfirm,
- 'GROUP_ID' => $groupID
- );
- if (!$this->getErrors()){
- $arAuthResult = $USER->Register(
- $registerInfo["NEW_LOGIN"],
- $registerInfo["NEW_NAME"],
- $registerInfo["NEW_LAST_NAME"],
- $registerInfo["NEW_PASSWORD"],
- $registerInfo["NEW_PASSWORD_CONFIRM"],
- $registerInfo["NEW_EMAIL"]
- );
- }
- if ($arAuthResult != false && $arAuthResult["TYPE"] == "ERROR"){
- $this->arResult['ERRORS'][] = $arAuthResult["MESSAGE"];
- }else{
- \CUser::SendUserInfo($USER->GetID(), $this->siteId, 'Вы успешно зарегистрированны!', true);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement