/**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params, $fantasy_type = 'all', $only_active = true)
 {
     $query = DotaFantasy::find()->joinWith('event');
     $dataProvider = new ActiveDataProvider(['query' => $query]);
     $this->load($params);
     if (!$this->validate()) {
         // uncomment the following line if you do not want to return any records when validation fails
         // $query->where('0=1');
         return $dataProvider;
     }
     $query->andFilterWhere(['id' => $this->id, 'event_id' => $this->event_id, 'draft_id' => $this->draft_id, 'users_count' => $this->users_count, 'deposit' => $this->deposit, 'prize_pool' => $this->prize_pool]);
     $query->andFilterWhere(['like', 'name', $this->name]);
     switch ($fantasy_type) {
         case self::FANTASY_LIST_NOW:
             $query->andFilterWhere(['<', 'start', time()]);
             $query->andFilterWhere(['>', 'end', time()]);
             break;
         case self::FANTASY_LIST_FUTURE:
             $query->andFilterWhere(['>', 'start', time()]);
             break;
     }
     if ($only_active == true) {
         $query->andFilterWhere(['=', 'status', self::FANTASY_ACTIVE]);
     }
     return $dataProvider;
 }
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = DotaFantasy::find();
     $dataProvider = new ActiveDataProvider(['query' => $query, 'sort' => ['defaultOrder' => ['id' => SORT_DESC]]]);
     $this->load($params);
     if (!$this->validate()) {
         // uncomment the following line if you do not want to return any records when validation fails
         // $query->where('0=1');
         return $dataProvider;
     }
     $query->andFilterWhere(['id' => $this->id, 'event_id' => $this->event_id, 'users_count' => $this->users_count, 'deposit' => $this->deposit, 'prize_pool' => $this->prize_pool]);
     $query->andFilterWhere(['like', 'name', $this->name]);
     return $dataProvider;
 }
Example #3
0
 public static function loadHeroesListOnFantasy($fantasy_id)
 {
     $event_id = DotaFantasy::getEventId($fantasy_id);
     $eventModel = DotaEvent::findOne($event_id);
     if ($eventModel === null) {
         return;
     }
     $rows = $eventModel->eventHeroesList;
     //echo'<pre>';print_r($rows);echo'</pre>';die;
     return $rows;
 }
}	else	{
	$current_events_url = Url::to(['dota2fantasy/'.$current_action, 'type'=>'current']);
	$futured_events_url = Url::to(['dota2fantasy/'.$current_action, 'type'=>'future']);	
}
*/
$current_events_url = Url::to(['dota2fantasy/' . $current_action, 'type' => 'all']);
$futured_events_url = Url::to(['dota2fantasy/' . $current_action]);
/*
if($fantasy_type != 'futured') {
	$fantasyType = ['type'=>$fantasy_type];
}	else	{
	$fantasyType = [];
}
*/
$fantasy_type_list = [];
$fantasy_type_list_ = DotaFantasy::getTypeList();
foreach ($fantasy_type_list_ as $k => $val) {
    $url = Url::to(['dota2fantasy/' . $current_action, 'type' => $k]);
    $fantasy_type_list[$url] = $val;
}
$active_fantasy_type = Url::to(['dota2fantasy/' . $current_action, 'type' => $fantasy_type]);
//echo'<pre>';print_r($fantasy_type_list);echo'</pre>';//die;
$event_type_params = ['id' => 'fantasy-type', 'class' => 'width-150'];
if ($current_action == 'stat') {
    $event_type_params['disabled'] = 'disabled';
}
?>

<div class="section-head head-menu">

	<?php 
Example #5
0
 /**
  * возвращает модель фантазии в зависимости от вида игры
  *
  * @param int $fantasy_id
  * @param int $game_id
  * @return mixed
  */
 private static function getFantasyModel($fantasy_id, $game_id)
 {
     switch ($game_id) {
         case Transaction::TR_GAME_DOTA:
             $fantasyModel = DotaFantasy::findOne($fantasy_id);
             break;
         case Transaction::TR_GAME_POKER:
             $fantasyModel = PokerFantasy::findOne($fantasy_id);
             break;
     }
     return $fantasyModel;
 }
Example #6
0
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getFantasies()
 {
     return $this->hasMany(DotaFantasy::className(), ['event_id' => 'id']);
 }
Example #7
0
 /**
  * добавляет в базу новую ставку
  *
  * @param $fantasy
  * @return bool
  */
 public function addRate($fantasy)
 {
     $draftModel = new DotaDraft();
     $draftModel->attributes = $this->attributes;
     if ($draftModel->save() === false) {
         return false;
     }
     //echo'<pre>'; print_r($draftModel);echo'</pre>';die;
     switch ($this->scenario) {
         case self::SCENARIO_MIXED_DRAFT:
             $DotaDraftPlayer = new DotaDraftPlayer();
             $DotaDraftHero = new DotaDraftHero();
             $DotaDraftPlayer->addPlayersRows($this->players, $draftModel->id, $this->draft_slots);
             $DotaDraftHero->addHeroesRows($this->heroes, $draftModel->id);
             break;
         case self::SCENARIO_PLAYERS_DRAFT:
             $DotaDraftPlayer = new DotaDraftPlayer();
             $DotaDraftPlayer->addPlayersRows($this->players, $draftModel->id, $this->draft_slots);
             break;
         case self::SCENARIO_HEROES_DRAFT:
             $DotaDraftHero = new DotaDraftHero();
             $DotaDraftHero->addHeroesRows($this->heroes, $draftModel->id);
             break;
     }
     //снимаем взнос+комиссия у игрока
     $user = User::findOne(Yii::$app->user->id);
     $deposit_before = $user->deposit;
     $user->deposit = $user->deposit - $fantasy->deposit - $fantasy->fee;
     if ($user->save() === false) {
         $draftModel->delete();
         //если возникла ошибка - удаляем из базы ставку пользователя
         return false;
     }
     //заносим в лог
     $data = ['fantasy_id' => $fantasy->id, 'game' => Transaction::TR_GAME_DOTA];
     $trans_descr = Transaction::buildTransactionDescrForSave(Transaction::TR_TYPE_FANTASY_PAYMENT, $data);
     Transaction::saveTransaction($user->id, $deposit_before, -($fantasy->deposit + $fantasy->fee), $trans_descr);
     //если нужно - увеличиваем призовой фонд
     $total_sum_rates = $draftModel->getCountFantasyDrafts($fantasy->id) * $fantasy->deposit;
     if ($total_sum_rates > $fantasy->prize_pool_real) {
         DotaFantasy::upateRealPrizePool($fantasy->id, $total_sum_rates);
     }
     return true;
 }
 /**
  * Расчет призовых выплат
  * 1. загрузить модель фантазии по которой нужно сделать расчет
  * 2. получить рейтинг игроков, сыгравших в данной фантазии
  * 3. получить ставки пользователей на игроков по данной фантазии
  * 4. Просуммировать очки игроков в соответствии со ставками пользователей
  * 5. Отсортировать массив по убыванию.
  * 6. Получить массив распределения ставок пользователей по местам и массив
  *    в котором представлено кол-во ставок пользователеей на каждое призовое место
  * 7. Получить колонку в матрице призовых, с которой будем работать
  * 8. Рассчитать процент выплат для каждой ставки
  * 9. Рассчитать сумму выплаты для каждой ставки
  * 10. Перечислить сумму выйгрыша на балланс пользователя, сделавшего ставку.
  * 11. Занести данну операцию в лог пользователя.
  *
  */
 public function actionCalculatePrize()
 {
     echo '<pre>';
     print_r('actionCalculatePrize');
     echo '</pre>';
     //die;
     // 1. загрузить модель фантазии по которой нужно сделать расчет
     $fantasyModel = DotaFantasy::findOne(7);
     $event_id = $fantasyModel->event_id;
     // 2. получить рейтинг игроков, сыгравших в данной фантазии
     $players_rating = DotaEventPlayerStat::getRatingForEvent($event_id);
     // 3. получить ставки пользователей на игроков по данной фантазии
     $users_players_draft = [];
     foreach ($fantasyModel->dotaDraft as $draft) {
         switch ($fantasyModel->draft_id) {
             case DotaFantasy::DOTA_PLAYERS_DRAFT_ID:
                 $users_players_draft[$draft->user_id] = ArrayHelper::map($draft->dotaDraftPlayers, 'id', 'account_id');
                 break;
             case DotaFantasy::DOTA_HEROES_DRAFT_ID:
                 break;
             case DotaFantasy::DOTA_MIXED_DRAFT_ID:
                 break;
         }
     }
     // 4. Просуммировать очки игроков в соответствии со ставками пользователей
     $scores_arr = [];
     foreach ($users_players_draft as $user_id => $user_draft) {
         $summ = 0;
         foreach ($user_draft as $account_id) {
             $summ += isset($players_rating[$account_id]) ? $players_rating[$account_id] : 0;
         }
         $scores_arr[$user_id] = $summ;
     }
     // без одинаковых очков
     $scores_arr = [19 => 780.14, 14 => 432.94, 20 => 631.01, 23 => 621.04, 12 => 321.1, 10 => 415.14, 24 => 508.26, 18 => 319.05, 45 => 194.05, 44 => 694.5];
     /**/
     /*
     		// есть 2 одинаковых
     		$scores_arr = [
     			79 => 694.50,
     			19 => 621.04,	
     			14 => 432.94,	
     			20 => 631.01,	
     			23 => 621.04,
     			12 => 631.01,
     			10 => 580.14,
     			24 => 508.26,
     			18 => 319.05,
     			45 => 194.05,
     			44 => 694.50,
     		];
     		/**/
     /*
     		// есть 3 одинаковых по 2 раза
     		$scores_arr = [
     			19 => 580.14,	
     			14 => 432.94,	
     			20 => 580.14,
     			23 => 621.04,
     			12 => 321.10,
     			10 => 580.14,
     			24 => 621.04,
     			18 => 621.04,
     			45 => 194.05,
     			44 => 694.50,
     		];
     		/**/
     //echo'<pre>';print_r($scores_arr);echo'</pre>';//die;
     // 5. Отсортировать массив по убыванию.
     arsort($scores_arr);
     echo '<pre>';
     print_r($scores_arr);
     echo '</pre>';
     //die;
     // 	6. Получить массив распределения ставок пользователей по местам и массив,
     //	в котором представлено кол-во ставок пользователеей на каждое призовое место
     $places = $places1 = $equal_places = [];
     $place = $prev_scores = 0;
     $place1 = 1;
     foreach ($scores_arr as $k => $i) {
         if ($i != $prev_scores) {
             $place++;
         }
         $equal_places[$place][] = $k;
         $places[$k] = $place;
         $prev_scores = $i;
         $places1[$k] = $place1;
         $place1++;
     }
     echo '<pre>';
     print_r($places);
     echo '</pre>';
     //die;
     echo '<pre>';
     print_r($places1);
     echo '</pre>';
     //die;
     echo '<pre>';
     print_r($equal_places);
     echo '</pre>';
     //die;
     // 7. Получить колонку в матрице призовых, с которой будем работать
     $usersColumn = PrizeMatrix::getUsersColumn(count($places));
     echo '$usersColumn<pre>';
     print_r($usersColumn);
     echo '</pre>';
     //die;
     // загружаем матрицу процентов
     $PrizeMatrix = PrizeMatrix::findOne(1);
     $PrizeMatrix->loadGrid();
     // 8. Рассчитать процент выплат для каждой ставки
     $percents_arr = [];
     //$place = 1;
     foreach ($equal_places as $place_ => $places_) {
         //$percent = $PrizeMatrix->getPercent($place, count($places));
         //$percent_part = floor(($percent / count($places_)) * 100) / 100;
         //$percent_part = $percent / count($places_);
         //foreach($places_ as $user_id) $places[$user_id] = $percent_part;
         $summ_percent = 0;
         //echo'<pre>';print_r($places_);echo'</pre>';//die;
         foreach ($places_ as $user_id) {
             $place = $places1[$user_id];
             $percent = $PrizeMatrix->getPercent($place, count($places));
             $summ_percent += $percent;
         }
         $percent_part = floor($summ_percent / count($places_) * 100) / 100;
         foreach ($places_ as $user_id) {
             $places[$user_id] = $percent_part;
         }
         //echo'<pre>$summ_percent = ';print_r($summ_percent);echo'</pre>';//die;
     }
     //die;
     //echo'<pre>$places ';print_r($places);echo'</pre>';//die;
     //проверка корректности расчета
     $summ = 0;
     foreach ($places as $place) {
         $summ += $place;
     }
     //echo'<pre>';print_r($summ);echo'</pre>';//die;
     // 9. Рассчитать сумму выплаты для каждой ставки
     //$fantasyModel->prize_pool = 7097;
     //$fantasyModel->prize_pool = 1000;
     $prizes = [];
     foreach ($places as $user_id => $percent) {
         $prizes[$user_id] = floor($fantasyModel->prize_pool * ($percent / 100) * 100) / 100;
     }
     //$prizes[$user_id] = $fantasyModel->prize_pool * ($percent / 100);
     echo '<pre>$fantasyModel->prize_pool = ';
     print_r($fantasyModel->prize_pool);
     echo '</pre>';
     //die;
     echo '<pre>';
     print_r($prizes);
     echo '</pre>';
     //die;
     //проверка корректности расчета
     $summ = 0;
     foreach ($prizes as $prize) {
         $summ += $prize;
     }
     echo '<pre>';
     print_r($summ);
     echo '</pre>';
     //die;
     // 10. Перечислить сумму выйгрыша на балланс пользователя, сделавшего ставку.
     //User::updateUserDeposit(-10, 14);
     // 11. Занести данну операцию в лог пользователя.
     die;
 }
 public function actionShowRatings($id)
 {
     $modelFantasy = new DotaFantasy();
     $model = $modelFantasy->loadFantasyInfo($id);
     //echo'<pre>';print_r($model);echo'</pre>';die;
     if ($model === false) {
         return;
     }
     $DraftModel = new DotaDraft();
     $rates_list = $DraftModel->getRatesListWithResults([$id]);
     $params = DotaParams::loadParams();
     $prizes = PrizeMatrix::getPrizesForFantasy($model);
     return $this->renderPartial('/common/show-ratings', ['model' => $model, 'rates_list' => $rates_list, 'params' => $params, 'prizes' => $prizes, 'game_id' => GamesParams::GAME_DOTA, 'game_name' => GamesParams::GAME_DOTA_NAME]);
 }
Example #10
0
 /**
  *
  */
 public function createNewTransaction()
 {
     //echo'<pre>';print_r($this);echo'</pre>';die;
     $result = 0;
     $err_msg = '';
     $deposit_before = $this->user->deposit;
     $created_by = Yii::$app->user->id;
     switch ($this->trans_type) {
         case Transaction::TR_TYPE_DEPOSIT:
             //echo'<pre>';print_r($this->user);echo'</pre>';die;
             $res = User::updateUserDeposit($this->value, $this->user->id);
             //echo'<pre>';var_dump($res);echo'</pre>';die;
             if ($res == 1) {
                 $data = ['payment_system' => $this->payment_type, 'payment_status' => PaymentSystem::PAYMENT_STATUS_OK];
                 $result = Transaction::addNewTransaction(Transaction::TR_TYPE_DEPOSIT, $data, $this->user->id, $deposit_before, $this->value, $created_by, $this->comment);
                 if ($result != 1) {
                     $err_msg = 'При создании транзакции возникла ошибка.';
                 }
             } else {
                 $err_msg = 'При обновлении депозита пользователя возникла ошибка.';
             }
             //echo'<pre>';var_dump($result);echo'</pre>';die;
             //$result = true;
             break;
         case Transaction::TR_TYPE_FANTASY_PAYMENT:
             if (($fantasy_model = DotaFantasy::findOne($this->fantasy_id)) !== null) {
                 if ($this->user->deposit >= $fantasy_model->deposit + $fantasy_model->fee) {
                     //$this->value = 0 - ($fantasy_model->deposit + $fantasy_model->fee);
                     $this->value = 0 - $this->value;
                     $res = User::updateUserDeposit($this->value, $this->user->id);
                     if ($res == 1) {
                         $data = ['fantasy_id' => $fantasy_model->id, 'game' => $this->game_id];
                         $result = Transaction::addNewTransaction(Transaction::TR_TYPE_FANTASY_PAYMENT, $data, $this->user->id, $deposit_before, $this->value, $created_by, $this->comment);
                         //echo'<pre>';var_dump($result);echo'</pre>';die;
                     } else {
                         $err_msg = 'При обновлении депозита пользователя возникла ошибка';
                     }
                 } else {
                     $err_msg = 'Недостаточно средств.';
                 }
             } else {
                 $err_msg = 'Ошибка загрузки фантазии.';
             }
             //$result = true;
             break;
         case Transaction::TR_TYPE_FANTASY_CANCEL:
             if (($fantasy_model = DotaFantasy::findOne($this->fantasy_id)) !== null) {
                 $res = User::updateUserDeposit($this->value, $this->user->id);
                 if ($res == 1) {
                     $data = ['fantasy_id' => $fantasy_model->id, 'game' => $this->game_id];
                     $result = Transaction::addNewTransaction(Transaction::TR_TYPE_FANTASY_CANCEL, $data, $this->user->id, $deposit_before, $this->value, $created_by, $this->comment);
                     //echo'<pre>';var_dump($result);echo'</pre>';die;
                 } else {
                     $err_msg = 'При обновлении депозита пользователя возникла ошибка';
                 }
             } else {
                 $err_msg = 'Ошибка загрузки фантазии.';
             }
             //$result = true;
             break;
         case Transaction::TR_TYPE_PAYOUT_PRIZES:
             if (($fantasy_model = DotaFantasy::findOne($this->fantasy_id)) !== null) {
                 $res = User::updateUserDeposit($this->value, $this->user->id);
                 if ($res == 1) {
                     $data = ['fantasy_id' => $fantasy_model->id, 'prize' => $this->value, 'game' => $this->game_id];
                     $result = Transaction::addNewTransaction(Transaction::TR_TYPE_PAYOUT_PRIZES, $data, $this->user->id, $deposit_before, $this->value, $created_by, $this->comment);
                     //echo'<pre>';var_dump($result);echo'</pre>';die;
                 } else {
                     $err_msg = 'При обновлении депозита пользователя возникла ошибка';
                 }
             } else {
                 $err_msg = 'Ошибка загрузки фантазии.';
             }
             //$result = true;
             break;
         case Transaction::TR_TYPE_WITHDRAW:
             //echo'<pre>';print_r($this);echo'</pre>';die;
             if ($this->user->deposit > $this->value) {
                 $this->value = 0 - $this->value;
                 $res = User::updateUserDeposit($this->value, $this->user->id);
                 if ($res == 1) {
                     $data = ['payment_system' => $this->payment_type];
                     $result = Transaction::addNewTransaction(Transaction::TR_TYPE_WITHDRAW, $data, $this->user->id, $deposit_before, $this->value, $created_by, $this->comment);
                 } else {
                     $err_msg = 'При обновлении депозита пользователя возникла ошибка';
                 }
             } else {
                 $err_msg = 'Депозит пользователя меньше выводимой суммы';
             }
             //$result = true;
             break;
         default:
             $result = 0;
             break;
     }
     if ($result != 1 && $err_msg != '') {
         Yii::$app->session->setFlash('error', $err_msg);
     }
     return $result;
 }
Example #11
0
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getFantasy()
 {
     return $this->hasOne(DotaFantasy::className(), ['id' => 'fantasy_id']);
 }
Example #12
0
 /**
  * @return bool
  */
 public static function updateDotaDraftPrizes()
 {
     // 1. получить список активных фантазий (активность из event)
     $events = DotaEvent::getActualEventsList();
     $event_ids = ArrayHelper::map($events, 'id', 'id');
     $fantasies = DotaFantasy::getActiveFantasies($event_ids);
     echo '<pre>';
     print_r($fantasies);
     echo '</pre>';
     //die;
     $DotaDraft = new DotaDraft();
     foreach ($fantasies as $fantasy) {
         $fantasyModel = DotaFantasy::findOne($fantasy['id']);
         $stat_heroes_on_event = DotaEventHeroStat::isPresentHeroesStatInEvent($fantasyModel->event_id);
         $stat_players_on_event = DotaEventPlayerStat::isPresentPlayersStatInEvent($fantasyModel->event_id);
         //echo'<pre>';print_r($fantasyModel->name);echo'</pre>';//die;
         //echo'<pre>';var_dump($stat_heroes_on_event);echo'</pre>';//die;
         //echo'<pre>';var_dump($stat_players_on_event);echo'</pre>';//die;
         //если статистики по матчам еще нет - дальше не обрабатываем
         if (DotaEventHeroStat::isPresentHeroesStatInEvent($fantasyModel->event_id) === false && DotaEventPlayerStat::isPresentPlayersStatInEvent($fantasyModel->event_id) === false) {
             continue;
         }
         //echo'<pre>';print_r($fantasy_id);echo'</pre>';die;
         $DotaFantasy = new DotaFantasy();
         $places = $DotaFantasy->calculatePlacesInFantasy($fantasyModel);
         //echo'<pre>';print_r($places);echo'</pre>';//die;
         //проверка корректности расчета процентов по выйгрышу
         //if(PrizeMatrix::calculationIsCorrect($places) === false) return 1;
         $prizes = $DotaFantasy->calculatePrizesInFantasy($fantasyModel, $places);
         echo '<pre>';
         print_r($prizes);
         echo '</pre>';
         //die;
         //проверка корректности расчета сумм по выйгрышу
         //if(PrizeMatrix::calculationIsCorrect($places, $fantasyModel->prize_pool) === false) return 2;
         $DotaDraft->updatePrizeValues($prizes, $fantasy['id']);
         /*
         foreach($prizes as $user_id=>$value) {
         	$values = [
         		'prize' => $value,
         	];
         
         	$where = [
         		'fantasy_id = ' . $fantasy['id'],
         		'user_id = ' . $user_id,
         	];
         	$DotaDraft->updateRow($values, $where);
         }
         */
     }
     //die;
     return true;
 }