Commit ab917b7436f86e52d80f204b5ec2a14e41312c25

Authored by Karnovsky A
1 parent 58552c89

Import

common/modules/product/controllers/ManageController.php
... ... @@ -268,15 +268,23 @@ class ManageController extends Controller
268 268 if ($model->load(Yii::$app->request->post())) {
269 269 $file = UploadedFile::getInstances($model, 'file');
270 270 $method = 'go'. ucfirst($model->type);
  271 + $target = Yii::getAlias('@uploadDir') .'/'. Yii::getAlias('@uploadFile'. ucfirst($model->type));
271 272 if (empty($file)) {
272 273 $model->errors[] = 'File not upload';
273 274 } elseif ($method == 'goPrices' && $file[0]->name != 'file_1.csv') {
274 275 $model->errors[] = 'File need "file_1.csv"';
275 276 } elseif ($method == 'goProducts' && $file[0]->name == 'file_1.csv') {
276 277 $model->errors[] = 'File can not "file_1.csv"';
277   - } elseif ($model->validate()) {
278   - $file[0]->saveAs(Yii::getAlias('@uploadDir') .'/'. Yii::getAlias('@uploadFile'. ucfirst($model->type)));
279   - $model->$method();
  278 + } elseif ($model->validate() && $file[0]->saveAs($target)) {
  279 + // PROCESS PAGE
  280 + return $this->render('import-process', [
  281 + 'model' => $model,
  282 + 'method' => $model->type,
  283 + 'target' => $target,
  284 + ]);
  285 +// $model->$method();
  286 + } else {
  287 + $model->errors[] = 'File can not be upload or other error';
280 288 }
281 289 }
282 290  
... ... @@ -285,6 +293,28 @@ class ManageController extends Controller
285 293 ]);
286 294 }
287 295  
  296 + public function actionProducts() {
  297 + $from = Yii::$app->request->get('from', 0);
  298 +
  299 + $model = new Import();
  300 +
  301 + if (Yii::$app->request->isAjax) {
  302 + Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  303 + return $model->goProducts($from, 10);
  304 + }
  305 + }
  306 +
  307 + public function actionPrices() {
  308 + $from = Yii::$app->request->get('from', 0);
  309 +
  310 + $model = new Import();
  311 +
  312 + if (Yii::$app->request->isAjax) {
  313 + Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  314 + return $model->goPrices($from, 10);
  315 + }
  316 + }
  317 +
288 318 public function actionExport() {
289 319 $model = new Export();
290 320 if (($file = $model->process(Yii::getAlias('@uploadDir')))) {
... ...
common/modules/product/views/manage/import-process.php 0 → 100644
  1 +<?php
  2 +
  3 +use yii\helpers\Html;
  4 +use yii\widgets\ActiveForm;
  5 +
  6 +$this->registerJs("
  7 +
  8 +");
  9 +?>
  10 +
  11 +<script type="text/javascript">
  12 + jQuery(document).ready(function () {
  13 + var in_process=false;
  14 + var count=1;
  15 +
  16 + in_process=true;
  17 +
  18 + doImport();
  19 +
  20 +// $('ul#process-result').prepend('<li style="color: green; font-weight: bold">Импорт завершен</li>');
  21 +
  22 + function doImport(from) {
  23 + from = typeof(from) != 'undefined' ? from : 0;
  24 + console.log('go', from);
  25 + $.ajax({
  26 + url: "<?= Yii::$app->request->baseUrl .'/product/manage/'. $method?>",
  27 + data: {from:from},
  28 + dataType: 'json',
  29 + success: function(data){
  30 + for(var key in data.items)
  31 + {
  32 + $('ul#process-result').prepend('<li>'+ data.items[key] +'</li>');
  33 + count++;
  34 + }
  35 +
  36 + var per = Math.round(100*data.from/data.totalsize)+'%';
  37 + $('#progressbar div').css({width: per});
  38 +// $('#progressbar .ui-progressbar-value').html(per);
  39 +
  40 + if(data != false && !data.end)
  41 + {
  42 + doImport(data.from);
  43 + }
  44 + else
  45 + {
  46 + progressbar.hide('fast');
  47 + in_process = false;
  48 + }
  49 + },
  50 + error: function(xhr, status, errorThrown) {
  51 + alert(errorThrown+'\n'+xhr.responseText);
  52 + }
  53 + });
  54 + }
  55 +
  56 + });
  57 +</script>
  58 +
  59 +<div class="product-import-process-form">
  60 + <h1>Импорт <?= $method == 'prices' ? 'цен' : 'данных'?> товаров</h1>
  61 +
  62 + <?= \yii\jui\ProgressBar::widget([
  63 + 'clientOptions' => [
  64 + 'value' => 100,
  65 + 'label' => 'ddd'
  66 + ],
  67 + 'options' => [
  68 + 'id' => 'progressbar'
  69 + ],
  70 + ]);?>
  71 + <ul id="process-result"></ul>
  72 +</div>
... ...
console/controllers/ImportController.php
... ... @@ -4,6 +4,7 @@ namespace console\controllers;
4 4  
5 5 use common\modules\product\models\Category;
6 6 use common\modules\product\models\CategoryName;
  7 +use common\modules\product\models\Import;
7 8 use common\modules\product\models\ProductImage;
8 9 use common\modules\product\models\ProductVariantType;
9 10 use common\modules\product\models\Stock;
... ... @@ -28,473 +29,16 @@ class ImportController extends Controller {
28 29 return fopen ($filename, 'r');
29 30 }
30 31  
31   - public function actionIndex() {
32   - $new_products = $linked_products = 0;
33   -
34   - $db = yii::$app->db;
35   -
36   - if ( !($handle = $this->getProductsFile()) ) {
37   - return Controller::EXIT_CODE_ERROR;
38   - }
39   -
40   - $j = 0;
41   -
42   - while (($data = fgetcsv ($handle, 10000, ";")) !== FALSE)
43   - {
44   - $j++;
45   -
46   - foreach ($data as &$value)
47   - {
48   - //$value = mb_convert_encoding ($value, "UTF-8", mb_detect_encoding ($value));
49   - $value = iconv ('windows-1251', "UTF-8//TRANSLIT//IGNORE", $value);
50   - $value = trim ($value);
51   - }
52   -
53   - // будет всегда 19 элементов
54   - for ($i = 0; $i <= 18; $i++)
55   - {
56   - if (! isset ($data[$i]))
57   - {
58   - $data[$i] = null;
59   - }
60   - }
61   -
62   - // 1 Группа (категория)
63   - $catalog_name = $data[0];
64   - if (empty ($catalog_name))
65   - {
66   - CONTINUE;
67   - }
68   -
69   - // 2 Бренд
70   - $brand_name = $data[1];
71   - if (empty ($brand_name))
72   - {
73   - CONTINUE;
74   - }
75   -
76   - // 3 Название товара
77   - $product_name = $data[2];
78   - if (empty ($product_name))
79   - {
80   - CONTINUE;
81   - }
82   -
83   - // 4 Описание Укр
84   - $product_body_uk = $data[3];
85   -
86   - // 5 Описание Рус
87   - $product_body_ru = $data[4];
88   -
89   - // 6 Фильтр (через запятую)
90   - $filters = explode (',', $data[5]);
91   -
92   - // 7 Доп фильтр через запятую
93   - $filters_extra = explode (',', $data[6]);
94   -
95   - // 8 Пол череззапятую (мужской, женский, детский, унисекс)
96   - $gender = explode (',', $data[7]);
97   -
98   - // 9 Год
99   - $years = explode (',', $data[8]);
100   -
101   - // 10 Цена старая
102   - $product_cost_old = $data[10];
103   -
104   - // 11 Цена
105   - $product_cost = $data[9];
106   -
107   - // 12 Акция
108   - $product_akciya = (bool)$data[11];
109   -
110   - // 13 Сопуд. Тов.
111   - $similar = explode (',', $data[12]);
112   -
113   - // 14 Новинки
114   - $product_new = (bool)$data[13];
115   -
116   - // 15 Топ продаж
117   - $product_top = (bool)$data[14];
118   -
119   - // 16 Сетка Характеристик
120   - $feature = explode ('=', $data[15]);
121   -
122   - // 17 ВИДЕО КОД
123   - $product_video = $data[16];
124   -
125   - // 18 Галлерея фото
126   - $fotos = explode (',', $data[17]);
127   -
128   - // 19 Штрих код товара.
129   - // расшифровал - это модификации товара!
130   -
131   - $product_image = explode ('=', $data[18]);
132   - $product_image = @$product_image[3];
133   -
134   - if ( ($_product = Product::find()->filterWhere(['ilike', 'name', trim($product_name)])->one()) === null ) {
135   - $_product = new Product();
136   - }
137   -
138   - $is_new_product = empty($_product->product_id);
139   -
140   - // ==== Set category ====
141   - if ( ($category = CategoryName::find()->filterWhere(['ilike', 'value', trim($catalog_name)])->one()) === null ) {
142   - // Create category
143   - $category = new Category();
144   - $category->name = trim($catalog_name);
145   - $category->save();
146   - }
147   - $_product->categories = [$category->category_id];
148   -
149   - // ===== Set brand ====
150   - if ( $brand_name ) {
151   - if ( ($brand = BrandName::find()->filterWhere(['ilike', 'value', trim($brand_name)])->one()) !== null ) {
152   - $_product->brand_id = $brand->brand_id;
153   - } else {
154   - // Create brand
155   - $brand = new Brand();
156   - $brand->name = trim($brand_name);
157   - $brand->save();
158   - $_product->brand_id = $brand->brand_id;
159   - }
160   - }
161   -
162   - $_product->name = $product_name;
163   - $_product->video = $product_video;
164   - $_product->description = $product_body_ru;
165   - $_product->is_top = $product_top;
166   - $_product->akciya = $product_akciya;
167   - $_product->is_new = $product_new;
168   -
169   - if (!$_product->save()) {
170   - var_dump($category->category_id, $_product->categories);exit;
171   - }
172   -
173   -
174   - // @todo Set image
175   - /*// картинки
176   - if (is_file ($dir.'/mod/' . $product_image))
177   - {
178   - $resizeObj = new resize ($dir.'/mod/' . $product_image);
179   - $resizeObj->resizeImage (135, 200, 'auto');
180   - $resizeObj->saveImage ($dir.'/products/ico/' . $product_image, 100);
181   - $resizeObj->resizeImage (370, 370, 'auto');
182   - $resizeObj->saveImage ($dir.'/products/big/' . $product_image, 100);
183   - }*/
184   -
185   - // ==== mods ====
186   -
187   - // (типа штрих код товара)
188   -
189   - // нужно для проставления характеристик относящихся к модификациям
190   - $MOD_ARRAY = [];
191   -
192   - for ($i = 18; $i < count ($data); $i ++)
193   - {
194   - if (! empty ($data[$i]))
195   - {
196   - $mod_arr = explode ('=', $data[$i]);
197   - $mod_art = $mod_arr[0];
198   - $mod_size = $mod_arr[1];
199   - $mod_color = $mod_arr[2];
200   - $mod_image = $mod_arr[3];
201   - $mod_cost = floatval($product_cost);
202   - $mod_old_cost = floatval($product_cost_old);
203   -
204   - // Check product variant
205   - if ( ($_productVariant = ProductVariant::find()->andFilterWhere(['ilike', 'sku', $mod_art])->andFilterWhere(['product_id' => $_product->product_id])->one()) === null ) {
206   - $_productVariant = new ProductVariant();
207   - $_productVariant->product_id = $_product->product_id;
208   - }
209   - $_productVariant->product_unit_id = 1;
210   -
211   - $_productVariant->sku = $mod_art;
212   - $_productVariant->price = $mod_cost;
213   - $_productVariant->price_old = $mod_old_cost;
214   - $_productVariant->stock = 1;
215   -
216   - $product_variant_type_name = '';
217   - if (! empty ($mod_color)) {
218   - $product_variant_type_name = 'Цвет';
219   - $_productVariant->name = $mod_color;
220   - }
221   - elseif (! empty ($mod_size)) {
222   - $product_variant_type_name = 'Размер';
223   - $_productVariant->name = $mod_size;
224   - }
225   -
226   - // ===== Set variant type ====
227   - if ( $product_variant_type_name ) {
228   - if ( ($product_variant_type = ProductVariantType::find()->filterWhere(['ilike', 'name', $product_variant_type_name])->one()) !== null ) {
229   - $_productVariant->product_variant_type_id = $product_variant_type->product_variant_type_id;
230   - } else {
231   - $product_variant_type = new ProductVariantType();
232   - $product_variant_type->name = $product_variant_type_name;
233   - $product_variant_type->save();
234   - $_productVariant->product_variant_type_id = $product_variant_type->product_variant_type_id;
235   - }
236   - }
237   - $_productVariant->save(false);
238   -// if (!$_productVariant->save(false)) {
239   -//// $this->stdout("$j: Product {$_product->name} #{$_product->product_id} NOT saved (". ($is_new_product ? 'new product' : 'exists product') .")\n");
240   -//// var_dump($_productVariant);exit;
241   -// continue;
242   -// }
243   -
244   -// if ($mod_art == '610934725148') {
245   -// var_dump($_productVariant);
246   -// exit;
247   -// }
248   -
249   - $MOD_ARRAY[] = $_productVariant->product_variant_id;
250   -
251   - if ($mod_image) {
252   - $url = 'http://rukzachok.com.ua/upload/mod/' . urlencode($mod_image);
253   - $image = @file_get_contents($url);
254   - if ($image) {
255   - if (($variantImage = ProductImage::find()->andFilterWhere(['ilike', 'image', $mod_image])->andFilterWhere(['product_variant_id' => $_productVariant->product_variant_id])->one()) === null) {
256   - file_put_contents(Yii::getAlias('@productsDir') . "/" . $mod_image, $image);
257   - $variantImage = new ProductImage();
258   - $variantImage->product_id = $_product->product_id;
259   - $variantImage->product_variant_id = $_productVariant->product_variant_id;
260   - $variantImage->image = $mod_image;
261   - $variantImage->save();
262   - }
263   - }
264   - }
265   - }
266   - }
267   -
268   - /*// ==== fotos ====
269   -
270   - foreach ($fotos as $foto)
271   - {
272   - $fields = [
273   - 'product_id' => $product_id,
274   - 'image' => $foto
275   - ];
276   -
277   - $modelFotos = Fotos::find ()
278   - ->where ('image=:image', [
279   - ':image' => $foto
280   - ])
281   - ->one ();
282   -
283   - if (empty ($modelFotos->id))
284   - {
285   - $db->createCommand ()
286   - ->insert ('products_fotos', $fields)
287   - ->execute ();
288   - }
289   - else
290   - {
291   - $db->createCommand ()
292   - ->update ('products_fotos', $fields, 'id = ' . $modelFotos->id)
293   - ->execute ();
294   - }
295   -
296   - if (is_file ($dir.'/fotos/' . $foto))
297   - {
298   - $resizeObj = new resize ($dir.'/fotos/' . $foto);
299   - $resizeObj->resizeImage (100, 100, 'crop');
300   - $resizeObj->saveImage ($dir.'/fotos/ico/' . $foto, 100);
301   - $resizeObj->resizeImage (400, 400, 'crop');
302   - $resizeObj->saveImage ($dir.'/fotos/big/' . $foto, 100);
303   - }
304   - }*/
305   -
306   - $options = [];
307   -
308   - if (! empty ($filters)) {
309   - // Set Naznachenie (tax_group_id = 20)
310   - foreach($filters as $filter) {
311   - $filter = trim($filter);
312   - if (!$filter) {
313   - continue;
314   - }
315   - if ( ($value = TaxValueString::find()->innerJoinWith('taxOption')->andFilterWhere(['ilike', 'value', $filter])->andFilterWhere(['tax_option.tax_group_id' => 20])->one()) === null ) {
316   - // Create option
317   - $option = new TaxOption();
318   - $option->tax_group_id = 20;
319   - $option->save();
320   -
321   - $value = new TaxValueString();
322   - $value->tax_option_id = $option->tax_option_id;
323   - $value->value = $filter;
324   - $value->save();
325   -
326   - $option->default_value = $value->tax_value_id;
327   - $option->save();
328   - }
329   - $options[] = $value->tax_option_id;
330   - }
331   - }
332   -
333   - if (! empty ($years)) {
334   - // Set God (tax_group_id = 21)
335   - foreach($years as $filter) {
336   - $filter = trim($filter);
337   - if (!$filter) {
338   - continue;
339   - }
340   - if ( ($value = TaxValueString::find()->innerJoinWith('taxOption')->andFilterWhere(['ilike', 'value', $filter])->andFilterWhere(['tax_option.tax_group_id' => 21])->one()) === null ) {
341   - // Create option
342   - $option = new TaxOption();
343   - $option->tax_group_id = 21;
344   - $option->save();
345   -
346   - $value = new TaxValueString();
347   - $value->tax_option_id = $option->tax_option_id;
348   - $value->value = $filter;
349   - $value->save();
350   -
351   - $option->default_value = $value->tax_value_id;
352   - $option->save();
353   - }
354   - $options[] = $value->tax_option_id;
355   - }
356   - }
357   -
358   - if (! empty ($gender)) {
359   - // Set Pol (tax_group_id = 22)
360   - foreach($gender as $filter) {
361   - $filter = trim($filter);
362   - if (!$filter) {
363   - continue;
364   - }
365   - if ( ($value = TaxValueString::find()->innerJoinWith('taxOption')->andFilterWhere(['ilike', 'value', $filter])->andFilterWhere(['tax_option.tax_group_id' => 22])->one()) === null ) {
366   - // Create option
367   - $option = new TaxOption();
368   - $option->tax_group_id = 22;
369   - $option->save();
370   -
371   - $value = new TaxValueString();
372   - $value->tax_option_id = $option->tax_option_id;
373   - $value->value = $filter;
374   - $value->save();
375   -
376   - $option->default_value = $value->tax_value_id;
377   - $option->save();
378   - }
379   - $options[] = $value->tax_option_id;
380   - }
381   - }
382   -
383   - if (!empty($options)) {
384   - $_product->options = $options;
385   - }
386   -
387   - $_product->save();
388   -
389   - $this->stdout("$j: Product {$_product->name} #{$_product->product_id} saved (". ($is_new_product ? 'new product' : 'exists product') .")\n");
390   -
391   - /*if ($j > 100) {
392   - $this->stdout("Dev OK");
393   - exit;
394   - }*/
395   -
396   - }
397   -
398   - fclose ($handle);
  32 + public function actionProducts() {
  33 + $model = new Import();
  34 + $data = $model->goProducts(0, null);
399 35  
400 36 return Controller::EXIT_CODE_NORMAL;
401 37 }
402 38  
403   - public function goProducts() {
404   -
405   - }
406   -
407 39 public function actionPrices() {
408   - $new_products = $linked_products = 0;
409   -
410   - if ( !($handle = $this->getProductsFile('uploadFilePrices')) ) {
411   - $this->stdout("File not found\n");
412   - return Controller::EXIT_CODE_ERROR;
413   - }
414   -
415   - $j = 0;
416   -
417   - while (($data = fgetcsv ($handle, 10000, ";")) !== FALSE) {
418   - $j++;
419   -// if ($j > 1) {
420   -// return TRUE;
421   -// }
422   -
423   - foreach ($data as &$value)
424   - {
425   - //$value = mb_convert_encoding ($value, "UTF-8", mb_detect_encoding ($value));
426   - $value = iconv ('windows-1251', "UTF-8//TRANSLIT//IGNORE", $value);
427   - $value = trim ($value);
428   - }
429   -
430   - // данные строк
431   - $modification_code = @$data[0];
432   - $_price = floatval(@$data[1]);
433   - $_price_promo = floatval(@$data[2]);
434   - $count = intval(@$data[3]);
435   - $city_name = @$data[4];
436   - $product_title = @$data[5];
437   -
438   - // @todo refactory this code
439   - $price = $_price_promo > 0 ? $_price_promo : $_price;
440   - $price_promo = $_price_promo > 0 ? $_price : $_price_promo;
441   -
442   - $modification_code = trim($modification_code);
443   -
444   - if (empty ($modification_code)) {
445   - continue;
446   - }
447   - // товары в пути
448   - if (empty ($city_name))
449   - {
450   - $this->saveNotFoundRecord (
451   - [$modification_code, $product_title],
452   - Yii::getAlias('@uploadFilePricesAway')
453   - );
454   -
455   - $this->stdout("~ Товар $product_title в пути\n");
456   -
457   - continue;
458   - }
459   -
460   - if ( ($productVariant = ProductVariant::find()->filterWhere(['sku' => $modification_code])->one()) === null ) {
461   - // 'Нет даной модификации в базе';
462   - $this->saveNotFoundRecord (
463   - [$modification_code, $product_title],
464   - Yii::getAlias('@uploadFilePricesNoVariant')
465   - );
466   -
467   - $this->stdout("- Для товара $product_title (#$modification_code) не найдено соотвествия\n");
468   -
469   - continue;
470   - }
471   -
472   - $quantity = 0;
473   -
474   - // ===== Set stock ====
475   - if ( $city_name ) {
476   - if ( ($stock = Stock::find()->filterWhere(['name' => trim($city_name)])->one()) === null ) {
477   - // Create stock
478   - $stock = new Stock();
479   - $stock->name = trim($city_name);
480   - $stock->save();
481   - }
482   -
483   - $productVariant->stocks[$stock->stock_id] = $count;
484   - $quantity = $quantity + $count;
485   - }
486   -
487   - $productVariant->price = $price;
488   - $productVariant->price_old = $price_promo;
489   - $productVariant->stock = $quantity;
490   -
491   - $productVariant->save();
492   -
493   - $this->stdout("+ Товар $product_title успешно сохранен\n");
494   - }
495   - fclose ($handle);
496   -
497   - unlink(Yii::getAlias('@uploadDir') .'/'. Yii::getAlias('@uploadFilePrices'));
  40 + $model = new Import();
  41 + $data = $model->goPrices(0, null);
498 42  
499 43 return Controller::EXIT_CODE_NORMAL;
500 44 }
... ...