public function actionRusRoomNames($query, $return = false) { $currentLimit = appParams('autocompleteLimit'); $items = Yii::app()->cache->get('autocompleteRusRoomNames' . $query); $items = array(); if (!$items) { $items = array(); $roomNames = array(); $criteria = new CDbCriteria(); $criteria->limit = $currentLimit; $criteria->params[':roomNameRus'] = '%' . $query . '%'; //$criteria->params[':localEn'] = $query.'%'; $criteria->addCondition('t.roomNameRus LIKE :roomNameRus'); /** @var RusNamesRus[] $roomNamesRus */ $roomNamesRus = RoomNamesRus::model()->findAll($criteria); if ($roomNamesRus) { foreach ($roomNamesRus as $roomNameRus) { $items[] = array('id' => $roomNameRus->primaryKey, 'label' => $this->parseTemplate('{roomNameRus}, {id}', $roomNameRus), 'value' => $this->parseTemplate('{roomNameRus}', $roomNameRus)); $roomNames[$roomNameRus->id] = $roomNameRus->id; } } $currentLimit -= count($items); Yii::app()->cache->set('autocompleteRusRoomNames' . $query, $items, appParams('autocompleteCacheTime')); } if ($return) { return $items; } else { $this->send($items); } }
public function actionIndex($isTab = false) { Yii::import('site.common.modules.hotel.models.*'); $hotelForm = new HotelForm(); if (isset($_POST['ajax']) && $_POST['ajax'] === 'hotel-form') { echo CActiveForm::validate($hotelForm); Yii::app()->end(); } if (isset($_POST['HotelForm'])) { $hotelForm->attributes = $_POST['HotelForm']; $rooms = array(); if (isset($_POST['HotelRoomForm'])) { foreach ($_POST['HotelRoomForm'] as $i => $info) { $room = new HotelRoomForm(); $room->attributes = $info; if ($room->validate()) { $rooms[] = $room; } } } $hotelForm->rooms = $rooms; if ($hotelForm->validate()) { $hotelSearchParams = new HotelSearchParams(); $hotelSearchParams->checkIn = date('Y-m-d', strtotime($hotelForm->fromDate)); $hotelSearchParams->city = City::getCityByPk($hotelForm->cityId); $hotelSearchParams->duration = $hotelForm->duration; foreach ($hotelForm->rooms as $room) { if ($room->childCount == 1) { $hotelSearchParams->addRoom($room->adultCount, $room->cots, $room->childAge); } else { $hotelSearchParams->addRoom($room->adultCount, $room->cots, false); } } $HotelClient = new HotelBookClient(); $resultSearch = $HotelClient->fullHotelSearch($hotelSearchParams); Yii::app()->hotelsRating->injectRating($resultSearch->hotels, $hotelSearchParams->city); $cacheId = substr(md5(uniqid('', true)), 0, 10); Yii::app()->cache->set('hotelResult' . $cacheId, $resultSearch, appParams('hotel_search_cache_time')); Yii::app()->cache->set('hotelSearchParams' . $cacheId, $hotelSearchParams, appParams('hotel_search_cache_time')); Yii::app()->cache->set('hotelForm' . $cacheId, $hotelForm, appParams('hotel_search_cache_time')); Yii::app()->user->setState('hotel.cacheId', $cacheId); //die(); $this->redirect('/booking/hotel/result/cacheId/' . $cacheId); } else { $this->render('index', array('items' => $this->generateItems(), 'hotelForm' => $hotelForm, 'autosearch' => false, 'cityName' => '', 'duration' => 1)); } } else { if ($isTab) { $this->renderPartial('index', array('items' => $this->generateItems(), 'hotelForm' => $hotelForm, 'autosearch' => false, 'cityName' => '', 'duration' => 1)); } else { $this->render('index', array('items' => $this->generateItems(), 'hotelForm' => $hotelForm, 'autosearch' => false, 'cityName' => '', 'duration' => 1)); } } }
public function run() { Yii::import('site.common.modules.hotel.models.*'); $hotelForm = new HotelForm(); if (isset($_REQUEST['HotelForm'])) { $hotelForm->attributes = $_REQUEST['HotelForm']; $rooms = array(); if (isset($_REQUEST['HotelRoomForm'])) { foreach ($_REQUEST['HotelRoomForm'] as $i => $info) { $room = new HotelRoomForm(); $room->attributes = $info; if ($room->validate()) { $rooms[] = $room; } } } $hotelForm->rooms = $rooms; if ($hotelForm->validate()) { $hotelSearchParams = new HotelSearchParams(); $hotelSearchParams->checkIn = date('Y-m-d', strtotime($hotelForm->fromDate)); $hotelSearchParams->city = City::getCityByPk($hotelForm->cityId); $hotelSearchParams->duration = $hotelForm->duration; foreach ($hotelForm->rooms as $room) { if ($room->childCount == 1) { $hotelSearchParams->addRoom($room->adultCount, $room->cots, $room->childAge); } else { $hotelSearchParams->addRoom($room->adultCount, $room->cots, false); } } $HotelClient = new HotelBookClient(); $pCacheId = md5(serialize($hotelSearchParams)); Yii::app()->pCache->set('hotelSearchParams' . $pCacheId, $hotelSearchParams, appParams('hotel_search_cache_time')); $resultSearch = $HotelClient->fullHotelSearch($hotelSearchParams); Yii::app()->hotelsRating->injectRating($resultSearch->hotels, $hotelSearchParams->city); $cacheId = substr(md5(uniqid('', true)), 0, 10); Yii::app()->cache->set('hotelResult' . $cacheId, $resultSearch, appParams('hotel_search_cache_time')); Yii::app()->cache->set('hotelSearchParams' . $cacheId, $hotelSearchParams, appParams('hotel_search_cache_time')); Yii::app()->cache->set('hotelForm' . $cacheId, $hotelForm, appParams('hotel_search_cache_time')); if ($resultSearch['hotels']) { $hotelStack = new HotelStack($resultSearch); $results = $hotelStack->groupBy('hotelId')->groupBy('roomSizeId')->groupBy('rubPrice')->sortBy('rubPrice', 2)->getJsonObject(); echo json_encode(array('pCacheId' => $pCacheId, 'cacheId' => $cacheId, 'hotels' => $results)); } else { echo json_encode(array('cacheId' => $cacheId, 'hotels' => array())); } } else { //invalid form throw new CHttpException(500, CHtml::errorSummary($hotelForm)); } Yii::app()->end(); } else { throw new CHttpException(404); } }
/** * @static * @param FlightForm $flightForm * @return mixed */ public static function getAllPricesAsJson($flightForm) { if (!$flightForm instanceof FlightForm) { throw new CHttpException(500, 'MFlightSearch requires instance of FlightForm as incoming param'); } $flightSearchParams = self::buildSearchParams($flightForm); $cacheId = md5(serialize($flightSearchParams)); Yii::app()->pCache->set('flightSearchParams' . $cacheId, $flightSearchParams, appParams('flight_search_cache_time')); $fs = new FlightSearch(); $fs->status = 1; $fs->requestId = '1'; $fs->data = '{}'; $variants = $fs->sendRequest($flightSearchParams, false); $json = $variants->getAsJson(array('pCacheId' => $cacheId)); return $json; }
public static function sendEmailOrderInfo($params, $pdfFileNames) { $msg = new YiiMailMessage(); $msg->view = 'orderInfo'; $msg->setFrom(appParams('adminEmail'), appParams('adminEmailName'))->setTo($params['email'])->setSubject('Заказ номер ' . $params['orderBookingId'] . ' готов'); $msg->setBody($params, 'text/html'); foreach ($pdfFileNames as $key => $pdfInfo) { $attachment = Swift_Attachment::fromPath($pdfInfo['filename']); $attachment->setFilename($pdfInfo['visibleName']); $msg->attach($attachment); } Yii::app()->mail->send($msg); foreach ($pdfFileNames as $key => $pdfInfo) { if (file_exists($pdfInfo['filename'])) { unlink($pdfInfo['filename']); } } }
public function actionCitiesReadable(array $codes) { $cacheKey = 'apiAutocompleteCitiesReadable4' . md5(serialize($codes)); $citiesCache = Yii::app()->cache->get($cacheKey); if ($citiesCache) { $this->send($citiesCache); Yii::app()->end(); } $result = array(); foreach ($codes as $cityCode) { $city = City::getCityByCode($cityCode); $element = array(); $element['id'] = $city->id; $result[$cityCode] = $element; } $result = $this->addMoreInfo($result); Yii::app()->cache->set($cacheKey, $result, appParams('autocompleteCacheTime')); $this->send($result); }
public function execute() { //TODO: need testing possibility go to state startPaymentAction $payments = Yii::app()->payments; $booker = Yii::app()->hotelBooker->getCurrent(); $bill = $payments->getBillForBooker($booker); if ($bill->transactionId) { Yii::app()->payments->updateBillStatus($bill); // We have transactionId for this bill, check its status and go // to next step if everything is ok if ($bill->status == Bill::STATUS_PREAUTH) { Yii::app()->hotelBooker->status('moneyTransfer'); return true; } //! FIXME: DO WE NEED THIS if ($bill->status == Bill::STATUS_PAID) { Yii::app()->hotelBooker->status('moneyTransfer'); Yii::app()->hotelBooker->status('done'); return; } } $params = $payments->getParamsForBillAndBooker($bill, $booker); // $params['ReturnUrl'] = 'http://ya.ru';// $this->controller->createAbsoluteUrl('/booking/hotel/buy/', Array('key'=>$booker->hotel->id)); $context = array('paymentUrl' => $bill->paymentUrl, 'params' => $params); $this->getController()->render('hotelBooker.views.payment_form', $context); return; //! FIXME $this->hotel is undefined if ($this->hotel->cancelExpiration - time() > appParams('hotel_payment_time')) { $res = Yii::app()->cron->add(date(time() + appParams('hotel_payment_time')), 'HotelBooker', 'ChangeState', array('hotelBookerId' => $this->hotelBooker->id, 'newState' => 'softWaitingForPayment')); if ($res) { $this->hotelBooker->saveTaskInfo('paymentTimeLimit', $res); return true; } //! FIXME how should we handle this case } return false; }
protected function updateOrderBookingInfo() { if (!self::$bookingContactInfo) { $orderBookingId = Yii::app()->user->getState('orderBookingId'); $orderBooking = OrderBooking::model()->findByPk($orderBookingId); if (!$orderBooking) { throw new CHttpException(500, "Your order is gone away"); } self::$bookingContactInfo = $orderBooking; self::$bookingContactInfo->attributes = $this->getBookingContactFormData(); $user = Yii::app()->user->getUserWithEmail(self::$bookingContactInfo->email); self::$bookingContactInfo->userId = $user->id; if (!self::$bookingContactInfo->save()) { $errMsg = 'Saving of order booking fails: ' . CVarDumper::dumpAsString($this->bookingContactInfo->errors); $this->logAndThrowException($errMsg, 'OrderComponent.updateOrderBookingInfo'); } if (appParams('autoAssignCurrentOrders')) { $criteria = new CDbCriteria(); $criteria->addColumnCondition(array('email' => self::$bookingContactInfo->email)); OrderBooking::model()->updateAll(array('userId' => $user->id), $criteria); } } return self::$bookingContactInfo; }
public function actionRusRoomNames($query, $return = false) { $currentLimit = appParams('autocompleteLimit'); $currentLimit = 100; $cacheKey = md5($query); $items = Yii::app()->cache->get('autocompleteRusRoomNames' . $cacheKey); //$query = str_replace(' ','%',$query); $words = explode(' ', $query); $words = array_map('trim', $words); $aWords = array(); $i = 0; foreach ($words as $word) { if ($word) { $aWords[] = $word; $i++; if ($i > 6) { $aWords = array($query); break; } } } $queries = array(); $combWords = self::recombineArray($aWords); foreach ($combWords as $comb) { $queries[] = '%' . implode('%', $comb) . '%'; } $items = array(); if (!$items) { $items = array(); $roomNames = array(); $criteria = new CDbCriteria(); $criteria->limit = $currentLimit; foreach ($queries as $key => $query1) { $criteria->params[':roomNameRus' . $key] = $query1; $criteria->addCondition('t.roomNameRus LIKE :roomNameRus' . $key, 'OR'); } /** @var RusNamesRus[] $roomNamesRus */ $roomNamesRus = RoomNamesRus::model()->findAll($criteria); if ($roomNamesRus) { foreach ($roomNamesRus as $roomNameRus) { $items[] = array('id' => $roomNameRus->primaryKey, 'label' => $roomNameRus->roomNameRus . ', ' . $roomNameRus->id, 'value' => $roomNameRus->roomNameRus); $roomNames[$roomNameRus->id] = $roomNameRus->id; } } $currentLimit -= count($items); Yii::app()->cache->set('autocompleteRusRoomNames' . $cacheKey, $items, appParams('autocompleteCacheTime')); } header('Content-type: application/json'); echo json_encode($items); die; }
/** * Do HotelSearch requests with all combinations of room types, * @param HotelSearchParams $hotelSearchParams * @return HotelSearchResponse */ public function fullHotelSearch(HotelSearchParams $hotelSearchParams) { $rooms = $hotelSearchParams->rooms; //Make combinations to combinations Array uasort($rooms, 'HotelBookClient::compareArrayAdultCount'); $combinations = array(); foreach ($rooms as $key => $room) { $rooms[$key]['sizeCount'] = count(self::$roomSizeRoomTypesMap[$room['adultCount']]); $rooms[$key]['sizeIndex'] = 0; } $allCombined = false; // Make ALL possible combinations while (!$allCombined) { $combination = array(); $allCombined = true; foreach ($rooms as $key => $room) { if ($room['sizeCount'] !== $room['sizeIndex'] + 1) { $allCombined = false; } $rooms[$key]['roomSizeId'] = self::$roomSizeRoomTypesMap[$room['adultCount']][$room['sizeIndex']]; $combination[] = array('roomSizeId' => $rooms[$key]['roomSizeId'], 'child' => $rooms[$key]['childCount'], 'cots' => $rooms[$key]['cots'], 'ChildAge' => $rooms[$key]['childAge']); } sort($combination); $combinations[] = $combination; if (!$allCombined) { //next possible state $overflow = false; $iterationComplete = false; foreach ($rooms as $key => $room) { if ($room['sizeCount'] == 1) { continue; } if ($iterationComplete) { if ($overflow) { if ($room['sizeCount'] == $room['sizeIndex'] + 1) { $rooms[$key]['sizeIndex'] = 0; } else { $rooms[$key]['sizeIndex']++; $overflow = false; break; } } else { break; } } else { if ($room['sizeCount'] == $room['sizeIndex'] + 1) { $rooms[$key]['sizeIndex'] = 0; $iterationComplete = true; $overflow = true; } else { $rooms[$key]['sizeIndex']++; break; } } } } } //delete same combinations sort($combinations); foreach ($combinations as $key => $combination) { if (!isset($prevComb)) { $prevComb = $combination; continue; } if ($prevComb == $combination) { unset($combinations[$key]); } $prevComb = $combination; } unset($prevComb); unset($combination); //add requests to queue self::$groupId = substr(md5(uniqid('', true)), 0, 10); $params = array('cityId' => $hotelSearchParams->city->hotelbookId, 'checkIn' => $hotelSearchParams->checkIn, 'duration' => $hotelSearchParams->duration); if (!$params['cityId']) { throw new CException('City ' . $hotelSearchParams->city->localEn . ' does not linked with hotelBookId. You cannot find any hotels there'); } foreach ($combinations as $key => $combination) { $params['rooms'] = array(); foreach ($combination as $i => $room) { if (!isset($prevInd)) { $prevInd = $i; $roomNumber = 1; continue; } if ($combination[$i] === $combination[$prevInd]) { $roomNumber++; continue; } else { $combination[$prevInd]['roomNumber'] = $roomNumber; $params['rooms'][] = $combination[$prevInd]; $prevInd = $i; $roomNumber = 1; } } $combination[$prevInd]['roomNumber'] = $roomNumber; $params['rooms'][] = $combination[$prevInd]; //print_r($params); unset($prevInd); $this->hotelSearch($params, true); } //run all requests $startTime = microtime(true); $this->processAsyncRequests(); $endTime = microtime(true); //Header('ExecutionTimeProcessAsync:'.($endTime - $startTime)); self::$groupId = null; $hotels = array(); $errorDescriptions = array(); foreach ($this->requests as $request) { //echo count($request['result']->hotels).'<br>'; //die(); if (isset($request['result'])) { if ($request['result']->hotels) { foreach ($request['result']->hotels as $hotel) { $key = $hotel->key; if (isset($hotels[$key])) { //echo '--duplicate'; //echo 'have:'; //VarDumper::dump($hotels[$key]); //echo 'new:'; //VarDumper::dump($hotel); //echo "key: $key"; } $hotels[$key] = $hotel; } } if ($request['result']->errorsDescriptions) { foreach ($request['result']->errorsDescriptions as $desc) { $errorDescriptions[] = $desc; } } } else { print_r($request); die; } } //die(); $response = new HotelSearchResponse(); if ($hotels) { $response->responseStatus = ResponseStatus::ERROR_CODE_NO_ERRORS; } else { if (!$errorDescriptions) { $response->responseStatus = ResponseStatus::ERROR_CODE_EMPTY; } else { $response->responseStatus = ResponseStatus::ERROR_CODE_EXTERNAL; $response->errorsDescriptions = $errorDescriptions; } } /* //print_r($combinations); print_r(count($hotels)); print_r($errorDescriptions);*/ if ($hotels) { //echo "pre results count:".count($hotels); if (count($hotelSearchParams->rooms) == 1) { // O_o foreach ($hotelSearchParams->rooms as $room) { break; } if ($room['adultCount'] == 2 && $room['childCount'] == 0 && $room['cots'] == 0) { $allHotelStack = new HotelStack(array('hotels' => $hotels)); //echo "post results count:".count($allHotelStack->_hotels); //die(); //VarDumper::dump($allHotelStack);die(); $allHotelStack->groupBy('categoryId')->groupBy('roomSizeId')->groupBy('roomTypeId')->groupBy('centerDistance')->groupBy('rubPrice'); //$allHotelStack->groupBy('categoryId')->groupBy('centerDistance')->groupBy('rubPrice'); //print_r($allHotelStack); //die(); //VarDumper::dump($allHotelStack);die(); //VarDumper::dump($hotelStack->hotelStacks); foreach ($allHotelStack->hotelStacks as $categoryId => $hotelStack) { //categoryId - star rating (we need 3..5 stars) if ($categoryId == Hotel::STARS_THREE || $categoryId == Hotel::STARS_FOUR || $categoryId == Hotel::STARS_FIVE) { //echo "category: $categoryId<br>"; //VarDumper::dump($hotelStack); die(); $haveStack = false; foreach ($hotelStack->hotelStacks as $i => $hotelStackSize) { //VarDumper::dump($i); //echo "roomSizeId: $i<br>"; //todo: move to room class if (!in_array($i, array(appParams('HotelBook.room.DBL'), appParams('HotelBook.room.TWIN')))) { $hotelStack->deleteStackWithIndex("{$i}"); //unset($hotelStack->hotelStacks[$i]); } else { //echo "in 2"; foreach ($hotelStack->hotelStacks[$i]->hotelStacks as $j => $hotelStackType) { //echo "roomTypeId: $j<br>"; if (!in_array($j, appParams('HotelBook.room.STD'))) { $hotelStack->deleteStackWithIndex("{$i},{$j}"); //unset($hotelStack->hotelStacks[$i]->hotelStacks[$j]); } else { //echo "in 3"; foreach ($hotelStack->hotelStacks[$i]->hotelStacks[$j]->hotelStacks as $k => $hotelStackDistance) { //echo "distance: $k"; if ($k > appParams('HotelBook.distanceFromCityCenter')) { //echo "out $k"; $hotelStack->deleteStackWithIndex("{$i},{$j},{$k}"); //unset($hotelStack->hotelStacks[$i]->hotelStacks[$j]->hotelStacks[$k]); } else { //echo "in 4"; $haveStack = true; } } } } } } if ($haveStack) { $jsonObject = $hotelStack->sortBy('rubPrice', 5)->getHotel()->getJsonObject(); $jsonObject['cityId'] = $hotelSearchParams->city->id; $jsonObject['dateFrom'] = $hotelSearchParams->checkIn; $from = DateTime::createFromFormat('Y-m-d', $hotelSearchParams->checkIn); $jsonObject['dateTo'] = $from->add(new DateInterval('P' . $hotelSearchParams->duration . 'D'))->format('Y-m-d'); Yii::log('TRYING TO SAVE HOTEL CACHE'); $hotelCache = new HotelCache(); $hotelCache->populateFromJsonObject($jsonObject); $hotelCache->save(); } else { //echo "havent"; //VarDumper::dump($hotelStack->getJsonObject(5)); } } } } } $response->hotels = $hotels; } return $response; }
* A view used to create new {@link User} models * @var User $model The User model to be inserted */ $this->breadcrumbs = array('Бронирование' => array('/admin/booking/'), 'Гостиница' => array('/admin/booking/hotel'), 'Поиск'); ?> <?php echo $this->renderPartial('_form_hotel', array('model' => $hotelForm, 'autosearch' => $autosearch, 'cityName' => $cityName)); ?> <a href='#result' class="result-hotel-link" style="display: none">Результаты поиска</a> <h3 id='result'>Результаты поиска</h3> <?php if ($results) { ?> <?php echo $this->renderPartial('_hotels', array('results' => $results, 'variable' => 'hotelResults', 'cacheId' => $cacheId)); } else { ?> <?php echo $this->renderPartial('_hotels_empty', array('cacheId' => $cacheId)); } ?> <?php Yii::app()->clientScript->registerScript('smooth-scroll', "\nvar Utils = new Object();\nUtils.scrollToInfo = new Object();\nUtils.scrollToInfo.duration = 10;\nUtils.scrollToInfo.startPos = 0;\nUtils.scrollToInfo.endPos = 0;\nUtils.scrollToInfo.currentPos = 0;\nUtils.scrollToInfo.Interval = 0;\nUtils.scrollToIteration = function(){\n\n var delta = (Utils.scrollToInfo.endPos - Utils.scrollToInfo.startPos) / 24;\n Utils.scrollToInfo.currentPos = Utils.scrollToInfo.currentPos + delta;\n \$(window).scrollTop(Utils.scrollToInfo.currentPos);\n if(Math.abs(Utils.scrollToInfo.currentPos - Utils.scrollToInfo.endPos) < Math.abs(delta+1)){\n window.clearInterval(Utils.scrollToInfo.Interval);\n }\n}\nUtils.scrollTo = function(selector) {\n if(typeof(selector) == 'string'){\n var oPos = \$(selector).offset();\n }else{\n var oPos = new Object();\n oPos.top = selector;\n }\n var oDocumentTop = \$(document).scrollTop();\n Utils.scrollToInfo.endPos = oPos.top\n Utils.scrollToInfo.startPos = oDocumentTop;\n Utils.scrollToInfo.currentPos = Utils.scrollToInfo.startPos;\n Utils.scrollToInfo.Interval = window.setInterval(Utils.scrollToIteration,Utils.scrollToInfo.duration);\n}\nUtils.scrollTo('#result');\n", CClientScript::POS_READY); ?> <?php $this->widget('site.common.widgets.expiredNotification.expiredNotificationWidget', array('time' => appParams('hotel_search_cache_time'), 'header' => false, 'message' => 'Информация о найденных вами отелях устарела. <a href="">Выполнить поиск снова</a>', 'showCancel' => false, 'modalOptions' => array()));
public function stageTicketingRepeat() { $this->status('ticketingError'); return; //pass; $this->flightBooker->tryCount++; $this->flightBooker->save(); if ($this->flightBooker->tryCount > 3) { $this->status('ticketingError'); } else { $flightTicketingParams = new FlightTicketingParams(); $flightTicketingParams->nemoBookId = $this->flightBooker->nemoBookId; $flightTicketingParams->pnr = $this->flightBooker->pnr; /** @var FlightTicketingResponse $flightTicketingResponse */ $flightTicketingResponse = Yii::app()->gdsAdapter->FlightTicketing($flightTicketingParams); SWLogActiveRecord::$requestIds = array_merge(SWLogActiveRecord::$requestIds, GDSNemoAgency::$requestIds); GDSNemoAgency::$requestIds = array(); if ($flightTicketingResponse->status == 1) { $this->status('ticketReady'); } else { //TODO: переставить стутус через время T + считать количество раз. $res = Yii::app()->cron->add(time() + appParams('flight_repeat_time'), 'flightbooking', 'ChangeState', array('flightBookerId' => $this->flightBooker->id, 'newState' => 'ticketingRepeat')); if ($res) { $this->flightBooker->saveTaskInfo('ticketingRepeat', $res); return true; } //$this->status('ticketingRepeat'); } } }
public static function checkIfExists($code) { $airportCodes = Yii::app()->cache->get('airportCodes'); if (!$airportCodes) { $criteria = new CDbCriteria(); $criteria->select = array('id', 'code'); $criteria->index = 'code'; $values = self::model()->findAll($criteria); $airportCodes = array_keys($values); Yii::app()->cache->set('airportCodes', $airportCodes, appParams('airport_codes_cache')); } return in_array($code, $airportCodes); }
public function stageTicketingRepeat() { echo "event ticketing repeat {$this->hotelBooker->tryCount}\n"; $this->hotelBooker->tryCount++; echo "after ++ {$this->hotelBooker->tryCount}\n"; //return; //$this->hotelBooker->save(); рекурсия if ($this->hotelBooker->tryCount > 3) { $this->status('ticketingError'); return; } $hotelOrderParams = new HotelOrderParams(); $hotelOrderParams->hotel = $this->hotel; $contactName = ''; foreach ($this->hotelBooker->hotelBookingPassports as $passport) { $roomer = new Roomer(); $roomer->setFromHotelBookingPassport($passport); $roomer->roomId = $passport->roomKey; if (!$contactName) { $contactName = $roomer->fullName; } $hotelOrderParams->roomers[] = $roomer; } $hotelOrderParams->contactPhone = $this->hotelBooker->orderBooking->phone; $hotelOrderParams->contactEmail = $this->hotelBooker->orderBooking->email; $hotelOrderParams->contactName = $contactName; $hotelBookClient = new HotelBookClient(); if ($this->hotelBooker->orderId) { $orderInfo = new HotelOrderResponse(); $orderInfo->orderId = $this->hotelBooker->orderId; } else { $orderInfo = $hotelBookClient->addOrder($hotelOrderParams); SWLogActiveRecord::$requestIds = array_merge(SWLogActiveRecord::$requestIds, HotelBookClient::$requestIds); HotelBookClient::$requestIds = array(); } if ($orderInfo->orderId) { $this->hotelBooker->orderId = $orderInfo->orderId; $confirmInfo = $hotelBookClient->confirmOrder($orderInfo->orderId); SWLogActiveRecord::$requestIds = array_merge(SWLogActiveRecord::$requestIds, HotelBookClient::$requestIds); HotelBookClient::$requestIds = array(); if (!$confirmInfo->error) { $this->status('ticketReady'); } else { echo $this->hotelBooker->id; $res = Yii::app()->cron->add(time() + appParams('hotel_repeat_time'), 'hotelbooking', 'ChangeState', array('hotelBookerId' => $this->hotelBooker->id, 'newState' => 'ticketingRepeat')); if ($res) { $this->hotelBooker->saveTaskInfo('repeatTime', $res); } //$this->status('ticketingRepeat'); } } else { $res = Yii::app()->cron->add(time() + appParams('hotel_repeat_time'), 'hotelbooking', 'ChangeState', array('hotelBookerId' => $this->hotelBooker->id, 'newState' => 'ticketingRepeat')); if ($res) { $this->hotelBooker->saveTaskInfo('repeatTime', $res); } //$this->status('ticketingRepeat'); } }
private static function storeToCache($hotelSearchParams, $variants) { $cacheId = md5(serialize($hotelSearchParams)); Yii::app()->pCache->set('hotelSearchResult' . $cacheId, $variants, appParams('hotel_search_cache_time')); Yii::app()->pCache->set('hotelSearchParams' . $cacheId, $hotelSearchParams, appParams('hotel_search_cache_time')); return $cacheId; }
public static function getCities($query) { $currentLimit = appParams('autocompleteLimit'); $items = Yii::app()->cache->get('autocompleteCities' . $query); if (!$items) { $items = array(); $cityIds = array(); if (strlen($query) == 3) { $criteria = new CDbCriteria(); $criteria->limit = $currentLimit; $criteria->with = 'country'; $criteria->params[':code'] = $query; $criteria->addCondition('t.code = :code'); $criteria->order = 'country.position desc, t.position desc'; /** @var City[] $cities */ $cities = City::model()->findAll($criteria); if ($cities) { foreach ($cities as $city) { $items[] = array('id' => $city->primaryKey, 'label' => self::parseTemplate(self::templateForLabelAutocomplete(), $city), 'value' => self::parseTemplate(self::templateForValueAutocomplete(), $city)); $cityIds[$city->id] = $city->id; } } $currentLimit -= count($items); } $criteria = new CDbCriteria(); $criteria->limit = $currentLimit; $criteria->params[':localRu'] = $query . '%'; $criteria->params[':localEn'] = $query . '%'; $criteria->addCondition('t.localRu LIKE :localRu OR t.localEn LIKE :localEn'); if ($cityIds) { $criteria->addCondition('t.id NOT IN (' . join(',', $cityIds) . ')'); } $criteria->with = 'country'; $criteria->order = 'country.position desc, t.position desc'; $cities = City::model()->findAll($criteria); if ($cities) { foreach ($cities as $city) { $items[] = array('id' => $city->primaryKey, 'label' => self::parseTemplate(self::templateForLabelAutocomplete(), $city), 'value' => self::parseTemplate(self::templateForValueAutocomplete(), $city)); $cityIds[$city->id] = $city->id; } } $currentLimit -= count($items); if ($currentLimit) { $criteria = new CDbCriteria(); $criteria->limit = $currentLimit; if (UtilsHelper::countRussianCharacters($query) > 0) { $nameRu = $query; } else { $nameRu = UtilsHelper::cityNameToRus($query); } $metaphoneRu = UtilsHelper::ruMetaphone($nameRu); if ($metaphoneRu) { $criteria->params[':metaphoneRu'] = $metaphoneRu; $criteria->addCondition('t.metaphoneRu = :metaphoneRu'); if ($cityIds) { $criteria->addCondition('t.id NOT IN (' . join(',', $cityIds) . ')'); } $criteria->with = 'country'; $criteria->order = 'country.position desc, t.position desc'; $cities = City::model()->findAll($criteria); if ($cities) { foreach ($cities as $city) { $items[] = array('id' => $city->primaryKey, 'label' => self::parseTemplate(self::templateForLabelAutocomplete(), $city), 'value' => self::parseTemplate(self::templateForValueAutocomplete(), $city)); $cityIds[$city->id] = $city->id; } } $currentLimit -= count($items); } } Yii::app()->cache->set('autocompleteCities' . $query, $items, appParams('autocompleteCacheTime')); } return $items; }
public function startPaymentOld() { // perekluchaem v state startpayment // i proveraem $bookingModel = $this->getOrderBooking(); //test states and time //make StartPayment State $validForPayment = true; $nowTime = time(); /** @var $bookingModel OrderBooking */ if ($bookingModel) { foreach ($bookingModel->flightBookers as $flightBooker) { $flightBookerComponent = new FlightBookerComponent(); $flightBookerComponent->setFlightBookerFromId($flightBooker->id); $expiration = strtotime($flightBookerComponent->getCurrent()->timeout); if (appParams('time_for_payment') < $expiration - $nowTime) { //next state $status = strtolower($flightBookerComponent->getStatus()); if (strpos($status, 'waitingforpayment') !== false) { $flightBookerComponent->status('startPayment'); } else { $validForPayment = false; } } else { $validForPayment = false; } } foreach ($bookingModel->hotelBookers as $hotelBooker) { $hotelBookerComponent = new HotelBookerComponent(); $hotelBookerComponent->setHotelBookerFromId($hotelBooker->id); $expiration = $hotelBookerComponent->hotel->cancelExpiration; if (appParams('time_for_payment') < $expiration - $nowTime) { //next state $status = $hotelBookerComponent->getStatus(); if (strpos($status, 'soft') !== false) { $hotelBookerComponent->status('softStartPayment'); } elseif (strpos($status, 'hard') !== false) { $hotelBookerComponent->status('hardStartPayment'); } else { $validForPayment = false; } } else { $validForPayment = false; } } } else { return false; } return $validForPayment; }
private function createNewOrderBooking() { if (is_numeric(Yii::app()->user->getState('todayOrderId'))) { return Yii::app()->user->getState('todayOrderId'); } $orderBooking = new OrderBooking(); $orderBooking->secretKey = md5(microtime() . time() . appParams('salt')); $orderBooking->save(); $todayOrderId = OrderBooking::model()->count(array('condition' => "DATE(`timestamp`) = CURDATE()")); $readableNumber = OrderBooking::buildReadableNumber($todayOrderId); $orderBooking->saveAttributes(array('readableId' => $readableNumber)); Yii::app()->user->setState('orderBookingId', $orderBooking->id); Yii::app()->user->setState('todayOrderId', $readableNumber); Yii::app()->user->setState('secretKey', $orderBooking->secretKey); return $readableNumber; }
<div class="modal-footer"> <?php $this->widget('bootstrap.widgets.BootButton', array('label' => 'Close', 'url' => '#', 'htmlOptions' => array('data-dismiss' => 'modal'))); ?> </div> <?php $this->endWidget(); ?> <?php $templateVariable = 'flightSearchResult'; $this->renderPartial('_flights', array('variable' => $templateVariable, 'showSaveTour' => false, 'showDelete' => false)); ?> <?php Yii::app()->clientScript->registerScript('flight-search', "\r\n \$('#searchFlight,.repeatFlightSearch').live('click', function(){\r\n \$('#popupInfo').modal('show');\r\n \$('#modalText').html('Поиск перелёта...');\r\n \$('#{$templateVariable}Counter').expiredNotification('stopTimer');\r\n \$.ajax({\r\n url: '/tour/constructor/flightSearch',\r\n dataType: 'json',\r\n data: \$('#flight-form').serialize(),\r\n timeout: 90000\r\n })\r\n .done(function(data) {\r\n var html = {$templateVariable}(data);\r\n \$('#flight-search-result').html(html);\r\n \$('#popupInfo').modal('hide');\r\n \$('#{$templateVariable}Counter').expiredNotification('startTimer');\r\n })\r\n .fail(function(data){\r\n console.log(data);\r\n if (data.statusText=='timeout')\r\n data.responseText = 'Время ожидания запроса превышено.';\r\n \$('#modalText').html('<div class=\"alert alert-error\">Произошла ошибка! Попробуйте <a class=\"repeatFlightSearch\" href=\"#\">повторить поиск</a>.<br>Текст ошибки:<br>'+data.responseText+'</div>');\r\n });\r\n return false;\r\n });\r\n", CClientScript::POS_READY); ?> <?php if (isset($autosearch) and $autosearch) { Yii::app()->clientScript->registerScript('flight-search-autostart', '$("#searchFlight").trigger("click"); $(".fromField").val("' . $fromCityName . '"); $(".toField").val("' . $toCityName . '");', CClientScript::POS_READY); } ?> <?php $this->widget('site.common.widgets.expiredNotification.expiredNotificationWidget', array('id' => $templateVariable . 'Counter', 'autoStart' => false, 'time' => appParams('flight_search_cache_time'), 'header' => false, 'message' => 'Информация о найденных вами перелётах устарела. <a class="repeatFlightSearch" href="#">Выполнить поиск снова</a>', 'showCancel' => false, 'modalOptions' => array()));
private function storeToCache($flightSearchParams) { $cacheId = md5(serialize($flightSearchParams)); Yii::app()->pCache->set('flightSearchResult' . $cacheId, $this->results, appParams('flight_search_cache_time')); Yii::app()->pCache->set('flightSearchParams' . $cacheId, $flightSearchParams, appParams('flight_search_cache_time')); return $cacheId; }