Commit 4702bfa719ed35dd616231aff9b10616e4e244af

Authored by Mihail
1 parent 9be31ea0

change writing crossing data to BD

backend/controllers/CrossingUploadController.php
... ... @@ -9,6 +9,7 @@
9 9 namespace backend\controllers;
10 10  
11 11 use backend\components\base\BaseController;
  12 +use common\components\CustomArrayHelper;
12 13 use common\components\CustomVarDamp;
13 14 use yii\data\ArrayDataProvider;
14 15 use yii\filters\VerbFilter;
... ... @@ -24,21 +25,17 @@ class CrossingUploadController extends BaseController
24 25 public $layout = "/column";
25 26  
26 27  
27   - /**
28   - * @inheritdoc
29   - */
30   - public function behaviors()
  28 + /**
  29 + * @inheritdoc
  30 + */
  31 + public function behaviors()
31 32 {
32 33 return [
33 34 'access' => [
34 35 'class' => AccessControl::className(),
35 36 'rules' => [
36 37 [
37   - 'actions' => ['login', 'error', 'download-photo','delete-image','result' ],
38   - 'allow' => true,
39   - ],
40   - [
41   - 'actions' => ['logout', 'index','create','update','view','delete',],
  38 + 'actions' => ['result', 'index', 'write'],
42 39 'allow' => true,
43 40 'roles' => ['@'],
44 41 ],
... ... @@ -52,6 +49,7 @@ class CrossingUploadController extends BaseController
52 49 ],
53 50 ];
54 51 }
  52 +
55 53 /**
56 54 * @inheritdoc
57 55 */
... ... @@ -77,56 +75,16 @@ class CrossingUploadController extends BaseController
77 75 $data = [];
78 76 if ($model->load(Yii::$app->request->post())) {
79 77 $model->file = UploadedFile::getInstance($model, 'file');
80   -
81 78 if ($model->validate()) {
82 79 $file_name = $model->file->name;
83 80 $model->file_path = Yii::getAlias('@temp_upload') . '/' . $file_name;
84   -
85 81 $model->file->saveAs($model->file_path);
86 82 //запускаем парсинг
87 83 $data = $model->readFile();
88 84 // сохраняем в кеш отпарсенные даные
89   - Yii::$app->getCache()->set('parser_data', json_encode($data), 1800);
90   - // сохраняем в кеш модель - в ней настройки для дальнейшей обработки данных
91   - Yii::$app->getCache()->set('parser_configuration', serialize($model), 1800);
92   -
93   -
94   -// // доп. опции для парсера - удаление префикса в артикулах
95   -// $options['mode'] = 'crosses';
96   -// $fields = [];
97   -// if ($model->delete_prefix1) {
98   -// $fields[] = 'ARTICLE';
99   -// }
100   -// if ($model->delete_prefix2) {
101   -// $fields[] = 'CROSS_ARTICLE';
102   -// }
103   -// if ( $fields ) {
104   -// $options [ 'converter_conf' ] = [ 'configuration' => [ "article" => $fields ,
105   -// "string" => ['ARTICLE', 'CROSS_ARTICLE'],] ];
106   -// } else {
107   -// $options [ 'converter_conf' ] = [ 'configuration' => [ "string" => ['ARTICLE', 'CROSS_ARTICLE'], ] ];
108   -// }
109   -//
110   -// $data = $model->readFile( $options );
111   -// $crosses_model = new DetailsCrosses();
112   -// $crosses_model->ManualInsertWithIgnore( $data );
113   -//
114   -// Yii::$app->session->setFlash('success', 'Файл кроссов успешно загружен');
115   -// return $this->render('index', ['model' => $model]);
116   -// }else{
117   -// // не прошла валидация форма загрузки файлов
118   -// $errors_str = '';
119   -// foreach ($model->getErrors() as $error) {
120   -// $errors_str .= implode( array_values($error) );
121   -// }
122   -// throw new \ErrorException( $errors_str );
123   -// }
124   -
125   -
  85 + $this->cacheHandler( true, $data, $model );
126 86 } else if (Yii::$app->getCache()->get('parser_data')) {
127   -
128 87 $data = json_decode(Yii::$app->getCache()->get('parser_data'), true);
129   -
130 88 }
131 89 $provider = new ArrayDataProvider([
132 90 'allModels' => $data,
... ... @@ -152,8 +110,6 @@ class CrossingUploadController extends BaseController
152 110 }
153 111 }
154 112  
155   -
156   -
157 113 public function actionWrite()
158 114 {
159 115 //получим колонки которые выбрал пользователь
... ... @@ -162,7 +118,7 @@ class CrossingUploadController extends BaseController
162 118 $model = DynamicFormHelper::CreateDynamicModel($arr_attributes);
163 119 //добавим правила валидации (колонки должны быть те что в модели)
164 120 foreach ($arr_attributes as $key => $value) {
165   - $model->addRule($key, 'in', [ 'range' => $this->getBasicColumns() ]);
  121 + $model->addRule($key, 'in', [ 'range' => array_keys( $this->getBasicColumns() ) ]);
166 122 }
167 123  
168 124 // провалидируем выбранные колонки
... ... @@ -172,77 +128,99 @@ class CrossingUploadController extends BaseController
172 128 $arr = $model->toArray();
173 129  
174 130 // получим данные из кеша
175   - if (Yii::$app->getCache()->get('parser_data') && Yii::$app->getCache()->get('parser_configuration')) {
176   - $data = json_decode(Yii::$app->getCache()->get('parser_data'), true);
177   - $configuration = unserialize(Yii::$app->getCache()->get('parser_configuration'));
178   - } else {
179   - throw new \ErrorException('Ошибка кеша');
180   - }
181   -
182   - array_walk($arr, function (&$val) {
183   - $val = '!' . $val;
184   - });
  131 + $this->cacheHandler( false, $data, $configuration );
185 132  
186 133 // соотнесем отпарсенные данные с соответствием полученным от пользователя
187 134 // для этого преобразуем массив отпарсенных данных - назначим ключи согласно соответствию
188 135 $data = CustomArrayHelper::createAssocArray($data, $arr, 'attr_');
189 136  
190   - // в первой строке у нас заголовки - уберем
191   - unset($data[0]);
192   - // подготовим данные для записи в таблицу w_margins_groups
193   - $arr_values = [];
194   - $group = '';
195   - $importer_id = $configuration['importer_id'];
196   - foreach ($data as $row_data) {
197   -
198   - if (isset($row_data['!group'])) {
199   - $group = $row_data['!group'];
200   - unset($row_data['!group']);
201   - }
202   - if (isset($row_data['!_null'])) {
203   - unset($row_data['!_null']);
204   - }
205   -
206   - foreach ($row_data as $key => $value) {
207   - if ($group)
208   - $row['group'] = trim($group);
  137 + // запустим конвертер над над данными
  138 + $data = $this->convertDataByConfiguration( $data, $configuration );
209 139  
210   - $row['importer_id'] = trim($importer_id);
211   - $row['margin_id'] = ltrim($key, '!');
212   - $row['koef'] = \Yii::$app->converter->convertTo('float', $value, ['precision' => 6]);
  140 + $crosses_model = new DetailsCrosses();
  141 + $crosses_model->ManualInsertWithIgnore($data);
213 142  
214   -
215   - $arr_values[] = $row;
216   -
217   - }
218   -
219   - }
220   - // сохраним подготовленные данные
221   - MarginsGroups::ManualInsertWithUpdate( $arr_values, [ 'group','importer_id','margin_id' ] );
222   -
223   -
224   - Yii::$app->session->setFlash('success', "Файл {$configuration['file']} успешно загружен");
  143 + Yii::$app->session->setFlash('success', 'Файл кроссов успешно загружен');
225 144 // все прошло успешно - очищаем кеш
226 145 Yii::$app->getCache()->delete('parser_data');
227 146 Yii::$app->getCache()->delete('parser_configuration');
228 147  
229 148 if (file_exists($configuration['file_path']))
230 149 unlink($configuration['file_path']);
231   -
232 150 return $this->render('index', ['model' => $configuration]);
233 151  
  152 + } else {
  153 + // не прошла валидация форма загрузки файлов
  154 + $errors_str = '';
  155 + foreach ($model->getErrors() as $error) {
  156 + $errors_str .= implode(array_values($error));
  157 + }
  158 + throw new \ErrorException($errors_str);
  159 + }
  160 + }
  161 +
  162 + protected function getBasicColumns()
  163 + {
  164 + $basicColumns_array = Yii::$app->multiparser->getConfiguration('csv', 'crosses');
  165 + if (isset($basicColumns_array['basic_column'])) {
  166 + return $basicColumns_array['basic_column'];
  167 + } else {
  168 + throw new \ErrorException('Ошибка конфигурационного файла кроссов. Не указаны базовые колнки для пользовательской формы выбора.');
234 169 }
235 170  
236 171 }
237 172  
238   - protected function getBasicColumns(){
  173 + protected function convertDataByConfiguration( $data, $configuration ){
  174 +
  175 + // доп. опции для парсера - удаление префикса в артикулах
  176 + $options['mode'] = 'crosses';
  177 + $fields = [];
  178 + if ($configuration['delete_prefix1']) {
  179 + $fields[] = 'ARTICLE';
  180 + }
  181 + if ($configuration['delete_prefix2']) {
  182 + $fields[] = 'CROSS_ARTICLE';
  183 + }
  184 + if ($fields) {
  185 + $options ['configuration'] = ["article" => $fields,
  186 + "string" => ['ARTICLE', 'CROSS_ARTICLE'],];
  187 + } else {
  188 + $options ['configuration'] = ["string" => ['ARTICLE', 'CROSS_ARTICLE'],];
  189 + }
  190 +
  191 + foreach ($data as &$row) {
  192 + $row = Yii::$app->converter->convertByConfiguration($row, $options);
  193 + }
  194 +
  195 + return $data;
  196 +
  197 + }
  198 +
  199 + /**
  200 + * @param $mode - bool - true - put in cache, otherwise - fetch from cache
  201 + * @param $data - array
  202 + * @param $configuration - array
  203 + * @throws \ErrorException
  204 + */
  205 + protected function cacheHandler( $mode, &$data, &$configuration ){
  206 +
  207 + if ( $mode ) {
  208 +
  209 + Yii::$app->getCache()->set('parser_data', json_encode($data), 1800);
  210 + // сохраняем в кеш модель - в ней настройки для дальнейшей обработки данных
  211 + Yii::$app->getCache()->set('parser_configuration', serialize($configuration), 1800);
239 212  
240   - $basicColumns_array = Yii::$app->multiparser->getConfiguration( 'csv','crosses' );
241   - if ( isset( $basicColumns_array['basic_column'] ) ) {
242   - return $basicColumns_array['basic_column'];
243 213 } else {
244   - throw new \ErrorException( 'Ошибка конфигурационного файла кроссов. Не указаны базовые колнки для пользовательской формы выбора.' );
  214 +
  215 + if (Yii::$app->getCache()->get('parser_data') && Yii::$app->getCache()->get('parser_configuration')) {
  216 + $data = json_decode(Yii::$app->getCache()->get('parser_data'), true);
  217 + $configuration = unserialize(Yii::$app->getCache()->get('parser_configuration'));
  218 + } else {
  219 + throw new \ErrorException('Ошибка кеша');
  220 + }
  221 +
245 222 }
246 223  
  224 +
247 225 }
248 226 }
249 227 \ No newline at end of file
... ...
backend/views/crossing-upload/index.php
... ... @@ -19,7 +19,7 @@ use yii\helpers\ArrayHelper;
19 19 <?= $form->field($model, 'file')->fileInput()->label(false) ?>
20 20  
21 21 <div class="form-group">
22   - <?= Html::submitButton(Yii::t( 'app', 'Выполнить' ), ['class' => 'btn btn-primary']) ?>
  22 + <?= Html::submitButton(Yii::t( 'app', 'Прочитать' ), ['class' => 'btn btn-primary']) ?>
23 23 </div>
24 24  
25 25 <?php ActiveForm::end() ?>
... ...
common/components/parsers/config.php
... ... @@ -39,7 +39,7 @@
39 39 'crosses' => ['class' => 'common\components\parsers\CustomCsvParser',
40 40 'auto_detect_first_line' => true,
41 41 'min_column_quantity' => 4,
42   - 'keys' =>['ARTICLE', 'CROSS_ARTICLE', 'BRAND', 'CROSS_BRAND'],
  42 + // 'keys' =>['ARTICLE', 'CROSS_ARTICLE', 'BRAND', 'CROSS_BRAND'],
43 43 'converter_conf' => [
44 44 'class' => ' common\components\parsers\CustomConverter',
45 45 'configuration' => [
... ...