/** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = WeatherAlert::find(); $query->joinWith(['userReadAlerts.weatherAlert']); $dataProvider = new ActiveDataProvider(['query' => $query]); $dataProvider->setSort(['attributes' => ['id', 'magnitude', 'event', 'date', 'severity', 'stormName' => ['asc' => ['id' => SORT_ASC], 'desc' => ['id' => SORT_DESC], 'label' => 'Storm Name', 'default' => SORT_ASC]]]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to any records when validation fails // $query->where('0=1'); return $dataProvider; } $query->andFilterWhere(['id' => $this->id, 'magnitude' => $this->magnitude, 'identifier' => $this->identifier]); $query->andFilterWhere(['like', 'severity', $this->severity]); $query->andFilterWhere(['=', 'WeatherAlert.type', $this->type]); $query->andFilterWhere(['=', 'WeatherAlert.event', $this->event]); $query->andFilterWhere(['=', 'WeatherAlert.status', WeatherAlert::STATUS_ACTUAL]); // var_dump(time() - Yii::$app->params['timePeriodForRecentAlerts']*3600);die; $timePeriodForAlert = $this->type == 0 ? Yii::$app->params['timePeriodForRecentPreAlerts'] : Yii::$app->params['timePeriodForRecentPostAlerts']; // if ($this->type == 1) { // var_dump($timePeriodForAlert);die; // } $query->andFilterWhere(['>', 'WeatherAlert.date', time() - $timePeriodForAlert * 3600]); // $query->addSelect('COUNT(UserReadAlerts.User_id)'); // $query->andFilterWhere(['=', 'UserReadAlerts.User_id', Yii::$app->user->id]); // $query->andFilterWhere(['=', 'UserReadAlerts.WeatherAlert_id', $this->id]); // if (!Yii::$app->request->isPjax) { // // } $query->orderBy(['WeatherAlert.date' => SORT_DESC]); // $query->orderBy(['UserReadAlerts.User_id'=>'DESC']); $query->groupBy(['WeatherAlert.id']); return $dataProvider; }
public function actionAlerts() { $alertsModel = new models\WeatherAlert(); $searchModelPre = new models\WeatherAlertSearch(); $searchModelPre->type = 0; $dataProviderPre = $searchModelPre->search(ArrayHelper::merge(Yii::$app->request->queryParams, ['type' => 0])); $searchModelPost = new models\WeatherAlertSearch(); $searchModelPost->type = 1; $dataProviderPost = $searchModelPost->search(ArrayHelper::merge(Yii::$app->request->queryParams, ['type' => 1])); $unreadedPre = $alertsModel->getUnreadAlertsCount(0); $unreadedPost = $alertsModel->getUnreadAlertsCount(1); // // if (Yii::$app->request->isPjax) { // return $this->renderAjax('_pre_storm', [ // 'searchModelPre' => $searchModelPre, // 'dataProviderPre' => $dataProviderPre, // 'searchModelPost' => $searchModelPost, // 'dataProviderPost' => $dataProviderPost, // ]); // } return $this->render('alerts', ['searchModelPre' => $searchModelPre, 'dataProviderPre' => $dataProviderPre, 'searchModelPost' => $searchModelPost, 'dataProviderPost' => $dataProviderPost, 'unreadedPre' => $unreadedPre, 'unreadedPost' => $unreadedPost]); }
public function getUnreadAlertsCount($type) { $query = new Query(); $ids = []; $timePeriodForAlert = $type == 0 ? Yii::$app->params['timePeriodForRecentPreAlerts'] : Yii::$app->params['timePeriodForRecentPostAlerts']; $allAlerts = WeatherAlert::find()->where(['type' => $type, 'status' => WeatherAlert::STATUS_ACTUAL])->andFilterWhere(['>', 'date', time() - $timePeriodForAlert * 3600])->all(); foreach ($allAlerts as $alert) { $ids[] = $alert->id; } // var_dump($ids);die; // $readedAlerts = UserReadAlerts::find()->andFilterWhere(['in','WeatherAlert_id',implode(',',$ids)])->all(); $readedAlerts = UserReadAlerts::find()->where(['WeatherAlert_id' => $ids, 'User_id' => Yii::$app->user->id])->count(); return count($ids) - (int) $readedAlerts; }
public function actionExportcsv() { $post = Yii::$app->request->post(); $get = Yii::$app->request->get(); if (Yii::$app->request->isAjax) { if (isset($post['alertId'])) { $alertData = $this->getAlertIdInformation($post['alertId']); } $filename = date('Ymd_His') . '_' . $alertData->id . '.csv'; $output = fopen(Yii::$app->basePath . '/web/' . $this->tmpPath . '/' . $filename, 'w'); $headerArray = array('AlertID', 'AlertDate', 'AlertMagnitude', 'AlertSeverity', 'Event', 'PropertyID', 'PropertyStreetAddress', 'PropertyCity', 'PropertyState', 'PropertyZipcode', 'PropertyClient', 'PropertyLatitude', 'PropertyLongitude', 'PropertyStatus'); fputcsv($output, $headerArray); foreach ($this->_affectedProperties as $property) { $csvLine = []; $csvLine[] = $alertData->id; $csvLine[] = date('M d, Y H:i', $alertData->date); $csvLine[] = $alertData->magnitude; $csvLine[] = $alertData->severity; $csvLine[] = \app\models\WeatherAlert::getAlertTypeByEventId($alertData->event); $csvLine[] = $property->id; $csvLine[] = $property->streetAddress; $csvLine[] = $property->city; $csvLine[] = $property->state; $csvLine[] = $property->zipcode; $csvLine[] = $property->client; $csvLine[] = $property->latitude; $csvLine[] = $property->longitude; $csvLine[] = $property->status; fputcsv($output, $csvLine); $csvInlineOutput[] = $csvLine; } echo json_encode(['file' => $filename]); } else { if (isset($get['file']) && file_exists(Yii::$app->basePath . '/web/' . $this->tmpPath . '/' . $get['file'])) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . basename($get['file'])); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize(Yii::$app->basePath . '/web/' . $this->tmpPath . '/' . $get['file'])); readfile(Yii::$app->basePath . '/web/' . $this->tmpPath . '/' . $get['file']); Yii::$app->end(); } } }
/** * @return \yii\db\ActiveQuery */ public function getWeatherAlert() { return $this->hasOne(WeatherAlert::className(), ['id' => 'WeatherAlert_id']); }
public function insertNewLSRRecords($records) { foreach ($records['alerts'] as $record) { if (in_array(strtolower($record['event']), $this->filterEventType)) { $weatherAlertsModel = new models\WeatherAlert(); switch (strtolower($record['event'])) { case 'hurricane': $weatherAlertsModel->event = 0; break; case 'tornado': $weatherAlertsModel->event = 1; break; default: $weatherAlertsModel->event = 2; break; } $weatherAlertsModel->status = models\WeatherAlert::STATUS_ACTUAL; $weatherAlertsModel->type = 1; $weatherAlertsModel->magnitude = $record['magnitude']; $weatherAlertsModel->magnitudeUnit = $record['magnitudeUnit']; //We need to display date in needed format $newTime = substr_replace($record['time'], ':', 2, 0); // $newDate = str_replace('/', '-', $record['date']); $dateforConvertionArray = explode('/', $record['date']); $finalDateTime = $dateforConvertionArray[2] . '-' . $dateforConvertionArray[0] . '-' . $dateforConvertionArray[1] . 'T' . date("H:i:s", strtotime($newTime)); $weatherAlertsModel->date = DateTimeHelper::createUnixtimeFromDate($finalDateTime); $weatherAlertsModel->save(); $weatherAlertAreaModel = new models\WeatherAlertArea(); $weatherAlertAreaModel->WeatherAlert_id = $weatherAlertsModel->id; $weatherAlertAreaModel->save(); $areaDefinitionModel = new models\AreaDefinition(); $areaDefinitionModel->WeatherAlertArea_id = $weatherAlertAreaModel->id; $areaDefinitionModel->latitude = $record['latitude']; $areaDefinitionModel->longitude = $record['longitude']; $areaDefinitionModel->save(); $this->insertedAlerts++; $this->consoleLog('One alert entry added (ID: ' . $weatherAlertsModel->id . ')'); } else { $this->ignoredAlerts++; $this->consoleLog('One alert entry skipped (Filtered by event type)'); } } }
public function actionExportrest() { $startTime = time(); $this->_writeLogLine('Start Date/Time - ' . date('Y-m-d\\TH:i:s', $startTime)); header('Content-type: application/json'); try { $data = file_get_contents("php://input"); $data = json_decode($data); if ($data && isset($data->alertId)) { $this->format = isset($data->format) && $data->format ? $data->format : $this->format; $this->tmpPath = isset($data->tmpPath) && $data->tmpPath ? $data->tmpPath : $this->tmpPath; if (!is_dir(Yii::$app->basePath . '/' . $this->tmpPath . '/')) { throw new Exception('Temp directory path is invalid.'); } $alertData = models\WeatherAlert::findOne($data->alertId); if (!$alertData) { throw new Exception('Record with alertId=' . $data->alertId . ' not found in our database'); } $areaForAlertData = models\AreaDefinition::findAll(['WeatherAlertArea_id' => $alertData->id]); $alertCircle = new \stdClass(); $alertPolygonCoordinates = []; foreach ($areaForAlertData as $coordinates) { if ($coordinates->radius) { $alertCircle->radius = $coordinates->radius; //Radius can be only one record $alertCircle->centerLat = $coordinates->latitude; //Radius can be only one record $alertCircle->centerLon = $coordinates->longitude; //Radius can be only one record } else { $alertPolygonCoordinates[] = $coordinates->latitude . ' ' . $coordinates->longitude; } } // var_dump($alertPolygonCoordinates);die; $propertiesList = models\NRESProperty::find()->all(); $pointChecker = new PointInPolygon(); $this->_affectedProperties = []; foreach ($propertiesList as $property) { $isPropertyAffectedByAlert = false; if (isset($alertCircle->radius)) { //Checking circle coordinates if ($pointChecker->pointInsideCircle($alertCircle->centerLat, $alertCircle->centerLon, $alertCircle->radius, $property->latitude, $property->longitude)) { $isPropertyAffectedByAlert = true; } } if (!empty($alertPolygonCoordinates)) { if ($pointChecker->pointInPolygon($property->latitude . ' ' . $property->longitude, $alertPolygonCoordinates) !== "outside") { $isPropertyAffectedByAlert = true; } } if ($isPropertyAffectedByAlert) { $this->_affectedProperties[] = $property; } } if (!$this->_affectedProperties) { throw new Exception("There are no properties affected by this Alert (" . $alertData->id . ")"); } switch ($this->format) { case 'csv': $generatedFileURL = $this->generateCSV($alertData); break; case 'pdf': $generatedFileURL = $this->generatePDF($alertData); break; default: throw new Exception("Invalid format of output file is defined"); } $this->_writeLogLine('Affected Properties - ' . count($this->_affectedProperties)); $this->_writeLogLine('Generated File URL - ' . $generatedFileURL); $this->_writeLogLine('End Date/Time - ' . date('Y-m-d\\TH:i:s', time())); //Now we need to check if some properties are located inside this coordinates $responce = ['fileUrl' => $generatedFileURL, 'affectedProperties' => count($this->_affectedProperties)]; header('Content-type: application/json'); echo json_encode($responce); // if ($this->_debug == 'true') { // // echo json_encode(array_merge(['start'=>date('Y-m-d\TH:i:s',$startTime),'end'=>date('Y-m-d\TH:i:s',$endTime)],(array)$atomGeneralInformation)); // } else { // echo json_encode(['result'=>'Job Done']); // } } else { throw new Exception('Missing alertId parameter'); } } catch (\Exception $e) { echo json_encode(['error' => $e->getMessage()]); $this->_writeLogLine($e->getMessage()); } Yii::$app->end(); }
private function _getCapAreaInformationInDatabse($entry) { try { $atomGeneralInformation = Yii::$app->CAPParser->getCapContent($entry[0]); //Simple way to create object instad of XML object $atomGeneralInformation = json_decode(json_encode($atomGeneralInformation)); $polygonInfo = isset($atomGeneralInformation->info->area->polygon) ? (array) $atomGeneralInformation->info->area->polygon : NULL; $circleInfo = isset($atomGeneralInformation->info->area->circle) ? (array) $atomGeneralInformation->info->area->circle : NULL; if ((!empty($polygonInfo) || !empty($circleInfo)) && $atomGeneralInformation->status == 'Actual' && ($atomGeneralInformation->msgType == 'Alert' || $atomGeneralInformation->msgType == 'Update')) { //We don't need to use such information without geo info $returnArray = ['identifier' => $atomGeneralInformation->identifier, 'polygon' => $polygonInfo, 'circle' => $circleInfo, 'date' => $atomGeneralInformation->sent, 'event' => $atomGeneralInformation->info->event, 'severity' => $atomGeneralInformation->info->severity, 'type' => 0, 'msgType' => models\WeatherAlert::assignMsgType($atomGeneralInformation->msgType)]; $returnArray['status'] = models\WeatherAlert::STATUS_ACTUAL; if (!in_array(strtolower($returnArray['event']), Yii::$app->params['AtomFeedParser']['filter'])) { $this->skippedAlertsCount++; $this->consoleLog('One alert entry skipped (Filtered by event type)'); return false; } if ($returnArray['msgType'] == models\WeatherAlert::MSG_TYPE_UPDATED) { if (isset($atomGeneralInformation->references)) { $referencesArray = explode(',', $atomGeneralInformation->references); $returnArray['updates'] = trim($referencesArray[1]); // Logic for updated references } } switch (strtolower($returnArray['event'])) { case 'hurricane': $returnArray['event'] = 0; break; case 'tornado': $returnArray['event'] = 1; break; default: $returnArray['event'] = 2; break; } return $returnArray; } else { $this->skippedAlertsCount++; $this->consoleLog('One alert entry skipped (It has missed information)'); } } catch (\Exception $e) { $this->consoleLog('Process ERROR - ' . $e->getMessage()); // echo json_encode(['error'=>$e->getMessage()]); } return false; }
/** * @return \yii\db\ActiveQuery */ public function getWeatherAlert() { return $this->hasOne(WeatherAlert::className(), ['id' => 'WeatherAlert_id'])->from(['WeatherAlertAlias' => WeatherAlert::tableName()]); }
public function generatePreStorm() { if ((int) $this->countPreStorm) { for ($i = 0; $i < (int) $this->countPreStorm; $i++) { $preStormModel = new WeatherAlert(); $preStormModel->type = 0; //Pre-storm $preStormModel->status = WeatherAlert::STATUS_ACTUAL; $preStormModel->date = time(); $preStormModel->event = rand(0, 1); $preStormModel->msgType = 1; $preStormModel->severity = 'Moderate'; $preStormModel->save(); $weatherAlertArea = new WeatherAlertArea(); $weatherAlertArea->WeatherAlert_id = $preStormModel->id; $weatherAlertArea->save(); $this->_generateCoordinates($weatherAlertArea->id, false, rand(3, 6)); } } if ((int) $this->countPostStorm) { for ($i = 0; $i < (int) $this->countPostStorm; $i++) { $preStormModel = new WeatherAlert(); $preStormModel->type = 1; //Pre-storm $preStormModel->status = WeatherAlert::STATUS_ACTUAL; $preStormModel->date = time(); $preStormModel->event = rand(0, 1); $preStormModel->msgType = 1; $preStormModel->magnitude = rand(1, 10); $preStormModel->save(); $weatherAlertArea = new WeatherAlertArea(); $weatherAlertArea->WeatherAlert_id = $preStormModel->id; $weatherAlertArea->save(); $this->_generateCoordinates($weatherAlertArea->id, true); } } if ((int) $this->countStormPath) { $this->isStormPath = true; for ($i = 0; $i < (int) $this->countStormPath; $i++) { //generate pre-storm path $stormCount = rand(3, 6); $identifierOfUpdates = null; $event = rand(0, 1); for ($j = 0; $j < $stormCount; $j++) { $isLast = $stormCount - 1 - $j ? false : true; $preStormModel = new WeatherAlert(); $preStormModel->status = WeatherAlert::STATUS_UPDATED; $preStormModel->type = 0; //Pre-storm if ($isLast) { $preStormModel->status = WeatherAlert::STATUS_ACTUAL; } $preStormModel->date = time(); $preStormModel->event = $event; $preStormModel->identifier = 'identifier' . $j; $preStormModel->severity = 'Moderate'; $preStormModel->msgType = 1; $preStormModel->updates = $identifierOfUpdates; $preStormModel->save(); $identifierOfUpdates = $preStormModel->identifier; $weatherAlertArea = new WeatherAlertArea(); $weatherAlertArea->WeatherAlert_id = $preStormModel->id; $weatherAlertArea->save(); $this->_generateCoordinates($weatherAlertArea->id, false); } } } }
<h1>Alert Information</h1> <table width="100%" border="1"> <tr> <th>ID</th> <th>Date</th> <th>EventID</th> <th>Magnitude</th> <th>Severity</th> </tr> <tr> <td><?= $alert->id ?></td> <td><?= date('M d, Y H:i',$alert->date) ?></td> <td><?= \app\models\WeatherAlert::getAlertTypeByEventId($alert->event) ?></td> <td><?= $alert->magnitude ?></td> <td><?= $alert->severity ?></td> </tr> </table> <h1>Affected Properties Information</h1> <table width="100%" border="1"> <tr> <th>ID</th> <th>Street Address</th> <th>City</th> <th>State</th> <th>Zip Code</th> <th>Client</th> <th>Latitude</th> <th>Longitude</th>