diff --git a/backend/controllers/CrossingUploadController.php b/backend/controllers/CrossingUploadController.php index ebc5b36..f6b6167 100755 --- a/backend/controllers/CrossingUploadController.php +++ b/backend/controllers/CrossingUploadController.php @@ -8,20 +8,16 @@ namespace backend\controllers; -use backend\components\base\BaseActiveRecord; use backend\components\base\BaseController; use common\components\CustomArrayHelper; -use common\components\CustomVarDamp; -use yii\base\ErrorException; -use yii\base\Model; use yii\data\ArrayDataProvider; -use yii\db\ActiveRecord; use yii\filters\VerbFilter; use yii\filters\AccessControl; use backend\models\UploadFileCrossingForm; use backend\models\DetailsCrosses; use yii\multiparser\DynamicFormHelper; use yii\web\UploadedFile; +use common\components\ModelArrayValidator; use \Yii; class CrossingUploadController extends BaseController @@ -141,11 +137,19 @@ class CrossingUploadController extends BaseController // запустим конвертер над над данными $data = $this->convertDataByConfiguration( $data, $configuration ); + // валидируем отпарсенные данные моделью в которую будем записывать $crosses_model = new DetailsCrosses(); + $model_validator = new ModelArrayValidator( $crosses_model ); + $data = $model_validator->validate( $data ); + $msg = $model_validator->getMassage(); + $type_msg = $model_validator->hasError() ? 'warning' : 'success'; + $model_validator->close(); + + $data = $this->reverseCrosses( $data ); if ( $crosses_model->ManualInsertWithIgnore( $data ) ) { - Yii::$app->session->setFlash('success', 'Файл кроссов успешно загружен'); + Yii::$app->session->setFlash( $type_msg, $msg ); // очистим кеш $this->cacheHandler( 2 ); @@ -200,20 +204,10 @@ class CrossingUploadController extends BaseController $basic_options = Yii::$app->multiparser->getConfiguration( 'csv', 'crosses' ); $options = array_merge_recursive( $options, $basic_options ); - // для доп массива обратных строк - $i = count( $data ) - 1; - $reverse_data = []; foreach ( $data as &$row ) { $row = Yii::$app->converter->convertByConfiguration( $row, $options['converter_conf'] ); - // нужно добавить обратную строку по кроссам - $reverse_data[ $i ]['ARTICLE'] = $row['CROSS_ARTICLE']; - $reverse_data[ $i ]['CROSS_ARTICLE'] = $row['ARTICLE']; - $reverse_data[ $i ]['BRAND'] = $row['CROSS_BRAND']; - $reverse_data[ $i ]['CROSS_BRAND'] = $row['BRAND']; - $i++; } - $data = array_merge( $data, $reverse_data ); return $data; } @@ -251,21 +245,22 @@ class CrossingUploadController extends BaseController } -// protected function validateModel( BaseActiveRecord $model, array $data ){ -// -// foreach ( $data as $row ) { -// // подготовим данные к валидации -// $validate_attr[$model->formName()] = $row; -// if( !$model->load( $validate_attr ) ){ -// // такой ситуации не должно быть, но на всякий случай -// throw new ErrorException('Незаполнены обязательные поля формы.'); -// } -// if ( !$model->validate( ) ) { -// $model->throwStringErrorException( key( $data ) ); -// }; -// } -// -// return true; -// -// } + protected function reverseCrosses ( $data ) + { + // для доп массива обратных строк + $i = count( $data ) - 1; + $reverse_data = []; + foreach ( $data as &$row ) { + // нужно добавить обратную строку по кроссам + $reverse_data[ $i ]['ARTICLE'] = $row['CROSS_ARTICLE']; + $reverse_data[ $i ]['CROSS_ARTICLE'] = $row['ARTICLE']; + $reverse_data[ $i ]['BRAND'] = $row['CROSS_BRAND']; + $reverse_data[ $i ]['CROSS_BRAND'] = $row['BRAND']; + $i++; + } + $data = array_merge( $data, $reverse_data ); + + return $data; + } + } \ No newline at end of file diff --git a/backend/controllers/RgGrupController.php b/backend/controllers/RgGrupController.php index 073256b..82fcbde 100755 --- a/backend/controllers/RgGrupController.php +++ b/backend/controllers/RgGrupController.php @@ -125,7 +125,7 @@ class RgGrupController extends BaseController } // провалидируем выбранные колонки - if ($model->validate()) { + if ( $model->validate() ) { // валидация успешна у нас есть соответсвие колонок, преобразуем в массив данное соответсвие для дальнейшей работы $arr = $model->toArray(); @@ -147,7 +147,7 @@ class RgGrupController extends BaseController $data = CustomArrayHelper::createAssocArray($data, $arr, 'attr_'); // в первой строке у нас заголовки - уберем - unset($data[0]); + unset( $data[0] ); // подготовим данные для записи в таблицу w_margins_groups $arr_values = []; $group = ''; diff --git a/backend/views/crossing-upload/index.php b/backend/views/crossing-upload/index.php index 4d1b1a0..1d07aaf 100755 --- a/backend/views/crossing-upload/index.php +++ b/backend/views/crossing-upload/index.php @@ -8,9 +8,6 @@ use yii\helpers\ArrayHelper;
['enctype' => 'multipart/form-data',],'action'=>['crossing-upload/result']]); - if ($msg = \Yii::$app->session->getFlash('success')) { // вернулись после успешной загрузки данного файла - echo Html::tag('h3', $msg ,['class'=>'bg-success']); - } ?>

Кросс файлы

@@ -22,7 +19,16 @@ use yii\helpers\ArrayHelper; 'btn btn-primary']) ?>
- + session->getFlash('success')) + { + echo Html::tag('p', $msg ,['class'=>'bg-success']); + } elseif ($msg = \Yii::$app->session->getFlash('warning')) + { + echo Html::tag('p', $msg, ['class' => 'bg-warning']); + } + ?> diff --git a/backend/views/currency/index.php b/backend/views/currency/index.php index e9aa22d..58a3bd7 100755 --- a/backend/views/currency/index.php +++ b/backend/views/currency/index.php @@ -27,7 +27,7 @@ $this->params['breadcrumbs'][] = $this->title; 'rate', 'timestamp', ['class' => 'yii\grid\ActionColumn', - 'template' => '{update}'], + 'template' => '{update}{delete}'], ], ]); ?> diff --git a/common/components/ModelArrayValidator.php b/common/components/ModelArrayValidator.php new file mode 100644 index 0000000..257691f --- /dev/null +++ b/common/components/ModelArrayValidator.php @@ -0,0 +1,127 @@ +model = $model; + } + + /** + * @return array + */ + public function getErrors() + { + return $this->arr_errors; + } + + /** + * @return mixed + */ + public function getValidData() + { + return $this->valid_data; + } + + /** + * @return string - сообщение на форму с результатми обработки + */ + public function getMassage () + { + $total_count = $this->total_rows; + $success_count = $this->total_rows - count($this->arr_errors); + $error_count = count($this->arr_errors); + + $msg = "Обработано - {$total_count} строк.
+ Успешно загрузились - {$success_count} строк.
+ Найдено строк с ошибками - {$error_count}.
"; + + foreach ($this->arr_errors as $row => $error) { + $msg .= "Ошибка в строке {$row}
+ Текст ошибки: {$error}
"; + } + + return $msg; + } + + /** + * @param $data + * @return array + * метод регистрирует ошибки, регистрирует "чистые данные" и возвращает их + */ + public function validate( $data ) + { + foreach ( $data as $row ) { + $this->total_rows++; + $validate_row[$this->model->formName()] = $row; + // clear previous loading + $this->clearModelAttributes(); + if ( $this->model->load( $validate_row ) && $this->model->validate() ) { + // everything OK, registred row to valid data + $this->valid_data[] = $row; + } else{ + // we have errors + $this->registredError( $this->total_rows ); + } + } + + return $this->valid_data; + } + + protected function registredError ($index) + { + $errors_str = ''; + foreach ($this->model->getErrors() as $error) { + $errors_str .= implode(array_values($error)); + } + + $this->arr_errors[$index] = $errors_str; + } + + + public function hasError () + { + return (bool) count($this->arr_errors); + } + + protected function clearModelAttributes() + { + $attributes = $this->model->safeAttributes(); + + foreach ( $attributes as $key => $value ) { + $this->model->$value = ''; + } + +} + + public function close(){ + + unset( $this->valid_data ); + unset( $this->arr_errors ); + unset( $this->model ); + + } +} \ No newline at end of file diff --git a/common/components/parsers/CustomConverter.php b/common/components/parsers/CustomConverter.php index 347ae9f..853f58a 100755 --- a/common/components/parsers/CustomConverter.php +++ b/common/components/parsers/CustomConverter.php @@ -25,15 +25,17 @@ class CustomConverter extends Converter $details_model = new Details(); // проверим все ли обязательные колонки были указаны пользователем - $details_model->load(['Details' => $row]); +// $details_model->load(['Details' => $row]); +// +// if (!$details_model->validate()) { +// $errors = ''; +// foreach ($details_model->errors as $key => $arr_errors) { +// $errors .= "Аттрибут $key - " . implode(' , ', $arr_errors); +// } +// throw new \ErrorException($errors); +// } + - if (!$details_model->validate()) { - $errors = ''; - foreach ($details_model->errors as $key => $arr_errors) { - $errors .= "Аттрибут $key - " . implode(' , ', $arr_errors); - } - throw new \ErrorException($errors); - } return $row; } @@ -53,7 +55,7 @@ class CustomConverter extends Converter return $row; } - public function ConvertToMultiply(array $row) + public function ConvertToMultiply( array $row ) { $PRICE = $row['PRICE']; $sign = self::$sign; diff --git a/common/components/parsers/config.php b/common/components/parsers/config.php index b068243..ee95464 100755 --- a/common/components/parsers/config.php +++ b/common/components/parsers/config.php @@ -45,7 +45,7 @@ 'hasKey' => 1, 'configuration' => [ "brand" => ['BRAND', 'CROSS_BRAND'], - "crosses" => [], + // "crosses" => [], ] ], 'basic_column' => [ diff --git a/common/models/Currency.php b/common/models/Currency.php index e177145..5e2723c 100755 --- a/common/models/Currency.php +++ b/common/models/Currency.php @@ -30,9 +30,6 @@ class Currency extends \yii\db\ActiveRecord { return [ [['name', 'rate'], 'required'], -// [['rate'], 'filter','filter' => function($value){ -// return (float) str_replace( ',', '.', $value );} -// ], ['rate', \common\components\CommaNumberValidator::className()], [['is_default'], 'integer'], [['timestamp'], 'safe'], -- libgit2 0.21.4