/** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = NRESProperty::find(); $dataProvider = new ActiveDataProvider(['query' => $query]); $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, 'latitude' => $this->latitude, 'longitude' => $this->longitude, 'status' => $this->status]); $query->andFilterWhere(['like', 'streetAddress', $this->streetAddress])->andFilterWhere(['like', 'name', $this->name])->andFilterWhere(['like', 'city', $this->city])->andFilterWhere(['like', 'state', $this->state])->andFilterWhere(['like', 'zipcode', $this->zipcode])->andFilterWhere(['=', 'client', $this->client]); if (isset($params['ids'])) { $query->andWhere('id IN (' . $params['ids'] . ')'); } if (isset($params['orderBy'])) { $query->orderBy([$params['orderBy'] => SORT_ASC]); } return $dataProvider; }
private function getAlertIdInformation($alertId) { try { if ($alertId) { $alertData = models\WeatherAlert::findOne($alertId); if (!$alertData) { throw new Exception('Record with alertId=' . $alertId . ' not found in our database'); } $WeatherAlertArea = models\WeatherAlertArea::find()->where(['WeatherAlert_id' => $alertData->id])->one(); $areaForAlertData = models\AreaDefinition::findAll(['WeatherAlertArea_id' => $WeatherAlertArea->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()->where(['status' => models\NRESProperty::STATUS_ACTIVE])->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. Nothing to export"); } return $alertData; } else { throw new Exception('Please choose Alert that you want to export'); } } catch (\Exception $e) { echo json_encode(['error' => $e->getMessage()]); } Yii::$app->end(); }
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 _createAffectedProperties($weatherAlertAreaId) { $areaDefinition = AreaDefinition::find()->where(['WeatherAlertArea_id' => $weatherAlertAreaId])->all(); $pointChecker = new PointInPolygon(); if (count($areaDefinition) && count($areaDefinition) == 1) { $needToInsertProperties = (int) $this->countPostAffected; $alertCircle = $areaDefinition[0]; while ($needToInsertProperties) { $property = new \stdClass(); $property->latitude = $alertCircle->latitude + $this->_generateRand(false, rand(300, 1000)); $property->longitude = $alertCircle->longitude + $this->_generateRand(false, rand(300, 1000)); if ($pointChecker->pointInsideCircle($alertCircle->latitude, $alertCircle->longitude, $alertCircle->radius, $property->latitude, $property->longitude)) { //insert property $newProperty = new NRESProperty(); $newProperty->attributes = (array) $property; $newProperty->name = 'Generated'; $newProperty->zipcode = '12345-6789'; $newProperty->city = 'Test'; $newProperty->state = 'CA'; $newProperty->streetAddress = 'Test'; $newProperty->client = 'Test'; $newProperty->status = 2; $newProperty->save(); if ($newProperty->getErrors()) { var_dump($newProperty->getErrors()); die; } $needToInsertProperties--; } } } else { $allCoordinates = []; $needToInsertProperties = $this->isStormPath ? $this->countAffectedInStormPath : (int) $this->countPreAffected; foreach ($areaDefinition as $point) { $allCoordinates[] = $point->latitude . ' ' . $point->longitude; } while ($needToInsertProperties) { $propertyToGet = rand(0, count($areaDefinition) - 1); $property = new \stdClass(); $property->latitude = $areaDefinition[$propertyToGet]->latitude + $this->_generateRand(); $property->longitude = $areaDefinition[$propertyToGet]->longitude + $this->_generateRand(); if ($pointChecker->pointInPolygon($property->latitude . ' ' . $property->longitude, $allCoordinates) !== "outside") { //insert property $newProperty = new NRESProperty(); $newProperty->attributes = (array) $property; $newProperty->name = 'Generated'; $newProperty->zipcode = '12345-6789'; $newProperty->city = 'Test'; $newProperty->state = 'CA'; $newProperty->streetAddress = 'Test'; $newProperty->client = 'Test'; $newProperty->status = 2; $newProperty->save(); $needToInsertProperties--; } } } }
public static function getStatusAlias() { $filter = NRESProperty::alias('status'); return $filter; }
$this->title = 'Properties'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="actions"> <div class="container"> <?= Html::a(Yii::t('user', 'Add New Properties...'), ['/nresproperty/create'], ['data-method' => 'post','id'=>'addProperty','class'=>'btn btn-blue']) ?> </div> </div> <div class="container"> <div class="filters"> <?php $form = ActiveForm::begin([ 'action' => ['index'], 'method' => 'get', ]); ?> <?php echo $form->field($searchModel, 'client')->dropDownList(ArrayHelper::map(NRESProperty::find()->orderBy('client ASC')->all(), 'client', 'client') ,['class'=>'','onchange'=>'this.form.submit()','prompt'=>'Client: All'])->label(false) ?> <?php ActiveForm::end(); ?> </div> <div class="data-index"> <?php Pjax::begin(['id' => 'properties']) ?> <?= GridView::widget([ 'dataProvider' => $dataProvider, 'layout'=>"{items}\n{pager}", 'tableOptions'=>['class'=>'table table-striped table-hover table-normal'], 'pager' => [ 'firstPageLabel' => 'First',
/** * Finds the NRESProperty model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return NRESProperty the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = NRESProperty::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } }
<?= $form->field($model, 'state')->textInput(['maxlength' => 45]) ?> </div> <div class="form-group"> <?= $form->field($model, 'zipcode')->textInput(['maxlength' => 45]) ?> </div> <div class="form-group"> <?= $form->field($model, 'client')->textInput(['maxlength' => 45]) ?> </div> <div class="form-group"> <?= $form->field($model, 'latitude')->textInput(['disabled'=>true]) ?> </div> <div class="form-group"> <?= $form->field($model, 'longitude')->textInput(['disabled'=>true]) ?> </div> <div class="form-group"> <?= $form->field($model, 'status')->dropDownList(\app\models\NRESProperty::getStatusAlias()) ?> </div> <?= $form->field($model, 'addNew')->hiddenInput() ?> <sup class="req">*</sup> Required fields. <div class="form-group"> <div class="modal-footer"> <div class="text-center"> <?php if ($model->isNewRecord) echo Html::submitButton('Save & Add Another', ['class' => 'btn btn-sm btn-gray','id'=>'property-save-add-another']) ?> <?= Html::submitButton($model->isNewRecord ? 'Save' : 'Update', ['class' => 'btn btn-sm btn-blue','id'=>'property-save-one']) ?> <?= Html::button(Yii::t('user', 'Cancel'), ['class' => 'btn btn-sm btn-link', 'tabindex' => '3','onclick'=>'$(\'#modal\').modal(\'hide\')']) ?> <div class="small-ajax-loader"></div>
public function processCsv($file) { ini_set('auto_detect_line_endings', true); try { $uploadedFile = Yii::$app->basePath . '/uploads/' . $file->baseName . '.' . $file->extension; $fileSize = $file->size; $delimiter = ","; $propertiesFromCSV = []; if (($handle = fopen($uploadedFile, 'r')) !== FALSE) { $csvFirstLine = fgetcsv($handle, 0, $delimiter); if (!$csvFirstLine) { $this->_log(1, 'Wrong CSV file format (can\'t read header information)'); echo json_encode($this->log); Yii::$app->end(); } if (count($csvFirstLine) != 7) { $this->_log(1, 'Wrong CSV file format (count of headers should be equal 7)'); echo json_encode($this->log); Yii::$app->end(); } $lineNumber = 2; while (($row = fgetcsv($handle, $fileSize, $delimiter)) !== FALSE) { $newProperty = new \stdClass(); $newProperty->line = $lineNumber; foreach ($row as $key => $element) { $newProperty->{$csvFirstLine}[$key] = $element; } $propertiesFromCSV[] = $newProperty; $lineNumber++; } } //Now we need to identify lat and lon for each record $googleAPIHelper = new GoogleAPIHelper(); foreach ($propertiesFromCSV as $property) { if (!isset($property->streetAddress) || !isset($property->city) || !isset($property->state) || !isset($property->zipcode)) { throw new Exception('CSV has missing parameters (Check headers line)'); } //Special check for our QA $propertyCheck = new NRESProperty(); $propertyCheck->attributes = (array) $property; $propertyCheck->status = NRESProperty::STATUS_ACTIVE; if (!$propertyCheck->validate()) { $modelValidationErrors = []; foreach ($propertyCheck->getErrors() as $err) { $modelValidationErrors[] = $err[0]; } $this->_log($property->line, "ERROR, NOT inserted (" . implode(',', $modelValidationErrors) . ")"); continue; } $coordinates = $googleAPIHelper->identifyLatLon([$property->streetAddress, $property->city, $property->state, $property->zipcode]); if ($coordinates) { $property->latitude = $coordinates->lat; $property->longitude = $coordinates->lng; if ($property->id) { //It's a record that we already have in our database $propertyFromTheDatabase = new NRESProperty(); $recordInDb = $propertyFromTheDatabase->findOne($property->id); if ($recordInDb) { $recordInDb->attributes = (array) $property; if ($recordInDb->save()) { $this->_log($property->line, "SUCCESS, Updated in the database, ID #" . $recordInDb->id); } else { $errorArray = []; foreach ($recordInDb->getErrors() as $error) { $errorArray[] = $error[0]; } $this->_log($property->line, "ERROR, NOT updated, ID #" . $recordInDb->id . ", Errors: (" . implode(',', $errorArray) . ")"); } } else { $this->_log($property->line, "ERROR, Record with ID #" . $property->id . ", does not exist."); } } else { //absolutelly new one $propertyNewModel = new NRESProperty(); $propertyNewModel->attributes = (array) $property; $propertyNewModel->status = NRESProperty::STATUS_ACTIVE; unset($propertyNewModel->id); if ($propertyNewModel->save()) { $this->_log($property->line, "SUCCESS, Added in the database, ID #" . $propertyNewModel->id); } else { $errorArray = []; foreach ($propertyNewModel->getErrors() as $error) { $errorArray[] = $error[0]; } $this->_log($property->line, "ERROR, NOT inserted (" . implode(',', $errorArray) . ")"); } } } else { // We need to reject such properties $this->_log($property->line, "ERROR, Can't detect geolocation information about provided address"); } } // var_dump($this->log);die; echo json_encode((object) $this->log); // die; } catch (Exception $e) { $this->_log(0, $e->getMessage()); echo json_encode((object) $this->log); } Yii::$app->end(); }