diff --git a/backend/components/base/BaseController.php b/backend/components/base/BaseController.php index 87d48b2..4f7aab4 100755 --- a/backend/components/base/BaseController.php +++ b/backend/components/base/BaseController.php @@ -137,4 +137,36 @@ 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/controllers/CrossingUploadController.php b/backend/controllers/CrossingUploadController.php index f6b6167..948defa 100755 --- a/backend/controllers/CrossingUploadController.php +++ b/backend/controllers/CrossingUploadController.php @@ -82,7 +82,7 @@ class CrossingUploadController extends BaseController //запускаем парсинг $data = $model->readFile(); // сохраняем в кеш отпарсенные даные - $this->cacheHandler( 1, $data, $model ); + $this->parserCacheHandler( 1, $data, $model ); } else if (Yii::$app->getCache()->get('parser_data')) { $data = json_decode(Yii::$app->getCache()->get('parser_data'), true); } @@ -128,7 +128,7 @@ class CrossingUploadController extends BaseController $arr = $model->toArray(); // получим данные из кеша - $this->cacheHandler( 0, $data, $configuration ); + $this->parserCacheHandler( 0, $data, $configuration ); // соотнесем отпарсенные данные с соответствием полученным от пользователя // для этого преобразуем массив отпарсенных данных - назначим ключи согласно соответствию @@ -149,18 +149,17 @@ class CrossingUploadController extends BaseController if ( $crosses_model->ManualInsertWithIgnore( $data ) ) { - Yii::$app->session->setFlash( $type_msg, $msg ); - // очистим кеш - $this->cacheHandler( 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]); } - } else { // не прошла валидация формы загрузки файлов $errors_str = ''; @@ -212,39 +211,6 @@ class CrossingUploadController extends BaseController } - /** - * @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 cacheHandler( $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'); - } - - } - protected function reverseCrosses ( $data ) { // для доп массива обратных строк diff --git a/backend/controllers/ParserController.php b/backend/controllers/ParserController.php index 4b5cf87..898c0f7 100755 --- a/backend/controllers/ParserController.php +++ b/backend/controllers/ParserController.php @@ -72,59 +72,26 @@ class ParserController extends BaseController public function actionResults($mode = 0) { - $model = new UploadFileParsingForm(['mode' => $mode]); + $model = new UploadFileParsingForm( ['mode' => $mode] ); $data = []; - if ($model->load(Yii::$app->request->post())) { + if ( $model->load(Yii::$app->request->post()) ) { $model->file = UploadedFile::getInstance($model, 'file'); - // первый проход - валидируем, сохраняем файл, ложим в кеш (для ручной загрузки) отпарсенные данные и параметры модели (потом при записи в базу данных они пригодятся) - if ($model->validate()) { - // запишем дату загрузки файла в таблицу файлов поставщика (ImportersFiles) - $files_model = new ImportersFiles(); - // id поставщика получим из конфигурации - $files_model->load(['ImportersFiles' => $model->toArray()]); - try { - $files_model->save(); - } catch (ErrorException $e) { - throw $e; - } - // получим id только что записанной записи - его запишем в название файла - $model->record_id = $files_model->find() - ->where(['importer_id' => $files_model->importer_id]) - ->orderBy(['id' => SORT_DESC]) - ->one() - ->id; - - $file_name = $model->record_id . '.' . $model->file->extension; - - if ($model->mode) { - $model->file_path = Yii::getAlias('@temp_upload') . '/' . $file_name; - } else { - $model->file_path = Yii::getAlias('@manual_upload') . '/' . $file_name; - } - - $model->file->saveAs($model->file_path); + // первый проход - валидируем, + // сохраняем файл, + // ложим в кеш (для ручной загрузки) отпарсенные данные и параметры модели + // (потом при записи в базу данных они пригодятся) + if ( $model->validate() ) { + // сохраним файл и создадим модель - ImportersFiles + $files_model = $this->saveParserFile($model); // для авто загрузки, обработка завершена - if ($model->mode) { + if ( $model->mode ) { $model->success = true; - return $this->render('index', ['model' => $model]); } // === ручная загрузка =========== //запускаем парсинг - // доп. опции для парсера - $options = ['converter_conf' => - ['importer_id' => $files_model->importer_id] - ]; - - if( ! $model->action ) // обработка с кастомным разделителем - $options['$delimiter'] = $model->delimiter; - - $data = $model->readFile( $options ); - // сохраняем в кеш отпарсенные даные - Yii::$app->getCache()->set('parser_data', json_encode($data), 1800); - // сохраняем в кеш модель - в ней настройки для дальнейшей обработки данных - Yii::$app->getCache()->set('parser_configuration', serialize($model), 1800); + $data = $this->parseDataFromFile( $files_model, $model ); } else { // не прошла валидация форма загрузки файлов @@ -136,7 +103,7 @@ class ParserController extends BaseController $model->throwStringErrorException(); } // листаем пагинатором, или повторно вызываем - считываем из кеша отпрасенные данные - } else if (Yii::$app->getCache()->get('parser_data')) { + } else if ( Yii::$app->getCache()->get('parser_data') ) { $data = json_decode(Yii::$app->getCache()->get('parser_data'), true); @@ -180,12 +147,7 @@ class ParserController extends BaseController $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 ); // соотнесем отпарсенные данные с соответсивем полученным от пользователя // для этого преобразуем массив отпарсенных данных - назначим ключи согласно соответствию @@ -198,14 +160,12 @@ class ParserController extends BaseController $writer->setMode(0); //web-режим if ( $writer->writePriceToDB() ) { - $configuration['success'] = true; - // все прошло успешно - очищаем кеш - Yii::$app->getCache()->delete('parser_data'); - Yii::$app->getCache()->delete('parser_configuration'); + $this->parserCacheHandler( 2 ); if( file_exists($configuration['file_path']) ) unlink($configuration['file_path']); + Yii::$app->session->setFlash( $writer->getValidatedTypeMsg(), $writer->getValidatedMsg() ); return $this->render('index', ['model' => $configuration]); }; @@ -291,5 +251,53 @@ class ParserController extends BaseController } + /** + * сохраняет файл на диск и регистрирует в ImportersFiles + * @param $model - модель с настройками + * @return ImportersFiles + * @throws ErrorException + * @throws \Exception + */ + protected function saveParserFile ($model) + { + $files_model = new ImportersFiles(); + // id поставщика получим из конфигурации + $files_model->load(['ImportersFiles' => $model->toArray()]); + try { + $files_model->save(); + } catch (ErrorException $e) { + throw $e; + } + // получим id только что записанной записи - его запишем в название файла + $model->record_id = $files_model->id; + + $file_name = $model->record_id . '.' . $model->file->extension; + + if ($model->mode) { + $model->file_path = Yii::getAlias('@temp_upload') . '/' . $file_name; + } else { + $model->file_path = Yii::getAlias('@manual_upload') . '/' . $file_name; + } + + $model->file->saveAs($model->file_path); + + return $files_model; + } + protected function parseDataFromFile ( $files_model, $model ) + { + // доп. опции для парсера + $options = ['converter_conf' => + ['importer_id' => $files_model->importer_id] + ]; + + if( ! $model->action ) // обработка с кастомным разделителем + $options['$delimiter'] = $model->delimiter; + + $data = $model->readFile( $options ); + // сохраняем в кеш отпарсенные даные + $this->parserCacheHandler( 1, $data, $model ); + + return $data; + } } diff --git a/backend/views/crossing-upload/index.php b/backend/views/crossing-upload/index.php index 1d07aaf..920bf67 100755 --- a/backend/views/crossing-upload/index.php +++ b/backend/views/crossing-upload/index.php @@ -20,14 +20,8 @@ use yii\helpers\ArrayHelper; 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']); - } + // подключим шаблон сообщения + echo $this->render('../templates/parser_massage'); ?> diff --git a/backend/views/parser/index.php b/backend/views/parser/index.php index 44864c4..337b8b8 100755 --- a/backend/views/parser/index.php +++ b/backend/views/parser/index.php @@ -20,9 +20,6 @@ if ( $model->mode ) { if (!$model->action) { $model->action = 1; } - if ($model->success) { // вернулись после успешной загрузки данного файла - echo Html::tag('h3', 'Файл успешно загружен',['class'=>'bg-success']); - } ?>