Blame view

backend/controllers/ParserController.php 11.2 KB
58743b31   Mihail   init commit - bas...
1
2
3
  <?php
  namespace backend\controllers;
  
c4da20f0   Mihail   temp commit - tes...
4
5
6
  use common\components\archives\ArchiveCreator;
  use common\components\mail\ImapMailReader;
  use common\components\mail\MailAttachmentsSaver;
91fdff80   Mihail   merge with server
7
  use common\components\parsers\MailParser;
58743b31   Mihail   init commit - bas...
8
  use Yii;
2fb5a757   Mihail   add menu and chec...
9
  use yii\data\ActiveDataProvider;
58743b31   Mihail   init commit - bas...
10
  use yii\filters\AccessControl;
54ada04a   Mihail   add base classes ...
11
  use backend\components\base\BaseController;
58743b31   Mihail   init commit - bas...
12
  use yii\filters\VerbFilter;
febcec0b   Mihail   final version par...
13
  use backend\models\UploadFileParsingForm;
58743b31   Mihail   init commit - bas...
14
  use yii\web\UploadedFile;
9bfcfcaf   Mihail   parser csv v1
15
  use yii\data\ArrayDataProvider;
2a7a75b8   Mihail   add first version...
16
  use yii\multiparser\DynamicFormHelper;
942bad48   Mihail   adapt project to ...
17
18
  use backend\models\ImportersFiles;
  use backend\models\Importers;
d7f6bdbb   Mihail   add Importers fil...
19
  use yii\base\ErrorException;
f0dbd829   Mihail   add PriceWriter a...
20
  use common\components\PriceWriter;
02e174a3   Mihail   work with custome...
21
  use common\components\CustomVarDamp;
67adc788   Mihail   add converter int...
22
  use common\components\CustomArrayHelper;
58743b31   Mihail   init commit - bas...
23
24
  
  /**
febcec0b   Mihail   final version par...
25
   * Parser controller
58743b31   Mihail   init commit - bas...
26
   */
54ada04a   Mihail   add base classes ...
27
  class ParserController extends BaseController
58743b31   Mihail   init commit - bas...
28
  {
2509e17e   Administrator   JSON
29
      public $layout = "/column";
d7f6bdbb   Mihail   add Importers fil...
30
  
58743b31   Mihail   init commit - bas...
31
32
33
34
35
36
37
38
39
40
      /**
       * @inheritdoc
       */
      public function behaviors()
      {
          return [
              'access' => [
                  'class' => AccessControl::className(),
                  'rules' => [
                      [
58743b31   Mihail   init commit - bas...
41
42
43
44
45
                          'allow' => true,
                          'roles' => ['@'],
                      ],
                  ],
              ],
d11ec8b2   Mihail   fixed permissions...
46
47
48
49
50
51
  //            'verbs' => [
  //                'class' => VerbFilter::className(),
  //                'actions' => [
  //                    'logout' => ['post'],
  //                ],
  //            ],
58743b31   Mihail   init commit - bas...
52
53
54
          ];
      }
  
58743b31   Mihail   init commit - bas...
55
  
2509e17e   Administrator   JSON
56
  
1fa22312   Mihail   add auto upload a...
57
      public function actionIndex($mode = 0)
58743b31   Mihail   init commit - bas...
58
      {
5be26bf2   Mihail   edit upload form
59
          $model = new UploadFileParsingForm();
1fa22312   Mihail   add auto upload a...
60
61
          // установим режим, 0 - ручная загрузка, 1 - автозагрузка
          $model->mode = $mode;
2509e17e   Administrator   JSON
62
63
64
          return $this->render('index', ['model' => $model]);
      }
  
f0dbd829   Mihail   add PriceWriter a...
65
66
67
68
69
70
71
      public function actionError()
      {
          $exception = Yii::$app->errorHandler->exception;
          if ($exception !== null) {
              return $this->render('error', ['message' => $exception->getMessage()]);
          }
      }
55cc05aa   Mihail   try organize ini ...
72
  
1fa22312   Mihail   add auto upload a...
73
      public function actionResults($mode = 0)
d7f6bdbb   Mihail   add Importers fil...
74
      {
b6247a0e   Mihail   rewrite parser wr...
75
          $model = new UploadFileParsingForm( ['mode' => $mode] );
7a80e74c   Mihail   add DynamicFormHe...
76
          $data = [];
b6247a0e   Mihail   rewrite parser wr...
77
          if ( $model->load(Yii::$app->request->post()) ) {
58743b31   Mihail   init commit - bas...
78
              $model->file = UploadedFile::getInstance($model, 'file');
b6247a0e   Mihail   rewrite parser wr...
79
80
81
82
83
84
85
              // первый проход - валидируем,
              // сохраняем файл,
              // ложим в кеш (для ручной загрузки) отпарсенные данные и параметры модели
              // (потом при записи в базу данных они пригодятся)
              if ( $model->validate() ) {
                  // сохраним файл и создадим модель - ImportersFiles
                  $files_model = $this->saveParserFile($model);
1fa22312   Mihail   add auto upload a...
86
                  // для авто загрузки, обработка завершена
b6247a0e   Mihail   rewrite parser wr...
87
                  if ( $model->mode ) {
1fa22312   Mihail   add auto upload a...
88
                      $model->success = true;
1fa22312   Mihail   add auto upload a...
89
90
91
92
                      return $this->render('index', ['model' => $model]);
                  }
  
                  // === ручная загрузка ===========
d7f6bdbb   Mihail   add Importers fil...
93
                  //запускаем парсинг
b6247a0e   Mihail   rewrite parser wr...
94
                 $data = $this->parseDataFromFile( $files_model, $model );
2509e17e   Administrator   JSON
95
  
1fa22312   Mihail   add auto upload a...
96
97
              } else {
                  // не прошла валидация форма загрузки файлов
c4da20f0   Mihail   temp commit - tes...
98
99
100
101
102
103
  //                $errors_str = '';
  //                foreach ($model->getErrors() as $error) {
  //                    $errors_str .= implode( array_values($error) );
  //                }
  //               throw new ErrorException( $errors_str );
                  $model->throwStringErrorException();
58743b31   Mihail   init commit - bas...
104
              }
d7f6bdbb   Mihail   add Importers fil...
105
              // листаем пагинатором, или повторно вызываем - считываем из кеша отпрасенные данные
b6247a0e   Mihail   rewrite parser wr...
106
          } else if ( Yii::$app->getCache()->get('parser_data') ) {
2509e17e   Administrator   JSON
107
  
d7f6bdbb   Mihail   add Importers fil...
108
              $data = json_decode(Yii::$app->getCache()->get('parser_data'), true);
2509e17e   Administrator   JSON
109
  
58743b31   Mihail   init commit - bas...
110
111
          }
  
7a80e74c   Mihail   add DynamicFormHe...
112
113
114
115
116
117
118
          $provider = new ArrayDataProvider([
              'allModels' => $data,
              'pagination' => [
                  'pageSize' => 10,
              ],
          ]);
  
40cac1b6   Mihail   add delete func i...
119
120
          $last_index = end( array_flip( $data[0] ) );
          $header_counts = $last_index + 1;
d7f6bdbb   Mihail   add Importers fil...
121
          //формируем заголовок для пользователя, где он сможет выбрать соответсвие полей (выпадающий список)
40cac1b6   Mihail   add delete func i...
122
          $header_model = DynamicFormHelper::CreateDynamicModel( $header_counts );
7a80e74c   Mihail   add DynamicFormHe...
123
  
7a80e74c   Mihail   add DynamicFormHe...
124
125
126
          return $this->render('results',
              ['model' => $data,
                  'header_model' => $header_model,
d7f6bdbb   Mihail   add Importers fil...
127
128
                  // список колонок для выбора
                  'basic_column' => Yii::$app->multiparser->getConfiguration('csv', 'basic_column'),
7a80e74c   Mihail   add DynamicFormHe...
129
                  'dataProvider' => $provider]);
58743b31   Mihail   init commit - bas...
130
      }
7a80e74c   Mihail   add DynamicFormHe...
131
  
d7f6bdbb   Mihail   add Importers fil...
132
133
      public function actionWrite()
      {
d7f6bdbb   Mihail   add Importers fil...
134
135
136
137
138
139
140
141
          //получим колонки которые выбрал пользователь
          $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...
142
  
d7f6bdbb   Mihail   add Importers fil...
143
144
          // провалидируем выбранные колонки
          if ($model->validate()) {
33d902b8   Mihail   add converter as ...
145
  
d7f6bdbb   Mihail   add Importers fil...
146
147
              // валидация успешна у нас есть соответсвие колонок, преобразуем в массив данное соответсвие для дальнейшей работы
              $arr = $model->toArray();
492d8ac1   Mihail   finishing with co...
148
  
d7f6bdbb   Mihail   add Importers fil...
149
              // получим данные из кеша
b6247a0e   Mihail   rewrite parser wr...
150
              $this->parserCacheHandler( 0, $data, $configuration );
7a80e74c   Mihail   add DynamicFormHe...
151
  
d7f6bdbb   Mihail   add Importers fil...
152
153
              // соотнесем отпарсенные данные с соответсивем полученным от пользователя
              // для этого преобразуем массив отпарсенных данных - назначим ключи согласно соответствию
67adc788   Mihail   add converter int...
154
              $data = CustomArrayHelper::createAssocArray( $data, $arr , 'attr_' );
d7f6bdbb   Mihail   add Importers fil...
155
  
f0dbd829   Mihail   add PriceWriter a...
156
157
              // запустим специальный класс который запишет данные в таблицы связанные с прайсами
              $writer = new PriceWriter();
edfa67b1   Mihail   add delete price ...
158
159
160
161
              $writer->setConfiguration( $configuration );
              $writer->setData($data);
              $writer->setMode(0); //web-режим
              if ( $writer->writePriceToDB() ) {
d7f6bdbb   Mihail   add Importers fil...
162
  
b6247a0e   Mihail   rewrite parser wr...
163
                  $this->parserCacheHandler( 2 );
1fa22312   Mihail   add auto upload a...
164
  
3be5e214   Mihail   fixed issues with...
165
166
167
                  if( file_exists($configuration['file_path']) )
                      unlink($configuration['file_path']);
  
b6247a0e   Mihail   rewrite parser wr...
168
                  Yii::$app->session->setFlash( $writer->getValidatedTypeMsg(), $writer->getValidatedMsg() );
f0dbd829   Mihail   add PriceWriter a...
169
                  return $this->render('index', ['model' => $configuration]);
d7f6bdbb   Mihail   add Importers fil...
170
  
f0dbd829   Mihail   add PriceWriter a...
171
              };
d7f6bdbb   Mihail   add Importers fil...
172
173
174
175
  
          }
  
      }
58743b31   Mihail   init commit - bas...
176
  
1fa22312   Mihail   add auto upload a...
177
178
      public function actionAutoUpload()
      {
942bad48   Mihail   adapt project to ...
179
          $query = Importers::find()->where(['active' => true])->orderBy(['price_date_update' => SORT_DESC]);
1fa22312   Mihail   add auto upload a...
180
181
182
183
184
185
186
187
188
189
190
  
          $provider = new ActiveDataProvider([
              'query' => $query,
              'pagination' => [
                  'pageSize' => 10,
              ],
          ]);
          return $this->render('check_price',
              [
                  'dataProvider' => $provider]);
      }
35764921   Mihail   add action and vi...
191
192
193
  
      public function actionServerFiles ()
      {
ef41533d   Mihail   temp commit - wor...
194
195
              $arr_id_files = [];
  
35764921   Mihail   add action and vi...
196
          // получим список файлов которые ожидают к загрузке
ea4ecf3d   Mihail   console csv parsing
197
          foreach ( glob(Yii::getAlias('@temp_upload') . '/*.csv' ) as $server_file ) {
35764921   Mihail   add action and vi...
198
              $file_id = basename($server_file,".csv");
0ade45a9   Mihail   add ajax handler ...
199
              $arr_id_files[] = (int) $file_id;
35764921   Mihail   add action and vi...
200
          }
181d3f16   Mihail   merge with server
201
  
942bad48   Mihail   adapt project to ...
202
          $query = ImportersFiles::find()->where(['in', 'id', $arr_id_files])->orderBy(['upload_time' => SORT_DESC]);
35764921   Mihail   add action and vi...
203
204
205
206
207
208
209
210
211
212
213
214
  
          $provider = new ActiveDataProvider([
              'query' => $query,
              'pagination' => [
                  'pageSize' => 10,
              ],
          ]);
          return $this->render('server-files',
              [
                  'dataProvider' => $provider]);
      }
  
0ade45a9   Mihail   add ajax handler ...
215
      public function actionDelete ()
35764921   Mihail   add action and vi...
216
      {
0ade45a9   Mihail   add ajax handler ...
217
          if ( Yii::$app->request->isAjax ) {
35764921   Mihail   add action and vi...
218
  
942bad48   Mihail   adapt project to ...
219
              $files_model = new ImportersFiles();
0ade45a9   Mihail   add ajax handler ...
220
221
222
223
              if ( isset(Yii::$app->request->post()['id'] )) {
                  $id = Yii::$app->request->post()['id'];
                  try {
                      $files_model->delete($id);
ef41533d   Mihail   temp commit - wor...
224
                      unlink(Yii::getAlias('@temp_upload') . '/' . $id . '.csv' );
0ade45a9   Mihail   add ajax handler ...
225
226
227
                      // сообщим скрипту что все ОК
                      echo 1;
                  } catch (ErrorException  $e) {
35764921   Mihail   add action and vi...
228
  
1fe29bbe   Mihail   fixed parser and ...
229
                      throw $e;
35764921   Mihail   add action and vi...
230
  
0ade45a9   Mihail   add ajax handler ...
231
232
                  }
              }
35764921   Mihail   add action and vi...
233
234
          }
  
35764921   Mihail   add action and vi...
235
      }
1fe29bbe   Mihail   fixed parser and ...
236
  
ef41533d   Mihail   temp commit - wor...
237
238
      public function actionLaunchCroneUploads ()
      {
ef41533d   Mihail   temp commit - wor...
239
          foreach (glob(Yii::getAlias('@temp_upload') . '/*.csv') as $server_file) {
1fe29bbe   Mihail   fixed parser and ...
240
  
ef41533d   Mihail   temp commit - wor...
241
              $file_name = basename($server_file,".csv");
ea4ecf3d   Mihail   console csv parsing
242
              copy( $server_file, Yii::getAlias('@auto_upload') . '/' . $file_name . '.csv' );
ef41533d   Mihail   temp commit - wor...
243
244
  
          }
78684ed4   Mihail   add multiply pric...
245
  
ea4ecf3d   Mihail   console csv parsing
246
247
          Yii::$app->session->setFlash( 'server-files', 'Файл успешно загружен' );
          $this->redirect('server-files');
1fe29bbe   Mihail   fixed parser and ...
248
  
78684ed4   Mihail   add multiply pric...
249
250
  //        $csv = new \console\controllers\ParserController( 'parse-csv', $this->module );
  //        $csv->actionParseCsv();
48b58a13   Mihail   finish with xml a...
251
      }
1fe29bbe   Mihail   fixed parser and ...
252
  
ef41533d   Mihail   temp commit - wor...
253
  
b6247a0e   Mihail   rewrite parser wr...
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
      /**
       * сохраняет файл на диск и регистрирует в ImportersFiles
       * @param $model - модель с настройками
       * @return ImportersFiles
       * @throws ErrorException
       * @throws \Exception
       */
      protected function saveParserFile ($model)
      {
          $files_model = new ImportersFiles();
          // id поставщика получим из конфигурации
          $files_model->load(['ImportersFiles' => $model->toArray()]);
          try {
              $files_model->save();
          } catch (ErrorException  $e) {
              throw $e;
          }
          // получим id только что записанной записи - его запишем в название файла
          $model->record_id = $files_model->id;
  
          $file_name = $model->record_id . '.' . $model->file->extension;
  
          if ($model->mode) {
              $model->file_path = Yii::getAlias('@temp_upload') . '/' . $file_name;
          } else {
              $model->file_path = Yii::getAlias('@manual_upload') . '/' . $file_name;
          }
  
          $model->file->saveAs($model->file_path);
  
          return $files_model;
      }
      protected function parseDataFromFile ( $files_model, $model )
      {
          // доп. опции для парсера
          $options = ['converter_conf' =>
              ['importer_id' => $files_model->importer_id]
          ];
  
          if( ! $model->action ) // обработка с кастомным разделителем
              $options['$delimiter'] = $model->delimiter;
  
          $data = $model->readFile( $options );
          // сохраняем в кеш отпарсенные даные
          $this->parserCacheHandler( 1, $data, $model );
  
          return $data;
      }
1fd14fc9   Mihail   fixed errors with...
302
  
58743b31   Mihail   init commit - bas...
303
  }