Commit b6247a0e5f665e01e57261b0ca417259e37de1cf
1 parent
ecec9a21
rewrite parser writer and parser controller - add array model validator
Showing
9 changed files
with
230 additions
and
192 deletions
Show diff stats
backend/components/base/BaseController.php
| @@ -137,4 +137,36 @@ class BaseController extends Controller { | @@ -137,4 +137,36 @@ class BaseController extends Controller { | ||
| 137 | } | 137 | } |
| 138 | } | 138 | } |
| 139 | 139 | ||
| 140 | + /** | ||
| 141 | + * @param $mode - int: 0 - fetch from cache, - 1 - put in cache, <2 - delete from cache | ||
| 142 | + * @param $data - array | ||
| 143 | + * @param $configuration - array | ||
| 144 | + * @throws \ErrorException | ||
| 145 | + */ | ||
| 146 | + protected function parserCacheHandler( $mode, &$data = [], &$configuration = [] ){ | ||
| 147 | + switch ( $mode ) { | ||
| 148 | + case 0: | ||
| 149 | + if (Yii::$app->getCache()->get('parser_data') && Yii::$app->getCache()->get('parser_configuration')) { | ||
| 150 | + $data = json_decode(Yii::$app->getCache()->get('parser_data'), true); | ||
| 151 | + $configuration = unserialize(Yii::$app->getCache()->get('parser_configuration')); | ||
| 152 | + } else { | ||
| 153 | + throw new \ErrorException('Ошибка кеша'); | ||
| 154 | + } | ||
| 155 | + break; | ||
| 156 | + | ||
| 157 | + case 1: | ||
| 158 | + Yii::$app->getCache()->set('parser_data', json_encode($data), 1800); | ||
| 159 | + // сохраняем в кеш модель - в ней настройки для дальнейшей обработки данных | ||
| 160 | + Yii::$app->getCache()->set('parser_configuration', serialize($configuration), 1800); | ||
| 161 | + break; | ||
| 162 | + | ||
| 163 | + default: | ||
| 164 | + if( Yii::$app->getCache()->exists('parser_data') ) | ||
| 165 | + Yii::$app->getCache()->delete('parser_data'); | ||
| 166 | + | ||
| 167 | + if( Yii::$app->getCache()->exists('parser_configuration') ) | ||
| 168 | + Yii::$app->getCache()->delete('parser_configuration'); | ||
| 169 | + } | ||
| 170 | + | ||
| 171 | + } | ||
| 140 | } | 172 | } |
| 141 | \ No newline at end of file | 173 | \ No newline at end of file |
backend/controllers/CrossingUploadController.php
| @@ -82,7 +82,7 @@ class CrossingUploadController extends BaseController | @@ -82,7 +82,7 @@ class CrossingUploadController extends BaseController | ||
| 82 | //запускаем парсинг | 82 | //запускаем парсинг |
| 83 | $data = $model->readFile(); | 83 | $data = $model->readFile(); |
| 84 | // сохраняем в кеш отпарсенные даные | 84 | // сохраняем в кеш отпарсенные даные |
| 85 | - $this->cacheHandler( 1, $data, $model ); | 85 | + $this->parserCacheHandler( 1, $data, $model ); |
| 86 | } else if (Yii::$app->getCache()->get('parser_data')) { | 86 | } else if (Yii::$app->getCache()->get('parser_data')) { |
| 87 | $data = json_decode(Yii::$app->getCache()->get('parser_data'), true); | 87 | $data = json_decode(Yii::$app->getCache()->get('parser_data'), true); |
| 88 | } | 88 | } |
| @@ -128,7 +128,7 @@ class CrossingUploadController extends BaseController | @@ -128,7 +128,7 @@ class CrossingUploadController extends BaseController | ||
| 128 | $arr = $model->toArray(); | 128 | $arr = $model->toArray(); |
| 129 | 129 | ||
| 130 | // получим данные из кеша | 130 | // получим данные из кеша |
| 131 | - $this->cacheHandler( 0, $data, $configuration ); | 131 | + $this->parserCacheHandler( 0, $data, $configuration ); |
| 132 | 132 | ||
| 133 | // соотнесем отпарсенные данные с соответствием полученным от пользователя | 133 | // соотнесем отпарсенные данные с соответствием полученным от пользователя |
| 134 | // для этого преобразуем массив отпарсенных данных - назначим ключи согласно соответствию | 134 | // для этого преобразуем массив отпарсенных данных - назначим ключи согласно соответствию |
| @@ -149,18 +149,17 @@ class CrossingUploadController extends BaseController | @@ -149,18 +149,17 @@ class CrossingUploadController extends BaseController | ||
| 149 | 149 | ||
| 150 | if ( $crosses_model->ManualInsertWithIgnore( $data ) ) { | 150 | if ( $crosses_model->ManualInsertWithIgnore( $data ) ) { |
| 151 | 151 | ||
| 152 | - Yii::$app->session->setFlash( $type_msg, $msg ); | ||
| 153 | - | ||
| 154 | // очистим кеш | 152 | // очистим кеш |
| 155 | - $this->cacheHandler( 2 ); | 153 | + $this->parserCacheHandler( 2 ); |
| 154 | + | ||
| 155 | + if ( file_exists($configuration['file_path']) ) | ||
| 156 | + unlink( $configuration['file_path'] ); | ||
| 156 | 157 | ||
| 157 | - if (file_exists($configuration['file_path'])) | ||
| 158 | - unlink($configuration['file_path']); | 158 | + Yii::$app->session->setFlash( $type_msg, $msg ); |
| 159 | return $this->render('index', ['model' => $configuration]); | 159 | return $this->render('index', ['model' => $configuration]); |
| 160 | 160 | ||
| 161 | } | 161 | } |
| 162 | 162 | ||
| 163 | - | ||
| 164 | } else { | 163 | } else { |
| 165 | // не прошла валидация формы загрузки файлов | 164 | // не прошла валидация формы загрузки файлов |
| 166 | $errors_str = ''; | 165 | $errors_str = ''; |
| @@ -212,39 +211,6 @@ class CrossingUploadController extends BaseController | @@ -212,39 +211,6 @@ class CrossingUploadController extends BaseController | ||
| 212 | 211 | ||
| 213 | } | 212 | } |
| 214 | 213 | ||
| 215 | - /** | ||
| 216 | - * @param $mode - int: 0 - fetch from cache, - 1 - put in cache, <2 - delete from cache | ||
| 217 | - * @param $data - array | ||
| 218 | - * @param $configuration - array | ||
| 219 | - * @throws \ErrorException | ||
| 220 | - */ | ||
| 221 | - protected function cacheHandler( $mode, &$data = [], &$configuration = [] ){ | ||
| 222 | - switch ( $mode ) { | ||
| 223 | - case 0: | ||
| 224 | - if (Yii::$app->getCache()->get('parser_data') && Yii::$app->getCache()->get('parser_configuration')) { | ||
| 225 | - $data = json_decode(Yii::$app->getCache()->get('parser_data'), true); | ||
| 226 | - $configuration = unserialize(Yii::$app->getCache()->get('parser_configuration')); | ||
| 227 | - } else { | ||
| 228 | - throw new \ErrorException('Ошибка кеша'); | ||
| 229 | - } | ||
| 230 | - break; | ||
| 231 | - | ||
| 232 | - case 1: | ||
| 233 | - Yii::$app->getCache()->set('parser_data', json_encode($data), 1800); | ||
| 234 | - // сохраняем в кеш модель - в ней настройки для дальнейшей обработки данных | ||
| 235 | - Yii::$app->getCache()->set('parser_configuration', serialize($configuration), 1800); | ||
| 236 | - break; | ||
| 237 | - | ||
| 238 | - default: | ||
| 239 | - if( Yii::$app->getCache()->exists('parser_data') ) | ||
| 240 | - Yii::$app->getCache()->delete('parser_data'); | ||
| 241 | - | ||
| 242 | - if( Yii::$app->getCache()->exists('parser_configuration') ) | ||
| 243 | - Yii::$app->getCache()->delete('parser_configuration'); | ||
| 244 | - } | ||
| 245 | - | ||
| 246 | - } | ||
| 247 | - | ||
| 248 | protected function reverseCrosses ( $data ) | 214 | protected function reverseCrosses ( $data ) |
| 249 | { | 215 | { |
| 250 | // для доп массива обратных строк | 216 | // для доп массива обратных строк |
backend/controllers/ParserController.php
| @@ -72,59 +72,26 @@ class ParserController extends BaseController | @@ -72,59 +72,26 @@ class ParserController extends BaseController | ||
| 72 | 72 | ||
| 73 | public function actionResults($mode = 0) | 73 | public function actionResults($mode = 0) |
| 74 | { | 74 | { |
| 75 | - $model = new UploadFileParsingForm(['mode' => $mode]); | 75 | + $model = new UploadFileParsingForm( ['mode' => $mode] ); |
| 76 | $data = []; | 76 | $data = []; |
| 77 | - if ($model->load(Yii::$app->request->post())) { | 77 | + if ( $model->load(Yii::$app->request->post()) ) { |
| 78 | $model->file = UploadedFile::getInstance($model, 'file'); | 78 | $model->file = UploadedFile::getInstance($model, 'file'); |
| 79 | - // первый проход - валидируем, сохраняем файл, ложим в кеш (для ручной загрузки) отпарсенные данные и параметры модели (потом при записи в базу данных они пригодятся) | ||
| 80 | - if ($model->validate()) { | ||
| 81 | - // запишем дату загрузки файла в таблицу файлов поставщика (ImportersFiles) | ||
| 82 | - $files_model = new ImportersFiles(); | ||
| 83 | - // id поставщика получим из конфигурации | ||
| 84 | - $files_model->load(['ImportersFiles' => $model->toArray()]); | ||
| 85 | - try { | ||
| 86 | - $files_model->save(); | ||
| 87 | - } catch (ErrorException $e) { | ||
| 88 | - throw $e; | ||
| 89 | - } | ||
| 90 | - // получим id только что записанной записи - его запишем в название файла | ||
| 91 | - $model->record_id = $files_model->find() | ||
| 92 | - ->where(['importer_id' => $files_model->importer_id]) | ||
| 93 | - ->orderBy(['id' => SORT_DESC]) | ||
| 94 | - ->one() | ||
| 95 | - ->id; | ||
| 96 | - | ||
| 97 | - $file_name = $model->record_id . '.' . $model->file->extension; | ||
| 98 | - | ||
| 99 | - if ($model->mode) { | ||
| 100 | - $model->file_path = Yii::getAlias('@temp_upload') . '/' . $file_name; | ||
| 101 | - } else { | ||
| 102 | - $model->file_path = Yii::getAlias('@manual_upload') . '/' . $file_name; | ||
| 103 | - } | ||
| 104 | - | ||
| 105 | - $model->file->saveAs($model->file_path); | 79 | + // первый проход - валидируем, |
| 80 | + // сохраняем файл, | ||
| 81 | + // ложим в кеш (для ручной загрузки) отпарсенные данные и параметры модели | ||
| 82 | + // (потом при записи в базу данных они пригодятся) | ||
| 83 | + if ( $model->validate() ) { | ||
| 84 | + // сохраним файл и создадим модель - ImportersFiles | ||
| 85 | + $files_model = $this->saveParserFile($model); | ||
| 106 | // для авто загрузки, обработка завершена | 86 | // для авто загрузки, обработка завершена |
| 107 | - if ($model->mode) { | 87 | + if ( $model->mode ) { |
| 108 | $model->success = true; | 88 | $model->success = true; |
| 109 | - | ||
| 110 | return $this->render('index', ['model' => $model]); | 89 | return $this->render('index', ['model' => $model]); |
| 111 | } | 90 | } |
| 112 | 91 | ||
| 113 | // === ручная загрузка =========== | 92 | // === ручная загрузка =========== |
| 114 | //запускаем парсинг | 93 | //запускаем парсинг |
| 115 | - // доп. опции для парсера | ||
| 116 | - $options = ['converter_conf' => | ||
| 117 | - ['importer_id' => $files_model->importer_id] | ||
| 118 | - ]; | ||
| 119 | - | ||
| 120 | - if( ! $model->action ) // обработка с кастомным разделителем | ||
| 121 | - $options['$delimiter'] = $model->delimiter; | ||
| 122 | - | ||
| 123 | - $data = $model->readFile( $options ); | ||
| 124 | - // сохраняем в кеш отпарсенные даные | ||
| 125 | - Yii::$app->getCache()->set('parser_data', json_encode($data), 1800); | ||
| 126 | - // сохраняем в кеш модель - в ней настройки для дальнейшей обработки данных | ||
| 127 | - Yii::$app->getCache()->set('parser_configuration', serialize($model), 1800); | 94 | + $data = $this->parseDataFromFile( $files_model, $model ); |
| 128 | 95 | ||
| 129 | } else { | 96 | } else { |
| 130 | // не прошла валидация форма загрузки файлов | 97 | // не прошла валидация форма загрузки файлов |
| @@ -136,7 +103,7 @@ class ParserController extends BaseController | @@ -136,7 +103,7 @@ class ParserController extends BaseController | ||
| 136 | $model->throwStringErrorException(); | 103 | $model->throwStringErrorException(); |
| 137 | } | 104 | } |
| 138 | // листаем пагинатором, или повторно вызываем - считываем из кеша отпрасенные данные | 105 | // листаем пагинатором, или повторно вызываем - считываем из кеша отпрасенные данные |
| 139 | - } else if (Yii::$app->getCache()->get('parser_data')) { | 106 | + } else if ( Yii::$app->getCache()->get('parser_data') ) { |
| 140 | 107 | ||
| 141 | $data = json_decode(Yii::$app->getCache()->get('parser_data'), true); | 108 | $data = json_decode(Yii::$app->getCache()->get('parser_data'), true); |
| 142 | 109 | ||
| @@ -180,12 +147,7 @@ class ParserController extends BaseController | @@ -180,12 +147,7 @@ class ParserController extends BaseController | ||
| 180 | $arr = $model->toArray(); | 147 | $arr = $model->toArray(); |
| 181 | 148 | ||
| 182 | // получим данные из кеша | 149 | // получим данные из кеша |
| 183 | - if (Yii::$app->getCache()->get('parser_data') && Yii::$app->getCache()->get('parser_configuration')) { | ||
| 184 | - $data = json_decode(Yii::$app->getCache()->get('parser_data'), true); | ||
| 185 | - $configuration = unserialize(Yii::$app->getCache()->get('parser_configuration')); | ||
| 186 | - } else { | ||
| 187 | - throw new \ErrorException('Ошибка кеша'); | ||
| 188 | - } | 150 | + $this->parserCacheHandler( 0, $data, $configuration ); |
| 189 | 151 | ||
| 190 | // соотнесем отпарсенные данные с соответсивем полученным от пользователя | 152 | // соотнесем отпарсенные данные с соответсивем полученным от пользователя |
| 191 | // для этого преобразуем массив отпарсенных данных - назначим ключи согласно соответствию | 153 | // для этого преобразуем массив отпарсенных данных - назначим ключи согласно соответствию |
| @@ -198,14 +160,12 @@ class ParserController extends BaseController | @@ -198,14 +160,12 @@ class ParserController extends BaseController | ||
| 198 | $writer->setMode(0); //web-режим | 160 | $writer->setMode(0); //web-режим |
| 199 | if ( $writer->writePriceToDB() ) { | 161 | if ( $writer->writePriceToDB() ) { |
| 200 | 162 | ||
| 201 | - $configuration['success'] = true; | ||
| 202 | - // все прошло успешно - очищаем кеш | ||
| 203 | - Yii::$app->getCache()->delete('parser_data'); | ||
| 204 | - Yii::$app->getCache()->delete('parser_configuration'); | 163 | + $this->parserCacheHandler( 2 ); |
| 205 | 164 | ||
| 206 | if( file_exists($configuration['file_path']) ) | 165 | if( file_exists($configuration['file_path']) ) |
| 207 | unlink($configuration['file_path']); | 166 | unlink($configuration['file_path']); |
| 208 | 167 | ||
| 168 | + Yii::$app->session->setFlash( $writer->getValidatedTypeMsg(), $writer->getValidatedMsg() ); | ||
| 209 | return $this->render('index', ['model' => $configuration]); | 169 | return $this->render('index', ['model' => $configuration]); |
| 210 | 170 | ||
| 211 | }; | 171 | }; |
| @@ -291,5 +251,53 @@ class ParserController extends BaseController | @@ -291,5 +251,53 @@ class ParserController extends BaseController | ||
| 291 | } | 251 | } |
| 292 | 252 | ||
| 293 | 253 | ||
| 254 | + /** | ||
| 255 | + * сохраняет файл на диск и регистрирует в ImportersFiles | ||
| 256 | + * @param $model - модель с настройками | ||
| 257 | + * @return ImportersFiles | ||
| 258 | + * @throws ErrorException | ||
| 259 | + * @throws \Exception | ||
| 260 | + */ | ||
| 261 | + protected function saveParserFile ($model) | ||
| 262 | + { | ||
| 263 | + $files_model = new ImportersFiles(); | ||
| 264 | + // id поставщика получим из конфигурации | ||
| 265 | + $files_model->load(['ImportersFiles' => $model->toArray()]); | ||
| 266 | + try { | ||
| 267 | + $files_model->save(); | ||
| 268 | + } catch (ErrorException $e) { | ||
| 269 | + throw $e; | ||
| 270 | + } | ||
| 271 | + // получим id только что записанной записи - его запишем в название файла | ||
| 272 | + $model->record_id = $files_model->id; | ||
| 273 | + | ||
| 274 | + $file_name = $model->record_id . '.' . $model->file->extension; | ||
| 275 | + | ||
| 276 | + if ($model->mode) { | ||
| 277 | + $model->file_path = Yii::getAlias('@temp_upload') . '/' . $file_name; | ||
| 278 | + } else { | ||
| 279 | + $model->file_path = Yii::getAlias('@manual_upload') . '/' . $file_name; | ||
| 280 | + } | ||
| 281 | + | ||
| 282 | + $model->file->saveAs($model->file_path); | ||
| 283 | + | ||
| 284 | + return $files_model; | ||
| 285 | + } | ||
| 286 | + protected function parseDataFromFile ( $files_model, $model ) | ||
| 287 | + { | ||
| 288 | + // доп. опции для парсера | ||
| 289 | + $options = ['converter_conf' => | ||
| 290 | + ['importer_id' => $files_model->importer_id] | ||
| 291 | + ]; | ||
| 292 | + | ||
| 293 | + if( ! $model->action ) // обработка с кастомным разделителем | ||
| 294 | + $options['$delimiter'] = $model->delimiter; | ||
| 295 | + | ||
| 296 | + $data = $model->readFile( $options ); | ||
| 297 | + // сохраняем в кеш отпарсенные даные | ||
| 298 | + $this->parserCacheHandler( 1, $data, $model ); | ||
| 299 | + | ||
| 300 | + return $data; | ||
| 301 | + } | ||
| 294 | 302 | ||
| 295 | } | 303 | } |
backend/views/crossing-upload/index.php
| @@ -20,14 +20,8 @@ use yii\helpers\ArrayHelper; | @@ -20,14 +20,8 @@ use yii\helpers\ArrayHelper; | ||
| 20 | </div> | 20 | </div> |
| 21 | 21 | ||
| 22 | <?php ActiveForm::end(); | 22 | <?php ActiveForm::end(); |
| 23 | - Html::tag('br'); | ||
| 24 | - if ($msg = \Yii::$app->session->getFlash('success')) | ||
| 25 | - { | ||
| 26 | - echo Html::tag('p', $msg ,['class'=>'bg-success']); | ||
| 27 | - } elseif ($msg = \Yii::$app->session->getFlash('warning')) | ||
| 28 | - { | ||
| 29 | - echo Html::tag('p', $msg, ['class' => 'bg-warning']); | ||
| 30 | - } | 23 | + // подключим шаблон сообщения |
| 24 | + echo $this->render('../templates/parser_massage'); | ||
| 31 | ?> | 25 | ?> |
| 32 | </div> | 26 | </div> |
| 33 | </div> | 27 | </div> |
backend/views/parser/index.php
| @@ -20,9 +20,6 @@ if ( $model->mode ) { | @@ -20,9 +20,6 @@ if ( $model->mode ) { | ||
| 20 | if (!$model->action) { | 20 | if (!$model->action) { |
| 21 | $model->action = 1; | 21 | $model->action = 1; |
| 22 | } | 22 | } |
| 23 | - if ($model->success) { // вернулись после успешной загрузки данного файла | ||
| 24 | - echo Html::tag('h3', 'Файл успешно загружен',['class'=>'bg-success']); | ||
| 25 | - } | ||
| 26 | ?> | 23 | ?> |
| 27 | <h3>Загрузка прайсов поставщиков</h3> | 24 | <h3>Загрузка прайсов поставщиков</h3> |
| 28 | 25 | ||
| @@ -49,7 +46,10 @@ if ( $model->mode ) { | @@ -49,7 +46,10 @@ if ( $model->mode ) { | ||
| 49 | <?= Html::submitButton(Yii::t( 'app', $button_label ), ['class' => 'btn btn-primary']) ?> | 46 | <?= Html::submitButton(Yii::t( 'app', $button_label ), ['class' => 'btn btn-primary']) ?> |
| 50 | </div> | 47 | </div> |
| 51 | 48 | ||
| 52 | - <?php ActiveForm::end() ?> | 49 | + <?php ActiveForm::end(); |
| 50 | + // подключим шаблон сообщения | ||
| 51 | + echo $this->render('../templates/parser_massage'); | ||
| 52 | + ?> | ||
| 53 | </div> | 53 | </div> |
| 54 | </div> | 54 | </div> |
| 55 | 55 |
| 1 | +<?php | ||
| 2 | +use yii\helpers\Html; | ||
| 3 | + | ||
| 4 | +Html::tag('br'); | ||
| 5 | +if ( $msg = \Yii::$app->session->getFlash('success') ) { | ||
| 6 | + echo Html::tag('p', $msg, ['class' => 'bg-success']); | ||
| 7 | +} elseif ( $msg = \Yii::$app->session->getFlash('warning') ) { | ||
| 8 | + echo Html::tag('p', $msg, ['class' => 'bg-warning']); | ||
| 9 | +}?> | ||
| 10 | + | ||
| 11 | + | ||
| 12 | + | ||
| 13 | + | ||
| 14 | + |
common/components/PriceWriter.php
| @@ -13,6 +13,7 @@ use yii\base\ErrorException; | @@ -13,6 +13,7 @@ use yii\base\ErrorException; | ||
| 13 | use backend\models\ImportersFiles; | 13 | use backend\models\ImportersFiles; |
| 14 | use backend\models\Importers; | 14 | use backend\models\Importers; |
| 15 | use backend\models\Details; | 15 | use backend\models\Details; |
| 16 | +use common\components\ModelArrayValidator; | ||
| 16 | 17 | ||
| 17 | /** | 18 | /** |
| 18 | * Class PriceWriter | 19 | * Class PriceWriter |
| @@ -37,6 +38,17 @@ class PriceWriter | @@ -37,6 +38,17 @@ class PriceWriter | ||
| 37 | */ | 38 | */ |
| 38 | protected $data; | 39 | protected $data; |
| 39 | 40 | ||
| 41 | + /** | ||
| 42 | + * @var - сообщение валидатора об ошибках | ||
| 43 | + */ | ||
| 44 | + protected $validated_msg; | ||
| 45 | + /** | ||
| 46 | + * @var - тип сообщения валидатора - success, warning | ||
| 47 | + */ | ||
| 48 | + protected $validated_type_msg; | ||
| 49 | + | ||
| 50 | + | ||
| 51 | + | ||
| 40 | function __construct() | 52 | function __construct() |
| 41 | { | 53 | { |
| 42 | set_time_limit(300); | 54 | set_time_limit(300); |
| @@ -66,6 +78,21 @@ class PriceWriter | @@ -66,6 +78,21 @@ class PriceWriter | ||
| 66 | $this->data = $data; | 78 | $this->data = $data; |
| 67 | } | 79 | } |
| 68 | 80 | ||
| 81 | + /** | ||
| 82 | + * @return mixed | ||
| 83 | + */ | ||
| 84 | + public function getValidatedMsg() | ||
| 85 | + { | ||
| 86 | + return $this->validated_msg; | ||
| 87 | + } | ||
| 88 | + | ||
| 89 | + /** | ||
| 90 | + * @return mixed | ||
| 91 | + */ | ||
| 92 | + public function getValidatedTypeMsg() | ||
| 93 | + { | ||
| 94 | + return $this->validated_type_msg; | ||
| 95 | + } | ||
| 69 | 96 | ||
| 70 | 97 | ||
| 71 | public function writePriceToDB() | 98 | public function writePriceToDB() |
| @@ -81,44 +108,78 @@ class PriceWriter | @@ -81,44 +108,78 @@ class PriceWriter | ||
| 81 | throw new \ErrorException(implode(', ', $files_model->getErrors())); | 108 | throw new \ErrorException(implode(', ', $files_model->getErrors())); |
| 82 | } | 109 | } |
| 83 | 110 | ||
| 84 | - // 2. запишем полученные данные в таблицу товаров (Details) | ||
| 85 | - $details_model = new Details(); | 111 | + // 2. конвертируем данные |
| 86 | // только для ручной загрузки, в авто режиме все делает конвертер при первом же проходе (в процессе парсинга) | 112 | // только для ручной загрузки, в авто режиме все делает конвертер при первом же проходе (в процессе парсинга) |
| 87 | - if ($this->mode == 0) { | ||
| 88 | - // преобразуем числовые значения | ||
| 89 | - foreach ($this->data as &$row) { | ||
| 90 | - if (isset($row['PRICE'])) | ||
| 91 | - $row['PRICE'] = \Yii::$app->converter->convertTo('float', $row['PRICE']); | ||
| 92 | - | ||
| 93 | - if (isset($row['BOX'])) | ||
| 94 | - $row['BOX'] = \Yii::$app->converter->convertTo('integer', $row['BOX']); | ||
| 95 | - // присвоим полный артикул | ||
| 96 | - | ||
| 97 | - if (isset($row['ARTICLE'])) { | ||
| 98 | - | ||
| 99 | - $row['FULL_ARTICLE'] = $row['ARTICLE']; | ||
| 100 | - | ||
| 101 | - if ((int)$this->configuration['delete_prefix']) { | ||
| 102 | - $row = \Yii::$app->converter->convertTo('Article', $row, ['importer_id' => $this->configuration['importer_id']]); | ||
| 103 | - } else { | ||
| 104 | - if (isset($row['ARTICLE'])) | ||
| 105 | - $row['ARTICLE'] = \Yii::$app->converter->convertTo('Article', $row['ARTICLE']); | ||
| 106 | - } | ||
| 107 | - } | 113 | + if ( $this->mode == 0 ) { |
| 114 | + // преобразуем значения перед записью в БД | ||
| 115 | + $this->convertDataByConfiguration(); | ||
| 108 | 116 | ||
| 109 | - if (isset($row['ADD_BOX'])) | ||
| 110 | - $row['ADD_BOX'] = \Yii::$app->converter->convertTo('integer', $row['ADD_BOX']); | 117 | + } |
| 118 | + //3. провалидируем полученные данные моделью - Details | ||
| 119 | + $details_model = $this->validateByDetailsModel(); | ||
| 111 | 120 | ||
| 112 | - // проверим все ли обязательные колонки были указаны пользователем | ||
| 113 | - $details_model->load(['Details' => $row]); | ||
| 114 | - if (!$details_model->validate()) | ||
| 115 | - $details_model->throwStringErrorException(key($this->data)); | 121 | + //4. дополним данные значением импортера и даты обновления цены |
| 122 | + $this->data = CustomArrayHelper::addColumns($this->data, ['IMPORT_ID' => $this->configuration['importer_id'], 'timestamp' => $update_date]); | ||
| 116 | 123 | ||
| 124 | + //5. запишем данные в связанные таблицы | ||
| 125 | + $this->writePriceInTransaction($details_model, $files_model, $update_date); | ||
| 126 | + | ||
| 127 | + return true; | ||
| 128 | + } | ||
| 129 | + | ||
| 130 | + public function deletePriceFromDB() | ||
| 131 | + { | ||
| 132 | + $importer_id = ''; | ||
| 133 | + $update_date = ''; | ||
| 134 | + | ||
| 135 | + if (isset($this->configuration['importer_id'])) | ||
| 136 | + $importer_id = $this->configuration['importer_id']; | ||
| 137 | + | ||
| 138 | + if (isset($this->configuration['update_date'])) | ||
| 139 | + $update_date = $this->configuration['update_date']; | ||
| 140 | + | ||
| 141 | + if (!$importer_id) { | ||
| 142 | + throw new \ErrorException('Не указан поставщик прайса для удаления'); | ||
| 143 | + } elseif (!$update_date) { | ||
| 144 | + throw new \ErrorException('Не указана дата загрузки прайса для удаления'); | ||
| 145 | + } | ||
| 146 | + | ||
| 147 | + $this->deletePriceInTransaction( $importer_id, $update_date ); | ||
| 148 | + | ||
| 149 | + return true; | ||
| 150 | + } | ||
| 151 | + | ||
| 152 | + /** | ||
| 153 | + * ковертирует отпарсенные данные конвертером по конфигурации | ||
| 154 | + */ | ||
| 155 | + protected function convertDataByConfiguration () | ||
| 156 | + { | ||
| 157 | + foreach ($this->data as &$row) { | ||
| 158 | + if (isset($row['PRICE'])) | ||
| 159 | + $row['PRICE'] = \Yii::$app->converter->convertTo('float', $row['PRICE']); | ||
| 160 | + | ||
| 161 | + if (isset($row['BOX'])) | ||
| 162 | + $row['BOX'] = \Yii::$app->converter->convertTo('integer', $row['BOX']); | ||
| 163 | + // присвоим полный артикул | ||
| 164 | + | ||
| 165 | + if (isset($row['ARTICLE'])) { | ||
| 166 | + | ||
| 167 | + $row['FULL_ARTICLE'] = $row['ARTICLE']; | ||
| 168 | + | ||
| 169 | + if ((int)$this->configuration['delete_prefix']) { | ||
| 170 | + $row = \Yii::$app->converter->convertTo('Article', $row, ['importer_id' => $this->configuration['importer_id']]); | ||
| 171 | + } else { | ||
| 172 | + if (isset($row['ARTICLE'])) | ||
| 173 | + $row['ARTICLE'] = \Yii::$app->converter->convertTo('Article', $row['ARTICLE']); | ||
| 174 | + } | ||
| 117 | } | 175 | } |
| 176 | + | ||
| 177 | + if (isset($row['ADD_BOX'])) | ||
| 178 | + $row['ADD_BOX'] = \Yii::$app->converter->convertTo('integer', $row['ADD_BOX']); | ||
| 118 | } | 179 | } |
| 180 | + } | ||
| 119 | 181 | ||
| 120 | - // дополним данные значением импортера и даты обновления цены | ||
| 121 | - $this->data = CustomArrayHelper::addColumns($this->data, ['IMPORT_ID' => $this->configuration['importer_id'], 'timestamp' => $update_date]); | 182 | + protected function writePriceInTransaction($details_model, $files_model, $update_date){ |
| 122 | $transaction = \Yii::$app->db->beginTransaction(); | 183 | $transaction = \Yii::$app->db->beginTransaction(); |
| 123 | try { | 184 | try { |
| 124 | 185 | ||
| @@ -150,28 +211,9 @@ class PriceWriter | @@ -150,28 +211,9 @@ class PriceWriter | ||
| 150 | throw new \ErrorException($e->getMessage()); | 211 | throw new \ErrorException($e->getMessage()); |
| 151 | } | 212 | } |
| 152 | 213 | ||
| 153 | - | ||
| 154 | - return true; | ||
| 155 | } | 214 | } |
| 156 | 215 | ||
| 157 | - public function deletePriceFromDB() | ||
| 158 | - { | ||
| 159 | - | ||
| 160 | - $importer_id = ''; | ||
| 161 | - $update_date = ''; | ||
| 162 | - | ||
| 163 | - if (isset($this->configuration['importer_id'])) | ||
| 164 | - $importer_id = $this->configuration['importer_id']; | ||
| 165 | - | ||
| 166 | - if (isset($this->configuration['update_date'])) | ||
| 167 | - $update_date = $this->configuration['update_date']; | ||
| 168 | - | ||
| 169 | - if (!$importer_id) { | ||
| 170 | - throw new \ErrorException('Не указан поставщик прайса для удаления'); | ||
| 171 | - } elseif (!$update_date) { | ||
| 172 | - throw new \ErrorException('Не указана дата загрузки прайса для удаления'); | ||
| 173 | - } | ||
| 174 | - | 216 | + protected function deletePriceInTransaction( $importer_id, $update_date ){ |
| 175 | $transaction = \Yii::$app->db->beginTransaction(); | 217 | $transaction = \Yii::$app->db->beginTransaction(); |
| 176 | try { | 218 | try { |
| 177 | // 1. удалим из таблицы файлов поставщика (ImportersFiles) | 219 | // 1. удалим из таблицы файлов поставщика (ImportersFiles) |
| @@ -184,8 +226,8 @@ class PriceWriter | @@ -184,8 +226,8 @@ class PriceWriter | ||
| 184 | 226 | ||
| 185 | $last_upload_time = ImportersFiles::find()->where(['importer_id' => $importer_id])->orderBy(['time_start' => SORT_DESC])->one()->time_start; | 227 | $last_upload_time = ImportersFiles::find()->where(['importer_id' => $importer_id])->orderBy(['time_start' => SORT_DESC])->one()->time_start; |
| 186 | 228 | ||
| 187 | - // 2. удалим прайс из таблицы товаров (Details) | ||
| 188 | - $details_model = new Details(); | 229 | + // 2. удалим прайс из таблицы товаров (Details) |
| 230 | + $details_model = new Details(); | ||
| 189 | $conditions = "import_id = {$importer_id} AND timestamp ='$update_date'"; | 231 | $conditions = "import_id = {$importer_id} AND timestamp ='$update_date'"; |
| 190 | 232 | ||
| 191 | $details_model->manualDelete( $conditions ); | 233 | $details_model->manualDelete( $conditions ); |
| @@ -204,8 +246,19 @@ class PriceWriter | @@ -204,8 +246,19 @@ class PriceWriter | ||
| 204 | $transaction->rollBack(); | 246 | $transaction->rollBack(); |
| 205 | throw new \ErrorException($e->getMessage()); | 247 | throw new \ErrorException($e->getMessage()); |
| 206 | } | 248 | } |
| 207 | - | ||
| 208 | - return true; | ||
| 209 | } | 249 | } |
| 210 | 250 | ||
| 251 | + protected function validateByDetailsModel(){ | ||
| 252 | + | ||
| 253 | + $details_model = new Details(); | ||
| 254 | + | ||
| 255 | + $model_validator = new ModelArrayValidator( $details_model ); | ||
| 256 | + $this->data = $model_validator->validate( $this->data ); | ||
| 257 | + $this->validated_msg = $model_validator->getMassage(); | ||
| 258 | + $this->validated_type_msg = $model_validator->hasError() ? 'warning' : 'success'; | ||
| 259 | + | ||
| 260 | + $model_validator->close(); | ||
| 261 | + | ||
| 262 | + return $details_model; | ||
| 263 | + } | ||
| 211 | } | 264 | } |
| 212 | \ No newline at end of file | 265 | \ No newline at end of file |
common/components/parsers/CustomConverter.php
| @@ -23,37 +23,9 @@ class CustomConverter extends Converter | @@ -23,37 +23,9 @@ class CustomConverter extends Converter | ||
| 23 | // присвоим полный артикул | 23 | // присвоим полный артикул |
| 24 | $row['FULL_ARTICLE'] = $row['ARTICLE']; | 24 | $row['FULL_ARTICLE'] = $row['ARTICLE']; |
| 25 | 25 | ||
| 26 | - $details_model = new Details(); | ||
| 27 | - // проверим все ли обязательные колонки были указаны пользователем | ||
| 28 | -// $details_model->load(['Details' => $row]); | ||
| 29 | -// | ||
| 30 | -// if (!$details_model->validate()) { | ||
| 31 | -// $errors = ''; | ||
| 32 | -// foreach ($details_model->errors as $key => $arr_errors) { | ||
| 33 | -// $errors .= "Аттрибут $key - " . implode(' , ', $arr_errors); | ||
| 34 | -// } | ||
| 35 | -// throw new \ErrorException($errors); | ||
| 36 | -// } | ||
| 37 | - | ||
| 38 | - | ||
| 39 | return $row; | 26 | return $row; |
| 40 | } | 27 | } |
| 41 | 28 | ||
| 42 | - public static function convertToCrosses( array $row ) | ||
| 43 | - { | ||
| 44 | - $details_model = new DetailsCrosses(); | ||
| 45 | - // проверим все ли обязательные колонки были указаны пользователем | ||
| 46 | - $details_model->load(['DetailsCrosses' => $row]); | ||
| 47 | - | ||
| 48 | - if (!$details_model->validate()) { | ||
| 49 | - $errors = ''; | ||
| 50 | - foreach ($details_model->errors as $key => $arr_errors) { | ||
| 51 | - $errors .= "Аттрибут $key - " . implode(' , ', $arr_errors); | ||
| 52 | - } | ||
| 53 | - throw new \ErrorException($errors); | ||
| 54 | - } | ||
| 55 | - return $row; | ||
| 56 | - } | ||
| 57 | 29 | ||
| 58 | public function ConvertToMultiply( array $row ) | 30 | public function ConvertToMultiply( array $row ) |
| 59 | { | 31 | { |
common/components/parsers/config.php