Blame view

backend/controllers/RgGrupController.php 8.65 KB
293f57f9   Mihail   add upload rg gro...
1
2
3
4
5
6
7
8
9
10
11
12
  <?php
  /**
   * Created by PhpStorm.
   * User: Tsurkanov
   * Date: 27.10.2015
   * Time: 15:22
   */
  
  namespace backend\controllers;
  
  use backend\components\base\BaseController;
  use backend\models\UploadFileRgForm;
1e337311   Mihail   add parser trait ...
13
  use common\components\exceptions\RgParsingException;
209dad04   Mihail   add validator for...
14
  use common\components\ModelArrayValidator;
8e7f5c9b   Mihail   add MailAttachmen...
15
  use common\components\parsers\MailAttachmentsSaver;
293f57f9   Mihail   add upload rg gro...
16
17
  use common\models\Margins;
  use common\models\MarginsGroups;
293f57f9   Mihail   add upload rg gro...
18
19
20
21
  use yii\filters\AccessControl;
  use Yii;
  use yii\web\UploadedFile;
  use yii\data\ArrayDataProvider;
ad2e91f7   Mihail   move multyparser ...
22
  use common\components\parsers\DynamicFormHelper;
293f57f9   Mihail   add upload rg gro...
23
  use common\components\CustomArrayHelper;
1e337311   Mihail   add parser trait ...
24
  use backend\components\traits\ParserTrait;
293f57f9   Mihail   add upload rg gro...
25
  
8b8083ef   Mihail   add manual insert...
26
27
  class RgGrupController extends BaseController
  {
1e337311   Mihail   add parser trait ...
28
      use ParserTrait;
293f57f9   Mihail   add upload rg gro...
29
30
31
32
33
34
35
36
37
38
39
40
      public $layout = "/column";
  
      /**
       * @inheritdoc
       */
      public function behaviors()
      {
          return [
              'access' => [
                  'class' => AccessControl::className(),
                  'rules' => [
                      [
293f57f9   Mihail   add upload rg gro...
41
42
43
44
45
                          'allow' => true,
                          'roles' => ['@'],
                      ],
                  ],
              ],
9755cb59   Mihail   fixed permissions...
46
47
48
49
50
51
  //            'verbs' => [
  //                'class' => VerbFilter::className(),
  //                'actions' => [
  //                    'logout' => ['post'],
  //                ],
  //            ],
293f57f9   Mihail   add upload rg gro...
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
          ];
      }
  
      public function actionIndex()
      {
          $model = new UploadFileRgForm();
  
          return $this->render('index', ['model' => $model]);
      }
  
      public function actionResults()
      {
          $model = new UploadFileRgForm();
          $data = [];
  
          if ($model->load(Yii::$app->request->post())) {
              $model->file = UploadedFile::getInstance($model, 'file');
              // первый проход - валидируем, сохраняем файл, ложим в кеш  отпарсенные данные и параметры модели (потом при записи в базу данных они пригодятся)
              if ($model->validate()) {
293f57f9   Mihail   add upload rg gro...
71
72
                  $model->file_path = Yii::getAlias('@manual_upload') . '/' . $model->file->name;
                  $model->file->saveAs($model->file_path);
293f57f9   Mihail   add upload rg gro...
73
74
75
                  //запускаем парсинг
                  $data = $model->readFile();
                  // сохраняем в кеш отпарсенные даные
1e337311   Mihail   add parser trait ...
76
                  $this->parserCacheHandler(1, $data, $model);
293f57f9   Mihail   add upload rg gro...
77
78
              } else {
                  // не прошла валидация форма загрузки файлов
1e337311   Mihail   add parser trait ...
79
                  $this->throwStringErrorException($model, 'common\components\exceptions\RgParsingException');
293f57f9   Mihail   add upload rg gro...
80
81
82
83
84
85
86
              }
              // листаем пагинатором, или повторно вызываем - считываем из кеша отпрасенные данные
          } else if (Yii::$app->getCache()->get('parser_data')) {
  
              $data = json_decode(Yii::$app->getCache()->get('parser_data'), true);
  
          }
1e337311   Mihail   add parser trait ...
87
88
          // сборка динамической модели и её рендеринг
          return $this->renderResultView($data);
293f57f9   Mihail   add upload rg gro...
89
90
91
92
93
94
      }
  
      public function actionWrite()
      {
          //получим колонки которые выбрал пользователь
          $arr_attributes = Yii::$app->request->post()['DynamicModel'];
209dad04   Mihail   add validator for...
95
          $margin_model = new MarginsGroups();
293f57f9   Mihail   add upload rg gro...
96
97
98
99
100
101
          //соберем модель по полученным данным
          $model = DynamicFormHelper::CreateDynamicModel($arr_attributes);
          //добавим правила валидации (колонки должны быть те что в модели)
          foreach ($arr_attributes as $key => $value) {
              $model->addRule($key, 'in', ['range' => array_keys(Margins::getHeader())]);
          }
209dad04   Mihail   add validator for...
102
103
          // установим режим проверки обязательных полей
          $margin_model->setScenario('form_upload_validation');
1e337311   Mihail   add parser trait ...
104
          $model_validator = new ModelArrayValidator($margin_model);
293f57f9   Mihail   add upload rg gro...
105
          // провалидируем выбранные колонки
1e337311   Mihail   add parser trait ...
106
          if ($model->validate() && $model_validator->validateRow($this->getAttributesForValidate($arr_attributes))) {
293f57f9   Mihail   add upload rg gro...
107
108
109
110
111
  
              // валидация успешна у нас есть соответсвие колонок, преобразуем в массив данное соответсвие для дальнейшей работы
              $arr = $model->toArray();
  
              // получим данные из кеша
1e337311   Mihail   add parser trait ...
112
              $this->parserCacheHandler(0, $data, $configuration);
293f57f9   Mihail   add upload rg gro...
113
  
8b8083ef   Mihail   add manual insert...
114
115
              array_walk($arr, function (&$val) {
                  $val = '!' . $val;
293f57f9   Mihail   add upload rg gro...
116
117
118
119
              });
  
              // соотнесем отпарсенные данные с соответсивем полученным от пользователя
              // для этого преобразуем массив отпарсенных данных - назначим ключи согласно соответствию
8b8083ef   Mihail   add manual insert...
120
              $data = CustomArrayHelper::createAssocArray($data, $arr, 'attr_');
293f57f9   Mihail   add upload rg gro...
121
122
  
              // в первой строке у нас заголовки - уберем
1e337311   Mihail   add parser trait ...
123
              unset($data[0]);
293f57f9   Mihail   add upload rg gro...
124
              // подготовим данные для записи в таблицу w_margins_groups
1e337311   Mihail   add parser trait ...
125
              $data = $this->convertDataByConfiguration($data, $configuration);
8b8083ef   Mihail   add manual insert...
126
  
209dad04   Mihail   add validator for...
127
128
              // валидируем отпарсенные данные моделью в которую будем записывать
              $margin_model->setScenario('default');
1e337311   Mihail   add parser trait ...
129
              $data = $model_validator->validate($data);
209dad04   Mihail   add validator for...
130
              $msg = $model_validator->getMassage();
1e337311   Mihail   add parser trait ...
131
              $type_msg = $model_validator->hasError() ? 'warning' : 'success';
209dad04   Mihail   add validator for...
132
              $model_validator->close();
8b8083ef   Mihail   add manual insert...
133
              // сохраним подготовленные данные
1e337311   Mihail   add parser trait ...
134
135
136
137
              if (!empty($data)) {
                  if (MarginsGroups::ManualInsertWithUpdate($data, ['group', 'importer_id', 'margin_id'])) {
                      // все прошло успешно - очищаем кеш
                      $this->parserCacheHandler(2);
293f57f9   Mihail   add upload rg gro...
138
  
1e337311   Mihail   add parser trait ...
139
140
141
                      if (file_exists($configuration['file_path']))
                          unlink($configuration['file_path']);
                  }
293f57f9   Mihail   add upload rg gro...
142
  
1e337311   Mihail   add parser trait ...
143
144
              }
              Yii::$app->session->setFlash($type_msg, $msg);
8b8083ef   Mihail   add manual insert...
145
              return $this->render('index', ['model' => $configuration]);
293f57f9   Mihail   add upload rg gro...
146
  
209dad04   Mihail   add validator for...
147
148
149
          } else {
              // не прошла валидация формы загрузки файлов
              $errors_str = "Ошибка валидации формы загрузки файлов. ";
1e337311   Mihail   add parser trait ...
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
              $this->throwStringErrorException($margin_model, 'common\components\exceptions\RgParsingException', $errors_str);
          }
      }
  
      protected function convertDataByConfiguration($data, $configuration)
      {
          $arr_values = [];
          $group = '';
          $importer_id = $configuration['importer_id'];
          foreach ($data as $row_data) {
  
              if (isset($row_data['!group'])) {
                  $group = $row_data['!group'];
                  unset($row_data['!group']);
              }
              if (isset($row_data['!_null'])) {
                  unset($row_data['!_null']);
              }
  
              foreach ($row_data as $key => $value) {
                  if ($group)
                      $row['group'] = trim($group);
  
                  $row['importer_id'] = trim($importer_id);
                  $row['margin_id'] = ltrim($key, '!');
                  $row['koef'] = \Yii::$app->converter->convertTo('float', $value, ['precision' => 6]);
  
                  $arr_values[] = $row;
209dad04   Mihail   add validator for...
178
              }
293f57f9   Mihail   add upload rg gro...
179
          }
1e337311   Mihail   add parser trait ...
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
          return $arr_values;
      }
  
      protected function getBasicColumns()
      {
          return Margins::getHeader();
      }
  
      // подготавливает массив для валидирования моделью - MarginsGroups
      // для этого меняем выбранные значения именем поля - margin_id
      protected function getAttributesForValidate($arr)
      {
          $base_columns_arr = Margins::find()->select('id')->asArray()->all();
          $base_columns_arr = array_column($base_columns_arr,'id');
  
          array_walk( $arr, function (&$value, $key, $base_columns_arr) {
              if (in_array( $value, $base_columns_arr )){
                  $value = 'margin_id';
              }
          }, $base_columns_arr );
293f57f9   Mihail   add upload rg gro...
200
  
1e337311   Mihail   add parser trait ...
201
          return array_flip( $arr );
293f57f9   Mihail   add upload rg gro...
202
      }
8e7f5c9b   Mihail   add MailAttachmen...
203
  
1fae1653   Mihail   fixed errors with...
204
205
206
207
208
209
  //    public function actionMail()
  //    {
  //        $mail_saver = new MailAttachmentsSaver('{imap.gmail.com:993/imap/ssl/novalidate-cert}', 'tsurkanovm@gmail.com', 'Wtvr@2000');
  //        //$mail_saver = new MailAttachmentsSaver('{imap.gmail.com:993/imap/ssl/novalidate-cert}', 'price@italauto.com.ua', '67853562');
  //        $mail_saver->saveAttachmentsTo();
  //    }
8e7f5c9b   Mihail   add MailAttachmen...
210
211
  
  }