diff --git a/.idea/test-1.artwebua.in.ua.iml b/.idea/test-1.artwebua.in.ua.iml index 19a64cc..1dcf07c 100644 --- a/.idea/test-1.artwebua.in.ua.iml +++ b/.idea/test-1.artwebua.in.ua.iml @@ -6,5 +6,15 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/workspace.xml b/.idea/workspace.xml index 82635c9..4066ee0 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -2,7 +2,6 @@ - @@ -21,22 +20,17 @@ - - - + - - - + - - - - - - + + + + + @@ -177,24 +171,28 @@ - - + + - - + + - + + - - + + - - - + + + + + + @@ -202,20 +200,84 @@ - - + + - - + + + + + + + + + + + + - - + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -230,16 +292,6 @@ @@ -333,6 +395,80 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -464,126 +600,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -621,11 +637,11 @@ + + - - @@ -646,22 +662,19 @@ + + + - - - - - - @@ -671,6 +684,9 @@ + + + @@ -745,9 +761,9 @@ - - + + @@ -756,7 +772,7 @@ - + @@ -764,8 +780,8 @@ - + @@ -787,9 +803,9 @@ - - + + @@ -812,426 +828,428 @@ + + + file://$PROJECT_DIR$/backend/controllers/RgGrupController.php + 148 + + - - - + + + + - + - - + + + - + - - + + + - + - - + + + - + - - + + - + - - + + - + - - + + + - + - - - + + - + - - + + - + - - - + + - + - - + + - + - - + + + - + - - + + + + + - + - - - + + - + - - + + - + - - - + + - + - - - + + - + - - - + + - + - - - + + - + - - - - - + + - + - - - + + - + - - - + + - + - + + + + + + + + - + - - + + - + - - - - - - - + + - + - - + + - + - - - + + - + - - - + + - + - - + + - + - - + + - + - - + + - + - - + + - + - - + + - + - - + + - + - - + + - - - - + - - + + - + - - + + - + - - + + - + - - + + - + - - + + - + - - + + - + - - + + - + - - + + - + - - - + + + + + - + - - - + + + + + - + - - + + - + - - + + - + - - + + - + - - + + + - - - - - - - - - + - - + + - + + - + - - - + + + + + diff --git a/backend/components/base/BaseController.php b/backend/components/base/BaseController.php index 8d6f7ec..0573b77 100755 --- a/backend/components/base/BaseController.php +++ b/backend/components/base/BaseController.php @@ -216,36 +216,5 @@ class BaseController extends Controller { } } - /** - * @param $mode - int: 0 - fetch from cache, - 1 - put in cache, <2 - delete from cache - * @param $data - array - * @param $configuration - array - * @throws \ErrorException - */ - protected function parserCacheHandler( $mode, &$data = [], &$configuration = [] ){ - switch ( $mode ) { - case 0: - if (Yii::$app->getCache()->get('parser_data') && Yii::$app->getCache()->get('parser_configuration')) { - $data = json_decode(Yii::$app->getCache()->get('parser_data'), true); - $configuration = unserialize(Yii::$app->getCache()->get('parser_configuration')); - } else { - throw new \ErrorException('Ошибка кеша'); - } - break; - - case 1: - Yii::$app->getCache()->set('parser_data', json_encode($data), 1800); - // сохраняем в кеш модель - в ней настройки для дальнейшей обработки данных - Yii::$app->getCache()->set('parser_configuration', serialize($configuration), 1800); - break; - - default: - if( Yii::$app->getCache()->exists('parser_data') ) - Yii::$app->getCache()->delete('parser_data'); - - if( Yii::$app->getCache()->exists('parser_configuration') ) - Yii::$app->getCache()->delete('parser_configuration'); - } - } } \ No newline at end of file diff --git a/backend/components/traits/ParserTrait.php b/backend/components/traits/ParserTrait.php new file mode 100644 index 0000000..df74cdc --- /dev/null +++ b/backend/components/traits/ParserTrait.php @@ -0,0 +1,88 @@ +getCache()->get('parser_data') && Yii::$app->getCache()->get('parser_configuration')) { + $data = json_decode(Yii::$app->getCache()->get('parser_data'), true); + $configuration = unserialize(Yii::$app->getCache()->get('parser_configuration')); + } else { + throw new \ErrorException('Ошибка кеша'); + } + break; + + case 1: + Yii::$app->getCache()->set('parser_data', json_encode($data), 1800); + // сохраняем в кеш модель - в ней настройки для дальнейшей обработки данных + Yii::$app->getCache()->set('parser_configuration', serialize($configuration), 1800); + break; + + default: + if (Yii::$app->getCache()->exists('parser_data')) + Yii::$app->getCache()->delete('parser_data'); + + if (Yii::$app->getCache()->exists('parser_configuration')) + Yii::$app->getCache()->delete('parser_configuration'); + } + + } + + public function renderResultView($data) + { + $provider = new ArrayDataProvider([ + 'allModels' => $data, + 'pagination' => [ + 'pageSize' => 10, + ], + ]); + + // создадим модель на столько реквизитов сколько колонок в отпарсенном файле + $last_index = end(array_flip($data[0])); + $header_counts = $last_index + 1; + $header_model = DynamicFormHelper::CreateDynamicModel($header_counts); + + // соберем массив данных из которых будет пользователь выбирать значения в конструкторе (выпадающий список) + $basicColumns = $this->getBasicColumns(); + + return $this->render('results', + ['model' => $data, + 'header_model' => $header_model, + // список колонок для выбора + 'basic_column' => $basicColumns, + 'dataProvider' => $provider]); + + } + + public function throwStringErrorException( $model , $exception, $errors_str = '' ) + { + foreach ( $model->getErrors() as $error ) + { + $errors_str .= ' ' . implode( array_values( $error ) ); + } + + throw new $exception( $errors_str ); + } + + } \ No newline at end of file diff --git a/backend/controllers/CrossingUploadController.php b/backend/controllers/CrossingUploadController.php index 4d802b1..68cfdad 100755 --- a/backend/controllers/CrossingUploadController.php +++ b/backend/controllers/CrossingUploadController.php @@ -10,6 +10,8 @@ namespace backend\controllers; use backend\components\base\BaseController; use common\components\CustomArrayHelper; +use common\components\exceptions\CrossParsingException; +use yii\base\Exception; use yii\data\ArrayDataProvider; use yii\filters\VerbFilter; use yii\filters\AccessControl; @@ -19,12 +21,13 @@ use common\components\parsers\DynamicFormHelper; use yii\web\UploadedFile; use common\components\ModelArrayValidator; use \Yii; +use backend\components\traits\ParserTrait; class CrossingUploadController extends BaseController { + use ParserTrait; public $layout = "/column"; - /** * @inheritdoc */ @@ -35,7 +38,7 @@ class CrossingUploadController extends BaseController 'class' => AccessControl::className(), 'rules' => [ [ - 'actions' => ['result', 'index', 'write'], + 'actions' => ['result', 'index', 'write', 'error'], 'allow' => true, 'roles' => ['@'], ], @@ -50,18 +53,6 @@ class CrossingUploadController extends BaseController ]; } - /** - * @inheritdoc - */ - public function actions() - { - return [ - 'error' => [ - 'class' => 'yii\web\ErrorAction', - ], - ]; - } - public function actionIndex() { @@ -69,63 +60,56 @@ class CrossingUploadController extends BaseController return $this->render('index', ['model' => $model]); } + public function actionResult() { $model = new UploadFileCrossingForm(); $data = []; - if ($model->load(Yii::$app->request->post())) { + if ( $model->load(Yii::$app->request->post()) ) { $model->file = UploadedFile::getInstance($model, 'file'); - if ($model->validate()) { + + if ( $model->validate() ) { $file_name = $model->file->name; $model->file_path = Yii::getAlias('@temp_upload') . '/' . $file_name; $model->file->saveAs($model->file_path); //запускаем парсинг $data = $model->readFile(); // сохраняем в кеш отпарсенные даные - $this->parserCacheHandler( 1, $data, $model ); - } else if (Yii::$app->getCache()->get('parser_data')) { - $data = json_decode(Yii::$app->getCache()->get('parser_data'), true); + $this->parserCacheHandler( 1, $data, $model ); + } else { + // не прошла валидация формы загрузки файлов + $errors_str = "Ошибка загрузки файла. "; + $this->throwStringErrorException( $model , new CrossParsingException( $errors_str ) ); } - $provider = new ArrayDataProvider([ - 'allModels' => $data, - 'pagination' => [ - 'pageSize' => 10, - ], - ]); - - // создадим модель на столько реквизитов сколько колонок в отпарсенном файле - $last_index = end(array_flip($data[0])); - $header_counts = $last_index + 1; - $header_model = DynamicFormHelper::CreateDynamicModel($header_counts); - - // соберем массив данных из которых будет пользователь выбирать значения в конструкторе (выпадающий список) - $basicColumns = $this->getBasicColumns(); - - return $this->render('results', - ['model' => $data, - 'header_model' => $header_model, - // список колонок для выбора - 'basic_column' => $basicColumns, - 'dataProvider' => $provider]); + + } else if ( Yii::$app->getCache()->get('parser_data') ) { + + $data = json_decode( Yii::$app->getCache()->get('parser_data'), true ); + } + // сборка динамической модели и её рендеринг + return $this->renderResultView( $data ); } public function actionWrite() { + set_time_limit(600); //получим колонки которые выбрал пользователь $arr_attributes = Yii::$app->request->post()['DynamicModel']; //соберем модель по полученным данным $model = DynamicFormHelper::CreateDynamicModel($arr_attributes); $crosses_model = new DetailsCrosses(); + $arr_keys = array_keys($this->getBasicColumns()); + //добавим правила валидации (колонки должны быть те что в модели) foreach ($arr_attributes as $key => $value) { - $model->addRule($key, 'in', [ 'range' => array_keys( $this->getBasicColumns() ) ]); + $model->addRule($key, 'in', ['range' => $arr_keys]); } // установим режим проверки обязательных полей $crosses_model->setScenario('form_upload_validation'); - $model_validator = new ModelArrayValidator( $crosses_model ); + $model_validator = new ModelArrayValidator($crosses_model); // провалидируем выбранные колонки - if ( $model->validate() && $model_validator->validateRow( array_flip( $arr_attributes ) ) ) { + if ( $model->validate() && $model_validator->validateRow( array_flip( $arr_attributes ) ) ) { // валидация успешна у нас есть соответсвие колонок, преобразуем в массив данное соответсвие для дальнейшей работы $arr = $model->toArray(); @@ -135,7 +119,7 @@ class CrossingUploadController extends BaseController // соотнесем отпарсенные данные с соответствием полученным от пользователя // для этого преобразуем массив отпарсенных данных - назначим ключи согласно соответствию - $data = CustomArrayHelper::createAssocArray($data, $arr, 'attr_'); + $data = CustomArrayHelper::createAssocArray( $data, $arr, 'attr_' ); // запустим конвертер над над данными $data = $this->convertDataByConfiguration( $data, $configuration ); @@ -144,31 +128,33 @@ class CrossingUploadController extends BaseController $crosses_model->setScenario('default'); $data = $model_validator->validate( $data ); $msg = $model_validator->getMassage(); - $type_msg = $model_validator->hasError() ? 'warning' : 'success'; + $type_msg = $model_validator->hasError() ? 'warning' : 'success'; $model_validator->close(); - $data = $this->reverseCrosses( $data ); + $data = $this->reverseCrosses($data); + + try { + if ($crosses_model->ManualInsertWithIgnore( $data )) { - if ( $crosses_model->ManualInsertWithIgnore( $data ) ) { + // очистим кеш + $this->parserCacheHandler(2); - // очистим кеш - $this->parserCacheHandler( 2 ); + if (file_exists($configuration['file_path'])) + unlink($configuration['file_path']); - if ( file_exists($configuration['file_path']) ) - unlink( $configuration['file_path'] ); + Yii::$app->session->setFlash($type_msg, $msg); + return $this->render('index', ['model' => $configuration]); - Yii::$app->session->setFlash( $type_msg, $msg ); - return $this->render('index', ['model' => $configuration]); + } + } catch (Exception $e) { + new CrossParsingException( $e->getMessage() ); } } else { // не прошла валидация формы загрузки файлов $errors_str = "Ошибка валидации формы загрузки файлов. "; - foreach ($crosses_model->getErrors() as $error) { - $errors_str .= implode(array_values($error)); - } - throw new \ErrorException($errors_str); + $this->throwStringErrorException( $crosses_model , 'common\components\exceptions\CrossParsingException', $errors_str ); } } @@ -183,7 +169,8 @@ class CrossingUploadController extends BaseController } - protected function convertDataByConfiguration( $data, $configuration ){ + protected function convertDataByConfiguration($data, $configuration) + { // доп. опции для парсера - удаление префикса в артикулах $options['mode'] = 'crosses'; @@ -195,38 +182,38 @@ class CrossingUploadController extends BaseController $fields[] = 'CROSS_ARTICLE'; } if ($fields) { - $options ['converter_conf']['configuration'] = ["article" => $fields, + $options ['converter_conf']['configuration'] = ["article" => $fields, "string" => ['ARTICLE', 'CROSS_ARTICLE'],]; } else { - $options ['converter_conf']['configuration'] = ["string" => ['ARTICLE', 'CROSS_ARTICLE'],]; + $options ['converter_conf']['configuration'] = ["string" => ['ARTICLE', 'CROSS_ARTICLE'],]; } // получим базовую конфигурацию и объеденим её с той что образовалась после выбора пользователем настроек - $basic_options = Yii::$app->multiparser->getConfiguration( 'csv', 'crosses' ); - $options = array_merge_recursive( $options, $basic_options ); + $basic_options = Yii::$app->multiparser->getConfiguration('csv', 'crosses'); + $options = array_merge_recursive($options, $basic_options); - foreach ( $data as &$row ) { - $row = Yii::$app->converter->convertByConfiguration( $row, $options['converter_conf'] ); + foreach ($data as &$row) { + $row = Yii::$app->converter->convertByConfiguration($row, $options['converter_conf']); } return $data; } - protected function reverseCrosses ( $data ) + protected function reverseCrosses($data) { // для доп массива обратных строк - $i = count( $data ) - 1; + $i = count($data) - 1; $reverse_data = []; - foreach ( $data as &$row ) { + 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']; + $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 ); + $data = array_merge($data, $reverse_data); return $data; } diff --git a/backend/controllers/ParserController.php b/backend/controllers/ParserController.php index 795c926..97f69f2 100755 --- a/backend/controllers/ParserController.php +++ b/backend/controllers/ParserController.php @@ -2,9 +2,9 @@ namespace backend\controllers; use backend\models\Details; -use common\components\archives\ArchiveCreator; -use common\components\mail\ImapMailReader; -use common\components\mail\MailAttachmentsSaver; +use common\components\exceptions\CrossParsingException; +use common\components\exceptions\PriceParsingException; +use common\components\exceptions\RgParsingException; use common\components\ModelArrayValidator; use common\components\parsers\MailParser; use Yii; @@ -20,14 +20,15 @@ use backend\models\ImportersFiles; use backend\models\Importers; use yii\base\ErrorException; use common\components\PriceWriter; -use common\components\CustomVarDamp; use common\components\CustomArrayHelper; +use backend\components\traits\ParserTrait; /** * Parser controller */ class ParserController extends BaseController { + use ParserTrait; public $layout = "/column"; /** @@ -55,7 +56,6 @@ class ParserController extends BaseController } - public function actionIndex($mode = 0) { $model = new UploadFileParsingForm(); @@ -67,8 +67,19 @@ class ParserController extends BaseController public function actionError() { $exception = Yii::$app->errorHandler->exception; - if ($exception !== null) { - return $this->render('error', ['message' => $exception->getMessage()]); + $action_name = ''; + + if ( $exception instanceof CrossParsingException ) { + $action_name = ['crossing-upload/result']; + }elseif ( $exception instanceof PriceParsingException ) { + $action_name = ['results']; + }elseif ( $exception instanceof RgParsingException ) { + $action_name = ['rg-grup/results']; + } + + if ( $exception !== null ) { + $msg = $exception->getMessage(); + return $this->render( 'error', [ 'message' => $msg, 'action_name' => $action_name ] ); } } @@ -89,44 +100,19 @@ class ParserController extends BaseController $model->success = true; return $this->render('index', ['model' => $model]); } - // === ручная загрузка =========== //запускаем парсинг $data = $this->parseDataFromFile( $files_model, $model ); } else { // не прошла валидация форма загрузки файлов - $errors_str = ''; - foreach ($model->getErrors() as $error) { - $errors_str .= implode( array_values($error) ); - } - throw new ErrorException( $errors_str ); + $this->throwStringErrorException( $model , 'common\components\exceptions\PriceParsingException' ); } // листаем пагинатором, или повторно вызываем - считываем из кеша отпрасенные данные } else if ( Yii::$app->getCache()->get('parser_data') ) { - $data = json_decode(Yii::$app->getCache()->get('parser_data'), true); - } - - $provider = new ArrayDataProvider([ - 'allModels' => $data, - 'pagination' => [ - 'pageSize' => 10, - ], - ]); - - $last_index = end( array_flip( $data[0] ) ); - $header_counts = $last_index + 1; - //формируем заголовок для пользователя, где он сможет выбрать соответсвие полей (выпадающий список) - $header_model = DynamicFormHelper::CreateDynamicModel( $header_counts ); - - return $this->render('results', - ['model' => $data, - 'header_model' => $header_model, - // список колонок для выбора - 'basic_column' => Yii::$app->multiparser->getConfiguration('csv', 'basic_column'), - 'dataProvider' => $provider]); + return $this->renderResultView( $data ); } public function actionWrite() @@ -170,19 +156,14 @@ class ParserController extends BaseController unlink($configuration['file_path']); $validated_type_msg = $writer->hasValidationError() ? 'warning' : 'success'; Yii::$app->session->setFlash( $validated_type_msg, $writer->getValidatedMsg() ); - return $this->render('index', ['model' => $configuration]); + return $this->render('index', ['model' => $configuration]); }; } else { // не прошла валидация формы загрузки файлов $errors_str = "Ошибка валидации формы загрузки файлов. "; - - foreach ( $details_model->getErrors() as $error ) { - $errors_str .= implode(array_values($error)); - } - - throw new \ErrorException($errors_str); + $this->throwStringErrorException( $details_model , 'common\components\exceptions\PriceParsingException', $errors_str ); } } @@ -313,4 +294,9 @@ class ParserController extends BaseController return $data; } + protected function getBasicColumns() + { + return Yii::$app->multiparser->getConfiguration('csv', 'basic_column'); + + } } diff --git a/backend/controllers/RgGrupController.php b/backend/controllers/RgGrupController.php index ab7f0dc..6c5c4c5 100755 --- a/backend/controllers/RgGrupController.php +++ b/backend/controllers/RgGrupController.php @@ -10,7 +10,7 @@ namespace backend\controllers; use backend\components\base\BaseController; use backend\models\UploadFileRgForm; -use common\components\CustomVarDamp; +use common\components\exceptions\RgParsingException; use common\components\ModelArrayValidator; use common\components\parsers\MailAttachmentsSaver; use common\models\Margins; @@ -21,9 +21,11 @@ use yii\web\UploadedFile; use yii\data\ArrayDataProvider; use common\components\parsers\DynamicFormHelper; use common\components\CustomArrayHelper; +use backend\components\traits\ParserTrait; class RgGrupController extends BaseController { + use ParserTrait; public $layout = "/column"; /** @@ -66,25 +68,15 @@ class RgGrupController extends BaseController $model->file = UploadedFile::getInstance($model, 'file'); // первый проход - валидируем, сохраняем файл, ложим в кеш отпарсенные данные и параметры модели (потом при записи в базу данных они пригодятся) if ($model->validate()) { - $model->file_path = Yii::getAlias('@manual_upload') . '/' . $model->file->name; $model->file->saveAs($model->file_path); - //запускаем парсинг $data = $model->readFile(); // сохраняем в кеш отпарсенные даные - Yii::$app->getCache()->set('parser_data', json_encode($data), 1800); - // сохраняем в кеш модель - в ней настройки для дальнейшей обработки данных - Yii::$app->getCache()->set('parser_configuration', serialize($model), 1800); - - + $this->parserCacheHandler(1, $data, $model); } else { // не прошла валидация форма загрузки файлов - $errors_str = ''; - foreach ($model->getErrors() as $error) { - $errors_str .= implode(array_values($error)); - } - throw new \ErrorException($errors_str); + $this->throwStringErrorException($model, 'common\components\exceptions\RgParsingException'); } // листаем пагинатором, или повторно вызываем - считываем из кеша отпрасенные данные } else if (Yii::$app->getCache()->get('parser_data')) { @@ -92,26 +84,8 @@ class RgGrupController extends BaseController $data = json_decode(Yii::$app->getCache()->get('parser_data'), true); } - $provider = new ArrayDataProvider([ - 'allModels' => $data, - 'pagination' => [ - 'pageSize' => 10, - ], - ]); - // создадим модель на столько реквизитов сколько колонок в отпарсенном файле - $last_index = end(array_flip($data[0])); - $header_counts = $last_index + 1; - $header_model = DynamicFormHelper::CreateDynamicModel($header_counts); - - // соберем массив данных из которых будет пользователь выбирать значения в конструкторе (выпадающий список) - $header_array = Margins::getHeader(); - - return $this->render('results', - ['model' => $data, - 'header_model' => $header_model, - // список колонок для выбора - 'basic_column' => $header_array, - 'dataProvider' => $provider]); + // сборка динамической модели и её рендеринг + return $this->renderResultView($data); } public function actionWrite() @@ -127,20 +101,15 @@ class RgGrupController extends BaseController } // установим режим проверки обязательных полей $margin_model->setScenario('form_upload_validation'); - $model_validator = new ModelArrayValidator( $margin_model ); + $model_validator = new ModelArrayValidator($margin_model); // провалидируем выбранные колонки - if ( $model->validate() && $model_validator->validateRow( array_flip( $arr_attributes ) )) { + if ($model->validate() && $model_validator->validateRow($this->getAttributesForValidate($arr_attributes))) { // валидация успешна у нас есть соответсвие колонок, преобразуем в массив данное соответсвие для дальнейшей работы $arr = $model->toArray(); // получим данные из кеша - if (Yii::$app->getCache()->get('parser_data') && Yii::$app->getCache()->get('parser_configuration')) { - $data = json_decode(Yii::$app->getCache()->get('parser_data'), true); - $configuration = unserialize(Yii::$app->getCache()->get('parser_configuration')); - } else { - throw new \ErrorException('Ошибка кеша'); - } + $this->parserCacheHandler(0, $data, $configuration); array_walk($arr, function (&$val) { $val = '!' . $val; @@ -151,63 +120,85 @@ class RgGrupController extends BaseController $data = CustomArrayHelper::createAssocArray($data, $arr, 'attr_'); // в первой строке у нас заголовки - уберем - unset( $data[0] ); + unset($data[0]); // подготовим данные для записи в таблицу w_margins_groups - $arr_values = []; - $group = ''; - $importer_id = $configuration['importer_id']; - foreach ($data as $row_data) { - - if (isset($row_data['!group'])) { - $group = $row_data['!group']; - unset($row_data['!group']); - } - if (isset($row_data['!_null'])) { - unset($row_data['!_null']); - } - - foreach ($row_data as $key => $value) { - if ($group) - $row['group'] = trim($group); + $data = $this->convertDataByConfiguration($data, $configuration); - $row['importer_id'] = trim($importer_id); - $row['margin_id'] = ltrim($key, '!'); - $row['koef'] = \Yii::$app->converter->convertTo('float', $value, ['precision' => 6]); - - $arr_values[] = $row; - } - } - unset($data); // валидируем отпарсенные данные моделью в которую будем записывать $margin_model->setScenario('default'); - $arr_values = $model_validator->validate( $arr_values ); + $data = $model_validator->validate($data); $msg = $model_validator->getMassage(); - $type_msg = $model_validator->hasError() ? 'warning' : 'success'; + $type_msg = $model_validator->hasError() ? 'warning' : 'success'; $model_validator->close(); // сохраним подготовленные данные - if ( !empty( $arr_values ) ) { - MarginsGroups::ManualInsertWithUpdate( $arr_values, [ 'group','importer_id','margin_id' ] ); - // все прошло успешно - очищаем кеш - Yii::$app->getCache()->delete('parser_data'); - Yii::$app->getCache()->delete('parser_configuration'); - - if (file_exists($configuration['file_path'])) - unlink($configuration['file_path']); - } + if (!empty($data)) { + if (MarginsGroups::ManualInsertWithUpdate($data, ['group', 'importer_id', 'margin_id'])) { + // все прошло успешно - очищаем кеш + $this->parserCacheHandler(2); + if (file_exists($configuration['file_path'])) + unlink($configuration['file_path']); + } - Yii::$app->session->setFlash( $type_msg, $msg ); + } + Yii::$app->session->setFlash($type_msg, $msg); return $this->render('index', ['model' => $configuration]); } else { // не прошла валидация формы загрузки файлов $errors_str = "Ошибка валидации формы загрузки файлов. "; - foreach ($margin_model->getErrors() as $error) { - $errors_str .= implode(array_values($error)); + $this->throwStringErrorException($margin_model, 'common\components\exceptions\RgParsingException', $errors_str); + } + } + + protected function convertDataByConfiguration($data, $configuration) + { + $arr_values = []; + $group = ''; + $importer_id = $configuration['importer_id']; + foreach ($data as $row_data) { + + if (isset($row_data['!group'])) { + $group = $row_data['!group']; + unset($row_data['!group']); + } + if (isset($row_data['!_null'])) { + unset($row_data['!_null']); + } + + foreach ($row_data as $key => $value) { + if ($group) + $row['group'] = trim($group); + + $row['importer_id'] = trim($importer_id); + $row['margin_id'] = ltrim($key, '!'); + $row['koef'] = \Yii::$app->converter->convertTo('float', $value, ['precision' => 6]); + + $arr_values[] = $row; } - throw new \ErrorException($errors_str); } + return $arr_values; + } + + protected function getBasicColumns() + { + return Margins::getHeader(); + } + + // подготавливает массив для валидирования моделью - MarginsGroups + // для этого меняем выбранные значения именем поля - margin_id + protected function getAttributesForValidate($arr) + { + $base_columns_arr = Margins::find()->select('id')->asArray()->all(); + $base_columns_arr = array_column($base_columns_arr,'id'); + + array_walk( $arr, function (&$value, $key, $base_columns_arr) { + if (in_array( $value, $base_columns_arr )){ + $value = 'margin_id'; + } + }, $base_columns_arr ); + return array_flip( $arr ); } // public function actionMail() diff --git a/backend/views/crossing-upload/index.php b/backend/views/crossing-upload/index.php index 920bf67..900a506 100755 --- a/backend/views/crossing-upload/index.php +++ b/backend/views/crossing-upload/index.php @@ -14,9 +14,10 @@ use yii\helpers\ArrayHelper; field($model, 'delete_prefix1')->checkbox() ?> field($model, 'delete_prefix2')->checkbox() ?> field($model, 'file')->fileInput()->label(false) ?> +
- 'btn btn-primary']) ?> + 'btn btn-primary']) ?>
title = $name; +$this->title = 'Ошибка'; ?>

title) ?>

- + "; + echo "
"; + echo Html::a('Вернуться', $action_name, ['class' => 'btn btn-info', 'name' => 'Return',]); + } + ?>

diff --git a/backend/views/rg-grup/index.php b/backend/views/rg-grup/index.php index 9e4f6b1..3d396b7 100755 --- a/backend/views/rg-grup/index.php +++ b/backend/views/rg-grup/index.php @@ -4,7 +4,7 @@ use yii\helpers\Html; use backend\models\Importers; use yii\helpers\ArrayHelper; -$button_label = 'Прочитать'; +$button_label = 'Выполнить'; ?> @@ -21,6 +21,8 @@ $button_label = 'Прочитать'; field($model, 'file')->fileInput()->label(false) ?>

'btn btn-primary']) ?> + +
params['breadcrumbs'][] = $this->title;
- 'btn btn-primary', 'name' => 'Return',]) ?> + 'btn btn-primary', 'name' => 'Return',]) ?> \ No newline at end of file diff --git a/common/components/exceptions/CrossParsingException.php b/common/components/exceptions/CrossParsingException.php new file mode 100644 index 0000000..2d309f9 --- /dev/null +++ b/common/components/exceptions/CrossParsingException.php @@ -0,0 +1,16 @@ + 'default'], - ['group', 'required', 'on' => ['default','form_upload_validation']], + [['group','importer_id', 'margin_id', 'koef'], 'required', 'on' => 'default'], + [['margin_id'], 'required', 'on' => 'form_upload_validation', 'message' => 'Должен быть указан хотя бы один тип цен.'], + [['group'], 'required', 'on' => 'form_upload_validation', 'message' => 'Группа RG - обязательное поле.'], [['importer_id', 'margin_id'], 'integer' , 'on' => 'default'], [['koef'], 'number' , 'on' => 'default'], [['timestamp'], 'safe' , 'on' => 'default'], @@ -83,7 +84,6 @@ class MarginsGroups extends \yii\db\ActiveRecord //@todo - вынести все ручные инсерты в отдельный класс public static function ManualInsertWithUpdate($data, $keys) { - // \common\components\CustomVarDamp::dumpAndDie($data); $table_name = self::tableName(); $keys_arr = array_keys($data[0]); // найдем те поля которые не являются ключами. Их нужно будет при дубляже апдейтить @@ -107,9 +107,9 @@ class MarginsGroups extends \yii\db\ActiveRecord // добавим фрагмент с апдейтом при дубляже $query = "{$query_insert} {$query_update}"; - // \common\components\CustomVarDamp::dumpAndDie($query); Yii::$app->db->createCommand($query)->execute(); } + return true; } } -- libgit2 0.21.4