Blame view

backend/controllers/ParserController.php 9.19 KB
58743b31   Mihail   init commit - bas...
1
2
3
4
5
  <?php
  namespace backend\controllers;
  
  use Yii;
  use yii\filters\AccessControl;
54ada04a   Mihail   add base classes ...
6
  use backend\components\base\BaseController;
58743b31   Mihail   init commit - bas...
7
  use yii\filters\VerbFilter;
febcec0b   Mihail   final version par...
8
  use backend\models\UploadFileParsingForm;
58743b31   Mihail   init commit - bas...
9
  use yii\web\UploadedFile;
9bfcfcaf   Mihail   parser csv v1
10
  use yii\data\ArrayDataProvider;
2a7a75b8   Mihail   add first version...
11
  use yii\multiparser\DynamicFormHelper;
7a80e74c   Mihail   add DynamicFormHe...
12
  use backend\components\parsers\CustomParserConfigurator;
d7f6bdbb   Mihail   add Importers fil...
13
14
  use backend\models\Details;
  use backend\models\ImporterFiles;
51514d7d   Mihail   add writing data ...
15
  use backend\models\Importer;
d7f6bdbb   Mihail   add Importers fil...
16
  use yii\base\ErrorException;
2509e17e   Administrator   JSON
17
  
02e174a3   Mihail   work with custome...
18
  use common\components\CustomVarDamp;
58743b31   Mihail   init commit - bas...
19
20
  
  /**
febcec0b   Mihail   final version par...
21
   * Parser controller
58743b31   Mihail   init commit - bas...
22
   */
54ada04a   Mihail   add base classes ...
23
  class ParserController extends BaseController
58743b31   Mihail   init commit - bas...
24
  {
2509e17e   Administrator   JSON
25
      public $layout = "/column";
d7f6bdbb   Mihail   add Importers fil...
26
  
58743b31   Mihail   init commit - bas...
27
28
29
30
31
32
33
34
35
36
      /**
       * @inheritdoc
       */
      public function behaviors()
      {
          return [
              'access' => [
                  'class' => AccessControl::className(),
                  'rules' => [
                      [
d7f6bdbb   Mihail   add Importers fil...
37
                          'actions' => ['index', 'results', 'write'],
58743b31   Mihail   init commit - bas...
38
39
40
41
42
                          'allow' => true,
                          'roles' => ['@'],
                      ],
                  ],
              ],
02e174a3   Mihail   work with custome...
43
44
45
46
47
48
  //            'verbs' => [
  //                'class' => VerbFilter::className(),
  //                'actions' => [
  //                    'logout' => ['post'],
  //                ],
  //            ],
58743b31   Mihail   init commit - bas...
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
          ];
      }
  
      /**
       * @inheritdoc
       */
      public function actions()
      {
          return [
              'error' => [
                  'class' => 'yii\web\ErrorAction',
              ],
          ];
      }
  
2509e17e   Administrator   JSON
64
  
58743b31   Mihail   init commit - bas...
65
66
      public function actionIndex()
      {
5be26bf2   Mihail   edit upload form
67
          $model = new UploadFileParsingForm();
58743b31   Mihail   init commit - bas...
68
  
2509e17e   Administrator   JSON
69
70
71
          return $this->render('index', ['model' => $model]);
      }
  
d7f6bdbb   Mihail   add Importers fil...
72
73
      public function actionResults()
      {
2509e17e   Administrator   JSON
74
          $model = new UploadFileParsingForm();
7a80e74c   Mihail   add DynamicFormHe...
75
          $data = [];
febcec0b   Mihail   final version par...
76
          if ($model->load(Yii::$app->request->post())) {
58743b31   Mihail   init commit - bas...
77
              $model->file = UploadedFile::getInstance($model, 'file');
d7f6bdbb   Mihail   add Importers fil...
78
              // первый проход - валидируем, сохраняем файл, ложим в кеш отпарсенные данные и параметры модели (потом при записи в базу данных они пригодятся)
165348a4   Mihail   draft commit
79
              if ($model->validate()) {
9bfcfcaf   Mihail   parser csv v1
80
                  $filePath = Yii::getAlias('@webroot') . '/uploads/' . $model->file->baseName . '.' . $model->file->extension;
2509e17e   Administrator   JSON
81
  
d7f6bdbb   Mihail   add Importers fil...
82
83
                  $model->file->saveAs($filePath);
                  //запускаем парсинг
2509e17e   Administrator   JSON
84
                  $data = $model->readFile($filePath);
d7f6bdbb   Mihail   add Importers fil...
85
86
87
88
                  // сохраняем в кеш отпарсенные даные
                  Yii::$app->getCache()->set('parser_data', json_encode($data));
                  // сохраняем в кеш модель - в ней настройки для дальнейшей обработки данных
                  Yii::$app->getCache()->set('parser_configuration', serialize($model));
2509e17e   Administrator   JSON
89
  
2509e17e   Administrator   JSON
90
  
58743b31   Mihail   init commit - bas...
91
              }
d7f6bdbb   Mihail   add Importers fil...
92
93
              // листаем пагинатором, или повторно вызываем - считываем из кеша отпрасенные данные
          } else if (Yii::$app->getCache()->get('parser_data')) {
2509e17e   Administrator   JSON
94
  
d7f6bdbb   Mihail   add Importers fil...
95
              $data = json_decode(Yii::$app->getCache()->get('parser_data'), true);
2509e17e   Administrator   JSON
96
  
58743b31   Mihail   init commit - bas...
97
98
          }
  
7a80e74c   Mihail   add DynamicFormHe...
99
100
101
102
103
104
105
          $provider = new ArrayDataProvider([
              'allModels' => $data,
              'pagination' => [
                  'pageSize' => 10,
              ],
          ]);
  
d7f6bdbb   Mihail   add Importers fil...
106
107
          //формируем заголовок для пользователя, где он сможет выбрать соответсвие полей (выпадающий список)
          $header_model = DynamicFormHelper::CreateDynamicModel(count($data[0]));
7a80e74c   Mihail   add DynamicFormHe...
108
  
7a80e74c   Mihail   add DynamicFormHe...
109
110
111
          return $this->render('results',
              ['model' => $data,
                  'header_model' => $header_model,
d7f6bdbb   Mihail   add Importers fil...
112
113
                  // список колонок для выбора
                  'basic_column' => Yii::$app->multiparser->getConfiguration('csv', 'basic_column'),
7a80e74c   Mihail   add DynamicFormHe...
114
                  'dataProvider' => $provider]);
58743b31   Mihail   init commit - bas...
115
      }
7a80e74c   Mihail   add DynamicFormHe...
116
  
d7f6bdbb   Mihail   add Importers fil...
117
118
      public function actionWrite()
      {
d7f6bdbb   Mihail   add Importers fil...
119
120
121
122
123
124
125
126
          //получим колонки которые выбрал пользователь
          $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...
127
  
d7f6bdbb   Mihail   add Importers fil...
128
129
          // провалидируем выбранные колонки
          if ($model->validate()) {
33d902b8   Mihail   add converter as ...
130
  
d7f6bdbb   Mihail   add Importers fil...
131
132
              // валидация успешна у нас есть соответсвие колонок, преобразуем в массив данное соответсвие для дальнейшей работы
              $arr = $model->toArray();
492d8ac1   Mihail   finishing with co...
133
  
d7f6bdbb   Mihail   add Importers fil...
134
135
136
137
138
139
140
              // получим данные из кеша
              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...
141
  
d7f6bdbb   Mihail   add Importers fil...
142
143
144
145
146
              // соотнесем отпарсенные данные с соответсивем полученным от пользователя
              // для этого преобразуем массив отпарсенных данных - назначим ключи согласно соответствию
              $data = \Yii::$app->multiparser->convertToAssocArray($data, $arr, 'attr_');
  
  
51514d7d   Mihail   add writing data ...
147
              // 1. запишем дату старта в таблицу файлов поставщика (ImportersFiles)
d7f6bdbb   Mihail   add Importers fil...
148
149
150
151
152
153
              $files_model = new ImporterFiles();
              // id поставщика получим из конфигурации
              $files_model->load(['ImporterFiles' => $configuration->toArray()]);
              if ($files_model->validate()) {
                  try {
                      $files_model->save();
51514d7d   Mihail   add writing data ...
154
155
156
157
158
159
160
                      $update_date = $files_model->find()
                          ->where(['importer_id' => $files_model->importer_id])
                          ->orderBy(['id' => SORT_DESC])
                          ->one()
                          ->upload_time;
                      $update_date = date('Y-m-d H:i:s',strtotime($update_date));
                     // CustomVarDamp::dumpAndDie(strtotime($update_date));
d7f6bdbb   Mihail   add Importers fil...
161
162
163
164
165
                  } catch (ErrorException  $e) {
                      CustomVarDamp::dump($e->getMessage());
                  }
  
  
51514d7d   Mihail   add writing data ...
166
                  // 2. запишем полученные данные в таблицу товаров (Details)
d7f6bdbb   Mihail   add Importers fil...
167
168
169
170
                  $details_model = new Details('web');
                  // проверим все ли обязательные колонки были указаны пользователем
                  $details_model->load(['Details' => $data[0]]);
                  if ($details_model->validate()) {
51514d7d   Mihail   add writing data ...
171
172
                      // дополним данные значением импортера и даты обновления цены
                      $data = \Yii::$app->multiparser->addColumns( $data, ['IMPORT_ID' => $configuration['importer_id'],'timestamp' => $update_date] );
d7f6bdbb   Mihail   add Importers fil...
173
174
  
                      try {
51514d7d   Mihail   add writing data ...
175
                          //@todo add transaction
d7f6bdbb   Mihail   add Importers fil...
176
177
178
                          // попытаемся вставить данные в БД с апдейтом по ключам
                          $details_model->save($data);
  
51514d7d   Mihail   add writing data ...
179
180
181
                          // 3. зафиксируем дату конца загрузки в файлах поставщика
                          $files_model->time_end = date('Y-m-d H:i:s');
                         // CustomVarDamp::dumpAndDie($files_model);
d7f6bdbb   Mihail   add Importers fil...
182
183
                          $files_model->save();
  
51514d7d   Mihail   add writing data ...
184
185
186
187
188
189
190
191
                          // 4. зафиксируем дату загрузки в таблице поставщиков
                          $imp_model = Importer::findOne( $configuration['importer_id'] );
                          $imp_model->price_date_update = ''.strtotime($update_date);
  
                          if (!$imp_model->save()) {
                              CustomVarDamp::dumpAndDie( $imp_model->getErrors() );
                          }
  
d7f6bdbb   Mihail   add Importers fil...
192
193
194
                          // все прошло успешно - очищаем кеш
                          Yii::$app->getCache()->delete('parser_data');
                          Yii::$app->getCache()->delete('parser_configuration');
51514d7d   Mihail   add writing data ...
195
                          // @todo - Delete the file
d7f6bdbb   Mihail   add Importers fil...
196
197
198
199
200
201
202
203
204
205
206
207
208
  
                          CustomVarDamp::dumpAndDie('!!!');
                      } 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));
                      }
  
                  }
7a80e74c   Mihail   add DynamicFormHe...
209
  
58743b31   Mihail   init commit - bas...
210
  
d7f6bdbb   Mihail   add Importers fil...
211
212
213
214
215
216
              }
  
  
          }
  
      }
58743b31   Mihail   init commit - bas...
217
218
  
  }