public function init() { parent::init(); if (!Yii::$app->user->isGuest) { $user = Yii::$app->user; } else { $user = false; } if ($this->type == 'recent') { if ($user) { $this->_games = Games::getAllRecentGamesWithForecast($user->id); $this->_view = 'recentGamesUser'; } else { $this->_games = Games::getAllRecentGames(); $this->_view = 'recentGamesGuest'; } } else { if ($user) { $this->_games = Games::getAllFutureGamesWithForecast($user->id); $this->_view = 'futureGamesUser'; } else { $this->_games = Games::getAllFutureGames(); $this->_view = 'futureGamesGuest'; } } }
public function getForecastersListNew() { $forecasters = UsersTournaments::find()->where(['id_tournament' => $this->id_tournament])->with('idUser')->asArray()->all(); $tours = Games::getNumberOfGamesPerTour($this->id_tournament); foreach ($forecasters as &$one) { $one['tours'] = Forecasts::getUserForecastTour($one['id_user'], $this->id_tournament, $tours); } return $forecasters; }
public function actionDetails($id) { $user = Yii::$app->user; Yii::$app->user->returnUrl = Yii::$app->request->url; $tournament = Tournaments::findOne($id); if ($tournament === null) { throw new NotFoundHttpException('Запрашиваемая страница не найдена.'); } $teamParticipants = new ArrayDataProvider(['allModels' => Result::getStandings($id), 'pagination' => false]); //games list prep if (Yii::$app->request->post('tours')) { $tours = Yii::$app->request->post('tours'); } else { $tours = range(1, $tournament->num_tours, 1); } for ($i = 1; $i <= $tournament->num_tours; $i++) { $tour_list[$i] = "{$i} тур"; } $forecasters = new ActiveDataProvider(['query' => UsersTournaments::find()->forecastersStandings($id), 'pagination' => false]); //if guest or not participating in the tournament if ($user->isGuest || !$user->identity->isUserParticipatesInTournament($id)) { $tourGames = Games::getGamesGroupedByTour($id, $tours); $viewFile = 'tournamentDetailsGuest'; $winners = []; $forecastedStandings = []; } else { $forecastedStandings = new ArrayDataProvider(['allModels' => Result::getForecastedStandings($id, $user->id), 'pagination' => false]); $tourGames = Games::getGamesGroupedByTourWithForecast($id, $tours, $user->id); $viewFile = 'tournamentDetailsUser'; //preparing tournament winners forecast form $winners = new TopTeamsForm($user->id, $id); if ($winners->load(Yii::$app->request->post()) && $winners->validate()) { if (time() < $tournament->wfDueTo) { $winners->edit(); Yii::$app->getSession()->setFlash('success', 'Прогноз на призеров турнира успешно сохранен'); } else { Yii::$app->getSession()->setFlash('success', 'Не нужно пытаться обмануть :)'); } return $this->refresh(); } } $data = compact('tournament', 'teamParticipants', 'forecasters', 'tour_list', 'tourGames', 'winners', 'forecastedStandings'); if ($tournament->is_active == Tournaments::FINISHED) { $data['additionalPoints'] = implode('</br>', Top3TeamsForecast::getClarifications($user->id, $id)); $userTournamentsModel = UsersTournaments::find()->where(['id_tournament' => $id])->andWhere(['id_user' => $user->id])->with('winnersForecast')->one(); if (!empty($userTournamentsModel)) { $data['totalAdditionalPoints'] = $userTournamentsModel->calculateAdditionalPoints(); } } else { $data['additionalPoints'] = ''; $data['totalAdditionalPoints'] = ''; } return $this->render($viewFile, $data); }
public static function getAutoReminderRecipients($tournament, $tour) { $candidates = self::find()->joinWith('idUser')->where(['id_tournament' => $tournament, 'notification' => self::NOTIFICATION_ENABLED, 'active' => Users::STATUS_ACTIVE])->all(); $recipients = []; $tours = Games::getNumberOfGamesPerTour($tournament); foreach ($candidates as $one) { if (Forecasts::getUserForecastTour($one['id_user'], $tournament, $tours)[$tour] != '2' && Reminders::ifEligible($tournament, $tour, $one['id_user'])) { $recipients[] = Users::find()->where(['id' => $one['id_user']])->one(); } } return $recipients; }
protected function addNewGames() { foreach ($this->gamesFromWeb as $gameWeb) { $newGame = new Games(); foreach ($gameWeb as $k => $attribute) { $newGame->{$k} = $attribute; } if (!Games::find()->where(['tour' => $newGame->tour])->andWhere(['id_team_home' => $newGame->id_team_home])->andWhere(['id_team_guest' => $newGame->id_team_guest])->exists()) { $newGame->save(false); } } }
public static function getForecastedStandings($id_tournament, $id_user) { //getting list of games for the tournament $games = Games::getGamesForTournament($id_tournament); $gameIDs = array_map(function ($item) { return $item->id_game; }, $games); //getting forecasts for the user for the tournament $forecasts = Forecasts::find()->where(['id_game' => $gameIDs, 'id_user' => $id_user])->indexBy('id_game')->asArray()->all(); //if there's a forecast for the game -> put forecast score as a game score + recalculating points foreach ($games as &$game) { if (isset($forecasts[$game->id_game])) { $game->score_home = $forecasts[$game->id_game]['fscore_home']; $game->score_guest = $forecasts[$game->id_game]['fscore_guest']; $game->getGamePoints(); } } $games = ArrayHelper::toArray($games); $teams = array_unique(array_merge(array_map(function ($value) { return $value['id_team_home']; }, $games), array_map(function ($value) { return $value['id_team_guest']; }, $games))); $teamObjects = TeamTournaments::find()->where(['id' => $teams])->joinWith('idTeam')->indexBy('id')->all(); $result = array_map(function ($item) use($games, $teamObjects) { $row['pts'] = 0; $row['participant'] = $item; $row['id'] = $item; $row['team_logo'] = $teamObjects[$item]->idTeam->team_logo; $row['team_name'] = $teamObjects[$item]->idTeam->team_name; $row['games_played'] = 0; foreach ($games as $game) { if ($game['id_team_home'] == $item) { $row['pts'] += $game['points_home']; if (isset($game['points_home'])) { $row['games_played'] += 1; } } if ($game['id_team_guest'] == $item) { $row['pts'] += $game['points_guest']; if (isset($game['points_guest'])) { $row['games_played'] += 1; } } } return $row; }, $teams); usort($result, function ($a, $b) { return $b['pts'] - $a['pts']; }); return $result; }
private static function sendReminder($tour, $tournament, $users) { $subject = "Напоминание: сделайте прогноз на матчи {$tour} тура турнира " . Tournaments::findOne($tournament)->tournament_name; $firstGameStarts = date('d-m-Y в H:i', ArrayHelper::getValue(Result::find()->select(['min(dtime) as dtime'])->where(['id_tournament' => $tournament, 'tour' => $tour])->all()[0], 'dtime')); $tours = Games::getNumberOfGamesPerTour($tournament); foreach ($users as $user) { if (Forecasts::getUserForecastTour($user->id, $tournament, $tours)[$tour] == 0) { $description = "Вы не сделали прогноз на матчи {$tour} тура турнира " . Tournaments::findOne($tournament)->tournament_name . ". Поторопитесь, первая игра тура начинается <strong>{$firstGameStarts}</strong>"; } else { $description = "Вы сделали прогноз не на все матчи: {$tour} тура турнира " . Tournaments::findOne($tournament)->tournament_name . ". Поторопитесь, первая игра тура начинается {$firstGameStarts}"; } $content = new ArrayDataProvider(['allModels' => Forecasts::getTourUserForecastStatus($tour, $tournament, $user->id), 'sort' => false, 'pagination' => false]); $messages[] = Yii::$app->mailer->compose('reminder', ['content' => $content, 'description' => $description, 'user' => $user])->setFrom([Yii::$app->params['adminEmail'] => 'Sportforecast'])->setTo($user->email)->setSubject($subject); //adding a record to the DB $reminder = self::getReminder($user->id, $tournament, $tour); $reminder->save(); } if (!empty($messages)) { Yii::$app->mailer->sendMultiple($messages); } return true; }
<div class="form-group col-xs-12"> <?php echo Html::submitButton('Выбрать', ['class' => 'btn btn-primary']); ?> </div> <?php ActiveForm::end(); ?> <?php $count = 0; ?> <?php $unfinishedTours = Games::listOfUnfinishedTours($tournament->id_tournament); foreach ($tourGames as $tour => $games) { ?> <div class="col-xs-12 col-sm-10 col-lg-6"> <?php if (!in_array($tour, $unfinishedTours)) { ?> <?php echo GridView::widget(['dataProvider' => $tourGames[$tour], 'responsive' => false, 'hover' => true, 'showPageSummary' => true, 'responsiveWrap' => false, 'export' => false, 'bordered' => false, 'showHeader' => false, 'caption' => "Тур {$tour}", 'summary' => '', 'columns' => [['attribute' => 'date_time_game', 'content' => function ($model) { return '<strong>' . date('d.m.y H:i', $model['date_time_game']) . '</strong>'; }, 'contentOptions' => ['class' => 'reduceDateFont'], 'options' => ['class' => 'col-xs-1'], 'hAlign' => 'center', 'vAlign' => 'middle'], ['content' => function ($model) { return "<row>" . "<div class = 'text-right col-xs-4'>" . $model['idTeamHome']['idTeam']['team_name'] . " " . "</div>" . "<div class = 'text-center col-xs-4'>" . "<strong>" . $model['score_home'] . " - " . $model['score_guest'] . "</strong>" . "</div>" . "<div class = 'text-left col-xs-4'>" . " " . $model['idTeamGuest']['idTeam']['team_name'] . "</div>" . "</row>" . "<div class='clearfix visible-xs-block visible-sm-block visible-md-block visible-lg-block'></div>" . "<row>" . "<div class = 'col-xs-4 col-xs-offset-4 col-sm-2 col-sm-offset-5 text-center'>" . Html::tag('div', isset($model['f_id']) ? $model['fscore_home'] . ' - ' . $model['fscore_guest'] : " - ", ['class' => !isset($model['f_id']) ? '' : ($model['fpoints'] == 0 ? 'bg-danger' : ($model['fpoints'] == 1 ? 'bg-info' : ($model['fpoints'] == 3 ? 'bg-success' : ($model['fpoints'] == 2 ? 'bg-warning' : ''))))]) . "</div>" . "<div class = 'col-xs-4 col-sm-2 col-sm-offset-3 text-right'>" . Html::tag('span', isset($model['f_id']) ? "Очки: " . $model['fpoints'] : '', []) . "</div>" . "</row>"; }, 'options' => ['class' => 'col-xs-11'], 'attribute' => 'fpoints', 'pageSummary' => function ($summary, $data, $widget) { return "<div class = 'row'>" . "<div class = 'col-xs-10'>" . "<p class = 'pull-left'>Всего очков в туре:</p>" . "</div>" . "<div class = 'col-xs-2'>" . "<p class = 'pull-left'>{$summary}</p>" . "</div>" . "</div>"; }, 'hAlign' => 'right', 'vAlign' => 'middle']]]); ?>
/** * Finds the games model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return games the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Games::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } }
/** * @return \yii\db\ActiveQuery */ public function getIdGame() { return $this->hasOne(Games::className(), ['id_game' => 'id_game']); }
/** * @param $file * @return mixed */ public static function uploadExcel($file) { $excel = PHPExcel_IOFactory::load($file); $workSheet = $excel->getActiveSheet(); $success = 0; $failure = ''; foreach ($workSheet->getRowIterator(2) as $row) { $cellIterator = $row->getCellIterator(); $cellIterator->setIterateOnlyExistingCells(false); foreach ($cellIterator as $cell) { $cellData[] = $cell->getValue(); } if (isset($cellData[0]) && isset($cellData[1])) { $game = new Games(); $game->id_team_home = $cellData[0]; $game->id_team_guest = $cellData[1]; $game->tour = $cellData[2]; //getting time difference between local place and greenwich to enable correct time offset with PHPExcel $tz = new \DateTimeZone(date_default_timezone_get()); $d = new \DateTime("now"); $offset = $tz->getOffset($d); $game->date_time_game = \PHPExcel_Shared_date::ExcelToPHP($cellData[3]) - $offset; $game->score_home = $cellData[4]; $game->score_guest = $cellData[5]; if ($game->save()) { $success += 1; } else { $failure .= "При загрузке игры {$game->competitors} произошла ошибка " . $game->getFirstError('id_team_home') . "<br>"; } } unset($cellData); } if (empty($failure)) { $return['success'] = "Все {$success} записей успешно загружены"; } else { $return['failure'] = $failure; } $excel->disconnectWorksheets(); unset($excel); return $return; }
/** * Finds games with empty points but with not empty score * @return int */ public function actionGetNull() { $tournaments = Tournaments::getAutoprocessTournaments(); $games = []; foreach ($tournaments as $one) { $teamTournament = TeamTournaments::find()->where(['id_tournament' => $one->id_tournament])->all(); //getting Participant IDs for the tournament $teamIDs = ArrayHelper::getColumn($teamTournament, 'id'); $games = ArrayHelper::merge($games, Games::find()->where(['or', ['in', 'id_team_home', $teamIDs], ['in', 'id_team_guest', $teamIDs]])->andWhere(['and', ['or', ['not', ['score_home' => null]], ['not', ['score_guest' => null]]], ['or', ['points_home' => null], ['points_guest' => null]]])->all()); } if (!empty($games)) { $this->getErrorMessage($games); } else { Yii::info('No games with score but with no points', 'console'); } return 0; }
/** * @return \yii\db\ActiveQuery */ public function getGames() { return $this->hasMany(Games::className(), ['id_team_home' => 'id']); }