Blame view

common/modules/product/models/Import.php 19.6 KB
8724ec1f   Karnovsky A   -
1
2
3
4
  <?php
  
  namespace common\modules\product\models;
  
c7852657   Karnovsky A   -
5
  use common\modules\product\helpers\ProductHelper;
8724ec1f   Karnovsky A   -
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  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\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;
  
  class Import extends Model {
      public $file;
5ee9ab1f   Karnovsky A   -
22
      public $type;
8724ec1f   Karnovsky A   -
23
24
25
26
27
28
29
30
31
32
  
      public $errors = [];
      public $output = [];
  
      /**
       * @inheritdoc
       */
      public function rules()
      {
          return [
5ee9ab1f   Karnovsky A   -
33
34
              [['type'], 'required'],
              [['type'], 'string'],
10e0f427   Karnovsky A   -
35
  //            [['file'], 'safe'],
5ee9ab1f   Karnovsky A   -
36
              [['file'], 'file', 'extensions' => 'csv'],
8724ec1f   Karnovsky A   -
37
38
39
40
41
42
43
44
45
46
47
48
49
          ];
      }
  
      /**
       * @inheritdoc
       */
      public function attributeLabels()
      {
          return [
              'file' => Yii::t('product', 'File'),
          ];
      }
  
5ee9ab1f   Karnovsky A   -
50
51
52
53
54
55
      public function getType() {
          if (!$this->type) {
              $this->type = 'products';
          }
          return $this->type;
      }
8724ec1f   Karnovsky A   -
56
  
37c2918b   Karnovsky A   -
57
58
59
60
61
62
63
64
65
      public function goPrices($from = 0, $limit = null) {
          set_time_limit(0);
          $new_products = $linked_products = 0;
  
          if ( !($handle = $this->getProductsFile('uploadFilePrices')) ) {
              $this->errors[] = 'File not found';
              return FALSE;
          }
  
f7f95504   Karnovsky A   -
66
          $filesize = filesize(Yii::getAlias('@uploadDir') .'/'. Yii::getAlias('@uploadFilePrices'));
37c2918b   Karnovsky A   -
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
          if ($from) {
              fseek($handle, $from);
          }
  
          $j = 0;
  
          $is_utf = (preg_match('//u', file_get_contents(Yii::getAlias('@uploadDir') .'/'. Yii::getAlias('@uploadFilePrices'), null, null, null, 1000000)));
  
          while (($data = fgetcsv ($handle, 10000, ";")) !== FALSE && (empty($limit) || $j++ < $limit))
          {
              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)) {
49c47c76   Karnovsky A   -
94
                  continue;
37c2918b   Karnovsky A   -
95
96
97
98
              }
              // товары в пути
              if (empty ($city_name))
              {
f7f95504   Karnovsky A   -
99
100
101
102
  //                $this->saveNotFoundRecord (
  //                    [$modification_code, $product_title],
  //                    Yii::getAlias('@uploadFilePricesAway')
  //                );
37c2918b   Karnovsky A   -
103
104
105
  
                  $this->output[] = 'Товар '. $product_title . ' в пути';
  
49c47c76   Karnovsky A   -
106
                  continue;
37c2918b   Karnovsky A   -
107
108
              }
  
f7f95504   Karnovsky A   -
109
              if ( ($productVariant = ProductVariant::find()->filterWhere(['sku' => $modification_code])->one()) === null ) {
37c2918b   Karnovsky A   -
110
                  // 'Нет даной модификации в базе';
f7f95504   Karnovsky A   -
111
112
113
114
  //                $this->saveNotFoundRecord (
  //                    [$modification_code, $product_title],
  //                    Yii::getAlias('@uploadFilePricesNoVariant')
  //                );
37c2918b   Karnovsky A   -
115
116
117
  
                  $this->output[] = 'Для товара '. $product_title . ' не найдено соотвествие';
  
49c47c76   Karnovsky A   -
118
                  continue;
37c2918b   Karnovsky A   -
119
120
              }
  
f7f95504   Karnovsky A   -
121
  
37c2918b   Karnovsky A   -
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
              $quantity = 0;
  
              // ===== Set stock ====
              if ( $city_name ) {
                  if ( ($stock = Stock::find()->filterWhere(['ilike', 'name', trim($city_name)])->one()) === null ) {
                      // Create stock
                      $stock = new Stock();
                      $stock->name = trim($city_name);
                      $stock->save();
                  }
  
                  $productVariant->stocks[$stock->stock_id] = $count;
                  $quantity = $quantity + $count;
              }
  
49c47c76   Karnovsky A   -
137
138
139
140
141
142
143
144
              if ($price_promo) {
                  $productVariant->price_old = $price;
                  $productVariant->price = $price_promo;
              } else {
                  $productVariant->price = $price;
                  $productVariant->price_old = $price_promo;
              }
  
37c2918b   Karnovsky A   -
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
              $productVariant->stock = $quantity;
  
              $productVariant->save();
  
              $this->output[] = '<font style="color:blue">Товар '. $product_title .' успешно сохранен</font>';
          }
  
          $result = [
              'end' => feof($handle),
              'from' => ftell($handle),
              'totalsize' => $filesize,
              'items' => $this->output,
  
          ];
  
          fclose ($handle);
  
          if ($result['end']) {
              unlink(Yii::getAlias('@uploadDir') .'/'. Yii::getAlias('@uploadFilePrices'));
37c2918b   Karnovsky A   -
164
165
166
167
168
169
          }
  
          return $result;
      }
  
      public function goProducts($from = 0, $limit = null) {
5ee9ab1f   Karnovsky A   -
170
          set_time_limit(0);
8724ec1f   Karnovsky A   -
171
172
          $new_products = $linked_products = 0;
  
5ee9ab1f   Karnovsky A   -
173
          if ( !($handle = $this->getProductsFile('uploadFileProducts')) ) {
8724ec1f   Karnovsky A   -
174
175
176
177
              $this->errors[] = 'File not found';
              return FALSE;
          }
  
37c2918b   Karnovsky A   -
178
179
180
181
182
183
          $filesize = filesize(Yii::getAlias('@uploadDir') .'/'. Yii::getAlias('@uploadFileProducts'));
  
          if ($from) {
              fseek($handle, $from);
          }
  
8724ec1f   Karnovsky A   -
184
185
          $j = 0;
  
c7852657   Karnovsky A   -
186
187
          $is_utf = (preg_match('//u', file_get_contents(Yii::getAlias('@uploadDir') .'/'. Yii::getAlias('@uploadFileProducts'), null, null, null, 1000000)));
  
37c2918b   Karnovsky A   -
188
          $result_items = [];
8724ec1f   Karnovsky A   -
189
  
37c2918b   Karnovsky A   -
190
191
          while (($data = fgetcsv ($handle, 10000, ";")) !== FALSE && (empty($limit) || $j++ < $limit))
          {
8724ec1f   Karnovsky A   -
192
193
              foreach ($data as &$value)
              {
c7852657   Karnovsky A   -
194
195
196
                  if (!$is_utf) {
                      $value = iconv ('windows-1251', "UTF-8//TRANSLIT//IGNORE", $value);
                  }
8724ec1f   Karnovsky A   -
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
                  $value = trim ($value);
              }
  
              // будет всегда 19 элементов
              for ($i = 0; $i <= 18; $i++)
              {
                  if (! isset ($data[$i]))
                  {
                      $data[$i] = null;
                  }
              }
  
              // 1  Группа (категория)
              $catalog_name = $data[0];
              if (empty ($catalog_name))
              {
37c2918b   Karnovsky A   -
213
                  $result_items[] = "Не указана категория (строка $j)";
49c47c76   Karnovsky A   -
214
                  continue;
8724ec1f   Karnovsky A   -
215
216
217
218
219
220
              }
  
              // 2  Бренд
              $brand_name = $data[1];
              if (empty ($brand_name))
              {
37c2918b   Karnovsky A   -
221
                  $result_items[] = "Не указан бренд (строка $j)";
49c47c76   Karnovsky A   -
222
                  continue;
8724ec1f   Karnovsky A   -
223
224
225
226
227
228
              }
  
              // 3  Название товара
              $product_name = $data[2];
              if (empty ($product_name))
              {
37c2918b   Karnovsky A   -
229
                  $result_items[] = "Не указано наименование товара (строка $j)";
49c47c76   Karnovsky A   -
230
                  continue;
8724ec1f   Karnovsky A   -
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
              }
  
              // 4  Описание Укр
              $product_body_uk = $data[3];
  
              // 5  Описание Рус
              $product_body_ru = $data[4];
  
              // 6  Фильтр (через запятую)
              $filters = explode (',', $data[5]);
  
              // 7  Доп фильтр через запятую
              $filters_extra = explode (',', $data[6]);
  
              // 8  Пол череззапятую (мужской, женский, детский, унисекс)
              $gender = explode (',', $data[7]);
  
              // 9  Год
              $years = explode (',', $data[8]);
  
49c47c76   Karnovsky A   -
251
252
              // 11 Цена акция
              $product_cost_old = floatval($data[10]);
8724ec1f   Karnovsky A   -
253
  
49c47c76   Karnovsky A   -
254
255
256
257
258
              // 10 Цена
              if ($product_cost_old) {
                  $product_cost_old = floatval($data[9]);
                  $product_cost = floatval($data[10]);
              }
8724ec1f   Karnovsky A   -
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
  
              // 12 Акция
              $product_akciya = (bool)$data[11];
  
              // 13 Сопуд. Тов.
              $similar = explode (',', $data[12]);
  
              // 14 Новинки
              $product_new = (bool)$data[13];
  
              // 15 Топ продаж
              $product_top = (bool)$data[14];
  
              // 16 Сетка  Характеристик
              $feature = explode ('=', $data[15]);
  
              // 17 ВИДЕО КОД
              $product_video = $data[16];
  
              // 18 Галлерея фото
37c2918b   Karnovsky A   -
279
280
281
              if (trim($data[17])) {
                  $fotos = explode (',', trim($data[17]));
              }
8724ec1f   Karnovsky A   -
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
  
              // 19 Штрих код товара.
              // расшифровал - это модификации товара!
  
              $product_image = explode ('=', $data[18]);
              $product_image = @$product_image[3];
  
              if ( ($_product = Product::find()->filterWhere(['ilike', 'name', trim($product_name)])->one()) === null ) {
                  $_product = new Product();
              }
  
              $is_new_product = empty($_product->product_id);
  
              // ==== Set category ====
              if ( ($category = CategoryName::find()->filterWhere(['ilike', 'value', trim($catalog_name)])->one()) === null ) {
                  // Create category
                  $category = new Category();
                  $category->name = trim($catalog_name);
                  $category->save();
              }
              $_product->categories = [$category->category_id];
  
              // ===== Set brand ====
              if ( $brand_name ) {
                  if ( ($brand = BrandName::find()->filterWhere(['ilike', 'value', 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;
                  }
              }
  
              $_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()) {
37c2918b   Karnovsky A   -
325
                  $result_items[] = 'Product #'. $_product->name .' not saved' . " (строка $j)";
8724ec1f   Karnovsky A   -
326
327
328
                  continue;
              }
  
37c2918b   Karnovsky A   -
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
              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(['ilike', '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();
                          }
                      }
                  }
              }
  
8724ec1f   Karnovsky A   -
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
              // нужно для проставления характеристик относящихся к модификациям
              $MOD_ARRAY = [];
  
              for ($i = 18; $i < count ($data); $i ++)
              {
                  if (! empty ($data[$i]))
                  {
                      $mod_arr    = explode ('=', $data[$i]);
                      $mod_art    = $mod_arr[0];
                      $mod_size   = $mod_arr[1];
                      $mod_color  = $mod_arr[2];
                      $mod_image  = $mod_arr[3];
                      $mod_cost   = floatval($product_cost);
                      $mod_old_cost = floatval($product_cost_old);
  
                      // Check product variant
                      if ( ($_productVariant = ProductVariant::find()->andFilterWhere(['ilike', '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 = 1;
  
                      $product_variant_type_name = '';
                      if (! empty ($mod_color)) {
                          $product_variant_type_name = 'Цвет';
                          $_productVariant->name = $mod_color;
                      }
                      elseif (! empty ($mod_size)) {
                          $product_variant_type_name = 'Размер';
                          $_productVariant->name = $mod_size;
                      }
  
                      // ===== Set variant type ====
                      if ( $product_variant_type_name ) {
                          if ( ($product_variant_type = ProductVariantType::find()->filterWhere(['ilike', '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(false);
  
                      $MOD_ARRAY[] = $_productVariant->product_variant_id;
  
                      if ($mod_image) {
37c2918b   Karnovsky A   -
398
399
                          $source_image = Yii::getAlias('@uploadDir') . '/product_images/'. urlencode($mod_image);
                          if (file_exists($source_image)) {
8724ec1f   Karnovsky A   -
400
                              if (($variantImage = ProductImage::find()->andFilterWhere(['ilike', 'image', $mod_image])->andFilterWhere(['product_variant_id' => $_productVariant->product_variant_id])->one()) === null) {
37c2918b   Karnovsky A   -
401
                                  copy($source_image, Yii::getAlias('@productsDir') . "/" . $mod_image);
8724ec1f   Karnovsky A   -
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
                                  $variantImage = new ProductImage();
                                  $variantImage->product_id = $_product->product_id;
                                  $variantImage->product_variant_id = $_productVariant->product_variant_id;
                                  $variantImage->image = $mod_image;
                                  $variantImage->save();
                              }
                          }
                      }
                  }
              }
  
              $options = [];
  
              if (! empty ($filters)) {
                  // Set Naznachenie (tax_group_id = 20)
                  foreach($filters as $filter) {
                      $filter = trim($filter);
                      if (!$filter) {
                          continue;
                      }
c7852657   Karnovsky A   -
422
                      if ( ($value = TaxValueString::find()->innerJoinWith('taxOption')->andFilterWhere(['ilike', 'value', $filter])->andFilterWhere(['tax_option.tax_group_id' => ProductHelper::PRODUCT_TAX_GROUP_ID_TARGET])->one()) === null ) {
8724ec1f   Karnovsky A   -
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
                          // Create option
                          $option = new TaxOption();
                          $option->tax_group_id = 20;
                          $option->save();
  
                          $value = new TaxValueString();
                          $value->tax_option_id = $option->tax_option_id;
                          $value->value = $filter;
                          $value->save();
  
                          $option->default_value = $value->tax_value_id;
                          $option->save();
                      }
                      $options[] = $value->tax_option_id;
                  }
              }
  
              if (! empty ($years)) {
                  // Set God (tax_group_id = 21)
                  foreach($years as $filter) {
                      $filter = trim($filter);
                      if (!$filter) {
                          continue;
                      }
c7852657   Karnovsky A   -
447
                      if ( ($value = TaxValueString::find()->innerJoinWith('taxOption')->andFilterWhere(['ilike', 'value', $filter])->andFilterWhere(['tax_option.tax_group_id' => ProductHelper::PRODUCT_TAX_GROUP_ID_YEAR])->one()) === null ) {
8724ec1f   Karnovsky A   -
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
                          // Create option
                          $option = new TaxOption();
                          $option->tax_group_id = 21;
                          $option->save();
  
                          $value = new TaxValueString();
                          $value->tax_option_id = $option->tax_option_id;
                          $value->value = $filter;
                          $value->save();
  
                          $option->default_value = $value->tax_value_id;
                          $option->save();
                      }
                      $options[] = $value->tax_option_id;
                  }
              }
  
              if (! empty ($gender)) {
                  // Set Pol (tax_group_id = 22)
                  foreach($gender as $filter) {
                      $filter = trim($filter);
                      if (!$filter) {
                          continue;
                      }
c7852657   Karnovsky A   -
472
                      if ( ($value = TaxValueString::find()->innerJoinWith('taxOption')->andFilterWhere(['ilike', 'value', $filter])->andFilterWhere(['tax_option.tax_group_id' => ProductHelper::PRODUCT_TAX_GROUP_ID_SEX])->one()) === null ) {
8724ec1f   Karnovsky A   -
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
                          // Create option
                          $option = new TaxOption();
                          $option->tax_group_id = 22;
                          $option->save();
  
                          $value = new TaxValueString();
                          $value->tax_option_id = $option->tax_option_id;
                          $value->value = $filter;
                          $value->save();
  
                          $option->default_value = $value->tax_value_id;
                          $option->save();
                      }
                      $options[] = $value->tax_option_id;
                  }
              }
  
              if (!empty($options)) {
                  $_product->options = $options;
              }
  
              $_product->save();
  
37c2918b   Karnovsky A   -
496
              $result_items[] = "Product {$_product->name} #{$_product->product_id} saved (". ($is_new_product ? 'new product' : 'exists product') .")" . " (строка $j)";
8724ec1f   Karnovsky A   -
497
498
          }
  
37c2918b   Karnovsky A   -
499
500
501
502
503
          $result = [
              'end' => feof($handle),
              'from' => ftell($handle),
              'totalsize' => $filesize,
              'items' => $result_items,
8724ec1f   Karnovsky A   -
504
  
37c2918b   Karnovsky A   -
505
          ];
8724ec1f   Karnovsky A   -
506
  
37c2918b   Karnovsky A   -
507
          fclose ($handle);
5ee9ab1f   Karnovsky A   -
508
  
37c2918b   Karnovsky A   -
509
510
          if ($result['end']) {
              unlink(Yii::getAlias('@uploadDir') .'/'. Yii::getAlias('@uploadFileProducts'));
5ee9ab1f   Karnovsky A   -
511
512
          }
  
37c2918b   Karnovsky A   -
513
          return $result;
5ee9ab1f   Karnovsky A   -
514
515
516
517
      }
  
      private function getProductsFile($file_type) {
          $filename = Yii::getAlias('@uploadDir') .'/'. Yii::getAlias('@'. $file_type);
8724ec1f   Karnovsky A   -
518
          if (!is_file($filename)) {
5ee9ab1f   Karnovsky A   -
519
              $this->errors[] = "File $filename not found";
8724ec1f   Karnovsky A   -
520
521
522
523
              return FALSE;
          }
          return fopen ($filename, 'r');
      }
5ee9ab1f   Karnovsky A   -
524
525
526
527
528
529
530
531
532
533
  
      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);
      }
8724ec1f   Karnovsky A   -
534
  }