Blame view

common/modules/product/models/Import.php 30 KB
8072159c   Alex Savenko   create proj
1
  <?php
91fc4901   Yarik   Import fix
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
      
      namespace common\modules\product\models;
      
      use common\models\EventsToProducts;
      use common\modules\product\helpers\ProductHelper;
      use common\modules\product\models\Category;
      use common\modules\product\models\CategoryName;
      use common\modules\product\models\ProductImage;
      use common\modules\product\models\ProductVariantType;
      use common\modules\rubrication\models\TaxGroup;
      use common\modules\rubrication\models\TaxOption;
      use common\modules\rubrication\models\TaxValueString;
      use Yii;
      use common\modules\product\models\Brand;
      use common\modules\product\models\BrandName;
      use common\modules\product\models\Product;
      use common\modules\product\models\ProductVariant;
      use common\modules\product\models\RemoteProducts;
      use yii\base\Model;
      use yii\helpers\ArrayHelper;
      
      class Import extends Model
8072159c   Alex Savenko   create proj
24
      {
91fc4901   Yarik   Import fix
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
          public $file;
          public $type;
          
          public $errors = [];
          public $output = [];
          
          /**
           * @inheritdoc
           */
          public function rules()
          {
              return [
                  [
                      [ 'type' ],
                      'required',
                  ],
                  [
                      [ 'type' ],
                      'string',
                  ],
                  //            [['file'], 'safe'],
                  [
                      [ 'file' ],
                      'file',
                      'extensions' => 'csv',
                  ],
              ];
2a47d6e7   Administrator   Ntr
52
          }
91fc4901   Yarik   Import fix
53
54
55
56
57
58
59
60
61
          
          /**
           * @inheritdoc
           */
          public function attributeLabels()
          {
              return [
                  'file' => Yii::t('product', 'File'),
              ];
8072159c   Alex Savenko   create proj
62
          }
91fc4901   Yarik   Import fix
63
64
65
66
67
68
69
          
          public function getType()
          {
              if (!$this->type) {
                  $this->type = 'products';
              }
              return $this->type;
8072159c   Alex Savenko   create proj
70
          }
91fc4901   Yarik   Import fix
71
72
          
          public function goPrices($from = 0, $limit = null)
8072159c   Alex Savenko   create proj
73
          {
91fc4901   Yarik   Import fix
74
75
76
77
78
79
              set_time_limit(0);
              $new_products = $linked_products = 0;
              
              if (!( $handle = $this->getProductsFile('uploadFilePrices') )) {
                  $this->errors[] = 'File not found';
                  return false;
8072159c   Alex Savenko   create proj
80
              }
91fc4901   Yarik   Import fix
81
82
83
              
              if (file_exists(Yii::getAlias('@uploadDir/goPrices.lock'))) {
                  return 'Task already executed';
8072159c   Alex Savenko   create proj
84
              }
91fc4901   Yarik   Import fix
85
86
87
88
89
90
91
              $ff = fopen(Yii::getAlias('@uploadDir/goPrices.lock'), 'w+');
              fclose($ff);
              
              $filesize = filesize(Yii::getAlias('@uploadDir') . '/' . Yii::getAlias('@uploadFilePrices'));
              if ($from) {
                  fseek($handle, $from);
                  
8072159c   Alex Savenko   create proj
92
              }
91fc4901   Yarik   Import fix
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
              
              $j = 0;
              
              $is_utf = ( preg_match(
                  '//u',
                  file_get_contents(
                      Yii::getAlias('@uploadDir') . '/' . Yii::getAlias('@uploadFilePrices'),
                      null,
                      null,
                      null,
                      1000000
                  )
              ) );
              
              if ($from == 0) {
                  ProductStock::updateAll([ 'quantity' => 0 ]);
                  ProductVariant::updateAll([ 'status' => 1 ]);
8072159c   Alex Savenko   create proj
110
              }
91fc4901   Yarik   Import fix
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
              
              while (empty( $limit ) || $j++ < $limit) {
                  
                  if (!( ( $data = fgetcsv($handle, 10000, ";") ) !== false )) {
                      break;
                  }
                  
                  foreach ($data as &$value) {
                      if (!$is_utf) {
                          $value = iconv('windows-1251', "UTF-8//TRANSLIT//IGNORE", $value);
                      }
                      $value = trim($value);
                  }
                  
                  // данные строк
                  $modification_code = @$data[ 0 ];
                  $price = floatval(@$data[ 1 ]);
                  $price_promo = floatval(@$data[ 2 ]);
                  $count = intval(@$data[ 3 ]);
                  $city_name = @$data[ 4 ];
                  $product_title = @$data[ 5 ];
                  
                  if (empty ( $modification_code )) {
                      continue;
                  }
                  // товары в пути
                  //            if (empty ($city_name))
                  //            {
                  //                $this->saveNotFoundRecord (
                  //                    [$modification_code, $product_title],
                  //                    Yii::getAlias('@uploadFilePricesAway')
                  //                );
                  //
                  //                $this->output[] = 'Товар '. $product_title . ' в пути';
                  //
                  //                continue;
                  //            }
                  
                  if (( $productVariant = ProductVariant::find()
                                                        ->filterWhere([ 'sku' => $modification_code ])
                                                        ->one() ) === null
                  ) {
                      // 'Нет даной модификации в базе';
                      //                $this->saveNotFoundRecord (
                      //                    [$modification_code, $product_title],
                      //                    Yii::getAlias('@uploadFilePricesNoVariant')
                      //                );
                      
                      $this->output[] = 'Для товара ' . $product_title . ' не найдено соотвествие';
                      
                      continue;
                  }
                  
                  // ===== Set stock ====
                  if (!$city_name) {
                      if (!$count) {
4a98cdd2   Alexey Boroda   -Import fix with ...
167
                          $productVariant->status = 0;
cf039359   Alexey Boroda   -Import price fix
168
169
170
171
172
173
174
175
                          if ($price_promo) {
                              $productVariant->price_old = $price;
                              $productVariant->price = $price_promo;
                          } else {
                              $productVariant->price = $price;
                              $productVariant->price_old = $price_promo;
                          }
                          $productVariant->save(false, ['status', 'price', 'price_promo']);
91fc4901   Yarik   Import fix
176
177
178
179
180
181
182
183
184
                          continue;
                      }
                      $city_name = 'Склад';
                  }
                  if (( $stock = Stock::find()
                                      ->filterWhere([ 'name' => trim($city_name) ])
                                      ->one() ) === null
                  ) {
                      
8072159c   Alex Savenko   create proj
185
186
187
188
189
                      // Create stock
                      $stock = new Stock();
                      $stock->name = trim($city_name);
                      $stock->save();
                  }
91fc4901   Yarik   Import fix
190
191
192
193
194
195
196
197
198
199
                  
                  $productStock = ProductStock::find()
                                              ->where(
                                                  [
                                                      'product_variant_id' => $productVariant->product_variant_id,
                                                      'stock_id'           => $stock->stock_id,
                                                  ]
                                              )
                                              ->one();
                  if (!$productStock instanceof ProductStock) {
8072159c   Alex Savenko   create proj
200
201
202
203
204
205
                      $productStock = new ProductStock;
                      $productStock->product_variant_id = $productVariant->product_variant_id;
                      $productStock->stock_id = $stock->stock_id;
                      $productStock->product_id = $productVariant->product_id;
                  }
                  $productStock->quantity = $count;
91fc4901   Yarik   Import fix
206
                  
8072159c   Alex Savenko   create proj
207
                  $productStock->save();
91fc4901   Yarik   Import fix
208
209
210
211
212
213
214
215
216
217
218
                  $productStocks = ProductStock::find()
                                               ->where([ 'product_variant_id' => $productVariant->product_variant_id ])
                                               ->andWhere(
                                                   [
                                                       '<>',
                                                       'stock_id',
                                                       $stock->stock_id,
                                                   ]
                                               )
                                               ->all();
                  
8072159c   Alex Savenko   create proj
219
                  $quantity = array_sum(ArrayHelper::getColumn($productStocks, 'quantity')) + $count;
91fc4901   Yarik   Import fix
220
221
222
223
                  
                  if ($price_promo) {
                      $productVariant->price_old = $price;
                      $productVariant->price = $price_promo;
8072159c   Alex Savenko   create proj
224
                  } else {
91fc4901   Yarik   Import fix
225
226
                      $productVariant->price = $price;
                      $productVariant->price_old = $price_promo;
8072159c   Alex Savenko   create proj
227
                  }
91fc4901   Yarik   Import fix
228
229
230
231
232
233
                  
                  $productVariant->stock = $quantity;
                  $productVariant->status = 0;
                  $productVariant->save();
                  
                  $this->output[] = '<font style="color:blue">Товар ' . $product_title . ' успешно сохранен</font>';
8072159c   Alex Savenko   create proj
234
              }
91fc4901   Yarik   Import fix
235
236
237
238
239
240
241
242
243
244
245
246
247
              
              $result = [
                  'end'       => feof($handle),
                  'from'      => ftell($handle),
                  'totalsize' => $filesize,
                  'items'     => $this->output,
              
              ];
              
              fclose($handle);
              
              if ($result[ 'end' ]) {
                  unlink(Yii::getAlias('@uploadDir') . '/' . Yii::getAlias('@uploadFilePrices'));
8072159c   Alex Savenko   create proj
248
              }
91fc4901   Yarik   Import fix
249
250
              unlink(Yii::getAlias('@uploadDir/goPrices.lock'));
              return $result;
2a47d6e7   Administrator   Ntr
251
          }
91fc4901   Yarik   Import fix
252
253
          
          public function goProducts($from = 0, $limit = null)
8072159c   Alex Savenko   create proj
254
          {
91fc4901   Yarik   Import fix
255
256
257
258
259
260
              set_time_limit(0);
              $new_products = $linked_products = 0;
              
              if (!( $handle = $this->getProductsFile('uploadFileProducts') )) {
                  $this->errors[] = 'File not found';
                  return false;
8072159c   Alex Savenko   create proj
261
              }
91fc4901   Yarik   Import fix
262
263
              if (file_exists(Yii::getAlias('@uploadDir/goProducts.lock'))) {
                  return 'Task already executed';
8072159c   Alex Savenko   create proj
264
              }
91fc4901   Yarik   Import fix
265
266
267
268
269
270
271
              $ff = fopen(Yii::getAlias('@uploadDir/goProducts.lock'), 'w+');
              fclose($ff);
              
              $filesize = filesize(Yii::getAlias('@uploadDir') . '/' . Yii::getAlias('@uploadFileProducts'));
              
              if ($from) {
                  fseek($handle, $from);
8072159c   Alex Savenko   create proj
272
              }
91fc4901   Yarik   Import fix
273
274
275
276
277
278
              
              $j = 0;
              
              $is_utf = ( preg_match(
                  '//u',
                  file_get_contents(
441c281b   Yarik   Import test
279
                      Yii::getAlias('@uploadDir') . '/' . Yii::getAlias('@uploadFileProducts'),
91fc4901   Yarik   Import fix
280
281
282
283
284
285
286
287
288
289
290
291
                      null,
                      null,
                      null,
                      1000000
                  )
              ) );
              
              $result_items = [];
              
              while (empty( $limit ) || $j++ < $limit) {
                  if (!( ( $data = fgetcsv($handle, 10000, ";") ) !== false )) {
                      break;
8072159c   Alex Savenko   create proj
292
                  }
91fc4901   Yarik   Import fix
293
294
295
296
                  
                  foreach ($data as &$value) {
                      if (!$is_utf) {
                          $value = iconv('windows-1251', "UTF-8//TRANSLIT//IGNORE", $value);
8072159c   Alex Savenko   create proj
297
                      }
91fc4901   Yarik   Import fix
298
                      $value = trim($value);
8072159c   Alex Savenko   create proj
299
                  }
91fc4901   Yarik   Import fix
300
301
302
303
304
                  
                  // будет всегда 19 элементов
                  for ($i = 0; $i <= 18; $i++) {
                      if (!isset ( $data[ $i ] )) {
                          $data[ $i ] = null;
8072159c   Alex Savenko   create proj
305
                      }
91fc4901   Yarik   Import fix
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
                  }
                  
                  // 1  Группа (категория)
                  $catalog_names = explode(',', $data[ 0 ]);
                  
                  if (empty ( $catalog_names )) {
                      $result_items[] = "Не указана категория (строка $j) ";
                      continue;
                  }
                  
                  // 2  Бренд
                  $brand_name = $data[ 1 ];
                  if (empty ( $brand_name )) {
                      $result_items[] = "Не указан бренд (строка $j)";
                      continue;
                  }
                  
                  // 3  Название товара
                  $product_name = $data[ 2 ];
                  if (empty ( $product_name )) {
                      $result_items[] = "Не указано наименование товара (строка $j)";
                      continue;
                  }
aac46b79   Yarik   Import test
329
330
331
                  if (preg_match('/^.+\(#(\d+)#\)$/', trim($product_name), $remote_id)) {
                      if (!empty( $remote_id[ 1 ] )) {
                          $remote_id = $remote_id[ 1 ];
096128d9   Yarik   Import test
332
333
334
                          $product_name = substr($product_name, 0, strpos($product_name, '(#' . $remote_id . '#)'));
                      }
                  }
91fc4901   Yarik   Import fix
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
                  
                  // 4  Описание Укр
                  $product_body_uk = $data[ 3 ];
                  
                  // 5  Описание Рус
                  $product_body_ru = $data[ 4 ];
                  
                  // 6  Фильтр [god:2013-2014]*[pol:мужской]*[naznacenie-germo-beg:Для вещей]*[material-germo-bag:нет]*[value-germo-bag:нет]*[weight-germo-bag:нет]*[ipx-germo-bag:нет]*[in-pacage-bag:нет]*[size-germo-bag:нет]*[rekomend-germo-bag:нет]
                  $filters = explode('*', $data[ 5 ]);
                  
                  // 11 Цена акция
                  $product_cost_old = floatval($data[ 7 ]);
                  $product_cost = '';
                  // 10 Цена
                  if ($product_cost_old) {
                      $product_cost_old = floatval($data[ 6 ]);
                      $product_cost = floatval($data[ 7 ]);
                  }
                  
                  // 12 Акция
                  $product_akciya = (bool) $data[ 8 ];
                  
                  // 13 Сопуд. Тов.
                  $similar = explode(',', $data[ 9 ]);
                  
                  // 14 Новинки
                  $product_new = (bool) $data[ 10 ];
                  
                  // 15 Топ продаж
                  $product_top = (bool) $data[ 11 ];
                  
                  // 17 ВИДЕО КОД
                  $product_video = $data[ 12 ];
                  
                  // 18 Галлерея фото
                  if (trim($data[ 13 ])) {
                      $fotos = explode(',', trim($data[ 13 ]));
                  }
                  
                  // 19 Штрих код товара.
                  // расшифровал - это модификации товара!
                  
                  $product_image = explode('=', $data[ 14 ]);
                  $product_image = @$product_image[ 3 ];
                  
aac46b79   Yarik   Import test
380
381
382
383
384
                  if (!empty( $remote_id )) {
                      if (( $_product = Product::find()
                                               ->filterWhere([ 'product_id' => $remote_id ])
                                               ->one() ) === null
                      ) {
096128d9   Yarik   Import test
385
386
387
                          $_product = new Product();
                      }
                  } elseif (( $_product = Product::find()
aac46b79   Yarik   Import test
388
389
                                                 ->filterWhere([ 'name' => trim($product_name) ])
                                                 ->one() ) === null
91fc4901   Yarik   Import fix
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
                  ) {
                      $_product = new Product();
                  }
                  
                  $is_new_product = empty( $_product->product_id );
                  $category_id = [];
                  foreach ($catalog_names as $catalog_name) {
                      
                      // ==== Set category ====
                      if (( $category = Category::find()
                                                ->filterWhere([ 'name' => trim($catalog_name) ])
                                                ->one() ) === null
                      ) {
                          // Create category
                          $category = new Category();
                          $category->name = trim($catalog_name);
                          $category->save();
8072159c   Alex Savenko   create proj
407
                      }
91fc4901   Yarik   Import fix
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
                      
                      $category_id[] = $category->category_id;
                  }
                  
                  $_product->categories = $category_id;
                  
                  // ===== Set brand ====
                  if ($brand_name) {
                      if (( $brand = Brand::find()
                                          ->filterWhere([ 'name' => trim($brand_name) ])
                                          ->one() ) !== null
                      ) {
                          $_product->brand_id = $brand->brand_id;
                      } else {
                          // Create brand
                          $brand = new Brand();
                          $brand->name = trim($brand_name);
                          $brand->save();
                          $_product->brand_id = $brand->brand_id;
8072159c   Alex Savenko   create proj
427
                      }
91fc4901   Yarik   Import fix
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
                  }
                  
                  $_product->name = $product_name;
                  $_product->video = $product_video;
                  $_product->description = $product_body_ru;
                  $_product->is_top = $product_top;
                  $_product->akciya = $product_akciya;
                  $_product->is_new = $product_new;
                  
                  if (!$_product->save()) {
                      $result_items[] = 'Product #' . $_product->name . ' not saved' . " (строка $j)";
                      continue;
                  }
                  
                  if (!empty( $fotos )) {
                      foreach ($fotos as $foto) {
                          $source_image = Yii::getAlias('@uploadDir') . '/product_images/' . urlencode($foto);
                          
                          if (file_exists($source_image)) {
                              if (( $productImage = ProductImage::find()
                                                                ->andFilterWhere([ 'image' => $foto ])
                                                                ->andFilterWhere(
                                                                    [ 'product_id' => $_product->product_id ]
                                                                )
                                                                ->one() ) === null
                              ) {
                                  copy($source_image, Yii::getAlias('@productsDir') . "/" . $foto);
                                  $productImage = new ProductImage();
                                  $productImage->product_id = $_product->product_id;
                                  $productImage->image = $foto;
                                  $productImage->save();
                              }
8072159c   Alex Savenko   create proj
460
461
                          }
                      }
91fc4901   Yarik   Import fix
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
                  }
                  
                  // нужно для проставления характеристик относящихся к модификациям
                  $MOD_ARRAY = [];
                  
                  for ($i = 14; $i < count($data); $i++) {
                      if (!empty ( $data[ $i ] )) {
                          $mod_arr = explode('=', $data[ $i ]);
                          $mod_art = $mod_arr[ 0 ];
                          $variant_filters = explode('*', $mod_arr[ 1 ]);
                          $mod_color = $mod_arr[ 2 ];
                          $mod_image = $mod_arr[ 3 ];
                          $mod_stock = isset( $mod_arr[ 4 ] ) ? $mod_arr[ 4 ] : 1;
                          $mod_cost = isset( $product_cost ) ? floatval($product_cost) : 0;
                          $mod_old_cost = floatval($product_cost_old);
                          
                          // Check product variant
                          if (( $_productVariant = ProductVariant::find()
                                                                 ->andFilterWhere([ 'sku' => $mod_art ])
                                                                 ->andFilterWhere(
                                                                     [ 'product_id' => $_product->product_id ]
                                                                 )
                                                                 ->one() ) === null
                          ) {
                              $_productVariant = new ProductVariant();
                              $_productVariant->product_id = $_product->product_id;
                          }
                          $_productVariant->product_unit_id = 1;
                          
                          $_productVariant->sku = $mod_art;
                          $_productVariant->price = $mod_cost;
                          $_productVariant->price_old = $mod_old_cost;
                          $_productVariant->stock = $mod_stock;
                          
                          $product_variant_type_name = '';
                          if (!empty ( $mod_color )) {
                              $product_variant_type_name = 'Цвет';
                              $_productVariant->name = $mod_color;
                          }
                          
                          if (!empty ( $variant_filters )) {
                              
                              $variants_options = $this->saveFilters($variant_filters, 1, $category_id);
                              
                          }
                          
                          if (isset( $variants_options ) && !empty( $variants_options )) {
                              $_productVariant->options = $variants_options;
                          }
                          
                          // ===== Set variant type ====
                          if ($product_variant_type_name) {
                              if (( $product_variant_type = ProductVariantType::find()
                                                                              ->filterWhere(
                                                                                  [ 'name' => $product_variant_type_name ]
                                                                              )
                                                                              ->one() ) !== null
                              ) {
                                  $_productVariant->product_variant_type_id = $product_variant_type->product_variant_type_id;
                              } else {
                                  $product_variant_type = new ProductVariantType();
                                  $product_variant_type->name = $product_variant_type_name;
                                  $product_variant_type->save();
                                  $_productVariant->product_variant_type_id = $product_variant_type->product_variant_type_id;
                              }
                          }
                          
                          $_productVariant->save();
                          
                          $MOD_ARRAY[] = $_productVariant->product_variant_id;
                          
                          if ($mod_image) {
                              $source_image = Yii::getAlias('@productsDir') . '/' . urlencode($mod_image);
                              if (file_exists($source_image)) {
                                  if (( $variantImage = ProductImage::find()
                                                                    ->andFilterWhere([ 'image' => $mod_image ])
                                                                    ->andFilterWhere(
                                                                        [ 'product_variant_id' => $_productVariant->product_variant_id ]
                                                                    )
                                                                    ->one() ) === null
                                  ) {
                                      //                                copy($source_image, Yii::getAlias('@productsDir') . "/" . $mod_image);
                                      $variantImage = new ProductImage();
                                      $variantImage->product_id = $_product->product_id;
                                      $variantImage->product_variant_id = $_productVariant->product_variant_id;
                                      $variantImage->image = $mod_image;
                                      $variantImage->save();
                                  }
8072159c   Alex Savenko   create proj
550
551
552
553
                              }
                          }
                      }
                  }
91fc4901   Yarik   Import fix
554
555
556
557
558
559
560
561
562
563
564
565
566
567
                  
                  if (!empty ( $filters )) {
                      
                      $options = $this->saveFilters($filters, 0, $category_id);
                      
                  }
                  
                  if (isset( $options ) && !empty( $options )) {
                      $_product->options = $options;
                  }
                  
                  $_product->save();
                  
                  $result_items[] = "Product {$_product->name} #{$_product->product_id} saved (" . ( $is_new_product ? 'new product' : 'exists product' ) . ")" . " (строка $j)";
8072159c   Alex Savenko   create proj
568
              }
91fc4901   Yarik   Import fix
569
570
571
572
573
574
575
576
577
578
579
580
581
              
              $result = [
                  'end'       => feof($handle),
                  'from'      => ftell($handle),
                  'totalsize' => $filesize,
                  'items'     => $result_items,
              
              ];
              
              fclose($handle);
              
              if ($result[ 'end' ]) {
                  unlink(Yii::getAlias('@uploadDir') . '/' . Yii::getAlias('@uploadFileProducts'));
8072159c   Alex Savenko   create proj
582
              }
91fc4901   Yarik   Import fix
583
584
              unlink(Yii::getAlias('@uploadDir/goProducts.lock'));
              return $result;
8072159c   Alex Savenko   create proj
585
          }
91fc4901   Yarik   Import fix
586
587
588
589
590
591
592
593
594
          
          private function getProductsFile($file_type)
          {
              $filename = Yii::getAlias('@uploadDir') . '/' . Yii::getAlias('@' . $file_type);
              if (!is_file($filename)) {
                  $this->errors[] = "File $filename not found";
                  return false;
              }
              return fopen($filename, 'r');
8072159c   Alex Savenko   create proj
595
          }
91fc4901   Yarik   Import fix
596
597
598
599
600
601
602
603
604
          
          private function saveNotFoundRecord(array $line, $filename)
          {
              $str = implode(';', $line) . "\n";
              $str = iconv("UTF-8//TRANSLIT//IGNORE", "windows-1251", $str);
              
              $fg = fopen(Yii::getAlias('@uploadDir') . '/' . $filename, 'a+');
              fputs($fg, $str);
              fclose($fg);
8072159c   Alex Savenko   create proj
605
          }
91fc4901   Yarik   Import fix
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
          
          /**
           * @param $filters       array of filters like [['pol'='мужской'],['god' = '2013'],['volume'='25
           *                       л']*['size'='49 x 30 x 20см'],['composition'='600D полиэстер']]
           * @param $level         0 for products and 1 for product variant
           * @param $catalog_names array catalogs id
           *
           * @return array
           */
          private function saveFilters($filters, $level, $catalog_names)
          {
              $options = [];
              foreach ($filters as $filter) {
                  
                  preg_match_all('/\[(.*):(.*)\]/', $filter, $filter);
                  
                  if (empty( $filter[ 1 ][ 0 ] )) {
                      continue;
                  }
                  $filter_name = trim($filter[ 1 ][ 0 ]);
                  
                  $taxGroup = TaxGroup::find()
                                      ->where([ 'alias' => $filter_name ])
                                      ->one();
                  if (!$taxGroup instanceof TaxGroup) {
                      $taxGroup = new TaxGroup();
                      $taxGroup->alias = $filter_name;
                      $taxGroup->level = $level;
                      $taxGroup->name = $filter_name;
                      $taxGroup->module = 'string';
                      $taxGroup->hierarchical = false;
                      $taxGroup->categories = $catalog_names;
                      $taxGroup->is_filter = false;
                      $taxGroup->save();
                  }
                  
                  $filters_options = explode(',', $filter[ 2 ][ 0 ]);
                  
                  foreach ($filters_options as $filter_options) {
aac46b79   Yarik   Import test
645
646
647
648
649
650
651
652
653
                      $parsed_filter = $this->parseFilter($filter_options);
                      $value = null;
                      if ($parsed_filter !== false) {
                          $value = TaxValueString::find()
                                                 ->innerJoinWith('taxOption')
                                                 ->andWhere([ 'tax_option.alias' => $parsed_filter[ 2 ] ])
                                                 ->andWhere([ 'tax_option.tax_group_id' => $taxGroup->tax_group_id ])
                                                 ->one();
                      }
91fc4901   Yarik   Import fix
654
655
656
657
658
                      
                      if (!$value instanceof TaxValueString) {
                          // Create option
                          $option = new TaxOption();
                          $option->tax_group_id = $taxGroup->tax_group_id;
aac46b79   Yarik   Import test
659
660
661
662
663
664
                          if($parsed_filter !== false) {
                              $option->name = $parsed_filter[1];
                              $option->alias = $parsed_filter[2];
                          } else {
                              $option->name = $filter_options;
                          }
91fc4901   Yarik   Import fix
665
666
667
668
                          $option->save();
                          
                          $value = new TaxValueString();
                          $value->tax_option_id = $option->tax_option_id;
aac46b79   Yarik   Import test
669
                          $value->value = $option->name;
91fc4901   Yarik   Import fix
670
671
672
673
                          $value->save();
                          
                          $option->default_value = $value->tax_value_id;
                          $option->save();
2e23f037   Yarik   Import test
674
675
676
677
678
679
680
681
682
                      } else {
                          if($parsed_filter !== false) {
                              $value->value = $parsed_filter[1];
                              $value->taxOption->name = $parsed_filter[1];
                          } else {
                              $value->value = $filter_options;
                              $value->taxOption->name = $filter_options;
                          }
                          $value->save();
91fc4901   Yarik   Import fix
683
684
685
                      }
                      $options[] = $value->tax_option_id;
                      
8072159c   Alex Savenko   create proj
686
                  }
91fc4901   Yarik   Import fix
687
                  
8072159c   Alex Savenko   create proj
688
              }
91fc4901   Yarik   Import fix
689
690
              
              return $options;
8072159c   Alex Savenko   create proj
691
          }
aac46b79   Yarik   Import test
692
693
694
695
696
697
698
699
700
701
          
          private function parseFilter($filter)
          {
              $regex = '/^(.+)\(#(.+)#\)$/';
              if (preg_match($regex, $filter, $result)) {
                  return $result;
              } else {
                  return false;
              }
          }
91fc4901   Yarik   Import fix
702
      }