Blame view

console/controllers/ImportController.php 19.4 KB
3f2bc3d0   Administrator   first commit
1
2
3
4
5
6
  <?php

  

  namespace console\controllers;

  

  use common\modules\product\models\Category;

  use common\modules\product\models\CategoryName;

ccc7a9d3   Karnovsky A   Karnovsky 12052016
7
  use common\modules\product\models\ProductImage;

3f2bc3d0   Administrator   first commit
8
  use common\modules\product\models\ProductVariantType;

5ee9ab1f   Karnovsky A   -
9
  use common\modules\product\models\Stock;

055ecc3b   Karnovsky A   Karnovsky 11052016
10
11
  use common\modules\rubrication\models\TaxOption;

  use common\modules\rubrication\models\TaxValueString;

3f2bc3d0   Administrator   first commit
12
13
14
15
16
17
18
19
20
21
  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\console\Controller;

  use yii\helpers\Console;

  

  class ImportController extends Controller {

5ee9ab1f   Karnovsky A   -
22
23
      private function getProductsFile($file_type = 'uploadFileProducts') {

          $filename = Yii::getAlias('@uploadDir') .'/'. Yii::getAlias('@'. $file_type);

3f2bc3d0   Administrator   first commit
24
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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
94
95
96
97
98
99
100
101
          if (!is_file($filename)) {

              $this->stderr("File $filename not found");

              return FALSE;

          }

          return fopen ($filename, 'r');

      }

  

      public function actionIndex() {

          $new_products = $linked_products = 0;

  

          $db = yii::$app->db;

  

          if ( !($handle = $this->getProductsFile()) ) {

              return Controller::EXIT_CODE_ERROR;

          }

  

          $j = 0;

  

          while (($data = fgetcsv ($handle, 10000, ";")) !== FALSE)

          {

              $j++;

  

              foreach ($data as &$value)

              {

                  //$value = mb_convert_encoding ($value,  "UTF-8", mb_detect_encoding ($value));

                  $value = iconv ('windows-1251', "UTF-8//TRANSLIT//IGNORE", $value);

                  $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))

              {

                  CONTINUE;

              }

  

              // 2  Бренд

              $brand_name = $data[1];

              if (empty ($brand_name))

              {

                  CONTINUE;

              }

  

              // 3  Название товара

              $product_name = $data[2];

              if (empty ($product_name))

              {

                  CONTINUE;

              }

  

              // 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]);

  

              // 10 Цена старая

c34b3aa0   Karnovsky A   -
102
              $product_cost_old = $data[10];

3f2bc3d0   Administrator   first commit
103
104
  

              // 11 Цена

c34b3aa0   Karnovsky A   -
105
              $product_cost = $data[9];

3f2bc3d0   Administrator   first commit
106
107
108
109
110
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
  

              // 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 Галлерея фото

              $fotos = explode (',', $data[17]);

  

              // 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();

              }

  

ccc7a9d3   Karnovsky A   Karnovsky 12052016
138
139
              $is_new_product = empty($_product->product_id);

  

3f2bc3d0   Administrator   first commit
140
              // ==== Set category ====

067092f7   Karnovsky A   -
141
              if ( ($category = CategoryName::find()->filterWhere(['ilike', 'value', trim($catalog_name)])->one()) === null ) {

3f2bc3d0   Administrator   first commit
142
143
144
145
                  // Create category

                  $category = new Category();

                  $category->name = trim($catalog_name);

                  $category->save();

3f2bc3d0   Administrator   first commit
146
              }

067092f7   Karnovsky A   -
147
              $_product->categories = [$category->category_id];

3f2bc3d0   Administrator   first commit
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
  

              // ===== 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;

ccc7a9d3   Karnovsky A   Karnovsky 12052016
165
              $_product->is_top = $product_top;

3f2bc3d0   Administrator   first commit
166
              $_product->akciya = $product_akciya;

ccc7a9d3   Karnovsky A   Karnovsky 12052016
167
              $_product->is_new = $product_new;

3f2bc3d0   Administrator   first commit
168
  

067092f7   Karnovsky A   -
169
170
171
              if (!$_product->save()) {

                  var_dump($category->category_id, $_product->categories);exit;

              }

3f2bc3d0   Administrator   first commit
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
  

  

              // @todo Set image

              /*// картинки

              if (is_file ($dir.'/mod/' . $product_image))

              {

                  $resizeObj = new resize ($dir.'/mod/' . $product_image);

                  $resizeObj->resizeImage (135, 200, 'auto');

                  $resizeObj->saveImage ($dir.'/products/ico/' . $product_image, 100);

                  $resizeObj->resizeImage (370, 370, 'auto');

                  $resizeObj->saveImage ($dir.'/products/big/' . $product_image, 100);

              }*/

  

              // ==== mods ====

  

              // (типа штрих код товара)

  

              // нужно для проставления характеристик относящихся к модификациям

              $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];

c34b3aa0   Karnovsky A   -
201
202
                      $mod_cost   = floatval($product_cost);

                      $mod_old_cost = floatval($product_cost_old);

3f2bc3d0   Administrator   first commit
203
204
  

                      // Check product variant

ccc7a9d3   Karnovsky A   Karnovsky 12052016
205
                      if ( ($_productVariant = ProductVariant::find()->andFilterWhere(['ilike', 'sku', $mod_art])->andFilterWhere(['product_id' => $_product->product_id])->one()) === null ) {

3f2bc3d0   Administrator   first commit
206
207
208
                          $_productVariant = new ProductVariant();

                          $_productVariant->product_id = $_product->product_id;

                      }

ccc7a9d3   Karnovsky A   Karnovsky 12052016
209
                      $_productVariant->product_unit_id = 1;

3f2bc3d0   Administrator   first commit
210
211
212
213
  

                      $_productVariant->sku = $mod_art;

                      $_productVariant->price = $mod_cost;

                      $_productVariant->price_old = $mod_old_cost;

ccc7a9d3   Karnovsky A   Karnovsky 12052016
214
                      $_productVariant->stock = 1;

3f2bc3d0   Administrator   first commit
215
216
  

                      $product_variant_type_name = '';

ccc7a9d3   Karnovsky A   Karnovsky 12052016
217
                      if (! empty ($mod_color)) {

3f2bc3d0   Administrator   first commit
218
                          $product_variant_type_name = 'Цвет';

ccc7a9d3   Karnovsky A   Karnovsky 12052016
219
220
221
                          $_productVariant->name = $mod_color;

                      }

                      elseif (! empty ($mod_size)) {

3f2bc3d0   Administrator   first commit
222
                          $product_variant_type_name = 'Размер';

ccc7a9d3   Karnovsky A   Karnovsky 12052016
223
224
                          $_productVariant->name = $mod_size;

                      }

3f2bc3d0   Administrator   first commit
225
226
227
228
229
230
  

                      // ===== 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 {

3f2bc3d0   Administrator   first commit
231
232
233
234
235
236
                              $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;

                          }

                      }

c34b3aa0   Karnovsky A   -
237
238
239
240
241
242
243
244
245
246
247
                      $_productVariant->save(false);

  //                    if (!$_productVariant->save(false)) {

  ////                        $this->stdout("$j: Product {$_product->name} #{$_product->product_id} NOT saved (". ($is_new_product ? 'new product' : 'exists product') .")\n");

  ////                        var_dump($_productVariant);exit;

  //                        continue;

  //                    }

  

  //                    if ($mod_art == '610934725148') {

  //                        var_dump($_productVariant);

  //                        exit;

  //                    }

ccc7a9d3   Karnovsky A   Karnovsky 12052016
248
249
250
251
  

                      $MOD_ARRAY[] = $_productVariant->product_variant_id;

  

                      if ($mod_image) {

c34b3aa0   Karnovsky A   -
252
253
                          $url = 'http://rukzachok.com.ua/upload/mod/' . urlencode($mod_image);

                          $image = @file_get_contents($url);

ccc7a9d3   Karnovsky A   Karnovsky 12052016
254
255
256
257
258
259
260
261
262
263
264
                          if ($image) {

                              if (($variantImage = ProductImage::find()->andFilterWhere(['ilike', 'image', $mod_image])->andFilterWhere(['product_variant_id' => $_productVariant->product_variant_id])->one()) === null) {

                                  file_put_contents(Yii::getAlias('@productsDir') . "/" . $mod_image, $image);

                                  $variantImage = new ProductImage();

                                  $variantImage->product_id = $_product->product_id;

                                  $variantImage->product_variant_id = $_productVariant->product_variant_id;

                                  $variantImage->image = $mod_image;

                                  $variantImage->save();

                              }

                          }

                      }

3f2bc3d0   Administrator   first commit
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
302
303
304
305
                  }

              }

  

              /*// ==== fotos ====

  

              foreach ($fotos as $foto)

              {

                  $fields = [

                      'product_id' => $product_id,

                      'image' => $foto

                  ];

  

                  $modelFotos = Fotos::find ()

                      ->where ('image=:image', [

                          ':image' => $foto

                      ])

                      ->one ();

  

                  if (empty ($modelFotos->id))

                  {

                      $db->createCommand ()

                          ->insert ('products_fotos', $fields)

                          ->execute ();

                  }

                  else

                  {

                      $db->createCommand ()

                          ->update ('products_fotos', $fields, 'id = ' . $modelFotos->id)

                          ->execute ();

                  }

  

                  if (is_file ($dir.'/fotos/' . $foto))

                  {

                      $resizeObj = new resize ($dir.'/fotos/' . $foto);

                      $resizeObj->resizeImage (100, 100, 'crop');

                      $resizeObj->saveImage ($dir.'/fotos/ico/' . $foto, 100);

                      $resizeObj->resizeImage (400, 400, 'crop');

                      $resizeObj->saveImage ($dir.'/fotos/big/' . $foto, 100);

                  }

              }*/

  

055ecc3b   Karnovsky A   Karnovsky 11052016
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
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
380
381
382
383
384
385
386
              $options = [];

  

              if (! empty ($filters)) {

                  // Set Naznachenie (tax_group_id = 20)

                  foreach($filters as $filter) {

                      $filter = trim($filter);

                      if (!$filter) {

                          continue;

                      }

                      if ( ($value = TaxValueString::find()->innerJoinWith('taxOption')->andFilterWhere(['ilike', 'value', $filter])->andFilterWhere(['tax_option.tax_group_id' => 20])->one()) === null ) {

                          // 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;

                      }

                      if ( ($value = TaxValueString::find()->innerJoinWith('taxOption')->andFilterWhere(['ilike', 'value', $filter])->andFilterWhere(['tax_option.tax_group_id' => 21])->one()) === null ) {

                          // 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;

                      }

                      if ( ($value = TaxValueString::find()->innerJoinWith('taxOption')->andFilterWhere(['ilike', 'value', $filter])->andFilterWhere(['tax_option.tax_group_id' => 22])->one()) === null ) {

                          // 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;

              }

  

3f2bc3d0   Administrator   first commit
387
              $_product->save();

055ecc3b   Karnovsky A   Karnovsky 11052016
388
389
390
  

              $this->stdout("$j: Product {$_product->name} #{$_product->product_id} saved (". ($is_new_product ? 'new product' : 'exists product') .")\n");

  

3f2bc3d0   Administrator   first commit
391
392
393
394
              /*if ($j > 100) {

                  $this->stdout("Dev OK");

                  exit;

              }*/

055ecc3b   Karnovsky A   Karnovsky 11052016
395
  

3f2bc3d0   Administrator   first commit
396
397
398
399
400
401
402
403
404
405
          }

  

          fclose ($handle);

  

          return Controller::EXIT_CODE_NORMAL;

      }

  

      public function goProducts() {

  

      }

5ee9ab1f   Karnovsky A   -
406
407
408
409
410
411
412
413
414
415
416
417
418
  

      public function actionPrices() {

          $new_products = $linked_products = 0;

  

          if ( !($handle = $this->getProductsFile('uploadFilePrices')) ) {

              $this->stdout("File not found\n");

              return Controller::EXIT_CODE_ERROR;

          }

  

          $j = 0;

  

          while (($data = fgetcsv ($handle, 10000, ";")) !== FALSE) {

              $j++;

d48d8bc0   Karnovsky A   -
419
  //            if ($j > 1) {

5ee9ab1f   Karnovsky A   -
420
421
422
423
424
425
426
427
428
429
430
431
  //                return TRUE;

  //            }

  

              foreach ($data as &$value)

              {

                  //$value = mb_convert_encoding ($value,  "UTF-8", mb_detect_encoding ($value));

                  $value = iconv ('windows-1251', "UTF-8//TRANSLIT//IGNORE", $value);

                  $value = trim ($value);

              }

  

              // данные строк

              $modification_code = @$data[0];

d48d8bc0   Karnovsky A   -
432
433
              $_price             = floatval(@$data[1]);

              $_price_promo       = floatval(@$data[2]);

5ee9ab1f   Karnovsky A   -
434
435
436
437
              $count             = intval(@$data[3]);

              $city_name         = @$data[4];

              $product_title     = @$data[5];

  

d48d8bc0   Karnovsky A   -
438
439
440
441
442
443
              // @todo refactory this code

              $price = $_price_promo > 0 ? $_price_promo : $_price;

              $price_promo = $_price_promo > 0 ? $_price : $_price_promo;

  

              $modification_code = trim($modification_code);

  

5ee9ab1f   Karnovsky A   -
444
              if (empty ($modification_code)) {

d48d8bc0   Karnovsky A   -
445
                  continue;

5ee9ab1f   Karnovsky A   -
446
447
448
449
450
451
452
453
454
              }

              // товары в пути

              if (empty ($city_name))

              {

                  $this->saveNotFoundRecord (

                      [$modification_code, $product_title],

                      Yii::getAlias('@uploadFilePricesAway')

                  );

  

d48d8bc0   Karnovsky A   -
455
                  $this->stdout("~ Товар $product_title в пути\n");

5ee9ab1f   Karnovsky A   -
456
  

d48d8bc0   Karnovsky A   -
457
                  continue;

5ee9ab1f   Karnovsky A   -
458
459
              }

  

d48d8bc0   Karnovsky A   -
460
              if ( ($productVariant = ProductVariant::find()->filterWhere(['sku' => $modification_code])->one()) === null ) {

5ee9ab1f   Karnovsky A   -
461
462
463
464
465
466
                  // 'Нет даной модификации в базе';

                  $this->saveNotFoundRecord (

                      [$modification_code, $product_title],

                      Yii::getAlias('@uploadFilePricesNoVariant')

                  );

  

d48d8bc0   Karnovsky A   -
467
                  $this->stdout("- Для товара $product_title (#$modification_code) не найдено соотвествия\n");

5ee9ab1f   Karnovsky A   -
468
  

d48d8bc0   Karnovsky A   -
469
                  continue;

5ee9ab1f   Karnovsky A   -
470
471
472
473
474
475
              }

  

              $quantity = 0;

  

              // ===== Set stock ====

              if ( $city_name ) {

d48d8bc0   Karnovsky A   -
476
                  if ( ($stock = Stock::find()->filterWhere(['name' => trim($city_name)])->one()) === null ) {

5ee9ab1f   Karnovsky A   -
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
                      // Create stock

                      $stock = new Stock();

                      $stock->name = trim($city_name);

                      $stock->save();

                  }

  

                  $productVariant->stocks[$stock->stock_id] = $count;

                  $quantity = $quantity + $count;

              }

  

              $productVariant->price = $price;

              $productVariant->price_old = $price_promo;

              $productVariant->stock = $quantity;

  

              $productVariant->save();

  

d48d8bc0   Karnovsky A   -
493
              $this->stdout("+ Товар $product_title успешно сохранен\n");

5ee9ab1f   Karnovsky A   -
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
          }

          fclose ($handle);

  

          unlink(Yii::getAlias('@uploadDir') .'/'. Yii::getAlias('@uploadFilePrices'));

  

          return Controller::EXIT_CODE_NORMAL;

      }

  

      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);

      }

3f2bc3d0   Administrator   first commit
511
  }