diff --git a/backend/components/parsers/config.php b/backend/components/parsers/config.php index 78f141e..3db7f86 100644 --- a/backend/components/parsers/config.php +++ b/backend/components/parsers/config.php @@ -1,9 +1,5 @@ - ['ini' => ['upload_max_filesize' => '20M', - 'post_max_size integer' => '30M', - ]], 'csv' => ['web' => ['class' => 'backend\components\parsers\CustomCsvParser', @@ -22,6 +18,25 @@ "ADD_BOX"=> 'В пути', "GROUP" => 'Группа RG' ], + 'console' => + ['class' => 'backend\components\parsers\CustomCsvParser', + 'auto_detect_first_line' => true, + 'converter_conf' => ['class' => ' backend\components\parsers\CustomConverter', + 'configuration' => ["string" => 'DESCR', + "float" => 'PRICE', + "integer" => ['BOX','ADD_BOX'] + ] + ],], + + 'basic_column' => [ + "BRAND" => 'Бренд', + "ARTICLE"=> 'Артикул', + "PRICE" => 'Цена', + "DESCR" => 'Наименование', + "BOX" => 'Колво', + "ADD_BOX"=> 'В пути', + "GROUP" => 'Группа RG' + ], ], 'xml' => ['web' => diff --git a/backend/config/main.php b/backend/config/main.php index 390ddbc..8486a60 100644 --- a/backend/config/main.php +++ b/backend/config/main.php @@ -28,7 +28,7 @@ return [ ], ], 'errorHandler' => [ - 'errorAction' => 'site/error', + 'errorAction' => 'parser/error', ], 'request'=>[ diff --git a/backend/controllers/ParserController.php b/backend/controllers/ParserController.php index 7dab9b3..4a0271f 100644 --- a/backend/controllers/ParserController.php +++ b/backend/controllers/ParserController.php @@ -11,13 +11,12 @@ use yii\web\UploadedFile; use yii\data\ArrayDataProvider; use yii\multiparser\DynamicFormHelper; use backend\components\parsers\CustomParserConfigurator; -use backend\models\Details; use backend\models\ImportersFiles; use backend\models\Importers; use yii\base\ErrorException; -use yii\db\Query; - +use common\components\PriceWriter; use common\components\CustomVarDamp; +use yii\web\ErrorAction; /** * Parser controller @@ -50,17 +49,6 @@ class ParserController extends BaseController ]; } - /** - * @inheritdoc - */ - public function actions() - { - return [ - 'error' => [ - 'class' => 'yii\web\ErrorAction', - ], - ]; - } public function actionIndex($mode = 0) @@ -72,12 +60,13 @@ class ParserController extends BaseController return $this->render('index', ['model' => $model]); } -// public function beforeAction($action) -// { -// if($action->actionMethod ='actionResults'){ -// CustomVarDamp::dumpAndDie(phpinfo()); -// } -// } + public function actionError() + { + $exception = Yii::$app->errorHandler->exception; + if ($exception !== null) { + return $this->render('error', ['message' => $exception->getMessage()]); + } + } public function actionResults($mode = 0) { @@ -94,7 +83,8 @@ class ParserController extends BaseController try { $files_model->save(); } catch (ErrorException $e) { - CustomVarDamp::dump($e->getMessage()); + // CustomVarDamp::dump($e->getMessage()); + throw $e; } // получим id только что записанной записи - его запишем в название файла $model->record_id = $files_model->find() @@ -184,75 +174,29 @@ class ParserController extends BaseController $data = json_decode(Yii::$app->getCache()->get('parser_data'), true); $configuration = unserialize(Yii::$app->getCache()->get('parser_configuration')); } else { - CustomVarDamp::dumpAndDie('Ошибка кеша'); + throw new \ErrorException('Ошибка кеша'); } // соотнесем отпарсенные данные с соответсивем полученным от пользователя // для этого преобразуем массив отпарсенных данных - назначим ключи согласно соответствию $data = \Yii::$app->multiparser->convertToAssocArray($data, $arr, 'attr_'); + // запустим специальный класс который запишет данные в таблицы связанные с прайсами + $writer = new PriceWriter(); + $writer->configuration = $configuration; + $writer->data = $data; + $writer->mode = 0; //web-режим + if ( $writer->writeDataToDB() ) { - // 1. запишем дату старта в таблицу файлов поставщика (ImportersFiles) - // id загруженного файла получим из конфигурации - $files_model = ImportersFiles::findOne( $configuration->record_id ); - - //$files_model->load(['ImportersFiles' => $configuration->toArray()]); - $update_date = date('Y-m-d H:i:s'); - $files_model->time_start = $update_date; - // запишем дату начала загрузки - if (!$files_model->save()) { - CustomVarDamp::dumpAndDie($files_model->getErrors()); - } - - - // 2. запишем полученные данные в таблицу товаров (Details) - $details_model = new Details(); - // проверим все ли обязательные колонки были указаны пользователем - $details_model->load(['Details' => $data[0]]); - if ($details_model->validate()) { - // дополним данные значением импортера и даты обновления цены - $data = \Yii::$app->multiparser->addColumns($data, ['IMPORT_ID' => $configuration->importer_id, 'timestamp' => $update_date]); + $configuration['success'] = true; + // все прошло успешно - очищаем кеш + Yii::$app->getCache()->delete('parser_data'); + Yii::$app->getCache()->delete('parser_configuration'); - try { - //@todo add transaction - // попытаемся вставить данные в БД с апдейтом по ключам - $details_model->ManualInsert($data); - - // 3. зафиксируем дату конца загрузки в файлах поставщика - - $files_model->time_end = date('Y-m-d H:i:s'); - // CustomVarDamp::dumpAndDie($files_model); - if (!$files_model->save()) { - CustomVarDamp::dumpAndDie($files_model->getErrors()); - } - - // 4. зафиксируем дату загрузки в таблице поставщиков - $imp_model = Importers::findOne($configuration['importer_id']); - $imp_model->price_date_update = $update_date; - - if (!$imp_model->save()) { - CustomVarDamp::dumpAndDie($imp_model->getErrors()); - } - $configuration['success'] = true; - // все прошло успешно - очищаем кеш - Yii::$app->getCache()->delete('parser_data'); - Yii::$app->getCache()->delete('parser_configuration'); - - unlink($configuration['file_path']); - return $this->render('index', ['model' => $configuration]); - - } catch (ErrorException $e) { - CustomVarDamp::dump($e->getMessage()); - } - } - if ($details_model->hasErrors()) { - $errors_arr = $details_model->getErrors(); - foreach ($errors_arr as $error) { - CustomVarDamp::dump(array_values($error)); - } - - } + unlink($configuration['file_path']); + return $this->render('index', ['model' => $configuration]); + }; } diff --git a/backend/views/parser/error.php b/backend/views/parser/error.php new file mode 100644 index 0000000..47aef92 --- /dev/null +++ b/backend/views/parser/error.php @@ -0,0 +1,26 @@ +title = $name; +?> +
+ +

title) ?>

+ +
+ +
+ +

+ +

+

+

+ +
diff --git a/common/components/PriceWriter.php b/common/components/PriceWriter.php new file mode 100644 index 0000000..b18550d --- /dev/null +++ b/common/components/PriceWriter.php @@ -0,0 +1,103 @@ +configuration->record_id ); + + //$files_model->load(['ImportersFiles' => $this->configuration->toArray()]); + $update_date = date('Y-m-d H:i:s'); + $files_model->time_start = $update_date; + // запишем дату начала загрузки + if (!$files_model->save()) { + $this->errors[] = implode( ', ', $files_model->getErrors()); + return false; + //CustomVarDamp::dumpAndDie($files_model->implode ( ', ', getErrors())()); + } + + + // 2. запишем полученные данные в таблицу товаров (Details) + $details_model = new Details(); + // преобразуем числовые значения + foreach ($this->data as &$row) { + $row['PRICE'] = \Yii::$app->multiparser->convertToFloat($row['PRICE']); + $row['BOX'] = \Yii::$app->multiparser->convertToInteger($row['BOX']); + // присвоим полный артикул + $row['FULL_ARTICLE'] = $row['ARTICLE']; + if(isset($row['ADD_BOX'])) + $row['ADD_BOX'] = \Yii::$app->multiparser->convertToInteger($row['ADD_BOX']); + + // проверим все ли обязательные колонки были указаны пользователем + $details_model->load(['Details' => $row]); + + if (!$details_model->validate()) + break; + } + + if ($details_model->hasErrors()) { + //@todo предоставить более детальную информацию об ошибке + throw new \ErrorException('Ошибка записи товаров'); + } + else{ + // дополним данные значением импортера и даты обновления цены + $this->data = \Yii::$app->multiparser->addColumns($this->data, ['IMPORT_ID' => $this->configuration->importer_id, 'timestamp' => $update_date]); + + try { + //@todo add transaction + // попытаемся вставить данные в БД с апдейтом по ключам + $details_model->ManualInsert($this->data); + + // 3. зафиксируем дату конца загрузки в файлах поставщика + + $files_model->time_end = date('Y-m-d H:i:s'); + // CustomVarDamp::dumpAndDie($files_model); + if (!$files_model->save()) { + throw new \ErrorException(implode( ', ', $files_model->getErrors())); +// $this->errors[] = $files_model->implode ( ', ', getErrors()); +// return false; + // CustomVarDamp::dumpAndDie($files_model->implode ( ', ', getErrors())()); + } + + // 4. зафиксируем дату загрузки в таблице поставщиков + $imp_model = Importers::findOne($this->configuration['importer_id']); + $imp_model->price_date_update = $update_date; + + if (!$imp_model->save()) { +// $this->errors[] = $imp_model->implode ( ', ', getErrors())(); +// return false; + throw new \ErrorException(implode( ', ', $imp_model->getErrors())); + // CustomVarDamp::dumpAndDie($imp_model->implode ( ', ', getErrors())()); + } + + + } catch (ErrorException $e) { + //CustomVarDamp::dump($e->getMessage()); + throw new \ErrorException( $e->getMessage() ); + } + } + + + return true; + } +} \ No newline at end of file diff --git a/console/controllers/ParserController.php b/console/controllers/ParserController.php new file mode 100644 index 0000000..a600e17 --- /dev/null +++ b/console/controllers/ParserController.php @@ -0,0 +1,24 @@ +multiparser->parse( $file_path ); + + } +} \ No newline at end of file -- libgit2 0.21.4