· 5 years ago · Oct 14, 2020, 10:26 AM
1<?php
2/**
3 * Created by PhpStorm.
4 * User: Vovca
5 * Date: 20.02.2018
6 * Time: 17:45
7 */
8
9use Bitrix\Iblock\ElementTable,
10 Bitrix\Main\Config\Option,
11 Bitrix\Sale\Internals\OrderPropsValueTable,
12 Swebs\Helper;
13
14CModule::IncludeModule('sale');
15CModule::IncludeModule('iblock');
16CModule::IncludeModule('biletik.tes');
17require_once($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/nemo_requests/lib/nemo_requests.php");
18
19class BiletikTES
20{
21 /**
22 * BiletikTES constructor.
23 * @throws \Bitrix\Main\ArgumentNullException
24 */
25 function __construct()
26 {
27 $this->moduleParameters = Option::getForModule('biletik.tes');
28 $this->moduleURL = '/bitrix/modules/biletik.tes';
29 $this->requestURL = array(
30 'availableProductsRequest' => '/policies/availableProducts.json',
31 'calculationParametersRequest' => '/policies/calculationParameters.json',
32 'policyParametersRequest' => '/policies/policyParameters.json',
33 'calculatePolicyRequest' => '/policies/calculate.json',
34 'createPolicyRequest' => '/policies/create.json',
35 'confirmPolicyRequest' => '/policies/confirm.json',
36 'refundPolicyRequest' => '/policies/refund.json', // возврат в связи с заявлением на возврат страховки
37 'tripCancellationRequest' => '/policies/tripCancellation.json', // возврат в связи с возвратом билета
38 );
39 $this->calculationFields = array(
40 'FLIGHT_SEGMENTS_COUNT',
41 'FLIGHT_SEGMENT_TRANSPORT_OPERATOR_CODE',
42 'TICKET_ISSUE_DATE',
43 'TICKET_TOTAL_VALUE',
44 );
45
46 if (!empty($this->moduleParameters['AVAILABLE_PRODUCTS']))
47 $this->moduleParameters['AR_AVAILABLE_PRODUCTS'] = explode(',', $this->moduleParameters['AVAILABLE_PRODUCTS']);
48 }
49
50 /**
51 * Метод собирает данные пассажиров и производит калькуляцию стоимости полисов
52 * @param $products - типы полисов
53 * @param $orderID
54 * @return false|string
55 */
56 public function getCalculation($products, $orderID) {
57 if (empty($products))
58 return false;
59
60 if (!isset($this->dataCalculation) || empty($this->dataCalculation)) {
61 $dbApiVer = OrderPropsValueTable::getList(array(
62 'filter'=>array('ORDER_ID'=>$orderID, 'CODE'=>'ORDER_API'),
63 'select'=>array('VALUE')
64 ));
65 if ($apiVer = $dbApiVer->fetch()) {
66 if ($apiVer['VALUE'] == 'zeus') {
67 $this->dataCalculation = TesHelper::getCompileTravellersDataZeus($orderID);
68 }
69 else {
70 $this->dataCalculation = TesHelper::getCompileTravellersData($orderID);
71 }
72 }
73 else {
74 $this->dataCalculation = TesHelper::getCompileTravellersData($orderID);
75 }
76 }
77 // if we don't have product code, lets get default
78 if (isset($products['RAW'])) {
79 foreach ($products['RAW']->availableProductsResult->productList->product as $k => $prod) {
80 $arProd = get_object_vars($prod);
81 if ($arProd['@isDefault'] == 'true') {
82 $productCode = $arProd['@code'];
83 break;
84 }
85 }
86 }
87 elseif (is_string($products)) {
88 foreach ($this->dataCalculation['TRAVELLERS'] as $key => $arTraveller) {
89 $productCode[$key] = $products;
90 }
91 }
92 else {
93
94 foreach ($products as $code => $productCode) {
95 // get calculation for each traveller
96 foreach ($productCode as $kTraveller => $productCode) {
97
98 $policyParameters = $this->dataCalculation['TRAVELLERS'][$kTraveller];
99 if ($productCode === 'ON_TC_BG_ZV_NS_165_235')
100 unset($policyParameters['riskValue']);
101
102 $params = array(
103 'calculatePolicyRequest' => array(
104 'operator' => array(
105 'code' => $this->moduleParameters['OPERATOR_CODE']
106 ),
107 'product' => array(
108 'code' => $productCode
109 ),
110 'policyParameters' => $policyParameters
111 )
112 );
113 $arParams[] = $params;
114 $resp = $this->execRequest($params, $this->requestURL['calculatePolicyRequest']);
115 $response[$kTraveller] = json_decode($resp);
116
117 }
118 // now let's modify prices with our extra charge
119 $response = json_encode($this->getExtraCharge($response));
120
121 $arResponse[$code] = $response;
122 $response = array();
123
124 }
125
126 return json_encode($arResponse);
127 }
128
129 // get calculation for each traveller
130 foreach ($this->dataCalculation['TRAVELLERS'] as $key => $arTraveller) {
131
132 $policyParameters = $arTraveller;
133 if ($productCode[$key] === 'ON_TC_BG_ZV_NS_165_235')
134 unset($policyParameters['riskValue']);
135
136 $params = array(
137 'calculatePolicyRequest' => array(
138 'operator' => array(
139 'code' => $this->moduleParameters['OPERATOR_CODE']
140 ),
141 'product' => array(
142 'code' => $productCode[$key]
143 ),
144 'policyParameters' => $policyParameters
145 )
146 );
147 $arParams[] = $params;
148 $response[$key] = json_decode($this->execRequest($params, $this->requestURL['calculatePolicyRequest']));
149 }
150
151 // now let's modify prices with our extra charge
152 $response = json_encode($this->getExtraCharge($response));
153
154 return $response;
155 }
156
157 /**
158 * this method finalizing policy.
159 * 1. check if there policy in order and if order is fully payed
160 * 2. get data about policy
161 * 3. if all ok we create policy and confirm it
162 * @param $orderID
163 */
164 public function processInsuranse($orderID) {
165 $arOrder = CSaleOrder::GetByID($orderID);
166
167 if ($arOrder['PAYED'] == 'Y' && (int)$arOrder['SUM_PAID'] >= (int)$arOrder['PRICE']) {
168 $dbBasket = CSaleBasket::GetList(
169 array(),
170 array('ORDER_ID'=>$orderID),
171 false,
172 false,
173 array('ID', 'PRODUCT_ID')
174 );
175 while ($ob = $dbBasket->GetNext()) {
176 $arItems[$ob['ID']] = $ob['PRODUCT_ID'];
177 }
178
179 if (empty($arItems))
180 return false;
181
182 $dbElement = CIBlockElement::GetList(
183 array(),
184 array('ID'=>$arItems, 'IBLOCK_ID'=>$this->moduleParameters['POLICIES_IBLOCK_ID']),
185 false,
186 false,
187 array('ID', 'CODE', 'DETAIL_TEXT')
188 );
189 while ($obElement = $dbElement->GetNext()) {
190 $arElement = $obElement;
191
192 if ((string)$obElement['CODE'] === (string)$orderID || $obElement['CODE'] == $orderID.'_error_not_created')
193 $arPolicyParameters = unserialize($obElement['~DETAIL_TEXT']); // not created
194 elseif ($obElement['CODE'] == $orderID.'_created')
195 $policy = unserialize($obElement['~DETAIL_TEXT']); // already created
196 elseif ($obElement['CODE'] == $orderID.'_confirmed')
197 $finalData = unserialize($obElement['~DETAIL_TEXT'])['finalData']; // confirmed
198 }
199
200 if (!empty($arPolicyParameters)) {
201 $policy = $this->createPolicy($arPolicyParameters, $orderID);
202
203 $notCreatedPolicies = false;
204 foreach ($policy as $code => $arPolicyType) {
205 foreach ($arPolicyType as $user => $arPolicy) {
206 $obPolicy = json_decode($arPolicy['policy']);
207
208 if ($obPolicy->createPolicyResult->returnCode->code != 'OK') {
209 $notCreatedPolicies = true;
210 }
211 }
212 }
213
214 if (!$notCreatedPolicies) { // Если ошибок запроса createPolicy нету
215 $createdFields = array('DETAIL_TEXT'=>serialize($policy), 'CODE'=>$orderID.'_created');
216 }
217 else { // иначе данные логируем в PREVIEW_TEXT и обновляем CODE
218 $mailMessage = 'На сайте biletik.aero произошла ошибка создания полиса. ID заказа в битриксе - '.$orderID.'. Ответ сервиса: '.json_encode($policy);
219 fp(array('params'=>$arPolicyParameters, 'response'=>$policy, 'mail_mess'=>$mailMessage), 'error_create_policy_'.$orderID);
220 $createdFields = array('PREVIEW_TEXT'=>serialize($policy), 'CODE'=>$orderID.'_error_not_created');
221 mail('scantiket@gmail.com', 'Альфастрахование. Ошибка создания полиса', $mailMessage);
222 unset($policy);
223 }
224
225 $el = new CIBlockElement();
226 $el->Update($arElement['ID'], $createdFields);
227 }
228
229 if (!empty($policy)) {
230 foreach ($policy as $code => $arPolicyType) {
231 foreach ($arPolicyType as $user => $arPolicy) {
232 $obPolicy = json_decode($arPolicy['policy']);
233
234 if ($obPolicy->createPolicyResult->returnCode->code == 'OK') {
235 $final = $this->confirmPolicy($arPolicy);
236 $finalData[$code][$user] = $final;
237 $policy['finalData'][$code][$user] = $final;
238 }
239 else { // если была ошибка попытаемся еще раз сделать createPolicy
240 $arPolicyParameters = array();
241 }
242 }
243 }
244
245 if (!empty($finalData)) {
246 $el = new CIBlockElement();
247 $el->Update($arElement['ID'], array('DETAIL_TEXT'=>serialize($policy), 'CODE'=>$orderID.'_confirmed'));
248 }
249 }
250
251 if (!empty($finalData)) {
252 foreach ($finalData as $code => $policeType) {
253 foreach($policeType as $user => $confirmedPolice) {
254 $obConfirmedPolice = json_decode($confirmedPolice);
255
256 if ($obConfirmedPolice->confirmPolicyResult->returnCode->code == 'OK') {
257 $arReturn[$user][] = array(
258 'police_url' => $obConfirmedPolice->confirmPolicyResult->policyDocument->url,
259 'fullNumber' => $obConfirmedPolice->confirmPolicyResult->fullNumber,
260 'series' => $obConfirmedPolice->confirmPolicyResult->series
261 );
262 }
263 }
264 }
265 if (!empty($arReturn))
266 return $arReturn;
267 else
268 return array('ERROR'=>'Ошибка при подтверждении полиса. Обратитесь к администратору сайта. ID заказа: '.$orderID);
269 }
270
271 }
272 return false;
273 }
274
275 /**
276 * Метод возвращает полисы заказа из товара
277 */
278 public static function getPolicies($orderProducts, $orderID) {
279 $prod = false;
280
281 $tesOptions = Option::getForModule('biletik.tes', SITE_ID);
282
283 $obElements = ElementTable::getList(array(
284 'filter'=>array('IBLOCK_ID'=>$tesOptions['POLICIES_IBLOCK_ID'], 'ID'=>$orderProducts),
285 'select'=>array('ID', 'DETAIL_TEXT', 'CODE')
286 ));
287 if ($arElement = $obElements->fetch()) {
288 if ($arElement['CODE'] == $orderID.'_confirmed') {
289 $policyData = unserialize($arElement['DETAIL_TEXT'])['finalData'];
290 foreach ($policyData as $productCode => $arProducts) {
291 foreach ($arProducts as $key => $item) {
292 $res = json_decode($item);
293 $prod[] = $res->confirmPolicyResult->policyDocument->url;
294 unset($res);
295 }
296 }
297 }
298 }
299
300 return $prod;
301 }
302
303 /**
304 * Метод выписывает созданный полис
305 */
306 private function confirmPolicy($arPolicy) {
307 $obPolicy = json_decode($arPolicy['policy']);
308
309 $params = array(
310 'confirmPolicyRequest' => array(
311 'operator' => array(
312 'code' => $this->moduleParameters['OPERATOR_CODE'],
313 ),
314 'policyId' => $obPolicy->createPolicyResult->policyId
315 )
316 );
317 $response = $this->execRequest($params, $this->requestURL['confirmPolicyRequest']);
318 return $response;
319 }
320
321 /**
322 * Калькуляция стоимости с учетом наценки. Наценка может быть фиксированная сумма либо процент от стоимости
323 */
324 private function getExtraCharge($response) {
325 if ($this->moduleParameters['EXTRA_CHARGE_PRICE_ALL_VAL'] != 0) {
326 foreach ($response as $k => $ob) {
327 if (empty($ob) || !isset($ob->calculatePolicyResult->calculationResult->premium)) continue;
328
329 if ($this->moduleParameters['EXTRA_CHARGE_ALL_TYPE'] == 'N')
330 $response[$k]->calculatePolicyResult->calculationResult->premium = $ob->calculatePolicyResult->calculationResult->premium +
331 $this->moduleParameters['EXTRA_CHARGE_PRICE_ALL_VAL'];
332 elseif ($this->moduleParameters['EXTRA_CHARGE_ALL_TYPE'] == 'P')
333 $response[$k]->calculatePolicyResult->calculationResult->premium = $response[$k]->calculatePolicyResult->calculationResult->premium /
334 100 * (100 + $this->moduleParameters['EXTRA_CHARGE_PRICE_ALL_VAL']);
335 }
336 }
337
338 return $response;
339 }
340
341 /**
342 * Запрос создания полисов
343 */
344 public function createPolicy($productCode, $orderID) {
345 $dbApiVer = OrderPropsValueTable::getList(array(
346 'filter'=>array('ORDER_ID'=>$orderID, 'CODE'=>'ORDER_API'),
347 'select'=>array('VALUE')
348 ));
349 if ($apiVer = $dbApiVer->fetch()) {
350 if ($apiVer['VALUE'] == 'zeus') {
351 $dataCalculation = TesHelper::getCompileTravellersDataZeus($orderID);
352 }
353 else {
354 $dataCalculation = TesHelper::getCompileTravellersData($orderID);
355 }
356 }
357 else {
358 $dataCalculation = TesHelper::getCompileTravellersData($orderID);
359 }
360
361 foreach ($productCode as $code => $arProduct) {
362 foreach ($arProduct as $kTraveller => $prod) {
363
364 $policyParameters = $dataCalculation['TRAVELLERS'][$kTraveller];
365 if ($prod === 'ON_TC_BG_ZV_NS_165_235')
366 unset($policyParameters['riskValue']);
367
368 $params = array(
369 'createPolicyRequest' => array(
370 'operator' => array(
371 'code' => $this->moduleParameters['OPERATOR_CODE']
372 ),
373 'product' => array(
374 'code' => $prod
375 ),
376 'policyParameters' => $policyParameters
377 )
378 );
379 $requestParameters[] = $params;
380
381 $response[$code][$kTraveller] = array(
382 'product' => $prod,
383 'policy' => $this->execRequest($params, $this->requestURL['createPolicyRequest'])
384 );
385 }
386 }
387
388 $notCreatedPolicies = false;
389 foreach ($response as $code => $arPolicyType) {
390 foreach ($arPolicyType as $user => $arPolicy) {
391 $obPolicy = json_decode($arPolicy['policy']);
392
393 if ($obPolicy->createPolicyResult->returnCode->code != 'OK') {
394 $notCreatedPolicies = true;
395 }
396 }
397 }
398 if ($notCreatedPolicies)
399 fp(
400 array(
401 'params'=>$requestParameters,
402 'response'=>$response
403 ),
404 'error_create_policy_'.$orderID
405 );
406
407 return $response;
408 }
409
410 /**
411 * Добавление полисов к заказу
412 */
413 public function addPolicyToOrder($policyData, $orderID) {
414 $basketAction = 'ADD';
415 $price = 0;
416 $currentPolicies = array();
417
418 // get the policy code:
419 $policyCode = array_shift(array_values($policyData));
420
421 // first we need to check if there are already some policies in order. Getting basket for order:
422 $dbCurrent = CSaleBasket::GetList(
423 array(),
424 array('ORDER_ID'=>$orderID),
425 false,
426 false,
427 array('ID', 'PRODUCT_ID', 'ORDER_ID')
428 );
429 while ($obCurrent = $dbCurrent->GetNext()) {
430 $arElements[$obCurrent['ID']] = $obCurrent['PRODUCT_ID'];
431 }
432
433 // now check if there policies in basket:
434 if (!empty($arElements)) {
435 $dbElement = CIBlockElement::GetList(
436 array(),
437 array('ID' => $arElements, 'IBLOCK_ID' => $this->moduleParameters['POLICIES_IBLOCK_ID']),
438 false,
439 false,
440 array('ID', 'IBLOCK_ID', 'DETAIL_TEXT')
441 );
442 if ($obElement = $dbElement->GetNext()) {
443 $currentPolicies = unserialize($obElement['~DETAIL_TEXT']);
444 $policeID = $obElement['ID'];
445 $basketAction = 'UPDATE';
446 $basketItemID = array_search($obElement['ID'], $arElements);
447 }
448 $currentPolicies[$policyCode] = $policyData;
449
450 }
451
452 // calculate price for police:
453 $arPrice = json_decode($this->getCalculation($currentPolicies, $orderID));
454
455 $arPriceProp = array();
456 foreach ($arPrice as $code_policy => $json) {
457 $calculations = json_decode($json);
458 foreach ($calculations as $key_traveller => $calculation) {
459 $arPriceProp[$code_policy][$key_traveller] = array(
460 'PRICE'=>$calculation->calculatePolicyResult->calculationResult->premium,
461 'CURRENCY'=>$calculation->calculatePolicyResult->calculationResult->currency
462 );
463 if ($calculation->calculatePolicyResult->returnCode->code == 'OK')
464 $price += $calculation->calculatePolicyResult->calculationResult->premium;
465 }
466 }
467
468 $PROP = array();
469 if(!empty($arPrice)) {
470 $properties = CIBlockProperty::GetList(Array("sort" => "asc", "name" => "asc"), Array("ACTIVE" => "Y", "IBLOCK_ID" => $this->moduleParameters['POLICIES_IBLOCK_ID'], "CODE" => "PREVIEW_INFO_POLICY"));
471 if ($prop_fields = $properties->Fetch()) {
472 $PROP[$prop_fields["ID"]] = serialize($arPriceProp);
473 }
474 }
475
476 // now add/update policy
477 $el = new CIBlockElement();
478
479 $itemDetailText = serialize($currentPolicies);
480
481 $arFields = array(
482 'IBLOCK_ID' => $this->moduleParameters['POLICIES_IBLOCK_ID'],
483 'NAME' => 'Полисы для заказа '.$orderID,
484 'DETAIL_TEXT' => $itemDetailText,
485 'DETAIL_TEXT_TYPE' => 'TEXT',
486 'CODE' => $orderID,
487 'ACTIVE' => 'Y',
488 "PROPERTY_VALUES"=> $PROP,
489 );
490 if (isset($policeID)) {
491 $el->Update($policeID, $arFields);
492 $productExist = true;
493 }
494 else
495 $policeID = $el->Add($arFields);
496
497
498 if ($policeID && $price > 0) {
499 $arFieldsProduct = array(
500 'ID'=>$policeID,
501 'AVAILABLE'=>'Y',
502 'VAT_INCLUDED'=>'Y',
503 'PRICE_TYPE'=>'S',
504 'CAN_BUY_ZERO'=>'Y'
505 );
506 if ($productExist != 'Y')
507 $productExist = CCatalogProduct::Add($arFieldsProduct);
508
509 if ($productExist) {
510 $PRICE_TYPE_ID = 1;
511 $arFieldsPrice = Array(
512 "PRODUCT_ID" => $policeID,
513 "CATALOG_GROUP_ID" => $PRICE_TYPE_ID,
514 "PRICE" => intval($price),
515 "CURRENCY" => "RUB",
516 );
517 $dbPrice = CPrice::GetList(
518 array(),
519 array(
520 "PRODUCT_ID" => $policeID,
521 "CATALOG_GROUP_ID" => $PRICE_TYPE_ID
522 )
523 );
524 if ($arPrice = $dbPrice->Fetch()) {
525 CPrice::Update($arPrice["ID"], $arFieldsPrice);
526 } else {
527 CPrice::Add($arFieldsPrice);
528 }
529 }
530
531 // and add item to basket/order
532 $arBasketItem = array(
533 'PRODUCT_ID' => $policeID,
534 'PRICE' => $price,
535 'CURRENCY' => 'RUB',
536 'QUANTITY' => 1,
537 'LID' => SITE_ID,
538 'NAME' => $arFields['NAME'],
539 'ORDER_ID' => $orderID,
540 'DETAIL_PAGE_URL' => '/bitrix/admin/iblock_element_edit.php?IBLOCK_ID='.$this->moduleParameters['POLICIES_IBLOCK_ID']
541 .'&type=catalog_migration&ID='.$policeID.'&lang=ru',
542 );
543 if ($basketAction == 'ADD')
544 CSaleBasket::Add($arBasketItem);
545 elseif ($basketAction == 'UPDATE')
546 CSaleBasket::Update($basketItemID, $arBasketItem);
547
548 return number_format($price, 0, '.', ' ');
549 }
550 }
551
552 /**
553 * Удаление полисов из заказа
554 */
555 public function removePolicyFromOrder($policyData, $orderID) {
556 $policyCode = array_shift(array_values($policyData));
557 $dbBasket = CSaleBasket::GetList(
558 array(),
559 array('ORDER_ID'=>$orderID),
560 false,
561 false,
562 array('ID', 'PRODUCT_ID')
563 );
564 while($ob = $dbBasket->GetNext()) {
565 $arBasket[$ob['ID']] = $ob['PRODUCT_ID'];
566 }
567
568 $dbElement = CIBlockElement::GetList(
569 array(),
570 array('ID'=>$arBasket, 'IBLOCK_ID' => $this->moduleParameters['POLICIES_IBLOCK_ID']),
571 false,
572 false,
573 array('ID', 'IBLOCK_ID', 'DETAIL_TEXT')
574 );
575 if ($ob = $dbElement->GetNext()) {
576 $policyBasketItem = array_search($ob['ID'], $arBasket);
577 CSaleBasket::Delete($policyBasketItem);
578
579 $data = unserialize($ob['~DETAIL_TEXT']);
580 unset($data[$policyCode]);
581
582 if(CIBlock::GetPermission($this->moduleParameters['POLICIES_IBLOCK_ID'])>='W')
583 {
584 global $DB;
585 $DB->StartTransaction();
586 if(!CIBlockElement::Delete($ob['ID']))
587 {
588 $DB->Rollback();
589 }
590 else
591 $DB->Commit();
592 }
593
594 if (!empty($data)) {
595 $return = 0;
596 foreach ($data as $code => $arData)
597 $return += $this->addPolicyToOrder($arData, $orderID);
598
599 return $return;
600 }
601
602 return false;
603 }
604
605
606 }
607
608 /**
609 * Получение набора полей для запроса калькуляции типа полиса
610 */
611 public function getCalcFieldsRequired($productCode) {
612 $params = array(
613 'calculationParametersRequest'=>array(
614 'operator'=>array(
615 'code'=>$this->moduleParameters['OPERATOR_CODE'],
616 ),
617 'product'=>array(
618 'code'=>$productCode
619 )
620 )
621 );
622
623 $response = $this->execRequest($params, $this->requestURL['calculationParametersRequest']);
624 $obResponse = json_decode($response);
625
626 return $obResponse;
627 }
628
629 /**
630 * Инициализация калькуляции полисов
631 */
632 public function init($orderID) {
633 $this->orderID = $orderID;
634
635 if ($products = $this->getProductList())
636 $calculatedProducts = $this->getCalculation($products, $orderID);
637
638 return $calculatedProducts;
639 }
640
641 /**
642 * @param $orderID
643 * @return mixed
644 * возвращает список доступных продуктов, селект и калькуляцию дефолтного продукта
645 */
646 public function getProductList($orderID = 0) {
647 $parameters = array(
648 "availableProductsRequest"=>array(
649 "operator"=>array(
650 "code"=>$this->moduleParameters['OPERATOR_CODE']
651 )
652 )
653 );
654
655 $response = $this->execRequest($parameters, $this->requestURL['availableProductsRequest']);
656
657 $obResponse = json_decode($response);
658
659
660 if (!empty($this->moduleParameters['AR_AVAILABLE_PRODUCTS'])) {
661 foreach ($obResponse->availableProductsResult->productList->product as $k => $obProduct) {
662 $arProduct = get_object_vars($obProduct);
663 if (!in_array($arProduct['@code'], $this->moduleParameters['AR_AVAILABLE_PRODUCTS']))
664 unset($obResponse->availableProductsResult->productList->product[$k]);
665 }
666 }
667 $arResponse['RAW'] = $obResponse;
668
669 if ($orderID == 0)
670 return $obResponse;
671
672 if (!empty($obResponse->availableProductsResult->productList->product)) {
673 // lets get travelers count for drawing select for each traveller
674 $dbApiVer = OrderPropsValueTable::getList(array(
675 'filter'=>array('ORDER_ID'=>$orderID, 'CODE'=>'ORDER_API'),
676 'select'=>array('VALUE')
677 ));
678 if ($apiVer = $dbApiVer->fetch()) {
679 if ($apiVer['VALUE'] == 'zeus') {
680 $travellers = TesHelper::getCompileTravellersDataZeus($orderID);
681 }
682 else {
683 $travellers = TesHelper::getCompileTravellersData($orderID);
684 }
685 }
686 else {
687 $travellers = TesHelper::getCompileTravellersData($orderID);
688 }
689
690 //$arResponse['productSelect'] = $this->getProductSelect($orderID, $obResponse, $travellers);
691 $products = TesHelper::getInsuranceProducts($orderID, $obResponse, $travellers);
692 $arResponse['productsBlocks'] = $products['html'];
693// $arResponse['productsBlocksPopup'] = str_replace(array('id="', 'for="'), array('id="popup_', 'for="popup_'), $arResponse['productsBlocks']);
694 $arResponse['productsPopup'] = $products['popup'];
695 $arResponse['fullPrice'] = $products['total'];
696 $arResponse['minPrice'] = $products['minPrice'];
697 $arResponse['availProducts'] = $products['availProducts'];
698 }
699
700// $arResponse['defaultProduct'] = $this->getCalculation($arResponse, $orderID);
701 $arResponse['currentPrice'] = $this->getPrice($orderID);
702 $arResponse['rulesLink'] = $this->moduleParameters['RULES_LINK'];
703
704 return $arResponse;
705 }
706
707 /**
708 * Возвращает стоимость добавленных к заказу полисов
709 */
710 private function getPrice($orderID) {
711 // Lets check order if there already some policy. First let's get order basket items
712 $dbBasket = CSaleBasket::GetList(
713 array(),
714 array('ORDER_ID'=>$orderID),
715 false,
716 false,
717 array('ID', 'PRODUCT_ID', 'PRICE')
718 );
719 while ($obBasket = $dbBasket->GetNext()) {
720 $arElement[$obBasket['ID']] = $obBasket['PRODUCT_ID'];
721 $arPrices[$obBasket['PRODUCT_ID']] = $obBasket['PRICE'];
722 }
723
724 // Now let's look if there is policyes iblock item
725 $dbElement = CIBlockElement::GetList(
726 array(),
727 array('IBLOCK_ID'=>$this->moduleParameters['POLICIES_IBLOCK_ID'], 'ID'=>$arElement),
728 false,
729 false,
730 array('ID', 'DETAIL_TEXT')
731 );
732 while ($arItem = $dbElement->GetNext()) {
733 return $arPrices[$arItem['ID']];
734 }
735 }
736
737 /**
738 * Возвращает данные о выбранных и добавленных в заказа страховых услугах
739 */
740 private function getSelectedProducts($orderID) {
741 // Lets check order if there already some policy. First let's get order basket items
742 $dbBasket = CSaleBasket::GetList(
743 array(),
744 array('ORDER_ID'=>$orderID),
745 false,
746 false,
747 array('ID', 'PRODUCT_ID')
748 );
749 while ($obBasket = $dbBasket->GetNext()) {
750 $arElement[$obBasket['ID']] = $obBasket['PRODUCT_ID'];
751 }
752
753 // Now let's look if there is policyes iblock item
754 $dbElement = CIBlockElement::GetList(
755 array(),
756 array('IBLOCK_ID'=>$this->moduleParameters['POLICIES_IBLOCK_ID'], 'ID'=>$arElement),
757 false,
758 false,
759 array('ID', 'DETAIL_TEXT')
760 );
761 while ($arItem = $dbElement->GetNext()) {
762 return $arItem['~DETAIL_TEXT'];
763 }
764 return false;
765 }
766
767 /**
768 * Возвращает стоимость заказа без учета страховки
769 */
770 private function getOrderPriceWithoutInsurance($orderID) {
771 $dbProducts = CSaleBasket::GetList(
772 array(),
773 array('ORDER_ID'=>$orderID),
774 false,
775 false,
776 array('PRICE', 'QUANTITY', 'ID', 'PRODUCT_ID')
777 );
778 while($arProduct = $dbProducts->Fetch()) {
779 $arProducts[$arProduct['PRODUCT_ID']] = $arProduct;
780 $productsID[] = $arProduct['PRODUCT_ID'];
781 }
782 if (empty($productsID)) return false;
783
784 $dbElement = CIBlockElement::GetList(
785 array(),
786 array('ID'=>$productsID),
787 false,
788 false,
789 array('ID', 'IBLOCK_ID')
790 );
791 while($arElement = $dbElement->Fetch()) {
792 if ($arElement['IBLOCK_ID'] == $this->moduleParameters['POLICIES_IBLOCK_ID'])
793 unset($arProducts[$arElement['ID']]);
794 }
795
796 $orderPrice = 0;
797 foreach ($arProducts as $product) {
798 $orderPrice += $product['PRICE']*$product['QUANTITY'];
799 }
800 return $orderPrice;
801 }
802
803 /**
804 * Получение параметров страховых услуг. Использовалось для первоначальной отладки запросов. Можно использовать если
805 * изменятся параметры запросов или будут добавлены новые услуги
806 */
807 private function getPolicyParameters($productCode) {
808 $params = array(
809 'calculationParametersRequest' => array(
810 'operator' => array(
811 'code' => $this->moduleParameters['OPERATOR_CODE']
812 ),
813 'product' => array(
814 'code' => $productCode
815 )
816 )
817 );
818
819 $response = $this->execRequest($params, $this->requestURL['calculationParametersRequest']);
820 $obResponse = json_decode($response);
821
822 return $obResponse;
823 }
824
825 /**
826 * @param array $parameters - parameters of the request
827 * @param $methodUrl - url of the api method
828 * @return array|mixed returns array if error and json if success
829 */
830 private function execRequest($parameters = array(), $methodUrl) {
831 if (empty($methodUrl))
832 return array('error'=>'emptyMethod');
833 $url = $this->moduleParameters['API_URL'].$methodUrl;
834 $strRequest = json_encode($parameters);
835
836 $ch = curl_init();
837
838 curl_setopt($ch, CURLOPT_URL, $url);
839 curl_setopt($ch, CURLOPT_POST, true);
840 curl_setopt($ch, CURLOPT_POSTFIELDS, $strRequest);
841 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
842 curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
843
844 $result = curl_exec($ch);
845
846 curl_close($ch);
847
848 return $result;
849 }
850}