Commit 2edfb9012d82bbda54aed31d35471d9ab9860d6e

Authored by Mihail
1 parent 1967135b

add PriceWriter and organize error view for users

backend/components/parsers/config.php
1 1 <?php
2 2 return [
3   - 'global' =>
4   - ['ini' => ['upload_max_filesize' => '20M',
5   - 'post_max_size integer' => '30M',
6   - ]],
7 3 'csv' =>
8 4 ['web' =>
9 5 ['class' => 'backend\components\parsers\CustomCsvParser',
... ... @@ -22,6 +18,25 @@
22 18 "ADD_BOX"=> 'В пути',
23 19 "GROUP" => 'Группа RG'
24 20 ],
  21 + 'console' =>
  22 + ['class' => 'backend\components\parsers\CustomCsvParser',
  23 + 'auto_detect_first_line' => true,
  24 + 'converter_conf' => ['class' => ' backend\components\parsers\CustomConverter',
  25 + 'configuration' => ["string" => 'DESCR',
  26 + "float" => 'PRICE',
  27 + "integer" => ['BOX','ADD_BOX']
  28 + ]
  29 + ],],
  30 +
  31 + 'basic_column' => [
  32 + "BRAND" => 'Бренд',
  33 + "ARTICLE"=> 'Артикул',
  34 + "PRICE" => 'Цена',
  35 + "DESCR" => 'Наименование',
  36 + "BOX" => 'Колво',
  37 + "ADD_BOX"=> 'В пути',
  38 + "GROUP" => 'Группа RG'
  39 + ],
25 40 ],
26 41 'xml' =>
27 42 ['web' =>
... ...
backend/config/main.php
... ... @@ -28,7 +28,7 @@ return [
28 28 ],
29 29 ],
30 30 'errorHandler' => [
31   - 'errorAction' => 'site/error',
  31 + 'errorAction' => 'parser/error',
32 32 ],
33 33 'request'=>[
34 34  
... ...
backend/controllers/ParserController.php
... ... @@ -11,13 +11,12 @@ use yii\web\UploadedFile;
11 11 use yii\data\ArrayDataProvider;
12 12 use yii\multiparser\DynamicFormHelper;
13 13 use backend\components\parsers\CustomParserConfigurator;
14   -use backend\models\Details;
15 14 use backend\models\ImportersFiles;
16 15 use backend\models\Importers;
17 16 use yii\base\ErrorException;
18   -use yii\db\Query;
19   -
  17 +use common\components\PriceWriter;
20 18 use common\components\CustomVarDamp;
  19 +use yii\web\ErrorAction;
21 20  
22 21 /**
23 22 * Parser controller
... ... @@ -50,17 +49,6 @@ class ParserController extends BaseController
50 49 ];
51 50 }
52 51  
53   - /**
54   - * @inheritdoc
55   - */
56   - public function actions()
57   - {
58   - return [
59   - 'error' => [
60   - 'class' => 'yii\web\ErrorAction',
61   - ],
62   - ];
63   - }
64 52  
65 53  
66 54 public function actionIndex($mode = 0)
... ... @@ -72,12 +60,13 @@ class ParserController extends BaseController
72 60 return $this->render('index', ['model' => $model]);
73 61 }
74 62  
75   -// public function beforeAction($action)
76   -// {
77   -// if($action->actionMethod ='actionResults'){
78   -// CustomVarDamp::dumpAndDie(phpinfo());
79   -// }
80   -// }
  63 + public function actionError()
  64 + {
  65 + $exception = Yii::$app->errorHandler->exception;
  66 + if ($exception !== null) {
  67 + return $this->render('error', ['message' => $exception->getMessage()]);
  68 + }
  69 + }
81 70  
82 71 public function actionResults($mode = 0)
83 72 {
... ... @@ -94,7 +83,8 @@ class ParserController extends BaseController
94 83 try {
95 84 $files_model->save();
96 85 } catch (ErrorException $e) {
97   - CustomVarDamp::dump($e->getMessage());
  86 + // CustomVarDamp::dump($e->getMessage());
  87 + throw $e;
98 88 }
99 89 // получим id только что записанной записи - его запишем в название файла
100 90 $model->record_id = $files_model->find()
... ... @@ -184,75 +174,29 @@ class ParserController extends BaseController
184 174 $data = json_decode(Yii::$app->getCache()->get('parser_data'), true);
185 175 $configuration = unserialize(Yii::$app->getCache()->get('parser_configuration'));
186 176 } else {
187   - CustomVarDamp::dumpAndDie('Ошибка кеша');
  177 + throw new \ErrorException('Ошибка кеша');
188 178 }
189 179  
190 180 // соотнесем отпарсенные данные с соответсивем полученным от пользователя
191 181 // для этого преобразуем массив отпарсенных данных - назначим ключи согласно соответствию
192 182 $data = \Yii::$app->multiparser->convertToAssocArray($data, $arr, 'attr_');
193 183  
  184 + // запустим специальный класс который запишет данные в таблицы связанные с прайсами
  185 + $writer = new PriceWriter();
  186 + $writer->configuration = $configuration;
  187 + $writer->data = $data;
  188 + $writer->mode = 0; //web-режим
  189 + if ( $writer->writeDataToDB() ) {
194 190  
195   - // 1. запишем дату старта в таблицу файлов поставщика (ImportersFiles)
196   - // id загруженного файла получим из конфигурации
197   - $files_model = ImportersFiles::findOne( $configuration->record_id );
198   -
199   - //$files_model->load(['ImportersFiles' => $configuration->toArray()]);
200   - $update_date = date('Y-m-d H:i:s');
201   - $files_model->time_start = $update_date;
202   - // запишем дату начала загрузки
203   - if (!$files_model->save()) {
204   - CustomVarDamp::dumpAndDie($files_model->getErrors());
205   - }
206   -
207   -
208   - // 2. запишем полученные данные в таблицу товаров (Details)
209   - $details_model = new Details();
210   - // проверим все ли обязательные колонки были указаны пользователем
211   - $details_model->load(['Details' => $data[0]]);
212   - if ($details_model->validate()) {
213   - // дополним данные значением импортера и даты обновления цены
214   - $data = \Yii::$app->multiparser->addColumns($data, ['IMPORT_ID' => $configuration->importer_id, 'timestamp' => $update_date]);
  191 + $configuration['success'] = true;
  192 + // все прошло успешно - очищаем кеш
  193 + Yii::$app->getCache()->delete('parser_data');
  194 + Yii::$app->getCache()->delete('parser_configuration');
215 195  
216   - try {
217   - //@todo add transaction
218   - // попытаемся вставить данные в БД с апдейтом по ключам
219   - $details_model->ManualInsert($data);
220   -
221   - // 3. зафиксируем дату конца загрузки в файлах поставщика
222   -
223   - $files_model->time_end = date('Y-m-d H:i:s');
224   - // CustomVarDamp::dumpAndDie($files_model);
225   - if (!$files_model->save()) {
226   - CustomVarDamp::dumpAndDie($files_model->getErrors());
227   - }
228   -
229   - // 4. зафиксируем дату загрузки в таблице поставщиков
230   - $imp_model = Importers::findOne($configuration['importer_id']);
231   - $imp_model->price_date_update = $update_date;
232   -
233   - if (!$imp_model->save()) {
234   - CustomVarDamp::dumpAndDie($imp_model->getErrors());
235   - }
236   - $configuration['success'] = true;
237   - // все прошло успешно - очищаем кеш
238   - Yii::$app->getCache()->delete('parser_data');
239   - Yii::$app->getCache()->delete('parser_configuration');
240   -
241   - unlink($configuration['file_path']);
242   - return $this->render('index', ['model' => $configuration]);
243   -
244   - } catch (ErrorException $e) {
245   - CustomVarDamp::dump($e->getMessage());
246   - }
247   - }
248   - if ($details_model->hasErrors()) {
249   - $errors_arr = $details_model->getErrors();
250   - foreach ($errors_arr as $error) {
251   - CustomVarDamp::dump(array_values($error));
252   - }
253   -
254   - }
  196 + unlink($configuration['file_path']);
  197 + return $this->render('index', ['model' => $configuration]);
255 198  
  199 + };
256 200  
257 201 }
258 202  
... ...
backend/views/parser/error.php 0 → 100644
  1 +<?php
  2 +
  3 +/* @var $this yii\web\View */
  4 +/* @var $name string */
  5 +/* @var $message string */
  6 +/* @var $exception Exception */
  7 +
  8 +use yii\helpers\Html;
  9 +
  10 +$this->title = $name;
  11 +?>
  12 +<div class="site-error">
  13 +
  14 + <h1><?= Html::encode($this->title) ?></h1>
  15 +
  16 + <div class="alert alert-danger">
  17 + <?= nl2br(Html::encode($message)) ?>
  18 + </div>
  19 +
  20 + <p>
  21 +
  22 + </p>
  23 + <p>
  24 + </p>
  25 +
  26 +</div>
... ...
common/components/PriceWriter.php 0 → 100644
  1 +<?php
  2 +/**
  3 + * Created by PhpStorm.
  4 + * User: Cibermag
  5 + * Date: 30.09.2015
  6 + * Time: 9:34
  7 + */
  8 +
  9 +namespace common\components;
  10 +
  11 +
  12 +use yii\base\ErrorException;
  13 +use backend\models\ImportersFiles;
  14 +use backend\models\Importers;
  15 +use backend\models\Details;
  16 +
  17 +class PriceWriter {
  18 + public $mode;
  19 + public $configuration;
  20 + public $data;
  21 + // public $errors = [];
  22 +
  23 + public function writeDataToDB ()
  24 + {
  25 + // 1. запишем дату старта в таблицу файлов поставщика (ImportersFiles)
  26 + // id загруженного файла получим из конфигурации
  27 + $files_model = ImportersFiles::findOne( $this->configuration->record_id );
  28 +
  29 + //$files_model->load(['ImportersFiles' => $this->configuration->toArray()]);
  30 + $update_date = date('Y-m-d H:i:s');
  31 + $files_model->time_start = $update_date;
  32 + // запишем дату начала загрузки
  33 + if (!$files_model->save()) {
  34 + $this->errors[] = implode( ', ', $files_model->getErrors());
  35 + return false;
  36 + //CustomVarDamp::dumpAndDie($files_model->implode ( ', ', getErrors())());
  37 + }
  38 +
  39 +
  40 + // 2. запишем полученные данные в таблицу товаров (Details)
  41 + $details_model = new Details();
  42 + // преобразуем числовые значения
  43 + foreach ($this->data as &$row) {
  44 + $row['PRICE'] = \Yii::$app->multiparser->convertToFloat($row['PRICE']);
  45 + $row['BOX'] = \Yii::$app->multiparser->convertToInteger($row['BOX']);
  46 + // присвоим полный артикул
  47 + $row['FULL_ARTICLE'] = $row['ARTICLE'];
  48 + if(isset($row['ADD_BOX']))
  49 + $row['ADD_BOX'] = \Yii::$app->multiparser->convertToInteger($row['ADD_BOX']);
  50 +
  51 + // проверим все ли обязательные колонки были указаны пользователем
  52 + $details_model->load(['Details' => $row]);
  53 +
  54 + if (!$details_model->validate())
  55 + break;
  56 + }
  57 +
  58 + if ($details_model->hasErrors()) {
  59 + //@todo предоставить более детальную информацию об ошибке
  60 + throw new \ErrorException('Ошибка записи товаров');
  61 + }
  62 + else{
  63 + // дополним данные значением импортера и даты обновления цены
  64 + $this->data = \Yii::$app->multiparser->addColumns($this->data, ['IMPORT_ID' => $this->configuration->importer_id, 'timestamp' => $update_date]);
  65 +
  66 + try {
  67 + //@todo add transaction
  68 + // попытаемся вставить данные в БД с апдейтом по ключам
  69 + $details_model->ManualInsert($this->data);
  70 +
  71 + // 3. зафиксируем дату конца загрузки в файлах поставщика
  72 +
  73 + $files_model->time_end = date('Y-m-d H:i:s');
  74 + // CustomVarDamp::dumpAndDie($files_model);
  75 + if (!$files_model->save()) {
  76 + throw new \ErrorException(implode( ', ', $files_model->getErrors()));
  77 +// $this->errors[] = $files_model->implode ( ', ', getErrors());
  78 +// return false;
  79 + // CustomVarDamp::dumpAndDie($files_model->implode ( ', ', getErrors())());
  80 + }
  81 +
  82 + // 4. зафиксируем дату загрузки в таблице поставщиков
  83 + $imp_model = Importers::findOne($this->configuration['importer_id']);
  84 + $imp_model->price_date_update = $update_date;
  85 +
  86 + if (!$imp_model->save()) {
  87 +// $this->errors[] = $imp_model->implode ( ', ', getErrors())();
  88 +// return false;
  89 + throw new \ErrorException(implode( ', ', $imp_model->getErrors()));
  90 + // CustomVarDamp::dumpAndDie($imp_model->implode ( ', ', getErrors())());
  91 + }
  92 +
  93 +
  94 + } catch (ErrorException $e) {
  95 + //CustomVarDamp::dump($e->getMessage());
  96 + throw new \ErrorException( $e->getMessage() );
  97 + }
  98 + }
  99 +
  100 +
  101 + return true;
  102 + }
  103 +}
0 104 \ No newline at end of file
... ...
console/controllers/ParserController.php 0 → 100644
  1 +<?php
  2 +/**
  3 + * Created by PhpStorm.
  4 + * User: Cibermag
  5 + * Date: 30.09.2015
  6 + * Time: 14:38
  7 + */
  8 +use yii\console\Controller;
  9 +
  10 +class ParserController extends Controller{
  11 + public function actionParseCSV ()
  12 + {
  13 +
  14 + }
  15 + public function actionParseXML ()
  16 + {
  17 +
  18 + }
  19 + protected function parseFileConsole( $file_path ){
  20 +
  21 + $data = Yii::$app->multiparser->parse( $file_path );
  22 +
  23 + }
  24 +}
0 25 \ No newline at end of file
... ...