diff --git a/backend/controllers/CrossingUploadController.php b/backend/controllers/CrossingUploadController.php index 69e7af9..0f3fe04 100755 --- a/backend/controllers/CrossingUploadController.php +++ b/backend/controllers/CrossingUploadController.php @@ -9,6 +9,7 @@ namespace backend\controllers; use backend\components\base\BaseController; +use common\components\CustomArrayHelper; use common\components\CustomVarDamp; use yii\data\ArrayDataProvider; use yii\filters\VerbFilter; @@ -24,21 +25,17 @@ class CrossingUploadController extends BaseController public $layout = "/column"; - /** - * @inheritdoc - */ - public function behaviors() + /** + * @inheritdoc + */ + public function behaviors() { return [ 'access' => [ 'class' => AccessControl::className(), 'rules' => [ [ - 'actions' => ['login', 'error', 'download-photo','delete-image','result' ], - 'allow' => true, - ], - [ - 'actions' => ['logout', 'index','create','update','view','delete',], + 'actions' => ['result', 'index', 'write'], 'allow' => true, 'roles' => ['@'], ], @@ -52,6 +49,7 @@ class CrossingUploadController extends BaseController ], ]; } + /** * @inheritdoc */ @@ -77,56 +75,16 @@ class CrossingUploadController extends BaseController $data = []; if ($model->load(Yii::$app->request->post())) { $model->file = UploadedFile::getInstance($model, 'file'); - 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(); // сохраняем в кеш отпарсенные даные - Yii::$app->getCache()->set('parser_data', json_encode($data), 1800); - // сохраняем в кеш модель - в ней настройки для дальнейшей обработки данных - Yii::$app->getCache()->set('parser_configuration', serialize($model), 1800); - - -// // доп. опции для парсера - удаление префикса в артикулах -// $options['mode'] = 'crosses'; -// $fields = []; -// if ($model->delete_prefix1) { -// $fields[] = 'ARTICLE'; -// } -// if ($model->delete_prefix2) { -// $fields[] = 'CROSS_ARTICLE'; -// } -// if ( $fields ) { -// $options [ 'converter_conf' ] = [ 'configuration' => [ "article" => $fields , -// "string" => ['ARTICLE', 'CROSS_ARTICLE'],] ]; -// } else { -// $options [ 'converter_conf' ] = [ 'configuration' => [ "string" => ['ARTICLE', 'CROSS_ARTICLE'], ] ]; -// } -// -// $data = $model->readFile( $options ); -// $crosses_model = new DetailsCrosses(); -// $crosses_model->ManualInsertWithIgnore( $data ); -// -// Yii::$app->session->setFlash('success', 'Файл кроссов успешно загружен'); -// return $this->render('index', ['model' => $model]); -// }else{ -// // не прошла валидация форма загрузки файлов -// $errors_str = ''; -// foreach ($model->getErrors() as $error) { -// $errors_str .= implode( array_values($error) ); -// } -// throw new \ErrorException( $errors_str ); -// } - - + $this->cacheHandler( true, $data, $model ); } else if (Yii::$app->getCache()->get('parser_data')) { - $data = json_decode(Yii::$app->getCache()->get('parser_data'), true); - } $provider = new ArrayDataProvider([ 'allModels' => $data, @@ -152,8 +110,6 @@ class CrossingUploadController extends BaseController } } - - public function actionWrite() { //получим колонки которые выбрал пользователь @@ -162,7 +118,7 @@ class CrossingUploadController extends BaseController $model = DynamicFormHelper::CreateDynamicModel($arr_attributes); //добавим правила валидации (колонки должны быть те что в модели) foreach ($arr_attributes as $key => $value) { - $model->addRule($key, 'in', [ 'range' => $this->getBasicColumns() ]); + $model->addRule($key, 'in', [ 'range' => array_keys( $this->getBasicColumns() ) ]); } // провалидируем выбранные колонки @@ -172,77 +128,99 @@ class CrossingUploadController 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('Ошибка кеша'); - } - - array_walk($arr, function (&$val) { - $val = '!' . $val; - }); + $this->cacheHandler( false, $data, $configuration ); // соотнесем отпарсенные данные с соответствием полученным от пользователя // для этого преобразуем массив отпарсенных данных - назначим ключи согласно соответствию $data = CustomArrayHelper::createAssocArray($data, $arr, 'attr_'); - // в первой строке у нас заголовки - уберем - 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]); + $crosses_model = new DetailsCrosses(); + $crosses_model->ManualInsertWithIgnore($data); - - $arr_values[] = $row; - - } - - } - // сохраним подготовленные данные - MarginsGroups::ManualInsertWithUpdate( $arr_values, [ 'group','importer_id','margin_id' ] ); - - - Yii::$app->session->setFlash('success', "Файл {$configuration['file']} успешно загружен"); + Yii::$app->session->setFlash('success', 'Файл кроссов успешно загружен'); // все прошло успешно - очищаем кеш Yii::$app->getCache()->delete('parser_data'); Yii::$app->getCache()->delete('parser_configuration'); if (file_exists($configuration['file_path'])) unlink($configuration['file_path']); - return $this->render('index', ['model' => $configuration]); + } else { + // не прошла валидация форма загрузки файлов + $errors_str = ''; + foreach ($model->getErrors() as $error) { + $errors_str .= implode(array_values($error)); + } + throw new \ErrorException($errors_str); + } + } + + protected function getBasicColumns() + { + $basicColumns_array = Yii::$app->multiparser->getConfiguration('csv', 'crosses'); + if (isset($basicColumns_array['basic_column'])) { + return $basicColumns_array['basic_column']; + } else { + throw new \ErrorException('Ошибка конфигурационного файла кроссов. Не указаны базовые колнки для пользовательской формы выбора.'); } } - protected function getBasicColumns(){ + protected function convertDataByConfiguration( $data, $configuration ){ + + // доп. опции для парсера - удаление префикса в артикулах + $options['mode'] = 'crosses'; + $fields = []; + if ($configuration['delete_prefix1']) { + $fields[] = 'ARTICLE'; + } + if ($configuration['delete_prefix2']) { + $fields[] = 'CROSS_ARTICLE'; + } + if ($fields) { + $options ['configuration'] = ["article" => $fields, + "string" => ['ARTICLE', 'CROSS_ARTICLE'],]; + } else { + $options ['configuration'] = ["string" => ['ARTICLE', 'CROSS_ARTICLE'],]; + } + + foreach ($data as &$row) { + $row = Yii::$app->converter->convertByConfiguration($row, $options); + } + + return $data; + + } + + /** + * @param $mode - bool - true - put in cache, otherwise - fetch from cache + * @param $data - array + * @param $configuration - array + * @throws \ErrorException + */ + protected function cacheHandler( $mode, &$data, &$configuration ){ + + if ( $mode ) { + + Yii::$app->getCache()->set('parser_data', json_encode($data), 1800); + // сохраняем в кеш модель - в ней настройки для дальнейшей обработки данных + Yii::$app->getCache()->set('parser_configuration', serialize($configuration), 1800); - $basicColumns_array = Yii::$app->multiparser->getConfiguration( 'csv','crosses' ); - if ( isset( $basicColumns_array['basic_column'] ) ) { - return $basicColumns_array['basic_column']; } else { - throw new \ErrorException( 'Ошибка конфигурационного файла кроссов. Не указаны базовые колнки для пользовательской формы выбора.' ); + + 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('Ошибка кеша'); + } + } + } } \ No newline at end of file diff --git a/backend/views/crossing-upload/index.php b/backend/views/crossing-upload/index.php index 7b8cf4d..4d1b1a0 100755 --- a/backend/views/crossing-upload/index.php +++ b/backend/views/crossing-upload/index.php @@ -19,7 +19,7 @@ use yii\helpers\ArrayHelper; field($model, 'file')->fileInput()->label(false) ?>
- 'btn btn-primary']) ?> + 'btn btn-primary']) ?>
diff --git a/common/components/parsers/config.php b/common/components/parsers/config.php index 1863297..edce06d 100755 --- a/common/components/parsers/config.php +++ b/common/components/parsers/config.php @@ -39,7 +39,7 @@ 'crosses' => ['class' => 'common\components\parsers\CustomCsvParser', 'auto_detect_first_line' => true, 'min_column_quantity' => 4, - 'keys' =>['ARTICLE', 'CROSS_ARTICLE', 'BRAND', 'CROSS_BRAND'], + // 'keys' =>['ARTICLE', 'CROSS_ARTICLE', 'BRAND', 'CROSS_BRAND'], 'converter_conf' => [ 'class' => ' common\components\parsers\CustomConverter', 'configuration' => [ -- libgit2 0.21.4