Advertisement
Guest User

Untitled

a guest
Oct 26th, 2016
251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 19.50 KB | None | 0 0
  1. <? if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED !== true) die();
  2.  
  3. use \Bitrix\Main,
  4. \Bitrix\Main\Localization\Loc as Loc,
  5. Bitrix\Main\Loader,
  6. Bitrix\Main\Config\Option,
  7. Bitrix\Sale\Delivery,
  8. Bitrix\Sale\PaySystem,
  9. Bitrix\Sale,
  10. Bitrix\Sale\Order,
  11. Bitrix\Sale\DiscountCouponsManager,
  12. Bitrix\Main\Context;
  13.  
  14. class OrderComponent extends \CBitrixComponent
  15. {
  16. protected $siteId;
  17. protected $currencyCode;
  18. protected $userType = [
  19. 'phisic' => 1,
  20. ];
  21.  
  22. /**
  23. * cache keys in arResult
  24. * @var array()
  25. */
  26. protected $cacheKeys = array();
  27.  
  28. /**
  29. * add parameters from cache dependence
  30. * @var array
  31. */
  32. protected $cacheAddon = array();
  33.  
  34. /**
  35. * pager navigation params
  36. * @var array
  37. */
  38. protected $navParams = array();
  39.  
  40. protected function getPropertyByCode($propertyCollection, $code)
  41. {
  42. $tmpAr = $propertyCollection->getArray();
  43. $codes = [];
  44. foreach($tmpAr['properties'] as $property){
  45. $codes[] = $property['CODE'];
  46. }
  47.  
  48. if (!in_array($code, $codes)) return;
  49.  
  50. foreach ($propertyCollection as $property)
  51. {
  52. if($property->getField('CODE') == $code)
  53. return $property;
  54. }
  55. }
  56.  
  57. /**
  58. * include lang files
  59. */
  60. public function onIncludeComponentLang()
  61. {
  62. $this->includeComponentLang(basename(__FILE__));
  63. Loc::loadMessages(__FILE__);
  64. }
  65.  
  66. /**
  67. * prepare input params
  68. * @param array $arParams
  69. * @return array
  70. */
  71. public function onPrepareComponentParams($params)
  72. {
  73. $params['CACHE_TIME'] = intval($params['CACHE_TIME']) > 0 ? intval($params['CACHE_TIME']) : 3600;
  74.  
  75. return $params;
  76. }
  77.  
  78. /**
  79. * read data from cache or not
  80. * @return bool
  81. */
  82. protected function readDataFromCache()
  83. {
  84. if ($this->arParams['CACHE_TYPE'] == 'N') // no cache
  85. return false;
  86.  
  87. return !($this->StartResultCache(false, $this->cacheAddon));
  88. }
  89.  
  90. /**
  91. * cache arResult keys
  92. */
  93. protected function putDataToCache()
  94. {
  95. if (is_array($this->cacheKeys) && sizeof($this->cacheKeys) > 0)
  96. {
  97. $this->SetResultCacheKeys($this->cacheKeys);
  98. }
  99. }
  100.  
  101. /**
  102. * abort cache process
  103. */
  104. protected function abortDataCache()
  105. {
  106. $this->AbortResultCache();
  107. }
  108.  
  109. /**
  110. * check needed modules
  111. * @throws LoaderException
  112. */
  113. protected function checkModules()
  114. {
  115. if (!Main\Loader::includeModule('sale'))
  116. throw new Main\LoaderException('Модуль интернет магазина не установлен');
  117. }
  118.  
  119. /**
  120. * check required input params
  121. * @throws SystemException
  122. */
  123. protected function checkParams()
  124. {
  125. }
  126.  
  127. /**
  128. * some actions before cache
  129. */
  130. protected function executeProlog()
  131. {
  132.  
  133. }
  134.  
  135. /**
  136. * get component results
  137. */
  138. protected function getResult()
  139. {
  140. global $APPLICATION, $USER;
  141.  
  142. $this->siteId = Context::getCurrent()->getSite();
  143. $this->currencyCode = Option::get('sale', 'default_currency', 'RUB');
  144.  
  145. $this->arResult['DATA'] = $this->getData();
  146.  
  147. if (check_bitrix_sessid() && $_SERVER['REQUEST_METHOD'] == 'POST'&& $_REQUEST['final'] == 'yes')
  148. $this->validOrder();
  149.  
  150. if (check_bitrix_sessid() && $_SERVER['REQUEST_METHOD'] == 'POST'&& !$USER->isAuthorized() && !$this->getErrors() && $_REQUEST['final'] == 'yes')
  151. $this->autoRegiser();
  152.  
  153. $this->arResult['USER_ID'] = $this->getUserId();
  154. $this->arResult['PERSON_TYPE_ID'] = $this->getPersonTypeId();
  155.  
  156. DiscountCouponsManager::init();
  157.  
  158. $this->initOrder();
  159.  
  160. if (isset($_REQUEST['ORDER_ID'])){
  161. if ($this->order){
  162. $this->initPaymentForm();
  163. }
  164. }else{
  165. $this->order->setPersonTypeId($this->arResult['PERSON_TYPE_ID']);
  166. $this->order->setField('CURRENCY', $this->currencyCode);
  167. $basket = Sale\Basket::loadItemsForFUser(\CSaleBasket::GetBasketUserID(), $this->siteId)->getOrderableItems();
  168.  
  169. if (!$basket->getBasketItems() || !$this->canOrder())
  170. LocalRedirect('/cart/');
  171.  
  172. $this->order->setBasket($basket);
  173. $this->initShipment();
  174. $this->initPayment($this->arResult['DATA']['PAYMENT_ID']);
  175.  
  176. if (check_bitrix_sessid() && $_SERVER['REQUEST_METHOD'] == 'POST'){
  177. $propertyCollection = $this->order->getPropertyCollection();
  178. foreach ($this->arResult['DATA'] as $key => $item){
  179. $property = $this->getPropertyByCode($propertyCollection, $key);
  180. if ($property)
  181. $property->setValue($item);
  182. }
  183.  
  184. $this->order->setField('COMMENTS', $this->arResult['DATA']['COMMENTS']);
  185.  
  186. if ($_REQUEST['final'] == 'yes' && !$this->getErrors()){
  187. $this->order->save();
  188. $this->saveProfile();
  189. $id = $this->order->getId();
  190. LocalRedirect($APPLICATION->GetCurPageParam('ORDER_ID=' . $id, ['ORDER_ID']));
  191. }
  192. }
  193.  
  194. $this->arResult['ORDER_PRICE'] = SaleFormatCurrency($this->order->getPrice(), $this->order->getCurrency());
  195. }
  196.  
  197. /*result*/
  198. $this->arResult['ORDER'] = $this->order;
  199. }
  200.  
  201. private function getPersonTypeId()
  202. {
  203. return $this->userType['phisic'];
  204. }
  205.  
  206. private function getUserId(){
  207. global $USER;
  208. if ($this->userId)
  209. return $this->userId;
  210.  
  211. if ($USER->getId())
  212. $this->userId = $USER->getId();
  213. elseif(check_bitrix_sessid()){
  214. $this->userId = \CSaleUser::GetAnonymousUserID();
  215. }
  216.  
  217. return $this->userId;
  218. }
  219.  
  220. private function initShipment()
  221. {
  222. $shipmentCollection = $this->order->getShipmentCollection();
  223. $shipment = $shipmentCollection->createItem();
  224. $shipmentItemCollection = $shipment->getShipmentItemCollection();
  225. $shipment->setField('CURRENCY', $this->order->getCurrency());
  226. foreach ($this->order->getBasket() as $item)
  227. {
  228. $shipmentItem = $shipmentItemCollection->createItem($item);
  229. $shipmentItem->setQuantity($item->getQuantity());
  230. }
  231. $arDeliveryServiceAll = Delivery\Services\Manager::getRestrictedObjectsList($shipment);
  232. $shipmentCollection = $shipment->getCollection();
  233.  
  234. if (!empty($arDeliveryServiceAll)) {
  235. reset($arDeliveryServiceAll);
  236. $deliveryObj = current($arDeliveryServiceAll);
  237.  
  238. if ($deliveryObj->isProfile()) {
  239. $name = $deliveryObj->getNameWithParent();
  240. } else {
  241. $name = $deliveryObj->getName();
  242. }
  243.  
  244. $shipment->setFields(array(
  245. 'DELIVERY_ID' => $deliveryObj->getId(),
  246. 'DELIVERY_NAME' => $name,
  247. 'CURRENCY' => $this->order->getCurrency()
  248. ));
  249.  
  250. $shipmentCollection->calculateDelivery();
  251. }
  252. $this->arResult['DELIVERY'] = $arDeliveryServiceAll;
  253. }
  254.  
  255. private function initPayment($paySystemId)
  256. {
  257. global $USER;
  258.  
  259. $arPaySystemServiceAll = [];
  260. $paymentCollection = $this->order->getPaymentCollection();
  261.  
  262. $remainingSum = $this->order->getPrice() - $paymentCollection->getSum();
  263. if ($remainingSum > 0 || $this->order->getPrice() == 0)
  264. {
  265. $extPayment = $paymentCollection->createItem();
  266. $extPayment->setField('SUM', $remainingSum);
  267. $arPaySystemServices = PaySystem\Manager::getListWithRestrictions($extPayment);
  268. foreach($arPaySystemServices as $key => $service){
  269. if ($service['CODE'] == 'card' && Site\User::isAnonymous() && !$USER->isAuthorized())
  270. unset($arPaySystemServices[$key]);
  271. }
  272.  
  273. $arPaySystemServiceAll += $arPaySystemServices;
  274.  
  275. if (array_key_exists($paySystemId, $arPaySystemServiceAll))
  276. {
  277. $arPaySystem = $arPaySystemServiceAll[$paySystemId];
  278. }
  279. else
  280. {
  281. reset($arPaySystemServiceAll);
  282.  
  283. $arPaySystem = current($arPaySystemServiceAll);
  284. }
  285.  
  286. if (!empty($arPaySystem))
  287. {
  288. $extPayment->setFields(array(
  289. 'PAY_SYSTEM_ID' => $arPaySystem["ID"],
  290. 'PAY_SYSTEM_NAME' => $arPaySystem["NAME"]
  291. ));
  292. }
  293. else
  294. $extPayment->delete();
  295. }
  296.  
  297. $this->arResult['PAY_SYSTEMS'] = $arPaySystemServiceAll;
  298. }
  299.  
  300. private function getData()
  301. {
  302. global $USER;
  303.  
  304. $userId = $USER->getId();
  305.  
  306. $return = [];
  307.  
  308. if ($userId){
  309. $filter = ["ID"=> $userId];
  310. $rsUsers = CUser::GetList(($by="personal_country"), ($order="desc"), $filter, ["SELECT" => ["UF_*"]]);
  311. if($user = $rsUsers->fetch()){
  312. $return = [
  313. 'EMAIL' => $user['EMAIL'],
  314. 'NAME' => $user['NAME'],
  315. 'LAST_NAME' => $user['LAST_NAME'],
  316. 'SECOND_NAME' => $user['SECOND_NAME'],
  317. 'PHONE' => $user['PERSONAL_PHONE'],
  318. 'COMPANY' => $user['WORK_COMPANY'],
  319. 'COMPANY_ADRESS' => $user['WORK_ZIP'] . ' ' . $user['WORK_STREET'],
  320. 'ADDRESS' => $user['PERSONAL_STREET'],
  321. ];
  322. }
  323.  
  324. /**/
  325. $profileData = $this->getProfile();
  326. if ($profileData)
  327. $return = $profileData + $return;
  328. /**/
  329. }
  330.  
  331. if (check_bitrix_sessid() && $_SERVER['REQUEST_METHOD'] == 'POST'){
  332. $return = $_REQUEST + $return;
  333. }
  334.  
  335. return $return;
  336. }
  337.  
  338. /**
  339. * some actions after component work
  340. */
  341. protected function executeEpilog()
  342. {
  343.  
  344. }
  345.  
  346. /**
  347. * component logic
  348. */
  349. public function executeComponent()
  350. {
  351. try
  352. {
  353. $this->checkModules();
  354. $this->checkParams();
  355. $this->executeProlog();
  356. if (!$this->readDataFromCache())
  357. {
  358. $this->getResult();
  359. $this->putDataToCache();
  360. $this->includeComponentTemplate();
  361. }
  362. $this->executeEpilog();
  363. }
  364. catch (Exception $e)
  365. {
  366. $this->abortDataCache();
  367. ShowError($e->getMessage());
  368. }
  369. }
  370.  
  371. private function initOrder()
  372. {
  373. if (isset($_REQUEST['ORDER_ID'])) {
  374. $orderId = intval($_REQUEST['ORDER_ID']);
  375. $this->order = Sale\Order::loadByAccountNumber($orderId);
  376. }else{
  377. $userId = $this->arResult['USER_ID'];
  378. if (!$userId)
  379. $userId = \CSaleUser::GetAnonymousUserID();
  380. $this->order = Order::create($this->siteId, $userId);
  381. }
  382. }
  383.  
  384. private function initPaymentForm()
  385. {
  386. $paymentCollection = $this->order->getPaymentCollection();
  387. foreach ($paymentCollection as $payment)
  388. {
  389. $this->arResult["PAYMENT"][$payment->getId()] = $payment->getFieldValues();
  390.  
  391. if (intval($payment->getPaymentSystemId()) > 0 && !$payment->isPaid())
  392. {
  393. $paySystemService = PaySystem\Manager::getObjectById($payment->getPaymentSystemId());
  394. if (!empty($paySystemService))
  395. {
  396. $arPaySysAction = $paySystemService->getFieldsValues();
  397.  
  398. $initResult = $paySystemService->initiatePay($payment, null, PaySystem\BaseServiceHandler::STRING);
  399.  
  400. if ($initResult->isSuccess())
  401. $arPaySysAction['BUFFERED_OUTPUT'] = $initResult->getTemplate();
  402. else
  403. $arPaySysAction["ERROR"] = $initResult->getErrorMessages();
  404.  
  405. $this->arResult["PAYMENT"][$payment->getId()]['PAID'] = $payment->getField('PAID');
  406.  
  407. $arPaySysAction["NAME"] = htmlspecialcharsEx($arPaySysAction["NAME"]);
  408. $arPaySysAction["IS_AFFORD_PDF"] = $paySystemService->isAffordPdf();
  409.  
  410. if ($arPaySysAction > 0)
  411. $arPaySysAction["LOGOTIP"] = CFile::GetFileArray($arPaySysAction["LOGOTIP"]);
  412.  
  413. $this->arResult["PAY_SYSTEM_LIST"][$payment->getPaymentSystemId()] = $arPaySysAction;
  414. }
  415. else
  416. $this->arResult["PAY_SYSTEM_LIST"][$payment->getPaymentSystemId()] = array('ERROR' => true);
  417. }
  418. }
  419. }
  420.  
  421. private function getProfile()
  422. {
  423. $userId = $this->getUserId();
  424. if (!$userId) return [];
  425.  
  426. $profileData = [];
  427.  
  428. $dbUserProfiles = \CSaleOrderUserProps::GetList(
  429. ["DATE_UPDATE" => "DESC"],
  430. [
  431. "PERSON_TYPE_ID" => $this->getPersonTypeId(),
  432. "USER_ID" => $userId
  433. ]
  434. );
  435.  
  436. if ($arUserProfiles = $dbUserProfiles->fetch())
  437. {
  438. $this->profileId = intval($arUserProfiles["ID"]);
  439. }
  440.  
  441. if (!$this->profileId)
  442. return;
  443.  
  444. $res = \CSaleOrderUserPropsValue::GetList(
  445. [],
  446. [
  447. "PERSON_TYPE_ID" => $this->getPersonTypeId(),
  448. "USER_PROPS_ID" => $this->profileId,
  449. ],
  450. false,
  451. false,
  452. []
  453. );
  454.  
  455. while ($profileItem = $res->fetch())
  456. {
  457. $profileData[$profileItem['PROP_CODE']] = $profileItem['VALUE'];
  458. }
  459.  
  460. return $profileData;
  461. }
  462.  
  463. private function saveProfile()
  464. {
  465. \CSaleOrderUserProps::DoSaveUserProfile(
  466. $this->order->getUserId(),
  467. $this->profileId,
  468. 'Профиль пользователя [ID: ' . $this->order->getUserId() . ']',
  469. $this->order->getPersonTypeId(),
  470. $this->order->getId(),
  471. $errors
  472. );
  473. }
  474.  
  475. private function getErrors()
  476. {
  477. return $this->arResult['ERRORS'];
  478. }
  479.  
  480. private function validOrder()
  481. {
  482. if (!$this->arResult['DATA']['EMAIL'])
  483. $this->arResult['ERRORS']['EMAIL'] = 'Не указан электронный адрес';
  484. if (!$this->arResult['DATA']['NAME'])
  485. $this->arResult['ERRORS']['NAME'] = 'Не указано имя покупателя';
  486. if (!$this->arResult['DATA']['PHONE'])
  487. $this->arResult['ERRORS']['PHONE'] = 'Не указан номер телефона';
  488. if (!$this->arResult['DATA']['DELIVERY_ID'])
  489. $this->arResult['ERRORS']['DELIVERY_ID'] = 'Не указан способ доставки';
  490. if (!$this->arResult['DATA']['PAYMENT_ID'])
  491. $this->arResult['ERRORS']['PAYMENT_ID'] = 'Не указан способ оплаты';
  492. if (!$this->arResult['DATA']['ADDRESS'])
  493. $this->arResult['ERRORS']['ADDRESS'] = 'Укажите пожалуйста адрес доставки';
  494.  
  495. if ($this->arResult['DATA']['NAME'] && strlen($this->arResult['DATA']['NAME']) < 4)
  496. $this->arResult['ERRORS']['NAME'] = 'Имя покупателя не должно быть короче 4-х символов';
  497.  
  498. if ($this->arResult['DATA']['PHONE'] && !\Shantilab\Tools\Helpers\Str::isPhone($this->arResult['DATA']['PHONE']))
  499. $this->arResult['ERRORS']['PHONE'] = 'Неверно указан номер телефона';
  500.  
  501. if ($this->arResult['DATA']['EMAIL'] && !check_email($this->arResult['DATA']['EMAIL']))
  502. $this->arResult['ERRORS']['EMAIL'] = 'Неверно указан электронный адрес';
  503. }
  504.  
  505. private function canOrder()
  506. {
  507. $qnt = 0;
  508. $basket = Sale\Basket::loadItemsForFUser(\CSaleBasket::GetBasketUserID(), $this->siteId)->getOrderableItems();
  509. foreach($basket as $basketItem){
  510. if($basketItem->canBuy() && !$basketItem->isDelay()){
  511. $qnt += $basketItem->getQuantity();
  512. }
  513. }
  514.  
  515. if ($qnt > 6)
  516. return false;
  517.  
  518. return true;
  519. }
  520.  
  521. private function autoRegiser()
  522. {
  523. global $USER;
  524. global $APPLICATION;
  525.  
  526. $userEmail = $this->arResult['DATA']['EMAIL'];
  527. $newLogin = $userEmail;
  528. $newEmail = $userEmail;
  529.  
  530. $payerName = $this->arResult['DATA']['NAME'];
  531.  
  532. $newName = "";
  533. $newLastName = "";
  534.  
  535. if (strlen($payerName) > 0)
  536. {
  537. $arNames = explode(" ", $payerName);
  538. if (count($arNames) > 1){
  539. $newName = $arNames[1];
  540. $newLastName = $arNames[0];
  541. }else{
  542. $newName = $arNames[0];
  543. }
  544. }
  545.  
  546. if (strlen($newLogin) > 47)
  547. $newLogin = substr($newLogin, 0, 47);
  548.  
  549. if (strlen($newLogin) < 3)
  550. $newLogin .= "_";
  551.  
  552. if (strlen($newLogin) < 3)
  553. $newLogin .= "_";
  554.  
  555. $dbUserLogin = \CUser::GetByLogin($newLogin);
  556. if ($arUserLogin = $dbUserLogin->Fetch())
  557. {
  558. $newLoginTmp = $newLogin;
  559. $uind = 0;
  560. do
  561. {
  562. $uind++;
  563. if ($uind == 10)
  564. {
  565. $newLogin = $userEmail;
  566. $newLoginTmp = $newLogin;
  567. }
  568. elseif ($uind > 10)
  569. {
  570. $newLogin = "buyer".time().GetRandomCode(2);
  571. $newLoginTmp = $newLogin;
  572. break;
  573. }
  574. else
  575. {
  576. $newLoginTmp = $newLogin.$uind;
  577. }
  578. $dbUserLogin = \CUser::GetByLogin($newLoginTmp);
  579. }
  580. while ($arUserLogin = $dbUserLogin->Fetch());
  581. $newLogin = $newLoginTmp;
  582. }
  583.  
  584. $def_group = Option::get("main", "new_user_registration_def_group", "");
  585. if ($def_group != "")
  586. {
  587. $groupID = explode(",", $def_group);
  588. $arPolicy = $USER->GetGroupPolicy($groupID);
  589. }
  590. else
  591. {
  592. $arPolicy = $USER->GetGroupPolicy(array());
  593. }
  594.  
  595. $password_min_length = intval($arPolicy["PASSWORD_LENGTH"]);
  596. if ($password_min_length <= 0)
  597. $password_min_length = 6;
  598. $password_chars = array(
  599. "abcdefghijklnmopqrstuvwxyz",
  600. "ABCDEFGHIJKLNMOPQRSTUVWXYZ",
  601. "0123456789",
  602. );
  603. if ($arPolicy["PASSWORD_PUNCTUATION"] === "Y")
  604. $password_chars[] = ",.<>/?;:'\"[]{}\|`~!@#\$%^&*()-_+=";
  605. $newPassword = $newPasswordConfirm = randString($password_min_length+2, $password_chars);
  606.  
  607. $registerInfo = array(
  608. 'NEW_EMAIL' => $newEmail,
  609. 'NEW_LOGIN' => $newLogin,
  610. 'NEW_NAME' => $newName,
  611. 'NEW_LAST_NAME' => $newLastName,
  612. 'NEW_PASSWORD' => $newPassword,
  613. 'NEW_PASSWORD_CONFIRM' => $newPasswordConfirm,
  614. 'GROUP_ID' => $groupID
  615. );
  616.  
  617. if (!$this->getErrors()){
  618. $arAuthResult = $USER->Register(
  619. $registerInfo["NEW_LOGIN"],
  620. $registerInfo["NEW_NAME"],
  621. $registerInfo["NEW_LAST_NAME"],
  622. $registerInfo["NEW_PASSWORD"],
  623. $registerInfo["NEW_PASSWORD_CONFIRM"],
  624. $registerInfo["NEW_EMAIL"]
  625. );
  626. }
  627.  
  628. if ($arAuthResult != false && $arAuthResult["TYPE"] == "ERROR"){
  629. $this->arResult['ERRORS'][] = $arAuthResult["MESSAGE"];
  630. }else{
  631. \CUser::SendUserInfo($USER->GetID(), $this->siteId, 'Вы успешно зарегистрированны!', true);
  632. }
  633. }
  634. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement