Blame view

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