Blame view

backend/controllers/ParserController.php 13.4 KB
3cf42f5c   Mihail   init commit - bas...
1
2
3
4
  <?php
  namespace backend\controllers;
  
  use Yii;
dd60c760   Mihail   add menu and chec...
5
  use yii\data\ActiveDataProvider;
3cf42f5c   Mihail   init commit - bas...
6
  use yii\filters\AccessControl;
693c46cb   Mihail   add base classes ...
7
  use backend\components\base\BaseController;
3cf42f5c   Mihail   init commit - bas...
8
  use yii\filters\VerbFilter;
b13b1c83   Mihail   final version par...
9
  use backend\models\UploadFileParsingForm;
3cf42f5c   Mihail   init commit - bas...
10
  use yii\web\UploadedFile;
fcd9278e   Mihail   parser csv v1
11
  use yii\data\ArrayDataProvider;
74072a2a   Mihail   add first version...
12
  use yii\multiparser\DynamicFormHelper;
474f35bf   Mihail   add DynamicFormHe...
13
  use backend\components\parsers\CustomParserConfigurator;
1967135b   Mihail   adapt project to ...
14
15
  use backend\models\ImportersFiles;
  use backend\models\Importers;
8894c93a   Mihail   add Importers fil...
16
  use yii\base\ErrorException;
2edfb901   Mihail   add PriceWriter a...
17
  use common\components\PriceWriter;
e774f057   Mihail   work with custome...
18
  use common\components\CustomVarDamp;
3cf42f5c   Mihail   init commit - bas...
19
20
  
  /**
b13b1c83   Mihail   final version par...
21
   * Parser controller
3cf42f5c   Mihail   init commit - bas...
22
   */
693c46cb   Mihail   add base classes ...
23
  class ParserController extends BaseController
3cf42f5c   Mihail   init commit - bas...
24
  {
500b481a   Administrator   JSON
25
      public $layout = "/column";
8894c93a   Mihail   add Importers fil...
26
  
3cf42f5c   Mihail   init commit - bas...
27
28
29
30
31
32
33
34
35
36
      /**
       * @inheritdoc
       */
      public function behaviors()
      {
          return [
              'access' => [
                  'class' => AccessControl::className(),
                  'rules' => [
                      [
3cf42f5c   Mihail   init commit - bas...
37
38
39
40
41
                          'allow' => true,
                          'roles' => ['@'],
                      ],
                  ],
              ],
e774f057   Mihail   work with custome...
42
43
44
45
46
47
  //            'verbs' => [
  //                'class' => VerbFilter::className(),
  //                'actions' => [
  //                    'logout' => ['post'],
  //                ],
  //            ],
3cf42f5c   Mihail   init commit - bas...
48
49
50
          ];
      }
  
3cf42f5c   Mihail   init commit - bas...
51
  
500b481a   Administrator   JSON
52
  
9e481998   Mihail   add auto upload a...
53
      public function actionIndex($mode = 0)
3cf42f5c   Mihail   init commit - bas...
54
      {
77422ce3   Mihail   edit upload form
55
          $model = new UploadFileParsingForm();
9e481998   Mihail   add auto upload a...
56
57
          // установим режим, 0 - ручная загрузка, 1 - автозагрузка
          $model->mode = $mode;
9d57a9ea   Mihail   try organize ini ...
58
          //CustomVarDamp::dumpAndDie(phpinfo());
500b481a   Administrator   JSON
59
60
61
          return $this->render('index', ['model' => $model]);
      }
  
2edfb901   Mihail   add PriceWriter a...
62
63
64
65
66
67
68
      public function actionError()
      {
          $exception = Yii::$app->errorHandler->exception;
          if ($exception !== null) {
              return $this->render('error', ['message' => $exception->getMessage()]);
          }
      }
9d57a9ea   Mihail   try organize ini ...
69
  
9e481998   Mihail   add auto upload a...
70
      public function actionResults($mode = 0)
8894c93a   Mihail   add Importers fil...
71
      {
9e481998   Mihail   add auto upload a...
72
          $model = new UploadFileParsingForm(['mode' => $mode]);
474f35bf   Mihail   add DynamicFormHe...
73
          $data = [];
b13b1c83   Mihail   final version par...
74
          if ($model->load(Yii::$app->request->post())) {
3cf42f5c   Mihail   init commit - bas...
75
              $model->file = UploadedFile::getInstance($model, 'file');
9e481998   Mihail   add auto upload a...
76
              // первый проход - валидируем, сохраняем файл, ложим в кеш (для ручной загрузки) отпарсенные данные и параметры модели (потом при записи в базу данных они пригодятся)
3663f570   Mihail   draft commit
77
              if ($model->validate()) {
9e481998   Mihail   add auto upload a...
78
                  // запишем дату загрузки файла в таблицу файлов поставщика (ImportersFiles)
1967135b   Mihail   adapt project to ...
79
                  $files_model = new ImportersFiles();
9e481998   Mihail   add auto upload a...
80
                  // id поставщика получим из конфигурации
1967135b   Mihail   adapt project to ...
81
                  $files_model->load(['ImportersFiles' => $model->toArray()]);
9e481998   Mihail   add auto upload a...
82
83
84
                  try {
                      $files_model->save();
                  } catch (ErrorException  $e) {
2edfb901   Mihail   add PriceWriter a...
85
86
                     // CustomVarDamp::dump($e->getMessage());
                      throw $e;
9e481998   Mihail   add auto upload a...
87
88
                  }
                  // получим id только что записанной записи - его запишем в название файла
01746976   Mihail   fix errors with w...
89
                  $model->record_id = $files_model->find()
9e481998   Mihail   add auto upload a...
90
91
92
93
94
                      ->where(['importer_id' => $files_model->importer_id])
                      ->orderBy(['id' => SORT_DESC])
                      ->one()
                      ->id;
  
01746976   Mihail   fix errors with w...
95
                  $file_name = $model->record_id . '.' . $model->file->extension;
9e481998   Mihail   add auto upload a...
96
97
98
99
100
101
  
                  if ($model->mode) {
                      $model->file_path = Yii::getAlias('@auto_upload') . '/' . $file_name;
                  } else {
                      $model->file_path = Yii::getAlias('@manual_upload') . '/' . $file_name;
                  }
500b481a   Administrator   JSON
102
  
dd60c760   Mihail   add menu and chec...
103
                  $model->file->saveAs($model->file_path);
9e481998   Mihail   add auto upload a...
104
105
106
107
108
109
110
111
  
                  // для авто загрузки, обработка завершена
                  if ($model->mode) {
                      $model->success = true;
                      return $this->render('index', ['model' => $model]);
                  }
  
                  // === ручная загрузка ===========
8894c93a   Mihail   add Importers fil...
112
                  //запускаем парсинг
dd60c760   Mihail   add menu and chec...
113
                  $data = $model->readFile();
8894c93a   Mihail   add Importers fil...
114
115
116
117
                  // сохраняем в кеш отпарсенные даные
                  Yii::$app->getCache()->set('parser_data', json_encode($data));
                  // сохраняем в кеш модель - в ней настройки для дальнейшей обработки данных
                  Yii::$app->getCache()->set('parser_configuration', serialize($model));
500b481a   Administrator   JSON
118
  
500b481a   Administrator   JSON
119
  
9e481998   Mihail   add auto upload a...
120
121
122
123
124
125
126
127
              } else {
                  // не прошла валидация форма загрузки файлов
                  //@todo - отправка на страницу ошибок
                  $errors_arr = $model->getErrors();
                  foreach ($errors_arr as $error) {
                      CustomVarDamp::dump(array_values($error));
                  }
                  die;
3cf42f5c   Mihail   init commit - bas...
128
              }
8894c93a   Mihail   add Importers fil...
129
130
              // листаем пагинатором, или повторно вызываем - считываем из кеша отпрасенные данные
          } else if (Yii::$app->getCache()->get('parser_data')) {
500b481a   Administrator   JSON
131
  
8894c93a   Mihail   add Importers fil...
132
              $data = json_decode(Yii::$app->getCache()->get('parser_data'), true);
500b481a   Administrator   JSON
133
  
3cf42f5c   Mihail   init commit - bas...
134
135
          }
  
474f35bf   Mihail   add DynamicFormHe...
136
137
138
139
140
141
142
          $provider = new ArrayDataProvider([
              'allModels' => $data,
              'pagination' => [
                  'pageSize' => 10,
              ],
          ]);
  
8894c93a   Mihail   add Importers fil...
143
144
          //формируем заголовок для пользователя, где он сможет выбрать соответсвие полей (выпадающий список)
          $header_model = DynamicFormHelper::CreateDynamicModel(count($data[0]));
474f35bf   Mihail   add DynamicFormHe...
145
  
474f35bf   Mihail   add DynamicFormHe...
146
147
148
          return $this->render('results',
              ['model' => $data,
                  'header_model' => $header_model,
8894c93a   Mihail   add Importers fil...
149
150
                  // список колонок для выбора
                  'basic_column' => Yii::$app->multiparser->getConfiguration('csv', 'basic_column'),
474f35bf   Mihail   add DynamicFormHe...
151
                  'dataProvider' => $provider]);
3cf42f5c   Mihail   init commit - bas...
152
      }
474f35bf   Mihail   add DynamicFormHe...
153
  
8894c93a   Mihail   add Importers fil...
154
155
      public function actionWrite()
      {
8894c93a   Mihail   add Importers fil...
156
157
158
159
160
161
162
163
          //получим колонки которые выбрал пользователь
          $arr_attributes = Yii::$app->request->post()['DynamicModel'];
          //соберем модель по полученным данным
          $model = DynamicFormHelper::CreateDynamicModel($arr_attributes);
          //добавим правила валидации (колонки должны быть те что указаны в конфиге)
          foreach ($arr_attributes as $key => $value) {
              $model->addRule($key, 'in', ['range' => array_keys(Yii::$app->multiparser->getConfiguration('csv', 'basic_column'))]);
          }
474f35bf   Mihail   add DynamicFormHe...
164
  
8894c93a   Mihail   add Importers fil...
165
166
          // провалидируем выбранные колонки
          if ($model->validate()) {
28253169   Mihail   add converter as ...
167
  
8894c93a   Mihail   add Importers fil...
168
169
              // валидация успешна у нас есть соответсвие колонок, преобразуем в массив данное соответсвие для дальнейшей работы
              $arr = $model->toArray();
aa518ad3   Mihail   finishing with co...
170
  
8894c93a   Mihail   add Importers fil...
171
172
173
174
175
              // получим данные из кеша
              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 {
2edfb901   Mihail   add PriceWriter a...
176
                  throw new \ErrorException('Ошибка кеша');
8894c93a   Mihail   add Importers fil...
177
              }
474f35bf   Mihail   add DynamicFormHe...
178
  
8894c93a   Mihail   add Importers fil...
179
180
181
182
              // соотнесем отпарсенные данные с соответсивем полученным от пользователя
              // для этого преобразуем массив отпарсенных данных - назначим ключи согласно соответствию
              $data = \Yii::$app->multiparser->convertToAssocArray($data, $arr, 'attr_');
  
2edfb901   Mihail   add PriceWriter a...
183
184
185
186
187
188
              // запустим специальный класс который запишет данные в таблицы связанные с прайсами
              $writer = new PriceWriter();
              $writer->configuration = $configuration;
              $writer->data = $data;
              $writer->mode = 0; //web-режим
              if ( $writer->writeDataToDB() ) {
8894c93a   Mihail   add Importers fil...
189
  
2edfb901   Mihail   add PriceWriter a...
190
191
192
193
                  $configuration['success'] = true;
                  // все прошло успешно - очищаем кеш
                  Yii::$app->getCache()->delete('parser_data');
                  Yii::$app->getCache()->delete('parser_configuration');
9e481998   Mihail   add auto upload a...
194
  
2edfb901   Mihail   add PriceWriter a...
195
196
                  unlink($configuration['file_path']);
                  return $this->render('index', ['model' => $configuration]);
8894c93a   Mihail   add Importers fil...
197
  
2edfb901   Mihail   add PriceWriter a...
198
              };
8894c93a   Mihail   add Importers fil...
199
200
201
202
  
          }
  
      }
3cf42f5c   Mihail   init commit - bas...
203
  
9e481998   Mihail   add auto upload a...
204
205
      public function actionAutoUpload()
      {
1967135b   Mihail   adapt project to ...
206
          $query = Importers::find()->where(['active' => true])->orderBy(['price_date_update' => SORT_DESC]);
9e481998   Mihail   add auto upload a...
207
208
209
210
211
212
213
214
215
216
217
  
          $provider = new ActiveDataProvider([
              'query' => $query,
              'pagination' => [
                  'pageSize' => 10,
              ],
          ]);
          return $this->render('check_price',
              [
                  'dataProvider' => $provider]);
      }
9075f464   Mihail   add action and vi...
218
219
220
  
      public function actionServerFiles ()
      {
ae27b007   Mihail   add ajax handler ...
221
          $arr_id_files = [];
9075f464   Mihail   add action and vi...
222
223
224
          // получим список файлов которые ожидают к загрузке
          foreach (glob(Yii::getAlias('@auto_upload') . '/*') as $server_file) {
              $file_id = basename($server_file,".csv");
ae27b007   Mihail   add ajax handler ...
225
              $arr_id_files[] = (int) $file_id;
9075f464   Mihail   add action and vi...
226
          }
93e39994   Mihail   fixed parser and ...
227
          Yii::$app->cache->set( 'files_to_parse',json_encode( $arr_id_files ) );
1967135b   Mihail   adapt project to ...
228
          $query = ImportersFiles::find()->where(['in', 'id', $arr_id_files])->orderBy(['upload_time' => SORT_DESC]);
9075f464   Mihail   add action and vi...
229
230
231
232
233
234
235
236
237
238
239
240
  
          $provider = new ActiveDataProvider([
              'query' => $query,
              'pagination' => [
                  'pageSize' => 10,
              ],
          ]);
          return $this->render('server-files',
              [
                  'dataProvider' => $provider]);
      }
  
ae27b007   Mihail   add ajax handler ...
241
      public function actionDelete ()
9075f464   Mihail   add action and vi...
242
      {
ae27b007   Mihail   add ajax handler ...
243
          if ( Yii::$app->request->isAjax ) {
9075f464   Mihail   add action and vi...
244
  
1967135b   Mihail   adapt project to ...
245
              $files_model = new ImportersFiles();
ae27b007   Mihail   add ajax handler ...
246
247
248
249
250
251
252
              if ( isset(Yii::$app->request->post()['id'] )) {
                  $id = Yii::$app->request->post()['id'];
                  try {
                      $files_model->delete($id);
                      unlink(Yii::getAlias('@auto_upload') . '/' . $id . '.csv' );
  
                      // удалим этот id и из кэша
93e39994   Mihail   fixed parser and ...
253
                     if( $arr_id_files = Yii::$app->cache->get( 'files_to_parse' ) ){
ae27b007   Mihail   add ajax handler ...
254
255
256
257
                         $arr_id_files = json_decode($arr_id_files);
                         if (isset( $arr_id_files[$id] ) ) {
                             unset( $arr_id_files[$id] );
                             // положем уже обновленный массив
93e39994   Mihail   fixed parser and ...
258
                             Yii::$app->cache->set( 'files_to_parse',json_encode( $arr_id_files ) );
ae27b007   Mihail   add ajax handler ...
259
260
261
262
263
                         }
                     }
                      // сообщим скрипту что все ОК
                      echo 1;
                  } catch (ErrorException  $e) {
9075f464   Mihail   add action and vi...
264
  
93e39994   Mihail   fixed parser and ...
265
266
                      //CustomVarDamp::dump($e->getMessage());
                      throw $e;
9075f464   Mihail   add action and vi...
267
  
ae27b007   Mihail   add ajax handler ...
268
269
                  }
              }
9075f464   Mihail   add action and vi...
270
271
          }
  
9075f464   Mihail   add action and vi...
272
      }
93e39994   Mihail   fixed parser and ...
273
274
275
276
277
278
279
280
  
  
  
  
      public function actionParse ()
      {
  //        $comand = "/usr/bin/php -f ".Yii::getAlias('@console') ."/Controllers/ParserController.php";
  //        exec($comand);
7aaeda8e   Mihail   add getKeys from ...
281
  
93e39994   Mihail   fixed parser and ...
282
283
284
          if( $arr_id_files = Yii::$app->cache->get( 'files_to_parse' ) ) {
              $arr_id_files = json_decode( $arr_id_files );
              foreach ( $arr_id_files as $file_name ) {
7aaeda8e   Mihail   add getKeys from ...
285
286
287
288
  
                  $importer_id = ImportersFiles::findOne(['id' => $file_name])->importer_id;
                  $keys = Importers::findOne( ['id' => $importer_id] )->keys;
  
93e39994   Mihail   fixed parser and ...
289
290
                  $file_path = Yii::getAlias('@auto_upload') . '/' . $file_name . '.csv';
                  $config = ['record_id' => $file_name,
7aaeda8e   Mihail   add getKeys from ...
291
292
                      'importer_id' => $importer_id,
                      'parser_config' => ['keys' => $keys,
93e39994   Mihail   fixed parser and ...
293
294
295
296
297
298
299
300
301
                                          'mode' => 'console']
                  ];
                  if( $this->parseFileConsole( $file_path, $config ) ){
                      unlink( $file_path );
                      if (isset( $arr_id_files[$file_path] ) ) {
                          unset($arr_id_files[$file_path]);
                      }
                  } else {
                      // Yii::$app->log->
2d10c44d   Mihail   temp commit - wor...
302
                      // не дошли до конца по этому остатки вернем в кеш
93e39994   Mihail   fixed parser and ...
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
                      Yii::$app->cache->set( 'files_to_parse',json_encode( $arr_id_files ) );
                  }
              }
              if ( !count( $arr_id_files ) ) {
                  Yii::$app->cache->delete( 'files_to_parse' );
              }
          }
  
          return $this->redirect('serverFiles');
      }
  
      protected function parseFileConsole( $file_path, $configuration ){
          $parser_config = [];
          if ( isset( $configuration['parser_config'] ) ) {
              $parser_config = $configuration['parser_config'];
          }
  
          $data = Yii::$app->multiparser->parse( $file_path, $parser_config );
          CustomVarDamp::dumpAndDie($data);
          $writer = new PriceWriter();
          $writer->configuration = $configuration;
          $writer->data = $data;
          $writer->mode = 1; //console-режим
          if ( $writer->writeDataToDB() ){
              //Console::output('It is working');
              return true;
          }
  
          return false;
      }
3cf42f5c   Mihail   init commit - bas...
333
  }